text:
package ru.fly.client.event;

import com.google.gwt.event.shared.EventHandler;
import com.google.gwt.event.shared.GwtEvent;
import com.google.gwt.event.shared.HandlerRegistration;

/**
 * User: fil
 * Date: 11.05.2014
 */
public class CompleteEvent extends GwtEvent<CompleteEvent.CompleteHandler> {

    private static Type TYPE;

    public CompleteEvent(){}

    @SuppressWarnings("unchecked")
    public static Type<CompleteHandler> getType() {
        if (TYPE == null) {
            TYPE = new Type<>();
        }
        return TYPE;
    }

    @Override
    public Type<CompleteHandler> getAssociatedType() {
        return getType();
    }

    @Override
    protected void dispatch(CompleteHandler handler) {
        handler.onComplete();
    }

    public interface CompleteHandler extends EventHandler {
        void onComplete();
    }

    public interface HasCompleteHandler {
        HandlerRegistration addCompleteHandler(CompleteHandler h);
    }
}


text:
module.exports = function(Submission) {
    Submission.observe('before save', function(ctx, next) {
        console.log('before save!');
      if (ctx.instance) {
        ctx.instance.modified = new Date();
        ctx.instance.created = ctx.instance.created || new Date();
      } else {
        ctx.data.modified = new Date();
        ctx.data.created = ctx.data.created || new Date();
      }
      next();
    });
};

redpajama_set_name: RedPajamaGithub


text:
title: Caminante
active: "journal"
date: 2012-06-02T02:47:00-04:00
author: David Hernandez
layout: post
permalink: /errante/
image:
  feature: "http://micheandino.files.wordpress.com/2012/06/tumblr_m4yyellt2u1qa1qgjo1_1280.jpg"
header-img: "http://micheandino.files.wordpress.com/2012/06/tumblr_m4yyellt2u1qa1qgjo1_1280.jpg"
categories:
  - street
tags:
  - black and white
  - street
  - people
format: image
comments: "true"
---

Errante


text:
{% extends "govuk_template.html" %}

{% block head %}
  {% include "includes/head.html" %}
{% endblock %}

{% block cookie_message %}

{{cookieText | safe }}

{% endblock %}

{% block proposition_header %}

      Menu

          {# Set serviceName in config.js. Use a block to override on a page. #}
          {% block service_name %}
            {% if serviceName %} {{ serviceName }} {% endif %}
          {% endblock %}

{% endblock %}

{% block header_class %}
  with-proposition
{% endblock %}

{% block body_end %}
  {% include "includes/scripts.html" %}

{% endblock %}


text:
package com.theoryinpractice.testng.configuration;

import com.intellij.execution.Location;
import com.intellij.execution.RunConfigurationExtension;
import com.intellij.execution.RunnerAndConfigurationSettings;
import com.intellij.execution.actions.ConfigurationContext;
import com.intellij.execution.junit.JUnitUtil;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleUtil;
import com.intellij.openapi.project.Project;
import com.intellij.psi.JavaPsiFacade;
import com.intellij.psi.PsiDirectory;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiPackage;
import com.intellij.psi.search.GlobalSearchScope;
import com.theoryinpractice.testng.model.TestData;
import com.theoryinpractice.testng.model.TestType;
import com.theoryinpractice.testng.util.TestNGUtil;

public class TestNGPackageConfigurationProducer extends TestNGConfigurationProducer {
  private PsiPackage myPackage = null;

  protected RunnerAndConfigurationSettings createConfigurationByElement(final Location location, final ConfigurationContext context) {
    final Project project = location.getProject();
    final PsiElement element = location.getPsiElement();
    myPackage = checkPackage(element);
    if (myPackage == null) return null;
    final JavaPsiFacade facade = JavaPsiFacade.getInstance(project);
    boolean testngJarFound = false;
    for (PsiDirectory directory : myPackage.getDirectories()) {
      final Module module = ModuleUtil.findModuleForFile(directory.getVirtualFile(), project);
      if (module != null) {
        if (facade.findClass(TestNGUtil.TEST_ANNOTATION_FQN, GlobalSearchScope.moduleWithDependenciesAndLibrariesScope(module, true)) != null) {
          testngJarFound = true;
          break;
        }
      }
    }
    if (!testngJarFound) return null;
    RunnerAndConfigurationSettings settings = cloneTemplateConfiguration(project, context);
    final TestNGConfiguration configuration = (TestNGConfiguration)settings.getConfiguration();
    final TestData data = configuration.data;
    data.PACKAGE_NAME = myPackage.getQualifiedName();
    data.TEST_OBJECT = TestType.PACKAGE.getType();
    data.setScope(setupPackageConfiguration(context, project, configuration, data.getScope()));
    configuration.setGeneratedName();
    RunConfigurationExtension.patchCreatedConfiguration(configuration);
    return settings;
  }

  public PsiElement getSourceElement() {
    return myPackage;
  }

  public int compareTo(final Object o) {
    return PREFERED;
  }
}


text:
require File.expand_path('../helper', __FILE__)

class AgileZenTest < Service::TestCase
  def setup
    @stubs = Faraday::Adapter::Test::Stubs.new
  end

  def test_unspecified_branch
    payload = {'answer' => 42, 'ref' => 'refs/heads/master'}
    @stubs.post '/api/v1/projects/123/changesets/github' do |env|
      assert_equal payload.to_json,   env[:body]
      assert_equal 'test_api_key',     env[:request_headers]['X-Zen-ApiKey']
      assert_equal 'application/json', env[:request_headers]['Content-Type']
      [200, {}, '']
    end

    svc = service({'api_key' => 'test_api_key', 'project_id' => '123'}, payload)
    svc.receive_push
    @stubs.verify_stubbed_calls
  end

  def test_matching_branch
    payload = {"ref" => "refs/heads/foo"}
    @stubs.post("/api/v1/projects/123/changesets/github") { |e| [200, {}, ''] }

    svc = service({'api_key' => 'test_api_key', 'project_id' => '123', 'branches' => 'foo'}, payload)
    svc.receive_push
    @stubs.verify_stubbed_calls
  end

  def test_unmatching_branch
    payload = {"ref" => "refs/heads/bar"}
    @stubs.post("/api/v1/projects/123/changesets/github") { |e| [200, {}, ''] }

    svc = service({'api_key' => 'test_api_key', 'project_id' => '123', 'branches' => 'foo'}, payload)
    svc.receive_push

    # Test that no post fired
    begin
      @stubs.verify_stubbed_calls
    rescue RuntimeError
    else
      assert_true false
    end
  end

  def test_matching_branch_of_many
    payload = {"ref" => "refs/heads/foo"}
    @stubs.post("/api/v1/projects/123/changesets/github") { |e| [200, {}, ''] }

    svc = service({'api_key' => 'test_api_key', 'project_id' => '123', 'branches' => 'baz foo'}, payload)
    svc.receive_push
    @stubs.verify_stubbed_calls
  end

  def test_unmatching_branch_of_many
    payload = {"ref" => "refs/heads/bar"}
    @stubs.post("/api/v1/projects/123/changesets/github") { |e| [200, {}, ''] }

    svc = service({'api_key' => 'test_api_key', 'project_id' => '123', 'branches' => 'baz foo'}, payload)
    svc.receive_push

    # Test that no post fired
    begin
      @stubs.verify_stubbed_calls
    rescue RuntimeError
    else
      assert_true false
    end
  end

  def test_matching_tag
    payload = {"ref" => "refs/tags/foo"}
    @stubs.post("/api/v1/projects/123/changesets/github") { |e| [200, {}, ''] }

    svc = service({'api_key' => 'test_api_key', 'project_id' => '123', 'branches' => 'foo'}, payload)
    svc.receive_push
    @stubs.verify_stubbed_calls
  end

  def service(*args)
    super Service::AgileZen, *args
  end
end


text:
/**
 * This file is testing 4 Dependencies of both types, scripts and packages (scripts with @root)
 * The focus is on testing the @nocompile annotation.
 *
 * The output should be that some/nocompile/package.js will be referenced in the manifest
 * instead of some/nocompile/package.compiled.js.
 *
 * -
 * TODO these tests need an easily machine detectable way to indicate before/after compilation.
 *      For example: a variable named thisisavariable. After compilation that string should not be present in the code
 *      but 'a' should be.
 *
 * -
 * Memo for the future:
 * The some/nocompile/script.js should be compiled in normally, as without an inline require annotation, it does not
 * really make great sense to merge together compiled and uncompiled in one file. It does make sense, but it is a
 * code smell. I really dislike having the annotation at all honestly, but I see the practical uses for it.
 *
 * In the future this should support merging together it all, in which case script should come in uncompiled.
 *
 */

// @require some/nocompile/package.js
// @require some/nocompile/script.js
// @require some/normal/package.js
// @require some/normal/script.js

window.main = true;


text: <header> apibūdinimas </header> Trumpas šios knygos aprašymas žmonėms <hr>


text:
package jp

import (
	"bytes"
	"encoding/json"
	"log"
	"os/exec"
)

type VerbSimpleConjugation struct {
	KForm, Conjugated string
}

type VerbComplexConjugation struct {
	CForm, Politeness, Polarity, Conjugated string
}

type japkatResult struct {
	Basic   []VerbSimpleConjugation
	Complex []VerbComplexConjugation
}

type Verb struct {
	Stem, Raw string
}

func NewVerb(verb string) Verb {
	return Verb{Raw: verb}
}

func (verb *Verb) Conjugate() (error, []VerbSimpleConjugation, []VerbComplexConjugation) {
	cmd := exec.Command("JapKatsuyouCLI", verb.Raw)
	var out bytes.Buffer
	cmd.Stdout = &out
	err := cmd.Run()
	if err != nil {
		log.Fatal(err)
	}

	result := japkatResult{}
	err = json.Unmarshal(out.Bytes(), &result)
	if err != nil {
		log.Fatal(err)
	}

	verb.Stem = getStem(result.Complex)

	return err, result.Basic, result.Complex
}

func getStem(conjugations []VerbComplexConjugation) string {
	for _, value := range conjugations {
		if value.CForm == "Present" && value.Politeness == "Polite" && value.Polarity == "Affirmative" {
			// to runes
			runes := []rune(value.Conjugated)
			// remove masu (ます) and return stem
			return string(runes[:len(runes)-2])
		}
	}
	return ""
}


text:
For large applications with extensive routes files, the expense of loading
the routes file for every command that requires the rails stack can become
painfully slow.  In this case, time can be saved by marshalling the
routes to a file so that subsequent loads of the rails stack can just
unmarshal that file and be on its way.

## Installation

Add this line to your application's Gemfile:

    gem 'rails-cached-routes'

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install rails-cached-routes

## Usage

No special steps are needed to utilize rails-cached-routes as the railtie
automatically adds the functionality into place.  For each route file
processed by rails, a .cached file will be created on-the-fly whenever
the rails stack is loaded the first time.  From then on the cached
file will be used until its timestamp becomes older than the original
routes file.

## Contributing

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


text:
import * as path from 'path';
import { readServerIP } from '../aws-helper';
import { WizardBase } from './WizardBase';

export class JMeterConfigPage extends WizardBase {

  get fileUpload() { return $('//input[@type="file"]'); }
  get serverNameInput() { return $('//form//input[@name="ServerName"]'); }
  get removeButton() { return $('button=Remove'); }
  get saveButton() { return $('button*=Save'); }

  updateProperties(properties: { property: string; value: any; }[]) {
    browser.waitUntil(() => this.fileUpload.isExisting(), 15000);
    if (!this.serverNameInput.isExisting()) {
      this.uploadFile();
    }

    this.fillProperties(properties);
    browser.waitUntil(() => this.saveButton.isEnabled(), 10000);
    this.saveButton.click();
    browser.waitUntil(() => this.nextButton.isEnabled(), 10000);
    this.nextButton.click();
  }

  private fillProperties(properties: { property: string; value: any; }[]) {
    properties.forEach(({ property, value }) => {
      if (property === "ServerName") {
        value = readServerIP(value);
      }

      $(`//form//input[@name="${property}"]`).setValue(value);
    });
  }

  private uploadFile() {
    browser.execute(() => document
      .querySelector('[role="File Upload"]')
      .setAttribute("style", "display: block"));
    const filePath = path.resolve("data", "hailstorm-site-basic.jmx");
    const remoteFilePath = browser.uploadFile(filePath);
    this.fileUpload.setValue(remoteFilePath);
    browser.waitUntil(() => this.removeButton.isDisplayed(), 20000);
  }
}


text:
package iterator

import "gonum.org/v1/gonum/graph"

// Lines implements the graph.Lines interfaces.
// The iteration order of Lines is randomized.
type Lines struct {
	lines int
	iter  *mapIter
	pos   int
	curr  graph.Line
}

// NewLines returns a Lines initialized with the provided lines, a
// map of line IDs to graph.Lines. No check is made that the keys
// match the graph.Line IDs, and the map keys are not used.
//
// Behavior of the Lines is unspecified if lines is mutated after
// the call to NewLines.
func NewLines(lines map[int64]graph.Line) *Lines {
	return &Lines{lines: len(lines), iter: newMapIterLines(lines)}
}

// Len returns the remaining number of lines to be iterated over.
func (l *Lines) Len() int {
	return l.lines - l.pos
}

// Next returns whether the next call of Line will return a valid line.
func (l *Lines) Next() bool {
	if l.pos >= l.lines {
		return false
	}
	ok := l.iter.next()
	if ok {
		l.pos++
		l.curr = l.iter.line()
	}
	return ok
}

// Line returns the current line of the iterator. Next must have been
// called prior to a call to Line.
func (l *Lines) Line() graph.Line {
	return l.curr
}

// Reset returns the iterator to its initial state.
func (l *Lines) Reset() {
	l.curr = nil
	l.pos = 0
	l.iter.hiter = hiter{}
}

// LineSlice returns all the remaining lines in the iterator and advances
// the iterator. The order of lines within the returned slice is not
// specified.
func (l *Lines) LineSlice() []graph.Line {
	if l.Len() == 0 {
		return nil
	}
	lines := make([]graph.Line, 0, l.Len())
	for l.iter.next() {
		lines = append(lines, l.iter.line())
	}
	l.pos = l.lines
	return lines
}

// WeightedLines implements the graph.WeightedLines interfaces.
// The iteration order of WeightedLines is randomized.
type WeightedLines struct {
	lines int
	iter  *mapIter
	pos   int
	curr  graph.WeightedLine
}

// NewWeightedLines returns a WeightedLines initialized with the provided lines, a
// map of line IDs to graph.WeightedLines. No check is made that the keys
// match the graph.WeightedLine IDs, and the map keys are not used.
//
// Behavior of the WeightedLines is unspecified if lines is mutated after
// the call to NewWeightedLines.
func NewWeightedLines(lines map[int64]graph.WeightedLine) *WeightedLines {
	return &WeightedLines{lines: len(lines), iter: newMapIterWeightedLines(lines)}
}

// Len returns the remaining number of lines to be iterated over.
func (l *WeightedLines) Len() int {
	return l.lines - l.pos
}

// Next returns whether the next call of Line will return a valid line.
func (l *WeightedLines) Next() bool {
	if l.pos >= l.lines {
		return false
	}
	ok := l.iter.next()
	if ok {
		l.pos++
		l.curr = l.iter.weightedLine()
	}
	return ok
}

// WeightedLine returns the current line of the iterator. Next must have been
// called prior to a call to WeightedLine.
func (l *WeightedLines) WeightedLine() graph.WeightedLine {
	return l.curr
}

// Reset returns the iterator to its initial state.
func (l *WeightedLines) Reset() {
	l.curr = nil
	l.pos = 0
	l.iter.hiter = hiter{}
}

// WeightedLineSlice returns all the remaining lines in the iterator and advances
// the iterator. The order of lines within the returned slice is not
// specified.
func (l *WeightedLines) WeightedLineSlice() []graph.WeightedLine {
	if l.Len() == 0 {
		return nil
	}
	lines := make([]graph.WeightedLine, 0, l.Len())
	for l.iter.next() {
		lines = append(lines, l.iter.weightedLine())
	}
	l.pos = l.lines
	return lines
}


text: nfsprodriver's Website


text:
Referees = new Mongo.Collection('Referees');

refereesOptionMapper = function () {
    return Referees.find({}, {sort: {name: 1}}).map(function (coach) {
        return {
            label: coach.name,
            value: coach._id
        };
    });
};

RefereeSchema = new SimpleSchema({
    name: {
        type: String,
        label: 'Name'
    },
    createdAt: {
        type: Date,
        autoValue: function () {
            if (this.isInsert) {
                return new Date();
            }
        },
        denyUpdate: true,
        optional: true
    },
    updatedAt: {
        type: Date,
        autoValue: function() {
            if (this.isUpdate) {
                return new Date();
            }
        },
        optional: true
    }
});

Referees.attachSchema(RefereeSchema);

if (Meteor.isServer) {
    Referees.allow({
        insert: function () {
            return true;
        },
        update: function () {
            return true;
        },
        remove: function () {
            return true;
        }
    });

    Meteor.methods({
        addReferee: function (referee) {
            if (!Meteor.userId()) {
                throw new Meteor.Error("not-authorized");
            }

            check(referee, Referees.simpleSchema());

            if (Referees.findOne({name: referee.name}) != null) {
                throw new Meteor.Error("referee-duplicate-code", "Ein Schiedsrichter mit diesem Namen existiert bereits!");
            }

            Referees.insert({
                name: referee.name
            });

            var redirect = {
                template: 'adminReferees'
            };

            return redirect;
        },
        updateReferee: function (referee, refereeId) {
            if (!Meteor.userId()) {
                throw new Meteor.Error("not-authorized");
            }

            check(referee, Object);
            check(referee.$set, Referees.simpleSchema());
            check(refereeId, String);

            var thisReferee = Referees.findOne(refereeId);
            if (thisReferee == null) {
                throw new Meteor.Error("referee-not-found", "Schiedsrichter nicht gefunden!");
            }

            var otherReferee = Referees.findOne({name: referee.$set.name});
            if (otherReferee != null && otherReferee._id !== refereeId) {
                throw new Meteor.Error("referee-duplicate-code", "Ein Schiedsrichter mit diesem Namen existiert bereits!");
            }

            Referees.update(refereeId, referee);

            var redirect = {
                template: 'adminRefereeDetail',
                param: {_id: thisReferee._id}
            };

            return redirect;
        },
        deleteReferee: function (refereeId) {
            if (!this.userId) {
                throw new Meteor.Error("not-authorized");
            }

            check(refereeId, String);

            Referees.remove({_id: refereeId}, function (error) {
                if (error) {
                    throw new Meteor.Error("referee-remove", "Während dem Löschen ist ein Fehler aufgetreten!");
                }
            });

            var redirect = {
                template: 'adminReferees'
            };

            return redirect;
        }
    });
}


text:
ifeq ($(CONFIG),)
	CONFIG = release_x64
endif

ifeq ($(VERBOSE),)
	VERBOSE=1
endif

all : bin/nativejson_release_x64_gmake
	cd bin && ./nativejson_release_x64_gmake $(ARGS)
	cd result && make -f makefile

bin/nativejson_%_gmake : build/gmake/nativejson.make bin/nativejson_%_gmake.a
	cd build/gmake && make -f jsonstat.make config=$(CONFIG) verbose=$(VERBOSE)
	cd build/gmake && make -f nativejson.make config=$(CONFIG) verbose=$(VERBOSE)

clean :
	rm -rf build/gmake
	rm -rf build/vs2005
	rm -rf build/vs2008
	rm -rf build/vs2010
	rm -rf intermediate
	rm -rf src/machine.h
	rm -rf bin
	cd result && make -f makefile clean

setup :
	cd build && ./premake.sh && ./machine.sh

build/gmake/nativejson.make : setup
build/gmake/benchmark.make : setup
build/gmake/jsonstat.make : setup

bin/nativejson_release_x64_gmake.a : build/gmake/benchmark.make
	cd build/gmake && make -f benchmark.make config=$(CONFIG) verbose=$(VERBOSE)

clean_status :
	@echo "Filesystem status according to GIT"
	@git clean -dfxn


text:
package com.google.template.soy.jbcsrc;

import static com.google.common.base.Preconditions.checkState;

import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import com.google.template.soy.basetree.CopyState;
import com.google.template.soy.exprtree.AbstractExprNodeVisitor;
import com.google.template.soy.exprtree.DataAccessNode;
import com.google.template.soy.exprtree.ExprEquivalence;
import com.google.template.soy.exprtree.ExprNode;
import com.google.template.soy.exprtree.ExprNode.OperatorNode;
import com.google.template.soy.exprtree.ExprNode.PrimitiveNode;
import com.google.template.soy.exprtree.ExprRootNode;
import com.google.template.soy.exprtree.FunctionNode;
import com.google.template.soy.exprtree.IntegerNode;
import com.google.template.soy.exprtree.ListLiteralNode;
import com.google.template.soy.exprtree.OperatorNodes.AndOpNode;
import com.google.template.soy.exprtree.OperatorNodes.ConditionalOpNode;
import com.google.template.soy.exprtree.OperatorNodes.NullCoalescingOpNode;
import com.google.template.soy.exprtree.OperatorNodes.OrOpNode;
import com.google.template.soy.exprtree.RecordLiteralNode;
import com.google.template.soy.exprtree.VarDefn;
import com.google.template.soy.exprtree.VarRefNode;
import com.google.template.soy.jbcsrc.runtime.JbcSrcRuntime;
import com.google.template.soy.msgs.internal.MsgUtils;
import com.google.template.soy.msgs.restricted.SoyMsgPart;
import com.google.template.soy.msgs.restricted.SoyMsgPart.Case;
import com.google.template.soy.msgs.restricted.SoyMsgPlaceholderPart;
import com.google.template.soy.msgs.restricted.SoyMsgPluralCaseSpec;
import com.google.template.soy.msgs.restricted.SoyMsgPluralPart;
import com.google.template.soy.msgs.restricted.SoyMsgPluralRemainderPart;
import com.google.template.soy.msgs.restricted.SoyMsgRawTextPart;
import com.google.template.soy.msgs.restricted.SoyMsgSelectPart;
import com.google.template.soy.shared.RangeArgs;
import com.google.template.soy.shared.internal.BuiltinFunction;
import com.google.template.soy.soytree.AbstractSoyNodeVisitor;
import com.google.template.soy.soytree.CallNode;
import com.google.template.soy.soytree.CallParamContentNode;
import com.google.template.soy.soytree.CallParamNode;
import com.google.template.soy.soytree.CallParamValueNode;
import com.google.template.soy.soytree.DebuggerNode;
import com.google.template.soy.soytree.ForIfemptyNode;
import com.google.template.soy.soytree.ForNode;
import com.google.template.soy.soytree.ForNonemptyNode;
import com.google.template.soy.soytree.IfCondNode;
import com.google.template.soy.soytree.IfElseNode;
import com.google.template.soy.soytree.IfNode;
import com.google.template.soy.soytree.LetContentNode;
import com.google.template.soy.soytree.LetValueNode;
import com.google.template.soy.soytree.LogNode;
import com.google.template.soy.soytree.MsgFallbackGroupNode;
import com.google.template.soy.soytree.MsgHtmlTagNode;
import com.google.template.soy.soytree.MsgNode;
import com.google.template.soy.soytree.MsgPlaceholderNode;
import com.google.template.soy.soytree.PrintDirectiveNode;
import com.google.template.soy.soytree.PrintNode;
import com.google.template.soy.soytree.RawTextNode;
import com.google.template.soy.soytree.SoyNode;
import com.google.template.soy.soytree.SoyNode.BlockNode;
import com.google.template.soy.soytree.SoyNode.ParentSoyNode;
import com.google.template.soy.soytree.SoyNode.StandaloneNode;
import com.google.template.soy.soytree.SwitchCaseNode;
import com.google.template.soy.soytree.SwitchDefaultNode;
import com.google.template.soy.soytree.SwitchNode;
import com.google.template.soy.soytree.TemplateNode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;

/**
 * A static analyzer for how templates will access variables.
 *
 *
This class contains a generic method for constructing a control flow graph through a given Soy
 * template. We then use this graph to answer questions about the template.
 *
 *
Supported queries
 *
 *

 *
{@link #isResolved(DataAccessNode)} can tell us whether or not a particular variable or
 *       field reference has already been referenced at a given point and therefore {code
 *       SoyValueProvider#status()} has already returned {@link
 *       com.google.template.soy.jbcsrc.api.RenderResult#done()}.
 *

 *
 *
TODO(lukes): consider adding the following
 *
 *

 *
Identify the last use of a variable. Currently we use variable scopes to decide when to
 *       stop saving/restoring variables, but if we knew they were no longer in use we could save
 *       generating save/restore logic.
 *
Identify the last render of a variable. We could use this to save temporary buffers.
 *
Identify the first use of a variable. We could use this to move {let...} definitions closer
 *       to their uses.
 *

 */
final class TemplateAnalysis {
  static TemplateAnalysis analyze(TemplateNode node) {
    AccessGraph templateGraph = new PseudoEvaluatorVisitor().evaluate(node);
    return new TemplateAnalysis(templateGraph.getResolvedExpressions());
  }

  private final ImmutableSet<ExprNode> resolvedExpressions;

  private TemplateAnalysis(Set<ExprNode> definitelyAccessedRefs) {
    this.resolvedExpressions = ImmutableSet.copyOf(definitelyAccessedRefs);
  }

  /**
   * Returns true if this variable reference is definitely not the first reference to the variable
   * within a given template.
   */
  boolean isResolved(VarRefNode ref) {
    return resolvedExpressions.contains(ref);
  }

  /**
   * Returns true if this data access is definitely not the first reference to the field or item
   * within a given template.
   */
  boolean isResolved(DataAccessNode ref) {
    return resolvedExpressions.contains(ref);
  }

  /**
   * This visitor (and the {@link PseudoEvaluatorExprVisitor}) visits every Soy node in the order
   * that the code generated from those node would execute and contructs an {@link AccessGraph}.
   */
  private static final class PseudoEvaluatorVisitor extends AbstractSoyNodeVisitor<Void> {
    final Map<VarDefn, AccessGraph> letNodes = new HashMap<>();
    final PseudoEvaluatorExprVisitor exprVisitor = new PseudoEvaluatorExprVisitor(letNodes);
    final ExprEquivalence exprEquivalence = new ExprEquivalence();
    Block current;

    AccessGraph evaluate(TemplateNode node) {
      Block start = new Block();
      Block finalNode = exec(start, node);
      checkState(finalNode.successors.isEmpty());
      // annotate the graph with predecessor links
      addPredecessors(start);
      // TODO(lukes): due to the way we build the graph we may have lots of either empty nodes or
      // nodes with unconditional branches.  We could reduce the size of the graph by trying to
      // eliminate such nodes.  This may be worth it if we end up doing many traversals instead of
      // the current 1.
      return new AccessGraph(start, finalNode, exprEquivalence);
    }

    /**
     * Visit the given node and append all accesses to the given block.
     *
     *
Returns the ending block.
     */
    Block exec(Block block, SoyNode node) {
      Block original = this.current;
      this.current = block;
      visit(node);
      Block rVal = current;
      this.current = original;
      return rVal;
    }

    @Override
    protected void visitPrintNode(PrintNode node) {
      evalInline(node.getExpr());
      for (PrintDirectiveNode directive : node.getChildren()) {
        for (ExprRootNode arg : directive.getArgs()) {
          evalInline(arg);
        }
      }
    }

    @Override
    protected void visitRawTextNode(RawTextNode node) {
      // do nothing
    }

    @Override
    protected void visitLogNode(LogNode node) {
      visitChildren(node);
    }

    @Override
    protected void visitDebuggerNode(DebuggerNode node) {
      // do nothing
    }

    @Override
    protected void visitTemplateNode(TemplateNode node) {
      visitChildren(node);
    }

    @Override
    protected void visitForNode(ForNode node) {
      // the list is always evaluated first.
      evalInline(node.getExpr());

      Block loopBegin = this.current;
      // create a branch for the loop body
      Block loopBody = loopBegin.addBranch();
      Block loopEnd = exec(loopBody, node.getChild(0));
      // If we can statically prove the list empty, use that information.
      StaticAnalysisResult isLoopEmpty = isListExpressionEmpty(node);
      if (node.numChildren() == 2) { // there is an {ifempty} block
        Block ifEmptyBlock = loopBegin.addBranch();
        Block ifEmptyEnd = exec(ifEmptyBlock, node.getChild(1));
        switch (isLoopEmpty) {
          case FALSE:
            this.current = loopEnd.addBranch();
            break;
          case TRUE:
            this.current = ifEmptyEnd.addBranch();
            break;
          case UNKNOWN:
            this.current = Block.merge(loopEnd, ifEmptyEnd);
            break;
        }
      } else {
        switch (isLoopEmpty) {
          case FALSE:
            this.current = loopEnd.addBranch();
            break;
          case TRUE:
            this.current = loopBegin.addBranch();
            break;
          case UNKNOWN:
            this.current = Block.merge(loopEnd, loopBegin);
            break;
        }
      }
    }

    @Override
    protected void visitForIfemptyNode(ForIfemptyNode node) {
      visitChildren(node);
    }

    @Override
    protected void visitForNonemptyNode(ForNonemptyNode node) {
      visitChildren(node);
    }

    @Override
    protected void visitLetContentNode(LetContentNode node) {
      // Due to lazy evaluation we don't evaluate these at the declaration site.  Instead we have
      // to fix them up after the fact.  So calculate and store their basic blocks here.  We will
      // wire them into the graph later.
      Block startBlock = new Block();
      Block block = startBlock;
      for (StandaloneNode child : node.getChildren()) {
        block = exec(block, child);
      }
      letNodes.put(node.getVar(), new AccessGraph(startBlock, block, exprEquivalence));
    }

    @Override
    protected void visitLetValueNode(LetValueNode node) {
      // see visitLetContentNode
      Block start = new Block();
      Block end = exprVisitor.eval(start, node.getExpr());
      letNodes.put(node.getVar(), new AccessGraph(start, end, exprEquivalence));
    }

    @Override
    protected void visitSwitchNode(SwitchNode node) {
      // A few special cases.  See SoyNodeCompiler.visitSwitchNode
      // * no children => don't evaluate the switch expression
      // * no cases => don't evaluate the switch expression

      List<BlockNode> children = node.getChildren();
      if (children.isEmpty()) {
        return;
      }
      if (children.size() == 1 && children.get(0) instanceof SwitchDefaultNode) {
        visitChildren(children.get(0));
        return;
      }
      // otherwise we are in the normal case and this is much like an if-elseif-else statement
      // First eval the expr
      evalInline(node.getExpr());
      // The one special case is that there are allowed to be multiple conditions per case.
      // For these, only the first one is necessarily evaluated.
      Block conditions = null;
      List<Block> branchEnds = new ArrayList<>();
      boolean hasDefault = false;
      for (SoyNode child : node.getChildren()) {
        if (child instanceof SwitchCaseNode) {
          SwitchCaseNode scn = (SwitchCaseNode) child;
          Block caseBlockStart = new Block();
          Block caseBlockEnd = exec(caseBlockStart, scn);
          branchEnds.add(caseBlockEnd);

          for (ExprRootNode expr : scn.getExprList()) {
            if (conditions == null) {
              evalInline(expr); // the very first condition is always evaluated
              conditions = this.current;
            } else {
              // otherwise we are only maybe evaluating this condition
              Block condition = conditions.addBranch();
              conditions = exprVisitor.eval(condition, expr);
            }
            conditions.successors.add(caseBlockStart);
          }

        } else {
          SwitchDefaultNode ien = (SwitchDefaultNode) child;
          Block defaultBlockStart = conditions.addBranch();
          Block defaultBlockEnd = exec(defaultBlockStart, ien);
          branchEnds.add(defaultBlockEnd);
          hasDefault = true;
        }
      }
      if (!hasDefault) {
        branchEnds.add(conditions);
      }
      this.current = Block.merge(branchEnds);
    }

    @Override
    protected void visitSwitchCaseNode(SwitchCaseNode node) {
      visitChildren(node);
    }

    @Override
    protected void visitSwitchDefaultNode(SwitchDefaultNode node) {
      visitChildren(node);
    }

    @Override
    protected void visitIfNode(IfNode node) {
      // For ifs we always evaluate the first condition and if there is an 'else' clause at least
      // one of the branches.  Things get trickier if we have multiple conditions.  for example,
      // {if $p1}W{elseif $p2}X{else}Y{/if}Z
      // at position W $p1 has been ref'd
      // at position X $p1 and $p2 have been ref'd
      // at position Y $p1 and $p2 have been ref'd
      // at position Z only $p1 has definitely been ref'd
      // To handle all these cases we need to manage a bunch of forks
      Block conditionFork = null;
      List<Block> branchEnds = new ArrayList<>();
      boolean hasElse = false;
      for (SoyNode child : node.getChildren()) {
        if (child instanceof IfCondNode) {
          IfCondNode icn = (IfCondNode) child;
          ExprRootNode conditionExpression = icn.getExpr();
          if (conditionFork == null) {
            // first condition is always evaluated
            evalInline(conditionExpression);
            conditionFork = this.current;
          } else {
            conditionFork = exprVisitor.eval(conditionFork.addBranch(), conditionExpression);
          }
          Block branch = conditionFork.addBranch();
          branch = exec(branch, icn);
          branchEnds.add(branch);
        } else {
          IfElseNode ien = (IfElseNode) child;
          Block branch = conditionFork.addBranch();
          branch = exec(branch, ien);
          branchEnds.add(branch);
          hasElse = true;
        }
      }
      if (!hasElse) {
        branchEnds.add(conditionFork);
      }
      this.current = Block.merge(branchEnds);
    }

    @Override
    protected void visitIfCondNode(IfCondNode node) {
      visitChildren(node);
    }

    @Override
    protected void visitIfElseNode(IfElseNode node) {
      visitChildren(node);
    }

    @Override
    protected void visitCallNode(CallNode node) {
      // If there is a data="<expr>" this is always evaluated first.
      ExprRootNode dataExpr = node.getDataExpr();
      if (dataExpr != null) {
        evalInline(dataExpr);
      }
      // template params are evaluated lazily in the callee, so we don't know whether or not any
      // of them will be evaluated.  So treat each param like an optional branch.
      // Also we don't know anything about the relative ordering of each param. technically all
      // orderings are possible, but instead of that we just assume they are all mutually exclusive.
      // TODO(lukes): if we were modeling 'back-edges' we could treat params like a loop by putting
      // an optional back edge at the bottom of each one.  this would achieve the result of
      // modelling all possible orderings.  For our current usecases this is unnecessary.
      Block begin = this.current;
      List<Block> branchEnds = new ArrayList<>();
      branchEnds.add(
          begin); // this ensures that there is a path that doesn't go through any of the params
      for (CallParamNode param : node.getChildren()) {
        Block paramBranch = begin.addBranch();
        Block paramBranchEnd = exec(paramBranch, param);
        branchEnds.add(paramBranchEnd);
      }
      this.current = Block.merge(branchEnds);
    }

    @Override
    protected void visitCallParamValueNode(CallParamValueNode node) {
      // params are evaluated in their own fork.
      evalInline(node.getExpr());
    }

    @Override
    protected void visitCallParamContentNode(CallParamContentNode node) {
      visitChildren(node);
    }

    @Override
    protected void visitMsgFallbackGroupNode(MsgFallbackGroupNode node) {
      if (node.numChildren() == 1) {
        // there is a single message, evaluate inline
        visit(node.getChild(0));
      } else {
        // there is a fallback. then we have normal a branching structure
        Block normalBranch = this.current.addBranch();
        Block fallbackBranch = this.current.addBranch();

        normalBranch = exec(normalBranch, node.getChild(0));
        fallbackBranch = exec(fallbackBranch, node.getChild(1));
        this.current = Block.merge(normalBranch, fallbackBranch);
      }
    }

    @Override
    protected void visitMsgNode(MsgNode node) {
      // for {msg} nodes we always build a placeholder map of all the placeholders in the order
      // defined by the parsed 'msg parts'.  See MsgCompiler.
      evaluateMsgParts(node, MsgUtils.buildMsgPartsAndComputeMsgIdForDualFormat(node).parts);
    }

    /**
     * Visits all the placeholders of a {msg} in the same order that the MsgCompiler generates code.
     */
    private void evaluateMsgParts(MsgNode msgNode, Iterable<? extends SoyMsgPart> parts) {
      // Note:  The same placeholder may show up multiple times.  In the MsgCompiler we use a
      // separate data structure to dedup so we don't generate the same code for the same
      // placeholder multiple times.  This isn't a concern here because our 'pseudo evaluation'
      // process is idempotent.
      for (SoyMsgPart part : parts) {
        if (part instanceof SoyMsgRawTextPart || part instanceof SoyMsgPluralRemainderPart) {
          // raw text and plural remainders don't have associated expressions
          continue;
        }
        if (part instanceof SoyMsgPluralPart) {
          SoyMsgPluralPart plural = (SoyMsgPluralPart) part;
          evalInline(msgNode.getRepPluralNode(plural.getPluralVarName()).getExpr());
          // Recursively visit plural cases
          for (Case<SoyMsgPluralCaseSpec> caseOrDefault : plural.getCases()) {
            evaluateMsgParts(msgNode, caseOrDefault.parts());
          }
        } else if (part instanceof SoyMsgSelectPart) {
          SoyMsgSelectPart select = (SoyMsgSelectPart) part;
          evalInline(msgNode.getRepSelectNode(select.getSelectVarName()).getExpr());
          // Recursively visit select cases
          for (Case<String> caseOrDefault : select.getCases()) {
            evaluateMsgParts(msgNode, caseOrDefault.parts());
          }
        } else if (part instanceof SoyMsgPlaceholderPart) {
          SoyMsgPlaceholderPart placeholder = (SoyMsgPlaceholderPart) part;
          visit(msgNode.getRepPlaceholderNode(placeholder.getPlaceholderName()).getChild(0));
        } else {
          throw new AssertionError("unexpected part: " + part);
        }
      }
    }

    @Override
    protected void visitMsgPlaceholderNode(MsgPlaceholderNode node) {
      visitChildren(node);
    }

    @Override
    protected void visitMsgHtmlTagNode(MsgHtmlTagNode node) {
      visitChildren(node);
    }

    @Override
    protected void visitSoyNode(SoyNode node) {
      throw new UnsupportedOperationException("unsupported node type: " + node.getKind());
    }

    // override to make it visible
    @Override
    protected void visitChildren(ParentSoyNode<?> node) {
      super.visitChildren(node);
    }

    /** Evaluates the given expression in the current block. */
    void evalInline(ExprNode expr) {
      Block begin = current;
      Block end = exprVisitor.eval(begin, expr);
      current = end;
    }
  }

  private enum StaticAnalysisResult {
    TRUE,
    FALSE,
    UNKNOWN;
  }

  // consider moving this to SoyTreeUtils or some similar place.
  private static StaticAnalysisResult isListExpressionEmpty(ForNode node) {
    Optional<RangeArgs> rangeArgs = RangeArgs.createFromNode(node);
    if (rangeArgs.isPresent()) {
      return isRangeExpressionEmpty(rangeArgs.get());
    }
    ExprNode expr = node.getExpr().getRoot();
    if (expr instanceof ListLiteralNode) {
      return ((ListLiteralNode) expr).numChildren() > 0
          ? StaticAnalysisResult.FALSE
          : StaticAnalysisResult.TRUE;
    }
    return StaticAnalysisResult.UNKNOWN;
  }

  private static StaticAnalysisResult isRangeExpressionEmpty(RangeArgs range) {
    int start = 0;
    if (range.start().isPresent()) {
      if (range.start().get() instanceof IntegerNode) {
        long startAsLong = ((IntegerNode) range.start().get()).getValue();
        if (startAsLong != (int) startAsLong) {
          return StaticAnalysisResult.UNKNOWN;
        }
        start = (int) startAsLong;
      } else {
        // if the start is not a constant then we don't know anything
        return StaticAnalysisResult.UNKNOWN;
      }
    }

    int limit;
    if (range.limit() instanceof IntegerNode) {
      long limitAsLong = ((IntegerNode) range.limit()).getValue();
      if (limitAsLong != (int) limitAsLong) {
        return StaticAnalysisResult.UNKNOWN;
      }
      limit = (int) limitAsLong;
    } else {
      return StaticAnalysisResult.UNKNOWN;
    }

    int step = 1;
    if (range.increment().isPresent()) {
      if (range.increment().get() instanceof IntegerNode) {
        long stepAsLong = ((IntegerNode) range.increment().get()).getValue();
        if (stepAsLong != (int) stepAsLong) {
          return StaticAnalysisResult.UNKNOWN;
        }
        step = (int) stepAsLong;
      } else {
        return StaticAnalysisResult.UNKNOWN;
      }
    }
    return JbcSrcRuntime.rangeLoopLength(start, limit, step) > 0
        ? StaticAnalysisResult.FALSE
        : StaticAnalysisResult.TRUE;
  }

  private static final class PseudoEvaluatorExprVisitor extends AbstractExprNodeVisitor<Void> {
    final Map<VarDefn, AccessGraph> letNodes;
    Block current;

    PseudoEvaluatorExprVisitor(Map<VarDefn, AccessGraph> letNodes) {
      this.letNodes = letNodes;
    }

    /** Evaluates the given expression in the given block. Returns the ending or 'exit' block. */
    Block eval(Block block, ExprNode expr) {
      Block orig = this.current;
      this.current = block;
      visit(expr);
      Block rVal = this.current;
      this.current = orig;
      return rVal;
    }

    @Override
    protected void visitExprRootNode(ExprRootNode node) {
      visit(node.getRoot());
    }

    @Override
    protected void visitVarRefNode(VarRefNode node) {
      AccessGraph letContent = letNodes.get(node.getDefnDecl());
      if (letContent != null) {
        // because let nodes are lazily executed, we model this in the access graph as each let
        // varref branching to a copy of the implementation and back. This ensures that each
        // variable referenced by the {let} is referenced prior to the let variable.
        // Additionally we add a dead end branch from just prior the let to the canonical let
        // implementation block
        //
        // this means that the graph structure for this:
        // {let $foo : $p /}
        // {$foo}
        //
        // is
        //          -> <foo-original>
        // <begin>
        //          -> <foo copy> -> <$foo>  -> <end>
        // This ensures that the variable references within the let are analyzed as being executed
        // immediately prior to any of the references.
        AccessGraph copy = letContent.copy();
        // dead end branch to the canonical
        this.current.successors.add(letContent.start);
        // branch to and back from the copy
        this.current.successors.add(copy.start);
        this.current = copy.end.addBranch();
      }
      current.add(node);
    }

    @Override
    protected void visitDataAccessNode(DataAccessNode node) {
      visitChildren(node); // visit subexpressions first
      current.add(node);
    }

    @Override
    protected void visitFunctionNode(FunctionNode node) {
      if (node.getSoyFunction() instanceof BuiltinFunction) {
        BuiltinFunction builtinFunction = (BuiltinFunction) node.getSoyFunction();
        switch (builtinFunction) {
          case INDEX:
          case IS_FIRST:
          case IS_LAST:
            // early return for these.  the AST looks like we are evaluating a var, but in fact we
            // generate alternate code to reference a synthetic variable.
            // See ExpressionCompiler
            return;
          case CHECK_NOT_NULL:
          case CSS:
          case XID:
            // fall through
            break;
          case UNKNOWN_JS_GLOBAL:
          case LEGACY_DYNAMIC_TAG:
          case V1_EXPRESSION:
            throw new UnsupportedOperationException(
                "the "
                    + builtinFunction.getName()
                    + " function can't be used in templates compiled to Java");
          default:
            throw new AssertionError("unexpected builtin function");
        }
      }
      // eval all arguments in order
      visitChildren(node);
    }

    @Override
    protected void visitPrimitiveNode(PrimitiveNode node) {
      // do nothing.
    }

    @Override
    protected void visitListLiteralNode(ListLiteralNode node) {
      visitChildren(node);
    }

    @Override
    protected void visitRecordLiteralNode(RecordLiteralNode node) {
      visitChildren(node);
    }

    // Most operators always evaluate their arguments, the control flow operators are handled
    // separately
    @Override
    protected void visitOperatorNode(OperatorNode node) {
      visitChildren(node);
    }

    @Override
    protected void visitNullCoalescingOpNode(NullCoalescingOpNode node) {
      visit(node.getLeftChild());
      // The right side may or may not be evaluated
      executeInBranch(node.getRightChild());
    }

    @Override
    protected void visitOrOpNode(OrOpNode node) {
      visit(node.getChild(0));
      executeInBranch(node.getChild(1));
    }

    @Override
    protected void visitAndOpNode(AndOpNode node) {
      visit(node.getChild(0));
      executeInBranch(node.getChild(1));
    }

    /** Evaluates the given node in an optional branch. */
    private void executeInBranch(ExprNode expr) {
      Block prev = current;
      Block branch = prev.addBranch();
      branch = eval(branch, expr);
      // Add a successor node to merge the branches back together.
      current = Block.merge(prev, branch);
    }

    @Override
    protected void visitConditionalOpNode(ConditionalOpNode node) {
      visit(node.getChild(0));
      current =
          Block.merge(
              eval(current.addBranch(), node.getChild(1)),
              eval(current.addBranch(), node.getChild(2)));
    }
  }

  /**
   * Traverses the control flow graph reachable from {@code start} and adds all the predecessor
   * links.
   */
  private static void addPredecessors(Block start) {
    Set<Block> visited = Sets.newIdentityHashSet();
    addPredecessors(start, visited);
  }

  private static void addPredecessors(Block current, Set<Block> visited) {
    if (!visited.add(current)) {
      return;
    }
    for (Block successor : current.successors) {
      successor.predecessors.add(current);
      addPredecessors(successor, visited);
    }
  }

  /**
   * A graph of {@link Block blocks} for a given template showing how control flows through the
   * expressions of the template.
   *
   *
Note this is almost a classic Control Flow Graph
   * https://en.wikipedia.org/wiki/Control_flow_graph with the following exceptions
   *
   *

   *
We aren't tracking 'back edges' (e.g. loops) accurately.
   *
We are tracking a small subset of the operations performed while evaluating a template.
   *       Currently only {@link VarRefNode variable references} and {@link DataAccessNode data
   *       access} operations.
   *

   *
   * Both of these limitations exist simply because we don't have usecases for tracking this data
   * yet.
   */
  private static final class AccessGraph {
    final Block start;
    final Block end;
    final ExprEquivalence exprEquivalence;

    AccessGraph(Block start, Block end, ExprEquivalence exprEquivalence) {
      this.start = start;
      this.end = end;
      this.exprEquivalence = exprEquivalence;
    }

    /** Creates a copy of the block. Note, this does not clone the {@code #exprs}. */
    AccessGraph copy() {
      Map<Block, Block> originalToCopy = new IdentityHashMap<>();
      Block newStart = shallowCopyBlock(start, originalToCopy);
      Block newEnd = originalToCopy.get(end);
      return new AccessGraph(newStart, newEnd, exprEquivalence);
    }

    /** Returns a set of ExprNodes that have definitely already been resolved. */
    Set<ExprNode> getResolvedExpressions() {
      // To implement we need to walk through the access graph and if we find any path to an
      // expression that doesn't go through another reference to the 'same expression'
      // The easiest way to do this is to calculate 'all paths' through the graph and then do a
      // search. Unfortunately, 'all paths through a DAG' is technically an exponential time
      // algorithm
      // But fortunately we can do better.  We can do a DFS from every expression to the start node
      // and if we go through another reference to the same expression we can abort. If we find any
      // path to 'start' from the expression then we can remove it from the set.
      // Still, DFS from every node is technically O(N^2 + MN)).  This too can be resolved with
      // dynamic programming to make it O(N + M).  To do this we have to limit the number of paths
      // traversed by accumulating results.
      // If we do a Topological traversal from the start node then whenever we visit a node we will
      // have already visited all of its predecessors.  The set of variables definitely accessed
      // prior to a node is simply the intersection of all the accessed variables from its
      // predecessors.  So each node can be processed in time relative to the number of incoming
      // edges.

      Set<ExprNode> resolvedExprs = Sets.newIdentityHashSet();
      Map<Block, Set<ExprEquivalence.Wrapper>> blockToAccessedExprs = new IdentityHashMap<>();
      for (Block current : getTopologicalOrdering()) {
        // First calculate the set of exprs that were definitely accessed prior to this node
        Set<ExprEquivalence.Wrapper> currentBlockSet =
            mergePredecessors(blockToAccessedExprs, current);
        // Then figure out which nodes in this block were _already_ accessed.
        for (ExprNode expr : current.exprs) {
          ExprEquivalence.Wrapper wrapped = exprEquivalence.wrap(expr);
          if (!currentBlockSet.add(wrapped)) {
            resolvedExprs.add(expr);
          }
        }
        blockToAccessedExprs.put(current, currentBlockSet);
      }
      return resolvedExprs;
    }

    static Set<ExprEquivalence.Wrapper> mergePredecessors(
        Map<Block, Set<ExprEquivalence.Wrapper>> blockToAccessedExprs, Block current) {
      Set<ExprEquivalence.Wrapper> currentBlockSet = null;
      for (Block predecessor : current.predecessors) {
        Set<ExprEquivalence.Wrapper> predecessorBlockSet = blockToAccessedExprs.get(predecessor);
        if (currentBlockSet == null) {
          currentBlockSet = new HashSet<>(predecessorBlockSet);
        } else {
          currentBlockSet.retainAll(predecessorBlockSet);
        }
      }
      if (currentBlockSet == null) {
        currentBlockSet = new HashSet<>();
      }
      return currentBlockSet;
    }

    private List<Block> getTopologicalOrdering() {
      List<Block> ordering = new ArrayList<>();
      Set<Block> visited = Sets.newIdentityHashSet();
      Set<Block> discoveredButNotVisited = Sets.newIdentityHashSet();
      discoveredButNotVisited.add(start);
      outer:
      while (!discoveredButNotVisited.isEmpty()) {
        for (Block notVisited : discoveredButNotVisited) {
          // If we have already visited all predecessors
          if (visited.containsAll(notVisited.predecessors)) {
            discoveredButNotVisited.remove(notVisited);
            visited.add(notVisited);
            discoveredButNotVisited.addAll(notVisited.successors);
            ordering.add(notVisited);
            continue outer;
          }
        }
        throw new AssertionError("failed to make progress");
      }
      return ordering;
    }

    private static Block shallowCopyBlock(Block original, Map<Block, Block> originalToCopy) {
      if (originalToCopy.containsKey(original)) {
        return originalToCopy.get(original);
      }
      Block copy = new Block();
      for (ExprNode expr : original.exprs) {
        copy.exprs.add(expr.copy(new CopyState()));
      }
      // update the map before recursing to avoid infinite loops
      originalToCopy.put(original, copy);
      for (Block successor : original.successors) {
        copy.successors.add(shallowCopyBlock(successor, originalToCopy));
      }
      for (Block predecessor : original.predecessors) {
        copy.predecessors.add(shallowCopyBlock(predecessor, originalToCopy));
      }
      return copy;
    }
  }

  /**
   * A block is a linear sequence of evaluations that happen with no branches.
   *
   *
Each block has an arbitrary number of {@link Block#predecessors} and {@link
   * Block#successors} representing all the blocks that come immediately prior to or after this
   * node.
   *
   *
This essentially a 'basic block' https://en.wikipedia.org/wiki/Basic_block with the caveat
   * that we are tracking expressions instead of instructions.
   */
  private static final class Block {
    static Block merge(Block... preds) {
      return merge(Arrays.asList(preds));
    }

    static Block merge(List<Block> preds) {
      Block end = new Block();
      for (Block pred : preds) {
        pred.successors.add(end);
      }
      return end;
    }

    // This list will contain either DataAccessNode or VarRefNodes, eventually we may want to add
    // all 'leaf' nodes.
    final List<ExprNode> exprs = new ArrayList<>();
    final Collection<Block> successors = new LinkedHashSet<>();
    final Collection<Block> predecessors = new LinkedHashSet<>();

    void add(VarRefNode var) {
      exprs.add(var);
    }

    void add(DataAccessNode dataAccess) {
      exprs.add(dataAccess);
    }

    // Returns a new block that is a successor to this one
    Block addBranch() {
      Block branch = new Block();
      successors.add(branch);
      return branch;
    }

    @Override
    public String toString() {
      return getClass().getSimpleName()
          + ImmutableMap.of(
              "exprs", exprs,
              "in_edges", predecessors.size(),
              "out_edges", successors.size());
    }
  }
}


text:
package com.percolate.sdk.dto;

import com.fasterxml.jackson.annotation.*;
import com.percolate.sdk.interfaces.HasExtraFields;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;

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

@SuppressWarnings("UnusedDeclaration")
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class InstagramMediaUrls implements Serializable, HasExtraFields {

    private static final long serialVersionUID = 2367488877752973375L;

    @JsonProperty("standardResolution")
    protected InstagramMediaUrl standardResolution;

    @JsonProperty("low_resolution")
    protected InstagramMediaUrl lowResolution;

    @JsonProperty("low_bandwidth")
    protected InstagramMediaUrl lowBandwidth;

    @JsonIgnore
    protected Map<String, Object> extraFields = new HashMap<>();

    @Override
    public String toString() {
        return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
    }

    public InstagramMediaUrl getStandardResolution() {
        return standardResolution;
    }

    public void setStandardResolution(InstagramMediaUrl standardResolution) {
        this.standardResolution = standardResolution;
    }

    public InstagramMediaUrl getLowResolution() {
        return lowResolution;
    }

    public void setLowResolution(InstagramMediaUrl lowResolution) {
        this.lowResolution = lowResolution;
    }

    public InstagramMediaUrl getLowBandwidth() {
        return lowBandwidth;
    }

    public void setLowBandwidth(InstagramMediaUrl lowBandwidth) {
        this.lowBandwidth = lowBandwidth;
    }

    @Override
    public Map<String, Object> getExtraFields() {
        if(extraFields == null) {
            extraFields = new HashMap<>();
        }
        return extraFields;
    }

    @Override
    @JsonAnySetter
    public void putExtraField(String key, Object value) {
        getExtraFields().put(key, value);
    }
}


text:
package org.adoptajsr.java8.benchmarks;

import org.junit.Assert;
import org.junit.Test;

/**
 *
 * @author richard
 */
public class VectorDotProductTest {

    private static final VectorDotProducts underTest = new VectorDotProducts();
    static {
        underTest.x = new double[] {1, 2};
        underTest.y = new double[] {2, 1};
        underTest.setupDerivedData();
    }

    @Test
    public void gsImplementation() {
        Assert.assertEquals(4D, underTest.timeGSDotProduct(1), 0.0001);
    }

    @Test
    public void imperativeImplementation() {
        Assert.assertEquals(4D, underTest.timeImperativeDotProduct(1), 0.0001);
    }

    @Test
    public void imperativeBoxedImplementation() {
        Assert.assertEquals(4D, underTest.timeImperativeBoxedDotProduct(1), 0.0001);
    }

    @Test
    public void lambdaImplementation() {
        Assert.assertEquals(4D, underTest.timeLambdaDotProduct(1), 0.0001);
    }

}


text:
<?php

class Mage_Core_Block_Profiler extends Mage_Core_Block_Abstract
{
    protected function _toHtml()
    {
        if (!$this->_beforeToHtml()
            || !Mage::getStoreConfig('dev/debug/profiler')
            || !Mage::helper('core')->isDevAllowed()) {
            return '';
        }

        $timers = Varien_Profiler::getTimers();

        #$out = '
';
        #$out = '
';
        $out = "[profiler]";
        $out .= '
';
        $out .= '
Memory usage: real: '.memory_get_usage(true).', emalloc: '.memory_get_usage().'
';
        $out .= '
';
        $out .= '
Code Profiler	Time	Cnt	Emalloc	RealMem
';
        foreach ($timers as $name=>$timer) {
            $sum = Varien_Profiler::fetch($name,'sum');
            $count = Varien_Profiler::fetch($name,'count');
            $realmem = Varien_Profiler::fetch($name,'realmem');
            $emalloc = Varien_Profiler::fetch($name,'emalloc');
            if ($sum<.0010 && $count<10 && $emalloc<10000) {
                continue;
            }
            $out .= '
'
                .''.$name.'	'
                .''.number_format($sum,4).'	'
                .''.$count.'	'
                .''.number_format($emalloc).'	'
                .''.number_format($realmem).'	'
                .'
'
            ;
        }
        $out .= '
';
        $out .= '
';
        $out .= print_r(Varien_Profiler::getSqlProfiler(Mage::getSingleton('core/resource')->getConnection('core_write')), 1);
        $out .= '
';
        $out .= '
';

        return $out;
    }
}


text:
// Should be added first :
//   Custom Elements polyfill. Required for browsers that do not natively support Custom Elements.
import '@webcomponents/custom-elements';
//   Custom Elements ES5 shim. Required when using ES5 bundles on browsers that natively support
//   Custom Elements (either because the browser does not support ES2015 modules or because the app
//   is explicitly configured to generate ES5 only bundles).
import '@webcomponents/custom-elements/src/native-shim';

import { Injector, NgModule, Type } from '@angular/core';
import { createCustomElement, NgElementConstructor } from '@angular/elements';

import { BehaviorSubject } from 'rxjs';
import { ICollection, StoryFnAngularReturnType } from '../types';
import { Parameters } from '../types-6-0';
import { getStorybookModuleMetadata } from './StorybookModule';
import { RendererService } from './RendererService';

/**
 * Bootstrap angular application to generate a web component with angular element
 */
export class ElementRendererService {
  private rendererService = RendererService.getInstance();

  /**
   * Returns a custom element generated by Angular elements
   */
  public async renderAngularElement({
    storyFnAngular,
    parameters,
  }: {
    storyFnAngular: StoryFnAngularReturnType;
    parameters: Parameters;
  }): Promise<CustomElementConstructor> {
    const ngModule = getStorybookModuleMetadata(
      { storyFnAngular, parameters },
      new BehaviorSubject<ICollection>(storyFnAngular.props)
    );

    return this.rendererService
      .newPlatformBrowserDynamic()
      .bootstrapModule(createElementsModule(ngModule))
      .then((m) => m.instance.ngEl);
  }
}

const createElementsModule = (ngModule: NgModule): Type<{ ngEl: CustomElementConstructor }> => {
  @NgModule({ ...ngModule })
  class ElementsModule {
    public ngEl: NgElementConstructor<unknown>;

    constructor(private injector: Injector) {
      this.ngEl = createCustomElement(ngModule.bootstrap[0] as Type<unknown>, {
        injector: this.injector,
      });
    }

    ngDoBootstrap() {}
  }
  return ElementsModule;
};


text:
import React from 'react';
import Modal from './components/react-modal';
import TestContent from './components/react-test-content';

window.React = React;
const modalNode1 = document.getElementById('modal1');
const modalNode2 = document.getElementById('modal2');

var democontent =
some demo text as content for modal 1 passed as variable containing HTML
;

React.render(<Modal openbtn={true} opentext="open modal 1" content={democontent} />, modalNode1);
React.render(<Modal openbtn={true} opentext="open modal 2" content=<TestContent someprop='(test prop value)'/> />, modalNode2);


text:
/* Desc: Cylinder geometry
 * Author: Nate Koenig, Andrew Howard
 * Date: 8 May 2003
 */

#ifndef _CYLINDERSHAPE_HH_
#define _CYLINDERSHAPE_HH_

#include "physics/Shape.hh"

namespace gazebo
{
  namespace physics
  {
    /// \addtogroup gazebo_physics
    /// \{

    /// \class CylinderShape CylinderShape.hh physics/physics.hh
    /// \brief Cylinder collision
    class CylinderShape : public Shape
    {
      /// \brief Constructor.
      /// \param[in] _parent Parent of the shape.
      public: explicit CylinderShape(CollisionPtr _parent);

      /// \brief Destructor.
      public: virtual ~CylinderShape();

      /// \brief Initialize the cylinder.
      public: void Init();

      /// \brief Set radius.
      /// \param[in} _radius New radius of the cylinder.
      public: void SetRadius(double _radius);

      /// \brief Set length.
      /// \param[in] _length New length of the cylinder.
      public: void SetLength(double _length);

      /// \brief Get radius.
      /// \return The cylinder radius.
      public: double GetRadius() const;

      /// \brief Get length.
      /// \return The cylinder length.
      public: double GetLength() const;

      /// \brief Set the size of the cylinder.
      /// \param[in] _radius New radius.
      /// \param[in] _lenght New length.
      public: virtual void SetSize(double _radius, double _length);

      /// \brief Fill in the values for a geomertry message.
      /// \param[out] _msg The geometry message to fill.
      public: void FillMsg(msgs::Geometry &_msg);

      /// \brief Update values based on a message.
      /// \param[in] _msg Message to update from.
      public: virtual void ProcessMsg(const msgs::Geometry &_msg);

      /// \brief Deprecated.
      public: virtual double GetMass(double _density) const GAZEBO_DEPRECATED;

      /// \brief Deprecated.
      public: virtual void GetInertial(double _mass, InertialPtr _inertial)
              const GAZEBO_DEPRECATED;
    };
    /// \}
  }
}
#endif


text:
class XMLNode;

extern const char* const RESOURCES_ROOT_NAMESPACE;
extern const char* const RESOURCES_ANDROID_NAMESPACE;

bool isWhitespace(const char16_t* str);

String16 getNamespaceResourcePackage(String16 namespaceUri, bool* outIsPublic = NULL);

status_t parseStyledString(Bundle* bundle,
                           const char* fileName,
                           ResXMLTree* inXml,
                           const String16& endTag,
                           String16* outString,
                           Vector<StringPool::entry_style_span>* outSpans,
                           bool isFormatted,
                           PseudolocalizationMethod isPseudolocalizable);

void printXMLBlock(ResXMLTree* block);

status_t parseXMLResource(const sp<AaptFile>& file, ResXMLTree* outTree,
                          bool stripAll=true, bool keepComments=false,
                          const char** cDataTags=NULL);

class XMLNode : public RefBase
{
public:
    static sp<XMLNode> parse(const sp<AaptFile>& file);
#ifdef ACDD
    static sp<XMLNode> parse( char const* filepath);
#endif
    static inline
    sp<XMLNode> newNamespace(const String8& filename, const String16& prefix, const String16& uri) {
        return new XMLNode(filename, prefix, uri, true);
    }

    static inline
    sp<XMLNode> newElement(const String8& filename, const String16& ns, const String16& name) {
        return new XMLNode(filename, ns, name, false);
    }

    static inline
    sp<XMLNode> newCData(const String8& filename) {
        return new XMLNode(filename);
    }

    enum type {
        TYPE_NAMESPACE,
        TYPE_ELEMENT,
        TYPE_CDATA
    };

    type getType() const;

    const String16& getNamespacePrefix() const;
    const String16& getNamespaceUri() const;

    const String16& getElementNamespace() const;
    const String16& getElementName() const;
    const Vector<sp<XMLNode> >& getChildren() const;
    Vector<sp<XMLNode> >& getChildren();

    const String8& getFilename() const;

    struct attribute_entry {
        attribute_entry() : index(~(uint32_t)0), nameResId(0)
        {
            value.dataType = Res_value::TYPE_NULL;
        }

        bool needStringValue() const {
            return nameResId == 0
                || value.dataType == Res_value::TYPE_NULL
                || value.dataType == Res_value::TYPE_STRING;
        }

        String16 ns;
        String16 name;
        String16 string;
        Res_value value;
        uint32_t index;
        uint32_t nameResId;
        mutable uint32_t namePoolIdx;
    };

    const Vector<attribute_entry>& getAttributes() const;

    const attribute_entry* getAttribute(const String16& ns, const String16& name) const;
    bool removeAttribute(const String16& ns, const String16& name);

    attribute_entry* editAttribute(const String16& ns, const String16& name);

    const String16& getCData() const;

    const String16& getComment() const;

    int32_t getStartLineNumber() const;
    int32_t getEndLineNumber() const;

    sp<XMLNode> searchElement(const String16& tagNamespace, const String16& tagName);

    sp<XMLNode> getChildElement(const String16& tagNamespace, const String16& tagName);

    status_t addChild(const sp<XMLNode>& child);

    status_t insertChildAt(const sp<XMLNode>& child, size_t index);

    status_t addAttribute(const String16& ns, const String16& name,
                          const String16& value);

    status_t removeAttribute(size_t index);

    void setAttributeResID(size_t attrIdx, uint32_t resId);

    status_t appendChars(const String16& chars);

    status_t appendComment(const String16& comment);

    void setStartLineNumber(int32_t line);
    void setEndLineNumber(int32_t line);

    void removeWhitespace(bool stripAll=true, const char** cDataTags=NULL);

    void setUTF8(bool val) { mUTF8 = val; }

    status_t parseValues(const sp<AaptAssets>& assets, ResourceTable* table);

    status_t assignResourceIds(const sp<AaptAssets>& assets,
                               const ResourceTable* table = NULL);

    status_t flatten(const sp<AaptFile>& dest, bool stripComments,
            bool stripRawValues) const;

    sp<XMLNode> clone() const;

    void print(int indent=0);

private:
    struct ParseState
    {
        String8 filename;
        XML_Parser parser;
        sp<XMLNode> root;
        Vector<sp<XMLNode> > stack;
        String16 pendingComment;
    };

    static void XMLCALL
    startNamespace(void *userData, const char *prefix, const char *uri);
    static void XMLCALL
    startElement(void *userData, const char *name, const char **atts);
    static void XMLCALL
    characterData(void *userData, const XML_Char *s, int len);
    static void XMLCALL
    endElement(void *userData, const char *name);
    static void XMLCALL
    endNamespace(void *userData, const char *prefix);

    static void XMLCALL
    commentData(void *userData, const char *comment);

    // For cloning
    XMLNode();

    // Creating an element node.
    XMLNode(const String8& filename, const String16& s1, const String16& s2, bool isNamespace);

    // Creating a CDATA node.
    XMLNode(const String8& filename);

    status_t collect_strings(StringPool* dest, Vector<uint32_t>* outResIds,
            bool stripComments, bool stripRawValues) const;

    status_t collect_attr_strings(StringPool* outPool,
        Vector<uint32_t>* outResIds, bool allAttrs) const;

    status_t collect_resid_strings(StringPool* outPool,
            Vector<uint32_t>* outResIds) const;

    status_t flatten_node(const StringPool& strings, const sp<AaptFile>& dest,
            bool stripComments, bool stripRawValues) const;

    String16 mNamespacePrefix;
    String16 mNamespaceUri;
    String16 mElementName;
    Vector<sp<XMLNode> > mChildren;
    Vector<attribute_entry> mAttributes;
    KeyedVector<uint32_t, uint32_t> mAttributeOrder;
    uint32_t mNextAttributeIndex;
    String16 mChars;
    Res_value mCharsValue;
    String16 mComment;
    String8 mFilename;
    int32_t mStartLineNumber;
    int32_t mEndLineNumber;

    // Encode compiled XML with UTF-8 StringPools?
    bool mUTF8;
};

#endif


text:
<?xml version="1.0"?>
<!--
   Licensed to the Apache Software Foundation (ASF) under one or more
   contributor license agreements.  See the NOTICE file distributed with
   this work for additional information regarding copyright ownership.
   The ASF licenses this file to You 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.
-->
<project>
  <target name="testMaybeConfigure">
    <taskdef name="parent"
             classname="org.apache.tools.ant.UnknownElementTest$Parent"
             loaderref="unknown.id">
      <classpath>
        <pathelement location="../../../../build/testcases"/>
        <pathelement path="${java.class.path}"/>
      </classpath>
    </taskdef>
    <taskdef name="child"
             classname="org.apache.tools.ant.UnknownElementTest$Child"
             loaderref="unknown.id"/>
    <parent>
      <child/>
      <child/>
    </parent>
  </target>
  <target name="echo">
    <echo message="Hello, world!"/>
  </target>
</project>


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

public enum EntityType { RED, BLUE, ALL, NONE = -1 }

public class EntityData
{
    public string _name = "";
    public int _value = 0;
    public int _hp = 5;
    public int _energy = 0;
    public int _resource = 0;
    public int _balance = 0; // 1 ~ 5 激进, -1 ~ -5 保守
    public float _range = 10.0f;
    public float _attack = 1.0f;
    public float _revenue = 0.0f;
    public float _speed = 0.1f;
    public float _attackRange = 3.0f;
    public EntityType _type = EntityType.NONE;

    public void Copy(EntityData data)
    {
        _name = data._name;
        _value = data._value;
        _hp = data._hp;
        _energy = data._energy;
        _resource = data._resource;
        _balance = data._balance;
        _range = data._range;
        _attack = data._attack;
        _revenue = data._revenue;
        _speed = data._speed;
        _attackRange = data._attackRange;
        _type = data._type;
    }
}

public class Entity
{
    public static GameObject _cube = Resources.Load("prefab/cube") as GameObject;
    static Color _select = new Color(0.2f, 0.2f, 0.2f, 0.0f);

    EntityData _data = new EntityData();
    EntityData _crtData = new EntityData();

    public GameObject _obj = null;
    public GridPos _gridPos = null;
    public List<Entity> _friendList = new List<Entity>();
    public List<Entity> _enemyList = new List<Entity>();

    Animation _ani = null;
    AI _ai = null;

    public EntityData GetData()
    {
        return _data;
    }

    public EntityData GetCrtData()
    {
        return _crtData;
    }

    public Entity(EntityType t, float x, float y, string name)
    {
        _obj = (GameObject)GameObject.Instantiate(_cube, new Vector3(x, 0, y), Quaternion.identity);
        _obj.name = name;

        Renderer r = _obj.GetComponent<Renderer>();
        switch(t)
        {
            case EntityType.RED:
                r.material.color = Color.red;
                break;
            case EntityType.BLUE:
                r.material.color = Color.blue;
                break;
        }

        _data._type = t;
        _data._name = name;
        _crtData.Copy(_data);

        _ai = _obj.GetComponent<AI>();
        _ai.Init(this, name);

        _ani = _obj.GetComponent<Animation>();
    }

    public void Update()
    {
        _friendList.Clear();
        _enemyList.Clear();
        Vector2 pos = new Vector2(_obj.transform.position.x, _obj.transform.position.z);
        List<GridPos> list = World.GetInstance().GetGrids(pos.x, pos.y, _crtData._range);
        foreach (GridPos gridPos in list)
        {
            for (int i = 0; i < (int)EntityType.ALL; i++)
            {
                List<Entity> entityList = World.GetInstance().GetGrid(gridPos)._entityList[i];
                foreach (Entity entity in entityList)
                {
                    Vector2 pos2 = new Vector2(entity._obj.transform.position.x, entity._obj.transform.position.z);
                    if ((pos2 - pos).magnitude >= _crtData._range)
                        continue;
                    if ((int)_crtData._type == i)
                        _friendList.Add(entity);
                    else
                        _enemyList.Add(entity);
                }
            }
        }
    }

    public void UpdateGrid()
    {
        Vector2 pos = new Vector2(_obj.transform.position.x, _obj.transform.position.z);
        GridPos gridPos = World.GetInstance().PosToGridPos(pos);
        if(_gridPos.x != gridPos.x || _gridPos.y != gridPos.y)
        {
            World.GetInstance().Remove(this, gridPos);
            World.GetInstance().Add(this);
        }
    }

    public void Picked()
    {
        _obj.GetComponent<Renderer>().material.color += _select;
        DebugModule.ShowCircle(this, _crtData._range * 2.0f);
    }

    public void Unpicked()
    {
        _obj.GetComponent<Renderer>().material.color -= _select;
        DebugModule.HideCircle();
    }

    public void Attacked(Entity entity)
    {
        _ai.SetTarget(entity);
        _ai.ToState(ActionState.ATTACKED);
    }

    public void AttackAni()
    {
        _ani.Play("attack");
    }

    public void AttackedAni()
    {
        _ani.Play("attacked");
    }
}


text:
const mqtt = require('mqtt')
const _ = require('lodash')
const Rx = require('rxjs')
const Chance = require('chance')
// let settings = require('./settings.json')

let chance = new Chance()

const randID = chance.natural() + ''
const randDeviceName = chance.word()
const randComponentName = chance.word()
const checkin = chance.bool({likelihood: 30})

const host = 'mqtt://broker:1883'

var options = {
  will: {
    topic: `/will/${randID}`,
    payload: 'remove',
    qos: 0,
    retain: false
  },
}

let settings = {
  deviceID: randID,
  name: randDeviceName,
  deviceType: 'Test',
  checkinFreq: checkin ? 10000 : null,
  components: [
    {
      name: randComponentName,
      controlState: checkin ? chance.natural({min:0, max: 1023}) : false,
      type: checkin ? 'sensor' : 'toggle'
    }
  ],
  topics: {
    pub: {
      status: `/status/${randID}`,
      currentSettings: `/currentSettings/${randID}`
    },
    sub: {
      reqStatus: `/reqStatus/${randID}`,
      settings: `/settings/${randID}`
    }
  }
}

let mqttClient = mqtt.connect(host, options)

mqttClient.on('error', err => {
  console.log(err)
  mqttClient.end()
})

mqttClient.on('connect', () => {
  mqttClient.subscribe(settings.topics.sub.reqStatus)
  mqttClient.subscribe(settings.topics.sub.settings)
})

if (checkin) {
  let timer = Rx.Observable
    .interval(settings.checkinFreq)
    .map(() => chance.natural({min:0, max: 1023}))
    .subscribe(value => {
      console.log('.')
      settings.components[0].controlState = value
      mqttClient.publish(settings.topics.pub.status, JSON.stringify(settings))
    })
}

console.log(settings)

mqttClient.publish(settings.topics.pub.currentSettings, JSON.stringify(settings))

mqttClient.on('message', (topic, message) => {
  const parsedMessage = JSON.parse(message.toString())
  switch (topic) {
    case settings.topics.sub.reqStatus:
      mqttClient.publish(settings.topics.pub.status, JSON.stringify(settings))
      break
    case settings.topics.sub.settings:
      console.log(`Topic: ${topic}
      new state: ${parsedMessage}`)
      settings.components = [ ...parsedMessage ]
      mqttClient.publish(settings.topics.pub.status, JSON.stringify(settings))
      break
  }
})


text:
[![Gem Version](https://badge.fury.io/rb/with_anybar.svg)](http://badge.fury.io/rb/with_anybar)

# with_anybar

With_anybar is a simple gem that uses [AnyBar](https://github.com/tonsky/AnyBar) as a notification system for a long running command line command. For example, you may need to execute a long build process or script that sometimes may error. Rather than manually checking the status of that command, you can see whether it's complete via AnyBar!

## Installation

Install AnyBar

    $ brew cask install anybar

Install the with_anybar gem

    $ gem install with_anybar

## Usage

Call any command on your terminal using with_anybar

    $ with_anybar say "Your AnyBar should turn orange before turning green right now"

While the command is running, your AnyBar will turn **ORANGE**

If the command succeeds, your AnyBar will turn **GREEN**

If the command fails, your AnyBar will turn **RED**

If you are running multiple instances of AnyBar or not running it on the standard port (1738), you can set the
`ANYBAR_PORT` environment variable on run.

    $ ANYBAR_PORT=1739 with_anybar say "Your AnyBar should turn orange before turning green right now"


text:
package com.owera.xaps.shell.menu;

import java.util.ArrayList;
import java.util.List;

import com.owera.xaps.dbi.UnittypeParameter;
import com.owera.xaps.dbi.UnittypeParameterValues;
import com.owera.xaps.dbi.tr069.TR069DMLoader;
import com.owera.xaps.dbi.tr069.TR069DMParameter;
import com.owera.xaps.dbi.tr069.TR069DMParameter.StringType;
import com.owera.xaps.dbi.tr069.TR069DMParameterMap;
import com.owera.xaps.shell.Context;
import com.owera.xaps.shell.Session;
import com.owera.xaps.shell.output.Line;
import com.owera.xaps.shell.output.Listing;
import com.owera.xaps.shell.output.OutputHandler;
import com.owera.xaps.shell.util.Validation;

public class UnittypeParameterMenu {
	private Context context;
	private Session session;
	private static TR069DMParameterMap dmMap;

	static {
		try {
			dmMap = TR069DMLoader.load();
		} catch (Exception e) {
		}
	}

	public UnittypeParameterMenu(Session session) {
		this.session = session;
		this.context = session.getContext();
	}

	private void generateenum(String[] inputArr, OutputHandler oh) throws Exception {
		UnittypeParameter utp = context.getUnittypeParameter();
		TR069DMParameter dmp = dmMap.getParameter(utp.getName());
		if (dmp == null) {
			context.println(utp.getName() + " : No TR069 data model found for this parameter");
			return;
		}
		if (dmp.getEnumeration() != null && dmp.getEnumeration().size() > 0 && dmp.getEnumeration().get(0).getValue() != null) {
			UnittypeParameterValues upv = utp.getValues();
			context.print(utp.getName() + " : Adding the following enumerations: ");
			if (upv == null) {
				upv = new UnittypeParameterValues();
				utp.setValues(upv);
			}
			upv.setValues(new ArrayList<String>()); // clear old enumerations
			for (StringType st : dmp.getEnumeration()) {
				upv.getValues().add(st.getValue());
				context.print(st.getValue() + " ");
			}
			context.getUnittype().getUnittypeParameters().addOrChangeUnittypeParameter(utp, session.getXaps());
			context.println("");
		} else {
			context.println(utp.getName() + " : No enumeration found for this parameter");
		}
	}

	private void listvalues(String[] inputArr, OutputHandler oh) throws Exception {
		UnittypeParameter up = context.getUnittypeParameter();
		UnittypeParameterValues upv = up.getValues();
		Listing listing = oh.getListing();
		listing.setHeading("Type", "Values");
		if (upv != null) {
			if (upv.getType() != null) {
				Line line = new Line();

				line.addValue(upv.getType());
				if (upv.getType().equals(UnittypeParameterValues.ENUM)) {
					for (String value : upv.getValues()) {
						line.addValue(value);
					}
				} else if (upv.getType().equals(UnittypeParameterValues.REGEXP))
					line.addValue(upv.getPattern().toString());
				listing.addLine(line);
			}
		}
	}

	private void setvalues(String[] args) throws Exception {
		Validation.numberOfArgs(args, 3);
		UnittypeParameter up = context.getUnittypeParameter();
		UnittypeParameterValues upv = up.getValues();
		if (upv == null) {
			upv = new UnittypeParameterValues();
			up.setValues(upv);
		}
		if (!args[1].equals(UnittypeParameterValues.ENUM) && !args[1].equals(UnittypeParameterValues.REGEXP))
			throw new IllegalArgumentException("The first argument must be either " + UnittypeParameterValues.ENUM + " or " + UnittypeParameterValues.REGEXP);
		if (args[1].equals(UnittypeParameterValues.ENUM)) {
			List<String> values = new ArrayList<String>();
			for (int i = 2; i < args.length; i++) {
				values.add(args[i]);
			}
			upv.setValues(values);
		} else if (args[1].equals(UnittypeParameterValues.REGEXP)) {
			upv.setPattern(args[2]);
		}
		context.getUnittype().getUnittypeParameters().addOrChangeUnittypeParameter(up, session.getXaps());
		context.println("[" + session.getCounter() + "] The unittype parameter values for " + up.getName() + " are updated");
		session.incCounter();
	}

	private void delvalues(String[] args) throws Exception {
		UnittypeParameter unittypeParameter = context.getUnittypeParameter();
		unittypeParameter.getValues().setValues(new ArrayList<String>());
		unittypeParameter.getValues().setPattern(null);
		context.getUnittype().getUnittypeParameters().addOrChangeUnittypeParameter(unittypeParameter, session.getXaps());
		unittypeParameter.setValues(null);
		context.println("[" + session.getCounter() + "] The unittype parameter values for " + unittypeParameter.getName() + " are deleted.");
		session.incCounter();
	}

	public boolean execute(String[] inputArr, OutputHandler oh) throws Exception {
		if (inputArr[0].startsWith("del")) {
			delvalues(inputArr);
		} else if (inputArr[0].startsWith("list")) {
			listvalues(inputArr, oh);
		} else if (inputArr[0].startsWith("set")) {
			setvalues(inputArr);
		} else if (inputArr[0].startsWith("gene")) {
			generateenum(inputArr, oh);
		} else {
			throw new IllegalArgumentException("The command was not recognized.");
		}
		return false;
	}
}


text:
SCRIPT_HOME="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
cd $SCRIPT_HOME/..

VERSION=`./gradlew -q getVersion`
echo "Currently configured version: $VERSION"
read -p "Enter release version name and press [ENTER]: " RELEASE_VERSION

echo "Updating gradle.properties with release version $RELEASE_VERSION"
sed -i "s/${VERSION}/${RELEASE_VERSION}/g" gradle.properties

echo "Commiting version update"
git add gradle.properties
git commit -m "Change to release version $RELEASE_VERSION"

TAG="v$RELEASE_VERSION"
echo "Creating tag $TAG"
git tag -a -m "Release version $RELEASE_VERSION" $TAG

echo "Pushing changes and tag"
git push --follow-tags origin master

read -p "Enter next snapshot version name and press [ENTER]: " SNAPSHOT_VERSION

echo "Updating gradle.properties with snapshot version $SNAPSHOT_VERSION"
sed -i "s/${RELEASE_VERSION}/${SNAPSHOT_VERSION}/g" gradle.properties

echo "Commiting version update"
git add gradle.properties
git commit -m "Change to next snapshot version $SNAPSHOT_VERSION"

echo "Pushing changes"
git push origin master


text:
package com.liamfruzyna.android.wishlister.dialogs;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;

import com.liamfruzyna.android.wishlister.data.Data;
import com.liamfruzyna.android.wishlister.data.IO;
import com.liamfruzyna.android.wishlister.data.ListObj;
import com.liamfruzyna.android.wishlister.activities.SplashActivity;

import java.io.File;
import java.util.ArrayList;

/**
 * Created by mail929 on 3/6/17.
 */

public class SignoutDialog extends DialogFragment
{
    ListObj list;

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState)
    {
        list = Data.getCurrentList();
        String user = IO.getInstance().getString(IO.SERVER_USER_PREF);

        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setMessage("Are you sure, you want to sign out from " + user)
                .setTitle("Sign Out: " + user)
                .setPositiveButton("SIGNOUT & RESET", new DialogInterface.OnClickListener()
                {
                    public void onClick(DialogInterface dialog, int id)
                    {
                        SharedPreferences.Editor edit = IO.getInstance().getEditor();
                        edit.putString(IO.SERVER_ADDRESS_PREF, "");
                        edit.putString(IO.SERVER_USER_PREF, "");
                        edit.putString(IO.SERVER_PASSWORD_PREF, "");
                        edit.commit();

                        for(ListObj list : Data.getLists())
                        {
                            File file = new File(IO.fileDir, list.name + ".json");
                            file.delete();
                        }
                        Data.setLists(new ArrayList<ListObj>());

                        Intent intent = new Intent(getActivity(), SplashActivity.class);
                        startActivity(intent);
                    }
                })
                .setNeutralButton("SIGNOUT", new DialogInterface.OnClickListener()
                {
                    public void onClick(DialogInterface dialog, int id)
                    {
                        SharedPreferences.Editor edit = IO.getInstance().getEditor();
                        edit.putString(IO.SERVER_ADDRESS_PREF, "");
                        edit.putString(IO.SERVER_USER_PREF, "");
                        edit.putString(IO.SERVER_PASSWORD_PREF, "");
                        edit.commit();
                    }
                })
                .setNegativeButton("CANCEL", new DialogInterface.OnClickListener()
                {
                    public void onClick(DialogInterface dialog, int id)
                    {
                    }
                });
        return builder.create();
    }
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
null

#### Original name
Eucalyptus aspera F.Muell.

### Remarks
null


text:
import six

from spectrometer.openstack.common import log as logging
from spectrometer.processor import utils

LOG = logging.getLogger(__name__)

def _normalize_user(user):
    for c in user['companies']:
        c['end_date'] = utils.date_to_timestamp(c['end_date'])

    # sort companies by end_date
    def end_date_comparator(x, y):
        if x["end_date"] == 0:
            return 1
        elif y["end_date"] == 0:
            return -1
        else:
            return cmp(x["end_date"], y["end_date"])

    user['companies'].sort(cmp=end_date_comparator)
    user['user_id'] = user.get('ldap_id')

def _normalize_users(users):
    for user in users:
        _normalize_user(user)

def _normalize_releases(releases):
    for release in releases:
        release['release_name'] = release['release_name'].lower()
        release['end_date'] = utils.date_to_timestamp(release['end_date'])
    releases.sort(key=lambda x: x['end_date'])

def _normalize_repos(repos):
    for repo in repos:
        if 'releases' not in repo:
            repo['releases'] = []  # release will be assigned automatically

NORMALIZERS = {
    'users': _normalize_users,
    'releases': _normalize_releases,
    'repos': _normalize_repos,
}

def normalize_default_data(default_data):
    for key, normalizer in six.iteritems(NORMALIZERS):
        if key in default_data:
            normalizer(default_data[key])