text:
System.register(["aurelia-framework", "./grid/htmlCache", "./grid/controller", "./grid/mainMarkup", "./grid/mainScrollEvents", "./grid/rowMarkup", "./grid/rowScrollEvents", "./grid/columnMarkup", "./grid/htmlHeightWidth", "./grid/viewSlots", "./grid/columnBindingContext", "./grid/rowDataBinder", "./grid/rowClickHandler", "./grid/groupingElements", "./grid/loadingScreen", "./grid/contextMenu", "./grid/v-grid", "./gridConnector", "./dataSource", "./selection", "./utils/arrayFilter", "./utils/arraySort", "./utils/arrayGrouping", "./grid/footer"], function (exports_1, context_1) {
    var __moduleName = context_1 && context_1.id;
    var exportedNames_1 = {
        "HtmlCache": true,
        "Controller": true,
        "MainMarkup": true,
        "MainScrollEvents": true,
        "RowMarkup": true,
        "RowScrollEvents": true,
        "ColumnMarkup": true,
        "HtmlHeightWidth": true,
        "ViewSlots": true,
        "ColumnBindingContext": true,
        "RowDataBinder": true,
        "RowClickHandler": true,
        "GroupingElements": true,
        "LoadingScreen": true,
        "ContextMenu": true,
        "VGrid": true,
        "GridConnector": true,
        "DataSource": true,
        "Selection": true,
        "ArrayFilter": true,
        "ArraySort": true,
        "ArrayGrouping": true,
        "Footer": true
    };
    function exportStar_1(m) {
        var exports = {};
        for (var n in m) {
            if (n !== "default" && !exportedNames_1.hasOwnProperty(n)) exports[n] = m[n];
        }
        exports_1(exports);
    }
    return {
        setters: [
            function (aurelia_framework_1_1) {
                exportStar_1(aurelia_framework_1_1);
            },
            function (htmlCache_1_1) {
                exports_1({
                    "HtmlCache": htmlCache_1_1["HtmlCache"]
                });
            },
            function (controller_1_1) {
                exports_1({
                    "Controller": controller_1_1["Controller"]
                });
            },
            function (mainMarkup_1_1) {
                exports_1({
                    "MainMarkup": mainMarkup_1_1["MainMarkup"]
                });
            },
            function (mainScrollEvents_1_1) {
                exports_1({
                    "MainScrollEvents": mainScrollEvents_1_1["MainScrollEvents"]
                });
            },
            function (rowMarkup_1_1) {
                exports_1({
                    "RowMarkup": rowMarkup_1_1["RowMarkup"]
                });
            },
            function (rowScrollEvents_1_1) {
                exports_1({
                    "RowScrollEvents": rowScrollEvents_1_1["RowScrollEvents"]
                });
            },
            function (columnMarkup_1_1) {
                exports_1({
                    "ColumnMarkup": columnMarkup_1_1["ColumnMarkup"]
                });
            },
            function (htmlHeightWidth_1_1) {
                exports_1({
                    "HtmlHeightWidth": htmlHeightWidth_1_1["HtmlHeightWidth"]
                });
            },
            function (viewSlots_1_1) {
                exports_1({
                    "ViewSlots": viewSlots_1_1["ViewSlots"]
                });
            },
            function (columnBindingContext_1_1) {
                exports_1({
                    "ColumnBindingContext": columnBindingContext_1_1["ColumnBindingContext"]
                });
            },
            function (rowDataBinder_1_1) {
                exports_1({
                    "RowDataBinder": rowDataBinder_1_1["RowDataBinder"]
                });
            },
            function (rowClickHandler_1_1) {
                exports_1({
                    "RowClickHandler": rowClickHandler_1_1["RowClickHandler"]
                });
            },
            function (groupingElements_1_1) {
                exports_1({
                    "GroupingElements": groupingElements_1_1["GroupingElements"]
                });
            },
            function (loadingScreen_1_1) {
                exports_1({
                    "LoadingScreen": loadingScreen_1_1["LoadingScreen"]
                });
            },
            function (contextMenu_1_1) {
                exports_1({
                    "ContextMenu": contextMenu_1_1["ContextMenu"]
                });
            },
            function (v_grid_1_1) {
                exports_1({
                    "VGrid": v_grid_1_1["VGrid"]
                });
            },
            function (gridConnector_1_1) {
                exports_1({
                    "GridConnector": gridConnector_1_1["GridConnector"]
                });
            },
            function (dataSource_1_1) {
                exports_1({
                    "DataSource": dataSource_1_1["DataSource"]
                });
            },
            function (selection_1_1) {
                exports_1({
                    "Selection": selection_1_1["Selection"]
                });
            },
            function (arrayFilter_1_1) {
                exports_1({
                    "ArrayFilter": arrayFilter_1_1["ArrayFilter"]
                });
            },
            function (arraySort_1_1) {
                exports_1({
                    "ArraySort": arraySort_1_1["ArraySort"]
                });
            },
            function (arrayGrouping_1_1) {
                exports_1({
                    "ArrayGrouping": arrayGrouping_1_1["ArrayGrouping"]
                });
            },
            function (footer_1_1) {
                exports_1({
                    "Footer": footer_1_1["Footer"]
                });
            }
        ],
        execute: function () {
        }
    };
});
//# sourceMappingURL=interfaces.js.map


text:
#include <aws/securityhub/model/GetMasterAccountRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::SecurityHub::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;

GetMasterAccountRequest::GetMasterAccountRequest()
{
}

Aws::String GetMasterAccountRequest::SerializePayload() const
{
  return {};
}

redpajama_set_name: RedPajamaGithub


text:
package ginkgoext

/*

JUnit XML Reporter for Ginkgo

For usage instructions: http://onsi.github.io/ginkgo/#generating_junit_xml_output

Reference file:
https://github.com/onsi/ginkgo/blob/39febac9157b63aeba74d843d6b1c30990f3d7ed/reporters/junit_reporter.go
Junit Reference:
https://www.ibm.com/support/knowledgecenter/en/SSQ2R2_9.1.1/com.ibm.rsar.analysis.codereview.cobol.doc/topics/cac_useresults_junit.html
*/

import (
	"encoding/xml"
	"fmt"
	"math"
	"os"
	"strings"

	"github.com/onsi/ginkgo/config"
	"github.com/onsi/ginkgo/types"
)

// JUnitTestSuite main struct to report all test in Junit Format
type JUnitTestSuite struct {
	XMLName   xml.Name        `xml:"testsuite"`
	TestCases []JUnitTestCase `xml:"testcase"`
	Name      string          `xml:"name,attr"`
	Tests     int             `xml:"tests,attr"`
	Failures  int             `xml:"failures,attr"`
	Errors    int             `xml:"errors,attr"`
	Time      float64         `xml:"time,attr"`
}

// JUnitTestCase test case struct to report in Junit Format.
type JUnitTestCase struct {
	Name           string               `xml:"name,attr"`
	ClassName      string               `xml:"classname,attr"`
	FailureMessage *JUnitFailureMessage `xml:"failure,omitempty"`
	Skipped        *JUnitSkipped        `xml:"skipped,omitempty"`
	Time           float64              `xml:"time,attr"`
	SystemErr      string               `xml:"system-err,omitempty"`
	SystemOut      string               `xml:"system-out,omitempty"`
}

// JUnitFailureMessage failure message struct
type JUnitFailureMessage struct {
	Type    string `xml:"type,attr"`
	Message string `xml:",chardata"`
}

// JUnitSkipped skipped struct to report XML
type JUnitSkipped struct {
	XMLName xml.Name `xml:"skipped"`
}

// JUnitReporter struct that uses ginkgo to report
type JUnitReporter struct {
	suite         JUnitTestSuite
	filename      string
	testSuiteName string
}

//NewJUnitReporter creates a new JUnit XML reporter.  The XML will be stored in the passed in filename.
func NewJUnitReporter(filename string) *JUnitReporter {
	return &JUnitReporter{
		filename: filename,
	}
}

// SpecSuiteWillBegin create the main JUnitTestSuite based on Ginkgo parameters
func (reporter *JUnitReporter) SpecSuiteWillBegin(config config.GinkgoConfigType, summary *types.SuiteSummary) {
	reporter.suite = JUnitTestSuite{
		Name:      summary.SuiteDescription,
		TestCases: []JUnitTestCase{},
	}
	reporter.testSuiteName = summary.SuiteDescription
}

// SpecWillRun needed by ginkgo. Not used.
func (reporter *JUnitReporter) SpecWillRun(specSummary *types.SpecSummary) {
}

// BeforeSuiteDidRun Beforesuite report function
func (reporter *JUnitReporter) BeforeSuiteDidRun(setupSummary *types.SetupSummary) {
	reporter.handleSetupSummary("BeforeSuite", setupSummary)
}

// AfterSuiteDidRun ginkgo.Aftersuite report function
func (reporter *JUnitReporter) AfterSuiteDidRun(setupSummary *types.SetupSummary) {
	reporter.handleSetupSummary("AfterSuite", setupSummary)
}

func failureMessage(failure types.SpecFailure) string {
	return fmt.Sprintf("%s\n%s\n%s", failure.ComponentCodeLocation.String(), failure.Message, failure.Location.String())
}

func (reporter *JUnitReporter) handleSetupSummary(name string, setupSummary *types.SetupSummary) {
	if setupSummary.State != types.SpecStatePassed {
		testCase := JUnitTestCase{
			Name:      name,
			ClassName: reporter.testSuiteName,
		}

		testCase.FailureMessage = &JUnitFailureMessage{
			Type:    reporter.failureTypeForState(setupSummary.State),
			Message: failureMessage(setupSummary.Failure),
		}
		testCase.SystemErr = setupSummary.CapturedOutput
		testCase.Time = setupSummary.RunTime.Seconds()
		reporter.suite.TestCases = append(reporter.suite.TestCases, testCase)
	}
}

// SpecDidComplete reports the test results in a JUTestCase struct
func (reporter *JUnitReporter) SpecDidComplete(specSummary *types.SpecSummary) {
	testCase := JUnitTestCase{
		Name:      strings.Join(specSummary.ComponentTexts[1:], " "),
		ClassName: reporter.testSuiteName,
	}
	if specSummary.State == types.SpecStateFailed || specSummary.State == types.SpecStateTimedOut || specSummary.State == types.SpecStatePanicked {
		testCase.FailureMessage = &JUnitFailureMessage{
			Type:    reporter.failureTypeForState(specSummary.State),
			Message: failureMessage(specSummary.Failure),
		}
		checks, output := reportChecks(specSummary.CapturedOutput)
		testCase.SystemErr = checks
		testCase.SystemOut = output
	}
	if specSummary.State == types.SpecStateSkipped || specSummary.State == types.SpecStatePending {
		testCase.Skipped = &JUnitSkipped{}
	}
	testCase.Time = specSummary.RunTime.Seconds()
	reporter.suite.TestCases = append(reporter.suite.TestCases, testCase)
}

// SpecSuiteDidEnd summary information to Suite summary in the xml report
func (reporter *JUnitReporter) SpecSuiteDidEnd(summary *types.SuiteSummary) {
	reporter.suite.Tests = summary.NumberOfSpecsThatWillBeRun
	reporter.suite.Time = math.Trunc(summary.RunTime.Seconds() * 1000 / 1000)
	reporter.suite.Failures = summary.NumberOfFailedSpecs
	reporter.suite.Errors = 0
	file, err := os.Create(reporter.filename)
	if err != nil {
		fmt.Printf("Failed to create JUnit report file: %s\n\t%s", reporter.filename, err.Error())
	}
	defer file.Close()
	file.WriteString(xml.Header)
	encoder := xml.NewEncoder(file)
	encoder.Indent("  ", "    ")
	err = encoder.Encode(reporter.suite)
	if err != nil {
		fmt.Printf("Failed to generate JUnit report\n\t%s", err.Error())
	}
}

func (reporter *JUnitReporter) failureTypeForState(state types.SpecState) string {
	switch state {
	case types.SpecStateFailed:
		return "Failure"
	case types.SpecStateTimedOut:
		return "Timeout"
	case types.SpecStatePanicked:
		return "Panic"
	default:
		return "Unknown"
	}
}

// reportChecks filters the given string from the stdout and subtract the
// information that is within the <Checks></Checks> labels. It'll return the
// given output as first result, and the check output in the second string.
func reportChecks(output string) (string, string) {
	var checks string
	var stdout string
	var dest = "stdout"

	for _, line := range strings.Split(output, "\n") {
		if line == "<Checks>" {
			dest = "checks"
			continue
		}

		if line == "</Checks>" {
			dest = "stdout"
			continue
		}
		switch dest {
		case "stdout":
			stdout += line + "\n"
			continue
		case "checks":
			checks += line + "\n"
			continue
		}
	}
	return stdout, checks
}


text:
namespace ash {
const char kChromeUIGuestOSInstallerHost[] = "guest-os-installer";
const char kChromeUIGuestOSInstallerUrl[] = "chrome://guest-os-installer";
}  // namespace ash


text:
function ind = paramNameRegularExpressionLookup(model, pattern, isKernel)

% PARAMNAMEREGULAREXPRESSIONLOOKUP Returns the indices of the parameter containing the given regular expression.
% FORMAT
% DESC returns the index of the parameters which contain the given
% regular expression. If no matches
% are found then an empty vector is returned.
% ARG model : the model for which parameters are reverse looked up.
% ARG pattern : the regular expression that should match the names.
% RETURN ind : the indices of those parameters in the model.
%
% FORMAT
% DESC returns the index of the parameters which contain the given
% regular expression for a kernel structure. If no matches
% are found then an empty vector is returned.
% ARG model : the model for which parameters are reverse looked up.
% ARG pattern : the regular expression that should match the names.
% ARG isKernel : a logical value that specifies if a model corresponds to a
% kernel structure.
% RETURN ind : the indices of those parameters in the model.
%
% COPYRIGHT : Neil D. Lawrence, 2008
%
% MODIFICATIONS : Mauricio A. Alvarez, 2009
%
% SEEALSO : cmpndTieParameters, paramNameReverseLookup

% MLTOOLS

  ind = [];

  if nargin<3
      [void, names] = modelExtractParam(model);
  else
      if isKernel
          [void, names] = kernExtractParam(model);
      else
          [void, names] = modelExtractParam(model);
      end
  end

  for i = 1:length(names)
    if(regexp(names{i}, pattern))
      ind = [ind i];
    end
  end
end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace _12.Little_John
{
    class Program
    {
        static void Main(string[] args)
        {
            Regex pattern = new Regex(@">>>----->>|>>----->|>----->");
            int[] arrow = new int[3];

            for (int i = 0; i < 4; i++)
            {
                MatchCollection mat = pattern.Matches(Console.ReadLine());
                foreach (Match item in mat)
                {
                    if (item.Value == ">>>----->>")
                    {
                        arrow[2]++;
                    }
                    else if (item.Value == ">>----->")
                    {
                        arrow[1]++;
                    }
                    else
                    {
                        arrow[0]++;
                    }
                }
            }

            int num = int.Parse(string.Join("", arrow));
            string bin0 = Convert.ToString(num, 2);
            char[] rever = bin0.ToCharArray();
            Array.Reverse(rever);
            string bin1 = new string(rever);
            Console.WriteLine(Convert.ToInt32(bin0 + bin1, 2));
        }
    }
    }
}


text:
/* ----------- actions ----------- */

const SAMPLE_BRUSH = 'SAMPLE_BRUSH'
const CANCEL_BRUSH = 'CANCEL_BRUSH'
const BRUSH_POSITION = 'BRUSH_POSITION'

/* ----------- action creators ----------- */

export const setBrush = data=>({
  type: SAMPLE_BRUSH,
  data,
})
export const cancelBrush = ()=>({
  type: CANCEL_BRUSH,
})
export const brushPosition = position=>({
  type: BRUSH_POSITION,
  position,
})

/* ----------- reducer ----------- */

export default (state = null, action)=>{
  switch (action.type) {
    case SAMPLE_BRUSH:
      return action.data
    case CANCEL_BRUSH:
      return null
    case BRUSH_POSITION:
      return Object.assign({}, state, { position: action.position, onGrid: !!action.position })
    default:
      return state
  }
}


text:
import Ember from 'ember';

export default Ember.Route.extend({
    titleToken(model) {
        return model.movie.title;
    },
    model({ movie_id }) {
        let userId = this.get('session.currentUser.uid');
        let movie = Ember.$.getJSON(`https://api.themoviedb.org/3/movie/${movie_id}?api_key=0910db5745f86638474ffefa5d3ba687&append_to_response=videos,credits`);
        let userRating = this.get('firebaseUtil').findRecord(movie_id, `users/${userId}/ratings/${movie_id}`).catch(error => {
            //error
            alert(error);
        })
        let wannaSee = this.get('firebaseUtil').isRecordExisting(`users/${userId}/wannaSees/${movie_id}`)
        return Ember.RSVP.hash({
            movie,
            userRating,
            wannaSee
        });
    },
    afterModel(model) {
        this._super(model);
        Ember.RSVP.hash({
            tmp: Ember.$.getJSON("https://omdbapi.com/?apikey=8084da1&i=" + model.movie.imdb_id)
        }).then(hash => {
            Ember.set(model, 'movieOMDb', hash.tmp);
        })
    }
});


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.9.1"/>
<title>labyrinth2015: cli/exception.cpp Source File</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

labyrinth2015
    1.0

Main Page

Classes

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

File List

File Members

cli

exception.cpp

Go to the documentation of this file.

    1

    8 #include "exception.h"

    9

   16 Exception::Exception(string message, int line, string file){

   17     this->message = message;

   18     this->line = line;

   19     this->file = file;

   20 }

   21

   26 string Exception::getMessage(){

   27     return this->message;

   28 }

   29

   34 int Exception::getLine(){

   35     return this->line;

   36 }

   37

   42 string Exception::getFile(){

   43     return this->file;

   44 }

message

Struct represents message (text protocol)

Definition: utils.h:29

Exception::getMessage

string getMessage()

Getter for message attribute.

Definition: exception.cpp:26

exception.h

Header file for generic Exception class.

Exception::getLine

int getLine()

Getter for line attribute.

Definition: exception.cpp:34

Exception::Exception

Exception(string="", int=0, string="")

Constructor for class Exception.

Definition: exception.cpp:16

Exception::getFile

string getFile()

Getter for file attribute.

Definition: exception.cpp:42

<address class="footer">
Generated on Sun May 10 2015 17:58:40 for labyrinth2015 by

 1.8.9.1
</address>


text:
package org.opencommercesearch.repository;

public class RuleExpressionProperty {

	public static final String ITEM_DESCRIPTOR = "ruleExpression";
	public static final String VALUE = "value";
	public static final String NESTED_LEVEL = "nestLevel";
	public static final String TYPE = "type";
	public static final String OPERATOR = "operator";
}


text:
'use strict';

const cookieLib = require('cookie');
const Emitter = require('eventemitter3');
const qsParse = require('query-string').parse;
const urlUtils = require('@yr/url-utils');

const RE_SPLIT = /[?#]/;

class Request extends Emitter {
  /**
   * Constructor
   * @param {String} url
   * @param {Boolean} bootstrap
   */
  constructor(url, bootstrap) {
    super();

    url = url ? urlUtils.encode(url) : urlUtils.getCurrent();

    const path = url.split(RE_SPLIT);
    const qs = (~url.indexOf('?') && path[1]) || '';
    const hash = (~url.indexOf('#') && path[path.length - 1]) || '';

    this.app = null;
    this.baseUrl = '';
    this.bootstrap = bootstrap || false;
    this.cached = false;
    this.cookies = cookieLib.parse(document.cookie);
    this.hash = qsParse(hash);
    this.params = null;
    this.path = urlUtils.sanitize(path[0]);
    this.query = qsParse(qs);
    this.querystring = qs;
    this.reloaded = false;
    this.search = qs ? `?${qs}` : '';
    // Ignore hash
    this.url = this.originalUrl = url.split('#')[0];
  }

  /**
   * Abort response
   */
  abort() {
    this.reset();
    this.emit('close');
  }

  /**
   * Reset state
   * @param {Boolean} bootstrap
   */
  reset(bootstrap) {
    this.baseUrl = '';
    this.bootstrap = bootstrap || false;
    this.cached = false;
    this.path = urlUtils.sanitize(this.originalUrl.split('?')[0]);
    this.params = null;
    this.reloaded = false;
  }
}

/**
 * Instance factory
 * @param {String} url
 * @param {Boolean} bootstrap
 * @returns {Request}
 */
module.exports = function requestFactory(url, bootstrap) {
  return new Request(url, bootstrap);
};
module.exports.Request = Request;


text:
#ifndef SCHEINERMAN_STREAM_STREAM_PROVIDER_ITERATOR_H
#define SCHEINERMAN_STREAM_STREAM_PROVIDER_ITERATOR_H

namespace stream {
namespace provider {

template<typename T>
struct StreamProvider<T>::Iterator {

public:
    T& operator* ();
    Iterator& operator++ ();
    Iterator operator++ (int);
    bool operator== (Iterator& other);
    bool operator!= (Iterator& other);

    friend struct StreamProvider<T>;

private:
    enum class State {
        Initial,
        Consumed,
        Iterating,
        End
    };

    static Iterator begin(StreamProvider<T>* source);
    static Iterator iterating(StreamProvider<T>* source, std::shared_ptr<T> value);
    static Iterator end(StreamProvider<T>* source);

    Iterator(StreamProvider<T>* source, State state, std::shared_ptr<T> value);

    void update_initial();
    void check_consumed(const std::string& op) const;

    StreamProvider<T>* source_;
    State state_;
    std::shared_ptr<T> current_;

};

template<typename T>
typename StreamProvider<T>::Iterator
StreamProvider<T>::Iterator::begin(StreamProvider<T>* source) {
    return Iterator(source, State::Initial, nullptr);
}

template<typename T>
typename StreamProvider<T>::Iterator
StreamProvider<T>::Iterator::iterating(StreamProvider<T>* source,
                                       std::shared_ptr<T> value) {
    return Iterator(source, State::Iterating, value);
}

template<typename T>
typename StreamProvider<T>::Iterator
StreamProvider<T>::Iterator::end(StreamProvider<T>* source) {
    return Iterator(source, State::End, nullptr);
}

template<typename T>
StreamProvider<T>::Iterator::Iterator(StreamProvider<T>* source, State state,
                                      std::shared_ptr<T> value)
      : source_(source), state_(state), current_(value) {}

template<typename T>
T& StreamProvider<T>::Iterator::operator* () {
    update_initial();
    return *current_;
}

template<typename T>
typename StreamProvider<T>::Iterator&
StreamProvider<T>::Iterator::operator++() {
    update_initial();
    check_consumed("prefix increment");
    if(source_->advance()) {
        current_ = source_->get();
    } else {
        state_ = State::End;
        current_.reset();
    }
    return *this;
}

template<typename T>
typename StreamProvider<T>::Iterator
StreamProvider<T>::Iterator::operator++(int) {
    update_initial();
    check_consumed("postfix increment");
    Iterator result(nullptr, State::Consumed, current_);
    if(source_->advance()) {
        current_ = source_->get();
    } else {
        state_ = State::End;
        current_.reset();
    }
    return result;
}

template<typename T>
bool StreamProvider<T>::Iterator::operator== (Iterator& other) {
    update_initial();
    check_consumed("equality check");
    other.update_initial();
    other.check_consumed();
    if(state_ == State::End) {
        return other.state_ == State::End;
    }
    if(other.state_ == State::End) {
        return false;
    }
    return source_ == other.source_ && current_ == other.current_;
}

template<typename T>
bool StreamProvider<T>::Iterator::operator!= (Iterator& other) {
    update_initial();
    check_consumed("inequality check");
    other.update_initial();
    other.check_consumed("inequality check");
    if(state_ == State::End) {
        return other.state_ != State::End;
    }
    if(other.state_ == State::End) {
        return true;
    }
    return source_ != other.source_ || current_ != other.current_;
}

template<typename T>
void StreamProvider<T>::Iterator::update_initial() {
    if(state_ == State::Initial) {
        if(source_->advance()) {
            current_ = source_->get();
            state_ = State::Iterating;
        } else {
            current_.reset();
            state_ = State::End;
        }
    }
}

template<typename T>
void StreamProvider<T>::Iterator::check_consumed(const std::string& op) const {
    if(state_ == State::Consumed) {
        throw stream::ConsumedIteratorException(op);
    }
}

} /* namespace provider */
} /* namespace stream */

#endif


text:
interface I<T> {
    foo(x: number): T;
}

interface A extends I<number>, I<string> { }

var x: A;
// BUG 822524
var r = x.foo(1); // no error
var r2 = x.foo(''); // error

//// [callSignaturesThatDifferOnlyByReturnType2.js]
// Normally it is an error to have multiple overloads which differ only by return type in a single type declaration.
// Here the multiple overloads come from multiple bases.
var x;
// BUG 822524
var r = x.foo(1); // no error
var r2 = x.foo(''); // error


text:
package doc

import (
	"bytes"
	"errors"
	"fmt"
	"go/ast"
	"go/build"
	"go/doc"
	"go/parser"
	"go/printer"
	"go/token"
	"io"
	"io/ioutil"
	"os"
	"path"
	"regexp"
	"strings"
	"unicode"
	"unicode/utf8"

	"github.com/Unknwon/com"
)

// WalkDepth indicates how far the process goes.
type WalkDepth uint

const (
	WD_Imports WalkDepth = iota
	WD_All
)

// WalkType indicates which way to get data for walker.
type WalkType uint

const (
	WT_Local WalkType = iota
	WT_Memory
	WT_Zip
	WT_TarGz
	WT_Http
)

// WalkMode indicates which things to do.
type WalkMode uint

const (
	WM_All WalkMode = 1 << iota
	WM_NoReadme
	WM_NoExample
)

type WalkRes struct {
	WalkDepth
	WalkType
	WalkMode
	RootPath string    // For WT_Local mode.
	Srcs     []*Source // For WT_Memory mode.
	BuildAll bool
}

// ------------------------------
// WT_Local
// ------------------------------

func (w *Walker) setLocalContext(ctxt *build.Context) {
	ctxt.IsAbsPath = path.IsAbs
}

// ------------------------------
// WT_Memory
// ------------------------------

func (w *Walker) readDir(dir string) ([]os.FileInfo, error) {
	if dir != w.Pdoc.ImportPath {
		panic("unexpected")
	}
	fis := make([]os.FileInfo, 0, len(w.SrcFiles))
	for _, src := range w.SrcFiles {
		fis = append(fis, src)
	}
	return fis, nil
}

func (w *Walker) openFile(path string) (io.ReadCloser, error) {
	if strings.HasPrefix(path, w.Pdoc.ImportPath+"/") {
		if src, ok := w.SrcFiles[path[len(w.Pdoc.ImportPath)+1:]]; ok {
			return ioutil.NopCloser(bytes.NewReader(src.Data())), nil
		}
	}
	return nil, os.ErrNotExist
}

func (w *Walker) setMemoryContext(ctxt *build.Context) {
	ctxt.JoinPath = path.Join
	ctxt.IsAbsPath = path.IsAbs
	ctxt.IsDir = func(path string) bool { return true }
	ctxt.HasSubdir = func(root, dir string) (rel string, ok bool) { panic("unexpected") }
	ctxt.ReadDir = func(dir string) (fi []os.FileInfo, err error) { return w.readDir(dir) }
	ctxt.OpenFile = func(path string) (r io.ReadCloser, err error) { return w.openFile(path) }
}

var badSynopsisPrefixes = []string{
	"Autogenerated by Thrift Compiler",
	"Automatically generated ",
	"Auto-generated by ",
	"Copyright ",
	"COPYRIGHT ",
	`THE SOFTWARE IS PROVIDED "AS IS"`,
	"TODO: ",
	"vim:",
}

// Synopsis extracts the first sentence from s. All runs of whitespace are
// replaced by a single space.
func synopsis(s string) string {
	parts := strings.SplitN(s, "\n\n", 2)
	s = parts[0]

	var buf []byte
	const (
		other = iota
		period
		space
	)
	last := space
Loop:
	for i := 0; i < len(s); i++ {
		b := s[i]
		switch b {
		case ' ', '\t', '\r', '\n':
			switch last {
			case period:
				break Loop
			case other:
				buf = append(buf, ' ')
				last = space
			}
		case '.':
			last = period
			buf = append(buf, b)
		default:
			last = other
			buf = append(buf, b)
		}
	}

	// Ensure that synopsis fits an App Engine datastore text property.
	const m = 297
	if len(buf) > m {
		buf = buf[:m]
		if i := bytes.LastIndex(buf, []byte{' '}); i >= 0 {
			buf = buf[:i]
		}
		buf = append(buf, " ..."...)
	}

	s = string(buf)

	r, n := utf8.DecodeRuneInString(s)
	if n < 0 || unicode.IsPunct(r) || unicode.IsSymbol(r) {
		// ignore Markdown headings, editor settings, Go build constraints, and * in poorly formatted block comments.
		s = ""
	} else {
		for _, prefix := range badSynopsisPrefixes {
			if strings.HasPrefix(s, prefix) {
				s = ""
				break
			}
		}
	}

	return strings.TrimRight(s, " \t\n\r")
}

// poorMansImporter returns a (dummy) package object named
// by the last path component of the provided package path
// (as is the convention for packages). This is sufficient
// to resolve package identifiers without doing an actual
// import. It never returns an error.
//
func poorMansImporter(imports map[string]*ast.Object, path string) (*ast.Object, error) {
	pkg := imports[path]
	if pkg == nil {
		// Guess the package name without importing it. Start with the last
		// element of the path.
		name := path[strings.LastIndex(path, "/")+1:]

		// Trim commonly used prefixes and suffixes containing illegal name
		// runes.
		name = strings.TrimSuffix(name, ".go")
		name = strings.TrimSuffix(name, "-go")
		name = strings.TrimPrefix(name, "go.")
		name = strings.TrimPrefix(name, "go-")
		name = strings.TrimPrefix(name, "biogo.")

		pkg = ast.NewObj(ast.Pkg, name)
		pkg.Data = ast.NewScope(nil) // required by ast.NewPackage for dot-import
		imports[path] = pkg
	}
	return pkg, nil
}

type sliceWriter struct{ p *[]byte }

func (w sliceWriter) Write(p []byte) (int, error) {
	*w.p = append(*w.p, p...)
	return len(p), nil
}

func (w *Walker) printNode(node interface{}) string {
	w.Buf = w.Buf[:0]
	err := (&printer.Config{Mode: printer.UseSpaces, Tabwidth: 4}).Fprint(sliceWriter{&w.Buf}, w.Fset, node)
	if err != nil {
		return err.Error()
	}
	return string(w.Buf)
}

var exampleOutputRx = regexp.MustCompile(`(?i)//[[:space:]]*output:`)

func (w *Walker) getExamples() {
	var docs []*Example
	for _, e := range w.Examples {
		e.Name = strings.TrimPrefix(e.Name, "_")

		output := e.Output
		code := w.printNode(&printer.CommentedNode{
			Node:     e.Code,
			Comments: e.Comments,
		})

		// additional formatting if this is a function body
		if i := len(code); i >= 2 && code[0] == '{' && code[i-1] == '}' {
			// remove surrounding braces
			code = code[1 : i-1]
			// unindent
			code = strings.Replace(code, "\n    ", "\n", -1)
			// remove output comment
			if j := exampleOutputRx.FindStringIndex(code); j != nil {
				code = strings.TrimSpace(code[:j[0]])
			}
		} else {
			// drop output, as the output comment will appear in the code
			output = ""
		}

		// play := ""
		// if e.Play != nil {
		// 	w.buf = w.buf[:0]
		// 	if err := format.Node(sliceWriter{&w.buf}, w.fset, e.Play); err != nil {
		// 		play = err.Error()
		// 	} else {
		// 		play = string(w.buf)
		// 	}
		// }

		docs = append(docs, &Example{
			Name:   e.Name,
			Doc:    e.Doc,
			Code:   code,
			Output: output,
		})
		//Play:   play
	}

	w.Pdoc.Examples = docs
}

func (w *Walker) printDecl(decl ast.Node) string {
	var d Code
	d, w.Buf = printDecl(decl, w.Fset, w.Buf)
	return d.Text
}

func (w *Walker) printPos(pos token.Pos) string {
	position := w.Fset.Position(pos)
	src := w.SrcFiles[position.Filename]
	if src == nil || src.BrowseUrl == "" {
		// src can be nil when line comments are used (//line <file>:<line>).
		return ""
	}
	return src.BrowseUrl + fmt.Sprintf(w.LineFmt, position.Line)
}

func (w *Walker) values(vdocs []*doc.Value) (vals []*Value) {
	for _, d := range vdocs {
		vals = append(vals, &Value{
			Decl: w.printDecl(d.Decl),
			URL:  w.printPos(d.Decl.Pos()),
			Doc:  d.Doc,
		})
	}

	return vals
}

// printCode returns function or method code from source files.
func (w *Walker) printCode(decl ast.Node) string {
	pos := decl.Pos()
	posPos := w.Fset.Position(pos)
	src := w.SrcFiles[posPos.Filename]
	if src == nil || src.BrowseUrl == "" {
		// src can be nil when line comments are used (//line <file>:<line>).
		return ""
	}

	code, ok := w.SrcLines[posPos.Filename]
	// Check source file line arrays.
	if !ok {
		// Split source file to array and save into map when at the 1st time.
		w.SrcLines[posPos.Filename] = strings.Split(string(src.Data()), "\n")
		code = w.SrcLines[posPos.Filename]
	}

	// Get code.
	var buf bytes.Buffer
	l := len(code)
CutCode:
	for i := posPos.Line; i < l; i++ {
		// Check end of code block.
		switch {
		case len(code[i]) > 0 && code[i][0] == '}': // Normal end.
			break CutCode
		case (i == posPos.Line) && len(code[i]) == 0 && (strings.Index(code[i-1], "{") == -1): // Package `builtin`.
			break CutCode
		case len(code[i-1]) > 4 && code[i-1][:4] == "func" &&
			code[i-1][len(code[i-1])-1] == '}': // One line functions.
			line := code[i-1]
			buf.WriteString("       ")
			buf.WriteString(line[strings.Index(line, "{")+1 : len(line)-1])
			buf.WriteByte('\n')
			break CutCode
		}

		buf.WriteString(code[i])
		buf.WriteByte('\n')
	}
	return buf.String()
}

func (w *Walker) funcs(fdocs []*doc.Func) (funcs []*Func, ifuncs []*Func) {
	isBuiltIn := w.Pdoc.ImportPath == "builtin"
	for _, d := range fdocs {
		if unicode.IsUpper(rune(d.Name[0])) || isBuiltIn {
			// var exampleName string
			// switch {
			// case d.Recv == "":
			// 	exampleName = d.Name
			// case d.Recv[0] == '*':
			// 	exampleName = d.Recv[1:] + "_" + d.Name
			// default:
			// 	exampleName = d.Recv + "_" + d.Name
			// }
			funcs = append(funcs, &Func{
				Decl: w.printDecl(d.Decl),
				URL:  w.printPos(d.Decl.Pos()),
				Doc:  d.Doc,
				Name: d.Name,
				Code: w.printCode(d.Decl),
				// Recv:     d.Recv,
				// Examples: w.getExamples(exampleName),
			})
			continue
		}

		ifuncs = append(ifuncs, &Func{
			Decl: w.printDecl(d.Decl),
			URL:  w.printPos(d.Decl.Pos()),
			Doc:  d.Doc,
			Name: d.Name,
			Code: w.printCode(d.Decl),
		})
	}

	return funcs, ifuncs
}

func (w *Walker) types(tdocs []*doc.Type) (tps []*Type, itps []*Type) {
	isBuiltIn := w.Pdoc.ImportPath == "builtin"
	for _, d := range tdocs {
		funcs, ifuncs := w.funcs(d.Funcs)
		meths, imeths := w.funcs(d.Methods)

		if unicode.IsUpper(rune(d.Name[0])) || isBuiltIn {
			tps = append(tps, &Type{
				Doc:      d.Doc,
				Name:     d.Name,
				Decl:     w.printDecl(d.Decl),
				URL:      w.printPos(d.Decl.Pos()),
				Consts:   w.values(d.Consts),
				Vars:     w.values(d.Vars),
				Funcs:    funcs,
				IFuncs:   ifuncs,
				Methods:  meths,
				IMethods: imeths,
				// Examples: w.getExamples(d.Name),
			})
			continue
		}

		itps = append(itps, &Type{
			Doc:      d.Doc,
			Name:     d.Name,
			Decl:     w.printDecl(d.Decl),
			URL:      w.printPos(d.Decl.Pos()),
			Consts:   w.values(d.Consts),
			Vars:     w.values(d.Vars),
			Funcs:    funcs,
			IFuncs:   ifuncs,
			Methods:  meths,
			IMethods: imeths,
		})
	}
	return tps, itps
}

func (w *Walker) isCgo() bool {
	for _, name := range w.Pdoc.Imports {
		if name == "C" || name == "os/user" {
			return true
		}
	}
	return false
}

var goEnvs = []struct{ GOOS, GOARCH string }{
	{"linux", "amd64"},
	{"darwin", "amd64"},
	{"windows", "amd64"},
}

// Build generates documentation from given source files through 'WalkType'.
func (w *Walker) Build(wr *WalkRes) (*Package, error) {
	ctxt := build.Context{
		CgoEnabled:  true,
		ReleaseTags: build.Default.ReleaseTags,
		BuildTags:   build.Default.BuildTags,
		Compiler:    "gc",
	}

	if w.Pdoc.PkgDecl == nil {
		w.Pdoc.PkgDecl = &PkgDecl{}
	}

	// Check 'WalkType'.
	switch wr.WalkType {
	case WT_Local:
		// Check root path.
		if len(wr.RootPath) == 0 {
			return nil, errors.New("WT_Local: empty root path")
		} else if !com.IsDir(wr.RootPath) {
			return nil, errors.New("WT_Local: cannot find specific directory or it's a file")
		}

		w.setLocalContext(&ctxt)
		return nil, errors.New("Hasn't supported yet!")
	case WT_Memory:
		// Convert source files.
		w.SrcFiles = make(map[string]*Source)
		w.Pdoc.Readme = make(map[string][]byte)
		for _, src := range wr.Srcs {
			srcName := strings.ToLower(src.Name()) // For readme comparation.
			switch {
			case strings.HasSuffix(src.Name(), ".go"):
				w.SrcFiles[src.Name()] = src
			case len(w.Pdoc.Tag) > 0 || (wr.WalkMode&WM_NoReadme != 0):
				// This means we are not on the latest version of the code,
				// so we do not collect the README files.
				continue
			case strings.HasPrefix(srcName, "readme_zh") || strings.HasPrefix(srcName, "readme_cn"):
				w.Pdoc.Readme["zh"] = src.Data()
			case strings.HasPrefix(srcName, "readme"):
				w.Pdoc.Readme["en"] = src.Data()
			}
		}

		// Check source files.
		if w.SrcFiles == nil {
			return nil, errors.New("WT_Memory: no Go source file")
		}

		w.setMemoryContext(&ctxt)

	default:
		return nil, errors.New("Hasn't supported yet!")
	}

	var err error
	var bpkg *build.Package

	for _, env := range goEnvs {
		ctxt.GOOS = env.GOOS
		ctxt.GOARCH = env.GOARCH

		bpkg, err = ctxt.ImportDir(w.Pdoc.ImportPath, 0)
		// Continue if there are no Go source files; we still want the directory info.
		_, nogo := err.(*build.NoGoError)
		if err != nil {
			if nogo {
				err = nil
			} else {
				return nil, errors.New("Walker.Build -> ImportDir: " + err.Error())
			}
		}
	}

	w.Pdoc.IsCmd = bpkg.IsCommand()
	w.Pdoc.Synopsis = synopsis(bpkg.Doc)

	w.Pdoc.Imports = bpkg.Imports
	w.Pdoc.IsCgo = w.isCgo()
	w.Pdoc.TestImports = bpkg.TestImports

	// Check depth.
	if wr.WalkDepth <= WD_Imports {
		return w.Pdoc, nil
	}

	w.Fset = token.NewFileSet()
	// Parse the Go files
	files := make(map[string]*ast.File)
	for _, name := range append(bpkg.GoFiles, bpkg.CgoFiles...) {
		file, err := parser.ParseFile(w.Fset, name, w.SrcFiles[name].Data(), parser.ParseComments)
		if err != nil {
			return nil, errors.New("Walker.Build -> parse Go files: " + err.Error())
			continue
		}
		w.Pdoc.Files = append(w.Pdoc.Files, w.SrcFiles[name])
		// w.Pdoc.SourceSize += int64(len(w.SrcFiles[name].Data()))
		files[name] = file
	}

	w.apkg, _ = ast.NewPackage(w.Fset, files, poorMansImporter, nil)

	// Find examples in the test files.
	for _, name := range append(bpkg.TestGoFiles, bpkg.XTestGoFiles...) {
		file, err := parser.ParseFile(w.Fset, name, w.SrcFiles[name].Data(), parser.ParseComments)
		if err != nil {
			return nil, errors.New("Walker.Build -> find examples: " + err.Error())
			continue
		}
		w.Pdoc.TestFiles = append(w.Pdoc.TestFiles, w.SrcFiles[name])
		//w.pdoc.TestSourceSize += len(w.srcs[name].data)

		if wr.WalkMode&WM_NoExample != 0 {
			continue
		}
		w.Examples = append(w.Examples, doc.Examples(file)...)
	}

	mode := doc.Mode(0)
	if w.Pdoc.ImportPath == "builtin" || wr.BuildAll {
		mode |= doc.AllDecls
	}
	pdoc := doc.New(w.apkg, w.Pdoc.ImportPath, mode)

	// Get doc.
	pdoc.Doc = strings.TrimRight(pdoc.Doc, " \t\n\r")
	var buf bytes.Buffer
	doc.ToHTML(&buf, pdoc.Doc, nil)
	w.Pdoc.Doc = buf.String()
	// Highlight first sentence.
	w.Pdoc.Doc = strings.Replace(w.Pdoc.Doc, "
", "
", 1)
	w.Pdoc.Doc = strings.Replace(w.Pdoc.Doc, "
", "
", 1)

	if wr.WalkMode&WM_NoExample == 0 {
		w.getExamples()
	}

	w.SrcLines = make(map[string][]string)
	w.Pdoc.Consts = w.values(pdoc.Consts)
	w.Pdoc.Funcs, w.Pdoc.Ifuncs = w.funcs(pdoc.Funcs)
	w.Pdoc.Types, w.Pdoc.Itypes = w.types(pdoc.Types)
	w.Pdoc.Vars = w.values(pdoc.Vars)
	w.Pdoc.ImportPaths = strings.Join(pdoc.Imports, "|")
	w.Pdoc.ImportNum = int64(len(pdoc.Imports))
	//w.Pdoc.Notes = w.notes(pdoc.Notes)

	return w.Pdoc, nil
}


text:
All the essential magic is distilled and consolidated into the cpt_todo() method.

=======================================================================================

#### WPezClasses: Getting Started
- https://github.com/WPezClasses/wp-ezclasses-docs-getting-started

=======================================================================================

#### Overview

1) Make a copy of the boilerplate - giving it your own unique file + class name - into your theme or plugin:

https://github.com/WPezClasses/class-wp-ezclasses-cpt-rpt-1-boilerplate-1

2) Do the boilerplate's TODOs.

2.5) Don't forget to include / require it somewhere.

3) Your CPT is...Done! Yeah, that ez.


text:
package jp.mydns.sys1yagi.android.picassosample;

import jp.mydns.sys1yagi.android.picassosample.photo.GrayScaleTransformation;
import uk.co.senab.photoview.PhotoViewAttacher;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import com.squareup.picasso.Callback;
import com.squareup.picasso.Picasso;

public class PhotoDetailActivity extends Activity {
    private final static String TAG = PhotoDetailActivity.class.getSimpleName();

    private final static String PARAM_PHOTO_URL = "photo_url";

    public static Intent newIntent(Activity parent, String photoUrl) {
        Intent intent = new Intent(parent, PhotoDetailActivity.class);
        intent.putExtra(PARAM_PHOTO_URL, photoUrl);
        return intent;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTitle(getString(R.string.title_main_activity));
        setContentView(R.layout.activity_photo_detail);

        String url = getIntent().getExtras().getString(PARAM_PHOTO_URL);
        final ImageView photo = (ImageView) findViewById(R.id.photo_detail_image);

        Picasso.with(this).load(url)
        // .transform(new GrayScaleTransformation())
                .into(photo, new Callback() {
                    @Override
                    public void onError() {
                        Log.d(TAG, "error");
                    }

                    @Override
                    public void onSuccess() {
                        findViewById(R.id.progress_circular).setVisibility(
                                View.GONE);
                        // 以下はPhotoViewの機能です
                        PhotoViewAttacher attacher = new PhotoViewAttacher(
                                photo);
                    }
                });
    }
}


text:
layout: post
title: FeOpsConf Takeaways & Tools
published: true
---

Here are my main takeaways from FeOpsConf 2014. I've also aggregated and categorized all of the tools that the various speakers mentioned. For some fairly comprehensive notes, check out my [Day 1](/2014/04/24/feops-conf-day-1/) and [Day 2](/2014/04/25/feops-conf-day-2/) notes.

<!--more-->

## Takeaways

#### Lifecycle Logging

One concept that was brought up a few times was "lifecycle logging".  This means making your app rather chatty by default; having loads of log, warn & error statements in the code that explain the state of the app at all times. BazaarVoice ships with this logging in production but it is disabled until a specific cookie is set in the browser.  That way when an issue is reported, it's easy t debug in production and get closer to the root cause.

It seems like a good idea but I'm a little concerned about the extra amount of code and what kind of impact that may have on slower/mobile browsers.

#### Visual Image Diffs

It seemed like every other speaker was talking about visual regression tools. But I also think it would be hard to see through the noise.  Most development is going to cause a change and on purpose.  Image diffs might be a useful tool for QA when doing a full app regression, but I'm a little dubious about how helpful they would be to me as a developer.

#### Web Performance as a Cultural Good

This was the big takeaway for me.  Ensuring that your app is a high level of performance is not the responsibility of any one person or department.  Its not front-end's job nor is it QA's or anyone else's.  It should be a cultural value of the organization.  Everyone should know and care about what the goal is and the entire team should work every day to meet/exceed that goal.

## Tools

#### Automated Browser Testing

* [SauceLabs](https://saucelabs.com/)
* [Testling](https://ci.testling.com/)
* [dalekjs](http://dalekjs.com/)
* [QUnit Extras](https://github.com/jdalton/qunit-extras)
* [Appium](http://appium.io) - mobile test automation framework. Supports real devices, simulators and can test native, hybrid and web apps. Uses native automation capabilities of mobile platforms. Uses a Selenium WebDriver interface to connect to the various automation frameworks.
* [perfjankie](https://github.com/axemclion/perfjankie) - Grunt task to automate testing in browser, save data to CouchDB and generate graphs of metrics over time.
* [phantomas](https://github.com/macbre/phantomas) - easy to install, maintain. It has a grunt plugin.
* [gremlins.js](https://github.com/marmelab/gremlins.js)

#### Visual Regression Tools

* [scylla](http://getscylla.com/) - detect visual changes in a web app.
* [PhantomCSS](https://github.com/Huddle/PhantomCSS)
* [Wraith](https://github.com/BBC-News/wraith)
* [grunt-photobox](https://github.com/stefanjudis/grunt-photoBox)
* [Huxley](https://github.com/facebook/huxley)
* [SiteEffect](http://siteeffect.io) - can determine what changed and what was only shifted as a side effect of that change. Not released yet.

#### Web Application Performance

* [WebPageTest](http://webpagetest.org) - tool for measuring page load and request times with webpage thumbnails.
* [PageSpeed Insights](https://developers.google.com/speed/pagespeed/insights/) - best practices for desktop and mobile.
* [Boomerang](http://yahoo.github.io/boomerang/doc/) - measure webpage performance on client and report back to server.
* [chrome-ops](http://github.com/jlipps/chrome-ops) - Node.js helper library for dealing with Chromedriver performance logs
* [browser-perf](https://github.com/axemclion/browser-perf) - record actions, measure with probes and aggregate with metrics
* [SpeedCurve](http://speedcurve.com/) - dashboard tool for displaying front-end performance metrics.

#### Styleguides and Documentation

* [Rizzo](http://rizzo.lonelyplanet.com/styleguide/) - Lonely Planet's styleguide.
* [Source](http://sourcejs.com) is a front-end documentation engine.

#### CSS Testing & Optimization

* [csste.st](http://csste.st) - collection of current techniques and tools available for CSS testing
* [ucss](https://github.com/operasoftware/ucss)
* [uncss](https://github.com/giakki/uncss)
* [dom-prof](https://github.com/josh/dom-prof) - phantomjs crawler
* [DOM Monster](http://mir.aculo.us/dom-monster/) - bookmarklet
* [hardy.io](http://hardy.io) - based on selenium, uses gherkin syntax, checks copmuted style.

#### Translations

* [Transifex](https://www.transifex.com/) - SaaS translation provider
* [grunt-i18n-abide](https://github.com/mozilla/grunt-i18n-abide) - Grunt task for build translations
* [R2](https://github.com/ded/R2) - library to automatically switch styles from LTR to RTL
* [moment.js](http://momentjs.com/) - really good language support

#### Code Coverage

* [istanbul](https://github.com/gotwarlost/istanbul)
* [coveralls](http://coveralls.io)

#### Miscellaneous

* [Feature flags](https://github.com/etsy/feature) - Configuration driven access to features and library upgrades with staged rollout to users. Internal first, external piece meal.
* [Supergrep](https://github.com/etsy/supergrep) - web-based tool for accessing/reading logs.
* [node-jscs](https://github.com/mdevils/node-jscs) - Code style checker
* [git-ci-hooks](http://bit.do/git-ci)
* [Git Tutorials](http://atlassian.com/git)
* [Perspective](http://pixxa.com/) - presentation tool for displaying charts


text:
use rustc_middle::mir::visit::{
    MutatingUseContext, NonMutatingUseContext, NonUseContext, PlaceContext,
};

#[derive(Eq, PartialEq, Clone)]
pub enum DefUse {
    Def,
    Use,
    Drop,
}

pub fn categorize(context: PlaceContext) -> Option<DefUse> {
    match context {
        ///////////////////////////////////////////////////////////////////////////
        // DEFS

        PlaceContext::MutatingUse(MutatingUseContext::Store) |

        // This is potentially both a def and a use...
        PlaceContext::MutatingUse(MutatingUseContext::AsmOutput) |

        // We let Call define the result in both the success and
        // unwind cases. This is not really correct, however it
        // does not seem to be observable due to the way that we
        // generate MIR. To do things properly, we would apply
        // the def in call only to the input from the success
        // path and not the unwind path. -nmatsakis
        PlaceContext::MutatingUse(MutatingUseContext::Call) |
        PlaceContext::MutatingUse(MutatingUseContext::Yield) |

        // Storage live and storage dead aren't proper defines, but we can ignore
        // values that come before them.
        PlaceContext::NonUse(NonUseContext::StorageLive) |
        PlaceContext::NonUse(NonUseContext::StorageDead) => Some(DefUse::Def),

        ///////////////////////////////////////////////////////////////////////////
        // REGULAR USES
        //
        // These are uses that occur *outside* of a drop. For the
        // purposes of NLL, these are special in that **all** the
        // lifetimes appearing in the variable must be live for each regular use.

        PlaceContext::NonMutatingUse(NonMutatingUseContext::Projection) |
        PlaceContext::MutatingUse(MutatingUseContext::Projection) |

        // Borrows only consider their local used at the point of the borrow.
        // This won't affect the results since we use this analysis for generators
        // and we only care about the result at suspension points. Borrows cannot
        // cross suspension points so this behavior is unproblematic.
        PlaceContext::MutatingUse(MutatingUseContext::Borrow) |
        PlaceContext::NonMutatingUse(NonMutatingUseContext::SharedBorrow) |
        PlaceContext::NonMutatingUse(NonMutatingUseContext::ShallowBorrow) |
        PlaceContext::NonMutatingUse(NonMutatingUseContext::UniqueBorrow) |

        PlaceContext::MutatingUse(MutatingUseContext::AddressOf) |
        PlaceContext::NonMutatingUse(NonMutatingUseContext::AddressOf) |
        PlaceContext::NonMutatingUse(NonMutatingUseContext::Inspect) |
        PlaceContext::NonMutatingUse(NonMutatingUseContext::Copy) |
        PlaceContext::NonMutatingUse(NonMutatingUseContext::Move) |
        PlaceContext::NonUse(NonUseContext::AscribeUserTy) |
        PlaceContext::MutatingUse(MutatingUseContext::Retag) =>
            Some(DefUse::Use),

        ///////////////////////////////////////////////////////////////////////////
        // DROP USES
        //
        // These are uses that occur in a DROP (a MIR drop, not a
        // call to `std::mem::drop()`). For the purposes of NLL,
        // uses in drop are special because `#[may_dangle]`
        // attributes can affect whether lifetimes must be live.

        PlaceContext::MutatingUse(MutatingUseContext::Drop) =>
            Some(DefUse::Drop),

        // Debug info is neither def nor use.
        PlaceContext::NonUse(NonUseContext::VarDebugInfo) => None,
    }
}


text:
using System;
using System.Threading.Tasks;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Primitives;
using OrchardCore.Data;
using OrchardCore.Environment.Cache;
using OrchardCore.Shortcodes.Models;
using YesSql;

namespace OrchardCore.Shortcodes.Services
{
    public class ShortcodeTemplatesManager
    {
        private const string CacheKey = nameof(ShortcodeTemplatesManager);

        private readonly ISignal _signal;
        private readonly ISession _session;
        private readonly ISessionHelper _sessionHelper;
        private readonly IMemoryCache _memoryCache;

        public ShortcodeTemplatesManager(
            ISignal signal,
            ISession session,
            ISessionHelper sessionHelper,
            IMemoryCache memoryCache)
        {
            _signal = signal;
            _session = session;
            _sessionHelper = sessionHelper;
            _memoryCache = memoryCache;
        }

        public IChangeToken ChangeToken => _signal.GetToken(CacheKey);

        /// <summary>
        /// Returns the document from the database to be updated.
        /// </summary>
        public Task<ShortcodeTemplatesDocument> LoadShortcodeTemplatesDocumentAsync() => _sessionHelper.LoadForUpdateAsync<ShortcodeTemplatesDocument>();

        /// <summary>
        /// Returns the document from the cache or creates a new one. The result should not be updated.
        /// </summary>
        public async Task<ShortcodeTemplatesDocument> GetShortcodeTemplatesDocumentAsync()
        {
            if (!_memoryCache.TryGetValue<ShortcodeTemplatesDocument>(CacheKey, out var document))
            {
                var changeToken = ChangeToken;
                bool cacheable;

                (cacheable, document) = await _sessionHelper.GetForCachingAsync<ShortcodeTemplatesDocument>();

                if (cacheable)
                {
                    foreach (var template in document.ShortcodeTemplates.Values)
                    {
                        template.IsReadonly = true;
                    }

                    _memoryCache.Set(CacheKey, document, changeToken);
                }
            }

            return document;
        }

        public async Task RemoveShortcodeTemplateAsync(string name)
        {
            var document = await LoadShortcodeTemplatesDocumentAsync();
            document.ShortcodeTemplates.Remove(name);

            _session.Save(document);
            _signal.DeferredSignalToken(CacheKey);
        }

        public async Task UpdateShortcodeTemplateAsync(string name, ShortcodeTemplate template)
        {
            if (template.IsReadonly)
            {
                throw new ArgumentException("The object is read-only");
            }

            var document = await LoadShortcodeTemplatesDocumentAsync();
            document.ShortcodeTemplates[name.ToLower()] = template;

            _session.Save(document);
            _signal.DeferredSignalToken(CacheKey);
        }
    }
}


text:
macro(MITK_USE_MODULE)
  set(DEPENDS "")
  set(DEPENDS_BEFORE "not initialized")
  # check for each parameter if it is a package (3rd party)
  foreach(package ${ARGN})
    set(is_package)
    foreach(dir ${MODULES_PACKAGE_DEPENDS_DIRS})
      if(EXISTS "${dir}/MITK_${package}_Config.cmake")
        list(APPEND PACKAGE_DEPENDS ${package})
        set(is_package 1)
        break()
      endif()
    endforeach()
    if(NOT is_package)
      list(APPEND DEPENDS ${package})
    endif()
  endforeach(package)
  while(NOT "${DEPENDS}" STREQUAL "${DEPENDS_BEFORE}")
    set(DEPENDS_BEFORE ${DEPENDS})
    foreach(dependency ${DEPENDS})
      if(NOT ${dependency}_CONFIG_FILE)
        message(SEND_ERROR "Missing module: ${dependency}")
      endif()
      include(${${dependency}_CONFIG_FILE})
      list(APPEND DEPENDS ${${dependency}_DEPENDS})
      list(APPEND PACKAGE_DEPENDS ${${dependency}_PACKAGE_DEPENDS})
    endforeach(dependency)
    if(DEPENDS)
      list(REMOVE_DUPLICATES DEPENDS)
      list(SORT DEPENDS)
    endif(DEPENDS)
    if(PACKAGE_DEPENDS)
      list(REMOVE_DUPLICATES PACKAGE_DEPENDS)
      list(SORT PACKAGE_DEPENDS)
    endif(PACKAGE_DEPENDS)
  endwhile()
  # CMake Debug
  set(ALL_DEPENDENCIES ${DEPENDS})
  foreach(dependency ${DEPENDS} ${MODULE_DEPENDS_INTERNAL})
    if(NOT ${dependency}_CONFIG_FILE)
      message(SEND_ERROR "Missing module ${dependency}")
    endif()
    include(${${dependency}_CONFIG_FILE})
    set(ALL_INCLUDE_DIRECTORIES ${ALL_INCLUDE_DIRECTORIES} ${${dependency}_INCLUDE_DIRS})
    set(ALL_LIBRARIES ${ALL_LIBRARIES} ${${dependency}_PROVIDES})
    set(ALL_LIBRARY_DIRS ${ALL_LIBRARY_DIRS} ${${dependency}_LIBRARY_DIRS})
    if(TARGET ${dependency}-universe)
      list(APPEND ALL_META_DEPENDENCIES ${dependency}-universe)
    endif()
  endforeach(dependency)

  foreach(package ${PACKAGE_DEPENDS})
    foreach(dir ${MODULES_PACKAGE_DEPENDS_DIRS})
      if(EXISTS "${dir}/MITK_${package}_Config.cmake")
        include("${dir}/MITK_${package}_Config.cmake")
        break()
      endif()
    endforeach()
    #set(ALL_INCLUDE_DIRECTORIES ${ALL_INCLUDE_DIRECTORIES} ${${package}_INCLUDE_DIRS})
    # set(ALL_LIBRARIES ${ALL_LIBRARIES} ${${package}_LIBRARIES})
  endforeach(package)
  set(ALL_LIBRARIES ${ALL_LIBRARIES} ${MODULE_ADDITIONAL_LIBS})
  set(ALL_INCLUDE_DIRECTORIES ${ALL_INCLUDE_DIRECTORIES} ${MODULE_INCLUDE_DIRS} ${MODULE_INTERNAL_INCLUDE_DIRS} ${MODULES_CONF_DIRS})
  if(ALL_LIBRARY_DIRS)
    list(REMOVE_DUPLICATES ALL_LIBRARY_DIRS)
  endif(ALL_LIBRARY_DIRS)

endmacro(MITK_USE_MODULE)


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package app.metatron.discovery.domain.workbook.configurations.format;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;

public class PercentFormat extends NumberFieldFormat implements FieldFormat {

  public PercentFormat() {
  }

  @JsonCreator
  public PercentFormat(@JsonProperty("decimal") Integer decimal,
                       @JsonProperty("useThousandsSep") Boolean useThousandsSep) {
    super(decimal, useThousandsSep, null, null);
  }
}


text:
<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>R on StatSnips</title>
    <link>https://statsnips.github.io/tags/r/</link>
    <description>Recent content in R on StatSnips</description>
    <generator>Hugo -- gohugo.io</generator>
    <language>en-us</language>
    <copyright>&copy; 2017-2018 StatSnips. Distributed Under a MIT License.</copyright>
    <lastBuildDate>Tue, 20 Dec 2016 21:12:00 -0500</lastBuildDate>

	<atom:link href="https://statsnips.github.io/tags/r/index.xml" rel="self" type="application/rss+xml" />

    <item>
      <title>Bash R on Oracle Grid Engine (JHPCE)</title>
      <link>https://statsnips.github.io/2016/12/20/bash-r-on-oracle-grid-engine-jhpce/</link>
      <pubDate>Tue, 20 Dec 2016 21:12:00 -0500</pubDate>

      <guid>https://statsnips.github.io/2016/12/20/bash-r-on-oracle-grid-engine-jhpce/</guid>
      <description>I recently link posted on submitting Stata jobs to a Linux computing cluster running the Oracle Grid Engine. Here's a quick post on how to submit a R job.
I usually submit a qsub job by writing qsub Scripts/NAME_OF_SCRIPT into terminal. My R scripts use the following naming convention: R&lt;PROJECT&gt;_v&lt;NUM&gt;.sh or R_018v1.sh for a R bash file to run the v1 R script in the 018 project (I explain my project organization in another post).</description>
    </item>

  </channel>
</rss>


text:
<?php

namespace Magento\ImportExport\Test\Unit\Model\Import\Config;

class XsdMergedTest extends \PHPUnit_Framework_TestCase
{
    /**
     * Path to xsd schema file
     * @var string
     */
    protected $_xsdSchema;

    /**
     * @var \Magento\Framework\TestFramework\Unit\Utility\XsdValidator
     */
    protected $_xsdValidator;

    protected function setUp()
    {
        if (!function_exists('libxml_set_external_entity_loader')) {
            $this->markTestSkipped('Skipped on HHVM. Will be fixed in MAGETWO-45033');
        }
        $urnResolver = new \Magento\Framework\Config\Dom\UrnResolver();
        $this->_xsdSchema = $urnResolver->getRealPath('urn:magento:module:Magento_ImportExport:etc/import_merged.xsd');
        $this->_xsdValidator = new \Magento\Framework\TestFramework\Unit\Utility\XsdValidator();
    }

    /**
     * @param string $xmlString
     * @param array $expectedError
     * @dataProvider schemaCorrectlyIdentifiesInvalidXmlDataProvider
     */
    public function testSchemaCorrectlyIdentifiesInvalidXml($xmlString, $expectedError)
    {
        $actualError = $this->_xsdValidator->validate($this->_xsdSchema, $xmlString);
        $this->assertEquals($expectedError, $actualError);
    }

    public function testSchemaCorrectlyIdentifiesValidXml()
    {
        $xmlString = file_get_contents(__DIR__ . '/_files/valid_import_merged.xml');
        $actualResult = $this->_xsdValidator->validate($this->_xsdSchema, $xmlString);

        $this->assertEmpty($actualResult);
    }

    /**
     * Data provider with invalid xml array according to import_merged.xsd
     */
    public function schemaCorrectlyIdentifiesInvalidXmlDataProvider()
    {
        return include __DIR__ . '/_files/invalidImportMergedXmlArray.php';
    }
}


text:
package uk.co.szmg.grafana.example.dashboards;

import uk.co.szmg.grafana.DashboardFactory;
import uk.co.szmg.grafana.domain.Dashboard;

import javax.inject.Named;
import java.util.ArrayList;
import java.util.List;

import static uk.co.szmg.grafana.example.dashboards.Utils.createSimpleDashboard;

@Named
public class MyDashboardFactory implements DashboardFactory {

    @Override
    public List<Dashboard> create() {
        List<Dashboard> dashboards = new ArrayList<>();
        dashboards.add(createSimpleDashboard("By factory 1", MyDashboardFactory.class));
        dashboards.add(createSimpleDashboard("By factory 2", MyDashboardFactory.class));
        dashboards.add(createSimpleDashboard("By factory 3", MyDashboardFactory.class));
        return dashboards;
    }

}


text:
package com.xd.adhocroute1s.data;

public class Link {
	public String localIP;
	public String remoteIP;
	public int validityTime;
	public float linkQuality;
	public float neighborLinkQuality;
	public int linkCost;
}