text:
package router

import (
	"bytes"
	"encoding/json"
	"fmt"
	"net/http"
	"net/http/httptest"
	"testing"

	mocks "github.com/ghmeier/bloodlines/_mocks"
	"github.com/ghmeier/bloodlines/handlers"
	"github.com/ghmeier/bloodlines/models"

	"github.com/pborman/uuid"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/mock"
	"gopkg.in/gin-gonic/gin.v1"
)

func TestTriggerViewAllSuccess(t *testing.T) {
	assert := assert.New(t)

	gin.SetMode(gin.TestMode)

	b, mock := mockTrigger()
	mock.On("GetAll", 0, 20).Return(make([]*models.Trigger, 0), nil)

	w := httptest.NewRecorder()
	r, _ := http.NewRequest("GET", "/api/trigger", nil)
	b.router.ServeHTTP(w, r)

	assert.Equal(200, w.Code)
}

func TestTriggerViewAllParams(t *testing.T) {
	assert := assert.New(t)

	gin.SetMode(gin.TestMode)

	b, mock := mockTrigger()
	mock.On("GetAll", 20, 100).Return(make([]*models.Trigger, 0), nil)

	w := httptest.NewRecorder()
	r, _ := http.NewRequest("GET", "/api/trigger?offset=20&limit=100", nil)
	b.router.ServeHTTP(w, r)

	assert.Equal(200, w.Code)
}

func TestTriggerViewAllFail(t *testing.T) {
	assert := assert.New(t)

	gin.SetMode(gin.TestMode)

	b, mock := mockTrigger()
	mock.On("GetAll", 0, 20).Return(nil, fmt.Errorf("some error"))

	w := httptest.NewRecorder()
	r, _ := http.NewRequest("GET", "/api/trigger", nil)
	b.router.ServeHTTP(w, r)

	assert.Equal(500, w.Code)
}

func TestTriggerNewSuccess(t *testing.T) {
	assert := assert.New(t)

	gin.SetMode(gin.TestMode)
	trigger := models.Trigger{
		ContentID: uuid.NewUUID(),
		Key:       "test_key",
		Values:    make(map[string]string),
	}

	b, tMock := mockTrigger()
	tMock.On("Get", "test_key").Return(nil, nil)
	tMock.On("Insert", mock.AnythingOfType("*models.Trigger")).Return(nil)

	s, _ := json.Marshal(trigger)
	w := httptest.NewRecorder()
	r, _ := http.NewRequest("POST", "/api/trigger", bytes.NewReader(s))
	b.router.ServeHTTP(w, r)

	assert.Equal(200, w.Code)
}

func TestTriggerNewFail(t *testing.T) {
	assert := assert.New(t)

	gin.SetMode(gin.TestMode)
	trigger := models.Trigger{
		ContentID: uuid.NewUUID(),
		Key:       "test_key",
		Values:    make(map[string]string),
	}

	b, tMock := mockTrigger()
	tMock.On("Get", "test_key").Return(nil, nil)
	tMock.On("Insert", mock.AnythingOfType("*models.Trigger")).Return(fmt.Errorf("some error"))

	s, _ := json.Marshal(trigger)
	w := httptest.NewRecorder()
	r, _ := http.NewRequest("POST", "/api/trigger", bytes.NewReader(s))
	b.router.ServeHTTP(w, r)

	assert.Equal(500, w.Code)
}

func TestTriggerNewDuplicate(t *testing.T) {
	assert := assert.New(t)

	gin.SetMode(gin.TestMode)
	trigger := models.Trigger{
		ContentID: uuid.NewUUID(),
		Key:       "test_key",
		Values:    make(map[string]string),
	}

	b, tMock := mockTrigger()
	tMock.On("Get", "test_key").Return(&models.Trigger{}, nil)

	s, _ := json.Marshal(trigger)
	w := httptest.NewRecorder()
	r, _ := http.NewRequest("POST", "/api/trigger", bytes.NewReader(s))
	b.router.ServeHTTP(w, r)

	assert.Equal(400, w.Code)
}

func TestTriggerNewInvalid(t *testing.T) {
	assert := assert.New(t)

	gin.SetMode(gin.TestMode)
	b, _ := mockTrigger()

	s := []byte("{\"contentId\": \"invalid-id\"}")
	w := httptest.NewRecorder()
	r, _ := http.NewRequest("POST", "/api/trigger", bytes.NewReader(s))
	b.router.ServeHTTP(w, r)

	assert.Equal(400, w.Code)
}

func TestTriggerViewSuccess(t *testing.T) {
	assert := assert.New(t)

	gin.SetMode(gin.TestMode)

	b, mock := mockTrigger()
	mock.On("Get", "test_key").Return(&models.Trigger{}, nil)

	w := httptest.NewRecorder()
	r, _ := http.NewRequest("GET", "/api/trigger/test_key", nil)
	b.router.ServeHTTP(w, r)

	assert.Equal(200, w.Code)
}

func TestTriggerViewFail(t *testing.T) {
	assert := assert.New(t)

	gin.SetMode(gin.TestMode)

	b, mock := mockTrigger()
	mock.On("Get", "test_key").Return(nil, fmt.Errorf("some error"))

	w := httptest.NewRecorder()
	r, _ := http.NewRequest("GET", "/api/trigger/test_key", nil)
	b.router.ServeHTTP(w, r)

	assert.Equal(500, w.Code)
}

func TestTriggerUpdateSuccess(t *testing.T) {
	assert := assert.New(t)

	gin.SetMode(gin.TestMode)
	trigger := models.Trigger{
		ID:        uuid.NewUUID(),
		ContentID: uuid.NewUUID(),
		Values:    make(map[string]string),
		Key:       "test_key",
	}

	b, tMock := mockTrigger()
	tMock.On("Update", trigger.Key, trigger.ContentID, trigger.Values).Return(nil)

	s, _ := json.Marshal(trigger)
	w := httptest.NewRecorder()
	r, _ := http.NewRequest("PUT", "/api/trigger/test_key", bytes.NewReader(s))
	b.router.ServeHTTP(w, r)

	assert.Equal(200, w.Code)
}

func TestTriggerUpdateInvalid(t *testing.T) {
	assert := assert.New(t)

	gin.SetMode(gin.TestMode)

	b, _ := mockTrigger()

	s := []byte("{\"contentId\": \"invalid-id\"}")
	w := httptest.NewRecorder()
	r, _ := http.NewRequest("PUT", "/api/trigger/test_key", bytes.NewReader(s))
	b.router.ServeHTTP(w, r)

	assert.Equal(400, w.Code)
}

func TestTriggerUpdateFail(t *testing.T) {
	assert := assert.New(t)

	gin.SetMode(gin.TestMode)
	trigger := models.Trigger{
		ID:        uuid.NewUUID(),
		ContentID: uuid.NewUUID(),
		Key:       "test_key",
		Values:    make(map[string]string),
	}

	b, tMock := mockTrigger()
	tMock.On("Update", trigger.Key, trigger.ContentID, trigger.Values).Return(fmt.Errorf("some error"))

	s, _ := json.Marshal(trigger)
	w := httptest.NewRecorder()
	r, _ := http.NewRequest("PUT", "/api/trigger/test_key", bytes.NewReader(s))
	b.router.ServeHTTP(w, r)

	assert.Equal(500, w.Code)
}

func TestTriggerDeleteSuccess(t *testing.T) {
	assert := assert.New(t)

	gin.SetMode(gin.TestMode)
	key := "test_key"

	b, tMock := mockTrigger()
	tMock.On("Delete", key).Return(nil)

	w := httptest.NewRecorder()
	r, _ := http.NewRequest("DELETE", "/api/trigger/test_key", nil)
	b.router.ServeHTTP(w, r)

	assert.Equal(200, w.Code)
}

func TestTriggerDeleteFail(t *testing.T) {
	assert := assert.New(t)

	gin.SetMode(gin.TestMode)
	key := "test_key"

	b, tMock := mockTrigger()
	tMock.On("Delete", key).Return(fmt.Errorf("some error"))

	w := httptest.NewRecorder()
	r, _ := http.NewRequest("DELETE", "/api/trigger/test_key", nil)
	b.router.ServeHTTP(w, r)

	assert.Equal(500, w.Code)
}

func TestTriggerActivateSuccess(t *testing.T) {
	assert := assert.New(t)

	gin.SetMode(gin.TestMode)

	mockTrigger := &mocks.TriggerI{}
	mockContent := &mocks.ContentI{}
	mockReceipt := &mocks.ReceiptI{}
	b := getMockBloodlines()
	b.trigger = &handlers.Trigger{
		Trigger:     mockTrigger,
		Receipt:     mockReceipt,
		Content:     mockContent,
		BaseHandler: &handlers.BaseHandler{Stats: nil},
	}
	InitRouter(b)

	key := "test_key"
	values := make(map[string]string)
	values["first_name"] = "Wololo"

	trigger := &models.Trigger{
		Key:       key,
		ID:        uuid.NewUUID(),
		ContentID: uuid.NewUUID(),
		Values:    values,
	}

	content := &models.Content{
		ID:      trigger.ContentID,
		Type:    models.EMAIL,
		Text:    "$first_name$ $last_name$",
		Params:  []string{"first_name", "last_name"},
		Status:  models.ACTIVE,
		Subject: "Welcome",
	}

	values = make(map[string]string)
	values["last_name"] = "ololo"
	receipt := &models.Receipt{
		Values: values,
		UserID: uuid.NewUUID(),
	}
	s, _ := json.Marshal(receipt)

	mockTrigger.On("Get", key).Return(trigger, nil)
	mockContent.On("Get", trigger.ContentID.String()).Return(content, nil)
	mockReceipt.On("Insert", mock.AnythingOfType("*models.Receipt")).Return(nil)
	mockReceipt.On("Send", mock.AnythingOfType("*models.SendRequest")).Return(nil)

	w := httptest.NewRecorder()
	r, _ := http.NewRequest("POST", "/api/trigger/test_key/activate", bytes.NewReader(s))
	b.router.ServeHTTP(w, r)

	assert.Equal(200, w.Code)
}

func TestTriggerActivateInsertFail(t *testing.T) {
	assert := assert.New(t)

	gin.SetMode(gin.TestMode)

	mockTrigger := &mocks.TriggerI{}
	mockContent := &mocks.ContentI{}
	mockReceipt := &mocks.ReceiptI{}
	b := getMockBloodlines()
	b.trigger = &handlers.Trigger{
		Trigger:     mockTrigger,
		Receipt:     mockReceipt,
		Content:     mockContent,
		BaseHandler: &handlers.BaseHandler{Stats: nil},
	}
	InitRouter(b)

	key := "test_key"
	values := make(map[string]string)
	values["first_name"] = "Wololo"
	values["last_name"] = "lololo"

	trigger := &models.Trigger{
		Key:       key,
		ID:        uuid.NewUUID(),
		ContentID: uuid.NewUUID(),
		Values:    values,
	}

	content := &models.Content{
		ID:      trigger.ContentID,
		Type:    models.EMAIL,
		Text:    "$first_name$ $last_name$",
		Params:  []string{"first_name", "last_name"},
		Status:  models.ACTIVE,
		Subject: "Welcome",
	}

	values = make(map[string]string)
	receipt := &models.Receipt{
		Values: values,
		UserID: uuid.NewUUID(),
	}
	s, _ := json.Marshal(receipt)

	mockTrigger.On("Get", key).Return(trigger, nil)
	mockContent.On("Get", trigger.ContentID.String()).Return(content, nil)
	mockReceipt.On("Insert", mock.AnythingOfType("*models.Receipt")).Return(fmt.Errorf("some error"))

	w := httptest.NewRecorder()
	r, _ := http.NewRequest("POST", "/api/trigger/test_key/activate", bytes.NewReader(s))
	b.router.ServeHTTP(w, r)

	assert.Equal(500, w.Code)
}

func TestTriggerActivateValueMapError(t *testing.T) {
	assert := assert.New(t)

	gin.SetMode(gin.TestMode)

	mockTrigger := &mocks.TriggerI{}
	mockContent := &mocks.ContentI{}
	mockReceipt := &mocks.ReceiptI{}
	b := getMockBloodlines()
	b.trigger = &handlers.Trigger{
		Trigger:     mockTrigger,
		Receipt:     mockReceipt,
		Content:     mockContent,
		BaseHandler: &handlers.BaseHandler{Stats: nil},
	}
	InitRouter(b)

	key := "test_key"
	values := make(map[string]string)
	values["first_name"] = "Wololo"

	trigger := &models.Trigger{
		Key:       key,
		ID:        uuid.NewUUID(),
		ContentID: uuid.NewUUID(),
		Values:    values,
	}

	content := &models.Content{
		ID:      trigger.ContentID,
		Type:    models.EMAIL,
		Text:    "$first_name$ $last_name$",
		Params:  []string{"first_name", "last_name"},
		Status:  models.ACTIVE,
		Subject: "Welcome",
	}

	values = make(map[string]string)
	receipt := &models.Receipt{
		Values: values,
		UserID: uuid.NewUUID(),
	}
	s, _ := json.Marshal(receipt)

	mockTrigger.On("Get", key).Return(trigger, nil)
	mockContent.On("Get", trigger.ContentID.String()).Return(content, nil)

	w := httptest.NewRecorder()
	r, _ := http.NewRequest("POST", "/api/trigger/test_key/activate", bytes.NewReader(s))
	b.router.ServeHTTP(w, r)

	assert.Equal(400, w.Code)
}

func TestTriggerActivateTriggerFail(t *testing.T) {
	assert := assert.New(t)

	gin.SetMode(gin.TestMode)

	mockTrigger := &mocks.TriggerI{}
	b := getMockBloodlines()
	b.trigger = &handlers.Trigger{
		Trigger:     mockTrigger,
		BaseHandler: &handlers.BaseHandler{Stats: nil},
	}
	InitRouter(b)

	key := "test_key"

	values := make(map[string]string)
	values["last_name"] = "ololo"
	receipt := &models.Receipt{
		Values: values,
		UserID: uuid.NewUUID(),
	}
	s, _ := json.Marshal(receipt)

	mockTrigger.On("Get", key).Return(nil, fmt.Errorf("some error"))
	w := httptest.NewRecorder()
	r, _ := http.NewRequest("POST", "/api/trigger/test_key/activate", bytes.NewReader(s))
	b.router.ServeHTTP(w, r)

	assert.Equal(500, w.Code)
}

func TestTriggerActivateTriggerNil(t *testing.T) {
	assert := assert.New(t)

	gin.SetMode(gin.TestMode)

	mockTrigger := &mocks.TriggerI{}
	b := getMockBloodlines()
	b.trigger = &handlers.Trigger{
		Trigger:     mockTrigger,
		BaseHandler: &handlers.BaseHandler{Stats: nil},
	}
	InitRouter(b)

	key := "test_key"

	values := make(map[string]string)
	values["last_name"] = "ololo"
	receipt := &models.Receipt{
		Values: values,
		UserID: uuid.NewUUID(),
	}
	s, _ := json.Marshal(receipt)

	mockTrigger.On("Get", key).Return(nil, nil)
	w := httptest.NewRecorder()
	r, _ := http.NewRequest("POST", "/api/trigger/test_key/activate", bytes.NewReader(s))
	b.router.ServeHTTP(w, r)

	assert.Equal(404, w.Code)
}

func TestTriggerActivateContentFail(t *testing.T) {
	assert := assert.New(t)

	gin.SetMode(gin.TestMode)

	mockTrigger := &mocks.TriggerI{}
	mockContent := &mocks.ContentI{}
	b := getMockBloodlines()
	b.trigger = &handlers.Trigger{
		Trigger:     mockTrigger,
		Content:     mockContent,
		BaseHandler: &handlers.BaseHandler{Stats: nil},
	}
	InitRouter(b)

	key := "test_key"
	values := make(map[string]string)
	values["first_name"] = "Wololo"

	trigger := &models.Trigger{
		Key:       key,
		ID:        uuid.NewUUID(),
		ContentID: uuid.NewUUID(),
		Values:    values,
	}

	values = make(map[string]string)
	values["last_name"] = "ololo"
	receipt := &models.Receipt{
		Values: values,
		UserID: uuid.NewUUID(),
	}
	s, _ := json.Marshal(receipt)

	mockTrigger.On("Get", key).Return(trigger, nil)
	mockContent.On("Get", trigger.ContentID.String()).Return(nil, fmt.Errorf("some error"))

	w := httptest.NewRecorder()
	r, _ := http.NewRequest("POST", "/api/trigger/test_key/activate", bytes.NewReader(s))
	b.router.ServeHTTP(w, r)

	assert.Equal(500, w.Code)
}

func TestTriggerActivateInvalid(t *testing.T) {
	assert := assert.New(t)

	gin.SetMode(gin.TestMode)

	b := getMockBloodlines()
	b.trigger = &handlers.Trigger{
		BaseHandler: &handlers.BaseHandler{Stats: nil},
	}
	InitRouter(b)

	s := []byte("{\"userId\":\"invalid-id\"}")

	w := httptest.NewRecorder()
	r, _ := http.NewRequest("POST", "/api/trigger/test_key/activate", bytes.NewReader(s))
	b.router.ServeHTTP(w, r)

	assert.Equal(400, w.Code)
}


text:
package com.netease.automate.slave;

import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import org.apache.log4j.Logger;

import com.netease.automate.exception.AutomateException;
import com.netease.automate.meta.Global;
import com.netease.automate.utils.Utils;

/**
 * Process holder for slave managed processes.
 *
 * @author jiaozhihui@corp.netease.com
 */
public class ProcessHolder {
    private static Logger logger = Logger.getLogger(ProcessHolder.class);

    private ExecutorService executorService = null;
    private String launcher;
    private AutoSlave slave;
    private Map<String, ProcessCheckRunnable> processMap = new ConcurrentHashMap<String, ProcessCheckRunnable>();

    class ProcessStartupCallable implements Callable<String> {
        private String processName;
        private String cmd;

        private String pid = null;

        public ProcessStartupCallable(String processName, String launchScript) {
            this.processName = processName;
            String scriptDir = launchScript.substring(0, launchScript.lastIndexOf("/"));
            String processCmd = launchScript.substring(launchScript.lastIndexOf("/") + 1);

            this.cmd = Utils.constructString("cd ", scriptDir, " && ", launcher, " ./", processCmd, " ./", processName,
                    ".log");
        }

        @Override
        public String call() throws Exception {
            logger.info("process " + processName + " starting...");
            pid = Utils.executeOsCmdWithResult(cmd);
            logger.info("process " + processName + " started, PID = " + pid);

            return pid;
        }

    }

    class ProcessCheckRunnable implements Runnable {
        private String projectName;
        private String processName;
        private String launchScript;

        private volatile boolean stopped;
        private String pid = null;

        public ProcessCheckRunnable(String projectName, String processName, String launchScript, String pid) {
            this.projectName = projectName;
            this.processName = processName;
            this.launchScript = launchScript;
            this.pid = pid;
        }

        @Override
        public void run() {
            processMap.put(launchScript, this);

            // check process status, reboot if process shut down(exceptional)
            String checkCmd = getCheckCmd(pid);
            while (true) {
                if (stopped) {
                    break;
                }

                String count = Utils.executeOsCmdWithResult(checkCmd);
                if (!stopped && Integer.valueOf(count) == 0) {
                    logger.error("process " + processName + " quit abnormally");

                    stopped = true;
                    // just stop the process, wait master command to relaunch
                    instance.stopProcess(projectName, processName, launchScript);
                    break;
                }

                try {
                    Thread.sleep(Global.DEFAULT_CHECK_INTERNAL * 1000);
                } catch (InterruptedException e) {
                    // do nothing
                }
            }
        }

        public String stop() {
            if (!stopped) {
                String shellCmd = Utils.constructString("kill -9 ", pid);
                Utils.executeOsCmd(shellCmd);

                stopped = true;
                Thread.currentThread().interrupt();
            }

            logger.info("process " + processName + " stopped");

            return pid;
        }
    }

    private static ProcessHolder instance;

    public static ProcessHolder getInstance(String launcher, AutoSlave slave) {
        if (instance == null) {
            instance = new ProcessHolder(launcher, slave);
        }

        return instance;
    }

    private ProcessHolder(String launcher, AutoSlave slave) {
        this.launcher = launcher;
        this.slave = slave;

        executorService = new ThreadPoolExecutor(Runtime.getRuntime().availableProcessors(), 100, 60, TimeUnit.SECONDS,
                new LinkedBlockingQueue<Runnable>());
    }

    private String getCheckCmd(String pid) {
        return Utils.constructString("ps -p ", pid, " | grep ", pid, " | wc -l");
    }

    public void addProcess(String projectName, String processName, String launchScript) {
        Future<String> future = executorService.submit(new ProcessStartupCallable(processName, launchScript));
        String pid = null;
        try {
            pid = future.get();
        } catch (InterruptedException e) {
            throw new AutomateException(e);
        } catch (ExecutionException e) {
            throw new AutomateException(e);
        }

        try {
            Thread.sleep(Global.DEFAULT_WAIT_TIME * 1000);
        } catch (InterruptedException e) {
            // do nothing
        }

        executorService.execute(new ProcessCheckRunnable(projectName, processName, launchScript, pid));

        slave.addTargetPid(pid, projectName, processName, launchScript);
    }

    public void addLiveProcess(String projectName, String processName, String launchScript, String pid) {
        executorService.execute(new ProcessCheckRunnable(projectName, processName, launchScript, pid));
    }

    public void stopProcess(String projectName, String pkgName, String launchScript) {
        ProcessCheckRunnable processWrapper = processMap.get(launchScript);
        if (processWrapper != null) {
            String pid = processWrapper.stop();
            try {
                Thread.sleep(Global.DEFAULT_WAIT_TIME * 1000);
            } catch (InterruptedException e) {
                // do nothing
            }

            slave.deleteTargetPid(pid, projectName, pkgName);
        }

    }
}

redpajama_set_name: RedPajamaGithub


text:
@implementation NSNumber(KiwiAdditions)

#pragma mark - Creating Numbers

+ (id)numberWithBytes:(const void *)bytes objCType:(const char *)anObjCType {
    // Yeah, this is ugly.
    if (KWObjCTypeEqualToObjCType(anObjCType, @encode(BOOL)))
        return [self numberWithBoolBytes:bytes];
    else if (KWObjCTypeEqualToObjCType(anObjCType, @encode(bool)))
        return [self numberWithStdBoolBytes:bytes];
    else if (KWObjCTypeEqualToObjCType(anObjCType, @encode(char)))
        return [self numberWithCharBytes:bytes];
    else if (KWObjCTypeEqualToObjCType(anObjCType, @encode(double)))
        return [self numberWithDoubleBytes:bytes];
    else if (KWObjCTypeEqualToObjCType(anObjCType, @encode(float)))
        return [self numberWithFloatBytes:bytes];
    else if (KWObjCTypeEqualToObjCType(anObjCType, @encode(int)))
        return [self numberWithIntBytes:bytes];
    else if (KWObjCTypeEqualToObjCType(anObjCType, @encode(NSInteger)))
        return [self numberWithIntegerBytes:bytes];
    else if (KWObjCTypeEqualToObjCType(anObjCType, @encode(long)))
        return [self numberWithLongBytes:bytes];
    else if (KWObjCTypeEqualToObjCType(anObjCType, @encode(long long)))
        return [self numberWithLongLongBytes:bytes];
    else if (KWObjCTypeEqualToObjCType(anObjCType, @encode(short)))
        return [self numberWithShortBytes:bytes];
    else if (KWObjCTypeEqualToObjCType(anObjCType, @encode(unsigned char)))
        return [self numberWithUnsignedCharBytes:bytes];
    else if (KWObjCTypeEqualToObjCType(anObjCType, @encode(unsigned int)))
        return [self numberWithUnsignedIntBytes:bytes];
    else if (KWObjCTypeEqualToObjCType(anObjCType, @encode(NSUInteger)))
        return [self numberWithUnsignedIntegerBytes:bytes];
    else if (KWObjCTypeEqualToObjCType(anObjCType, @encode(unsigned long)))
        return [self numberWithUnsignedLongBytes:bytes];
    else if (KWObjCTypeEqualToObjCType(anObjCType, @encode(unsigned long long)))
        return [self numberWithUnsignedLongLongBytes:bytes];
    else if (KWObjCTypeEqualToObjCType(anObjCType, @encode(unsigned short)))
        return [self numberWithUnsignedShortBytes:bytes];
    else
        return nil;
}

+ (id)numberWithBoolBytes:(const void *)bytes {
    return @(*(const BOOL *)bytes);
}

+ (id)numberWithStdBoolBytes:(const void *)bytes {
    return @(*(const bool *)bytes);
}

+ (id)numberWithCharBytes:(const void *)bytes {
    return @(*(const char *)bytes);
}

+ (id)numberWithDoubleBytes:(const void *)bytes {
    return @(*(const double *)bytes);
}

+ (id)numberWithFloatBytes:(const void *)bytes {
    return @(*(const float *)bytes);
}

+ (id)numberWithIntBytes:(const void *)bytes {
    return @(*(const int *)bytes);
}

+ (id)numberWithIntegerBytes:(const void *)bytes {
    return @(*(const NSInteger *)bytes);
}

+ (id)numberWithLongBytes:(const void *)bytes {
    return @(*(const long *)bytes);
}

+ (id)numberWithLongLongBytes:(const void *)bytes {
    return @(*(const long long *)bytes);
}

+ (id)numberWithShortBytes:(const void *)bytes {
    return @(*(const short *)bytes);
}

+ (id)numberWithUnsignedCharBytes:(const void *)bytes {
    return @(*(const unsigned char *)bytes);
}

+ (id)numberWithUnsignedIntBytes:(const void *)bytes {
    return @(*(const unsigned int *)bytes);
}

+ (id)numberWithUnsignedIntegerBytes:(const void *)bytes {
    return @(*(const NSUInteger *)bytes);
}

+ (id)numberWithUnsignedLongBytes:(const void *)bytes {
    return @(*(const unsigned long *)bytes);
}

+ (id)numberWithUnsignedLongLongBytes:(const void *)bytes {
    return @(*(const unsigned long long *)bytes);
}

+ (id)numberWithUnsignedShortBytes:(const void *)bytes {
    return @(*(const unsigned short *)bytes);
}

@end


text:
package java.lang;

/**
 * Encapsulates an action for later execution. [Sun
 * docs]
 *
 *

 * This interface is provided only for JRE compatibility. GWT does not support
 * multithreading.
 *

 */
public interface Runnable {
  void run();
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project-private xmlns="http://www.netbeans.org/ns/project-private/1">
    <editor-bookmarks xmlns="http://www.netbeans.org/ns/editor-bookmarks/2" lastBookmarkId="0"/>
    <open-files xmlns="http://www.netbeans.org/ns/projectui-open-files/2">
        <group>
            <file>file:/C:/Documents%20and%20Settings/TUI/My%20Documents/NetBeansProjects/CalcGCM/src/CalcGCM.java</file>
        </group>
    </open-files>
</project-private>


text:
package org.lnu.is.resource.enrolment.status;

import java.text.MessageFormat;

import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;

import org.lnu.is.annotation.CrudableResource;
import org.lnu.is.resource.ApiResource;

/**
 * Enrolment Status Resource.
 * @author ivanursul
 *
 */
@CrudableResource
public class EnrolmentStatusResource extends ApiResource {

	@NotNull
	@Min(value = 1, message = "Minimal value is 1")
	private Long enrolmentId;

	@NotNull
	@Min(value = 1, message = "Minimal value is 1")
	private Long specOfferWaveId;

	@NotNull
	@Min(value = 1, message = "Minimal value is 1")
	private Long enrolmentStatusTypeId;

	@NotNull
	private Integer isState;

	@NotNull
	private Integer isContract;

	@Override
	public String getUri() {
		return MessageFormat.format("/enrolments/{0}/statuses/{1}", enrolmentId, getId());
	}

	@Override
	public String getRootUri() {
		return MessageFormat.format("/enrolments/{0}/statuses", enrolmentId);
	}

	public Integer getIsState() {
	    return isState;
	}

	public void setIsState(final Integer isState) {
	    this.isState = isState;
	}

	public Integer getIsContract() {
	    return isContract;
	}

	public void setIsContract(final Integer isContract) {
	    this.isContract = isContract;
	}

	public Long getEnrolmentId() {
		return enrolmentId;
	}

	public void setEnrolmentId(final Long enrolmentId) {
		this.enrolmentId = enrolmentId;
	}

	public Long getSpecOfferWaveId() {
		return specOfferWaveId;
	}

	public void setSpecOfferWaveId(final Long specOfferWaveId) {
		this.specOfferWaveId = specOfferWaveId;
	}

	public Long getEnrolmentStatusTypeId() {
		return enrolmentStatusTypeId;
	}

	public void setEnrolmentStatusTypeId(final Long enrolmentStatusTypeId) {
		this.enrolmentStatusTypeId = enrolmentStatusTypeId;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = super.hashCode();
		result = prime * result
				+ ((enrolmentId == null) ? 0 : enrolmentId.hashCode());
		result = prime
				* result
				+ ((enrolmentStatusTypeId == null) ? 0 : enrolmentStatusTypeId
						.hashCode());
		result = prime * result
				+ ((specOfferWaveId == null) ? 0 : specOfferWaveId.hashCode());
		result = prime * result
			+ ((isContract == null) ? 0 : isContract.hashCode());
		result = prime * result
			+ ((isState == null) ? 0 : isState.hashCode());
		return result;
	}

	@Override
	public boolean equals(final Object obj) {
		if (this == obj) {
			return true;
		}
		if (!super.equals(obj)) {
			return false;
		}
		if (getClass() != obj.getClass()) {
			return false;
		}
		EnrolmentStatusResource other = (EnrolmentStatusResource) obj;
		if (enrolmentId == null) {
			if (other.enrolmentId != null) {
				return false;
			}
		} else if (!enrolmentId.equals(other.enrolmentId)) {
			return false;
		}
		if (enrolmentStatusTypeId == null) {
			if (other.enrolmentStatusTypeId != null) {
				return false;
			}
		} else if (!enrolmentStatusTypeId.equals(other.enrolmentStatusTypeId)) {
			return false;
		}
		if (specOfferWaveId == null) {
			if (other.specOfferWaveId != null) {
				return false;
			}
		} else if (!specOfferWaveId.equals(other.specOfferWaveId)) {
			return false;
		}
		if (isState == null) {
			if (other.isState != null) {
				return false;
			}
		} else if (!isState.equals(other.isState)) {
			return false;
		}
		if (isContract == null) {
			if (other.isContract != null) {
				return false;
			}
		} else if (!isContract.equals(other.isContract)) {
			return false;
		}
		return true;
	}

	@Override
	public String toString() {
	    return "EnrolmentStatusResource [enrolmentId=" + enrolmentId
		    + ", specOfferWaveId=" + specOfferWaveId
		    + ", enrolmentStatusTypeId=" + enrolmentStatusTypeId
		    + ", isState=" + isState + ", isContract=" + isContract
		    + "]";
	}

}


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<event category="DRAW" id="0">
  <actions>
    <action id="603" library="1">
      <!--action name: Code-->
      <kind>CODE</kind>
      <allowRelative>false</allowRelative>
      <question>false</question>
      <canApplyTo>true</canApplyTo>
      <actionType>CODE</actionType>
      <functionName/>
      <relative>false</relative>
      <not>false</not>
      <appliesTo>.self</appliesTo>
      <arguments>
        <argument kind="STRING">draw_sprite(sprite_index,-1,x,y)
draw_set_color(c_white)
draw_set_font(fBasic)
if ready
{   temp = 0
    repeat(ds_list_size(colour))
    {
        draw_text(40,5+temp*15,string(ds_list_find_value(colour,temp))+"x"+string(count[temp]))
        temp += 1
    }
}
</argument>
      </arguments>
    </action>
  </actions>
</event>


text:
<?php
/**
 * Name :  Post.php

 * Desc :

 *
 * PHP version 5.5
 *
 * @category Blog\Model
 * @package  Blog\Model
 * @author   Susana Moreno <susana.ml82@gmail.com>
 * @license  Apache 2 License http://www.apache.org/licenses/LICENSE-2.0.html
 * @version  GIT: $Id$
 * @link     http://www.susosworld.com
 * @since    File available since Release 0.1.0
 */

namespace Blog\Model;

/**
 * Class Post
 *
 * @category   Blog\Model
 * @package    Blog\Model
 * @subpackage Post
 * @author     Susana Moreno <susana.ml82@gmail.com>
 * @license    Apache 2 License http://www.apache.org/licenses/LICENSE-2.0.html
 * @version    Release: <0.1.0>
 * @link       http://www.susosworld.com
 * @since      Class available since Release 0.1.0
 */
class Post implements PostInterface
{
    /**
     * Identifier
     *
     * @access protected
     * @var    integer
     */
    protected $id;

    /**
     * Title
     *
     * @access protected
     * @var    string
     */
    protected $title;

    /**
     * Text
     *
     * @access protected
     * @var    string
     */
    protected $text;

    /**
     * Getter Id
     *
     * @access public
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Setter Identifier
     *
     * @param integer $id identifier
     *
     * @access public
     * @return void
     */
    public function setId($id)
    {
        $this->id = $id;
    }

    /**
     * Getter Title
     *
     * @access public
     * @return string
     */
    public function getTitle()
    {
        return $this->title;
    }

    /**
     * Setter Title
     *
     * @param string $title title
     *
     * @access public
     * @return void
     */
    public function setTitle($title)
    {
        $this->title = $title;
    }

    /**
     * Getter Text
     *
     * @access public
     * @return string
     */
    public function getText()
    {
        return $this->text;
    }

    /**
     * Setter Text
     *
     * @param string $text text
     *
     * @access public
     * @return void
     */
    public function setText($text)
    {
        $this->text = $text;
    }
}


text:
package com.google.example.games.tanc;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

/**
 * Fragment for the gameplay portion of the game. It shows the keypad
 * where the user can request their score.
 *
 * @author Bruno Oliveira (Google)
 *
 */
public class GameplayFragment extends Fragment implements OnClickListener {
    int mRequestedScore = 5000;

    static int[] MY_BUTTONS = {
        R.id.digit_button_0, R.id.digit_button_1, R.id.digit_button_2,
        R.id.digit_button_3, R.id.digit_button_4, R.id.digit_button_5,
        R.id.digit_button_6, R.id.digit_button_7, R.id.digit_button_8,
        R.id.digit_button_9, R.id.digit_button_clear, R.id.ok_score_button
    };

    public interface Listener {
        public void onEnteredScore(int score);
    }

    Listener mListener = null;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_gameplay, container, false);
        for (int i : MY_BUTTONS) {
            ((Button) v.findViewById(i)).setOnClickListener(this);
        }
        return v;
    }

    public void setListener(Listener l) {
        mListener = l;
    }

    @Override
    public void onStart() {
        super.onStart();
        updateUi();
    }

    void updateUi() {
        if (getActivity() == null) return;
        TextView scoreInput = ((TextView) getActivity().findViewById(R.id.score_input));
        if (scoreInput != null) scoreInput.setText(String.format("%04d", mRequestedScore));
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
        case R.id.digit_button_clear:
            mRequestedScore = 0;
            updateUi();
            break;
        case R.id.digit_button_0:
        case R.id.digit_button_1:
        case R.id.digit_button_2:
        case R.id.digit_button_3:
        case R.id.digit_button_4:
        case R.id.digit_button_5:
        case R.id.digit_button_6:
        case R.id.digit_button_7:
        case R.id.digit_button_8:
        case R.id.digit_button_9:
            int x = Integer.parseInt(((Button)view).getText().toString().trim());
            mRequestedScore = (mRequestedScore * 10 + x) % 10000;
            updateUi();
            break;
        case R.id.ok_score_button:
            mListener.onEnteredScore(mRequestedScore);
            break;
        }
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<title>Box2D: b2ContactRegister Struct Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="doxygen.css" rel="stylesheet" type="text/css"/>

Main Page

Classes

Files

Class List

Class Hierarchy

Class Members

b2ContactRegister Struct Reference

#include <b2Contact.h>

List of all members.

Public Attributes

b2ContactCreateFcn * 	createFcn

b2ContactDestroyFcn * 	destroyFcn

bool 	primary

Member Data Documentation

          b2ContactCreateFcn* b2ContactRegister::createFcn

          b2ContactDestroyFcn* b2ContactRegister::destroyFcn

          bool b2ContactRegister::primary

The documentation for this struct was generated from the following file:

Box2D/Box2D/Dynamics/Contacts/b2Contact.h

<address style="text-align: right;">Generated on Sat Apr 3 18:18:09 2010 for Box2D by

 1.6.3 </address>


text:
from numpy.testing import assert_
from statsmodels.compatnp.collections import Counter

def test_counter():
    #just check a basic example
    c = Counter('gallahad')
    res = [('a', 3), ('d', 1), ('g', 1), ('h', 1), ('l', 2)]
    msg = 'gallahad fails\n'+repr(sorted(c.items()))
    assert_(sorted(c.items()) == res, msg=msg)


text: coffee index.coffee "$@"


text:
package org.apache.hadoop.yarn.server.resourcemanager.scheduler.policy;

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

import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

import org.apache.hadoop.yarn.api.records.Priority;
import org.junit.Assert;
import org.junit.Test;

public
class TestFifoOrderingPolicy {

  @Test
  public void testFifoOrderingPolicy() {
    FifoOrderingPolicy<MockSchedulableEntity> policy =
      new FifoOrderingPolicy<MockSchedulableEntity>();
    MockSchedulableEntity r1 = new MockSchedulableEntity();
    MockSchedulableEntity r2 = new MockSchedulableEntity();

    assertEquals("The comparator should return 0 because the entities are created with " +
            "the same values.", 0,
        policy.getComparator().compare(r1, r2));

    r1.setSerial(1);
    assertEquals("The lhs entity has a larger serial, the comparator return " +
            "value should be 1.", 1, policy.getComparator().compare(r1, r2));

    r2.setSerial(2);
    Assert.assertEquals("The rhs entity has a larger serial, the comparator return " +
        "value should be -1.", -1, policy.getComparator().compare(r1, r2));
  }

  @Test
  public void testIterators() {
    OrderingPolicy<MockSchedulableEntity> schedOrder =
     new FifoOrderingPolicy<MockSchedulableEntity>();

    MockSchedulableEntity msp1 = new MockSchedulableEntity();
    MockSchedulableEntity msp2 = new MockSchedulableEntity();
    MockSchedulableEntity msp3 = new MockSchedulableEntity();

    msp1.setSerial(3);
    msp2.setSerial(2);
    msp3.setSerial(1);

    schedOrder.addSchedulableEntity(msp1);
    schedOrder.addSchedulableEntity(msp2);
    schedOrder.addSchedulableEntity(msp3);

    //Assignment, oldest to youngest
    checkSerials(Arrays.asList(1L, 2L, 3L), schedOrder.getAssignmentIterator(
        IteratorSelector.EMPTY_ITERATOR_SELECTOR));

    //Preemption, youngest to oldest
    checkSerials(Arrays.asList(3L, 2L, 1L), schedOrder.getPreemptionIterator());
  }

  public void checkSerials(List<Long> expectedSerials, Iterator<MockSchedulableEntity>
      actualSerialIterator) {
    for (long expectedSerial : expectedSerials) {
      assertEquals(expectedSerial, actualSerialIterator.next().getSerial());
    }
  }

  @Test
  public void testFifoOrderingPolicyAlongWithPriority() {
    FifoOrderingPolicy<MockSchedulableEntity> policy =
        new FifoOrderingPolicy<MockSchedulableEntity>();
    MockSchedulableEntity r1 = new MockSchedulableEntity();
    MockSchedulableEntity r2 = new MockSchedulableEntity();

    assertEquals("Both r1 and r2 priority is null, the comparator should return 0.", 0,
        policy.getComparator().compare(r1, r2));

    Priority p2 = Priority.newInstance(0);

    // r1 is null and r2 is not null
    r2.setApplicationPriority(p2);
    Assert.assertTrue("The priority of r1 is null, the priority of r2 is not null, " +
            "the comparator should return a negative value.",
        policy.getComparator().compare(r1, r2) < 0);

    Priority p1 = Priority.newInstance(1);

    // r1 is not null and r2 is null
    r1.setApplicationPriority(p1);
    r2.setApplicationPriority(null);
    assertTrue("The priority of r1 is not null, the priority of r2 is null," +
            "the comparator should return a positive value.",
        policy.getComparator().compare(r1, r2) > 0);

    // r1 is not null and r2 is not null
    r1.setApplicationPriority(p1);
    r2.setApplicationPriority(p2);
    Assert.assertTrue("Both priorities are not null, the r1 has higher priority, " +
            "the result should be a negative value.",
        policy.getComparator().compare(r1, r2) < 0);
  }

  @Test
  public void testOrderingUsingAppSubmitTime() {
    FifoOrderingPolicy<MockSchedulableEntity> policy =
        new FifoOrderingPolicy<MockSchedulableEntity>();
    MockSchedulableEntity r1 = new MockSchedulableEntity();
    MockSchedulableEntity r2 = new MockSchedulableEntity();

    // R1, R2 has been started at same time
    assertEquals(r1.getStartTime(), r2.getStartTime());

    // No changes, equal
    assertEquals("The submit times are the same, the comparator should return 0.", 0,
        policy.getComparator().compare(r1, r2));

    // R2 has been started after R1
    r1.setStartTime(5);
    r2.setStartTime(10);
    Assert.assertTrue("r2 was started after r1, " +
            "the comparator should return a negative value.",
        policy.getComparator().compare(r1, r2) < 0);

    // R1 has been started after R2
    r1.setStartTime(10);
    r2.setStartTime(5);
    Assert.assertTrue("r2 was started before r1, the comparator should return a positive value.",
        policy.getComparator().compare(r1, r2) > 0);
  }
}


text:
const req = require.context('../../icons/svg', false, /\.svg$/)
const requireAll = requireContext => requireContext.keys()

const re = /\.\/(.*)\.svg/

const icons = requireAll(req).map(i => {
  return i.match(re)[1]
})

export default icons


text:
using System.Text;
using Voodoo.CodeGeneration.Helpers;
using Voodoo.CodeGeneration.Models;
using Voodoo.CodeGeneration.Models.Reflection;
using Voodoo.CodeGeneration.Models.VisualStudio;

namespace Voodoo.CodeGeneration.Templates.Logic.OperationLevel.Extras
{

    public class ListRequestFile : TypedCodeFile
    {

        public ListRequestFile(ProjectFacade project, TypeFacade type)
            : base(project, type)
        {

            Name = $"{Name}ListRequest";

            PageSpecificUsingStatements.Add("System");
            PageSpecificUsingStatements.Add("System.Collections.Generic");
            PageSpecificUsingStatements.Add("System.ComponentModel.DataAnnotations");
            PageSpecificUsingStatements.Add("System.Linq");
            PageSpecificUsingStatements.Add("Voodoo.Messages");
        }

        public override string GetFileContents()
        {

            var output = new StringBuilder();
            foreach (var item in UsingStatements)
            {
                output.AppendLine($"using {item};");
            }
            output.AppendLine($"namespace {Namespace}");
            output.AppendLine("{");
            output.AppendLine($"public class {Name} : PagedRequest");
            output.AppendLine("{");

            if (Type.HasActiveFlag)
            {
                output.AppendLine("public bool IncludeInactive {get;set;}");
            }
            var sortMember = "null";
            if (Type.HasName)
                sortMember = "Name";
            else if (Type.HasId)
                sortMember = "Id";
            output.AppendLine($"public override string DefaultSortMember => \"{sortMember}\";");

            output.AppendLine("}");
            output.AppendLine("}");

            return CodeFormatter.Format(output.ToString());

        }

        public override string GetFolder()
        {
            return $@"Operations\{ExtrasFolder}";
        }
    }
}


text:
'use strict';

//Answers service used to communicate Answers REST endpoints
angular.module('answers').factory('Answers', ['$resource',
	function($resource) {
		return $resource('answers/:answerId', { answerId: '@_id'
		}, {
			update: {
				method: 'PUT'
			}
		});
	}
]);


text:
using System;
using System.Reflection;

namespace MySubModule.Web.Areas.HelpPage.ModelDescriptions
{
    public interface IModelDocumentationProvider
    {
        string GetDocumentation(MemberInfo member);

        string GetDocumentation(Type type);
    }
}


text:
package gnu.javax.net.ssl.provider;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.InputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.StringReader;
import java.io.StringWriter;

import java.math.BigInteger;

import java.security.PublicKey;
import java.security.interfaces.RSAPublicKey;

import javax.crypto.interfaces.DHPublicKey;
import javax.crypto.spec.DHParameterSpec;

import javax.net.ssl.SSLProtocolException;

import gnu.javax.crypto.key.dh.GnuDHPublicKey;
import gnu.javax.crypto.key.srp6.SRPPublicKey;

class ServerKeyExchange implements Handshake.Body
{

  // Fields.
  // -------------------------------------------------------------------------

  private PublicKey publicKey;
  private Signature signature;
  private byte[] srpSalt;

  // Constructor.
  // -------------------------------------------------------------------------

  ServerKeyExchange(PublicKey publicKey, Signature signature)
  {
    this(publicKey, signature, null);
  }

  ServerKeyExchange(PublicKey publicKey, Signature signature, byte[] srpSalt)
  {
    this.publicKey = publicKey;
    this.signature = signature;
    this.srpSalt = srpSalt;
  }

  // Class methods.
  // -------------------------------------------------------------------------

  static ServerKeyExchange read(InputStream in, CipherSuite suite,
                                PublicKey serverKey)
    throws IOException
  {
    DataInputStream din = new DataInputStream(in);
    PublicKey key = null;
    byte[] salt = null;
    String kex = suite.getKeyExchange();
    if (kex.equals("DHE"))
      {
        BigInteger p, g, y;
        byte[] buf = new byte[din.readUnsignedShort()];
        din.readFully(buf);
        p = new BigInteger(1, buf);
        buf = new byte[din.readUnsignedShort()];
        din.readFully(buf);
        g = new BigInteger(1, buf);
        buf = new byte[din.readUnsignedShort()];
        din.readFully(buf);
        y = new BigInteger(1, buf);
        key = new GnuDHPublicKey(null, p, g, y);
      }
    else if (kex.equals("RSA"))
      {
        BigInteger n, e;
        byte[] buf = new byte[din.readUnsignedShort()];
        din.readFully(buf);
        n = new BigInteger(1, buf);
        buf = new byte[din.readUnsignedShort()];
        din.readFully(buf);
        e = new BigInteger(1, buf);
        key = new JessieRSAPublicKey(n, e);
      }
    else if (kex.equals("SRP"))
      {
        BigInteger N, g, B;
        byte[] buf = new byte[din.readUnsignedShort()];
        din.readFully(buf);
        N = new BigInteger(1, buf);
        buf = new byte[din.readUnsignedShort()];
        din.readFully(buf);
        g = new BigInteger(1, buf);
        salt = new byte[din.readUnsignedByte()];
        din.readFully(salt);
        buf = new byte[din.readUnsignedShort()];
        din.readFully(buf);
        B = new BigInteger(1, buf);
        try
          {
            key = new SRPPublicKey(N, g, B);
          }
        catch (IllegalArgumentException iae)
          {
            throw new SSLProtocolException(iae.getMessage());
          }
      }
    else
      {
        throw new SSLProtocolException("invalid kex algorithm");
      }

    Signature sig = null;
    if (!suite.getSignature().equals("anon"))
      {
        sig = Signature.read(in, suite, serverKey);
      }
    return new ServerKeyExchange(key, sig, salt);
  }

  // Instance methods.
  // -------------------------------------------------------------------------

  public void write(OutputStream out) throws IOException
  {
    write(out, ProtocolVersion.TLS_1);
  }

  public void write(OutputStream out, ProtocolVersion version)
    throws IOException
  {
    if (publicKey instanceof DHPublicKey)
      {
        writeBigint(out, ((DHPublicKey) publicKey).getParams().getP());
        writeBigint(out, ((DHPublicKey) publicKey).getParams().getG());
        writeBigint(out, ((DHPublicKey) publicKey).getY());
      }
    else if (publicKey instanceof RSAPublicKey)
      {
        writeBigint(out, ((RSAPublicKey) publicKey).getModulus());
        writeBigint(out, ((RSAPublicKey) publicKey).getPublicExponent());
      }
    else if (publicKey instanceof SRPPublicKey)
      {
        writeBigint(out, ((SRPPublicKey) publicKey).getN());
        writeBigint(out, ((SRPPublicKey) publicKey).getG());
        out.write(srpSalt.length);
        out.write(srpSalt);
        writeBigint(out, ((SRPPublicKey) publicKey).getY());
      }
    if (signature != null)
      {
        signature.write(out, version);
      }
  }

  PublicKey getPublicKey()
  {
    return publicKey;
  }

  Signature getSignature()
  {
    return signature;
  }

  byte[] getSRPSalt()
  {
    return srpSalt;
  }

  public String toString()
  {
    StringWriter str = new StringWriter();
    PrintWriter out = new PrintWriter(str);
    out.println("struct {");
    out.println("  publicKey = struct {");
    if (publicKey instanceof DHPublicKey)
      {
        out.println("    p = " +
                   ((DHPublicKey) publicKey).getParams().getP().toString(16) +
                   ";");
        out.println("    g = " +
                   ((DHPublicKey) publicKey).getParams().getG().toString(16) +
                   ";");
        out.println("    y = " + ((DHPublicKey) publicKey).getY().toString(16) +
                   ";");
        out.println("  } DHPublicKey;");
      }
    else if (publicKey instanceof RSAPublicKey)
      {
        out.println("    modulus = " +
                   ((RSAPublicKey) publicKey).getModulus().toString(16) +
                   ";");
        out.println("    exponent = " +
                   ((RSAPublicKey) publicKey).getPublicExponent().toString(16) +
                   ";");
        out.println("  } RSAPublicKey;");
      }
    else if (publicKey instanceof SRPPublicKey)
      {
        out.println("    N = "+((SRPPublicKey) publicKey).getN().toString(16)+";");
        out.println("    g = "+((SRPPublicKey) publicKey).getG().toString(16)+";");
        out.println("    salt = " + Util.toHexString(srpSalt, ':') + ";");
        out.println("    B = "+((SRPPublicKey) publicKey).getY().toString(16)+";");
        out.println("  } SRPPublicKey;");
      }
    if (signature != null)
      {
        out.println("  signature =");
        BufferedReader r = new BufferedReader(new StringReader(signature.toString()));
        String s;
        try
          {
            while ((s = r.readLine()) != null)
              {
                out.print("    ");
                out.println(s);
              }
          }
        catch (IOException ignored)
          {
          }
      }
    out.println("} ServerKeyExchange;");
    return str.toString();
  }

  private void writeBigint(OutputStream out, BigInteger bigint)
    throws IOException
  {
    byte[] b = bigint.toByteArray();
    if (b[0] == 0x00)
      {
        out.write((b.length - 1) >>> 8 & 0xFF);
        out.write((b.length - 1) & 0xFF);
        out.write(b, 1, b.length - 1);
      }
    else
      {
        out.write(b.length >>> 8 & 0xFF);
        out.write(b.length & 0xFF);
        out.write(b);
      }
  }
}


text:
<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
        <item name="android:spinnerItemStyle">@style/spinnerItemStyle</item>
        <item name="android:spinnerDropDownItemStyle">@style/spinnerDropDownItemStyle</item>
        <item name="android:windowBackground">@color/colorLightGray</item>
    </style>

    <style name="AppTheme.NoActionBar">
        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>
    </style>

    <style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />

    <style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />

    <style name="spinnerItemStyle">
        <item name="android:gravity">center</item>
    </style>

    <style name="spinnerDropDownItemStyle">
        <item name="android:gravity">center</item>
    </style>

    <style name="SplashTheme" parent="Theme.AppCompat.NoActionBar">
        <item name="android:windowBackground">@drawable/taap_app_splash</item>
    </style>

</resources>


text:
**Due back on Saturday, March 25 before 11:59 pm.**

### Goal

You are asked to create a commandline-based _interactive_ program that allows users to add two types of shapes: triangles and circles.  The program also allows the user the print the list of stored shapes.  Furthermore, it allows the user to modify the stored shapes.

#### Sample run of this program

The following run illustrates the interactions supported by this program.

~~~bash
./lab7
Choose a shape to add
	(a) for triangle
	(b) for circle
	(p) to print the shapes
	(0-9) to modify a shape
	(q) to exit
: a
== You selected a triangle. ==
Enter position: 0 0
Enter width and height: 1 2
Choose a shape to add
	(a) for triangle
	(b) for circle
	(p) to print the shapes
	(0-9) to modify a shape
	(q) to exit
: b
== You selected a circle. ==
Enter position: 10 2
Enter radius: 1
Choose a shape to add
	(a) for triangle
	(b) for circle
	(p) to print the shapes
	(0-9) to modify a shape
	(q) to exit
: a
== You selected a triangle. ==
Enter position: 3 4
Enter width and height: 1 22
Choose a shape to add
	(a) for triangle
	(b) for circle
	(p) to print the shapes
	(0-9) to modify a shape
	(q) to exit
: p
[0] Triangle
	location: (0, 0)
	width and height: (1, 2)
[1] Radius
	location: (10, 2)
	radius: (1)
[2] Triangle
	location: (3, 4)
	width and height: (1, 22)
Choose a shape to add
	(a) for triangle
	(b) for circle
	(p) to print the shapes
	(0-9) to modify a shape
	(q) to exit
: 1
Enter position: 11 3
Enter radius: 1000
Choose a shape to add
	(a) for triangle
	(b) for circle
	(p) to print the shapes
	(0-9) to modify a shape
	(q) to exit
: p
[0] Triangle
	location: (0, 0)
	width and height: (1, 2)
[1] Radius
	location: (11, 3)
	radius: (1000)
[2] Triangle
	location: (3, 4)
	width and height: (1, 22)
Choose a shape to add
	(a) for triangle
	(b) for circle
	(p) to print the shapes
	(0-9) to modify a shape
	(q) to exit
: q
~~~

#### Some specifics

- If user enters `a`, the programs prompts the user for information about a triangle (position x, position y, width, and height).
- If user enters `b`, the programs prompts the user for information about a circle (position x, position y, radius).
- If user enters `p`, the program prints the shapes (their types, position x, position y, and other info, e.g., width and height in case of triangles).
- The program can store up to 10 shapes.
- If user presses `0-9` the shape stored at that index allows user to re-enter the values (e.g., position x, position y, and radious for circle).

### Source Code

Please complete the `Tri` and `Cir` classes in the code below:

#### main

~~~cpp
#include <iostream>
using namespace std;

class Point
{
  public:
  int x, y;

  Point() {}
  Point(int x, int y) { this->x = x; this->y = y; }

  friend ostream& operator<<(ostream& os, const Point& pt) {
    os << "(" << pt.x << ", " << pt.y << ")";
    return os;
  }
};

class Shape
{
  // FEEL FREE TO CHANGE THE THIS CLASS
  // AS LONG AS YOU DON'T HAVE TO CHANGE THE
  // CONTENTS OF MAIN() AND
  // PRINT_SHAPES() FUNCTIONS

  protected:
  Point _location;

  public:
  Shape() {}
  Shape(const Point& location) : _location(location) {}
  ~Shape() {}

  void draw() {
    cout << "location: " << _location << endl;
  }

  void get_info_from_user() {
    cout << "Enter position: ";
    cin >> _location.x >> _location.y;
  }
};

// YOU NEED TO COMPLETE THIS CLASS
class Tri
{
  protected:
  int _width, _height;

  public:
  // TODO ...
};

// YOU NEED TO COMPLETE THIS CLASS
class Cir
{
  protected:
  int _radius;

  public:
  // TODO ...
};

/////////////////////////////////////////////////
//
// DO NOT CHANGE CODE BELOW THIS LINE
//
/////////////////////////////////////////////////
#define MAX_SHAPES 10

void print_shapes(Shape** shapes, int n)
{
  for (int i=0; i<n; ++i) {
    cout << "[" << i << "] "; shapes[i]->draw();
  }
}

int main()
{
  Shape* shapes[MAX_SHAPES];

  int n = 0;
  char shape_choice;
  do {
    cout << "Choose a shape to add" << endl;
    cout << "\t(a) for triangle" << endl;
    cout << "\t(b) for circle" << endl;
    cout << "\t(p) to print the shapes" << endl;
    cout << "\t(0-9) to modify a shape" << endl;
    cout << "\t(q) to exit" << endl;
    cout << ": ";
    cin >> shape_choice;

    if (shape_choice == 'q') break;

    switch(shape_choice)
    {
      case '0':
      case '1':
      case '2':
      case '3':
      case '4':
      case '5':
      case '6':
      case '7':
      case '8':
      case '9':
        shapes[((int) shape_choice) - 48]->get_info_from_user();
      break;
      case 'a':
        if (n >=  MAX_SHAPES) {
          cout << "== Cannot add any more shapes ==" << endl;
          continue;
        }
        cout << "== You selected a triangle. ==" << endl;
        shapes[n] = new Tri();
        shapes[n]->get_info_from_user();
        ++n;
      break;
      case 'b':
        if (n >=  MAX_SHAPES) {
          cout << "== Cannot add any more shapes ==" << endl;
          continue;
        }
        cout << "== You selected a circle. ==" << endl;
        shapes[n] = new Cir();
        shapes[n]->get_info_from_user();
        ++n;
      break;
      case 'p':
        print_shapes(shapes, n);
      break;
      case 'q':
      break;
      default:
        cerr << "== Invalid choice ==" << endl;
      break;
    }
  } while (true);

  for (int i=0; i<n; ++i) delete shapes[i];
}
~~~

### Submission

Please submit via Blackboard


text:
"use strict";

describe("token", () => {
  require("./token/makeTokenParser.js");
});


text:
:LastChangedDate: $LastChangedDate$
:LastChangedRevision: $LastChangedRevision$
:LastChangedBy: $LastChangedBy$

Choosing a Reactor and GUI Toolkit Integration
==============================================

Overview
--------

Twisted provides a variety of implementations of the :api:`twisted.internet.reactor <twisted.internet.reactor>` .  The specialized
implementations are suited for different purposes and are
designed to integrate better with particular platforms.

The :ref:`epoll()-based reactor <core-howto-choosing-reactor-epoll>` is Twisted's default on
Linux. Other platforms use :ref:`poll() <core-howto-choosing-reactor-poll>` , or the most
cross-platform reactor, :ref:`select() <core-howto-choosing-reactor-select>` .

Platform-specific reactor implementations exist for:

- :ref:`Poll for Linux <core-howto-choosing-reactor-poll>`
- :ref:`Epoll for Linux 2.6 <core-howto-choosing-reactor-epoll>`
- :ref:`WaitForMultipleObjects (WFMO) for Win32 <core-howto-choosing-reactor-win32_wfmo>`
- :ref:`Input/Output Completion Port (IOCP) for Win32 <core-howto-choosing-reactor-win32_iocp>`
- :ref:`KQueue for FreeBSD and Mac OS X <core-howto-choosing-reactor-kqueue>`
- :ref:`CoreFoundation for Mac OS X <core-howto-choosing-reactor-cfreactor>`

The remaining custom reactor implementations provide support
for integrating with the native event loops of various graphical
toolkits.  This lets your Twisted application use all of the
usual Twisted APIs while still being a graphical application.

Twisted currently integrates with the following graphical
toolkits:

- :ref:`GTK+ 2.0 <core-howto-choosing-reactor-gtk>`
- :ref:`GTK+ 3.0 and GObject Introspection <core-howto-choosing-reactor-gtk3>`
- :ref:`Tkinter <core-howto-choosing-reactor-tkinter>`
- :ref:`wxPython <core-howto-choosing-reactor-wxpython>`
- :ref:`Win32 <core-howto-choosing-reactor-win32_wfmo>`
- :ref:`CoreFoundation <core-howto-choosing-reactor-cfreactor>`
- :ref:`PyUI <core-howto-choosing-reactor-pyui>`

When using applications that are runnable using ``twistd`` , e.g.
TACs or plugins, there is no need to choose a reactor explicitly, since
this can be chosen using ``twistd`` 's -r option.

In all cases, the event loop is started by calling ``reactor.run()`` . In all cases, the event loop
should be stopped with ``reactor.stop()`` .

**IMPORTANT:** installing a reactor should be the first thing
done in the app, since any code that does
``from twisted.internet import reactor`` will automatically
install the default reactor if the code hasn't already installed one.

Reactor Functionality
---------------------

+-----------------------------------------------+--------------+-----+-----+-----+-----------+-----------+------------+-------------+
| \                                             | Status       | TCP | SSL | UDP | Threading | Processes | Scheduling | Platforms   |
+===============================================+==============+=====+=====+=====+===========+===========+============+=============+
| select()                                      | Stable       | Y   | Y   | Y   | Y         | Y         | Y          | Unix, Win32 |
+-----------------------------------------------+--------------+-----+-----+-----+-----------+-----------+------------+-------------+
| poll                                          | Stable       | Y   | Y   | Y   | Y         | Y         | Y          | Unix        |
+-----------------------------------------------+--------------+-----+-----+-----+-----------+-----------+------------+-------------+
| WaitForMultipleObjects (WFMO) for Win32       | Experimental | Y   | Y   | Y   | Y         | Y         | Y          | Win32       |
+-----------------------------------------------+--------------+-----+-----+-----+-----------+-----------+------------+-------------+
| Input/Output Completion Port (IOCP) for Win32 | Experimental | Y   | Y   | Y   | Y         | Y         | Y          | Win32       |
+-----------------------------------------------+--------------+-----+-----+-----+-----------+-----------+------------+-------------+
| CoreFoundation                                | Unmaintained | Y   | Y   | Y   | Y         | Y         | Y          | Mac OS X    |
+-----------------------------------------------+--------------+-----+-----+-----+-----------+-----------+------------+-------------+
| epoll                                         | Stable       | Y   | Y   | Y   | Y         | Y         | Y          | Linux 2.6   |
+-----------------------------------------------+--------------+-----+-----+-----+-----------+-----------+------------+-------------+
| GTK+                                          | Stable       | Y   | Y   | Y   | Y         | Y         | Y          | Unix, Win32 |
+-----------------------------------------------+--------------+-----+-----+-----+-----------+-----------+------------+-------------+
| wx                                            | Experimental | Y   | Y   | Y   | Y         | Y         | Y          | Unix, Win32 |
+-----------------------------------------------+--------------+-----+-----+-----+-----------+-----------+------------+-------------+
| kqueue                                        | Stable       | Y   | Y   | Y   | Y         | Y         | Y          | FreeBSD     |
+-----------------------------------------------+--------------+-----+-----+-----+-----------+-----------+------------+-------------+

General Purpose Reactors
------------------------

Select()-based Reactor
~~~~~~~~~~~~~~~~~~~~~~
.. _core-howto-choosing-reactor-select:

The ``select`` reactor is the default on platforms that don't
provide a better alternative that covers all use cases. If
the ``select`` reactor is desired, it may be installed via:

.. code-block:: python

    from twisted.internet import selectreactor
    selectreactor.install()

    from twisted.internet import reactor

Platform-Specific Reactors
--------------------------

Poll-based Reactor
~~~~~~~~~~~~~~~~~~
.. _core-howto-choosing-reactor-poll:

The PollReactor will work on any platform that provides ``select.poll`` .  With larger numbers of connected
sockets, it may provide for better performance than the SelectReactor.

.. code-block:: python

    from twisted.internet import pollreactor
    pollreactor.install()

    from twisted.internet import reactor

KQueue
~~~~~~
.. _core-howto-choosing-reactor-kqueue:

The KQueue Reactor allows Twisted to use FreeBSD's kqueue mechanism for
event scheduling. See instructions in the :api:`twisted.internet.kqreactor <twisted.internet.kqreactor>` 's
docstring for installation notes.

.. code-block:: python

    from twisted.internet import kqreactor
    kqreactor.install()

    from twisted.internet import reactor

WaitForMultipleObjects (WFMO) for Win32
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. _core-howto-choosing-reactor-win32_wfmo:

The Win32 reactor is not yet complete and has various limitations
and issues that need to be addressed.  The reactor supports GUI integration
with the win32gui module, so it can be used for native Win32 GUI applications.

.. code-block:: python

    from twisted.internet import win32eventreactor
    win32eventreactor.install()

    from twisted.internet import reactor

Input/Output Completion Port (IOCP) for Win32
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. _core-howto-choosing-reactor-win32_iocp:

Windows provides a fast, scalable event notification system known as IO
Completion Ports, or IOCP for short.  Twisted includes a reactor based
on IOCP which is nearly complete.

.. code-block:: python

    from twisted.internet import iocpreactor
    iocpreactor.install()

    from twisted.internet import reactor

Epoll-based Reactor
~~~~~~~~~~~~~~~~~~~
.. _core-howto-choosing-reactor-epoll:

The EPollReactor will work on any platform that provides
``epoll`` , today only Linux 2.6 and over. The
implementation of the epoll reactor currently uses the Level Triggered
interface, which is basically like poll() but scales much better.

.. code-block:: python

    from twisted.internet import epollreactor
    epollreactor.install()

    from twisted.internet import reactor

GUI Integration Reactors
------------------------

GTK+
~~~~
.. _core-howto-choosing-reactor-gtk:

Twisted integrates with `PyGTK <http://www.pygtk.org/>`_ version
2.0 using the ``gtk2reactor`` . An example Twisted application that
uses GTK+ can be found
in ``doc/core/examples/pbgtk2.py`` .

GTK-2.0 split the event loop out of the GUI toolkit and into a separate
module called "glib" . To run an application using the glib event loop,
use the ``glib2reactor`` . This will be slightly faster
than ``gtk2reactor`` (and does not require a working X display),
but cannot be used to run GUI applications.

.. code-block:: python

    from twisted.internet import gtk2reactor # for gtk-2.0
    gtk2reactor.install()

    from twisted.internet import reactor

.. code-block:: python

    from twisted.internet import glib2reactor # for non-GUI apps
    glib2reactor.install()

    from twisted.internet import reactor

GTK+ 3.0 and GObject Introspection
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. _core-howto-choosing-reactor-gtk3:

Twisted integrates with `GTK+ 3 <http://gtk.org>`_ and GObject
through `PyGObject's <http://live.gnome.org/PyGObject>`_
introspection using the ``gtk3reactor``
and ``gireactor`` reactors.

.. code-block:: python

    from twisted.internet import gtk3reactor
    gtk3reactor.install()

    from twisted.internet import reactor

.. code-block:: python

    from twisted.internet import gireactor # for non-GUI apps
    gireactor.install()

    from twisted.internet import reactor

GLib 3.0 introduces the concept of ``GApplication`` , a class
that handles application uniqueness in a cross-platform way and provides
its own main loop. Its counterpart ``GtkApplication`` also
handles application lifetime with respect to open windows. Twisted
supports registering these objects with the event loop, which should be
done before running the reactor:

.. code-block:: python

    from twisted.internet import gtk3reactor
    gtk3reactor.install()

    from gi.repository import Gtk
    app = Gtk.Application(...)

    from twisted import reactor
    reactor.registerGApplication(app)
    reactor.run()

wxPython
~~~~~~~~
.. _core-howto-choosing-reactor-wxpython:

Twisted currently supports two methods of integrating
wxPython. Unfortunately, neither method will work on all wxPython
platforms (such as GTK2 or Windows). It seems that the only
portable way to integrate with wxPython is to run it in a separate
thread. One of these methods may be sufficient if your wx app is
limited to a single platform.

As with :ref:`Tkinter <core-howto-choosing-reactor-tkinter>` , the support for integrating
Twisted with a `wxPython <http://www.wxpython.org>`_
application uses specialized support code rather than a simple reactor.

.. code-block:: python

    from wxPython.wx import *
    from twisted.internet import wxsupport, reactor

    myWxAppInstance = wxApp(0)
    wxsupport.install(myWxAppInstance)

However, this has issues when running on Windows, so Twisted now
comes with alternative wxPython support using a reactor. Using
this method is probably better. Initialization is done in two
stages. In the first, the reactor is installed:

.. code-block:: python

    from twisted.internet import wxreactor
    wxreactor.install()

    from twisted.internet import reactor

Later, once a ``wxApp`` instance has
been created, but before ``reactor.run()``
is called:

.. code-block:: python

    from twisted.internet import reactor
    myWxAppInstance = wxApp(0)
    reactor.registerWxApp(myWxAppInstance)

An example Twisted application that uses wxPython can be found
in ``doc/core/examples/wxdemo.py`` .

CoreFoundation
~~~~~~~~~~~~~~
.. _core-howto-choosing-reactor-cfreactor:

Twisted integrates with `PyObjC <http://pyobjc.sf.net/>`_ version 1.0. Sample applications using Cocoa and Twisted
are available in the examples directory under
``doc/core/examples/threadedselect/Cocoa`` .

.. code-block:: python

    from twisted.internet import cfreactor
    cfreactor.install()

    from twisted.internet import reactor

Non-Reactor GUI Integration
---------------------------

Tkinter
~~~~~~~
.. _core-howto-choosing-reactor-tkinter:

The support for `Tkinter <http://wiki.python.org/moin/TkInter>`_ doesn't use a specialized reactor.  Instead, there is
some specialized support code:

.. code-block:: python

    from Tkinter import *
    from twisted.internet import tksupport, reactor

    root = Tk()

    # Install the Reactor support
    tksupport.install(root)

    # at this point build Tk app as usual using the root object,
    # and start the program with "reactor.run()", and stop it
    # with "reactor.stop()".

PyUI
~~~~
.. _core-howto-choosing-reactor-pyui:

As with :ref:`Tkinter <core-howto-choosing-reactor-tkinter>` , the support for integrating
Twisted with a `PyUI <http://pyui.sourceforge.net>`_
application uses specialized support code rather than a simple reactor.

.. code-block:: python

    from twisted.internet import pyuisupport, reactor

    pyuisupport.install(args=(640, 480), kw={'renderer': 'gl'})

An example Twisted application that uses PyUI can be found in ``doc/core/examples/pyuidemo.py`` .


text:
package vision

import (
	gax "github.com/googleapis/gax-go"
	"golang.org/x/net/context"
	pb "google.golang.org/genproto/googleapis/cloud/vision/v1"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

// AnnotateImage runs image detection and annotation for a single image.
func (c *ImageAnnotatorClient) AnnotateImage(ctx context.Context, req *pb.AnnotateImageRequest, opts ...gax.CallOption) (*pb.AnnotateImageResponse, error) {
	res, err := c.BatchAnnotateImages(ctx, &pb.BatchAnnotateImagesRequest{
		Requests: []*pb.AnnotateImageRequest{req},
	}, opts...)
	if err != nil {
		return nil, err
	}
	return res.Responses[0], nil
}

// Called for a single image and a single feature.
func (c *ImageAnnotatorClient) annotateOne(ctx context.Context, img *pb.Image, ictx *pb.ImageContext, ftype pb.Feature_Type, maxResults int, opts []gax.CallOption) (*pb.AnnotateImageResponse, error) {
	res, err := c.AnnotateImage(ctx, &pb.AnnotateImageRequest{
		Image:        img,
		ImageContext: ictx,
		Features:     []*pb.Feature{{Type: ftype, MaxResults: int32(maxResults)}},
	}, opts...)
	if err != nil {
		return nil, err
	}
	// When there is only one image and one feature, the response's Error field is
	// unambiguously about that one detection, so we "promote" it to the error return
	// value.
	// res.Error is a google.rpc.Status. Convert to a Go error. Use a gRPC
	// error because it preserves the code as a separate field.
	// TODO(jba): preserve the details field.
	if res.Error != nil {
		return nil, status.Errorf(codes.Code(res.Error.Code), "%s", res.Error.Message)
	}
	return res, nil
}

// DetectFaces performs face detection on the image.
// At most maxResults results are returned.
func (c *ImageAnnotatorClient) DetectFaces(ctx context.Context, img *pb.Image, ictx *pb.ImageContext, maxResults int, opts ...gax.CallOption) ([]*pb.FaceAnnotation, error) {
	res, err := c.annotateOne(ctx, img, ictx, pb.Feature_FACE_DETECTION, maxResults, opts)
	if err != nil {
		return nil, err
	}
	return res.FaceAnnotations, nil
}

// DetectLandmarks performs landmark detection on the image.
// At most maxResults results are returned.
func (c *ImageAnnotatorClient) DetectLandmarks(ctx context.Context, img *pb.Image, ictx *pb.ImageContext, maxResults int, opts ...gax.CallOption) ([]*pb.EntityAnnotation, error) {
	res, err := c.annotateOne(ctx, img, ictx, pb.Feature_LANDMARK_DETECTION, maxResults, opts)
	if err != nil {
		return nil, err
	}
	return res.LandmarkAnnotations, nil
}

// DetectLogos performs logo detection on the image.
// At most maxResults results are returned.
func (c *ImageAnnotatorClient) DetectLogos(ctx context.Context, img *pb.Image, ictx *pb.ImageContext, maxResults int, opts ...gax.CallOption) ([]*pb.EntityAnnotation, error) {
	res, err := c.annotateOne(ctx, img, ictx, pb.Feature_LOGO_DETECTION, maxResults, opts)
	if err != nil {
		return nil, err
	}
	return res.LogoAnnotations, nil
}

// DetectLabels performs label detection on the image.
// At most maxResults results are returned.
func (c *ImageAnnotatorClient) DetectLabels(ctx context.Context, img *pb.Image, ictx *pb.ImageContext, maxResults int, opts ...gax.CallOption) ([]*pb.EntityAnnotation, error) {
	res, err := c.annotateOne(ctx, img, ictx, pb.Feature_LABEL_DETECTION, maxResults, opts)
	if err != nil {
		return nil, err
	}
	return res.LabelAnnotations, nil
}

// DetectTexts performs text detection on the image.
// At most maxResults results are returned.
func (c *ImageAnnotatorClient) DetectTexts(ctx context.Context, img *pb.Image, ictx *pb.ImageContext, maxResults int, opts ...gax.CallOption) ([]*pb.EntityAnnotation, error) {
	res, err := c.annotateOne(ctx, img, ictx, pb.Feature_TEXT_DETECTION, maxResults, opts)
	if err != nil {
		return nil, err
	}
	return res.TextAnnotations, nil
}

// DetectDocumentText performs full text (OCR) detection on the image.
func (c *ImageAnnotatorClient) DetectDocumentText(ctx context.Context, img *pb.Image, ictx *pb.ImageContext, opts ...gax.CallOption) (*pb.TextAnnotation, error) {
	res, err := c.annotateOne(ctx, img, ictx, pb.Feature_DOCUMENT_TEXT_DETECTION, 0, opts)
	if err != nil {
		return nil, err
	}
	return res.FullTextAnnotation, nil
}

// DetectSafeSearch performs safe-search detection on the image.
func (c *ImageAnnotatorClient) DetectSafeSearch(ctx context.Context, img *pb.Image, ictx *pb.ImageContext, opts ...gax.CallOption) (*pb.SafeSearchAnnotation, error) {
	res, err := c.annotateOne(ctx, img, ictx, pb.Feature_SAFE_SEARCH_DETECTION, 0, opts)
	if err != nil {
		return nil, err
	}
	return res.SafeSearchAnnotation, nil
}

// DetectImageProperties computes properties of the image.
func (c *ImageAnnotatorClient) DetectImageProperties(ctx context.Context, img *pb.Image, ictx *pb.ImageContext, opts ...gax.CallOption) (*pb.ImageProperties, error) {
	res, err := c.annotateOne(ctx, img, ictx, pb.Feature_IMAGE_PROPERTIES, 0, opts)
	if err != nil {
		return nil, err
	}
	return res.ImagePropertiesAnnotation, nil
}

// DetectWeb computes a web annotation on the image.
func (c *ImageAnnotatorClient) DetectWeb(ctx context.Context, img *pb.Image, ictx *pb.ImageContext, opts ...gax.CallOption) (*pb.WebDetection, error) {
	res, err := c.annotateOne(ctx, img, ictx, pb.Feature_WEB_DETECTION, 0, opts)
	if err != nil {
		return nil, err
	}
	return res.WebDetection, nil
}

// CropHints computes crop hints for the image.
func (c *ImageAnnotatorClient) CropHints(ctx context.Context, img *pb.Image, ictx *pb.ImageContext, opts ...gax.CallOption) (*pb.CropHintsAnnotation, error) {
	res, err := c.annotateOne(ctx, img, ictx, pb.Feature_CROP_HINTS, 0, opts)
	if err != nil {
		return nil, err
	}
	return res.CropHintsAnnotation, nil
}

// LocalizeObject runs the localizer for object detection.
func (c *ImageAnnotatorClient) LocalizeObjects(ctx context.Context, img *pb.Image, ictx *pb.ImageContext, opts ...gax.CallOption) ([]*pb.LocalizedObjectAnnotation, error) {
	res, err := c.annotateOne(ctx, img, ictx, pb.Feature_OBJECT_LOCALIZATION, 0, opts)
	if err != nil {
		return nil, err
	}
	return res.LocalizedObjectAnnotations, nil
}


text:
##1. Info
Autore: Samuel Dias da Silva
Data: 16.09.2016
Luogo: SAM, Trevano

##2. Lavori svolti
Nella prima parte della lezione abbiamo approfondito il primo punto del modello a cascata, cioè l'analisi del progetto.
####Il professore ha risposto alle seguenti domande
 **Quali materiali abbiamo a disposizione?**
 *Di base il compensato, ma se si fornisce per tempo una lista dei materiali di cui si ha bisogno, si possono avere tutti*
 **Quale dimensione deve avere l'holder?**
 *La dimensione dell'holder é a libera scelta, ma non bisogna superare il ```30x30```*
 **Che spessore deve avere l'holder?**
 *Lo spessore dell'holder é libera scelta, ma anche qui non si possono superare i ```5cm```*
 **Qual'è il budget del progetto?**
 *Il budget sarà il costo finale del progetto (tenendo conto anche del costo orario)*
 **Se si rovesciasse l'holder, l'arduino deve restare "incastrato" in esso?**
 *È una cosa opzionale*
 **Deve avere uno scompartimento per la batteria?**
 *Opzionale*
 **Deve avere un colore specifico?**
 *Il colore è a scelta*
 **Deve avere una copertura?**
 *È opzionale*

 ####Ed ha fornito ulteriori richieste
 - Bisogna poter mettere e togliere i cavi dall'arduino in modo semplice
 - Le uscite dell'arduino devono essere verso l'esterno
 - L'holder deve avere un piccolo deposito nella quale è possibile riporre dei componenti
 - Entro il ```14/10/2016``` la progettazione e l'analisi dev'essere finita
 - Il ```21/10/2016``` é la consegna del progetto

##3. Problemi riscontrati e soluzione adottate

N/A

##4. Punto della situazione rispetto alla pianificazione

N/A

##5. Programma di massima per la prossima giornata di lavoro

N/A


text:
***************************************
Topographica spatial coordinate systems
***************************************

Topographica allows simulation parameters to be specified in units
that are independent of the level of detail used in any particular
run of the simulation. To achieve this, Topographica provides
multiple spatial coordinate systems, called *Sheet* and *matrix*
coordinates. These coordinate systems are primarily described in the
`ImaGen package`_, which should be examined before going further on
this page. Here we describe only the Topographica-specific aspects
of the coordinate systems.

Connection fields
-----------------

Units in a Topographica Sheet can receive input from units in other
Sheets. Such inputs are generally contained within a
`ConnectionField`_, which is a spatially localized region of an
input Sheet. A ConnectionField is bounded by a BoundingBox that is a
subregion of the Sheet's BoundingBox. The units contained within a
ConnectionField are those whose centers lie within that BoundingBox.

For instance, if the user specifies a ConnectionField with Sheet
bounds from (-0.275,-0.0125) to (0.025,0.2885) for a sheet with a
density of 10, the corresponding matrix coordinate bounds are
(5.125,2.250) to (2.125,5.250):

|image0| |image1|

Here the medium black outline shows the user-specified
ConnectionField BoundingBox in matrix and Sheet coordinates. The
units contained in this ConnectionField are (4,2) to (2,4)
(inclusive; shown by black dots with a yellow background). Notice
that the Sheet area of the ConnectionField will not necessarily
correspond exactly to the user-specified BoundingBox, because the
matrix is discrete.

Note that a ConnectionField is similar to the biological concept of
a receptive field (RF), but the two concepts are the same only for
models with one input sheet and one cortical sheet. When there is
more than one hierarchical level, the ConnectionField of a top-level
unit is a set of weights on the previous Sheet, while the receptive
field is an area of the input sheet to which the unit responds. Thus
a ConnectionField is a lower-level concept than a receptive field,
and RFs can be thought of as constructed from CFs.

Edge buffering
--------------

If every Sheet has the default 1.0x1.0 area, units near the border
of higher-level Sheets will have ConnectionFields that extend past
the border of lower-level Sheets. This ConnectionField cropping will
often result in artifacts in the behavior of units near the border.
To avoid such artifacts, lower-level Sheets should usually have
areas larger than 1.0x1.0.

For instance, assume that Sheets have a 1.0x1.0 area. If a higher
level sheet U has a ConnectionField BoundingBox of size 0.4x0.4 on
lower-level Sheet L, neurons near the border of U will have up to
0.2 in Sheet coordinates cut off of their ConnectionFields. To
prevent this, the BoundingBox of L can be extended by 0.2 in Sheet
coordinates in each direction:

.. figure:: images/retina_edge_buffer.png
   :align: center
   :alt:

Here, the thick black line shows the calculated size of L to avoid
edge cropping, and the dotted line shows the size of U for
reference. If L were the size of U, up to three quarters of the
ConnectionField of units in U near the border would be cut off. With
the size of L extended as shown, all units in U will have full
ConnectionFields. Thus when calculating the behavior of U, the
extended L will work as if L were infinitely large in all
directions. This approach is appropriate for avoiding edge effects
when modeling a small patch of a larger system.

Of course, this technique cannot help you avoid such cropping for
lateral connections within U or feedback connections from areas
above U. In some simulators, periodic boundary conditions can be
enforced such that such connections wrap around like a torus,
avoiding these issues. However, such wrapping is not practical in
Topographica, which focuses on drawing realistic input patterns like
photographs, which cannot be rendered properly on a torus.

Technical details
~~~~~~~~~~~~~~~~~

In addition to the `details discussed with the ImaGen package`_,
Topographica Sheets have an additional complication for certain
bounds and densities when using non-square sheets. Consider the
example from ImaGen, but instead with rectangular bounds given by
``BoundingBox(points=((-0.3,-0.5),(0.3,0.5)))``. This time, the y
dimension would be tiled exactly by a density of 7, but the x
dimension would not. This problem could be solved by allowing a
Sheet to have different densities in each dimension (i.e. an
xdensity and a ydensity); indeed, the `SheetCoordinateSystem`_
underlying a Sheet does not require that the xdensity and ydensity
are equal. However, for a Sheet itself, it is simpler for the
density to be equal in both dimensions. To solve the problem above,
then, Topographica takes the bounds's x-width and calculate an
xdensity from this (as described for the previous example), and
makes the ydensity exactly equal to this by adjusting the top and
bottom bounds. In our example, the top bound would be adjusted to
0.525, and the bottom to -0.525---the closest bounds allowing a
density of 6.67 to tile the dimension exactly.

In summary, the bounds specified for a Sheet are respected, but the
density may be adjusted so that the plane is tiled exactly. In
certain cases where it is not possible to have the same density in
the y direction as in the x direction with the specified bounds, the
top and bottom bounds are adjusted so that the densities can remain
equal. This is an "x-bounds-master" approach; futher discussion of
this and alternatives is available in `SheetCoordinateSystem`_.

.. _ImaGen package: coords.html
.. _ConnectionField: ../Reference_Manual/topo.base.cf.ConnectionField-class.html
.. _details discussed with the ImaGen package: coords.html#technical-details
.. _SheetCoordinateSystem: ../Reference_Manual/imagen.sheetcoords.SheetCoordinateSystem-class.html

.. |image0| image:: images/connection_field.png
.. |image1| image:: images/sheet_coords_-0.275_-0.0125_0.025_0.2885.png


text:
class Region < ActiveRecord::Base
  validates_uniqueness_of :name

  has_many :region_organizers
  has_many :organizers, through: :region_organizers, source: :user
  has_many :region_slugs, dependent: :destroy

  scope :active, -> { where(active: true) }

  def to_param
    "#{id}-#{main_slug}"
  end

  def main_slug
    region_slugs.find_by(main_slug: true).try(:slug) || region_slugs.try(:first).try(:slug)
  end
end


text:
package request

import (
	"crypto/hmac"
	"crypto/sha256"
	"encoding/hex"
	"encoding/json"
	"github.com/5sigma/spyder/config"
	"github.com/5sigma/spyder/endpoint"
	"github.com/robertkrimen/otto"
	"github.com/robertkrimen/otto/parser"
	_ "github.com/robertkrimen/otto/underscore"
	"io/ioutil"
	"net/http"
	"path"
)

// ScriptEngine - A scripting engine used to execute hook scripts during the
// request process. It is built to execute arbitrary Javascript.
type ScriptEngine struct {
	VM             *otto.Otto
	Constants      map[string]string
	AssetPath      string
	Response       *Response
	EndpointConfig *endpoint.EndpointConfig
	Payload        []byte
	Request        *http.Request
	Debug          string
}

// NewScriptEngine - Generates a new script engine.
func NewScriptEngine(endpointConfig *endpoint.EndpointConfig) *ScriptEngine {
	vm := otto.New()

	eng := &ScriptEngine{
		VM:             vm,
		EndpointConfig: endpointConfig,
	}

	varObj, _ := vm.Object("$variables = {}")
	varObj.Set("set", eng.setLocalVar)
	varObj.Set("get", eng.getVar)

	vm.Set("$debug", eng.setDebug)
	vm.Set("$hmac", eng.hmac)

	reqObj, _ := eng.VM.Object("$request = {}")
	requestBytes := endpointConfig.RequestData()
	reqObj.Set("body", string(requestBytes))
	reqObj.Set("contentLength", len(requestBytes))
	headersObj, _ := eng.VM.Object(`$request.headers = {}`)
	headersObj.Set("get", eng.getReqHeader)
	headersObj.Set("set", eng.setReqHeader)
	reqObj.Set("setBody", eng.setPayload)
	vm.Set("$endpoint", eng.requestEndpoint)

	return eng
}

func NewTaskEngine() *ScriptEngine {

	vm := otto.New()

	eng := &ScriptEngine{
		VM: vm,
	}

	varObj, _ := vm.Object("$variables = {}")
	varObj.Set("set", eng.setLocalVar)
	varObj.Set("get", eng.getVar)

	vm.Set("$debug", eng.setDebug)
	vm.Set("$hmac", eng.hmac)
	vm.Set("$endpoint", eng.requestEndpoint)
	return eng
}

//ExecuteFile - Executes a script contianed in a file.
func (eng *ScriptEngine) ExecuteFile(filepath string) error {
	data, err := ioutil.ReadFile(filepath)
	if err != nil {
		return err
	}
	err = eng.Execute(string(data))
	if err != nil {
		return err
	}
	return nil
}

// SetResponse - Used to set the web respone on the engine. It also makes this
// available to the script.
func (engine *ScriptEngine) SetResponse(res *Response) {
	engine.Response = res
	requestObj, _ := engine.VM.Object(`$request = {}`)
	requestObj.Set("url", res.Request.URL.String())
	requestObj.Set("contentLength", res.Request.ContentLength)

	responseObj, _ := engine.VM.Object(`$response = {}`)
	responseObj.Set("contentLength", res.Response.ContentLength)
	if res.IsResponseJSON() {
		contentData := make(map[string]interface{})
		json.Unmarshal(res.Content, &contentData)
		responseObj.Set("body", contentData)
	} else {
		responseObj.Set("body", string(res.Content))
	}
	engine.VM.Object(`$response.headers = {}`)
	responseObj.Set("get", engine.getResHeader)
}

// SetRequest - Sets the request on the engine. This also builds the functions
// to expose the request to scripts.
func (engine *ScriptEngine) SetRequest(request *http.Request) {
	engine.Request = request
	reqVal, _ := engine.VM.Get("$request")
	reqObj := reqVal.Object()
	reqObj.Set("contentLength", request.ContentLength)
}

// SetPayload - Sets the request payload on the engine. Also exposes it to
// scripts within the request object.
func (engine *ScriptEngine) SetPayload(payload []byte) {
	engine.Payload = payload
	reqVal, _ := engine.VM.Get("$request")
	reqObj := reqVal.Object()
	contentData := make(map[string]interface{})
	json.Unmarshal(payload, &contentData)
	reqObj.Set("body", contentData)
}

//Execute - Executes a Javascript.
func (engine *ScriptEngine) Execute(script string) error {
	_, err := engine.VM.Run(script)
	return err
}

// Validate - Validates that the Javascript is valid.
func (eng *ScriptEngine) Validate(script string) error {
	_, err := parser.ParseFile(nil, "", script, 0)
	return err
}

// jsThrow - Used to throw javascript errors from Go.
func jsThrow(call otto.FunctionCall, err error) {
	call.Otto.Call("new Error", nil, err.Error())
}

// setLocalVar - Sets a config value in the local config.
func (engine *ScriptEngine) setLocalVar(call otto.FunctionCall) otto.Value {
	key, _ := call.Argument(0).ToString()
	value, _ := call.Argument(1).ToString()
	config.LocalConfig.SetVariable(key, value)
	return otto.Value{}
}

// getVar - Returns a config variable.
func (engine *ScriptEngine) getVar(call otto.FunctionCall) otto.Value {
	key, _ := call.Argument(0).ToString()
	if config.LocalConfig.VariableExists(key) {
		v := config.LocalConfig.GetVariable(key)
		ov, _ := otto.ToValue(v)
		return ov
	}
	if config.GlobalConfig.VariableExists(key) {
		v := config.LocalConfig.GetVariable(key)
		ov, _ := otto.ToValue(v)
		return ov
	}
	return otto.Value{}
}

// getPayload - Returns the request payload.
func (engine *ScriptEngine) getPayload(call otto.FunctionCall) otto.Value {
	ov, _ := otto.ToValue(string(engine.Payload))
	return ov
}

// setPayload - Sets the payload value on the engine.
func (engine *ScriptEngine) setPayload(call otto.FunctionCall) otto.Value {
	valArg := call.Argument(0)
	if valArg.IsString() {
		val, _ := valArg.ToString()
		engine.Payload = []byte(val)
	}
	if valArg.IsObject() {
		valRaw, _ := valArg.Export()
		valMap := valRaw.(map[string]interface{})
		valBytes, _ := json.Marshal(valMap)
		engine.Payload = valBytes
	}
	return otto.Value{}
}

// hmac - Calcualtes an HMAC signature using SHA256
func (engine *ScriptEngine) hmac(call otto.FunctionCall) otto.Value {
	secretStr, _ := call.Argument(0).ToString()
	payloadStr, _ := call.Argument(1).ToString()
	secret := []byte(secretStr)
	h := hmac.New(sha256.New, secret)
	h.Write([]byte(payloadStr))
	sigBytes := h.Sum(nil)
	v, _ := otto.ToValue(hex.EncodeToString(sigBytes))
	return v
}

// getReqHeader - Returns a header from the request.
func (engine *ScriptEngine) getReqHeader(call otto.FunctionCall) otto.Value {
	headerName, _ := call.Argument(0).ToString()
	val := engine.Request.Header.Get(headerName)
	v, _ := otto.ToValue(val)
	return v
}

// setReqHeader - sets a header on the request.
func (engine *ScriptEngine) setReqHeader(call otto.FunctionCall) otto.Value {
	headerName, _ := call.Argument(0).ToString()
	headerValue, _ := call.Argument(1).ToString()
	if engine.Request != nil {
		engine.Request.Header.Set(headerName, headerValue)
	} else {
		engine.EndpointConfig.Headers[headerName] = []string{headerValue}
	}
	return otto.Value{}
}

// getResHeader - Returns a header from the response.
func (engine *ScriptEngine) getResHeader(call otto.FunctionCall) otto.Value {
	headerName, _ := call.Argument(0).ToString()
	val := engine.Response.Response.Header.Get(headerName)
	v, _ := otto.ToValue(val)
	return v
}

// setDebug - Sets the debug value on the engine. Used for testing.
func (engine *ScriptEngine) setDebug(call otto.FunctionCall) otto.Value {
	val, _ := call.Argument(0).ToString()
	engine.Debug = val
	return otto.Value{}
}

func (engine *ScriptEngine) requestEndpoint(call otto.FunctionCall) otto.Value {
	epConfigFile, _ := call.Argument(0).ToString()
	epConfig, err := endpoint.Load(path.Join(config.ProjectPath, "endpoints", epConfigFile+".json"))
	if err != nil {
		jsThrow(call, err)
	}

	if !call.Argument(1).IsUndefined() {
		payload, _ := call.Argument(1).Export()
		epConfig.SetRequestData(payload.(map[string]interface{}))
	}

	res, err := Do(epConfig)
	if err != nil {
		jsThrow(call, err)
	}

	returnObj, _ := engine.VM.Object("EP_RESULT={}")
	if res.IsResponseJSON() {
		contentData := make(map[string]interface{})
		json.Unmarshal(res.Content, &contentData)
		returnObj.Set("body", contentData)
	} else {
		returnObj.Set("body", string(res.Content))
	}
	returnObj.Set("headers", res.Response.Header)
	returnObj.Set("status", res.Response.Status)
	returnObj.Set("statusCode", res.Response.StatusCode)

	return returnObj.Value()
}