text:
package org.lockss.plugin.iop;

import java.util.*;

import org.lockss.test.*;
import org.lockss.util.*;
import org.lockss.config.*;
import org.lockss.extractor.*;
import org.lockss.plugin.*;
import org.lockss.plugin.simulated.*;

/**
 * One of the articles used to get the html source for this plugin is:
 * http://www.IOPScience.com/cppm/vol5/iss1/17/
 *
 */
public class TestIOPMetadataExtractor extends LockssTestCase {

  static Logger log = Logger.getLogger(TestIOPMetadataExtractor.class);

  private MockLockssDaemon theDaemon;
  private SimulatedArchivalUnit sau; // Simulated AU to generate content
  private ArchivalUnit bau; // IOPScience AU

  // XML file in org.lockss.plugin.IOPScience package
  private static String PLUGIN_NAME = "org.lockss.plugin.iop.ClockssIOPSciencePlugin";

  private static String BASE_URL = "http://iopscience.iop.org/";
  private static String SIM_ROOT = BASE_URL + "xyzjn/";

  public void setUp() throws Exception {
    super.setUp();
    String tempDirPath = setUpDiskSpace();

    theDaemon = getMockLockssDaemon();
    theDaemon.getAlertManager();
    theDaemon.getPluginManager().setLoadablePluginsReady(true);
    theDaemon.setDaemonInited(true);
    theDaemon.getPluginManager().startService();
    theDaemon.getCrawlManager();

    sau = PluginTestUtil.createAndStartSimAu(MySimulatedPlugin.class,	simAuConfig(tempDirPath));
    bau = PluginTestUtil.createAndStartAu(PLUGIN_NAME, natureAuConfig());
  }

  public void tearDown() throws Exception {
    sau.deleteContentTree();
    theDaemon.stopDaemon();
    super.tearDown();
  }

  Configuration simAuConfig(String rootPath) {
    Configuration conf = ConfigManager.newConfiguration();
    conf.put("root", rootPath);
    conf.put("base_url", SIM_ROOT);
    conf.put("depth", "2");
    conf.put("branch", "3");
    conf.put("numFiles", "7");
    conf.put("fileTypes",""	+ (
        SimulatedContentGenerator.FILE_TYPE_PDF +
        SimulatedContentGenerator.FILE_TYPE_HTML));
    conf.put("default_article_mime_type", "application/html");
    return conf;
  }

  /**
   * Configuration method.
   * @return
   */
  Configuration natureAuConfig() {
    Configuration conf = ConfigManager.newConfiguration();
    conf.put("base_url", BASE_URL);
    conf.put("volume_name", "1");
    conf.put("journal_issn", "2043-6262");
    return conf;
  }

  String url = "http://iopscience.iop.org/2043-6262/1/4/043003";
  // the metadata that should be extracted
  String goodDOI = "10.1088/2043-6262/1/4/043003";
  String goodArticleTitle = "Polymer materials with spatially graded morphologies: " +
      "preparation, characterization and utilization";
  String goodVolume = "1";
  String goodIssue = "4";
  String goodStartPage = "043003";
  String goodISSN = "2043-6262";
  String goodDate = "2011-01-25";
  String[] goodAuthors = new String[] {
      "Daisuke Fujiki", "Chuanming Jing", "Dan-Thuy Van-Pham", "Hideyuki Nakanishi"
      ,"Tomohisa Norisuye","Qui Tran-Cong-Miyata"};
  String goodJournalTitle = "Advances in Natural Sciences: Nanoscience and Nanotechnology";

  // a chunk of html source code from the publisher's site from where the
  // metadata should be extracted
  String goodContent =
      "<TITLE>"+ "blabla"+"</TITLE>\n"
    + "<meta name=\"citation_journal_title\" content=\""+ goodJournalTitle+ "\">\n"
    + "<meta name=\"citation_author\" content=\""+ goodAuthors[0]+ "\">\n"
    + "<meta name=\"citation_author\" content=\""+ goodAuthors[1]+ "\">\n"
    + "<meta name=\"citation_author\" content=\""+ goodAuthors[2]+ "\">\n"
    + "<meta name=\"citation_author\" content=\""+ goodAuthors[3]+ "\">\n"
    + "<meta name=\"citation_author\" content=\""+ goodAuthors[4]+ "\">\n"
    + "<meta name=\"citation_author\" content=\""+ goodAuthors[5]+ "\">\n"
    + "<meta name=\"citation_title\" content=\""+ goodArticleTitle+ "\">\n"
    + "<meta name=\"citation_journal_title\" content=\""+ goodJournalTitle+ "\">\n"
    + "<meta name=\"citation_publication_date\" content=\""+ goodDate+ "\">\n"
    + "<meta name=\"citation_volume\""+ " content=\""+ goodVolume+ "\">\n"
    + "<meta name=\"citation_issue\" content=\""+ goodIssue	+ "\">\n"
    + "<meta name=\"citation_firstpage\""+ " content=\""+ goodStartPage	+ "\">\n"
    + "<meta name=\"citation_doi\"" + " content=\""     + goodDOI + "\">\n"
    + "<meta name=\"citation_issn\"" + " content=\""     + goodISSN + "\">\n"
    + "<meta name=\"citation_fulltext_html_url\" content=\"" + url + "/article/\"/>"
  ;

  /**
   * Method that creates a simulated Cached URL from the source code provided by
   * the goodContent String. It then asserts that the metadata extracted, by using
   * the IOPScienceHtmlMetadataExtractorFactory, match the metadata in the source code.
   * @throws Exception
   */
  public void testExtractFromGoodContent() throws Exception {
    MockCachedUrl cu = new MockCachedUrl(url, bau);
    cu.setContent(goodContent);
    cu.setContentSize(goodContent.length());
    cu.setProperty(CachedUrl.PROPERTY_CONTENT_TYPE, "text/html");
    FileMetadataExtractor me =
        new IOPScienceHtmlMetadataExtractorFactory.IOPScienceHtmlMetadataExtractor();
    FileMetadataListExtractor mle =
      new FileMetadataListExtractor(me);
    List<ArticleMetadata> mdlist = mle.extract(MetadataTarget.Any(), cu);
    assertNotEmpty(mdlist);
    ArticleMetadata md = mdlist.get(0);
    assertNotNull(md);
    assertEquals(goodDOI, md.get(MetadataField.FIELD_DOI));
    assertEquals(goodVolume, md.get(MetadataField.FIELD_VOLUME));
    assertEquals(goodIssue, md.get(MetadataField.FIELD_ISSUE));
    assertEquals(goodStartPage, md.get(MetadataField.FIELD_START_PAGE));
    assertEquals(goodISSN, md.get(MetadataField.FIELD_ISSN));

    assertEquals(Arrays.asList(goodAuthors), md.getList(MetadataField.FIELD_AUTHOR));
    assertEquals(goodAuthors[0], md.get(MetadataField.FIELD_AUTHOR));
    assertEquals(goodArticleTitle, md.get(MetadataField.FIELD_ARTICLE_TITLE));
    assertEquals(goodJournalTitle, md.get(MetadataField.FIELD_PUBLICATION_TITLE));
    assertEquals(goodDate, md.get(MetadataField.FIELD_DATE));
    assertEquals(url, md.get(MetadataField.FIELD_ACCESS_URL));
  }

  // a chunk of html source code from where the IOPScienceHtmlMetadataExtractorFactory
  // should NOT be able to extract metadata
  String badContent = "<TITLE>"
    + goodArticleTitle
    + "</TITLE>\n"
    + "<meta name=\"foo\""
    + " content=\"bar\">\n"
    + "
"
    + "MUMBLE: "
    + goodISSN + "
\n";

  /**
   * Method that creates a simulated Cached URL from the source code provided by the
   * badContent String. It then asserts that NO metadata is extracted by using
   * the IOPScienceHtmlMetadataExtractorFactory as the source code is broken.
   * @throws Exception
   */
  public void testExtractFromBadContent() throws Exception {
    MockCachedUrl cu = new MockCachedUrl(url, bau);
    cu.setContent(badContent);
    cu.setContentSize(badContent.length());
    cu.setProperty(CachedUrl.PROPERTY_CONTENT_TYPE, "text/html");
    FileMetadataExtractor me =
        new IOPScienceHtmlMetadataExtractorFactory.IOPScienceHtmlMetadataExtractor();
    FileMetadataListExtractor mle =
      new FileMetadataListExtractor(me);
    List<ArticleMetadata> mdlist = mle.extract(MetadataTarget.Any(), cu);
    assertNotEmpty(mdlist);
    ArticleMetadata md = mdlist.get(0);
    assertNotNull(md);
    assertNull(md.get(MetadataField.FIELD_DOI));
    assertNull(md.get(MetadataField.FIELD_VOLUME));
    assertNull(md.get(MetadataField.FIELD_ISSUE));
    assertNull(md.get(MetadataField.FIELD_START_PAGE));
    assertNull(md.get(MetadataField.FIELD_ISSN));

    assertEquals(1, md.rawSize());
    assertEquals("bar", md.getRaw("foo"));
  }

  /**
   * Inner class that where a number of Archival Units can be created
   *
   */
  public static class MySimulatedPlugin extends SimulatedPlugin {
    public ArchivalUnit createAu0(Configuration auConfig)
	throws ArchivalUnit.ConfigurationException {
      ArchivalUnit au = new SimulatedArchivalUnit(this);
      au.setConfiguration(auConfig);
      return au;
    }

    public SimulatedContentGenerator getContentGenerator(Configuration cf, String fileRoot) {
      return new MySimulatedContentGenerator(fileRoot);
    }

  }

  /**
   * Inner class to create a html source code simulated content
   *
   */
  public static class MySimulatedContentGenerator extends	SimulatedContentGenerator {
    protected MySimulatedContentGenerator(String fileRoot) {
      super(fileRoot);
    }

    public String getHtmlFileContent(String filename, int fileNum, int depth,
        int branchNum, boolean isAbnormal) {

      String file_content = "<TITLE>" + filename + "</TITLE>\n";

      file_content += "  <meta name=\"lockss.filenum\" content=\""+ fileNum + "\">\n";
      file_content += "  <meta name=\"lockss.depth\" content=\"" + depth + "\">\n";
      file_content += "  <meta name=\"lockss.branchnum\" content=\"" + branchNum + "\">\n";

      file_content += getHtmlContent(fileNum, depth, branchNum,	isAbnormal);
      file_content += "\n";
      logger.debug2("MySimulatedContentGenerator.getHtmlFileContent: "
		    + file_content);

      return file_content;
    }
  }
}


text:
require 'yaml'

module Database
  DATABASE_FILE_PATH = "#{__dir__}/vision.database.yml"

  # Load the standard vision toolkit database and re-arrage it to be simply exportable
  # to liquid as assigns. All this is based on Shopify
  def self.tables
    @tables ||= begin
      db =
        if YAML.respond_to?(:unsafe_load_file) # Only Psych 4+ can use unsafe_load_file
          # unsafe_load_file is needed for YAML references
          YAML.unsafe_load_file(DATABASE_FILE_PATH)
        else
          YAML.load_file(DATABASE_FILE_PATH)
        end

      # From vision source
      db['products'].each do |product|
        collections = db['collections'].find_all do |collection|
          collection['products'].any? { |p| p['id'].to_i == product['id'].to_i }
        end
        product['collections'] = collections
      end

      # key the tables by handles, as this is how liquid expects it.
      db = db.each_with_object({}) do |(key, values), assigns|
        assigns[key] = values.each_with_object({}) do |v, h|
          h[v['handle']] = v
        end
      end

      # Some standard direct accessors so that the specialized templates
      # render correctly
      db['collection'] = db['collections'].values.first
      db['product']    = db['products'].values.first
      db['blog']       = db['blogs'].values.first
      db['article']    = db['blog']['articles'].first

      db['cart']       = {
        'total_price' => db['line_items'].values.inject(0) { |sum, item| sum + item['line_price'] * item['quantity'] },
        'item_count' => db['line_items'].values.inject(0) { |sum, item| sum + item['quantity'] },
        'items' => db['line_items'].values,
      }

      db
    end
  end
end

if __FILE__ == $PROGRAM_NAME
  p(Database.tables['collections']['frontpage'].keys)
  # p Database.tables['blog']['articles']
end

redpajama_set_name: RedPajamaGithub


text:
var Html = function(info) {
    if (info.mode == client) {
        return logBoxHtml(client);
    };
    return '
<form role="form" id="js-form" name="spiderForm" onsubmit="return runStop();" method="POST" enctype="multipart/form-data">\

\
              \

\

\

\

\
                      #	\
                      Testing	\
                      ID	\
                      Name	\
                      Description	\

' + spidersHtml(info.spiders) + '

\

\

\
                自定义配置(多任务请分别多包一层"<>",例如:<关键词1><关键词2>)\
                <textarea name="Keyins" class="form-control" rows="2" placeholder="Enter ...">' + info.Keyins + '</textarea>\

\

\

\
                采集上限(默认限制URL数)\
                <input name="Limit" type="number" class="form-control" min="0" value="' + info.Limit + '">\

' +
        ThreadNumHtml(info.ThreadNum) +
        PausetimeHtml(info.Pausetime) +
        ProxyMinuteHtml(info.ProxyMinute) +
        DockerCapHtml(info.DockerCap) +
        OutTypeHtml(info.OutType) +
        SuccessInheritHtml(info.SuccessInherit) +
        FailureInheritHtml(info.FailureInherit) +
        '
' +
        '
\

\
                ' + btnHtml(info.mode, info.status) +
        '
\
          </form>' + logBoxHtml(info.mode) + '
';
}

var spidersHtml = function(spiders) {
    var html = '';

    for (var i in spiders.menu) {
        html += '
\
            \

\
                  \
                    <input name="spiders" id="spider-' + i + '" type="checkbox" value="' + spiders.menu[i].name + '"' +
            function() {
                if (spiders.curr[spiders.menu[i].name]) {
                    return " checked";
                }
                return '';
            }() + '>\
                  \

\
            	\
            测试	\
            ' + i + '	\
            ' + spiders.menu[i].name + '	\
            ' + spiders.menu[i].description + '	\

'
    }

    return html;
}
var ThreadNumHtml = function(ThreadNum) {
    return '
\
                并发协程\
                <input name="ThreadNum" type="number" class="form-control" min="' + ThreadNum.min + '" max="' + ThreadNum.max + '" value="' + ThreadNum.curr + '">\

';
}

var DockerCapHtml = function(DockerCap) {
    return '
\
                分批输出限制\
                <input name="DockerCap" type="number" class="form-control" min="' + DockerCap.min + '" max="' + DockerCap.max + '" value="' + DockerCap.curr + '">\

';
}

var PausetimeHtml = function(Pausetime) {
    var html = '
\
                暂停时长参考\
                <select class="form-control" name="Pausetime">';
    for (var i in Pausetime.menu) {
        var isSelect = ""
        if (Pausetime.menu[i] == Pausetime.curr[0]) {
            isSelect = " selected";
        };
        if (Pausetime.menu[i] == 0) {
            html += '<option value="' + Pausetime.menu[i] + '"' + isSelect + '>' + "无暂停" + '</option>';
        } else {
            html += '<option value="' + Pausetime.menu[i] + '"' + isSelect + '>' + Pausetime.menu[i] + ' ms</option>';
        }
    };
    html += '</select>
';
    return html;
}

var ProxyMinuteHtml = function(ProxyMinute) {
    var html = '
\
                代理IP更换频率\
                <select class="form-control" name="ProxyMinute">';
    for (var i in ProxyMinute.menu) {
        var isSelect = ""
        if (ProxyMinute.menu[i] == ProxyMinute.curr[0]) {
            isSelect = " selected";
        };
        if (ProxyMinute.menu[i] == 0) {
            html += '<option value="' + ProxyMinute.menu[i] + '"' + isSelect + '>' + "不使用代理" + '</option>';
        } else {
            html += '<option value="' + ProxyMinute.menu[i] + '"' + isSelect + '>' + ProxyMinute.menu[i] + ' min</option>';
        }
    };
    html += '</select>
';
    return html;
}

var OutTypeHtml = function(OutType) {
    var html = '
 \
            输出方式\
            <select class="form-control" name="OutType">';
    for (var i in OutType.menu) {
        var isSelect = "";
        if (OutType.curr == OutType.menu[i]) {
            isSelect = " selected";
        };
        html += '<option value="' + OutType.menu[i] + '"' + isSelect + '>' + OutType.menu[i] + '</option>';
    }
    return html + '</select>
';
}

var SuccessInheritHtml = function(SuccessInherit) {
    var html = '
 \
            继承并保存成功记录\
            <select class="form-control" name="SuccessInherit">';

    var True = "";
    var False = "";
    if (SuccessInherit == true) {
        True = " selected";
    } else {
        False = " selected";
    };

    html += '<option value="true"' + True + '>' + "Yes" + '</option>';
    html += '<option value="false"' + False + '>' + "No" + '</option>';
    return html + '</select>
';
}

var FailureInheritHtml = function(FailureInherit) {
    var html = '
 \
            继承并保存失败记录\
            <select class="form-control" name="FailureInherit">';

    var True = "";
    var False = "";
    if (FailureInherit == true) {
        True = " selected";
    } else {
        False = " selected";
    };

    html += '<option value="true"' + True + '>' + "Yes" + '</option>';
    html += '<option value="false"' + False + '>' + "No" + '</option>';
    return html + '</select>
';
}

var btnHtml = function(mode, status) {
    if (parseInt(mode) != offline) {
        return '<button type="submit" id="btn-run" class="btn btn-primary" data-type="run">Run</button>';
    }
    switch (status) {
        case _stopped:
            return '<button type="button" id="btn-pause" class="btn btn-warning" onclick="pauseRecover()" disabled="disabled">Pause</button>\
            <button type="submit" id="btn-run" class="btn btn-primary" data-type="run">Run</button>';
        case _stop:
            return '<button type="button" id="btn-pause" class="btn btn-warning" onclick="pauseRecover()" disabled="disabled">Pause</button>\
            <button type="submit" id="btn-run" class="btn btn-danger" data-type="stop" disabled="disabled">Stopping...</button>';
        case _run:
            return '<button type="button" id="btn-pause" class="btn btn-warning" onclick="pauseRecover()" style="display:inline-block;" >Pause</button>\
            <button type="submit" id="btn-run" class="btn btn-danger" data-type="stop">Stop</button>';
        case _pause:
            return '<button type="button" id="btn-pause" class="btn btn-info" onclick="pauseRecover()" style="display:inline-block;" >Go on...</button>\
            <button type="submit" id="btn-run" class="btn btn-danger" data-type="stop">Stop</button>';
    }
}

var logBoxHtml = function(m) {
    if (m == client) {
        return '
\

\

\

';
    };
    return '
\

\

\

\

';
}

function switchHeight(obj){
    var a=$(obj);
    var i=a.children('i');
    if(i.hasClass('glyphicon-chevron-up')){
        i.removeClass('glyphicon-chevron-up').addClass('glyphicon-chevron-down');
        $('#log-box-wrap').css('height','100%');
    }else{
        i.removeClass('glyphicon-chevron-down').addClass('glyphicon-chevron-up');
        $('#log-box-wrap').css('height','20%');
    }
}


text:
published: true
title: How Tim Cook Became a Bulwark for Digital Privacy
layout: post
---
SAN FRANCISCO — Letters from around the globe began pouring into the inbox of Timothy D. Cook not long after the publication of the first revelations from Edward J. Snowden about mass government surveillance

Do you know how much privacy means to us? they asked Apple's chief executive. Do you understand?

Mr. Cook did. He was proud that Apple sold physical products — phones, tablets and laptops — and did not traffic in the intimate, digital details of its customers' lives.

That stance crystallized on Tuesday when Mr. Cook huddled for hours with lawyers and others at Apple's headquarters to figure out how to respond to a federal court order requiring the company to let the United States government break into the iPhone of one of the gunmen in a San Bernardino, Calif., mass shooting. Late Tuesday, Mr. Cook took the fight public with a letter to customers that he personally signed.


text:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class OptionSaver : MonoBehaviour {
	private MusicController music;
	public Slider musikLautstaerke;

	// Use this for initialization
	void Start () {
		musikLautstaerke.value = PlayerPrefs.GetFloat ("options_volume_music", 0.1f);
		//music = GameObject.Find ("MusicController").GetComponent<MusicController>();
	}

	public void VolumeUpdate() {
		PlayerPrefs.SetFloat ("options_volume_music", musikLautstaerke.value);
		//music.setGain (musikLautstaerke.value);
		print ("Volume Updated");
	}
}


text:
(function (factory) {
  if (typeof define === "function" && define.amd) {
    define(["exports", "foo"], factory);
  } else if (typeof exports !== "undefined") {
    factory(exports, require("foo"));
  }
})(function (exports, _foo) {
  "use strict";

  (function (obj) {
    for (var i in obj) {
      exports[i] = obj[i];
    }
  })(_foo);

  exports.foo = _foo.foo;
  exports.foo = _foo.foo;
  exports.bar = _foo.bar;
  exports.bar = _foo.foo;
  exports["default"] = _foo.foo;
  exports["default"] = _foo.foo;
  exports.bar = _foo.bar;
});


text:
This is [[Lee Dohm|Lee Dohm's]] personal wiki to keep all the crap that won't fit in his head anymore!

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

# Lists of Stuff

* [[This]]
* [[That]]
* [[The Other]]<ref>Really riveting stuff, I know ...</ref>

1. [[One]]
1. [[Two]]
1. [[Three]]

# Emoji

* I :heart_eyes: Emoji!

# Math

Math within \\( a \ne b \\) some text ...

\\[
x = {-b \pm \sqrt{b^2-4ac} \over 2a}
\\]

# Code

```ruby
def test
  puts "foo"
end
```

# Blockquote

> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

# Footnotes

<references/>


text:
/*
 ====================
 canvas setup for drawing tiles
 ====================
 */

if(typeof(google) !== 'undefined' && typeof(google.maps) !== 'undefined') {

function CanvasTileLayer(canvas_setup, render) {
  this.tileSize = new google.maps.Size(256, 256);
  this.maxZoom = 19;
  this.name = "Tile #s";
  this.alt = "Canvas tile layer";
  this.tiles = {};
  this.canvas_setup = canvas_setup;
  this.render = render;
  if (!render) {
      this.render = canvas_setup;
  }
}

// create a tile with a canvas element
CanvasTileLayer.prototype.create_tile_canvas = function (coord, zoom, ownerDocument) {

  // create canvas and reset style
  var canvas = ownerDocument.createElement('canvas');
  var hit_canvas = ownerDocument.createElement('canvas');
  canvas.style.border = hit_canvas.style.border = "none";
  canvas.style.margin = hit_canvas.style.margin = "0";
  canvas.style.padding = hit_canvas.style.padding = "0";

  // prepare canvas and context sizes
  var ctx = canvas.getContext('2d');
  ctx.width = canvas.width = this.tileSize.width;
  ctx.height = canvas.height = this.tileSize.height;

  var hit_ctx = hit_canvas.getContext('2d');
  hit_canvas.width = hit_ctx.width = this.tileSize.width;
  hit_canvas.height = hit_ctx.height = this.tileSize.height;

  //set unique id
  var tile_id = coord.x + '_' + coord.y + '_' + zoom;

  canvas.setAttribute('id', tile_id);
  hit_canvas.setAttribute('id', tile_id);

  if (tile_id in this.tiles)
      delete this.tiles[tile_id];

  this.tiles[tile_id] = {canvas:canvas, ctx:ctx, hit_canvas:hit_canvas, hit_ctx:hit_ctx, coord:coord, zoom:zoom, primitives:null};

  // custom setup
  //if (tile_id == '19295_24654_16'){
  if (this.canvas_setup)
      this.canvas_setup(this.tiles[tile_id], coord, zoom);
  //}
  return canvas;

}

CanvasTileLayer.prototype.each = function (callback) {
  for (var t in this.tiles) {
      var tile = this.tiles[t];
      callback(tile);
  }
}

CanvasTileLayer.prototype.recreate = function () {
  for (var t in this.tiles) {
      var tile = this.tiles[t];
      this.canvas_setup(tile, tile.coord, tile.zoom);
  }
};

CanvasTileLayer.prototype.redraw_tile = function (tile) {
  this.render(tile, tile.coord, tile.zoom);
};

CanvasTileLayer.prototype.redraw = function () {
  for (var t in this.tiles) {
      var tile = this.tiles[t];
      this.render(tile, tile.coord, tile.zoom);
  }
};

// could be called directly...
CanvasTileLayer.prototype.getTile = function (coord, zoom, ownerDocument) {
  return this.create_tile_canvas(coord, zoom, ownerDocument);
};

CanvasTileLayer.prototype.releaseTile = function (tile) {
  var id = tile.getAttribute('id');
  delete this.tiles[id];
};

}


text:
'''
使用difflib模块比较nginx配置文件的不同

执行python diff_nginx.py pydns.py pydns2.py > pydns.html
'''

import difflib
import sys
from logging import FileHandler

try:
    textfile1 = sys.argv[1]  #配置文件1的路径
    textfile2 = sys.argv[2]  #配置文件2的路径
except Exception,e:
    print "Error:" +str(e)
    print "Usage:diff_nginx.py filename1 filename2"
    sys.exit()

def readfile(filename):   #文件读取的分割函数
    try:
        fileHandle = open (filename,'rb')
        text = fileHandle.read().splitlines()
        fileHandle.close()
        return text
    except IOError as error:
        print ("Read file error" +str(error))
        sys.exit()

if textfile1=="" or textfile2=="":
    print "Usage:diff_nginx.py filename1 filename2"
    sys.exit()

text1_file = readfile(textfile1)   #调用文件处理函数
text2_file = readfile(textfile2)

d = difflib.HtmlDiff()   #创建differ()对象
print d.make_file(text1_file,text2_file)


text:
//package org.scalatra
//package oauth2
//package auth
//
//import org.scalatra.liftjson.LiftJsonSupport
//import org.scalatra.auth.ScentryStrategy
//import scalaz._
//import Scalaz._
//import OAuth2Imports._
//
///**
//* Strategy for signing in a user, based on a token. This works for both params
//* and http headers. For the former, all you need to do is to pass the params in the URL:
//*
//*   http://myapp.example.com/?auth_token=SECRET
//*
//* For HTTP, you can pass the token as username and blank password. Since some clients may require
//* a password, you can pass "X" as password and it will simply be ignored.
//*/
//class AppTokenStrategy[UserClass <: AppUser[_]](
//    protected val app: ScalatraBase with LiftJsonSupport,
//    userProvider: UserProvider[UserClass],
//    tokenName: String = "auth_token",
//    headerModifier: String = "AuthToken") extends ScentryStrategy[UserClass] {
//
//
//
//  def authenticate(): Option[UserClass] = {
//
//  }
//
//
//  override def isValid: Boolean =
//    app.params.get(tokenName).isDefined ||
//    (app.request.providesAuth && app.request.authScheme == Some(headerModifier.toLowerCase))
//}


text:
package com.bnmi.ourmap.web.actions;

import com.bnmi.ourmap.control.EasyDelegate;
import com.bnmi.ourmap.model.Project;
import com.bnmi.ourmap.web.Constantes;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

/**
 *
 * @author Manuel Camilo Cuesta
 */
public class EditProject extends Action {

    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpSession session = request.getSession();
        EasyDelegate del = (EasyDelegate) session.getAttribute(Constantes.DELEGATE);
        EditProjectForm forma = (EditProjectForm) form;

        Project p = forma.getProject();
        del.updateProject(p);

        response.sendRedirect("listprojects.do");
        return null;
    }

}


text:
package com.helloandroid.app;

import android.app.Activity;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by scott on 15/9/5.
 */
public class TypeAdapter extends RecyclerView.Adapter<TypeAdapter.CardViewHolder> {

    private Activity activity;
    Config.TypeItem[] TYPE_ITEMS;

    public TypeAdapter(Activity activity, Config.TypeItem[] TYPE_ITEMS) {
        this.activity = activity;
        this.TYPE_ITEMS = TYPE_ITEMS;
    }

    @Override
    public CardViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(activity).inflate(R.layout.item_type, parent, false);
        v.setOnClickListener(clickListener);
        return new CardViewHolder(v);
    }

    @Override
    public void onBindViewHolder(CardViewHolder holder, int position) {
        holder.typeText.setText(TYPE_ITEMS[position].TITLE);
        holder.itemView.setTag(position);
    }

    @Override
    public int getItemCount() {
        return TYPE_ITEMS.length;
    }

    View.OnClickListener clickListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            int position = (int) v.getTag();
            Config.TypeItem typeItem = TYPE_ITEMS[position];
            if (typeItem.TARGET != null) {
                Intent intent = new Intent();
                intent.setClass(activity, typeItem.TARGET);
                activity.startActivity(intent);
            }
        }
    };

    public class CardViewHolder extends RecyclerView.ViewHolder {

        @Bind(R.id.type_text) TextView typeText;

        public CardViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }
}


text:
test_description="Test user-provided config values"

. lib/test-lib.sh

test_init_ipfs

test_expect_success "bootstrap doesn't overwrite user-provided config keys (top-level)" '
  ipfs config Foo.Bar baz &&
  ipfs bootstrap rm --all &&
  echo "baz" >expected &&
  ipfs config Foo.Bar >actual &&
  test_cmp expected actual
'

test_done


text:
singlequote
--------------

Transform all double quote strings in a piece of JavaScript code to single quoted strings

```
npm install singlequote
```

usage
-----
```js
var singlequote = require("singlequote");

function x(){
	return "hello\" I am a string's for sure";
}

var singleQuoteStringsCode = singlequote(x.toString())

//singleQuoteStringsCode will contain the string:
function x(){
	return 'hello" I am a string\'s for sure';
}
```

singlequote will throw an exception if the JavaScript code can not be parsed.

singlequote will throw an error if there is a bug in singlequote, that would produce invalid JavaScript code.

running singlequote on an entire directory of .js files
-------------------------------------------------------
Use the command line tool [jsq](https://github.com/Muscula/jsq)

License
-------
MIT


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

<title>ServerInterceptors.ForwardingListener (grpc-core 0.1.0-SNAPSHOT API)</title>
<meta name="date" content="2015-03-17">
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

io.grpc

Class ServerInterceptors.ForwardingListener<RespT>

java.lang.Object

io.grpc.ServerCall.Listener<RespT>

io.grpc.ServerInterceptors.ForwardingListener<RespT>

Enclosing class:

ServerInterceptors

public static class ServerInterceptors.ForwardingListener<RespT>
extends ServerCall.Listener<RespT>

Utility base class for decorating ServerCall.Listener instances.

Constructor Summary

Constructors

Constructor and Description

ServerInterceptors.ForwardingListener(ServerCall.Listener<RespT> delegate)

Method Summary

Methods

Modifier and Type
Method and Description

void
onCancel()

The call was cancelled and the server is encouraged to abort processing to save resources,
 since the client will not process any further messages.

void
onComplete()

The call is considered complete and ServerCall.Listener.onCancel() is guaranteed not to be called.

void
onHalfClose()

The client completed all message sending.

void
onPayload(RespT payload)

A request message has been received.

void
onReady(int numMessages)

This indicates that the call is now capable of sending the given number of messages (via
 ServerCall.sendPayload(ResponseT)) without requiring excessive buffering internally.

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

ServerInterceptors.ForwardingListener

public ServerInterceptors.ForwardingListener(ServerCall.Listener<RespT> delegate)

Method Detail

onPayload

public void onPayload(RespT payload)

Description copied from class: ServerCall.Listener

A request message has been received. For streaming calls, there may be zero or more request
 messages.

Specified by:

onPayload in class ServerCall.Listener<RespT>

Parameters:

payload - a received request message.

onHalfClose

public void onHalfClose()

Description copied from class: ServerCall.Listener

The client completed all message sending. However, the call may still be cancelled.

Specified by:

onHalfClose in class ServerCall.Listener<RespT>

onCancel

public void onCancel()

Description copied from class: ServerCall.Listener

The call was cancelled and the server is encouraged to abort processing to save resources,
 since the client will not process any further messages. Cancellations can be caused by
 timeouts, explicit cancellation by the client, network errors, etc.

There will be no further callbacks for the call.

Specified by:

onCancel in class ServerCall.Listener<RespT>

onComplete

public void onComplete()

Description copied from class: ServerCall.Listener

The call is considered complete and ServerCall.Listener.onCancel() is guaranteed not to be called.
 However, the client is not guaranteed to have received all messages.

There will be no further callbacks for the call.

Specified by:

onComplete in class ServerCall.Listener<RespT>

onReady

public void onReady(int numMessages)

Description copied from class: ServerCall.Listener

This indicates that the call is now capable of sending the given number of messages (via
 ServerCall.sendPayload(ResponseT)) without requiring excessive buffering internally. This event is
 just a suggestion and the application is free to ignore it, however doing so may
 result in excessive buffering within the call.

NOTE: this method is not yet implemented!

Overrides:

onReady in class ServerCall.Listener<RespT>

Parameters:

numMessages - the number of messages that can be sent without requiring excessive
        buffering.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
MyQuad::MyQuad(MyIndexedVertexArray *vertexArray, MyVector3D & position, MyVector3D & scale, MyVector3D & rotation) :
	MyGraphicsObject3D(vertexArray, position, scale, rotation)
{
}

MyQuad::~MyQuad()
{
}


text:
I welcome contributions to the project. Please open an issue or send a pull
request.

## Documentation and wording mistakes

Since english is not my first language, the comments and documentation may be
difficult to understand and/or have spelling mistakes. Feel free to open an
issue or send a pull request to fix them.

## Code of Conduct

Please follow [Rust's code of conduct][coc] when interacting in this repository.

[coc]: https://www.rust-lang.org/en-US/conduct.html


text:
#ifndef __vvTrackInfo_h
#define __vvTrackInfo_h

#include <QString>
#include <QList>

#include <vgExport.h>

#include <vtkVgTrack.h>

#include <vgColor.h>

struct VV_VTKWIDGETS_EXPORT vvTrackInfo
{
  vvTrackInfo();
  explicit vvTrackInfo(vtkVgTrack::enumTrackPVOType);

  /// Save track information to settings.
  ///
  /// This saves the track information held by this structure to the user's
  /// configuration.
  bool write() const;

  int Source;
  vtkVgTrack::enumTrackPVOType Type;
  QString Name;
  vgColor PenColor;
  vgColor ForegroundColor;
  vgColor BackgroundColor;

public:
  static bool getTrackType(vvTrackInfo& ti, vtkVgTrack::enumTrackPVOType type);
  static bool getTrackSource(vvTrackInfo& ti, int source);

  /// Read per-type track information from settings.
  ///
  /// This returns a list of vvTrackInfo structures describing possible track
  /// classifications. The information is read from the user's configuration,
  /// using a set of 'canned' default values.
  static QList<vvTrackInfo> trackTypes();

  /// Read per-source track information from settings.
  ///
  /// This returns a list of vvTrackInfo structures describing possible track
  /// sources. The information is read from the user's configuration. There are
  /// no default track sources; if the user has not configured any track
  /// sources, this list will be empty.
  static QList<vvTrackInfo> trackSources();

  /// Remove a track source from settings.
  ///
  /// This erases the user configuration keys for the specified track source,
  /// so that it is no longer returned by trackSources().
  static void eraseTrackSource(int source);
};

#endif


text:
"""Test the flow_management interface."""

import os

from grr.gui import gui_test_lib
from grr.gui import runtests_test

from grr.lib import action_mocks
from grr.lib import aff4
from grr.lib import flags
from grr.lib import flow
from grr.lib import hunts
from grr.lib import test_lib
from grr.lib.flows.general import filesystem as flows_filesystem
from grr.lib.flows.general import processes as flows_processes
from grr.lib.flows.general import transfer as flows_transfer
from grr.lib.flows.general import webhistory as flows_webhistory
from grr.lib.hunts import standard
from grr.lib.hunts import standard_test
from grr.lib.rdfvalues import client as rdf_client
from grr.lib.rdfvalues import flows as rdf_flows
from grr.lib.rdfvalues import paths as rdf_paths

class TestFlowManagement(gui_test_lib.GRRSeleniumTest,
                         standard_test.StandardHuntTestMixin):
  """Test the flow management GUI."""

  def setUp(self):
    super(TestFlowManagement, self).setUp()

    with self.ACLChecksDisabled():
      self.client_id = rdf_client.ClientURN("C.0000000000000001")
      with aff4.FACTORY.Open(
          self.client_id, mode="rw", token=self.token) as client:
        client.Set(client.Schema.HOSTNAME("HostC.0000000000000001"))
      self.RequestAndGrantClientApproval(self.client_id)
      self.action_mock = action_mocks.FileFinderClientMock()

  def testOpeningManageFlowsOfUnapprovedClientRedirectsToHostInfoPage(self):
    self.Open("/#/clients/C.0000000000000002/flows/")

    # As we don't have an approval for C.0000000000000002, we should be
    # redirected to the host info page.
    self.WaitUntilEqual("/#/clients/C.0000000000000002/host-info",
                        self.GetCurrentUrlPath)
    self.WaitUntil(self.IsTextPresent,
                   "You do not have an approval for this client.")

  def testPageTitleReflectsSelectedFlow(self):
    pathspec = rdf_paths.PathSpec(
        path=os.path.join(self.base_path, "test.plist"),
        pathtype=rdf_paths.PathSpec.PathType.OS)
    flow_urn = flow.GRRFlow.StartFlow(
        flow_name=flows_transfer.GetFile.__name__,
        client_id=self.client_id,
        pathspec=pathspec,
        token=self.token)

    self.Open("/#/clients/C.0000000000000001/flows/")
    self.WaitUntilEqual("GRR | C.0000000000000001 | Flows", self.GetPageTitle)

    self.Click("css=td:contains('GetFile')")
    self.WaitUntilEqual("GRR | C.0000000000000001 | " + flow_urn.Basename(),
                        self.GetPageTitle)

  def testFlowManagement(self):
    """Test that scheduling flows works."""
    self.Open("/")

    self.Type("client_query", "C.0000000000000001")
    self.Click("client_query_submit")

    self.WaitUntilEqual(u"C.0000000000000001", self.GetText,
                        "css=span[type=subject]")

    # Choose client 1
    self.Click("css=td:contains('0001')")

    # First screen should be the Host Information already.
    self.WaitUntil(self.IsTextPresent, "HostC.0000000000000001")

    self.Click("css=a[grrtarget='client.launchFlows']")
    self.Click("css=#_Processes")
    self.Click("link=" + flows_processes.ListProcesses.__name__)
    self.WaitUntil(self.IsTextPresent, "C.0000000000000001")

    self.WaitUntil(self.IsTextPresent, "List running processes on a system.")

    self.Click("css=button.Launch")
    self.WaitUntil(self.IsTextPresent, "Launched Flow ListProcesses")

    self.Click("css=#_Browser")
    # Wait until the tree has expanded.
    self.WaitUntil(self.IsTextPresent, flows_webhistory.FirefoxHistory.__name__)

    # Check that we can get a file in chinese
    self.Click("css=#_Filesystem")

    # Wait until the tree has expanded.
    self.WaitUntil(self.IsTextPresent,
                   flows_filesystem.UpdateSparseImageChunks.__name__)

    self.Click("link=" + flows_transfer.GetFile.__name__)

    self.Select("css=.form-group:has(> label:contains('Pathtype')) select",
                "OS")
    self.Type("css=.form-group:has(> label:contains('Path')) input",
              u"/dev/c/msn[1].exe")

    self.Click("css=button.Launch")

    self.WaitUntil(self.IsTextPresent, "Launched Flow GetFile")

    # Test that recursive tests are shown in a tree table.
    with self.ACLChecksDisabled():
      flow.GRRFlow.StartFlow(
          client_id="aff4:/C.0000000000000001",
          flow_name=gui_test_lib.RecursiveTestFlow.__name__,
          token=self.token)

    self.Click("css=a[grrtarget='client.flows']")

    # Some rows are present in the DOM but hidden because parent flow row
    # wasn't expanded yet. Due to this, we have to explicitly filter rows
    # with "visible" jQuery filter.
    self.WaitUntilEqual("RecursiveTestFlow", self.GetText,
                        "css=grr-client-flows-list tr:visible:nth(1) td:nth(2)")

    self.WaitUntilEqual("GetFile", self.GetText,
                        "css=grr-client-flows-list tr:visible:nth(2) td:nth(2)")

    # Click on the first tree_closed to open it.
    self.Click("css=grr-client-flows-list tr:visible:nth(1) .tree_closed")

    self.WaitUntilEqual("RecursiveTestFlow", self.GetText,
                        "css=grr-client-flows-list tr:visible:nth(2) td:nth(2)")

    # Select the requests tab
    self.Click("css=td:contains(GetFile)")
    self.Click("css=li[heading=Requests]")

    self.WaitUntil(self.IsElementPresent,
                   "css=td:contains(flow:request:00000001)")

    # Check that a StatFile client action was issued as part of the GetFile
    # flow.
    self.WaitUntil(self.IsElementPresent,
                   "css=.tab-content td.proto_value:contains(StatFile)")

  def testOverviewIsShownForNestedFlows(self):
    with self.ACLChecksDisabled():
      for _ in test_lib.TestFlowHelper(
          gui_test_lib.RecursiveTestFlow.__name__,
          self.action_mock,
          client_id=self.client_id,
          token=self.token):
        pass

    self.Open("/#c=C.0000000000000001")
    self.Click("css=a[grrtarget='client.flows']")

    # There should be a RecursiveTestFlow in the list. Expand nested flows.
    self.Click("css=tr:contains('RecursiveTestFlow') span.tree_branch")
    # Click on a nested flow.
    self.Click("css=tr:contains('RecursiveTestFlow'):nth(2)")

    # Nested flow should have Depth argument set to 1.
    self.WaitUntil(self.IsElementPresent,
                   "css=td:contains('Depth') ~ td:nth(0):contains('1')")

    # Check that flow id of this flow has forward slash - i.e. consists of
    # 2 components.
    self.WaitUntil(self.IsTextPresent, "Flow ID")
    flow_id = self.GetText("css=dt:contains('Flow ID') ~ dd:nth(0)")
    self.assertTrue("/" in flow_id)

  def testOverviewIsShownForNestedHuntFlows(self):
    with self.ACLChecksDisabled():
      with hunts.GRRHunt.StartHunt(
          hunt_name=standard.GenericHunt.__name__,
          flow_runner_args=rdf_flows.FlowRunnerArgs(
              flow_name=gui_test_lib.RecursiveTestFlow.__name__),
          client_rate=0,
          token=self.token) as hunt:
        hunt.Run()

      self.AssignTasksToClients(client_ids=[self.client_id])
      self.RunHunt(client_ids=[self.client_id])

    self.Open("/#c=C.0000000000000001")
    self.Click("css=a[grrtarget='client.flows']")

    # There should be a RecursiveTestFlow in the list. Expand nested flows.
    self.Click("css=tr:contains('RecursiveTestFlow') span.tree_branch")
    # Click on a nested flow.
    self.Click("css=tr:contains('RecursiveTestFlow'):nth(2)")

    # Nested flow should have Depth argument set to 1.
    self.WaitUntil(self.IsElementPresent,
                   "css=td:contains('Depth') ~ td:nth(0):contains('1')")

    # Check that flow id of this flow has forward slash - i.e. consists of
    # 2 components.
    self.WaitUntil(self.IsTextPresent, "Flow ID")
    flow_id = self.GetText("css=dt:contains('Flow ID') ~ dd:nth(0)")
    self.assertTrue("/" in flow_id)

  def testLogsCanBeOpenedByClickingOnLogsTab(self):
    # RecursiveTestFlow doesn't send any results back.
    with self.ACLChecksDisabled():
      for _ in test_lib.TestFlowHelper(
          "FlowWithOneLogStatement",
          self.action_mock,
          client_id=self.client_id,
          token=self.token):
        pass

    self.Open("/#c=C.0000000000000001")
    self.Click("css=a[grrtarget='client.flows']")
    self.Click("css=td:contains('FlowWithOneLogStatement')")
    self.Click("css=li[heading=Log]")

    self.WaitUntil(self.IsTextPresent, "I do log.")

  def testLogTimestampsArePresentedInUTC(self):
    with self.ACLChecksDisabled():
      with test_lib.FakeTime(42):
        for _ in test_lib.TestFlowHelper(
            "FlowWithOneLogStatement",
            self.action_mock,
            client_id=self.client_id,
            token=self.token):
          pass

    self.Open("/#c=C.0000000000000001")
    self.Click("css=a[grrtarget='client.flows']")
    self.Click("css=td:contains('FlowWithOneLogStatement')")
    self.Click("css=li[heading=Log]")

    self.WaitUntil(self.IsTextPresent, "1970-01-01 00:00:42 UTC")

  def testResultsAreDisplayedInResultsTab(self):
    with self.ACLChecksDisabled():
      for _ in test_lib.TestFlowHelper(
          "FlowWithOneStatEntryResult",
          self.action_mock,
          client_id=self.client_id,
          token=self.token):
        pass

    self.Open("/#c=C.0000000000000001")
    self.Click("css=a[grrtarget='client.flows']")
    self.Click("css=td:contains('FlowWithOneStatEntryResult')")
    self.Click("css=li[heading=Results]")

    self.WaitUntil(self.IsTextPresent,
                   "aff4:/C.0000000000000001/fs/os/some/unique/path")

  def testEmptyTableIsDisplayedInResultsWhenNoResults(self):
    with self.ACLChecksDisabled():
      flow.GRRFlow.StartFlow(
          flow_name="FlowWithOneStatEntryResult",
          client_id=self.client_id,
          sync=False,
          token=self.token)

    self.Open("/#c=" + self.client_id.Basename())
    self.Click("css=a[grrtarget='client.flows']")
    self.Click("css=td:contains('FlowWithOneStatEntryResult')")
    self.Click("css=li[heading=Results]")

    self.WaitUntil(self.IsElementPresent, "css=#main_bottomPane table thead "
                   "th:contains('Value')")

  def testHashesAreDisplayedCorrectly(self):
    with self.ACLChecksDisabled():
      for _ in test_lib.TestFlowHelper(
          "FlowWithOneHashEntryResult",
          self.action_mock,
          client_id=self.client_id,
          token=self.token):
        pass

    self.Open("/#c=C.0000000000000001")
    self.Click("css=a[grrtarget='client.flows']")
    self.Click("css=td:contains('FlowWithOneHashEntryResult')")
    self.Click("css=li[heading=Results]")

    self.WaitUntil(self.IsTextPresent,
                   "9e8dc93e150021bb4752029ebbff51394aa36f069cf19901578"
                   "e4f06017acdb5")
    self.WaitUntil(self.IsTextPresent,
                   "6dd6bee591dfcb6d75eb705405302c3eab65e21a")
    self.WaitUntil(self.IsTextPresent, "8b0a15eefe63fd41f8dc9dee01c5cf9a")

  def testChangingTabUpdatesUrl(self):
    with self.ACLChecksDisabled():
      flow_urn = flow.GRRFlow.StartFlow(
          flow_name=gui_test_lib.FlowWithOneStatEntryResult.__name__,
          client_id=self.client_id,
          token=self.token)

    flow_id = flow_urn.Basename()
    base_url = "/#/clients/C.0000000000000001/flows/%s" % flow_id

    self.Open(base_url)

    self.Click("css=li[heading=Requests]")
    self.WaitUntilEqual(base_url + "/requests", self.GetCurrentUrlPath)

    self.Click("css=li[heading=Results]")
    self.WaitUntilEqual(base_url + "/results", self.GetCurrentUrlPath)

    self.Click("css=li[heading=Log]")
    self.WaitUntilEqual(base_url + "/log", self.GetCurrentUrlPath)

    self.Click("css=li[heading='Flow Information']")
    self.WaitUntilEqual(base_url, self.GetCurrentUrlPath)

  def testDirectLinksToFlowsTabsWorkCorrectly(self):
    with self.ACLChecksDisabled():
      flow_urn = flow.GRRFlow.StartFlow(
          flow_name=gui_test_lib.FlowWithOneStatEntryResult.__name__,
          client_id=self.client_id,
          token=self.token)

    flow_id = flow_urn.Basename()
    base_url = "/#/clients/C.0000000000000001/flows/%s" % flow_id

    self.Open(base_url + "/requests")
    self.WaitUntil(self.IsElementPresent, "css=li.active[heading=Requests]")

    self.Open(base_url + "/results")
    self.WaitUntil(self.IsElementPresent, "css=li.active[heading=Results]")

    self.Open(base_url + "/log")
    self.WaitUntil(self.IsElementPresent, "css=li.active[heading=Log]")

    # Check that both clients/.../flows/... and clients/.../flows/.../ URLs
    # work.
    self.Open(base_url)
    self.WaitUntil(self.IsElementPresent,
                   "css=li.active[heading='Flow Information']")

    self.Open(base_url + "/")
    self.WaitUntil(self.IsElementPresent,
                   "css=li.active[heading='Flow Information']")

  def testCancelFlowWorksCorrectly(self):
    """Tests that cancelling flows works."""
    flow.GRRFlow.StartFlow(
        client_id=self.client_id,
        flow_name=gui_test_lib.RecursiveTestFlow.__name__,
        token=self.token)

    # Open client and find the flow
    self.Open("/")

    self.Type("client_query", "C.0000000000000001")
    self.Click("client_query_submit")

    self.WaitUntilEqual(u"C.0000000000000001", self.GetText,
                        "css=span[type=subject]")
    self.Click("css=td:contains('0001')")
    self.Click("css=a[grrtarget='client.flows']")

    self.Click("css=td:contains('RecursiveTestFlow')")
    self.Click("css=button[name=cancel_flow]")

    # The window should be updated now
    self.WaitUntil(self.IsTextPresent, "Cancelled in GUI")

  def testGlobalFlowManagement(self):
    """Test that scheduling flows works."""
    with self.ACLChecksDisabled():
      self.CreateAdminUser(self.token.username)

    self.Open("/")

    self.Click("css=a[grrtarget=globalFlows]")
    self.Click("css=#_Reporting")

    self.assertEqual("RunReport", self.GetText("link=RunReport"))
    self.Click("link=RunReport")
    self.WaitUntil(self.IsTextPresent, "Report name")

def main(argv):
  # Run the full test suite
  runtests_test.SeleniumTestProgram(argv=argv)

if __name__ == "__main__":
  flags.StartMain(main)


text:
using Midori.Runtime;
using System;
using System.Collections.Generic;
using System.Threading;

namespace BenchmarkRegionCreation
{

  public class BenchmarkRegionCreation
  {

    public static void Print(Int64 cycles)
    {
      Int64 frequency = RegionAllocator.NativeGetPerformanceFrequency();
      Console.WriteLine("Cycles: {0}\n", cycles);
      cycles *= 1000000000;
      double duration = (double)cycles / (double)frequency;
      Console.WriteLine("Time(ns): {0}\n", duration);
    }

    public static void Print(double cycles)
    {
      Int64 frequency = RegionAllocator.NativeGetPerformanceFrequency();
      Console.WriteLine("Cycles: {0}\n", cycles);
      cycles *= 1000000000.0;
      double duration = cycles / (double)frequency;
      Console.WriteLine("Time(ns): {0}\n", duration);
    }

    public static void Main(string[] args)
    {
      if (args.Length != 2)
      {
        Console.WriteLine("Unexpected number of arguments. Please specify: size_of_region, num_repetitions");
        return;
      }
      RegionAllocator.Initialize();
      uint size_of_region = (uint)Convert.ToInt32(args[0]);
      int num_repetitions = Convert.ToInt32(args[1]);
      Int64 start;
      Int64 end;
      Int64 cycles = 0;
      for (int i = 0; i < num_repetitions; ++i)
      {
        Region region = RegionAllocator.AllocateRegion(size_of_region);
        start = RegionAllocator.NativeGetPerformanceCounter();
        RegionAllocator.FreeRegion(region);
        end = RegionAllocator.NativeGetPerformanceCounter();
        cycles += end - start;
      }
      Print(cycles / num_repetitions);
    }

  }

}


text:
layout: media
title: "Beauty is in the moment"
excerpt: "PaperFaces portrait commission drawn with Paper by 53 on an iPad."
image:
  feature: paperfaces-beauty-profile-lg.jpg
  thumb: paperfaces-beauty-profile-150.jpg
category: paperfaces
tags: [portrait, illustration, paper by 53, blend, bokeh]
---

PaperFaces portrait commission. *Beauty is in the moment, not the image.*

{% include paperfaces-boilerplate-4.html %}

Work in progress screen captures Made with Paper.


text:
Elixir Bencode
==============

Bencode decoder / encoder using Elixir data structures.

[Documentation for Elixir Bencode is available online](http://hexdocs.pm/elixir_bencode/)

## Installation
Add it to to your `mix.exs` dependencies:

```elixir
defp deps do
  [{:elixir_bencode, "~> 1.0.0"}]
end
```

## Examples
```elixir
## Encode strings (with thrown exceptions)
Bencode.encode!("hello world")
"11:hello world"

## Encode integers
Bencode.encode!(42)
"i42e"

## Encode lists
Bencode.encode!([1,2,3])
"li1ei2ei3ee"

## Encode maps
Bencode.encode!(%{"a" => 1, 2 => "b"})
#"di2e1:b1:ai1ee"

## Encode Dicts
Bencode.encode!(HashDict.new |> Dict.put :hello, :world)
"d5:hello5:worlde"

## Encode bitstrings
Bencode.encode!(<<1,2,3,4>>)
<<52, 58, 1, 2, 3, 4>>

## Encode without exceptions
Bencode.encode(2.0)
{:error, :invalid_format}

## Decode strings (with thrown expcetions)
Bencode.decode!("5:hello")
"hello"

## Decode integers
Bencode.decode!("i42e")
42

## Decode lists
Bencode.decode!("li1ei2ei3ee")
[1, 2, 3]

## Decode maps
Bencode.decode!("d5:hello5:worlde")
%{"hello" => "world"}

## Decode without exceptions
Bencode.decode("4:spam")
{:ok, "spam"}
```

## Copyright

Copyright (c) 2014 Anton Fagerberg. See [LICENSE](LICENSE) for further details


text:
package com.omiplekevin.android.f45testbench.timelinehelper;

import com.google.gson.annotations.SerializedName;

import java.io.Serializable;
import java.util.Map;

/**
 * Created by Fatima Ledesma on 9/8/2015.
 */
public class Data implements Serializable {

    @SerializedName("id")
    public int id;

    @SerializedName("title")
    public String title;

    @SerializedName("timestamp")
    public String timestamp;

    @SerializedName("timeline")
    public Map<Integer, Timeline> timeline;

}


text:
"""Tests for utilities working with arbitrarily nested structures."""

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

import collections

import numpy as np

from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.platform import test
from tensorflow.python.util import nest

class NestTest(test.TestCase):

  def testFlattenAndPack(self):
    structure = ((3, 4), 5, (6, 7, (9, 10), 8))
    flat = ["a", "b", "c", "d", "e", "f", "g", "h"]
    self.assertEqual(nest.flatten(structure), [3, 4, 5, 6, 7, 9, 10, 8])
    self.assertEqual(
        nest.pack_sequence_as(structure, flat), (("a", "b"), "c",
                                                 ("d", "e", ("f", "g"), "h")))
    point = collections.namedtuple("Point", ["x", "y"])
    structure = (point(x=4, y=2), ((point(x=1, y=0),),))
    flat = [4, 2, 1, 0]
    self.assertEqual(nest.flatten(structure), flat)
    restructured_from_flat = nest.pack_sequence_as(structure, flat)
    self.assertEqual(restructured_from_flat, structure)
    self.assertEqual(restructured_from_flat[0].x, 4)
    self.assertEqual(restructured_from_flat[0].y, 2)
    self.assertEqual(restructured_from_flat[1][0][0].x, 1)
    self.assertEqual(restructured_from_flat[1][0][0].y, 0)

    self.assertEqual([5], nest.flatten(5))
    self.assertEqual([np.array([5])], nest.flatten(np.array([5])))

    self.assertEqual("a", nest.pack_sequence_as(5, ["a"]))
    self.assertEqual(
        np.array([5]), nest.pack_sequence_as("scalar", [np.array([5])]))

    with self.assertRaisesRegexp(ValueError, "Structure is a scalar"):
      nest.pack_sequence_as("scalar", [4, 5])

    with self.assertRaisesRegexp(TypeError, "flat_sequence"):
      nest.pack_sequence_as([4, 5], "bad_sequence")

    with self.assertRaises(ValueError):
      nest.pack_sequence_as([5, 6, [7, 8]], ["a", "b", "c"])

  def testFlattenDictOrder(self):
    """`flatten` orders dicts by key, including OrderedDicts."""
    ordered = collections.OrderedDict([("d", 3), ("b", 1), ("a", 0), ("c", 2)])
    plain = {"d": 3, "b": 1, "a": 0, "c": 2}
    ordered_flat = nest.flatten(ordered)
    plain_flat = nest.flatten(plain)
    self.assertEqual([0, 1, 2, 3], ordered_flat)
    self.assertEqual([0, 1, 2, 3], plain_flat)

  def testPackDictOrder(self):
    """Packing orders dicts by key, including OrderedDicts."""
    ordered = collections.OrderedDict([("d", 0), ("b", 0), ("a", 0), ("c", 0)])
    plain = {"d": 0, "b": 0, "a": 0, "c": 0}
    seq = [0, 1, 2, 3]
    ordered_reconstruction = nest.pack_sequence_as(ordered, seq)
    plain_reconstruction = nest.pack_sequence_as(plain, seq)
    self.assertEqual(
        collections.OrderedDict([("d", 3), ("b", 1), ("a", 0), ("c", 2)]),
        ordered_reconstruction)
    self.assertEqual({"d": 3, "b": 1, "a": 0, "c": 2}, plain_reconstruction)

  def testFlattenAndPack_withDicts(self):
    # A nice messy mix of tuples, lists, dicts, and `OrderedDict`s.
    named_tuple = collections.namedtuple("A", ("b", "c"))
    mess = [
        "z",
        named_tuple(3, 4),
        {
            "c": [
                1,
                collections.OrderedDict([
                    ("b", 3),
                    ("a", 2),
                ]),
            ],
            "b": 5
        },
        17
    ]

    flattened = nest.flatten(mess)
    self.assertEqual(flattened, ["z", 3, 4, 5, 1, 2, 3, 17])

    structure_of_mess = [
        14,
        named_tuple("a", True),
        {
            "c": [
                0,
                collections.OrderedDict([
                    ("b", 9),
                    ("a", 8),
                ]),
            ],
            "b": 3
        },
        "hi everybody",
    ]

    unflattened = nest.pack_sequence_as(structure_of_mess, flattened)
    self.assertEqual(unflattened, mess)

    # Check also that the OrderedDict was created, with the correct key order.
    unflattened_ordered_dict = unflattened[2]["c"][1]
    self.assertIsInstance(unflattened_ordered_dict, collections.OrderedDict)
    self.assertEqual(list(unflattened_ordered_dict.keys()), ["b", "a"])

  def testFlatten_numpyIsNotFlattened(self):
    structure = np.array([1, 2, 3])
    flattened = nest.flatten(structure)
    self.assertEqual(len(flattened), 1)

  def testFlatten_stringIsNotFlattened(self):
    structure = "lots of letters"
    flattened = nest.flatten(structure)
    self.assertEqual(len(flattened), 1)
    unflattened = nest.pack_sequence_as("goodbye", flattened)
    self.assertEqual(structure, unflattened)

  def testPackSequenceAs_notIterableError(self):
    with self.assertRaisesRegexp(TypeError,
                                 "flat_sequence must be a sequence"):
      nest.pack_sequence_as("hi", "bye")

  def testPackSequenceAs_wrongLengthsError(self):
    with self.assertRaisesRegexp(
        ValueError,
        "Structure had 2 elements, but flat_sequence had 3 elements."):
      nest.pack_sequence_as(["hello", "world"],
                            ["and", "goodbye", "again"])

  def testIsSequence(self):
    self.assertFalse(nest.is_sequence("1234"))
    self.assertTrue(nest.is_sequence([1, 3, [4, 5]]))
    self.assertTrue(nest.is_sequence(((7, 8), (5, 6))))
    self.assertTrue(nest.is_sequence([]))
    self.assertTrue(nest.is_sequence({"a": 1, "b": 2}))
    self.assertFalse(nest.is_sequence(set([1, 2])))
    ones = array_ops.ones([2, 3])
    self.assertFalse(nest.is_sequence(ones))
    self.assertFalse(nest.is_sequence(math_ops.tanh(ones)))
    self.assertFalse(nest.is_sequence(np.ones((4, 5))))

  def testFlattenDictItems(self):
    dictionary = {(4, 5, (6, 8)): ("a", "b", ("c", "d"))}
    flat = {4: "a", 5: "b", 6: "c", 8: "d"}
    self.assertEqual(nest.flatten_dict_items(dictionary), flat)

    with self.assertRaises(TypeError):
      nest.flatten_dict_items(4)

    bad_dictionary = {(4, 5, (4, 8)): ("a", "b", ("c", "d"))}
    with self.assertRaisesRegexp(ValueError, "not unique"):
      nest.flatten_dict_items(bad_dictionary)

    another_bad_dictionary = {(4, 5, (6, 8)): ("a", "b", ("c", ("d", "e")))}
    with self.assertRaisesRegexp(
        ValueError, "Key had [0-9]* elements, but value had [0-9]* elements"):
      nest.flatten_dict_items(another_bad_dictionary)

  def testAssertSameStructure(self):
    structure1 = (((1, 2), 3), 4, (5, 6))
    structure2 = ((("foo1", "foo2"), "foo3"), "foo4", ("foo5", "foo6"))
    structure_different_num_elements = ("spam", "eggs")
    structure_different_nesting = (((1, 2), 3), 4, 5, (6,))
    nest.assert_same_structure(structure1, structure2)
    nest.assert_same_structure("abc", 1.0)
    nest.assert_same_structure("abc", np.array([0, 1]))
    nest.assert_same_structure("abc", constant_op.constant([0, 1]))

    with self.assertRaisesRegexp(
        ValueError,
        ("don't have the same number of elements\\.\n\n"
         "First structure \\(6 elements\\):.*?"
         "\n\nSecond structure \\(2 elements\\):")):
      nest.assert_same_structure(structure1, structure_different_num_elements)

    with self.assertRaisesRegexp(
        ValueError,
        ("don't have the same number of elements\\.\n\n"
         "First structure \\(2 elements\\):.*?"
         "\n\nSecond structure \\(1 elements\\):")):
      nest.assert_same_structure([0, 1], np.array([0, 1]))

    with self.assertRaisesRegexp(
        ValueError,
        ("don't have the same number of elements\\.\n\n"
         "First structure \\(1 elements\\):.*"
         "\n\nSecond structure \\(2 elements\\):")):
      nest.assert_same_structure(0, [0, 1])

    self.assertRaises(TypeError, nest.assert_same_structure, (0, 1), [0, 1])

    with self.assertRaisesRegexp(
        ValueError,
        ("don't have the same nested structure\\.\n\n"
         "First structure: .*?\n\nSecond structure: ")):
      nest.assert_same_structure(structure1, structure_different_nesting)

    named_type_0 = collections.namedtuple("named_0", ("a", "b"))
    named_type_1 = collections.namedtuple("named_1", ("a", "b"))
    self.assertRaises(TypeError, nest.assert_same_structure, (0, 1),
                      named_type_0("a", "b"))

    nest.assert_same_structure(named_type_0(3, 4), named_type_0("a", "b"))

    self.assertRaises(TypeError, nest.assert_same_structure,
                      named_type_0(3, 4), named_type_1(3, 4))

    with self.assertRaisesRegexp(
        ValueError,
        ("don't have the same nested structure\\.\n\n"
         "First structure: .*?\n\nSecond structure: ")):
      nest.assert_same_structure(named_type_0(3, 4), named_type_0([3], 4))

    with self.assertRaisesRegexp(
        ValueError,
        ("don't have the same nested structure\\.\n\n"
         "First structure: .*?\n\nSecond structure: ")):
      nest.assert_same_structure([[3], 4], [3, [4]])

    structure1_list = [[[1, 2], 3], 4, [5, 6]]
    with self.assertRaisesRegexp(TypeError,
                                 "don't have the same sequence type"):
      nest.assert_same_structure(structure1, structure1_list)
    nest.assert_same_structure(structure1, structure2, check_types=False)
    nest.assert_same_structure(structure1, structure1_list, check_types=False)

    with self.assertRaisesRegexp(ValueError,
                                 "don't have the same set of keys"):
      nest.assert_same_structure({"a": 1}, {"b": 1})

  def testMapStructure(self):
    structure1 = (((1, 2), 3), 4, (5, 6))
    structure2 = (((7, 8), 9), 10, (11, 12))
    structure1_plus1 = nest.map_structure(lambda x: x + 1, structure1)
    nest.assert_same_structure(structure1, structure1_plus1)
    self.assertAllEqual(
        [2, 3, 4, 5, 6, 7],
        nest.flatten(structure1_plus1))
    structure1_plus_structure2 = nest.map_structure(
        lambda x, y: x + y, structure1, structure2)
    self.assertEqual(
        (((1 + 7, 2 + 8), 3 + 9), 4 + 10, (5 + 11, 6 + 12)),
        structure1_plus_structure2)

    self.assertEqual(3, nest.map_structure(lambda x: x - 1, 4))

    self.assertEqual(7, nest.map_structure(lambda x, y: x + y, 3, 4))

    # Empty structures
    self.assertEqual((), nest.map_structure(lambda x: x + 1, ()))
    self.assertEqual([], nest.map_structure(lambda x: x + 1, []))
    self.assertEqual({}, nest.map_structure(lambda x: x + 1, {}))
    empty_nt = collections.namedtuple("empty_nt", "")
    self.assertEqual(empty_nt(), nest.map_structure(lambda x: x + 1,
                                                    empty_nt()))

    # This is checking actual equality of types, empty list != empty tuple
    self.assertNotEqual((), nest.map_structure(lambda x: x + 1, []))

    with self.assertRaisesRegexp(TypeError, "callable"):
      nest.map_structure("bad", structure1_plus1)

    with self.assertRaisesRegexp(ValueError, "at least one structure"):
      nest.map_structure(lambda x: x)

    with self.assertRaisesRegexp(ValueError, "same number of elements"):
      nest.map_structure(lambda x, y: None, (3, 4), (3, 4, 5))

    with self.assertRaisesRegexp(ValueError, "same nested structure"):
      nest.map_structure(lambda x, y: None, 3, (3,))

    with self.assertRaisesRegexp(TypeError, "same sequence type"):
      nest.map_structure(lambda x, y: None, ((3, 4), 5), [(3, 4), 5])

    with self.assertRaisesRegexp(ValueError, "same nested structure"):
      nest.map_structure(lambda x, y: None, ((3, 4), 5), (3, (4, 5)))

    structure1_list = [[[1, 2], 3], 4, [5, 6]]
    with self.assertRaisesRegexp(TypeError, "same sequence type"):
      nest.map_structure(lambda x, y: None, structure1, structure1_list)

    nest.map_structure(lambda x, y: None, structure1, structure1_list,
                       check_types=False)

    with self.assertRaisesRegexp(ValueError, "same nested structure"):
      nest.map_structure(lambda x, y: None, ((3, 4), 5), (3, (4, 5)),
                         check_types=False)

    with self.assertRaisesRegexp(ValueError, "Only valid keyword argument"):
      nest.map_structure(lambda x: None, structure1, foo="a")

    with self.assertRaisesRegexp(ValueError, "Only valid keyword argument"):
      nest.map_structure(lambda x: None, structure1, check_types=False, foo="a")

  def testMapStructureWithStrings(self):
    ab_tuple = collections.namedtuple("ab_tuple", "a, b")
    inp_a = ab_tuple(a="foo", b=("bar", "baz"))
    inp_b = ab_tuple(a=2, b=(1, 3))
    out = nest.map_structure(lambda string, repeats: string * repeats,
                             inp_a,
                             inp_b)
    self.assertEqual("foofoo", out.a)
    self.assertEqual("bar", out.b[0])
    self.assertEqual("bazbazbaz", out.b[1])

    nt = ab_tuple(a=("something", "something_else"),
                  b="yet another thing")
    rev_nt = nest.map_structure(lambda x: x[::-1], nt)
    # Check the output is the correct structure, and all strings are reversed.
    nest.assert_same_structure(nt, rev_nt)
    self.assertEqual(nt.a[0][::-1], rev_nt.a[0])
    self.assertEqual(nt.a[1][::-1], rev_nt.a[1])
    self.assertEqual(nt.b[::-1], rev_nt.b)

  def testMapStructureOverPlaceholders(self):
    inp_a = (array_ops.placeholder(dtypes.float32, shape=[3, 4]),
             array_ops.placeholder(dtypes.float32, shape=[3, 7]))
    inp_b = (array_ops.placeholder(dtypes.float32, shape=[3, 4]),
             array_ops.placeholder(dtypes.float32, shape=[3, 7]))

    output = nest.map_structure(lambda x1, x2: x1 + x2, inp_a, inp_b)

    nest.assert_same_structure(output, inp_a)
    self.assertShapeEqual(np.zeros((3, 4)), output[0])
    self.assertShapeEqual(np.zeros((3, 7)), output[1])

    feed_dict = {
        inp_a: (np.random.randn(3, 4), np.random.randn(3, 7)),
        inp_b: (np.random.randn(3, 4), np.random.randn(3, 7))
    }

    with self.test_session() as sess:
      output_np = sess.run(output, feed_dict=feed_dict)
    self.assertAllClose(output_np[0],
                        feed_dict[inp_a][0] + feed_dict[inp_b][0])
    self.assertAllClose(output_np[1],
                        feed_dict[inp_a][1] + feed_dict[inp_b][1])

  def testAssertShallowStructure(self):
    inp_ab = ["a", "b"]
    inp_abc = ["a", "b", "c"]
    expected_message = (
        "The two structures don't have the same sequence length. Input "
        "structure has length 2, while shallow structure has length 3.")
    with self.assertRaisesRegexp(ValueError, expected_message):
      nest.assert_shallow_structure(inp_abc, inp_ab)

    inp_ab1 = [(1, 1), (2, 2)]
    inp_ab2 = [[1, 1], [2, 2]]
    expected_message = (
        "The two structures don't have the same sequence type. Input structure "
        "has type <(type|class) 'tuple'>, while shallow structure has type "
        "<(type|class) 'list'>.")
    with self.assertRaisesRegexp(TypeError, expected_message):
      nest.assert_shallow_structure(inp_ab2, inp_ab1)
    nest.assert_shallow_structure(inp_ab2, inp_ab1, check_types=False)

  def testFlattenUpTo(self):
    # Shallow tree ends at scalar.
    input_tree = [[[2, 2], [3, 3]], [[4, 9], [5, 5]]]
    shallow_tree = [[True, True], [False, True]]
    flattened_input_tree = nest.flatten_up_to(shallow_tree, input_tree)
    flattened_shallow_tree = nest.flatten_up_to(shallow_tree, shallow_tree)
    self.assertEqual(flattened_input_tree, [[2, 2], [3, 3], [4, 9], [5, 5]])
    self.assertEqual(flattened_shallow_tree, [True, True, False, True])

    # Shallow tree ends at string.
    input_tree = [[("a", 1), [("b", 2), [("c", 3), [("d", 4)]]]]]
    shallow_tree = [["level_1", ["level_2", ["level_3", ["level_4"]]]]]
    input_tree_flattened_as_shallow_tree = nest.flatten_up_to(shallow_tree,
                                                              input_tree)
    input_tree_flattened = nest.flatten(input_tree)
    self.assertEqual(input_tree_flattened_as_shallow_tree,
                     [("a", 1), ("b", 2), ("c", 3), ("d", 4)])
    self.assertEqual(input_tree_flattened, ["a", 1, "b", 2, "c", 3, "d", 4])

    # Make sure dicts are correctly flattened, yielding values, not keys.
    input_tree = {"a": 1, "b": {"c": 2}, "d": [3, (4, 5)]}
    shallow_tree = {"a": 0, "b": 0, "d": [0, 0]}
    input_tree_flattened_as_shallow_tree = nest.flatten_up_to(shallow_tree,
                                                              input_tree)
    self.assertEqual(input_tree_flattened_as_shallow_tree,
                     [1, {"c": 2}, 3, (4, 5)])

    # Namedtuples.
    ab_tuple = collections.namedtuple("ab_tuple", "a, b")
    input_tree = ab_tuple(a=[0, 1], b=2)
    shallow_tree = ab_tuple(a=0, b=1)
    input_tree_flattened_as_shallow_tree = nest.flatten_up_to(shallow_tree,
                                                              input_tree)
    self.assertEqual(input_tree_flattened_as_shallow_tree,
                     [[0, 1], 2])

    # Nested dicts, OrderedDicts and namedtuples.
    input_tree = collections.OrderedDict(
        [("a", ab_tuple(a=[0, {"b": 1}], b=2)),
         ("c", {"d": 3, "e": collections.OrderedDict([("f", 4)])})])
    shallow_tree = input_tree
    input_tree_flattened_as_shallow_tree = nest.flatten_up_to(shallow_tree,
                                                              input_tree)
    self.assertEqual(input_tree_flattened_as_shallow_tree, [0, 1, 2, 3, 4])
    shallow_tree = collections.OrderedDict([("a", 0),
                                            ("b", {"d": 3, "e": 1})])
    input_tree_flattened_as_shallow_tree = nest.flatten_up_to(shallow_tree,
                                                              input_tree)
    self.assertEqual(input_tree_flattened_as_shallow_tree,
                     [ab_tuple(a=[0, {"b": 1}], b=2),
                      3,
                      collections.OrderedDict([("f", 4)])])
    shallow_tree = collections.OrderedDict([("a", 0), ("c", 0)])
    input_tree_flattened_as_shallow_tree = nest.flatten_up_to(shallow_tree,
                                                              input_tree)
    self.assertEqual(input_tree_flattened_as_shallow_tree,
                     [ab_tuple(a=[0, {"b": 1}], b=2),
                      {"d": 3, "e": collections.OrderedDict([("f", 4)])}])

    ## Shallow non-list edge-case.
    # Using iterable elements.
    input_tree = ["input_tree"]
    shallow_tree = "shallow_tree"
    flattened_input_tree = nest.flatten_up_to(shallow_tree, input_tree)
    flattened_shallow_tree = nest.flatten_up_to(shallow_tree, shallow_tree)
    self.assertEqual(flattened_input_tree, [input_tree])
    self.assertEqual(flattened_shallow_tree, [shallow_tree])

    input_tree = ["input_tree_0", "input_tree_1"]
    shallow_tree = "shallow_tree"
    flattened_input_tree = nest.flatten_up_to(shallow_tree, input_tree)
    flattened_shallow_tree = nest.flatten_up_to(shallow_tree, shallow_tree)
    self.assertEqual(flattened_input_tree, [input_tree])
    self.assertEqual(flattened_shallow_tree, [shallow_tree])

    # Using non-iterable elements.
    input_tree = [0]
    shallow_tree = 9
    flattened_input_tree = nest.flatten_up_to(shallow_tree, input_tree)
    flattened_shallow_tree = nest.flatten_up_to(shallow_tree, shallow_tree)
    self.assertEqual(flattened_input_tree, [input_tree])
    self.assertEqual(flattened_shallow_tree, [shallow_tree])

    input_tree = [0, 1]
    shallow_tree = 9
    flattened_input_tree = nest.flatten_up_to(shallow_tree, input_tree)
    flattened_shallow_tree = nest.flatten_up_to(shallow_tree, shallow_tree)
    self.assertEqual(flattened_input_tree, [input_tree])
    self.assertEqual(flattened_shallow_tree, [shallow_tree])

    ## Both non-list edge-case.
    # Using iterable elements.
    input_tree = "input_tree"
    shallow_tree = "shallow_tree"
    flattened_input_tree = nest.flatten_up_to(shallow_tree, input_tree)
    flattened_shallow_tree = nest.flatten_up_to(shallow_tree, shallow_tree)
    self.assertEqual(flattened_input_tree, [input_tree])
    self.assertEqual(flattened_shallow_tree, [shallow_tree])

    # Using non-iterable elements.
    input_tree = 0
    shallow_tree = 0
    flattened_input_tree = nest.flatten_up_to(shallow_tree, input_tree)
    flattened_shallow_tree = nest.flatten_up_to(shallow_tree, shallow_tree)
    self.assertEqual(flattened_input_tree, [input_tree])
    self.assertEqual(flattened_shallow_tree, [shallow_tree])

    ## Input non-list edge-case.
    # Using iterable elements.
    input_tree = "input_tree"
    shallow_tree = ["shallow_tree"]
    expected_message = ("If shallow structure is a sequence, input must also "
                        "be a sequence. Input has type: <(type|class) 'str'>.")
    with self.assertRaisesRegexp(TypeError, expected_message):
      flattened_input_tree = nest.flatten_up_to(shallow_tree, input_tree)
    flattened_shallow_tree = nest.flatten_up_to(shallow_tree, shallow_tree)
    self.assertEqual(flattened_shallow_tree, shallow_tree)

    input_tree = "input_tree"
    shallow_tree = ["shallow_tree_9", "shallow_tree_8"]
    with self.assertRaisesRegexp(TypeError, expected_message):
      flattened_input_tree = nest.flatten_up_to(shallow_tree, input_tree)
    flattened_shallow_tree = nest.flatten_up_to(shallow_tree, shallow_tree)
    self.assertEqual(flattened_shallow_tree, shallow_tree)

    # Using non-iterable elements.
    input_tree = 0
    shallow_tree = [9]
    expected_message = ("If shallow structure is a sequence, input must also "
                        "be a sequence. Input has type: <(type|class) 'int'>.")
    with self.assertRaisesRegexp(TypeError, expected_message):
      flattened_input_tree = nest.flatten_up_to(shallow_tree, input_tree)
    flattened_shallow_tree = nest.flatten_up_to(shallow_tree, shallow_tree)
    self.assertEqual(flattened_shallow_tree, shallow_tree)

    input_tree = 0
    shallow_tree = [9, 8]
    with self.assertRaisesRegexp(TypeError, expected_message):
      flattened_input_tree = nest.flatten_up_to(shallow_tree, input_tree)
    flattened_shallow_tree = nest.flatten_up_to(shallow_tree, shallow_tree)
    self.assertEqual(flattened_shallow_tree, shallow_tree)

  def testMapStructureUpTo(self):
    # Named tuples.
    ab_tuple = collections.namedtuple("ab_tuple", "a, b")
    op_tuple = collections.namedtuple("op_tuple", "add, mul")
    inp_val = ab_tuple(a=2, b=3)
    inp_ops = ab_tuple(a=op_tuple(add=1, mul=2), b=op_tuple(add=2, mul=3))
    out = nest.map_structure_up_to(
        inp_val, lambda val, ops: (val + ops.add) * ops.mul, inp_val, inp_ops)
    self.assertEqual(out.a, 6)
    self.assertEqual(out.b, 15)

    # Lists.
    data_list = [[2, 4, 6, 8], [[1, 3, 5, 7, 9], [3, 5, 7]]]
    name_list = ["evens", ["odds", "primes"]]
    out = nest.map_structure_up_to(
        name_list, lambda name, sec: "first_{}_{}".format(len(sec), name),
        name_list, data_list)
    self.assertEqual(out, ["first_4_evens", ["first_5_odds", "first_3_primes"]])

if __name__ == "__main__":
  test.main()


text:
      LIVE
      OFFLINE

    {{viewerCount}}


text:
require "spec_helper"

RSpec.describe "Mapper definition DSL" do
  include_context "container"

  before do
    configuration.relation(:users)

    users = container.gateways[:default].dataset(:users)

    users.insert(name: "Joe", email: "joe@doe.com")
    users.insert(name: "Jane", email: "jane@doe.com")
  end

  describe "exclude" do
    let(:mapped_users) { container.relations[:users].map_with(:users).to_a }

    it "removes the attribute" do
      configuration.mappers do
        define(:users) { exclude :email }
      end

      expect(mapped_users).to eql [{name: "Joe"}, {name: "Jane"}]
    end
  end
end


text:
namespace blink {

enum class CaseMapIntend { kKeepSameCase, kUpperCase, kLowerCase };

class CaseMappingHarfBuzzBufferFiller {
  STACK_ALLOCATED();

 public:
  CaseMappingHarfBuzzBufferFiller(CaseMapIntend,
                                  AtomicString locale,
                                  hb_buffer_t* harfbuzz_buffer,
                                  const String& text,
                                  unsigned start_index,
                                  unsigned num_characters);

 private:
  void FillSlowCase(CaseMapIntend,
                    AtomicString locale,
                    const UChar* buffer,
                    unsigned buffer_length,
                    unsigned start_index,
                    unsigned num_characters);
  hb_buffer_t* harfbuzz_buffer_;
};

}  // namespace blink

#endif


text:
import contextlib
import datetime

import mock
from oslo.config import cfg

from nova.openstack.common import timeutils
from nova import test
from nova.tests.virt.vmwareapi import fake
from nova.virt.vmwareapi import ds_util
from nova.virt.vmwareapi import imagecache
from nova.virt.vmwareapi import vim_util
from nova.virt.vmwareapi import vmops

CONF = cfg.CONF

class ImageCacheManagerTestCase(test.NoDBTestCase):
    def setUp(self):
        super(ImageCacheManagerTestCase, self).setUp()
        self._session = mock.Mock(name='session')
        self._imagecache = imagecache.ImageCacheManager(self._session,
                                                        'fake-base-folder')
        self._time = datetime.datetime(2012, 11, 22, 12, 00, 00)
        self._file_name = 'ts-2012-11-22-12-00-00'
        fake.reset()

    def tearDown(self):
        super(ImageCacheManagerTestCase, self).tearDown()
        fake.reset()

    def test_timestamp_cleanup(self):
        def fake_get_timestamp(ds_browser, ds_path):
            self.assertEqual('fake-ds-browser', ds_browser)
            self.assertEqual('[fake-ds] fake-path', str(ds_path))
            if not self.exists:
                return
            ts = '%s%s' % (imagecache.TIMESTAMP_PREFIX,
                    timeutils.strtime(at=self._time,
                                      fmt=imagecache.TIMESTAMP_FORMAT))
            return ts

        with contextlib.nested(
            mock.patch.object(self._imagecache, '_get_timestamp',
                              fake_get_timestamp),
            mock.patch.object(ds_util, 'file_delete')
        ) as (_get_timestamp, _file_delete):
            self.exists = False
            self._imagecache.timestamp_cleanup(
                    'fake-dc-ref', 'fake-ds-browser',
                    ds_util.DatastorePath('fake-ds', 'fake-path'))
            self.assertEqual(0, _file_delete.call_count)
            self.exists = True
            self._imagecache.timestamp_cleanup(
                    'fake-dc-ref', 'fake-ds-browser',
                    ds_util.DatastorePath('fake-ds', 'fake-path'))
            expected_ds_path = ds_util.DatastorePath(
                    'fake-ds', 'fake-path', self._file_name)
            _file_delete.assert_called_once_with(self._session,
                    expected_ds_path, 'fake-dc-ref')

    def test_get_timestamp(self):
        def fake_get_sub_folders(session, ds_browser, ds_path):
            self.assertEqual('fake-ds-browser', ds_browser)
            self.assertEqual('[fake-ds] fake-path', str(ds_path))
            if self.exists:
                files = set()
                files.add(self._file_name)
                return files

        with contextlib.nested(
            mock.patch.object(ds_util, 'get_sub_folders',
                              fake_get_sub_folders)
        ):
            self.exists = True
            ts = self._imagecache._get_timestamp(
                    'fake-ds-browser',
                    ds_util.DatastorePath('fake-ds', 'fake-path'))
            self.assertEqual(self._file_name, ts)
            self.exists = False
            ts = self._imagecache._get_timestamp(
                    'fake-ds-browser',
                    ds_util.DatastorePath('fake-ds', 'fake-path'))
            self.assertIsNone(ts)

    def test_get_timestamp_filename(self):
        timeutils.set_time_override(override_time=self._time)
        fn = self._imagecache._get_timestamp_filename()
        self.assertEqual(self._file_name, fn)

    def test_get_datetime_from_filename(self):
        t = self._imagecache._get_datetime_from_filename(self._file_name)
        self.assertEqual(self._time, t)

    def test_get_ds_browser(self):
        cache = self._imagecache._ds_browser
        ds_browser = mock.Mock()
        moref = fake.ManagedObjectReference('datastore-100')
        self.assertIsNone(cache.get(moref.value))
        mock_get_method = mock.Mock(return_value=ds_browser)
        with mock.patch.object(vim_util, 'get_dynamic_property',
                               mock_get_method):
            ret = self._imagecache._get_ds_browser(moref)
            mock_get_method.assert_called_once_with(mock.ANY, moref,
                                                    'Datastore', 'browser')
            self.assertIs(ds_browser, ret)
            self.assertIs(ds_browser, cache.get(moref.value))

    def test_list_base_images(self):
        def fake_get_dynamic_property(vim, mobj, type, property_name):
            return 'fake-ds-browser'

        def fake_get_sub_folders(session, ds_browser, ds_path):
            files = set()
            files.add('image-ref-uuid')
            return files

        with contextlib.nested(
            mock.patch.object(vim_util, 'get_dynamic_property',
                              fake_get_dynamic_property),
            mock.patch.object(ds_util, 'get_sub_folders',
                              fake_get_sub_folders)
        ) as (_get_dynamic, _get_sub_folders):
            fake_ds_ref = fake.ManagedObjectReference('fake-ds-ref')
            datastore = ds_util.Datastore(name='ds', ref=fake_ds_ref)
            ds_path = datastore.build_path('base_folder')
            images = self._imagecache._list_datastore_images(
                    ds_path, datastore)
            originals = set()
            originals.add('image-ref-uuid')
            self.assertEqual({'originals': originals,
                              'unexplained_images': []},
                             images)

    def test_age_cached_images(self):
        def fake_get_ds_browser(ds_ref):
            return 'fake-ds-browser'

        def fake_get_timestamp(ds_browser, ds_path):
            self._get_timestamp_called += 1
            path = str(ds_path)
            if path == '[fake-ds] fake-path/fake-image-1':
                # No time stamp exists
                return
            if path == '[fake-ds] fake-path/fake-image-2':
                # Timestamp that will be valid => no deletion
                return 'ts-2012-11-22-10-00-00'
            if path == '[fake-ds] fake-path/fake-image-3':
                # Timestamp that will be invalid => deletion
                return 'ts-2012-11-20-12-00-00'
            self.fail()

        def fake_mkdir(session, ts_path, dc_ref):
            self.assertEqual(
                    '[fake-ds] fake-path/fake-image-1/ts-2012-11-22-12-00-00',
                    str(ts_path))

        def fake_file_delete(session, ds_path, dc_ref):
            self.assertEqual('[fake-ds] fake-path/fake-image-3', str(ds_path))

        def fake_timestamp_cleanup(dc_ref, ds_browser, ds_path):
            self.assertEqual('[fake-ds] fake-path/fake-image-4', str(ds_path))

        with contextlib.nested(
            mock.patch.object(self._imagecache, '_get_ds_browser',
                              fake_get_ds_browser),
            mock.patch.object(self._imagecache, '_get_timestamp',
                              fake_get_timestamp),
            mock.patch.object(ds_util, 'mkdir',
                              fake_mkdir),
            mock.patch.object(ds_util, 'file_delete',
                              fake_file_delete),
            mock.patch.object(self._imagecache, 'timestamp_cleanup',
                              fake_timestamp_cleanup),
        ) as (_get_ds_browser, _get_timestamp, _mkdir, _file_delete,
              _timestamp_cleanup):
            timeutils.set_time_override(override_time=self._time)
            datastore = ds_util.Datastore(name='ds', ref='fake-ds-ref')
            dc_info = vmops.DcInfo(ref='dc_ref', name='name',
                                   vmFolder='vmFolder')
            self._get_timestamp_called = 0
            self._imagecache.originals = set(['fake-image-1', 'fake-image-2',
                                              'fake-image-3', 'fake-image-4'])
            self._imagecache.used_images = set(['fake-image-4'])
            self._imagecache._age_cached_images(
                    'fake-context', datastore, dc_info,
                    ds_util.DatastorePath('fake-ds', 'fake-path'))
            self.assertEqual(3, self._get_timestamp_called)

    def test_update(self):
        def fake_list_datastore_images(ds_path, datastore):
            return {'unexplained_images': [],
                    'originals': self.images}

        def fake_age_cached_images(context, datastore,
                                   dc_info, ds_path):
            self.assertEqual('[ds] fake-base-folder', str(ds_path))
            self.assertEqual(self.images,
                             self._imagecache.used_images)
            self.assertEqual(self.images,
                             self._imagecache.originals)

        with contextlib.nested(
            mock.patch.object(self._imagecache, '_list_datastore_images',
                              fake_list_datastore_images),
            mock.patch.object(self._imagecache,
                              '_age_cached_images',
                              fake_age_cached_images)
        ) as (_list_base, _age_and_verify):
            instances = [{'image_ref': '1',
                          'host': CONF.host,
                          'name': 'inst-1',
                          'uuid': '123',
                          'vm_state': '',
                          'task_state': ''},
                         {'image_ref': '2',
                          'host': CONF.host,
                          'name': 'inst-2',
                          'uuid': '456',
                          'vm_state': '',
                          'task_state': ''}]
            self.images = set(['1', '2'])
            datastore = ds_util.Datastore(name='ds', ref='fake-ds-ref')
            dc_info = vmops.DcInfo(ref='dc_ref', name='name',
                                   vmFolder='vmFolder')
            datastores_info = [(datastore, dc_info)]
            self._imagecache.update('context', instances, datastores_info)


text:
package org.elasticsearch.xpack.core.spatial;

import org.elasticsearch.Version;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.xpack.core.XPackFeatureSet;
import org.elasticsearch.xpack.core.XPackField;
import org.elasticsearch.xpack.core.spatial.action.SpatialStatsAction;

import java.io.IOException;
import java.util.Objects;

public class SpatialFeatureSetUsage extends XPackFeatureSet.Usage {

    private final SpatialStatsAction.Response statsResponse;

    public SpatialFeatureSetUsage(boolean available, boolean enabled, SpatialStatsAction.Response statsResponse) {
        super(XPackField.SPATIAL, available, enabled);
        this.statsResponse = statsResponse;
    }

    public SpatialFeatureSetUsage(StreamInput input) throws IOException {
        super(input);
        if (input.getVersion().onOrAfter(Version.V_8_0_0)) {
            this.statsResponse = new SpatialStatsAction.Response(input);
        } else {
            this.statsResponse = null;
        }
    }

    @Override
    public Version getMinimalSupportedVersion() {
        return Version.V_7_4_0;
    }

    SpatialStatsAction.Response statsResponse() {
        return statsResponse;
    }

    @Override
    public void writeTo(StreamOutput out) throws IOException {
        super.writeTo(out);
        if (out.getVersion().onOrAfter(Version.V_8_0_0)) {
            this.statsResponse.writeTo(out);
        }
    }

    @Override
    public int hashCode() {
        return Objects.hash(available, enabled, statsResponse);
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        SpatialFeatureSetUsage other = (SpatialFeatureSetUsage) obj;
        return Objects.equals(available, other.available)
            && Objects.equals(enabled, other.enabled)
            && Objects.equals(statsResponse, other.statsResponse);
    }
}


text:
[![Gem Version](https://img.shields.io/gem/v/block_yundun.svg)](https://img.shields.io/gem/v/block_yundun.svg)
[![Build Status](https://travis-ci.org/42thcoder/block_yundun.svg?branch=master)](https://travis-ci.org/42thcoder/block_yundun)
[![Code Coverage](https://img.shields.io/codecov/c/github/42thcoder/block_yundun.svg?branch=master)](https://img.shields.io/codecov/c/github/42thcoder/block_yundun.svg)
[![Code Climate](https://img.shields.io/codeclimate/github/kabisaict/flow.svg)](https://img.shields.io/codeclimate/github/kabisaict/flow.svg)

## Installation

Add this line to your application's Gemfile:

```ruby
gem 'block_yundun'
```

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install block_yundun

## Usage

Add `app.middleware.use Rack::BlockYundun` to `config/production.rb` and your world is finally in peace.

## Development

After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.

To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).

## Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/42thcoder/block_yundun.

## License

The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).


text:
AmaranJS Laravel 5 Package
==========================
[![Laravel](https://img.shields.io/badge/Laravel-5.0-orange.svg?style=flat-square)](http://laravel.com)
[![Source](http://img.shields.io/badge/source-hakanersu/amaranlaravel-blue.svg?style=flat-square)](https://github.com/hakanersu/amaran-laravel)
[![License](http://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square)](https://tldrlegal.com/license/mit-license)

[AmaranJS][1] L5 package is a Laravel wrapper for my jquery plugin [AmaranJS][1].You can create easy and stylish notifications with [AmaranJS][1].

Package Demo: http://ersu.me/laravel-amaranjs

Installation
------------
Begin by installing the package through Composer. You can add your composer.json require section:
```json
"xuma/laravel-amaran": "~1.0@dev"
```
Don't forget to update `composer update`.

Once this operation is complete, simply add both the service provider and facade classes to your project's `config/app.php` file:

#### Service Provider
```php
'Xuma\Amaran\AmaranServiceProvider'
```
#### Facade
```php
'Amaran' => 'Xuma\Amaran\Facades\Amaran'
```

#### Installing AmaranJS jQuery Plugin

Before starting download and extract your [AmaranJS][1] files to public/ directory and add necessary plugin files to your view.You can find installation documentation of [AmaranJS][1] [here][1].

#### Adding Output View

Add required view after your jQuery and AmaranJS links.

```php
@include('amaran::javascript')
```

Example:

```php
<script src="//cdn.jsdelivr.net/jquery/2.1.3/jquery.js"></script>
<script src="js/jquery.amaran.js"></script>
@include('amaran::javascript')
```

Usage
-----

Usage is very simple.If you want to use default theme;

```php
Amaran::content(['message'=>'Hello World!'])->create();
```

#### Using AmaranJS Functions

You can use most [AmaranJS][1] functions as methods like :

```php
Amaran::content([ 'message'=>'Hello World!'])
    ->position('top right')
    ->inEffect('slideRight')
    ->outEffect('slideBottom')
    ->sticky(true)
    ->create();
```

#### Binding Javascript Events to Element
You can define javascript events with `bind()` method
```php
Amaran::content(['message'=>'Hello World!'])
    ->position('top right')
    ->bind('#start','click')
  - >create();
```

#### Using as Flash Message
Normally AmaranJS bind to current view but you can add ```->flash()``` method for bind to redirected methods view.

```php
Amaran::content(['message'=>'Hello World'])->flash()->create();
```

Theme Usage
-----

Theme usage is simple just set theme name and set content as theme template array.
```php
Amaran::theme('awesome ok')->content([
        'title'=>'My first funcy example!',
        'message'=>'1.4 GB',
        'info'=>'my_birthday.mp4',
        'icon'=>'fa fa-download'
    ])->create();
```

> Little note if you want to use awesome theme you have to include [font awesome][2].

[1]: https://github.com/hakanersu/AmaranJS
[2]: http://fortawesome.github.io/Font-Awesome/icons/


text:
export default class State<T> {
	onEnter(self: T, prev: State<T>): void {}
	onExit(self: T, next: State<T>): void {}
	onUpdate(self: T, dt: number): void {}
	onDown(self: T, ret: any): void {}
	onUp(self: T): void {}
}
export const BeginState = new State();
export const EndState = new State();