text:
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace Linq2Azure.TrafficManagement
{
    public class TrafficManagerMonitor
    {
        /// Right now, the Azure management server doesn't anything other than the default value here.
        public int IntervalInSeconds { get; set; }

        /// Right now, the Azure management server doesn't anything other than the default value here.
        public int TimeoutInSeconds { get; set; }

        public int ToleratedNumberOfFailures { get; set; }
        public MonitorProtocol Protocol { get; set; }
        public int Port { get; set; }
        public TrafficManagerHttpOptions HttpOptions { get; set; }

        public TrafficManagerMonitor()
        {
            IntervalInSeconds = 30;
            TimeoutInSeconds = 10;
            ToleratedNumberOfFailures = 3;
        }

        public TrafficManagerMonitor(int port, TrafficManagerHttpOptions httpOptions) : this()
        {
            Port = port;
            HttpOptions = httpOptions;
        }

        internal TrafficManagerMonitor(XElement xml)
        {
            var ns = XmlNamespaces.WindowsAzure;
            xml.HydrateObject(ns, this);
            HttpOptions = new TrafficManagerHttpOptions(xml.Element(ns + "HttpOptions"));
        }

        internal XElement ToXml()
        {
            var ns = XmlNamespaces.WindowsAzure;
            return new XElement(ns + "Monitor",
                new XElement(ns + "IntervalInSeconds", IntervalInSeconds),
                new XElement(ns + "TimeoutInSeconds", TimeoutInSeconds),
                new XElement(ns + "ToleratedNumberOfFailures", ToleratedNumberOfFailures),
                new XElement(ns + "Protocol", Protocol.ToString()),
                new XElement(ns + "Port", Port),
                HttpOptions.ToXml());
        }
    }

    public class TrafficManagerHttpOptions
    {
        public string RelativePath { get; set; }
        public string Verb { get; set; }
        public int ExpectedStatusCode { get; set; }

        public TrafficManagerHttpOptions()
        {
            Verb = "GET";
            ExpectedStatusCode = 200;
        }

        public TrafficManagerHttpOptions(string relativePath) : this()
        {
            RelativePath = relativePath;
        }

        internal TrafficManagerHttpOptions(XElement xml)
        {
            xml.HydrateObject(XmlNamespaces.WindowsAzure, this);
        }

        internal XElement ToXml()
        {
            var ns = XmlNamespaces.WindowsAzure;
            return new XElement(ns + "HttpOptions",
                new XElement(ns + "Verb", Verb),
                new XElement(ns + "RelativePath", RelativePath),
                new XElement(ns + "ExpectedStatusCode", ExpectedStatusCode));
        }
    }

    public enum MonitorProtocol { HTTP, HTTPS }
}


text:
/*
 * Maintained by brightSPARK Labs.
 * www.brightsparklabs.com
 *
 * Refer to LICENSE at repository root for license details.
 */

package com.brightsparklabs.asanti.reader.parser;

import static com.google.common.base.Preconditions.*;

import com.brightsparklabs.asanti.model.schema.AsnModuleTaggingMode;
import com.brightsparklabs.asanti.model.schema.AsnSchemaModule;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import java.text.ParseException;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Logic for parsing a module within an ASN.1 schema
 *
 * @author brightSPARK Labs
 */
public class AsnSchemaModuleParser {
    // -------------------------------------------------------------------------
    // CONSTANTS
    // -------------------------------------------------------------------------

    /** pattern to match a simple type definition (one with no parameterization) */
    private static final Pattern PATTERN_TYPE_DEFINITION_SIMPLE =
            Pattern.compile("^([A-Za-z0-9\\-]+) ?::= ?(.+)");

    /** pattern to match a parameterized type definition */
    private static final Pattern PATTERN_TYPE_DEFINITION_PARAMETERIZED =
            Pattern.compile("^(([A-Za-z0-9\\-]+(\\{[A-Za-z0-9\\-:, ]+\\})?)+) ?::= ?(.+)");

    /** pattern to match a value assignment */
    private static final Pattern PATTERN_VALUE_ASSIGNMENT =
            Pattern.compile(
                    "^(([A-Za-z0-9\\-]+(\\{[A-Za-z0-9\\-:, ]+\\})?)+( [A-Za-z0-9\\-]+)+) ?::= ?(.+)");

    /** pattern to find the module level tagging mode */
    private static final Pattern PATTERN_DEFINITIONS = Pattern.compile("(([A-Z]+)( TAGS) ?::= ?)");

    /** error message if schema is missing header keywords */
    private static final String ERROR_MISSING_HEADERS =
            "Schema does not contain all expected module headers";

    /** error message if schema is missing content */
    private static final String ERROR_MISSING_CONTENT =
            "Schema does not contain any information within the 'BEGIN' and 'END' keywords";

    /** error message if a type definition or value assignment is not found */
    private static final String ERROR_UNKNOWN_CONTENT =
            "Parser expected a type definition or value assignment but found: ";

    // -------------------------------------------------------------------------
    // CLASS VARIABLES
    // -------------------------------------------------------------------------

    /** class logger */
    private static final Logger logger = LoggerFactory.getLogger(AsnSchemaModuleParser.class);

    // -------------------------------------------------------------------------
    // PUBLIC METHODS
    // -------------------------------------------------------------------------

    /**
     * Parses the supplied module from an ASN.1 schema
     *
     * @param moduleText all text from module within the ASN.1 schema
     * @return an {@link com.brightsparklabs.asanti.model.schema.AsnSchemaModule.Builder}
     *     representing the parsed data
     * @throws NullPointerException if {@code moduleText} is {@code null}
     * @throws ParseException if any errors occur while parsing the module
     */
    public static AsnSchemaModule.Builder parse(Iterable<String> moduleText) throws ParseException {
        checkNotNull(moduleText);

        final Iterator<String> iterator = moduleText.iterator();
        final AsnSchemaModule.Builder moduleBuilder = AsnSchemaModule.builder();
        AsnModuleTaggingMode taggingMode = parseHeader(iterator, moduleBuilder);
        parseBody(iterator, moduleBuilder, taggingMode);

        return moduleBuilder;
    }

    // -------------------------------------------------------------------------
    // PRIVATE METHODS
    // -------------------------------------------------------------------------

    /**
     * Parses the module header. This data is located before the 'BEGIN' keyword.
     *
     *
Prior to calling this method, the iterator should be pointing at the first line of the
     * schema file, or the line containing 'END' of the previous module. I.e. calling {@code
     * iterator.next()} will return the first line of a module within the schema.
     *
     *
After calling this method, the iterator will be pointing at the line following the 'BEGIN'
     * keyword. I.e. calling {@code iterator.next()} will return the line following the 'BEGIN'
     * keyword.
     *
     * @param lineIterator iterator pointing at the first line following the 'BEGIN' keyword
     * @param moduleBuilder builder to use to construct module from the parsed information
     * @return the AsnModuleTaggingMode as parsed from the header. {@link
     *     AsnModuleTaggingMode#DEFAULT} if not found
     * @throws ParseException if any errors occur while parsing the schema
     */
    private static AsnModuleTaggingMode parseHeader(
            Iterator<String> lineIterator, AsnSchemaModule.Builder moduleBuilder)
            throws ParseException {
        try {
            final String moduleName = Iterables.get(Splitter.on(' ').split(lineIterator.next()), 0);
            logger.debug("Found module: {}", moduleName);
            moduleBuilder.setName(moduleName);

            final StringBuilder lines = new StringBuilder();
            String line = lineIterator.next();

            while (!"BEGIN".equals(line)) {
                lines.append(line).append(" ");
                line = lineIterator.next();
            }

            AsnModuleTaggingMode result = AsnModuleTaggingMode.DEFAULT;
            // split to make the regex easier
            final List<String> a = Splitter.on("DEFINITIONS ").splitToList(lines.toString());
            if (a.size() == 2) // it is optional
            {
                final Matcher matcher = PATTERN_DEFINITIONS.matcher(a.get(1));
                if (matcher.matches()) {
                    final String mode = matcher.group(2);
                    if (!Strings.isNullOrEmpty(mode)) {
                        try {
                            final AsnModuleTaggingMode tagMode = AsnModuleTaggingMode.valueOf(mode);
                            logger.debug("Module tagging mode is {}", tagMode);
                            result = tagMode;
                        } catch (Exception e) {
                            throw new ParseException(
                                    "Unrecognised module tagging mode " + mode, -1);
                        }
                    }
                }
            }
            return result;
        } catch (final NoSuchElementException ex) {
            throw new ParseException(ERROR_MISSING_HEADERS, -1);
        }
    }

    /**
     * Parses the data located between the 'BEGIN' and 'END' keywords.
     *
     *
Prior to calling this method, the iterator should be pointing at the line following the
     * 'BEGIN' keyword.I.e. calling {@code iterator.next()} will return the line following the
     * 'BEGIN' keyword.
     *
     *
After calling this method, the iterator will be pointing at the line containing the 'END'
     * keyword. I.e. calling {@code iterator.next()} will return the line following the 'END'
     * keyword.
     *
     * @param lineIterator iterator pointing at the first line following the 'BEGIN' keyword
     * @param moduleBuilder builder to use to construct module from the parsed information
     * @param taggingMode the Module wide tagging mode, determines whether to automatically generate
     *     tags.
     * @throws ParseException if any errors occur while parsing the schema
     */
    private static void parseBody(
            Iterator<String> lineIterator,
            AsnSchemaModule.Builder moduleBuilder,
            AsnModuleTaggingMode taggingMode)
            throws ParseException {
        try {
            final String lastLineRead = parseImportsAndExports(lineIterator, moduleBuilder);
            parseTypeDefinitionsAndValueAssignments(
                    lastLineRead, lineIterator, moduleBuilder, taggingMode);
        } catch (final NoSuchElementException ex) {
            throw new ParseException(ERROR_MISSING_CONTENT, -1);
        }
    }

    /**
     * Parses the data located between the 'BEGIN' and 'END' keywords.
     *
     *
Prior to calling this method, the iterator should be pointing at the line following the
     * 'BEGIN' keyword.I.e. calling {@code iterator.next()} will return the line following the
     * 'BEGIN' keyword.
     *
     *
After calling this method, the iterator will be pointing at the line following all
     * imports/exports. I.e. calling {@code iterator.next()} will return the line *following* the
     * first type definition or value assignment.
     *
     * @param lineIterator iterator pointing at the first line following the 'BEGIN' keyword
     * @param moduleBuilder builder to use to construct module from the parsed information
     * @return the line following the imports/exports, i.e. the first type definition or value
     *     assignment
     * @throws ParseException if any errors occur while parsing the schema
     * @throws NoSuchElementException if there is data missing
     */
    private static String parseImportsAndExports(
            Iterator<String> lineIterator, AsnSchemaModule.Builder moduleBuilder)
            throws ParseException, NoSuchElementException {
        String line = lineIterator.next();

        while (true) {
            if (line.startsWith("EXPORTS")) {
                // skip past all exports
                while (!(";".equals(line) || line.startsWith("IMPORTS"))) {
                    line = lineIterator.next();
                }
            } else if (line.startsWith("IMPORTS")) {
                final StringBuilder builder = new StringBuilder();
                line = lineIterator.next();
                while (!(";".equals(line) || line.startsWith("EXPORTS"))) {
                    builder.append(line).append(" ");
                    line = lineIterator.next();
                }
                final ImmutableMap<String, String> imports =
                        AsnSchemaImportsParser.parse(builder.toString());
                moduleBuilder.addImports(imports);
            } else {
                // reached end of import/exports
                if (";".equals(line)) {
                    // skip the semi-colon
                    line = lineIterator.next();
                } else {
                    break;
                }
            }
        }

        return line;
    }

    /**
     * Parses the type definitions and value assignments data. This data located after the
     * imports/exports and before the 'END' keyword.
     *
     *
Prior to calling this method, the iterator should be pointing at the line following all
     * imports/exports. I.e. calling {@code iterator.next()} will return the line *following* the
     * first type definition or value assignment.
     *
     *
After calling this method, the iterator will be pointing at the line containing the 'END'
     * keyword. I.e. calling {@code iterator.next()} will return the line following the 'END'
     * keyword.
     *
     * @param firstLine the first type definition or value assignment (i.e. the first line following
     *     all imports/exports)
     * @param lineIterator iterator pointing at the first line following all imports/exports
     * @param moduleBuilder builder to use to construct module from the parsed information
     * @param taggingMode the Module wide tagging mode, determines whether to automatically generate
     *     tags.
     * @throws ParseException if parsing errors are encountered.
     */
    private static void parseTypeDefinitionsAndValueAssignments(
            String firstLine,
            Iterator<String> lineIterator,
            AsnSchemaModule.Builder moduleBuilder,
            AsnModuleTaggingMode taggingMode)
            throws ParseException {
        String line = firstLine;
        while (!"END".equals(line)) {
            if (!line.contains("::=")) {
                final String error = ERROR_UNKNOWN_CONTENT + line;
                throw new ParseException(error, -1);
            }

            // read to the next definition or assignment
            final StringBuilder builder = new StringBuilder();
            do {
                builder.append(line).append(" ");
                line = lineIterator.next();
            } while (!line.contains("::=") && !"END".equals(line));

            final String content = builder.toString().trim();
            logger.trace("Found content: {}", content);

            // check if content is a type definition
            Matcher matcher = PATTERN_TYPE_DEFINITION_SIMPLE.matcher(content);
            if (matcher.matches()) {
                final String name = matcher.group(1);
                final String value = matcher.group(2);

                moduleBuilder.addType(
                        AsnSchemaTypeDefinitionParser.parse(name, value, taggingMode));
                continue;
            }

            // check if content is a value assignment
            matcher = PATTERN_VALUE_ASSIGNMENT.matcher(content);
            if (matcher.matches()) {
                parseValueAssignment(matcher);
                continue;
            }

            // check if content is a parameterized type definition.
            // This is last as it can be a VERY poor performing check to fail (not match).
            matcher = PATTERN_TYPE_DEFINITION_PARAMETERIZED.matcher(content);
            if (matcher.matches()) {
                // TODO ASN-148
                logger.warn("Parameterized Type Definitions not yet supported: {}", content);

                // final String name = matcher.group(1);
                // final String value = matcher.group(4);
                // moduleBuilder.addType(AsnSchemaTypeDefinitionParser.parse(name, value));
                continue;
            }

            // unknown content
            final String error = ERROR_UNKNOWN_CONTENT + content;
            throw new ParseException(error, -1);
        }
    }

    /**
     * Parses a value assignment
     *
     * @param valueAssignmentMatcher the matcher that identified the content as a value assignment
     *     (generated from {@link #PATTERN_VALUE_ASSIGNMENT})
     */
    private static void parseValueAssignment(Matcher valueAssignmentMatcher) {
        final String name = valueAssignmentMatcher.group(1);
        final String value = valueAssignmentMatcher.group(5);
        logger.trace("Found value assignment: {} - {}", name, value);
        // TODO ASN-79 - parse value assignment
    }
}

redpajama_set_name: RedPajamaGithub


text:
layout: docs
title:  "Introduction"

---

```sh
devctl up
```


text:
package org.camunda.bpm.extension.jbehave.example.simple.unit;

import static org.camunda.bpm.engine.test.assertions.ProcessEngineAssertions.assertThat;
import static org.camunda.bpm.engine.test.assertions.ProcessEngineTests.complete;
import static org.camunda.bpm.engine.test.assertions.ProcessEngineTests.withVariables;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doThrow;

import java.util.UUID;

import javax.inject.Inject;

import org.camunda.bpm.bdd.Slf4jLoggerRule;
import org.camunda.bpm.engine.delegate.BpmnError;
import org.camunda.bpm.engine.delegate.DelegateExecution;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.camunda.bpm.engine.task.Task;
import org.camunda.bpm.engine.test.Deployment;
import org.camunda.bpm.engine.test.mock.Mocks;
import org.camunda.bpm.extension.jbehave.example.simple.SimpleProcessAdapter;
import org.camunda.bpm.extension.jbehave.example.simple.SimpleProcessConstants;
import org.camunda.bpm.extension.needle.ProcessEngineNeedleRule;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;

/**
 * Unit test durable process.
 *
 * @author Simon Zambrovski, Holisticon AG.
 */
public class DurableUnitTest {

  static {
    Slf4jLoggerRule.DEFAULT.before();
  }

  @Rule
  public ProcessEngineNeedleRule processEngine = ProcessEngineNeedleRule.fluentNeedleRule(this).build();

  @Inject
  private SimpleProcessAdapter simpleProcessAdapter;

  private ProcessInstance processInstance;

  public static void mockLoadContract(final SimpleProcessAdapter mock, final boolean isAutomatically) {
    doAnswer(new Answer<Boolean>() {

      @Override
      public Boolean answer(final InvocationOnMock invocation) throws Throwable {
        final DelegateExecution execution = (DelegateExecution) invocation.getArguments()[0];

        // set contract id to random uuid
        execution.setVariable(SimpleProcessConstants.Variables.CONTRACT_ID, UUID.randomUUID().toString());

        return isAutomatically;
      }
    }).when(mock).loadContractData(any(DelegateExecution.class));

  }

  /**
   * Glue code in order to separate all application control code from test
   * assertions.
   */
  class Glue {

    public void loadContractData(final boolean isAutomatically) {
      mockLoadContract(simpleProcessAdapter, isAutomatically);
    }

    public void startSimpleProcess() {
      processInstance = processEngine.getRuntimeService().startProcessInstanceByKey(SimpleProcessConstants.PROCESS);
      assertThat(processInstance).isNotNull();
    }

    public void processAutomatically(final boolean withErrors) {
      if (withErrors) {
        doThrow(new BpmnError(SimpleProcessConstants.Events.ERROR_PROCESS_AUTOMATICALLY_FAILED)).when(simpleProcessAdapter).processContract();
      }
    }

    /**
     * Assert process end event.
     *
     * @param name
     *          name of the end event.
     */
    private void assertEndEvent(final String name) {
      assertThat(processInstance).hasPassed(name).isEnded();
    }

    public void waitsInManualProcessing() {
      assertThat(processInstance).isWaitingAt(SimpleProcessConstants.Elements.TASK_PROCESS_MANUALLY);
    }

    /**
     * Process manually.
     *
     * @param withErrors
     */
    public void processManually(boolean withErrors) {
      final Task task = processEngine.getTaskService().createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
      complete(task, withVariables("processingErrorsPresent", Boolean.valueOf(withErrors)));
    }

  }

  private final Glue glue = new Glue();

  @Before
  public void initMocks() {
    Mocks.register(SimpleProcessAdapter.NAME, simpleProcessAdapter);
  }

  @Test
  @Deployment(resources = SimpleProcessConstants.BPMN_DURABLE)
  public void shouldDeploy() {
    // nothing to do.
  }

  @Test
  @Deployment(resources = SimpleProcessConstants.BPMN_DURABLE)
  public void shouldStartProcessAutomaticallyAndWaitForManual() {

    // given
    glue.loadContractData(true);
    glue.processAutomatically(true);

    // when
    glue.startSimpleProcess();

    // then
    glue.waitsInManualProcessing();
  }

  @Test
  @Deployment(resources = SimpleProcessConstants.BPMN_DURABLE)
  public void shouldStartAndRunAutomatically() {

    // given
    glue.loadContractData(true);
    glue.processAutomatically(false);

    // when
    glue.startSimpleProcess();

    // then
    glue.assertEndEvent(SimpleProcessConstants.Events.EVENT_CONTRACT_PROCESSED);
  }

  @Test
  @Deployment(resources = SimpleProcessConstants.BPMN_DURABLE)
  public void shouldProcessContractManuallySuccessfully() {
    // given
    glue.loadContractData(false);
    glue.startSimpleProcess();
    glue.waitsInManualProcessing();

    // when
    glue.processManually(false);

    // then
    glue.assertEndEvent(SimpleProcessConstants.Events.EVENT_CONTRACT_PROCESSED);
  }

  @Test
  @Deployment(resources = SimpleProcessConstants.BPMN_DURABLE)
  public void shouldProcessContractManuallyAndCancel() {
    // given
    glue.loadContractData(false);
    glue.startSimpleProcess();
    glue.waitsInManualProcessing();

    // when
    glue.processManually(true);

    // then
    glue.assertEndEvent(SimpleProcessConstants.Events.EVENT_CONTRACT_PROCESSING_CANCELLED);
  }

}


text:
"""Convenience functions for training and evaluating a TFGAN CIFAR example."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

from six.moves import xrange  # pylint: disable=redefined-builtin
import tensorflow as tf
tfgan = tf.contrib.gan

def get_generator_conditioning(batch_size, num_classes):
  """Generates TFGAN conditioning inputs for evaluation.

  Args:
    batch_size: A Python integer. The desired batch size.
    num_classes: A Python integer. The number of classes.

  Returns:
    A Tensor of one-hot vectors corresponding to an even distribution over
    classes.

  Raises:
    ValueError: If `batch_size` isn't evenly divisible by `num_classes`.
  """
  if batch_size % num_classes != 0:
    raise ValueError('`batch_size` %i must be evenly divisible by '
                     '`num_classes` %i.' % (batch_size, num_classes))
  labels = [lbl for lbl in xrange(num_classes)
            for _ in xrange(batch_size // num_classes)]
  return tf.one_hot(tf.constant(labels), num_classes)

def get_image_grid(images, batch_size, num_classes, num_images_per_class):
  """Combines images from each class in a single summary image.

  Args:
    images: Tensor of images that are arranged by class. The first
      `batch_size / num_classes` images belong to the first class, the second
      group belong to the second class, etc. Shape is
      [batch, width, height, channels].
    batch_size: Python integer. Batch dimension.
    num_classes: Number of classes to show.
    num_images_per_class: Number of image examples per class to show.

  Raises:
    ValueError: If the batch dimension of `images` is known at graph
      construction, and it isn't `batch_size`.
    ValueError: If there aren't enough images to show
      `num_classes * num_images_per_class` images.
    ValueError: If `batch_size` isn't divisible by `num_classes`.

  Returns:
    A single image.
  """
  # Validate inputs.
  images.shape[0:1].assert_is_compatible_with([batch_size])
  if batch_size < num_classes * num_images_per_class:
    raise ValueError('Not enough images in batch to show the desired number of '
                     'images.')
  if batch_size % num_classes != 0:
    raise ValueError('`batch_size` must be divisible by `num_classes`.')

  # Only get a certain number of images per class.
  num_batches = batch_size // num_classes
  indices = [i * num_batches + j for i in xrange(num_classes)
             for j in xrange(num_images_per_class)]
  sampled_images = tf.gather(images, indices)
  return tfgan.eval.image_reshaper(
      sampled_images, num_cols=num_images_per_class)

def get_inception_scores(images, batch_size, num_inception_images):
  """Get Inception score for some images.

  Args:
    images: Image minibatch. Shape [batch size, width, height, channels]. Values
      are in [-1, 1].
    batch_size: Python integer. Batch dimension.
    num_inception_images: Number of images to run through Inception at once.

  Returns:
    Inception scores. Tensor shape is [batch size].

  Raises:
    ValueError: If `batch_size` is incompatible with the first dimension of
      `images`.
    ValueError: If `batch_size` isn't divisible by `num_inception_images`.
  """
  # Validate inputs.
  images.shape[0:1].assert_is_compatible_with([batch_size])
  if batch_size % num_inception_images != 0:
    raise ValueError(
        '`batch_size` must be divisible by `num_inception_images`.')

  # Resize images.
  size = 299
  resized_images = tf.image.resize_bilinear(images, [size, size])

  # Run images through Inception.
  num_batches = batch_size // num_inception_images
  inc_score = tfgan.eval.inception_score(
      resized_images, num_batches=num_batches)

  return inc_score

def get_frechet_inception_distance(real_images, generated_images, batch_size,
                                   num_inception_images):
  """Get Frechet Inception Distance between real and generated images.

  Args:
    real_images: Real images minibatch. Shape [batch size, width, height,
      channels. Values are in [-1, 1].
    generated_images: Generated images minibatch. Shape [batch size, width,
      height, channels]. Values are in [-1, 1].
    batch_size: Python integer. Batch dimension.
    num_inception_images: Number of images to run through Inception at once.

  Returns:
    Frechet Inception distance. A floating-point scalar.

  Raises:
    ValueError: If the minibatch size is known at graph construction time, and
      doesn't batch `batch_size`.
  """
  # Validate input dimensions.
  real_images.shape[0:1].assert_is_compatible_with([batch_size])
  generated_images.shape[0:1].assert_is_compatible_with([batch_size])

  # Resize input images.
  size = 299
  resized_real_images = tf.image.resize_bilinear(real_images, [size, size])
  resized_generated_images = tf.image.resize_bilinear(
      generated_images, [size, size])

  # Compute Frechet Inception Distance.
  num_batches = batch_size // num_inception_images
  fid = tfgan.eval.frechet_inception_distance(
      resized_real_images, resized_generated_images, num_batches=num_batches)

  return fid


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Feddes Repert. Spec. Nov. Regni Veg. 96(4): 266 (1985)

#### Original name
Parmentaria andamanica Ajay Singh

### Remarks
null


text:
'''
Created on 14/03/2013

@author: Jose Antonio Ruiperez Valiente
'''

from models import Video
from models import Exercise

from google.appengine.ext import db

class ViewerUser(db.Model):

    user = db.UserProperty()
    user_id = db.StringProperty()
    user_nickname = db.StringProperty()
    professor = db.BooleanProperty(default = False)
    student = db.BooleanProperty(default = False)

# Modelo que representa a todos los perfiles de medidas de un usuario
class UserProfile(db.Model):

    user = db.UserProperty()
    user_id = db.StringProperty()
    user_nickname = db.StringProperty()

    evaluation_exercise = db.IntegerProperty(default = -1, indexed=False)
    evaluation_video = db.IntegerProperty(default = -1, indexed=False)
    evaluation_ranking = db.IntegerProperty(default =-1 ,indexed=False)

    video_explorer = db.IntegerProperty(default = -1, indexed=False)
    exercise_explorer = db.IntegerProperty(default = -1, indexed=False)
    video_abandon = db.IntegerProperty(default = -1, indexed=False)
    exercise_abandon = db.IntegerProperty(default = -1, indexed=False)
    optional_elements = db.IntegerProperty(default = -1, indexed=False)
    exercise_one_correct = db.IntegerProperty(default = -1, indexed=False)
    focus_videos = db.IntegerProperty(default = -1, indexed=False)
    focus_exercises = db.IntegerProperty(default = -1, indexed=False)

    video_efficiency = db.IntegerProperty(default = -1, indexed=False)
    correct_exercise_effiency = db.IntegerProperty(default = -1, indexed=False)
    correct_exercise_solving_efficiency = db.IntegerProperty(default = -1, indexed=False)
    exercise_progress = db.IntegerProperty(default = -1, indexed=False)
    video_progress = db.IntegerProperty(default = -1, indexed=False)
    correct_exercises = db.IntegerProperty(default = -1, indexed=False)
    efficiency_proficiencies = db.IntegerProperty(default = -1, indexed=False)

    time_schedule_morning = db.IntegerProperty(default = -1, indexed=False)
    time_schedule_afternoon = db.IntegerProperty(default = -1, indexed=False)
    time_schedule_night = db.IntegerProperty(default = -1, indexed=False)
    morning_schedule_efficiency = db.IntegerProperty(default = -1, indexed=False)
    afternoon_schedule_efficiency = db.IntegerProperty(default = -1, indexed=False)
    night_schedule_efficiency = db.IntegerProperty(default = -1, indexed=False)
    average_schedule_efficiency = db.IntegerProperty(default = -1, indexed=False)
    constancy_mean = db.IntegerProperty(default = -1, indexed=False)
    constancy_variance = db.IntegerProperty(default = -1, indexed=False)

    recommendation_listener = db.IntegerProperty(default = -1, indexed=False)
    forgetful_exercises = db.IntegerProperty(default = -1, indexed=False)
    hint_avoidance = db.IntegerProperty(default = -1, indexed=False)
    video_avoidance = db.IntegerProperty(default = -1, indexed=False)
    unreflective_user = db.IntegerProperty(default = -1, indexed=False)
    hint_abuser = db.IntegerProperty(default = -1, indexed=False)

    badge_over_time = db.IntegerProperty(default = -1, indexed=False)
    badge_point_percentage = db.IntegerProperty(default = -1, indexed=False)

# Valor medio de los perfiles para las visualizaciones de clase
class ClassMeanProfile(db.Model):

    profile_name = db.StringProperty(indexed=True)
    mean_value = db.IntegerProperty(default = 0, indexed=False)

class ViewerVideo(db.Model):

    youtube_id = db.StringProperty()
    video = db.ReferenceProperty(Video)

class ViewerExercise(db.Model):

    name = db.StringProperty()
    exercise = db.ReferenceProperty(Exercise)


text:
extern "C" {
double GetAirspeedDerivative(double loop_angle, double dloop_angle,
                             CrosswindPathType path_type,
                             const FlightStatus *flight_status,
                             const PlaybookEntry *playbook_entry,
                             const CrosswindPowerParams *params,
                             CrosswindPowerState *state);
}

TEST(GetAirspeedDerivative, AnalyticAgreement) {
  CrosswindPowerParams params;
  PlaybookEntry playbook_entry;
  CrosswindPowerState state = CrosswindPowerState();
  FlightStatus flight_status;
  const double airspeed_variation_loop_angle_offset = 2.0;
  const double airspeed_variation = 15.0;
  const double mean_airspeed_cmd = 42.0;

  flight_status.flight_mode = kFlightModeCrosswindNormal;
  for (int i = 0; i < CROSSWIND_SCHEDULE_TABLE_LENGTH; i++) {
    double loop_angle = (2.0 * PI / (CROSSWIND_SCHEDULE_TABLE_LENGTH - 1)) * i;
    playbook_entry.lookup_loop_angle[i] = loop_angle;
    playbook_entry.airspeed_lookup[i] =
        mean_airspeed_cmd +
        airspeed_variation *
            cos(loop_angle - airspeed_variation_loop_angle_offset);
  }

  params.min_airspeed = 10.0;
  params.max_airspeed = 100.0;

  double dloop_angle =
      playbook_entry.lookup_loop_angle[1] - playbook_entry.lookup_loop_angle[0];
  for (double loop_angle = 0.0; loop_angle < 2.0 * PI; loop_angle += 0.1) {
    EXPECT_NEAR(
        GetAirspeedDerivative(loop_angle, dloop_angle, kCrosswindPathNormal,
                              &flight_status, &playbook_entry, &params, &state),
        -airspeed_variation *
            sin(loop_angle - airspeed_variation_loop_angle_offset),
        airspeed_variation * 1e-2);
  }
}

int main(int argc, char **argv) {
  ::testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}


text:
package store

import (
	"context"
	"sync"

	ccontent "github.com/containerd/containerd/content"
	"github.com/deislabs/oras/pkg/content"
	"github.com/opencontainers/go-digest"
	ocispec "github.com/opencontainers/image-spec/specs-go/v1"
)

// ensure interface
var (
	_ ccontent.Manager  = &MemoryStore{}
	_ ccontent.Provider = &MemoryStore{}
	_ ccontent.Ingester = &MemoryStore{}
)

type labelStore struct {
	l      sync.Mutex
	labels map[digest.Digest]map[string]string
}

// MemoryStore implements a simple in-memory content store for labels and
// descriptors (and associated content for manifests and configs)
type MemoryStore struct {
	store  *content.Memorystore
	labels labelStore
}

func newLabelStore() labelStore {
	return labelStore{
		labels: map[digest.Digest]map[string]string{},
	}
}

// NewMemoryStore creates a memory store that implements the proper
// content interfaces to support simple push/inspect operations on
// containerd's content in a memory-only context
func NewMemoryStore() *MemoryStore {
	return &MemoryStore{
		store:  content.NewMemoryStore(),
		labels: newLabelStore(),
	}
}

// Update updates mutable label field content related to a descriptor
func (m *MemoryStore) Update(ctx context.Context, info ccontent.Info, fieldpaths ...string) (ccontent.Info, error) {
	newLabels, err := m.update(info.Digest, info.Labels)
	if err != nil {
		return ccontent.Info{}, nil
	}
	info.Labels = newLabels
	return info, nil
}

// Walk is unimplemented
func (m *MemoryStore) Walk(ctx context.Context, fn ccontent.WalkFunc, filters ...string) error {
	// unimplemented
	return nil
}

func (m *MemoryStore) update(d digest.Digest, update map[string]string) (map[string]string, error) {
	m.labels.l.Lock()
	labels, ok := m.labels.labels[d]
	if !ok {
		labels = map[string]string{}
	}
	for k, v := range update {
		if v == "" {
			delete(labels, k)
		} else {
			labels[k] = v
		}
	}
	m.labels.labels[d] = labels
	m.labels.l.Unlock()

	return labels, nil
}

// Delete is unimplemented as we don't use it in the flow of manifest-tool
func (m *MemoryStore) Delete(ctx context.Context, d digest.Digest) error {
	return nil
}

// Info returns the info for a specific digest
func (m *MemoryStore) Info(ctx context.Context, d digest.Digest) (ccontent.Info, error) {
	info := ccontent.Info{
		Digest: d,
		Labels: m.labels.labels[d],
	}
	return info, nil
}

// ReaderAt returns a reader for a descriptor
func (m *MemoryStore) ReaderAt(ctx context.Context, desc ocispec.Descriptor) (ccontent.ReaderAt, error) {
	return m.store.ReaderAt(ctx, desc)
}

// Writer returns a content writer given the specific options
func (m *MemoryStore) Writer(ctx context.Context, opts ...ccontent.WriterOpt) (ccontent.Writer, error) {
	return m.store.Writer(ctx, opts...)
}

// Get returns the content for a specific descriptor
func (m *MemoryStore) Get(desc ocispec.Descriptor) (ocispec.Descriptor, []byte, bool) {
	return m.store.Get(desc)
}

// Set sets the content for a specific descriptor
func (m *MemoryStore) Set(desc ocispec.Descriptor, content []byte) {
	m.store.Set(desc, content)
}

// GetByName retrieves a descriptor based on the associated name
func (m *MemoryStore) GetByName(name string) (ocispec.Descriptor, []byte, bool) {
	return m.store.GetByName(name)
}

// Abort is not implemented or needed in this context
func (m *MemoryStore) Abort(ctx context.Context, ref string) error {
	return nil
}

// ListStatuses is not implemented or needed in this context
func (m *MemoryStore) ListStatuses(ctx context.Context, filters ...string) ([]ccontent.Status, error) {
	return []ccontent.Status{}, nil
}

// Status is not implemented or needed in this context
func (m *MemoryStore) Status(ctx context.Context, ref string) (ccontent.Status, error) {
	return ccontent.Status{}, nil
}


text:
<?php

namespace Samleybrize\Valoa\ValueObject\Validator;

use Samleybrize\Valoa\ValueObject\ValueObjectException;

class ValidatorObject implements ValidatorInterface
{
    /**
     * Class name
     * @var string
     */
    private $classname;

    /**
     * Indicates if the classname is absolute
     * @var boolean
     */
    private $isAbsolute;

    /**
     * {@inheritdoc}
     */
    public function __construct(array $tags = array())
    {
        if (!array_key_exists("classname", $tags)) {
            throw new ValueObjectException("Tag list must have a 'classname' tag");
        } elseif (!is_string($tags["classname"][0])) {
            throw new ValueObjectException("Tag 'classname' must be a string");
        }

        $this->classname    = $tags["classname"][0];
        $this->isAbsolute   = false !== strpos($this->classname, "\\");
    }

    /**
     * {@inheritdoc}
     */
    public function isValid(&$value)
    {
        if ($this->isAbsolute) {
            // absolute classname
            if (!is_a($value, $this->classname)) {
                // failed validation
                $givenType = ("object" == gettype($value)) ? get_class($value) : gettype($value);
                throw new ValueObjectException("Instance of [$this->classname] expected, [$givenType] given");
            }
        } else {
            // relative classname
            // we check the end of the classname of the given value
            if ("object" !== gettype($value)) {
                // failed validation
                $givenType = ("object" == gettype($value)) ? get_class($value) : gettype($value);
                throw new ValueObjectException("Instance of [$this->classname] expected, [$givenType] given");
            }

            $valueType  = "\\" . get_class($value);
            $classname  = "\\" . $this->classname;
            $compare    = substr($valueType, -strlen($classname));

            if ($compare !== $classname) {
                // failed validation
                $givenType = ("object" == gettype($value)) ? get_class($value) : gettype($value);
                throw new ValueObjectException("Instance of [$this->classname] expected, [$givenType] given");
            }
        }

        return true;
    }
}


text:
@implementation MAZeroingWeakProxy

+ (id)proxyWithTarget: (id)target
{
    return [[[self alloc] initWithTarget: target] autorelease];
}

- (id)initWithTarget: (id)target
{
    // stash the class of the target so we can get method signatures after it goes away
    _targetClass = [target class];
    _weakRef = [[MAZeroingWeakRef alloc] initWithTarget: target];
    return self;
}

- (void)dealloc
{
    [_weakRef release];
    [super dealloc];
}

- (id)zeroingProxyTarget
{
    return [_weakRef target];
}

#if NS_BLOCKS_AVAILABLE
- (void)setCleanupBlock: (void (^)(id target))block
{
    [_weakRef setCleanupBlock: block];
}
#endif

- (id)forwardingTargetForSelector: (SEL)sel
{
    return [_weakRef target];
}

- (NSMethodSignature *)methodSignatureForSelector: (SEL)sel
{
    return [_targetClass instanceMethodSignatureForSelector: sel];
}

- (void)forwardInvocation: (NSInvocation *)inv
{
    NSMethodSignature *sig = [inv methodSignature];
    NSUInteger returnLength = [sig methodReturnLength];

    if(returnLength)
    {
        char buf[returnLength];
        bzero(buf, sizeof(buf));
        [inv setReturnValue: buf];
    }
}

- (BOOL)respondsToSelector: (SEL)sel
{
    id target = [_weakRef target];
    if(target)
        return [target respondsToSelector: sel];
    else
        return [_targetClass instancesRespondToSelector: sel];
}

- (BOOL)conformsToProtocol: (Protocol *)protocol
{
    id target = [_weakRef target];
    if(target)
        return [target conformsToProtocol: protocol];
    else
        return [_targetClass conformsToProtocol: protocol];
}

// NSProxy implements these for some incomprehensibly stupid reason

- (NSUInteger)hash
{
    return [[_weakRef target] hash];
}

- (BOOL)isEqual: (id)obj
{
    return [[_weakRef target] isEqual: obj];
}

@end


text:
// --
//  BasicGenerator.hpp
//  WorldGenerator
//
//  Simplest generator, circle of land around a point

#ifndef BasicGenerator_hpp
#define BasicGenerator_hpp

#include <memory>

#include "Generator.hpp"

namespace WorldBuilder {
    class World;
    /*************** Basic Generator ***************/
    /*  Our basic generator,
     *  creates a domed circle of land around a random point
     */
    class BasicGenerator : public Generator {
    public:
        BasicGenerator(std::shared_ptr<Random> random) : Generator(random){};

        // required parent function
        void Generate(std::shared_ptr<World> theWorld);

    protected:
    }; // class Basic Generator
} // namespace WorldBuilder

#endif /* BasicGenerator_hpp */


text:
require "model.BuildingBaseSprite"
require "model.BaseTowerSprite"
require "model.HeroHotelSprite"
require "model.MineFactorySprite"
require "model.WoodFactorySprite"
require "model.ResearchLabSprite"
require "model.CampSprite"
require "model.RaiderSprite"

require "model.ArrowTowerSprite"
require "model.CannonSprite"
require "model.LaserSprite"

require "model.HumanBaseSprite"
require "model.HeroSprite"
require "model.FighterSprite"
require "model.BowmanSprite"
require "model.GunnerSprite"
require "model.MeatShieldSprite"

require "model.BulletSprite"


text:
'use strict';

require('coffee-script').register();

module.exports = require('./index.coffee');


text:
package com.github.shchurov.prefseditor.helpers.adb;

import com.github.shchurov.prefseditor.helpers.exceptions.ExecuteAdbCommandException;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class AdbCommandExecutor {

    String execute(String command) throws ExecuteAdbCommandException {
        try {
            Process p = Runtime.getRuntime().exec(command);
            BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                if (line.length() != 0) {
                    sb.append(line).append("\n");
                }
            }
            return sb.toString().trim();
        } catch (IOException e) {
            throw new ExecuteAdbCommandException(e);
        }
    }

}


text:
import { getPointerData } from './get-pointer-data';

/**
 * Get pointer/finger position
 */
export function getPosition(evt: any) {
  const data = getPointerData(evt);

  return {
    x: data.clientX,
    y: data.clientY,
  };
}


text:
package com.linecorp.armeria.client.endpoint;

import com.linecorp.armeria.client.Endpoint;
import com.linecorp.armeria.common.Flags;

/**
 * An {@link EndpointGroupException} raised when the resolution of an {@link EndpointGroup} fails
 * because there are no {@link Endpoint}s in the {@link EndpointGroup}.
 */
public final class EmptyEndpointGroupException extends EndpointGroupException {

    private static final long serialVersionUID = 7595286618131200852L;

    static final EmptyEndpointGroupException INSTANCE = new EmptyEndpointGroupException(false);

    /**
     * Returns an {@link EmptyEndpointGroupException} which may be a singleton or a new instance, depending on
     * {@link Flags#verboseExceptionSampler()}'s decision.
     */
    public static EmptyEndpointGroupException get() {
        return Flags.verboseExceptionSampler().isSampled(EmptyEndpointGroupException.class) ?
               new EmptyEndpointGroupException() : INSTANCE;
    }

    EmptyEndpointGroupException() {}

    private EmptyEndpointGroupException(@SuppressWarnings("unused") boolean dummy) {
        super(null, null, false, false);
    }
}


text:
swoole_timer: swoole_timer_after,swoole_timer_exists,swoole_timer_clear
--SKIPIF--
<?php require __DIR__ . "/../include/skipif.inc"; ?>
--INI--
assert.active=1
assert.warning=1
assert.bail=0
assert.quiet_eval=0

--FILE--
<?php
class TimerTest {
    public static $count = 0;
    private $timer_id = null;

    protected function resetTimer($ms) {
        if ($this->timer_id && swoole_timer_exists($this->timer_id)) {
            swoole_timer_clear($this->timer_id);
            $this->timer_id = null;
        }
        if (self::$count == 10) {
            return;
        }
        $this->timer_id = swoole_timer_after($ms, array($this, 'onTimerTick'));
        assert($this->timer_id > 0);
    }

    public function onTimerTick() {
        self::$count++;
        echo "onTimerTick:" . self::$count . "\n";
        $this->resetTimer(10);
    }
}

$timer_test = new TimerTest();
$timer_test->onTimerTick();

?>
--EXPECT--
onTimerTick:1
onTimerTick:2
onTimerTick:3
onTimerTick:4
onTimerTick:5
onTimerTick:6
onTimerTick:7
onTimerTick:8
onTimerTick:9
onTimerTick:10


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="org.wso2.carbon.iot.android.sense.realtimeviewer.ActivitySelectSensor"
    android:touchscreenBlocksFocus="false">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay"/>

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_activity_select_sensor"/>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_gravity="bottom|center"
        android:layout_height="100dp"
        android:layout_margin="20dp"
        android:orientation="horizontal">

        <!--<RelativeLayout-->
            <!--android:layout_width="0dp"-->
            <!--android:layout_height="match_parent"-->
            <!--android:layout_weight="0.25"-->
            <!-->-->
            <!--<android.support.design.widget.FloatingActionButton-->
                <!--android:id="@+id/beacon"-->
                <!--android:layout_width="match_parent"-->
                <!--android:layout_height="match_parent"-->
                <!--android:layout_margin="15dp"-->
                <!--android:src="@drawable/beacon"/>-->
        <!--</RelativeLayout>-->

        <RelativeLayout
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="0.5"
            >
            <android.support.design.widget.FloatingActionButton
                android:id="@+id/addSensors"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_margin="15dp"
                android:layout_centerInParent="true"
                android:src="@android:drawable/ic_input_add"/>

        </RelativeLayout>

        <!--<RelativeLayout-->
            <!--android:layout_width="0dp"-->
            <!--android:layout_height="match_parent"-->
            <!--android:layout_weight="0.25"-->
            <!-->-->
            <!--<android.support.design.widget.FloatingActionButton-->
                <!--android:id="@+id/speech"-->
                <!--android:layout_width="match_parent"-->
                <!--android:layout_height="match_parent"-->
                <!--android:layout_margin="15dp"-->
                <!--android:src="@drawable/mic"/>-->
        <!--</RelativeLayout>-->

        <RelativeLayout
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="0.5"
            >
            <android.support.design.widget.FloatingActionButton
                android:id="@+id/publish"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_margin="15dp"
                android:layout_centerInParent="true"
                android:src="@drawable/pushtoserver"/>
        </RelativeLayout>
    </LinearLayout>
</android.support.design.widget.CoordinatorLayout>


text:
@class GTCrashReportData;

@interface GTReportSender : NSObject

- (void)send:(GTCrashReportData *)reportData;

@end


text:
// Pen by OutKast <https://codepen.io/0utKast/> MIT licenced

document.addEventListener("DOMContentLoaded", function(event) {
//Fuente Original :  http://timelessname.com/sandbox/matrix.html
//Configura el canvas para que ocupe la pantalla entera
    canvas.height = window.screen.height;
    canvas.width = window.screen.width;

// una entrada en el array por columna de texto
//cada valor represnta la posición y actual de la columna.  (en canvas 0 es en la parte superior y los valores positivos de y van disminuyendo)
    var columns = [];
    for (var i = 0; i < 256; columns[i++] = 1);

//ejecutado una vez por fotograma
    function step() {
        //Ligeramente oscurece todo el canvas dibujando un rectángulo negro casi trasnsparente sobre todo el canvas
        /*esto explica tanto el flash inicial de blanco a negro (por defecto el canvas es blanco y progresivamente se convierte en negro) como el fading de los caracteres.*/
        canvas.getContext('2d').fillStyle = 'rgba(0,0,0,0.05)';
        canvas.getContext('2d').fillRect(0, 0, canvas.width, canvas.height);

        //verde
        canvas.getContext('2d').fillStyle = '#0F0';
        //para cada clolumna
        columns.map(function (value, index) {
            //fromCharCode convierte puntos de código unicode ( http://en.wikipedia.org/wiki/Code_point ) a un string
            //Los code points están en el rango 30000-30032 (0x7530-0x7550) (田-畐)
            //que está incluido en el bloque de ideogramas unificado CJK ( http://en.wikipedia.org/wiki/CJK_Unified_Ideographs )
            var character = String.fromCharCode(3e4 +
                Math.random() * 33);
            //dibujar el carácter
            canvas.getContext('2d').fillText(character, //texto
                index * 10, //x
                value //y
            );

            //desplaza hacia abajo el carácter
            //si el carácter es menor de 758 entonces hay una posibilidad aleatoria de que sea reseteado
            columns[index] = value > 758 + Math.random() * 1e4 ? 0 : value + 10
        })
    }

//1000/33 = ~30 veces por segundo
    setInterval(step, 33)
});


text:
class TasksForm : public ActivityForm {
	Q_OBJECT
public:
	TasksForm(QWidget* parent = nullptr);
	~TasksForm() override;

	QString title() const override;
	QIcon icon() const override;

public slots:
	void loadSettings();
	void saveSettings();

private:
	QIcon icon_;

	void setupUi();
};

#endif // MINDCACHE_TASKS_TASKSFORM_H


text:
_or how I learned to calm the hyperspatial index_

[Dave Rostron](http://github.com/drostron) — [\@yastero](http://twitter.com/yastero)

Feb 17, 2015

---

> All our wisdom is stored in the trees.
>
> — Santosh Kalwar

---

## opening notes

- this is not complete
- more of a chance to dig into shapeless than look in depth at R-Trees (_at least initially_)
- just having some fun, please join me

---

## exploration inspiration

"Designing Data-Intensive Applications"
by Martin Kleppmann (_recommended_)

---

## how do we find the needle in the haystack?

- could scan through the whole stack
- maybe there's something faster
- B-Tree to the rescue

---

## wait, we want to index our data over multiple dimensions

- could get part of the way there with a B-Tree but what about a range query over both dimensions?
- R-Tree to the rescue

---

R-Tree Overview

- spatial n-dimensional index

- variants: M-Tree, X-Tree, Hilbert R-tree
- sounds useful, tell us more...

---

how bout some code

. . .

```tut:silent
trait Data2D {
  case class Point[T](x: T, y: T)
  case class Entry[V, T](value: V, point: Point[T])
  case class Box[T](xLower: T, xUpper: T, yLower: T, yUpper: T) // inclusive

  sealed trait RTree[V, T]
  case class Empty[V, T]() extends RTree[V, T]
  case class Leaf[V, T](entry: Entry[V, T]) extends RTree[V, T]
  case class Node[V, T](
    box: Box[T], left: RTree[V, T], right: RTree[V, T])
    extends RTree[V, T]
}

object data2D extends Data2D
```

---

```tut:silent
import data2D._, spire._, algebra._

trait Ops2D {
  def initBox[T : Order](point1: Point[T], point2: Point[T]): Box[T]

  def expandBox[T : Order](box: Box[T], point: Point[T]): Box[T]

  def expandBox[T : Order](box1: Box[T], box2: Box[T]): Box[T]

  def withinBox[T : Order](box: Box[T], point: Point[T]): Boolean

  def overlaps[T : Order](box1: Box[T], box2: Box[T]): Boolean

  def add[V, T](rtree: RTree[V, T], entry: Entry[V, T]): RTree[V, T]

  def remove[V, T](rtree: RTree[V, T], entry: Entry[V, T]): RTree[V, T]

  def find[V, T](rtree: RTree[V, T], point: Point[T]): Option[Entry[V, T]]

  def contains[V, T](rtree: RTree[V, T], entry: Entry[V, T]): Boolean

  def search[V, T](space: Box[T]): List[Entry[V, T]]
}
```

---

what if we have more than 2 dimensions?

. . .

```tut:silent

trait DataDynamicNDim {
  case class Point[T](terms: List[T])
  case class Entry[V, T](value: V, point: Point[T])
  case class Box[T](lowerBounds: List[T], upperBounds: List[T])

  sealed trait RTree[V, T]
  case class Empty[V, T]() extends RTree[V, T]
  case class Leaf[V, T](entry: Entry[V, T]) extends RTree[V, T]
  case class Node[V, T](
    box: Box[T], left: RTree[V, T], right: RTree[V, T])
    extends RTree[V, T]
}
```

---

> Traveling through hyperspace ain't like dusting crops, farm boy. Without precise calculations we could fly right through a star or bounce too close to a supernova, and that'd end your trip real quick, wouldn't it?
>
> — Han Solo, Star Wars Episode IV: A New Hope

. . .

---

I hear type systems perform calculations

. . .

and support a class of constraints

. . .

there's a library that explores this space

. . .

shapeless : supercharged generic coding

---

> Empty your mind, be formless. Shapeless, like water.
>
> — Bruce Lee

. . .

. . .

let's build a well typed Generic N-Dim R-Tree

---

shapeless Sized

. . .

```tut:silent
import shapeless._, ops.nat._

trait DataSizedNDim {
  case class Point[T, N <: Nat](terms: Sized[Seq[T], N])
  case class Entry[V, T, N <: Nat](value: V, point: Point[T, N])
  case class Interval[T](l: T, u: T)
  case class Box[T, N <: Nat](intervals: Sized[Seq[Interval[T]], N])

  sealed trait RTree[T, N <: Nat]
  case class Leaf[T, N <: Nat](point: Point[T, N]) extends RTree[T, N]
  case class Node[T, N <: Nat](
    bound: Box[T, N], left: RTree[T, N], right: RTree[T, N])
    extends RTree[T, N]
}
```

. . .

perhaps, what if we want heterogeneous types for our dimensions?

---

shapeless HList

. . .

```tut:silent
trait DataHListNDim {
  case class Point[T <: HList](terms: T)
  case class Entry[V, T <: HList](value: V, point: Point[T])
  case class Box[T <: HList](lowerBounds: T, upperBounds: T) // inclusive

  sealed trait RTree[V, T <: HList]
  case class Empty[V, T <: HList]() extends RTree[V, T]
  case class Leaf[V, T <: HList](entry: Entry[V, T]) extends RTree[V, T]
  case class Node[V, T <: HList](
    box: Box[T], left: RTree[V, T], right: RTree[V, T])
    extends RTree[V, T]
}

object dataHListNDim extends DataHListNDim
```

. . .

looks promising

---

note: intentionally postponed a few items

- balancing
- splitting
- performance
- heterogeneous distance function (_similarity_)

---

```tut:silent
import dataHListNDim._, shapeless.ops.hlist._
import spire.math.{ min, max }, spire.implicits.{eqOps => _, _}

trait OpsHListFunctions {
  object minimum extends Poly2 {
    implicit def default[T : Order] = at[T, T](implicitly[Order[T]].min)
  }

  object maximum extends Poly2 {
    implicit def default[T : Order] = at[T, T](implicitly[Order[T]].max)
  }

  object lte extends Poly2 {
    implicit def default[T : Order] = at[T, T](_ <= _)
  }

  object gte extends Poly2 {
    implicit def default[T : Order] = at[T, T](_ >= _)
  }

  object and extends Poly2 {
    implicit def caseBoolean = at[Boolean, Boolean](_ && _)
  }
}
```

---

```tut:silent
trait OpsHListTypes { self: OpsHListFunctions =>
  type ZWMin[T <: HList] = ZipWith.Aux[T, T, minimum.type, T]
  type ZWMax[T <: HList] = ZipWith.Aux[T, T, maximum.type, T]

  type ZWLB[T <: HList] = {
    type λ[U <: HList] = ZipWith.Aux[T, T, lte.type, U]
  }
  type ZWUB[T <: HList] = {
    type λ[U <: HList] = ZipWith.Aux[T, T, gte.type, U]
  }

  type LFLB[T <: HList] = {
    type λ[U <: HList] =
      LeftFolder.Aux[
        ZipWith.Aux[T, T, lte.type, U]#Out,
        Boolean,
        and.type,
        Boolean]
  }
  type LFUB[T <: HList] = {
    type λ[U <: HList] =
      LeftFolder.Aux[
        ZipWith.Aux[T, T, gte.type, U]#Out,
        Boolean,
        and.type,
        Boolean]
  }
}
```

---

```tut:silent
trait OpsHList extends OpsHListFunctions with OpsHListTypes {
  def initBox
    [T <: HList : ZWMin : ZWMax]
    (point1: Point[T], point2: Point[T])
    : Box[T] = Box(
    point1.terms.zipWith(point2.terms)(minimum),
    point1.terms.zipWith(point2.terms)(maximum))

  def expandBox
    [T <: HList : ZWMin : ZWMax]
    (box: Box[T], point: Point[T])
    : Box[T] = Box(
    box.lowerBounds.zipWith(point.terms)(minimum),
    box.upperBounds.zipWith(point.terms)(maximum))

  def withinBox
    [T <: HList, L <: HList : ZWLB[T]#λ : LFLB[T]#λ, U <: HList : ZWUB[T]#λ : LFUB[T]#λ]
    (box: Box[T], point: Point[T])
    : Boolean =
    box.lowerBounds.zipWith(point.terms)(lte).foldLeft(true)(and) &&
    box.upperBounds.zipWith(point.terms)(gte).foldLeft(true)(and)

  def overlaps
    [T <: HList, L <: HList : ZWLB[T]#λ : LFLB[T]#λ, U <: HList : ZWUB[T]#λ : LFUB[T]#λ]
    (box1: Box[T], box2: Box[T])
    : Boolean =
    box1.lowerBounds.zipWith(box2.upperBounds)(lte).foldLeft(true)(and) &&
    box1.upperBounds.zipWith(box2.lowerBounds)(gte).foldLeft(true)(and)
}
```

. . .

incomplete implementation for for sake of brevity

---

still with me? good, let's speed this up a bit.

. . .

```tut:silent
import ndimrtree._, NDimRTree._
```

```tut
val b1 = initBox(Point(1 :: HNil), Point(3 :: HNil))

val b2 = initBox(Point(2 :: HNil), Point(4 :: HNil))

val b3 = initBox(Point("a" :: HNil), Point("z" :: HNil))

import shapeless.test._

illTyped("""

initBox(Point(1 :: HNil), Point("a" :: HNil))

""")

expandBox(b1, b2)

illTyped("""

expandBox(b1, b3)

""")

val t1: RTree[String, Int :: Double :: HNil] = RTree(List(Entry("z", Point(3 :: 1.7 :: HNil))))

illTyped("""

val t1: RTree[String, Int :: Long :: HNil] = RTree(List(Entry("z", Point(3 :: 1.7 :: HNil))))

""")
```

---

how bout some property based tests

```tut:silent
import NDimRTreeOps._, org.scalacheck._, Arbitrary._, Prop._, Shapeless._
import scalaz.{ Ordering => _, _ }, Scalaz._, shapeless.{ :: => :×: }

class NDimRTreeTest extends Properties("NDimRTree") {
  type V = String
  type N = Int :×: Double :×: String :×: HNil

  implicit def setEqual[T] = Equal.equalA[Set[T]]

  property("insert entry") = forAll { (r: RTree[V, N], e: Entry[V, N]) =>
    r.add(e).find(e.point) === e.some
  }

  property("build from list of entries") = forAll { entries: List[Entry[V, N]] =>
    RTree(entries).entries.toSet === entries.toSet
  }

  property("rtree.contains works") = forAll { (es: List[Entry[V, N]], e: Entry[V, N]) =>
    val rt = RTree(es)

    es.forall(rt.contains) && (rt.contains(e) === es.contains(e))
  }
}
```

---

```tut:silent
object nDimRTreeTest extends NDimRTreeTest {

  property("rtree.search agrees with withinBox(box, point) filtering") = forAll {
    (es: List[Entry[V, N]], p1: Point[N], p2: Point[N]) =>

    val rt = RTree(es)

    val box1 = initBox(p1, p2)
    require(rt.search(box1).toSet === es.filter(e => withinBox(box1, e.point)).toSet)

    es.foreach { e =>
      val box2 = initBox(e.point, p2)
      require(rt.search(box2).toSet === es.filter(e => withinBox(box2, e.point)).toSet)
    }
    true
  }
}
```

. . .

```tut
nDimRTreeTest.check
```

---

initial benchmarking:

plenty of room for improvement. just a first naive pass. confident that reasonable performance is achievable.

---

fun things explored

- generic programming with shapeless
- indexes
- R-Trees (but you already know that)

---

 libraries utilized

> - [shapeless](https://github.com/milessabin/shapeless) : Generic programming for Scala
> - [spire](https://github.com/non/spire) : Powerful new number types and numeric abstractions for Scala
> - [scalacheck](https://github.com/rickynils/scalacheck) : Property-based testing for Scala
> - [scalacheck-shapeless](https://github.com/alexarchambault/scalacheck-shapeless) : Generation of arbitrary case classes / ADTs with scalacheck and shapeless
> - [archery](https://github.com/meetup/archery) : 2D R-Tree implementation in Scala
>     - leveraged for scalacheck tests and benchmarking
> - [thyme](https://github.com/Ichoran/thyme) -  microbenchmark utility for Scala
> - [scalaz](https://github.com/scalaz/scalaz) - An extension to the core Scala library for functional programming
>     - utilized mostly for type-safe equality (_looking forward to spending more time with [cats](https://github.com/non/cats)_)
> - [tut](https://github.com/tpolecat/tut) - doc/tutorial generator for scala
>     - sent the code used in this presentation to scalac

---

future explorations

- heterogenous distance functions
- specialization and/or miniboxing
- visualization with d3, perhaps leverage archery and scala-js
- turn this exploration into a usable and efficient library
- R-Tree variants, e.g. M-Tree, X-Tree, Hilbert R-tree
- distributed implementation

---

Thanks!

repo : [rtree-explorations](https://github.com/drostron/rtree-explorations)

slides : [Generic N-Dim R-Tree Explorations](http://drostron.github.io/rtree-explorations/slides/pdxscala-2015-february/index.html)


text:
/*
eslint-disable no-param-reassign
 */

import EntityManagerMongoDB from 'entity-manager';
import { REQUIRED, SERVER_FAILED, OBJECT_ALREADY_EXISTS } from 'nagu-validates';
import { ObjectId } from 'mongodb';

export default class ResourceManager extends EntityManagerMongoDB {
  // 添加资源
  async add(res, initState) {
    if (!res || !res.name || !res.catagory) {
      return Promise.reject({
        ret: REQUIRED,
        msg: 'name和catagory必须提供',
      });
    }
    const { name, catagory } = res;
    initState = {
      _id: new ObjectId(),
      date: new Date(),
      ...initState,
    };
    if (!initState.catagory || !initState.note || !initState.creator) {
      return Promise.reject({
        ret: REQUIRED,
        msg: '状态信息必须指定catagory、note和creator',
      });
    }
    if (!initState.date || !initState.date.getUTCDate) {
      initState.date = new Date();
    }
    const entity = {
      name,
      catagory,
      currentState: initState,
      statesLength: 1,
      states: [initState],
    };
    try {
      const existObj = await super.findOne({ name, catagory });
      if (existObj) {
        return Promise.reject({ ret: OBJECT_ALREADY_EXISTS, msg: '资源已经存在' });
      }
      const result = await super.insert(entity);
      return Promise.resolve(result.insertedId);
    } catch (msg) {
      return Promise.reject({ ret: SERVER_FAILED, msg });
    }
  }

  // 添加状态
  addState(resId, state) {
    if (!resId) return Promise.reject({ ret: REQUIRED, msg: '必须指定资源Id' });
    if (!state || !state.catagory || !state.note || !state.creator) {
      return Promise.reject({ ret: REQUIRED, msg: '状态信息不完整' });
    }
    const newState = {
      _id: new ObjectId(),
      date: new Date(),
      ...state,
    };
    return super.updateById(resId, {
      $addToSet: { states: newState },
      $inc: { statesLength: 1 },
      $set: {
        currentState: newState,
      },
    });
  }

  list({ catagory, state, before } = {}) {
    let query = {};
    if (catagory) {
      query = { ...query, catagory };
    }
    if (state) {
      query = { ...query, 'currentState.catagory': state };
    }
    if (before) {
      query = {
        ...query,
        states: { $elemMatch: { date: { $gte: before } } },
      };
    }
    console.log(query, catagory, state);
    return super.find({ query });
  }
}


text:
package com.akjava.gwt.html5.client.media;

import com.google.gwt.core.client.JavaScriptObject;

public class UserMediaError extends JavaScriptObject{
	protected UserMediaError(){}
}


text:
/**
 * Command supports
 * @author xiemalin
 * @since 1.8.0
 */
package com.baidu.bjf.remoting.protobuf.command;


text:
import {
    prepareClassName,
    isValidEntity,
    getEntitiesFromBEMJSON
} from './utils';

function validateBEMJSON(bemjson, entity, bemNaming) {
    // retrieve and prepare className
    const className = prepareClassName(entity);

    // retrieve entities
    const entities = getEntitiesFromBEMJSON(bemjson);

    const isValidBlocks = entities.blocks.every(blockName => {
        return className.some(item => {
            // ignore if not block
            if (!bemNaming.isBlock(item)) {
                return false;
            }

            const parsedItem = bemNaming.parse(item);

            return parsedItem.block === blockName;
        });
    });

    if (!isValidBlocks) {
        return false;
    }

    const isValidElems = entities.elems.every(bemjsonEntity => {
        return className.some(item => {
            // ignore if not element
            if (!bemNaming.isElem(item)) {
                return false;
            }

            const parsedItem = bemNaming.parse(item);

            return (
                parsedItem.block === bemjsonEntity.block &&
                parsedItem.elem === bemjsonEntity.elem
            );
        });
    });

    if (!isValidElems) {
        return false;
    }

    const isValidMods = entities.mods.every(bemjsonEntity => {
        const { block, elem, modName } = bemjsonEntity;
        const modVal = String(bemjsonEntity.modVal);

        return className.some(item => {
            // ignore if no mods
            if (!bemNaming.isBlockMod(item) && !bemNaming.isElemMod(item)) {
                return false;
            }

            const parsedItem = bemNaming.parse(item);

            return (
                parsedItem.block === block &&
                parsedItem.elem === elem &&
                parsedItem.modName === modName &&
                String(parsedItem.modVal) === modVal
            );
        });
    });

    return isValidMods;
}

export function bemjsonMethod(bemNaming, chai, entityHook) {
    const { assert } = chai;
    const { typeOf } = assert;

    return function(bemjson) {
        const entity = entityHook(this._obj);

        // check input
        assert(
            isValidEntity(entity),
            `${entity} is neither a DOM element nor a className`
        );
        typeOf(bemjson, 'object');

        this.assert(
            validateBEMJSON(bemjson, entity, bemNaming),
            'expected #{this} to be #{exp} bemjson',
            'expected #{this} to not be #{exp} bemjson',
            bemjson,
            entity
        );
    };
}


text:
    {{ field_text }}{% if field_required %} (required){% endif %}
    {% if tooltip %}

    {% endif %}
    {% if help_text %}

{{ help_text }}

    {% endif %}

    <select class="form-control select-multiple custom-request-form-data" multiple size="5" id="{{ field_name }}-{{ instance_id }}" name="{{ field_name }}-{{ instance_id }}" {% if field_required %}data-parsley-required{% endif %}>
        {% for option in options %}
            <option value="{{ option }}">{{ option }}</option>
        {% endfor %}
    </select>


text:
var _ = require('lodash');

module.exports = {
    post: function(postData) {
        var fieldsQty = _.max(_.map(_.keys(postData), function(name) {
            return name.split('_')[1];
        }));
        var fields = [];
        for(i = 1; i <= fieldsQty; i++) {
            fields.push(_.pickBy(postData, function(value, key) {
                return key.split('_')[1] == i;
            }));
        }
        var formGenerator = [];
        var i = 0;
        _.forEach(fields, function(values, name) {
            i++;
            if(values["name_" + i]) {
                var field = {
                    type: values["type_" + i],
                    name: values["name_" + i].replace(' ', ''),
                    label: values["label_" + i],
                    disabled: values.hasOwnProperty("disabled_" + i) && values["disabled_" + i] == "on",
                    required: values.hasOwnProperty("required_" + i) && values["required_" + i] == "on"
                };
                if(/*type*/["select", "checkboxes", "radios"].indexOf(values["type_" + i]) >= 0) {
                    var options = {};
                    var defaultValue = [];
                    var j = 1;
                    while(values.hasOwnProperty("option_" + i + "_Value" + j)) {
                        if(values["option_" + i + "_Value" + j]) {
                            options[values["option_" + i + "_Value" + j]] = values["option_" + i + "_Text" + j];
                            if(values.hasOwnProperty("option_" + i + "_Selected" + j) && values["option_" + i + "_Selected" + j]) {
                                defaultValue.push(values["option_" + i + "_Value" + j]);
                            }
                        }
                        j++;
                    }
                    field.options = options;
                    field.defaultValue = defaultValue;
                }
                formGenerator.push(field);
            }
        });
        return formGenerator;
    }
};


text:
package com.bonnguyen.tax.test;

/**
 * Created by nguyenbon on 10/18/16.
 */

public interface BaseInteractor {
    long calcTax() throws IllegalArgumentException;
}


text:
<!-- smoosh -->
<script src='.tmp/bundle.js'></script>
<!-- endsmoosh -->


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

	<flex:message-broker mapping-order="1">
		<flex:mapping pattern="/messagebroker/*"/>
		<flex:message-service default-channels="longpolling-amf" />
	</flex:message-broker>

</beans>


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Bihangtill K. Svenska Vetensk. -Akad. Handl. , Afd. 3 25(no. 6): 3 (1899)

#### Original name
Stuartella drimydis Rehm

### Remarks
null


text:
<?php

namespace Log\Factory;

use Log\Service\LogService;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

class LogFactory implements FactoryInterface
 {
     /**
      * Create service
      *
      * @param ServiceLocatorInterface $serviceLocator
      *
      * @return mixed
      */
     public function createService(ServiceLocatorInterface $serviceLocator,  $Options = false)
     {
        return new LogService($serviceLocator, $Options);
     }
 }


text:
<?xml version="1.0"?>
<cd:ProductDefinition xmlns:cd="http://www.stcorp.nl/coda/definition/2008/07" id="AATSR_L3_nc3" format="netcdf" last-modified="2017-02-15">
</cd:ProductDefinition>


text:
"""
# Definition for a Node.
class Node:
    def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):
        self.val = int(x)
        self.next = next
        self.random = random
"""

class Solution:
    def copyRandomList(self, head: 'Node') -> 'Node':
        if not head:
            return None

        copies = collections.defaultdict(lambda: Node(0))
        copies[None] = None
        curr = head
        while curr:
            copies[curr].val = curr.val
            copies[curr].next = copies[curr.next]
            copies[curr].random = copies[curr.random]
            curr = curr.next
        return copies[head]

#         newHead = Node(head.val)
#         copies = {head: newHead}

#         curr = head.next
#         newCurr = newHead
#         while curr:
#             newNode = Node(curr.val)
#             copies[curr] = newNode
#             newCurr.next = newNode

#             newCurr = newCurr.next
#             curr = curr.next

#         newCurr = newHead
#         curr = head
#         while curr:
#             if curr.random:
#                 newCurr.random = copies[curr.random]
#             curr = curr.next
#             newCurr = newCurr.next
#         return newHead


text:
#pragma once
#include <aws/ec2/EC2_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSStreamFwd.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/ec2/model/LaunchPermission.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Xml
{
  class XmlNode;
} // namespace Xml
} // namespace Utils
namespace EC2
{
namespace Model
{

  /**
   *
Describes a launch permission modification.

See Also:
   AWS
   * API Reference

   */
  class AWS_EC2_API LaunchPermissionModifications
  {
  public:
    LaunchPermissionModifications();
    LaunchPermissionModifications(const Aws::Utils::Xml::XmlNode& xmlNode);
    LaunchPermissionModifications& operator=(const Aws::Utils::Xml::XmlNode& xmlNode);

    void OutputToStream(Aws::OStream& ostream, const char* location, unsigned index, const char* locationValue) const;
    void OutputToStream(Aws::OStream& oStream, const char* location) const;

    /**
     *
The Amazon Web Services account ID, organization ARN, or OU ARN to add to the
     * list of launch permissions for the AMI.

     */
    inline const Aws::Vector<LaunchPermission>& GetAdd() const{ return m_add; }

    /**
     *
The Amazon Web Services account ID, organization ARN, or OU ARN to add to the
     * list of launch permissions for the AMI.

     */
    inline bool AddHasBeenSet() const { return m_addHasBeenSet; }

    /**
     *
The Amazon Web Services account ID, organization ARN, or OU ARN to add to the
     * list of launch permissions for the AMI.

     */
    inline void SetAdd(const Aws::Vector<LaunchPermission>& value) { m_addHasBeenSet = true; m_add = value; }

    /**
     *
The Amazon Web Services account ID, organization ARN, or OU ARN to add to the
     * list of launch permissions for the AMI.

     */
    inline void SetAdd(Aws::Vector<LaunchPermission>&& value) { m_addHasBeenSet = true; m_add = std::move(value); }

    /**
     *
The Amazon Web Services account ID, organization ARN, or OU ARN to add to the
     * list of launch permissions for the AMI.

     */
    inline LaunchPermissionModifications& WithAdd(const Aws::Vector<LaunchPermission>& value) { SetAdd(value); return *this;}

    /**
     *
The Amazon Web Services account ID, organization ARN, or OU ARN to add to the
     * list of launch permissions for the AMI.

     */
    inline LaunchPermissionModifications& WithAdd(Aws::Vector<LaunchPermission>&& value) { SetAdd(std::move(value)); return *this;}

    /**
     *
The Amazon Web Services account ID, organization ARN, or OU ARN to add to the
     * list of launch permissions for the AMI.

     */
    inline LaunchPermissionModifications& AddAdd(const LaunchPermission& value) { m_addHasBeenSet = true; m_add.push_back(value); return *this; }

    /**
     *
The Amazon Web Services account ID, organization ARN, or OU ARN to add to the
     * list of launch permissions for the AMI.

     */
    inline LaunchPermissionModifications& AddAdd(LaunchPermission&& value) { m_addHasBeenSet = true; m_add.push_back(std::move(value)); return *this; }

    /**
     *
The Amazon Web Services account ID, organization ARN, or OU ARN to remove
     * from the list of launch permissions for the AMI.

     */
    inline const Aws::Vector<LaunchPermission>& GetRemove() const{ return m_remove; }

    /**
     *
The Amazon Web Services account ID, organization ARN, or OU ARN to remove
     * from the list of launch permissions for the AMI.

     */
    inline bool RemoveHasBeenSet() const { return m_removeHasBeenSet; }

    /**
     *
The Amazon Web Services account ID, organization ARN, or OU ARN to remove
     * from the list of launch permissions for the AMI.

     */
    inline void SetRemove(const Aws::Vector<LaunchPermission>& value) { m_removeHasBeenSet = true; m_remove = value; }

    /**
     *
The Amazon Web Services account ID, organization ARN, or OU ARN to remove
     * from the list of launch permissions for the AMI.

     */
    inline void SetRemove(Aws::Vector<LaunchPermission>&& value) { m_removeHasBeenSet = true; m_remove = std::move(value); }

    /**
     *
The Amazon Web Services account ID, organization ARN, or OU ARN to remove
     * from the list of launch permissions for the AMI.

     */
    inline LaunchPermissionModifications& WithRemove(const Aws::Vector<LaunchPermission>& value) { SetRemove(value); return *this;}

    /**
     *
The Amazon Web Services account ID, organization ARN, or OU ARN to remove
     * from the list of launch permissions for the AMI.

     */
    inline LaunchPermissionModifications& WithRemove(Aws::Vector<LaunchPermission>&& value) { SetRemove(std::move(value)); return *this;}

    /**
     *
The Amazon Web Services account ID, organization ARN, or OU ARN to remove
     * from the list of launch permissions for the AMI.

     */
    inline LaunchPermissionModifications& AddRemove(const LaunchPermission& value) { m_removeHasBeenSet = true; m_remove.push_back(value); return *this; }

    /**
     *
The Amazon Web Services account ID, organization ARN, or OU ARN to remove
     * from the list of launch permissions for the AMI.

     */
    inline LaunchPermissionModifications& AddRemove(LaunchPermission&& value) { m_removeHasBeenSet = true; m_remove.push_back(std::move(value)); return *this; }

  private:

    Aws::Vector<LaunchPermission> m_add;
    bool m_addHasBeenSet;

    Aws::Vector<LaunchPermission> m_remove;
    bool m_removeHasBeenSet;
  };

} // namespace Model
} // namespace EC2
} // namespace Aws


text:
maintainer       'Wesleyan University'
maintainer_email 'software@wesleyan.edu'
license          'Apache 2.0'
description      'Installs Adobe Illustrator'
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
version          '0.3.0'


text:
var Path = nodeRequire('path');
var $ = require('jquery');
var _ = require('underscore');
var Files = require('./files');

var menubar = new gui.Menu({ type: 'menubar' });
if (!isWin) {
  menubar.createMacBuiltin("p5");
}
var fileMenu = new gui.Menu();
var help = new gui.Menu();

var view = new gui.Menu();
var win = gui.Window.get();
var recentFilesMenu = new gui.Menu();
var exampleCategoryMenu = new gui.Menu();
var openRecent, examples;
var fs = nodeRequire('fs');

/* setup the menubar menus, submenus, functions and shortcuts. Conceptually the
 * menubar is an array of Menus, each of which is an array of MenuItems.
 * Menuitems may themselves be a submenu
 */
module.exports.setup = function(app) {
  if (isWin) {
    //Setup menus for windows
    fileMenu.append(new gui.MenuItem({
      label: 'New Project                          Ctrl+Shift+N',
      modifiers: 'shift-ctrl', key: 'n', click: function(){
        app.newWindow(app.windowURL);
    }}));

    fileMenu.append(new gui.MenuItem({
      label: 'New File                                           Ctrl+N',
      modifiers: 'ctrl', key: 'n', click: function(){
        app.newFile();
    }}));

    fileMenu.append(new gui.MenuItem({
      label: 'New Folder',
      click: function(){
        app.newFolder();
    }}));

    fileMenu.append(new gui.MenuItem({
      label: 'Open                                                 Ctrl+O',
      modifiers: 'ctrl', key: 'o', click: function(){
        $('#openFile').trigger('click');
    }}));

    openRecent = new gui.MenuItem({label: 'Open Recent'});
    module.exports.updateRecentFiles(app);
    fileMenu.append(openRecent);

    fileMenu.append(new gui.MenuItem({
      label: 'Close                                                Ctrl+W',
      modifiers: 'ctrl', key: 'w', click: function(){
        app.closeProject();
    }}));

    fileMenu.append(new gui.MenuItem({
      label: 'Save                                                   Ctrl+S',
      modifiers: 'ctrl', key: 's', click: function(){
        app.saveFile();
    }}));

    // fileMenu.append(new gui.MenuItem({
    //   label: 'Save File As...                         Ctrl+Shift+S',
    //   modifiers: 'shift-ctrl', key: 's', click: function(){
    //     app.saveFileAs(app.currentFile.path);
    // }}));

    fileMenu.append(new gui.MenuItem({
      label: 'Save As...           Ctrl+Shift+S',
      modifiers: 'shift-ctrl', key: 's', click: function(){
        $('#saveProject').trigger('click');
    }}));

    // add menu option for loading example sketches
    examples = new gui.MenuItem({label: 'Examples'});
    // create submenu
    var exampleDir = Path.join('mode_assets', 'p5', 'examples');
    // get latest example categories
    var files = fs.readdirSync(exampleDir);

    files.forEach(function(category) {
      var sketchMenu = new gui.Menu();
      var categoryLabel = new gui.MenuItem({label: category});
      // populate submenu with sketches for that category
      var categoryDir = Path.join(exampleDir, category);
      if (fs.lstatSync(categoryDir).isDirectory()) {
        var sketches = fs.readdirSync(categoryDir);
        sketches.forEach(function(fileName) {
          sketchMenu.append(new gui.MenuItem({label: Files.cleanExampleName(fileName), click: function(){
            app.modeFunction('launchExample', exampleDir.concat('/').concat(category).concat('/').concat(fileName));
          }}));
        });
        categoryLabel.submenu = sketchMenu;
        exampleCategoryMenu.append(categoryLabel);
      }
    });

    examples.submenu = exampleCategoryMenu;
    fileMenu.append(examples);

    fileMenu.append(new gui.MenuItem({ type: 'separator' }));

    fileMenu.append(new gui.MenuItem({
      label: 'Run                           Ctrl+R',
      modifiers: 'ctrl', key: 'r', click: function(){
        app.run();
    }}));

    view.append(new gui.MenuItem({
      label: 'Show Sketch Folder             Ctrl+K',
        modifiers: 'ctrl', key: 'k', click: function(){
          gui.Shell.showItemInFolder(app.projectPath);
    }}));

    view.append(new gui.MenuItem({ type: 'separator' }));

    view.append(new gui.MenuItem({
      label: 'Reformat                               Ctrl+T',
        modifiers: 'ctrl', key: 't', click: function(){
          app.$.editor.reformat();
    }}));

    view.append(new gui.MenuItem({ type: 'separator' }));

    view.append(new gui.MenuItem({
      label: 'Toggle Settings Panel           Ctrl+,',
      modifiers: 'ctrl', key: ',', click: function(){
        app.toggleSettingsPane();
    }}))

    view.append(new gui.MenuItem({
      label: 'Toggle Sidebar                       Ctrl+.',
      modifiers: 'ctrl', key: '.', click: function(){
        app.toggleSidebar();
    }}))

    view.append(new gui.MenuItem({ type: 'separator' }));

    view.append(new gui.MenuItem({
      label: 'Increase Font Size                 Ctrl+=',
      modifiers: 'ctrl', key: '=', click: function(){
        app.changeFontSize(1);
    }}))

    view.append(new gui.MenuItem({
      label: 'Decrease Font Size                Ctrl+-',
      modifiers: 'ctrl', key: '-', click: function(){
        app.changeFontSize(-1);
    }}))
  } else {
    fileMenu.append(new gui.MenuItem({ label: 'New Project',
      modifiers: 'shift-cmd', key: 'n', click: function(){
        app.newWindow(app.windowURL);
    }}));

    fileMenu.append(new gui.MenuItem({ label: 'New File',
      modifiers: 'cmd', key: 'n', click: function(){
        app.newFile();
    }}));

    fileMenu.append(new gui.MenuItem({ label: 'New Folder',
      click: function(){
        app.newFolder();
    }}));

    fileMenu.append(new gui.MenuItem({ label: 'Open',
      modifiers: 'cmd', key: 'o', click: function(){
        $('#openFile').trigger('click');
    }}));

    openRecent = new gui.MenuItem({label: 'Open Recent'});
    openRecent.submenu = recentFilesMenu;
    fileMenu.append(openRecent);

    fileMenu.append(new gui.MenuItem({ label: 'Close',
      modifiers: 'cmd', key: 'w', click: function(){
        app.closeProject();
    }}));

    fileMenu.append(new gui.MenuItem({ label: 'Save',
      modifiers: 'cmd', key: 's', click: function(){
        app.saveFile();
    }}));

    // fileMenu.append(new gui.MenuItem({ label: 'Save File As...',
    //   modifiers: 'shift-cmd', key: 's', click: function(){
    //     app.saveFileAs(app.currentFile.path);
    // }}));

    fileMenu.append(new gui.MenuItem({ label: 'Save As...',
      modifiers: 'shift-cmd', key: 's', click: function(){
        $('#saveProject').trigger('click');
    }}));

    // add menu option for loading example sketches
    examples = new gui.MenuItem({label: 'Examples'});
    // create submenu
    var exampleDir = Path.join('mode_assets', 'p5', 'examples');
    // get latest example categories
    var files = fs.readdirSync(exampleDir);

    files.forEach(function(category) {
      var sketchMenu = new gui.Menu();
      var categoryLabel = new gui.MenuItem({label: category});
      // populate submenu with sketches for that category
      var categoryDir = Path.join(exampleDir, category);
      if (fs.lstatSync(categoryDir).isDirectory()) {
        var sketches = fs.readdirSync(categoryDir);
        sketches.forEach(function(fileName) {
          sketchMenu.append(new gui.MenuItem({label: Files.cleanExampleName(fileName), click: function(){
            app.modeFunction('launchExample', exampleDir.concat('/').concat(category).concat('/').concat(fileName));
          }}));
        });
        categoryLabel.submenu = sketchMenu;
        exampleCategoryMenu.append(categoryLabel);
      }
    });

    examples.submenu = exampleCategoryMenu;
    fileMenu.append(examples);

    fileMenu.append(new gui.MenuItem({ type: 'separator' }));

    fileMenu.append(new gui.MenuItem({ label: 'Run',
      modifiers: 'cmd', key: 'r', click: function(){
        app.run();

    }}));

    view.append(new gui.MenuItem({ label: 'Show Sketch Folder',
        modifiers: 'cmd', key: 'k', click: function(){
          gui.Shell.showItemInFolder(app.projectPath);
    }}));

    view.append(new gui.MenuItem({ type: 'separator' }));

    view.append(new gui.MenuItem({ label: 'Reformat',
        modifiers: 'cmd', key: 't', click: function(){
          app.$.editor.reformat();
    }}));

    view.append(new gui.MenuItem({ type: 'separator' }));

    view.append(new gui.MenuItem({ label: 'Toggle Settings Panel',
      modifiers: 'cmd', key: ',', click: function(){
        app.toggleSettingsPane();
    }}))

    view.append(new gui.MenuItem({ label: 'Toggle Sidebar',
      modifiers: 'cmd', key: '.', click: function(){
        app.toggleSidebar();
    }}))

    view.append(new gui.MenuItem({ type: 'separator' }));

    view.append(new gui.MenuItem({ label: 'Increase Font Size',
      modifiers: 'cmd', key: '=', click: function(){
        app.changeFontSize(1);
    }}))

    view.append(new gui.MenuItem({ label: 'Decrease Font Size',
      modifiers: 'cmd', key: '-', click: function(){
        app.changeFontSize(-1);
    }}))
  }

  help.append(new gui.MenuItem({ label: 'Reference', click: function(){
    app.showHelp();
  }}));

  if (isWin) {
    menubar.append(new gui.MenuItem({ label: 'File', submenu: fileMenu}));
    menubar.append(new gui.MenuItem({ label: 'View', submenu: view}));
  } else {
    menubar.insert(new gui.MenuItem({ label: 'File', submenu: fileMenu}),1);
    menubar.insert(new gui.MenuItem({ label: 'View', submenu: view}), 3);
  }

  menubar.append(new gui.MenuItem({ label: 'Help', submenu: help}));

  /* The Edit Menu exists by default, so we obtain the reference to it here and
   * add tot he pre-existing menu
   */
  // Many of these menuItems are different because the ace/brace editor has
  // native shortcuts for these commands. Their respective menuItmes only react
  // to being clicked on, so the shortcuts work without interference.
  if (isWin) {
    var edit = new gui.Menu();

    var undo = new gui.MenuItem(
        { label: 'Undo                                       Ctrl+Z',
          modifiers: 'ctrl', key: 'z', click: function(){
        }});
    undo.on('click', function(){
      app.$.editor.ace.execCommand("undo");
    });
    edit.append(undo);

    var redo = new gui.MenuItem(
        { label: 'Redo                             Ctrl+Shift+Z',
          modifiers: 'shift-ctrl', key: 'z', click: function(){
        }});
    redo.on('click', function(){
      app.$.editor.ace.execCommand("redo");
    });
    edit.append(redo);

    edit.append(new gui.MenuItem({ type: 'separator' }));

    var cut = new gui.MenuItem(
        { label: 'Cut                                          Ctrl+X',
          modifiers: 'ctrl', key: 'x', click: function(){
        }});
    cut.on('click', function(){
      document.execCommand("cut");
    });
    edit.append(cut);

    var copy = new gui.MenuItem(
        { label: 'Copy                                       Ctrl+C',
          modifiers: 'ctrl', key: 'c', click: function(){
        }});
    copy.on('click', function(){
      document.execCommand("copy");
    });
    edit.append(copy);

    var paste = new gui.MenuItem(
        { label: 'Paste                                       Ctrl+V',
          modifiers: 'ctrl', key: 'v', click: function(){
        }});
    paste.on('click', function(){
      document.execCommand("paste");
    });
    edit.append(paste);

    var del = new gui.MenuItem(
        { label: 'Delete                                     Ctrl+D',
          modifiers: 'ctrl', key: 'd', click: function(){
        }});
    del.on('click', function(){
      app.$.editor.ace.execCommand("del");
    });
    edit.append(del);

    var selAll  = new gui.MenuItem(
        { label: 'Select All                                Ctrl+A',
          modifiers: 'ctrl', key: 'a', click: function(){
        }});
    selAll.on('click', function(){
      app.$.editor.ace.execCommand("selectall");
    });
    edit.append(selAll);

    edit.append(new gui.MenuItem({ type: 'separator' }));

    var findItem = new gui.MenuItem(
        { label: 'Find                                         Ctrl+F',
        modifiers: 'ctrl', key: 'f', click: function(){
        }});
    findItem.on('click', function(){
      app.$.editor.ace.execCommand("find");
    });
    edit.append(findItem);

    var repItem = new gui.MenuItem(
      { label: 'Find and Replace           Ctrl+Alt+F',
        modifiers: 'ctrl-alt', key: 'f', click: function(){
      }});
    repItem.on('click', function(e){
      app.$.editor.ace.execCommand("replace");
    });
    edit.append(repItem);

    menubar.insert(new gui.MenuItem({ label: 'Edit', submenu: edit}), 2);

  } else {
    // get the existing edit menu
    var edit = menubar.items[2].submenu;

    // the native undo isn't allowing us to bind a click event on OS X,
    // current (hacky) solution is to remove the existing one and add a new one
    edit.remove(edit.items[0]);

    // create the new undo menu item
    var undo = new gui.MenuItem({
        label: 'Undo',
        key: "z"
    });

    // add event listener
    undo.on('click', function() {
      // execute ace editor undo command
      app.$.editor.ace.execCommand("undo");
    });

    // insert the new undo at the beginning
    edit.insert(undo, 0);

    edit.append(new gui.MenuItem({ type: 'separator' }));

    // Find and Find and Replace are different because the ace/brace editor has
    // native shortcuts for these commands. These two MenuItems only react
    // to being clicked on, so the shortcuts work without interference.
    var findItem = new gui.MenuItem(
        { label: 'Find', modifiers: 'cmd', key: 'f', click: function(){
        }});

    findItem.on('click', function(){
      console.log('find');
      app.$.editor.ace.execCommand("find");
    });

    edit.append(findItem);

    var repItem = new gui.MenuItem(
      { label: 'Find and Replace',
        modifiers: 'cmd-alt', key: 'f', click: function(){
      }});

    repItem.on('click', function(e){
      app.$.editor.ace.execCommand("replace");
    });

    edit.append(repItem);
  }

  win.menu = menubar;

};

//reset the menubar to the current window's frame of reference. Used whenever
//the user switches focus between windows
module.exports.resetMenu = function() {
  win.menu = menubar;
};

module.exports.updateRecentFiles = function(app, path) {
  var recentFiles = JSON.parse(localStorage.recentFiles || '[]');

  if (typeof path !== 'undefined' && !app.temp) {
    recentFiles.unshift(path);
  }

  recentFiles = _.unique(recentFiles);

  if (recentFiles.length > 10) recentFiles.pop();

  localStorage.recentFiles = JSON.stringify(recentFiles);

  // clear the recentFilesMenu because we're going to repopulate it
  recentFilesMenu = new gui.Menu();
  openRecent.submenu = recentFilesMenu;

  // iterate through the recentFiles and append to the openRecent submenu
  recentFiles.forEach(function(p) {
    var m = new gui.MenuItem({ label: Path.basename(p), click: function() {
      app.openProject(p);
    }});
    recentFilesMenu.append(m);
  });
  if (recentFiles.length > 0) {
    recentFilesMenu.append(new gui.MenuItem({type: 'separator'}));
    recentFilesMenu.append(new gui.MenuItem({label: 'Clear Recent Projects', click: function(){
      localStorage.recentFiles = [];
      module.exports.updateRecentFiles(app);
    }}));
  }

  openRecent.enabled = (recentFiles.length !== 0);
};