text:
<!doctype html>

  <meta charset="UTF-8">
  <title>David Uli's Blog</title>
  <link href="blogpoststylesheet.css" rel="stylesheet" type="text/css">

David Uli

Software Developer

Phase 0 - Week 3 Thinking Styles

Friday, May 15, 2015

Tweet

 Dev Bootcamp Phase 0 - Week Three:  Students Log

Early on in the Dev Bootcamp experience you are asked to research the Gregorc Thinking Styles to determine which of the four thinking styles your prefer, Concrete Sequential, Abstract Sequential, Abstract Random or Concrete Random.  After taking the Personal Thinking Style Quiz, I found out that I fell into the Abstract Random bucket.  Doing some initial research, I could easily see some of the personality traits closely matched me.  I recall that my first thought was "yes, I am a spontaneous, adaptable, perceptive and social person by nature, but what does that really mean and how does knowing this change my experience at Dev Bootcamp?"

Well, I am almost three weeks in and I can already start to see more of the personality traits and how they directly impact some of the challenges and/or exercises that I have struggled with as well as the ones that I excelled at.  For example, in Learning Styles: Concrete, Abstract, Random, and Sequential, J.D. Meier  says that Abstract Random thinkers learn easily, they are comfortable processing large amounts of data and jumping around from one thing to another but have a hard time expressing what they learned.  Well if you read my first cultural bog, you remember how comfortable I am with this whole blogging thing.

Besides a pathological aversion to blogging, my first three weeks at Dev Bootcamp has uncovered a couple challenging areas for me.  The first portion of the curriculum that I have found challenging has been the time boxing expectations.  Understanding more about my thinking style, specifically the preference to hop around from one topic to another and maintain a balance between social activities and work, I can better identify the reasons why I have struggled with time boxing.  In addition, I found the longer technical reading portions can be borderline painful.

For me, the benefit of learning about and understanding my learning style is that I can adjust how I perform some of these tasks to better fit my learning style.  One example of this is with the technical reading, by mixing in time reading and time actually trying some of the examples I have found that I am able to stay focused and even excited to get back and read more about the thing that I just experienced.  The challenge will come when we are time restrained, it will be important that I not only be able to identify and flex my style, I will also have to be able to acknowledge areas that will be challenging and focus to push through them.

After just a few weeks at Dev Bootcamp it is clear that understanding and adjusting your thinking style is important.  Much like the DISC Personality Assessment, which is a tool that is used by many businesses to help there employees understand there preferred communication style so that they can work better together as a Team; the Gregorc Thinking Styles are important because they help us understand how we can make the most out of our Dev Bootcamp experience and work together effectively in pairing sessions and team projects.

Click Here for more information on the Gregorc Thinking Styles that I found helpful.

David Uli

Email : mail@daviduli.com

Website : http://norcaldavid.github.io

Phone : (504) 201-4466

          Home

          Projects

          Blog

Recent Blog Postings

5/1/15 - Version Control

5/1/15 - Fireside Chat

5/8/15 - The CSS Box Model

5/15/15 - Arrays vs Hashes

5/15/15 - Thinking Styles

5/22/15 - Enumberable Music

5/22/15 - Tech Issues

5/29/15 - The Cooking Class

5/29/15 - Pairing and Feedback

6/7/15 - Functional vs Object Oriented

6/7/15 - Stereotype Threat

6/12/15 - Ruby Docs vs Javascript Docs

6/12/15 - Cultural Blog - Values

6/19/15 - What is Rails Anyway

6/19/15 - Cultural Blog - Conflict

2015  Copyright David Uli - All Rights Reserved


text:
#include <mpi.h>

/* If we use libmpichcxx.dylib, we need to compile
 * this package as c++ project because libmpichcxx.dylib
 * need c++ runtimes.
 * this file makes dependency for c++ runtime.
 */
void mpicxx_dummy() {}

redpajama_set_name: RedPajamaGithub


text:
package de.ust.skill.ir.internal;

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

import de.ust.skill.ir.ContainerType;
import de.ust.skill.ir.Declaration;
import de.ust.skill.ir.Field;
import de.ust.skill.ir.Hint;
import de.ust.skill.ir.InterfaceType;
import de.ust.skill.ir.ParseException;
import de.ust.skill.ir.Restriction;
import de.ust.skill.ir.Type;
import de.ust.skill.ir.TypeContext;
import de.ust.skill.ir.UserType;

/**
 * Substitutes interfaces.
 *
 * @author Timm Felden
 */
public class InterfaceSubstitution extends Substitution {

	public InterfaceSubstitution() {
	}

	@Override
	public void addTypes(TypeContext tc, List<Declaration> defs) throws ParseException {
		// no types are added by us
	}

	@Override
	public boolean drop(Type t) {
		return t instanceof InterfaceType;
	}

	@Override
	public Field substitute(TypeContext tc, Field f) throws ParseException {

		// just replace interface types by base types, this can be done in an
		// field agnostic way

		return f.cloneWith(substitute(tc, f.getType()), Collections.<Restriction>emptySet(),
				Collections.<Hint>emptySet());
	}

	@Override
	public Type substitute(TypeContext tc, Type t) throws ParseException {
		if (null == t)
			return null;

		// substitute interfaces with their super types
		Type target;
		if (t instanceof InterfaceType)
			target = ((InterfaceType) t).getSuperType();
		else
			target = t;

		// convert base types to argument type context
		if (target instanceof ContainerType) {
			return ((ContainerType) target).substituteBase(tc, this);
		}
		return tc.get(target.getSkillName());
	}

	@Override
	public void initialize(TypeContext fromTC, TypeContext tc, UserType d) throws ParseException {
		UserType t = (UserType) fromTC.types.get(d.getSkillName());

		// collect fields from super interfaces
		List<Field> fields = TypeContext.substituteFields(this, tc, t.getFields());
		for (InterfaceType i : t.getSuperInterfaces())
			addFieldsRecursive(tc, fields, i);

		UserType superType = findSuperType(t);

		d.initialize((UserType) substitute(tc, superType), Collections.emptyList(), fields, t.getViews(),
				t.getCustomizations());
	}

	public static UserType findSuperType(UserType t) {
		UserType rval = t.getSuperType();
		// search interfaces
		if (null == rval)
			for (InterfaceType i : t.getSuperInterfaces())
				if (null == rval)
					rval = findSuperType(i);

		return rval;
	}

	public static UserType findSuperType(InterfaceType t) {
		UserType rval = null;
		if (t.getSuperType() instanceof UserType)
			rval = (UserType) t.getSuperType();

		// search interfaces
		if (null == rval)
			for (InterfaceType i : t.getSuperInterfaces())
				if (null == rval)
					rval = findSuperType(i);

		return rval;
	}

	public void addFieldsRecursive(TypeContext tc, List<Field> fields, InterfaceType i) throws ParseException {
		fields.addAll(TypeContext.substituteFields(this, tc, i.getFields()));
		for (InterfaceType sub : i.getSuperInterfaces())
			addFieldsRecursive(tc, fields, sub);
	}

}


text:
**Base**

  * Galletitas de chocolate (Chocolinas) 350 gr
  * Manteca 100 gr
  * Oporto 30 cc
  * Azúcar impalpable 35 gr

**Relleno**

  * Crema semimontada (1/2 punto) 200 gr
  * Azúcar 50 gr
  * Almidón de maíz 40 gr
  * Dulce de leche 500 gr
  * Huevos 3 Unidades
  * Queso crema 400 gr

### Preparación

**Base**

  Procesar las galletitas de chocolate junto con la manteca fundida, el oporto
  y el azúcar impalpable.

  Forrar un molde de 24 cm de diámetro con la preparación y hornear a 180ºC por
  8 minutos.Reservar.

  > *Nota*: Quizás no hace falta hornear 8min. Un poco menos puede funcionar.

**Relleno**

  Mezclar los huevos, el dulce y el queso con batidor de alambre hasta que
  queden bien incorporados.

  Agregar al final la crema de leche batida a medio punto. Por último agregar
  los secos.

  Volcar sobre la base y cocinar 40/45 minutos en horno precalentado
  (160°C/170°C).

  > *Nota*: Cocinar en horno hasta que se mueva ligeramente y retirar. Si se
  > pasa de tiempo de cocción, se resquebraja el centro y queda con
  > fea presentación.

*Fuentes:*

  * [http://elgourmet.com/receta/cheesecake-de-dulce-de-leche-2](http://elgourmet.com/receta/cheesecake-de-dulce-de-leche-2)
  * [http://www.foxlife.tv/recetas/7822-cheesecake-de-dulce-leche.html](http://www.foxlife.tv/recetas/7822-cheesecake-de-dulce-leche.html)


text:
id: 5900f4e01000cf542c50fff2
challengeType: 5
isHidden: false
title: 'Problem 371: Licence plates'
forumTopicId: 302033
---

## Description

Oregon licence plates consist of three letters followed by a three digit number (each digit can be from [0..9]).
While driving to work Seth plays the following game:
Whenever the numbers of two licence plates seen on his trip add to 1000 that's a win.

E.g. MIC-012 and HAN-988 is a win and RYU-500 and SET-500 too. (as long as he sees them in the same trip).

Find the expected number of plates he needs to see for a win.
Give your answer rounded to 8 decimal places behind the decimal point.

Note: We assume that each licence plate seen is equally likely to have any three digit number on it.

## Instructions

## Tests

```yml
tests:
  - text: <code>euler371()</code> should return 40.66368097.
    testString: assert.strictEqual(euler371(), 40.66368097);

```

## Challenge Seed

```js
function euler371() {
  // Good luck!
  return true;
}

euler371();
```

## Solution

```js
// solution required
```


text:
package com.me.silencedut.nbaplus.utils.blur;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter;
import android.view.View;

/**
 * Created by SlienceDut on 2015/12/2.
 */
public class BitmapUtils {
    public static Bitmap drawViewToBitmap(View view, int width, int height, int downSampling,String color) {
        return drawViewToBitmap(view, width, height, 0f, 0f, downSampling,color);
    }

    public static Bitmap drawViewToBitmap(View view, int width, int height, float translateX,
                                          float translateY, int downSampling,String color) {
        float scale = 1f / downSampling;
        int bmpWidth = (int) (width * scale - translateX / downSampling);
        int bmpHeight = (int) (height * scale - translateY / downSampling);
        Bitmap dest = Bitmap.createBitmap(bmpWidth, bmpHeight, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(dest);
        canvas.translate(-translateX / downSampling, -translateY / downSampling);
        if (downSampling > 1) {
            canvas.scale(scale, scale);
        }
        Paint paint = new Paint();
        paint.setFlags(Paint.FILTER_BITMAP_FLAG | Paint.ANTI_ALIAS_FLAG);
        PorterDuffColorFilter filter =
                new PorterDuffColorFilter(Color.parseColor(color),PorterDuff.Mode.SRC_ATOP);
        paint.setColorFilter(filter);
        view.buildDrawingCache();
        Bitmap cache = view.getDrawingCache();
        canvas.drawBitmap(cache, 0, 0, paint);
        cache.recycle();
        view.destroyDrawingCache();

        return dest;
    }
}


text:
require 'common/logging/filters'

module Bosh::Director
  class JobRunner

    # @param [Class] job_class Job class to instantiate and run
    # @param [Integer] task_id Existing task id
    def initialize(job_class, task_id, worker_name)
      unless job_class.kind_of?(Class) &&
        job_class <= Jobs::BaseJob
        raise DirectorError, "Invalid director job class '#{job_class}'"
      end

      @task_id = task_id
      @worker_name = worker_name
      setup_task_logging_for_files
      task_manager = Bosh::Director::Api::TaskManager.new

      @job_class = job_class
      @task_logger.info("Looking for task with task id #{@task_id}")
      @task = task_manager.find_task(@task_id)
      setup_task_logging_for_db
      @task_logger.info("Found task #{@task.inspect}")
    end

    # Runs director job
    def run(*args)
      Config.current_job = nil

      @task_logger.info("Running from worker '#{@worker_name}' on #{Config.runtime['instance']} (#{Config.runtime['ip']})")
      @task_logger.info("Starting task: #{@task_id}")
      started_at = Time.now

      with_thread_name("task:#{@task_id}") { perform_job(*args) }

      duration = Duration.duration(Time.now - started_at)
      @task_logger.info("Task took #{duration} to process.")
    end

    private

    # Sets up job logging.
    # @return [void]
    def setup_task_logging_for_files
      log_dir = File.join(Config.base_dir, 'tasks', @task_id.to_s)
      FileUtils.mkdir_p(log_dir)

      debug_log = File.join(log_dir, 'debug')

      @task_logger = Logging::Logger.new('DirectorJobRunner')
      shared_appender = Logging.appenders.file(
        'DirectorJobRunnerFile',
        filename: debug_log,
        layout: ThreadFormatter.layout,
        filters: [Bosh::Common::Logging.null_query_filter],
      )
      @task_logger.add_appenders(shared_appender)
      @task_logger.level = Config.logger.level

      Config.logger = @task_logger

      Config.db.logger = @task_logger
      Config.dns_db.logger = @task_logger if Config.dns_db

      cpi_log = File.join(log_dir, 'cpi')
      Config.cloud_options['properties'] ||= {}
      Config.cloud_options['properties']['cpi_log'] = cpi_log
    end

    # Sets up job logging.
    # @return [void]
    def setup_task_logging_for_db
      Config.event_log = EventLog::Log.new(TaskDBWriter.new(:event_output, @task.id))
      Config.result = TaskDBWriter.new(:result_output, @task.id)
    end

    # Instantiates and performs director job.
    # @param [Array] args Opaque list of job arguments that will be used to
    #   instantiate the new job object.
    # @return [void]
    def perform_job(*args)
      @task_logger.info('Creating job')

      job = @job_class.new(*args)
      Config.current_job = job

      job.task_id = @task_id
      job.task_checkpoint # cancelled in the queue?

      run_checkpointing

      @task_logger.info("Performing task: #{@task.inspect}")

      @task.timestamp = Time.now
      @task.started_at = Time.now
      @task.checkpoint_time = Time.now
      @task.save

      result = job.perform

      @task_logger.info('Done')
      finish_task(:done, result)

    rescue Bosh::Director::TaskCancelled => e
      log_exception(e)
      @task_logger.info("Task #{@task.id} cancelled")
      finish_task(:cancelled, 'task cancelled')
    rescue Exception => e
      log_exception(e)
      @task_logger.error("#{e}\n#{e.backtrace.join("\n")}")
      finish_task(:error, e)
    end

    # Spawns a thread that periodically updates task checkpoint time.
    # There is no need to kill this thread as job execution lifetime is the
    # same as worker process lifetime.
    # @return [Thread] Checkpoint thread
    def run_checkpointing
      # task check pointer is scoped to separate class to avoid
      # the secondary thread and main thread modifying the same @task
      # variable (and accidentally clobbering it in the process)
      task_checkpointer = TaskCheckPointer.new(@task.id)
      Thread.new do
        with_thread_name("task:#{@task.id}-checkpoint") do
          while true
            sleep(Config.task_checkpoint_interval)
            task_checkpointer.checkpoint
          end
        end
      end
    end

    # Truncates string to fit task result length
    # @param [String] string The original string
    # @param [Integer] len Desired string length
    # @return [String] Truncated string
    def truncate(string, len = 128)
      stripped = string.strip[0..len]
      if stripped.length > len
        stripped.gsub(/\s+?(\S+)?$/, "") + "..."
      else
        stripped
      end
    end

    # Marks task completion
    # @param [Symbol] state Task completion state
    # @param [#to_s] result
    def finish_task(state, result)
      @task.refresh
      @task.state = state
      @task.result = truncate(result.to_s)
      @task.timestamp = Time.now
      @task.save
    end

    # Logs the exception in the event log
    # @param [Exception] exception
    def log_exception(exception)
      # Event log is being used here to propagate the error.
      # It's up to event log renderer to find the error and
      # signal it properly.
      director_error = DirectorError.create_from_exception(exception)
      Config.event_log.log_error(director_error)
    end
  end

  class TaskCheckPointer
    def initialize(task_id)
      task_manager = Bosh::Director::Api::TaskManager.new
      @task = task_manager.find_task(task_id)
    end

    def checkpoint
      @task.update(:checkpoint_time => Time.now)
    end
  end
end


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

package com.azure.ai.formrecognizer.documentanalysis.implementation.util;

import com.azure.ai.formrecognizer.documentanalysis.administration.models.ResourceDetails;

/**
 * The helper class to set the non-public properties of an {@link ResourceDetails} instance.
 */
public final class ResourceDetailsHelper {
    private static ResourceDetailsAccessor accessor;

    private ResourceDetailsHelper() {
    }

    /**
     * Type defining the methods to set the non-public properties of an {@link ResourceDetails} instance.
     */
    public interface ResourceDetailsAccessor {
        void setDocumentModelCount(ResourceDetails resourceDetails, int documentModelCount);
        void setDocumentModelLimit(ResourceDetails resourceDetails, int documentModelLimit);
    }

    /**
     * The method called from {@link ResourceDetails} to set it's accessor.
     *
     * @param resourceDetailsAccessor The accessor.
     */
    public static void setAccessor(final ResourceDetailsAccessor resourceDetailsAccessor) {
        accessor = resourceDetailsAccessor;
    }

    static void setDocumentModelCount(ResourceDetails resourceDetails, int documentModelCount) {
        accessor.setDocumentModelCount(resourceDetails, documentModelCount);
    }

    static void setDocumentModelLimit(ResourceDetails resourceDetails, int documentModelLimit) {
        accessor.setDocumentModelLimit(resourceDetails, documentModelLimit);
    }
}


text:
<?php

namespace Assetic\Filter;

/**
 * Process is a thin wrapper around proc_* functions to ease
 * start independent PHP processes.
 *
 * @author Fabien Potencier <fabien.potencier@symfony-project.com>
 */
class Process
{
    protected $commandline;
    protected $cwd;
    protected $env;
    protected $stdin;
    protected $timeout;
    protected $options;
    protected $exitcode;
    protected $status;
    protected $stdout;
    protected $stderr;

    /**
     * Constructor.
     *
     * @param string  $commandline The command line to run
     * @param string  $cwd         The working directory
     * @param array   $env         The environment variables
     * @param string  $stdin       The STDIN content
     * @param integer $timeout     The timeout in seconds
     * @param array   $options     An array of options for proc_open
     *
     * @throws \RuntimeException When proc_open is not installed
     */
    public function __construct($commandline, $cwd = null, array $env = array(), $stdin = null, $timeout = 60, array $options = array())
    {
        if (!function_exists('proc_open')) {
            throw new \RuntimeException('The Process class relies on proc_open, which is not available on your PHP installation.');
        }

        $this->commandline = $commandline;
        $this->cwd = null === $cwd ? getcwd() : $cwd;
        $this->env = array();
        foreach ($env as $key => $value) {
            $this->env[(binary) $key] = (binary) $value;
        }
        $this->stdin = $stdin;
        $this->timeout = $timeout;
        $this->options = array_merge($options, array('suppress_errors' => true, 'binary_pipes' => true));
    }

    /**
     * Runs the process.
     *
     * The callback receives the type of output (out or err) and
     * some bytes from the output in real-time. It allows to have feedback
     * from the independent process during execution.
     *
     * If you don't provide a callback, the STDOUT and STDERR are available only after
     * the process is finished via the getOutput() and getErrorOutput() methods.
     *
     * @param Closure|string|array $callback A PHP callback to run whenever there is some
     *                                       output available on STDOUT or STDERR
     *
     * @return integer The exit status code
     *
     * @throws \RuntimeException When process can't be launch or is stopped
     */
    public function run($callback = null)
    {
        if (null === $callback) {
            $this->stdout = '';
            $this->stderr = '';
            $that = $this;
            $callback = function ($type, $line) use ($that)
            {
                if ('out' == $type) {
                    $that->addOutput($line);
                } else {
                    $that->addErrorOutput($line);
                }
            };
        }

        $descriptors = array(array('pipe', 'r'), array('pipe', 'w'), array('pipe', 'w'));

        $process = proc_open($this->commandline, $descriptors, $pipes, $this->cwd, $this->env, $this->options);

        stream_set_blocking($pipes[1], false);
        stream_set_blocking($pipes[2], false);

        if (!is_resource($process)) {
            throw new \RuntimeException('Unable to launch a new process.');
        }

        if (null !== $this->stdin) {
            fwrite($pipes[0], (binary) $this->stdin);
        }
        fclose($pipes[0]);

        while (true) {
            $r = $pipes;
            $w = null;
            $e = null;

            $n = @stream_select($r, $w, $e, $this->timeout);

            if (false === $n) {
                break;
            } elseif ($n === 0) {
                proc_terminate($process);

                throw new \RuntimeException('The process timed out.');
            } elseif ($n > 0) {
                $called = false;

                while (true) {
                    $c = false;
                    if ($line = (binary) fgets($pipes[1], 1024)) {
                        $called = $c = true;
                        call_user_func($callback, 'out', $line);
                    }

                    if ($line = fgets($pipes[2], 1024)) {
                        $called = $c = true;
                        call_user_func($callback, 'err', $line);
                    }

                    if (!$c) {
                        break;
                    }
                }

                if (!$called) {
                    break;
                }
            }
        }

        $this->status = proc_get_status($process);

        proc_close($process);

        if ($this->status['signaled']) {
            throw new \RuntimeException(sprintf('The process stopped because of a "%s" signal.', $this->status['stopsig']));
        }

        return $this->exitcode = $this->status['exitcode'];
    }

    /**
     * Returns the output of the process (STDOUT).
     *
     * This only returns the output if you have not supplied a callback
     * to the run() method.
     *
     * @return string The process output
     */
    public function getOutput()
    {
        return $this->stdout;
    }

    /**
     * Returns the error output of the process (STDERR).
     *
     * This only returns the error output if you have not supplied a callback
     * to the run() method.
     *
     * @return string The process error output
     */
    public function getErrorOutput()
    {
        return $this->stderr;
    }

    /**
     * Returns the exit code returned by the process.
     *
     * @return integer The exit status code
     */
    public function getExitCode()
    {
        return $this->exitcode;
    }

    /**
     * Checks if the process ended successfully.
     *
     * @return Boolean true if the process ended successfully, false otherwise
     */
    public function isSuccessful()
    {
        return 0 == $this->exitcode;
    }

    /**
     * Returns true if the child process has been terminated by an uncaught signal.
     *
     * It always returns false on Windows.
     *
     * @return Boolean
     */
    public function hasBeenSignaled()
    {
        return $this->status['signaled'];
    }

    /**
     * Returns the number of the signal that caused the child process to terminate its execution.
     *
     * It is only meaningful if hasBeenSignaled() returns true.
     *
     * @return integer
     */
    public function getTermSignal()
    {
        return $this->status['termsig'];
    }

    /**
     * Returns true if the child process has been stopped by a signal.
     *
     * It always returns false on Windows.
     *
     * @return Boolean
     */
    public function hasBeenStopped()
    {
        return $this->status['stopped'];
    }

    /**
     * Returns the number of the signal that caused the child process to stop its execution
     *
     * It is only meaningful if hasBeenStopped() returns true.
     *
     * @return integer
     */
    public function getStopSignal()
    {
        return $this->status['stopsig'];
    }

    public function addOutput($line)
    {
        $this->stdout .= $line;
    }

    public function addErrorOutput($line)
    {
        $this->stderr .= $line;
    }
}


text:
/* This program generates a random number between 1 and 15
    and the user has to guess the number within three attempts
---------------------------------------------------------*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <ctype.h>

int main()
{
    time_t sek;
    char run;
    unsigned int number;
    unsigned int guess;
    unsigned int attempts;

    do {
        time(&sek);
        srand((unsigned) sek);
        number = rand() % 15 + 1;
        attempts = 0;

        while(attempts < 3)
        {
            ++attempts;
            printf("Your guess: ");
            scanf("%d", &guess);
            fflush(stdin);

            if(guess == number)
            {
                printf("Congratiolation, it\'s correct!\n");
                break;
            }
            else if(attempts == 3)
                printf("Bad luck! Number was: %d\n", number);
            else if(guess > number)
                printf("Your guess is too big.\n");
            else if(guess < number)
                printf("Your guess is too small.\n");
        }
        printf("Another run? (Y/N): ");
        scanf("%c", &run);
        fflush(stdin);
        run = toupper(run);
    } while(run == 'Y');
}


text:
var inspectBasis = basis;
var inspectBasisDomEvent = inspectBasis.require('basis.dom.event');

var Value = require('basis.data').Value;
var Node = require('basis.ui').Node;
var MoveableElement = require('basis.dragdrop').MoveableElement;
var templateInspector = resource('./inspector/template.js');

var currentInspector = new Value({
  handler: {
    change: function(sender, oldValue){
      if (oldValue)
        oldValue.stopInspect();
      if (this.value)
        this.value.startInspect();
    }
  }
});
var inspectMode = currentInspector.as(Boolean);
var currentInspectorName = currentInspector.as(function(inspector){
  return inspector ? inspector.name : '';
});

templateInspector.ready(function(inspector){
  inspector.inspectMode.link(null, function(value){
    if (value)
      currentInspector.set(inspector);
    else
      if (currentInspector.value === inspector)
        currentInspector.set();
  });
});

//
// panel
//

var isOnline;

if (typeof basisjsToolsFileSync != 'undefined')
{
  // new basisjs-tools
  isOnline = new basis.Token(basisjsToolsFileSync.isOnline.value);
  basisjsToolsFileSync.isOnline.attach(isOnline.set, isOnline);
}
else
{
  // old basisjs-tools
  isOnline = inspectBasis.devtools && Value.from(inspectBasis.devtools.serverState, 'update', 'data.isOnline');
}

var panel = new Node({
  container: document.body,
  activated: false,

  template: resource('./template/panel.tmpl'),
  binding: {
    activated: 'activated',
    isOnline: isOnline,
    inspectMode: inspectMode,
    inspector: currentInspectorName,
    inspectorId: currentInspectorName.as(function(inspectorName){
      return inspectorName
        ? inspectorName.replace(/\s/g, '').toLowerCase()
        : '';
    })
  },
  action: {
    inspectTemplate: function(e){
      e.die();
      currentInspector.set(templateInspector());
    },
    storePosition: function(){
      if (localStorage)
        localStorage['basis-devpanel'] = parseInt(this.element.style.left) + ';' + parseInt(this.element.style.top);
    },
    cancelInspect: function(){
      currentInspector.set();
    },
    reload: function(){
      global.location.reload();
    }
  },

  init: function(){
    Node.prototype.init.call(this);

    this.dde = new MoveableElement();
  },
  templateSync: function(){
    Node.prototype.templateSync.call(this);

    this.dde.setElement(this.element, this.tmpl.dragElement);
  },
  destroy: function(){
    this.dde.destroy();
    this.dde = null;

    Node.prototype.destroy.call(this);
  }
});

//
// drag stuff
//
if (typeof localStorage != 'undefined')
{
  var position = (localStorage['basis-devpanel'] || '10;10').split(';');
  panel.element.style.left = position[0] + 'px';
  panel.element.style.top = position[1] + 'px';
}

//
// exports
//

module.exports = panel;


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>PFG Algoritmos Geneticos</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <link rel="stylesheet" href="./assets/css/bootstrap.css" media="screen">
    <link rel="stylesheet" href="./assets/css/bootswatch.min.css">
    <link rel="shortcut icon" href="http://portal.uned.es/favicon.png" />

    <link rel="stylesheet" href="./bower_components/font-awesome/css/font-awesome.min.css">
    <link rel="stylesheet" href="./assets/css/ekko-lightbox.min.css">

          PFGAE
          <button class="navbar-toggle" type="button" data-toggle="collapse" data-target="#navbar-main" style="border-color:#ECF0F1">

          </button>

              	  Documentos

Anteproyecto

Memoria

                Instrucciones

                Ejecutar

                Pruebas Empíricas

Ejecución

          <form class="form-horizontal" id="theForm">
            <fieldset>
              <legend>Elección de Parámetros</legend>

                Tamaño de la Población

                  <input type="text" class="form-control" value="500" name="tamaño.poblacion" id="poblacion">

                Generaciones

                  <input type="text" class="form-control" value="60" id="generaciones" name="generaciones">

                Función

                  <select class="form-control" id="selectFuncion" name="funcion">
                    <optgroup label="Multidimensionales">
                      <option selected="selected">Rastrigin</option>
                      <option>Griewank</option>
                      <option>Ackley</option>
                      <option>Schwefel</option>
                    </optgroup>
                    <optgroup label="Dos Dimensiones">
                      <option>Schaffer2</option>
                      <option>Schubert</option>
                    </optgroup>
                  </select>

                Dimensión

                  <input type="text" class="form-control" value="10" id="dimension" name="dimension.funcion">

              <legend>Elección de Operadores</legend>

                Recombinación

                  <select class="form-control" id="selectRecombinacion" name="recombinacion">
                    <optgroup label="Discretas">
                      <option selected="selected">DiscretaBGA</option>
                      <option>UnPunto</option>
                    </optgroup>
                    <optgroup label="Aritméticas">
                      <option>AlphaBeta</option>
                      <option>K</option>
                      <option>AritmeticaCompleta</option>
                      <option>Simple</option>
                      <option>Unica</option>
                    </optgroup>
                    <optgroup label="Otras">
                      <option>NoOp</option>
                    </optgroup>
                  </select>

                Selección de Padres

                  <select class="form-control" id="selectSeleccion" name="seleccion">
                    <option>NoOp</option>
                    <option selected="selected">Torneo</option>
                  </select>

                Mutación

                  <select class="form-control" id="selectMutacion" name="mutacion">
                    <option>NoOp</option>
                    <option selected="selected">Normal</option>
                    <option>Uniforme</option>
                  </select>

              <legend>Otros Parámetros</legend>

                Desviación

                  <input type="text" class="form-control" value="0.5" id="desviacion" name="desviacion.mutacion">

                Aplicable solamente a la Mutación Normal

                Probabilidad de Mutación

                  <input type="text" class="form-control" value="0.05" id="probMutacion" name="probabilidad.mutacion">

                    <a href="#" class="btn btn-info" title="" data-toggle="popover"
                       data-trigger="focus" data-placement="right" data-html="true"
                       data-content="Probabilidad de mutación para cada gen. Debe valer entre [0, 1]">

                Tamaño de K

                  <select class="form-control" id="selectTamanioK" name="puntos.combinacion">
                    <option selected="selected">2</option>
                    <option>3</option>
                    <option>4</option>
                    <option>5</option>
                    <option>6</option>
                    <option>7</option>
                    <option>8</option>
                    <option>9</option>
                    <option>10</option>
                  </select>

                Aplicable solamente a la Recombinación K

                Tamaño del Torneo

                  <input type="text" class="form-control" value="2" id="desviacion" name="tamaño.torneo">

                Aplicable solamente a la Selección por Torneo

                Alpha

                  <input type="text" class="form-control" value="0.1" id="alpha" name="alpha">

                Beta

                  <input type="text" class="form-control" value="0.3" id="beta" name="beta">

                  <button type="reset" class="btn btn-default" onClick="window.location.reload()">Cancelar</button>
                  <button id="ejecutar" type="submit" class="btn btn-primary">Ejecutar</button>

            </fieldset>
          </form>

Ir hacia arriba

Realizado por el Alumno Fermin Silva.

Dirigido por el Prof. Severino Fernández Galán.

Basado en Bootstrap. Iconos de Font Awesome. Web fonts de Google.


text:
import macro from 'vtk.js/Sources/macros';
import vtkWebGPUTexture from 'vtk.js/Sources/Rendering/WebGPU/Texture';
import vtkWebGPURenderEncoder from 'vtk.js/Sources/Rendering/WebGPU/RenderEncoder';
import vtkWebGPUShaderCache from 'vtk.js/Sources/Rendering/WebGPU/ShaderCache';
import vtkRenderPass from 'vtk.js/Sources/Rendering/SceneGraph/RenderPass';
import vtkWebGPUFullScreenQuad from 'vtk.js/Sources/Rendering/WebGPU/FullScreenQuad';

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

const oitpFragTemplate = `
//VTK::Mapper::Dec

//VTK::TCoord::Dec

//VTK::RenderEncoder::Dec

//VTK::IOStructs::Dec

@fragment
fn main(
//VTK::IOStructs::Input
)
//VTK::IOStructs::Output
{
  var output: fragmentOutput;

  var tcoord: vec2<i32> = vec2<i32>(i32(input.fragPos.x), i32(input.fragPos.y));
  var reveal: f32 = textureLoad(oitpAccumTexture, tcoord, 0).r;
  if (reveal == 1.0) { discard; }
  var tcolor: vec4<f32> = textureLoad(oitpColorTexture, tcoord, 0);
  var total: f32 = max(tcolor.a, 0.01);
  var computedColor: vec4<f32> = vec4<f32>(tcolor.r/total, tcolor.g/total, tcolor.b/total, 1.0 - reveal);

  //VTK::RenderEncoder::Impl
  return output;
}
`;

function vtkWebGPUOrderIndependentTranslucentPass(publicAPI, model) {
  // Set our className
  model.classHierarchy.push('vtkWebGPUOrderIndependentTranslucentPass');

  // this pass implements a forward rendering pipeline
  // if both volumes and opaque geometry are present
  // it will mix the two together by capturing a zbuffer
  // first
  publicAPI.traverse = (renNode, viewNode) => {
    if (model.deleted) {
      return;
    }

    // we just render our delegates in order
    model.currentParent = viewNode;

    const device = viewNode.getDevice();

    if (!model.translucentRenderEncoder) {
      publicAPI.createRenderEncoder();
      publicAPI.createFinalEncoder();
      model.translucentColorTexture = vtkWebGPUTexture.newInstance({
        label: 'translucentPassColor',
      });
      model.translucentColorTexture.create(device, {
        width: viewNode.getCanvas().width,
        height: viewNode.getCanvas().height,
        format: 'rgba16float',
        /* eslint-disable no-undef */
        /* eslint-disable no-bitwise */
        usage:
          GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING,
      });
      const v1 = model.translucentColorTexture.createView('oitpColorTexture');
      model.translucentRenderEncoder.setColorTextureView(0, v1);

      model.translucentAccumulateTexture = vtkWebGPUTexture.newInstance({
        label: 'translucentPassAccumulate',
      });
      model.translucentAccumulateTexture.create(device, {
        width: viewNode.getCanvas().width,
        height: viewNode.getCanvas().height,
        format: 'r16float',
        /* eslint-disable no-undef */
        /* eslint-disable no-bitwise */
        usage:
          GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING,
      });
      const v2 =
        model.translucentAccumulateTexture.createView('oitpAccumTexture');
      model.translucentRenderEncoder.setColorTextureView(1, v2);
      model.fullScreenQuad = vtkWebGPUFullScreenQuad.newInstance();
      model.fullScreenQuad.setDevice(viewNode.getDevice());
      model.fullScreenQuad.setPipelineHash('oitpfsq');
      model.fullScreenQuad.setTextureViews(
        model.translucentRenderEncoder.getColorTextureViews()
      );
      model.fullScreenQuad.setFragmentShaderTemplate(oitpFragTemplate);
    } else {
      model.translucentColorTexture.resizeToMatch(
        model.colorTextureView.getTexture()
      );
      model.translucentAccumulateTexture.resizeToMatch(
        model.colorTextureView.getTexture()
      );
    }

    model.translucentRenderEncoder.setDepthTextureView(model.depthTextureView);
    model.translucentRenderEncoder.attachTextureViews();
    publicAPI.setCurrentOperation('translucentPass');
    renNode.setRenderEncoder(model.translucentRenderEncoder);
    renNode.traverse(publicAPI);
    publicAPI.finalPass(viewNode, renNode);
  };

  publicAPI.finalPass = (viewNode, renNode) => {
    model.translucentFinalEncoder.setColorTextureView(
      0,
      model.colorTextureView
    );
    model.translucentFinalEncoder.attachTextureViews();

    model.translucentFinalEncoder.begin(viewNode.getCommandEncoder());
    renNode.scissorAndViewport(model.translucentFinalEncoder);
    model.fullScreenQuad.prepareAndDraw(model.translucentFinalEncoder);
    model.translucentFinalEncoder.end();
  };

  publicAPI.getTextures = () => [
    model.translucentColorTexture,
    model.translucentAccumulateTexture,
  ];

  publicAPI.createRenderEncoder = () => {
    model.translucentRenderEncoder = vtkWebGPURenderEncoder.newInstance({
      label: 'translucentRender',
    });
    const rDesc = model.translucentRenderEncoder.getDescription();
    rDesc.colorAttachments = [
      {
        view: undefined,
        clearValue: [0.0, 0.0, 0.0, 0.0],
        loadOp: 'clear',
        storeOp: 'store',
      },
      {
        view: undefined,
        clearValue: [1.0, 0.0, 0.0, 0.0],
        loadOp: 'clear',
        storeOp: 'store',
      },
    ];
    rDesc.depthStencilAttachment = {
      view: undefined,
      depthLoadOp: 'load',
      depthStoreOp: 'store',
    };

    model.translucentRenderEncoder.setReplaceShaderCodeFunction((pipeline) => {
      const fDesc = pipeline.getShaderDescription('fragment');
      fDesc.addOutput('vec4<f32>', 'outColor');
      fDesc.addOutput('f32', 'outAccum');
      fDesc.addBuiltinInput('vec4<f32>', '@builtin(position) fragPos');
      let code = fDesc.getCode();

      code = vtkWebGPUShaderCache.substitute(
        code,
        '//VTK::RenderEncoder::Impl',
        [
          // very simple depth weighting in w z ranges from 1.0 near to 0.0
          'var w: f32 = computedColor.a * pow(0.1 + input.fragPos.z, 2.0);',
          'output.outColor = vec4<f32>(computedColor.rgb*w, w);',
          'output.outAccum = computedColor.a;',
        ]
      ).result;
      fDesc.setCode(code);
    });
    model.translucentRenderEncoder.setPipelineHash('oitpr');
    model.translucentRenderEncoder.setPipelineSettings({
      primitive: { cullMode: 'none' },
      depthStencil: {
        depthWriteEnabled: false,
        depthCompare: 'greater',
        format: 'depth32float',
      },
      fragment: {
        targets: [
          {
            format: 'rgba16float',
            blend: {
              color: {
                srcFactor: 'one',
                dstFactor: 'one',
              },
              alpha: { srcfactor: 'one', dstFactor: 'one' },
            },
          },
          {
            format: 'r16float',
            blend: {
              color: {
                srcFactor: 'zero',
                dstFactor: 'one-minus-src',
              },
              alpha: { srcfactor: 'one', dstFactor: 'one-minus-src-alpha' },
            },
          },
        ],
      },
    });
  };

  publicAPI.createFinalEncoder = () => {
    model.translucentFinalEncoder = vtkWebGPURenderEncoder.newInstance({
      label: 'translucentFinal',
    });
    model.translucentFinalEncoder.setDescription({
      colorAttachments: [
        {
          view: null,
          loadOp: 'load',
          storeOp: 'store',
        },
      ],
    });
    model.translucentFinalEncoder.setReplaceShaderCodeFunction((pipeline) => {
      const fDesc = pipeline.getShaderDescription('fragment');
      fDesc.addOutput('vec4<f32>', 'outColor');
      fDesc.addBuiltinInput('vec4<f32>', '@builtin(position) fragPos');
      let code = fDesc.getCode();
      code = vtkWebGPUShaderCache.substitute(
        code,
        '//VTK::RenderEncoder::Impl',
        ['output.outColor = vec4<f32>(computedColor.rgb, computedColor.a);']
      ).result;
      fDesc.setCode(code);
    });
    model.translucentFinalEncoder.setPipelineHash('oitpf');
    model.translucentFinalEncoder.setPipelineSettings({
      primitive: { cullMode: 'none' },
      fragment: {
        targets: [
          {
            format: 'rgba16float',
            blend: {
              color: {
                srcFactor: 'src-alpha',
                dstFactor: 'one-minus-src-alpha',
              },
              alpha: { srcfactor: 'one', dstFactor: 'one-minus-src-alpha' },
            },
          },
        ],
      },
    });
  };
}

// ----------------------------------------------------------------------------
// Object factory
// ----------------------------------------------------------------------------

const DEFAULT_VALUES = {
  colorTextureView: null,
  depthTextureView: null,
};

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

export function extend(publicAPI, model, initialValues = {}) {
  Object.assign(model, DEFAULT_VALUES, initialValues);

  // Build VTK API
  vtkRenderPass.extend(publicAPI, model, initialValues);

  macro.setGet(publicAPI, model, ['colorTextureView', 'depthTextureView']);

  // Object methods
  vtkWebGPUOrderIndependentTranslucentPass(publicAPI, model);
}

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

export const newInstance = macro.newInstance(
  extend,
  'vtkWebGPUOrderIndependentTranslucentPass'
);

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

export default { newInstance, extend };


text:
class CreateTaxes < ActiveRecord::Migration
  def change
    create_table :taxes do |t|
      t.string :name
      t.decimal :rate, precision: 5, scale: 2

      t.timestamps null: false
    end
  end
end


text:
/**
 * This task builds OpenLayers with the Closure Compiler.
 */
var path = require('path');

var async = require('async');
var closure = require('@camptocamp/closure-util');
var fs = require('fs-extra');
var nomnom = require('nomnom');
var exec = require('child_process').exec;

var generateExports = require('./generate-exports');

var log = closure.log;
var root = path.join(__dirname, '..');

/**
 * Assert that a provided config object is valid.
 * @param {Object} config Build configuration object.
 * @param {function(Error)} callback Called with an error if config is invalid.
 */
function assertValidConfig(config, callback) {
  process.nextTick(function() {
    if (!Array.isArray(config.exports)) {
      callback(new Error('Config missing "exports" array'));
      return;
    }
    if (config.namespace && typeof config.namespace !== 'string') {
      callback(new Error('Config "namespace" must be a string'));
      return;
    }
    if (config.compile && typeof config.compile !== 'object') {
      callback(new Error('Config "compile" must be an object'));
      return;
    }
    if (config.jvm && !Array.isArray(config.jvm)) {
      callback(new Error('Config "jvm" must be an array'));
      return;
    }
    if (config.src && !Array.isArray(config.src)) {
      callback(new Error('Config "src" must be an array'));
      return;
    }
    callback(null);
  });
}

/**
 * Read the build configuration file.
 * @param {string} configPath Path to config file.
 * @param {function(Error, Object)} callback Callback.
 */
function readConfig(configPath, callback) {
  fs.readFile(configPath, function(err, data) {
    if (err) {
      if (err.code === 'ENOENT') {
        err = new Error('Unable to find config file: ' + configPath);
      }
      callback(err);
      return;
    }
    var config;
    try {
      config = JSON.parse(String(data));
    } catch (err2) {
      callback(new Error('Trouble parsing config as JSON: ' + err2.message));
      return;
    }
    callback(null, config);
  });
}

/**
 * Write the exports code to dist/exports.js.
 * @param {string} exports Exports code.
 * @param {function(Error, string)} callback Called with the path to the temp
 *     file (or any error).
 */
function writeExports(exports, callback) {
  var path = 'dist/exports.js';
  log.verbose('build', 'Writing exports: to ' + path);
  fs.writeFile(path, exports, function(err) {
    if (err) {
      callback(err);
    } else {
      callback(null, path)
    }
  });
}

/**
 * Get the list of sources sorted in dependency order.
 * @param {Object} config Build configuration object.
 * @param {string} exports Exports code (with goog.exportSymbol calls).
 * @param {function(Error, Array.<string>)} callback Called with a list of paths
 *     or any error.
 */
function getDependencies(config, exports, callback) {
  writeExports(exports, function(err, exportsPath) {
    if (err) {
      callback(err);
      return;
    }
    log.info('ol-cesium', 'Parsing dependencies');
    var options;
    if (config.src) {
      options = {
        lib: config.src,
        cwd: config.cwd
      };
    } else {
      options = {
        lib: ['src/**/*.js'],
        cwd: root
      };
    }
    closure.getDependencies(options, function(err, paths) {
      if (err) {
        callback(err);
        return;
      }
      paths.push(exportsPath);
      callback(null, paths);
    });
  });
}

/**
 * Concatenate all sources.
 * @param {Array.<string>} paths List of paths to source files.
 * @param {function(Error, string)} callback Called with the concatenated
 *     output or any error.
 */
function concatenate(paths, callback) {
  async.map(paths, fs.readFile, function(err, results) {
    if (err) {
      var msg = 'Trouble concatenating sources.  ' + err.message;
      callback(new Error(msg));
    } else {
      var preamble = 'var CLOSURE_NO_DEPS = true;\n';
      callback(null, preamble + results.join('\n'));
    }
  });
}

/**
 * Run the compiler.
 * @param {Object} config Build configuration object.
 * @param {Array.<string>} paths List of paths to source files.
 * @param {function(Error, string)} callback Called with the compiled output or
 *     any error.
 */
function build(config, paths, callback) {
  var options = {
    compile: config.compile,
    cwd: config.cwd || root,
    jvm: config.jvm
  };
  if (!options.compile) {
    log.info('ol-cesium', 'No compile options found.  Concatenating ' +
        paths.length + ' sources');
    concatenate(paths, callback);
  } else {
    log.info('ol-cesium', 'Compiling ' + paths.length + ' sources');
    paths = paths.concat('node_modules/openlayers/src/ol/typedefs.js');
    options.compile.js = paths.concat(options.compile.js || []);
    closure.compile(options, callback);
  }
}

/**
 * Adds a file header with the most recent Git tag.
 * @param {string} compiledSource The compiled library.
 * @param {function(Error, string)} callback Called with the output
 *     ready to be written into a file, or any error.
 */
function addHeader(compiledSource, callback) {
  exec('git describe --tags', function(error, stdout, stderr) {
    var header = '// Ol-Cesium. See https://github.com/openlayers/ol-cesium/\n';
    header += '// License: https://github.com/openlayers/ol-cesium/blob/master/LICENSE\n';
    if (stdout !== '') {
      header += '// Version: ' + stdout + '\n';
    }
    callback(null, header + compiledSource);
  });
}

/**
 * Generate a build of the library.
 * @param {Object} config Build configuration object.  Must have an "exports"
 *     array and a "compile" object with options for the compiler.
 * @param {function(Error, string)} callback Called with the compiled source
 *     or any error.
 */
function main(config, callback) {
  async.waterfall([
    assertValidConfig.bind(null, config),
    generateExports.bind(null, config),
    getDependencies.bind(null, config),
    build.bind(null, config),
    addHeader
  ], callback);
}

/**
 * If running this module directly, read the config file and call the main
 * function.
 */
if (require.main === module) {
  var options = nomnom.options({
    config: {
      position: 0,
      required: true,
      help: 'Path to JSON config file'
    },
    output: {
      position: 1,
      required: true,
      help: 'Output file path'
    },
    loglevel: {
      abbr: 'l',
      choices: ['silly', 'verbose', 'info', 'warn', 'error'],
      default: 'info',
      help: 'Log level',
      metavar: 'LEVEL'
    }
  }).parse();

  /**
   * Set the log level.
   * @type {string}
   */
  log.level = options.loglevel;

  // read the config, run the main function, and write the output file
  async.waterfall([
    readConfig.bind(null, options.config),
    main,
    fs.outputFile.bind(fs, options.output)
  ], function(err) {
    if (err) {
      log.error(err.message);
      process.exit(1);
    } else {
      process.exit(0);
    }
  });
}

/**
 * Export main function.
 */
module.exports = main;


text:
// Copyright 2016 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package server

import (
	"context"
	"fmt"
	"strconv"
	"sync"
	"time"

	"github.com/golang/glog"
	"github.com/google/trillian"
	"github.com/google/trillian/extension"
	"github.com/google/trillian/merkle"
	"github.com/google/trillian/merkle/hashers"
	"github.com/google/trillian/merkle/smt"
	"github.com/google/trillian/monitoring"
	"github.com/google/trillian/storage"
	"github.com/google/trillian/trees"
	"github.com/google/trillian/types"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"

	stree "github.com/google/trillian/storage/tree"
)

const (
	// Used internally by GetLeaves.
	mostRecentRevision = -1
)

var (
	optsMapRead  = trees.NewGetOpts(trees.Query, trillian.TreeType_MAP)
	optsMapWrite = trees.NewGetOpts(trees.UpdateMap, trillian.TreeType_MAP)
)

// TODO(codingllama): There is no access control in the server yet and clients could easily modify
// any tree.

// TrillianMapServerOptions allows various options to be provided when creating
// a new TrillianMapServer.
type TrillianMapServerOptions struct {
	// UseSingleTransaction specifies whether updates to a map should be
	// attempted within a single transaction.
	UseSingleTransaction bool

	// UseLargePreload enables the performance workaround applied when
	// UseSingleTransaction is set.
	UseLargePreload bool
}

// TrillianMapServer implements the RPC API defined in the proto
type TrillianMapServer struct {
	trillian.UnimplementedTrillianMapServer
	registry extension.Registry
	opts     TrillianMapServerOptions

	setLeafCounter monitoring.Counter
	getLeafCounter monitoring.Counter
}

// NewTrillianMapServer creates a new RPC server backed by registry
func NewTrillianMapServer(registry extension.Registry, opts TrillianMapServerOptions) *TrillianMapServer {
	if opts.UseSingleTransaction {
		glog.Warning("Using experimental single-transaction mode for map server.")
	}
	mf := registry.MetricFactory
	if mf == nil {
		mf = monitoring.InertMetricFactory{}
	}

	return &TrillianMapServer{
		registry: registry,
		opts:     opts,
		setLeafCounter: mf.NewCounter(
			"set_leaves",
			"Number of map leaves requested to be set",
			"map_id",
		),
		getLeafCounter: mf.NewCounter(
			"get_leaves",
			"Number of map leaves request to be read",
			"map_id",
		),
	}
}

// IsHealthy returns nil if the server is healthy, error otherwise.
func (t *TrillianMapServer) IsHealthy() error {
	ctx, spanEnd := spanFor(context.Background(), "IsHealthy")
	defer spanEnd()
	return t.registry.MapStorage.CheckDatabaseAccessible(ctx)
}

// GetLeaves implements the GetLeaves RPC method.  Each requested index will
// return an inclusion proof to the leaf, or nil if the leaf does not exist.
func (t *TrillianMapServer) GetLeaves(ctx context.Context, req *trillian.GetMapLeavesRequest) (*trillian.GetMapLeavesResponse, error) {
	ctx, spanEnd := spanFor(ctx, "GetLeaves")
	defer spanEnd()
	return t.getLeavesByRevision(ctx, req.MapId, req.Index, mostRecentRevision)
}

// GetLeaf returns an inclusion proof to the leaf, or nil if the leaf does not exist.
func (t *TrillianMapServer) GetLeaf(ctx context.Context, req *trillian.GetMapLeafRequest) (*trillian.GetMapLeafResponse, error) {
	ctx, spanEnd := spanFor(ctx, "GetLeaf")
	defer spanEnd()
	ret, err := t.getLeavesByRevision(ctx, req.MapId, [][]byte{req.Index}, mostRecentRevision)
	if err != nil {
		return nil, err
	}
	if got := len(ret.MapLeafInclusion); got != 1 {
		return nil, status.Errorf(codes.Internal, "Requested 1 leaf, got %v leaves", got)
	}
	return &trillian.GetMapLeafResponse{
		MapRoot:          ret.MapRoot,
		MapLeafInclusion: ret.MapLeafInclusion[0],
	}, nil
}

// GetLeafByRevision returns an inclusion proof to the leaf, or nil if the leaf does not exist.
func (t *TrillianMapServer) GetLeafByRevision(ctx context.Context, req *trillian.GetMapLeafByRevisionRequest) (*trillian.GetMapLeafResponse, error) {
	ctx, spanEnd := spanFor(ctx, "GetLeafByRevision")
	defer spanEnd()
	ret, err := t.getLeavesByRevision(ctx, req.MapId, [][]byte{req.Index}, req.Revision)
	if err != nil {
		return nil, err
	}
	if got := len(ret.MapLeafInclusion); got != 1 {
		return nil, status.Errorf(codes.Internal, "Requested 1 leaf, got %v leaves", got)
	}
	return &trillian.GetMapLeafResponse{
		MapRoot:          ret.MapRoot,
		MapLeafInclusion: ret.MapLeafInclusion[0],
	}, nil
}

// GetLeavesByRevision implements the GetLeavesByRevision RPC method.
func (t *TrillianMapServer) GetLeavesByRevision(ctx context.Context, req *trillian.GetMapLeavesByRevisionRequest) (*trillian.GetMapLeavesResponse, error) {
	ctx, spanEnd := spanFor(ctx, "GetLeavesByRevision")
	defer spanEnd()
	if req.Revision < 0 {
		return nil, fmt.Errorf("map revision %d must be >= 0", req.Revision)
	}
	return t.getLeavesByRevision(ctx, req.MapId, req.Index, req.Revision)
}

// GetLeavesByRevisionNoProof implements the GetLeavesByRevision RPC method.
func (t *TrillianMapServer) GetLeavesByRevisionNoProof(ctx context.Context, req *trillian.GetMapLeavesByRevisionRequest) (*trillian.MapLeaves, error) {
	if req.Revision < 0 {
		return nil, fmt.Errorf("map revision %d must be >= 0", req.Revision)
	}
	tree, hasher, err := t.getTreeAndHasher(ctx, req.MapId, optsMapRead)
	if err != nil {
		return nil, fmt.Errorf("could not get map %v: %v", req.MapId, err)
	}
	if err := validateIndices(hasher.Size(), len(req.Index), func(i int) []byte { return req.Index[i] }); err != nil {
		return nil, err
	}

	tx, err := t.snapshotForTree(ctx, tree, "GetLeavesByRevisionNoProof")
	if err != nil {
		return nil, fmt.Errorf("could not create database snapshot: %v", err)
	}
	defer t.closeAndLog(ctx, tree.TreeId, tx, "GetLeavesByRevisionNoProof")

	leaves, err := tx.Get(ctx, req.Revision, req.Index)
	if err != nil {
		return nil, err
	}

	// Remove LeafHash because SetLeaves does not supply it.
	for _, l := range leaves {
		l.LeafHash = nil
	}

	return &trillian.MapLeaves{Leaves: leaves}, nil
}

func (t *TrillianMapServer) getLeavesByRevision(ctx context.Context, mapID int64, indices [][]byte, revision int64) (*trillian.GetMapLeavesResponse, error) {
	tree, hasher, err := t.getTreeAndHasher(ctx, mapID, optsMapRead)
	if err != nil {
		return nil, fmt.Errorf("could not get map %v: %v", mapID, err)
	}

	if err := validateIndices(hasher.Size(), len(indices), func(i int) []byte { return indices[i] }); err != nil {
		return nil, err
	}

	ctx = trees.NewContext(ctx, tree)
	t.getLeafCounter.Add(float64(len(indices)), strconv.FormatInt(mapID, 10))

	tx, err := t.snapshotForTree(ctx, tree, "GetLeavesByRevision")
	if err != nil {
		return nil, fmt.Errorf("could not create database snapshot: %v", err)
	}
	defer t.closeAndLog(ctx, tree.TreeId, tx, "GetLeavesByRevision")

	var root *trillian.SignedMapRoot
	if revision < 0 {
		// need to know the newest published revision
		r, err := tx.LatestSignedMapRoot(ctx)
		if err != nil {
			return nil, fmt.Errorf("could not fetch the latest SignedMapRoot: %v", err)
		}
		root = r
	} else {
		r, err := tx.GetSignedMapRoot(ctx, revision)
		if err != nil {
			return nil, fmt.Errorf("could not fetch SignedMapRoot %v: %v", revision, err)
		}
		root = r
	}

	var mapRoot types.MapRootV1
	if err := mapRoot.UnmarshalBinary(root.MapRoot); err != nil {
		return nil, err
	}
	revision = int64(mapRoot.Revision)

	// Fetch leaves and their inclusion proofs concurrently:
	wg := &sync.WaitGroup{}

	////////////////////////////////////////////////////
	// Leaves
	leavesByIndex := make(map[string]*trillian.MapLeaf)
	errCh := make(chan error, 2)
	defer close(errCh)
	wg.Add(1)
	go func() {
		defer wg.Done()

		leaves, err := tx.Get(ctx, revision, indices)
		if err != nil {
			errCh <- fmt.Errorf("could not fetch leaves: %v", err)
			return
		}
		for _, l := range leaves {
			leavesByIndex[string(l.Index)] = l
		}
		glog.V(1).Infof("%v: wanted %v leaves, found %v", mapID, len(indices), len(leaves))

		// Add empty leaf values for indices that were not returned.
		for _, index := range indices {
			if _, ok := leavesByIndex[string(index)]; !ok {
				leavesByIndex[string(index)] = &trillian.MapLeaf{Index: index}
			}
		}
	}()
	////////////////////////////////////////////////////

	////////////////////////////////////////////////////
	// Inclusion proofs
	var proofs map[string][][]byte
	wg.Add(1)
	go func() {
		defer wg.Done()

		var err error
		// Fetch inclusion proofs in parallel.
		smtReader := merkle.NewSparseMerkleTreeReader(revision, hasher, tx)
		proofs, err = smtReader.BatchInclusionProof(ctx, revision, indices)
		if err != nil {
			errCh <- fmt.Errorf("could not fetch inclusion proofs: %v", err)
		}
	}()
	////////////////////////////////////////////////////

	wg.Wait()

	select {
	case e := <-errCh:
		return nil, e
	default:
		{
		}
	}

	if err := tx.Commit(ctx); err != nil {
		return nil, fmt.Errorf("could not commit db transaction: %v", err)
	}

	inclusions := make([]*trillian.MapLeafInclusion, len(indices))
	for i, index := range indices {
		inclusions[i] = &trillian.MapLeafInclusion{
			Leaf:      leavesByIndex[string(index)],
			Inclusion: proofs[string(index)],
		}
	}

	return &trillian.GetMapLeavesResponse{
		MapLeafInclusion: inclusions,
		MapRoot:          root,
	}, nil
}

// SetLeaves implements the SetLeaves RPC method.
func (t *TrillianMapServer) SetLeaves(ctx context.Context, req *trillian.SetMapLeavesRequest) (*trillian.SetMapLeavesResponse, error) {
	ctx, spanEnd := spanFor(ctx, "SetLeaves")
	defer spanEnd()
	t.setLeafCounter.Add(float64(len(req.Leaves)), strconv.FormatInt(req.MapId, 10))

	if req.Revision <= 0 {
		return nil, status.Error(codes.FailedPrecondition, "revision must be > 0")
	}

	if len(req.Leaves) == 0 {
		newSMR, err := t.addRevision(ctx, req.MapId, req.Revision, req.Metadata)
		if err != nil {
			return nil, err
		}
		return &trillian.SetMapLeavesResponse{MapRoot: newSMR}, nil
	}

	tree, hasher, err := t.getTreeAndHasher(ctx, req.MapId, optsMapWrite)
	if err != nil {
		return nil, err
	}
	ctx = trees.NewContext(ctx, tree)

	if err := validateIndices(hasher.Size(), len(req.Leaves), func(i int) []byte { return req.Leaves[i].Index }); err != nil {
		return nil, err
	}

	// Overwrite/set the leaf hashes in the request and create a summary of
	// the leaf indices and new hash values.
	nodes := make([]smt.Node, 0, len(req.Leaves))
	for _, l := range req.Leaves {
		l.LeafHash = hasher.HashLeaf(tree.TreeId, l.Index, l.LeafValue)
		nodes = append(nodes, smt.Node{
			ID:   stree.NewNodeID2(string(l.Index), uint(hasher.BitLen())),
			Hash: l.LeafHash,
		})
	}

	layout, err := t.registry.MapStorage.Layout(tree)
	if err != nil {
		return nil, err
	}
	updater := &mapTreeUpdater{
		tree:     tree,
		layout:   layout,
		hasher:   hasher,
		ms:       t.registry.MapStorage,
		writeRev: req.Revision,
		singleTX: t.opts.UseSingleTransaction,
		preload:  t.opts.UseLargePreload,
	}

	var newRoot *trillian.SignedMapRoot
	err = t.registry.MapStorage.ReadWriteTransaction(ctx, tree, func(ctx context.Context, tx storage.MapTreeTX) error {
		writeRev, err := t.getWriteRevision(ctx, tree, tx, req.Revision)
		if err != nil {
			return err
		}
		glog.V(2).Infof("%v: Writing at revision %v", tree.TreeId, writeRev)

		if err := t.writeLeaves(ctx, tx, req.Leaves); err != nil {
			return err
		}
		hash, err := updater.update(ctx, tx, nodes)
		if err != nil {
			return err
		}
		if newRoot, err = t.makeSignedMapRoot(ctx, tree, hash, writeRev, req.Metadata); err != nil {
			return fmt.Errorf("makeSignedMapRoot(): %v", err)
		}
		return tx.StoreSignedMapRoot(ctx, newRoot)
	})
	if err != nil {
		return nil, err
	}
	return &trillian.SetMapLeavesResponse{MapRoot: newRoot}, nil
}

// getWriteRevision returns the revision that this transaction will be written
// at, and asserts that it corresponds to assertRev and the read revision + 1.
// Only one transaction can be committed for a given revision, so this one will
// compete with any other transactions with the same write revision.
//
// TODO(pavelkalinnikov): One of Read/WriteRevision storage calls should be
// gone really, because the +1 relation between them is fixed.
func (t *TrillianMapServer) getWriteRevision(ctx context.Context, tree *trillian.Tree, tx storage.MapTreeTX, assertRev int64) (int64, error) {
	writeRev, err := tx.WriteRevision(ctx)
	if err != nil {
		return 0, err
	}
	if writeRev != assertRev {
		return 0, status.Errorf(codes.FailedPrecondition, "can't write to revision %v", assertRev)
	}
	if readRev, err := tx.ReadRevision(ctx); err != nil {
		return 0, err
	} else if readRev+1 != writeRev {
		return 0, status.Error(codes.Internal, "read/write revisions are not consecutive")
	}
	return writeRev, nil
}

// writeLeaves updates the leaf values, but does not calculate nor update the Merkle tree.
func (t *TrillianMapServer) writeLeaves(ctx context.Context, tx storage.MapTreeTX, leaves []*trillian.MapLeaf) error {
	for _, l := range leaves {
		if err := tx.Set(ctx, l.Index, l); err != nil {
			return err
		}
	}
	return nil
}

func (t *TrillianMapServer) makeSignedMapRoot(ctx context.Context, tree *trillian.Tree,
	rootHash []byte, revision int64, meta []byte) (*trillian.SignedMapRoot, error) {
	smr := &types.MapRootV1{
		RootHash:       rootHash,
		TimestampNanos: uint64(time.Now().UnixNano()),
		Revision:       uint64(revision),
		Metadata:       meta,
	}
	signer, err := trees.Signer(ctx, tree)
	if err != nil {
		return nil, fmt.Errorf("trees.Signer(): %v", err)
	}
	root, err := signer.SignMapRoot(smr)
	if err != nil {
		return nil, fmt.Errorf("SignMapRoot(): %v", err)
	}
	return root, nil
}

// GetSignedMapRoot implements the GetSignedMapRoot RPC method.
func (t *TrillianMapServer) GetSignedMapRoot(ctx context.Context, req *trillian.GetSignedMapRootRequest) (*trillian.GetSignedMapRootResponse, error) {
	ctx, spanEnd := spanFor(ctx, "GetSignedMapRoot")
	defer spanEnd()
	tree, ctx, err := t.getTreeAndContext(ctx, req.MapId, optsMapRead)
	if err != nil {
		return nil, err
	}
	tx, err := t.snapshotForTree(ctx, tree, "GetSignedMapRoot")
	if err != nil {
		return nil, err
	}
	defer t.closeAndLog(ctx, tree.TreeId, tx, "GetSignedMapRoot")

	r, err := tx.LatestSignedMapRoot(ctx)
	if err != nil {
		return nil, err
	}

	if err := tx.Commit(ctx); err != nil {
		glog.Warningf("%v: Commit failed for GetSignedMapRoot: %v", req.MapId, err)
		return nil, err
	}

	return &trillian.GetSignedMapRootResponse{MapRoot: r}, nil
}

// GetSignedMapRootByRevision implements the GetSignedMapRootByRevision RPC
// method.
func (t *TrillianMapServer) GetSignedMapRootByRevision(ctx context.Context, req *trillian.GetSignedMapRootByRevisionRequest) (*trillian.GetSignedMapRootResponse, error) {
	ctx, spanEnd := spanFor(ctx, "GetSignedMapRootByRevision")
	defer spanEnd()
	if req.Revision < 0 {
		return nil, fmt.Errorf("map revision %d must be >= 0", req.Revision)
	}
	tree, ctx, err := t.getTreeAndContext(ctx, req.MapId, optsMapRead)
	if err != nil {
		return nil, err
	}
	tx, err := t.snapshotForTree(ctx, tree, "GetSignedMapRootByRevision")
	if err != nil {
		return nil, err
	}
	defer t.closeAndLog(ctx, tree.TreeId, tx, "GetSignedMapRootByRevision")

	r, err := tx.GetSignedMapRoot(ctx, req.Revision)
	if err != nil {
		return nil, err
	}

	if err := tx.Commit(ctx); err != nil {
		glog.Warningf("%v: Commit failed for GetSignedMapRootByRevision: %v", req.MapId, err)
		return nil, err
	}

	return &trillian.GetSignedMapRootResponse{MapRoot: r}, nil
}

func (t *TrillianMapServer) getTreeAndHasher(ctx context.Context, treeID int64, opts trees.GetOpts) (*trillian.Tree, hashers.MapHasher, error) {
	tree, err := trees.GetTree(ctx, t.registry.AdminStorage, treeID, opts)
	if err != nil {
		return nil, nil, err
	}
	th, err := hashers.NewMapHasher(tree.HashStrategy)
	if err != nil {
		return nil, nil, err
	}
	return tree, th, nil
}

func (t *TrillianMapServer) getTreeAndContext(ctx context.Context, treeID int64, opts trees.GetOpts) (*trillian.Tree, context.Context, error) {
	tree, err := trees.GetTree(ctx, t.registry.AdminStorage, treeID, opts)
	if err != nil {
		return nil, nil, err
	}
	return tree, trees.NewContext(ctx, tree), nil
}

// InitMap implements the RPC Method of the same name.
func (t *TrillianMapServer) InitMap(ctx context.Context, req *trillian.InitMapRequest) (*trillian.InitMapResponse, error) {
	ctx, spanEnd := spanFor(ctx, "InitMap")
	defer spanEnd()
	newSMR, err := t.addRevision(ctx, req.MapId, 0 /* rev */, nil /* meta */)
	if err != nil {
		return nil, err
	}
	return &trillian.InitMapResponse{Created: newSMR}, nil
}

// addRevision adds a new revision without changing the tree contents.
//
// TODO(pavelkalinnikov): Consider making it a CreateRevision RPC of the
// MapService, a more generic version of InitMap that allows creating empty
// revisions other than the 0th.
func (t *TrillianMapServer) addRevision(ctx context.Context, treeID, rev int64, meta []byte) (*trillian.SignedMapRoot, error) {
	tree, hasher, err := t.getTreeAndHasher(ctx, treeID, optsMapWrite)
	if err != nil {
		return nil, status.Errorf(codes.FailedPrecondition, "getTreeAndHasher(): %v", err)
	}
	ctx = trees.NewContext(ctx, tree)

	var newSMR *trillian.SignedMapRoot
	if err := t.registry.MapStorage.ReadWriteTransaction(ctx, tree, func(ctx context.Context, tx storage.MapTreeTX) error {
		// Check that the map has an existing root, or needs initialising.
		smr, err := tx.LatestSignedMapRoot(ctx)
		if err != nil && (err != storage.ErrTreeNeedsInit || rev != 0) {
			return status.Errorf(codes.FailedPrecondition, "LatestSignedMapRoot(): %v", err)
		}

		var hash []byte // The new root hash.
		if rev == 0 {
			if err == nil {
				return status.Error(codes.AlreadyExists, "map is already initialised")
			} // Otherwise it's ErrTreeNeedsInit.
			hash = hasher.HashEmpty(tree.TreeId, nil, hasher.BitLen())
		} else if mapRoot := smr.GetMapRoot(); mapRoot != nil {
			var root types.MapRootV1
			if err := root.UnmarshalBinary(mapRoot); err != nil {
				return status.Errorf(codes.Internal, "UnmarshalBinary: %v", err)
			}
			if got, want := root.Revision, uint64(rev-1); got != want {
				return status.Errorf(codes.FailedPrecondition, "can't write revision %d, latest is %d", rev, got)
			}
			hash = root.RootHash
		} else {
			return status.Error(codes.Internal, "LatestSignedMapRoot is nil")
		}

		if newSMR, err = t.makeSignedMapRoot(ctx, tree, hash, rev, meta); err != nil {
			return status.Errorf(codes.Internal, "makeSignedMapRoot(): %v", err)
		}
		return tx.StoreSignedMapRoot(ctx, newSMR)
	}); err != nil {
		return nil, err
	}
	return newSMR, nil
}

func (t *TrillianMapServer) closeAndLog(ctx context.Context, logID int64, tx storage.ReadOnlyMapTreeTX, op string) {
	err := tx.Close()
	if err != nil {
		glog.Warningf("%v: Close failed for %v: %v", logID, op, err)
	}
}

func (t *TrillianMapServer) snapshotForTree(ctx context.Context, tree *trillian.Tree, method string) (storage.ReadOnlyMapTreeTX, error) {
	tx, err := t.registry.MapStorage.SnapshotForTree(ctx, tree)
	if err != nil && tx != nil {
		// Special case to handle ErrTreeNeedsInit, which leaves the TX open.
		// To avoid leaking it make sure it's closed.
		defer t.closeAndLog(ctx, tree.TreeId, tx, method)
	}
	return tx, err
}

// validateIndices confirms that all indices have the given size and there are no duplicates.
// indexSize is the expected size of each index in bytes.
// n is the number of indices to check.
// indices is a function that returns indices from [0 .. n).
func validateIndices(indexSize, n int, indices func(i int) []byte) error {
	// The parameter is named 'index' (here and in the RPC API) because it's the ordinal number
	// of the leaf, but that number is obtained by hashing the key value that corresponds to the
	// leaf.  Leaf "indices" are therefore sparsely scattered in the range [0, 2^hashsize) and
	// are represented as a []byte, and every leaf must have an index that is the same size.
	//
	// We currently police this by requiring that the hash size for the index space be the same
	// as the hash size for the tree itself, although that's not strictly required (e.g. could
	// have SHA-256 for generating leaf indices, but SHA-512 for building the root hash).
	seenIndices := make(map[string]bool)
	for i := 0; i < n; i++ {
		index := indices(i)
		if got, want := len(index), indexSize; got != want {
			return status.Errorf(codes.InvalidArgument, "index at position %d has wrong length: got=%d,want=%d", i, got, want)
		}
		if seenIndices[string(index)] {
			return status.Errorf(codes.InvalidArgument, "duplicate index detected at position %d", i)
		}
		seenIndices[string(index)] = true
	}
	return nil
}


text:
layout: post
title: "Testing Video Synth Prototype"
description: "Fractals"
tags: [Electronics, testing]
comments: false
---

Testing Video synth prototype. It's running from Raspberry Pi 2 and is powered by Open Frameworks.

<video controls="controls" width="480" height="480" style="width: 100%; display: block; margin: 0 auto; background-color: black;" name="Video Name" src="/images/13056918_1723139641260216_469459794_n.mp4"></video>


text:
const toggleList = document.getElementById('toggleList');
const listDiv = document.querySelector('.list');
const descriptionInput = document.querySelector('input.description');
const descriptionP = document.querySelector('p.description');
const descriptionButton = document.querySelector('button.description');
const listUl = listDiv.querySelector('ul');
const addItemInput = document.querySelector('input.addItemInput');
const addItemButton = document.querySelector('button.addItemButton');
const lis = listUl.children;

function attachListItemButtons(li) {
  let up = document.createElement('button');
  up.className = 'up';
  up.textContent = 'Up';
  li.appendChild(up);

  let down = document.createElement('button');
  down.className = 'down';
  down.textContent = 'Down';
  li.appendChild(down);

  let remove = document.createElement('button');
  remove.className = 'remove';
  remove.textContent = 'Remove';
  li.appendChild(remove);
}

for (let i = 0; i < lis.length; i += 1) {
  attachListItemButtons(lis[i]);
}

listUl.addEventListener('click', (event) => {
  if (event.target.tagName == 'BUTTON') {
    if (event.target.className == 'remove') {
      let li = event.target.parentNode;
      let ul = li.parentNode;
      ul.removeChild(li);
    }
    if (event.target.className == 'up') {
      let li = event.target.parentNode;
      let prevLi = li.previousElementSibling;
      let ul = li.parentNode;
      if (prevLi) {
        ul.insertBefore(li, prevLi);
      }
    }
    if (event.target.className == 'down') {
      let li = event.target.parentNode;
      let nextLi = li.nextElementSibling;
      let ul = li.parentNode;
      if (nextLi) {
        ul.insertBefore(nextLi, li);
      }
    }
  }
});

toggleList.addEventListener('click', () => {
  if (listDiv.style.display == 'none') {
    toggleList.textContent = 'Hide list';
    listDiv.style.display = 'block';
  } else {
    toggleList.textContent = 'Show list';
    listDiv.style.display = 'none';
  }
});

descriptionButton.addEventListener('click', () => {
  descriptionP.innerHTML = descriptionInput.value + ':';
  descriptionInput.value = '';
});

addItemButton.addEventListener('click', () => {
  let ul = document.getElementsByTagName('ul')[0];
  let li = document.createElement('li');
  li.textContent = addItemInput.value;
  attachListItemButtons(li);
  ul.appendChild(li);
  addItemInput.value = '';
});


text:
Random wallpapers and a matching login screen

This is a collection of things that will give you some randomly picked
wallpapers to use for X11 and with SLiM (and slimlock).  It uses systemd and is
generally geared toward arch linux but I suppose you could use it elsewhere if
you want.

## Prerequisites

 - bash
 - feh
 - find
 - imagemagick
 - shuf (coreutils)
 - pgregp

## Wallpaper picking script

This script (`/usr/bin/randwall`) will read a configuration file from
`/etc/randwall.conf` and choose a random wallpaper to use.  It will resize and
crop the image to the configured resolution and save it in `/tmp/`.

## Wallpaper fetching script

This script (`/usr/bin/getwalls`) will look on reddit for wallpapers.  It uses
the same configuration script as above.

## Installation

Running `make install` should get everything put in place.  After that you will
want to enable the service with `systemctl enable randwall`.  You will also
probably want to add something to your `.xinitrc` to set the wallpaper when your
X session starts.  I use the following: `feh --bg-fill /tmp/wallpaper &`.  You
will also probably want to edit your SLiM config to use the `randwall` theme.

### Notice

SLiM will not run if you set this theme and there is no wallpaper found at
`/tmp/wallpaper`.  You can change the scripts and the theme symlink to point
elsewhere if you are worried about it.  It should work if the `randwall` service
is enabled, but it can fail if, for example, your wallpapers are stored in an
encrypted volume.

## Customization

You can customize the SLiM theme panel.  There is an SVG file of it in the
`theme` directory.  The makefile will use inkscape to make it into the png that
SLiM wants.

If you want to customize the install directories or whatever, you are on your
own.  I wish you luck.

## Preview

Here is a sample of what the login screen will look like if you happen to have
this same wallpaper as me in your list and it picks it.

![preview](https://raw.github.com/bentglasstube/randwall/master/preview.png)


text: <!doctype html>


text:
package com.yuanyu.fitapp.ui;

import java.util.ArrayList;

import com.yuanyu.fitapp.R;
import com.yuanyu.fitapp.model.Exercise.ExerciseType;

import android.content.Intent;
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.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;

public class QuickStartFragment extends Fragment implements OnClickListener, AnimationListener {

	ImageView mPlayImage;

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

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View v = inflater.inflate(R.layout.fragment_quick_start, container, false);

		mPlayImage = (ImageView) v.findViewById(R.id.fragment_quick_start_image);
		mPlayImage.setOnClickListener(this);

		return v;
	}

	@Override
	public void onClick(View v) {
		if(v.getId() == R.id.fragment_quick_start_image) {
			Animation animation = AnimationUtils.loadAnimation(getActivity(), R.anim.scale_fade);
			animation.setAnimationListener(this);
			animation.setFillAfter(true);
			v.startAnimation(animation);
		}
	}

	@Override
	public void onAnimationEnd(Animation animation) {
		quickStart();
	}

	@Override
	public void onAnimationRepeat(Animation animation) {

	}

	@Override
	public void onAnimationStart(Animation animation) {

	}

	private void quickStart() {
		// TODO, use random parameters
		Intent intent = new Intent(getActivity(), ExerciseActivity.class);
		intent.putExtra(ExerciseActivity.INTENT_KEY_NAME, getString(R.string.item_quick_start));
		intent.putExtra(ExerciseActivity.INTENT_KEY_TYPE , ExerciseType.TABATA);
		intent.putExtra(ExerciseActivity.INTENT_KEY_ACTIVITY_TIME, 20);
		intent.putExtra(ExerciseActivity.INTENT_KEY_REST_TIME, 10);
		ArrayList<String> gifList = new ArrayList<String>();
		gifList.add("situp");
		gifList.add("situp");
		intent.putStringArrayListExtra(ExerciseActivity.INTENT_KEY_GIF_LIST, gifList);
		startActivity(intent);
	}
}


text:
//
//  ObjectArray.m
//  NSObjectJSON
//
//  Created by Benjamin on 12/16/13.
//
//

#import "ObjectArray.h"

#import "NSObject+JSON.h"

@interface ObjectArray()
@property (nonatomic, strong)   NSMutableArray      *internalDataArray;
@property (nonatomic, strong)   Class               objectType;
@end

@implementation ObjectArray

- (id)initSelf {
	self = [super init];
	if (self) {
		self.internalDataArray = [[NSMutableArray alloc] init];
	}
	return self;
}

- (id)init {
	// Forbid calls to –init or +new
	NSAssert(NO, @"Cannot create instance of Singleton");
	return nil;
}

+ (id)arrayWithObjectType:(Class)type {
	ObjectArray *array = [[ObjectArray alloc] initSelf];
	array.objType = type;
	return array;
}

- (void)fillInJSONObject:(NSArray *)jsonObj {
	Class type = self.objType;
	for (id item in jsonObj) {
        if ([item isKindOfClass:[NSDictionary class]]) {
			NSObject *obj = [[type alloc] init];
			[obj fillInJSONObject:item];
			[self addObject:obj];
		} else {
			[self addObject:item];
		}
	}
}

/**
 *
 NSMutableArray, in a subclass, you must override all these methods.

 insertObject:atIndex:
 removeObjectAtIndex:
 addObject:
 removeLastObject
 replaceObjectAtIndex:withObject:

 */
#pragma mark - NSMutableArray override five primitive methods

- (void) insertObject:(id)anObject atIndex:(NSUInteger)index {
    [self.internalDataArray insertObject:anObject atIndex:index];
}

- (void) removeObjectAtIndex:(NSUInteger)index {
    [self.internalDataArray removeObjectAtIndex:index];
}

- (void) addObject:(id)anObject {
    [self.internalDataArray addObject:anObject];
}

- (void) removeLastObject {
    [self.internalDataArray removeLastObject];
}

- (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject {
    [self.internalDataArray replaceObjectAtIndex:index withObject:anObject];
}

/**
 *
 NSArray, in a subclass, you must override all these methods.

 count
 objectAtIndex:

 */
#pragma mark - NSArray override two primitive methods

- (NSUInteger)count {
    return self.internalDataArray.count;
}

- (id)objectAtIndex:(NSUInteger)index {
    return [self.internalDataArray objectAtIndex:index];
}

@end


text:
package net.kebernet.configuration.desktop;

import com.intellij.uiDesigner.core.GridConstraints;
import com.intellij.uiDesigner.core.GridLayoutManager;
import com.intellij.uiDesigner.core.Spacer;
import net.kebernet.configuration.client.app.DeviceListView;
import net.kebernet.configuration.client.model.Device;

import javax.annotation.Nonnull;
import javax.inject.Singleton;
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.logging.Logger;

/**
 * Created by rcooper on 7/3/17.
 */
@Singleton
public class DeviceListViewImpl implements DeviceListView {
    private static final Logger LOGGER = Logger.getLogger(DeviceListViewImpl.class.getCanonicalName());
    JPanel root;
    private JPanel devicePanel;
    private JLabel devicesLabel;
    private JButton refreshButton;
    private JScrollPane scrollPane;
    private Set<Device> devices = Collections.synchronizedSet(new LinkedHashSet<Device>());
    private RefreshCallback refreshCallback;
    private DeviceSelectionCallback deviceSelected;

    DeviceListViewImpl() {
        devicePanel.setLayout(new BoxLayout(devicePanel, BoxLayout.Y_AXIS));
        refreshButton.addActionListener((e) -> {
            if (refreshCallback != null) {
                refreshCallback.onRefreshClicked();
            }
        });
    }

    @Override
    public synchronized void showDeviceList(@Nonnull List<Device> devices) {
        SwingUtilities.invokeLater(() -> {
            this.devices.addAll(devices);
            render();
        });

    }

    @Override
    public synchronized void addDevicesToList(@Nonnull List<Device> devices) {
        SwingUtilities.invokeLater(() -> {
            LOGGER.info("Got devices " + devices);
            this.devices.addAll(devices);
            render();
        });
    }

    private void render() {
        devicePanel.removeAll();
        for (Device d : devices) {
            DeviceListItem item = new DeviceListItem(d);
            Color bg = item.root.getBackground();

            item.root.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    if (deviceSelected != null) {
                        deviceSelected.onDeviceSelected(d);
                    }
                }

                @Override
                public void mousePressed(MouseEvent e) {
                    item.root.setBackground(Color.DARK_GRAY);
                }

                @Override
                public void mouseReleased(MouseEvent e) {
                    item.root.setBackground(bg);
                }
            });
            devicePanel.add(item.root);
        }
        devicePanel.revalidate();
        devicePanel.repaint();
    }

    @Override
    public void setDeviceSelectionCallback(DeviceSelectionCallback callback) {
        this.deviceSelected = callback;
    }

    @Override
    public void setRefreshClicked(RefreshCallback callback) {
        this.refreshCallback = callback;
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame("DeviceListViewImpl");
        DeviceListViewImpl impl = new DeviceListViewImpl();
        frame.setContentPane(impl.root);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setSize(640, 480);
        frame.setVisible(true);
    }

    {
// GUI initializer generated by IntelliJ IDEA GUI Designer
// >>> IMPORTANT!! <<<
// DO NOT EDIT OR ADD ANY CODE HERE!
        $$$setupUI$$$();
    }

    /**
     * Method generated by IntelliJ IDEA GUI Designer
     * >>> IMPORTANT!! <<<
     * DO NOT edit this method OR call it in your code!
     *
     * @noinspection ALL
     */
    private void $$$setupUI$$$() {
        root = new JPanel();
        root.setLayout(new GridLayoutManager(2, 3, new Insets(8, 8, 8, 8), -1, -1));
        scrollPane = new JScrollPane();
        root.add(scrollPane, new GridConstraints(1, 0, 1, 3, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, null, null, null, 0, false));
        devicePanel = new JPanel();
        devicePanel.setLayout(new GridLayoutManager(1, 1, new Insets(8, 8, 8, 8), -1, -1));
        scrollPane.setViewportView(devicePanel);
        refreshButton = new JButton();
        refreshButton.setText("Refresh");
        root.add(refreshButton, new GridConstraints(0, 2, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
        final Spacer spacer1 = new Spacer();
        root.add(spacer1, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, 1, null, null, null, 0, false));
        devicesLabel = new JLabel();
        devicesLabel.setText("Devices");
        root.add(devicesLabel, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
    }

    /**
     * @noinspection ALL
     */
    public JComponent $$$getRootComponent$$$() {
        return root;
    }
}


text:
[![Code Climate](https://codeclimate.com/repos/54b886b869568018bf0001d5/badges/6ce69715f7e4dea39724/gpa.svg)](https://codeclimate.com/repos/54b886b869568018bf0001d5/feed) Code Quality

[![Codeship Status for davidacji/super-zapatos](https://codeship.com/projects/5385e390-7fa1-0132-fa27-6afafd33df4f/status?branch=master)](https://codeship.com/projects/57302) Continuous Integration

[![Test Coverage](https://codeclimate.com/repos/54b886b869568018bf0001d5/badges/6ce69715f7e4dea39724/coverage.svg)](https://codeclimate.com/repos/54b886b869568018bf0001d5/feed) Test Coverage

# super-zapatos

This application is for the company "Super Zapatos".

it's a Simple CRUD application for two tables: Articles and Stores.

The application also acts as a REST Backend Service for an Android application.

The services respond with both JSON and XML. The XML implementation has a lower priority.

## Data Base Structure

The following is the database tables structure:

### stores

An establishment for sale of shoes or any other merchandise offered by the company "Super Zapatos"

| Column   |      Type     |  Constraints                     |
|----------|:-------------:|:-------------:|---------------------------------:|
| id       |  integer      | (PK) uniq: true, null: false     |
| name     |  string       | uniq: true, null: false          |
| address  |  text         | null: false                      |

### articles

Any merchandise offered by the company "Super Zapatos" like shoes or boots

Note: In Rails, the :decimal type is returned as BigDecimal, which is great for price calculation if needed at some point of the project.

| Column          | Type          |  Constraints                             |
|-----------------|:-------------:|:-------------:|-----------------------------------------:|
| id              | integer       |  (PK) uniq: true, null: false            |
| name            | string        |  uniq: (by store), null: false           |
| description     | text          |                                          |
| price           | decimal       |  precision: 8, scale: 2, null: false     |
| total_in_shelf  | integer       |  default: 0, null: false                 |
| total_in_vault  | integer       |  default: 0, null: false                 |
| store_id        | integer       |  (FK) null: false                        |

## System dependencies

* rvm (Optional, but preferably use it. More information at https://rvm.io/rvm/install)
* postgresql (SQLite added in development if needed)
* rubygems
* bundler

## Environment

* Programming Language:   Ruby 2.1.5
* Framework:              Rails 4.2.0
* Database:               PostgreSQL
* Version Control System: git
* Repository:             https://davidacji@github.com/davidacji/super-zapatos.git
* Test Suit:              Rspec
* Deployment:             Capistrano

## Configuration

Rails 4.2.0 generates a new secrets.yml file in the config folder. By default, this file contains the application's secret_key_base, but it could also be used to store other secrets such as access keys for external APIs.

The secrets added to this file are accessible via Rails.application.secrets. For example, with the following config/secrets.yml:

```yml
  development:
    secret_key_base: 3b7cd727ee24e8444053437c36cc66c3
    some_api_key: SOMEKEY
```

Rails.application.secrets.some_api_key returns SOMEKEY in the development environment.

The database.yml were removed from the version control, in order to prevent security issues in the repository.

Copy the config/database.yml.bak to the config/ folder and fill it out. Also be sure that the content of the secrets yml is valid

## Database creation

Be sure to fill the correct information in your database.yml file and run:

* rake db:create
* rake db:schema:load

## Database initialization

In order to fill the database with basic data run:

* rake db:seed

## How to run the test suite

Be sure to fill the correct information in your database.yml file in the testing and run:

* rake db:test:prepare (although this command is deprecated in rails 4 it may be useful when the test database has an unexpected behavior)
* rspec spec

## Services (job queues, cache servers, search engines, etc.)

The application isn't using background processing, cache server or search engines by the time.

## Notes

* HAML is used by default on this app
* Foundation and SimpleForm was added because they play nicely together and they make the development easy