text:
package org.deviceconnect.android.deviceplugin.host.video;

import org.deviceconnect.android.deviceplugin.host.R;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.MediaController;
import android.widget.VideoView;

/**
 * Video Player.
 *
 * @author NTT DOCOMO, INC.
 */
public class VideoPlayer extends Activity implements OnCompletionListener {

    /** VideoView. */
    private VideoView mVideoView;

    /** URI. */
    private Uri mUri;

    /** Ready flag. */
    private Boolean mIsReady = false;

    @Override
    public void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // タイトルを非表示
        requestWindowFeature(Window.FEATURE_NO_TITLE);

        setContentView(R.layout.video_player);
        mVideoView = (VideoView) findViewById(R.id.videoView);

        // 再生するVideoのURI
        Intent mIntent = this.getIntent();
        mUri = mIntent.getData();
    }

    @Override
    public void onResume() {
        super.onResume();
        // ReceiverをRegister
        IntentFilter mIntentFilter = new IntentFilter();
        mIntentFilter.addAction(VideoConst.SEND_HOSTDP_TO_VIDEOPLAYER);
        registerReceiver(mReceiver, mIntentFilter);

        MediaController mMediaController = new MediaController(this);
        mMediaController.setVisibility(View.GONE);
        mMediaController.setAnchorView(mVideoView);

        mVideoView.setMediaController(mMediaController);
        mVideoView.setKeepScreenOn(true);
        mVideoView.setVideoURI(mUri);
        mVideoView.requestFocus();
        mVideoView.setOnCompletionListener(this);
        mVideoView.setOnPreparedListener(new OnPreparedListener() {
            @Override
            public void onPrepared(final MediaPlayer mp) {
                mVideoView.start();
                mIsReady = true;
            }
        });
    }

    @Override
    protected void onPause() {
        super.onPause();

        // ReceiverをUnregister
        if (mReceiver != null) {
            unregisterReceiver(mReceiver);
        }
    }

    /**
     * 受信. 受信用のReceiver
     */
    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(final Context context, final Intent intent) {
            if (intent.getAction().equals(VideoConst.SEND_HOSTDP_TO_VIDEOPLAYER)) {
                String mVideoAction = intent.getStringExtra(VideoConst.EXTRA_NAME);
                if (mVideoAction.equals(VideoConst.EXTRA_VALUE_VIDEO_PLAYER_PLAY)) {
                    mVideoView.start();
                } else if (mVideoAction.equals(VideoConst.EXTRA_VALUE_VIDEO_PLAYER_STOP)) {
                    if (mIsReady) {
                        mVideoView.stopPlayback();
                    }
                    unregisterReceiver(mReceiver);
                    mReceiver = null;
                    mIsReady = false;
                    Intent mIntent = new Intent(VideoConst.SEND_VIDEOPLAYER_TO_HOSTDP);
                    mIntent.putExtra(VideoConst.EXTRA_NAME, VideoConst.EXTRA_VALUE_VIDEO_PLAYER_STOP);
                    sendBroadcast(mIntent);
                    finish();
                } else if (mVideoAction.equals(VideoConst.EXTRA_VALUE_VIDEO_PLAYER_PAUSE)) {
                    mVideoView.pause();
                } else if (mVideoAction.equals(VideoConst.EXTRA_VALUE_VIDEO_PLAYER_RESUME)) {
                    mVideoView.resume();
                    mVideoView.start();
                } else if (mVideoAction.equals(VideoConst.EXTRA_VALUE_VIDEO_PLAYER_SEEK)) {
                    int pos = intent.getIntExtra("pos", -1);
                    mVideoView.seekTo(pos);
                } else if (mVideoAction.equals(VideoConst.EXTRA_VALUE_VIDEO_PLAYER_GET_POS)) {
                    Intent mIntent = new Intent(VideoConst.SEND_VIDEOPLAYER_TO_HOSTDP);
                    mIntent.putExtra(VideoConst.EXTRA_NAME, VideoConst.EXTRA_VALUE_VIDEO_PLAYER_PLAY_POS);
                    mIntent.putExtra("pos", mVideoView.getCurrentPosition());
                    sendBroadcast(mIntent);
                }
            }
        }
    };

    @Override
    public void onCompletion(final MediaPlayer mp) {
        mIsReady = false;
        Intent mIntent = new Intent(VideoConst.SEND_VIDEOPLAYER_TO_HOSTDP);
        mIntent.putExtra(VideoConst.EXTRA_NAME, VideoConst.EXTRA_VALUE_VIDEO_PLAYER_PLAY_COMPLETION);
        sendBroadcast(mIntent);
        finish();
    }
}


text:
package com.brandon.snake.render.renderer;

import java.util.HashMap;
import java.util.Map;

import com.brandon.snake.game.Cell;
import com.brandon.snake.game.Game;
import com.brandon.snake.graphics.Mesh;
import com.brandon.snake.graphics.Shader;
import com.brandon.snake.math.Matrix4f;
import com.brandon.snake.math.Vector3f;
import com.brandon.snake.render.Renderer;
import com.brandon.snake.render.renderer.entity.EntityModel;
import com.brandon.snake.util.MeshUtil;

public class EntityRenderer implements Renderer {
	//Constants
	final private static Vector3f POISON_COLOR = new Vector3f(1, 0, 0);
	final private static Vector3f FOOD_COLOR = new Vector3f(0, 1, 0);

	private Map<Cell, EntityModel> poisonModels;
	private EntityModel foodModel;

	//Rendering resources
	private Shader shader;
	private Mesh mesh;

	final private int GAME_WIDTH;
	final private int GAME_HEIGHT;

	public EntityRenderer(int gameWidth, int gameHeight) {
		GAME_WIDTH = gameWidth;
		GAME_HEIGHT = gameHeight;
		poisonModels = new HashMap<>();
	}

	@Override
	public void init() {
		shader = new Shader("res/shaders/entity.vs", "res/shaders/entity.fs");
		shader.setUniformMat4f("proj", Matrix4f.orthographic(0, GAME_WIDTH, 0, GAME_HEIGHT, 1, -1));
		mesh = MeshUtil.createEntityMesh(-.5f, -.5f, .5f, .5f);
	}

	@Override
	public void reset(Game game) {
		poisonModels.clear();
		foodModel = new EntityModel(game.getFood());
	}

	@Override
	public void render(Game game) {
		boolean paused = game.isPaused();
		shader.bind();

		//Draw Food
		shader.setUniform3f("color", FOOD_COLOR);
		foodModel.render(shader, mesh, paused);

		//Draw poison models
		shader.setUniform3f("color", POISON_COLOR);
		poisonModels.values().removeIf(e -> renderAndRemove(e, shader, mesh, paused));
	}

	private boolean renderAndRemove(EntityModel poison, Shader s, Mesh m, boolean paused) {
		poison.render(shader, mesh, paused);
		return poison.isDoneRemoving();
	}
	@Override
	public void update(Game game) {
		Cell poison = game.getAddedPoison();
		if (poison != null) {
			poisonModels.put(poison, new EntityModel(poison));
		}

		poison = game.getRemovedPoison();
		if (poison != null) {
			poisonModels.get(poison).beginRemoving();
		}

		Cell food = game.getAddedFood();
		if (food != null) {
			foodModel = new EntityModel(food);
		}
	}

	@Override
	public void destroy() {
		shader.destroy();
		mesh.destroy();
	}
}

redpajama_set_name: RedPajamaGithub


text:
require 'ipscan'
require 'thor'

module IPScan
  class CLI < Thor
    desc "range [SCAN_RANGE]", "scan 192.168.1.0-254"
    def range(range)
      IPScan.scan(range)
    end
  end
end


text:
package builtin

import (
  "github.com/twitchyliquid64/CNC/plugin/exec"
  "github.com/twitchyliquid64/CNC/logging"
  "github.com/robertkrimen/otto"
  "bytes"
	"crypto/tls"
	"encoding/base64"
	"errors"
	"fmt"
	"io/ioutil"
	"net/smtp"
	"path/filepath"
	"strings"
)

var fromAddr string
var password string

// Called when JS code executes gmail.setup()
// passes in gmail address and the password to use
// when authenticating.
func function_gmail_setup(plugin *exec.Plugin, call otto.FunctionCall)otto.Value{
  fromAddr = call.Argument(0).String()
  password = call.Argument(1).String()
  return otto.Value{}
}

// Called when JS code executes gmail.sendMessage()
//
//
func function_gmail_sendMessage(plugin *exec.Plugin, call otto.FunctionCall)otto.Value{
  subjectName := call.Argument(0).String()
  destObj,err := call.Argument(1).Export()
  message     := call.Argument(2).String()
  if err != nil {
    logging.Error("plugin-gmail", err.Error())
  }

  destinations, ok := destObj.([]interface{})
  if !ok {
    logging.Error("plugin-gmail", "Destination array invalid.")
  }

  email := Compose(subjectName, message)
  email.From = fromAddr
  email.Password = password

  // Defaults to "text/plain; charset=utf-8" if unset.
  email.ContentType = "text/html; charset=utf-8"

  // Normally you'll only need one of these, but I thought I'd show both.
  for _, destination := range destinations{
    email.AddRecipient(destination.(string))
  }

  err = email.Send()
  if err != nil {
      logging.Error("plugin-gmail", err.Error())
  }

  return otto.Value{}
}

// Email represents a single message, which may contain
// attachments.
type Email struct {
	Subject, Body string
	From          string
	Password      string
	ContentType   string
	To            []string
	Attachments   map[string][]byte
}

// Compose begins a new email, filling the subject and body,
// and allocating memory for the list of recipients and the
// attachments.
func Compose(Subject, Body string) *Email {
	out := new(Email)
	out.Subject = Subject
	out.Body = Body
	out.To = make([]string, 0, 1)
	out.Attachments = make(map[string][]byte)
	return out
}

// Attach takes a filename and adds this to the message.
// Note that since only the filename is stored (and not
// its path, for privacy reasons), multiple files in
// different directories but with the same filename and
// extension cannot be sent.
func (e *Email) Attach(Filename string) error {
	b, err := ioutil.ReadFile(Filename)
	if err != nil {
		return err
	}

	_, fname := filepath.Split(Filename)
	e.Attachments[fname] = b
	return nil
}

// AddRecipient adds a single recipient.
func (e *Email) AddRecipient(Recipient string) {
	e.To = append(e.To, Recipient)
}

// AddRecipients adds one or more recipients.
func (e *Email) AddRecipients(Recipients ...string) {
	e.To = append(e.To, Recipients...)
}

// Send sends the email, returning any error encountered.
func (e *Email) Send() error {
	if e.From == "" {
		return errors.New("Error: No sender specified. Please set the Email.From field.")
	}
	if e.To == nil || len(e.To) == 0 {
		return errors.New("Error: No recipient specified. Please set the Email.To field.")
	}
	if e.Password == "" {
		return errors.New("Error: No password specified. Please set the Email.Password field.")
	}

	auth := smtp.PlainAuth(
		"",
		e.From,
		e.Password,
		"smtp.gmail.com",
	)

	conn, err := smtp.Dial("smtp.gmail.com:587")
	if err != nil {
		return err
	}

	err = conn.StartTLS(&tls.Config{ServerName: "smtp.gmail.com"})
	if err != nil {
		return err
	}

	err = conn.Auth(auth)
	if err != nil {
		return err
	}

	err = conn.Mail(e.From)
	if err != nil {
		if strings.Contains(err.Error(), "530 5.5.1") {
			return errors.New("Error: Authentication failure. Your username or password is incorrect.")
		}
		return err
	}

	for _, recipient := range e.To {
		err = conn.Rcpt(recipient)
		if err != nil {
			return err
		}
	}

	wc, err := conn.Data()
	if err != nil {
		return err
	}
	defer wc.Close()
	_, err = wc.Write(e.Bytes())
	if err != nil {
		return err
	}

	return nil
}

func (e *Email) Bytes() []byte {
	buf := bytes.NewBuffer(nil)

	buf.WriteString("Subject: " + e.Subject + "\n")
	buf.WriteString("MIME-Version: 1.0\n")

	// Boundary is used by MIME to separate files.
	boundary := "f46d043c813270fc6b04c2d223da"

	if len(e.Attachments) > 0 {
		buf.WriteString("Content-Type: multipart/mixed; boundary=" + boundary + "\n")
		buf.WriteString("--" + boundary + "\n")
	}

	if e.ContentType == "" {
		e.ContentType = "text/plain; charset=utf-8"
	}
	buf.WriteString(fmt.Sprintf("Content-Type: %s\n", e.ContentType))
	buf.WriteString(e.Body)

	if len(e.Attachments) > 0 {
		for k, v := range e.Attachments {
			buf.WriteString("\n\n--" + boundary + "\n")
			buf.WriteString("Content-Type: application/octet-stream\n")
			buf.WriteString("Content-Transfer-Encoding: base64\n")
			buf.WriteString("Content-Disposition: attachment; filename=\"" + k + "\"\n\n")

			b := make([]byte, base64.StdEncoding.EncodedLen(len(v)))
			base64.StdEncoding.Encode(b, v)
			buf.Write(b)
			buf.WriteString("\n--" + boundary)
		}

		buf.WriteString("--")
	}

	return buf.Bytes()
}


text:
import { PolymerElement } from '@polymer/polymer/polymer-element.js';
import { html } from '@polymer/polymer/lib/utils/html-tag.js';

import {PopupSelector} from "./PopupSelector";

class TimeSelector extends PolymerElement {
  static get template() {
    return html`
        <style>
            :host {
                --selector-font-size: 20px;
            }
            .time-selector {
                font-size: var(--selector-font-size);
            }
        </style>

        <label class="time-selector" on-click="_openCircle">[[value]]</label>`;
  }

  static get is() {
    return 'time-selector'
  }

  static get properties() {
    return {
      value: {
        type: String,
        notify: true
      },
      open: {
        type: Boolean,
        value: false
      },
      hours: {
        type: Boolean,
        value: true
      },
      updating: {
        type: Boolean,
        value: false
      }
    }
  }

  _openCircle() {
    const popup = new PopupSelector();
    document.body.appendChild(popup);
    popup.hours = this._parseHours();
    popup.minutes = this._parseMinutes();
    popup._populateString();
    popup._initializeCircle();

    popup.addEventListener('values', function (event) {
      this._valueChange(event)
    }.bind(this));
  }

  _valueChange(event) {
    if (event.detail) {
      this._populateString(event.detail.hours, event.detail.minutes);
    } else {
      console.log(event);
    }
  }

  // Parse the current minute value from the value string
  _parseMinutes() {
    return this.value.substring(this.value.indexOf(":") + 1, this.value.length);
  }

  // Parse the current hour value from the value string
  _parseHours() {
    return this.value.substring(0, this.value.indexOf(":"))
  }

  _populateString(hours, minutes) {
    if (hours.length < 2) {
      hours = '0' + hours;
    }
    if (minutes.length < 2) {
      minutes = '0' + minutes;
    }
    this.value = hours + ':' + minutes;
  }
}

window.customElements.define(TimeSelector.is, TimeSelector);


text:
package io.proleap.vb6.asg.metamodel.statement.ifstmt;

import java.util.List;

import io.proleap.vb6.asg.metamodel.statement.Statement;

/**
 * Conditionally executes a group of statements, depending on the value of an
 * expression.
 */
public interface BlockIfThenElse extends Statement {

	void addElseIfBlock(ElseIfBlock elseIfBlock);

	ElseBlock getElseBlock();

	List<ElseIfBlock> getElseIfBlocks();

	IfBlock getIfBlock();

	void setElseBlock(ElseBlock elseBlock);

	void setIfBlock(IfBlock ifBlock);

}


text:
package com.hazelcast.cache.impl;

import com.hazelcast.cache.CacheFromDifferentNodesTest;
import com.hazelcast.cache.CacheTestSupport;
import com.hazelcast.cache.HazelcastCacheManager;
import com.hazelcast.config.CacheConfig;
import com.hazelcast.config.Config;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.instance.Node;
import com.hazelcast.instance.TestUtil;
import com.hazelcast.internal.partition.InternalPartitionService;
import com.hazelcast.nio.serialization.DataSerializableFactory;
import com.hazelcast.nio.serialization.IdentifiedDataSerializable;
import com.hazelcast.spi.impl.AbstractNamedOperation;
import com.hazelcast.spi.impl.NodeEngineImpl;
import com.hazelcast.spi.impl.operationservice.InternalOperationService;
import com.hazelcast.test.HazelcastParallelClassRunner;
import com.hazelcast.test.TestHazelcastInstanceFactory;
import com.hazelcast.test.annotation.ParallelTest;
import com.hazelcast.test.annotation.QuickTest;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;

import javax.cache.Cache;
import javax.cache.configuration.FactoryBuilder;
import javax.cache.configuration.MutableCacheEntryListenerConfiguration;
import java.util.concurrent.Future;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;

@RunWith(HazelcastParallelClassRunner.class)
@Category({QuickTest.class, ParallelTest.class})
public class InternalCacheRecordStoreTest extends CacheTestSupport {

    private TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(2);

    @Override
    protected void onSetup() {
    }

    @Override
    protected void onTearDown() {
        factory.shutdownAll();
    }

    @Override
    protected HazelcastInstance getHazelcastInstance() {
        return factory.newHazelcastInstance(createConfig());
    }

    @Override
    protected Config createConfig() {
        Config config = super.createConfig();
        config.getSerializationConfig().addDataSerializableFactory(InternalCacheRecordStoreTestFactory.F_ID,
                new InternalCacheRecordStoreTestFactory());
        return config;
    }

    /**
     * Test for issue: https://github.com/hazelcast/hazelcast/issues/6618
     */
    @Test
    public void batchEventMapShouldBeCleanedAfterRemoveAll() {
        String cacheName = randomString();

        CacheConfig<Integer, String> config = createCacheConfig();
        CacheFromDifferentNodesTest.SimpleEntryListener<Integer, String> listener =
                new CacheFromDifferentNodesTest.SimpleEntryListener<Integer, String>();
        MutableCacheEntryListenerConfiguration<Integer, String> listenerConfiguration =
                new MutableCacheEntryListenerConfiguration<Integer, String>(
                        FactoryBuilder.factoryOf(listener), null, true, true);

        config.addCacheEntryListenerConfiguration(listenerConfiguration);

        Cache<Integer, String> cache = cacheManager.createCache(cacheName, config);
        assertNotNull(cache);

        Integer key = 1;
        String value = "value";
        cache.put(key, value);

        HazelcastInstance instance = ((HazelcastCacheManager) cacheManager).getHazelcastInstance();
        int partitionId = instance.getPartitionService().getPartition(key).getPartitionId();

        cache.removeAll();

        Node node = getNode(instance);
        assertNotNull(node);

        ICacheService cacheService = node.getNodeEngine().getService(ICacheService.SERVICE_NAME);
        AbstractCacheRecordStore recordStore = (AbstractCacheRecordStore) cacheService
                .getRecordStore("/hz/" + cacheName, partitionId);
        assertEquals(0, recordStore.batchEvent.size());
    }

    /**
     * Test for issue: https://github.com/hazelcast/hazelcast/issues/6983
     */
    @Test
    public void ownerStateShouldBeUpdatedAfterMigration() throws Exception {
        HazelcastCacheManager hzCacheManager = (HazelcastCacheManager) cacheManager;

        HazelcastInstance instance1 = hzCacheManager.getHazelcastInstance();
        Node node1 = TestUtil.getNode(instance1);
        NodeEngineImpl nodeEngine1 = node1.getNodeEngine();
        InternalPartitionService partitionService1 = nodeEngine1.getPartitionService();
        int partitionCount = partitionService1.getPartitionCount();

        String cacheName = randomName();
        CacheConfig cacheConfig = new CacheConfig().setName(cacheName);
        Cache<String, String> cache = cacheManager.createCache(cacheName, cacheConfig);
        String fullCacheName = hzCacheManager.getCacheNameWithPrefix(cacheName);

        for (int i = 0; i < partitionCount; i++) {
            String key = generateKeyForPartition(instance1, i);
            cache.put(key, "Value");
        }

        for (int i = 0; i < partitionCount; i++) {
            verifyPrimaryState(node1, fullCacheName, i, true);
        }

        HazelcastInstance instance2 = getHazelcastInstance();
        Node node2 = TestUtil.getNode(instance2);

        warmUpPartitions(instance1, instance2);
        waitAllForSafeState(instance1, instance2);

        for (int i = 0; i < partitionCount; i++) {
            boolean ownedByNode1 = partitionService1.isPartitionOwner(i);
            if (ownedByNode1) {
                verifyPrimaryState(node1, fullCacheName, i, true);
                verifyPrimaryState(node2, fullCacheName, i, false);
            } else {
                verifyPrimaryState(node1, fullCacheName, i, false);
                verifyPrimaryState(node2, fullCacheName, i, true);
            }
        }
    }

    private void verifyPrimaryState(Node node, String fullCacheName, int partitionId, boolean expectedState) throws Exception {
        NodeEngineImpl nodeEngine = node.getNodeEngine();
        InternalOperationService operationService = nodeEngine.getOperationService();
        Future<Boolean> isPrimaryOnNode = operationService.invokeOnTarget(
                ICacheService.SERVICE_NAME,
                createCacheOwnerStateGetterOperation(fullCacheName, partitionId),
                node.getThisAddress());
        assertEquals(expectedState, isPrimaryOnNode.get());
    }

    private CachePrimaryStateGetterOperation createCacheOwnerStateGetterOperation(String fullCacheName, int partitionId) {
        CachePrimaryStateGetterOperation operation = new CachePrimaryStateGetterOperation(fullCacheName);
        operation.setPartitionId(partitionId);
        operation.setValidateTarget(false);
        return operation;
    }

    static class CachePrimaryStateGetterOperation extends AbstractNamedOperation {

        private boolean isPrimary;

        private CachePrimaryStateGetterOperation() {
        }

        private CachePrimaryStateGetterOperation(String cacheName) {
            super(cacheName);
        }

        @Override
        public void run() throws Exception {
            ICacheService cacheService = getService();
            AbstractCacheRecordStore cacheRecordStore =
                    (AbstractCacheRecordStore) cacheService.getRecordStore(name, getPartitionId());
            isPrimary = cacheRecordStore.primary;
        }

        @Override
        public Object getResponse() {
            return isPrimary;
        }

        @Override
        public String getServiceName() {
            return ICacheService.SERVICE_NAME;
        }

        @Override
        public int getFactoryId() {
            return InternalCacheRecordStoreTestFactory.F_ID;
        }

        @Override
        public int getId() {
            return InternalCacheRecordStoreTestFactory.INTERNAL_CACHE_PRIMARY_STATE_GETTER;
        }
    }

    static class InternalCacheRecordStoreTestFactory implements DataSerializableFactory {

        static final int F_ID = 1;
        static final int INTERNAL_CACHE_PRIMARY_STATE_GETTER = 0;

        @Override
        public IdentifiedDataSerializable create(int typeId) {
            if (typeId == INTERNAL_CACHE_PRIMARY_STATE_GETTER) {
                return new CachePrimaryStateGetterOperation();
            } else {
                throw new UnsupportedOperationException("Could not create instance of type id " + typeId);
            }
        }
    }
}


text:
require 'containers/deque'
=begin rdoc
    A Stack is a container that keeps elements in a last-in first-out (LIFO) order. There are many
    uses for stacks, including prefix-infix-postfix conversion and backtracking problems.

    This implementation uses a doubly-linked list, guaranteeing O(1) complexity for all operations.

=end
class Containers::Stack
  include Enumerable
  # Create a new stack. Takes an optional array argument to initialize the stack.
  #
  #   s = Containers::Stack.new([1, 2, 3])
  #   s.pop #=> 3
  #   s.pop #=> 2
  def initialize(ary=[])
    @container = Containers::Deque.new(ary)
  end

  # Returns the next item from the stack but does not remove it.
  #
  #   s = Containers::Stack.new([1, 2, 3])
  #   s.next #=> 3
  #   s.size #=> 3
  def next
    @container.back
  end

  # Adds an item to the stack.
  #
  #   s = Containers::Stack.new([1])
  #   s.push(2)
  #   s.pop #=> 2
  #   s.pop #=> 1
  def push(obj)
    @container.push_back(obj)
  end
  alias_method :<<, :push

  # Removes the next item from the stack and returns it.
  #
  #   s = Containers::Stack.new([1, 2, 3])
  #   s.pop #=> 3
  #   s.size #=> 2
  def pop
    @container.pop_back
  end

  # Return the number of items in the stack.
  #
  #   s = Containers::Stack.new([1, 2, 3])
  #   s.size #=> 3
  def size
    @container.size
  end

  # Returns true if the stack is empty, false otherwise.
  def empty?
    @container.empty?
  end

  # Iterate over the Stack in LIFO order.
  def each(&block)
    @container.each_backward(&block)
  end

end


text:
<?php

namespace AdminBundle\Admin;

use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Route\RouteCollection;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Show\ShowMapper;
use Sonata\AdminBundle\Form\FormMapper;
use Sonata\AdminBundle\Admin\Admin;
use Doctrine\ORM\EntityRepository;

class ReportAdmin extends Admin {

    /**
     * this variable holds the route name prefix for this actions
     * @var string
     */
    protected $baseRouteName = 'report_admin';

    /**
     * this variable holds the url route prefix for this actions
     * @var string
     */
    protected $baseRoutePattern = 'report';

    public function configureListFields(ListMapper $listMapper) {
        $listMapper
                ->addIdentifier('id')
                ->add('user', null, array('admin_code' => 'user_admin'))
                ->add('_action', 'actions', array(
                    'actions' => array(
                        'show' => array(),
                        'edit' => array(),
                        'delete' => array(),
                    )
                ))
        ;
    }

    public function configureShowFields(ShowMapper $showMapper) {
        $showMapper
                ->add('id')
                ->add('content')
                ->add('user', null, array('admin_code' => 'user_admin'))
        ;
    }

    public function configureDatagridFilters(DatagridMapper $datagridMapper) {
        $datagridMapper
                ->add('id')
                ->add('user', null, array(),null,array(
                    'class' => 'KitchenBundle:User',
                    'query_builder' => function(EntityRepository $er) {
                        $qb = $er->createQueryBuilder('u');
                        return $qb->where($qb->expr()->eq('u.type', '1'));
                    }
                ))
        ;
    }

    public function configureFormFields(FormMapper $formMapper) {
        $formMapper
                ->add('user', 'entity', array(
                    'required' => false,
                    'class' => 'KitchenBundle:User',
                    'query_builder' => function(EntityRepository $er) {
                        $qb = $er->createQueryBuilder('u');
                        return $qb->where($qb->expr()->eq('u.type', '1'));
                    }
                ),array('admin_code' => 'user_admin'))
                ->add('content')
        ;
    }
}


text:
// ReSharper disable CheckNamespace

using System;
using System.Windows;
using System.Windows.Controls;

namespace Metrolib
// ReSharper restore CheckNamespace
{
	/// <summary>
	///     Similar to a <see cref="StackPanel" /> in that children are either laid out in a vertical
	///     or horizontal manner. But each child is assigned a 1* column, giving each equal width/height.
	/// </summary>
	public class GridPanel
		: Grid
	{
		/// <summary>
		///     Definition of the <see cref="Orientation" /> dependency property.
		/// </summary>
		public static readonly DependencyProperty OrientationProperty =
			DependencyProperty.Register("Orientation", typeof (Orientation), typeof (GridPanel),
			                            new PropertyMetadata(Orientation.Vertical));

		/// <summary>
		///     The orientation of the children added to this panel.
		/// </summary>
		public Orientation Orientation
		{
			get { return (Orientation) GetValue(OrientationProperty); }
			set { SetValue(OrientationProperty, value); }
		}

		/// <summary>
		///     Measures the children of a System.Windows.Controls.Grid in anticipation of arranging them during the System.Windows.Controls.Grid.ArrangeOverride(System.Windows.Size) pass.
		/// </summary>
		/// <param name="availableSize"></param>
		/// <returns></returns>
		protected override System.Windows.Size MeasureOverride(System.Windows.Size availableSize)
		{
			if (Children.Count > 0)
			{
				if (double.IsInfinity(availableSize.Width) ||
				    double.IsInfinity(availableSize.Height))
				{
					availableSize = MeasuredDesiredSize();
				}

				System.Windows.Size size;
				if (Orientation == Orientation.Horizontal)
				{
					size = new System.Windows.Size(availableSize.Width / Children.Count, availableSize.Height);
				}
				else
				{
					size = new System.Windows.Size(availableSize.Width, availableSize.Height / Children.Count);
				}

				foreach (UIElement child in Children)
				{
					child.Measure(size);
				}
				return availableSize;
			}

			return new System.Windows.Size();
		}

		private System.Windows.Size MeasuredDesiredSize()
		{
			double desiredWidth = 0;
			double desiredHeight = 0;

			foreach (UIElement child in Children)
			{
				child.Measure(new System.Windows.Size(double.PositiveInfinity, double.PositiveInfinity));

				if (Orientation == Orientation.Horizontal)
				{
					desiredWidth += child.DesiredSize.Width;
					desiredHeight = Math.Max(desiredHeight, child.DesiredSize.Height);
				}
				else
				{
					desiredWidth = Math.Max(desiredWidth, child.DesiredSize.Width);
					desiredHeight += child.DesiredSize.Height;
				}
			}
			var desiredSize = new System.Windows.Size(desiredWidth, desiredHeight);
			return desiredSize;
		}

		/// <summary>
		///     Arranges the content of a System.Windows.Controls.Grid element.
		/// </summary>
		/// <param name="finalSize"></param>
		/// <returns></returns>
		protected override System.Windows.Size ArrangeOverride(System.Windows.Size finalSize)
		{
			if (Children.Count > 0)
			{
				for (int i = 0; i < Children.Count; ++i)
				{
					Rect rect;
					if (Orientation == Orientation.Horizontal)
					{
						double width = finalSize.Width/Children.Count;
						rect = new Rect(i*width, 0, width, finalSize.Height);
					}
					else
					{
						double height = finalSize.Height/Children.Count;
						rect = new Rect(0, i*height, finalSize.Width, height);
					}
					Children[i].Arrange(rect);
				}
			}
			return finalSize;
		}
	}
}


text:
                            {{column.title}}

                            {{column.name}}

                            <bb-context-menu ng-if="$ctrl.contextMenuItems[item[$ctrl.options.index]].length > 0" bb-context-menu-label="Reorder Table Context">
                                <bb-context-menu-item ng-repeat="action in $ctrl.contextMenuItems[item[$ctrl.options.index]]" bb-context-menu-action="action.cmd()">{{action.title}}</bb-context-menu-item>
                            </bb-context-menu>

{{item[column.jsonmap]}}

                            <button type="button" ng-if="!$ctrl.sorting && $ctrl.options.fixed < $index" ng-click="$ctrl.pushToTop(item)" class="btn btn-link">

                              Top
                           </button>


text:
namespace policy {

namespace {

const char kPublicAccountDomainPrefix[] = "public-accounts";
const char kKioskAppAccountDomainPrefix[] = "kiosk-apps";
const char kDeviceLocalAccountDomainSuffix[] = ".device-local.localhost";

}  // namespace

DeviceLocalAccount::DeviceLocalAccount(Type type,
                                       const std::string& account_id,
                                       const std::string& kiosk_app_id,
                                       const std::string& kiosk_app_update_url)
    : type(type),
      account_id(account_id),
      user_id(GenerateDeviceLocalAccountUserId(account_id, type)),
      kiosk_app_id(kiosk_app_id),
      kiosk_app_update_url(kiosk_app_update_url) {
}

DeviceLocalAccount::~DeviceLocalAccount() {
}

std::string GenerateDeviceLocalAccountUserId(const std::string& account_id,
                                             DeviceLocalAccount::Type type) {
  std::string domain_prefix;
  switch (type) {
    case DeviceLocalAccount::TYPE_PUBLIC_SESSION:
      domain_prefix = kPublicAccountDomainPrefix;
      break;
    case DeviceLocalAccount::TYPE_KIOSK_APP:
      domain_prefix = kKioskAppAccountDomainPrefix;
      break;
    case DeviceLocalAccount::TYPE_COUNT:
      NOTREACHED();
      break;
  }
  return gaia::CanonicalizeEmail(
      base::HexEncode(account_id.c_str(), account_id.size()) + "@" +
      domain_prefix + kDeviceLocalAccountDomainSuffix);
}

bool IsDeviceLocalAccountUser(const std::string& user_id,
                              DeviceLocalAccount::Type* type) {
  // For historical reasons, the guest user ID does not contain an @ symbol and
  // therefore, cannot be parsed by gaia::ExtractDomainName().
  if (user_id == chromeos::login::kGuestUserName)
    return false;
  const std::string domain = gaia::ExtractDomainName(user_id);
  if (!base::EndsWith(domain, kDeviceLocalAccountDomainSuffix, true))
    return false;

  const std::string domain_prefix = domain.substr(
      0, domain.size() - arraysize(kDeviceLocalAccountDomainSuffix) + 1);

  if (domain_prefix == kPublicAccountDomainPrefix) {
    if (type)
      *type = DeviceLocalAccount::TYPE_PUBLIC_SESSION;
    return true;
  }
  if (domain_prefix == kKioskAppAccountDomainPrefix) {
    if (type)
      *type = DeviceLocalAccount::TYPE_KIOSK_APP;
    return true;
  }

  // |user_id| is a device-local account but its type is not recognized.
  NOTREACHED();
  if (type)
    *type = DeviceLocalAccount::TYPE_COUNT;
  return true;
}

void SetDeviceLocalAccounts(chromeos::OwnerSettingsServiceChromeOS* service,
                            const std::vector<DeviceLocalAccount>& accounts) {
  base::ListValue list;
  for (std::vector<DeviceLocalAccount>::const_iterator it = accounts.begin();
       it != accounts.end(); ++it) {
    scoped_ptr<base::DictionaryValue> entry(new base::DictionaryValue);
    entry->SetStringWithoutPathExpansion(
        chromeos::kAccountsPrefDeviceLocalAccountsKeyId,
        it->account_id);
    entry->SetIntegerWithoutPathExpansion(
        chromeos::kAccountsPrefDeviceLocalAccountsKeyType,
        it->type);
    if (it->type == DeviceLocalAccount::TYPE_KIOSK_APP) {
      entry->SetStringWithoutPathExpansion(
          chromeos::kAccountsPrefDeviceLocalAccountsKeyKioskAppId,
          it->kiosk_app_id);
      if (!it->kiosk_app_update_url.empty()) {
        entry->SetStringWithoutPathExpansion(
            chromeos::kAccountsPrefDeviceLocalAccountsKeyKioskAppUpdateURL,
            it->kiosk_app_update_url);
      }
    }
    list.Append(entry.release());
  }

  service->Set(chromeos::kAccountsPrefDeviceLocalAccounts, list);
}

std::vector<DeviceLocalAccount> GetDeviceLocalAccounts(
    chromeos::CrosSettings* cros_settings) {
  std::vector<DeviceLocalAccount> accounts;

  const base::ListValue* list = NULL;
  cros_settings->GetList(chromeos::kAccountsPrefDeviceLocalAccounts, &list);
  if (!list)
    return accounts;

  std::set<std::string> account_ids;
  for (size_t i = 0; i < list->GetSize(); ++i) {
    const base::DictionaryValue* entry = NULL;
    if (!list->GetDictionary(i, &entry)) {
      LOG(ERROR) << "Corrupt entry in device-local account list at index " << i
                 << ".";
      continue;
    }

    std::string account_id;
    if (!entry->GetStringWithoutPathExpansion(
            chromeos::kAccountsPrefDeviceLocalAccountsKeyId, &account_id) ||
        account_id.empty()) {
      LOG(ERROR) << "Missing account ID in device-local account list at index "
                 << i << ".";
      continue;
    }

    int type;
    if (!entry->GetIntegerWithoutPathExpansion(
            chromeos::kAccountsPrefDeviceLocalAccountsKeyType, &type) ||
        type < 0 || type >= DeviceLocalAccount::TYPE_COUNT) {
      LOG(ERROR) << "Missing or invalid account type in device-local account "
                 << "list at index " << i << ".";
      continue;
    }

    std::string kiosk_app_id;
    std::string kiosk_app_update_url;
    if (type == DeviceLocalAccount::TYPE_KIOSK_APP) {
      if (!entry->GetStringWithoutPathExpansion(
              chromeos::kAccountsPrefDeviceLocalAccountsKeyKioskAppId,
              &kiosk_app_id)) {
        LOG(ERROR) << "Missing app ID in device-local account entry at index "
                   << i << ".";
        continue;
      }
      entry->GetStringWithoutPathExpansion(
          chromeos::kAccountsPrefDeviceLocalAccountsKeyKioskAppUpdateURL,
          &kiosk_app_update_url);
    }

    if (!account_ids.insert(account_id).second) {
      LOG(ERROR) << "Duplicate entry in device-local account list at index "
                 << i << ": " << account_id << ".";
      continue;
    }

    accounts.push_back(
        DeviceLocalAccount(static_cast<DeviceLocalAccount::Type>(type),
                           account_id,
                           kiosk_app_id,
                           kiosk_app_update_url));
  }
  return accounts;
}

}  // namespace policy


text:
package com.locus.game.sprites;

import com.badlogic.gdx.physics.box2d.Contact;
import com.badlogic.gdx.physics.box2d.ContactImpulse;
import com.badlogic.gdx.physics.box2d.ContactListener;
import com.badlogic.gdx.physics.box2d.Manifold;
import com.locus.game.sprites.bullets.Bullet;
import com.locus.game.sprites.entities.Entity;

/**
 * Created by Divya Mamgai on 9/21/2016.
 * Collision Detector
 */

public class CollisionDetector implements ContactListener {

    // Only powers of 2 up to 16th.
    public static final short CATEGORY_PLANET = 0x1;
    // Enable Collision with all.
    public static final short MASK_PLANET = -1;
    public static final short CATEGORY_MOON = 0x2;
    public static final short MASK_MOON = -1;
    public static final short CATEGORY_ASTEROID = 0x4;
    public static final short MASK_ASTEROID = -1;
    public static final short CATEGORY_BULLET = 0x8;
    // Bullets do not collide with each other.
    public static final short MASK_BULLET = ~CATEGORY_BULLET;
    public static final short CATEGORY_SHIP = 0x16;
    public static final short MASK_SHIP = -1;

    public CollisionDetector() {
    }

    @Override
    public void beginContact(Contact contact) {
        Object objectA = contact.getFixtureA().getBody().getUserData();
        Object objectB = contact.getFixtureB().getBody().getUserData();
        boolean isObjectABullet = objectA instanceof Bullet;
        boolean isObjectBBullet = objectB instanceof Bullet;
        // Both cannot be Bullet due to Category masking.
        if (isObjectABullet || isObjectBBullet) {
            // We now know with absolute certainty that one is a Bullet.
            Bullet bullet;
            // We technically also know that remaining object is Entity but we try to be sure
            // just in case.
            Entity entity = null;
            if (isObjectABullet) {
                bullet = (Bullet) objectA;
                if (objectB instanceof Entity) {
                    entity = (Entity) objectB;
                }
            } else {
                bullet = (Bullet) objectB;
                if (objectA instanceof Entity) {
                    entity = (Entity) objectA;
                }
            }
            if (entity != null) {
                if (bullet.getShip() != entity) {
                    switch (entity.getType()) {
                        case Planet:
                        case Moon:
                            break;
                        case Asteroid:
                            entity.reduceHealth(bullet.getDamage());
                            switch (bullet.getType()) {
                                case Normal:
                                    bullet.getShip().getShipState().score += 5;
                                    break;
                                default:
                                    bullet.getShip().getShipState().score += 15;
                                    break;
                            }
                            break;
                        default:
                            entity.reduceHealth(bullet.getDamage());
                            switch (bullet.getType()) {
                                case Normal:
                                    bullet.getShip().getShipState().score += 10;
                                    break;
                                default:
                                    bullet.getShip().getShipState().score += 30;
                                    break;
                            }
                    }
                    bullet.kill();
                }
            }
        } else {
            if (objectA != null && objectB != null) {
                Entity entityA = (Entity) objectA;
                Entity entityB = (Entity) objectB;
                switch (entityA.getDefinition().type) {
                    case Ship:
                        switch (entityB.getDefinition().type) {
                            case Ship:
                                break;
                            case Planet:
                                entityA.reduceHealth(
                                        entityA.getBody().getLinearVelocity().len2()
                                                > 900f ? 75f : 25f);
                                break;
                            case Moon:
                                entityA.reduceHealth(entityA.getBody().getLinearVelocity().len2()
                                        > 900f ? 30f : 15f);
                                break;
                            case Asteroid:
                                entityA.reduceHealth(entityA.getBody().getLinearVelocity().len2()
                                        > 900f ? 50f : 25f);
                                entityB.kill();
                                break;
                        }
                        break;
                    case Planet:
                        switch (entityB.getDefinition().type) {
                            case Ship:
                                entityB.reduceHealth(entityB.getBody().getLinearVelocity().len2()
                                        > 900f ? 75f : 25f);
                                break;
                            case Planet:
                                break;
                            case Moon:
                                break;
                            case Asteroid:
                                entityB.kill();
                                break;
                        }
                        break;
                    case Moon:
                        switch (entityB.getDefinition().type) {
                            case Ship:
                                entityB.reduceHealth(entityB.getBody().getLinearVelocity().len2()
                                        > 900f ? 30f : 15f);
                                break;
                            case Planet:
                                break;
                            case Moon:
                                break;
                            case Asteroid:
                                entityB.kill();
                                break;
                        }
                        break;
                    case Asteroid:
                        switch (entityB.getDefinition().type) {
                            case Ship:
                                entityB.reduceHealth(entityB.getBody().getLinearVelocity().len2()
                                        > 900f ? 50f : 25f);
                            case Planet:
                            case Moon:
                            case Asteroid:
                                entityA.kill();
                                break;
                        }
                        break;
                }
            }
        }
    }

    @Override
    public void endContact(Contact contact) {

    }

    @Override
    public void preSolve(Contact contact, Manifold oldManifold) {

    }

    @Override
    public void postSolve(Contact contact, ContactImpulse impulse) {

    }
}


text:
module Rip::Nodes
  class If < Base
    attr_reader :argument
    attr_reader :true_body
    attr_reader :false_body

    def initialize(location, argument, true_body, false_body)
      super(location)
      @argument = argument
      @true_body = true_body
      @false_body = false_body
    end

    def ==(other)
      super &&
        (argument == other.argument) &&
        (true_body == other.true_body) &&
        (false_body == other.false_body)
    end

    def interpret(context)
      _argument = argument.interpret(context)['to_boolean'].call(context, [])

      if _argument == Rip::Core::Boolean.true
        true_body.interpret(context)
      else
        false_body.interpret(context)
      end
    end

    def to_debug(level = 0)
      argument_debug = [ [ level + 1, 'argument =' ] ] +
        argument.to_debug(level + 2)

      true_body_debug = [ [ level + 1, 'true_body = [' ] ] +
        true_body.to_debug(level + 2) +
        [ [ level + 1, ']' ] ]

      false_body_debug = [ [ level + 1, 'false_body = [' ] ] +
        false_body.to_debug(level + 2) +
        [ [ level + 1, ']' ] ]

      super + argument_debug + true_body_debug + false_body_debug
    end
  end
end


text:
similar with `Builder Pattern`. Split a entire process into pieces.
such as `t.buildPart1(xxx).buildPart2(yyy)`

## partial function


text:
package io.opencensus.stats;

import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.fail;

import com.google.common.collect.Collections2;
import com.google.common.testing.EqualsTester;
import io.opencensus.common.Function;
import io.opencensus.internal.SimpleEventQueue;
import io.opencensus.testing.common.TestClock;
import io.opencensus.internal.VarInt;
import io.opencensus.stats.View.DistributionView;
import io.opencensus.stats.View.IntervalView;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/** Tests for {@link StatsContext}. */
@RunWith(JUnit4.class)
public class StatsContextTest {
  private static final double TOLERANCE = 1e-6;

  private final StatsManagerImplBase statsManager =
      new StatsManagerImplBase(new SimpleEventQueue(), TestClock.create());
  private final StatsContextFactory factory = statsManager.getStatsContextFactory();
  private final StatsContext defaultStatsContext = factory.getDefault();

  private static final int VERSION_ID = 0;
  private static final int VALUE_TYPE_STRING = 0;

  private static final TagKey K_EMPTY = TagKey.create("");
  private static final TagKey K1 = TagKey.create("k1");
  private static final TagKey K2 = TagKey.create("k2");
  private static final TagKey K3 = TagKey.create("k3");
  private static final TagKey K4 = TagKey.create("k4");
  private static final TagKey K10 = TagKey.create("k10");

  private static final TagValue V_EMPTY = TagValue.create("");
  private static final TagValue V1 = TagValue.create("v1");
  private static final TagValue V2 = TagValue.create("v2");
  private static final TagValue V3 = TagValue.create("v3");
  private static final TagValue V4 = TagValue.create("v4");
  private static final TagValue V10 = TagValue.create("v10");
  private static final TagValue V20 = TagValue.create("v20");
  private static final TagValue V30 = TagValue.create("v30");
  private static final TagValue V100 = TagValue.create("v100");

  private static final Tag T1 = Tag.create(K1, V1);
  private static final Tag T2 = Tag.create(K2, V2);
  private static final Tag T3 = Tag.create(K3, V3);
  private static final Tag T4 = Tag.create(K4, V4);

  @Test
  public void testWith() {
    assertThat(defaultStatsContext.builder().set(K1, V1).build())
        .isEqualTo(defaultStatsContext.with(K1, V1));

    assertThat(defaultStatsContext.builder().set(K1, V1).set(K2, V2).build())
        .isEqualTo(defaultStatsContext.with(K1, V1, K2, V2));

    assertThat(defaultStatsContext.builder().set(K1, V1).set(K2, V2).set(K3, V3).build())
        .isEqualTo(defaultStatsContext.with(K1, V1, K2, V2, K3, V3));
  }

  @Test
  public void testWithComposed() {
    StatsContext context1 = defaultStatsContext.with(K1, V1);
    assertThat(defaultStatsContext.builder().set(K1, V1).build()).isEqualTo(context1);

    StatsContext context2 = context1.with(K1, V10, K2, V2);
    assertThat(defaultStatsContext.with(K1, V10, K2, V2)).isEqualTo(context2);

    StatsContext context3 = context2.with(K1, V100, K2, V20, K3, V3);
    assertThat(defaultStatsContext.with(K1, V100, K2, V20, K3, V3)).isEqualTo(context3);

    StatsContext context4 = context3.with(K3, V30, K4, V4);
    assertThat(
            defaultStatsContext
                .builder()
                .set(K1, V100)
                .set(K2, V20)
                .set(K3, V30)
                .set(K4, V4)
                .build())
        .isEqualTo(context4);
  }

  // The main tests for stats recording are in StatsManagerImplTest.
  @Test
  public void testRecord() {
    statsManager.registerView(RpcViewConstants.RPC_CLIENT_ROUNDTRIP_LATENCY_VIEW);
    View beforeView = statsManager.getView(RpcViewConstants.RPC_CLIENT_ROUNDTRIP_LATENCY_VIEW);
    beforeView.match(
        new Function<DistributionView, Void>() {
          @Override
          public Void apply(DistributionView view) {
            assertThat(view.getDistributionAggregations()).isEmpty();
            return null;
          }
        },
        new Function<IntervalView, Void>() {
          @Override
          public Void apply(IntervalView view) {
            fail("Expected a DistributionView");
            return null;
          }
        });
    StatsContext context =
        defaultStatsContext.with(
            RpcMeasurementConstants.RPC_CLIENT_METHOD, TagValue.create("myMethod"));
    MeasurementMap measurements =
        MeasurementMap.of(RpcMeasurementConstants.RPC_CLIENT_ROUNDTRIP_LATENCY, 5.1);
    context.record(measurements);
    View afterView = statsManager.getView(RpcViewConstants.RPC_CLIENT_ROUNDTRIP_LATENCY_VIEW);
    afterView.match(
        new Function<DistributionView, Void>() {
          @Override
          public Void apply(DistributionView view) {
            assertThat(view.getDistributionAggregations()).hasSize(1);
            DistributionAggregation agg = view.getDistributionAggregations().get(0);
            assertThat(agg.getTags())
                .containsExactly(
                    Tag.create(
                        RpcMeasurementConstants.RPC_CLIENT_METHOD, TagValue.create("myMethod")));
            assertThat(agg.getCount()).isEqualTo(1);
            assertThat(agg.getMean()).isWithin(TOLERANCE).of(5.1);
            return null;
          }
        },
        new Function<IntervalView, Void>() {
          @Override
          public Void apply(IntervalView view) {
            fail("Expected a DistributionView");
            return null;
          }
        });
  }

  @Test
  public void testSerializeDefault() throws Exception {
    testSerialize();
  }

  @Test
  public void testSerializeWithOneStringTag() throws Exception {
    testSerialize(T1);
  }

  @Test
  public void testSerializeWithMultiStringTags() throws Exception {
    testSerialize(T1, T2, T3, T4);
  }

  @Test
  public void testRoundtripSerialization() throws Exception {
    testRoundtripSerialization(defaultStatsContext.builder().build());
    testRoundtripSerialization(defaultStatsContext.with(K1, V1));
    testRoundtripSerialization(defaultStatsContext.with(K1, V1, K2, V2, K3, V3));
    testRoundtripSerialization(defaultStatsContext.with(K1, V_EMPTY));
    testRoundtripSerialization(defaultStatsContext.with(K_EMPTY, V1));
    testRoundtripSerialization(defaultStatsContext.with(K_EMPTY, V_EMPTY));
  }

  // Tests for Object overrides.

  @Test
  public void testEquals() {
    new EqualsTester()
        .addEqualityGroup(defaultStatsContext, defaultStatsContext)
        .addEqualityGroup(defaultStatsContext.with(K1, V1), defaultStatsContext.with(K1, V1))
        .addEqualityGroup(
            defaultStatsContext.with(K1, V1, K2, V2),
            defaultStatsContext.with(K1, V1, K2, V2),
            defaultStatsContext.with(K2, V2, K1, V1))
        .addEqualityGroup(defaultStatsContext.with(K10, V1))
        .addEqualityGroup(defaultStatsContext.with(K1, V10))
        .addEqualityGroup("foo")
        .testEquals();
  }

  @Test
  public void testToString() {
    assertThat(defaultStatsContext.with(K1, V1).toString())
        .isEqualTo(defaultStatsContext.with(K1, V1).toString());
    assertThat(defaultStatsContext.with(K10, V1).toString())
        .isNotEqualTo(defaultStatsContext.with(K1, V1).toString());
    assertThat(defaultStatsContext.with(K1, V10).toString())
        .isNotEqualTo(defaultStatsContext.with(K1, V1).toString());
  }

  private void testSerialize(Tag... tags) throws IOException {
    StatsContext.Builder builder = defaultStatsContext.builder();
    for (Tag tag : tags) {
      builder.set(tag.getKey(), tag.getValue());
    }

    ByteArrayOutputStream actual = new ByteArrayOutputStream();
    builder.build().serialize(actual);

    Collection<List<Tag>> tagPermutation = Collections2.permutations(Arrays.asList(tags));
    Set<String> possibleOutputs = new HashSet<String>();
    for (List<Tag> list : tagPermutation) {
      ByteArrayOutputStream expected = new ByteArrayOutputStream();
      expected.write(VERSION_ID);
      for (Tag tag : list) {
        expected.write(VALUE_TYPE_STRING);
        encodeString(tag.getKey().asString(), expected);
        encodeString(tag.getValue().asString(), expected);
      }
      possibleOutputs.add(expected.toString());
    }

    assertThat(possibleOutputs).contains(actual.toString());
  }

  private void testRoundtripSerialization(StatsContext expected) throws Exception {
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    expected.serialize(output);
    ByteArrayInputStream input = new ByteArrayInputStream(output.toByteArray());
    StatsContext actual = factory.deserialize(input);
    assertThat(actual).isEqualTo(expected);
  }

  private static final void encodeString(String input, ByteArrayOutputStream byteArrayOutputStream)
      throws IOException {
    VarInt.putVarInt(input.length(), byteArrayOutputStream);
    byteArrayOutputStream.write(input.getBytes("UTF-8"));
  }
}


text:
import { shallow, render, mount } from 'enzyme'
import fetchMock from 'jest-fetch-mock'
import readJson from './helpers/readJson'

global.shallow = shallow
global.render = render
global.mount = mount
global.fetch = fetchMock
global.readJson = readJson


text:
package com.thoughtworks.go.plugin.access.authorization;

import com.thoughtworks.go.config.PluginRoleConfig;
import com.thoughtworks.go.config.SecurityAuthConfig;
import com.thoughtworks.go.config.SecurityAuthConfigs;
import com.thoughtworks.go.domain.packagerepository.ConfigurationPropertyMother;
import com.thoughtworks.go.plugin.access.authentication.models.User;
import com.thoughtworks.go.plugin.access.authorization.models.AuthenticationResponse;
import com.thoughtworks.go.plugin.access.authorization.models.SupportedAuthType;
import com.thoughtworks.go.plugin.api.request.GoPluginApiRequest;
import com.thoughtworks.go.plugin.api.response.DefaultGoPluginApiResponse;
import com.thoughtworks.go.plugin.api.response.validation.ValidationError;
import com.thoughtworks.go.plugin.api.response.validation.ValidationResult;
import com.thoughtworks.go.plugin.domain.common.Metadata;
import com.thoughtworks.go.plugin.domain.common.PluginConfiguration;
import com.thoughtworks.go.plugin.infra.PluginManager;
import org.hamcrest.core.Is;
import org.json.JSONException;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.skyscreamer.jsonassert.JSONAssert;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import static com.thoughtworks.go.plugin.access.authorization.AuthorizationPluginConstants.*;
import static com.thoughtworks.go.plugin.api.response.DefaultGoPluginApiResponse.SUCCESS_RESPONSE_CODE;
import static org.hamcrest.CoreMatchers.hasItem;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.hasSize;
import static org.mockito.Mockito.*;
import static org.mockito.MockitoAnnotations.initMocks;

public class AuthorizationExtensionTest {
    public static final String PLUGIN_ID = "plugin-id";

    @Mock
    private PluginManager pluginManager;
    private ArgumentCaptor<GoPluginApiRequest> requestArgumentCaptor;
    private AuthorizationExtension authorizationExtension;

    @Rule
    public ExpectedException thrown = ExpectedException.none();

    @Before
    public void setUp() throws Exception {
        initMocks(this);
        when(pluginManager.resolveExtensionVersion(PLUGIN_ID, Arrays.asList("1.0"))).thenReturn("1.0");
        when(pluginManager.isPluginOfType(AuthorizationPluginConstants.EXTENSION_NAME, PLUGIN_ID)).thenReturn(true);

        authorizationExtension = new AuthorizationExtension(pluginManager);

        requestArgumentCaptor = ArgumentCaptor.forClass(GoPluginApiRequest.class);
    }

    @Test
    public void shouldTalkToPlugin_To_GetCapabilities() throws Exception {
        String responseBody = "{\"supported_auth_type\":\"password\",\"can_search\":true}";
        when(pluginManager.submitTo(eq(PLUGIN_ID), requestArgumentCaptor.capture())).thenReturn(new DefaultGoPluginApiResponse(SUCCESS_RESPONSE_CODE, responseBody));

        com.thoughtworks.go.plugin.domain.authorization.Capabilities capabilities = authorizationExtension.getCapabilities(PLUGIN_ID);

        assertRequest(requestArgumentCaptor.getValue(), AuthorizationPluginConstants.EXTENSION_NAME, "1.0", REQUEST_GET_CAPABILITIES, null);
        assertThat(capabilities.getSupportedAuthType().toString(), is(SupportedAuthType.Password.toString()));
        assertThat(capabilities.canSearch(), is(true));
    }

    @Test
    public void shouldTalkToPlugin_To_GetPluginConfigurationMetadata() throws Exception {
        String responseBody = "[{\"key\":\"username\",\"metadata\":{\"required\":true,\"secure\":false}},{\"key\":\"password\",\"metadata\":{\"required\":true,\"secure\":true}}]";
        when(pluginManager.submitTo(eq(PLUGIN_ID), requestArgumentCaptor.capture())).thenReturn(new DefaultGoPluginApiResponse(SUCCESS_RESPONSE_CODE, responseBody));

        List<PluginConfiguration> authConfigMetadata = authorizationExtension.getAuthConfigMetadata(PLUGIN_ID);

        assertRequest(requestArgumentCaptor.getValue(), AuthorizationPluginConstants.EXTENSION_NAME, "1.0", REQUEST_GET_AUTH_CONFIG_METADATA, null);

        assertThat(authConfigMetadata.size(), is(2));
        assertThat(authConfigMetadata, containsInAnyOrder(
                new PluginConfiguration("username", new Metadata(true, false)),
                new PluginConfiguration("password", new Metadata(true, true))
        ));
    }

    @Test
    public void shouldTalkToPlugin_To_GetAuthConfigView() throws Exception {
        String responseBody = "{ \"template\": \"
This is view snippet
\" }";
        when(pluginManager.submitTo(eq(PLUGIN_ID), requestArgumentCaptor.capture())).thenReturn(new DefaultGoPluginApiResponse(SUCCESS_RESPONSE_CODE, responseBody));

        String pluginConfigurationView = authorizationExtension.getAuthConfigView(PLUGIN_ID);

        assertRequest(requestArgumentCaptor.getValue(), AuthorizationPluginConstants.EXTENSION_NAME, "1.0", REQUEST_GET_AUTH_CONFIG_VIEW, null);

        assertThat(pluginConfigurationView, is("
This is view snippet
"));
    }

    @Test
    public void shouldTalkToPlugin_To_ValidateAuthConfig() throws Exception {
        String responseBody = "[{\"message\":\"Url must not be blank.\",\"key\":\"Url\"},{\"message\":\"SearchBase must not be blank.\",\"key\":\"SearchBase\"}]";
        when(pluginManager.submitTo(eq(PLUGIN_ID), requestArgumentCaptor.capture())).thenReturn(new DefaultGoPluginApiResponse(SUCCESS_RESPONSE_CODE, responseBody));

        ValidationResult validationResult = authorizationExtension.validateAuthConfig(PLUGIN_ID, Collections.emptyMap());

        assertRequest(requestArgumentCaptor.getValue(), AuthorizationPluginConstants.EXTENSION_NAME, "1.0", REQUEST_VALIDATE_AUTH_CONFIG, "{}");

        assertThat(validationResult.isSuccessful(), is(false));
        assertThat(validationResult.getErrors(), containsInAnyOrder(
                new ValidationError("Url", "Url must not be blank."),
                new ValidationError("SearchBase", "SearchBase must not be blank.")
        ));
    }

    @Test
    public void shouldTalkToPlugin_To_VerifyConnection() throws Exception {
        String responseBody = "{\"status\":\"success\"}";
        when(pluginManager.submitTo(eq(PLUGIN_ID), requestArgumentCaptor.capture())).thenReturn(new DefaultGoPluginApiResponse(SUCCESS_RESPONSE_CODE, responseBody));
        AuthorizationExtension authorizationExtensionSpy = spy(authorizationExtension);

        authorizationExtensionSpy.verifyConnection(PLUGIN_ID, Collections.emptyMap());

        assertRequest(requestArgumentCaptor.getValue(), AuthorizationPluginConstants.EXTENSION_NAME, "1.0", REQUEST_VERIFY_CONNECTION, "{}");

        verify(authorizationExtensionSpy).verifyConnection(PLUGIN_ID, Collections.emptyMap());
    }

    @Test
    public void shouldTalkToPlugin_To_GetRoleConfigurationMetadata() throws Exception {
        String responseBody = "[{\"key\":\"memberOf\",\"metadata\":{\"required\":true,\"secure\":false}}]";
        when(pluginManager.submitTo(eq(PLUGIN_ID), requestArgumentCaptor.capture())).thenReturn(new DefaultGoPluginApiResponse(SUCCESS_RESPONSE_CODE, responseBody));

        List<PluginConfiguration> roleConfigurationMetadata = authorizationExtension.getRoleConfigurationMetadata(PLUGIN_ID);

        assertRequest(requestArgumentCaptor.getValue(), AuthorizationPluginConstants.EXTENSION_NAME, "1.0", REQUEST_GET_ROLE_CONFIG_METADATA, null);

        assertThat(roleConfigurationMetadata.size(), is(1));
        assertThat(roleConfigurationMetadata, containsInAnyOrder(
                new PluginConfiguration("memberOf", new Metadata(true, false))
        ));
    }

    @Test
    public void shouldTalkToPlugin_To_GetRoleConfigurationView() throws Exception {
        String responseBody = "{ \"template\": \"
This is view snippet
\" }";
        when(pluginManager.submitTo(eq(PLUGIN_ID), requestArgumentCaptor.capture())).thenReturn(new DefaultGoPluginApiResponse(SUCCESS_RESPONSE_CODE, responseBody));

        String pluginConfigurationView = authorizationExtension.getRoleConfigurationView(PLUGIN_ID);

        assertRequest(requestArgumentCaptor.getValue(), AuthorizationPluginConstants.EXTENSION_NAME, "1.0", REQUEST_GET_ROLE_CONFIG_VIEW, null);

        assertThat(pluginConfigurationView, is("
This is view snippet
"));
    }

    @Test
    public void shouldTalkToPlugin_To_ValidateRoleConfiguration() throws Exception {
        String responseBody = "[{\"message\":\"memberOf must not be blank.\",\"key\":\"memberOf\"}]";
        when(pluginManager.submitTo(eq(PLUGIN_ID), requestArgumentCaptor.capture())).thenReturn(new DefaultGoPluginApiResponse(SUCCESS_RESPONSE_CODE, responseBody));

        ValidationResult validationResult = authorizationExtension.validateRoleConfiguration(PLUGIN_ID, Collections.emptyMap());

        assertRequest(requestArgumentCaptor.getValue(), AuthorizationPluginConstants.EXTENSION_NAME, "1.0", REQUEST_VALIDATE_ROLE_CONFIG, "{}");

        assertThat(validationResult.isSuccessful(), is(false));
        assertThat(validationResult.getErrors(), containsInAnyOrder(
                new ValidationError("memberOf", "memberOf must not be blank.")
        ));
    }

    @Test
    public void shouldTalkToPlugin_To_AuthenticateUser() throws Exception {
        String requestBody = "{\n" +
                "  \"credentials\": {\n" +
                "    \"username\": \"bob\",\n" +
                "    \"password\": \"secret\"\n" +
                "  },\n" +
                "  \"auth_configs\": [\n" +
                "    {\n" +
                "      \"id\": \"ldap\",\n" +
                "      \"configuration\": {\n" +
                "        \"url\": \"some-url\"\n" +
                "      }\n" +
                "    }\n" +
                "  ],\n" +
                "  \"role_configs\": [\n" +
                "    {\n" +
                "      \"name\": \"foo\",\n" +
                "      \"auth_config_id\": \"ldap\",\n" +
                "      \"configuration\": {\n" +
                "        \"memberOf\": \"ou=some-value\"\n" +
                "      }\n" +
                "    }\n" +
                "  ]\n" +
                "}";

        String responseBody = "{\"user\":{\"username\":\"bob\",\"display_name\":\"Bob\",\"email\":\"bob@example.com\"},\"roles\":[\"blackbird\"]}";

        when(pluginManager.submitTo(eq(PLUGIN_ID), requestArgumentCaptor.capture())).thenReturn(new DefaultGoPluginApiResponse(SUCCESS_RESPONSE_CODE, responseBody));

        final PluginRoleConfig roleConfig = new PluginRoleConfig("foo", "ldap", ConfigurationPropertyMother.create("memberOf", false, "ou=some-value"));
        final List<PluginRoleConfig> pluginRoleConfigs = Collections.singletonList(roleConfig);

        final SecurityAuthConfigs authConfigs = new SecurityAuthConfigs();
        authConfigs.add(new SecurityAuthConfig("ldap", "cd.go.ldap", ConfigurationPropertyMother.create("url", false, "some-url")));

        AuthenticationResponse authenticationResponse = authorizationExtension.authenticateUser(PLUGIN_ID, "bob", "secret", authConfigs, pluginRoleConfigs);

        assertRequest(requestArgumentCaptor.getValue(), AuthorizationPluginConstants.EXTENSION_NAME, "1.0", REQUEST_AUTHENTICATE_USER, requestBody);
        assertThat(authenticationResponse.getUser(), is(new User("bob", "Bob", "bob@example.com")));
        assertThat(authenticationResponse.getRoles().get(0), is("blackbird"));
    }

    @Test
    public void shouldTalkToPlugin_To_AuthenticateUserWithEmptyListIfRoleConfigsAreNotProvided() throws Exception {
        String requestBody = "{\n" +
                "  \"credentials\": {\n" +
                "    \"username\": \"bob\",\n" +
                "    \"password\": \"secret\"\n" +
                "  },\n" +
                "  \"auth_configs\": [\n" +
                "    {\n" +
                "      \"id\": \"ldap\",\n" +
                "      \"configuration\": {\n" +
                "        \"url\": \"some-url\"\n" +
                "      }\n" +
                "    }\n" +
                "  ],\n" +
                "  \"role_configs\": []\n" +
                "}";

        String responseBody = "{\"user\":{\"username\":\"bob\",\"display_name\":\"Bob\",\"email\":\"bob@example.com\"},\"roles\":[\"blackbird\"]}";

        when(pluginManager.submitTo(eq(PLUGIN_ID), requestArgumentCaptor.capture())).thenReturn(new DefaultGoPluginApiResponse(SUCCESS_RESPONSE_CODE, responseBody));

        final SecurityAuthConfigs authConfigs = new SecurityAuthConfigs();
        authConfigs.add(new SecurityAuthConfig("ldap", "cd.go.ldap", ConfigurationPropertyMother.create("url", false, "some-url")));

        AuthenticationResponse authenticationResponse = authorizationExtension.authenticateUser(PLUGIN_ID, "bob", "secret", authConfigs, null);

        assertRequest(requestArgumentCaptor.getValue(), AuthorizationPluginConstants.EXTENSION_NAME, "1.0", REQUEST_AUTHENTICATE_USER, requestBody);
        assertThat(authenticationResponse.getUser(), is(new User("bob", "Bob", "bob@example.com")));
        assertThat(authenticationResponse.getRoles().get(0), is("blackbird"));
    }

    @Test
    public void authenticateUser_shouldErrorOutInAbsenceOfSecurityAuthConfigs() throws Exception {
        thrown.expect(MissingAuthConfigsException.class);
        thrown.expectMessage("No AuthConfigs configured for plugin: plugin-id, Plugin would need at-least one auth_config to authenticate user.");

        authorizationExtension.authenticateUser(PLUGIN_ID, "bob", "secret", null, null);

        verifyNoMoreInteractions(pluginManager);
    }

    @Test
    public void shouldTalkToPlugin_To_SearchUsers() throws Exception {
        String requestBody = "{\n" +
                "  \"search_term\": \"bob\",\n" +
                "  \"auth_configs\": [\n" +
                "    {\n" +
                "      \"id\": \"ldap\",\n" +
                "      \"configuration\": {\n" +
                "        \"foo\": \"bar\"\n" +
                "      }\n" +
                "    }\n" +
                "  ]\n" +
                "}";
        String responseBody = "[{\"username\":\"bob\",\"display_name\":\"Bob\",\"email\":\"bob@example.com\"}]";
        when(pluginManager.submitTo(eq(PLUGIN_ID), requestArgumentCaptor.capture())).thenReturn(new DefaultGoPluginApiResponse(SUCCESS_RESPONSE_CODE, responseBody));

        List<User> users = authorizationExtension.searchUsers(PLUGIN_ID, "bob", Collections.singletonList(new SecurityAuthConfig("ldap", "cd.go.ldap", ConfigurationPropertyMother.create("foo", false, "bar"))));

        assertRequest(requestArgumentCaptor.getValue(), AuthorizationPluginConstants.EXTENSION_NAME, "1.0", REQUEST_SEARCH_USERS, requestBody);
        assertThat(users, hasSize(1));
        assertThat(users, hasItem(new User("bob", "Bob", "bob@example.com")));
    }

    @Test
    public void shouldTalkToPlugin_To_GetAuthorizationServerUrl() throws JSONException {
        String requestBody = "{\n" +
                "  \"auth_configs\": [\n" +
                "    {\n" +
                "      \"id\": \"github\",\n" +
                "      \"configuration\": {\n" +
                "        \"url\": \"some-url\"\n" +
                "      }\n" +
                "    }\n" +
                "  ],\n" +
                "  \"authorization_server_callback_url\": \"http://go.site.url/go/plugin/plugin-id/authenticate\"\n"+
                "}";
        String responseBody = "{\"authorization_server_url\":\"url_to_authorization_server\"}";
        SecurityAuthConfig authConfig = new SecurityAuthConfig("github", "cd.go.github", ConfigurationPropertyMother.create("url", false, "some-url"));

        when(pluginManager.submitTo(eq(PLUGIN_ID), requestArgumentCaptor.capture())).thenReturn(new DefaultGoPluginApiResponse(SUCCESS_RESPONSE_CODE, responseBody));

        String authorizationServerRedirectUrl = authorizationExtension.getAuthorizationServerUrl(PLUGIN_ID, Collections.singletonList(authConfig), "http://go.site.url");

        assertRequest(requestArgumentCaptor.getValue(), AuthorizationPluginConstants.EXTENSION_NAME, "1.0", REQUEST_AUTHORIZATION_SERVER_URL, requestBody);
        assertThat(authorizationServerRedirectUrl, is("url_to_authorization_server"));
    }

    private void assertRequest(GoPluginApiRequest goPluginApiRequest, String extensionName, String version, String requestName, String requestBody) throws JSONException {
        Assert.assertThat(goPluginApiRequest.extension(), Is.is(extensionName));
        Assert.assertThat(goPluginApiRequest.extensionVersion(), Is.is(version));
        Assert.assertThat(goPluginApiRequest.requestName(), Is.is(requestName));
        JSONAssert.assertEquals(requestBody, goPluginApiRequest.requestBody(), true);
    }
}


text:
Multi Tenant Site for multiple Db´s in same App for Ristorantino Mágico

 - *bootstrap.php*. Es donde se cargan los archivos de configuracion del sitio (settings.ini). Tambien agrega el evento para escuchar "on User.login"

 - *Event/MtSitesUserLoginListener*. Es para escuchar eventos despues del login

 - *MtSitesAuthorized* es para validar que el usuario tenga permisos para acceder y manejar redirecciones dependiendo donde estoy. Redefine el metodo authorized()

  - *MultiTenantBehavior* es para decirle a cada Model la base de datos que debe usar. En base a si el Model es tenant o no. Se configuran los Models del core aqui para que no sean leidos como "tenants".


text:
;
export function shouldRemove() {
    ;
    ;
}
export function locallyDefinedConsole() {
    let console = {
        log: ()=>{
        }
    };
    console.log();
}
export function capturedConsole() {
    let console = {
        log: ()=>{
        }
    };
    function innerFunc() {
        console.log();
    }
}
export function overrideInParam(console) {
    console.log("");
}
export function overrideInParamObjectPatPropAssign({ console  }) {
    console.log("");
}
export function overrideInParamObjectPatPropKeyValue({ c: console  }) {
    console.log("");
}
export function overrideInParamObjectPatPropKeyValueNested({ c: { console  }  }) {
    console.log("");
}
export function overrideInParamArray([console]) {
    console.log("");
}


text:
<?php

require_once('./../config.php');
require_once(PATH . CLASSES . 'alkaline.php');

$alkaline = new Alkaline;
$user = new User;

$user->perm(true);

$alkaline->setCallback();

// Preference: page_limit
if(!$max = $user->returnPref('page_limit')){
	$max = 100;
}

$image_ids = new Find('images');
$image_ids->clearMemory();
$image_ids->page(null, $max);
$image_ids->find();

$images = new Image($image_ids);
$images->getSizes('square');
$images->hook();

$shoebox_count = $alkaline->countDirectory(PATH . SHOEBOX);
if($shoebox_count > 0){
	$shoebox_count = '(' . $shoebox_count . ') ';
}
else{
	$shoebox_count = '';
}

define('TAB', 'library');
define('TITLE', 'Alkaline Library');
require_once(PATH . ADMIN . 'includes/header.php');

?>

		<a href="<?php echo BASE . ADMIN . 'upload' . URL_CAP; ?>">
			<button>Upload image</button>

		<?php if($badges['images'] > 0){ ?>
		<a href="<?php echo BASE . ADMIN . 'shoebox' . URL_CAP; ?>">
			<button>Process images (<?php echo $badges['images']; ?>)</button>

		<?php } ?>

<img src="<?php echo BASE . ADMIN; ?>images/icons/images.png" alt="" /> Images (<?php echo number_format($image_ids->count); ?>)

	<form action="<?php echo BASE . ADMIN; ?>search<?php echo URL_CAP; ?>" method="post">

			<input type="search" name="q" style="width: 30em; margin-left: 0;" results="10" /> <input type="submit" value="Search" />

			▸ Show options and presets

						Tags:

							<input type="text" id="tags" name="tags" class="l" />

							Tip: Use the uppercase boolean operators AND, OR, and NOT.

						EXIF metadata:

							<?php echo $alkaline->showEXIFNames('exif_name'); ?>
							<input type="text" id="exif_value" name="exif_value" class="s" />

						Rights set:

							<?php echo $alkaline->showRights('rights'); ?>

						Date taken:

							between <input type="text" class="date s" name="taken_begin" />
							and <input type="text" class="date s" name="taken_end" />

						Date uploaded:

							between <input type="text" class="date s" name="uploaded_begin" />
							and <input type="text" class="date s" name="uploaded_end" />

						Location:

							within
							<select name="location_proximity">
								<option value="10">10</option>
								<option value="25">25</option>
								<option value="50">50</option>
								<option value="100" selected="selected">100</option>
								<option value="250">250</option>
								<option value="500">500</option>
								<option value="1000">1,000</option>
								<option value="2500">2,500</option>
							</select>
							miles of
							<input type="text" name="location" class="image_geo m" />

						Dominant color:

							<select id="color" name="color">
								<option></option>
								<option value="blue">Blue</option>
								<option value="red">Red</option>
								<option value="yellow">Yellow</option>
								<option value="green">Green</option>
								<option value="purple">Purple</option>
								<option value="orange">Orange</option>
								<option value="brown">Brown</option>
								<option value="pink">Pink</option>
							</select>

						Views:

							<select name="views_operator">
								<option value="greater">≥</option>
								<option value="less">≤</option>
								<option value="equal">=</option>
							</select>
							<input type="text" name="views" class="xs" />

						Orientation:

							<select id="orientation" name="orientation">
								<option value="">All</option>
								<option value="portrait">Portrait</option>
								<option value="landscape">Landscape</option>
								<option value="square">Square</option>
							</select>

						Privacy level:

							<select id="privacy" name="privacy">
								<option value="">All</option>
								<option value="public">Public</option>
								<option value="protected">Protected</option>
								<option value="private">Private</option>
							</select>

						Publication status:

							<select id="published" name="published">
								<option value="">All</option>
								<option value="published">Published</option>
								<option value="unpublished">Unpublished</option>
							</select>

						Sort results by:

							<select name="sort">
								<option value="taken">Date taken</option>
								<option value="updated">Date last updated</option>
								<option value="published">Date published</option>
								<option value="uploaded" selected="selected">Date uploaded</option>
								<option value="title">Title</option>
								<option value="views">Views</option>
							</select>
							<select name="sort_direction">
								<option value="DESC">Descending</option>
								<option value="ASC">Ascending</option>
							</select>

Presets

<a href="<?php echo BASE . ADMIN . 'search' . URL_ACT . 'displayed' . URL_RW; ?>">Displayed images

<a href="<?php echo BASE . ADMIN . 'search' . URL_ACT . 'updated' . URL_RW; ?>">Recently updated images

<a href="<?php echo BASE . ADMIN . 'search' . URL_ACT . 'views' . URL_RW; ?>">Most viewed images

<a href="<?php echo BASE . ADMIN . 'search' . URL_ACT . 'nonpublic' . URL_RW; ?>">Nonpublic images

<a href="<?php echo BASE . ADMIN . 'search' . URL_ACT . 'unpublished' . URL_RW; ?>">Unpublished images

<a href="<?php echo BASE . ADMIN . 'search' . URL_ACT . 'untitled' . URL_RW; ?>">Untitled images

<a href="<?php echo BASE . ADMIN . 'search' . URL_ACT . 'untagged' . URL_RW; ?>">Untagged images

	</form>

		<?php

		foreach($images->images as $image){
			?>
			<a href="<?php echo BASE . ADMIN . 'image' . URL_ID . $image['image_id'] . URL_RW; ?>" class="nu">
				<img src="<?php echo $image['image_src_square']; ?>" alt="" title="<?php echo $alkaline->makeHTMLSafe($image['image_title']); ?>" class="frame tip" />

			<?php
		}

		?>

	<?php
	if($image_ids->page_count > 1){
		?>

			<?php
			if(!empty($image_ids->page_previous)){
				for($i = 1; $i <= $image_ids->page_previous; ++$i){
					$page_uri = 'page_' . $i . '_uri';
					echo '$page_uri  .'" class="page_no">' . number_format($i) . '';
				}
			}
			?>
			Page <?php echo $image_ids->page; ?> of <?php echo $image_ids->page_count; ?>
			<?php
			if(!empty($image_ids->page_next)){
				for($i = $image_ids->page_next; $i <= $image_ids->page_count; ++$i){
					$page_uri = 'page_' . $i . '_uri';
					echo '$page_uri  .'" class="page_no">' . number_format($i) . '';
				}
			}
			?>

		<?php
	}
	?>

<?php

require_once(PATH . ADMIN . 'includes/footer.php');

?>


text:
/* ================================================================
 * About NPOI
 * Author: Tony Qu
 * Author's email: tonyqus (at) gmail.com
 * Author's Blog: tonyqus.wordpress.com.cn (wp.tonyqus.cn)
 * HomePage: http://www.codeplex.com/npoi
 * Contributors:
 *
 * ==============================================================*/
using System;
using System.Collections;
using System.IO;
using NPOI.POIFS.Common;
using System.Collections.Generic;

namespace NPOI.POIFS.Storage
{
    /// <summary>
    /// A list of RawDataBlocks instances, and methods to manage the list
    /// @author Marc Johnson (mjohnson at apache dot org
    /// </summary>
    internal class RawDataBlockList:BlockListImpl
    {

        /// <summary>
        /// Initializes a new instance of the <see cref="RawDataBlockList"/> class.
        /// </summary>
        /// <param name="stream">the InputStream from which the data will be read</param>
        /// <param name="bigBlockSize">The big block size, either 512 bytes or 4096 bytes</param>
        public RawDataBlockList(Stream stream, POIFSBigBlockSize bigBlockSize)
        {
            List<RawDataBlock> blocks = new List<RawDataBlock>();

            while (true)
            {
                RawDataBlock block = new RawDataBlock(stream, bigBlockSize.GetBigBlockSize());

                // If there was data, add the block to the list
                if(block.HasData) {
            	    blocks.Add(block);
                }

                // If the stream is now at the End Of File, we're done
                if (block.EOF) {
                    break;
                }
            }
             SetBlocks((ListManagedBlock[])blocks.ToArray());
        }
    }
}


text:
using namespace maps;

uint64_t Utils::
rand64() {
  std::chrono::high_resolution_clock::duration duration =
    std::chrono::high_resolution_clock::now().time_since_epoch();
  std::default_random_engine generator;
  generator.seed(duration.count());
  std::uniform_int_distribution<uint64_t> distribution;
  return distribution(generator);
}

bool Utils::
isOrthographic(const Eigen::Matrix4f& iMatrix) {
  const Eigen::Vector4f unitW(0,0,0,1);
  float dot = fabs(iMatrix.row(3).normalized()[3]);
  return (fabs(dot-1) < 1e-6);
}

bool Utils::
composeViewMatrix(Eigen::Projective3f& oMatrix, const Eigen::Matrix3f& iCalib,
                  const Eigen::Isometry3f& iPose, const bool iIsOrthographic) {
  Eigen::Projective3f calib = Eigen::Projective3f::Identity();
  calib.matrix().col(2).swap(calib.matrix().col(3));
  calib.matrix().topLeftCorner<2,3>() = iCalib.matrix().topRows<2>();
  calib.matrix().bottomLeftCorner<1,3>() = iCalib.matrix().bottomRows<1>();
  if (iIsOrthographic) calib.matrix().col(2).swap(calib.matrix().col(3));
  oMatrix = calib*iPose.inverse();
  return true;
}

bool Utils::
factorViewMatrix(const Eigen::Projective3f& iMatrix,
                 Eigen::Matrix3f& oCalib, Eigen::Isometry3f& oPose,
                 bool& oIsOrthographic) {
  oIsOrthographic = isOrthographic(iMatrix.matrix());

  // get appropriate rows
  std::vector<int> rows = {0,1,2};
  if (!oIsOrthographic) rows[2] = 3;

  // get A matrix (upper left 3x3) and t vector
  Eigen::Matrix3f A;
  Eigen::Vector3f t;
  for (int i = 0; i < 3; ++i) {
    for (int j = 0; j < 3; ++j) {
      A(i,j) = iMatrix(rows[i],j);
    }
    t[i] = iMatrix(rows[i],3);
  }

  // determine translation vector
  oPose.setIdentity();
  oPose.translation() = -(A.inverse()*t);

  // determine calibration matrix
  Eigen::Matrix3f AAtrans = A*A.transpose();
  AAtrans.col(0).swap(AAtrans.col(2));
  AAtrans.row(0).swap(AAtrans.row(2));
  Eigen::LLT<Eigen::Matrix3f, Eigen::Upper> llt(AAtrans);
  oCalib = llt.matrixU();
  oCalib.col(0).swap(oCalib.col(2));
  oCalib.row(0).swap(oCalib.row(2));
  oCalib.transposeInPlace();

  // compute rotation matrix
  oPose.linear() = (oCalib.inverse()*A).transpose();

  return true;
}


text:
function elegirTabTaskForce( tf_id ) {
	document.getElementById( 'tabber_tf' ).tabber.tabShow( tf_id - 1 );
}
function showLoading() {
	$('#popup').html('
Cargando datos...
').dialog(
		{ modal: true,
		  buttons: {},
		  title: 'Por favor espere...' }
	);
}
function showModal( html, title ) {
	$('#popup').html('
' + html + '
').dialog(
		{ modal: true,
		  buttons: {},
		  width: 800,
		  title: title }
	);
}
function showSmallModal( html, title ) {
	$('#popup').html('
' + html + '
').dialog(
		{ modal: true,
		  width: '400px',
		  buttons: {},
		  title: title }
	).css('padding-top', '0px');
}
function showModalW( html, title, width ) {
	$('#popup').html('
' + html + '
').dialog(
		{ modal: true,
		  buttons: {},
		  width: width,
		  title: title }
	);
}
/*
function abrirReportados( userid ) {
//       var mylink = "http://srvca/caisd/pdmweb.exe?OP=SEARCH+FACTORY=cr+QBE.EQ.log_agent.userid="+userid+"+QBE.NE.status.description=Cerrada+QBE.NE.assignee.userid="+userid;
       window.open(mylink, "Tickets", "directories=no, location=no, menubar=no, scrollbars=yes, statusbar=no, tittlebar=no, width=1200, height=900");
           }
  */
/*
function abrirAsignados( userid )
{
//	var mylink = "http://srvca/caisd/pdmweb.exe?OP=SEARCH+FACTORY=cr+QBE.NE.status.description=Cerrada+QBE.EQ.assignee.userid="+userid;
	window.open(mylink, "Tickets", "directories=no, location=no, menubar=no, scrollbars=yes, statusbar=no, tittlebar=no, width=1200, height=900");
}
*/
function abrirAuto( mylink )
{
	window.open(mylink, "Tickets", "directories=no, location=no, menubar=no, scrollbars=yes, statusbar=no, tittlebar=no, width=1200, height=900");
}
/*
function abrirTotalAbiertos()
{
//	var mylink = "http://srvca/caisd/pdmweb.exe?OP=SEARCH+FACTORY=cr+QBE.NE.status.description=Cerrada";
	window.open(mylink, "Tickets", "directories=no, location=no, menubar=no, scrollbars=yes, statusbar=no, tittlebar=no, width=1200, height=900");
}
*/

$.ajaxSetup({
	// Evitar problemas de cache en IE
	cache: false
});

function setupCalendarios() {
	$('.calendario').datepicker({dateFormat: 'dd-mm-yy',
		monthNames: ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio',
			'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre' ],
		dayNamesMin: ['Do', 'Lu', 'Ma', 'Mi', 'Ju', 'Vi', 'Sa'],
		firstDay: 1
	 });
	$('.calendario_time').datetimepicker({dateFormat: 'dd-mm-yy',
		monthNames: ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio',
			'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre' ],
		dayNamesMin: ['Do', 'Lu', 'Ma', 'Mi', 'Ju', 'Vi', 'Sa'],
		timeText: "Hora",
		hourText: "Hora",
		minuteText: "Minuto",
		stepMinute: 5,
		hourMin: 8,
		hourMax: 21,
		currentText: 'Ahora',
		closeText: 'Aceptar',
		firstDay: 1
	 });
}

var notif_t = null;

function generarPopupNotificaciones( pendientes ) {
	var htmlpop = '';
	var htmlemb = '';
	for( var i = 0; i < pendientes.length; i++ ) {
		var pendiente = pendientes[i];
		var html = "
";
		html += "
Eliminar
";
		html += "
Posponer 30'
";
		html += "
De " + pendiente['fecha'] + ":
";
		html += "
" + pendiente['mensaje'] + "
";
		if( pendiente['link'] )
			html += "
Seguir link
";
		html += "

";
		if( pendiente['embebida'] )
			htmlemb += html;
		else
			htmlpop += html;
	}
	if( htmlpop.length )
		showSmallModal( htmlpop, "Notificaciones pendientes" );
	if( htmlemb.length )
		$('#notificaciones').html( htmlemb );
}

function runBucleNotificaciones() {
	if( typeof( raiz ) != 'undefined' ) {
		$.ajax( { url: raiz + 'notificaciones/check',
			error: function() {},
			success: function(data) {
				var ev = eval('(' + data + ')');
				if( ev['cantidad'] > 0 ) {
					generarPopupNotificaciones( ev['pendientes'] );
				}
			}
		} );
		notif_t = setTimeout( 'runBucleNotificaciones()', 60000 );
	}
}

function iniciarBucleNotificaciones() {
	notif_t = setTimeout( 'runBucleNotificaciones()', 2000 );
	$('.notificacion .close a').live('click', function(e) {
		e.preventDefault();
		$.ajax( { url: raiz + 'notificaciones/delete?id=' + $(this).attr('nid'),
			error: function() { alert( 'Error' ); },
			success: function( data ) {
				$('#popup').dialog('close');
				clearTimeout( notif_t );
				runBucleNotificaciones();
			} } );
	} );
	$('.notificacion .posponer a').live('click', function(e) {
		e.preventDefault();
		$.ajax( { url: raiz + 'notificaciones/posponer?id=' + $(this).attr('nid') + '&minutos='
			+ $(this).attr('minutos'),
			error: function() { alert( 'Error' ); },
			success: function( data ) {
				$('#popup').dialog('close');
				clearTimeout( notif_t );
				runBucleNotificaciones();
			} } );
	} );
}

function prepareAutoContacts() {
	$('.autocontact').each( function() {
		var src = $(this).attr('src');
		if( !src )
			alert('Un autocontact siempre debe tener el atributo src');
		$(this).autocomplete( { source: src } );
	} );
	$('.autocontact_ex').each( function() {
		var src = $(this).attr('src');
		if( !src )
			alert('Un autocontact siempre debe tener el atributo src');
		$(this).autocomplete( { source: src } );
		$(this).change( function( e ) {
			var exclude = $(this).attr('exclude');
			$(exclude).val('');
		} );
	} );
}

$(document).ready( function() {
	iniciarBucleNotificaciones();
	setupCalendarios();
/*
	$('.reportados').click( function(e ) {
		e.preventDefault();
		abrirReportados( $(this).attr('iniciales') );
	} );
*/
/*
	$('.asignados').click( function(e ) {
		e.preventDefault();
		abrirAsignados( $(this).attr('iniciales') );
	} );
*/
	$('.autoopen').live('click', function(e ) {
		e.preventDefault();
		abrirAuto( $(this).attr('href') );
	} );
	$('.autodialog').live('click', function(e ) {
		e.preventDefault();
		$.ajax( { url: $(this).attr('href'),
			error: function() {
				alert('Error');
			},
			success: function(data) {
				showModalW( data, 'Filtro',600 );
			}
		} );
	} );
	prepareAutoContacts();
	$('.confirmarDelete').live('click', function(e) {
		if( !(confirm( '¿Confirmas que deseas borrar o desactivar el registro?') ) ) {
			e.preventDefault();
		}
	} );
	$('#crearTicketABM').click( function(e) {
		e.preventDefault();
		var url = $(this).attr('url');
		$.ajax( { url: url,
			error: function() {
				$('#popup').dialog('close');
				alert( 'Error' );
			},
			success: function( data ) {
				if(parseInt(data) != undefined ) {
					$('.error_crear_ticket').html(data.replace(/\n/g,"
")).show();
					$('#crid').val( '' );
					$('#popup').dialog('close');
				} else {
					$('#crid').val( data );
					$('#popup').dialog('close');
					$('.error_crear_ticket').hide();
				}
			}
		} );
	} );
/*
	$('.total_abiertos').click( function(e ) {
		e.preventDefault();
		abrirTotalAbiertos();
	} );
*/
} );