text:
///////////////////////////////////////////////////////////////////
/*
definitions and prototypes for LAPPD PSEC4 DAQ readout
updated 31-10-2014
author: eric oberla
*/
///////////////////////////////////////////////////////////////////

#pragma once

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <time.h>
#include <vector>
#include <string>

#include "stdUSB.h"
#include "Definitions.h"
#include "Packet.h"

enum cc_readout_mode {
  USB = 0, USB2x = 1, ETH = 2, UNK = 3
};

class SuMo {

public:
  SuMo();

  ~SuMo();

  void sync_usb(bool SYNC);

  //instructions to hardware
  void reset_dll(bool sync = false);

  void reset_self_trigger(unsigned int mask, int device = 0);

  void reset_time_stamp(bool sync = false);

  void reset_acdc();

  void align_lvds();

  //front-end card specific instructions
  void toggle_LED(bool EN);

  void toggle_CAL(bool EN, int device = 0);

  void set_self_trigger_lo(bool ENABLE_TRIG, bool SYS_TRIG_OPTION,
                           bool RATE_ONLY, bool TRIG_SIGN, bool USE_SMA,
                           bool USE_COINCIDENCE, bool USE_FAST_COINCIDENCE,
                           unsigned int coinc_window,
                           unsigned int mask, int device = 0);

  void set_self_trigger_hi(unsigned int coinc_pulse_width,
                           unsigned int asic_coincidence_min,
                           unsigned int channel_coincidence_min,
                           unsigned int mask, int device = 0);

  void set_self_trigger_mask(int mask, bool HILO, unsigned int board_mask, int device = 0);

  //chip-level instructions
  void set_pedestal_value(unsigned int PED_VALUE, unsigned int mask, int device = 0, unsigned int psec_mask = 31);

  void set_dll_vdd(unsigned int VALUE, unsigned int mask, int device = 0, unsigned int psec_mask = 31);

  void set_trig_threshold(unsigned int TRIG_VALUE, unsigned int mask, int device = 0, unsigned int psec_mask = 31);

  void
  set_ro_target_count(unsigned int TARGET_RO_COUNT, unsigned int mask, int device = 0, unsigned int psec_mask = 31);

  //manage PC interface
  void set_usb_read_mode(unsigned int READ_MODE);

  void set_usb_read_mode_slaveDevice(unsigned int READ_MODE);

  void manage_cc_fifo(bool VALUE);

  void manage_cc_fifo_slaveDevice(bool VALUE);

  void system_card_trig_valid(bool valid);

  void system_slave_card_trig_valid(bool valid);

  void hard_reset(bool DEVICE = false);

  void usb_force_wakeup();

  void readACDC_RAM(int device, unsigned int mask);

  void cleanup();

  void prep_sync();

  void make_sync();

  //send trigger over software
  void software_trigger(unsigned int SOFT_TRIG_MASK, bool set_bin = false, unsigned int bin = 0);

  void software_trigger_slaveDevice(unsigned int SOFT_TRIG_MASK, bool set_bin = false, unsigned int bin = 0);

  //readout functions
  int check_readout_mode();

  int read_CC(bool SHOW_CC_STATUS, bool SHOW_AC_STATUS, int device = 0, int triGmode = 0);

  int measure_rate(bool *AC_read_mask); //To be used in Automation function.
  void adjust_thresh(int threshold, unsigned int board_number);

  /* this function modifies class variables BOARDS_READOUT & BOARDS_TIMEOUT for additional retval handling: */
  int read_AC(unsigned int trig_mode, bool *mask, bool FILESAVE,
              bool sync = false, bool set_bin = false, unsigned int bin = 0);

  void dump_data();

  //int  get_AC_info(bool PRINT, int AC_adr);
  int *get_AC_info(bool PRINT, int frontEnd, bool PRINTALL = false, int count = 0, double time = 0.,
                   double dateTime = 0., int evts = 0);         //parse meta-data from raw data stream

  int generate_ped(
          bool ENABLE_FILESAVE);              //generate pedestal calibration files for each active board (one per sample cell)
  int
  make_count_to_voltage();                     //make count-to-voltage LUT for each active board (# active boards * 6 channels * 1536 cells * 4096 !!)

  int load_ped();

  int log_data(unsigned int NUM_READS, int trig_mode, int acq_rate, const char *log_filename);

  int check_active_boards(bool print);

  int check_active_boards(int NUM);

  int check_active_boards_slaveDevice();

  bool DC_ACTIVE[numFrontBoards];           //TRUE if boards are connected and synced
  bool EVENT_FLAG[numFrontBoards];
  bool CAUGHT_EVENT_FLAG[numFrontBoards];
  bool DIGITIZING_START_FLAG[numFrontBoards];
  bool BOARDS_READOUT[numFrontBoards];      //TRUE if board was successfully readout when data requested
  bool BOARDS_TIMEOUT[numFrontBoards];      //TRUE if board was unsuccessfully readout when data requested (timeout error)

  unsigned int CC_EVENT_COUNT_FROMCC0;
  unsigned int CC_EVENT_COUNT_FROMCC1;

  struct packet_t *adcDat[numFrontBoards];
  enum cc_readout_mode mode;

  static void sys_wait(unsigned int sleep) {
      usleep(sleep);
  }

  bool fileExists(const std::string &filename);

  unsigned int PED_DATA[numFrontBoards][AC_CHANNELS][psecSampleCells];

private:
  void createUSBHandles();

  void closeUSBHandles();

  int unwrap(int ASIC);

  void unwrap_baseline(int *baseline, int ASIC);

  void print_to_terminal(int k, int NUM_READS, int cc_event, int board_trig, double t);

  struct cal_t {
    unsigned short raw_ped_data_array[AC_CHANNELS][psecSampleCells][num_ped_reads];
    /* calibration arrays */
    unsigned int PED_DATA[AC_CHANNELS][psecSampleCells];
    float PED_RMS[AC_CHANNELS][psecSampleCells];
    bool PED_SUCCESS;
  } calData[numFrontBoards];

  static int compare(const void *a, const void *b) {
      return (*(unsigned short *) a - *(unsigned short *) b);
  }

  int metaData[psecSampleCells];

  int put_lut_on_heap(
          bool *range); // cpu memory management when taking full count-to-voltage calibration scan
  void free_lut_from_heap(
          bool *range); // cpu memory management when taking full count-to-voltage calibration scan

  float ***LUT_CELL;
  int ***LUT_CELL_COPY;
  float ***LUT;
  float ***LUT_COPY;

  /* metadata from CC */
  unsigned int CC_INFO[cc_buffersize];
  unsigned int LAST_CC_INSTRUCT;
  unsigned int CC_TIMESTAMP_LO;
  unsigned int CC_TIMESTAMP_HI;
  unsigned int CC_EVENT_COUNT;
  unsigned int CC_BIN_COUNT;
  unsigned int CC_EVENT_NO;

protected:
  stdUSB usb;        //object to handle USB device
  stdUSBSlave usb2;       //object to handle USB slave device

};


text:
require('./errors')

Parse_Result = Struct.new(:symbol, :remaining_tokens)

def parse(symbol_to_parse, tokens, parser_table, terminals, nullables)

    if tokens.length == 0
        if nullables.include?(symbol_to_parse)
            return Parse_Result.new({type: symbol_to_parse, value: nil}, tokens)
        else
            raise ParserError.new, "Unexpected end of input"
        end
    end

    current_token_type = tokens[0].type

    if terminals.include? symbol_to_parse
        if current_token_type == symbol_to_parse
            return Parse_Result.new({type: symbol_to_parse, value: tokens[0].value}, tokens[1..-1])
        else
            raise ParserError.new, "Unexpected " + tokens[0].value
        end
    else

        rule = parser_table[current_token_type][symbol_to_parse]
        puts  "Parsing: " + symbol_to_parse.to_s +  " Current Token: " + tokens[0].value + " using rule " + symbol_to_parse.to_s + " ::= " + rule.to_s

        raise ParserError.new, "Unexpected " + tokens[0].value if rule == nil

        return Parse_Result.new({type: symbol_to_parse, value: nil}, tokens) if rule == []

        parsed_symbols = []
        rule.each do | symbol |
            parse_result = parse(symbol, tokens, parser_table, terminals, nullables)
            # Remove parentheses nodes from expression
            parse_result[0][:value] = [parse_result[0][:value][1]] if parse_result[0][:type] == :F && parse_result[0][:value][0][:type] == :OPENPAREN
            tokens = parse_result.remaining_tokens
            parsed_symbols << parse_result.symbol
        end

        return Parse_Result.new({type: symbol_to_parse, value:parsed_symbols}, tokens)
    end

end

redpajama_set_name: RedPajamaGithub


text:
"""Testing for pkg_tar."""

import tarfile
import unittest

from bazel_tools.tools.python.runfiles import runfiles
from pkg.private.tar import tar_writer

PORTABLE_MTIME = 946684800  # 2000-01-01 00:00:00.000 UTC

class PkgTarTest(unittest.TestCase):
  """Testing for pkg_tar rule."""

  def assertTarFileContent(self, file_name, content, verbose=False):
    """Assert that tarfile contains exactly the entry described by `content`.

    Args:
        file_name: the path to the TAR file to test.
        content: an array describing the expected content of the TAR file.
            Each entry in that list should be a dictionary where each field
            is a field to test in the corresponding TarInfo. For
            testing the presence of a file "x", then the entry could simply
            be `{'name': 'x'}`, the missing field will be ignored. To match
            the content of a file entry, use the key 'data'.
    """
    # NOTE: This is portable to Windows. os.path.join('rules_pkg', 'tests',
    # filename) is not.
    file_path = runfiles.Create().Rlocation('rules_pkg/tests/tar/' + file_name)
    got = []
    with tarfile.open(file_path, 'r:*') as f:
      i = 0
      for info in f:
        if verbose:
          print('  >> from tar file:', info.name)
        error_msg = 'Extraneous file at end of archive %s: %s' % (
            file_path,
            info.name
            )
        self.assertLess(i, len(content), error_msg)
        for k, v in content[i].items():
          if k == 'halt':
            return
          elif k == 'data':
            value = f.extractfile(info).read()
          elif k == 'isdir':
            value = info.isdir()
          else:
            value = getattr(info, k)
          if k == 'mode':
            p_value = '0o%o' % value
            p_v = '0o%o' % v
          else:
            p_value = str(value)
            p_v = str(v)
          error_msg = ' '.join([
              'Value `%s` for key `%s` of file' % (p_value, k),
              '%s in archive %s does' % (info.name, file_path),
              'not match expected value `%s`' % p_v
              ])
          self.assertEqual(value, v, error_msg)
          if value != v:
            print(error_msg)
        i += 1
      if i < len(content):
        self.fail('Missing file %s in archive %s of [%s]' % (
            content[i], file_path, ',\n    '.join(got)))

  def test_strip_prefix_empty(self):
    content = [
        {'name': 'nsswitch.conf'},
    ]
    self.assertTarFileContent('test-tar-strip_prefix-empty.tar', content)

  def test_strip_prefix_none(self):
    content = [
        {'name': 'nsswitch.conf'},
    ]
    self.assertTarFileContent('test-tar-strip_prefix-none.tar', content)

  def test_strip_prefix_etc(self):
    content = [
        {'name': 'nsswitch.conf'},
    ]
    self.assertTarFileContent('test-tar-strip_prefix-etc.tar', content)

  def test_strip_prefix_substring(self):
    content = [
        {'name': 'etc', 'isdir': True},
        {'name': 'etc/nsswitch.conf'},
    ]
    self.assertTarFileContent('test-tar-strip_prefix-substring.tar', content)

  def test_strip_prefix_dot(self):
    content = [
        {'name': 'etc'},
        {'name': 'etc/nsswitch.conf'},
        {'name': 'external'},
        {'name': 'external/bazel_tools'},
        {'name': 'external/bazel_tools/tools'},
        {'name': 'external/bazel_tools/tools/python'},
        {'name': 'external/bazel_tools/tools/python/runfiles'},
        # This is brittle. In old bazel the next file would be
        # external/bazel_tools/tools/python/runfiles/runfiles.py, but there
        # is now _runfiles_constants.py, first. So this is too brittle.
        {'halt': None},
    ]
    self.assertTarFileContent('test-tar-strip_prefix-dot.tar', content)

  def test_strip_files_dict(self):
    content = [
        {'name': 'not-etc'},
        {'name': 'not-etc/mapped-filename.conf'},
    ]
    self.assertTarFileContent('test-tar-files_dict.tar', content)

  def test_empty_files(self):
    content = [
        {'name': 'a', 'size': 0, 'uid': 0},
        {'name': 'b', 'size': 0, 'uid': 0, 'mtime': PORTABLE_MTIME},
    ]
    self.assertTarFileContent('test-tar-empty_files.tar', content)

  def test_empty_dirs(self):
    content = [
        {'name': 'pmt', 'isdir': True, 'size': 0, 'uid': 0,
         'mtime': PORTABLE_MTIME},
        {'name': 'tmp', 'isdir': True, 'size': 0, 'uid': 0,
         'mtime': PORTABLE_MTIME},
    ]
    self.assertTarFileContent('test-tar-empty_dirs.tar', content)

  def test_mtime(self):
    # Note strange mtime. It is specified in the BUILD file.
    content = [
        {'name': 'nsswitch.conf', 'mtime': 946684740},
    ]
    self.assertTarFileContent('test-tar-mtime.tar', content)

  def test_basic(self):
    # Check the set of 'test-tar-basic-*' smoke test.
    content = [
        {'name': 'etc',
         'uid': 24, 'gid': 42, 'uname': 'tata', 'gname': 'titi'},
        {'name': 'etc/nsswitch.conf',
         'mode': 0o644,
         'uid': 24, 'gid': 42, 'uname': 'tata', 'gname': 'titi'
         },
        {'name': 'usr',
         'uid': 42, 'gid': 24, 'uname': 'titi', 'gname': 'tata'},
        {'name': 'usr/bin'},
        {'name': 'usr/bin/java', 'linkname': '/path/to/bin/java'},
        {'name': 'usr/titi',
         'mode': 0o755,
         'uid': 42, 'gid': 24, 'uname': 'titi', 'gname': 'tata'},
    ]
    for ext in [('.' + comp if comp else '')
                for comp in tar_writer.COMPRESSIONS]:
      with self.subTest(ext=ext):
        self.assertTarFileContent('test-tar-basic-%s.tar%s' % (ext[1:], ext),
                                  content)

  def test_file_inclusion(self):
    content = [
        {'name': 'etc', 'uid': 24, 'gid': 42},
        {'name': 'etc/nsswitch.conf', 'mode': 0o644, 'uid': 24, 'gid': 42},
        {'name': 'usr', 'uid': 42, 'gid': 24},
        {'name': 'usr/bin'},
        {'name': 'usr/bin/java', 'linkname': '/path/to/bin/java'},
        {'name': 'usr/titi', 'mode': 0o755, 'uid': 42, 'gid': 24},
        {'name': 'BUILD'},
    ]
    for ext in [('.' + comp if comp else '')
                for comp in tar_writer.COMPRESSIONS]:
      with self.subTest(ext=ext):
        self.assertTarFileContent('test-tar-inclusion-%s.tar' % ext[1:],
                                  content)

  def test_strip_prefix_empty(self):
    content = [
        {'name': 'level1'},
        {'name': 'level1/some_value'},
        {'name': 'level1/some_value/level3'},
        {'name': 'level1/some_value/level3/BUILD'},
    ]
    self.assertTarFileContent('test_tar_package_dir_substitution.tar', content)

  def test_tar_with_long_file_name(self):
    content = [
      {'name': 'file_with_a_ridiculously_long_name_consectetur_adipiscing_elit_fusce_laoreet_lorem_neque_sed_pharetra_erat.txt'}
    ]
    self.assertTarFileContent('test-tar-long-filename.tar', content)

  def test_repackage_file_with_long_name(self):
    content = [
      {'name': 'can_i_repackage_a_file_with_a_long_name'},
      {'name': 'can_i_repackage_a_file_with_a_long_name/file_with_a_ridiculously_long_name_consectetur_adipiscing_elit_fusce_laoreet_lorem_neque_sed_pharetra_erat.txt'}
    ]
    self.assertTarFileContent('test-tar-repackaging-long-filename.tar', content)

  def test_tar_with_tree_artifact(self):
    # (sorted) list of files:
    #  "a/a"
    #  "a/b/c"
    #  "b/c/d"
    #  "b/d"
    #  "b/e"

    content = [
      {'name': 'a_tree', 'isdir': True},
      {'name': 'a_tree/generate_tree', 'isdir': True, 'mode': 0o755},
      {'name': 'a_tree/generate_tree/a', 'isdir': True, 'mode': 0o755},
      {'name': 'a_tree/generate_tree/a/a'},
      {'name': 'a_tree/generate_tree/a/b', 'isdir': True, 'mode': 0o755},
      {'name': 'a_tree/generate_tree/a/b/c'},
      {'name': 'a_tree/generate_tree/b', 'isdir': True, 'mode': 0o755},
      {'name': 'a_tree/generate_tree/b/c', 'isdir': True, 'mode': 0o755},
      {'name': 'a_tree/generate_tree/b/c/d'},
      {'name': 'a_tree/generate_tree/b/d'},
      {'name': 'a_tree/generate_tree/b/e'},
      {'name': 'a_tree/loremipsum.txt'},
    ]
    self.assertTarFileContent('test-tar-tree-artifact.tar', content)

    # Now test against the tree artifact with the dir name stripped.
    noroot_content = []
    for c in content[1:]:  # one less level in tree. Skip first element.
      nc = dict(c)
      nc['name'] = c['name'].replace('/generate_tree', '')
      noroot_content.append(nc)
    self.assertTarFileContent('test-tar-tree-artifact-noroot.tar',
                              noroot_content)

  def test_tar_with_runfiles(self):
    content = [
      {'name': 'BUILD' },
      {'name': 'a_program' },
      {'name': 'executable.sh' },
    ]
    self.assertTarFileContent('test-tar-with-runfiles.tar', content)

  def test_tar_leading_dotslash(self):
    content = [
      {'name': './loremipsum.txt'},
    ]
    self.assertTarFileContent('test_tar_leading_dotslash.tar', content)

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


text:
import { env, inject, on, state } from "oly";
import { action } from "./decorators/action";
import { attach } from "./decorators/attach";

/**
 * use @inject/on/state/env on React.Component will also set @attach.
 */
export const autoAttach = () => {

  const setAttach = (instance: any) => {
    const target = instance.constructor;

    if (!target || !target.prototype || !target.prototype.render) {
      return;
    }

    attach()(target);
  };

  [inject, state, env].forEach((decorator: any) => {
    decorator["hooks"].beforeAsProperty.push(setAttach);
  });

  [action, on].forEach((decorator: any) => {
    decorator["hooks"].beforeAsMethod.push(setAttach);
  });
};


text:
{% load cms_tags %}
<div class="container">
{% for plugin in instance.child_plugin_instances %}
    {% render_plugin plugin %}
{% endfor %}
</div>


text:
package ru.job4j.selfhashtabletest;

import org.junit.Test;
import ru.job4j.selfhashtable.SelfHashTable;

import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;

/**
 * Created by user on 15.12.2017.
 */
public class SelfHashTableTest {
    @Test
    public void iteratorTest1() {
        SelfHashTable selfHashTable = new SelfHashTable();

        selfHashTable.add(5);
        selfHashTable.remove(5);
        Object result = selfHashTable.contains(0);

        assertThat(result, is(true));
    }

    @Test
    public void iteratorTest2() {
        SelfHashTable selfHashTable = new SelfHashTable();

        selfHashTable.add(5);
        Object result = selfHashTable.contains(0);

        assertThat(result, is(true));
    }
}


text:
<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateCommentsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('comments', function (Blueprint $table) {
            $table->increments('id')->unsigned();
            $table->integer('post_id')->unsigned();
            $table->integer('user_id')->unsigned();
            $table->text('body');
            $table->boolean('active');
            $table->integer('parent');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('comments');
    }
}


text:
package com.facebook.buck.distributed;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;

import com.facebook.buck.core.cell.Cell;
import com.facebook.buck.core.cell.TestCellBuilder;
import com.facebook.buck.core.config.BuckConfig;
import com.facebook.buck.core.config.FakeBuckConfig;
import com.facebook.buck.core.model.BuildTarget;
import com.facebook.buck.core.model.BuildTargetFactory;
import com.facebook.buck.core.model.actiongraph.ActionGraph;
import com.facebook.buck.core.rulekey.AddToRuleKey;
import com.facebook.buck.core.rules.ActionGraphBuilder;
import com.facebook.buck.core.rules.BuildRuleParams;
import com.facebook.buck.core.rules.SourcePathRuleFinder;
import com.facebook.buck.core.rules.TestBuildRuleParams;
import com.facebook.buck.core.rules.impl.NoopBuildRuleWithDeclaredAndExtraDeps;
import com.facebook.buck.core.rules.resolver.impl.TestActionGraphBuilder;
import com.facebook.buck.core.sourcepath.ArchiveMemberSourcePath;
import com.facebook.buck.core.sourcepath.PathSourcePath;
import com.facebook.buck.core.sourcepath.SourcePath;
import com.facebook.buck.core.sourcepath.resolver.SourcePathResolver;
import com.facebook.buck.core.sourcepath.resolver.impl.DefaultSourcePathResolver;
import com.facebook.buck.core.toolchain.tool.Tool;
import com.facebook.buck.distributed.testutil.FakeFileContentsProvider;
import com.facebook.buck.distributed.thrift.BuildJobStateFileHashEntry;
import com.facebook.buck.distributed.thrift.BuildJobStateFileHashes;
import com.facebook.buck.io.ArchiveMemberPath;
import com.facebook.buck.io.file.MostFiles;
import com.facebook.buck.io.filesystem.ProjectFilesystem;
import com.facebook.buck.io.filesystem.TestProjectFilesystems;
import com.facebook.buck.jvm.java.JavaLibraryBuilder;
import com.facebook.buck.parser.exceptions.NoSuchBuildTargetException;
import com.facebook.buck.rules.keys.config.TestRuleKeyConfigurationFactory;
import com.facebook.buck.slb.ThriftUtil;
import com.facebook.buck.util.cache.FileHashCacheMode;
import com.facebook.buck.util.cache.ProjectFileHashCache;
import com.facebook.buck.util.cache.impl.DefaultFileHashCache;
import com.facebook.buck.util.cache.impl.StackedFileHashCache;
import com.facebook.buck.util.zip.CustomJarOutputStream;
import com.facebook.buck.util.zip.ZipOutputStreams;
import com.google.common.base.Charsets;
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.hash.HashCode;
import com.google.common.hash.Hashing;
import com.google.common.util.concurrent.MoreExecutors;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.file.FileSystem;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.easymock.EasyMock;
import org.hamcrest.Matchers;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;

public class DistBuildFileHashesTest {
  private static final long FUTURES_GET_TIMEOUT_SECONDS = 2;

  @Rule public TemporaryFolder tempDir = new TemporaryFolder();

  @Rule public TemporaryFolder archiveTempDir = new TemporaryFolder();

  private abstract static class Fixture {

    protected final ProjectFilesystem projectFilesystem;
    protected final FileSystem javaFs;

    protected final ProjectFilesystem secondProjectFilesystem;
    protected final FileSystem secondJavaFs;

    protected final ActionGraph actionGraph;
    protected final ActionGraphBuilder graphBuilder;
    protected final SourcePathRuleFinder ruleFinder;
    protected final SourcePathResolver sourcePathResolver;
    protected final DistBuildFileHashes distributedBuildFileHashes;

    public Fixture(ProjectFilesystem first, ProjectFilesystem second)
        throws InterruptedException, IOException, NoSuchBuildTargetException {
      projectFilesystem = first;
      javaFs = projectFilesystem.getRootPath().getFileSystem();

      secondProjectFilesystem = second;
      secondJavaFs = secondProjectFilesystem.getRootPath().getFileSystem();

      graphBuilder = new TestActionGraphBuilder();
      ruleFinder = new SourcePathRuleFinder(graphBuilder);
      sourcePathResolver = DefaultSourcePathResolver.from(ruleFinder);
      setUpRules(graphBuilder, sourcePathResolver);
      actionGraph = new ActionGraph(graphBuilder.getBuildRules());
      BuckConfig buckConfig = createBuckConfig();
      Cell rootCell =
          new TestCellBuilder().setFilesystem(projectFilesystem).setBuckConfig(buckConfig).build();

      distributedBuildFileHashes =
          new DistBuildFileHashes(
              actionGraph,
              sourcePathResolver,
              ruleFinder,
              createFileHashCache(),
              new DistBuildCellIndexer(rootCell),
              MoreExecutors.newDirectExecutorService(),
              TestRuleKeyConfigurationFactory.create(),
              rootCell);
    }

    public Fixture(TemporaryFolder tempDir)
        throws InterruptedException, IOException, NoSuchBuildTargetException {
      this(
          TestProjectFilesystems.createProjectFilesystem(
              tempDir.newFolder("first").toPath().toRealPath()),
          TestProjectFilesystems.createProjectFilesystem(
              tempDir.newFolder("second").toPath().toRealPath()));
    }

    protected BuckConfig createBuckConfig() {
      return FakeBuckConfig.builder().build();
    }

    protected abstract void setUpRules(
        ActionGraphBuilder graphBuilder, SourcePathResolver sourcePathResolver)
        throws IOException, NoSuchBuildTargetException;

    private StackedFileHashCache createFileHashCache() {
      ImmutableList.Builder<ProjectFileHashCache> cacheList = ImmutableList.builder();
      cacheList.add(
          DefaultFileHashCache.createDefaultFileHashCache(
              projectFilesystem, FileHashCacheMode.DEFAULT));
      cacheList.add(
          DefaultFileHashCache.createDefaultFileHashCache(
              secondProjectFilesystem, FileHashCacheMode.DEFAULT));
      for (Path path : javaFs.getRootDirectories()) {
        if (Files.isDirectory(path)) {
          cacheList.add(
              DefaultFileHashCache.createDefaultFileHashCache(
                  TestProjectFilesystems.createProjectFilesystem(path), FileHashCacheMode.DEFAULT));
        }
      }
      return new StackedFileHashCache(cacheList.build());
    }

    public Path getPath(String first, String... more) {
      return javaFs.getPath(first, more);
    }
  }

  private static class SingleFileFixture extends Fixture {
    protected Path javaSrcPath;
    protected HashCode writtenHashCode;
    protected String writtenContents;

    public SingleFileFixture(TemporaryFolder tempDir)
        throws InterruptedException, IOException, NoSuchBuildTargetException {
      super(tempDir);
    }

    @Override
    protected void setUpRules(
        ActionGraphBuilder graphBuilder, SourcePathResolver sourcePathResolver)
        throws IOException, NoSuchBuildTargetException {
      javaSrcPath = getPath("src", "A.java");

      projectFilesystem.createParentDirs(javaSrcPath);
      writtenContents = "public class A {}";
      projectFilesystem.writeContentsToPath(writtenContents, javaSrcPath);
      writtenHashCode = Hashing.sha1().hashString(writtenContents, Charsets.UTF_8);

      JavaLibraryBuilder.createBuilder(
              BuildTargetFactory.newInstance(projectFilesystem.getRootPath(), "//:java_lib"),
              projectFilesystem)
          .addSrc(javaSrcPath)
          .build(graphBuilder, projectFilesystem);
    }
  }

  @Test
  public void recordsFileHashes() throws Exception {
    SingleFileFixture f = new SingleFileFixture(tempDir);

    List<BuildJobStateFileHashes> recordedHashes = f.distributedBuildFileHashes.getFileHashes();

    assertThat(toDebugStringForAssert(recordedHashes), recordedHashes, Matchers.hasSize(1));
    BuildJobStateFileHashes rootCellHashes = getRootCellHashes(recordedHashes);
    assertThat(rootCellHashes.entries, Matchers.hasSize(1));
    BuildJobStateFileHashEntry fileHashEntry = rootCellHashes.entries.get(0);
    // It's intentional that we hardcode the path as a string here as we expect the thrift data
    // to contain unix-formated paths.
    assertThat(fileHashEntry.getPath().getPath(), Matchers.equalTo("src/A.java"));
    assertFalse(fileHashEntry.isPathIsAbsolute());
    assertFalse(fileHashEntry.isIsDirectory());
  }

  @Test
  public void cacheReadsHashesForFiles() throws Exception {
    SingleFileFixture f = new SingleFileFixture(tempDir);

    List<BuildJobStateFileHashes> fileHashes = f.distributedBuildFileHashes.getFileHashes();

    ProjectFilesystem readProjectFilesystem =
        TestProjectFilesystems.createProjectFilesystem(
            tempDir.newFolder("read_hashes").toPath().toRealPath());
    ProjectFileHashCache mockCache = EasyMock.createMock(ProjectFileHashCache.class);
    EasyMock.expect(mockCache.getFilesystem()).andReturn(readProjectFilesystem).anyTimes();
    EasyMock.replay(mockCache);
    ProjectFileHashCache fileHashCache =
        DistBuildFileHashes.createFileHashCache(mockCache, fileHashes.get(0));

    assertThat(
        fileHashCache.willGet(readProjectFilesystem.resolve(f.javaSrcPath)),
        Matchers.equalTo(true));

    assertThat(
        fileHashCache.get(readProjectFilesystem.resolve(f.javaSrcPath)),
        Matchers.equalTo(f.writtenHashCode));
  }

  @Test
  public void materializerWritesContents()
      throws InterruptedException, NoSuchBuildTargetException, IOException, TimeoutException,
          ExecutionException {
    SingleFileFixture f = new SingleFileFixture(tempDir);

    List<BuildJobStateFileHashes> fileHashes = f.distributedBuildFileHashes.getFileHashes();

    ProjectFilesystem materializeProjectFilesystem =
        TestProjectFilesystems.createProjectFilesystem(
            tempDir.newFolder("read_hashes").getCanonicalFile().toPath());

    ProjectFileHashCache mockCache = EasyMock.createMock(ProjectFileHashCache.class);
    EasyMock.expect(mockCache.getFilesystem())
        .andReturn(materializeProjectFilesystem)
        .atLeastOnce();
    EasyMock.expect(mockCache.get(EasyMock.<Path>notNull()))
        .andReturn(f.writtenHashCode)
        .atLeastOnce();
    EasyMock.replay(mockCache);

    FakeFileContentsProvider fakeFileContentsProvider =
        new FakeFileContentsProvider.Builder()
            .setFilesystemToWrite(materializeProjectFilesystem)
            // We store paths with unix separator, which will be different than a path generated by
            // a windows filesystem. So replace '\' by '/'.
            .putFileContents(f.javaSrcPath.toString().replace('\\', '/'), f.writtenContents)
            .build();
    MaterializerDummyFileHashCache materializer =
        new MaterializerDummyFileHashCache(
            mockCache,
            fileHashes.get(0),
            fakeFileContentsProvider,
            MoreExecutors.newDirectExecutorService());

    materializer.get(f.javaSrcPath);
    materializer
        .getMaterializationFuturesAsList()
        .get(FUTURES_GET_TIMEOUT_SECONDS, TimeUnit.SECONDS);
    assertThat(
        materializeProjectFilesystem.readFileIfItExists(f.javaSrcPath),
        Matchers.equalTo(Optional.of(f.writtenContents)));
  }

  @SuppressWarnings("PMD.EmptyCatchBlock")
  @Test
  public void materializerThrowsOnCorruption()
      throws InterruptedException, NoSuchBuildTargetException, IOException, TimeoutException {
    SingleFileFixture f = new SingleFileFixture(tempDir);

    List<BuildJobStateFileHashes> fileHashes = f.distributedBuildFileHashes.getFileHashes();

    ProjectFilesystem materializeProjectFilesystem =
        TestProjectFilesystems.createProjectFilesystem(
            tempDir.newFolder("read_hashes").getCanonicalFile().toPath());

    ProjectFileHashCache mockCache = EasyMock.createMock(ProjectFileHashCache.class);
    EasyMock.expect(mockCache.getFilesystem())
        .andReturn(materializeProjectFilesystem)
        .atLeastOnce();
    EasyMock.expect(mockCache.get(EasyMock.<Path>notNull()))
        .andReturn(HashCode.fromInt(42))
        .atLeastOnce();
    EasyMock.replay(mockCache);
    MaterializerDummyFileHashCache materializer =
        new MaterializerDummyFileHashCache(
            mockCache,
            fileHashes.get(0),
            new InlineContentsProvider(MoreExecutors.newDirectExecutorService()),
            MoreExecutors.newDirectExecutorService());

    try {
      materializer.get(f.javaSrcPath);
      materializer
          .getMaterializationFuturesAsList()
          .get(FUTURES_GET_TIMEOUT_SECONDS, TimeUnit.SECONDS);
      Assert.fail("Materialization should have thrown because of mismatching hash.");
    } catch (RuntimeException | ExecutionException e) {
      // expected.
    }
  }

  @Test
  public void cacheMaterializes() throws Exception {
    SingleFileFixture f = new SingleFileFixture(tempDir);

    List<BuildJobStateFileHashes> fileHashes = f.distributedBuildFileHashes.getFileHashes();

    ProjectFilesystem readProjectFilesystem =
        TestProjectFilesystems.createProjectFilesystem(
            tempDir.newFolder("read_hashes").toPath().toRealPath());
    ProjectFileHashCache mockCache = EasyMock.createMock(ProjectFileHashCache.class);
    EasyMock.expect(mockCache.getFilesystem()).andReturn(readProjectFilesystem).anyTimes();
    EasyMock.replay(mockCache);
    ProjectFileHashCache fileHashCache =
        DistBuildFileHashes.createFileHashCache(mockCache, fileHashes.get(0));

    assertThat(
        fileHashCache.willGet(readProjectFilesystem.resolve("src/A.java")), Matchers.equalTo(true));

    assertThat(
        fileHashCache.get(readProjectFilesystem.resolve("src/A.java")),
        Matchers.equalTo(f.writtenHashCode));
  }

  private static class ArchiveFilesFixture extends Fixture implements AutoCloseable {
    private final Path firstFolder;
    private final Path secondFolder;
    protected Path archivePath;
    protected Path archiveMemberPath;
    protected HashCode archiveMemberHash;

    private ArchiveFilesFixture(Path firstFolder, Path secondFolder)
        throws InterruptedException, IOException, NoSuchBuildTargetException {
      super(
          TestProjectFilesystems.createProjectFilesystem(firstFolder),
          TestProjectFilesystems.createProjectFilesystem(secondFolder));
      this.firstFolder = firstFolder;
      this.secondFolder = secondFolder;
    }

    public static ArchiveFilesFixture create(TemporaryFolder archiveTempDir)
        throws InterruptedException, IOException, NoSuchBuildTargetException {
      return new ArchiveFilesFixture(
          archiveTempDir.newFolder("first").toPath().toRealPath(),
          archiveTempDir.newFolder("second").toPath().toRealPath());
    }

    @Override
    protected void setUpRules(
        ActionGraphBuilder graphBuilder, SourcePathResolver sourcePathResolver)
        throws IOException, NoSuchBuildTargetException {
      archivePath = getPath("src", "archive.jar");
      archiveMemberPath = getPath("Archive.class");

      projectFilesystem.createParentDirs(archivePath);
      try (CustomJarOutputStream jarWriter =
          ZipOutputStreams.newJarOutputStream(projectFilesystem.newFileOutputStream(archivePath))) {
        jarWriter.setEntryHashingEnabled(true);
        byte[] archiveMemberData = "data".getBytes(Charsets.UTF_8);
        archiveMemberHash = Hashing.murmur3_128().hashBytes(archiveMemberData);
        jarWriter.writeEntry("Archive.class", new ByteArrayInputStream(archiveMemberData));
      }

      BuildTarget target = BuildTargetFactory.newInstance("//:with_tool");
      graphBuilder.addToIndex(
          new BuildRuleWithToolAndPath(
              target,
              projectFilesystem,
              TestBuildRuleParams.create(),
              null,
              ArchiveMemberSourcePath.of(
                  PathSourcePath.of(projectFilesystem, archivePath), archiveMemberPath)));
    }

    @Override
    public void close() throws IOException {
      MostFiles.deleteRecursively(firstFolder);
      MostFiles.deleteRecursively(secondFolder);
    }
  }

  @Test
  public void recordsArchiveHashes() throws Exception {
    try (ArchiveFilesFixture f = ArchiveFilesFixture.create(archiveTempDir)) {
      List<BuildJobStateFileHashes> recordedHashes = f.distributedBuildFileHashes.getFileHashes();

      assertThat(toDebugStringForAssert(recordedHashes), recordedHashes, Matchers.hasSize(1));
      BuildJobStateFileHashes hashes = getRootCellHashes(recordedHashes);
      assertThat(hashes.entries, Matchers.hasSize(1));
      BuildJobStateFileHashEntry fileHashEntry = hashes.entries.get(0);
      assertThat(fileHashEntry.getPath().getPath(), Matchers.equalTo("src/archive.jar"));
      assertTrue(fileHashEntry.isSetArchiveMemberPath());
      assertThat(fileHashEntry.getArchiveMemberPath(), Matchers.equalTo("Archive.class"));
      assertFalse(fileHashEntry.isPathIsAbsolute());
      assertFalse(fileHashEntry.isIsDirectory());
    }
  }

  @Test
  public void readsHashesForArchiveMembers() throws Exception {
    try (ArchiveFilesFixture f = ArchiveFilesFixture.create(archiveTempDir)) {
      List<BuildJobStateFileHashes> recordedHashes = f.distributedBuildFileHashes.getFileHashes();

      ProjectFilesystem readProjectFilesystem =
          TestProjectFilesystems.createProjectFilesystem(
              tempDir.newFolder("read_hashes").toPath().toRealPath());
      ProjectFileHashCache mockCache = EasyMock.createMock(ProjectFileHashCache.class);
      EasyMock.expect(mockCache.getFilesystem()).andReturn(readProjectFilesystem).anyTimes();
      EasyMock.replay(mockCache);
      ProjectFileHashCache fileHashCache =
          DistBuildFileHashes.createFileHashCache(mockCache, recordedHashes.get(0));

      ArchiveMemberPath archiveMemberPath =
          ArchiveMemberPath.of(readProjectFilesystem.resolve(f.archivePath), f.archiveMemberPath);
      assertThat(fileHashCache.willGet(archiveMemberPath), Matchers.is(true));

      assertThat(fileHashCache.get(archiveMemberPath), Matchers.is(f.archiveMemberHash));
    }
  }

  @Test
  public void worksCrossCell() throws Exception {
    Fixture f =
        new Fixture(tempDir) {

          @Override
          protected void setUpRules(
              ActionGraphBuilder graphBuilder, SourcePathResolver sourcePathResolver)
              throws IOException, NoSuchBuildTargetException {
            Path firstPath = javaFs.getPath("src", "A.java");

            projectFilesystem.createParentDirs(firstPath);
            projectFilesystem.writeContentsToPath("public class A {}", firstPath);

            Path secondPath = secondJavaFs.getPath("B.java");
            secondProjectFilesystem.writeContentsToPath("public class B {}", secondPath);

            JavaLibraryBuilder.createBuilder(
                    BuildTargetFactory.newInstance(
                        projectFilesystem.getRootPath(), "//:java_lib_at_root"),
                    projectFilesystem)
                .addSrc(firstPath)
                .build(graphBuilder, projectFilesystem);

            JavaLibraryBuilder.createBuilder(
                    BuildTargetFactory.newInstance(
                        secondProjectFilesystem.getRootPath(), "//:java_lib_at_secondary"),
                    secondProjectFilesystem)
                .addSrc(secondPath)
                .build(graphBuilder, secondProjectFilesystem);
          }

          @Override
          protected BuckConfig createBuckConfig() {
            return FakeBuckConfig.builder()
                .setSections(
                    "[repositories]",
                    "second_repo = " + secondProjectFilesystem.getRootPath().toAbsolutePath())
                .build();
          }
        };

    List<BuildJobStateFileHashes> recordedHashes = f.distributedBuildFileHashes.getFileHashes();
    assertThat(toDebugStringForAssert(recordedHashes), recordedHashes, Matchers.hasSize(2));

    BuildJobStateFileHashes rootCellHash = getRootCellHashes(recordedHashes);
    Assert.assertEquals(1, rootCellHash.getEntriesSize());
    Assert.assertEquals("src/A.java", rootCellHash.getEntries().get(0).getPath().getPath());

    BuildJobStateFileHashes secondaryCellHashes = getCellHashesByIndex(recordedHashes, 1);
    Assert.assertEquals(1, secondaryCellHashes.getEntriesSize());
    Assert.assertEquals("B.java", secondaryCellHashes.getEntries().get(0).getPath().getPath());
  }

  private static class BuildRuleWithToolAndPath extends NoopBuildRuleWithDeclaredAndExtraDeps {

    @AddToRuleKey Tool tool;

    @AddToRuleKey SourcePath sourcePath;

    public BuildRuleWithToolAndPath(
        BuildTarget buildTarget,
        ProjectFilesystem projectFilesystem,
        BuildRuleParams params,
        Tool tool,
        SourcePath sourcePath) {
      super(buildTarget, projectFilesystem, params);
      this.tool = tool;
      this.sourcePath = sourcePath;
    }
  }

  private static BuildJobStateFileHashes getCellHashesByIndex(
      List<BuildJobStateFileHashes> recordedHashes, int index) {
    Preconditions.checkArgument(index >= 0);
    Preconditions.checkArgument(index < recordedHashes.size());
    return recordedHashes
        .stream()
        .filter(hashes -> hashes.getCellIndex() == index)
        .findFirst()
        .get();
  }

  private static BuildJobStateFileHashes getRootCellHashes(
      List<BuildJobStateFileHashes> recordedHashes) {
    return getCellHashesByIndex(recordedHashes, DistBuildCellIndexer.ROOT_CELL_INDEX);
  }

  private static String toDebugStringForAssert(List<BuildJobStateFileHashes> recordedHashes) {
    return Joiner.on("\n")
        .join(
            recordedHashes
                .stream()
                .map(ThriftUtil::thriftToDebugJson)
                .collect(ImmutableList.toImmutableList()));
  }
}


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

<TITLE>
R-Index
</TITLE>

<META NAME="date" CONTENT="2012-10-15">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
      Use
      Tree
      Deprecated
    Index
      Help

 PREV LETTER
 NEXT LETTER

  FRAMES
 NO FRAMES

  All Classes

A B C D E F G H I J L M N P R S T U V W

R

RAW_HAND_NONCE -
Static variable in class mentalpoker.SigService

The Constant RAW_HAND_NONCE.

readObject(byte[]) -
Static method in class mentalpoker.Passable

Read object.

REQUEST_COM_CARDS_NONCE -
Static variable in class mentalpoker.SigService

The Constant REQUEST_COM_CARDS_NONCE.

requestDecryptComCards(EncryptedCommunityCards, User) -
Method in class mentalpoker.ComService

Request to decrypt community cards.

requestDecryptHand(EncryptedHand, User) -
Method in class mentalpoker.ComService

Request a user to decrypt your hand.

requestEncDeck(User, EncryptedDeck) -
Method in class mentalpoker.ComService

Request a user to encrypt the deck.

RSAService - Class in mentalpoker
The Class RSAService.
RSAService() -
Constructor for class mentalpoker.RSAService

Instantiates a new rsa service.

RSAService(BigInteger, BigInteger) -
Constructor for class mentalpoker.RSAService

Instantiates a new rsa service with given p and q.

RSAService(BigInteger, BigInteger, BigInteger) -
Constructor for class mentalpoker.RSAService

Instantiates a new rsa service.

      Overview
      Package
      Class
      Use
      Tree
      Deprecated
    Index
      Help

 PREV LETTER
 NEXT LETTER

  FRAMES
 NO FRAMES

  All Classes

A B C D E F G H I J L M N P R S T U V W


text:
preso = window.preso || {};

preso.canvasDemo = function(slide) {
  var editor, results = slide.getElementsByClassName('results')[0];

  var dateMatch = /(\d+)-(\d+)-(\d+)T\d+:\d+:\d+\.\d+Z/;

  function gen(type, cls) {var e=document.createElement(type); e.setAttribute('class',cls); return e; }
  function text(txt) { return document.createTextNode(txt); }
  function render(js) {
    var resultParent = results.parentElement;
    resultParent.removeChild(results);
    results = document.createElement('iframe');
    results.setAttribute('class','results');
    resultParent.appendChild(results);
    setTimeout(function(){
      var doc = (results.contentDocument||results.contentWindow.document);
      doc.head.innerHTML = '<style>html{height:100%;} body{margin:0;height:100%;} '
          + 'canvas{width:100%;height:100%;}</style>'
      doc.body.innerHTML = '<canvas id="c"></canvas>';
      var script = doc.createElement('script');
      script.innerHTML = js;
      doc.body.appendChild(script);
    },10);
  }

  function init( forward, back ) {
    var editorElement = slide.getElementsByClassName('editor')[0];
    var editorId = editorElement.id;
    editor = ace.edit(editorId);
    editor.setTheme("ace/theme/merbivore_soft");
    editor.getSession().setMode("ace/mode/javascript");
    editor.getSession().setTabSize(2);
    editor.getSession().setUseSoftTabs(true);
    editor.setShowPrintMargin(false)
    editor.commands.addCommand({
        name: 'toggleEditor',
        bindKey: {win: 'Ctrl-Alt-Enter',  mac: 'Ctrl-Alt-Enter'},
        exec: function() {render(editor.getValue())}
    });

    editorElement.onkeyup = function(e) { e.stopPropagation(); return false; }

    var results = slide.getElementsByClassName('results')[0];
  }

  function show() { editor.focus() }
  function hide() {
    if (editor) editor.blur()
    var results = slide.getElementsByClassName('results')[0]; if (results) results.innerHTML='';
  }
  var listeners = {};
  function addEventListener(type, f) { if (f) (listeners[type]=listeners[type]||[]).push(f); }
  function trigger(type) { for (var i=0,f; f=(listeners[type]||[])[i];i++) f() }

  return { init: init, show: show, hide: hide, addEventListener:addEventListener   }
}


text:
Sorts: sortNumbers
#PURPOSE of the 4 number and alpha fields, sort by the first one
#
#
#
// If [ steward::chosenSort = "number" ]
// Set Variable [ $$record; Value:brainstate::_lockBrainstateID ]
// Sort Records [ Specified Sort Order: brainstate::sortNumber; descending
brainstate::sortAlpha; descending
brainstate::sortSubNumber; descending
brainstate::sortCategory; descending
brainstate::description; ascending ]
[ Restore; No dialog ]
// Sort Records [ Specified Sort Order: brainstate::sortNumber; based on value list: "__-99"
brainstate::sortAlpha; based on value list: "sortAlpha"
brainstate::sortSubNumber; based on value list: "__-99"
brainstate::sortCategory; based on value list: "sortAlpha"
brainstate::description; ascending ]
[ Restore; No dialog ]
// Set Field [ steward::chosenSort; "rebmun" ]
// Go to Record/Request/Page
[ First ]
// Loop
// Exit Loop If [ $$record = brainstate::_lockBrainstateID ]
// Go to Record/Request/Page
[ Next ]
// End Loop
// Set Variable [ $$record ]
// Go to Field [ ]
// Halt Script
// End If
// If [ steward::chosenSort ≠ "number" ]
Set Variable [ $$record; Value:brainstate::_lockBrainstateID ]
Sort Records [ Specified Sort Order: brainstate::sortNumber; based on value list: "__-99"
brainstate::sortAlpha; based on value list: "sortAlpha"
brainstate::sortSubNumber; based on value list: "__-99"
brainstate::sortCategory; based on value list: "sortAlpha"
brainstate::description; ascending ]
[ Restore; No dialog ]
Set Field [ steward::chosenSort; "number" ]
Go to Record/Request/Page
[ First ]
Loop
Exit Loop If [ $$record = brainstate::_lockBrainstateID ]
Go to Record/Request/Page
[ Next ]
End Loop
Set Variable [ $$record ]
Go to Field [ ]
// End If
January 6, 平成26 0:34:17 ActionLog.fp7 - sortNumbers -1-


text:
namespace algo {

template<typename T>
class stack1T {
private:
    node<T> *head;
    node<T> *tail;
    size_t length;
public:
    stack1T() : head(new node<T>(T(0))), length(0) { tail = head; }
    ~stack1T() {}
    T& top();
    const T& top() const;

    bool empty() const;
    size_t size() const;

    void push(T value);
    void pop();
};

template<typename T>
T& stack1T<T>::top() {
  return tail->value;
}

template<typename T>
const T& stack1T<T>::top() const {
  return tail->value;
}

template<typename T>
bool stack1T<T>::empty() const {
  return (head == tail);
}

template<typename T>
size_t stack1T<T>::size() const {
  return length;
}

template<typename T>
void stack1T<T>::push(T value) {
  node<T>* tmp = new node<T>(value, tail, NULL);
  tail->after = tmp;
  tail = tail->after;
  length++;
}

template<typename T>
void stack1T<T>::pop() {
  if(tail != head) {
    node<T>* tmp = tail;
    tail = tail->before;
    T val = tmp->value;
    delete tmp;
    length--;
  }
}

}


text:
package org.neo4j.kernel.impl.transaction.log;

import java.io.IOException;

public interface LogVersionRepository
{
    long INITIAL_LOG_VERSION = 0;

	/**
	 * Returns the current log version. It is non blocking.
	 */
    long getCurrentLogVersion();

    /**
     * Increments (making sure it is persisted on disk) and returns the latest log version for this repository.
     * It does so atomically and can potentially block.
     */
    long incrementAndGetVersion() throws IOException;
}


text:
<?php
/* @var $this UserController */
/* @var $model User */

?>

Create User

<?php echo $this->renderPartial('_form', array('model'=>$model)); ?>


text:
package com.pasenger.activitytest;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Window;

public class SecondActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        findViewById(R.id.button2).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(SecondActivity.this, MainActivity.class);

                intent.putExtra("return_data", "Hello MainActivity");
                setResult(RESULT_OK, intent);

                finish();
//                startActivity(intent);

//                Intent intent = new Intent(Intent.ACTION_VIEW);
//                intent.setData(Uri.parse("https://www.baidu.com"));

//                startActivity(intent);
            }
        });
    }

    /**
     * 返回键传送数据
     */
    @Override
    public void onBackPressed() {
        Intent intent = new Intent(SecondActivity.this, MainActivity.class);

        intent.putExtra("return_data", "Hello MainActivity");
        setResult(RESULT_OK, intent);

        finish();
    }
}


text:
/**
 * This copy of Woodstox XML processor is licensed under the
 * Apache (Software) License, version 2.0 ("the License").
 * See the License for details about distribution rights, and the
 * specific rights regarding derivate works.
 *
 * You may obtain a copy of the License at:
 *
 * http://www.apache.org/licenses/
 *
 * A copy is also included in the downloadable source code package
 * containing Woodstox, in file "ASL2.0", under the same directory
 * as this file.
 */
package org.briljantframework.examples;

import org.briljantframework.data.Is;
import org.briljantframework.data.SortOrder;
import org.briljantframework.data.dataframe.DataFrame;
import org.briljantframework.data.dataframe.DataFrames;
import org.briljantframework.data.vector.Vector;
import org.briljantframework.dataset.io.Datasets;
import org.briljantframework.mimir.classification.Classifier;
import org.briljantframework.mimir.classification.conformal.ClassifierNonconformity;
import org.briljantframework.mimir.classification.conformal.InductiveConformalClassifier;
import org.briljantframework.mimir.classification.conformal.ProbabilityCostFunction;
import org.briljantframework.mimir.classification.conformal.ProbabilityEstimateNonconformity;
import org.briljantframework.mimir.classification.conformal.evaluation.ConformalClassifierValidator;
import org.briljantframework.mimir.evaluation.Result;
import org.briljantframework.mimir.evaluation.Validator;
import org.briljantframework.mimir.supervised.Predictor;
import org.briljantframework.mimir.weka.WekaClassifier;

import weka.classifiers.trees.RandomForest;

/**
 * @author Isak Karlsson <isak-kar@dsv.su.se>
 */
public class WekaClassifierExample {

  public static void main(String[] args) {
    DataFrame iris = DataFrames.permuteRecords(Datasets.loadIris());
    DataFrame x = iris.drop("Class").apply(v -> v.set(v.where(Is::NA), v.mean()));
    Vector y = iris.get("Class");

    // Construct a weka classifier
    Predictor.Learner<? extends Classifier> classifier =
        new WekaClassifier.Learner<>(new RandomForest());

    // Use the classifier as a probability estimator
    ClassifierNonconformity.Learner nc =
        new ProbabilityEstimateNonconformity.Learner(classifier, ProbabilityCostFunction.margin());

    // Construct an inductive conformal classifier
    InductiveConformalClassifier.Learner cp = new InductiveConformalClassifier.Learner(nc);

    // and a suitable validator
    Validator<InductiveConformalClassifier> validator =
        ConformalClassifierValidator.crossValidator(10, 0.2);

    // Evaluate the conformal classifier
    Result result = validator.test(cp, x, y);

    // Compute the mean of all measures grouped by significance level
    DataFrame meanPerSignificance =
        result.getMeasures().groupBy("significance").collect(Vector::mean).sort(SortOrder.ASC);
    System.out.println(meanPerSignificance);
  }
}


text:
"""
Meraki Networks API Resource
"""

import urllib
from .meraki_api_resource import MerakiAPIResource
from .devices import Devices
from .ssids import SSIDs
from .site_to_site_vpn import SiteToSiteVPN
from .phone_contacts import PhoneContacts
from .sm import SM
from .static_routes import StaticRoutes
from .vlans import VLANs
from .utils import clean
from .clients import Clients

class Networks(MerakiAPIResource):
    """ Meraki API Networks resource. """

    resource = "networks"

    parameters = ["name", "timeZone", "tags", "type"]

    traffic_parameters = ["timespan", "deviceType"]

    air_marshal_parameters = ["timespan"]

    bind_parameters = ["configurationTemplateId", "autoBind"]

    clients_parameters = ["id_or_mac_or_ip"]

    events_parameters = ["productType", "includedEventTypes", "excludedEventTypes", "deviceMac", "deviceSerial", "deviceName", "clientIp", "clientMac", "clientName", "smDeviceMac", "smDeviceName", "perPage", "startingAfter", "endingBefore"]

    def __init__(self, key, prefix=None, resource_id=None):
        MerakiAPIResource.__init__(self, key, prefix, resource_id)

    def check_timespan(self, query):
        """ Checks if the query object has the timespan value configured. """
        if query is None or query.get("timespan") is None:
            raise ValueError("You must set the timespan query value.")

    def static_routes(self, static_route_id=None):
        """ Returns the Networks Static Routes API Resource. """
        self.check_for_resource_id()
        return StaticRoutes(self.key, self.endpoint(), static_route_id)

    def devices(self, serial=None):
        """ Returns the Networks Devices API Resource. """
        self.check_for_resource_id()
        return Devices(self.key, self.endpoint(), serial)

    def ssids(self, ssid_id=None):
        """ Returns the Network SSIDs API Resource."""
        self.check_for_resource_id()
        return SSIDs(self.key, self.endpoint(), ssid_id)

    def site_to_site_vpn(self, site_to_site_vpn_id=None):
        """ Returns site-to-site VPN settings API Resource. """
        self.check_for_resource_id()
        return SiteToSiteVPN(self.key, self.endpoint(), site_to_site_vpn_id)

    def vlans(self, vlan_id=None):
        """ Returns VLANs VPN settings API Resource. """
        self.check_for_resource_id()
        return VLANs(self.key, self.endpoint(), vlan_id)

    def sm(self):
        """ Returns Network SM API Resource. """
        self.check_for_resource_id()
        return SM(self.key, self.endpoint())

    def traffic(self, query):
        """
        The traffic analysis data for this network. Traffic Analysis with
        Hostname Visibility must be enabled on the network.
        """
        self.check_for_resource_id()
        self.check_timespan(query)
        query = clean(query, self.traffic_parameters)
        return self.get("/traffic?" + urllib.parse.urlencode(query))

    def bind(self, data):
        """ Binds template to network. """
        self.check_for_resource_id()
        data = clean(data, self.bind_parameters)
        return self.post("/bind", data)

    def unbind(self):
        """ Unbind template from network. """
        self.check_for_resource_id()
        return self.post("/unbind")

    def access_policies(self):
        """ List the access policies (MS). """
        self.check_for_resource_id()
        return self.get("/accessPolicies")

    def air_marshal(self, query):
        """ Air marshal scan results from a network. """
        self.check_timespan(query)
        self.check_for_resource_id()
        query = clean(query, self.air_marshal_parameters)
        return self.get("/airMarshal?" + urllib.parse.urlencode(query))

    def phone_contacts(self, phone_contact_id=None):
        """ List the phone contacts in a network. """
        self.check_for_resource_id()
        return PhoneContacts(self.key, self.endpoint(), phone_contact_id)

    def phone_numbers(self):
        """ List all the phone numbers in a network. """
        self.check_for_resource_id()
        return self.get("/phoneNumbers")

    def available_phone_numbers(self):
        """ List all the available phone numbers in a network. """
        self.check_for_resource_id()
        return self.get("/phoneNumbers/available")

    def clients(self, clients_id=None):
        """ Returns the Clients API Resource. """
        self.check_for_resource_id()
        return Clients(self.key, self.endpoint(), clients_id)

    def events(self, query):
        """ Returns the Clients API Resource. """
        self.check_for_resource_id()
        query = clean(query, self.events_parameters)
        return self.get("/events?" + urllib.parse.urlencode(query))


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <parent>
        <artifactId>spring-io-samples</artifactId>
        <groupId>com.yd.spring</groupId>
        <version>1.0.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <artifactId>spring-jms-demo</artifactId>
    <packaging>war</packaging>
    <name>spring-jms-demo Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <build>
        <finalName>spring-jms-demo</finalName>
    </build>
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.integration</groupId>
            <artifactId>spring-integration-jms</artifactId>
        </dependency>
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-api</artifactId>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-simple</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
        </dependency>
    </dependencies>
</project>


text:
namespace WAMPP {

std::string  genRandomId(int size);

}

#endif // WAMPP_UTIL_HPP_


text:
package com.wordpress.technicalpractical.currencyconvert;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.List;

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

@RunWith(SpringRunner.class)
@SpringBootTest(classes = CurrencyConvertApplication.class)
public class CurrencyConvertApplicationTests {
    @Autowired
    private CurrencyEndpoint currencyEndpoint;

    @Autowired
    private CurrencyRateQuery currencyRateQuery;

    @Value("${currencyRatesLocation}")
    private String currencyRatesLocation;

	@Test
	public void convertUSDToPounds() {
	    assertNotNull("CurrencyEndpoint was null, could not be created.", currencyEndpoint);

	    List<CurrencyRate> currencyRateList = currencyEndpoint.currentRates();
        System.out.printf("Currency List: %d%n", currencyRateList.size());
    }

    @Before
    public void init() {
		currencyEndpoint = new CurrencyEndpoint(currencyRateQuery);

        assertNotNull("Currency Rates Location was null.", currencyRatesLocation);
    }

}


text:
module Twitter
  class Version
    MAJOR = 4 unless defined? Twitter::Version::MAJOR
    MINOR = 8 unless defined? Twitter::Version::MINOR
    PATCH = 1 unless defined? Twitter::Version::PATCH
    PRE = nil unless defined? Twitter::Version::PRE

    class << self

      # @return [String]
      def to_s
        [MAJOR, MINOR, PATCH, PRE].compact.join('.')
      end

    end

  end
end


text:
namespace Graph_lib {
	// Binary tree class
	class Binary_tree : public Shape
	{
	public:
		Binary_tree(Point pt, int ww, int hh, int levels, Color lc = Color::black, bool arrow = false);
		virtual ~Binary_tree();

		virtual void draw_lines() const;

		// set label of a node
		void set_label(string pos, string val);
	protected:
		Point p;	// position
		int w;		// width
		int h;		// height
		int lv;		// level
		Color lc;	// line color
		bool arrow;	// use arrow
		Binary_node<string>* top;	// top node

		vector<Shape*> nodes;		// shapes of nodes
		vector<Shape*> lines;		// connecting lines of nodes
		vector<Text*> labels;		// labels of nodes

		virtual void create_shapes();	// create shape objects
		void add_real_line(Point p1, Point p2);	// add line with points
	private:
		double radius;	// radius (as a const)

		// helper functions
		void create_nodes();
		void create_nodes_helper(Binary_node<string>*, int&);

		void create_shape(Point, Binary_node<string>&);
		void add_line(Point p1, Point p2, double r);

		Binary_node<string>* find_node(string pos);
	};
}

#endif


text:
package net.i2p.router.peermanager;

/**
 * Determine how well integrated the peer is - how likely they will be useful
 * to us if we are trying to get further connected.
 *
 */
class IntegrationCalculator {

    public static double calc(PeerProfile profile) {
        long val = 0;
        if (profile.getIsExpandedDB()) {
            // give more weight to recent counts
            val = profile.getDbIntroduction().getRate(24*60*60*1000l).getCurrentEventCount();
            val += 2 * 4 * profile.getDbIntroduction().getRate(6*60*60*1000l).getLastEventCount();
            val += 3 * 4 * profile.getDbIntroduction().getRate(6*60*60*1000l).getCurrentEventCount();
            val += 4 * 24 * profile.getDbIntroduction().getRate(60*60*1000l).getCurrentEventCount();
            val /= 10;
        }
        val += profile.getIntegrationBonus();
        return val;
    }
}


text: A polyfill of es6 promise


text:
import os
import numpy as np
import dipy as dp
import nibabel as ni
import resources
import time
from subprocess import Popen,PIPE

#Registration options
#similarity 'cc', 'cr', 'crl1', 'mi', je', 'ce', 'nmi', 'smi'.  'cr'
similarity='cr'
#interp 'pv', 'tri'
interp =  'tri'
#subsampling None or sequence (3,)
subsampling=[1,1,1]
#search 'affine', 'rigid', 'similarity' or ['rigid','affine']
search='affine'
#optimizer 'simplex', 'powell', 'steepest', 'cg', 'bfgs' or
#sequence of optimizers
optimizer= 'powell'

def eddy_current_correction(data,affine,target=None,target_affine=None):
    result=[]

    no_dirs=data.shape[-1]

    if target==None and target_affine==None:
        target=ni.Nifti1Image(data[:,:,:,0],affine)
    else:
        target=ni.Nifti1Image(target,target_affine)

    for i in range(1,no_dirs):

        source=ni.Nifti1Image(data[:,:,:,i],affine)
        T=dp.volume_register(source,target,similarity,\
                                 interp,subsampling,search,optimizer)
        sourceT=dp.volume_transform(source, T.inv(), reference=target)
        print i, sourceT.get_data().shape, sourceT.get_affine().shape
        result.append(sourceT)

    result.insert(0,target)
    print 'no of images',len(result)
    return ni.concat_images(result)

def register_source_2_target(source_data,source_affine,target_data,target_affine):

    #subsampling=target_data.shape[:3]

    target=ni.Nifti1Image(target_data,target_affine)
    source=ni.Nifti1Image(source_data,source_affine)
    T=dp.volume_register(source,target,similarity,\
                              interp,subsampling,search,optimizer)
    sourceT=dp.volume_transform(source, T.inv(), reference=target)

    return sourceT

def save_volumes_as_mosaic(fname,volume_list):

    import Image

    vols=[]
    for vol in volume_list:

        vol=np.rollaxis(vol,2,1)
        sh=vol.shape
        arr=vol.reshape(sh[0],sh[1]*sh[2])
        arr=np.interp(arr,[arr.min(),arr.max()],[0,255])
        arr=arr.astype('ubyte')

        print 'arr.shape',arr.shape

        vols.append(arr)

    mosaic=np.concatenate(vols)
    Image.fromarray(mosaic).save(fname)

def haircut_dwi_reference(nii,nii_hair):
    cmd='bet '+nii+' '+ nii_hair + ' -f .2 -g 0'
    print cmd
    p = Popen(cmd, shell=True,stdout=PIPE,stderr=PIPE)
    sto=p.stdout.readlines()
    ste=p.stderr.readlines()

    print sto
    print ste

def register_FA_same_subj_diff_sessions(dname_grid,dname_shell):

    print('create temporary directory')
    tmp_dir='/tmp'

    print('load dicom data')
    data_gr,affine_gr,bvals_gr,gradients_gr=dp.load_dcm_dir(dname_grid)
    data_sh,affine_sh,bvals_sh,gradients_sh=dp.load_dcm_dir(dname_shell)

    print('save DWI reference as nifti')
    tmp_grid=os.path.join(tmp_dir,os.path.basename(dname_grid)+'_ref.nii')
    tmp_shell=os.path.join(tmp_dir,os.path.basename(dname_shell)+'_ref.nii')
    ni.save(ni.Nifti1Image(data_gr[...,0],affine_gr),tmp_grid)
    ni.save(ni.Nifti1Image(data_sh[...,0],affine_sh),tmp_shell)

    print('prepare filenames for haircut (bet)')
    tmp_grid_bet=os.path.join(os.path.dirname(tmp_grid),\
                                  os.path.splitext(os.path.basename(dname_grid))[0]+\
                                  '_ref_bet.nii.gz')
    tmp_shell_bet=os.path.join(os.path.dirname(tmp_shell),\
                                   os.path.splitext(os.path.basename(dname_shell))[0]+\
                                   '_ref_bet.nii.gz')

    print('bet is running')
    haircut_dwi_reference(tmp_grid,tmp_grid_bet)
    haircut_dwi_reference(tmp_shell,tmp_shell_bet)

    print('load nii.gz reference (s0) volumes')
    img_gr_bet=ni.load(tmp_grid_bet)
    img_sh_bet=ni.load(tmp_shell_bet)

    print('register the shell reference to the grid reference')
    source=img_sh_bet
    target=img_gr_bet
    T=dp.volume_register(source,target,similarity,\
                              interp,subsampling,search,optimizer)

    print('apply the inverse of the transformation matrix')
    sourceT=dp.volume_transform(source, T.inv(), reference=target)
    #ni.save(sourceT,'/tmp/result.nii.gz')

    print('calculate FA for grid and shell data')
    FA_grid=dp.Tensor( data_gr,bvals_gr,gradients_gr,thresh=50).FA
    FA_shell=dp.Tensor(data_sh,bvals_sh,gradients_sh,thresh=50).FA

    print('create an FA nibabel image for shell')
    FA_shell_img=ni.Nifti1Image(FA_shell,affine_sh)

    print('transform FA_shell')
    FA_shell_imgT=dp.volume_transform(FA_shell_img,T.inv(),reference=target)

    return ni.Nifti1Image(FA_grid,affine_gr),FA_shell_imgT

def flirt(in_nii, ref_nii,out_nii,transf_mat):
    cmd='flirt -in ' + in_nii + ' -ref ' + ref_nii + ' -out ' \
        + out_nii +' -dof 6 -omat ' + transf_mat
    print(cmd)
    pipe(cmd)

def flirt_apply_transform(in_nii, target_nii, out_nii, transf_mat):
    cmd='flirt -in ' + in_nii + ' -ref ' + target_nii + ' -out ' \
        + out_nii +' -init ' + transf_mat +' -applyxfm'
    print(cmd)
    pipe(cmd)

def test_registration():

    S012='/tmp/compare_12_with_32_Verio_directly/18620_0004.nii_S0.nii.gz'
    S032='/tmp/compare_12_with_32_Verio_directly/18620_0006.nii_S0.nii.gz'
    S012T='/tmp/compare_12_with_32_Verio_directly/S0_reg.nii.gz'
    MP='/tmp/compare_12_with_32_Verio_directly/MPRAGE.nii'
    D114=resources.get_paths('DTI STEAM 114 Trio')[2]
    data,affine,bvals,gradients=dp.load_dcm_dir(D114)
    D114i=ni.Nifti1Image(data[...,0],affine)

    D101=resources.get_paths('DSI STEAM 101 Trio')[2]
    data,affine,bvals,gradients=dp.load_dcm_dir(D101)
    D101i=ni.Nifti1Image(data[...,0],affine)
    ni.save(D101i,'/tmp/compare_12_with_32_Verio_directly/S0_101_reg.nii.gz')

    #source=ni.load(S012)
    source=D114i
    #target=D101i
    #target=ni.load(S032)
    target=ni.load(MP)

    target._data=np.squeeze(target._data)
    #target._affine= np.dot(np.diag([-1, -1, 1, 1]), target._affine)

    similarity='cr'
    interp =  'tri'
    subsampling=None
    search='affine'
    optimizer= 'powell'

    T=dp.volume_register(source,target,similarity,\
                              interp,subsampling,search,optimizer)

    print('Transformation matrix')
    print(T.inv())

    sourceT=dp.volume_transform(source,T.inv(),reference=target,interp_order=0)

    sourceTd=sourceT.get_data()
    sourceTd[sourceTd<0]=0

    sourceT._data=sourceTd

    ni.save(sourceT,S012T)

    sourced=source.get_data()
    targetd=target.get_data()
    sourceTd=sourceT.get_data()

    print 'source info',sourced.min(), sourced.max()
    print 'target info',targetd.min(), targetd.max()
    print 'sourceT info',sourceTd.min(), sourceTd.max()

    #save_volumes_as_mosaic('/tmp/mosaic_S0_MP_cr_pv_powell.png',\
    #                           [sourced,sourceTd,targetd])

    # RAS to LPS np.dot(np.diag([-1, -1, 1, 1]), A)
    # LPS to RAS

if __name__ == '__main__':

    '''
    print('Goal is to compare FA of grid versus shell acquisitions using STEAM')

    print('find filenames for grid and shell data')
    dname_grid=resources.get_paths('DSI STEAM 101 Trio')[2]
    dname_shell=resources.get_paths('DTI STEAM 114 Trio')[2]
    #print('find filenames for T1')
    #fname_T1=resources.get_paths('MPRAGE nifti Trio')[2]

    FA_grid_img,FA_shell_imgT=register_FA_same_subj_diff_sessions(dname_grid,dname_shell)

    #FA_shell_data=FA_shell_imgT.get_data()
    #FA_shell_data[FA_shell_data<0]=0

    print('tile volumes')
    save_volumes_as_mosaic('/tmp/mosaic_fa.png',\
                               [FA_grid_img.get_data(),FA_shell_imgT.get_data()])

    '''


text:
package com.bwssystems.HABridge;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.util.Base64;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.UUID;
import java.util.Map.Entry;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.bwssystems.HABridge.api.hue.HueError;
import com.bwssystems.HABridge.api.hue.HueErrorResponse;
import com.bwssystems.HABridge.api.hue.WhitelistEntry;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;

import spark.Request;

public class BridgeSecurity {
	private static final Logger log = LoggerFactory.getLogger(BridgeSecurity.class);
	private static final String USER_SESSION_ID = "user";
	private static final String DEPRACATED_INTERNAL_USER = "thehabridgeuser";
	private static final String TEST_USER_TYPE = "test_ha_bridge";
    private static final byte[] SALT = {
            (byte) 0xde, (byte) 0x33, (byte) 0x10, (byte) 0x12,
            (byte) 0xde, (byte) 0x33, (byte) 0x10, (byte) 0x12,
        };
	private static char[] habridgeKey;
	private String execGarden;
    private BridgeSecurityDescriptor securityDescriptor;
	private boolean settingsChanged;

	public BridgeSecurity(char[] theKey, String theExecGarden) {
		habridgeKey = theKey;
		execGarden = theExecGarden;
		securityDescriptor = null;
		settingsChanged = false;
	}

	public void setSecurityData(String theData) {
		String anError = null;
		if(theData != null && !theData.isEmpty()) {
			try {
				securityDescriptor = new Gson().fromJson(decrypt(theData), BridgeSecurityDescriptor.class);
			} catch (JsonSyntaxException e) {
				anError = e.getMessage();
			} catch (GeneralSecurityException e) {
				anError = e.getMessage();
			} catch (IOException e) {
				anError = e.getMessage();
			}
			if(anError != null)
				log.warn("Cound not get security data, using default security (none): " + anError);
		}

		if(theData == null || anError != null) {
			securityDescriptor = new BridgeSecurityDescriptor();
		}
	}

	public String getSecurityDescriptorData() throws UnsupportedEncodingException, GeneralSecurityException {
		return encrypt(new Gson().toJson(securityDescriptor));
	}

	public boolean isUseLinkButton() {
		return securityDescriptor.isUseLinkButton();
	}

	public String setPassword(User aUser) throws IOException {
		String error = null;
		if(aUser != null) {
			error = aUser.validate();
			if(error == null) {
				if(securityDescriptor.getUsers() != null) {
					User theUser = securityDescriptor.getUsers().get(aUser.getUsername());
					if(theUser != null) {
						theUser.setPassword(aUser.getPassword());
						theUser.setPassword2(null);
						settingsChanged = true;
					}
					else
						error = "User not found";
				}
				else
					error = "User not found";
			}
		}
		else
			error = "invalid user object given";

		return error;
	}

	public String addUser(User aUser) throws IOException {
		String error = null;
		if(aUser != null) {
			error = aUser.validate();
			if(error == null) {
				if(securityDescriptor.getUsers() == null)
					securityDescriptor.setUsers(new HashMap<String, User>());
				if(securityDescriptor.getUsers().get(aUser.getUsername()) == null) {
					securityDescriptor.getUsers().put(aUser.getUsername(), aUser);
					settingsChanged = true;
				}
				else
					error = "Invalid request";
			}
		}
		else
			error = "invalid user object given";

		return error;
	}

	public String delUser(User aUser) throws IOException {
		String error = null;
		if(aUser != null) {
				if(securityDescriptor.getUsers() != null) {
				if(securityDescriptor.getUsers().get(aUser.getUsername()) != null) {
					securityDescriptor.getUsers().remove(aUser.getUsername());
					settingsChanged = true;
				}
				else
					error = "User not found";
				}
		}
		else
			error = "invalid user object given";

		return error;
	}

	public String getExecGarden() {
		return execGarden;
	}

	String getKeyfilePath() {
		return securityDescriptor.getKeyfilePath();
	}

	String getKeyfilePassword() {
		return securityDescriptor.getKeyfilePassword();
	}

	private void setUseLinkButton(boolean useThis) {
		securityDescriptor.setUseLinkButton(useThis);
		settingsChanged = true;
	}

	public boolean isSecureHueApi() {
		return securityDescriptor.isSecureHueApi();
	}

	public boolean isUseHttps() {
		return securityDescriptor.isUseHttps();
	}

	public boolean isKeyfilePW() {
		if(securityDescriptor.getKeyfilePassword() != null && !securityDescriptor.getKeyfilePassword().trim().isEmpty()) {
			return true;
		}

		return false;
	}

	private void setSecureHueApi(boolean theState) {
		securityDescriptor.setSecureHueApi(theState);
		settingsChanged = true;
	}

	private void setUseHttps(boolean usehttps, String keyfilepath, String keyfilepassword) {
		if(usehttps) {
			if(!isUseHttps()) {
				securityDescriptor.setKeyfilePath(keyfilepath);
				securityDescriptor.setKeyfilePassword(keyfilepassword);
				securityDescriptor.setUseHttps(usehttps);
				settingsChanged = true;
			} else {
				if(!keyfilepassword.equals("########")) {
					securityDescriptor.setKeyfilePassword(keyfilepassword);
					settingsChanged = true;
				}

				if(!securityDescriptor.getKeyfilePath().equals(keyfilepath)) {
					securityDescriptor.setKeyfilePath(keyfilepath);
					settingsChanged = true;
				}
			}
		} else {
			if(isUseHttps()) {
				securityDescriptor.setKeyfilePassword("");
				securityDescriptor.setKeyfilePath("");
				securityDescriptor.setUseHttps(usehttps);
				settingsChanged = true;
			}
		}
	}

	public SecurityInfo getSecurityInfo() {
		SecurityInfo theInfo = new SecurityInfo();
		theInfo.setUseLinkButton(isUseLinkButton());
		theInfo.setSecureHueApi(isSecureHueApi());
		theInfo.setSecure(isSecure());
		theInfo.setUseHttps(isUseHttps());
		theInfo.setKeyfilePath(securityDescriptor.getKeyfilePath());

		if(isKeyfilePW()) {
			theInfo.setKeyfilePassword("########");
		}
		else {
			theInfo.setKeyfilePassword("");
		}
		if(isSecure()) {
			theInfo.setExecGarden(execGarden);
		}
		return theInfo;
	}

	public void setSecurityDataByInfo(SecurityInfo theInfo) {
		setUseLinkButton(theInfo.isUseLinkButton());
		setSecureHueApi(theInfo.isSecureHueApi());
		setUseHttps(theInfo.isUseHttps(), theInfo.getKeyfilePath(), theInfo.getKeyfilePassword());
	}

	public LoginResult validatePassword(User targetUser) throws IOException {
		LoginResult result = new LoginResult();
		if(targetUser != null && targetUser.getUsername() != null) {
			if(securityDescriptor.getUsers() != null && securityDescriptor.getUsers().get(targetUser.getUsername()) != null) {
				User theUser = securityDescriptor.getUsers().get(targetUser.getUsername());
				if(theUser.getPassword() != null) {
					theUser.setPassword2(targetUser.getPassword());
					if(theUser.validatePassword()) {
						theUser.setPassword2(null);
						result.setUser(targetUser);
					}
					else
						result.setError("user or password not correct");
				} else {
					result.setError("input password is not set....");
				}
			}
			else
				result.setError("user or password not correct");
		}
		else
			result.setError("input user not given");
		return result;
	}

	public boolean isSecure() {
		return securityDescriptor.isSecure();
	}

	public boolean isSettingsChanged() {
		return settingsChanged;
	}

	public void setSettingsChanged(boolean settingsChanged) {
		this.settingsChanged = settingsChanged;
	}
	public Map<String, WhitelistEntry> getWhitelist() {
		return securityDescriptor.getWhitelist();
	}

	public void setWhitelist(Map<String, WhitelistEntry> aWhitelist) {
		securityDescriptor.setWhitelist(aWhitelist);
		settingsChanged = true;
		return;
	}

	public HueError[] validateWhitelistUser(String aUser, String userDescription, boolean strict) {
		String validUser = null;
		boolean found = false;
		if (aUser != null && !aUser.equalsIgnoreCase("undefined") && !aUser.equalsIgnoreCase("null")
				&& !aUser.equalsIgnoreCase("") && !aUser.equals(DEPRACATED_INTERNAL_USER)) {
			if (securityDescriptor.getWhitelist() != null) {
				Set<String> theUserIds = securityDescriptor.getWhitelist().keySet();
				Iterator<String> userIterator = theUserIds.iterator();
				while (userIterator.hasNext()) {
					validUser = userIterator.next();
					if (validUser.equals(aUser)) {
						found = true;
						log.debug("validateWhitelistUser: found a user <" + aUser + ">");
					}
				}
			}

			if(!found && !strict) {
				log.debug("validateWhitelistUser: a user was not found and it is not strict rules <" + aUser + "> being created");
				newWhitelistUser(aUser, userDescription);

				found = true;
			}
		}

		if (!found) {
			log.debug("validateWhitelistUser: a user was not found and strict rules is set to: " + strict + "for user <" + aUser + ">");
			return HueErrorResponse.createResponse("1", "/api/" + aUser == null ? "" : aUser, "unauthorized user", null, null, null).getTheErrors();
		}

		return null;
	}

	public String findWhitelistUserByDeviceType(String aDeviceType) {
		String validUser = null;
		boolean found = false;
		WhitelistEntry anEntry = null;
		if (aDeviceType != null) {
			if (securityDescriptor.getWhitelist() != null) {
				Set<String> theUserIds = securityDescriptor.getWhitelist().keySet();
				Iterator<String> userIterator = theUserIds.iterator();
				while (!found && userIterator.hasNext()) {
					validUser = userIterator.next();
					anEntry = securityDescriptor.getWhitelist().get(validUser);
					if (anEntry.getName().equals(aDeviceType)) {
						found = true;
						log.debug("findWhitelistUserByDeviceType: found a user <" + validUser + "> for device type <" + aDeviceType + ">");
					}
				}
			}
		}

		if(!found)
			validUser = null;

		return validUser;
	}

	private void newWhitelistUser(String aUser, String userDescription) {
		if (securityDescriptor.getWhitelist() == null) {
			securityDescriptor.setWhitelist(new HashMap<>());
		}
		if(userDescription == null)
			userDescription = "auto insert user";

		securityDescriptor.getWhitelist().put(aUser, WhitelistEntry.createEntry(userDescription));
		setSettingsChanged(true);
	}

	public String createWhitelistUser(String userDescription) {
		String aUser = null;
		String theEntry = findWhitelistUserByDeviceType(userDescription);
		if(theEntry == null) {
			aUser = getNewUserID();
			newWhitelistUser(aUser, userDescription);
		} else {
			aUser = theEntry;
		}
		return aUser;
	}

	public void convertWhitelist(Map<String, WhitelistEntry> whitelist) {
		securityDescriptor.setWhitelist(whitelist);
	}

	private String getNewUserID() {
		UUID uid = UUID.randomUUID();
		StringTokenizer st = new StringTokenizer(uid.toString(), "-");
		String newUser = "";
		while (st.hasMoreTokens()) {
			newUser = newUser + st.nextToken();
		}

		return newUser;
	}

	public void removeHttpsSettings() {
		securityDescriptor.setUseHttps(false);
		securityDescriptor.setKeyfilePassword(null);
		securityDescriptor.setKeyfilePath(null);
		setSettingsChanged(true);
	}

	public void removeTestUsers() {
		if (securityDescriptor.getWhitelist() != null) {
			Object anUser = securityDescriptor.getWhitelist().remove(DEPRACATED_INTERNAL_USER);
			if(anUser != null)
				setSettingsChanged(true);

		    Iterator<Entry<String, WhitelistEntry>> it = securityDescriptor.getWhitelist().entrySet().iterator();
		    while (it.hasNext()) {
		        Map.Entry<String, WhitelistEntry> pair = it.next();
		        if(pair.getValue().getName().equals(TEST_USER_TYPE)) {
			        it.remove(); // avoids a ConcurrentModificationException
					setSettingsChanged(true);
		        }
		    }
		}
	}

	static String encrypt(String property) throws GeneralSecurityException, UnsupportedEncodingException {
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
        SecretKey key = keyFactory.generateSecret(new PBEKeySpec(habridgeKey));
        Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
        pbeCipher.init(Cipher.ENCRYPT_MODE, key, new PBEParameterSpec(SALT, 20));
        return base64Encode(pbeCipher.doFinal(property.getBytes("UTF-8")));
    }

    private static String base64Encode(byte[] bytes) {
        return Base64.getEncoder().encodeToString(bytes);
    }

    static String decrypt(String property) throws GeneralSecurityException, IOException {
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
        SecretKey key = keyFactory.generateSecret(new PBEKeySpec(habridgeKey));
        Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
        pbeCipher.init(Cipher.DECRYPT_MODE, key, new PBEParameterSpec(SALT, 20));
        return new String(pbeCipher.doFinal(base64Decode(property)), "UTF-8");
    }

    private static byte[] base64Decode(String property) throws IOException {
        return Base64.getDecoder().decode(property);
    }

    public void addAuthenticatedUser(Request request, User u) {
		request.session().attribute(USER_SESSION_ID, u);

	}

	public void removeAuthenticatedUser(Request request) {
		request.session().removeAttribute(USER_SESSION_ID);
		request.session().invalidate();
	}

	public User getAuthenticatedUser(Request request) {
		User theUser = request.session().attribute(USER_SESSION_ID);
		if(theUser == null) {
			String authHeader = request.headers("Authorization");
			if(authHeader != null) {
			    byte[] authData;
				try {
					authData = base64Decode(authHeader.substring(6));
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					return theUser;
				}
			    String[] credentials = new String(authData).split(":");
			    String username = credentials[0];
			    String password = credentials[1];
			    theUser = new User();
			    theUser.setUsername(username);
			    theUser.setPassword(password);
			    LoginResult theResult = null;
				try {
					theResult = validatePassword(theUser);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					return null;
				}
				if(theResult != null && theResult.getError() == null) {
					addAuthenticatedUser(request, theUser);
				}
			}
		}
		return theUser;
	}
}


text:
NTL_OPEN_NNS

struct IntFactor {
   IntFactor() { }
   ~IntFactor() { }

   long q;
   long a;
   long val;
   long link;
};

NTL_vector_decl(IntFactor,vec_IntFactor)
typedef vec_IntFactor FacVec;

void FactorInt(FacVec& fvec, long n);

NTL_CLOSE_NNS

#endif


text:
///This is a header only, small class that gets a  string as url and parse it to "Protocol", "Host", "Port", "Path", "File", "Parameters".
#include <boost/regex.hpp>
#include <vector>
#include <string>

///This class gets a url string and parse it to "Protocol", "Host", "Port", "Path", "File", "Parameters".
class UrlParser{
	public:
		UrlParser(std::string url){
			std::vector<std::string> values;
			boost::regex expression(
			//       proto                 host               port
					"^(\?:([^:/\?#]+)://)\?(\\w+[^/\?#:]*)(\?::(\\d+))\?"
			//       path                  file       parameters
					"(/\?(\?:[^\?#/]*/)*)\?([^\?#]*)\?(\\\?(.*))\?"
						           );

			if (boost::regex_split(std::back_inserter(values), url, expression)){
			/*
				const char* names[] = {"Protocol", "Host", "Port", "Path", "File", "Parameters", NULL};
				for (int i = 0; names[i]; i++)
					printf("%s: %s\n", names[i], values[i].c_str());
			}*/
				protocol = values[0].c_str();
				host = values[1].c_str();
				port = values[2].c_str();
				path = values[3];//.c_str();
				file = values[4].c_str();
				parameters = values[5];
			}else{//Fatal error
			}
		}//constructor

		~UrlParser(){};

		//variables
		std::string protocol;
		std::string host;
		std::string port;
		std::string path;
		std::string file;
		std::string parameters;
};


text:
require 'spec_helper'
require 'base64'

module Aws
  module S3
    describe PresignedPost do

      let(:creds) { Credentials.new('akid', 'secret') }

      let(:region) { 'us-east-1' }

      let(:bucket) { 'bucket-name' }

      let(:options) {{}}

      let(:post) { PresignedPost.new(creds, region, bucket, options) }

      def decode(policy)
        Json.load(Base64.decode64(policy))
      end

      def policy(post)
        decode(post.fields['policy'])['conditions']
      end

      describe '#initialize' do

        it 'rejects unknown options' do
          expect {
            PresignedPost.new(creds, region, bucket, foo: 'bar')
          }.to raise_error(/undefined method `foo'/)
        end

      end

      describe '#url' do

        it 'puts dns compatible bucket names in the host' do
          post = PresignedPost.new(creds, 'us-east-1', 'bucket-name')
          expect(post.url).to eq('https://bucket-name.s3.amazonaws.com')
        end

        it 'puts dns compatible bucket name that contain dots in the path' do
          post = PresignedPost.new(creds, 'us-east-1', 'bucket.name')
          expect(post.url).to eq('https://s3.amazonaws.com/bucket.name')
        end

        it 'puts non-dns compatible bucket name in the path' do
          post = PresignedPost.new(creds, 'us-east-1', 'BucketName')
          expect(post.url).to eq('https://s3.amazonaws.com/BucketName')
        end

        it 'creates regionalized urls for other regions' do
          post = PresignedPost.new(creds, 'eu-central-1', 'bucket-name')
          expect(post.url).to eq('https://bucket-name.s3.eu-central-1.amazonaws.com')
        end

      end

      describe 'key' do

        it 'is required' do
          expect { post.fields }.to raise_error(/you must provide a key/)
        end

        it 'can be set via :key' do
          options[:key] = 'obj-key'
          expect(post.fields['key']).to eq('obj-key')
          expect(policy(post)).to include({'key' => 'obj-key'})
        end

        it 'can be set via :key_starts_with' do
          options[:key_starts_with] = 'prefix/'
          expect(post.fields['key']).to be(nil)
          expect(policy(post)).to include(['starts-with', '$key', 'prefix/'])
        end

        it 'can be set via #key' do
          post.key('obj-key')
          expect(post.fields['key']).to eq('obj-key')
          expect(policy(post)).to include({'key' => 'obj-key'})
        end

        it 'can be set via #key_starts_with' do
          post.key_starts_with('prefix/')
          expect(post.fields['key']).to be(nil)
          expect(policy(post)).to include(['starts-with', '$key', 'prefix/'])
        end

        it 'can be set via :allow_any' do
          options[:allow_any] = 'key'
          expect(post.fields['key']).to be(nil)
          expect(policy(post)).to include(['starts-with', '$key', ''])
        end

        it 'can be set via #allow_any' do
          post.allow_any('key')
          expect(post.fields['key']).to be(nil)
          expect(policy(post)).to include(['starts-with', '$key', ''])
        end

      end

      describe ':signature_expiration' do

        it 'defaults to one hour from now' do
          now = Time.now
          allow(Time).to receive(:now).and_return(now)
          policy = decode(post.key('key').fields['policy'])
          expect(policy['expiration']).to eq((now + 3600).utc.iso8601)
        end

        it 'can be set in the constructor' do
          now = Time.now
          options[:signature_expiration] = now
          policy = decode(post.key('key').fields['policy'])
          expect(policy['expiration']).to eq(now.utc.iso8601)
        end

      end

      describe 'fields' do

        before(:each) do
          post.key('key')
        end

        it 'provides methods for setting fields or fields starts with' do
          post = PresignedPost.new(creds, region, bucket).key('key')
          post.acl('public-read')
          expect(post.fields['acl']).to eq('public-read')
          expect(policy(post)).to include({ 'acl' => 'public-read' })

          post = PresignedPost.new(creds, region, bucket).key('key')
          post.acl_starts_with('')
          expect(post.fields['acl']).to be(nil)
          expect(policy(post)).to include(['starts-with', '$acl', ''])
        end

        it 'formats the Expires time value as httpdate' do
          now = Time.now
          post.expires(now)
          expect(post.fields['Expires']).to eq(now.httpdate)
        end

        it 'allows prefixed Expires' do
          post.expires_starts_with('')
          expect(post.fields['Expires']).to be(nil)
          expect(policy(post)).to include(['starts-with', '$Expires', ''])
        end

        it 'accepts a range for content_length_range' do
          post.content_length_range(10..20)
          expect(policy(post)).to include(['content-length-range', 10, 20])
        end

        it 'respects non-inclusive ranges' do
          post.content_length_range(10...20)
          expect(policy(post)).to include(['content-length-range', 10, 19])
        end

        it 'accepts a hash to :metadata' do
          post.metadata(foo: 'bar', 'mno' => 'xyz')
          expect(post.fields['x-amz-meta-foo']).to eq('bar')
          expect(post.fields['x-amz-meta-mno']).to eq('xyz')
          expect(policy(post)).to include('x-amz-meta-foo' => 'bar')
          expect(policy(post)).to include('x-amz-meta-mno' => 'xyz')
        end

        it 'accepts a hash to :metadata_starts_with' do
          post.metadata_starts_with(foo: 'foo/', 'mno' => 'mno/')
          expect(post.fields['x-amz-meta-foo']).to be(nil)
          expect(post.fields['x-amz-meta-mno']).to  be(nil)
          expect(policy(post)).to include(['starts-with','$x-amz-meta-foo','foo/'])
          expect(policy(post)).to include(['starts-with','$x-amz-meta-mno','mno/'])
        end

        it 'computes a MD5 of the customer provided encryption key' do
          key = 'abcmnoxyz12345'
          md5 = Base64.strict_encode64(OpenSSL::Digest::MD5.digest(key))
          post.server_side_encryption_customer_key(key)
          expect(post.fields['x-amz-server-side-encryption-customer-key']).to eq(key)
          expect(post.fields['x-amz-server-side-encryption-customer-key-MD5']).to eq(md5)
          expect(policy(post)).to include('x-amz-server-side-encryption-customer-key' => key)
          expect(policy(post)).to include('x-amz-server-side-encryption-customer-key-MD5' => md5)
        end

        it 'does not computes MD5 for starts with' do
          post.server_side_encryption_customer_key_starts_with('prefix')
          expect(post.fields['x-amz-server-side-encryption-customer-key']).to be(nil)
          expect(post.fields['x-amz-server-side-encryption-customer-key-MD5']).to be(nil)
          expect(policy(post)).to include(['starts-with', '$x-amz-server-side-encryption-customer-key', 'prefix'])
        end

        it 'accepts ${filename} to eq' do
          post.metadata('orig-filename' => '${filename}')
          expect(post.fields['x-amz-meta-orig-filename']).to eq('${filename}')
          expect(policy(post)).to include(['starts-with', '$x-amz-meta-orig-filename', ''])
        end

        it 'accepts ${filename} and removes it from the condition for starts with' do
          post = PresignedPost.new(creds, region, bucket)
          post.key('prefix/${filename}')
          expect(post.fields['key']).to eq('prefix/${filename}')
          expect(policy(post)).to include(['starts-with', '$key', 'prefix/'])
        end

        it 'requires ${filename} to be at the end of the value' do
          post = PresignedPost.new(creds, region, bucket)
          expect {
            post.key('${filename}/foo')
          }.to raise_error(ArgumentError)
        end

        it 'accepts a list of fields to white-list' do
          post.allow_any(['foo']).allow_any('Filename')
          expect(post.fields['foo']).to be(nil)
          expect(post.fields['Filename']).to be(nil)
          expect(policy(post)).to include(['starts-with', '$foo', ''])
          expect(policy(post)).to include(['starts-with', '$Filename', ''])
        end

      end

      describe '#fields' do

        it 'returns a hash with a policy document and signature' do
          now = Time.now
          allow(Time).to receive(:now).and_return(now)
          post.key('key')
          expect(post.fields.keys).to eq(%w(
            key policy x-amz-credential x-amz-algorithm
            x-amz-date x-amz-signature
          ))
          expect(post.fields['x-amz-algorithm']).to eq('AWS4-HMAC-SHA256')
          expect(post.fields['x-amz-credential']).to eq("akid/#{now.strftime('%Y%m%d')}/#{region}/s3/aws4_request")
          expect(post.fields['x-amz-date']).to eq(now.strftime('%Y%m%dT%H%M%SZ'))
        end

        it 'generates a valid signature' do
          # test example from http://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-post-example.html
          creds = Credentials.new('AKIAIOSFODNN7EXAMPLE', 'wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY')
          region = 'us-east-1'
          bucket = 'examplebucket'
          now = Time.parse('20130806T000000Z')
          allow(Time).to receive(:now).and_return(now)
          post = PresignedPost.new(creds, region, bucket, key: 'key')
          policy = <<-POLICY.strip
eyAiZXhwaXJhdGlvbiI6ICIyMDEzLTA4LTA3VDEyOjAwOjAwLjAwMFoiLA0KICAiY29uZGl0aW9ucyI6IFsNCiAgICB7ImJ1Y2tldCI6ICJleGFtcGxlYnVja2V0In0sDQogICAgWyJzdGFydHMtd2l0aCIsICIka2V5IiwgInVzZXIvdXNlcjEvIl0sDQogICAgeyJhY2wiOiAicHVibGljLXJlYWQifSwNCiAgICB7InN1Y2Nlc3NfYWN0aW9uX3JlZGlyZWN0IjogImh0dHA6Ly9leGFtcGxlYnVja2V0LnMzLmFtYXpvbmF3cy5jb20vc3VjY2Vzc2Z1bF91cGxvYWQuaHRtbCJ9LA0KICAgIFsic3RhcnRzLXdpdGgiLCAiJENvbnRlbnQtVHlwZSIsICJpbWFnZS8iXSwNCiAgICB7IngtYW16LW1ldGEtdXVpZCI6ICIxNDM2NTEyMzY1MTI3NCJ9LA0KICAgIFsic3RhcnRzLXdpdGgiLCAiJHgtYW16LW1ldGEtdGFnIiwgIiJdLA0KDQogICAgeyJ4LWFtei1jcmVkZW50aWFsIjogIkFLSUFJT1NGT0ROTjdFWEFNUExFLzIwMTMwODA2L3VzLWVhc3QtMS9zMy9hd3M0X3JlcXVlc3QifSwNCiAgICB7IngtYW16LWFsZ29yaXRobSI6ICJBV1M0LUhNQUMtU0hBMjU2In0sDQogICAgeyJ4LWFtei1kYXRlIjogIjIwMTMwODA2VDAwMDAwMFoiIH0NCiAgXQ0KfQ==
          POLICY
          allow(post).to receive(:policy).and_return(policy)
          expect(post.fields['x-amz-signature']).to eq('21496b44de44ccb73d545f1a995c68214c9cb0d41c45a17a5daeec0b1a6db047')
        end

        it 'adds x-amz-security-token as appropriate' do
          creds = Credentials.new('key', 'secret', 'token')
          post = PresignedPost.new(creds, region, bucket).key('key')
          expect(post.fields['x-amz-security-token']).to eq('token')
          expect(policy(post)).to include('x-amz-security-token' => 'token')
        end

        it 'sets the storage class if requested' do
          creds = Credentials.new('key', 'secret', 'token')
          post = PresignedPost.new(creds, region, bucket).key('key').storage_class('REDUCED_REDUNDANCY')
          expect(post.fields['x-amz-storage-class']).to eq('REDUCED_REDUNDANCY')
        end
      end
    end
  end
end