text:
module Bot
  module Fish
    module ArtStuff
      extend Discordrb::Commands::CommandContainer
      puts 'Art loaded'

      command :art, description: "Get a randomly chosen artwork that contains <tag1>\n Usage: !!art <tag1> <-tag2>\n- excludes that tag from the request" do |event, *args|
        output args, event
      end

      command :ca, description: "Get a random art with Chloe" do |event|
        output "chloe", event
      end

      command :pfa, description: "Get a random art with Pricefield" do |event|
        output "pricefield", event
      end

      command :arrt, description: "Get a random art with pirates" do |event|
        output "pirates", event
      end

      command :ka, description: "Get a random art with Kate" do |event|
        output "kate", event
      end

      command :cua, description: "Get a random cute art" do |event|
        output "cute", event
      end

      command :ra, description: "Get a random art with Rachel" do |event|
        output "rachel", event
      end

      protected

      def ArtStuff::output(args, event=nil)
        args = [] << args unless args.kind_of?(Array)
        result = get_art parse_input args
        if !result.nil?
          begin
            raise Discordrb::Errors::NoPermission if event.nil?
            event.channel.send_embed do |embed|
              embed.title = "Artist page"
              embed.author = Discordrb::Webhooks::EmbedAuthor.new(name: "Random #{result[:args]} art")
              embed.colour = 0x14506f
              if result[:art].tags.include?("nsfw")
                embed.description = "**[NSFW]**"
              else
                embed.image = Discordrb::Webhooks::EmbedImage.new(url: "#{result[:art].preview}")
              end
              embed.url = "#{result[:art].source}"
              embed.footer = Discordrb::Webhooks::EmbedFooter.new(text: "#{result[:art].tags.include?("nsfw") ? "**[NSFW]**, " : ""}#{result[:count]} results")
              embed.add_field(name: "Tags:", value: "```#{result[:art].tags.reject(&:empty?).join(', ')}```")
            end
          rescue Discordrb::Errors::NoPermission
            random_text result
          end
        else
          'Sorry, got nothing on that.'
        end
      end

      def ArtStuff::get_art(tags)
        art = tags[:inc].blank? ? Art.where(tags: { '$nin' => tags[:exc]}) : Art.where(tags: { '$all' => tags[:inc] }).and(tags: { '$nin' => tags[:exc] })
        count = art.count
        art = art.order_by(last_use: :desc)
        art = count>11 ? art[(count-(count*0.1).ceil)..-1].sample : art.last
        if art.present?
          art.update(:last_use => DateTime.now)
          {:art => art, :args => tags[:raw_input], :count => count}
        else
          nil
        end
      end

      def ArtStuff::parse_input(input)
        inc = []
        exc = []
        unless input.blank?
          inc = Marshal.load(Marshal.dump(input))
          inc.each(&:downcase!)
          inc.each do |a|
            exc.push a if a.chars.first == '-'
          end
          inc.delete_if do |a|
            a.start_with? '-'
          end
          inc.delete_if do |a|
            a.start_with? '+'
          end
          exc.each do |a|
            a.slice!(0)
          end
        end
        unless input.include? '+nsfw'
          exc.push 'nsfw' unless input.include? 'nsfw'
        end
        {:inc => inc, :exc => exc, :raw_input => input}
      end

      def ArtStuff::random_text(art)
        "Random #{art[:args]} art (#{art[:count]} results): " << (art[:art].tags.include?("nsfw") ? "[NSFW] <#{art[:art].link}>" : "#{art[:art].link}")
      end

    end
  end
end

class Art
  include Mongoid::Document

  field :link,      type: String
  field :tags,      type: Array
  field :preview,   type: String
  field :source,    type: String
  field :last_use,  type: DateTime
end


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<APIProxy revision="3" name="shared-flow-client-proxy">
    <Basepaths>/shared-flow-client-proxy</Basepaths>
    <ConfigurationVersion majorVersion="4" minorVersion="0"/>
    <CreatedAt>1485208896402</CreatedAt>
    <CreatedBy>gladys@example.com</CreatedBy>
    <Description></Description>
    <DisplayName>shared-flow-client-proxy</DisplayName>
    <LastModifiedAt>1485208896402</LastModifiedAt>
    <LastModifiedBy>gladys@example.com</LastModifiedBy>
    <Policies>
        <Policy>Auth-Flow-Callout</Policy>
    </Policies>
    <ProxyEndpoints>
        <ProxyEndpoint>default</ProxyEndpoint>
    </ProxyEndpoints>
    <Resources/>
    <Spec></Spec>
    <TargetServers/>
    <TargetEndpoints>
        <TargetEndpoint>default</TargetEndpoint>
    </TargetEndpoints>
</APIProxy>

redpajama_set_name: RedPajamaGithub


text:
cask 'font-unifrakturcook' do
  version :latest
  sha256 :no_check

  # github.com/google/fonts was verified as official when first introduced to the cask
  url 'https://github.com/google/fonts/raw/master/ofl/unifrakturcook/UnifrakturCook-Bold.ttf'
  name 'UnifrakturCook'
  homepage 'http://www.google.com/fonts/specimen/UnifrakturCook'

  font 'UnifrakturCook-Bold.ttf'
end


text:
/**
 * Bean Validation TCK
 *
 * License: Apache License, Version 2.0
 * See the license.txt file in the root directory or <http://www.apache.org/licenses/LICENSE-2.0>.
 */
package org.hibernate.beanvalidation.tck.tests.validation.groupconversion;

import javax.validation.groups.Default;

/**
 * @author Gunnar Morling
 */
public interface Complete extends Default, Complex {
}


text:
"""Support for Google Home alarm sensor."""
from datetime import timedelta
import logging

from homeassistant.const import DEVICE_CLASS_TIMESTAMP
from homeassistant.helpers.entity import Entity
import homeassistant.util.dt as dt_util

from . import CLIENT, DOMAIN as GOOGLEHOME_DOMAIN, NAME

DEPENDENCIES = ['googlehome']

SCAN_INTERVAL = timedelta(seconds=10)

_LOGGER = logging.getLogger(__name__)

ICON = 'mdi:alarm'

SENSOR_TYPES = {
    'timer': 'Timer',
    'alarm': 'Alarm',
}

async def async_setup_platform(
        hass, config, async_add_entities, discovery_info=None):
    """Set up the googlehome sensor platform."""
    if discovery_info is None:
        _LOGGER.warning(
            "To use this you need to configure the 'googlehome' component")
        return

    await hass.data[CLIENT].update_info(discovery_info['host'])
    data = hass.data[GOOGLEHOME_DOMAIN][discovery_info['host']]
    info = data.get('info', {})

    devices = []
    for condition in SENSOR_TYPES:
        device = GoogleHomeAlarm(hass.data[CLIENT], condition,
                                 discovery_info, info.get('name', NAME))
        devices.append(device)

    async_add_entities(devices, True)

class GoogleHomeAlarm(Entity):
    """Representation of a GoogleHomeAlarm."""

    def __init__(self, client, condition, config, name):
        """Initialize the GoogleHomeAlarm sensor."""
        self._host = config['host']
        self._client = client
        self._condition = condition
        self._name = None
        self._state = None
        self._available = True
        self._name = "{} {}".format(name, SENSOR_TYPES[self._condition])

    async def async_update(self):
        """Update the data."""
        await self._client.update_alarms(self._host)
        data = self.hass.data[GOOGLEHOME_DOMAIN][self._host]

        alarms = data.get('alarms')[self._condition]
        if not alarms:
            self._available = False
            return
        self._available = True
        time_date = dt_util.utc_from_timestamp(min(element['fire_time']
                                                   for element in alarms)
                                               / 1000)
        self._state = time_date.isoformat()

    @property
    def state(self):
        """Return the state."""
        return self._state

    @property
    def name(self):
        """Return the name."""
        return self._name

    @property
    def device_class(self):
        """Return the device class."""
        return DEVICE_CLASS_TIMESTAMP

    @property
    def available(self):
        """Return the availability state."""
        return self._available

    @property
    def icon(self):
        """Return the icon."""
        return ICON


text:
package edu.hws.jcm.data;

/**
 * An object of type Cases stores a list of "case values" that is generated
 * while an expression is being evaluated using the routine Expression.getValuesWithCases().
 * This information can be used as a heuristic (i.e. a fudge) to help detect
 * a possible discontinuity between two evaluations of the expression.  Suppose
 * that the expression is evaluated twice, with some change of variable values
 * between the two evaluations.  If the variables' values are not changed too much,
 * and if the Cases objects generated by the two evaluations are equal (as determined
 * by the "equals" method defined in this class), then it is likely that
 * there is no discontinuity.  (However, this is not perfect.  The discontinuity
 * in 1/x^2 won't be detected since the case value generated by 1/f(x) only
 * checks the sign of f(x), and the denominator of 1/x^2 is positive on both
 * sides of x=0.  If you want to be more paranoid, check both the expression
 * and its derivative.)  (I really don't like this very much, but it can be used to draw
 * pretty good graphs in general.)
 */
public class Cases {
   private int[] cases = new int[1];  // Array of values that have been added with addCase(value).
   private int caseCt;                // Number of items stored in cases array.

   /**
    * Remove all the cases that have been added with addCase().
    * This makes it possible to reuse this object in another
    * call to Expression.getValueWithCases().
    */
   public void clear() {
     caseCt = 0;
   }

   /**
    * Add a new case value to the list stored in this object.
    */
   public void addCase(int value) {
     if (caseCt == cases.length) {
        int[] temp = new int[2*caseCt];
        System.arraycopy(cases,0,temp,0,caseCt);
        cases = temp;
     }
     cases[caseCt++] = value;
   }

   /**
    * Test whether c contains exactly the same list of case
    * values as this Cases object does.
    */
   public boolean equals(Cases c) {
     if (c.caseCt != caseCt)
        return false;
     for (int i = 0; i < caseCt; i++)
        if (c.cases[i] != cases[i])
           return false;
     return true;
   }

} // end class Cases


text:
package be.wegenenverkeer.designtests;

import be.wegenenverkeer.UsingWireMockRxJava;
import be.wegenenverkeer.rxhttpclient.ClientRequest;
import be.wegenenverkeer.rxhttpclient.HttpClientError;
import be.wegenenverkeer.rxhttpclient.HttpServerError;
import be.wegenenverkeer.rxhttpclient.ServerResponse;
import be.wegenenverkeer.rxhttpclient.rxjava.RxJavaHttpClient;
import io.reactivex.rxjava3.core.Flowable;
import io.reactivex.rxjava3.subscribers.TestSubscriber;
import org.junit.Test;

import java.nio.charset.Charset;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import static com.github.tomakehurst.wiremock.client.WireMock.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;

/**
 * Behavior Unit test
 * Created by Karel Maesen, Geovise BVBA on 06/12/14.
 */
public class RxHttpClientDesignTests extends UsingWireMockRxJava {

    @Test
    public void GETObservably() {
        //set up stub
        String expectBody = "{ 'contacts': [1,2,3] }";
        stubFor(get(urlPathEqualTo("/contacts"))
                .withQueryParam("q", equalTo("test"))
                .withHeader("Accept", equalTo("application/json"))
                .willReturn(aResponse()
                        .withStatus(200)
                        .withHeader("Content-Type", "application/json")
                        .withBody(expectBody)));

        //set up use case
        String path = "/contacts";
        ClientRequest request = client.requestBuilder()
                .setMethod("GET")
                .setUrlRelativetoBase(path)
                .addQueryParam("q", "test")
                .build();

        Flowable<String> flowable = client.executeObservably(request, bytes -> new String(bytes, Charset.forName("UTF8")));
        TestSubscriber<String> sub = flowable.test();

        sub.awaitDone(getTimeOut(), TimeUnit.MILLISECONDS);
        sub.assertNoErrors();
        sub.assertValues(expectBody);
    }

    @Test
    public void GETHappyPath() {
        //set up stub
        String expectBody = "{ 'contacts': [1,2,3] }";
        stubFor(get(urlPathEqualTo("/contacts"))
                .withQueryParam("q", equalTo("test"))
                .withHeader("Accept", equalTo("application/json"))
                .willReturn(aResponse()
                        .withStatus(200)
                        .withHeader("Content-Type", "application/json")
                        .withBody(expectBody)));

        //set up use case
        String path = "/contacts";
        ClientRequest request = client.requestBuilder()
                .setMethod("GET")
                .setUrlRelativetoBase(path)
                .addQueryParam("q", "test")
                .build();

        Flowable<String> flowable = client.executeToCompletion(request, ServerResponse::getResponseBody);
        TestSubscriber<String> sub = flowable.test();

        sub.awaitDone(getTimeOut(), TimeUnit.MILLISECONDS);
        sub.assertNoErrors();
        sub.assertValues(expectBody);
    }

    /**
     * Proves that UTF-8 charset is used as default.
     */
    @Test
    public void testCharsetEncodingDefaultsToUTF8() {

        //set up stub
        String expectBody = "{ 'contacts': 'žẽūș' }"; // with chars only available in UTF-8

        stubFor(get(urlPathEqualTo("/contacts"))
                .withQueryParam("q", equalTo("test"))
                .withHeader("Accept", equalTo("application/json"))
                .willReturn(aResponse().withFixedDelay(200)
                        .withStatus(200)
                        .withHeader("Content-Type", "application/json")
                        .withBody(expectBody)));

        //set up use case
        String path = "/contacts";
        ClientRequest request = client.requestBuilder()
                .setMethod("GET")
                .setUrlRelativetoBase(path)
                .addQueryParam("q", "test")
                .build();

        Flowable<String> flowable = client.executeToCompletion(request, ServerResponse::getResponseBody);

        TestSubscriber<String> sub = flowable.test();
        sub.awaitDone(getTimeOut(), TimeUnit.MILLISECONDS);
        sub.assertNoErrors();
        sub.assertValues(expectBody);
    }

    /**
     * Proves that charset when present in content type gets priority over default UTF-8
     */
    @Test
    public void testCharsetEncodingInContentType() {

        //set up stub
        String expectBody = "{ 'contacts': 'žẽūș' }"; // with chars only available in UTF-8

        stubFor(get(urlPathEqualTo("/contacts"))
                .withQueryParam("q", equalTo("test"))
                .withHeader("Accept", equalTo("application/json"))
                .willReturn(aResponse().withFixedDelay(200)
                        .withStatus(200)
                        .withHeader("Content-Type", "application/json;charset=ISO-8859-1") // explicitly picking Latin-1
                        .withBody(expectBody)));

        //set up use case
        String path = "/contacts";
        ClientRequest request = client.requestBuilder()
                .setMethod("GET")
                .setUrlRelativetoBase(path)
                .addQueryParam("q", "test")
                .build();

        Flowable<String> flowable = client.executeToCompletion(request, ServerResponse::getResponseBody);
        TestSubscriber<String> sub = flowable.test();
        sub.awaitDone(getTimeOut(), TimeUnit.MILLISECONDS);
        sub.assertNoErrors();

        try {
            sub.assertValues(expectBody);
            fail("Expecting wrongly parsed body");
        } catch (AssertionError exp) {
            // failure expected
        }

    }

    @Test
    public void GETHappyPathWithFuture() throws InterruptedException, TimeoutException, ExecutionException {
        //set up stub
        String expectBody = "{ 'contacts': [1,2,3] }";
        stubFor(get(urlPathEqualTo("/contacts"))
                .withQueryParam("q", equalTo("test"))
                .withHeader("Accept", equalTo("application/json"))
                .willReturn(aResponse().withFixedDelay(200)
                        .withStatus(200)
                        .withHeader("Content-Type", "application/json")
                        .withBody(expectBody)));

        //set up use case
        String path = "/contacts";
        ClientRequest request = client.requestBuilder()
                .setMethod("GET")
                .setUrlRelativetoBase(path)
                .addQueryParam("q", "test")
                .build();

        Future<String> f = client.execute(request, ServerResponse::getResponseBody);
        String result = f.get(getTimeOut(), TimeUnit.MILLISECONDS);
        assertEquals(expectBody, result);

    }

    @Test
    public void testHttp4xxResponseOnGET() {
        stubFor(get(urlPathEqualTo("/contacts")).willReturn(aResponse().withStatus(404)));

        //set up use case
        String path = "/contacts";
        ClientRequest request = client.requestBuilder().setMethod("GET").setUrlRelativetoBase(path).build();
        Flowable<String> flowable = client.executeToCompletion(request, ServerResponse::getResponseBody);

        TestSubscriber<String> sub = flowable.test();

        sub.awaitDone(getTimeOut(), TimeUnit.MILLISECONDS);
        sub.assertError(t -> {
            if (t instanceof HttpClientError) {
                return ((HttpClientError) t).getStatusCode() == 404;
            }
            return false;
        });
    }

    @Test
    public void testHttp5xxResponseOnGET() {
        //set up stub
        stubFor(get(urlEqualTo("/contacts"))
                .withHeader("Accept", equalTo("application/json"))
                .willReturn(aResponse().withFixedDelay(20)
                        .withStatus(500)));

        //set up use case
        String path = "/contacts";
        ClientRequest request = client
                .requestBuilder().setMethod("GET")
                .setUrlRelativetoBase(path)
                .build();

        Flowable<String> flowable = client.executeToCompletion(request, ServerResponse::getResponseBody);
        TestSubscriber<String> testsubscriber = flowable.test();

        testsubscriber.awaitDone(getTimeOut(), TimeUnit.MILLISECONDS);

        testsubscriber.assertError(t -> {
            if (t instanceof HttpServerError) {
                return ((HttpServerError) t).getStatusCode() == 500;
            }
            return false;
        });

    }

    @Test
    public void testConnectionTimeOut() {
        //set up stub
        stubFor(get(urlEqualTo("/contacts"))
                .withHeader("Accept", equalTo("application/json"))
                .willReturn(aResponse().withFixedDelay(500)
                        .withStatus(200)));

        //set up client with very low connection time-out values
        RxJavaHttpClient client = new RxJavaHttpClient.Builder()
                .setRequestTimeout(100)
                .setMaxConnections(1)
                .setAccept("application/json")
                .setBaseUrl("http://localhost:" + port())
                .build();

        //set up use case
        String path = "/contacts";
        ClientRequest request = client.requestBuilder().setMethod("GET").setUrlRelativetoBase(path).build();
        Flowable<String> flowable = client.executeToCompletion(request, ServerResponse::getResponseBody);

        TestSubscriber<String> testsubscriber = flowable.test();

        testsubscriber.awaitDone(1000, TimeUnit.MILLISECONDS);

        testsubscriber.assertError(TimeoutException.class);

    }

}


text:
package com.example.penguin.timetagger.Adapters;

import android.content.Context;
import android.support.v4.app.FragmentActivity;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.example.penguin.timetagger.Database.DatabaseHelper;
import com.example.penguin.timetagger.Fragments.TagFragment;
import com.example.penguin.timetagger.TimeTag;
import com.example.penguin.timetagger.R;

import java.sql.Timestamp;
import java.util.Arrays;
import java.util.List;

/*
 * Created by penguin on 17. 5. 16.
 */

public class TagListAdapter extends RecyclerView.Adapter<TagListAdapter.TagListViewHolder> {
	private Context context;
	private List<TimeTag> timeTagItems;

	public class TagListViewHolder extends RecyclerView.ViewHolder{
		TextView v_tag;
		TextView v_duration;
		CardView cv;

		public TagListViewHolder(View v){
			super(v);
			v_tag = (TextView) v.findViewById(R.id.tagTag);
			v_duration = (TextView) v.findViewById(R.id.tagDuration);
			cv = (CardView)v.findViewById(R.id.tagItem);
		}
	}

	@Override
	public TagListViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
		// create a new view
		View v = LayoutInflater
				.from(parent.getContext())
				.inflate(R.layout.item_tag, parent, false);
		return new TagListViewHolder(v);
	}

	public TagListAdapter(Context context){
		this.context = context;
		timeTagItems = DatabaseHelper.selectAllTags();

	}

	@Override
	public void onBindViewHolder(final TagListViewHolder holder, final int position) {
		TimeTag tt = timeTagItems.get(0);
		String tmpstr = timeTagItems.get(position).getTag();
        holder.v_tag.setText(tmpstr);

		String duration = timeTagItems.get(position).getStart().toString() +
				"~" + timeTagItems.get(position).getEnd().toString();
		holder.v_duration.setText(duration);

        /* 클릭 함수 */
		holder.cv.setOnClickListener(new View.OnClickListener(){
			@Override
			public void onClick(View v){
				TimeTag timeTag = timeTagItems.get(position);
				TagFragment fragment = TagFragment.newInstance(timeTag);

				((FragmentActivity)context).getSupportFragmentManager()
						.beginTransaction()
						.replace(R.id.frame_content, fragment)
						.addToBackStack(null)
						.commit();
			}
		});
	}

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


text:
"""Add inland_water to placemark_reports table

Revision ID: 2698789ba4a4
Revises: 8f22f932fa58
Create Date: 2016-01-25 23:11:18.515616

"""

# revision identifiers, used by Alembic.
revision = '2698789ba4a4'
down_revision = '8f22f932fa58'
branch_labels = None
depends_on = None

from alembic import op
from sqlalchemy import Column, String

def upgrade():
    op.add_column('placemark_reports', Column('inland_water', String))

def downgrade():
    op.drop_column('placemark_reports', 'inland_water')


text:
import datetime
import os
import socket
from django.db import models
from core.models import PlCoreBase, Site, Slice, Instance, Deployment
from core.models.plcorebase import StrippedCharField
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
from django.db.models import Sum
from django.utils import timezone

class Account(PlCoreBase):
    site = models.ForeignKey(Site, related_name="accounts", help_text="Site for this account")

    @property
    def total_invoices(self):
        # Since the amount of an invoice is the sum of it's charges, we can
        # compute the sum of the invoices by summing all charges where
        # charge.invoice != Null.
        x=self.charges.filter(invoice__isnull=False).aggregate(Sum('amount'))["amount__sum"]
        if (x==None):
            return 0.0
        return x

    @property
    def total_payments(self):
        x=self.payments.all().aggregate(Sum('amount'))["amount__sum"]
        if (x==None):
            return 0.0
        return x

    @property
    def balance_due(self):
        return self.total_invoices - self.total_payments

    def __unicode__(self):  return u'%s' % (self.site.name)

class Invoice(PlCoreBase):
    date = models.DateTimeField()
    account = models.ForeignKey(Account, related_name="invoices")

    @property
    def amount(self):
        return str(self.charges.all().aggregate(Sum('amount'))["amount__sum"])

    def __unicode__(self):  return u'%s-%s' % (self.account.site.name, str(self.date))

class UsableObject(PlCoreBase):
    name = StrippedCharField(max_length=1024)

    def __unicode__(self):  return u'%s' % (self.name)

class Payment(PlCoreBase):
    account = models.ForeignKey(Account, related_name="payments")
    amount = models.FloatField(default=0.0)
    date = models.DateTimeField(default=timezone.now)

    def __unicode__(self): return u'%s-%0.2f-%s' % (self.account.site.name, self.amount, str(self.date))

class Charge(PlCoreBase):
    KIND_CHOICES = (('besteffort', 'besteffort'), ('reservation', 'reservation'), ('monthlyfee', 'monthlyfee'))
    STATE_CHOICES = (('pending', 'pending'), ('invoiced', 'invoiced'))

    account = models.ForeignKey(Account, related_name="charges")
    slice = models.ForeignKey(Slice, related_name="charges", null=True, blank=True)
    kind = StrippedCharField(max_length=30, choices=KIND_CHOICES, default="besteffort")
    state = StrippedCharField(max_length=30, choices=STATE_CHOICES, default="pending")
    date = models.DateTimeField()
    object = models.ForeignKey(UsableObject)
    amount = models.FloatField(default=0.0)
    coreHours = models.FloatField(default=0.0)
    invoice = models.ForeignKey(Invoice, blank=True, null=True, related_name="charges")

    def __unicode__(self):  return u'%s-%0.2f-%s' % (self.account.site.name, self.amount, str(self.date))


text:
package mccarthy.brian.dte.nac;

/**
 * Interface for GameLogic, the can be extended by 3rd parties to provide
 * custom logic
 * @author Brian McCarthy
 */
public abstract class GameLogic {

	public abstract void placeComputerPiece();

	/**
	 * This should return a unique string for each logic type.
	 * @return id
	 */
	public abstract String getId();

	public String toString() {
		return getId();
	}

	public boolean equals(Object o) {
		if (!(o instanceof GameLogic)) {
			return false;
		}
		GameLogic other = (GameLogic) o;
		return getId().equals(other.getId());
	}

}


text:
@implementation DNLLRegisterUrl

// Seperator
NSString *seperator = @"-";

// Format for a register URL
// <scheme>://<appname>#<returnscheme><seperator><description>
NSString *registerUrlFormat = @"ripple://com.ripple.register#%@%@%@";

-(instancetype _Nullable) initWithUrl:(NSURL * _Nonnull) url {
    self = [super init];

    if (self != nil)
    {
        self.urlType = RegisterUrl;

        if ([url fragment] != nil)
        {
            NSString * fragment = [url fragment];
            if ([fragment containsString:seperator])
            {
                NSArray *seperatedStrings = [fragment componentsSeparatedByString:seperator];
                if ([seperatedStrings count] > 1)
                {
                    self.responseName = [seperatedStrings objectAtIndex:0];
                    self.appDescription = [seperatedStrings objectAtIndex:1];
                    self.url = url;
                }
                else
                {
                    self = nil;
                }

            }
            else
            {
                self = nil;
            }
        }
        else
        {
            self = nil;
        }
    }

    return self;
}

-(instancetype _Nullable) initWithDescription:(NSString *) applicationDescription andUrlScheme:(NSString *) scheme {
    self = [super init];

    if (self != nil)
    {
        self.urlType = RegisterUrl;
        NSString *urlString = [NSString stringWithFormat:registerUrlFormat, [scheme urlEncode], seperator, [applicationDescription urlEncode]];
        self.url = [NSURL URLWithString:urlString];
        self.appDescription = applicationDescription;
        self.responseName = scheme;
    }
    return self;
}
@end


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

<!--
	The beans available in this file must be identified in the "description" element for the Spring configuration application. Beans are listed between braces
	in the description separated with a comma like the following sample: {somebean,anotherbean}
-->
	<description>Beans included in this file: {directedgeclient}</description>
	<import resource="direct.beans.xml"/>

   	<alias alias="directedgeclient" name="directedgeclientsmtp" />

	<!-- No-op Implementation -->
	<bean lazy-init="true" class="gov.hhs.fha.nhinc.direct.edge.proxy.DirectEdgeProxyNoOpImpl" id="directedgeclientnoop" name="directedgeclientnoop">
		<meta key="impltype" value="noop"/>
	</bean>

	<!-- Java Implementation -->
	<bean lazy-init="true" class="gov.hhs.fha.nhinc.direct.edge.proxy.DirectEdgeProxyJavaImpl" id="directedgeclientjava" name="directedgeclientjava">
		<meta key="impltype" value="java"/>
	</bean>

	<!-- Unsecured web service Implementation -->
    <bean lazy-init="true" class="gov.hhs.fha.nhinc.webserviceproxy.WebServiceProxyHelper" id="proxyHelper" name="proxyHelper"/>
	<bean lazy-init="true" class="gov.hhs.fha.nhinc.direct.edge.proxy.DirectEdgeProxySoapImpl" id="directedgeclientsoap" name="directedgeclientsoap">
        <meta key="impltype" value="soap"/>
        <constructor-arg><ref bean="proxyHelper" /></constructor-arg>
	</bean>

    <!-- SMTP Implementation -->
    <bean lazy-init="true" class="gov.hhs.fha.nhinc.direct.edge.proxy.DirectEdgeProxySmtpImpl" id="directedgeclientsmtp" name="directedgeclientsmtp">
        <meta key="impltype" value="smtp"/>
        <constructor-arg><ref bean="intMailSender" /></constructor-arg>
    </bean>

</beans>


text:
<?php

/**
 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
 *
 * @author Guy Brand <gb@unistra.fr>
 * @author Delassaux Julien <julien@delassaux.fr>
 * @author Maurice A. LeBlanc <leblancma@cooptel.qc.ca>
 * @author stephane.gully <stephane.gully@gmail.com>
 * @author Guillaume Turri <guillaume.turri@gmail.com>
 * @author Erik Pedersen <erik.pedersen@shaw.ca>
 * @author olivier duperray <duperray.olivier@laposte.net>
 * @author Vincent Feltz <psycho@feltzv.fr>
 * @author Philippe Bajoit <philippe.bajoit@gmail.com>
 * @author Florian Gaub <floriang@floriang.net>
 * @author Johan Guilbaud <guilbaud.johan@gmail.com>
 * @author Yannick Aure <yannick.aure@gmail.com>
 * @author Olivier DUVAL <zorky00@gmail.com>
 * @author Anael Mobilia <contrib@anael.eu>
 * @author Bruno Veilleux <bruno.vey@gmail.com>
 * @author Antoine Turmel <geekshadow@gmail.com>
 * @author Jérôme Brandt <jeromebrandt@gmail.com>
 * @author Schplurtz le Déboulonné <Schplurtz@laposte.net>
 * @author Olivier Humbert <trebmuh@tuxfamily.org>
 * @author Eric <ericstevenart@netc.fr>
 */
$lang['menu']                  = 'Gestion des utilisateurs';
$lang['noauth']                = '(authentification de l\'utilisateur non disponible)';
$lang['nosupport']             = '(gestion de l\'utilisateur non pris en charge)';
$lang['badauth']               = 'mécanisme d\'authentification invalide';
$lang['user_id']               = 'Identifiant ';
$lang['user_pass']             = 'Mot de passe ';
$lang['user_name']             = 'Nom ';
$lang['user_mail']             = 'Courriel ';
$lang['user_groups']           = 'Groupes ';
$lang['field']                 = 'Champ';
$lang['value']                 = 'Valeur';
$lang['add']                   = 'Ajouter';
$lang['delete']                = 'Supprimer';
$lang['delete_selected']       = 'Supprimer la sélection';
$lang['edit']                  = 'Modifier';
$lang['edit_prompt']           = 'Modifier cet utilisateur';
$lang['modify']                = 'Enregistrer les modifications';
$lang['search']                = 'Rechercher';
$lang['search_prompt']         = 'Effectuer la recherche';
$lang['clear']                 = 'Réinitialiser la recherche';
$lang['filter']                = 'Filtre';
$lang['export_all']            = 'Exporter tous les utilisateurs (CSV)';
$lang['export_filtered']       = 'Exporter la liste d\'utilisateurs filtrés (CSV)';
$lang['import']                = 'Importer de nouveaux utilisateurs';
$lang['line']                  = 'Ligne n°';
$lang['error']                 = 'Message d\'erreur';
$lang['summary']               = 'Affichage des utilisateurs %1$d-%2$d parmi %3$d trouvés. %4$d utilisateurs au total.';
$lang['nonefound']             = 'Aucun utilisateur trouvé. %d utilisateurs au total.';
$lang['delete_ok']             = '%d utilisateurs effacés';
$lang['delete_fail']           = '%d effacements échoués.';
$lang['update_ok']             = 'Utilisateur mis à jour avec succès';
$lang['update_fail']           = 'Échec lors de la mise à jour de l\'utilisateur';
$lang['update_exists']         = 'Échec lors du changement du nom d\'utilisateur : le nom spécifié (%s) existe déjà (toutes les autres modifications seront effectuées).';
$lang['start']                 = 'Début';
$lang['prev']                  = 'Précédent';
$lang['next']                  = 'Suivant';
$lang['last']                  = 'Fin';
$lang['edit_usermissing']      = 'Utilisateur sélectionné non trouvé, cet utilisateur a peut-être été supprimé ou modifié ailleurs.';
$lang['user_notify']           = 'Notifier l\'utilisateur ';
$lang['note_notify']           = 'Expédition de notification par courriel uniquement lorsque l\'utilisateur fourni un nouveau mot de passe.';
$lang['note_group']            = 'Les nouveaux utilisateurs seront ajoutés au groupe par défaut (%s) si aucun groupe n\'est spécifié.';
$lang['note_pass']             = 'Le mot de passe sera généré automatiquement si le champ est laissé vide et si la notification de l\'utilisateur est activée.';
$lang['add_ok']                = 'Utilisateur ajouté avec succès';
$lang['add_fail']              = 'Échec de l\'ajout de l\'utilisateur';
$lang['notify_ok']             = 'Courriel de notification expédié';
$lang['notify_fail']           = 'Échec de l\'expédition du courriel de notification';
$lang['import_userlistcsv']    = 'Liste utilisateur (fichier CSV)';
$lang['import_header']         = 'Erreurs d\'import les plus récentes';
$lang['import_success_count']  = 'Import d'utilisateurs : %d utilisateurs trouvés, %d utilisateurs importés avec succès.';
$lang['import_failure_count']  = 'Import d\'utilisateurs : %d ont échoué. Les erreurs sont listées ci-dessous.';
$lang['import_error_fields']   = 'Nombre de champs insuffisant, %d trouvé, 4 requis.';
$lang['import_error_baduserid'] = 'Identifiant de l\'utilisateur manquant';
$lang['import_error_badname']  = 'Mauvais nom';
$lang['import_error_badmail']  = 'Mauvaise adresse e-mail';
$lang['import_error_upload']   = 'L\'import a échoué. Le fichier csv n\'a pas pu être téléchargé ou bien il est vide.';
$lang['import_error_readfail'] = 'L\'import a échoué. Impossible de lire le fichier téléchargé.';
$lang['import_error_create']   = 'Impossible de créer l\'utilisateur';
$lang['import_notify_fail']    = 'Impossible d\'expédier une notification à l\'utilisateur importé %s, adresse %s.';
$lang['import_downloadfailures'] = 'Télécharger les erreurs au format CSV pour correction';
$lang['addUser_error_missing_pass'] = 'Veuillez saisir un mot de passe ou activer la notification à l\'utilisateur pour permettre la génération d\'un mot de passe.';
$lang['addUser_error_pass_not_identical'] = 'Les mots de passe saisis diffèrent.';
$lang['addUser_error_modPass_disabled'] = 'La modification des mots de passe est actuellement désactivée.';
$lang['addUser_error_name_missing'] = 'Veuillez saisir un nom pour le nouvel utilisateur.';
$lang['addUser_error_modName_disabled'] = 'La modification des noms est actuellement désactivée.';
$lang['addUser_error_mail_missing'] = 'Veuillez saisir une adresse de courriel pour le nouvel utilisateur.';
$lang['addUser_error_modMail_disabled'] = 'La modification des adresses de courriel est actuellement désactivée.';
$lang['addUser_error_create_event_failed'] = 'Un greffon a empêché l\'ajout du nouvel utilisateur. Examinez les autres messages potentiels pour obtenir de plus amples informations.';


text:
/*!
  \author Timo Latvala, Marco Roveri
  \brief The header file for the <tt>cmd</tt> module, the user
  commands handling layer.

  \todo: Missing description

*/

#ifndef __NUSMV_SHELL_BMC_SBMC_SBMC_CMD_H__
#define __NUSMV_SHELL_BMC_SBMC_SBMC_CMD_H__

#if HAVE_CONFIG_H
# include "nusmv-config.h"
#endif

#include "nusmv/core/utils/utils.h"
#include "nusmv/core/prop/Prop.h"

/**AutomaticStart*************************************************************/

/*---------------------------------------------------------------------------*/
/* Function prototypes                                                       */
/*---------------------------------------------------------------------------*/

/*!
  \brief Adds all bmc-related commands to the interactive shell

  \sa CInit_Init
*/
void SBmc_AddCmd(NuSMVEnv_ptr env);

/*!
  \brief Adds all bmc-related commands to the interactive shell

  \sa CInit_Init
*/
void Sbmc_Cmd_quit(NuSMVEnv_ptr env);

/*!
  \command{check_ltlspec_sbmc} Finds error up to depth k

  \command_args{[-h | -n idx | -p "formula" [IN context] | -P
  "name"] [-k max_length] [-l loopback] [-1] [-o filename]}

  This command generates one or more problems, and calls
  SAT solver for each one. Each problem is related to a specific problem
  bound, which increases from zero (0) to the given maximum problem
  length. Here "length" is the bound of the problem that system
  is going to generate and/or solve.

  In this context the maximum problem bound is represented by the
  -k command parameter, or by its default value stored in the
  environment variable bmc_length.

  The single generated problem also depends on the "loopback"
  parameter you can explicitly specify by the -l option, or by its
  default value stored in the environment variable bmc_loopback.

  The property to be checked may be specified using the -n idx or
  the -p "formula" options.

  If you need to generate a dimacs dump file of all generated problems, you
  must use the option -o "filename".

  Command options:

 <tt>-n index</tt>

 index is the numeric index of a valid LTL specification
       formula actually located in the properties database.

 <tt>-p "formula" [IN context]</tt>

 Checks the <tt>formula</tt> specified on the command-line.

            <tt>context</tt> is the module instance name which the variables
            in <tt>formula</tt> must be evaluated in.

 <tt>-P name</tt>

 Checks the LTLSPEC property with name <tt>name</tt> in the property
            database.

 <tt>-k max_length</tt>

 max_length is the maximum problem bound must be reached.
       Only natural number are valid values for this option. If no value
       is given the environment variable bmc_length is considered
       instead.

 <tt>-l loopback</tt>

 loopback value may be:

       - a natural number in (0, max_length-1). Positive sign ('+') can
       be also used as prefix of the number. Any invalid combination of length
       and loopback will be skipped during the generation/solving process.

       - a negative number in (-1, -bmc_length). In this case
       loopback is considered a value relative to max_length.
       Any invalid combination of length and loopback will be skipped
       during the generation/solving process.

       - the symbol 'X', which means "no loopback"

       - the symbol '*', which means "all possible loopback from zero to
       length-1"

 <tt>-1</tt>

 Generates and solves a single problem with length <tt>k</tt>

 <tt>-o filename</tt>

 filename is the name of the dumped dimacs file.
       It may contain special symbols which will be macro-expanded to form
       the real file name. Possible symbols are:

       - @F: model name with path part

       - @f: model name without path part

       - @k: current problem bound

       - @l: current loopback value

       - @n: index of the currently processed formula in the properties
       database

       - @@: the '@' character

  For further information about this implementation see:
  T. Latvala, A. Biere, K. Heljanko, and T. Junttila. Simple is
  Better: Efficient Bounded Model Checking for Past LTL. In: R. Cousot
  (ed.), Verification, Model Checking, and Abstract Interpretation,
  6th International Conference VMCAI 2005, Paris, France, Volume 3385
  of LNCS, pp. 380-395, Springer, 2005.  Copyright (C)
  Springer-Verlag.

*/
int
Sbmc_CommandCheckLtlSpecSBmc(NuSMVEnv_ptr env, int argc, char** argv);

/*!
  \command{gen_ltlspec_sbmc} Dumps into one or more dimacs files the given LTL
  specification, or all LTL specifications if no formula is given.
  Generation and dumping parameters are the maximum bound and the loopback
  values. Uses Kepa's and Timo's method for doing bmc.

  \command_args{[-h | -n idx | -p "formula" [IN context] | -P "name"]
  [-k max_length] [-l loopback] [-1] [-o filename]}

   This command generates one or more problems, and
  dumps each problem into a dimacs file. Each problem is related to a specific
  problem bound, which increases from zero (0) to the given maximum problem
  bound. In this short description "length" is the bound of the
  problem that system is going to dump out. Uses Kepa's and Timo's method for doing bmc.

  In this context the maximum problem bound is represented by the
  max_length parameter, or by its default value stored in the
  environment variable bmc_length.

  Each dumped problem also depends on the loopback you can explicitly
  specify by the -l option, or by its default value stored in the
  environment variable bmc_loopback.

  The property to be checked may be specified using the -n idx or
  the -p "formula" options.

  You may specify dimacs file name by using the option -o "filename",
  otherwise the default value stored in the environment variable
  bmc_dimacs_filename will be considered.

  Command options:

 <tt>-n index</tt>

 index is the numeric index of a valid LTL specification
       formula actually located in the properties database.

 <tt>-p "formula" [IN context]</tt>

 Checks the <tt>formula</tt> specified on the command-line.

            <tt>context</tt> is the module instance name which the variables
            in <tt>formula</tt> must be evaluated in.

 <tt>-P name</tt>

 Checks the LTLSPEC property with name <tt>name</tt> in the property
            database.

 <tt>-k max_length</tt>

 max_length is the maximum problem bound must be reached.
       Only natural number are valid values for this option. If no value
       is given the environment variable bmc_length is considered
       instead.

 <tt>-l loopback</tt>

 loopback value may be:

       - a natural number in (0, max_length-1). Positive sign ('+') can
       be also used as prefix of the number. Any invalid combination of length
       and loopback will be skipped during the generation/solving process.

       - a negative number in (-1, -bmc_length). In this case
       loopback is considered a value relative to max_length.
       Any invalid combination of length and loopback will be skipped
       during the generation/solving process.

       - the symbol 'X', which means "no loopback"

       - the symbol '*', which means "all possible loopback from zero to
       length-1"

 <tt>-1</tt>

 Generates a single problem with length <tt>k</tt>

 <tt>-o filename</tt>

 filename is the name of the dumped dimacs file.
       It may contain special symbols which will be macro-expanded to form
       the real file name. Possible symbols are:

       - @F: model name with path part

       - @f: model name without path part

       - @k: current problem bound

       - @l: current loopback value

       - @n: index of the currently processed formula in the properties
       database

       - @@: the '@' character

  For further information about this implementation see:
  T. Latvala, A. Biere, K. Heljanko, and T. Junttila. Simple is
  Better: Efficient Bounded Model Checking for Past LTL. In: R. Cousot
  (ed.), Verification, Model Checking, and Abstract Interpretation,
  6th International Conference VMCAI 2005, Paris, France, Volume 3385
  of LNCS, pp. 380-395, Springer, 2005.  Copyright (C)
  Springer-Verlag.

*/
int
Sbmc_CommandGenLtlSpecSBmc(NuSMVEnv_ptr env, int argc, char** argv);

/*!
  \command{check_ltlspec_sbmc_inc} Incremental SBMC LTL model checking

  \command_args{[-h | -n idx | -p "formula" [IN context] | -P
  "name"] [-k max_length] [-c] [-N]}

  This command generates one or more problems, and calls
  SAT solver for each one. Each problem is related to a specific problem
  bound, which increases from zero (0) to the given maximum problem
  length. Here "length" is the bound of the problem that system
  is going to generate and/or solve.

  In this context the maximum problem bound is represented by the
  -k command parameter, or by its default value stored in the
  environment variable bmc_length.

  The property to be checked may be specified using the -n idx,
  -p "formula", or -P "property_name" options.

  Completeness check, although slower, can be used to determine whether
  the property holds.

  Command options:

 <tt>-n index</tt>

 index is the numeric index of a valid LTL specification
       formula actually located in the properties database.

 <tt>-p "formula" [IN context]</tt>

 Checks the <tt>formula</tt> specified on the command-line.

            <tt>context</tt> is the module instance name which the variables
            in <tt>formula</tt> must be evaluated in.

 <tt>-P name</tt>

 Checks the LTLSPEC property with name <tt>name</tt> in the property
            database.

 <tt>-k max_length</tt>

 max_length is the maximum problem bound must be reached.
       Only natural number are valid values for this option. If no value
       is given the environment variable bmc_length is considered
       instead.

 <tt>-c</tt>

 Performs completeness check at every step. This can be
       effectively used to determine whether a property holds.</tt>

<tt>-N</tt>

 Does not perform virtual unrolling.

  For further information about this implementation see:
  T. Latvala, A. Biere, K. Heljanko, and T. Junttila. Simple is
  Better: Efficient Bounded Model Checking for Past LTL. In: R. Cousot
  (ed.), Verification, Model Checking, and Abstract Interpretation,
  6th International Conference VMCAI 2005, Paris, France, Volume 3385
  of LNCS, pp. 380-395, Springer, 2005.  Copyright (C)
  Springer-Verlag.

*/
int
Sbmc_CommandLTLCheckZigzagInc(NuSMVEnv_ptr env, int argc, char** argv);

/**AutomaticEnd***************************************************************/

#endif /* _BMC_CMD_H */


text:
require_relative "php_shared_concurrency"

describe "A PHP 8.0/Nginx application for testing WEB_CONCURRENCY behavior", :requires_php_on_stack => "8.0" do
	include_examples "A PHP application for testing WEB_CONCURRENCY behavior", "8.0", "nginx"
end


text:
$LOAD_PATH.unshift File.expand_path("../../lib", __FILE__)
require "fluent/plugin/genhashvalue"


text:
package com.example.liangwenchao.appdemo.ui.view.fragment;

import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;

import com.example.liangwenchao.appdemo.R;
import com.example.liangwenchao.appdemo.ui.base.fragment.BaseFragment;

/**
 * Created by admin on 2016/5/11.
 */
public class ImageBrowserFragment extends BaseFragment {

    public static final String IMAGE_BROWSER_FRAGMENY_TAG = "ImageBrowserFragment";

    private int[] images = new int[]{R.drawable.image1, R.drawable.image2, R.drawable.image3, R.drawable.image4};
    //默认图片
    private int currentImage = 0;
    //默认透明度
    private float alpha = 1.0f;

    @Override
    public View inflateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_image_browser, null);
    }

    @Override
    public void initView(final View view) {
        final Button plus = (Button) view.findViewById(R.id.plus);
        final Button minus = (Button) view.findViewById(R.id.minus);
        final Button next = (Button) view.findViewById(R.id.next);

        final ImageView image1 = (ImageView) view.findViewById(R.id.iamge1);
        final ImageView image2 = (ImageView) view.findViewById(R.id.iamge2);
        image1.setImageResource(images[currentImage]);

        next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                image1.setImageResource(images[++currentImage % images.length]);
            }
        });

        View.OnClickListener listener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (v == plus) {//可以直接写"=="
                    alpha += 0.05;
                }
                if (v == minus) {
                    alpha -= 0.05;
                }
                if (alpha >= 1.0) {
                    alpha = 1.0f;
                }
                if (alpha <= 0) {
                    alpha = 0.0f;
                }
                image1.setAlpha(alpha);

            }
        };
        plus.setOnClickListener(listener);
        minus.setOnClickListener(listener);
        image1.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {

                BitmapDrawable bitmapDrawable = (BitmapDrawable) image1.getDrawable();
                Bitmap bitmap = bitmapDrawable.getBitmap();
                //bitmap图片实际大小与第一个ImageView的缩放比例
                double scale = 1.0 * bitmap.getHeight() / image1.getHeight();
                //获取需要显示的图片的开始点
                int x = (int) (event.getX() * scale);
                int y = (int) (event.getY() * scale);

                if (x + 120 > bitmap.getWidth()) {
                    x = bitmap.getWidth() - 120;
                }
                if (y + 120 > bitmap.getHeight()) {
                    y = bitmap.getHeight()-120;
                }
                image2.setImageBitmap(Bitmap.createBitmap(bitmap,x,y,120,120));
                image2.setAlpha(alpha);

                return false;
            }
        });
    }

    @Override
    public void initData() {

    }
}


text:
package eu.se_bastiaan.marietje.ui.main.queue;

import android.content.Context;

import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import eu.se_bastiaan.marietje.data.DataManager;
import eu.se_bastiaan.marietje.data.model.Empty;
import eu.se_bastiaan.marietje.data.model.Queue;
import eu.se_bastiaan.marietje.events.NeedsCsrfToken;
import eu.se_bastiaan.marietje.injection.ApplicationContext;
import eu.se_bastiaan.marietje.injection.PerFragment;
import eu.se_bastiaan.marietje.ui.base.BasePresenter;
import eu.se_bastiaan.marietje.util.EventBus;
import eu.se_bastiaan.marietje.util.RxSubscriber;
import eu.se_bastiaan.marietje.util.RxUtil;
import retrofit2.adapter.rxjava.HttpException;
import rx.Observable;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import timber.log.Timber;

@PerFragment
public class QueuePresenter extends BasePresenter<QueueView> {

    private final DataManager dataManager;
    private final Context context;
    private final EventBus eventBus;
    private Subscription loadingSubscription;

    @Inject
    public QueuePresenter(DataManager dataManager, @ApplicationContext Context context, EventBus eventBus) {
        this.dataManager = dataManager;
        this.context = context;
        this.eventBus = eventBus;
    }

    public void loadData() {
        loadData(0);
    }

    public void loadData(long delay) {
        checkViewAttached();

        if (loadingSubscription == null) {
            view().showLoading();
        }

        RxUtil.unsubscribe(loadingSubscription);

        loadingSubscription = Observable.timer(delay, TimeUnit.SECONDS)
                .flatMap(o -> dataManager.controlDataManager().queue())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new RxSubscriber<Queue>() {
                    @Override
                    public void onNext(Queue queue) {
                        view().showQueue(queue);
                    }

                    @Override
                    public void onError(Throwable e) {
                        Timber.w(e);
                        view().showLoadingError();

                        if (e instanceof HttpException) {
                            HttpException httpException = (HttpException) e;
                            if (httpException.code() == 403) {
                                eventBus.post(new NeedsCsrfToken());
                            }
                        }
                    }
                });

        unsubscribeOnDetachView(loadingSubscription);
    }

    public void skipCurrentSong() {
        checkViewAttached();

        Subscription subscription = dataManager.controlDataManager().skip()
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new RxSubscriber<Empty>() {
                    @Override
                    public void onNext(Empty emptyResponse) {
                        loadData();
                        view().showSkipSuccess();
                    }

                    @Override
                    public void onError(Throwable e) {
                        Timber.w(e);
                        view().showSkipError();
                    }
                });

        unsubscribeOnDetachView(subscription);
    }

    public void moveSongUpInQueue(long songId) {
        checkViewAttached();

        Subscription subscription = dataManager.controlDataManager().moveUp(songId)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new RxSubscriber<Empty>() {
                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                    }

                    @Override
                    public void onNext(Empty emptyResponse) {
                        loadData();
                        view().showMoveUpSuccess();
                    }

                    @Override
                    public void onError(Throwable e) {
                        Timber.w(e);
                        view().showMoveUpError();
                    }
                });

        unsubscribeOnDetachView(subscription);
    }

    public void moveSongDownInQueue(long songId) {
        checkViewAttached();

        Subscription subscription = dataManager.controlDataManager().moveDown(songId)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new RxSubscriber<Empty>() {
                    @Override
                    public void onNext(Empty emptyResponse) {
                        loadData();
                        view().showMoveDownSuccess();
                    }

                    @Override
                    public void onError(Throwable e) {
                        Timber.w(e);
                        view().showMoveDownError();
                    }
                });

        unsubscribeOnDetachView(subscription);
    }

    public void removeSongFromQueue(long songId) {
        checkViewAttached();

        Subscription subscription = dataManager.controlDataManager().cancel(songId)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new RxSubscriber<Empty>() {
                    @Override
                    public void onNext(Empty emptyResponse) {
                        loadData();
                        view().showRemoveSuccess();
                    }

                    @Override
                    public void onError(Throwable e) {
                        Timber.w(e);
                        view().showRemoveError();
                    }
                });

        unsubscribeOnDetachView(subscription);
    }

}


text:
author: robmyers
comments: true
date: 2005-10-31 05:05:56+00:00
layout: post
slug: double-negative
title: Double Negative
wordpress_id: 715
categories:
- Sketchblog
---

![](/wp-content/g4816.png)


text:
<form id="form-add-service" action="/facilities/{{ $facilityId }}/doctors/{{ $doctor->getId() }}/services"
      method="POST">

                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Add service to {{ $doctor->getName() }} {{ $doctor->getSurname() }}

                        Service:
                        <select name="service-id" id="ddl-service" required="required" class="form-control">
                            <option value="">Select service</option>
                            @foreach($services as $service)
                                <option value="{{ $service->getId() }}">{{ $service->getName() }}</option>
                            @endforeach
                        </select>

                        Minimum price:
                        <input type="number" min="0" class="form-control" id="txt-minimum-price"
                               name="minimum-price">

                        Maximum price:
                        <input type="number" min="0" class="form-control" id="txt-maximum-price"
                               name="maximum-price">

                    <button class="btn btn-primary btn-add-service">Add</button>
                    <button class="btn btn-danger btn-cancel-service" data-dismiss="modal">Cancel</button>

</form>


text:
<?php

namespace frontend\modules\test\controllers;

use common\models\SearchProfession;
use Yii;
use yii\web\Controller;

/**
 * Default controller for the `test` module
 */
class DefaultController extends Controller
{

    /**
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new SearchProfession();
        $dataProvider =$searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'dataProvider' => $dataProvider,
            'searchModel' => $searchModel,
        ]);
    }
}


text:
package diskReg;

import util.*;
import hydra.*;
import java.util.*;
import com.gemstone.gemfire.cache.*;
import com.gemstone.gemfire.internal.cache.lru.MemLRUCapacityController;
import com.gemstone.gemfire.internal.cache.LocalRegion;

public class SerialDiskRegTest extends DiskRegTest {

protected String sharedMapKey;  // key used for this VM to access the blackboard shared map
protected boolean checkLRU;     // true if this test can check LRU overflow objects
protected boolean isMemLRU;     // true if this VM uses memLRU for disk regions

// for memLRU disk regions
protected long bytesPerEntry_keyValue;   // number of bytes in the region per entry in the VM
protected long bytesPerEntry_keyOnly;    // number of bytes in the region per entry with value on disk
protected long minEvictionBytes;     // the minimum number of bytes that must be in the region before eviction occurs
protected long maxBytes;             // the maximum number of allowable bytes in the region
protected long perEntryOverhead;     // the number of bytes of overhead for a region entry
protected long numEntriesDeviation;  // the number of bytes of this number of entries that the region's
                                     // number of bytes can deviate from the set capacity for memLRU

// initialization methods
// ================================================================================
/** initialize fields in this class and its superclass */
public synchronized static void HydraTask_initialize() {
   if (testInstance == null) {
      testInstance = new SerialDiskRegTest();
      testInstance.initialize();
      Log.getLogWriter().info(testInstance.toVerboseString());
   }
}

protected void initialize() {
   super.initialize();
   // unable to verify LRU when numVMs > 1 because 1) we don't know which keys
   // are in this VM's region and 2) randomly getting objects from other caches
   // can pull in any key, even those orginially defined in another VM
   checkLRU = (numVMs == 1);
   sharedMapKey = "OldestKey_" + ProcessMgr.getProcessId();
   DiskRegBB.getBB().getSharedMap().put(sharedMapKey, new Long(1));
   isMemLRU = false;

   EvictionAttributes evAttr = aRegion.getAttributes().getEvictionAttributes();
   if (evAttr != null) {
     isMemLRU = evAttr.getAlgorithm().isLRUMemory();
     if (isMemLRU) {
        Object sampleValue = getNewValue(getFixedLengthKeyForName("Object_1"));
        long valueSize = (new DiskRegSizer()).sizeof(sampleValue);

        Region aRegion = RegionHelper.getRegion(REGION_NAME);
        perEntryOverhead = ((MemLRUCapacityController)(((LocalRegion)aRegion).getEvictionController())).getPerEntryOverhead();
        bytesPerEntry_keyOnly = TestHelper.calculateStringSize(getFixedLengthKeyForName("Object_1")) + perEntryOverhead;
        bytesPerEntry_keyValue = bytesPerEntry_keyOnly + valueSize + perEntryOverhead;
        numEntriesDeviation = TestConfig.tab().intAt(DiskRegPrms.numEntriesDeviation);
        minEvictionBytes = (evictionLimit * 1024 * 1024) - (bytesPerEntry_keyValue * numEntriesDeviation);
        maxBytes = (evictionLimit * 1024 * 1024) + (bytesPerEntry_keyValue * numEntriesDeviation);
        Log.getLogWriter().info(
            "KEY_LENGTH = " + KEY_LENGTH + "\n" +
            "valueSize = " + valueSize + "\n" +
            "perEntryOverhead = " + perEntryOverhead + "\n" +
            "bytesPerEntry_keyValue = " + bytesPerEntry_keyValue + "\n" +
            "bytesPerEntry_keyOnly = " + bytesPerEntry_keyOnly + "\n" +
            "numEntriesDeviation = " + numEntriesDeviation + "\n" +
            "minEvictionBytes = " + minEvictionBytes + "\n" +
            "maxBytes = " + maxBytes);
      }
   }
}

// task methods
//========================================================================

/** Hydra task for careful validation of disk regions. Add an entry and
 *  validate it. Run for minTaskGranularitySec (specified as a hydra param)
 */
public static void HydraTask_addNew() {
   ((SerialDiskRegTest)testInstance).addNew();
}

private void addNew() {
   long exeNum = DiskRegBB.getBB().getSharedCounters().incrementAndRead(DiskRegBB.EXECUTION_NUMBER);
   Log.getLogWriter().info("Beginning task with execution number " + exeNum);
   long timeToRunSec = TestConfig.tab().intAt(TestHelperPrms.minTaskGranularitySec);
   long timeToRunMS = timeToRunSec * TestHelper.SEC_MILLI_FACTOR;
   Log.getLogWriter().info("In HydraTask_addNew, adding for " + timeToRunSec + " seconds");
   long startTime = System.currentTimeMillis();
   do {
      ((SerialDiskRegTest)testInstance).doAddNew();
   } while (System.currentTimeMillis() - startTime < timeToRunMS);
   Log.getLogWriter().info("In HydraTask_addNew, done running for " + timeToRunSec + " seconds");
   int numKeys = testInstance.aRegion.keys().size();
   int endTestOnNumKeysInRegion = TestConfig.tab().intAt(DiskRegPrms.endTestOnNumKeysInRegion, Integer.MAX_VALUE);
      if (numKeys >= endTestOnNumKeysInRegion) {
         // some tests keep all keys in memory; on faster machines these tests run out of
         // memory in a time based test, so make it a workload based test instead
         throw new StopSchedulingOrder("Stopping client because the region has " + numKeys + " keys, endTestOnNumKeysInRegion is " + endTestOnNumKeysInRegion);
      }
}

/** Hydra task for careful validation of disk regions. Do a get on a
 *  previously created entry to see if we can get it from another cache.
 */
public static void HydraTask_getOld() {
   ((SerialDiskRegTest)testInstance).getOld();
}

private void getOld() {
   long exeNum = DiskRegBB.getBB().getSharedCounters().incrementAndRead(DiskRegBB.EXECUTION_NUMBER);
   Log.getLogWriter().info("Beginning task with execution number " + exeNum);
   long timeToRunSec = TestConfig.tab().intAt(TestHelperPrms.minTaskGranularitySec);
   long timeToRunMS = timeToRunSec * TestHelper.SEC_MILLI_FACTOR;
   Log.getLogWriter().info("In HydraTask_getOld, getting for " + timeToRunSec + " seconds");
   long startTime = System.currentTimeMillis();
   do {
      ((SerialDiskRegTest)testInstance).doGetOld();
   } while (System.currentTimeMillis() - startTime < timeToRunMS);
   Log.getLogWriter().info("In HydraTask_getOld, done running for " + timeToRunSec + " seconds");
   int numKeys = testInstance.aRegion.keys().size();
   int endTestOnNumKeysInRegion = TestConfig.tab().intAt(DiskRegPrms.endTestOnNumKeysInRegion, Integer.MAX_VALUE);
   if ((regionKind == NO_DISK) || (regionKind == DISK_FOR_PERSIST)) { //configs that keep things in memory
      if (numKeys >= endTestOnNumKeysInRegion) {
         // some tests keep all keys in memory; on faster machines these tests run out of
         // memory in a time based test, so make it a workload based test instead
         throw new StopSchedulingOrder("Stopping client because the region has " + numKeys + " keys, endTestOnNumKeysInRegion is " + endTestOnNumKeysInRegion);
      }
   }
}

// methods to do the work of the tasks
//========================================================================

/** Add a new entry to the region, and verify the add.
 */
protected void doAddNew() {
   // add the entry, getting the number of entries before and after on the disk
   int beforeNumKeys = aRegion.keys().size();
   long beforeNumInVM = DiskRegUtil.getNumEntriesInVM(aRegion);
   long beforeNumOnDisk = DiskRegUtil.getNumEntriesWrittenToDisk(aRegion);
   long beforeNumOverflowOnDisk = DiskRegUtil.getNumOverflowOnDisk(aRegion);

   Object[] keyAndValue;
   DataPolicy dataPolicy = aRegion.getAttributes().getDataPolicy();
   boolean putIfAbsentSupported = !(dataPolicy.equals(DataPolicy.NORMAL) || dataPolicy.equals(DataPolicy.EMPTY));
   if (putIfAbsentSupported && TestConfig.tab().getRandGen().nextBoolean()) {
     keyAndValue = putIfAbsent();
   } else {
     keyAndValue = addEntry();
   }
   Object key = keyAndValue[0];
   Object value = keyAndValue[1];
   boolean addViaGet = ((Boolean)keyAndValue[2]).booleanValue();
   verifyAfterAdd(key, value, beforeNumKeys, beforeNumInVM, beforeNumOnDisk, beforeNumOverflowOnDisk);

   if (addViaGet) { // doing a second get so as to show off bug 31102 (or lack thereof)
      Log.getLogWriter().info("Doing a second get on key " + key + "...");
      aRegion.get(key);
   }
   verifyAfterAdd(key, value, beforeNumKeys, beforeNumInVM, beforeNumOnDisk, beforeNumOverflowOnDisk);
   checkForEventError();
}

/** Do a get of a previously added key to see if we can find it in another cache.
 */
protected void doGetOld() {
   final int RANGE = 30; // look back to the last 30 keys created by this test
   int beforeNumKeys = aRegion.keys().size();
   long beforeNumInVM = DiskRegUtil.getNumEntriesInVM(aRegion);
   long beforeNumOnDisk = DiskRegUtil.getNumEntriesWrittenToDisk(aRegion);
   long beforeNumOverflowOnDisk = DiskRegUtil.getNumOverflowOnDisk(aRegion);
   Object[] objArr = randomGet(RANGE);
   if (objArr == null) // there are no keys yet
      return;
   Object key = objArr[0];
   Object value = objArr[1];
   boolean containsKeyBeforeGet = ((Boolean)objArr[2]).booleanValue();
   if (!containsKeyBeforeGet) { // we added a new entry; verify it
      verifyAfterAdd(key, value, beforeNumKeys, beforeNumInVM, beforeNumOnDisk, beforeNumOverflowOnDisk);
   }
   checkForEventError();
}

// verification methods
//========================================================================

/** Verify the state of the region after an add.
 *
 *  @params key The key that was added.
 *  @params value The value that was added.
 *  @params beforeNumKeys The number of keys before the add.
 *  @params beforeNumInVM The number of entries in the VM before the add.
 *  @params beforeNumOnDisk The number of entries on the disk before the add.
 *  @params beforeNumOverflowOnDisk The number of entries overflowed to disk before the add.
 *
 *  @throws TestException if any problems were detected.
 */
protected void verifyAfterAdd(Object key,
                              Object value,
                              long beforeNumKeys,
                              long beforeNumInVM,
                              long beforeNumOnDisk,
                              long beforeNumOverflowOnDisk) {
   int afterNumKeys = aRegion.size();
   long afterNumInVM = DiskRegUtil.getNumEntriesInVM(aRegion);
   long afterNumOnDisk = DiskRegUtil.getNumEntriesWrittenToDisk(aRegion);
   long afterNumOverflowOnDisk = DiskRegUtil.getNumOverflowOnDisk(aRegion);
   Object valueInVM = DiskRegUtil.getValueInVM(aRegion, key);
  Object valueOnDisk = DiskRegUtil.getValueOnDiskOrBuffer(aRegion, key);

   StringBuffer aStr = new StringBuffer();
   aStr.append("In verifyAfterAdd with key " + key + ", value " + TestHelper.toString(value) + "\n");
   aStr.append("   beforeNumKeys: " + beforeNumKeys + "\n");
   aStr.append("   beforeNumInVM: " + beforeNumInVM + "\n");
   aStr.append("   beforeNumOnDisk: " + beforeNumOnDisk + "\n");
   aStr.append("   beforeNumOverflowOnDisk: " + beforeNumOverflowOnDisk + "\n");
   aStr.append("   afterNumKeys: " + afterNumKeys + "\n");
   aStr.append("   afterNumInVM: " + afterNumInVM + "\n");
   aStr.append("   afterNumOnDisk: " + afterNumOnDisk + "\n");
   aStr.append("   afterNumOverflowOnDisk: " + afterNumOverflowOnDisk + "\n");
   aStr.append("   valueInVM: " + valueInVM + "\n");
   aStr.append("   valueOnDisk: " + valueOnDisk + "\n");
   Log.getLogWriter().info(aStr.toString());
//   printKeyStatus();

   // check expected number of keys; should increment by 1
   checkValue(beforeNumKeys+1, afterNumKeys, "after num keys");

   // check containsKey, containsValueForKey; these should always be true whether on disk or not
   boolean containsKey = aRegion.containsKey(key);
   boolean containsValueForKey = aRegion.containsValueForKey(key);
   checkValue(true, containsKey, "containsKey()");
   checkValue(true, containsValueForKey, "containsValueForKey()");

   switch (regionKind) {
      case NO_DISK: {
         // numInVM should increment
            checkValue(beforeNumKeys+1, afterNumInVM, "after numInVM");
         // zero should be on disk
            checkValue(0, afterNumOnDisk, "afterNumOnDisk");
            checkValue(0, afterNumOverflowOnDisk, "afterNumOverflowOnDisk");
         // value should be in VM
            checkValue(value, valueInVM, "value in VM");
         // value should not be on disk
            checkValue(null, valueOnDisk, "value on disk");
      } break;

      case DISK_FOR_OVRFLW: {
         if (isMemLRU) {
            // The number of bytes in the VM is found by:
            //     (num entries in VM that contain key AND value) * (num bytes for a key AND value)
            //     plus
            //     (num entries in VM that contain key only) * (num bytes for a key only)
            // For an overflow configuration, the number of entries in the VM that contain
            // the key only = number of entries overflowed to disk.
            long beforeBytesInVM = (beforeNumInVM * bytesPerEntry_keyValue) +
                                   (beforeNumOnDisk * bytesPerEntry_keyOnly);
            long afterBytesInVM = (afterNumInVM * bytesPerEntry_keyValue) +
                                  (afterNumOverflowOnDisk * bytesPerEntry_keyOnly);
            boolean evicted = (afterNumInVM <= beforeNumInVM);
            Log.getLogWriter().info("   beforeBytesInVM: " + beforeBytesInVM);
            Log.getLogWriter().info("   afterBytesInVM: " + afterBytesInVM);
            Log.getLogWriter().info("   evicted: " + evicted);
            if (evicted) { // we evicted
               if (afterBytesInVM < minEvictionBytes) { // we evicted too early
                  throw new TestException("Early eviction: afterBytesInVM is " + afterBytesInVM +
                        ", minEvictionBytes is " + minEvictionBytes);
               }
            }
            // whether we evicted or not, make sure num bytes didn't go too high
            // if we fill up the VM (all entries are on disk), allow the entry to
            // be added (successfully).  All entries will be written to disk (until
            // we run out of heap.
            if (afterBytesInVM > maxBytes) { // too high
               if (afterNumInVM == 0) {      // ok if all entries are being written to disk
                  Log.getLogWriter().info("Expected afterBytesInVM(" + afterBytesInVM + ") > maxBytes (" + maxBytes + ") but afterNumInVM == 0 so all entries are being written to disk; continuing test");
               } else {
                  throw new TestException("Expected afterBytesInVM " + afterBytesInVM +
                         " to be <= maxBytes " + maxBytes);
               }
            }

            if (afterNumInVM > 0) {
               // Any eviction done was done to an older entry, not the one we just put;
               // the object we just put should be in the VM.
               checkValue(value, valueInVM, "value in VM");

               // value should not be on disk whether we overflowed or not
               checkValue(null, valueOnDisk, "value on disk");
            } else {
               // All entries are on disk, even the one we just put because the region
               // is using all its space for the keys
               checkValue(null, valueInVM, "value in VM");

               // value should not be on disk whether we overflowed or not
               checkValue(value, valueOnDisk, "value on disk");
            }
         } else { // is LRU
            boolean  overflow = (beforeNumKeys >= evictionLimit);
            if (overflow) { // this add should have caused overflow
               // numInVM should remain unchanged
                  checkValue(beforeNumInVM, afterNumInVM, "numInVM");
               // numOverflowOnDisk should increment
                  checkValue(beforeNumOverflowOnDisk+1, afterNumOverflowOnDisk, "numOverflowOnDisk");
               // check that the LRU entry was evicted
                  checkOverflowEviction();
            } else { // this add should NOT have caused overflow
               // numInVM should increment
                  checkValue(beforeNumKeys+1, afterNumInVM, "after numInVM");
               // numOnDisk should remain unchanged
                  checkValue(beforeNumOnDisk, afterNumOnDisk, "afterNumOnDisk");
               // numOverflowOnDisk should remain unchanged
                  checkValue(beforeNumOverflowOnDisk, afterNumOverflowOnDisk, "afterNumOnDisk");
            }
            // Any eviction done was done to an older entry, not the one we just put;
            // the object we just put should be in the VM.
            checkValue(value, valueInVM, "value in VM");

            // value should not be on disk whether we overflowed or not
            checkValue(null, valueOnDisk, "value on disk");
         }

      } break;

      case DISK_FOR_PERSIST: {
         // numInVM should increment
            checkValue(beforeNumInVM+1, afterNumInVM, "numInVM");
         // numOnDisk should increment
            checkValue(beforeNumOnDisk+1, afterNumOnDisk, "numOnDisk");
         // value should be in vm
            checkValue(value, valueInVM, "value in VM");
         // value should be on disk
            checkValue(value, valueOnDisk, "value on disk");
      } break;

      case DISK_FOR_OVRFLW_PERSIST: {
         if (isMemLRU) {
            // The number of bytes in the VM is found by:
            //     (num entries in VM that contain key AND value) * (num bytes for a key AND value)
            //     plus
            //     (num entries in VM that contain key only) * (num bytes for a key only)
            // For an overflow with persistence configuration, the number of entries in the VM that
            // contain the key only =
            //    (total number of entries) - (number of entries with key AND value in the VM)
            // because all entries have a value on disk, but not all entries in the VM have a value in the VM
            long beforeNumKeysOnlyInVM = beforeNumKeys - beforeNumInVM;
            long beforeBytesInVM = (beforeNumInVM * bytesPerEntry_keyValue) +
                                   (beforeNumKeysOnlyInVM * bytesPerEntry_keyOnly);
            long afterNumKeysOnlyInVM = afterNumKeys - afterNumInVM;
            long afterBytesInVM = (afterNumInVM * bytesPerEntry_keyValue) +
                                  (afterNumKeysOnlyInVM * bytesPerEntry_keyOnly);
            boolean evicted = (afterNumInVM <= beforeNumInVM);
            Log.getLogWriter().info("   beforeNumKeysOnlyInVM: " + beforeNumKeysOnlyInVM);
            Log.getLogWriter().info("   beforeBytesInVM: " + beforeBytesInVM);
            Log.getLogWriter().info("   afterNumKeysOnlyInVM: " + afterNumKeysOnlyInVM);
            Log.getLogWriter().info("   afterBytesInVM: " + afterBytesInVM);
            Log.getLogWriter().info("   evicted: " + evicted);
            if (evicted) { // we evicted
               if (afterBytesInVM < minEvictionBytes) { // we evicted too early
                  throw new TestException("Early eviction: afterBytesInVM is " + afterBytesInVM +
                        ", minEvictionBytes is " + minEvictionBytes);
               }
            }
            // whether we evicted or not, make sure num bytes didn't go too high
            // if we fill up the VM (all entries are on disk), allow the entry to
            // be added (successfully).  All entries will be written to disk (until
            // we run out of heap.
            if (afterBytesInVM > maxBytes) { // too high
               if (afterNumInVM == 0) {      // ok if all entries are being written to disk
                  Log.getLogWriter().info("Expected afterBytesInVM(" + afterBytesInVM + ") > maxBytes (" + maxBytes + ") but afterNumInVM == 0 so all entries are being written to disk; continuing test");
               } else {
                  throw new TestException("Expected afterBytesInVM " + afterBytesInVM + " to be <= maxBytes " + maxBytes);
               }
            }

            if (afterNumInVM > 0) {
               // value should be in vm whether we overflowed or not
               checkValue(value, valueInVM, "value in VM");

               // value should be on disk whether we overflowed or not
               checkValue(value, valueOnDisk, "value on disk");
             } else {
               // All entries are on disk, even the one we just put because the region
               // is using all its space for the keys
               checkValue(null, valueInVM, "value in VM");

               // value should not be on disk whether we overflowed or not
               checkValue(value, valueOnDisk, "value on disk");
             }
         } else { // is LRU
            boolean overflow = (beforeNumKeys >= evictionLimit);
            if (overflow) { // this add should have caused overflow
               // numInVM should remain unchanged
                  checkValue(beforeNumInVM, afterNumInVM, "numInVM");
               // numOnDisk should increment
                  checkValue(beforeNumOnDisk+1, afterNumOnDisk, "numOnDisk");
               // check that the LRU entry was evicted
                  checkOverflowEviction();
            } else { // this add should NOT have caused overflow
               // numInVM should increment
                  checkValue(beforeNumKeys+1, afterNumInVM, "after numInVM");
               // numOnDisk should increment
                  checkValue(beforeNumOnDisk+1, afterNumOnDisk, "afterNumOnDisk");
            }
            // value should be in vm whether we overflowed or not
            checkValue(value, valueInVM, "value in VM");

            // value should be on disk whether we overflowed or not
            checkValue(value, valueOnDisk, "value on disk");
         }

      } break;

      default: {
         throw new TestException("Unknown region kind " + regionKind);
      }
   }
}

// other methods
//========================================================================

/** Verify the long has the expected value.
 *
 *  @params expectedValue The expected value of the long.
 *  @params actualValue The actual value of the long.
 *  @params valueDescript A String used for logging an error.
 *
 *  @throws TestException if the expected is not equal to the actual.
 */
protected void checkValue(long expectedValue, long actualValue, String valueDescript) {

   if (expectedValue != actualValue) {
      printKeyStatus();
      throw new TestException("Expected " + valueDescript + " to be " + expectedValue +
                ", but it is " + actualValue);
   }
}

/** Verify the int has the expected value.
 *
 *  @params expectedValue The expected value of the int.
 *  @params actualValue The actual value of the int.
 *  @params valueDescript A String used for logging an error.
 *
 *  @throws TestException if the expected is not equal to the actual.
 */
protected void checkValue(int expectedValue, int actualValue, String valueDescript) {

   if (expectedValue != actualValue) {
      printKeyStatus();
      throw new TestException("Expected " + valueDescript + " to be " + expectedValue +
                ", but it is " + actualValue);
   }
}

/** Verify the boolean has the expected value.
 *
 *  @params expectedValue The expected value of the boolean.
 *  @params actualValue The actual value of the boolean.
 *  @params valueDescript A String used for logging an error.
 *
 *  @throws TestException if the expected is not equal to the actual.
 */
protected void checkValue(boolean expectedValue, boolean actualValue, String valueDescript) {

   if (expectedValue != actualValue) {
      throw new TestException("Expected " + valueDescript + " to be " + expectedValue +
                ", but it is " + actualValue);
   }
}

/** Verify the Object has the expected value.
 *
 *  @params expectedObj The expected value of the Object.
 *  @params actualObj The actual value of the Object.
 *  @params descript A String used for logging an error.
 *
 *  @throws TestException if the expected is not equal to the actual.
 */
protected void checkValue(Object expectedObj, Object actualObj, String descript) {
  if (expectedObj == null) {
    if (actualObj == null) {
      return;
    }
    else {
      throw new TestException("Expected " + descript + " to be "
          + TestHelper.toString(expectedObj) + ", but it is "
          + TestHelper.toString(actualObj));
    }
  }
  if (expectedObj instanceof byte[]) {
    if (actualObj instanceof byte[]) {
      if (Arrays.equals((byte[])expectedObj, (byte[])actualObj)) {
        return;
      }
      else {
        throw new TestException("Expected " + descript + " to be "
            + TestHelper.toString(expectedObj) + ", but it is "
            + TestHelper.toString(actualObj));
      }
    }
  }

  if (expectedObj instanceof boolean[]) {
    if (actualObj instanceof boolean[]) {
      if (Arrays.equals((boolean[])expectedObj, (boolean[])actualObj)) {
        return;
      }
      else {
        throw new TestException("Expected " + descript + " to be "
            + TestHelper.toString(expectedObj) + ", but it is "
            + TestHelper.toString(actualObj));
      }
    }
  }

  if (expectedObj instanceof long[]) {
    if (actualObj instanceof long[]) {
      if (Arrays.equals((long[])expectedObj, (long[])actualObj)) {
        return;
      }
      else {
        throw new TestException("Expected " + descript + " to be "
            + TestHelper.toString(expectedObj) + ", but it is "
            + TestHelper.toString(actualObj));
      }
    }
  }

  if (expectedObj instanceof int[]) {
    if (actualObj instanceof int[]) {
      if (Arrays.equals((int[])expectedObj, (int[])actualObj)) {
        return;
      }
      else {
        throw new TestException("Expected " + descript + " to be "
            + TestHelper.toString(expectedObj) + ", but it is "
            + TestHelper.toString(actualObj));
      }
    }
  }

  if (expectedObj instanceof short[]) {
    if (actualObj instanceof short[]) {
      if (Arrays.equals((short[])expectedObj, (short[])actualObj)) {
        return;
      }
      else {
        throw new TestException("Expected " + descript + " to be "
            + TestHelper.toString(expectedObj) + ", but it is "
            + TestHelper.toString(actualObj));
      }
    }
  }

  if (expectedObj instanceof double[]) {
    if (actualObj instanceof double[]) {
      if (Arrays.equals((double[])expectedObj, (double[])actualObj)) {
        return;
      }
      else {
        throw new TestException("Expected " + descript + " to be "
            + TestHelper.toString(expectedObj) + ", but it is "
            + TestHelper.toString(actualObj));
      }
    }
  }

  if (expectedObj instanceof float[]) {
    if (actualObj instanceof float[]) {
      if (Arrays.equals((float[])expectedObj, (float[])actualObj)) {
        return;
      }
      else {
        throw new TestException("Expected " + descript + " to be "
            + TestHelper.toString(expectedObj) + ", but it is "
            + TestHelper.toString(actualObj));
      }
    }
  }

  if (expectedObj instanceof char[]) {
    if (actualObj instanceof char[]) {
      if (Arrays.equals((char[])expectedObj, (char[])actualObj)) {
        return;
      }
      else {
        throw new TestException("Expected " + descript + " to be "
            + TestHelper.toString(expectedObj) + ", but it is "
            + TestHelper.toString(actualObj));
      }
    }
  }

  if (expectedObj instanceof StringBuffer) {
    if (actualObj instanceof StringBuffer) {
     if( ( ( (StringBuffer)expectedObj).toString() ).equals( ( (StringBuffer)actualObj ).toString() ) ) {
        return ;
      }
      else {
        throw new TestException("Expected " + descript + " to be "
            + TestHelper.toString(expectedObj) + ", but it is "
            + TestHelper.toString(actualObj));
      }
    }
  }

  if (!expectedObj.equals(actualObj)) {
    throw new TestException("Expected " + descript + " to be "
        + TestHelper.toString(expectedObj) + ", but it is "
        + TestHelper.toString(actualObj));
  }

}

/** Check that the least recently used entry was evicted as overflow. Also,
 *  check that the next few least recently used entries were not evicted.
 */
protected void checkOverflowEviction() {
   if (!checkLRU)
      return;
   final int NEXT_LRU_TO_CHECK = 100;

   // Get the oldest key, the one we expected to have been evicted on overflow
   long expEvictedKeyCounter = ((Long)(DiskRegBB.getBB().getSharedMap().get(sharedMapKey))).longValue();
   String expEvictedKey = NameFactory.getObjectNameForCounter(expEvictedKeyCounter);
   Object valueInVM = DiskRegUtil.getValueInVM(aRegion, expEvictedKey);
   Object valueOnDisk =  DiskRegUtil.getValueOnDiskOrBuffer(aRegion, expEvictedKey);
   checkValue(null, valueInVM, "LRU overflowed value");
   if (valueOnDisk != null) {
      printKeyStatus();
      throw new TestException("Expected LRU overflowed value on disk to be null but it is " +
                TestHelper.toString(valueOnDisk));
   }

   // check that the next least recently used entries were not evicted
   long newestKeyCounter = NameFactory.getPositiveNameCounter();
   long numToCheck = Math.min(expEvictedKeyCounter + NEXT_LRU_TO_CHECK, newestKeyCounter);
   for (long i = expEvictedKeyCounter+1; i <= numToCheck; i++) {
      String key = NameFactory.getObjectNameForCounter(i);
      valueInVM = DiskRegUtil.getValueInVM(aRegion, key);
      checkValue(null, valueInVM, "value in VM (key: " + key + ")");
   }

   // change the least recently used key
   DiskRegBB.getBB().getSharedMap().put(sharedMapKey, new Long(expEvictedKeyCounter+1));
}

/** Prints the status of which keys are in the VM and which are on disk.
 *
 */
private void printKeyStatus() {
   long lastNameCounter = NameFactory.getPositiveNameCounter();
   BitSet onDisk = new BitSet((int)lastNameCounter+1);  // index 0 is ignored
   BitSet inVM = new BitSet((int)lastNameCounter+1);    // index 0 is ignored
   for (int index = 1; index <= lastNameCounter; index++) {
       Object key = getFixedLengthKeyForName(NameFactory.getObjectNameForCounter(index));
       Object valueInVM = DiskRegUtil.getValueInVM(aRegion, key);
       Object valueOnDisk =  DiskRegUtil.getValueOnDiskOrBuffer(aRegion, key);
       if (valueInVM != null)
          inVM.set(index);
       if (valueOnDisk != null)
          onDisk.set(index);
   }
   Log.getLogWriter().info("Entries in VM: " + getBitSetRanges(inVM, lastNameCounter) + "\n" +
                           "Entries on disk: " + getBitSetRanges(onDisk, lastNameCounter));

}

private String getBitSetRanges(BitSet aBitSet, long maxBits) {
   StringBuffer aStr = new StringBuffer();
   boolean firstTime = true;
   int firstIndex = 0;
   boolean currentBoolState = false;
   for (int i = 1; i <= maxBits; i++) {
      boolean aBool = aBitSet.get(i);
      if (firstTime) {
         firstTime = false;
         currentBoolState = aBool;
         firstIndex = i;
      }
      if (aBool != currentBoolState) { // we changed from one state to the other
         aStr.append(firstIndex + " - " + (i-1) + " is " + currentBoolState + "\n");
         currentBoolState = aBool;
         firstIndex = i;
      }
      if (i == maxBits) { // last index
         aStr.append(firstIndex + " - " + i + " is " + currentBoolState + "\n");
      }
   }
   return aStr.toString();
}

//========================================================================
// string methods

/** Return a string describing this test instance.
 *
 */
public String toVerboseString() {
   StringBuffer aStr = new StringBuffer();
   aStr.append(super.toVerboseString());
   aStr.append("     checkLRU: " + checkLRU + "\n");
   aStr.append("     isMemLRU: " + isMemLRU + "\n");
   aStr.append("     perEntryOverhead: " + perEntryOverhead + "\n");
   aStr.append("     bytesPerEntry_keyValue: " + bytesPerEntry_keyValue + "\n");
   aStr.append("     bytesPerEntry_keyOnly: " + bytesPerEntry_keyOnly + "\n");
   aStr.append("     numEntriesDeviation: " + numEntriesDeviation + "\n");
   aStr.append("     minEvictionBytes: " + minEvictionBytes + "\n");
   aStr.append("     maxBytes: " + maxBytes + "\n");
   return aStr.toString();
}

}


text:
package com.arm.hackbri.landmoney.view.adapter;

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

import com.arm.hackbri.landmoney.R;
import com.arm.hackbri.landmoney.model.response.Debit;
import com.arm.hackbri.landmoney.view.viewComponent.LoadingFeedItemView;

import java.text.NumberFormat;
import java.util.List;
import java.util.Locale;

import butterknife.Bind;
import butterknife.ButterKnife;

public class DebitAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    public static final int VIEW_TYPE_DEFAULT = 1;
    public static final int VIEW_TYPE_LOADER = 2;

    private final List<Debit> debits;

    private Context context;
    private OnDebitClickListener onDebitClickListener;

    private boolean showLoadingView = false;

    public DebitAdapter(Context context, List<Debit> debits) {

        this.debits = debits;
        this.context = context;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == VIEW_TYPE_DEFAULT) {
            View view = LayoutInflater.from(context).inflate(R.layout.item_debit, parent, false);
            CellHutangViewHolder cellHutangViewHolder = new CellHutangViewHolder(view);
            setupClickableViews(view, cellHutangViewHolder);
            return cellHutangViewHolder;
        } else if (viewType == VIEW_TYPE_LOADER) {
            LoadingFeedItemView view = new LoadingFeedItemView(context);
            view.setLayoutParams(new LinearLayoutCompat.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT)
            );
            return new LoadingCellHutangViewHolder(view);
        }

        return null;
    }

    private void setupClickableViews(final View view, final CellHutangViewHolder cellHutangViewHolder) {
        cellHutangViewHolder.btnBayar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onDebitClickListener.onBayarClick(v, cellHutangViewHolder.getAdapterPosition(), debits.get(cellHutangViewHolder.getAdapterPosition()).getDebtId());
            }
        });
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) {
        ((CellHutangViewHolder) viewHolder).bindView(debits.get(position));

        if (getItemViewType(position) == VIEW_TYPE_LOADER) {
            bindLoadingFeedItem((LoadingCellHutangViewHolder) viewHolder);
        } else {
            bindItemDebit((CellHutangViewHolder) viewHolder, debits.get(position));
        }
    }

    private void bindItemDebit(CellHutangViewHolder viewHolder, final Debit debit) {
        viewHolder.tvName.setText(debit.getUserName());
        viewHolder.tvAmount.setText("Rp. " + NumberFormat.getNumberInstance(Locale.US).format(debit.getDebtAmt()));
        viewHolder.tvDesc.setText(debit.getDebtDesc());
        viewHolder.tvType.setText(debit.getUserType());

//        switch (debit.getStatus()) {
//            case Debit.STATUS_COMPLETED:
//                viewHolder.btnBayar.setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View v) {
//                        onDebitClickListener.onBayarClick();
//                    }
//                });
//                break;
//            case Debit.STATUS_PENDING:
//                break;
//            case Debit.STATUS_UNPAID:
//                break;
//        }
//        viewHolder.btnBayar.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//
//                switch (debit.getStatus()) {
//                    case Debit.STATUS_COMPLETED:
//
//                        break;
//                    case Debit.STATUS_PENDING:
//                        break;
//                    case Debit.STATUS_UNPAID:
//                        break;
//                }
//            }
//        });
    }

    private void bindLoadingFeedItem(final LoadingCellHutangViewHolder holder) {
        holder.loadingFeedItemView.setOnLoadingFinishedListener(new LoadingFeedItemView.OnLoadingFinishedListener() {
            @Override
            public void onLoadingFinished() {
                showLoadingView = false;
                notifyItemChanged(0);
            }
        });
        holder.loadingFeedItemView.startLoading();
    }

    @Override
    public int getItemViewType(int position) {
        if (showLoadingView && position == 0) {
            return VIEW_TYPE_LOADER;
        } else {
            return VIEW_TYPE_DEFAULT;
        }
    }

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

    public void updateItems(boolean animated) {
        debits.clear();
//        debits.addAll(Arrays.asList(
//                new FeedItem(33, false),
//                new FeedItem(1, false),
//                new FeedItem(223, false),
//                new FeedItem(2, false),
//                new FeedItem(6, false),
//                new FeedItem(8, false),
//                new FeedItem(99, false)
//        ));
        if (animated) {
            notifyItemRangeInserted(0, debits.size());
        } else {
            notifyDataSetChanged();
        }
    }

    public void setOnDebitClickListener(OnDebitClickListener onDebitClickListener) {
        this.onDebitClickListener = onDebitClickListener;
    }

    public void showLoadingView() {
        showLoadingView = true;
        notifyItemChanged(0);
    }

    public static class CellHutangViewHolder extends RecyclerView.ViewHolder {

        @Bind(R.id.ivUserProfile)
        ImageView ivUserProfile;

        @Bind(R.id.btnBayar)
        Button btnBayar;

        @Bind(R.id.tvName)
        TextView tvName;

        @Bind(R.id.description)
        TextView tvDesc;

        @Bind(R.id.tvAmount)
        TextView tvAmount;
        @Bind(R.id.type)
        TextView tvType;
        Debit debit;

        public CellHutangViewHolder(View view) {
            super(view);
            ButterKnife.bind(this, view);
        }

        public void bindView(Debit debit) {
            this.debit = debit;
        }

        public Debit getDebit() {
            return debit;
        }
    }

    public static class LoadingCellHutangViewHolder extends CellHutangViewHolder {

        LoadingFeedItemView loadingFeedItemView;

        public LoadingCellHutangViewHolder(LoadingFeedItemView view) {
            super(view);
            this.loadingFeedItemView = view;
        }

        @Override
        public void bindView(Debit debit) {
            super.bindView(debit);
        }
    }

    public interface OnDebitClickListener {
        void onBayarClick(View v, int position, String debtId);

    }
}


text:
/* Shared assets*/

body {
    background: url(images/refugee_pic.jpg) no-repeat center center fixed;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}
div.white_overlay {
    width: 900px;
    height: 650px;
    align: "middle";
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translateX(-50%) translateY(-50%);
    opacity: 0.7;
    background-color: white;
    z-index: 0;
}
button {
    height: 50px;
    width: 150px;
    border-radius: 4px;
    background-color: #4CAF50;
    /* Green */
    border: none;
    color: white;
    padding: 16px 32px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    font-size: 16px;
    margin: 4px 2px;
    -webkit-transition-duration: 0.4s;
    /* Safari */
    transition-duration: 0.4s;
    cursor: pointer;
    background-color: white;
    color: black;
    border: 2px solid #F78F1E;
}
button:hover {
    background-color: #F78F1E;
    color: white;
}

/* language page assets*/

#language_heading {
    position: absolute;
    top: 22.5%;
    left: 50%;
    transform: translateX(-50%) translateY(-50%);
    color: #000;
    z-index: 1;
}
#language_table {
    align: "middle";
    position: absolute;
    top: 52%;
    left: 50%;
    transform: translateX(-50%) translateY(-50%);
    z-index: 1;
}
p.lang_text {
    font-size: 20px;
}
#language_button {
    position: absolute;
    top: 80%;
    left: 32.5%;
    transform: translateX(-50%) translateY(-50%);
    z-index: 2;
}