text:
package com.foc.web.unitTesting;

import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.helpers.DefaultHandler;

import com.foc.Globals;
import com.foc.access.FocLogger;
import com.foc.annotations.unit.FUSuite;
import com.foc.annotations.unit.FUTest;
import com.vaadin.server.ClassResource;

public class FocUnitTestingSuite {

  private String name = null;
  private String fileName = null;
  private boolean showInMenu = false;

  private boolean parsingDone = false;
  private String startingTest = null;

  private Map<String, FocUnitTest> testMap = null;
  private LinkedList<FocUnitTest> testSequence = null;

  private FocUnitDictionary dictionary = null;

  public FocUnitTestingSuite() {
  }

  public FocUnitTestingSuite(FocUnitDictionary dictionary, String name, String fileName) {
    setName(name);
    setFileName(fileName);
    setDictionary(dictionary);
  }

  /**
   * This is used for the new Test that do not use XML and support parsing methods "test_" for test declataion
   *
   * @param dictionary
   * @param name
   */
  public FocUnitTestingSuite(FocUnitDictionary dictionary, String name) {
    setName(name);
    setFileName(null);
    setDictionary(dictionary);

		setParsingDone(true);
		dictionary.putAndSequence(this);

		String description = "";
		FUSuite suiteAnnotation = getClass().getAnnotation(FUSuite.class);
		if(suiteAnnotation != null) {
			description = suiteAnnotation.description();
		}
		dictionary.unitDoc_AddSuite(name, description);
    declareAllTestMethods();
  }

  public void dispose(int mode) {

    if(mode == FocUnitDictionary.MODE_DISPOSE){
      name = null;
      fileName = null;
      dictionary = null;
      showInMenu = false;
    }

    parsingDone = false;

    if(testMap != null){
      Collection<FocUnitTest> collection = testMap.values();
      Iterator<FocUnitTest> itr = collection.iterator();

      while(itr.hasNext()){
        itr.next().dispose(mode);
      }

      collection.clear();
      collection = null;
      itr = null;

      testMap.clear();
      testMap = null;
    }
  }

  public void declareAllTestMethods() {
  	Class cls = getClass();

  	Method[] methodArray = getDeclaredMethodsInOrder(cls);

//  	Method[] methodArray = cls.getMethods();
  	for(int i=0; i<methodArray.length; i++) {
  		Method m = methodArray[i];
  		try{
  			boolean isATestMethod = m.getName().startsWith("test_");
  			boolean isImplemented = true;
  			String description = "";
				FUTest ann = m.getAnnotation(FUTest.class);
				if(ann != null) {
					isATestMethod = true;
					isImplemented = ann.implemented();
					description = ann.description();
				}

  			if(isATestMethod) {
  				if(ann == null || ann.show()) {
  					getDictionary().unitDoc_AddTest(ann, m.getName(), description, isImplemented);
  				}
  				if(isImplemented) {
			      Class[] clss = new Class[0];
			      Object[] args = new Object[0];
	  				m.invoke(this, clss);
  				}
  			}
			}catch (Exception e){
				Globals.logException(e);
			}
  	}
  }

  //REVERTME final
  public void runSuite() throws Exception {
  	if(!FocUnitDictionary.getInstance().isExitTesting()) {
//	    FocUnitDictionary.getInstance().clear();
      FocLogger.getInstance().openNode("Starting suite " + this.getName());
	    execute();
      FocLogger.getInstance().closeNode();
  	}
  }

  public void execute() throws Exception {
    String startingTest = getStartingTest();
    if (startingTest != null && getTestMap(false).get(startingTest) != null) {
      runTestByName(startingTest);
    } else {
      runAllTests();
    }
  }

  private void runAllTests() throws Exception {
    if (getTestMap(false) != null) {
      Collection<FocUnitTest> collection = getTestMap(false).values();

      if (collection != null) {
        Iterator<FocUnitTest> itr = collection.iterator();

        while (itr != null && itr.hasNext()) {
          FocUnitTest test = (FocUnitTest) itr.next();
          FocLogger.getInstance().openNode("Starting: Test " + test.getName() + " in suite " + test.getSuite().getName() + ".");
          test.init();
          test.runTest();
          FocLogger.getInstance().closeNode("Ending: Test " + test.getName() + " in suite " + test.getSuite().getName() + ".");
        }
      } else {
        FocLogger.getInstance().addError("Test suite " + this.getName() + " contains no tests.");
      }
    } else {
      FocLogger.getInstance().addError("Test suite " + this.getName() + " contains no tests.");
    }
  }

	public FocUnitTest getTest(String name) {
		return getTestMap(false).get(name);
	}

  public void runTestByName(String testName, FocUnitXMLAttributes callerArguments) throws Exception {
    if (testName != null) {
      Map<String, FocUnitTest> tempTestMap = getTestMap(false);
      if (tempTestMap != null) {
        FocUnitTest tempTest = tempTestMap.get(testName);
        if (tempTest != null) {
          tempTest.init();
          tempTest.setCallerArguments(callerArguments);
          tempTest.runTest();
        } else {
          FocLogger.getInstance().addFailure("Test " + testName + " not found in suite " + this.getName() + ".");
          Globals.logString("Available Tests in suite are:");
          Globals.logString("-----------------------------");
          Iterator<String> iter = tempTestMap.keySet().iterator();
          while(iter != null && iter.hasNext()){
          	String val = iter.next();
          	Globals.logString("Test: "+val);
          }
          Globals.logString("-----------------------------");
        }
      } else {
        FocLogger.getInstance().addError("Test map returned null in suite " + this.getName() + ".");
      }
    } else {
      FocLogger.getInstance().addError("Test name cannot be empty.");
    }
  }

  public void runTestByName(String testName) throws Exception {
    runTestByName(testName, null);
  }

  private void parseXML_IfNeeded() throws Exception {
    try {
      if (!isParsingDone()) {
        setParsingDone(true);
        String fileName = getFileName();
        ClassResource resource = null;
        InputStream inputStream = null;
        try {
          resource = new ClassResource(fileName);
          inputStream = resource.getStream().getStream();
        } catch (Exception e) {
          FocLogger.getInstance().addError("Could not load file : " + fileName);
          FocLogger.getInstance().addError(e.getMessage());
          Globals.logString("Could not load file : " + fileName);
          Globals.logException(e);
        }

        if (inputStream == null) {
          FocLogger.getInstance().addError("Input stream is null. Could not load file: " + fileName + ".");
        }

        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser saxParser = factory.newSAXParser();
        saxParser.parse(inputStream, new FocXMLUnitHandler());
      }
    } catch (Exception e) {
      Globals.logException(e);
      FocLogger.getInstance().addError(e.getMessage());
    }
  }

  private class FocXMLUnitHandler extends DefaultHandler {
    FocUnitTest test = null;

    public void startElement(String uri, String localName, String qName, Attributes attributes) {
      if (qName.equalsIgnoreCase(FXMLUnit.TAG_TEST_SUITE)) {
        FocLogger.getInstance(true).openNode("Parsing: Suite tag encountered.");
        if (attributes.getValue(FXMLUnit.ATT_STARTING_TEST) != null) {
          FocLogger.getInstance().addInfo("Parsing: Attribute " + FXMLUnit.ATT_STARTING_TEST + " encountered.");
          FocUnitTestingSuite.this.setStartingTest(attributes.getValue(FXMLUnit.ATT_STARTING_TEST));
        }
      } else if (qName.equalsIgnoreCase(FXMLUnit.TAG_TEST)) {
        FocLogger.getInstance().openNode("Parsing: Test tag encountered.");
        test = new FocUnitTest();
        test.setSuite(FocUnitTestingSuite.this);
        test.setName(attributes.getValue(FXMLUnit.ATT_NAME));
      } else {
        FocLogger.getInstance().addInfo("Parsing: " + qName + " tag encountered.");

        if (qName.equalsIgnoreCase(FXMLUnit.TAG_CALL)) {
          FocLogger.getInstance().openNode("Parsing: " + FXMLUnit.TAG_CALL + " tag encountered.");
          FocLogger.getInstance().addInfo("New node created.");
        }

        FocUnitMethodFactory methodFactory = FocUnitMethodFactory.getInstance();

        if (methodFactory.getMethodByName(qName) != null) {
          FocUnitTestingCommand command = new FocUnitTestingCommand(test, qName, attributes);
          test.addCommand(command);
          FocLogger.getInstance().addInfo("Parsing: Adding method " + command.getMethodName() + " to the test " + test.getName() + ".");
        } else {
          try{
						FocLogger.getInstance().addError("Parsing: Could not find method " + qName + " by name.");
					}catch (Exception e){
						Globals.logException(e);
					}
        }
      }

    }

    public void endElement(String uri, String localName, String qName) {
      if (qName.equalsIgnoreCase(FXMLUnit.TAG_TEST_SUITE)) {
        FocLogger.getInstance().closeNode("Parsing: Suite closing tag encountered.");
      } else if (qName.equalsIgnoreCase(FXMLUnit.TAG_TEST)) {
        if (test != null) {
          FocLogger.getInstance().addInfo("Parsing: Adding test " + test.getName() + " to suite " + FocUnitTestingSuite.this.getName() + ".");
          FocUnitTestingSuite.this.put(test);
        } else {
          try{
						FocLogger.getInstance().addError("Parsing: The created test is empty.");
					}catch (Exception e){
						Globals.logException(e);
					}
        }
        FocLogger.getInstance().closeNode("Parsing: Test closing tag encountered.");
      } else if (qName.equalsIgnoreCase(FXMLUnit.TAG_CALL)) {
        FocLogger.getInstance().closeNode("Parsing: Closing " + FXMLUnit.TAG_CALL + " tag encountered.");
        FocLogger.getInstance().addInfo("Node has been closed.");
      }
    }
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public String getFileName() {
    return fileName;
  }

  public void setFileName(String fileName) {
    this.fileName = fileName;
  }

  public String getStartingTest() {
    try{
			parseXML_IfNeeded();
		}catch (Exception e){
			Globals.logException(e);
		}
    return startingTest;
  }

  public void setStartingTest(String startingTest) {
    this.startingTest = startingTest;
  }

  public Map<String, FocUnitTest> getTestMap(boolean createIfNeeded) {
    try{
			parseXML_IfNeeded();
		}catch (Exception e){
			Globals.logException(e);
		}
    if (testMap == null && createIfNeeded) {
      testMap = new HashMap<String, FocUnitTest>();
    }
    return testMap;
  }

  public void put(FocUnitTest test) {
    getTestMap(true).put(test.getName(), test);
    if(testSequence == null) testSequence = new LinkedList<FocUnitTest>();
    testSequence.add(test);
  }

  public boolean isParsingDone() {
    return parsingDone;
  }

  public void setParsingDone(boolean parsingDone) {
    this.parsingDone = parsingDone;
  }

  public FocUnitDictionary getDictionary() {
    return dictionary;
  }

  protected void setDictionary(FocUnitDictionary dictionary) {
    this.dictionary = dictionary;
  }

  public boolean isShowInMenu() {
    return showInMenu;
  }

  public void setShowInMenu(boolean showInMenu) {
    this.showInMenu = showInMenu;
  }

  public int testSequence_Size() {
  	return testSequence != null ? testSequence.size() : 0;
  }

  public FocUnitTest testSequence_Get(int at) {
  	return testSequence != null ? testSequence.get(at) : null;
  }

  /** Grok the bytecode to get the declared order */
  public static Method[] getDeclaredMethodsInOrder(Class clazz) {
      Method[] methods = null;
      try {
          String resource = clazz.getName().replace('.', '/')+".class";

          methods = clazz.getDeclaredMethods();

          InputStream is = clazz.getClassLoader()
              .getResourceAsStream(resource);

          if (is == null) {
              return methods;
          }

          java.util.Arrays.sort(methods,new ByLength());
          ArrayList<byte[]> blocks = new ArrayList<byte[]>();
          int length = 0;
          for (;;) {
              byte[] block = new byte[16*1024];
              int n = is.read(block);
              if (n > 0) {
                  if (n < block.length) {
                      block = java.util.Arrays.copyOf(block,n);
                  }
                  length += block.length;
                  blocks.add(block);
              } else {
                  break;
              }
          }

          byte[] data = new byte[length];
          int offset = 0;
          for (byte[] block : blocks) {
              System.arraycopy(block,0,data,offset,block.length);
              offset += block.length;
          }

          String sdata = new String(data,java.nio.charset.Charset.forName("UTF-8"));
          int lnt = sdata.indexOf("LineNumberTable");
          if (lnt != -1) sdata = sdata.substring(lnt+"LineNumberTable".length()+3);
          int cde = sdata.lastIndexOf("SourceFile");
          if (cde != -1) sdata = sdata.substring(0,cde);

          MethodOffset mo[] = new MethodOffset[methods.length];

          for (int i=0; i<methods.length; ++i) {
              int pos = -1;
              for (;;) {
                  pos=sdata.indexOf(methods[i].getName(),pos);
                  if (pos == -1) break;
                  boolean subset = false;
                  for (int j=0; j<i; ++j) {
                      if (mo[j].offset >= 0 &&
                          mo[j].offset <= pos &&
                          pos < mo[j].offset + mo[j].method.getName().length()) {
                          subset = true;
                          break;
                      }
                  }
                  if (subset) {
                      pos += methods[i].getName().length();
                  } else {
                      break;
                  }
              }
              mo[i] = new MethodOffset(methods[i],pos);
          }
          java.util.Arrays.sort(mo);
          for (int i=0; i<mo.length; ++i) {
              methods[i]=mo[i].method;
          }
      } catch (Exception ex) {
          ex.printStackTrace();
      }

      return methods;
  }

  private static class MethodOffset implements Comparable<MethodOffset> {
    MethodOffset(Method _method, int _offset) {
        method=_method;
        offset=_offset;
    }

    @Override
    public int compareTo(MethodOffset target) {
        return offset-target.offset;
    }

    Method method;
    int offset;
  }

  static class ByLength implements Comparator<Method> {

    @Override
    public int compare(Method a, Method b) {
        return b.getName().length()-a.getName().length();
    }
  }
}


text:
const hooks = require('hooks');

hooks.before('Resource > Update Resource', (transaction, done) => {
  transaction.skip = true;
  done();
});

hooks.after('Resource > Update Resource', (transaction, done) => {
  if (transaction.test && transaction.test.request) {
    transaction.test.request.body = '';
  }
  done();
});

redpajama_set_name: RedPajamaGithub


text:
<?php

/*
 * This file is part of the Silex framework.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Silex\Tests;

use Silex\Controller;
use Silex\Route;

/**
 * Controller test cases.
 *
 * @author Igor Wiedler <igor@wiedler.ch>
 */
class ControllerTest extends \PHPUnit_Framework_TestCase
{
    public function testBind()
    {
        $controller = new Controller(new Route('/foo'));
        $ret = $controller->bind('foo');

        $this->assertSame($ret, $controller);
        $this->assertEquals('foo', $controller->getRouteName());
    }

    /**
    * @expectedException Silex\Exception\ControllerFrozenException
    */
    public function testBindOnFrozenControllerShouldThrowException()
    {
        $controller = new Controller(new Route('/foo'));
        $controller->bind('foo');
        $controller->freeze();
        $controller->bind('bar');
    }

    public function testAssert()
    {
        $controller = new Controller(new Route('/foo/{bar}'));
        $ret = $controller->assert('bar', '\d+');

        $this->assertSame($ret, $controller);
        $this->assertEquals(array('bar' => '\d+'), $controller->getRoute()->getRequirements());
    }

    public function testValue()
    {
        $controller = new Controller(new Route('/foo/{bar}'));
        $ret = $controller->value('bar', 'foo');

        $this->assertSame($ret, $controller);
        $this->assertEquals(array('bar' => 'foo'), $controller->getRoute()->getDefaults());
    }

    public function testConvert()
    {
        $controller = new Controller(new Route('/foo/{bar}'));
        $ret = $controller->convert('bar', $func = function ($bar) { return $bar; });

        $this->assertSame($ret, $controller);
        $this->assertEquals(array('bar' => $func), $controller->getRoute()->getOption('_converters'));
    }

    /**
     * @dataProvider provideRouteAndExpectedRouteName
     */
    public function testDefaultRouteNameGeneration(Route $route, $expectedRouteName)
    {
        $controller = new Controller($route);
        $controller->bind($controller->generateRouteName(''));

        $this->assertEquals($expectedRouteName, $controller->getRouteName());
    }

    public function provideRouteAndExpectedRouteName()
    {
        return array(
            array(new Route('/Invalid%Symbols#Stripped', array(), array('_method' => 'POST')), 'POST_InvalidSymbolsStripped'),
            array(new Route('/post/{id}', array(), array('_method' => 'GET')), 'GET_post_id'),
            array(new Route('/colon:pipe|dashes-escaped'), '_colon_pipe_dashes_escaped'),
            array(new Route('/underscores_and.periods'), '_underscores_and.periods'),
        );
    }
}


text:
using System;

namespace Mozu.Api.Contracts.Customer
{
		///
		///	Properties of the commerce summary associated with a customer account, which includes details about the shopper's most recent order, wish lists, and total order value over time.
		///
		public class CommerceSummary
		{
			///
			///The date and time the shopper last submitted an order for any site associated with the tenant.
			///
			public DateTime? LastOrderDate { get; set; }

			///
			///The total number of order the shopper submitted across all sites associated with the tenant.
			///
			public int OrderCount { get; set; }

			///
			///The aggregate total amount of all orders the shopper submitted, across all sites associated with the tenant.
			///
			public CurrencyAmount TotalOrderAmount { get; set; }

			///
			///The number of visits to a site associated with a customer account.
			///
			public int VisitsCount { get; set; }

			///
			///The number of wish lists associated with a customer account. This number represents the total number of a shopper's wish lists across all sites associated with a tenant.
			///
			public int WishlistCount { get; set; }

		}

}


text:
package com.amazonaws.services.kendra.model.transform;

import java.math.*;

import javax.annotation.Generated;

import com.amazonaws.services.kendra.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;

import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;

/**
 * JiraConfiguration JSON Unmarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class JiraConfigurationJsonUnmarshaller implements Unmarshaller<JiraConfiguration, JsonUnmarshallerContext> {

    public JiraConfiguration unmarshall(JsonUnmarshallerContext context) throws Exception {
        JiraConfiguration jiraConfiguration = new JiraConfiguration();

        int originalDepth = context.getCurrentDepth();
        String currentParentElement = context.getCurrentParentElement();
        int targetDepth = originalDepth + 1;

        JsonToken token = context.getCurrentToken();
        if (token == null)
            token = context.nextToken();
        if (token == VALUE_NULL) {
            return null;
        }

        while (true) {
            if (token == null)
                break;

            if (token == FIELD_NAME || token == START_OBJECT) {
                if (context.testExpression("JiraAccountUrl", targetDepth)) {
                    context.nextToken();
                    jiraConfiguration.setJiraAccountUrl(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("SecretArn", targetDepth)) {
                    context.nextToken();
                    jiraConfiguration.setSecretArn(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("UseChangeLog", targetDepth)) {
                    context.nextToken();
                    jiraConfiguration.setUseChangeLog(context.getUnmarshaller(Boolean.class).unmarshall(context));
                }
                if (context.testExpression("Project", targetDepth)) {
                    context.nextToken();
                    jiraConfiguration.setProject(new ListUnmarshaller<String>(context.getUnmarshaller(String.class))

                    .unmarshall(context));
                }
                if (context.testExpression("IssueType", targetDepth)) {
                    context.nextToken();
                    jiraConfiguration.setIssueType(new ListUnmarshaller<String>(context.getUnmarshaller(String.class))

                    .unmarshall(context));
                }
                if (context.testExpression("Status", targetDepth)) {
                    context.nextToken();
                    jiraConfiguration.setStatus(new ListUnmarshaller<String>(context.getUnmarshaller(String.class))

                    .unmarshall(context));
                }
                if (context.testExpression("IssueSubEntityFilter", targetDepth)) {
                    context.nextToken();
                    jiraConfiguration.setIssueSubEntityFilter(new ListUnmarshaller<String>(context.getUnmarshaller(String.class))

                    .unmarshall(context));
                }
                if (context.testExpression("AttachmentFieldMappings", targetDepth)) {
                    context.nextToken();
                    jiraConfiguration.setAttachmentFieldMappings(new ListUnmarshaller<DataSourceToIndexFieldMapping>(
                            DataSourceToIndexFieldMappingJsonUnmarshaller.getInstance())

                    .unmarshall(context));
                }
                if (context.testExpression("CommentFieldMappings", targetDepth)) {
                    context.nextToken();
                    jiraConfiguration.setCommentFieldMappings(new ListUnmarshaller<DataSourceToIndexFieldMapping>(DataSourceToIndexFieldMappingJsonUnmarshaller
                            .getInstance())

                    .unmarshall(context));
                }
                if (context.testExpression("IssueFieldMappings", targetDepth)) {
                    context.nextToken();
                    jiraConfiguration.setIssueFieldMappings(new ListUnmarshaller<DataSourceToIndexFieldMapping>(DataSourceToIndexFieldMappingJsonUnmarshaller
                            .getInstance())

                    .unmarshall(context));
                }
                if (context.testExpression("ProjectFieldMappings", targetDepth)) {
                    context.nextToken();
                    jiraConfiguration.setProjectFieldMappings(new ListUnmarshaller<DataSourceToIndexFieldMapping>(DataSourceToIndexFieldMappingJsonUnmarshaller
                            .getInstance())

                    .unmarshall(context));
                }
                if (context.testExpression("WorkLogFieldMappings", targetDepth)) {
                    context.nextToken();
                    jiraConfiguration.setWorkLogFieldMappings(new ListUnmarshaller<DataSourceToIndexFieldMapping>(DataSourceToIndexFieldMappingJsonUnmarshaller
                            .getInstance())

                    .unmarshall(context));
                }
                if (context.testExpression("InclusionPatterns", targetDepth)) {
                    context.nextToken();
                    jiraConfiguration.setInclusionPatterns(new ListUnmarshaller<String>(context.getUnmarshaller(String.class))

                    .unmarshall(context));
                }
                if (context.testExpression("ExclusionPatterns", targetDepth)) {
                    context.nextToken();
                    jiraConfiguration.setExclusionPatterns(new ListUnmarshaller<String>(context.getUnmarshaller(String.class))

                    .unmarshall(context));
                }
                if (context.testExpression("VpcConfiguration", targetDepth)) {
                    context.nextToken();
                    jiraConfiguration.setVpcConfiguration(DataSourceVpcConfigurationJsonUnmarshaller.getInstance().unmarshall(context));
                }
            } else if (token == END_ARRAY || token == END_OBJECT) {
                if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
                    if (context.getCurrentDepth() <= originalDepth)
                        break;
                }
            }
            token = context.nextToken();
        }

        return jiraConfiguration;
    }

    private static JiraConfigurationJsonUnmarshaller instance;

    public static JiraConfigurationJsonUnmarshaller getInstance() {
        if (instance == null)
            instance = new JiraConfigurationJsonUnmarshaller();
        return instance;
    }
}


text:
'''
Created on 2 Aug 2016

@author: sennikta
'''

# Input:
#    data              is the raw time series.
#    N                 is the length of sliding window (use the length of the raw time series
#                      instead if you don't want to have sliding windows)
#    n                 is the number of symbols in the low dimensional approximation of the sub sequence. (Size of the word to produce)
#    alphabet_size     is the number of discrete symbols. 2 <= alphabet_size <= 20, although
#                      alphabet_size = 2 is a special "useless" case.
#
# Output:
#    symbolic_data:    matrix of symbolic data (no-repetition).  If consecutive subsequences
#                      have the same string, then only the first occurrence is recorded, with
#                      a pointer to its location stored in "pointers"
#    pointers:         location of the first occurrences of the strings
#
#  The variable "win_size" is assigned to N/n, this is the number of data points on the raw
#  time series that will be mapped to a single symbol, and can be imagined as the
#  "compression rate".
#
# The symbolic data is returned in "symbolic_data", with pointers to the subsequences

import json
import os
from os import listdir
import numpy
import csv
from itertools import islice
import pandas as pd
import datetime
import time

#--------------------------------------------------------------------------------------------------------------------------------------------------------
#---------------- Define directories ---------------------- Define directories ---------------- Define directories --------------------------------------
#--------------------------------------------------------------------------------------------------------------------------------------------------------

base_dir = os.path.dirname(os.path.dirname(__file__))
data_dir = os.path.join(base_dir, 'data')
neighbors_dir = os.path.join(data_dir, 'neighbors')
seed_dir = os.path.join(data_dir, 'seed')
baseline_dir = os.path.join(data_dir, 'baseline')

# seed or baseline
scientists_file =  os.path.join(seed_dir, 'seed_creation_date.json')

# for topics change seed/baseline
topic_file =  os.path.join(neighbors_dir, 'baseline_neighbors_list_clean_en.json')

# views, edits or google trends
views_dir = os.path.join(data_dir, 'views')
edits_dir = os.path.join(data_dir, 'edits_normed_by_main_page')
edits_seed_dir = os.path.join(edits_dir, 'seed')
edits_baseline_dir = os.path.join(edits_dir, 'baseline')

scientist_dir = os.path.join(edits_baseline_dir, 'scientists_full')

google_trends_dir = os.path.join(data_dir, 'google_trends_normed_by_baseline')
test_dir = os.path.join(data_dir, 'test')

# scientists or topics
vews_seed_dir = os.path.join(views_dir, 'seed')
views_sci = os.path.join(vews_seed_dir, '3_years_before_nobel_cl')
edits_sci = os.path.join(edits_dir, 'scientists')
gooogle_trends_sci = os.path.join(google_trends_dir, 'scientists_before_the_award')

views_topic = os.path.join(views_dir, 'topics')
edits_topic = os.path.join(edits_dir, 'topics')
gooogle_trends_topic = os.path.join(google_trends_dir, 'topics')

# for output
sax_dir = os.path.join(data_dir, 'sax_representation')
views_sax = os.path.join(sax_dir, 'views')
edits_sax = os.path.join(sax_dir, 'edits')
google_trends_sax = os.path.join(sax_dir, 'google_trends')
test_sax = os.path.join(sax_dir, 'test')

# scientists or topics
views_sax_sci = os.path.join(views_sax, '3_years_before_nobel_cl')
edits_sax_sci = os.path.join(edits_sax, 'scientists')
gooogle_trends_sax_sci = os.path.join(google_trends_sax, 'scientists_cut')

views_sax_topic = os.path.join(views_sax, 'topics')
edits_sax_topic = os.path.join(edits_sax, 'topics')
gooogle_trends_sax_topic = os.path.join(google_trends_sax, 'topics')

# cutted ts
views_scientist_cut_dir = os.path.join(views_dir, 'scientists_cut')
views_sax_sci_cut = os.path.join(views_sax, 'scientists_cut')

def load_simple_json(filename):
    print filename
    with open(filename, 'r') as f:
        return json.load(f)

def output_txt(symbolic_data, file_name):
    output_path =  os.path.join(views_sax_sci, file_name)
    text_file = open(output_path, "w")
    for string in symbolic_data:
        text_file.write(",".join(map(lambda x: str(x), string)))
        text_file.write("\n")
    text_file.close()
    symbolic_data = []
    return

def map_to_string(PAA, alphabet_size):
    string = numpy.zeros(shape=(1,len(PAA)))
    switcher = {
                2:[-numpy.inf, 0],
                3:[-numpy.inf, -0.43, 0.43],
                4:[-numpy.inf, -0.67, 0, 0.67],
                5:[-numpy.inf, -0.84, -0.25, 0.25, 0.84],
                6:[-numpy.inf, -0.97, -0.43, 0, 0.43, 0.97],
                7:[-numpy.inf, -1.07, -0.57, -0.18, 0.18, 0.57, 1.07],
                8:[-numpy.inf, -1.15, -0.67, -0.32, 0, 0.32, 0.67, 1.15],
                9:[-numpy.inf, -1.22, -0.76, -0.43, -0.14, 0.14, 0.43, 0.76, 1.22],
                10:[-numpy.inf, -1.28, -0.84, -0.52, -0.25, 0, 0.25, 0.52, 0.84, 1.28]
                }
    for i in range(0, len(PAA)):
        cut_points = []
        for s in switcher.get(alphabet_size):
            if s<=PAA[i]:
                cut_points.append(1)
            else:
                cut_points.append(0)
        string[0][i] = sum(cut_points)
    #print 'SAX: ', string
    return string

def series_to_sax(data, N, n, alphabet_size):
    if alphabet_size > 10:
        print 'Currently alphabet_size cannot be larger than 10.  Please update the breakpoint table if you wish to do so'
        return
    #Z normalize entire data
    data = (data - numpy.mean(data))/numpy.std(data)
    #win_size is the number of data points on the raw time series that will be mapped to a single symbol
    win_size = int(N/n)
    #symbolic_data = numpy.zeros(shape=(1,n))
    symbolic_data = [0]
    PAA = []
    PAA = numpy.array(PAA)
    # Scan across the time series extract sub sequences, and converting them to strings.
    for i in range (0, (len(data) - N+1)):

        #Remove the current subsection
        sub_section = data[i:i+N]
        zero_array = [0]*len(sub_section)
        #Z normalize subsequence
        #if sub_section!= zero_array:
        #    sub_section = (sub_section - numpy.mean(sub_section))/numpy.std(sub_section)
        #else:
        #    sub_section =[-numpy.inf]*len(sub_section)
        # take care of the special case where there is no dimensionality reduction
        if N == n:
            PAA = sub_section

        # convert to PAA
        else:
            #N is not dividable by n
            if float(N)/n!=round(N/n):
                temp = numpy.zeros(shape=(n,N))
                for j in range(0,n):
                    temp[j,:] = sub_section
                expanded_sub_section = numpy.reshape(temp,(1, N*n), order='F')
                PAA = numpy.mean(numpy.reshape(expanded_sub_section, (N, n),order='F'), 0)
            # N is dividable by n
            else:
                PAA =numpy.mean(numpy.reshape(sub_section, (win_size,n), order='F'), 0)
        #print 'PAA: ', PAA
        current_string = list(map_to_string(PAA,alphabet_size)[0])
        current_string = map(int, current_string)
        if current_string!=symbolic_data[-1]:
            symbolic_data.append(current_string)
    symbolic_data.pop(0)
    return symbolic_data

def get_series_from_txt(scientist, dir):
    scientist_series = []
    scientist = scientist.rstrip().split('/')[-1]
    filename = os.path.join(dir + '\\' + scientist + '.txt')
    try:
        f = open(filename)
        for line in f:
            time_list = map(float, line.split(','))
            #comment for cutted ts
            #year = int(time_list.pop(0))
            #if  year>2001 and year<2016:
            #    scientist_series += time_list
            scientist_series += time_list
        f.close()
    except IOError:
        return []
#    print scientist_series
    return scientist_series

def get_series_from_csv(scientist, dir):
    scientist_series = []
    csvname = os.path.join(dir + '\\' + scientist + '.csv')
    try:
        f = open(csvname)
        reader = csv.reader(f)
        # skip template
        for row in islice(reader, 1, 653):
        #for row in islice(reader, 6, 30):

            year = int(row[2].rstrip().split('-')[0])
            if year>2004 and year<2016:
                scientist_series.append(float(row[1]))
        f.close()
    except IOError:
        return scientist_series
    return scientist_series

def scientists_collection(dir):
    files_list = listdir(dir)
    for scientist in files_list:
        print scientist
        scientist = scientist.replace('.txt','')
        # for Google Trends
        #scientist_series = get_series_from_csv(scientist, dir)
        # For views and edits
        scientist_series = get_series_from_txt(scientist, dir)
        symbolic_data = series_to_sax(scientist_series, 360, 9, 4)
        file_name = scientist.rstrip().split('/')[-1]+'.txt'
        output_txt(symbolic_data, file_name)
    #    series_to_sax([1,2,3,4,5,6,7,8], 8, 4, 3)
    return

def topics_collection(dir):
    files_list = listdir(dir)
    for topic in files_list:
#         topic=topic.replace(' ', '_')
#         topic = topic[0].upper() + topic[1:]
        topic = topic.replace('.txt','')
        print topic
        # For Google Trends
        #topic_series = get_series_from_csv(topic, dir)
        # For views and edits
        topic_series = get_series_from_txt(topic, dir)
        symbolic_data = series_to_sax(topic_series, 90, 9, 4)
        file_name = topic+'.txt'
        output_txt(symbolic_data, file_name)
    #    series_to_sax([1,2,3,4,5,6,7,8], 8, 4, 3)
    return

scientists_collection(views_sci)


text:
import json

from django.conf import settings
from django.core.exceptions import PermissionDenied
from django.http import HttpResponse
from django.shortcuts import get_object_or_404, redirect
from django.urls import reverse
from django.utils import timezone
from django.utils.html import format_html
from django.utils.http import urlquote
from django.utils.safestring import mark_safe
from django.utils.translation import gettext as _
from django.views.generic.base import ContextMixin, TemplateResponseMixin, View

from wagtail.admin import messages
from wagtail.admin.action_menu import PageActionMenu
from wagtail.admin.views.generic import HookResponseMixin
from wagtail.admin.views.pages.utils import get_valid_next_url_from_request
from wagtail.core.exceptions import PageClassNotFoundError
from wagtail.core.models import Page, UserPagePermissionsProxy, WorkflowState

class EditView(TemplateResponseMixin, ContextMixin, HookResponseMixin, View):
    def get_template_names(self):
        if self.page.alias_of_id:
            return ['wagtailadmin/pages/edit_alias.html']

        else:
            return ['wagtailadmin/pages/edit.html']

    def add_legacy_moderation_warning(self):
        # Check for revisions still undergoing moderation and warn - this is for the old moderation system
        if self.latest_revision and self.latest_revision.submitted_for_moderation:
            buttons = []

            if self.page.live:
                buttons.append(self.get_compare_with_live_message_button())

            messages.warning(self.request, _("This page is currently awaiting moderation"), buttons=buttons)

    def add_save_confirmation_message(self):
        if self.is_reverting:
            message = _(
                "Page '{0}' has been replaced with version from {1}."
            ).format(
                self.page.get_admin_display_title(),
                self.previous_revision.created_at.strftime("%d %b %Y %H:%M")
            )
        else:
            message = _(
                "Page '{0}' has been updated."
            ).format(
                self.page.get_admin_display_title()
            )

        messages.success(self.request, message)

    def get_edit_message_button(self):
        return messages.button(
            reverse('wagtailadmin_pages:edit', args=(self.page.id,)),
            _('Edit')
        )

    def get_view_draft_message_button(self):
        return messages.button(
            reverse('wagtailadmin_pages:view_draft', args=(self.page.id,)),
            _('View draft'),
            new_window=True
        )

    def get_view_live_message_button(self):
        return messages.button(self.page.url, _('View live'), new_window=True)

    def get_compare_with_live_message_button(self):
        return messages.button(
            reverse('wagtailadmin_pages:revisions_compare', args=(self.page.id, 'live', self.latest_revision.id)),
            _('Compare with live version')
        )

    def get_page_for_status(self):
        if self.page.live and self.page.has_unpublished_changes:
            # Page status needs to present the version of the page containing the correct live URL
            return self.real_page_record.specific
        else:
            return self.page

    def dispatch(self, request, page_id):
        self.real_page_record = get_object_or_404(Page, id=page_id)
        self.latest_revision = self.real_page_record.get_latest_revision()
        self.page_content_type = self.real_page_record.cached_content_type
        self.page_class = self.real_page_record.specific_class

        if self.page_class is None:
            raise PageClassNotFoundError(
                f"The page '{self.real_page_record}' cannot be edited because the "
                f"model class used to create it ({self.page_content_type.app_label}."
                f"{self.page_content_type.model}) can no longer be found in the codebase. "
                "This usually happens as a result of switching between git "
                "branches without running migrations to trigger the removal of "
                "unused ContentTypes. To edit the page, you will need to switch "
                "back to a branch where the model class is still present."
            )

        self.page = self.real_page_record.get_latest_revision_as_page()
        self.parent = self.page.get_parent()

        self.page_perms = self.page.permissions_for_user(self.request.user)

        if not self.page_perms.can_edit():
            raise PermissionDenied

        self.next_url = get_valid_next_url_from_request(self.request)

        response = self.run_hook('before_edit_page', self.request, self.page)
        if response:
            return response

        self.edit_handler = self.page_class.get_edit_handler()
        self.edit_handler = self.edit_handler.bind_to(instance=self.page, request=self.request)
        self.form_class = self.edit_handler.get_form_class()

        # Retrieve current workflow state if set, default to last workflow state
        self.workflow_state = self.page.current_workflow_state or self.page.workflow_states.order_by('created_at').last()
        if self.workflow_state:
            self.workflow_tasks = self.workflow_state.all_tasks_with_status()
        else:
            self.workflow_tasks = []

        self.errors_debug = None

        return super().dispatch(request)

    def get(self, request):
        if self.page_perms.user_has_lock():
            if self.page.locked_at:
                lock_message = format_html(_("Page '{}' was locked by you on {}."), self.page.get_admin_display_title(), self.page.locked_at.strftime("%d %b %Y %H:%M"))
            else:
                lock_message = format_html(_("Page '{}' is locked by you."), self.page.get_admin_display_title())

            lock_message += format_html(
                '<button class="button button-small button-secondary" data-locking-action="{}">{}</button>',
                reverse('wagtailadmin_pages:unlock', args=(self.page.id,)),
                _("Unlock")
            )
            messages.warning(self.request, lock_message, extra_tags='lock')

        elif self.page.locked and self.page_perms.page_locked():
            # the page can also be locked at a permissions level if in a workflow, on a task the user is not a reviewer for
            # this should be indicated separately
            if self.page.locked_by and self.page.locked_at:
                lock_message = format_html(_("Page '{}' was locked by {} on {}."), self.page.get_admin_display_title(), str(self.page.locked_by), self.page.locked_at.strftime("%d %b %Y %H:%M"))
            else:
                # Page was probably locked with an old version of Wagtail, or a script
                lock_message = format_html(_("Page '{}' is locked."), self.page.get_admin_display_title())

            if self.page_perms.can_unlock():
                lock_message += format_html(
                    '<button class="button button-small button-secondary" data-locking-action="{}">{}</button>',
                    reverse('wagtailadmin_pages:unlock', args=(self.page.id,)),
                    _("Unlock")
                )
            messages.error(self.request, lock_message, extra_tags='lock')

        if self.page.current_workflow_state:
            workflow = self.workflow_state.workflow
            task = self.workflow_state.current_task_state.task
            if (
                self.workflow_state.status != WorkflowState.STATUS_NEEDS_CHANGES
                and task.specific.page_locked_for_user(self.page, self.request.user)
            ):
                # Check for revisions still undergoing moderation and warn
                if len(self.workflow_tasks) == 1:
                    # If only one task in workflow, show simple message
                    workflow_info = _("This page is currently awaiting moderation.")
                else:
                    workflow_info = format_html(
                        _("This page is awaiting '{}' in the '{}' workflow."),
                        task.name, workflow.name
                    )
                messages.error(
                    self.request, mark_safe(workflow_info + " " + _("Only reviewers for this task can edit the page.")),
                    extra_tags="lock"
                )

        self.form = self.form_class(instance=self.page, parent_page=self.parent)
        self.has_unsaved_changes = False
        self.edit_handler = self.edit_handler.bind_to(form=self.form)
        self.add_legacy_moderation_warning()
        self.page_for_status = self.get_page_for_status()

        return self.render_to_response(self.get_context_data())

    def add_cancel_workflow_confirmation_message(self):
        message = _(
            "Workflow on page '{0}' has been cancelled."
        ).format(
            self.page.get_admin_display_title()
        )

        messages.success(self.request, message, buttons=[
            self.get_view_draft_message_button(),
            self.get_edit_message_button(),
        ])

    def post(self, request):
        # Don't allow POST requests if the page is an alias
        if self.page.alias_of_id:
            # Return 405 "Method Not Allowed" response
            return HttpResponse(status=405)

        self.form = self.form_class(
            self.request.POST, self.request.FILES, instance=self.page, parent_page=self.parent
        )

        self.is_cancelling_workflow = bool(self.request.POST.get('action-cancel-workflow')) and self.workflow_state and self.workflow_state.user_can_cancel(self.request.user)

        if self.form.is_valid() and not self.page_perms.page_locked():
            return self.form_valid(self.form)
        else:
            return self.form_invalid(self.form)

    def workflow_action_is_valid(self):
        self.workflow_action = self.request.POST['workflow-action-name']
        available_actions = self.page.current_workflow_task.get_actions(self.page, self.request.user)
        available_action_names = [name for name, verbose_name, modal in available_actions]
        return (self.workflow_action in available_action_names)

    def form_valid(self, form):
        self.is_reverting = bool(self.request.POST.get('revision'))
        # If a revision ID was passed in the form, get that revision so its
        # date can be referenced in notification messages
        if self.is_reverting:
            self.previous_revision = get_object_or_404(self.page.revisions, id=self.request.POST.get('revision'))

        self.has_content_changes = self.form.has_changed()

        if self.request.POST.get('action-publish') and self.page_perms.can_publish():
            return self.publish_action()
        elif self.request.POST.get('action-submit') and self.page_perms.can_submit_for_moderation():
            return self.submit_action()
        elif self.request.POST.get('action-restart-workflow') and self.page_perms.can_submit_for_moderation() and self.workflow_state and self.workflow_state.user_can_cancel(self.request.user):
            return self.restart_workflow_action()
        elif self.request.POST.get('action-workflow-action') and self.workflow_action_is_valid():
            return self.perform_workflow_action()
        elif self.is_cancelling_workflow:
            return self.cancel_workflow_action()
        else:
            return self.save_action()

    def save_action(self):
        self.page = self.form.save(commit=False)

        # Save revision
        self.page.save_revision(
            user=self.request.user,
            log_action=True,  # Always log the new revision on edit
            previous_revision=(self.previous_revision if self.is_reverting else None)
        )

        self.add_save_confirmation_message()

        response = self.run_hook('after_edit_page', self.request, self.page)
        if response:
            return response

        # Just saving - remain on edit page for further edits
        return self.redirect_and_remain()

    def publish_action(self):
        self.page = self.form.save(commit=False)

        # Save revision
        revision = self.page.save_revision(
            user=self.request.user,
            log_action=True,  # Always log the new revision on edit
            previous_revision=(self.previous_revision if self.is_reverting else None)
        )

        # store submitted go_live_at for messaging below
        go_live_at = self.page.go_live_at

        response = self.run_hook('before_publish_page', self.request, self.page)
        if response:
            return response

        revision.publish(
            user=self.request.user,
            changed=self.has_content_changes,
            previous_revision=(self.previous_revision if self.is_reverting else None)
        )

        # Need to reload the page because the URL may have changed, and we
        # need the up-to-date URL for the "View Live" button.
        self.page = self.page.specific_class.objects.get(pk=self.page.pk)

        response = self.run_hook('after_publish_page', self.request, self.page)
        if response:
            return response

        # Notifications
        if go_live_at and go_live_at > timezone.now():
            # Page has been scheduled for publishing in the future

            if self.is_reverting:
                message = _(
                    "Version from {0} of page '{1}' has been scheduled for publishing."
                ).format(
                    self.previous_revision.created_at.strftime("%d %b %Y %H:%M"),
                    self.page.get_admin_display_title()
                )
            else:
                if self.page.live:
                    message = _(
                        "Page '{0}' is live and this version has been scheduled for publishing."
                    ).format(
                        self.page.get_admin_display_title()
                    )

                else:
                    message = _(
                        "Page '{0}' has been scheduled for publishing."
                    ).format(
                        self.page.get_admin_display_title()
                    )

            messages.success(self.request, message, buttons=[self.get_edit_message_button()])

        else:
            # Page is being published now

            if self.is_reverting:
                message = _(
                    "Version from {0} of page '{1}' has been published."
                ).format(
                    self.previous_revision.created_at.strftime("%d %b %Y %H:%M"),
                    self.page.get_admin_display_title()
                )
            else:
                message = _(
                    "Page '{0}' has been published."
                ).format(
                    self.page.get_admin_display_title()
                )

            buttons = []
            if self.page.url is not None:
                buttons.append(self.get_view_live_message_button())
            buttons.append(self.get_edit_message_button())
            messages.success(self.request, message, buttons=buttons)

        response = self.run_hook('after_edit_page', self.request, self.page)
        if response:
            return response

        # we're done here - redirect back to the explorer
        return self.redirect_away()

    def submit_action(self):
        self.page = self.form.save(commit=False)

        # Save revision
        self.page.save_revision(
            user=self.request.user,
            log_action=True,  # Always log the new revision on edit
            previous_revision=(self.previous_revision if self.is_reverting else None)
        )

        if self.workflow_state and self.workflow_state.status == WorkflowState.STATUS_NEEDS_CHANGES:
            # If the workflow was in the needs changes state, resume the existing workflow on submission
            self.workflow_state.resume(self.request.user)
        else:
            # Otherwise start a new workflow
            workflow = self.page.get_workflow()
            workflow.start(self.page, self.request.user)

        message = _(
            "Page '{0}' has been submitted for moderation."
        ).format(
            self.page.get_admin_display_title()
        )

        messages.success(self.request, message, buttons=[
            self.get_view_draft_message_button(),
            self.get_edit_message_button(),
        ])

        response = self.run_hook('after_edit_page', self.request, self.page)
        if response:
            return response

        # we're done here - redirect back to the explorer
        return self.redirect_away()

    def restart_workflow_action(self):
        self.page = self.form.save(commit=False)

        self.workflow_state.cancel(user=self.request.user)

        if self.workflow_state and self.workflow_state.status == WorkflowState.STATUS_NEEDS_CHANGES:
            # If the workflow was in the needs changes state, resume the existing workflow on submission
            self.workflow_state.resume(self.request.user)
        else:
            # Otherwise start a new workflow
            workflow = self.page.get_workflow()
            workflow.start(self.page, self.request.user)

        message = _(
            "Workflow on page '{0}' has been restarted."
        ).format(
            self.page.get_admin_display_title()
        )

        messages.success(self.request, message, buttons=[
            self.get_view_draft_message_button(),
            self.get_edit_message_button(),
        ])

        response = self.run_hook('after_edit_page', self.request, self.page)
        if response:
            return response

        # we're done here - redirect back to the explorer
        return self.redirect_away()

    def perform_workflow_action(self):
        self.page = self.form.save(commit=False)

        if self.has_content_changes:
            # Save revision
            self.page.save_revision(
                user=self.request.user,
                log_action=True,  # Always log the new revision on edit
                previous_revision=(self.previous_revision if self.is_reverting else None)
            )

        extra_workflow_data_json = self.request.POST.get('workflow-action-extra-data', '{}')
        extra_workflow_data = json.loads(extra_workflow_data_json)
        self.page.current_workflow_task.on_action(self.page.current_workflow_task_state, self.request.user, self.workflow_action, **extra_workflow_data)

        self.add_save_confirmation_message()

        response = self.run_hook('after_edit_page', self.request, self.page)
        if response:
            return response

        # we're done here - redirect back to the explorer
        return self.redirect_away()

    def cancel_workflow_action(self):
        self.workflow_state.cancel(user=self.request.user)
        self.page = self.form.save(commit=False)

        # Save revision
        self.page.save_revision(
            user=self.request.user,
            log_action=True,  # Always log the new revision on edit
            previous_revision=(self.previous_revision if self.is_reverting else None)
        )

        # Notifications
        self.add_cancel_workflow_confirmation_message()

        response = self.run_hook('after_edit_page', self.request, self.page)
        if response:
            return response

        # Just saving - remain on edit page for further edits
        return self.redirect_and_remain()

    def redirect_away(self):
        if self.next_url:
            # redirect back to 'next' url if present
            return redirect(self.next_url)
        else:
            # redirect back to the explorer
            return redirect('wagtailadmin_explore', self.page.get_parent().id)

    def redirect_and_remain(self):
        target_url = reverse('wagtailadmin_pages:edit', args=[self.page.id])
        if self.next_url:
            # Ensure the 'next' url is passed through again if present
            target_url += '?next=%s' % urlquote(self.next_url)
        return redirect(target_url)

    def form_invalid(self, form):
        # even if the page is locked due to not having permissions, the original submitter can still cancel the workflow
        if self.is_cancelling_workflow:
            self.workflow_state.cancel(user=self.request.user)
            self.add_cancel_workflow_confirmation_message()

        if self.page_perms.page_locked():
            messages.error(self.request, _("The page could not be saved as it is locked"))
        else:
            messages.validation_error(
                self.request, _("The page could not be saved due to validation errors"), self.form
            )
        self.errors_debug = (
            repr(self.form.errors)
            + repr([
                (name, formset.errors)
                for (name, formset) in self.form.formsets.items()
                if formset.errors
            ])
        )
        self.has_unsaved_changes = True

        self.edit_handler = self.edit_handler.bind_to(form=self.form)
        self.add_legacy_moderation_warning()
        self.page_for_status = self.get_page_for_status()

        return self.render_to_response(self.get_context_data())

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context.update({
            'page': self.page,
            'page_for_status': self.page_for_status,
            'content_type': self.page_content_type,
            'edit_handler': self.edit_handler,
            'errors_debug': self.errors_debug,
            'action_menu': PageActionMenu(self.request, view='edit', page=self.page),
            'preview_modes': self.page.preview_modes,
            'form': self.form,
            'next': self.next_url,
            'has_unsaved_changes': self.has_unsaved_changes,
            'page_locked': self.page_perms.page_locked(),
            'workflow_state': self.workflow_state if self.workflow_state and self.workflow_state.is_active else None,
            'current_task_state': self.page.current_workflow_task_state,
            'publishing_will_cancel_workflow': self.workflow_tasks and getattr(settings, 'WAGTAIL_WORKFLOW_CANCEL_ON_PUBLISH', True),
            'locale': None,
            'translations': [],
        })

        if getattr(settings, 'WAGTAIL_I18N_ENABLED', False):
            user_perms = UserPagePermissionsProxy(self.request.user)

            context.update({
                'locale': self.page.locale,
                'translations': [
                    {
                        'locale': translation.locale,
                        'url': reverse('wagtailadmin_pages:edit', args=[translation.id]),
                    }
                    for translation in self.page.get_translations().only('id', 'locale', 'depth').select_related('locale')
                    if user_perms.for_page(translation).can_edit()
                ],
            })

        return context


text:
modules.define(
    'test',
    ['utils__compare'],
    function (provide, compare) {

    describe('utils__compare', function () {
        it('should compare integer numbers', function () {
            compare(123, 123).should.be.true;
            compare(123, 12).should.be.false;
        });

        it('should compare float numbers', function () {
            compare(0.000005, 0.000005).should.be.true;
            compare(123.3, 0.75).should.be.false;
        });

        it('should returns true for the same object', function () {
            var a;
            var b;
            a = b = {test: 1};
            compare(a, b).should.be.true;
        });
    });

    provide();
});


text:
package org.apache.camel.component.sjms2;

import org.apache.camel.AsyncEndpoint;
import org.apache.camel.Category;
import org.apache.camel.Component;
import org.apache.camel.component.sjms.SjmsEndpoint;
import org.apache.camel.component.sjms2.jms.Jms2ObjectFactory;
import org.apache.camel.spi.UriEndpoint;
import org.apache.camel.spi.UriParam;

/**
 * Send and receive messages to/from a JMS Queue or Topic using plain JMS 2.x API.
 *
 * This component uses plain JMS 2.x API where as the jms component uses Spring JMS.
 */
@UriEndpoint(firstVersion = "2.19.0", scheme = "sjms2", extendsScheme = "sjms", title = "Simple JMS2",
             syntax = "sjms2:destinationType:destinationName", category = { Category.MESSAGING })
public class Sjms2Endpoint extends SjmsEndpoint implements AsyncEndpoint {

    @UriParam(label = "consumer", description = "Sets the topic subscription id, required for durable or shared topics.")
    private String subscriptionId;
    @UriParam(label = "consumer", description = "Sets the topic to be durable")
    private boolean durable;
    @UriParam(label = "consumer", description = "Sets the topic to be shared")
    private boolean shared;

    public Sjms2Endpoint() {
    }

    public Sjms2Endpoint(String uri, Component component, String remaining) {
        super(uri, component, remaining);
        setJmsObjectFactory(new Jms2ObjectFactory());
    }

    @Override
    public Sjms2Component getComponent() {
        return (Sjms2Component) super.getComponent();
    }

    @Override
    public void setDurableSubscriptionName(String durableSubscriptionId) {
        super.setDurableSubscriptionName(durableSubscriptionId);
        subscriptionId = durableSubscriptionId;
        durable = true;
    }

    public String getSubscriptionId() {
        return subscriptionId;
    }

    public void setSubscriptionId(String subscriptionId) {
        this.subscriptionId = subscriptionId;
    }

    public boolean isDurable() {
        return durable;
    }

    public void setDurable(boolean durable) {
        this.durable = durable;
    }

    public boolean isShared() {
        return shared;
    }

    public void setShared(boolean shared) {
        this.shared = shared;
    }

}


text:
CREATE OR REPLACE FUNCTION ti.getecolgroupstable()
 RETURNS TABLE(taxonid integer, ecolsetid integer, ecolgroupid character varying)
 LANGUAGE sql
AS $function$
SELECT taxonid, ecolsetid, ecolgroupid
FROM ndb.ecolgroups
$function$


text:
__author__ = 'Brad Robel-Forrest'
__email__ = 'brad@bitpony.com'
__version__ = '0.1.0'

from .garbagetruck import GarbageTruck


text:
package org.projectodd.wunderboss.rack;

import org.jruby.RubyHash;

import java.io.IOException;
import java.io.InputStream;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;

public interface RackAdapter {

    public String getPathInfo();

    public String getScriptName();

    public String getRequestMethod();

    public String getQueryString();

    public String getScheme();

    public String getHostName();

    public int getPort();

    public String getRemoteAddr();

    public String getContentType();

    public int getContentLength();

    public InputStream getInputStream();

    public ReadableByteChannel getInputChannel();

    public WritableByteChannel getOutputChannel();

    public void populateRackHeaders(RubyHash rackEnv);

    public void populateRackHeaderFromBytes(RubyHash rackEnv, byte[] httpBytes, int from ,int to, byte[] rubyBytes);

    public void setResponseCode(int responseCode);

    public void addResponseHeader(byte[] keyBytes, int keyOffset, int keyLength, String value);

    public void write(byte[] bytes, int offset, int length) throws IOException;

    public void flush() throws IOException;

    public void async();
}


text:
from msrest.serialization import Model

class ApplicationArtifact(Model):
    """Managed application artifact.

    :param name: The managed application artifact name.
    :type name: str
    :param uri: The managed application artifact blob uri.
    :type uri: str
    :param type: The managed application artifact type. Possible values
     include: 'Template', 'Custom'
    :type type: str or
     ~azure.mgmt.resource.managedapplications.models.ApplicationArtifactType
    """

    _attribute_map = {
        'name': {'key': 'name', 'type': 'str'},
        'uri': {'key': 'uri', 'type': 'str'},
        'type': {'key': 'type', 'type': 'ApplicationArtifactType'},
    }

    def __init__(self, name=None, uri=None, type=None):
        super(ApplicationArtifact, self).__init__()
        self.name = name
        self.uri = uri
        self.type = type


text:
package cc.factorie.util

/**
 * @author John Sullivan
 */
object VectorUtils{
  implicit def doubleArrayToRichTensor(x:Array[Double]):ArrayVector = new ArrayVector(x)
  def randomArray(k:Int,random:scala.util.Random):Array[Double] = {
    val result = new Array[Double](k)
    var i = 0;while(i<result.length){result(i) = random.nextGaussian;i+=1}
    result
  }
  def zero(k:Int) = new Array[Double](k)
  def rep(v:Double,k:Int) = {val r=new Array[Double](k);var i=0;while(i<r.length){r(i)=v;i+=1};r}
}

class ArrayVector(val x:Array[Double]) extends AnyVal {
  import VectorUtils._//doubleArrayToRichTensor
  def copy():Array[Double] = {val r=new Array[Double](x.length);var i=0;while(i<x.length){r(i)=(i);i+=1};r}
  //basic arithmetic operations
  def + (y:Array[Double]):Array[Double] = {assert(x.length==y.length);val r=new Array[Double](x.length);var i=0;while(i<x.length){r(i)=x(i)+y(i);i+=1};r}
  def + (y:Double):Array[Double] = {val r=rep(y,x.length);var i=0;while(i<x.length){r(i)=r(i)+x(i);i+=1};r}
  def - (y:Double):Array[Double] = {val r=rep(y,x.length);var i=0;while(i<x.length){r(i)=r(i)-x(i);i+=1};r}
  def - (y:Array[Double]):Array[Double] = {assert(x.length==y.length);val r=new Array[Double](x.length);var i=0;while(i<x.length){r(i)=x(i)-y(i);i+=1};r}
  def * (y:Array[Double]):Array[Double] = {assert(x.length==y.length);val r=new Array[Double](x.length);var i=0;while(i<x.length){r(i)=x(i)*y(i);i+=1};r}
  def / (y:Array[Double]):Array[Double] = {assert(x.length==y.length);val r=new Array[Double](x.length);var i=0;while(i<x.length){r(i)=x(i)/y(i);i+=1};r}
  def * (y:Double):Array[Double] = {val r=new Array[Double](x.length);var i=0;while(i<x.length){r(i)=x(i)*y;i+=1};r}
  def / (y:Double):Array[Double] = {val r=new Array[Double](x.length);var i=0;while(i<x.length){r(i)=x(i)/y;i+=1};r}
  //modifiers
  def *= (y:Double){var i=0;while(i<x.length){x(i) *= y;i+=1}}
  def /= (y:Double){var i=0;while(i<x.length){x(i) /= y;i+=1}}
  def *= (y:Array[Double]){assert(x.length==y.length);var i=0;while(i<x.length){x(i) *= y(i);i+=1}}
  def /= (y:Array[Double]){assert(x.length==y.length);var i=0;while(i<x.length){x(i) /= y(i);i+=1}}
  def += (y:Array[Double],scalar:Double){assert(x.length==y.length);var i=0;while(i<x.length){x(i) += y(i)*scalar;i+=1}}
  def += (y:Array[Double]){assert(x.length==y.length);var i=0;while(i<x.length){x(i) += y(i);i+=1}}
  def -= (y:Array[Double]){this += (y,-1.0)}
  def -= (y:Array[Double],scalar:Double){this += (y,-scalar)}
  //norms
  def oneNorm():Double = {var r=0.0;var i=0;while(i<x.length){r+=scala.math.abs(x(i));i+=1};r}
  def twoNorm():Double = {var r=0.0;var i=0;while(i<x.length){r+=x(i)*x(i);i+=1};math.sqrt(r)}
  //distances/similarities
  def dot(y:Array[Double]):Double = {assert(x.length==y.length);var r=0.0;var i=0;while(i<x.length){r+=x(i)*y(i);i+=1};r}
  def cosineSimilarity(that:Array[Double]):Double = {val thisDotThat=this dot that;if(thisDotThat==0.0)0.0 else thisDotThat/(this.twoNorm*that.twoNorm())}
  def cosineSimilarityWithParent(parent:Array[Double]):Double = {
    var thisTwoNormSquared = twoNorm();thisTwoNormSquared*=thisTwoNormSquared
    var thatTwoNormSquared = parent.twoNorm();thatTwoNormSquared*=thatTwoNormSquared
    val thisDotThat = this dot parent
    if(math.abs(thisDotThat-thisTwoNormSquared)<=0.000001) 0.0 else (thisDotThat - thisTwoNormSquared)/(math.sqrt(thisTwoNormSquared)*math.sqrt(thatTwoNormSquared+thisTwoNormSquared-2.0*thisDotThat))
  }
  def hasNaN = {var r=false;var i=0;while(i<x.length && !r){if(x != x)r=true;i+=1};r}//(x.exists(e=> !(e == e)))
  def twoDistance(that:Array[Double]):Double = (this - that).twoNorm()
  def totalVariation(that:Array[Double]):Double = 0.5*(this - that).oneNorm()
  //noise
  def makeCorruptObservation(noiseSource:Array[Double]=>Unit):Array[Double] = {val r=copy();noiseSource(r);r}
  def corrupt(sigma:Double,random:scala.util.Random){var i=0;while(i<x.length){x(i)+=random.nextGaussian()*sigma;i+=1}}
  def corrupt(sigma:Array[Double],random:scala.util.Random){var i=0;while(i<x.length){x(i)+=random.nextGaussian()*sigma(i);i+=1}}
  //other
  //def pAsGauss(sigma:Double) =
  def compression(setSize:Int) = entropyForLogValues * setSize.toDouble
  def mean:Double ={var result=0.0;var i=0;while(i<x.length){result+=x(i);i+=1};result}
  //def stddev:Double = (x - mean).twoDistance
  //def variance:Double = {val s=stddev;s*s}
  def variance = {var r=0.0;val m = mean;var i=0;while(i<0){r+=(x(i)-m)*(x(i)-m);i+=1};r}
  def stddev = math.sqrt(variance)
  def entropyForLogValues:Double ={
    var h = 0.0
    val z = cc.factorie.maths.sumLogProbs(x)
    var i=0
    while(i<x.length){
      val logp = x(i)-z
      h += math.exp(logp)*logp
      i+=1
    }
    h
  }
  def normalizedEntropyForLogValues:Double = -entropyForLogValues/math.log(x.length)
  //def entropy:Double = {var result = 0.0;val z = oneNorm;var i=0;while(i<x.length){result += x(i)*math.log(x(i)/z);i+=1;result/z}}
}


text:
using System;
using System.Collections.Generic;
using Infusion.IO;

namespace Infusion.Packets.Client
{
    internal sealed class SkillRequest : MaterializedPacket
    {
        private static readonly Dictionary<Skill, string> skills = new Dictionary<Skill, string>
        {
            {Infusion.Skill.None, "0 0" },
            {Infusion.Skill.Anatomy, "1 0"},
            {Infusion.Skill.AnimalLore, "2 0"},
            {Infusion.Skill.ItemIdentification, "3 0"},
            {Infusion.Skill.ArmsLore, "4 0"},
            {Infusion.Skill.Begging, "6 0"},
            {Infusion.Skill.Peacemaking, "9 0"},
            {Infusion.Skill.Cartography, "12 0"},
            {Infusion.Skill.DetectingHidden, "14 0"},
            {Infusion.Skill.DiscordanceEnticement, "15 0"},
            {Infusion.Skill.EvaluateIntelligence, "16 0"},
            {Infusion.Skill.ForensicEvaluation, "19 0"},
            {Infusion.Skill.Hiding, "21 0"},
            {Infusion.Skill.Provocation, "22 0"},
            {Infusion.Skill.Inscription, "23 0"},
            {Infusion.Skill.Poisoning, "30 0"},
            {Infusion.Skill.SpiritSpeak, "32 0"},
            {Infusion.Skill.Stealing, "33 0"},
            {Infusion.Skill.AnimalTaming, "35 0"},
            {Infusion.Skill.TasteIdentification, "36 0"},
            {Infusion.Skill.Tracking, "38 0"},
            {Infusion.Skill.Meditation, "46 0"}
        };

        private static readonly Dictionary<Spell, string> spells = new Dictionary<Spell, string>
        {
            {Spell.Clumsy, "1"},
            {Spell.CreateFood, "2"},
            {Spell.Feeblemind, "3"},
            {Spell.Heal, "4"},
            {Spell.MagicArrow, "5"},
            {Spell.NightSight, "6"},
            {Spell.ReactiveArmor, "7"},
            {Spell.Weaken, "8"},
            {Spell.Agility, "9"},
            {Spell.Cunning, "10"},
            {Spell.Cure, "11"},
            {Spell.Harm, "12"},
            {Spell.MagicTrap, "13"},
            {Spell.MagicUntrap, "14"},
            {Spell.Protection, "15"},
            {Spell.Strength, "16"},
            {Spell.Bless, "17"},
            {Spell.Fireball, "18"},
            {Spell.MagicLock, "19"},
            {Spell.Poison, "20"},
            {Spell.Telekenisis, "21"},
            {Spell.Teleport, "22"},
            {Spell.Unlock, "23"},
            {Spell.WallOfStone, "24"},
            {Spell.ArchCure, "25"},
            {Spell.ArchProtection, "26"},
            {Spell.Curse, "27"},
            {Spell.FireField, "28"},
            {Spell.GreaterHeal, "29"},
            {Spell.Lightning, "30"},
            {Spell.ManaDrain, "31"},
            {Spell.Recall, "32"},
            {Spell.BladeSpirit, "33"},
            {Spell.DispelField, "34"},
            {Spell.Incognito, "35"},
            {Spell.Reflection, "36"},
            {Spell.MindBlast, "37"},
            {Spell.Paralyze, "38"},
            {Spell.PoisonField, "39"},
            {Spell.SummonCreature, "40"},
            {Spell.Dispel, "41"},
            {Spell.EnergyBolt, "42"},
            {Spell.Explosion, "43"},
            {Spell.Invisibility, "44"},
            {Spell.Mark, "45"},
            {Spell.MassCurse, "46"},
            {Spell.ParalyzeField, "47"},
            {Spell.Reveal, "48"},
            {Spell.ChainLightning, "49"},
            {Spell.EnergyField, "50"},
            {Spell.FlameStrike, "51"},
            {Spell.Gate, "52"},
            {Spell.ManaVampire, "53"},
            {Spell.MassDispel, "54"},
            {Spell.MeteorShower, "55"},
            {Spell.Polymorph, "56"},
            {Spell.Earthquake, "57"},
            {Spell.EnergyVortex, "58"},
            {Spell.Resurrection, "59"},
            {Spell.SummonAirElemental, "60"},
            {Spell.SummonDaemon, "61"},
            {Spell.SummonEarthElemental, "62"},
            {Spell.SummonFireElemental, "63"},
            {Spell.SummonWaterElemental, "64"}
        };

        public SkillRequest(byte type, string action)
        {
            var packetLength = (ushort) 5;
            var payload = new byte[packetLength];

            var writer = new ArrayPacketWriter(payload);
            writer.WriteByte((byte)PacketDefinitions.RequestSkills.Id);
            writer.WriteUShort(packetLength);
            writer.WriteByte(type);
            if (string.IsNullOrEmpty(action))
                writer.WriteByte(0);
            else
                writer.WriteString(action);

            rawPacket = new Packet(PacketDefinitions.RequestSkills.Id, payload);
        }

        public SkillRequest(Skill skill)
        {
            if (!skills.TryGetValue(skill, out string skillString))
                throw new InvalidOperationException($"Cannot request {skill}");

            Skill = skill;

            var packetLength = (ushort) (5 + skillString.Length);
            var payload = new byte[packetLength];

            var writer = new ArrayPacketWriter(payload);
            writer.WriteByte((byte) PacketDefinitions.RequestSkills.Id);
            writer.WriteUShort(packetLength);
            writer.WriteByte(0x24);
            writer.WriteString(skillString);
            writer.WriteByte(0x00);

            rawPacket = new Packet(PacketDefinitions.RequestSkills.Id, payload);
        }

        private Packet rawPacket;

        public SkillRequest()
        {
        }

        public SkillRequest(Spell spell)
        {
            var spellString = spells[spell];

            var packetLength = (ushort) (5 + spellString.Length);
            var payload = new byte[packetLength];

            var writer = new ArrayPacketWriter(payload);
            writer.WriteByte((byte) PacketDefinitions.RequestSkills.Id);
            writer.WriteUShort(packetLength);
            writer.WriteByte(0x56);
            writer.WriteString(spellString);
            writer.WriteByte(0x00);

            rawPacket = new Packet(PacketDefinitions.RequestSkills.Id, payload);
        }

        public override void Deserialize(Packet rawPacket)
        {
            this.rawPacket = rawPacket;
            var reader = new ArrayPacketReader(rawPacket.Payload);

            reader.Skip(3);
            byte type = reader.ReadByte();

            if (type == 0x24)
            {
                string skillText = reader.ReadNullTerminatedString();

                bool skillFound = false;
                foreach (var pair in skills)
                {
                    if (skillText.Equals(pair.Value))
                    {
                        Skill = pair.Key;
                        skillFound = true;
                        break;
                    }
                }
                if (!skillFound)
                    throw new NotImplementedException($"Unknown skill text: {skillText ?? "null"}");
            }
        }

        public Skill? Skill { get; private set; }

        public override Packet RawPacket => rawPacket;
    }
}


text:
title: Green Beans with Bacon and Mushrooms
categories: moosefood
tags:
  - side-dish
  - American
excerpt: ""
header:
  teaser:
  thumb:
---

## INGREDIENTS
* 12 ounces green beans (Wegmans Organic Cleaned & Cut)
* 2 slices thick-sliced bacon
* 1 8-ounce can sliced mushrooms
* 2-3 tablespoons chicken broth
* rounded ½ teaspoon lemon pepper seasoning
* fresh coarse ground black pepper *to taste*

## INSTRUCTIONS
1. Cut beans into bite-sized pieces (1-1¼ inches).
2. Put beans into boiling water for 5 minutes.
3. In the meantime, cut bacon into ½-inch squares. Brown in 10-inch skillet.
4. Remove bacon; reserve 1 tablespoon bacon drippings.
5. Drain beans; sauté in bacon drippings for 2 minutes.
6. Add mushrooms and sauté for 2-4 minutes.
7. Add chicken broth, lemon pepper seasoning and black pepper.
8. Sauté 2-3 minutes longer and serve.


text:
layout: post
title: Book Review – Learning Veeam Backup & Replication for VMware vSphere
uuid: 26a34645-4cb8-4369-867a-6215d85966d2
date: 2014-05-19T18:00:00+01:00
tags:
- Book Review
- Veeam
- Veeam Backup & Replication
- VMware
---
### *Disclaimer:*

*I have received this book as a free review sample, with the only requirement that I would write a review of it here on my blog and post short reviews of it on amazon.com, goodreads.com and books.dzone.com. These should be unbiased and I was in no way obligated to write positive reviews.*

{% include image.html img="/assets/2014/05/19/learning-veeam-backup-and-replication.jpg" alt-title="Learning Veeam Backup and Replication" %}

The book is available in both eBook and Print versions from [Packt Publishing](http://www.packtpub.com/learning-veeam-backup-and-replication-for-vmware-vsphere/book?utm_source=Blogs&utm_medium=Links&utm_campaign=create.com)

I know Christian Mohn, the author of  "Learning Veeam Backup & Replication for VMware vSphere" from Twitter ([@h0bbel](https://twitter.com/h0bbel){:target="_blank"}), his blog [vNinja.net](http://vninja.net){:target="_blank"} and I have also listened to a few of his podcasts, [vSoup](http://vsoup.net){:target="_blank"}, which he does regularly with co-presenters Ed Czerwin ([@eczerwin](https://twitter.com/eczerwin){:target="_blank"}) and Chris Dearden ([@ChrisDearden](https://twitter.com/chrisdearden){:target="_blank"}).

The book is not that long, only 110 pages, and is easily read. It gives a very good overview and introduction to Veeam Backup & Replications for people who are not familar with it beforehand.

The structure of the book is mostly like a guide, divided into 5 chapters, providing the reader with a step by step guide on how to setup Veeam Backup & Replication from scratch.

## Chapter 1 - Introduction to Veeam Backup & Replication v7 for VMware

Chapter 1 gives a good introduction to backup terms RPO and RTO. Then moves onto describing the components of Veeam Backup & Replication, and ends with a detailed guide on how to install and patch Veeam Backup & Replication v7.

## Chapter 2 - Configuring Backups

Chapter 2 walks through configuring backup repositories (the destination where backups are stored) and then describes the different transport modes that Veeam Backup & Replication support. After that there is a detailed description of the backup modes, "Incremental backup", "Incremental backup with synthetic full" and "Reversed incremental backup".

The chapter ends with a guide on how to configure first a virtual backup proxy (which is the processing engine in Veeam Backup & Replication), then a backup job, a tape backup job and lastly a backup copy job. All this to live up to the "3-2-1 Backup Rule", which states the following:

*   Have at least **three copies of your data**.
*   Store the copies on **two different media**.
*   Keep **one backup copy offsite**.

## Chapter 3 - Restoring Data

Backups are nice, but it is the restore that counts. So in this chapter some of the different restore options is detailed, all of which is possible from a single image based backup file.

The chapter walks through the following restore options:

*   Performing Instant VM Recovery
*   Performing Full VM Restore
*   Restoring VM files
*   Restoring VM Guest files

## Chapter 4 - Replicating Virtual Machines

To provide very fast recovery of services Veeam Backup & Replication gives the possibility to replicate VMs to either a different ESXi host in the same site, to a different datastore or to a remote ESXi host and a remote datastore. This can give the protection against a whole datacenter failure.

Replication creates a "shadow" VM which is powered off and where data is replicated to, every few minutes (if needed). Should there be a failure, it is simple a matter of failing over to the replicated "shadow" VM, and services should be up and running within a few minutes.

This chapter discuses the replication infrastructure components, how to setup a replication job, how to failover to a "shadow" VM and how to failback to the original VM.

## Chapter 5 - Other Features

The last chapter discuses some of the other / advanced features, which includes SureBackup, SureReplica, Universal Application-Item Recovery (U-AIR), Quick Migration, SAN Snapshot integration, vCloud Director, Veeam Backup Enterprise Manager and Veeam Backup Search.

That is a lot of features to put into a single chapter, which also mean that the level of detail in this chapter is limited compared to the earlier chapters. But it still succeeds in given a good overview of these "other features".

## Conclusion

This is a very good book, if you have some experience with VMware vSphere, but are new to Veeam Backup & Replication. It walks you through every step of the way to get a Veeam infrastructure setup, and getting your VMs backed up and replicated. And most importantly it gives you the knowledge on how to restore VMs and data from those backups.

The book is available in both eBook and Print versions from [Packt Publishing](http://www.packtpub.com/learning-veeam-backup-and-replication-for-vmware-vsphere/book?utm_source=Blogs&utm_medium=Links&utm_campaign=create.com){:target="_blank"}.


text:
<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;
use kartik\widgets\Select2;
use yii\helpers\ArrayHelper;
use kartik\widgets\DatePicker;
use kartik\label\LabelInPlace;
use lukisongroup\master\models\Kategoricus;
use lukisongroup\master\models\Province;
use lukisongroup\master\models\Kota;
use yii\web\JsExpression;
use yii\bootstrap\Modal;
use yii\helpers\Url;
use kartik\widgets\DepDrop;

/* @var $this yii\web\View */
/* @var $model lukisongroup\master\models\Customerskat */
/* @var $form yii\widgets\ActiveForm */

     $dropdis = ArrayHelper::map(\lukisongroup\master\models\Distributor::find()->all(), 'KD_DISTRIBUTOR', 'NM_DISTRIBUTOR');
         $config = ['template'=>"{input}\n{error}\n{hint}"];
// $dropparent = ArrayHelper::map(\lukisongroup\master\models\Kategori::find()->all(),'CUST_KTG_PARENT', 'CUST_KTG_NM');
   $no = 0;
   $dropparentkategori = ArrayHelper::map(Kategoricus::find()->where(['CUST_KTG_PARENT'=>$no])
                                                             ->asArray()
                                                             ->all(),'CUST_KTG', 'CUST_KTG_NM');

	$droppro = ArrayHelper::map(Province::find()->asArray()
                                              ->all(),'PROVINCE_ID','PROVINCE');
	// $dropcity = ArrayHelper::map(Kota::find()->all(),'POSTAL_CODE','CITY_NAME');
// print_r( $dropparentkategori);
// die();
    // Modal::begin([
    //          'header'=>'
Vlookup
',
    //          'id'=> 'modal',
    //          'size'=>'modal-lg',
    //      ]);
    //      echo"

";
    //      modal::end();

?>

    <?php $form = ActiveForm::begin([
	'id'=>$model->formName(),

	]); ?>

	  <?= $form->field($model, 'CUST_NM', $config)->widget(LabelInPlace::classname());?>

    <?= $form->field($model, 'CUST_GRP')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'TLP2', $config)->widget(LabelInPlace::classname());?>

    <?= $form->field($model, 'FAX')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'EMAIL', $config)->widget(LabelInPlace::classname());?>

    <?= $form->field($model, 'TLP1', $config)->widget(LabelInPlace::classname());?>

   <?=  $form->field($model, 'PARENT')->widget(Select2::classname(),

    [
    'options'=>[  'placeholder' => 'Select Customers parent ...'
    ],
    'data' => $dropparentkategori

]);?>

   <?= $form->field($model, 'CUST_KTG')->widget(DepDrop::classname(), [
    'options' => [//'id'=>'customers-cust_ktg',
    'placeholder' => 'Select Customers kategory'],
    'type' => DepDrop::TYPE_SELECT2,
    'select2Options'=>['pluginOptions'=>['allowClear'=>true]],
    'pluginOptions'=>[
        'depends'=>['customers-parent'],
        'url' => Url::to(['/master/customers/lisdata']),
      'loadingText' => 'Loading data ...',
    ]
]);?>

	   <?=  $form->field($model, 'PROVINCE_ID')->widget(Select2::classname(),

    [
    'options'=>[ 'id'=>'customers-province_id',
                'placeholder' => 'Select provinsi ...'
    ],
    'data' => $droppro

]);?>

   <?= $form->field($model, 'CITY_ID')->widget(DepDrop::classname(), [
    'options' => ['id'=>'customers-city_id',
    'placeholder' => 'Select Kota'],
    'type' => DepDrop::TYPE_SELECT2,
    'select2Options'=>['pluginOptions'=>['allowClear'=>true]],
    'pluginOptions'=>[
        'depends'=>['customers-province_id'],
        'url' => Url::to(['/master/customers/lisarea']),
      'loadingText' => 'Loading data ...',
    ]
]);?>

     <?= $form->field($model, 'PIC', $config)->widget(LabelInPlace::classname());?>

 <?= $form->field($model, 'JOIN_DATE')->widget(DatePicker::classname(), [
    'options' => ['placeholder' => 'Enter date ...'],
    'pluginOptions' => [
        'autoclose'=>true
    ],
	'pluginEvents' => [
			          'show' => "function(e) {show}",
	],
]);?>

  <?= $form->field($model, 'KD_DISTRIBUTOR')->widget(Select2::classname(), [
		     'data' => $dropdis,
        'options' => [
//            'id'=>'parent',
        'placeholder' => 'Pilih Distributor ...'],
        'pluginOptions' => [
            'allowClear' => true
             ],

    ]);?>

    <?= $form->field($model, 'WEBSITE', $config)->widget(LabelInPlace::classname());?>

    <?= $form->field($model, 'NOTE', $config)->widget(LabelInPlace::classname());?>

      <?= $form->field($model, 'NPWP', $config)->widget(LabelInPlace::classname());?>

	<?=$form->field($model, 'STT_TOKO')->dropDownList(['' => ' -- Silahkan Pilih --',
                                                     '0' => 'sewa',
                                                     '1' => 'hak milik']) ; ?>

    <?= $form->field($model, 'DATA_ALL')->textInput(['maxlength' => true]) ?>

	<?php

	if(!$model->isNewRecord )
	{
		echo $form->field($model, 'STATUS')->dropDownList(['' => ' -- Silahkan Pilih --', '0' => 'Tidak Aktif', '1' => 'Aktif']) ;
	}

	?>

        <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>

    <?php ActiveForm::end(); ?>

<?php

$this->registerJs("

   $('form#{$model->formName()}').on('beforeSubmit',function(e)
    {
        var \$form = $(this);
        $.post(
            \$form.attr('action'),
            \$form.serialize()

        )

            .done(function(result){
			        if(result == 1 )
                {
                  $(document).find('#createcus').modal('hide');
                  $('form#customers').trigger('reset');
                  $.pjax.reload({container:'#gv-cus'});

                  }
                else{
                      console.log(result)
                      }

            });

return false;

});

 ",$this::POS_END);


text:
namespace SimpleDemo.iOS
{
    using MonoTouch.Foundation;
    using MonoTouch.UIKit;
    using Xamarin.Forms;

    // The UIApplicationDelegate for the application. This class is responsible for launching the
    // User Interface of the application, as well as listening (and optionally responding) to
    // application events from iOS.
    [Register ("AppDelegate")]
    public partial class AppDelegate : UIApplicationDelegate
    {
        UIWindow window;

        public override bool FinishedLaunching(UIApplication app, NSDictionary options)
        {
            OxyPlot.XamarinFormsIOS.Forms.Init ();
            Forms.Init();

            this.window = new UIWindow(UIScreen.MainScreen.Bounds);

            var appController = App.GetMainPage ().CreateViewController ();
            appController.Title = "Xamarin.Forms demo on iOS";

            var navigationController = new UINavigationController ();
            navigationController.NavigationBar.Translucent = false;
            navigationController.PushViewController (appController, false);

            this.window.RootViewController =  navigationController;

            this.window.MakeKeyAndVisible();

            return true;
        }
    }
}


text:
struct OsmElement
{
  enum class EntityType
  {
    Unknown = 0x0,
    Node = 0x6F6E, // "no"
    Way = 0x6177, // "wa"
    Relation = 0x6572, // "re"
    Tag = 0x6174, // "ta"
    Nd = 0x646E, // "nd"
    Member = 0x656D, // "me"
    Osm = 0x736F, // "os"
  };

  struct Member
  {
    Member() = default;
    Member(uint64_t ref, EntityType type, std::string const & role)
      : m_ref(ref), m_type(type), m_role(role) {}

    bool operator==(Member const & other) const
    {
      return m_ref == other.m_ref && m_type == other.m_type && m_role == other.m_role;
    }

    uint64_t m_ref = 0;
    EntityType m_type = EntityType::Unknown;
    std::string m_role;
  };

  struct Tag
  {
    Tag() = default;
    Tag(std::string const & key, std::string const & value) : m_key(key), m_value(value) {}

    bool operator==(Tag const & other) const
    {
      return m_key == other.m_key && m_value == other.m_value;
    }

    bool operator<(Tag const & other) const
    {
      return m_key == other.m_key ? m_value < other.m_value : m_key < other.m_key;
    }

    std::string m_key;
    std::string m_value;
  };

  static EntityType StringToEntityType(std::string const & type)
  {
    if (type == "way")
      return EntityType::Way;
    if (type == "node")
      return EntityType::Node;
    if (type == "relation")
      return EntityType::Relation;
    ASSERT(false, ("Unknown type", type));
    return EntityType::Unknown;
  }

  void Clear()
  {
    m_type = EntityType::Unknown;
    m_id = 0;
    m_lon = 0.0;
    m_lat = 0.0;
    m_ref = 0;
    m_k.clear();
    m_v.clear();
    m_memberType = EntityType::Unknown;
    m_role.clear();

    m_nodes.clear();
    m_members.clear();
    m_tags.clear();
  }

  std::string ToString(std::string const & shift = std::string()) const;

  std::vector<uint64_t> const & Nodes() const { return m_nodes; }
  std::vector<Member> const & Members() const { return m_members; }
  std::vector<Tag> const & Tags() const { return m_tags; }

  bool IsNode() const { return m_type == EntityType::Node; }
  bool IsWay() const { return m_type == EntityType::Way; }
  bool IsRelation() const { return m_type == EntityType::Relation; }

  bool operator==(OsmElement const & other) const
  {
    return m_type == other.m_type
        && m_id == other.m_id
        && base::AlmostEqualAbs(m_lon, other.m_lon, 1e-7)
        && base::AlmostEqualAbs(m_lat, other.m_lat, 1e-7)
        && m_ref == other.m_ref
        && m_k == other.m_k
        && m_v == other.m_v
        && m_memberType == other.m_memberType
        && m_role == other.m_role
        && m_nodes == other.m_nodes
        && m_members == other.m_members
        && m_tags == other.m_tags;
  }

  void AddNd(uint64_t ref) { m_nodes.emplace_back(ref); }
  void AddMember(uint64_t ref, EntityType type, std::string const & role)
  {
    m_members.emplace_back(ref, type, role);
  }

  void AddTag(Tag const & tag);
  void AddTag(char const * key, char const * value);
  void AddTag(std::string const & key, std::string const & value);
  bool HasTag(std::string const & key) const;
  bool HasTag(std::string const & key, std::string const & value) const;
  bool HasAnyTag(std::unordered_multimap<std::string, std::string> const & tags) const;

  template <class Fn>
  void UpdateTag(std::string const & key, Fn && fn)
  {
    for (auto & tag : m_tags)
    {
      if (tag.m_key == key)
      {
        fn(tag.m_value);
        return;
      }
    }

    std::string value;
    fn(value);
    if (!value.empty())
      AddTag(key, value);
  }

  std::string GetTag(std::string const & key) const;
  std::string GetTagValue(std::string const & key, std::string const & defaultValue) const;
  EntityType m_type = EntityType::Unknown;
  uint64_t m_id = 0;
  double m_lon = 0;
  double m_lat = 0;
  uint64_t m_ref = 0;
  std::string m_k;
  std::string m_v;
  EntityType m_memberType = EntityType::Unknown;
  std::string m_role;

  std::vector<uint64_t> m_nodes;
  std::vector<Member> m_members;
  std::vector<Tag> m_tags;
};

base::GeoObjectId GetGeoObjectId(OsmElement const & element);

std::string DebugPrint(OsmElement const & element);
std::string DebugPrint(OsmElement::EntityType type);
std::string DebugPrint(OsmElement::Tag const & tag);