text:
from django.test import TestCase
from settings.test import SELENIUM_DRIVER
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import unittest

class MainTestCase(unittest.TestCase):

    def setUp(self):
        self.driver = SELENIUM_DRIVER
        self.addCleanup(self.driver.quit)

    def test_login(self):
        self.driver.get('http://127.0.0.1:8000')
        self.assertIn('Foreign-Guides', self.driver.title)
        element = self.driver.find_element_by_class_name('login-reveal')
        element.click()

        element = WebDriverWait(self.driver, 100).until(
        	EC.presence_of_element_located((By.ID, 'login',))
        )

        assert self.driver.find_element_by_id('login')
        assert self.driver.find_element_by_id('id_username')
        assert self.driver.find_element_by_id('id_password')
        assert self.driver.find_element_by_id
        assert self.driver.find_element_by_class_name(
        	'close-reveal-modal')

        # close_element = self.driver.find_element_by_class_name(
        # 	'close-reveal-modal')
        # close_element.click()

if __name__ == '__main__':
    unittest.main(verbosity=3)

redpajama_set_name: RedPajamaGithub


text:
import os
import glob
import numpy as np
import logging
import cPickle
from datasets import nav_env
from datasets import factory
from src import utils
from src import map_utils as mu

logging.basicConfig(level=logging.INFO)
DATA_DIR = 'data/stanford_building_parser_dataset_raw/'

mkdir_if_missing = utils.mkdir_if_missing
save_variables = utils.save_variables

def _get_semantic_maps(building_name, transform, map_, flip, cats):
  rooms = get_room_in_building(building_name)
  maps = []
  for cat in cats:
    maps.append(np.zeros((map_.size[1], map_.size[0])))

  for r in rooms:
    room = load_room(building_name, r, category_list=cats)
    classes = room['class_id']
    for i, cat in enumerate(cats):
      c_ind = cats.index(cat)
      ind = [_ for _, c in enumerate(classes) if c == c_ind]
      if len(ind) > 0:
        vs = [room['vertexs'][x]*1 for x in ind]
        vs = np.concatenate(vs, axis=0)
        if transform:
          vs = np.array([vs[:,1], vs[:,0], vs[:,2]]).T
          vs[:,0] = -vs[:,0]
          vs[:,1] += 4.20
          vs[:,0] += 6.20
        vs = vs*100.
        if flip:
          vs[:,1] = -vs[:,1]
        maps[i] = maps[i] + \
            mu._project_to_map(map_, vs, ignore_points_outside_map=True)
  return maps

def _map_building_name(building_name):
  b = int(building_name.split('_')[0][4])
  out_name = 'Area_{:d}'.format(b)
  if b == 5:
    if int(building_name.split('_')[0][5]) == 1:
      transform = True
    else:
      transform = False
  else:
    transform = False
  return out_name, transform

def get_categories():
  cats = ['beam', 'board', 'bookcase', 'ceiling', 'chair', 'clutter', 'column',
          'door', 'floor', 'sofa', 'table', 'wall', 'window']
  return cats

def _write_map_files(b_in, b_out, transform):
  cats = get_categories()

  env = utils.Foo(padding=10, resolution=5, num_point_threshold=2,
                  valid_min=-10, valid_max=200, n_samples_per_face=200)
  robot = utils.Foo(radius=15, base=10, height=140, sensor_height=120,
                    camera_elevation_degree=-15)

  building_loader = factory.get_dataset('sbpd')
  for flip in [False, True]:
    b = nav_env.Building(b_out, robot, env, flip=flip,
                         building_loader=building_loader)
    logging.info("building_in: %s, building_out: %s, transform: %d", b_in,
                 b_out, transform)
    maps = _get_semantic_maps(b_in, transform, b.map, flip, cats)
    maps = np.transpose(np.array(maps), axes=[1,2,0])

    #  Load file from the cache.
    file_name = '{:s}_{:d}_{:d}_{:d}_{:d}_{:d}_{:d}.pkl'
    file_name = file_name.format(b.building_name, b.map.size[0], b.map.size[1],
                                 b.map.origin[0], b.map.origin[1],
                                 b.map.resolution, flip)
    out_file = os.path.join(DATA_DIR, 'processing', 'class-maps', file_name)
    logging.info('Writing semantic maps to %s.', out_file)
    save_variables(out_file, [maps, cats], ['maps', 'cats'], overwrite=True)

def _transform_area5b(room_dimension):
  for a in room_dimension.keys():
    r = room_dimension[a]*1
    r[[0,1,3,4]] = r[[1,0,4,3]]
    r[[0,3]] = -r[[3,0]]
    r[[1,4]] += 4.20
    r[[0,3]] += 6.20
    room_dimension[a] = r
  return room_dimension

def collect_room(building_name, room_name):
  room_dir = os.path.join(DATA_DIR, 'Stanford3dDataset_v1.2', building_name,
                          room_name, 'Annotations')
  files = glob.glob1(room_dir, '*.txt')
  files = sorted(files, key=lambda s: s.lower())
  vertexs = []; colors = [];
  for f in files:
    file_name = os.path.join(room_dir, f)
    logging.info('  %s', file_name)
    a = np.loadtxt(file_name)
    vertex = a[:,:3]*1.
    color = a[:,3:]*1
    color = color.astype(np.uint8)
    vertexs.append(vertex)
    colors.append(color)
  files = [f.split('.')[0] for f in files]
  out = {'vertexs': vertexs, 'colors': colors, 'names': files}
  return out

def load_room(building_name, room_name, category_list=None):
  room = collect_room(building_name, room_name)
  room['building_name'] = building_name
  room['room_name']     = room_name
  instance_id = range(len(room['names']))
  room['instance_id'] = instance_id
  if category_list is not None:
    name = [r.split('_')[0] for r in room['names']]
    class_id = []
    for n in name:
      if n in category_list:
        class_id.append(category_list.index(n))
      else:
        class_id.append(len(category_list))
    room['class_id'] = class_id
    room['category_list'] = category_list
  return room

def get_room_in_building(building_name):
  building_dir = os.path.join(DATA_DIR, 'Stanford3dDataset_v1.2', building_name)
  rn = os.listdir(building_dir)
  rn = [x for x in rn if os.path.isdir(os.path.join(building_dir, x))]
  rn = sorted(rn, key=lambda s: s.lower())
  return rn

def write_room_dimensions(b_in, b_out, transform):
  rooms = get_room_in_building(b_in)
  room_dimension = {}
  for r in rooms:
    room = load_room(b_in, r, category_list=None)
    vertex = np.concatenate(room['vertexs'], axis=0)
    room_dimension[r] = np.concatenate((np.min(vertex, axis=0), np.max(vertex, axis=0)), axis=0)
  if transform == 1:
    room_dimension = _transform_area5b(room_dimension)

  out_file = os.path.join(DATA_DIR, 'processing', 'room-dimension', b_out+'.pkl')
  save_variables(out_file, [room_dimension], ['room_dimension'], overwrite=True)

def write_room_dimensions_all(I):
  mkdir_if_missing(os.path.join(DATA_DIR, 'processing', 'room-dimension'))
  bs_in = ['Area_1', 'Area_2', 'Area_3', 'Area_4', 'Area_5', 'Area_5', 'Area_6']
  bs_out = ['area1', 'area2', 'area3', 'area4', 'area5a', 'area5b', 'area6']
  transforms = [0, 0, 0, 0, 0, 1, 0]

  for i in I:
    b_in = bs_in[i]
    b_out = bs_out[i]
    t = transforms[i]
    write_room_dimensions(b_in, b_out, t)

def write_class_maps_all(I):
  mkdir_if_missing(os.path.join(DATA_DIR, 'processing', 'class-maps'))
  bs_in = ['Area_1', 'Area_2', 'Area_3', 'Area_4', 'Area_5', 'Area_5', 'Area_6']
  bs_out = ['area1', 'area2', 'area3', 'area4', 'area5a', 'area5b', 'area6']
  transforms = [0, 0, 0, 0, 0, 1, 0]

  for i in I:
    b_in = bs_in[i]
    b_out = bs_out[i]
    t = transforms[i]
    _write_map_files(b_in, b_out, t)

if __name__ == '__main__':
  write_room_dimensions_all([0, 2, 3, 4, 5, 6])
  write_class_maps_all([0, 2, 3, 4, 5, 6])


text:
package workloadupdater

import (
	"fmt"
	"time"

	"github.com/golang/mock/gomock"
	v12 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	v13 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/apimachinery/pkg/types"
	"k8s.io/client-go/kubernetes/fake"
	"k8s.io/client-go/testing"
	"k8s.io/client-go/tools/cache"
	framework "k8s.io/client-go/tools/cache/testing"
	"k8s.io/client-go/tools/record"

	k8sv1 "k8s.io/api/core/v1"

	v1 "kubevirt.io/client-go/api/v1"
	"kubevirt.io/client-go/kubecli"
	"kubevirt.io/kubevirt/pkg/testutils"
	virtconfig "kubevirt.io/kubevirt/pkg/virt-config"

	io_prometheus_client "github.com/prometheus/client_model/go"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
)

var _ = Describe("Workload Updater", func() {
	var ctrl *gomock.Controller
	var stop chan struct{}
	var virtClient *kubecli.MockKubevirtClient
	var migrationInterface *kubecli.MockVirtualMachineInstanceMigrationInterface
	var kubeVirtInterface *kubecli.MockKubeVirtInterface
	var vmiInterface *kubecli.MockVirtualMachineInstanceInterface
	var vmiSource *framework.FakeControllerSource
	var vmiInformer cache.SharedIndexInformer
	var podInformer cache.SharedIndexInformer
	var podSource *framework.FakeControllerSource
	var migrationInformer cache.SharedIndexInformer
	var migrationSource *framework.FakeControllerSource
	var kubeVirtSource *framework.FakeControllerSource
	var kubeVirtInformer cache.SharedIndexInformer
	var recorder *record.FakeRecorder
	var mockQueue *testutils.MockWorkQueue
	var kubeClient *fake.Clientset
	var migrationFeeder *testutils.MigrationFeeder

	var controller *WorkloadUpdateController

	var expectedImage string

	syncCaches := func(stop chan struct{}) {
		go vmiInformer.Run(stop)
		go podInformer.Run(stop)
		go migrationInformer.Run(stop)
		go kubeVirtInformer.Run(stop)

		Expect(cache.WaitForCacheSync(stop,
			vmiInformer.HasSynced,
			migrationInformer.HasSynced,
			kubeVirtInformer.HasSynced,
		)).To(BeTrue())
	}

	addKubeVirt := func(kv *v1.KubeVirt) {
		mockQueue.ExpectAdds(1)
		kubeVirtSource.Add(kv)
		mockQueue.Wait()
	}

	shouldExpectMultiplePodEvictions := func(evictionCount *int) {
		// Expect pod deletion
		kubeClient.Fake.PrependReactor("create", "pods", func(action testing.Action) (handled bool, ret runtime.Object, err error) {
			if action.GetSubresource() == "eviction" {
				*evictionCount++
				return true, nil, nil
			}
			return false, nil, nil
		})
	}

	BeforeEach(func() {

		expectedImage = "cur-image"

		outdatedVirtualMachineInstanceWorkloads.Set(0.0)
		stop = make(chan struct{})
		ctrl = gomock.NewController(GinkgoT())
		virtClient = kubecli.NewMockKubevirtClient(ctrl)
		migrationInterface = kubecli.NewMockVirtualMachineInstanceMigrationInterface(ctrl)
		kubeVirtInterface = kubecli.NewMockKubeVirtInterface(ctrl)
		vmiInterface = kubecli.NewMockVirtualMachineInstanceInterface(ctrl)

		vmiInformer, vmiSource = testutils.NewFakeInformerWithIndexersFor(&v1.VirtualMachineInstance{}, cache.Indexers{
			cache.NamespaceIndex: cache.MetaNamespaceIndexFunc,
			"node": func(obj interface{}) (strings []string, e error) {
				return []string{obj.(*v1.VirtualMachineInstance).Status.NodeName}, nil
			},
		})
		migrationInformer, migrationSource = testutils.NewFakeInformerFor(&v1.VirtualMachineInstanceMigration{})
		podInformer, podSource = testutils.NewFakeInformerFor(&k8sv1.Pod{})
		recorder = record.NewFakeRecorder(200)
		config, _, _, _ := testutils.NewFakeClusterConfig(&v12.ConfigMap{})

		kubeVirtInformer, _ = testutils.NewFakeInformerFor(&v1.KubeVirt{})
		kubeVirtInformer, kubeVirtSource = testutils.NewFakeInformerFor(&v1.KubeVirt{})

		controller = NewWorkloadUpdateController(expectedImage, vmiInformer, podInformer, migrationInformer, kubeVirtInformer, recorder, virtClient, config)
		mockQueue = testutils.NewMockWorkQueue(controller.queue)
		controller.queue = mockQueue
		migrationFeeder = testutils.NewMigrationFeeder(mockQueue, migrationSource)

		// Set up mock client
		virtClient.EXPECT().VirtualMachineInstanceMigration(v12.NamespaceDefault).Return(migrationInterface).AnyTimes()
		virtClient.EXPECT().VirtualMachineInstance(v12.NamespaceDefault).Return(vmiInterface).AnyTimes()
		virtClient.EXPECT().KubeVirt(v12.NamespaceDefault).Return(kubeVirtInterface).AnyTimes()
		kubeClient = fake.NewSimpleClientset()
		virtClient.EXPECT().CoreV1().Return(kubeClient.CoreV1()).AnyTimes()
		virtClient.EXPECT().PolicyV1beta1().Return(kubeClient.PolicyV1beta1()).AnyTimes()

		// Make sure that all unexpected calls to kubeClient will fail
		kubeClient.Fake.PrependReactor("*", "*", func(action testing.Action) (handled bool, obj runtime.Object, err error) {
			Expect(action).To(BeNil())
			return true, nil, nil
		})
		syncCaches(stop)
	})

	Context("workload update in progress", func() {
		It("should migrate the VMI", func() {
			newVirtualMachine("testvm", true, "madeup", vmiSource, podSource)
			time.Sleep(1 * time.Second)
			kv := newKubeVirt(1)
			kv.Spec.WorkloadUpdateStrategy.WorkloadUpdateMethods = []v1.WorkloadUpdateMethod{v1.WorkloadUpdateMethodLiveMigrate, v1.WorkloadUpdateMethodEvict}
			addKubeVirt(kv)

			migrationInterface.EXPECT().Create(gomock.Any()).Return(&v1.VirtualMachineInstanceMigration{ObjectMeta: v13.ObjectMeta{Name: "something"}}, nil)

			controller.Execute()
			testutils.ExpectEvent(recorder, SuccessfulCreateVirtualMachineInstanceMigrationReason)
		})

		It("should do nothing if deployment is updating", func() {
			newVirtualMachine("testvm", true, "madeup", vmiSource, podSource)
			time.Sleep(1 * time.Second)
			kv := newKubeVirt(1)
			kv.Spec.WorkloadUpdateStrategy.WorkloadUpdateMethods = []v1.WorkloadUpdateMethod{v1.WorkloadUpdateMethodLiveMigrate, v1.WorkloadUpdateMethodEvict}
			addKubeVirt(kv)

			kv.Status.ObservedDeploymentID = "something new"
			controller.Execute()
			Expect(recorder.Events).To(BeEmpty())
		})

		It("should update out of date value on kv and report prometheus metric", func() {

			By("Checking prometheus metric before sync")
			dto := &io_prometheus_client.Metric{}
			outdatedVirtualMachineInstanceWorkloads.Write(dto)

			zero := 0.0
			Expect(dto.GetGauge().Value).To(Equal(&zero), "outdated vmi workload reported should be equal to zero")

			reasons := []string{}
			for i := 0; i < 50; i++ {
				newVirtualMachine(fmt.Sprintf("testvm-migratable-%d", i), true, "madeup", vmiSource, podSource)
			}
			for i := 0; i < 50; i++ {
				newVirtualMachine(fmt.Sprintf("testvm-non-migratable-%d", i), false, "madeup", vmiSource, podSource)
			}
			// add vmis that are not outdated to ensure they are not counted as outdated in count
			for i := 0; i < 100; i++ {
				newVirtualMachine(fmt.Sprintf("testvm-up-to-date-%d", i), false, expectedImage, vmiSource, podSource)
			}
			for i := 0; i < int(virtconfig.ParallelMigrationsPerClusterDefault); i++ {
				reasons = append(reasons, SuccessfulCreateVirtualMachineInstanceMigrationReason)
			}
			for i := 0; i < defaultBatchDeletionCount; i++ {
				reasons = append(reasons, SuccessfulEvictVirtualMachineInstanceReason)
			}

			// wait for informer to catch up since we aren't watching for vmis directly
			time.Sleep(1 * time.Second)
			kv := newKubeVirt(0)
			kv.Spec.WorkloadUpdateStrategy.WorkloadUpdateMethods = []v1.WorkloadUpdateMethod{v1.WorkloadUpdateMethodLiveMigrate, v1.WorkloadUpdateMethodEvict}
			addKubeVirt(kv)

			kubeVirtInterface.EXPECT().PatchStatus(gomock.Any(), gomock.Any(), gomock.Any()).Do(func(name string, pt types.PatchType, data []byte) {
				str := string(data)
				Expect(str).To(Equal("[{ \"op\": \"test\", \"path\": \"/status/outdatedVirtualMachineInstanceWorkloads\", \"value\": 0}, { \"op\": \"replace\", \"path\": \"/status/outdatedVirtualMachineInstanceWorkloads\", \"value\": 100}]"))

			}).Return(nil, nil).Times(1)

			migrationInterface.EXPECT().Create(gomock.Any()).Return(&v1.VirtualMachineInstanceMigration{ObjectMeta: v13.ObjectMeta{Name: "something"}}, nil).Times(int(virtconfig.ParallelMigrationsPerClusterDefault))

			evictionCount := 0
			shouldExpectMultiplePodEvictions(&evictionCount)

			controller.Execute()
			testutils.ExpectEvents(recorder, reasons...)

			By("Checking prometheus metric")
			dto = &io_prometheus_client.Metric{}
			outdatedVirtualMachineInstanceWorkloads.Write(dto)

			val := 100.0

			Expect(dto.GetGauge().Value).To(Equal(&val))
			Expect(evictionCount).To(Equal(defaultBatchDeletionCount))

		})

		It("should migrate VMIs up to the global max migration count and delete up to delete batch count", func() {
			reasons := []string{}
			for i := 0; i < 50; i++ {
				newVirtualMachine(fmt.Sprintf("testvm-migratable-%d", i), true, "madeup", vmiSource, podSource)
			}
			for i := 0; i < 50; i++ {
				newVirtualMachine(fmt.Sprintf("testvm-%d", i), false, "madeup", vmiSource, podSource)
			}
			for i := 0; i < int(virtconfig.ParallelMigrationsPerClusterDefault); i++ {
				reasons = append(reasons, SuccessfulCreateVirtualMachineInstanceMigrationReason)
			}
			for i := 0; i < defaultBatchDeletionCount; i++ {
				reasons = append(reasons, SuccessfulEvictVirtualMachineInstanceReason)
			}

			// wait for informer to catch up since we aren't watching
			// for vmis directly
			time.Sleep(1 * time.Second)
			kv := newKubeVirt(100)
			kv.Spec.WorkloadUpdateStrategy.WorkloadUpdateMethods = []v1.WorkloadUpdateMethod{v1.WorkloadUpdateMethodLiveMigrate, v1.WorkloadUpdateMethodEvict}
			addKubeVirt(kv)

			migrationInterface.EXPECT().Create(gomock.Any()).Return(&v1.VirtualMachineInstanceMigration{ObjectMeta: v13.ObjectMeta{Name: "something"}}, nil).Times(int(virtconfig.ParallelMigrationsPerClusterDefault))
			evictionCount := 0
			shouldExpectMultiplePodEvictions(&evictionCount)

			controller.Execute()
			testutils.ExpectEvents(recorder, reasons...)
			Expect(evictionCount).To(Equal(defaultBatchDeletionCount))
		})

		It("should detect in-flight migrations when only migrate VMIs up to the global max migration count", func() {
			kv := newKubeVirt(50)
			kv.Spec.WorkloadUpdateStrategy.WorkloadUpdateMethods = []v1.WorkloadUpdateMethod{v1.WorkloadUpdateMethodLiveMigrate, v1.WorkloadUpdateMethodEvict}
			addKubeVirt(kv)

			reasons := []string{}
			for i := 0; i < 50; i++ {
				vmi := newVirtualMachine(fmt.Sprintf("testvm-migratable-%d", i), true, "madeup", vmiSource, podSource)
				// create enough migrations to only allow one more active one to be created
				if i < int(virtconfig.ParallelMigrationsPerClusterDefault)-1 {
					migrationFeeder.Add(newMigration(fmt.Sprintf("vmim-%d", i), vmi.Name, v1.MigrationRunning))
				} else if i < int(virtconfig.ParallelMigrationsPerClusterDefault) {
					migrationFeeder.Add(newMigration(fmt.Sprintf("vmim-%d", i), vmi.Name, v1.MigrationSucceeded))
					// expect only a single migration to occur due to global limit
					reasons = append(reasons, SuccessfulCreateVirtualMachineInstanceMigrationReason)
				} else {
					migrationFeeder.Add(newMigration(fmt.Sprintf("vmim-%d", i), vmi.Name, v1.MigrationSucceeded))
				}
			}

			// wait for informer to catch up since we aren't watching for vmis directly
			time.Sleep(1 * time.Second)

			//migrationInterface.EXPECT().Create(gomock.Any()).Return(&v1.VirtualMachineInstanceMigration{ObjectMeta: v13.ObjectMeta{Name: "something"}}, nil).AnyTimes()
			migrationInterface.EXPECT().Create(gomock.Any()).Return(&v1.VirtualMachineInstanceMigration{ObjectMeta: v13.ObjectMeta{Name: "something"}}, nil).Times(1)

			controller.Execute()
			testutils.ExpectEvents(recorder, reasons...)
		})

		It("should migrate/shutdown outdated VMIs and leave up to date VMIs alone", func() {
			reasons := []string{}
			newVirtualMachine("testvm-outdated-migratable", true, "madeup", vmiSource, podSource)
			reasons = append(reasons, SuccessfulCreateVirtualMachineInstanceMigrationReason)

			newVirtualMachine("testvm-outdated-non-migratable", false, "madeup", vmiSource, podSource)
			reasons = append(reasons, SuccessfulEvictVirtualMachineInstanceReason)

			for i := 0; i < 50; i++ {
				newVirtualMachine(fmt.Sprintf("testvm-up-to-date-migratable-%d", i), true, expectedImage, vmiSource, podSource)
				newVirtualMachine(fmt.Sprintf("testvm-up-to-date-non-migratable-%d", i), false, expectedImage, vmiSource, podSource)
			}

			// wait for informer to catch up since we aren't watching for vmis directly
			time.Sleep(1 * time.Second)
			kv := newKubeVirt(2)
			kv.Spec.WorkloadUpdateStrategy.WorkloadUpdateMethods = []v1.WorkloadUpdateMethod{v1.WorkloadUpdateMethodLiveMigrate, v1.WorkloadUpdateMethodEvict}
			addKubeVirt(kv)

			migrationInterface.EXPECT().Create(gomock.Any()).Return(&v1.VirtualMachineInstanceMigration{ObjectMeta: v13.ObjectMeta{Name: "something"}}, nil).Times(1)
			evictionCount := 0
			shouldExpectMultiplePodEvictions(&evictionCount)

			controller.Execute()
			testutils.ExpectEvents(recorder, reasons...)
			Expect(evictionCount).To(Equal(1))
		})

		It("should do nothing if no method is set", func() {
			for i := 0; i < 50; i++ {
				newVirtualMachine(fmt.Sprintf("testvm-migratable-%d", i), true, "madeup", vmiSource, podSource)
			}
			for i := 0; i < 50; i++ {
				newVirtualMachine(fmt.Sprintf("testvm-%d", i), false, "madeup", vmiSource, podSource)
			}

			// wait for informer to catch up since we aren't watching
			// for vmis directly
			time.Sleep(1 * time.Second)
			kv := newKubeVirt(100)
			addKubeVirt(kv)
			controller.Execute()
		})

		It("should shutdown VMIs and not migrate when only shutdown method is set", func() {
			reasons := []string{}
			for i := 0; i < 50; i++ {
				newVirtualMachine(fmt.Sprintf("testvm-migratable-%d", i), true, "madeup", vmiSource, podSource)
			}
			for i := 0; i < defaultBatchDeletionCount; i++ {
				reasons = append(reasons, SuccessfulEvictVirtualMachineInstanceReason)
			}

			// wait for informer to catch up since we aren't watching
			// for vmis directly
			time.Sleep(1 * time.Second)
			kv := newKubeVirt(50)
			kv.Spec.WorkloadUpdateStrategy.WorkloadUpdateMethods = []v1.WorkloadUpdateMethod{v1.WorkloadUpdateMethodEvict}
			addKubeVirt(kv)

			evictionCount := 0
			shouldExpectMultiplePodEvictions(&evictionCount)

			controller.Execute()
			testutils.ExpectEvents(recorder, reasons...)
			Expect(evictionCount).To(Equal(defaultBatchDeletionCount))
		})

		It("should not evict VMIs when an active migration is in flight", func() {
			kv := newKubeVirt(2)
			kv.Spec.WorkloadUpdateStrategy.WorkloadUpdateMethods = []v1.WorkloadUpdateMethod{v1.WorkloadUpdateMethodEvict}
			addKubeVirt(kv)

			vmi := newVirtualMachine("testvm-migratable", true, "madeup", vmiSource, podSource)
			migrationFeeder.Add(newMigration("vmim-1", vmi.Name, v1.MigrationRunning))
			vmi = newVirtualMachine("testvm-nonmigratable", true, "madeup", vmiSource, podSource)
			migrationFeeder.Add(newMigration("vmim-2", vmi.Name, v1.MigrationRunning))

			// wait for informer to catch up since we aren't watching
			// for vmis directly
			time.Sleep(1 * time.Second)

			controller.Execute()
			Expect(recorder.Events).To(BeEmpty())
		})

		It("should respect custom batch deletion count", func() {
			batchDeletions := 30
			reasons := []string{}
			for i := 0; i < 50; i++ {
				newVirtualMachine(fmt.Sprintf("testvm-migratable-%d", i), true, "madeup", vmiSource, podSource)
			}
			for i := 0; i < batchDeletions; i++ {
				reasons = append(reasons, SuccessfulEvictVirtualMachineInstanceReason)
			}

			// wait for informer to catch up since we aren't watching
			// for vmis directly
			time.Sleep(1 * time.Second)
			kv := newKubeVirt(50)
			kv.Spec.WorkloadUpdateStrategy.WorkloadUpdateMethods = []v1.WorkloadUpdateMethod{v1.WorkloadUpdateMethodEvict}
			kv.Spec.WorkloadUpdateStrategy.BatchEvictionSize = &batchDeletions
			addKubeVirt(kv)

			evictionCount := 0
			shouldExpectMultiplePodEvictions(&evictionCount)

			controller.Execute()
			testutils.ExpectEvents(recorder, reasons...)
			Expect(evictionCount).To(Equal(batchDeletions))
		})

		It("should respect custom batch interval", func() {
			controller.throttleIntervalSeconds = 0

			batchDeletions := 5
			batchInterval := time.Duration(2) * time.Second
			reasons := []string{}
			for i := 0; i < batchDeletions; i++ {
				reasons = append(reasons, SuccessfulEvictVirtualMachineInstanceReason)
			}

			for i := 0; i < batchDeletions*2; i++ {
				newVirtualMachine(fmt.Sprintf("testvm-migratable-1-%d", i), true, "madeup", vmiSource, podSource)
			}
			// wait for informer to catch up since we aren't watching
			// for vmis directly
			time.Sleep(1 * time.Second)
			kv := newKubeVirt(batchDeletions * 2)
			kv.Spec.WorkloadUpdateStrategy.WorkloadUpdateMethods = []v1.WorkloadUpdateMethod{v1.WorkloadUpdateMethodEvict}
			kv.Spec.WorkloadUpdateStrategy.BatchEvictionSize = &batchDeletions
			kv.Spec.WorkloadUpdateStrategy.BatchEvictionInterval = &metav1.Duration{
				Duration: batchInterval,
			}

			evictionCount := 0
			shouldExpectMultiplePodEvictions(&evictionCount)

			addKubeVirt(kv)
			controller.Execute()
			testutils.ExpectEvents(recorder, reasons...)

			// Should do nothing this second execute due to interval
			addKubeVirt(kv)
			controller.Execute()
			Expect(recorder.Events).To(BeEmpty())

			// sleep to account for batch interval
			time.Sleep(3 * time.Second)

			// Should execute another batch of deletions after sleep
			addKubeVirt(kv)
			controller.Execute()
			testutils.ExpectEvents(recorder, reasons...)
			Expect(evictionCount).To(Equal(batchDeletions * 2))
		})

		It("should respect reconcile loop throttling", func() {
			controller.throttleIntervalSeconds = 5

			batchDeletions := 5
			batchInterval := time.Duration(2) * time.Second
			reasons := []string{}
			for i := 0; i < batchDeletions; i++ {
				reasons = append(reasons, SuccessfulEvictVirtualMachineInstanceReason)
			}

			for i := 0; i < batchDeletions*2; i++ {
				newVirtualMachine(fmt.Sprintf("testvm-migratable-1-%d", i), true, "madeup", vmiSource, podSource)
			}
			// wait for informer to catch up since we aren't watching
			// for vmis directly
			time.Sleep(1 * time.Second)
			kv := newKubeVirt(batchDeletions * 2)
			kv.Spec.WorkloadUpdateStrategy.WorkloadUpdateMethods = []v1.WorkloadUpdateMethod{v1.WorkloadUpdateMethodEvict}
			kv.Spec.WorkloadUpdateStrategy.BatchEvictionSize = &batchDeletions
			kv.Spec.WorkloadUpdateStrategy.BatchEvictionInterval = &metav1.Duration{
				Duration: batchInterval,
			}

			evictionCount := 0
			shouldExpectMultiplePodEvictions(&evictionCount)

			addKubeVirt(kv)
			controller.Execute()
			testutils.ExpectEvents(recorder, reasons...)

			// Should do nothing this second execute due to interval
			addKubeVirt(kv)
			controller.Execute()
			Expect(recorder.Events).To(BeEmpty())

			// sleep to account for batch interval
			time.Sleep(3 * time.Second)

			// Should do nothing this third time due to reconcile loop throttle
			addKubeVirt(kv)
			controller.Execute()
			Expect(recorder.Events).To(BeEmpty())

			// sleep to account for throttle interval
			time.Sleep(3 * time.Second)

			// Should execute another batch of deletions after throttling expires
			addKubeVirt(kv)
			controller.Execute()
			testutils.ExpectEvents(recorder, reasons...)
			Expect(evictionCount).To(Equal(batchDeletions * 2))
		})

	})

	AfterEach(func() {
		close(stop)

		Expect(recorder.Events).To(BeEmpty())
		ctrl.Finish()
	})
})

func newKubeVirt(expectedNumOutdated int) *v1.KubeVirt {
	return &v1.KubeVirt{
		ObjectMeta: v13.ObjectMeta{
			Name:      "test",
			Namespace: "default",
		},
		Spec: v1.KubeVirtSpec{},
		Status: v1.KubeVirtStatus{
			Phase:                                   v1.KubeVirtPhaseDeployed,
			OutdatedVirtualMachineInstanceWorkloads: &expectedNumOutdated,
		},
	}
}

func newVirtualMachine(name string, isMigratable bool, image string, vmiSource *framework.FakeControllerSource, podSource *framework.FakeControllerSource) *v1.VirtualMachineInstance {
	vmi := v1.NewMinimalVMI("testvm")
	vmi.Name = name
	vmi.Namespace = v12.NamespaceDefault
	vmi.Status.LauncherContainerImageVersion = image
	vmi.Status.Phase = v1.Running
	vmi.UID = "1234"
	if isMigratable {
		vmi.Status.Conditions = []v1.VirtualMachineInstanceCondition{{Type: v1.VirtualMachineInstanceIsMigratable, Status: v12.ConditionTrue}}
	}

	pod := &k8sv1.Pod{
		ObjectMeta: metav1.ObjectMeta{
			Name:      vmi.Name,
			Namespace: vmi.Namespace,
			UID:       types.UID(vmi.Name),
			Labels: map[string]string{
				v1.AppLabel:       "virt-launcher",
				v1.CreatedByLabel: string(vmi.UID),
			},
			Annotations: map[string]string{
				v1.DomainAnnotation: vmi.Name,
			},
		},
		Status: k8sv1.PodStatus{
			Phase: k8sv1.PodRunning,
			ContainerStatuses: []k8sv1.ContainerStatus{
				{Ready: false, Name: "compute", State: k8sv1.ContainerState{Running: &k8sv1.ContainerStateRunning{}}},
			},
		},
	}
	vmi.Status.ActivePods = map[types.UID]string{
		pod.UID: "node1",
	}

	vmiSource.Add(vmi)
	podSource.Add(pod)
	return vmi
}

func newMigration(name string, vmi string, phase v1.VirtualMachineInstanceMigrationPhase) *v1.VirtualMachineInstanceMigration {
	migration := kubecli.NewMinimalMigration(name)
	migration.Status.Phase = phase
	migration.Spec.VMIName = vmi
	migration.Namespace = v12.NamespaceDefault
	return migration
}


text:
<?php

class EmpresaDAO implements DefaultDAO{

  private function __construct(){
  }

/* Função que instancia a classe DAO */
  public static function getInstance() {
    static $instance = null;
    if (null === $instance) {
        $instance = new static();
    }
    return $instance;
  }

//--************************************************************************--//
//--****************Inicio dos métodos de login da empresa******************--//
//--************************************************************************--//

  public function validate($data){
    $login = $data['login'];
    $senha = $data['senha'];

    $file = fopen("../private/empresaprivate/logindata/login.json",'r');
    $jsonStr = '';
    $jsonStr .= fgets($file);

    $arrayLogins = json_decode($jsonStr, true);
    session_start();
    if(!isset($_SESSION['empresa']))
      for($i=0; $i <= $this->getIdToCompany()-1; $i++){
        if($arrayLogins[$i]['login'] == $login)
          if($arrayLogins[$i]['senha'] == $senha){
            $_SESSION['empresa']['id']=$arrayLogins[$i]['id'];
          }
      }
    if(!isset($_SESSION['empresa']))
      throw new ValidateException();
  }

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

//--************************************************************************--//
//--****************Inicio dos métodos de logout do usuário******************--//
//--************************************************************************--//
  public function logout(){
    session_start();
    if(isset($_SESSION['empresa']))
      session_destroy();
    else
      throw new LogoutException();
  }
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

//--************************************************************************--//
//--*************Inicio dos métodos de persistência e cadastro**************--//
//--************************************************************************--//

  /*
  *  Função que faz a persistência dos dados de login dos usuários dentro do
  *  diretório src/private/logindata/ no arquivo login.json.
  */
  private function cadastra($id,$login,$senha){

    //Verificação do login do usuário.//
    $file = fopen('../private/empresaprivate/logindata/login.json', "r") or die("Unable to open file!");
    $json = "";
    $json = fgets($file);
    fclose($file);
    $jsonToVerify = json_decode($json, true);
    for($i=0; $jsonToVerify[$i]!=null; $i++){
      if($jsonToVerify[$i]['login']==$login)
        throw new AlreadyExistsCompanyException();
    }
    ////////////////////////////////////

    $jsonToPrint = array( 'id' => $id,
                          'login' => $login,
                          'senha' => $senha);

    $oldFile = fopen('../private/empresaprivate/logindata/login.json', "r") or die("Unable to open file!");
    $jsonStr = "";
    $jsonStr = fgets($oldFile);
    fclose($oldFile);

    json_encode($jsonToPrint);
    $newJson = json_decode($jsonStr, true);
    $newJson[] = $jsonToPrint;

    $newFile = fopen('../private/empresaprivate/logindata/login.json', "w") or die("Unable to open file!");
    fwrite($newFile, json_encode($newJson));
    fclose($newFile);
  }

  /*
  *  Função que faz a persistência dos dados do usuário
  *  no diretório src\private\userdata com o razaoSocial userdata-{id do usuário}.json
  */
  private function insertData($login,$senha,$razaoSocial,$cidade,$estado,$pais,$id,$email,$CNPJ,$CEP,$logradouro,$numero,$complementoLocalidade,$numTelefone){
    $jsonToPrint = array( 'id' => $id,
                          'login' => $login,
                          'senha' => $senha,
                          'razaoSocial' => $razaoSocial,
                          'cidade' => $cidade,
                          'estado' => $estado,
                          'pais' => $pais,
                          'email' => $email,
                          'CNPJ' => $CNPJ,
                          'CEP' => $CEP,
                          'logradouro' => $logradouro,
                          'numeroEndereco' => $numero,
                          'complementoLocalidade' => $complementoLocalidade,
                          'numTelefone' => $numTelefone
                          );

    $file = fopen('../private/empresaprivate/userdata/userdata-'.$id.'.json', "w") or die("Unable to open file!");
    fwrite($file, json_encode($jsonToPrint));
    fclose($file);
  }

  /*
  *  Função padrão de inserção da empresa no sistema.
  */
  public function insert($array){
    echo "

VEJA

";
    echo $array["login"];
    echo "

Acima

";

    $novaEmpresa = new Empresa($array);
    $novaEmpresa->setId($this->getIdToCompany());
    try{
      //Função que insere as informações para login, no arquivo login.json.
      $this->cadastra($novaEmpresa->getId(),$novaEmpresa->getLogin(),$novaEmpresa->getSenha());
    }catch(AlreadyExistsCompanyException $e){
      throw new InsertionException($e->getMessage());
    }
    //Função que insere informações do usuário no arquivo específico daquele usuário.
    $this->insertData($novaEmpresa->getLogin(),
                      $novaEmpresa->getSenha(),
                      $novaEmpresa->getrazaoSocial(),
                      $novaEmpresa->getCidade(),
                      $novaEmpresa->getEstado(),
                      $novaEmpresa->getPais(),
                      $novaEmpresa->getId(),
                      $novaEmpresa->getEmail(),
                      $novaEmpresa->getCNPJ(),
                      $novaEmpresa->getCEP(),
                      $novaEmpresa->getLogradouro(),
                      $novaEmpresa->getNumero(),
                      $novaEmpresa->getComplementoLocalidade(),
                      $novaEmpresa->getNumTelefone()
                    );
    return $novaEmpresa;
  }
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

//--************************************************************************--//
//--***********Início dos métodos para a exclusão dos usuários**************--//
//--************************************************************************--//

  /*
  *  Função padrão de deletar uma empresa específico do sistema.
  */
  public function delete($empresa){
    $file = fopen("../private/empresaprivate/logindata/login.json",'r');
    $jsonStr = fgets($file);
    fclose($file);
    $velhoArrayLogins = json_decode($jsonStr, true);
    $novoArrayLogins = [];
    $count=0;
    for($i=0;$velhoArrayLogins[$i]!=null;$i++){
      if($velhoArrayLogins[$i]['id']!=$empresa->getId())
        $novoArrayLogins[] = $velhoArrayLogins[$i];
      else
        $count++;
    }
    $file = fopen("../private/empresaprivate/logindata/login.json",'w');
    fwrite($file, json_encode($novoArrayLogins));
    fclose($file);

    if($count==0)
      throw new DeleteException('Impossível encontrar empresa na lista de logins!');
    if(!file_exists("../private/userdata/userdata-".$empresa->getId().".json"))
      throw new DeleteException();

    unlink("../private/empresaprivate/userdata/userdata-".$empresa->getId().".json");
  }

  /*
  *  Função padrão de deletar todos os usuários do sistema.
  */
  public function deleteAll() {
    $file = fopen("../private/empresaprivate/logindata/login.json", "w");
    fclose($file);
    cleanDirectory("../private/empresaprivate/userdata");
  }
  /*
  *   Função para limpar o diretório
  */
  public function cleanDirectory($directory)
  {
      foreach(glob("{$directory}/*") as $file)
      {
          if(is_dir($file)) {
              cleanDirectory($file);
              rmdir($file);
          } else {
              unlink($file);
          }
      }
  }
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

//--************************************************************************--//
//--*******Início dos métodos para a atualização de dados dos usuários******--//
//--************************************************************************--//

  /*
  *  Função padrão de atualização dos usuários do sistema.
  */
  public function update($object) {
    $empresa = getById([$object->id]);

    if($empresa){
      $candidato->login = $object->login;
      $candidato->senha = $object->senha;
      $candidato->razaoSocial = $object->razaoSocial;
      return true;
    }
    return false;
  }
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

//--************************************************************************--//
//--*******************Início dos métodos auxiliares************************--//
//--************************************************************************--//

  /*
  *  Função padrão que retorna um usuário em específico
  *  caçando pelo id dele no sistema.
  */
  public function getById($id){
    if(file_exists("../private/empresaprivate/userdata/userdata-".$id.".json"))
      $file = fopen("../private/empresaprivate/userdata/userdata-".$id.'.json','r');
    else
      throw new GetCompanyByIdException();

    $jsonStr = fgets($file);
    fclose($file);
    $arrayEmpresa = json_decode($jsonStr, true);
    $novaEmpresa = new Empresa($arrayEmpresa);
    $novaEmpresa->setId($arrayEmpresa['id']);
    return $novaEmpresa;
  }

  /*
  *  Função padrão que retorna um usuário em específico
  *  caçando pelo id dele no sistema.
  */
  public function getByLogin($login){
    $file = fopen("../private/empresaprivate/logindata/login.json",'r');
    $jsonStr = fgets($file);
    fclose($file);
    $arrayLogins = json_decode($jsonStr, true);
    for($i=0;$arrayLogins[$i]!=null;$i++)
      if($arrayLogins[$i]['login']==$login)
        return $this->getById($arrayLogins[$i]['id']);
    throw new GetCompanyByLoginException();
  }

  /*
  *  Função padrão que retorna todos os usuário do sistema.
  */
  public function getAll(){
    $file = fopen('../private/empresaprivate/logindata/login.json', "r") or die("Unable to proceed!");
    while(!feof($file)){
      $candidatos .= fgets($file);
    }
    return $candidatos;
  }
  /*
  * Função que retorna a quantidade de Candidatos cadastrados
  */
  public function getIdToCompany(){
    $file = fopen("../private/empresaprivate/logindata/login.json",'r');
    $jsonStr = '';

    $jsonStr = fgets($file);
    fclose($file);

    $arrayLogins = json_decode($jsonStr, true);
    $count=-1;
    for($i=0; $arrayLogins[$i]!=null; $i++) $count++;

    return $count+1;
  }
}


text:
package org.joverseer.ui.map;

import org.joverseer.JOApplication;
import org.joverseer.metadata.GameTypeEnum;
import org.joverseer.ui.LifecycleEventsEnum;

/**
 * Map Metadata utilities
 *
 * @author Marios Skounakis
 */
public class MapMetadataUtils {
    public void setMapSize(MapMetadata metadata, GameTypeEnum gameType) {
        if (gameType == GameTypeEnum.gameBOFA) {
            metadata.setMinMapColumn(25);
            metadata.setMinMapRow(1);
            metadata.setMaxMapColumn(40);
            metadata.setMaxMapRow(15);
            JOApplication.publishEvent(LifecycleEventsEnum.MapMetadataChangedEvent, this, this);

        } else if (gameType == GameTypeEnum.gameUW) {
            metadata.setMinMapColumn(19);
            metadata.setMinMapRow(2);
            metadata.setMaxMapColumn(32);
            metadata.setMaxMapRow(21);

            JOApplication.publishEvent(LifecycleEventsEnum.MapMetadataChangedEvent, this, this);

        } else if ((gameType == GameTypeEnum.gameCME) || (gameType == GameTypeEnum.gameCMF)) {
            metadata.setMinMapColumn(19);
            metadata.setMinMapRow(6);
            metadata.setMaxMapColumn(34);
            metadata.setMaxMapRow(25);

            JOApplication.publishEvent(LifecycleEventsEnum.MapMetadataChangedEvent, this, this);

    	} else {
            metadata.setMinMapColumn(1);
            metadata.setMinMapRow(1);
            metadata.setMaxMapColumn(44);
            metadata.setMaxMapRow(39);

            JOApplication.publishEvent(LifecycleEventsEnum.MapMetadataChangedEvent, this, this);

        }
    }
}


text:
[![inventid logo](https://cdn.inventid.nl/assets/logo-horizontally-ba8ae38ab1f53863fa4e99b977eaa1c7.png)](http://opensource.inventid.nl)

[![Docker downloads](https://img.shields.io/docker/pulls/inventid/redis-browser.svg)](https://registry.hub.docker.com/u/inventid/redis-browser/)
[![GitHub license](https://img.shields.io/github/license/inventid/redis-browser-docker.svg)](https://github.com/inventid/redis-browser-docker/blob/master/LICENSE)

# Redis Browser in Docker

This is a simple Docker container for the [redis-browser](https://github.com/monterail/redis-browser) gem built by the people of [MonteRail](https://github.com/monterail/).
This container is available from Docker Hub as well: https://hub.docker.com/r/inventid/redis-browser/

Since we use this in production, but didnt want to be bothered with more complex applications, it made sense to embed this into a Docker container and simply let it run somewhere on our Docker farm.
Since this is a fairly simple and static Docker container, we use Puppet for provisioning.
You can use the following snippet to start your container as well

````puppet
class iid_queue::admin {

  docker::image { 'inventid/redis-browser:latest': }

  docker::run { 'redis-browser':
    image   => 'inventid/redis-browser',
    ports   => ["${ipaddress_eth1}:8079:4567"],
    volumes => ["/opt/redis-browser-config:/opt/config"],
    require => File['/opt/redis-browser-config/config.yml'],
    env     => ["PREFIX=redis"]
  }

  file { '/opt/redis-browser-config':
    ensure => directory
  }

  file { '/opt/redis-browser-config/config.yml':
    ensure  => present,
    source  => 'puppet:///modules/iid_queue/config.yml',
    require => File['/opt/redis-browser-config']
  }
}
````

## Config file

You also ned to supply a config file.
The simplest config file which we use in production looks like this:

````yaml
connections:
  default:
    url: redis://queue.inventid.net:6379/12
````

## Credits

It took only a few minutes to make this container.
Instead I'd like to thank the [real contributors to this software](https://github.com/monterail/redis-browser/graphs/contributors)

:heart:


text:
<!DOCTYPE html>

    <meta http-equiv="refresh" content="0;URL=../../openssl_sys/constant.X509_V_ERR_SUITE_B_INVALID_VERSION.html">

Redirecting to ../../openssl_sys/constant.X509_V_ERR_SUITE_B_INVALID_VERSION.html...


text:
* Script to generate ellipsoidal meshes using icosphere

### Changed

### Fixed
- Deprecated import
      `scipy.misc.comb deprecated` -> `scipy.special.comb`
* CPU and GPU RHS function on matrixfree bug (missing cross terms when multiple surfaces)
* LSPR 7 spheres regression test (needed fix due to RHS bug)
* SyntaxError messages due to printing statements py2->py3 in generate brick file

### Removed

## 0.3.2
---
### Added

* Notes to Dockerfile on how to run.
* `pytest` specific version to Dockerfile otherwise pycuda won't installed properly

### Changed

* Log output to include information of the wavelength and electric field for lspr cases.
* How file-name is written  to include wavelength information for lspr cases

### Fixed

* CPU bug in matrixfree RHS function
* Docsrings problem with sphinxs
* Typo "thresold" in param files.

### Removed

## 0.3.1
---
### Added

* Suggestions from JOSS reviewers.
* Dockerfile for alternative installation.

### Changed

* README with latest version of packages tested.
  * Support for `CUDA 8.0` using `gcc 5.4.0` and, PyCUDA 2017.1.1.

### Fixed

* Problem with format of files needed to run performance check.
* Broken link in documentation.
* Small bug: overwriting a variable doesn't allow casting type.

### Removed

## 0.3
---
### Added

* Ported PyGBe to Python 3 (!!!).  This breaks Python 2 support, but who cares.
* Better regression tests (faster, anyway) using pytest
* Localized Surface Plasmon Resonance application.
* lspr main function to run this applications separately.
* lspr application's examples to the `examples` folder.
* Regression and convergence tests for the examples added.
* Update documentation with new application to github pages

### Changed

* Old regression test suite renamed to `convergence_tests`
* All surface related functions are now methods of the surface class
* All field related functions are now methods of the field class
* Use scipy.constants instead of hardcoded values
* Docstrings use proper references now (looks better on Sphinx)
* GMRES function to accept complex numbers. Changed based on `gmres_mgs`
from PyAMG, where modified Gram-Schmidt is used to orthogonalize the
Krylov Space and Givens Rotations are used to provide the residual
norm each iteration
* If complex dielectric, the matvec calls the tree code
separately with the Real part and Imaginary part of the solution and
multiplies by complex constant afterwards. This prevents to modify the
treecode to accept complex numbers.
* Add to RHS functions the corresponding terms to solve lspr problems.

### Fixed

* Py3 syntax for generator iteration
* Switched from `blas.rotg` to `lapack.lartg` since that apparently works correctly

### Removed

* All commented out code
* Unused imports and unused variables removed.

## 0.2.1
---
### Added

* All documentation is available on github pages
* Support for Cuda 7.5
* One liner for setting up Py2.7 environment (sans PyCUDA)
* Use Doctr to automatically generate documentation using Travis

### Changed
* `config` and `param` files are now globbed for so they can have a name different
  than the folder which contains them.
* Updated license with new contributors
* Layout of sphinx documentation toolbars (home button added, more verbose layout)

### Fixed

* Uncaught exception when pygbe doesn't run correctly
* Wrong error type in regression test master script
* Performance runs work on non-X backends
* Uncaught out-of-memory exceptions in regression tests

### Removed

## 0.2
---
### Added
* `setup.py` installer
* `argparse` ArgumentParser to handle command line arguments (all optional)
  * `-c` to specify config file
  * `-p` to specify param file
  * `-o` to specify output folder
  * `-g` to specify geometry folder
* Docstrings to all functions
* Checks for NVCC version and to warn if user doesn't have NVCC on PATH
* Sphinx documentation
* In addition to text output, numerical results are stored to a pickled dictionary for easy access

### Changed
* Repo structure altered to match Python packaging guidelines.
* Modularized code and removed all relative imports
* All `import *` (excepting files in `scripts/`) have been removed and changed to explicit imports
* Problems are now grouped-by-folder.  A given problem will have the format:
```
lys
  ˫ lys.param
  ˫ lys.config
  ˫ built_parse.pqr
  ˫ geometry/Lys1.face
  ˫ geometry/Lys1.vert
  ˫ output/

* Support running in current directory by passing '.' as path
```
* Refactored regression tests, added simple caching to avoid test repeats
* Move many, many functions around so that individual `.py` filenames are more descriptive and accurate

### Removed
* Makefiles (functionality replaced by `setup.py`)
* `pygbe_matrix` and `scripts` folder -- to be relocated to a more appropriate repo somewhere


text:
module.exports = function(grunt){
  // When sails is lifted in production
  grunt.registerTask('prod', [
    'clean:dev',
    'jst:dev',
    'less:dev',
    'copy:dev',
    'coffee:dev',
    'concat',
    'uglify',
    'cssmin',
    'sails-linker:prodJs',
    'sails-linker:prodStyles',
    'sails-linker:devTpl',
    'sails-linker:prodJsJADE',
    'sails-linker:prodStylesJADE',
    'sails-linker:devTplJADE'
  ]);
};


text:
export function enqueue(ractive, event) {
  if (ractive.event) {
    ractive._eventQueue.push(ractive.event);
  }

  ractive.event = event;
}

export function dequeue(ractive) {
  if (ractive._eventQueue.length) {
    ractive.event = ractive._eventQueue.pop();
  } else {
    ractive.event = null;
  }
}


text:
#include "stm32f10x.h"
#include "stm32f10x_spi.h"
#include "stm32f10x_dma.h"
#include "stm32f10x_gpio.h"
#include "stm32f10x_rcc.h"
#include "spi.h"

#define NOP         	0xFF  // Define No Operation, might be used to read status register

#define SPI_CE_1()		GPIO_SetBits(SPI_GPIO_PORT, SPI_GPIO_CE)
#define SPI_CE_0()		GPIO_ResetBits(SPI_GPIO_PORT, SPI_GPIO_CE)

/*
void nRF24L01_DMA_Configuration(void)
{
	DMA_InitTypeDef  DMA_InitStructure;

	RCC_AHBPeriphClockCmd(RCC_AHBPeriph_DMA1, ENABLE);

	DMA_DeInit(DMA1_Channel4);
	DMA_InitStructure.DMA_PeripheralBaseAddr = (uint32_t)SPI2_DR_Addr;
	DMA_InitStructure.DMA_MemoryBaseAddr = (uint32_t)SPI2_Rx_Buff;
	DMA_InitStructure.DMA_DIR = DMA_DIR_PeripheralSRC;
	DMA_InitStructure.DMA_BufferSize = SPI_BUFFER_SIZE;
	DMA_InitStructure.DMA_PeripheralInc = DMA_PeripheralInc_Disable;
	DMA_InitStructure.DMA_MemoryInc = DMA_MemoryInc_Enable;
	DMA_InitStructure.DMA_PeripheralDataSize = DMA_PeripheralDataSize_Byte;
	DMA_InitStructure.DMA_MemoryDataSize = DMA_MemoryDataSize_Byte;
	DMA_InitStructure.DMA_Mode = DMA_Mode_Normal;
	DMA_InitStructure.DMA_Priority = DMA_Priority_VeryHigh;
	DMA_InitStructure.DMA_M2M = DMA_M2M_Disable;
	DMA_Init(DMA1_Channel4, &DMA_InitStructure);

	DMA_DeInit(DMA1_Channel5);
	DMA_InitStructure.DMA_PeripheralBaseAddr = (uint32_t)SPI2_DR_Addr;
	DMA_InitStructure.DMA_MemoryBaseAddr = (uint32_t)SPI2_Tx_Buff;
	DMA_InitStructure.DMA_DIR = DMA_DIR_PeripheralDST;
	DMA_InitStructure.DMA_BufferSize = SPI_BUFFER_SIZE;
	DMA_InitStructure.DMA_PeripheralInc = DMA_PeripheralInc_Disable;
	DMA_InitStructure.DMA_MemoryInc = DMA_MemoryInc_Enable;
	DMA_InitStructure.DMA_PeripheralDataSize = DMA_PeripheralDataSize_Byte;
	DMA_InitStructure.DMA_MemoryDataSize = DMA_MemoryDataSize_Byte;
	DMA_InitStructure.DMA_Mode = DMA_Mode_Normal;
	DMA_InitStructure.DMA_Priority = DMA_Priority_Medium;
	DMA_InitStructure.DMA_M2M = DMA_M2M_Disable;
	DMA_Init(DMA1_Channel5, &DMA_InitStructure);

	SPI_I2S_DMACmd(SPI2, SPI_I2S_DMAReq_Rx, ENABLE);

	SPI_I2S_DMACmd(SPI2, SPI_I2S_DMAReq_Tx, ENABLE);

}*/

void spiInit(void)
{

	GPIO_InitTypeDef GPIO_InitStructure;
	SPI_InitTypeDef  SPI_InitStructure;

	RCC_APB1PeriphClockCmd(SPI_RCC, ENABLE);
	RCC_APB2PeriphClockCmd(SPI_GPIO_RCC | RCC_APB2Periph_AFIO, ENABLE);

	GPIO_InitStructure.GPIO_Pin = SPI_GPIO_CE;
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
	GPIO_Init(SPI_GPIO_PORT, &GPIO_InitStructure);

	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
	GPIO_InitStructure.GPIO_Pin = SPI_GPIO_SCK | SPI_GPIO_MOSI;
	GPIO_Init(SPI_GPIO_PORT, &GPIO_InitStructure);

	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
	GPIO_InitStructure.GPIO_Pin = SPI_GPIO_MISO;
	GPIO_Init(SPI_GPIO_PORT, &GPIO_InitStructure);

	SPI_InitStructure.SPI_Direction = SPI_Direction_2Lines_FullDuplex;
	SPI_InitStructure.SPI_Mode = SPI_Mode_Master;
	SPI_InitStructure.SPI_DataSize = SPI_DataSize_8b;

	SPI_InitStructure.SPI_CPOL = SPI_CPOL_Low;
	SPI_InitStructure.SPI_CPHA = SPI_CPHA_1Edge;
	SPI_InitStructure.SPI_NSS = SPI_NSS_Soft;

	SPI_InitStructure.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_16;
	SPI_InitStructure.SPI_FirstBit = SPI_FirstBit_MSB;
	SPI_InitStructure.SPI_CRCPolynomial = 7;
	SPI_Init(SPI_TYPE, &SPI_InitStructure);

	SPI_Cmd(SPI_TYPE, ENABLE);				/* 使能SPI  */

	SPI_CE_1();
}

uint8_t spiWriteReadByte(uint8_t dat)
{
	/* 当SPI发送缓冲器非空时等待 */
	while (SPI_I2S_GetFlagStatus(SPI2, SPI_I2S_FLAG_TXE) == RESET);

	/* 通过SPI发送一字节数据 */
	SPI_I2S_SendData(SPI2, dat);

	/* 当SPI接收缓冲器为空时等待 */
	while (SPI_I2S_GetFlagStatus(SPI2, SPI_I2S_FLAG_RXNE) == RESET);

	/* 通过SPI接收一字节数据 */
	return SPI_I2S_ReceiveData(SPI2);
}

uint8_t spiReadBuf(uint8_t *_pBuf, uint8_t _ucLen)
{
 	uint8_t i;

	SPI_CE_0();

	for(i = 0; i < _ucLen; i++)
	{
		_pBuf[i] = spiWriteReadByte(NOP);
	}

	SPI_CE_1();

 	return 0;
}


text:
package kr.pe.courage.common.code;

import java.util.HashMap;
import java.util.List;

import org.apache.commons.lang.StringUtils;

/**
 * <pre>
 * kr.pe.courage.cmm.code.service
 * CommonCodeMap.java
 * </pre>
 *
 * @Author : chseok82
 * @Date : 2013. 2. 4.
 * @Version : 1.0
 */
public class CommonCodeMap {
	static private CommonCodeMap m_CommonCodeMap;
	static private HashMap<Object, List<CommonCodeVO>> codeValues;
	static private String commonCodeImplClass;
	static private String commonDetailCodeImplClass;

	private CommonCodeMap() {
		super();
	}

	static public CommonCodeMap getInstance() {
		if (m_CommonCodeMap == null) {
			synchronized (CommonCodeMap.class) {
				if (m_CommonCodeMap == null) {
					m_CommonCodeMap = new CommonCodeMap();
				}
			}
		}

		return m_CommonCodeMap;
	}

	public void setCommonCode(HashMap<Object, List<CommonCodeVO>> codeValues) {
		CommonCodeMap.codeValues = codeValues;
	}

	public List<CommonCodeVO> getCode(String codeType) {
		List<CommonCodeVO> resultList = null;

		if (codeValues != null) {
			resultList = codeValues.get(codeType);
		}

		return resultList;
	}

	public String getCodeName(String codeId, String code) {
		String codeName = "";
		List<CommonCodeVO> codeList = codeValues.get(codeId);

		for (CommonCodeVO codeVo : codeList) {
			if (StringUtils.equals(codeVo.getCode(),code)) {
				codeName = codeVo.getCodeNm();
			}
		}

		return codeName;
	}

	public String getCommonCodeImplClass() {
		return commonCodeImplClass;
	}

	public void setCommonCodeImplClass(String commonCodeImplClass) {
		CommonCodeMap.commonCodeImplClass = commonCodeImplClass;
	}

	public String getCommonDetailCodeImplClass() {
		return commonDetailCodeImplClass;
	}

	public void setCommonDetailCodeImplClass(String commonDetailCodeImplClass) {
		CommonCodeMap.commonDetailCodeImplClass = commonDetailCodeImplClass;
	}
}


text:
import 'colors'

import { getAllTracks, isExceptionTrack } from '../utils'

export default (abletonObj: Object) => {
  const errors = []
  getAllTracks(abletonObj).forEach((track) => {
    if (track.DeviceChain.Mixer.Pan.ArrangerAutomation
      .Events.FloatEvent.length > 1 && !isExceptionTrack(track)) {
      errors.push(`Don't automate track panning on ${track.Name.EffectiveName.Value.green}, automate Utility or some other panning device`)
    }
  })
  return errors
}


text:
using DragonSpark.Runtime;
using DragonSpark.Testing.Objects;
using System.IO;
using System.Text;
using DragonSpark.Testing.Framework.Application;
using DragonSpark.Testing.Framework.Application.Setup;
using Xunit;

namespace DragonSpark.Testing.Runtime
{
	public class SerializerTests
	{
		const string Property = "Property2a258824-6489-4cd5-92e9-d6dd98d76002";
		readonly static string Expected = $@"<ClassWithProperty xmlns=""http://schemas.datacontract.org/2004/07/DragonSpark.Testing.Objects"" xmlns:i=""http://www.w3.org/2001/XMLSchema-instance""><Property>{Property}</Property></ClassWithProperty>";

		[Theory, AutoData, AdditionalTypes( typeof(Serializer) )]
		public void Save( ISerializer sut, ClassWithProperty item )
		{
			item.Property = Property;
			Assert.IsType<Serializer>( sut );
			Assert.Equal( Expected, sut.Save( item ) );
		}

		[Theory, AutoData, AdditionalTypes( typeof(Serializer) )]
		public void Load( ISerializer sut )
		{
			Assert.IsType<Serializer>( sut );

			var stream = new MemoryStream( Encoding.UTF8.GetBytes( Expected ) );

			var loaded = Assert.IsType<ClassWithProperty>( sut.Load<ClassWithProperty>( stream ) );
			Assert.Equal( "Property2a258824-6489-4cd5-92e9-d6dd98d76002", loaded.Property );
		}
	}
}


text:
package io.quarkus.grpc.runtime;

import java.util.List;

import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.inject.Instance;
import javax.inject.Inject;

import io.grpc.BindableService;
import io.grpc.ServerInterceptor;
import io.quarkus.grpc.GrpcService;

@ApplicationScoped
public class GrpcContainer {

    @Inject
    @GrpcService
    Instance<BindableService> services;

    @Inject
    ServerInterceptorStorage interceptorStorage;

    List<ServerInterceptor> getSortedPerServiceInterceptors(String serviceClassName) {
        return Interceptors.getSortedPerServiceInterceptors(serviceClassName,
                interceptorStorage.getInterceptors(serviceClassName));
    }

    List<ServerInterceptor> getSortedGlobalInterceptors() {
        return Interceptors.getSortedGlobalInterceptors(interceptorStorage.getGlobalInterceptors());
    }

    public Instance<BindableService> getServices() {
        return services;
    }
}


text:
package org.jboss.resteasy.test.providers.jaxb.resource;

public class GenericSuperInterfaceAbstractBackendResource<R extends GenericSuperInterfaceBaseResource, Q /* extends GenericSuperInterfaceIVdcQueryable */>
        extends GenericSuperInterfaceBackendResource {

}


text:
package org.stagemonitor.core.metrics.metrics2;

import com.codahale.metrics.Gauge;

import org.slf4j.LoggerFactory;
import org.stagemonitor.core.Stagemonitor;
import org.stagemonitor.core.metrics.MetricNameFilter;
import org.stagemonitor.core.metrics.SortedTableLogReporter;

import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;

import static org.stagemonitor.core.metrics.metrics2.MetricName.name;

public class MetricsStoreBenchmark {

	private final Metric2Registry metricRegistry;
	private final Integer reportingInterval;
	private final int reports;
	private final int gauges;
	private final int timers;
	private final int meters;

	public static void main(String[] args) throws Exception {
		final MetricsStoreBenchmark metricsStoreBenchmark = new MetricsStoreBenchmark(1, 1008, 3000, 1000, 2000);
		metricsStoreBenchmark.run();
	}

	public MetricsStoreBenchmark(Integer reportingInterval, int reports, int gauges, int timers, int meters) {
		this.reportingInterval = reportingInterval;
		this.reports = reports;
		this.gauges = gauges;
		this.timers = timers;
		this.meters = meters;
		System.setProperty("stagemonitor.elasticsearch.url", "http://192.168.99.100:9200");
		System.setProperty("stagemonitor.reporting.interval.elasticsearch", reportingInterval.toString());
		System.setProperty("stagemonitor.reporting.influxdb.url", "http://192.168.99.100:8086");
		System.setProperty("stagemonitor.reporting.interval.influxdb", reportingInterval.toString());
		System.setProperty("stagemonitor.reporting.interval.aggregation", "-1");
		System.setProperty("stagemonitor.applicationName", "Metrics Store Benchmark");
		System.setProperty("stagemonitor.instanceName", "instance");

		metricRegistry = Stagemonitor.getMetric2Registry();
	}

	private void run() throws InterruptedException {
		registerGauges(gauges);

		Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
			@Override
			public Thread newThread(Runnable r) {
				final Thread thread = new Thread(r);
				thread.setDaemon(true);
				return thread;
			}
		}).scheduleAtFixedRate(new Runnable() {
			@Override
			public void run() {
				updateMeters(meters);
				updateTimers(timers);
			}
		}, 0, 500, TimeUnit.MILLISECONDS);

		final SortedTableLogReporter logReporter = SortedTableLogReporter
				.forRegistry(metricRegistry)
				.filter(MetricNameFilter.includePatterns(name("reporting_time").build()))
				.log(LoggerFactory.getLogger(MetricsStoreBenchmark.class))
				.build();
		logReporter.start(10, TimeUnit.SECONDS);

		Thread.sleep((reportingInterval * reports * 1000) + reportingInterval);

		logReporter.report();
	}

	private void updateTimers(int numberOfTimers) {
		for (int i = 0; i < numberOfTimers; i++) {
			metricRegistry.timer(name("timer").tag("number", Integer.toString(i)).build()).update((long) (Math.random() * 1000), TimeUnit.MILLISECONDS);
		}
	}

	private void updateMeters(int n) {
		for (int i = 0; i < n; i++) {
			metricRegistry.meter(name("meter").tag("number", Integer.toString(i)).build()).mark();
		}
	}

	private void registerGauges(int n) {
		for (int i = 0; i < n; i++) {
			metricRegistry.register(name("gauge").tag("number", Integer.toString(i)).build(), new Gauge<Double>() {
				@Override
				public Double getValue() {
					return Math.random();
				}
			});
		}
	}

}


text:
{{ define "title" }}Add New Repository{{ end }}

{{ define "body" }}admin-repository-add{{ end }}

{{ define "content" }}

        <form action="/admin/repository/create" method="POST">
            <fieldset>

Add a new repository

                {{ if .error }}

                        {{ .error }}

                {{ end }}

                    Name for this repository
                    <input type="text" class="form-control" id="name" name="name" placeholder="Repository name">

                    URL for this repository
                    <input type="text" class="form-control" id="url" name="url" placeholder="Repository URL">

                    AccessKey - required for endpoint
                    <input type="text" class="form-control" id="access_key" name="access_key" placeholder="Enter access key">

                    Close pull requests if builds fail
                    <input type="checkbox" class="form-control" id="close_pr" name="close_pr">

                    Update status of commits with build results
                    <input type="checkbox" class="form-control" id="status_pr" name="status_pr">

                <button class="btn btn-info">Add</button>
            </fieldset>
        </form>

{{ end }}

{{ define "js" }}{{ end }}

{{ define "css" }}{{ end }}


text:
package org.coursera.capstone.repository;

import org.coursera.capstone.entity.PatientAnswer;
import org.springframework.data.repository.CrudRepository;

public interface PatientAnswerRepository extends CrudRepository<PatientAnswer, Long> {

}


text:
CentOS_InstallNTP()
{
    Echo_Blue "[+] Installing ntp ..."
    yum install -y ntp
    ntpdate -u pool.ntp.org
    date
}

Debian_InstallNTP()
{
    apt-get update -y
    Echo_Blue "[+] Installing ntp ..."
    apt-get install -y ntpdate
    ntpdate -u pool.ntp.org
    date
}

CentOS_RemoveAMP()
{
    Echo_Blue "[-] Yum remove packages ..."
    rpm -qa|grep httpd
    rpm -e httpd httpd-tools
    rpm -qa|grep mysql
    rpm -e mysql mysql-libs
    rpm -qa|grep php
    rpm -e php-mysql php-cli php-gd php-common php

    yum -y remove httpd*
    yum -y remove mysql-server mysql mysql-libs
    yum -y remove php*
    yum clean all
}

Debian_RemoveAMP()
{
    Echo_Blue "[-] apt-get remove packages ..."
    apt-get update -y
    for removepackages in apache2 apache2-doc apache2-utils apache2.2-common apache2.2-bin apache2-mpm-prefork apache2-doc apache2-mpm-worker mysql-client mysql-server mysql-common mysql-server-core-5.5 mysql-client-5.5 php5 php5-common php5-cgi php5-cli php5-mysql php5-curl php5-gd;
    do apt-get purge -y $removepackages; done
    killall apache2
    dpkg -l |grep apache
    dpkg -P apache2 apache2-doc apache2-mpm-prefork apache2-utils apache2.2-common
    dpkg -l |grep mysql
    dpkg -P mysql-server mysql-common libmysqlclient15off libmysqlclient15-dev
    dpkg -l |grep php
    dpkg -P php5 php5-common php5-cli php5-cgi php5-mysql php5-curl php5-gd
    apt-get autoremove -y && apt-get clean
}

Disable_Selinux()
{
    if [ -s /etc/selinux/config ]; then
        sed -i 's/SELINUX=enforcing/SELINUX=disabled/g' /etc/selinux/config
    fi
}

Xen_Hwcap_Setting()
{
    if [ -s /etc/ld.so.conf.d/libc6-xen.conf ]; then
        sed -i 's/hwcap 1 nosegneg/hwcap 0 nosegneg/g' /etc/ld.so.conf.d/libc6-xen.conf
    fi
}

RHEL_Modify_Source()
{
    Get_RHEL_Version
    \cp ${cur_dir}/conf/CentOS-Base-163.repo /etc/yum.repos.d/CentOS-Base-163.repo
    sed -i "s/\$releasever/${RHEL_Ver}/g" /etc/yum.repos.d/CentOS-Base-163.repo
    sed -i "s/RPM-GPG-KEY-CentOS-6/RPM-GPG-KEY-CentOS-${RHEL_Ver}/g" /etc/yum.repos.d/CentOS-Base-163.repo
    yum clean all
    yum makecache
}

Ubuntu_Modify_Source()
{
    CodeName=''
    if grep -Eqi "10.10" /etc/*-release || echo "${Ubuntu_Version}" | grep -Eqi '^10.10'; then
        CodeName='maverick'
    elif grep -Eqi "11.04" /etc/*-release || echo "${Ubuntu_Version}" | grep -Eqi '^11.04'; then
        CodeName='natty'
    elif  grep -Eqi "11.10" /etc/*-release || echo "${Ubuntu_Version}" | grep -Eqi '^11.10'; then
        CodeName='oneiric'
    elif grep -Eqi "12.10" /etc/*-release || echo "${Ubuntu_Version}" | grep -Eqi '^12.10'; then
        CodeName='quantal'
    elif grep -Eqi "13.04" /etc/*-release || echo "${Ubuntu_Version}" | grep -Eqi '^13.04'; then
        CodeName='raring'
    elif grep -Eqi "13.10" /etc/*-release || echo "${Ubuntu_Version}" | grep -Eqi '^13.10'; then
        CodeName='saucy'
    elif grep -Eqi "10.04" /etc/*-release || echo "${Ubuntu_Version}" | grep -Eqi '^10.04'; then
        CodeName='lucid'
#   elif grep -Eqi "14.04" /etc/*-release || echo "${Ubuntu_Version}" | grep -Eqi '^14.04'; then
#       Ubuntu_Deadline
    elif grep -Eqi "14.10" /etc/*-release || echo "${Ubuntu_Version}" | grep -Eqi '^14.10'; then
        Ubuntu_Deadline
    elif grep -Eqi "15.04" /etc/*-release || echo "${Ubuntu_Version}" | grep -Eqi '^15.04'; then
        Ubuntu_Deadline
    elif grep -Eqi "12.04" /etc/*-release || echo "${Ubuntu_Version}" | grep -Eqi '^12.04'; then
        Ubuntu_Deadline
    fi
    if [ "${CodeName}" != "" ]; then
        \cp /etc/apt/sources.list /etc/apt/sources.list.$(date +"%Y%m%d")
        cat > /etc/apt/sources.list<<EOF
deb http://old-releases.ubuntu.com/ubuntu/ ${CodeName} main restricted universe multiverse
deb http://old-releases.ubuntu.com/ubuntu/ ${CodeName}-security main restricted universe multiverse
deb http://old-releases.ubuntu.com/ubuntu/ ${CodeName}-updates main restricted universe multiverse
deb http://old-releases.ubuntu.com/ubuntu/ ${CodeName}-proposed main restricted universe multiverse
deb http://old-releases.ubuntu.com/ubuntu/ ${CodeName}-backports main restricted universe multiverse
deb-src http://old-releases.ubuntu.com/ubuntu/ ${CodeName} main restricted universe multiverse
deb-src http://old-releases.ubuntu.com/ubuntu/ ${CodeName}-security main restricted universe multiverse
deb-src http://old-releases.ubuntu.com/ubuntu/ ${CodeName}-updates main restricted universe multiverse
deb-src http://old-releases.ubuntu.com/ubuntu/ ${CodeName}-proposed main restricted universe multiverse
deb-src http://old-releases.ubuntu.com/ubuntu/ ${CodeName}-backports main restricted universe multiverse
EOF
    fi
}

Ubuntu_Deadline()
{
    utopic_deadline=`date -d "2015-7-24 00:00:00" +%s`
    vivid_deadline=`date -d "2016-1-24 00:00:00" +%s`
    precise_deadline=`date -d "2017-4-27 00:00:00" +%s`
    cur_time=`date  +%s`
    if [ ${cur_time} -gt ${utopic_deadline} ]; then
        echo "${cur_time} > ${utopic_deadline}"
        CodeName='utopic'
    elif [ ${cur_time} -gt ${vivid_deadline} ]; then
        echo "${cur_time} > ${vivid_deadline}"
        CodeName='vivid'
    elif [ ${cur_time} -gt ${precise_deadline} ]; then
        echo "${cur_time} > ${precise_deadline}"
        CodeName='precise'
    fi
}

CentOS_Dependent()
{
    cp /etc/yum.conf /etc/yum.conf.lnmp
    sed -i 's:exclude=.*:exclude=:g' /etc/yum.conf

    Echo_Blue "[+] Yum installing dependent packages ..."
    for packages in make cmake gcc gcc-c++ gcc-g77 flex bison file libtool libtool-libs autoconf kernel-devel patch wget libjpeg libjpeg-devel libpng libpng-devel libpng10 libpng10-devel gd gd-devel libxml2 libxml2-devel zlib zlib-devel glib2 glib2-devel unzip tar bzip2 bzip2-devel libevent libevent-devel ncurses ncurses-devel curl curl-devel e2fsprogs e2fsprogs-devel krb5 krb5-devel libidn libidn-devel openssl openssl-devel vim-minimal gettext gettext-devel ncurses-devel gmp-devel pspell-devel unzip libcap diffutils net-tools libc-client-devel psmisc libXpm-devel git-core c-ares-devel;
    do yum -y install $packages; done

    mv -f /etc/yum.conf.lnmp /etc/yum.conf
}

Debian_Dependent()
{
    Echo_Blue "[+] Apt-get installing dependent packages ..."
    apt-get update -y
    apt-get autoremove -y
    apt-get -fy install
    export DEBIAN_FRONTEND=noninteractive
    apt-get install -y build-essential gcc g++ make
    for packages in build-essential gcc g++ make cmake autoconf automake re2c wget cron bzip2 libzip-dev libc6-dev file rcconf flex vim bison m4 gawk less cpp binutils diffutils unzip tar bzip2 libbz2-dev libncurses5 libncurses5-dev libtool libevent-dev openssl libssl-dev zlibc libsasl2-dev libltdl3-dev libltdl-dev zlib1g zlib1g-dev libbz2-1.0 libbz2-dev libglib2.0-0 libglib2.0-dev libpng3 libjpeg62 libjpeg62-dev libjpeg-dev libpng-dev libpng12-0 libpng12-dev curl libcurl3 libcurl3-gnutls libcurl4-gnutls-dev libcurl4-openssl-dev libpq-dev libpq5 gettext libjpeg-dev libpng12-dev libxml2-dev libcap-dev ca-certificates debian-keyring debian-archive-keyring libc-client2007e-dev psmisc patch git libc-ares-dev;
    do apt-get install -y $packages --force-yes; done
}

Download_File()
{
    local URL=$1
    local FileName=$2
    if [ -z "${FileName}" ]; then
        FileName=`basename $1`
    fi
    if [ -s "${FileName}" ]; then
        Echo_Cyan "${FileName} [found]."
    else
        if [ -z "${FileName}" ]; then
            Echo_Red "Error: File not found!!! download now ..."
        else
            Echo_Red "Error: ${FileName} not found!!! download now ..."
        fi
        wget -c ${URL}
    fi
}

Check_Download_Files()
{
    Echo_Blue "[+] Downloading install package files ..."
    cd ${cur_dir}/src

    # Dependents
    Download_File ${Download_Mirror}/lib/autoconf/${Autoconf_Ver}.tar.gz ${Autoconf_Ver}.tar.gz
    Download_File ${Download_Mirror}/web/libiconv/${Libiconv_Ver}.tar.gz ${Libiconv_Ver}.tar.gz
    Download_File ${Download_Mirror}/web/libmcrypt/${LibMcrypt_Ver}.tar.gz ${LibMcrypt_Ver}.tar.gz
    Download_File ${Download_Mirror}/web/mcrypt/${Mcypt_Ver}.tar.gz ${Mcypt_Ver}.tar.gz
    Download_File ${Download_Mirror}/web/mhash/${Mash_Ver}.tar.gz ${Mash_Ver}.tar.gz
    Download_File ${Download_Mirror}/lib/freetype/${Freetype_Ver}.tar.gz ${Freetype_Ver}.tar.gz
    Download_File ${Download_Mirror}/lib/curl/${Curl_Ver}.tar.gz ${Curl_Ver}.tar.gz
    Download_File ${Download_Mirror}/web/pcre/${Pcre_Ver}.tar.gz ${Pcre_Ver}.tar.gz

    # Memory allocator
    if [ "${SelectMalloc}" = "2" ]; then
        Download_File ${Download_Mirror}/lib/jemalloc/${Jemalloc_Ver}.tar.bz2 ${Jemalloc_Ver}.tar.bz2
    elif [ "${SelectMalloc}" = "3" ]; then
        Download_File ${Download_Mirror}/lib/tcmalloc/${TCMalloc_Ver}.tar.gz ${TCMalloc_Ver}.tar.gz
        Download_File ${Download_Mirror}/lib/libunwind/${Libunwind_Ver}.tar.gz ${Libunwind_Ver}.tar.gz
    fi

    # Nginx
    Download_File ${Download_Mirror}/web/nginx/${Nginx_Ver}.tar.gz ${Nginx_Ver}.tar.gz

    # "$DBSelect": 1,2,3 is mysql, 4,5 is Mariadb.
    if [[ "${DBSelect}" = 4 || "${DBSelect}" = 5 ]]; then
        Download_File ${Download_Mirror}/datebase/mariadb/${Mariadb_Ver}.tar.gz ${Mariadb_Ver}.tar.gz
    else
        Download_File ${Download_Mirror}/datebase/mysql/${Mysql_Ver}.tar.gz ${Mysql_Ver}.tar.gz
    fi

    # PHP
    Download_File ${Download_Mirror}/web/php/${Php_Ver}.tar.gz ${Php_Ver}.tar.gz
    if [ ${PHPSelect} = "1" ]; then
        Download_File ${Download_Mirror}/web/phpfpm/${Php_Ver}-fpm-0.5.14.diff.gz ${Php_Ver}-fpm-0.5.14.diff.gz
    fi
    Download_File ${Download_Mirror}/datebase/phpmyadmin/${PhpMyAdmin_Ver}.tar.gz ${PhpMyAdmin_Ver}.tar.gz
    Download_File ${Download_Mirror}/prober/p.tar.gz p.tar.gz

    # Apache
    if [[ "${Stack}" == "lamp" || "${Stack}" == "lnamp" ]]; then
        Download_File ${Download_Mirror}/web/apache/${Apache_Version}.tar.gz ${Apache_Version}.tar.gz
        Download_File ${Download_Mirror}/web/apache/${APR_Ver}.tar.gz ${APR_Ver}.tar.gz
        Download_File ${Download_Mirror}/web/apache/${APR_Util_Ver}.tar.gz ${APR_Util_Ver}.tar.gz
        Download_File ${Download_Mirror}/web/apache/rpaf/${Mod_RPAF_Ver}.tar.gz ${Mod_RPAF_Ver}.tar.gz
    fi
}

Install_Autoconf()
{
    Echo_Blue "[+] Installing ${Autoconf_Ver} ..."
    Tar_Cd ${Autoconf_Ver}.tar.gz ${Autoconf_Ver}
    ./configure --prefix=/usr/local/autoconf-2.13
    make && make install
}

Install_Libiconv()
{
    Echo_Blue "[+] Installing ${Libiconv_Ver} ..."
    Tar_Cd ${Libiconv_Ver}.tar.gz ${Libiconv_Ver}
    patch -p0 < ${cur_dir}/src/patch/libiconv-glibc-2.16.patch
    # See: http://www.yundaiwei.com/post/375.html
    #./configure --prefix=/usr/local --enable-static
    ./configure --enable-static
    make && make install
}

Install_Libmcrypt()
{
    Echo_Blue "[+] Installing ${LibMcrypt_Ver} ..."
    Tar_Cd ${LibMcrypt_Ver}.tar.gz ${LibMcrypt_Ver}

    ./configure
    make && make install

    /sbin/ldconfig
    cd libltdl/
    ./configure --enable-ltdl-install
    make && make install

    ln -s /usr/local/lib/libmcrypt.la /usr/lib/libmcrypt.la
    ln -s /usr/local/lib/libmcrypt.so /usr/lib/libmcrypt.so
    ln -s /usr/local/lib/libmcrypt.so.4 /usr/lib/libmcrypt.so.4
    ln -s /usr/local/lib/libmcrypt.so.4.4.8 /usr/lib/libmcrypt.so.4.4.8
    ldconfig
}

Install_Mcrypt()
{
    Echo_Blue "[+] Installing ${Mcypt_Ver} ..."
    Tar_Cd ${Mcypt_Ver}.tar.gz ${Mcypt_Ver}
    ./configure
    make && make install
}

Install_Mhash()
{
    Echo_Blue "[+] Installing ${Mash_Ver} ..."
    Tar_Cd ${Mash_Ver}.tar.gz ${Mash_Ver}
    ./configure
    make && make install
    ln -s /usr/local/lib/libmhash.a /usr/lib/libmhash.a
    ln -s /usr/local/lib/libmhash.la /usr/lib/libmhash.la
    ln -s /usr/local/lib/libmhash.so /usr/lib/libmhash.so
    ln -s /usr/local/lib/libmhash.so.2 /usr/lib/libmhash.so.2
    ln -s /usr/local/lib/libmhash.so.2.0.1 /usr/lib/libmhash.so.2.0.1
    ldconfig
}

Install_Freetype()
{
    Echo_Blue "[+] Installing ${Freetype_Ver} ..."
    Tar_Cd ${Freetype_Ver}.tar.gz ${Freetype_Ver}
    ./configure --prefix=/usr/local/freetype
    make && make install

    cat > /etc/ld.so.conf.d/freetype.conf<<EOF
/usr/local/freetype/lib
EOF
    ldconfig
    ln -sf /usr/local/freetype/include/freetype2 /usr/local/include
    ln -sf /usr/local/freetype/include/ft2build.h /usr/local/include
}

Install_Curl()
{
    Echo_Blue "[+] Installing ${Curl_Ver} ..."
    Tar_Cd ${Curl_Ver}.tar.gz ${Curl_Ver}
    ./configure --prefix=/usr/local/curl --enable-ares
    make && make install
}

Install_Pcre()
{
    Cur_Pcre_Ver=`pcre-config --version`
    if echo "${Cur_Pcre_Ver}" | grep -vEqi '^8.'; then
        Echo_Blue "[+] Installing ${Pcre_Ver} ..."
        Tar_Cd ${Pcre_Ver}.tar.gz ${Pcre_Ver}
        ./configure
        make && make install
    fi
}

CentOS_Lib_Opt()
{
    if [ "${Is_64bit}" = "y" ]; then
        ln -s /usr/lib64/libpng.* /usr/lib/
        ln -s /usr/lib64/libjpeg.* /usr/lib/
    fi

    ulimit -v unlimited

    if [ `grep -L "/lib"    '/etc/ld.so.conf'` ]; then
        echo "/lib" >> /etc/ld.so.conf
    fi

    if [ `grep -L '/usr/lib'    '/etc/ld.so.conf'` ]; then
        echo "/usr/lib" >> /etc/ld.so.conf
        # echo "/usr/lib/openssl/engines" >> /etc/ld.so.conf
    fi

    if [ -d "/usr/lib64" ] && [ `grep -L '/usr/lib64'    '/etc/ld.so.conf'` ]; then
        echo "/usr/lib64" >> /etc/ld.so.conf
        # echo "/usr/lib64/openssl/engines" >> /etc/ld.so.conf
    fi

    if [ `grep -L '/usr/local/lib'    '/etc/ld.so.conf'` ]; then
        echo "/usr/local/lib" >> /etc/ld.so.conf
    fi

    ldconfig

    cat >>/etc/security/limits.conf<<eof
* soft nproc 65535
* hard nproc 65535
* soft nofile 65535
* hard nofile 65535
eof

    echo "fs.file-max=65535" >> /etc/sysctl.conf
}

Debian_Lib_Opt()
{
    if [ "${Is_64bit}" = "y" ]; then
        ln -s /usr/lib/x86_64-linux-gnu/libpng* /usr/lib/
        ln -s /usr/lib/x86_64-linux-gnu/libjpeg* /usr/lib/
    else
        ln -s /usr/lib/i386-linux-gnu/libpng* /usr/lib/
        ln -s /usr/lib/i386-linux-gnu/libjpeg* /usr/lib/
        ln -s /usr/include/i386-linux-gnu/asm /usr/include/asm
    fi

    ulimit -v unlimited

    if [ `grep -L "/lib"    '/etc/ld.so.conf'` ]; then
        echo "/lib" >> /etc/ld.so.conf
    fi

    if [ `grep -L '/usr/lib'    '/etc/ld.so.conf'` ]; then
        echo "/usr/lib" >> /etc/ld.so.conf
    fi

    if [ -d "/usr/lib64" ] && [ `grep -L '/usr/lib64'    '/etc/ld.so.conf'` ]; then
        echo "/usr/lib64" >> /etc/ld.so.conf
    fi

    if [ `grep -L '/usr/local/lib'    '/etc/ld.so.conf'` ]; then
        echo "/usr/local/lib" >> /etc/ld.so.conf
    fi

    ldconfig

    cat >>/etc/security/limits.conf<<eof
* soft nproc 65535
* hard nproc 65535
* soft nofile 65535
* hard nofile 65535
eof

    echo "fs.file-max=65535" >> /etc/sysctl.conf
}


text:
package org.jpmml.model.visitors;

import java.util.Set;

public interface HasActiveFields {

	Set<String> getActiveFields();
}


text:
<?php

namespace Stato\Webflow\Forms;

abstract class Input
{
    protected $attrs;
    protected $type = null;
    protected $isHidden = false;

    public function __construct(array $attrs = array())
    {
        $this->attrs = $attrs;
    }

    public function addAttrs(array $attrs)
    {
        $this->attrs = array_merge($this->attrs, $attrs);
    }

    public function isHidden()
    {
        return $this->isHidden;
    }

    public function render($name, $value = null, array $attrs = array())
    {
        $finalAttrs = array_merge(array('type' => $this->type, 'name' => $name), $this->attrs, $attrs);
        if ($value != '') $finalAttrs['value'] = $value;
        return '<input '.$this->flattenAttrs($finalAttrs).' />';
    }

    protected function flattenAttrs(array $attrs)
    {
        if (count($attrs) == 0) return;
        $set = array();
        foreach($attrs as $key => $value) {
            if ($value !== null && $value !== false) {
                if ($value === true) $set[] = $key.'="'.$key.'"';
                else $set[] = $key.'="'.htmlspecialchars($value, ENT_QUOTES, 'UTF-8').'"';
            }
        }
        return implode(" ", $set);
    }

    protected function htmlEscape($str)
    {
        return htmlspecialchars($str, ENT_QUOTES, 'UTF-8');
    }
}

class TextInput extends Input
{
    protected $type = 'text';
}

class PasswordInput extends Input
{
    protected $type = 'password';
}

class HiddenInput extends Input
{
    protected $type = 'hidden';
    protected $isHidden = true;
}

class FileInput extends Input
{
    protected $type = 'file';

    public function render($name, $value = null, array $attrs = array())
    {
        return parent::render($name, null, $attrs);
    }
}

class Textarea extends Input
{
    public function __construct(array $attrs = array())
    {
        $this->attrs = array_merge(array('cols' => 40, 'rows' => 10), $attrs);
    }

    public function render($name, $value = null, array $attrs = array())
    {
        $finalAttrs = array_merge(array('name' => $name), $this->attrs, $attrs);
        if ($value === null) $value = '';
        return '<textarea '.$this->flattenAttrs($finalAttrs).'>'.$value.'</textarea>';
    }
}

class DateInput extends TextInput
{
    protected $format = 'Y-m-d';

    public function __construct(array $attrs = array())
    {
        if (array_key_exists('format', $attrs)) {
            $this->format = $attrs['format'];
            unset($attrs['format']);
        }
        parent::__construct($attrs);
    }

    public function render($name, $value = null, array $attrs = array())
    {
        if ($value instanceof \DateTime) $value = $value->format($this->format);
        return parent::render($name, $value, $attrs);
    }
}

class DateTimeInput extends DateInput
{
    protected $format = 'Y-m-d H:i:s';
}

class TimeInput extends DateInput
{
    protected $format = 'H:i:s';
}

class CheckboxInput extends Input
{
    protected $type = 'checkbox';
}

class Select extends Input
{
    protected $choices = array();

    public function __construct(array $attrs = array())
    {
        if (array_key_exists('choices', $attrs)) {
            $this->setChoices($attrs['choices']);
            unset($attrs['choices']);
        }
        parent::__construct($attrs);
    }

    public function setChoices(array $choices)
    {
        $this->choices = $choices;
    }

    public function render($name, $value = null, array $attrs = array())
    {
        $finalAttrs = array_merge(array('name' => $name), $this->attrs, $attrs);
        $options = $this->renderOptions($this->choices, $value);
        return '<select '.$this->flattenAttrs($finalAttrs).'>'.$options.'</select>';
    }

    protected function renderOptions($set, $selected = null)
    {
        $str = '';
        $nonAssoc = (key($set) === 0);
        if (!is_array($selected)) $selected = array($selected);
        foreach ($set as $value => $lib) {
            if (is_array($lib)) {
                $str.= '<optgroup label="'.$this->htmlEscape($value).'">'
                    .$this->renderOptions($lib, $selected).'</optgroup>';
            } else {
                if ($nonAssoc) $value = $lib;
                $str.= '<option value="'.$this->htmlEscape($value).'"';
                if (in_array($value, $selected)) $str.= ' selected="selected"';
                $str.= '>'.$this->htmlEscape($lib)."</option>\n";
            }
        }
        return $str;
    }
}

class MultipleSelect extends Select
{
    public function render($name, $value = null, array $attrs = array())
    {
        if (!preg_match('/.*\[\]$/', $name)) $name.= '[]';
        $finalAttrs = array_merge(array('name' => $name), $this->attrs, $attrs);
        $options = $this->renderOptions($this->choices, $value);
        return '<select multiple="multiple" '.$this->flattenAttrs($finalAttrs).'>'.$options.'</select>';
    }
}

class CheckboxMultipleSelect extends MultipleSelect
{
    public function render($name, $value = null, array $attrs = array())
    {
        if (!preg_match('/.*\[\]$/', $name)) $name.= '[]';
        $htmlAttrs = array_merge(array('type' => 'checkbox', 'name' => $name), $this->attrs, $attrs);
        $options = $this->renderCheckboxes($this->choices, $htmlAttrs, $value);
        return "
\n".$options."
\n";
    }

    protected function renderCheckboxes($set, $htmlAttrs, $selected = null, $i = 1)
    {
        $str = '';
        $nonAssoc = (key($set) === 0);
        if (!is_array($selected)) $selected = array($selected);
        foreach ($set as $value => $lib) {
            if (is_array($lib)) {
                $str.= '
'.$this->htmlEscape($value)."
\n
\n"
                    .$this->renderCheckboxes($lib, $htmlAttrs, $selected, $i)."
\n";
                $i = $i + count($lib);
            } else {
                if ($nonAssoc) $value = $lib;
                $finalAttrs = $htmlAttrs;
                if (array_key_exists('id', $htmlAttrs)) {
                    $finalAttrs['id'] = $htmlAttrs['id'].'_'.$i;
                    $labelFor = ' for="'.$finalAttrs['id'].'"';
                } else {
                    $labelFor = '';
                }
                $str.= '
';
                $str.= '<input '.$this->flattenAttrs($finalAttrs).' value="'.$this->htmlEscape($value).'"';
                if (in_array($value, $selected)) $str.= ' checked="checked"';
                $str.= ' />'.$this->htmlEscape($lib)."
\n";
                $i++;
            }
        }
        return $str;
    }
}

class RadioSelect extends Select
{
    public function render($name, $value = null, array $attrs = array())
    {
        $htmlAttrs = array_merge(array('type' => 'radio', 'name' => $name), $this->attrs, $attrs);
        $options = $this->renderButtons($this->choices, $htmlAttrs, $value);
        return "
\n".$options."
\n";
    }

    protected function renderButtons($set, $htmlAttrs, $selected = null, $i = 1)
    {
        $str = '';
        $nonAssoc = (key($set) === 0);
        foreach ($set as $value => $lib) {
            if (is_array($lib)) {
                $str.= '
'.$this->htmlEscape($value)."
\n
\n"
                    .$this->renderButtons($lib, $htmlAttrs, $selected, $i)."
\n";
                $i = $i + count($lib);
            } else {
                if ($nonAssoc) $value = $lib;
                $finalAttrs = $htmlAttrs;
                if (array_key_exists('id', $htmlAttrs)) {
                    $finalAttrs['id'] = $htmlAttrs['id'].'_'.$i;
                    $labelFor = ' for="'.$finalAttrs['id'].'"';
                } else {
                    $labelFor = '';
                }
                $str.= '
';
                $str.= '<input '.$this->flattenAttrs($finalAttrs).' value="'.$this->htmlEscape($value).'"';
                if ($value == $selected) $str.= ' checked="checked"';
                $str.= ' />'.$this->htmlEscape($lib)."
\n";
                $i++;
            }
        }
        return $str;
    }
}


text:
- The recursive method support all orders.

- The traversal method using parent pointer support all orders: preorder, inorder and postorder. The code structure are almost the same, except the postions of the visit function.
  - For preorder, the visit function are called when "last == n->parent".
  - For inorder, the visit function are called when moving to the right child if has one, or moving to the parent node otherwise.
  - For postorder, the visit function are called whenever moving to the parent.

- For preorder traversal, there are two iterative ways.
  - The first one is just like the iterative in-order traversing, using a stack to save all ancestors of current node and moving towards the left-bottom.
  - The second one is similar to the iterative DFS of a graph, using a stack to save all the nodes pending.

- For inorder traversal, there is a morris method that does not need parent pointer or a stack. Basically speaking, for each node P, before we move to its left child L, we link the right child of the last node R in L's inorder sequence to P. In that way, while traversing L, we can finally move to P again.


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/ll_date"
    style="@style/layout_widthMatch_heightMatch"
    android:background="@drawable/corner_round_white"
    android:gravity="center"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/tv_title"
        style="@style/layout_widthMatch_heightWrap"
        android:gravity="center"
        android:paddingTop="@dimen/dimen_10"
        android:text="@string/calendar_choice_date"
        android:textColor="@color/body_font_gray" />

    <com.ai.android.picker.DatePicker
        android:id="@+id/datePicker"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="0.1dip"
        android:layout_marginTop="@dimen/dimen_10"
        android:background="@color/body_gray_bold" />

    <Button
        android:id="@+id/btn_sure"
        style="@style/TextItem_MatchMinHeight_Size30"
        android:layout_marginLeft="@dimen/dimen_15"
        android:layout_marginRight="@dimen/dimen_15"
        android:background="@android:color/transparent"
        android:text="@string/app_ok"
        android:textColor="@color/green_textcolor_selector" />

</LinearLayout>


text:
package s3

import (
	"io/ioutil"
	"os"
	"strconv"
	"testing"

	"github.com/AdRoll/goamz/aws"
	"github.com/docker/distribution/context"
	storagedriver "github.com/docker/distribution/registry/storage/driver"
	"github.com/docker/distribution/registry/storage/driver/testsuites"

	"gopkg.in/check.v1"
)

// Hook up gocheck into the "go test" runner.
func Test(t *testing.T) { check.TestingT(t) }

var s3DriverConstructor func(rootDirectory string) (*Driver, error)
var skipS3 func() string

func init() {
	accessKey := os.Getenv("AWS_ACCESS_KEY")
	secretKey := os.Getenv("AWS_SECRET_KEY")
	bucket := os.Getenv("S3_BUCKET")
	encrypt := os.Getenv("S3_ENCRYPT")
	secure := os.Getenv("S3_SECURE")
	v4auth := os.Getenv("S3_USE_V4_AUTH")
	region := os.Getenv("AWS_REGION")
	root, err := ioutil.TempDir("", "driver-")
	if err != nil {
		panic(err)
	}
	defer os.Remove(root)

	s3DriverConstructor = func(rootDirectory string) (*Driver, error) {
		encryptBool := false
		if encrypt != "" {
			encryptBool, err = strconv.ParseBool(encrypt)
			if err != nil {
				return nil, err
			}
		}

		secureBool := true
		if secure != "" {
			secureBool, err = strconv.ParseBool(secure)
			if err != nil {
				return nil, err
			}
		}

		v4AuthBool := false
		if v4auth != "" {
			v4AuthBool, err = strconv.ParseBool(v4auth)
			if err != nil {
				return nil, err
			}
		}

		parameters := DriverParameters{
			accessKey,
			secretKey,
			bucket,
			aws.GetRegion(region),
			encryptBool,
			secureBool,
			v4AuthBool,
			minChunkSize,
			rootDirectory,
		}

		return New(parameters)
	}

	// Skip S3 storage driver tests if environment variable parameters are not provided
	skipS3 = func() string {
		if accessKey == "" || secretKey == "" || region == "" || bucket == "" || encrypt == "" {
			return "Must set AWS_ACCESS_KEY, AWS_SECRET_KEY, AWS_REGION, S3_BUCKET, and S3_ENCRYPT to run S3 tests"
		}
		return ""
	}

	testsuites.RegisterSuite(func() (storagedriver.StorageDriver, error) {
		return s3DriverConstructor(root)
	}, skipS3)
}

func TestEmptyRootList(t *testing.T) {
	if skipS3() != "" {
		t.Skip(skipS3())
	}

	validRoot, err := ioutil.TempDir("", "driver-")
	if err != nil {
		t.Fatalf("unexpected error creating temporary directory: %v", err)
	}
	defer os.Remove(validRoot)

	rootedDriver, err := s3DriverConstructor(validRoot)
	if err != nil {
		t.Fatalf("unexpected error creating rooted driver: %v", err)
	}

	emptyRootDriver, err := s3DriverConstructor("")
	if err != nil {
		t.Fatalf("unexpected error creating empty root driver: %v", err)
	}

	slashRootDriver, err := s3DriverConstructor("/")
	if err != nil {
		t.Fatalf("unexpected error creating slash root driver: %v", err)
	}

	filename := "/test"
	contents := []byte("contents")
	ctx := context.Background()
	err = rootedDriver.PutContent(ctx, filename, contents)
	if err != nil {
		t.Fatalf("unexpected error creating content: %v", err)
	}
	defer rootedDriver.Delete(ctx, filename)

	keys, err := emptyRootDriver.List(ctx, "/")
	for _, path := range keys {
		if !storagedriver.PathRegexp.MatchString(path) {
			t.Fatalf("unexpected string in path: %q != %q", path, storagedriver.PathRegexp)
		}
	}

	keys, err = slashRootDriver.List(ctx, "/")
	for _, path := range keys {
		if !storagedriver.PathRegexp.MatchString(path) {
			t.Fatalf("unexpected string in path: %q != %q", path, storagedriver.PathRegexp)
		}
	}
}


text:
package com.navercorp.pinpoint.plugin.jdbc.postgresql;

import com.navercorp.pinpoint.pluginit.jdbc.DriverProperties;
import com.navercorp.pinpoint.pluginit.jdbc.JDBCDriverClass;
import com.navercorp.pinpoint.pluginit.jdbc.JDBCTestConstants;
import com.navercorp.pinpoint.pluginit.utils.AgentPath;
import com.navercorp.pinpoint.pluginit.utils.TestcontainersOption;
import com.navercorp.pinpoint.test.plugin.Dependency;
import com.navercorp.pinpoint.test.plugin.JvmVersion;
import com.navercorp.pinpoint.test.plugin.PinpointAgent;
import com.navercorp.pinpoint.test.plugin.PinpointConfig;
import com.navercorp.pinpoint.test.plugin.PinpointPluginTestSuite;

import com.navercorp.pinpoint.test.plugin.shared.SharedTestLifeCycleClass;
import org.junit.Assume;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;

import java.net.URL;

/**
 * @author HyunGil Jeong
 */
@RunWith(PinpointPluginTestSuite.class)
@PinpointAgent(AgentPath.PATH)
@JvmVersion(8)
//@Dependency({"org.postgresql:postgresql:[42.2.15.jre6]",
//        JDBCTestConstants.VERSION, TestcontainersOption.TEST_CONTAINER, TestcontainersOption.POSTGRESQL})
@PinpointConfig("pinpoint-postgresql.config")
@Dependency({"org.postgresql:postgresql:[9.4.1208,)",
        JDBCTestConstants.VERSION, TestcontainersOption.TEST_CONTAINER, TestcontainersOption.POSTGRESQL})
@SharedTestLifeCycleClass(PostgreSqlServer.class)
public class PostgreSql_Post_9_4_1208_IT extends PostgreSqlBase {

    private final Logger logger = LogManager.getLogger(getClass());

    private static PostgreSqlItHelper HELPER;
    private static PostgreSqlJDBCDriverClass driverClass;

    private static PostgreSqlJDBCApi jdbcApi;

    @BeforeClass
    public static void beforeClass() throws Exception {
        invalidJarCheck();

        DriverProperties driverProperties = getDriverProperties();
        driverClass = new PostgreSql_Post_9_4_1208_JDBCDriverClass();
        jdbcApi = new PostgreSqlJDBCApi(driverClass);

        driverClass.getDriver();

        HELPER = new PostgreSqlItHelper(driverProperties);
    }

    private static void invalidJarCheck() {
        ClassLoader classLoader = PostgreSql_Post_9_4_1208_IT.class.getClassLoader();
        // invalid jar : postgresql-42.2.15.jre6
        URL jar = classLoader.getResource("org.postgresql.Driver".replace('.', '/').concat(".class"));
        Assume.assumeTrue("test skip : invalid jar ", jar != null);
    }

    @Override
    protected JDBCDriverClass getJDBCDriverClass() {
        return driverClass;
    }

    @Test
    public void testStatements() throws Exception {
        HELPER.testStatements(jdbcApi);
    }
}


text:
<?php
/**
 * Genesis Framework.
 *
 * WARNING: This file is part of the core Genesis Framework. DO NOT edit this file under any circumstances.
 * Please do all modifications in the form of a child theme.
 *
 * @package Genesis\Sidebars
 * @author  StudioPress
 * @license GPL-2.0+
 * @link    http://my.studiopress.com/themes/genesis/
 */

add_action( 'genesis_sidebar', 'genesis_do_sidebar' );
/**
 * Echo primary sidebar default content.
 *
 * Only shows if sidebar is empty, and current user has the ability to edit theme options (manage widgets).
 *
 * @since 1.2.0
 *
 * @uses genesis_default_widget_area_content() Template for default widget are content.
 */
function genesis_do_sidebar() {

	if ( ! dynamic_sidebar( 'sidebar' ) && current_user_can( 'edit_theme_options' )  ) {
		genesis_default_widget_area_content( __( 'Primary Sidebar Widget Area', 'genesis' ) );
	}

}

add_action( 'genesis_sidebar_alt', 'genesis_do_sidebar_alt' );
/**
 * Echo alternate sidebar default content.
 *
 * Only shows if sidebar is empty, and current user has the ability to edit theme options (manage widgets).
 *
 * @since 1.2.0
 *
 * @uses genesis_default_widget_area_content() Template for default widget are content.
 */
function genesis_do_sidebar_alt() {

	if ( ! dynamic_sidebar( 'sidebar-alt' ) && current_user_can( 'edit_theme_options' ) ) {
		genesis_default_widget_area_content( __( 'Secondary Sidebar Widget Area', 'genesis' ) );
	}

}

/**
 * Template for default widget area content.
 *
 * @since 2.0.0
 *
 * @param string $name Name of the widget area e.g. `__( 'Secondary Sidebar Widget Area', 'yourtextdomain' )`.
 */
function genesis_default_widget_area_content( $name ) {

	echo genesis_html5() ? '
' : '
';
	echo '
';

		printf( '
%s
', esc_html( $name ) );
		echo '

';

			printf( __( 'This is the %s. You can add content to this area by visiting your Widgets Panel and adding new widgets to this area.', 'genesis' ), $name, admin_url( 'widgets.php' ) );

		echo '

';

	echo '
';
	echo genesis_html5() ? '
' : '
';

}