text:
module Itamae
  class Recipe
    NotFoundError = Class.new(StandardError)

    attr_reader :path
    attr_reader :runner
    attr_reader :children
    attr_reader :delayed_notifications

    class << self
      def find_recipe_in_gem(recipe)
        plugin_name, recipe_file = recipe.split('::', 2)
        recipe_file = recipe_file.gsub("::", "/") if recipe_file

        gem_name = "itamae-plugin-recipe-#{plugin_name}"
        begin
          gem gem_name
        rescue LoadError
        end
        spec = Gem.loaded_specs.values.find do |spec|
          spec.name == gem_name
        end

        return nil unless spec

        candidate_files = []
        if recipe_file
          recipe_file += '.rb' unless recipe_file.end_with?('.rb')
          candidate_files << "#{plugin_name}/#{recipe_file}"
        else
          candidate_files << "#{plugin_name}/default.rb"
          candidate_files << "#{plugin_name}.rb"
        end

        candidate_files.map do |file|
          File.join(spec.lib_dirs_glob, 'itamae', 'plugin', 'recipe', file)
        end.find do |path|
          File.exist?(path)
        end
      end
    end

    def initialize(runner, path)
      @runner = runner
      @path = path
      @delayed_notifications = []
      @children = RecipeChildren.new
    end

    def dir
      ::File.dirname(@path)
    end

    def load(vars = {})
      context = EvalContext.new(self, vars)
      context.instance_eval(File.read(path), path, 1)
    end

    def run
      show_banner

      @runner.handler.event(:recipe, path: @path) do
        Itamae.logger.with_indent do
          @children.run
          run_delayed_notifications
        end
      end
    end

    private

    def run_delayed_notifications
      @delayed_notifications.uniq! do |notification|
        [notification.action, notification.action_resource]
      end

      while notification = @delayed_notifications.shift
        notification.run
      end
    end

    def show_banner
      Itamae.logger.info "Recipe: #{@path}"
    end

    class EvalContext
      def initialize(recipe, vars)
        @recipe = recipe

        vars.each do |k, v|
          define_singleton_method(k) { v }
        end
      end

      def respond_to_missing?(method, include_private = false)
        Resource.get_resource_class(method)
        true
      rescue NameError
        false
      end

      def method_missing(*args, &block)
        super unless args.size == 2

        method, name = args
        begin
          klass = Resource.get_resource_class(method)
        rescue NameError
          super
        end

        resource = klass.new(@recipe, name, &block)
        @recipe.children << resource
      end

      def define(name, params = {}, &block)
        Resource.define_resource(name, Definition.create_class(name, params, @recipe, &block))
      end

      def include_recipe(target)
        expanded_path = ::File.expand_path(target, File.dirname(@recipe.path))
        expanded_path = ::File.join(expanded_path, 'default.rb') if ::Dir.exist?(expanded_path)
        expanded_path.concat('.rb') unless expanded_path.end_with?('.rb')
        candidate_paths = [expanded_path, Recipe.find_recipe_in_gem(target)].compact
        path = candidate_paths.find {|path| File.exist?(path) }

        unless path
          raise NotFoundError, "Recipe not found. (#{target})"
        end

        if runner.children.find_recipe_by_path(path)
          Itamae.logger.debug "Recipe, #{path}, is skipped because it is already included"
          return
        end

        recipe = Recipe.new(runner, path)
        @recipe.children << recipe
        recipe.load
      end

      def node
        runner.node
      end

      def runner
        @recipe.runner
      end

      def run_command(*args)
        runner.backend.run_command(*args)
      end
    end

    class RecipeFromDefinition < Recipe
      attr_accessor :definition

      def load(vars = {})
        context = EvalContext.new(self, vars)
        context.instance_eval(&@definition.class.definition_block)
      end

      def run
        if @definition.do_not_run_because_of_only_if?
          Itamae.logger.debug "#{@definition.resource_type}[#{@definition.resource_name}] Execution skipped because of only_if attribute"
          return
        elsif @definition.do_not_run_because_of_not_if?
          Itamae.logger.debug "#{@definition.resource_type}[#{@definition.resource_name}] Execution skipped because of not_if attribute"
          return
        end

        super
      end

      private

      def show_banner
        Itamae.logger.debug "#{@definition.resource_type}[#{@definition.resource_name}]"
      end
    end
  end
end


text:
layout: post
title: Tweets
date: 2019-06-09
summary: These are the tweets for June 9, 2019.
categories:
---

redpajama_set_name: RedPajamaGithub


text:
<?php

/* AngeAngeBundle:Utilisateur:show.html.twig */
class __TwigTemplate_9d41e1a71a23085956c66ec97b1c6991 extends Twig_Template
{
    protected function doDisplay(array $context, array $blocks = array())
    {
        // line 1
        echo "
Utilisateur

            Id
            ";
        // line 7
        echo twig_escape_filter($this->env, $this->getAttribute($this->getContext($context, "entity"), "id"), "html", null, true);
        echo "

            Nom
            ";
        // line 11
        echo twig_escape_filter($this->env, $this->getAttribute($this->getContext($context, "entity"), "nom"), "html", null, true);
        echo "

            Prenom
            ";
        // line 15
        echo twig_escape_filter($this->env, $this->getAttribute($this->getContext($context, "entity"), "prenom"), "html", null, true);
        echo "

            Login
            ";
        // line 19
        echo twig_escape_filter($this->env, $this->getAttribute($this->getContext($context, "entity"), "login"), "html", null, true);
        echo "

            Password
            ";
        // line 23
        echo twig_escape_filter($this->env, $this->getAttribute($this->getContext($context, "entity"), "password"), "html", null, true);
        echo "

            Adresse
            ";
        // line 27
        echo twig_escape_filter($this->env, $this->getAttribute($this->getContext($context, "entity"), "adresse"), "html", null, true);
        echo "

            Cp
            ";
        // line 31
        echo twig_escape_filter($this->env, $this->getAttribute($this->getContext($context, "entity"), "cp"), "html", null, true);
        echo "

            Ville
            ";
        // line 35
        echo twig_escape_filter($this->env, $this->getAttribute($this->getContext($context, "entity"), "ville"), "html", null, true);
        echo "

            Telephone
            ";
        // line 39
        echo twig_escape_filter($this->env, $this->getAttribute($this->getContext($context, "entity"), "telephone"), "html", null, true);
        echo "

            Mail
            ";
        // line 43
        echo twig_escape_filter($this->env, $this->getAttribute($this->getContext($context, "entity"), "mail"), "html", null, true);
        echo "

            Dateinscription
            ";
        // line 47
        echo twig_escape_filter($this->env, twig_date_format_filter($this->env, $this->getAttribute($this->getContext($context, "entity"), "dateInscription"), "Y-m-d H:i:s"), "html", null, true);
        echo "

        env, $this->env->getExtension('routing')->getPath("utilisateur"), "html", null, true);
        echo "\">
            Back to the list

        env, $this->env->getExtension('routing')->getPath("utilisateur_edit", array("id" => $this->getAttribute($this->getContext($context, "entity"), "id"))), "html", null, true);
        echo "\">
            Edit

        <form action=\"";
        // line 64
        echo twig_escape_filter($this->env, $this->env->getExtension('routing')->getPath("utilisateur_delete", array("id" => $this->getAttribute($this->getContext($context, "entity"), "id"))), "html", null, true);
        echo "\" method=\"post\">
            ";
        // line 65
        echo $this->env->getExtension('form')->renderWidget($this->getContext($context, "delete_form"));
        echo "
            <button type=\"submit\">Delete</button>
        </form>

";
    }

    public function getTemplateName()
    {
        return "AngeAngeBundle:Utilisateur:show.html.twig";
    }

    public function isTraitable()
    {
        return false;
    }
}


text:
package node.company;

import java.util.*;

import transaction.*;
import transaction.Lock.Token;
import communication.CommunicationException;
import communication.messages.DataRequestMessage;
import communication.messages.DataRequestReplyMessage;
import communication.messages.HelloMessage;
import communication.messages.HelloReplyMessage;
import communication.messages.Message;
import communication.protocols.Protocol;
import communication.unicast.UnicastSocketClient;
import data.request.BookableSectionDataRequest;
import data.request.NodeInfoRequest;
import data.system.NodeInfo;
import data.trainnetwork.*;
import node.NodeConstants;
import node.data.DataRepository;
import node.data.RepositoryException;

/**
 * The core module of a distributed {@link DataRepository}
 * @author Balazs Pete
 *
 */
public abstract class DistributedRepository extends DataRepository {

	/**
	 * An exception thrown when loading data from the {@link DistributedRepositoryDataStore} fails
	 * @author Balazs Pete
	 *
	 */
	public class DataLoadException extends Exception {
		private static final long serialVersionUID = -6869722814419718639L;
		public DataLoadException(String message) {
			super(message);
		}
	}

	protected static String REPOSITORY_NAME;
	public static final int
		PORT = NodeConstants.DYNAMIC_CLUSTER_PORT,
		HELLO_RATE = 60;

	public static String DATA_STORE_LOCATION;
	protected static final int DATA_STORE_PORT = NodeConstants.DYNAMIC_CLUSTER_STORE_PORT;

	protected static ShallowLock<Map<String, Vault<BookableSection>>> sections;
	protected static TransactionManager<String, Vault<BookableSection>, Set<Seat>> transactions;
	protected static TransactionCoordinatorManager<String, Vault<BookableSection>, Set<Seat>> transactionCoordinators;

	protected static WriteOnlyLock<Integer> communicationLock;

	protected static Set<NodeInfo> nodes;

	public DistributedRepository() throws RepositoryException {
		super(NodeConstants.DYNAMIC_CLUSTER_PORT);
		sayHello();
	}

	public void run() {
		super.run();

		UnicastSocketClient client = new UnicastSocketClient(DATA_STORE_LOCATION, DATA_STORE_PORT);
		while (true) {
			try {
				sleep(1000 * HELLO_RATE);
				getNodeInfo(client);
				sayHello();
			} catch (InterruptedException e) {
				// Just loop around...
				System.err.println("Failed to wait the minimum HELLO time: " + e.getMessage());
			}
		}
	}

	@Override
	protected void initialize() throws DistributedRepositoryException {
		sections = new ShallowLock<Map<String, Vault<BookableSection>>>(new HashMap<String, Vault<BookableSection>>());
		transactions = new TransactionManager<String, Vault<BookableSection>, Set<Seat>>(sections);
		transactionCoordinators = new TransactionCoordinatorManager<String, Vault<BookableSection>, Set<Seat>>();
		communicationLock = new WriteOnlyLock<Integer>(new Integer(NodeConstants.DYNAMIC_CLUSTER_PORT));
		nodes = Collections.synchronizedSet(new HashSet<NodeInfo>());

		try {
			restoreFromStore();
		} catch (DataLoadException e) {
			System.err.println(e.getMessage());
			throw DistributedRepositoryException.FAILED_TO_LOAD_DATA;
		}
	}

	@Override
	protected abstract Set<Protocol> getProtocols();

	private void sayHello() {
		HelloMessage message = HelloMessage.getHi();

		Iterator<NodeInfo> it = nodes.iterator();
		while (it.hasNext()) {
			NodeInfo node = it.next();
			Token token = communicationLock.writeLock();
			try {
				UnicastSocketClient.sendOneMessage(node.getLocation(), PORT, message, true);
			} catch (CommunicationException e) {
				System.err.println(e.getMessage());

				// Node is unreachable, remove it...
				nodes.remove(node);
			} finally {
				communicationLock.writeUnlock(token);
			}
		}
	}

	@SuppressWarnings("unchecked")
	private void restoreFromStore() throws DataLoadException {
		UnicastSocketClient client = new UnicastSocketClient(DATA_STORE_LOCATION, DATA_STORE_PORT);

		BookableSectionDataRequest request = new BookableSectionDataRequest();
		DataRequestMessage<BookableSection> requestMessage = new DataRequestMessage<BookableSection>(request, "BookableSection");

		Set<BookableSection> data = null;

		boolean error = false;

		Message msg;
		Token token = communicationLock.writeLock();
		try {
			msg = UnicastSocketClient.sendOneMessage(client, requestMessage, true);
			data = (Set<BookableSection>) msg.getContents();
		} catch (CommunicationException e) {
			// Failed to contact DataStore
			error = true;
		} finally {
			communicationLock.writeUnlock(token);
		}

		if (error) {
			throw new DataLoadException("Failed to load data from `store`");
		}

		boolean committed = false;
		while (data != null && !committed) {
			Token t = sections.writeLock();
			Map<String, Vault<BookableSection>> _sections;
			try {
				_sections = sections.getWriteable(t);
				for (BookableSection entry : data) {
					Vault<BookableSection> vault = new Vault<BookableSection>(entry);
					_sections.put(entry.getID().intern(), vault);
				}
				committed = true;
			} catch (LockException e) {
				System.err.println(e.getMessage());
				// Loop until all sections are saved
			} finally {
				sections.writeUnlock(t);
			}
		}

		error = getNodeInfo(client);

		if (error) {
			throw new DataLoadException("Failed to load data from `store`");
		}
	}

	@SuppressWarnings("unchecked")
	protected boolean getNodeInfo(UnicastSocketClient client) {
		boolean error = false;

		Token token = communicationLock.writeLock();
		try {
			//--- begin HELLO
			Message msg = HelloMessage.getHi();
			HelloReplyMessage reply = (HelloReplyMessage) UnicastSocketClient.sendOneMessage(client, msg, true);
			NodeInfo myOwn = reply.getHelloer();
			//--- end HELLO

			//--- begin GetNodes
			NodeInfoRequest _request = new NodeInfoRequest(myOwn);
			msg = new DataRequestMessage<NodeInfo>(_request, "NodeInfo");

			DataRequestReplyMessage<NodeInfo> _reply = (DataRequestReplyMessage<NodeInfo>) UnicastSocketClient.sendOneMessage(client, msg, true);
			nodes = (Set<NodeInfo>) _reply.getContents();
			//--- end GetNodes
		} catch (CommunicationException e) {
			// Failed to contact DataStore
			error = true;
		} finally {
			communicationLock.writeUnlock(token);
		}

		return error;
	}
}


text:
import * as React from "react";
import {Button} from "./Button";
import {ComponentProps, ComponentState, hex2rgba, inheritDefaultProps, styles} from "./Component";
import {Focus} from "./Focus";
import {Ink} from "./Ink";
import {
    Theme, ThemeStyle, DARK_VARIANT_FOCUS_SHADE, LIGHT_VARIANT_FOCUS_SHADE, DARK_VARIANT_INK_SPILL,
    LIGHT_VARIANT_INK_SPILL, DARK_VARIANT_SWITCH_TRACK, LIGHT_VARIANT_SWITCH_TRACK, DARK_VARIANT_SWITCH_TRACK_INACTIVE,
    LIGHT_VARIANT_SWITCH_TRACK_INACTIVE
} from "./Theme";
import "./Switch.css";

export interface SwitchProps {
    /**
     * Whether the switch is turned on or off.
     */
    isToggled: boolean
}

export interface SwitchState {
    /**
     * Whether the switch is turned on or off.
     */
    isToggled: boolean
}

/**
 * Selection controls allow the user to select options. Switches
 * allow a selection to be turned on or off. Selection controls
 * use an theme's accent color. This component adheres to Material
 * Design > Selection controls recommendations.
 */
export class Switch extends Button<SwitchProps & ComponentProps, SwitchState & ComponentState> {
    static defaultProps = {
    };

    /*
     * Note: colors below are overwritten,
     * as this component always has tinting.
     */
    public get tint() {
        return this.calcTintColor() || this.theme.accent;
    }

    public get focusColor() {
        if(this.state.isToggled && !this.props.isDisabled) {
            return "rgba(" + hex2rgba(Theme.colors[this.tint][500], 0.12).join() + ")";
        }

        return this.variantBase === ThemeStyle.Light ? LIGHT_VARIANT_FOCUS_SHADE : DARK_VARIANT_FOCUS_SHADE;
    }

    public get inkColor() {
        if(this.state.isToggled) {
            return Theme.colors[this.tint][600];
        }

        return this.variantBase === ThemeStyle.Light ? LIGHT_VARIANT_INK_SPILL : DARK_VARIANT_INK_SPILL;
    }

    constructor(props: SwitchProps & ComponentProps) {
        super(props);

        this.state = {
            isActive: false,
            isFocus: false,
            isToggled: props.isToggled
        };
    }

    protected _deactivate() {
        super._deactivate();

        this.setState({
            isActive: false,
            isFocus: this.state.isFocus,
            isToggled: !this.state.isToggled
        })
    }

    /*
     * Note: we override here to allow
     * disabled toggle to react to focus
     */
    onFocus() {
        this.setState({
            isActive: this.state.isActive,
            isFocus: true,
            isToggled: this.state.isToggled
        });
    }

    onBlur() {
        this.setState({
            isActive: this.state.isActive,
            isFocus: false,
            isToggled: this.state.isToggled
        });
    }

    render() {
        let cls:string = "mr-switch " + this.props.className;
        if(this.props.isDisabled) {
            cls += " mr-switch--disabled";
        }
        if(this.state.isActive) {
            cls += " mr-switch--active";
        }
        if(this.state.isToggled) {
            cls += " mr-switch--toggled";
        }

        let tabIndex:number = 0;
        if(this.props.isDisabled) {
            tabIndex = -1;
        }

        let trackColor:string;
        let sliderColor:string;
        if(this.variantBase === ThemeStyle.Dark) {
            if(this.props.isDisabled) {
                trackColor = DARK_VARIANT_SWITCH_TRACK_INACTIVE;
                sliderColor = Theme.colors["grey"][800];
            }
            else {
                trackColor = this.state.isToggled ? Theme.colors[this.tint][200] : DARK_VARIANT_SWITCH_TRACK;
                sliderColor = this.state.isToggled ? Theme.colors[this.tint][200] : Theme.colors["grey"][400];
            }
        }
        else {
            if(this.props.isDisabled) {
                trackColor = LIGHT_VARIANT_SWITCH_TRACK_INACTIVE;
                sliderColor = Theme.colors["grey"][400];
            }
            else {
                trackColor = this.state.isToggled ? Theme.colors[this.tint][500] : LIGHT_VARIANT_SWITCH_TRACK;
                sliderColor = this.state.isToggled ? Theme.colors[this.tint][500] : Theme.colors["grey"][50];
            }
        }

        return (

                    <Ink ref="ink"
                         isActive={this.state.isActive}
                         color={this.inkColor}
                         size={this.state.inkSpillSize}
                         originTop={this.state.inkOriginTop}
                         originLeft={this.state.inkOriginLeft}/>
                    <Focus isActive={this.state.isFocus}
                           color={this.focusColor}/>

        );
    }
}

inheritDefaultProps(Switch);


text:
import { Trie } from "@wry/trie";

import { Cache } from "./cache";
import { Entry, AnyEntry } from "./entry";
import { parentEntrySlot } from "./context";

// These helper functions are important for making optimism work with
// asynchronous code. In order to register parent-child dependencies,
// optimism needs to know about any currently active parent computations.
// In ordinary synchronous code, the parent context is implicit in the
// execution stack, but asynchronous code requires some extra guidance in
// order to propagate context from one async task segment to the next.
export {
  bindContext,
  noContext,
  setTimeout,
  asyncFromGen,
} from "./context";

// A lighter-weight dependency, similar to OptimisticWrapperFunction, except
// with only one argument, no makeCacheKey, no wrapped function to recompute,
// and no result value. Useful for representing dependency leaves in the graph
// of computation. Subscriptions are supported.
export { dep, OptimisticDependencyFunction } from "./dep";

function makeDefaultMakeCacheKeyFunction<
  TKeyArgs extends any[],
  TCacheKey = any,
>(): (...args: TKeyArgs) => TCacheKey {
  const keyTrie = new Trie<TCacheKey>(typeof WeakMap === "function");
  return function () {
    return keyTrie.lookupArray(arguments);
  };
}

// The defaultMakeCacheKey function is remarkably powerful, because it gives
// a unique object for any shallow-identical list of arguments. If you need
// to implement a custom makeCacheKey function, you may find it helpful to
// delegate the final work to defaultMakeCacheKey, which is why we export it
// here. However, you may want to avoid defaultMakeCacheKey if your runtime
// does not support WeakMap, or you have the ability to return a string key.
// In those cases, just write your own custom makeCacheKey functions.
export const defaultMakeCacheKey = makeDefaultMakeCacheKeyFunction();

// If you're paranoid about memory leaks, or you want to avoid using WeakMap
// under the hood, but you still need the behavior of defaultMakeCacheKey,
// import this constructor to create your own tries.
export { Trie as KeyTrie }

export type OptimisticWrapperFunction<
  TArgs extends any[],
  TResult,
  TKeyArgs extends any[] = TArgs,
  TCacheKey = any,
> = ((...args: TArgs) => TResult) & {
  // Get the current number of Entry objects in the LRU cache.
  readonly size: number;

  // "Dirty" any cached Entry stored for the given arguments, marking that Entry
  // and its ancestors as potentially needing to be recomputed. The .dirty(...)
  // method of an optimistic function takes the same parameter types as the
  // original function by default, unless a keyArgs function is configured, and
  // then it matters that .dirty takes TKeyArgs instead of TArgs.
  dirty: (...args: TKeyArgs) => void;
  // A version of .dirty that accepts a key returned by .getKey.
  dirtyKey: (key: TCacheKey) => void;

  // Examine the current value without recomputing it.
  peek: (...args: TKeyArgs) => TResult | undefined;
  // A version of .peek that accepts a key returned by .getKey.
  peekKey: (key: TCacheKey) => TResult | undefined;

  // Completely remove the entry from the cache, dirtying any parent entries.
  forget: (...args: TKeyArgs) => boolean;
  // A version of .forget that accepts a key returned by .getKey.
  forgetKey: (key: TCacheKey) => boolean;

  // In order to use the -Key version of the above functions, you need a key
  // rather than the arguments used to compute the key. These two functions take
  // TArgs or TKeyArgs and return the corresponding TCacheKey. If no keyArgs
  // function has been configured, TArgs will be the same as TKeyArgs, and thus
  // getKey and makeCacheKey will be synonymous.
  getKey: (...args: TArgs) => TCacheKey;

  // This property is equivalent to the makeCacheKey function provided in the
  // OptimisticWrapOptions, or (if no options.makeCacheKey function is provided)
  // a default implementation of makeCacheKey.
  makeCacheKey: (...args: TKeyArgs) => TCacheKey;
};

export type OptimisticWrapOptions<
  TArgs extends any[],
  TKeyArgs extends any[] = TArgs,
  TCacheKey = any,
> = {
  // The maximum number of cache entries that should be retained before the
  // cache begins evicting the oldest ones.
  max?: number;
  // Transform the raw arguments to some other type of array, which will then
  // be passed to makeCacheKey.
  keyArgs?: (...args: TArgs) => TKeyArgs;
  // The makeCacheKey function takes the same arguments that were passed to
  // the wrapper function and returns a single value that can be used as a key
  // in a Map to identify the cached result.
  makeCacheKey?: (...args: TKeyArgs) => TCacheKey;
  // If provided, the subscribe function should either return an unsubscribe
  // function or return nothing.
  subscribe?: (...args: TArgs) => void | (() => any);
};

const caches = new Set<Cache<any, AnyEntry>>();

export function wrap<
  TArgs extends any[],
  TResult,
  TKeyArgs extends any[] = TArgs,
  TCacheKey = any,
>(
  originalFunction: (...args: TArgs) => TResult,
  options: OptimisticWrapOptions<TArgs, TKeyArgs> = Object.create(null),
) {
  const cache = new Cache<TCacheKey, Entry<TArgs, TResult>>(
    options.max || Math.pow(2, 16),
    entry => entry.dispose(),
  );

  const keyArgs = options.keyArgs;
  const makeCacheKey = options.makeCacheKey ||
    makeDefaultMakeCacheKeyFunction<TKeyArgs, TCacheKey>();

  const optimistic = function (): TResult {
    const key = makeCacheKey.apply(
      null,
      keyArgs ? keyArgs.apply(null, arguments as any) : arguments as any
    );

    if (key === void 0) {
      return originalFunction.apply(null, arguments as any);
    }

    let entry = cache.get(key)!;
    if (!entry) {
      cache.set(key, entry = new Entry(originalFunction));
      entry.subscribe = options.subscribe;
      // Give the Entry the ability to trigger cache.delete(key), even though
      // the Entry itself does not know about key or cache.
      entry.forget = () => cache.delete(key);
    }

    const value = entry.recompute(
      Array.prototype.slice.call(arguments) as TArgs,
    );

    // Move this entry to the front of the least-recently used queue,
    // since we just finished computing its value.
    cache.set(key, entry);

    caches.add(cache);

    // Clean up any excess entries in the cache, but only if there is no
    // active parent entry, meaning we're not in the middle of a larger
    // computation that might be flummoxed by the cleaning.
    if (! parentEntrySlot.hasValue()) {
      caches.forEach(cache => cache.clean());
      caches.clear();
    }

    return value;
  } as OptimisticWrapperFunction<TArgs, TResult, TKeyArgs, TCacheKey>;

  Object.defineProperty(optimistic, "size", {
    get() {
      return cache["map"].size;
    },
    configurable: false,
    enumerable: false,
  });

  function dirtyKey(key: TCacheKey) {
    const entry = cache.get(key);
    if (entry) {
      entry.setDirty();
    }
  }
  optimistic.dirtyKey = dirtyKey;
  optimistic.dirty = function dirty() {
    dirtyKey(makeCacheKey.apply(null, arguments as any));
  };

  function peekKey(key: TCacheKey) {
    const entry = cache.get(key);
    if (entry) {
      return entry.peek();
    }
  }
  optimistic.peekKey = peekKey;
  optimistic.peek = function peek() {
    return peekKey(makeCacheKey.apply(null, arguments as any));
  };

  function forgetKey(key: TCacheKey) {
    return cache.delete(key);
  }
  optimistic.forgetKey = forgetKey;
  optimistic.forget = function forget() {
    return forgetKey(makeCacheKey.apply(null, arguments as any));
  };

  optimistic.makeCacheKey = makeCacheKey;
  optimistic.getKey = keyArgs ? function getKey() {
    return makeCacheKey.apply(null, keyArgs.apply(null, arguments as any));
  } : makeCacheKey as (...args: any[]) => TCacheKey;

  return Object.freeze(optimistic);
}


text:
import networkx as nx
from cStringIO import StringIO
from Bio import Phylo
import matplotlib.pyplot as plt
import random
import logging
from tqdm import tqdm
logger = logging.getLogger()
logger.setLevel(logging.INFO)
import numpy as np
import trees
from trees.ddt import DirichletDiffusionTree, Inverse, GaussianLikelihoodModel
from trees.mcmc import MetropolisHastingsSampler
from trees.util import plot_tree_2d
from sklearn.decomposition import PCA

import seaborn as sns

sns.set_style('white')
import cPickle as pickle

dataset = trees.data.load('zoo')
X, y = dataset.X, dataset.y
X += np.random.normal(scale=0.01, size=X.shape)

pca = PCA(2)
pca.fit(X)

# X = pca.transform(X)
N, D = X.shape

with open('../../scripts/zoo.tree', 'rb') as fp:
    master_tree = pickle.load(fp)

master_constraints = list(master_tree.generate_constraints())
random.seed(0)
random.shuffle(master_constraints)
train_constraints, test_constraints = master_constraints[:200], master_constraints[200:]
test_constraints = test_constraints[:10000]

df = Inverse(c=0.9)

lm = GaussianLikelihoodModel(sigma=np.eye(D) / 4.0, sigma0=np.eye(D) / 2.0, mu0=X.mean(axis=0)).compile()

model = DirichletDiffusionTree(df=df, likelihood_model=lm, constraints=[])
sampler = MetropolisHastingsSampler(model, X)
sampler.initialize_assignments()

constraint_add = 500
constraint_index = 0
n_iters = 100000
score_every = 1000

likelihoods = []
scores = []
for i in tqdm(xrange(n_iters + constraint_add)):
    if i != 0 and i % constraint_add == 0:
        sampler.add_constraint(train_constraints[constraint_index])
        constraint_index += 1
    sampler.sample()
    likelihoods.append(sampler.tree.marg_log_likelihood())
    if i % score_every == 0:
        scores.append(float(sampler.tree.score_constraints(test_constraints))
                            / len(test_constraints))

scores.append(float(sampler.tree.score_constraints(test_constraints))
                    / len(test_constraints))

fontsize = 18
plt.figure()
plt.xlim([0, n_iters + constraint_add])
plt.ylim([0, 1])
plt.xlabel("Iterations", fontsize=fontsize)
plt.ylabel("Constraint Score", fontsize=fontsize)
plt.plot(np.arange(0, n_iters + constraint_add + score_every, score_every), scores)
plt.plot(scores)
plt.legend(loc='best', fontsize=12)
plt.savefig('online-scores.png', bbox_inches='tight')

plt.figure()
plt.xlim([0, n_iters + constraint_add])
plt.xlabel("Iterations", fontsize=fontsize)
plt.ylabel("Data Log Likelihood", fontsize=fontsize)
plt.plot(likelihoods)
plt.legend(loc='best', fontsize=12)

plt.savefig('online-likelihoods.png', bbox_inches='tight')

final_tree = sampler.tree.copy()

plt.figure()
plot_tree_2d(final_tree, X, pca)

for node in final_tree.dfs():
    if node.is_leaf():
        node.point = y[node.point]

newick = final_tree.to_newick()
tree = Phylo.read(StringIO(newick), 'newick')

plt.figure()
Phylo.draw_graphviz(tree, prog='neato')
plt.savefig('tree.png', bbox_inches='tight')
graph = Phylo.to_networkx(tree)
with open('tree.nwk', 'w') as fp:
    print >>fp, newick,
nx.write_dot(graph, 'tree.dot')
plt.show()


text:
namespace offline_pages {

namespace {

using DailyUsageType = OfflineMetricsCollectorImpl::DailyUsageType;
using PrefetchUsageType = OfflineMetricsCollectorImpl::PrefetchUsageType;

void ReportOfflineUsageForOneDayToUma(DailyUsageType usage_type) {
  UMA_HISTOGRAM_ENUMERATION("OfflinePages.OfflineUsage", usage_type);
}

void ReportNotResilientOfflineUsageForOneDayToUma(DailyUsageType usage_type) {
  UMA_HISTOGRAM_ENUMERATION("OfflinePages.OfflineUsage.NotOfflineResilient",
                            usage_type);
}

void ReportPrefetchUsageForOneDayToUma(PrefetchUsageType usage_type) {
  UMA_HISTOGRAM_ENUMERATION("OfflinePages.PrefetchUsage", usage_type);
}

}  // namespace

// static
void OfflineMetricsCollectorImpl::RegisterPrefs(PrefRegistrySimple* registry) {
  registry->RegisterBooleanPref(prefs::kOfflineUsageStartObserved, false);
  registry->RegisterBooleanPref(prefs::kOfflineUsageOnlineObserved, false);
  registry->RegisterBooleanPref(prefs::kOfflineUsageOfflineObserved, false);
  registry->RegisterBooleanPref(prefs::kPrefetchUsageEnabledObserved, false);
  registry->RegisterBooleanPref(prefs::kPrefetchUsageFetchObserved, false);
  registry->RegisterBooleanPref(prefs::kPrefetchUsageOpenObserved, false);
  registry->RegisterInt64Pref(prefs::kOfflineUsageTrackingDay, 0L);
  registry->RegisterIntegerPref(prefs::kOfflineUsageUnusedCount, 0);
  registry->RegisterIntegerPref(prefs::kOfflineUsageStartedCount, 0);
  registry->RegisterIntegerPref(prefs::kOfflineUsageOfflineCount, 0);
  registry->RegisterIntegerPref(prefs::kOfflineUsageOnlineCount, 0);
  registry->RegisterIntegerPref(prefs::kOfflineUsageMixedCount, 0);
  registry->RegisterIntegerPref(prefs::kPrefetchUsageEnabledCount, 0);
  registry->RegisterIntegerPref(prefs::kPrefetchUsageFetchedCount, 0);
  registry->RegisterIntegerPref(prefs::kPrefetchUsageOpenedCount, 0);
  registry->RegisterIntegerPref(prefs::kPrefetchUsageMixedCount, 0);
}

OfflineMetricsCollectorImpl::OfflineMetricsCollectorImpl(PrefService* prefs)
    : prefs_(prefs) {}

OfflineMetricsCollectorImpl::~OfflineMetricsCollectorImpl() {}

void OfflineMetricsCollectorImpl::OnAppStartupOrResume() {
  SetTrackingFlag(&chrome_start_observed_);
}

void OfflineMetricsCollectorImpl::OnSuccessfulNavigationOffline() {
  SetTrackingFlag(&offline_navigation_observed_);
}

void OfflineMetricsCollectorImpl::OnSuccessfulNavigationOnline() {
  SetTrackingFlag(&online_navigation_observed_);
}

void OfflineMetricsCollectorImpl::OnPrefetchEnabled() {
  SetTrackingFlag(&prefetch_is_enabled_observed_);
}

void OfflineMetricsCollectorImpl::OnSuccessfulPagePrefetch() {
  SetTrackingFlag(&prefetch_fetch_observed_);
}

void OfflineMetricsCollectorImpl::OnPrefetchedPageOpened() {
  SetTrackingFlag(&prefetch_open_observed_);
}

void OfflineMetricsCollectorImpl::ReportAccumulatedStats() {
  EnsureLoaded();
  int total_day_count =
      unused_days_count_ + started_days_count_ + offline_days_count_ +
      online_days_count_ + mixed_days_count_ + prefetch_enable_count_ +
      prefetch_fetched_count_ + prefetch_opened_count_ + prefetch_mixed_count_;
  // No accumulated daily usage, nothing to report.
  if (total_day_count == 0)
    return;

  for (int i = 0; i < unused_days_count_; ++i)
    ReportOfflineUsageForOneDayToUma(DailyUsageType::kUnused);
  for (int i = 0; i < started_days_count_; ++i)
    ReportOfflineUsageForOneDayToUma(DailyUsageType::kStarted);
  for (int i = 0; i < offline_days_count_; ++i)
    ReportOfflineUsageForOneDayToUma(DailyUsageType::kOffline);
  for (int i = 0; i < online_days_count_; ++i)
    ReportOfflineUsageForOneDayToUma(DailyUsageType::kOnline);
  for (int i = 0; i < mixed_days_count_; ++i)
    ReportOfflineUsageForOneDayToUma(DailyUsageType::kMixed);

  for (int i = 0; i < prefetch_enable_count_; ++i) {
    UMA_HISTOGRAM_BOOLEAN("OfflinePages.PrefetchEnabled", true);
  }

  for (int i = 0; i < prefetch_fetched_count_; ++i)
    ReportPrefetchUsageForOneDayToUma(PrefetchUsageType::kFetchedNewPages);
  for (int i = 0; i < prefetch_opened_count_; ++i)
    ReportPrefetchUsageForOneDayToUma(PrefetchUsageType::kOpenedPages);
  for (int i = 0; i < prefetch_mixed_count_; ++i)
    ReportPrefetchUsageForOneDayToUma(
        PrefetchUsageType::kFetchedAndOpenedPages);

  unused_days_count_ = 0;
  started_days_count_ = 0;
  offline_days_count_ = 0;
  online_days_count_ = 0;
  mixed_days_count_ = 0;
  prefetch_enable_count_ = 0;
  prefetch_fetched_count_ = 0;
  prefetch_opened_count_ = 0;
  prefetch_mixed_count_ = 0;

  SaveToPrefs();
}

void OfflineMetricsCollectorImpl::EnsureLoaded() {
  if (!tracking_day_midnight_.is_null())
    return;

  DCHECK(prefs_);
  chrome_start_observed_ =
      prefs_->GetBoolean(prefs::kOfflineUsageStartObserved);
  offline_navigation_observed_ =
      prefs_->GetBoolean(prefs::kOfflineUsageOfflineObserved);
  online_navigation_observed_ =
      prefs_->GetBoolean(prefs::kOfflineUsageOnlineObserved);

  prefetch_is_enabled_observed_ =
      prefs_->GetBoolean(prefs::kPrefetchUsageEnabledObserved);
  prefetch_fetch_observed_ =
      prefs_->GetBoolean(prefs::kPrefetchUsageFetchObserved);
  prefetch_open_observed_ =
      prefs_->GetBoolean(prefs::kPrefetchUsageOpenObserved);

  tracking_day_midnight_ = prefs_->GetTime(prefs::kOfflineUsageTrackingDay);
  // For the very first run, initialize to current time.
  if (tracking_day_midnight_.is_null())
    tracking_day_midnight_ = OfflineTimeNow().LocalMidnight();

  unused_days_count_ = prefs_->GetInteger(prefs::kOfflineUsageUnusedCount);
  started_days_count_ = prefs_->GetInteger(prefs::kOfflineUsageStartedCount);
  offline_days_count_ = prefs_->GetInteger(prefs::kOfflineUsageOfflineCount);
  online_days_count_ = prefs_->GetInteger(prefs::kOfflineUsageOnlineCount);
  mixed_days_count_ = prefs_->GetInteger(prefs::kOfflineUsageMixedCount);

  prefetch_enable_count_ =
      prefs_->GetInteger(prefs::kPrefetchUsageEnabledCount);
  prefetch_fetched_count_ =
      prefs_->GetInteger(prefs::kPrefetchUsageFetchedCount);
  prefetch_opened_count_ = prefs_->GetInteger(prefs::kPrefetchUsageOpenedCount);
  prefetch_mixed_count_ = prefs_->GetInteger(prefs::kPrefetchUsageMixedCount);
}

void OfflineMetricsCollectorImpl::SaveToPrefs() {
  prefs_->SetBoolean(prefs::kOfflineUsageStartObserved, chrome_start_observed_);
  prefs_->SetBoolean(prefs::kOfflineUsageOfflineObserved,
                     offline_navigation_observed_);
  prefs_->SetBoolean(prefs::kOfflineUsageOnlineObserved,
                     online_navigation_observed_);
  prefs_->SetBoolean(prefs::kPrefetchUsageEnabledObserved,
                     prefetch_is_enabled_observed_);
  prefs_->SetBoolean(prefs::kPrefetchUsageFetchObserved,
                     prefetch_fetch_observed_);
  prefs_->SetBoolean(prefs::kPrefetchUsageOpenObserved,
                     prefetch_open_observed_);
  prefs_->SetTime(prefs::kOfflineUsageTrackingDay, tracking_day_midnight_);
  prefs_->SetInteger(prefs::kOfflineUsageUnusedCount, unused_days_count_);
  prefs_->SetInteger(prefs::kOfflineUsageStartedCount, started_days_count_);
  prefs_->SetInteger(prefs::kOfflineUsageOfflineCount, offline_days_count_);
  prefs_->SetInteger(prefs::kOfflineUsageOnlineCount, online_days_count_);
  prefs_->SetInteger(prefs::kOfflineUsageMixedCount, mixed_days_count_);

  prefs_->SetInteger(prefs::kPrefetchUsageEnabledCount, prefetch_enable_count_);
  prefs_->SetInteger(prefs::kPrefetchUsageFetchedCount,
                     prefetch_fetched_count_);
  prefs_->SetInteger(prefs::kPrefetchUsageOpenedCount, prefetch_opened_count_);
  prefs_->SetInteger(prefs::kPrefetchUsageMixedCount, prefetch_mixed_count_);

  prefs_->CommitPendingWrite();
}

void OfflineMetricsCollectorImpl::SetTrackingFlag(bool* flag) {
  EnsureLoaded();

  bool changed = UpdatePastDaysIfNeeded() || !(*flag);
  *flag = true;

  if (changed)
    SaveToPrefs();
}

bool OfflineMetricsCollectorImpl::UpdatePastDaysIfNeeded() {
  base::Time current_midnight = OfflineTimeNow().LocalMidnight();
  // 1. If days_since_last_update <= 0, continue to accumulate the current day.
  // 2. If days_since_last_update == 1, stats are recorded and initialized for
  //    the current day.
  // 3. If days_since_last_update > 1, we record days_since_last_update-1
  //    'unused' days, stats are recorded and initialized for the current day.
  const int days_since_last_update =
      (current_midnight - tracking_day_midnight_).InDays();
  if (days_since_last_update <= 0)
    return false;

  // The days between the day when tracking was done and the current one are
  // 'unused'.
  const int unused_days = days_since_last_update - 1;
  DCHECK_GE(unused_days, 0);

  // Increment the counter that corresponds to tracked usage.
  if (online_navigation_observed_ && offline_navigation_observed_) {
    mixed_days_count_++;
    ReportNotResilientOfflineUsageForOneDayToUma(DailyUsageType::kMixed);
  } else if (online_navigation_observed_) {
    online_days_count_++;
    ReportNotResilientOfflineUsageForOneDayToUma(DailyUsageType::kOnline);
  } else if (offline_navigation_observed_) {
    offline_days_count_++;
    ReportNotResilientOfflineUsageForOneDayToUma(DailyUsageType::kOffline);
  } else if (chrome_start_observed_) {
    started_days_count_++;
    ReportNotResilientOfflineUsageForOneDayToUma(DailyUsageType::kStarted);
  } else {
    unused_days_count_++;
    ReportNotResilientOfflineUsageForOneDayToUma(DailyUsageType::kUnused);
  }

  if (prefetch_is_enabled_observed_)
    prefetch_enable_count_++;

  if (prefetch_fetch_observed_ && prefetch_open_observed_)
    prefetch_mixed_count_++;
  else if (prefetch_open_observed_)
    prefetch_opened_count_++;
  else if (prefetch_fetch_observed_)
    prefetch_fetched_count_++;

  unused_days_count_ += unused_days;
  for (int i = 0; i < unused_days; ++i)
    ReportNotResilientOfflineUsageForOneDayToUma(DailyUsageType::kUnused);

  // Reset tracking
  chrome_start_observed_ = false;
  offline_navigation_observed_ = false;
  online_navigation_observed_ = false;
  prefetch_is_enabled_observed_ = false;
  prefetch_fetch_observed_ = false;
  prefetch_open_observed_ = false;

  tracking_day_midnight_ = current_midnight;

  return true;
}

}  // namespace offline_pages


text:
package com.siyeh.ig.errorhandling;

import com.intellij.psi.PsiClass;
import com.siyeh.InspectionGadgetsBundle;
import com.siyeh.ig.BaseInspection;
import com.siyeh.ig.BaseInspectionVisitor;
import com.siyeh.ig.psiutils.ClassUtils;
import org.jetbrains.annotations.NotNull;

public class UncheckedExceptionClassInspection extends BaseInspection {

    @NotNull
    public String getDisplayName() {
        return InspectionGadgetsBundle.message(
                "unchecked.exception.class.display.name");
    }

    @NotNull
    protected String buildErrorString(Object... infos) {
        return InspectionGadgetsBundle.message(
                "unchecked.exception.class.problem.descriptor");
    }

    public BaseInspectionVisitor buildVisitor() {
        return new UncheckedExceptionClassVisitor();
    }

    private static class UncheckedExceptionClassVisitor
            extends BaseInspectionVisitor {

        @Override public void visitClass(@NotNull PsiClass aClass) {
            if (!ClassUtils.isSubclass(aClass, "java.lang.Throwable")) {
                return;
            }
            if (ClassUtils.isSubclass(aClass, "java.lang.Exception") &&
                !ClassUtils.isSubclass(aClass, "java.lang.RuntimeException")) {
                return;
            }
            registerClassError(aClass);
        }
    }
}


text:
<mm-header size="large" unresolved>Header "Large", Arimo Bold, 20px, Color-A2</mm-header>
<mm-header size="medium" unresolved>Header "Medium", Arimo Bold, 15px, Color-A2</mm-header>
<mm-header size="small" unresolved>Header "Small", Arimo Bold, 13px, Color-A2</mm-header>
<mm-header size="normal" unresolved>Header "Normal", Arimo Bold, Uppercase, 11px, Color-D2</mm-header>
<mm-header size="tiny" unresolved>Header "tiny", Arimo Bold, uppercase, 9px, Color-A3</mm-header>


text:
var FTCResQCalculatorForm = React.createClass({
    getInitialState: function () {
        return {
            scores: {
                autonButtonScore1: 0,
                autonClimbersScore1: 0,
                autonMountainScore1: 0,
                teleopClimbersScore1: 0,
                highBucketScore1: 0,
                midBucketScore1: 0,
                lowBucketScore1: 0,
                floorGoalScore1: 0,
                lowZiplineClimberScore1: 0,
                midZiplineClimberScore1: 0,
                highZiplineClimberScore1: 0,
                allClearScore1: 0,
                endgameMountainScore1: 0,

                autonButtonScore2: 0,
                autonClimbersScore2: 0,
                autonMountainScore2: 0,
                teleopClimbersScore2: 0,
                highBucketScore2: 0,
                midBucketScore2: 0,
                lowBucketScore2: 0,
                floorGoalScore2: 0,
                lowZiplineClimberScore2: 0,
                midZiplineClimberScore2: 0,
                highZiplineClimberScore2: 0,
                allClearScore2: 0,
                endgameMountainScore2: 0
            },
        };
    },
    handleScoreChange: function (score, scoreType) {
        switch (scoreType) {
            case "autonButtonScore1":
                var s = this.state.scores;
                s.autonButtonScore1 = parseInt(score);
                this.setState({ scores: s });
                break;
            case "autonClimbersScore1":
                var s = this.state.scores;
                s.autonClimbersScore1 = parseInt(score);
                this.setState({ scores: s });
                break;
            case "autonMountainScore1":
                var s = this.state.scores;
                s.autonMountainScore1 = parseInt(score);
                this.setState({ scores: s });
                break;
            case "teleopClimbersScore1":
                var s = this.state.scores;
                s.teleopClimbersScore1 = parseInt(score);
                this.setState({ scores: s });
                break;
            case "highBucketScore1":
                var s = this.state.scores;
                s.highBucketScore1 = parseInt(score);
                this.setState({ scores: s });
                break;
            case "midBucketScore1":
                var s = this.state.scores;
                s.midBucketScore1 = parseInt(score);
                this.setState({ scores: s });
                break;
            case "lowBucketScore1":
                var s = this.state.scores;
                s.lowBucketScore1 = parseInt(score);
                this.setState({ scores: s });
                break;
            case "floorGoalScore1":
                var s = this.state.scores;
                s.floorGoalScore1 = parseInt(score);
                this.setState({ scores: s });
                break;
            case "lowZiplineClimberScore1":
                var s = this.state.scores;
                s.lowZiplineClimberScore1 = parseInt(score);
                this.setState({ scores: s });
                break;
            case "midZiplineClimberScore1":
                var s = this.state.scores;
                s.midZiplineClimberScore1 = parseInt(score);
                this.setState({ scores: s });
                break;
            case "highZiplineClimberScore1":
                var s = this.state.scores;
                s.highZiplineClimberScore1 = parseInt(score);
                this.setState({ scores: s });
                break;
            case "allClearScore1":
                var s = this.state.scores;
                s.allClearScore1 = parseInt(score);
                this.setState({ scores: s });
                break;
            case "endgameMountainScore1":
                var s = this.state.scores;
                s.endgameMountainScore1 = parseInt(score);
                this.setState({ scores: s });
                break;

            case "autonButtonScore2":
                var s = this.state.scores;
                s.autonButtonScore2 = parseInt(score);
                this.setState({ scores: s });
                break;
            case "autonClimbersScore2":
                var s = this.state.scores;
                s.autonClimbersScore2 = parseInt(score);
                this.setState({ scores: s });
                break;
            case "autonMountainScore2":
                var s = this.state.scores;
                s.autonMountainScore2 = parseInt(score);
                this.setState({ scores: s });
                break;
            case "teleopClimbersScore2":
                var s = this.state.scores;
                s.teleopClimbersScore2 = parseInt(score);
                this.setState({ scores: s });
                break;
            case "highBucketScore2":
                var s = this.state.scores;
                s.highBucketScore2 = parseInt(score);
                this.setState({ scores: s });
                break;
            case "midBucketScore2":
                var s = this.state.scores;
                s.midBucketScore2 = parseInt(score);
                this.setState({ scores: s });
                break;
            case "lowBucketScore2":
                var s = this.state.scores;
                s.lowBucketScore2 = parseInt(score);
                this.setState({ scores: s });
                break;
            case "floorGoalScore2":
                var s = this.state.scores;
                s.floorGoalScore2 = parseInt(score);
                this.setState({ scores: s });
                break;
            case "lowZiplineClimberScore2":
                var s = this.state.scores;
                s.lowZiplineClimberScore2 = parseInt(score);
                this.setState({ scores: s });
                break;
            case "midZiplineClimberScore2":
                var s = this.state.scores;
                s.midZiplineClimberScore2 = parseInt(score);
                this.setState({ scores: s });
                break;
            case "highZiplineClimberScore2":
                var s = this.state.scores;
                s.highZiplineClimberScore2 = parseInt(score);
                this.setState({ scores: s });
                break;
            case "allClearScore2":
                var s = this.state.scores;
                s.allClearScore2 = parseInt(score);
                this.setState({ scores: s });
                break;
            case "endgameMountainScore2":
                var s = this.state.scores;
                s.endgameMountainScore2 = parseInt(score);
                this.setState({ scores: s });
                break;
            default:
                break;
        }
    },
    render: function () {
        return (

FTC ResQ Calculator Form

                <Autonomous scores = {this.state.scores} handleScoreChange = {this.handleScoreChange}/>
                <Teleop scores = {this.state.scores} handleScoreChange = {this.handleScoreChange}/>
                <Endgame scores = {this.state.scores} handleScoreChange = {this.handleScoreChange}/>
                <ScoreLabel scores = {this.state.scores}/>

        );
    }
});

class ScoreCalculator {
    constructor(scores) {
        this.scores = scores;
    }
    getTotalAutonButtonScore(){
        var score = this.scores.autonButtonScore1 + this.scores.autonButtonScore2
        return score;
    }
    getZiplineClimbersScore1(){
        var ziplineClimbersScore = this.scores.lowZiplineClimberScore1 + this.scores.midZiplineClimberScore1
         + this.scores.highZiplineClimberScore1;
        return ziplineClimbersScore;
    }
    getZiplineClimbersScore2(){
        var ziplineClimbersScore = this.scores.lowZiplineClimberScore2 + this.scores.midZiplineClimberScore2
         + this.scores.highZiplineClimberScore2;
        return ziplineClimbersScore;
    }
    getTotalZiplineClimbersScore(){
        var high = 0;
        var mid = 0;
        var low = 0;
        if(this.scores.highZiplineClimberScore1 == 20 || this.scores.highZiplineClimberScore2 == 20){
            high = 20
        }
        if(this.scores.midZiplineClimberScore1 == 20 || this.scores.midZiplineClimberScore2 == 20){
            mid = 20
        }
        if(this.scores.lowZiplineClimberScore1 == 20 || this.scores.lowZiplineClimberScore2 == 20){
            low = 20
        }
        return high + mid + low;
    }
    getDebrisScore1() {
        var debrisScore = this.scores.highBucketScore1 + this.scores.midBucketScore1 + this.scores.lowBucketScore1
            + this.scores.floorGoalScore1;
        return debrisScore;
    }
    getDebrisScore2() {
        var debrisScore = this.scores.highBucketScore2 + this.scores.midBucketScore2 + this.scores.lowBucketScore2
            + this.scores.floorGoalScore2;
        return debrisScore;
    }
    getTotalDebrisScore() {
        var debrisScore = this.getDebrisScore1() + this.getDebrisScore2();
        return debrisScore;
    }
    getClimbersScore1() {
        var climbersScore = 0;
        switch(this.scores.autonClimbersScore1){
            case 0:
                climbersScore = this.scores.teleopClimbersScore1
                break;
            case 20:
                if(this.scores.teleopClimbersScore1 == 0){
                    climbersScore = 20;
                }
                else {
                    climbersScore = 30;
                }
                break;
            case 40:
                climbersScore = 40;
                break;
            default:
                break;
        }
        return climbersScore;
    }
    getClimbersScore2() {
        var climbersScore = 0;
        switch(this.scores.autonClimbersScore2){
            case 0:
                climbersScore = this.scores.teleopClimbersScore2
                break;
            case 20:
                if(this.scores.teleopClimbersScore2 == 0){
                    climbersScore = 20;
                }
                else {
                    climbersScore = 30;
                }
                break;
            case 40:
                climbersScore = 40;
                break;
            default:
                break;
        }
        return climbersScore;
    }
    getTotalClimbersScore() {
        var score = this.getClimbersScore1() + this.getClimbersScore2();
        return score;
    }
    getTotalAutonMountainScore(){
        var score = this.scores.autonMountainScore1 + this.scores.autonMountainScore2;
        return score;
    }
    getTotalAllClearScore(){
        var score = this.scores.allClearScore1 + this.scores.allClearScore2;
        return score;
    }
    getTotalEndgameMountainScore(){
        var score = this.scores.endgameMountainScore1 + this.scores.endgameMountainScore2;
        return score;
    }
    getPartialScore1() {
        var totalScore = this.scores.autonButtonScore1 + this.getClimbersScore1() + this.scores.autonMountainScore1 + this.getDebrisScore1()
         + this.getZiplineClimbersScore1() + this.scores.allClearScore1 + this.scores.endgameMountainScore1;
        return totalScore;
    }
    getPartialScore2() {
        var totalScore = this.scores.autonButtonScore2 + this.getClimbersScore2() + this.scores.autonMountainScore2 + this.getDebrisScore2()
         + this.getZiplineClimbersScore2() + this.scores.allClearScore2 + this.scores.endgameMountainScore2;
        return totalScore;
    }
    getTotalScore(){
        var totalScore = this.getTotalAutonButtonScore() + this.getTotalClimbersScore() + this.getTotalAutonMountainScore() + this.getTotalDebrisScore()
         + this.getTotalZiplineClimbersScore() + this.getTotalAllClearScore() + this.getTotalEndgameMountainScore();
        return totalScore;
    }
}

var ScoreLabel = React.createClass({
    getTotalScore: function (scores) {
        var scoreCalculator = new ScoreCalculator(scores);
        return scoreCalculator.getTotalScore();
    },
    getPartialScore1: function (scores) {
        var scoreCalculator = new ScoreCalculator(scores);
        return scoreCalculator.getPartialScore1();
    },
    getPartialScore2: function (scores) {
        var scoreCalculator = new ScoreCalculator(scores);
        return scoreCalculator.getPartialScore2();
    },
    render: function () {
        return (

                <MyHeader> Scores </MyHeader>

 Total: { this.getTotalScore(this.props.scores) }

 Partial Target 1: { this.getPartialScore1(this.props.scores) }

 Partial Target 2: { this.getPartialScore2(this.props.scores) }

        );
    }
});

var MyHeader = React.createClass({
    render: function () {
        return (

{this.props.children}

        );
    }
});

var Autonomous = React.createClass({
    render: function () {
        return (

                <MyHeader> Autonomous </MyHeader>
                <ScoreAutonButton scores = {this.props.scores} handleScoreChange = {this.props.handleScoreChange}/>
                <ScoreAutonClimbers scores = {this.props.scores} handleScoreChange = {this.props.handleScoreChange}/>
                <ScoreAutonMountain scores = {this.props.scores} handleScoreChange = {this.props.handleScoreChange}/>

        );
    }
});

var ScoreAutonButton = React.createClass({
    handleChange1: function (event) {
        var isPressed = (event.target.checked);
        var score = 0;
        if (isPressed) {
            score = 20;
        }
        else {
            score = 0;
        };
        this.props.handleScoreChange(score, "autonButtonScore1");
    },
    handleChange2: function (event) {
        var isPressed = (event.target.checked);
        var score = 0;
        if (isPressed) {
            score = 20;
        }
        else {
            score = 0;
        };
        this.props.handleScoreChange(score, "autonButtonScore2");
    },
    render: function () {
        return (

Button

                <form>

 Target 1:

                    <input type="checkbox" name="button1" value="pressed" onChange={this.handleChange1}
                    checked={this.props.scores.autonButtonScore1 == 20}/> Successful Button Press

                </form>
                <form>

 Target 2:

                    <input type="checkbox" name="button2" value="pressed" onChange={this.handleChange2}
                    checked={this.props.scores.autonButtonScore2 == 20}/> Successful Button Press

                </form>

        );
    }
});

var ScoreAutonClimbers = React.createClass({
    handleChange1: function (event) {
        var score = (event.target.value)
        this.props.handleScoreChange(score, "autonClimbersScore1");
    },
    handleChange2: function (event) {
        var score = (event.target.value)
        this.props.handleScoreChange(score, "autonClimbersScore2");
    },
    render: function () {
        return (

Climbers Delivered

                <form>

 Target 1:

                    <input type="radio" name="autonClimbersScore1" value={0} onChange={this.handleChange1}
                        checked={this.props.scores.autonClimbersScore1 == 0}/> None

                    <input type="radio" name="autonClimbersScore1" value={20} onChange={this.handleChange1}
                        checked={this.props.scores.autonClimbersScore1 == 20}/> One

                    <input type="radio" name="autonClimbersScore1" value={40} onChange={this.handleChange1}
                        checked={this.props.scores.autonClimbersScore1 == 40}/> Both

                </form>
                <form>

 Target 2:

                    <input type="radio" name="autonClimbersScore2" value={0} onChange={this.handleChange2}
                        checked={this.props.scores.autonClimbersScore2 == 0}/> None

                    <input type="radio" name="autonClimbersScore2" value={20} onChange={this.handleChange2}
                        checked={this.props.scores.autonClimbersScore2 == 20}/> One

                    <input type="radio" name="autonClimbersScore2" value={40} onChange={this.handleChange2}
                        checked={this.props.scores.autonClimbersScore2 == 40}/> Both

                </form>

        );
    }
});

var ScoreAutonMountain = React.createClass({
    handleChange1: function (event) {
        var score = (event.target.value)
        this.props.handleScoreChange(score, "autonMountainScore1");
    },
    handleChange2: function (event) {
        var score = (event.target.value)
        this.props.handleScoreChange(score, "autonMountainScore2");
    },
    render: function () {
        return (

Autonomous Mountain Position

                <form>

 Target 1:

                    <input type="radio" name="autonMountainScore1" value={0} onChange={this.handleChange1}
                        checked={this.props.scores.autonMountainScore1 == 0}/> None

                    <input type="radio" name="autonMountainScore1" value={5} onChange={this.handleChange1}
                        checked={this.props.scores.autonMountainScore1 == 5}/> Partial or Parking Zone

                    <input type="radio" name="autonMountainScore1" value={10} onChange={this.handleChange1}
                        checked={this.props.scores.autonMountainScore1 == 10}/> Low Zone

                    <input type="radio" name="autonMountainScore1" value={20} onChange={this.handleChange1}
                        checked={this.props.scores.autonMountainScore1 == 20}/> MidZone

                    <input type="radio" name="autonMountainScore1" value={40} onChange={this.handleChange1}
                        checked={this.props.scores.autonMountainScore1 == 40}/> High Zone

                </form>
                <form>

 Target 2:

                    <input type="radio" name="autonMountainScore2" value={0} onChange={this.handleChange2}
                        checked={this.props.scores.autonMountainScore2 == 0}/> None

                    <input type="radio" name="autonMountainScore2" value={5} onChange={this.handleChange2}
                        checked={this.props.scores.autonMountainScore2 == 5}/> Partial or Parking Zone

                    <input type="radio" name="autonMountainScore2" value={10} onChange={this.handleChange2}
                        checked={this.props.scores.autonMountainScore2 == 10}/> Low Zone

                    <input type="radio" name="autonMountainScore2" value={20} onChange={this.handleChange2}
                        checked={this.props.scores.autonMountainScore2 == 20}/> MidZone

                    <input type="radio" name="autonMountainScore2" value={40} onChange={this.handleChange}
                        checked={this.props.scores.autonMountainScore2 == 40}/> High Zone

                </form>

        );
    }
});

var Teleop = React.createClass({
    render: function () {
        return (

                <MyHeader> Teleop </MyHeader>
                <ScoreTeleopClimbers scores = {this.props.scores} handleScoreChange = {this.props.handleScoreChange}/>
                <Debris scores = {this.props.scores} handleScoreChange = {this.props.handleScoreChange}/>
                <ScoreZiplineClimbers scores = {this.props.scores} handleScoreChange = {this.props.handleScoreChange}/>

        );
    }
});

var ScoreTeleopClimbers = React.createClass({
    handleChange1: function (event) {
        var score = (event.target.value)
        this.props.handleScoreChange(score, "teleopClimbersScore1");
    },
    handleChange2: function (event) {
        var score = (event.target.value)
        this.props.handleScoreChange(score, "teleopClimbersScore2");
    },
    render: function () {
        return (

Climbers Delivered

                <form>

 Target 1:

                    <input type="radio" name="teleopClimbersScore1" value={0} onChange={this.handleChange1}
                        checked={this.props.scores.teleopClimbersScore1 == 0}/> None

                    <input type="radio" name="teleopClimbersScore1" value={10} onChange={this.handleChange1}
                        checked={this.props.scores.teleopClimbersScore1 == 10}/> One

                    <input type="radio" name="teleopClimbersScore1" value={20} onChange={this.handleChange1}
                        checked={this.props.scores.teleopClimbersScore1 == 20}/> Both

                </form>
                <form>

 Target 2:

                    <input type="radio" name="teleopClimbersScore2" value={0} onChange={this.handleChange2}
                        checked={this.props.scores.teleopClimbersScore2 == 0}/> None

                    <input type="radio" name="teleopClimbersScore2" value={10} onChange={this.handleChange2}
                        checked={this.props.scores.teleopClimbersScore2 == 10}/> One

                    <input type="radio" name="teleopClimbersScore2" value={20} onChange={this.handleChange2}
                        checked={this.props.scores.teleopClimbersScore2 == 20}/> Both

                </form>

        );
    }
});

var Debris = React.createClass({
    render: function () {
        return (

Debris Scored

                <ScoreHighBucket scores = {this.props.scores} handleScoreChange = {this.props.handleScoreChange}/>
                <ScoreMidBucket scores = {this.props.scores} handleScoreChange = {this.props.handleScoreChange}/>
                <ScoreLowBucket scores = {this.props.scores} handleScoreChange = {this.props.handleScoreChange}/>
                <ScoreFloorGoal scores = {this.props.scores} handleScoreChange = {this.props.handleScoreChange}/>

        );
    }
});

var ScoreHighBucket = React.createClass({
    handleChange1: function (event) {
        var score = (event.target.value) * 15;
        this.props.handleScoreChange(score, "highBucketScore1");
    },
    handleChange2: function (event) {
        var score = (event.target.value) * 15;
        this.props.handleScoreChange(score, "highBucketScore2");
    },
    render: function () {
        return (

                <form>

 High Bucket Target 1:

                    <input type="number" name="high1" min="0" max="16" value={(this.props.scores.highBucketScore1)/15} onChange={this.handleChange1}/>

                </form>
                <form>

 High Bucket Target 2:

                    <input type="number" name="high2" min="0" max="16" value={(this.props.scores.highBucketScore2)/15} onChange={this.handleChange2}/>

                </form>

        );
    }
});

var ScoreMidBucket = React.createClass({
    handleChange1: function (event) {
        var score = (event.target.value) * 10;
        this.props.handleScoreChange(score, "midBucketScore1");
    },
    handleChange2: function (event) {
        var score = (event.target.value) * 10;
        this.props.handleScoreChange(score, "midBucketScore2");
    },
    render: function () {
        return (

                <form>

 Mid Bucket Target 1:

                    <input type="number" name="mid1" min="0" max="16" value={(this.props.scores.midBucketScore1)/10} onChange={this.handleChange1}/>

                </form>
                <form>

 Mid Bucket Target 2:

                    <input type="number" name="mid2" min="0" max="16" value={(this.props.scores.midBucketScore2)/10} onChange={this.handleChange2}/>

                </form>

        );
    }
});

var ScoreLowBucket = React.createClass({
    handleChange1: function (event) {
        var score = (event.target.value) * 5;
        this.props.handleScoreChange(score, "lowBucketScore1");
    },
    handleChange2: function (event) {
        var score = (event.target.value) * 5;
        this.props.handleScoreChange(score, "lowBucketScore2");
    },
    render: function () {
        return (

                <form>

 Low Bucket Target 1:

                    <input type="number" name="low1" min="0" max="16" value={(this.props.scores.lowBucketScore1)/5} onChange={this.handleChange1}/>
                </form>
                <form>

 Low Bucket Target 2:

                    <input type="number" name="low2" min="0" max="16" value={(this.props.scores.lowBucketScore2)/5} onChange={this.handleChange2}/>
                </form>

        );
    }
});

var ScoreFloorGoal = React.createClass({
    handleChange1: function (event) {
        var score = (event.target.value) * 1;
        this.props.handleScoreChange(score, "floorGoalScore1");
    },
    handleChange2: function (event) {
        var score = (event.target.value) * 1;
        this.props.handleScoreChange(score, "floorGoalScore2");
    },
    render: function () {
        return (

                <form>

 Floor Goal Target 1:

                    <input type="number" name="floor1" min="0" max="40" value={this.props.scores.floorGoalScore1} onChange={this.handleChange1}/>
                </form>
                <form>

 Floor Goal Target 2:

                    <input type="number" name="floor2" min="0" max="40" value={this.props.scores.floorGoalScore2} onChange={this.handleChange2}/>
                </form>

        );
    }
});

var ScoreZiplineClimbers = React.createClass({
    handleChange1: function (event) {
        var isPressed = (event.target.checked);
        switch(event.target.name){
            case "low1":
                if(isPressed){
                    this.props.handleScoreChange(20, "lowZiplineClimberScore1");
                }
                else {
                    this.props.handleScoreChange(0, "lowZiplineClimberScore1");
                }
                break;
            case "mid1":
                if(isPressed){
                    this.props.handleScoreChange(20, "midZiplineClimberScore1");
                }
                else {
                    this.props.handleScoreChange(0, "midZiplineClimberScore1");
                }
                break;
            case "high1":
                if(isPressed){
                    this.props.handleScoreChange(20, "highZiplineClimberScore1");
                }
                else {
                    this.props.handleScoreChange(0, "highZiplineClimberScore1");
                }
                break;
            default:
                break;
        }
    },
    handleChange2: function (event) {
        var isPressed = (event.target.checked);
        switch(event.target.name){
            case "low2":
                if(isPressed){
                    this.props.handleScoreChange(20, "lowZiplineClimberScore2");
                }
                else {
                    this.props.handleScoreChange(0, "lowZiplineClimberScore2");
                }
                break;
            case "mid2":
                if(isPressed){
                    this.props.handleScoreChange(20, "midZiplineClimberScore2");
                }
                else {
                    this.props.handleScoreChange(0, "midZiplineClimberScore2");
                }
                break;
            case "high2":
                if(isPressed){
                    this.props.handleScoreChange(20, "highZiplineClimberScore2");
                }
                else {
                    this.props.handleScoreChange(0, "highZiplineClimberScore2");
                }
                break;
            default:
                break;
        }
    },
    render: function () {
        return (

Zipline Climbers Triggered Target 1:

                <form>
                    <input type="checkbox" name="low1" value="pressed" onChange={this.handleChange1}
                    checked={this.props.scores.lowZiplineClimberScore1 == 20}/> Low Zone Trigger

                    <input type="checkbox" name="mid1" value="pressed" onChange={this.handleChange1}
                    checked={this.props.scores.midZiplineClimberScore1 == 20}/> Mid Zone Trigger

                    <input type="checkbox" name="high1" value="pressed" onChange={this.handleChange1}
                    checked={this.props.scores.highZiplineClimberScore1 == 20}/> High Zone Trigger
                </form>

Zipline Climbers Triggered Target 2:

                <form>
                    <input type="checkbox" name="low2" value="pressed" onChange={this.handleChange2}
                    checked={this.props.scores.lowZiplineClimberScore2 == 20}/> Low Zone Trigger

                    <input type="checkbox" name="mid2" value="pressed" onChange={this.handleChange2}
                    checked={this.props.scores.midZiplineClimberScore2 == 20}/> Mid Zone Trigger

                    <input type="checkbox" name="high2" value="pressed" onChange={this.handleChange2}
                    checked={this.props.scores.highZiplineClimberScore2 == 20}/> High Zone Trigger
                </form>

        );
    }
});

var Endgame = React.createClass({
    render: function () {
        return (

                <MyHeader> Endgame </MyHeader>
                <ScoreEngameMountain scores = {this.props.scores} handleScoreChange = {this.props.handleScoreChange}/>
                <ScoreAllClearSignal scores = {this.props.scores} handleScoreChange = {this.props.handleScoreChange}/>

        );
    }
});

var ScoreAllClearSignal = React.createClass({
    handleChange1: function (event) {
        var isSignaled1 = (event.target.checked);
        var score = 0;
        if (isSignaled1) {
            score = 20;
        }
        else {
            score = 0;
        };
        this.props.handleScoreChange(score, "allClearScore1");
    },
    handleChange2: function (event) {
        var isSignaled2 = (event.target.checked);
        var score = 0;
        if (isSignaled2) {
            score = 20;
        }
        else {
            score = 0;
        };
        this.props.handleScoreChange(score, "allClearScore2");
    },
    render: function () {
        return (

All Clear Signal Target 1

                <form>
                    <input type="checkbox" name="isSignaled1" value="signaled" onChange={this.handleChange1}
                    checked={this.props.scores.allClearScore1 == 20}/> All Clear Signaled
                </form>

All Clear Signal Target 2

                <form>
                    <input type="checkbox" name="isSignaled2" value="signaled" onChange={this.handleChange2}
                    checked={this.props.scores.allClearScore2 == 20}/> All Clear Signaled
                </form>

        );
    }
});

var ScoreEngameMountain = React.createClass({
    handleChange1: function (event) {
        var score = (event.target.value)
        this.props.handleScoreChange(score, "endgameMountainScore1");
    },
    handleChange2: function (event) {
        var score = (event.target.value)
        this.props.handleScoreChange(score, "endgameMountainScore2");
    },
    render: function () {
        return (

Endgame Mountain Position

                <form>
                    <input type="radio" name="endgameMountainScore1" value={0} onChange={this.handleChange1}
                        checked={this.props.scores.endgameMountainScore1 == 0}/> None

                    <input type="radio" name="endgameMountainScore1" value={5} onChange={this.handleChange1}
                        checked={this.props.scores.endgameMountainScore1 == 5}/> Partial

                    <input type="radio" name="endgameMountainScore1" value={10} onChange={this.handleChange1}
                        checked={this.props.scores.endgameMountainScore1 == 10}/> Low Zone

                    <input type="radio" name="endgameMountainScore1" value={20} onChange={this.handleChange1}
                        checked={this.props.scores.endgameMountainScore1 == 20}/> MidZone

                    <input type="radio" name="endgameMountainScore1" value={40} onChange={this.handleChange1}
                        checked={this.props.scores.endgameMountainScore1 == 40}/> High Zone

                    <input type="radio" name="endgameMountainScore1" value={80} onChange={this.handleChange1}
                        checked={this.props.scores.endgameMountainScore1 == 80}/> Hanging
                </form>

Endgame Mountain Position

                <form>
                    <input type="radio" name="endgameMountainScore2" value={0} onChange={this.handleChange2}
                        checked={this.props.scores.endgameMountainScore2 == 0}/> None

                    <input type="radio" name="endgameMountainScore2" value={5} onChange={this.handleChange2}
                        checked={this.props.scores.endgameMountainScore2 == 5}/> Partial

                    <input type="radio" name="endgameMountainScore2" value={10} onChange={this.handleChange2}
                        checked={this.props.scores.endgameMountainScore2 == 10}/> Low Zone

                    <input type="radio" name="endgameMountainScore2" value={20} onChange={this.handleChange2}
                        checked={this.props.scores.endgameMountainScore2 == 20}/> MidZone

                    <input type="radio" name="endgameMountainScore2" value={40} onChange={this.handleChange2}
                        checked={this.props.scores.endgameMountainScore2 == 40}/> High Zone

                    <input type="radio" name="endgameMountainScore2" value={80} onChange={this.handleChange2}
                        checked={this.props.scores.endgameMountainScore2 == 80}/> Hanging
                </form>

        );
    }
});

ReactDOM.render(
    <FTCResQCalculatorForm/>,
    document.getElementById('content')
);


text:
#include "file_vname_generator.h"

#include "glog/logging.h"
#include "rapidjson/document.h"
#include "rapidjson/error/en.h"

namespace kythe {

// FullMatchN supports "3..16 args"
static constexpr int kMaxRegexArgs = 16;

FileVNameGenerator::FileVNameGenerator() {
  CHECK_EQ(RE2::NoError, substitution_matcher_.error_code());
}

std::string FileVNameGenerator::ApplyRule(const StringConsRule &rule,
                                          const re2::StringPiece *argv,
                                          int argc) const {
  std::string ret;
  for (const auto &node : rule) {
    switch (node.kind) {
      case StringConsNode::Kind::kEmitText:
        ret.append(node.raw_text);
        break;
      case StringConsNode::Kind::kUseSubstitution:
        // Invariant: 0 <= node.capture_index < argc
        ret.append(argv[node.capture_index].ToString());
        break;
    }
  }
  return ret;
}

bool FileVNameGenerator::ParseRule(const std::string &rule, int max_capture,
                                   StringConsRule *result,
                                   std::string *error_text) {
  CHECK(result != nullptr);
  CHECK(error_text != nullptr);
  re2::StringPiece rule_left(rule);
  while (!rule_left.empty()) {
    re2::StringPiece prefix, substitution;
    if (!RE2::Consume(&rule_left, substitution_matcher_, &prefix,
                      &substitution)) {
      prefix = rule_left;
      rule_left = re2::StringPiece();
    }
    if (!prefix.empty()) {
      StringConsNode node;
      node.kind = StringConsNode::Kind::kEmitText;
      node.raw_text = prefix.ToString();
      result->push_back(node);
    }
    if (!substitution.empty()) {
      StringConsNode node;
      node.kind = StringConsNode::Kind::kUseSubstitution;
      node.capture_index = std::stoi(substitution.ToString());
      if (node.capture_index == 0 || node.capture_index > max_capture) {
        *error_text =
            "Capture index out of range: " + std::to_string(node.capture_index);
        return false;
      }
      // Make these zero-based.
      --node.capture_index;
      result->push_back(node);
    }
  }
  return true;
}

kythe::proto::VName FileVNameGenerator::LookupBaseVName(
    const std::string &path) const {
  re2::StringPiece argv[kMaxRegexArgs];
  RE2::Arg args[kMaxRegexArgs];
  RE2::Arg *arg_pointers[kMaxRegexArgs];
  for (size_t n = 0; n < kMaxRegexArgs; ++n) {
    args[n] = &argv[n];
    arg_pointers[n] = &args[n];
  }
  for (const auto &rule : rules_) {
    // Invariant: capture_groups <= kMaxRegexArgs
    // RE2 will fail to match if we provide more args than there are captures
    // for a given regex.
    int capture_groups = rule.pattern->NumberOfCapturingGroups();
    if (RE2::FullMatchN(path, *rule.pattern, arg_pointers, capture_groups)) {
      kythe::proto::VName result;
      if (!rule.corpus.empty()) {
        result.set_corpus(ApplyRule(rule.corpus, argv, capture_groups));
      }
      if (!rule.root.empty()) {
        result.set_root(ApplyRule(rule.root, argv, capture_groups));
      }
      if (!rule.path.empty()) {
        result.set_path(ApplyRule(rule.path, argv, capture_groups));
      }
      return result;
    }
  }
  return kythe::proto::VName();
}

kythe::proto::VName FileVNameGenerator::LookupVName(
    const std::string &path) const {
  kythe::proto::VName vname = LookupBaseVName(path);
  if (vname.path().empty()) {
    vname.set_path(path);
  }
  return vname;
}

bool FileVNameGenerator::LoadJsonString(const std::string &data,
                                        std::string *error_text) {
  CHECK(error_text != nullptr);
  using Value = rapidjson::Value;
  rapidjson::Document document;
  document.Parse(data.c_str());
  if (document.HasParseError()) {
    if (error_text) {
      *error_text = rapidjson::GetParseError_En(document.GetParseError());
      error_text->append(" near offset ");
      error_text->append(std::to_string(document.GetErrorOffset()));
    }
    return false;
  }
  if (!document.IsArray()) {
    *error_text = "Root element in JSON was not an array.";
    return false;
  }
  for (Value::ConstValueIterator rule = document.Begin();
       rule != document.End(); ++rule) {
    if (!rule->IsObject()) {
      *error_text = "Expected an array of objects.";
      return false;
    }
    const auto regex = rule->FindMember("pattern");
    if (regex == rule->MemberEnd() || !regex->value.IsString()) {
      *error_text = "VName rule is missing its pattern.";
      return false;
    }
    VNameRule next_rule;
    // RE2s don't act like values. Just box them.
    next_rule.pattern = std::make_shared<RE2>(regex->value.GetString());
    if (next_rule.pattern->error_code() != RE2::NoError) {
      *error_text = next_rule.pattern->error();
      return false;
    }
    int num_captures = next_rule.pattern->NumberOfCapturingGroups();
    CHECK(num_captures <= kMaxRegexArgs);
    const auto vname = rule->FindMember("vname");
    if (vname == rule->MemberEnd() || !vname->value.IsObject()) {
      *error_text = "VName rule is missing its template.";
      return false;
    }
    const auto root = vname->value.FindMember("root");
    if (root != vname->value.MemberEnd()) {
      if (!root->value.IsString()) {
        *error_text = "VName template root is not a string.";
        return false;
      }
      if (!ParseRule(root->value.GetString(), num_captures, &next_rule.root,
                     error_text)) {
        return false;
      }
    }
    const auto corpus = vname->value.FindMember("corpus");
    if (corpus != vname->value.MemberEnd()) {
      if (!corpus->value.IsString()) {
        *error_text = "VName template corpus is not a string.";
        return false;
      }
      if (!ParseRule(corpus->value.GetString(), num_captures, &next_rule.corpus,
                     error_text)) {
        return false;
      }
    }
    const auto path = vname->value.FindMember("path");
    if (path != vname->value.MemberEnd()) {
      if (!path->value.IsString()) {
        *error_text = "VName template path is not a string.";
        return false;
      }
      if (!ParseRule(path->value.GetString(), num_captures, &next_rule.path,
                     error_text)) {
        return false;
      }
    }
    rules_.push_back(next_rule);
  }
  return true;
}
}  // namespace kythe


text:
To run the integration tests against the production environment one must setup
a number of resources. This document describes how to do so, assuming you have
an existing project in Google Cloud Platform.

## Setting up a Project

Set the `PROJECT_ID` environment variable to your test project:

```console
PROJECT_ID=... # Your test project
```

Create the project:

```console
gcloud projects create ${PROJECT_ID}
```

Configure `gcloud` (aka the "Google Cloud SDK") to use this project:

```console
gcloud config set core/project ${PROJECT_ID}
```

## Create a Service Account to run the integration tests.

First, create a new service account to execute the integration tests:

```console
AGENT_ACCOUNT=... # e.g. integration-tests-robot
gcloud --project=${PROJECT_ID} iam service-accounts create ${AGENT_ACCOUNT}
```

Grant the new service account account full access to Google Cloud Storage:

```
gcloud projects add-iam-policy-binding ${PROJECT_ID} \
  --member serviceAccount:${AGENT_ACCOUNT}@${PROJECT_ID}.iam.gserviceaccount.com \
  --role roles/storage.admin
```

Grant the new service account permissions to sign URLs, policy documents, and
other blobs:

```
gcloud projects add-iam-policy-binding ${PROJECT_ID} \
  --member serviceAccount:${AGENT_ACCOUNT}@${PROJECT_ID}.iam.gserviceaccount.com \
  --role roles/iam.serviceAccountTokenCreator
```

Download key files for the new service account:

```console
gcloud --project=${PROJECT_ID} iam service-accounts keys create \
    /dev/shm/service-account.p12 --key-file-type=p12 \
    --iam-account=${AGENT_ACCOUNT}@${PROJECT_ID}.iam.gserviceaccount.com
gcloud --project=${PROJECT_ID} iam service-accounts keys create \
    /dev/shm/service-account.json --key-file-type=json \
    --iam-account=${AGENT_ACCOUNT}@${PROJECT_ID}.iam.gserviceaccount.com
```

## Setting up a Bucket

Select a region that's close to your location. The
[documentation](https://cloud.google.com/storage/docs/locations) has the full
list of allowed locations. In this example, we'll use `us-central1`.

```console
BUCKET=... # e.g. cloud-cpp-testing-bucket
gsutil -l us-central1 gs://${BUCKET}
```

## Setting up a Destination Bucket

For testing purposes, we'll use a bucket that's in a different region from our
initial bucket.

```console
DESTINATION_BUCKET=... # e.g. cloud-cpp-testing-destination-bucket
gsutil -l us-east1 gs://${DESTINATION_BUCKET}
```

## Setting up a Pub/Sub Topic

Create the topic:

```console
gcloud pubsub topics create cloud-cpp-testing-topic
```

## Setting up a Customer-Managed Encryption Key

First, create the keyring and key:

```
KR=... # e.g cloud-cpp-testing-keyring
KEYID=... # e.g cloud-cpp-testing-key
gcloud kms keyrings create ${KR} --location=global
gcloud kms keys create ${KEYID} --purpose=encryption --location=global --keyring=${KR}
gcloud kms keys list --location=global --keyring=${KR}
```

Authorize our service account to use the new key:

```
KEYNAME=projects/${PROJECT_NAME}/locations/global/keyRings/${KR}/cryptoKeys/${KEYID}
gsutil kms authorize -p ${PROJECT_NAME} -k ${KEYNAME}
```

Configure the bucket to use this new key as the default:

```
gsutil kms encryption -k ${KEYNAME} gs://${BUCKET}
```

## Setting up a Service Account for HMAC Keys

List the current service accounts:

```console
gcloud iam service-accounts list
```

Create the new service account:

```console
gcloud iam service-accounts create test-hmac-key
```

Grant the service account permissions to manage HMAC keys:

```console
gcloud projects add-iam-policy-binding ${PROJECT_ID} \
  --member serviceAccount:test-hmac-key@${PROJECT_ID}.iam.gserviceaccount.com \
  --role roles/iam.hmacKeys
```

## Setting up a Service Account for Signing Blobs

List the current service accounts:

```console
gcloud iam service-accounts list
```

Create the new service account:

```console
gcloud iam service-accounts create test-sign-blob
```

Grant the new service account permissions to sign blobs:

```console
gcloud projects add-iam-policy-binding ${PROJECT_ID} \
  --member serviceAccount:test-sign-blob@${PROJECT_ID}.iam.gserviceaccount.com \
  --role roles/iam.serviceAccountTokenCreator
```

If needed, grant your account the same permissions, this is needed even if your
account is the owner of the project:

```console
gcloud projects add-iam-policy-binding ${PROJECT_ID} \
  --member user:$(gcloud config get-value account) \
  --role roles/iam.serviceAccountTokenCreator
```

If you are using a service account to access GCP (as opposed to an authorized
user), then replace the previous command with:

```console
gcloud projects add-iam-policy-binding ${PROJECT_ID} \
  --member serviceAccount:$(gcloud config get-value account) \
  --role roles/iam.serviceAccountTokenCreator
```

Verify the service account can sign blobs:

```console
echo 'Test string to sign' >to-sign.txt
gcloud iam service-accounts sign-blob \
    --iam-account=test-sign-blob@${PROJECT_ID}.iam.gserviceaccount.com \
    to-sign.txt signed.txt
```

You can now use `test-sign-blob@${PROJECT_ID}.iam.gserviceaccount.com` to run
the `SignBlob()` tests.


text:
/*
 *
 *
 *
 */

package classe;

import combat.entite.CombatEntite;
import java.util.Set;
import map.Tuile;

/**
 * Effet
 * Interface
 */
public interface Effet {

	public static final Effet DEBUT_COMBAT = (Set<Tuile> tuile, CombatEntite cible, CombatEntite lanceur) -> {
	};

	public abstract void affecter(Set<Tuile> tuile, CombatEntite cible, CombatEntite lanceur);

}


text:
import React from 'react';

export default class RemoveSectionButton extends React.Component {

  constructor(props) {
    super(props);

    this.handleClick = this.handleClick.bind(this);
  }

  handleClick(e) {
  	e.preventDefault();
  	this.props.removeSection(this.props.sectionNumber);
  }

  render() {
    return (
      <div className={'remove-section-button'} onClick={this.handleClick}>
      	-
      </div>
    );
  }
}


text:
import {AmpA4A} from '../../amp-a4a/0.1/amp-a4a';

/**
 * Oblivki base URL
 *
 * @type {string}
 * @private
 */
const OBLIVKI_BASE_URL_ = 'https://oblivki.biz/amp/';

/**
 * Oblivki A4A base URL
 *
 * @type {string}
 * @private
 */
const OBLIVKI_BASE_A4A_URL_ = 'https://oblivki.biz/amp/a4a/';

export class AmpAdNetworkOblivkiImpl extends AmpA4A {
  /** @override */
  getAdUrl(unusedConsentTuple, opt_rtcResponsesPromise) {
    return this.element
      .getAttribute('src')
      .replace(OBLIVKI_BASE_URL_, OBLIVKI_BASE_A4A_URL_);
  }

  /** @override */
  getSigningServiceNames() {
    return ['cloudflare'];
  }

  /** @override */
  isValidElement() {
    const src = this.element.getAttribute('src') || '';
    return (
      this.isAmpAdElement() &&
      (src.startsWith(OBLIVKI_BASE_URL_) ||
        src.startsWith(OBLIVKI_BASE_A4A_URL_))
    );
  }
}

AMP.extension('amp-ad-network-oblivki-impl', '0.1', (AMP) => {
  AMP.registerElement('amp-ad-network-oblivki-impl', AmpAdNetworkOblivkiImpl);
});