text:
package com.futonredemption.jasper.togglers;

import android.content.Context;

import com.futonredemption.jasper.Debugging;
import com.futonredemption.jasper.PreferenceHolder;

/** Manages the toggling a wrapped resourced based on implied ownership.
 * Auto-toggling occurs if the app believes that it has taken control ownership by flag setting as to not
 * conflict with the user's perceived.
 *
 * IE: If the app wants to turn off wifi but the user manually turned it on, the app won't turn it off.
*/
public class PreferencedResourceTogglerWrapper extends AbstractResourceTogglerWrapper {

	private final PreferenceHolder prefs;
	private final String statePreferenceName;

	public PreferencedResourceTogglerWrapper(final Context context, final IResourceToggler toggler, String statePreferenceName) {
		super(toggler);
		this.statePreferenceName = statePreferenceName;
		this.prefs = new PreferenceHolder(context);
	}

	public boolean isSupported() {
		return toggler.isSupported();
	}

	public boolean isEnabled() {
		return toggler.isEnabled();
	}

	public boolean isDisabled() {
		return toggler.isDisabled();
	}

	public boolean enable() {

		Debugging.log("Attempt Enable, " + statePreferenceName);
		// Only enables if the resource is currently off and the mode save preference is disabled as well.
		boolean performedEnable = false;
		if(isDisabled()) {
			Debugging.log("Ok doing it.");
			performedEnable = toggler.enable();
			setPreferenceValue(performedEnable);
		}

		return performedEnable;
	}

	public boolean disable() {
		boolean performedDisable = false;

		Debugging.log("attempt Disable, " + statePreferenceName);

		if(isEnabled()) {
			if(getPreferenceValue()) {
				Debugging.log("Ok doing it.");
				performedDisable = toggler.disable();
				setPreferenceValue(! performedDisable);
			}
		}

		return performedDisable;
	}

	protected boolean getPreferenceValue() {
		return prefs.get().getBoolean(statePreferenceName, false);
	}

	protected void setPreferenceValue(boolean newValue) {
		prefs.get().edit().putBoolean(statePreferenceName, newValue).commit();
	}
}


text:
<?php defined('SYSPATH') OR die('No direct script access.');

/**
 * This class indicates there is an SQL problem.
 *
 * @package Leap
 * @version 2012-11-14
 *
 * @abstract
 */
abstract class Base_Throwable_SQL_Exception extends Throwable_Exception {}
?>

redpajama_set_name: RedPajamaGithub


text:
namespace mozart {

////////////////
// ByteString //
////////////////

#include "ByteString-implem.hh"

// Core methods ----------------------------------------------------------------

ByteString::ByteString(VM vm, GR gr, ByteString& from)
  : _bytes(vm, from._bytes) {
}

bool ByteString::equals(VM vm, RichNode right) {
  return value() == right.as<ByteString>().value();
}

UnstableNode ByteString::getValueAt(VM vm, nativeint feature) {
  return mozart::build(vm, _bytes[feature]);
}

namespace internal {
  inline
  int compareByteStrings(LString<unsigned char> left,
                         LString<unsigned char> right) {
    int cmpRes = left.string != right.string;
    if (cmpRes) {
      size_t minLength = std::min(left.bytesCount(), right.bytesCount());
      cmpRes = memcmp(left.string, right.string, minLength);
    }
    if (!cmpRes) {
      return left.length < right.length ? -1 :
             left.length > right.length ? 1 : 0;
    } else {
      return cmpRes;
    }
  }
}

int ByteString::compare(VM vm, RichNode right) {
  return internal::compareByteStrings(_bytes,
                                      *StringLike(right).byteStringGet(vm));
}

// StringLike ------------------------------------------------------------------

LString<unsigned char>* ByteString::byteStringGet(VM vm) {
  return &_bytes;
}

LString<nchar>* ByteString::stringGet(RichNode self, VM vm) {
  return Interface<StringLike>().stringGet(self, vm);
}

nativeint ByteString::stringCharAt(RichNode self, VM vm, RichNode offsetNode) {
  auto offset = getArgument<nativeint>(vm, offsetNode, MOZART_STR("integer"));

  if (offset < 0 || offset >= _bytes.length)
    raiseIndexOutOfBounds(vm, offsetNode, self);

  return _bytes[offset];
}

UnstableNode ByteString::stringAppend(RichNode self, VM vm, RichNode right) {
  auto rightBytes = StringLike(right).byteStringGet(vm);
  LString<unsigned char> resultBytes = concatLString(vm, _bytes, *rightBytes);
  if (resultBytes.isError())
    raiseUnicodeError(vm, resultBytes.error, self, right);
  return ByteString::build(vm, resultBytes);
}

UnstableNode ByteString::stringSlice(RichNode self, VM vm,
                                     RichNode from, RichNode to) {
  auto fromOffset = getArgument<nativeint>(vm, from, MOZART_STR("integer"));
  auto toOffset = getArgument<nativeint>(vm, to, MOZART_STR("integer"));

  if (fromOffset < 0 || fromOffset > toOffset || toOffset > _bytes.length)
    raiseIndexOutOfBounds(vm, fromOffset, toOffset);

  return ByteString::build(vm, _bytes.slice(fromOffset, toOffset));
}

void ByteString::stringSearch(
  RichNode self, VM vm, RichNode from, RichNode needleNode,
  UnstableNode& begin, UnstableNode& end) {

  // TODO Fix this - it was deactivated because of a build problem on Mac OS
#ifdef __llvm__ // or is it __clang__?
  raiseError(vm, MOZART_STR("notImplemented"),
             MOZART_STR("ByteString::stringSearch"));
#else
  using namespace patternmatching;

  auto fromOffset = getArgument<nativeint>(vm, from, MOZART_STR("integer"));

  if (fromOffset < 0 || fromOffset > _bytes.length)
    raiseIndexOutOfBounds(vm, fromOffset);

  LString<unsigned char> haystack = _bytes.slice(fromOffset);

  nativeint character = 0;

  if (matches(vm, needleNode, capture(character))) {

    if (character < 0 || character >= 0x100)
      raiseTypeError(vm, MOZART_STR("Integer between 0 and 255"), needleNode);

    auto haystackUnsafe = const_cast<unsigned char*>(haystack.string);
    const void* searchRes = memchr(haystackUnsafe, character,
                                   haystack.bytesCount());
    if (searchRes == nullptr) {
      begin = Boolean::build(vm, false);
      end = Boolean::build(vm, false);
    } else {
      nativeint foundOffset =
        static_cast<const unsigned char*>(searchRes) - _bytes.string;
      begin = SmallInt::build(vm, foundOffset);
      end = SmallInt::build(vm, foundOffset + 1);
    }

  } else {

    auto needle = StringLike(needleNode).byteStringGet(vm);
    auto foundIter = std::search(haystack.begin(), haystack.end(),
                                 needle->begin(), needle->end());
    if (foundIter == haystack.end()) {
      begin = Boolean::build(vm, false);
      end = Boolean::build(vm, false);
    } else {
      nativeint foundOffset = foundIter - _bytes.string;
      begin = SmallInt::build(vm, foundOffset);
      end = SmallInt::build(vm, foundOffset + needle->length);
    }

  }
#endif
}

bool ByteString::stringHasPrefix(VM vm, RichNode prefixNode) {
  auto prefix = StringLike(prefixNode).stringGet(vm);
  if (_bytes.length < prefix->length)
    return false;
  else
    return memcmp(_bytes.string, prefix->string, prefix->bytesCount()) == 0;
}

bool ByteString::stringHasSuffix(VM vm, RichNode suffixNode) {
  auto suffix = StringLike(suffixNode).stringGet(vm);
  if (_bytes.length < suffix->length)
    return false;
  else
    return memcmp(_bytes.end() - suffix->length, suffix->string,
                  suffix->bytesCount()) == 0;
}

// VirtualString ---------------------------------------------------------------

void ByteString::toString(VM vm, std::basic_ostream<nchar>& sink) {
  sink << decodeLatin1(_bytes, EncodingVariant::none);
}

nativeint ByteString::vsLength(VM vm) {
  return _bytes.length;
}

// Encode & decode -------------------------------------------------------------

UnstableNode ByteString::decode(RichNode self, VM vm,
                                ByteStringEncoding encoding,
                                EncodingVariant variant) {
  DecoderFun decoder;
  switch (encoding) {
    case ByteStringEncoding::latin1: decoder = &decodeLatin1; break;
    case ByteStringEncoding::utf8:   decoder = &decodeUTF8;   break;
    case ByteStringEncoding::utf16:  decoder = &decodeUTF16;  break;
    case ByteStringEncoding::utf32:  decoder = &decodeUTF32;  break;
    default:
      assert(false);
      decoder = nullptr;
  }

  auto res = newLString(vm, decoder(_bytes, variant));
  if (res.isError())
    raiseUnicodeError(vm, res.error);
  return String::build(vm, res);
}

UnstableNode encodeToBytestring(VM vm, const BaseLString<nchar>& input,
                                ByteStringEncoding encoding,
                                EncodingVariant variant) {
  EncoderFun encoder;
  switch (encoding) {
    case ByteStringEncoding::latin1: encoder = &encodeLatin1; break;
    case ByteStringEncoding::utf8:   encoder = &encodeUTF8;   break;
    case ByteStringEncoding::utf16:  encoder = &encodeUTF16;  break;
    case ByteStringEncoding::utf32:  encoder = &encodeUTF32;  break;
    default:
      assert(false);
      encoder = nullptr;
  }

  auto res = newLString(vm, encoder(input, variant));
  if (res.isError())
    raiseUnicodeError(vm, res.error);
  return ByteString::build(vm, res);
}

// Miscellaneous ---------------------------------------------------------------

void ByteString::printReprToStream(VM vm, std::ostream& out, int depth) {
  out << "<ByteString \"";
  out.write(reinterpret_cast<const char*>(_bytes.string), _bytes.length);
  // TODO: Escape characters.
  out << "\">";
}

}

#endif // MOZART_GENERATOR

#endif // __BYTESTRING_H


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Simple.ServiceBus.Core
{
    public class ServiceRouting
    {
        public static ServiceRouting GlobalRouting = new ServiceRouting();

        public ServiceHandler GetHandler(string requestKey)
        {
            return ServiceRegister.GlobalRegister.GetHandler(requestKey);
        }
    }
}


text:
package br.com.next.repositories.custom;

/**
 * Created by felansu on 15/04/2015.
 */
public interface IRepositorySenhaCustom {
}


text:
CREATE TABLE `mini_blog` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(255) CHARACTER SET utf8 DEFAULT NULL,
  `introduction` text CHARACTER SET utf8,
  `text` text CHARACTER SET utf8,
  `created` datetime DEFAULT NULL,
  `edited` datetime DEFAULT NULL,
  `publish` enum('Y','N') CHARACTER SET utf8 DEFAULT 'Y',
  `user_id` int(11) DEFAULT NULL,
  `language` varchar(3) CHARACTER SET utf8 DEFAULT NULL,
  `meta_id` int(11) DEFAULT NULL,
  `awesomeness` int(11) DEFAULT '0',
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=8 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;


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

import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Function;
import com.google.devtools.build.lib.events.Location;
import java.util.Arrays;
import javax.annotation.Nullable;

/**
 * Provides attribute setting and retrieval for a Rule. Encapsulating attribute access
 * here means it can be passed around independently of the Rule itself. In particular,
 * it can be consumed by independent {@link AttributeMap} instances that can apply
 * varying kinds of logic for determining the "value" of an attribute. For example,
 * a configurable attribute's "value" may be a { config --> value } dictionary
 * or a configuration-bound lookup on that dictionary, depending on the context in
 * which it's requested.
 *
 * <p>This class provides the lowest-level access to attribute information. It is *not*
 * intended to be a robust public interface, but rather just an input to {@link AttributeMap}
 * instances. Use those instances for all domain-level attribute access.
 */
public class AttributeContainer {

  private final RuleClass ruleClass;

  // Attribute values, keyed by attribute index:
  private final Object[] attributeValues;

  // Holds two lists of attribute indices.
  // The first byte gives the length of the first list.
  // The first list records which attributes were set explicitly in the BUILD file.
  // The second list ends at the end of the array.
  // The second list records which attributes have Locations, in reverse order
  // from the attributeLocations array.
  // Between the lists there may be unused zero bytes (zeros are forbidden within each list).
  private byte[] state;

  // Attribute locations, packed:
  private Location[] attributeLocations;

  /**
   * Create a container for a rule of the given rule class.
   */
  public AttributeContainer(RuleClass ruleClass) {
   this(ruleClass, EMPTY_LOCATIONS);
  }

  AttributeContainer(RuleClass ruleClass, Location[] locations) {
    int n = ruleClass.getAttributeCount();
    if (n > 254) {
      // We reserve the zero byte as a hole/sentinel inside state[].
      // If you hit this limit, replace byte with char and remove the masking with 0xff.
      throw new AssertionError("can't pack " + n + " rule indices into bytes");
    }
    this.ruleClass = ruleClass;
    this.attributeValues = new Object[n];
    this.state = EMPTY_STATE;
    this.attributeLocations = locations;
  }

  private static final byte[] EMPTY_STATE = {0};
  private static final Location[] EMPTY_LOCATIONS = {};

  /**
   * Returns an attribute value by name, or null on no match.
   */
  @Nullable
  public Object getAttr(String attrName) {
    Integer idx = ruleClass.getAttributeIndex(attrName);
    return idx != null ? attributeValues[idx] : null;
  }

  /**
   * Returns true iff the given attribute exists for this rule and its value
   * is explicitly set in the BUILD file (as opposed to its default value).
   */
  public boolean isAttributeValueExplicitlySpecified(Attribute attribute) {
    return isAttributeValueExplicitlySpecified(attribute.getName());
  }

  public boolean isAttributeValueExplicitlySpecified(String attributeName) {
    Integer idx = ruleClass.getAttributeIndex(attributeName);
    return idx != null && getExplicit(idx);
  }

 /**
  * Returns the number of elements of state[] currently used to store
  * indices of "explicitly set" attributes.
  */
  private int explicitCount() {
    return 0xff & state[0];
  }

  private boolean getExplicit(int index) {
    int n = explicitCount();
    for (int i = 1; i <= n; ++i) {
      if ((0xff & state[i]) == index + 1) {
        return true;
      }
    }
    return false;
  }

  private int getLocationIndex(int index) {
    int n = explicitCount();
    for (int i = state.length - 1; i > n; --i) {
      if ((0xff & state[i]) == index + 1) {
        return state.length - 1 - i;
      }
    }
    return -1;
  }

  private void setExplicit(int index) {
    if (getExplicit(index)) {
      return;
    }
    ensureSpace();
    int n = explicitCount() + 1;
    state[0] = (byte) n;
    state[n] = (byte) (index + 1);
  }

  private int addLocationIndex(int index) {
    ensureSpace();
    for (int i = state.length - 1; ; --i) {
      if (i <= explicitCount()) {
        throw new AssertionError("ensureSpace() did not insert a zero");
      }
      if (state[i] == 0) {
        state[i] = (byte) (index + 1);
        return state.length - 1 - i;
      }
    }
  }

  /**
   * Ensures that the state[n] byte is equal to the sentinel value 0, so there is room for another
   * attribute's explicit bit to be set, or for an attribute's location to be set.
   */
  private void ensureSpace() {
    int n = explicitCount() + 1;
    if (n < state.length && state[n] == 0) {
      return;
    }
    // Grow up to the next multiple of eight bytes, as the object will be
    // aligned to eight bytes anyway.  Insert zeros between the two lists.
    byte[] newState = new byte[(state.length | 7) + 1];
    // Copy stored explicit attributes to the beginning of the array.
    System.arraycopy(state, 0, newState, 0, n);
    // Copy stored attribute locations to the *end* of the array.
    int oldLocations = state.length - n;
    System.arraycopy(state, n, newState, newState.length - oldLocations, oldLocations);
    state = newState;
  }

  /**
   * Returns the location of the attribute definition for this rule, or null if not found.
   */
  public Location getAttributeLocation(String attrName) {
    Integer idx = ruleClass.getAttributeIndex(attrName);
    int locationIndex = idx != null ? getLocationIndex(idx) : -1;
    return locationIndex >= 0 ? attributeLocations[locationIndex] : null;
  }

  Object getAttributeValue(int index) {
    return attributeValues[index];
  }

  void setAttributeValue(Attribute attribute, Object value, boolean explicit) {
    String name = attribute.getName();
    Integer index = ruleClass.getAttributeIndex(name);
    if (!explicit && getExplicit(index)) {
      throw new IllegalArgumentException("attribute " + name + " already explicitly set");
    }
    attributeValues[index] = value;
    if (explicit) {
      setExplicit(index);
    }
  }

  // This sets the attribute "explicitly" as if it came from the BUILD file.
  // At present, the sole use of this is for the test_suite.$implicit_tests
  // attribute, which is synthesized during package loading.  We do want to
  // consider that "explicitly set" so that it appears in query output.
  void setAttributeValueByName(String attrName, Object value) {
    setAttributeValue(ruleClass.getAttributeByName(attrName), value, true);
  }

  void setAttributeLocation(int attrIndex, Location location) {
    int locationIndex = getLocationIndex(attrIndex);
    if (locationIndex >= 0) {
      throw new IllegalArgumentException("already have a location for attribute "
          + ruleClass.getAttribute(attrIndex).getName() + ": " + attributeLocations[locationIndex]);
    }
    locationIndex = addLocationIndex(attrIndex);
    if (locationIndex >= attributeLocations.length) {
      // Grow by two references, as the object will be aligned to eight bytes anyway.
      attributeLocations = Arrays.copyOf(attributeLocations, attributeLocations.length + 2);
    }
    attributeLocations[locationIndex] = location;
  }

  @VisibleForTesting
  void setAttributeLocation(Attribute attribute, Location location) {
    Integer index = ruleClass.getAttributeIndex(attribute.getName());
    setAttributeLocation(index, location);
  }

  public static final Function<RuleClass, AttributeContainer> ATTRIBUTE_CONTAINER_FACTORY =
      new Function<RuleClass, AttributeContainer>() {
        @Override
        public AttributeContainer apply(RuleClass ruleClass) {
          return new AttributeContainer(ruleClass);
        }
      };
}


text:
FROM node:7-alpine
MAINTAINER Thebora Kompanioni

ENV NODE_ENV production

# Create app directory
RUN mkdir -p /app
WORKDIR /app

COPY ./ /app

RUN mkdir -p /app/logs/dev

EXPOSE 3000

CMD [ "node", "/app" ]


text:
package state

import (
	"fmt"
	"regexp"

	"github.com/hashicorp/consul/agent/consul/prepared_query"
	"github.com/hashicorp/consul/agent/structs"
	"github.com/hashicorp/go-memdb"
)

// validUUID is used to check if a given string looks like a UUID
var validUUID = regexp.MustCompile(`(?i)^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$`)

// isUUID returns true if the given string is a valid UUID.
func isUUID(str string) bool {
	const uuidLen = 36
	if len(str) != uuidLen {
		return false
	}

	return validUUID.MatchString(str)
}

// queryWrapper is an internal structure that is used to store a query alongside
// its compiled template, which can be nil.
type queryWrapper struct {
	// We embed the PreparedQuery structure so that the UUID field indexer
	// can see the ID directly.
	*structs.PreparedQuery

	// ct is the compiled template, or nil if the query isn't a template. The
	// state store manages this and keeps it up to date every time the query
	// changes.
	ct *prepared_query.CompiledTemplate
}

// toPreparedQuery unwraps the internal form of a prepared query and returns
// the regular struct.
func toPreparedQuery(wrapped interface{}) *structs.PreparedQuery {
	if wrapped == nil {
		return nil
	}
	return wrapped.(*queryWrapper).PreparedQuery
}

// PreparedQueries is used to pull all the prepared queries from the snapshot.
func (s *Snapshot) PreparedQueries() (structs.PreparedQueries, error) {
	queries, err := s.tx.Get("prepared-queries", "id")
	if err != nil {
		return nil, err
	}

	var ret structs.PreparedQueries
	for wrapped := queries.Next(); wrapped != nil; wrapped = queries.Next() {
		ret = append(ret, toPreparedQuery(wrapped))
	}
	return ret, nil
}

// PreparedQuery is used when restoring from a snapshot. For general inserts,
// use PreparedQuerySet.
func (s *Restore) PreparedQuery(query *structs.PreparedQuery) error {
	// If this is a template, compile it, otherwise leave the compiled
	// template field nil.
	var ct *prepared_query.CompiledTemplate
	if prepared_query.IsTemplate(query) {
		var err error
		ct, err = prepared_query.Compile(query)
		if err != nil {
			return fmt.Errorf("failed compiling template: %s", err)
		}
	}

	// Insert the wrapped query.
	if err := s.tx.Insert("prepared-queries", &queryWrapper{query, ct}); err != nil {
		return fmt.Errorf("failed restoring prepared query: %s", err)
	}
	if err := indexUpdateMaxTxn(s.tx, query.ModifyIndex, "prepared-queries"); err != nil {
		return fmt.Errorf("failed updating index: %s", err)
	}

	return nil
}

// PreparedQuerySet is used to create or update a prepared query.
func (s *Store) PreparedQuerySet(idx uint64, query *structs.PreparedQuery) error {
	tx := s.db.Txn(true)
	defer tx.Abort()

	if err := s.preparedQuerySetTxn(tx, idx, query); err != nil {
		return err
	}

	tx.Commit()
	return nil
}

// preparedQuerySetTxn is the inner method used to insert a prepared query with
// the proper indexes into the state store.
func (s *Store) preparedQuerySetTxn(tx *memdb.Txn, idx uint64, query *structs.PreparedQuery) error {
	// Check that the ID is set.
	if query.ID == "" {
		return ErrMissingQueryID
	}

	// Check for an existing query.
	wrapped, err := tx.First("prepared-queries", "id", query.ID)
	if err != nil {
		return fmt.Errorf("failed prepared query lookup: %s", err)
	}
	existing := toPreparedQuery(wrapped)

	// Set the indexes.
	if existing != nil {
		query.CreateIndex = existing.CreateIndex
		query.ModifyIndex = idx
	} else {
		query.CreateIndex = idx
		query.ModifyIndex = idx
	}

	// Verify that the query name doesn't already exist, or that we are
	// updating the same instance that has this name. If this is a template
	// and the name is empty then we make sure there's not an empty template
	// already registered.
	if query.Name != "" {
		wrapped, err := tx.First("prepared-queries", "name", query.Name)
		if err != nil {
			return fmt.Errorf("failed prepared query lookup: %s", err)
		}
		other := toPreparedQuery(wrapped)
		if other != nil && (existing == nil || existing.ID != other.ID) {
			return fmt.Errorf("name '%s' aliases an existing query name", query.Name)
		}
	} else if prepared_query.IsTemplate(query) {
		wrapped, err := tx.First("prepared-queries", "template", query.Name)
		if err != nil {
			return fmt.Errorf("failed prepared query lookup: %s", err)
		}
		other := toPreparedQuery(wrapped)
		if other != nil && (existing == nil || existing.ID != other.ID) {
			return fmt.Errorf("a query template with an empty name already exists")
		}
	}

	// Verify that the name doesn't alias any existing ID. We allow queries
	// to be looked up by ID *or* name so we don't want anyone to try to
	// register a query with a name equal to some other query's ID in an
	// attempt to hijack it. We also look up by ID *then* name in order to
	// prevent this, but it seems prudent to prevent these types of rogue
	// queries from ever making it into the state store. Note that we have
	// to see if the name looks like a UUID before checking since the UUID
	// index will complain if we look up something that's not formatted
	// like one.
	if isUUID(query.Name) {
		wrapped, err := tx.First("prepared-queries", "id", query.Name)
		if err != nil {
			return fmt.Errorf("failed prepared query lookup: %s", err)
		}
		if wrapped != nil {
			return fmt.Errorf("name '%s' aliases an existing query ID", query.Name)
		}
	}

	// Verify that the session exists.
	if query.Session != "" {
		sess, err := tx.First("sessions", "id", query.Session)
		if err != nil {
			return fmt.Errorf("failed session lookup: %s", err)
		}
		if sess == nil {
			return fmt.Errorf("invalid session %#v", query.Session)
		}
	}

	// We do not verify the service here, nor the token, if any. These are
	// checked at execute time and not doing integrity checking on them
	// helps avoid bootstrapping chicken and egg problems.

	// If this is a template, compile it, otherwise leave the compiled
	// template field nil.
	var ct *prepared_query.CompiledTemplate
	if prepared_query.IsTemplate(query) {
		var err error
		ct, err = prepared_query.Compile(query)
		if err != nil {
			return fmt.Errorf("failed compiling template: %s", err)
		}
	}

	// Insert the wrapped query.
	if err := tx.Insert("prepared-queries", &queryWrapper{query, ct}); err != nil {
		return fmt.Errorf("failed inserting prepared query: %s", err)
	}
	if err := tx.Insert("index", &IndexEntry{"prepared-queries", idx}); err != nil {
		return fmt.Errorf("failed updating index: %s", err)
	}

	return nil
}

// PreparedQueryDelete deletes the given query by ID.
func (s *Store) PreparedQueryDelete(idx uint64, queryID string) error {
	tx := s.db.Txn(true)
	defer tx.Abort()

	if err := s.preparedQueryDeleteTxn(tx, idx, queryID); err != nil {
		return fmt.Errorf("failed prepared query delete: %s", err)
	}

	tx.Commit()
	return nil
}

// preparedQueryDeleteTxn is the inner method used to delete a prepared query
// with the proper indexes into the state store.
func (s *Store) preparedQueryDeleteTxn(tx *memdb.Txn, idx uint64, queryID string) error {
	// Pull the query.
	wrapped, err := tx.First("prepared-queries", "id", queryID)
	if err != nil {
		return fmt.Errorf("failed prepared query lookup: %s", err)
	}
	if wrapped == nil {
		return nil
	}

	// Delete the query and update the index.
	if err := tx.Delete("prepared-queries", wrapped); err != nil {
		return fmt.Errorf("failed prepared query delete: %s", err)
	}
	if err := tx.Insert("index", &IndexEntry{"prepared-queries", idx}); err != nil {
		return fmt.Errorf("failed updating index: %s", err)
	}

	return nil
}

// PreparedQueryGet returns the given prepared query by ID.
func (s *Store) PreparedQueryGet(ws memdb.WatchSet, queryID string) (uint64, *structs.PreparedQuery, error) {
	tx := s.db.Txn(false)
	defer tx.Abort()

	// Get the table index.
	idx := maxIndexTxn(tx, "prepared-queries")

	// Look up the query by its ID.
	watchCh, wrapped, err := tx.FirstWatch("prepared-queries", "id", queryID)
	if err != nil {
		return 0, nil, fmt.Errorf("failed prepared query lookup: %s", err)
	}
	ws.Add(watchCh)
	return idx, toPreparedQuery(wrapped), nil
}

// PreparedQueryResolve returns the given prepared query by looking up an ID or
// Name. If the query was looked up by name and it's a template, then the
// template will be rendered before it is returned.
func (s *Store) PreparedQueryResolve(queryIDOrName string, source structs.QuerySource) (uint64, *structs.PreparedQuery, error) {
	tx := s.db.Txn(false)
	defer tx.Abort()

	// Get the table index.
	idx := maxIndexTxn(tx, "prepared-queries")

	// Explicitly ban an empty query. This will never match an ID and the
	// schema is set up so it will never match a query with an empty name,
	// but we check it here to be explicit about it (we'd never want to
	// return the results from the first query w/o a name).
	if queryIDOrName == "" {
		return 0, nil, ErrMissingQueryID
	}

	// Try first by ID if it looks like they gave us an ID. We check the
	// format before trying this because the UUID index will complain if
	// we look up something that's not formatted like one.
	if isUUID(queryIDOrName) {
		wrapped, err := tx.First("prepared-queries", "id", queryIDOrName)
		if err != nil {
			return 0, nil, fmt.Errorf("failed prepared query lookup: %s", err)
		}
		if wrapped != nil {
			query := toPreparedQuery(wrapped)
			if prepared_query.IsTemplate(query) {
				return idx, nil, fmt.Errorf("prepared query templates can only be resolved up by name, not by ID")
			}
			return idx, query, nil
		}
	}

	// prep will check to see if the query is a template and render it
	// first, otherwise it will just return a regular query.
	prep := func(wrapped interface{}) (uint64, *structs.PreparedQuery, error) {
		wrapper := wrapped.(*queryWrapper)
		if prepared_query.IsTemplate(wrapper.PreparedQuery) {
			render, err := wrapper.ct.Render(queryIDOrName, source)
			if err != nil {
				return idx, nil, err
			}
			return idx, render, nil
		}
		return idx, wrapper.PreparedQuery, nil
	}

	// Next, look for an exact name match. This is the common case for static
	// prepared queries, and could also apply to templates.
	{
		wrapped, err := tx.First("prepared-queries", "name", queryIDOrName)
		if err != nil {
			return 0, nil, fmt.Errorf("failed prepared query lookup: %s", err)
		}
		if wrapped != nil {
			return prep(wrapped)
		}
	}

	// Next, look for the longest prefix match among the prepared query
	// templates.
	{
		wrapped, err := tx.LongestPrefix("prepared-queries", "template_prefix", queryIDOrName)
		if err != nil {
			return 0, nil, fmt.Errorf("failed prepared query lookup: %s", err)
		}
		if wrapped != nil {
			return prep(wrapped)
		}
	}

	return idx, nil, nil
}

// PreparedQueryList returns all the prepared queries.
func (s *Store) PreparedQueryList(ws memdb.WatchSet) (uint64, structs.PreparedQueries, error) {
	tx := s.db.Txn(false)
	defer tx.Abort()

	// Get the table index.
	idx := maxIndexTxn(tx, "prepared-queries")

	// Query all of the prepared queries in the state store.
	queries, err := tx.Get("prepared-queries", "id")
	if err != nil {
		return 0, nil, fmt.Errorf("failed prepared query lookup: %s", err)
	}
	ws.Add(queries.WatchCh())

	// Go over all of the queries and build the response.
	var result structs.PreparedQueries
	for wrapped := queries.Next(); wrapped != nil; wrapped = queries.Next() {
		result = append(result, toPreparedQuery(wrapped))
	}
	return idx, result, nil
}


text:
package com.quasar_academy.twowayview;

import java.util.ArrayList;

/**
 * Created by Prashant on 12/18/2014.
 */

public class Post {
    private int id;
    private String type;
    String slug;
    String url;
    String status;
    String title;
    String title_plain;
    String content;
    String excerpt;
    String date;
    String modified;
    String previous_url;
    String next_url;
    Author author;
    ArrayList<Categories> categories;
    ArrayList<Tags> tags;
    String thumbnail;

    public String getThumbnail() {
        return thumbnail;
    }

    public void setThumbnail(String thumbnail) {
        this.thumbnail = thumbnail;
    }

    public Post() {
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getSlug() {
        return slug;
    }

    public void setSlug(String slug) {
        this.slug = slug;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getTitle_plain() {
        return title_plain;
    }

    public void setTitle_plain(String title_plain) {
        this.title_plain = title_plain;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public String getExcerpt() {
        return excerpt;
    }

    public void setExcerpt(String excerpt) {
        this.excerpt = excerpt;
    }

    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }

    public String getModified() {
        return modified;
    }

    public void setModified(String modified) {
        this.modified = modified;
    }

    public String getPrevious_url() {
        return previous_url;
    }

    public void setPrevious_url(String previous_url) {
        this.previous_url = previous_url;
    }

    public String getNext_url() {
        return next_url;
    }

    public void setNext_url(String next_url) {
        this.next_url = next_url;
    }

    public Author getAuthor() {
        return author;
    }

    public void setAuthor(Author author) {
        this.author = author;
    }

    public ArrayList<Categories> getCategories() {
        return categories;
    }

    public void setCategories(ArrayList<Categories> categories) {
        this.categories = categories;
    }

    public ArrayList<Tags> getTags() {
        return tags;
    }

    public void setTags(ArrayList<Tags> tags) {
        this.tags = tags;
    }
}


text:
SELECT
	REPLACE(icd9.concept_code, '.', '') AS source_code,
	icd9.concept_name AS source_name,
	icd9.concept_id AS source_concept_id,
	standard.concept_code AS target_code,
	standard.concept_name AS target_name,
	standard.concept_id AS target_concept_id,
	standard.domain_id
FROM concept icd9
INNER JOIN concept_relationship
	ON icd9.concept_id = concept_id_1
INNER JOIN concept standard
	ON standard.concept_id = concept_id_2
WHERE icd9.vocabulary_id = 'ICD9CM'
	AND standard.standard_concept = 'S'
	AND relationship_id = 'Maps to'
	AND (concept_relationship.invalid_reason IS NULL OR concept_relationship.invalid_reason = '')


text:
import os
import numpy as np
import cv2
import yaml
import click
from keras.models import load_model

from fujitsu.data_management.data_loader import load_dataset
from fujitsu.models.standard_classifier import ConvnetClassifier
from fujitsu.utils.log import setup_logger
from fujitsu.utils.visualize import create_tiles
from fujitsu.networks import get_network
from scipy.misc import imresize

log = setup_logger("demo")
grid_shape = (6, 6)

@click.command()
@click.option('--modeldir', prompt='Enter path to the directory of the model to demo',
              help='path to the directory of the model you want to demo with')
@click.option('--weights', prompt='Enter weights filename',
              help='Name of the weights file to load for the model.')
def run_demo(modeldir, weights):
    # load the model config
    with open(os.path.join(modeldir, 'config.yaml'), mode='rb') as f:
        config = yaml.load(f)

    # load a pretrained model
    model = load_model(os.path.join(modeldir, weights))
    model.save_weights('model_weights.h5')

    classifier = ConvnetClassifier(name=config['model']['name'],
                                   network_fn=get_network(config['training']['network']),
                                   n_classes=config['model']['n_classes'],
                                   n_channels=config['data']['n_channels'],
                                   img_width=config['data']['img_width'],
                                   img_height=config['data']['img_height'],
                                   dropout=config['training']['dropout'],
                                   learning_rate=config['training']['learning_rate'])
    classifier.model.load_weights('model_weights.h5')
    data, data_mean = load_dataset(os.path.join(os.path.dirname(__file__), "data"))
    np.save("data_mean.npy", data_mean)

    # test on the test set
    result = model.evaluate(data['X_test'], data['y_test'])
    log.info("Model performance: {}".format(result))

    # work with the video
    cap = cv2.VideoCapture(0)
    i = 0
    counter = 0
    is_coin = False
    while True:
        if cap.grab():
            flag, frame = cap.retrieve()
            if not flag:
                continue
            else:
                counter += 1
                # crop the frame to something smaller
                half_size = 100
                center_y = frame.shape[0] // 2
                center_x = frame.shape[1] // 2
                frame = frame[center_y - half_size:center_y + half_size,
                              center_x - half_size:center_x + half_size]

                # predict for this frame
                input_frame = np.expand_dims(frame.transpose((2, 0, 1)), axis=0)
                input_frame = np.asarray(input_frame, dtype="float32")

                # preprocessing
                input_frame /= 255
                input_frame -= data_mean

                score = model.predict(input_frame)[0]
                log.debug(score[1])
                is_coin = score[1] > 0.5

                # visualize the prediction
                if is_coin:
                    cv2.putText(frame, "coin", org=(20, 20),
                                fontFace=cv2.FONT_HERSHEY_PLAIN,
                                fontScale=1, color=(125, 255, 125),
                                thickness=2)
                else:
                    cv2.putText(frame, "no coin", org=(20, 20),
                                fontFace=cv2.FONT_HERSHEY_PLAIN,
                                fontScale=1, color=(255, 125, 125),
                                thickness=2)

                cv2.imshow('video', frame)

                # visualize a filter
                for i in [3, 6]:
                    activations = classifier.activations(i, input_frame)[0][0]
                    img_shape = activations.shape[1:]
                    activations_image = create_tiles(activations, img_shape=img_shape,
                                                     grid_shape=grid_shape,
                                                     tile_spacing=(10, 10))
                    activations_image = imresize(activations_image, size=(800, 800))
                    cv2.imshow('filters{}'.format(i), activations_image)

                i += 1
                counter = 0

        if cv2.waitKey(10) == 27:
            break

if __name__ == "__main__":
    # get the command line parameters
    run_demo()


text:
namespace {

scoped_refptr<const extensions::Extension> CreateExtension(
    const std::string& name,
    bool has_browser_action) {
  extensions::DictionaryBuilder manifest;
  manifest.Set("name", name).
           Set("description", "an extension").
           Set("manifest_version", 2).
           Set("version", "1.0");
  if (has_browser_action)
    manifest.Set("browser_action", extensions::DictionaryBuilder().Pass());
  return extensions::ExtensionBuilder().
      SetManifest(manifest.Pass()).
      SetID(crx_file::id_util::GenerateId(name)).
      Build();
}

}  // namespace

// BrowserActionsBarBrowserTest:

BrowserActionsBarBrowserTest::BrowserActionsBarBrowserTest()
    : toolbar_model_(nullptr) {
}

BrowserActionsBarBrowserTest::~BrowserActionsBarBrowserTest() {
}

void BrowserActionsBarBrowserTest::SetUpCommandLine(
    base::CommandLine* command_line) {
  ExtensionBrowserTest::SetUpCommandLine(command_line);
  ToolbarActionsBar::disable_animations_for_testing_ = true;
  // These tests are deliberately testing behavior without the redesign.
  // Forcefully disable it.
  override_redesign_.reset(new extensions::FeatureSwitch::ScopedOverride(
      extensions::FeatureSwitch::extension_action_redesign(), false));
}

void BrowserActionsBarBrowserTest::SetUpOnMainThread() {
  ExtensionBrowserTest::SetUpOnMainThread();
  browser_actions_bar_.reset(new BrowserActionTestUtil(browser()));
  toolbar_model_ = ToolbarActionsModel::Get(profile());
}

void BrowserActionsBarBrowserTest::TearDownOnMainThread() {
  ToolbarActionsBar::disable_animations_for_testing_ = false;
  ExtensionBrowserTest::TearDownOnMainThread();
}

void BrowserActionsBarBrowserTest::LoadExtensions() {
  // Create three extensions with browser actions.
  extension_a_ = CreateExtension("alpha", true);
  extension_b_ = CreateExtension("beta", true);
  extension_c_ = CreateExtension("gamma", true);

  const extensions::Extension* extensions[] =
      { extension_a(), extension_b(), extension_c() };
  extensions::ExtensionRegistry* registry =
      extensions::ExtensionRegistry::Get(profile());
  // Add each, and verify that it is both correctly added to the extension
  // registry and to the browser actions container.
  for (size_t i = 0; i < arraysize(extensions); ++i) {
    extension_service()->AddExtension(extensions[i]);
    EXPECT_TRUE(registry->enabled_extensions().GetByID(extensions[i]->id())) <<
        extensions[i]->name();
    EXPECT_EQ(static_cast<int>(i + 1),
              browser_actions_bar_->NumberOfBrowserActions());
    EXPECT_TRUE(browser_actions_bar_->HasIcon(i));
    EXPECT_EQ(static_cast<int>(i + 1),
              browser_actions_bar()->VisibleBrowserActions());
  }
}

// BrowserActionsBarRedesignBrowserTest:

BrowserActionsBarRedesignBrowserTest::BrowserActionsBarRedesignBrowserTest() {
}

BrowserActionsBarRedesignBrowserTest::~BrowserActionsBarRedesignBrowserTest() {
}

void BrowserActionsBarRedesignBrowserTest::SetUpCommandLine(
    base::CommandLine* command_line) {
  BrowserActionsBarBrowserTest::SetUpCommandLine(command_line);
  // Override to force the redesign. Completely clear the previous override
  // first, since doing so resets the value of the switch.
  override_redesign_.reset();
  override_redesign_.reset(new extensions::FeatureSwitch::ScopedOverride(
      extensions::FeatureSwitch::extension_action_redesign(), true));
}

// Test the basic functionality.
IN_PROC_BROWSER_TEST_F(BrowserActionsBarBrowserTest, Basic) {
  // Load an extension with no browser action.
  extension_service()->AddExtension(CreateExtension("alpha", false).get());
  // This extension should not be in the model (has no browser action).
  EXPECT_EQ(0, browser_actions_bar()->NumberOfBrowserActions());

  // Load an extension with a browser action.
  extension_service()->AddExtension(CreateExtension("beta", true).get());
  EXPECT_EQ(1, browser_actions_bar()->NumberOfBrowserActions());
  EXPECT_TRUE(browser_actions_bar()->HasIcon(0));

  // Unload the extension.
  std::string id = browser_actions_bar()->GetExtensionId(0);
  UnloadExtension(id);
  EXPECT_EQ(0, browser_actions_bar()->NumberOfBrowserActions());
}

// Test moving various browser actions. This is not to check the logic of the
// move (that's in the toolbar model tests), but just to check our ui.
IN_PROC_BROWSER_TEST_F(BrowserActionsBarBrowserTest, MoveBrowserActions) {
  LoadExtensions();

  EXPECT_EQ(3, browser_actions_bar()->VisibleBrowserActions());
  EXPECT_EQ(3, browser_actions_bar()->NumberOfBrowserActions());

  // Order is now A B C.
  EXPECT_EQ(extension_a()->id(), browser_actions_bar()->GetExtensionId(0));
  EXPECT_EQ(extension_b()->id(), browser_actions_bar()->GetExtensionId(1));
  EXPECT_EQ(extension_c()->id(), browser_actions_bar()->GetExtensionId(2));

  // Move C to first position. Order is C A B.
  toolbar_model()->MoveActionIcon(extension_c()->id(), 0);
  EXPECT_EQ(extension_c()->id(), browser_actions_bar()->GetExtensionId(0));
  EXPECT_EQ(extension_a()->id(), browser_actions_bar()->GetExtensionId(1));
  EXPECT_EQ(extension_b()->id(), browser_actions_bar()->GetExtensionId(2));

  // Move B to third position. Order is still C A B.
  toolbar_model()->MoveActionIcon(extension_b()->id(), 2);
  EXPECT_EQ(extension_c()->id(), browser_actions_bar()->GetExtensionId(0));
  EXPECT_EQ(extension_a()->id(), browser_actions_bar()->GetExtensionId(1));
  EXPECT_EQ(extension_b()->id(), browser_actions_bar()->GetExtensionId(2));

  // Move B to middle position. Order is C B A.
  toolbar_model()->MoveActionIcon(extension_b()->id(), 1);
  EXPECT_EQ(extension_c()->id(), browser_actions_bar()->GetExtensionId(0));
  EXPECT_EQ(extension_b()->id(), browser_actions_bar()->GetExtensionId(1));
  EXPECT_EQ(extension_a()->id(), browser_actions_bar()->GetExtensionId(2));
}

// Test that explicitly hiding an extension action results in it disappearing
// from the browser actions bar.
IN_PROC_BROWSER_TEST_F(BrowserActionsBarBrowserTest, ForceHide) {
  LoadExtensions();

  EXPECT_EQ(3, browser_actions_bar()->VisibleBrowserActions());
  EXPECT_EQ(extension_a()->id(), browser_actions_bar()->GetExtensionId(0));
  // Force hide one of the extensions' browser action.
  extensions::ExtensionActionAPI::Get(browser()->profile())->
      SetBrowserActionVisibility(extension_a()->id(), false);
  // The browser action for Extension A should be removed.
  EXPECT_EQ(2, browser_actions_bar()->VisibleBrowserActions());
  EXPECT_EQ(extension_b()->id(), browser_actions_bar()->GetExtensionId(0));
}

IN_PROC_BROWSER_TEST_F(BrowserActionsBarBrowserTest, Visibility) {
  LoadExtensions();

  // Change container to show only one action, rest in overflow: A, [B, C].
  toolbar_model()->SetVisibleIconCount(1);
  EXPECT_EQ(1, browser_actions_bar()->VisibleBrowserActions());

  // Disable extension A (should disappear). State becomes: B [C].
  DisableExtension(extension_a()->id());
  EXPECT_EQ(2, browser_actions_bar()->NumberOfBrowserActions());
  EXPECT_EQ(1, browser_actions_bar()->VisibleBrowserActions());
  EXPECT_EQ(extension_b()->id(), browser_actions_bar()->GetExtensionId(0));

  // Enable A again. A should get its spot in the same location and the bar
  // should not grow (chevron is showing). For details: http://crbug.com/35349.
  // State becomes: A, [B, C].
  EnableExtension(extension_a()->id());
  EXPECT_EQ(3, browser_actions_bar()->NumberOfBrowserActions());
  EXPECT_EQ(1, browser_actions_bar()->VisibleBrowserActions());
  EXPECT_EQ(extension_a()->id(), browser_actions_bar()->GetExtensionId(0));

  // Disable C (in overflow). State becomes: A, [B].
  DisableExtension(extension_c()->id());
  EXPECT_EQ(2, browser_actions_bar()->NumberOfBrowserActions());
  EXPECT_EQ(1, browser_actions_bar()->VisibleBrowserActions());
  EXPECT_EQ(extension_a()->id(), browser_actions_bar()->GetExtensionId(0));

  // Enable C again. State becomes: A, [B, C].
  EnableExtension(extension_c()->id());
  EXPECT_EQ(3, browser_actions_bar()->NumberOfBrowserActions());
  EXPECT_EQ(1, browser_actions_bar()->VisibleBrowserActions());
  EXPECT_EQ(extension_a()->id(), browser_actions_bar()->GetExtensionId(0));

  // Now we have 3 extensions. Make sure they are all visible. State: A, B, C.
  toolbar_model()->SetVisibleIconCount(3);
  EXPECT_EQ(3, browser_actions_bar()->VisibleBrowserActions());

  // Disable extension A (should disappear). State becomes: B, C.
  DisableExtension(extension_a()->id());
  EXPECT_EQ(2, browser_actions_bar()->NumberOfBrowserActions());
  EXPECT_EQ(2, browser_actions_bar()->VisibleBrowserActions());
  EXPECT_EQ(extension_b()->id(), browser_actions_bar()->GetExtensionId(0));

  // Disable extension B (should disappear). State becomes: C.
  DisableExtension(extension_b()->id());
  EXPECT_EQ(1, browser_actions_bar()->NumberOfBrowserActions());
  EXPECT_EQ(1, browser_actions_bar()->VisibleBrowserActions());
  EXPECT_EQ(extension_c()->id(), browser_actions_bar()->GetExtensionId(0));

  // Enable B. State becomes: B, C.
  EnableExtension(extension_b()->id());
  EXPECT_EQ(2, browser_actions_bar()->NumberOfBrowserActions());
  EXPECT_EQ(2, browser_actions_bar()->VisibleBrowserActions());
  EXPECT_EQ(extension_b()->id(), browser_actions_bar()->GetExtensionId(0));

  // Enable A. State becomes: A, B, C.
  EnableExtension(extension_a()->id());
  EXPECT_EQ(3, browser_actions_bar()->NumberOfBrowserActions());
  EXPECT_EQ(3, browser_actions_bar()->VisibleBrowserActions());
  EXPECT_EQ(extension_a()->id(), browser_actions_bar()->GetExtensionId(0));

  // Shrink the browser actions bar to zero visible icons.
  // No icons should be visible, but we *should* show the chevron and have a
  // non-empty size.
  toolbar_model()->SetVisibleIconCount(0);
  EXPECT_EQ(0, browser_actions_bar()->VisibleBrowserActions());
  EXPECT_TRUE(browser_actions_bar()->IsChevronShowing());

  // Reset visibility count to 2. State should be A, B, [C], and the chevron
  // should be visible.
  toolbar_model()->SetVisibleIconCount(2);
  EXPECT_EQ(2, browser_actions_bar()->VisibleBrowserActions());
  EXPECT_EQ(extension_a()->id(), browser_actions_bar()->GetExtensionId(0));
  EXPECT_EQ(extension_b()->id(), browser_actions_bar()->GetExtensionId(1));
  EXPECT_TRUE(browser_actions_bar()->IsChevronShowing());

  // Disable C (the overflowed extension). State should now be A, B, and the
  // chevron should be hidden.
  DisableExtension(extension_c()->id());
  EXPECT_EQ(2, browser_actions_bar()->VisibleBrowserActions());
  EXPECT_EQ(extension_a()->id(), browser_actions_bar()->GetExtensionId(0));
  EXPECT_EQ(extension_b()->id(), browser_actions_bar()->GetExtensionId(1));
  EXPECT_FALSE(browser_actions_bar()->IsChevronShowing());

  // Re-enable C. We should still only have 2 visible icons, and the chevron
  // should be visible.
  EnableExtension(extension_c()->id());
  EXPECT_EQ(2, browser_actions_bar()->VisibleBrowserActions());
  EXPECT_EQ(extension_a()->id(), browser_actions_bar()->GetExtensionId(0));
  EXPECT_EQ(extension_b()->id(), browser_actions_bar()->GetExtensionId(1));
  EXPECT_TRUE(browser_actions_bar()->IsChevronShowing());
}

// Test that, with the toolbar action redesign, actions that want to run have
// the proper appearance.
IN_PROC_BROWSER_TEST_F(BrowserActionsBarRedesignBrowserTest,
                       TestUiForActionsWantToRun) {
  LoadExtensions();
  EXPECT_EQ(3, browser_actions_bar()->VisibleBrowserActions());

  // Load an extension with a page action.
  scoped_refptr<const extensions::Extension> page_action_extension =
      extensions::extension_action_test_util::CreateActionExtension(
          "page action", extensions::extension_action_test_util::PAGE_ACTION);
  extension_service()->AddExtension(page_action_extension.get());

  // Verify that the extension was added at the last index.
  EXPECT_EQ(4, browser_actions_bar()->VisibleBrowserActions());
  EXPECT_EQ(page_action_extension->id(),
            browser_actions_bar()->GetExtensionId(3));
  EXPECT_FALSE(browser_actions_bar()->ActionButtonWantsToRun(3));

  // Make the extension want to run on the current page.
  ExtensionAction* action = extensions::ExtensionActionManager::Get(profile())->
      GetExtensionAction(*page_action_extension);
  ASSERT_TRUE(action);
  content::WebContents* web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();
  int tab_id = SessionTabHelper::IdForTab(web_contents);
  action->SetIsVisible(tab_id, true);
  extensions::ExtensionActionAPI* extension_action_api =
      extensions::ExtensionActionAPI::Get(profile());
  extension_action_api->NotifyChange(action, web_contents, profile());
  // Verify that the extension's button has the proper UI.
  EXPECT_TRUE(browser_actions_bar()->ActionButtonWantsToRun(3));

  // Make the extension not want to run, and check that the special UI goes
  // away.
  action->SetIsVisible(tab_id, false);
  extension_action_api->NotifyChange(action, web_contents, profile());
  EXPECT_FALSE(browser_actions_bar()->ActionButtonWantsToRun(3));

  // Reduce the visible icon count so that the extension is hidden.
  toolbar_model()->SetVisibleIconCount(3);

  // The extension should want to run whether or not it's hidden.
  action->SetIsVisible(tab_id, true);
  extension_action_api->NotifyChange(action, web_contents, profile());
  EXPECT_TRUE(browser_actions_bar()->ActionButtonWantsToRun(3));
}

IN_PROC_BROWSER_TEST_F(BrowserActionsBarBrowserTest,
                       BrowserActionPopupTest) {
  // Load up two extensions that have browser action popups.
  base::FilePath data_dir =
      test_data_dir_.AppendASCII("api_test").AppendASCII("browser_action");
  const extensions::Extension* first_extension =
      LoadExtension(data_dir.AppendASCII("open_popup"));
  ASSERT_TRUE(first_extension);
  const extensions::Extension* second_extension =
      LoadExtension(data_dir.AppendASCII("remove_popup"));
  ASSERT_TRUE(second_extension);

  // Verify state: two actions, in the order of [first, second].
  EXPECT_EQ(2, browser_actions_bar()->VisibleBrowserActions());
  EXPECT_EQ(first_extension->id(), browser_actions_bar()->GetExtensionId(0));
  EXPECT_EQ(second_extension->id(), browser_actions_bar()->GetExtensionId(1));

  // Do a little piping to get at the underlying ExtensionActionViewControllers.
  ToolbarActionsBar* toolbar_actions_bar =
      browser_actions_bar()->GetToolbarActionsBar();
  const std::vector<ToolbarActionViewController*>& toolbar_actions =
      toolbar_actions_bar->GetActions();
  ASSERT_EQ(2u, toolbar_actions.size());
  EXPECT_EQ(first_extension->id(), toolbar_actions[0]->GetId());
  EXPECT_EQ(second_extension->id(), toolbar_actions[1]->GetId());
  ExtensionActionViewController* first_controller =
      static_cast<ExtensionActionViewController*>(toolbar_actions[0]);
  ExtensionActionViewController* second_controller =
      static_cast<ExtensionActionViewController*>(toolbar_actions[1]);

  // Neither should yet be showing a popup.
  EXPECT_FALSE(browser_actions_bar()->HasPopup());
  EXPECT_FALSE(first_controller->is_showing_popup());
  EXPECT_FALSE(second_controller->is_showing_popup());

  // Click on the first extension's browser action. This should open a popup.
  browser_actions_bar()->Press(0);
  EXPECT_TRUE(browser_actions_bar()->HasPopup());
  EXPECT_TRUE(first_controller->is_showing_popup());
  EXPECT_FALSE(second_controller->is_showing_popup());

  {
    content::WindowedNotificationObserver observer(
        extensions::NOTIFICATION_EXTENSION_HOST_DESTROYED,
        content::NotificationService::AllSources());
    // Clicking on the second extension's browser action should open the
    // second's popup. Since we only allow one extension popup at a time, this
    // should also close the first popup.
    browser_actions_bar()->Press(1);
    // Closing an extension popup isn't always synchronous; wait for a
    // notification.
    observer.Wait();
    EXPECT_TRUE(browser_actions_bar()->HasPopup());
    EXPECT_FALSE(first_controller->is_showing_popup());
    EXPECT_TRUE(second_controller->is_showing_popup());
  }

  {
    // Clicking on the second extension's browser action a second time should
    // result in closing the popup.
    content::WindowedNotificationObserver observer(
        extensions::NOTIFICATION_EXTENSION_HOST_DESTROYED,
        content::NotificationService::AllSources());
    browser_actions_bar()->Press(1);
    observer.Wait();
    EXPECT_FALSE(browser_actions_bar()->HasPopup());
    EXPECT_FALSE(first_controller->is_showing_popup());
    EXPECT_FALSE(second_controller->is_showing_popup());
  }
}

IN_PROC_BROWSER_TEST_F(BrowserActionsBarRedesignBrowserTest,
                       OverflowedBrowserActionPopupTest) {
  scoped_ptr<BrowserActionTestUtil> overflow_bar =
      browser_actions_bar()->CreateOverflowBar();

  // Load up two extensions that have browser action popups.
  base::FilePath data_dir =
      test_data_dir_.AppendASCII("api_test").AppendASCII("browser_action");
  const extensions::Extension* first_extension =
      LoadExtension(data_dir.AppendASCII("open_popup"));
  ASSERT_TRUE(first_extension);
  const extensions::Extension* second_extension =
      LoadExtension(data_dir.AppendASCII("remove_popup"));
  ASSERT_TRUE(second_extension);

  // Verify state: two actions, in the order of [first, second].
  EXPECT_EQ(2, browser_actions_bar()->VisibleBrowserActions());
  EXPECT_EQ(first_extension->id(), browser_actions_bar()->GetExtensionId(0));
  EXPECT_EQ(second_extension->id(), browser_actions_bar()->GetExtensionId(1));

  // Do a little piping to get at the underlying ExtensionActionViewControllers.
  ToolbarActionsBar* main_tab = browser_actions_bar()->GetToolbarActionsBar();
  std::vector<ToolbarActionViewController*> toolbar_actions =
      main_tab->GetActions();
  ASSERT_EQ(2u, toolbar_actions.size());
  EXPECT_EQ(first_extension->id(), toolbar_actions[0]->GetId());
  EXPECT_EQ(second_extension->id(), toolbar_actions[1]->GetId());
  ExtensionActionViewController* first_controller_main =
      static_cast<ExtensionActionViewController*>(toolbar_actions[0]);
  ExtensionActionViewController* second_controller_main =
      static_cast<ExtensionActionViewController*>(toolbar_actions[1]);

  ToolbarActionsBar* overflow_tab = overflow_bar->GetToolbarActionsBar();
  toolbar_actions = overflow_tab->GetActions();
  ExtensionActionViewController* second_controller_overflow =
      static_cast<ExtensionActionViewController*>(toolbar_actions[1]);

  toolbar_model()->SetVisibleIconCount(0);

  EXPECT_EQ(0, browser_actions_bar()->VisibleBrowserActions());
  EXPECT_EQ(2, overflow_bar->VisibleBrowserActions());

  // Neither should yet be showing a popup.
  EXPECT_FALSE(browser_actions_bar()->HasPopup());
  EXPECT_FALSE(second_controller_main->is_showing_popup());
  EXPECT_FALSE(second_controller_overflow->is_showing_popup());

  // Click on the first extension's browser action. This should open a popup.
  overflow_bar->Press(1);
  base::RunLoop().RunUntilIdle();
  EXPECT_TRUE(browser_actions_bar()->HasPopup());
  EXPECT_FALSE(overflow_bar->HasPopup());
  EXPECT_TRUE(second_controller_main->is_showing_popup());
  EXPECT_FALSE(second_controller_overflow->is_showing_popup());

  EXPECT_EQ(1, browser_actions_bar()->VisibleBrowserActions());
  EXPECT_EQ(1u, main_tab->GetIconCount());
  EXPECT_EQ(second_controller_main->GetId(),
            browser_actions_bar()->GetExtensionId(0));
  EXPECT_EQ(2, overflow_bar->VisibleBrowserActions());
  EXPECT_EQ(2u, overflow_tab->GetIconCount());
  EXPECT_EQ(first_controller_main->GetId(),
            overflow_bar->GetExtensionId(0));

  {
    content::WindowedNotificationObserver observer(
        extensions::NOTIFICATION_EXTENSION_HOST_DESTROYED,
        content::NotificationService::AllSources());
    second_controller_main->HidePopup();
    observer.Wait();
  }

  EXPECT_FALSE(browser_actions_bar()->HasPopup());
  EXPECT_FALSE(overflow_bar->HasPopup());
  EXPECT_FALSE(second_controller_main->is_showing_popup());
  EXPECT_FALSE(second_controller_overflow->is_showing_popup());
  EXPECT_EQ(0, browser_actions_bar()->VisibleBrowserActions());
  EXPECT_EQ(2, overflow_bar->VisibleBrowserActions());
  base::RunLoop().RunUntilIdle();
  EXPECT_EQ(first_controller_main->GetId(),
            browser_actions_bar()->GetExtensionId(0));
  EXPECT_EQ(second_controller_main->GetId(),
            browser_actions_bar()->GetExtensionId(1));
}

// Test that page action popups work with the toolbar redesign.
IN_PROC_BROWSER_TEST_F(BrowserActionsBarRedesignBrowserTest,
                       PageActionPopupsTest) {
  ExtensionTestMessageListener listener("ready", false);
  const extensions::Extension* page_action_extension =
      LoadExtension(test_data_dir_.AppendASCII("trigger_actions").
                        AppendASCII("page_action_popup"));
  ASSERT_TRUE(page_action_extension);
  listener.WaitUntilSatisfied();
  EXPECT_EQ(1, browser_actions_bar()->VisibleBrowserActions());
  EXPECT_EQ(page_action_extension->id(),
            browser_actions_bar()->GetExtensionId(0));
  browser_actions_bar()->Press(0);
  base::RunLoop().RunUntilIdle();
  EXPECT_TRUE(browser_actions_bar()->HasPopup());
  // Cleanup the popup (to avoid having windows open at tear down).
  browser_actions_bar()->HidePopup();
  content::RunAllBlockingPoolTasksUntilIdle();
  EXPECT_FALSE(browser_actions_bar()->HasPopup());
}


text:
(function (HUB) {
  var SETTINGS = HUB.config.menuSettings;
  var COOKIE = {};   // replaced when menu is available

  //
  //  Set up the a11y path,if it isn't already in place
  //
  var PATH = MathJax.Ajax.config.path;
  if (!PATH.a11y) PATH.a11y = HUB.config.root + "/extensions/a11y";

  var Collapse = MathJax.Extension["auto-collapse"] = {
    version: "1.2.3",
    config: HUB.CombineConfig("auto-collapse",{
      disabled: false
    }),
    dependents: [],  // the extensions that depend on this one

    /*****************************************************************/

    Enable: function (update,menu) {
      SETTINGS.autocollapse = true;
      if (menu) COOKIE.autocollapse = true
      this.config.disabled = false;
      MathJax.Extension.collapsible.Enable(false,menu);
      if (update) {
        HUB.Queue(
          ["Reprocess",HUB],
          ["CollapseWideMath",this]
        );
      }
    },
    Disable: function (update,menu) {
      SETTINGS.autocollapse = false;
      if (menu) COOKIE.autocollapse = false;
      this.config.disabled = true;
      for (var i = this.dependents.length-1; i >= 0; i--) {
        var dependent = this.dependents[i];
        if (dependent.Disable) dependent.Disable(false,menu);
      }
      if (update) HUB.Queue(["Rerender",HUB]);
    },

    //
    //  Register a dependent
    //
    Dependent: function (extension) {
      this.dependents.push(extension);
    },

    Startup: function () {
      //
      //  Inform collapsible extension that we are a dependent
      //
      var Collapsible = MathJax.Extension.collapsible;
      if (Collapsible) Collapsible.Dependent(this);
      //
      //  Add the filter into the post-input hooks (priority 150, so other
      //  hooks run first, in particular, the enrichment and complexity hooks).
      //
      HUB.postInputHooks.Add(["Filter",Collapse],150);
      //
      //  Add the auto-collapsing
      //
      HUB.Queue(function () {return Collapse.CollapseWideMath()});
      //
      //  Add a resize handler to check for math that needs
      //  to be collapsed or expanded.
      //
      if (window.addEventListener) window.addEventListener("resize",Collapse.resizeHandler,false);
      else if (window.attachEvent) window.attachEvent("onresize",Collapse.resizeHandler);
      else window.onresize = Collapse.resizeHandler;
    },

    //
    //  If the math is block-level (or in an element "by itself"), then
    //  add the SRE actions for this element.
    //
    Filter: function (jax,id,script) {
      if (!jax.enriched || this.config.disabled) return;
      if (jax.root.Get("display") === "block" ||
          script.parentNode.childNodes.length <= 3) {
        jax.root.SRE = {action: this.Actions(jax.root)};
      }
    },
    //
    //  Produce an array of collapsible actions
    //  sorted by depth and complexity
    //
    Actions: function (node) {
      var actions = [];
      this.getActions(node,0,actions);
      return this.sortActions(actions);
    },
    getActions: function (node,depth,actions) {
      if (node.isToken || !node.data) return;
      depth++;
      for (var i = 0, m = node.data.length; i < m; i++) {
        if (node.data[i]) {
          var child = node.data[i];
          if (child.collapsible) {
            if (!actions[depth]) actions[depth] = [];
            actions[depth].push(child);
            this.getActions(child.data[1],depth,actions);
          } else {
            this.getActions(child,depth,actions);
          }
        }
      }
    },
    sortActions: function (actions) {
      var ACTIONS = [];
      for (var i = 0, m = actions.length; i < m; i++) {
        if (actions[i]) ACTIONS = ACTIONS.concat(actions[i].sort(this.sortActionsBy));
      }
      return ACTIONS;
    },
    sortActionsBy: function (a,b) {
      a = a.data[1].complexity; b = b.data[1].complexity;
      return (a < b ? -1 : a > b ? 1 : 0);
    },

    /*****************************************************************/
    /*
     *  These routines implement the automatic collapsing of equations
     *  based on container widths.
     */

    //
    //  Find math that is too wide and collapse it.
    //
    CollapseWideMath: function (element) {
      if (this.config.disabled) return;
      this.GetContainerWidths(element);
      var jax = HUB.getAllJax(element);
      var state = {collapse: [], jax: jax, m: jax.length, i: 0, changed:false};
      return this.collapseState(state);
    },
    collapseState: function (state) {
      var collapse = state.collapse;
      while (state.i < state.m) {
        var jax = state.jax[state.i];
        var SRE = jax.root.SRE; state.changed = false;
        if (SRE && SRE.action.length) {
          if (SRE.cwidth < SRE.m || SRE.cwidth > SRE.M) {
            var restart = this.getActionWidths(jax,state); if (restart) return restart;
            this.collapseActions(SRE,state);
            if (state.changed) collapse.push(jax.SourceElement());
          }
        }
        state.i++;
      }
      if (collapse.length === 0) return;
      if (collapse.length === 1) collapse = collapse[0];
      return HUB.Rerender(collapse);
    },

    //
    //  Find the actions that need to be collapsed to acheive
    //  the correct width, and retain the sizes that would cause
    //  the equation to be expanded or collapsed further.
    //
    collapseActions: function (SRE,state) {
      var w = SRE.width, m = w, M = 1000000;
      for (var j = SRE.action.length-1; j >= 0; j--) {
        var action = SRE.action[j], selection = action.selection;
        if (w > SRE.cwidth) {
          action.selection = 1;
          m = action.SREwidth; M = w;
        } else {
          action.selection = 2;
        }
        w = action.SREwidth;
        if (SRE.DOMupdate) {
          document.getElementById(action.id).setAttribute("selection",action.selection);
        } else if (action.selection !== selection) {
          state.changed = true;
        }
      }
      SRE.m = m; SRE.M = M;
    },

    //
    //  Get the widths of the different collapsings,
    //  trapping any restarts, and restarting the process
    //  when the event has occurred.
    //
    getActionWidths: function (jax,state) {
      if (!jax.root.SRE.actionWidths) {
        MathJax.OutputJax[jax.outputJax].getMetrics(jax);
        try {this.computeActionWidths(jax)} catch (err) {
          if (!err.restart) throw err;
          return MathJax.Callback.After(["collapseState",this,state],err.restart);
        }
        state.changed = true;
      }
      return null;
    },
    //
    //  Compute the action widths by collapsing each maction,
    //  and recording the width of the complete equation.
    //
    computeActionWidths: function (jax) {
      var SRE = jax.root.SRE, actions = SRE.action, j, state = {};
      SRE.width = jax.sreGetRootWidth(state);
      for (j = actions.length-1; j >= 0; j--) actions[j].selection = 2;
      for (j = actions.length-1; j >= 0; j--) {
        var action = actions[j];
        if (action.SREwidth == null) {
          action.selection = 1;
          action.SREwidth = jax.sreGetActionWidth(state,action);
        }
      }
      SRE.actionWidths = true;
    },

    //
    //  Get the widths of the containers of tall the math elements
    //  that can be collapsed (so we can tell which ones NEED to be
    //  collapsed).  Do this in a way that only causes two reflows.
    //
    GetContainerWidths: function (element) {
      var JAX = HUB.getAllJax(element);
      var i, m, script, span = MathJax.HTML.Element("span",{style:{display:"block"}});
      var math = [], jax, root;
      for (i = 0, m = JAX.length; i < m; i++) {
        jax = JAX[i], root = jax.root, SRE = root.SRE;
        if (SRE && SRE.action.length) {
          if (SRE.width == null) {
            jax.sreGetMetrics();
            SRE.m = SRE.width; SRE.M = 1000000;
          }
          script = jax.SourceElement();
          script.previousSibling.style.display = "none";
          script.parentNode.insertBefore(span.cloneNode(false),script);
          math.push([jax,script]);
        }
      }
      for (i = 0, m = math.length; i < m; i++) {
        jax = math[i][0], script = math[i][1];
        if (script.previousSibling.offsetWidth)
          jax.root.SRE.cwidth = script.previousSibling.offsetWidth * jax.root.SRE.em;
      }
      for (i = 0, m = math.length; i < m; i++) {
        jax = math[i][0], script = math[i][1];
        script.parentNode.removeChild(script.previousSibling);
        script.previousSibling.style.display = "";
      }
    },

    /*****************************************************************/

    //
    //  A resize handler that can be tied to the window resize event
    //  to collapse math automatically on resize.
    //

    timer: null,
    running: false,
    retry: false,
    saved_delay: 0,

    resizeHandler: function (event) {
      if (Collapse.config.disabled) return;
      if (Collapse.running) {Collapse.retry = true; return}
      if (Collapse.timer) clearTimeout(Collapse.timer);
      Collapse.timer = setTimeout(Collapse.resizeAction, 100);
    },
    resizeAction: function () {
      Collapse.timer = null;
      Collapse.running = true;
      HUB.Queue(
        function () {
          //
          //  Prevent flicker between input and output phases.
          //
          Collapse.saved_delay = HUB.processSectionDelay;
          HUB.processSectionDelay = 0;
        },
        ["CollapseWideMath",Collapse],
        ["resizeCheck",Collapse]
      );
    },
    resizeCheck: function () {
      Collapse.running = false;
      HUB.processSectionDelay = Collapse.saved_delay;
      if (Collapse.retry) {
        Collapse.retry = false;
        setTimeout(Collapse.resizeHandler,0);
      }
    }

  };

  HUB.Register.StartupHook("End Extensions", function () {
    if (SETTINGS.autocollapse == null) {
      SETTINGS.autocollapse = !Collapse.config.disabled;
    } else {
      Collapse.config.disabled = !SETTINGS.autocollapse;
    }
    HUB.Register.StartupHook("MathMenu Ready", function () {
      COOKIE = MathJax.Menu.cookie;
      var Switch = function(menu) {
        Collapse[SETTINGS.autocollapse ? "Enable" : "Disable"](true,true);
        MathJax.Menu.saveCookie();
      };
      var ITEM = MathJax.Menu.ITEM,
          MENU = MathJax.Menu.menu;
      var menu = ITEM.CHECKBOX(
        ['AutoCollapse','Auto Collapse'], 'autocollapse', {action: Switch}
      );
      var submenu = (MENU.FindId('Accessibility')||{}).submenu, index;
      if (submenu) {
        index = submenu.IndexOfId('AutoCollapse');
        if (index !== null) {
          submenu.items[index] = menu;
        } else {
          index = submenu.IndexOfId('CollapsibleMath');
          submenu.items.splice(index+1,0,menu);
        }
      } else {
        index = MENU.IndexOfId('CollapsibleMath');
        MENU.items.splice(index+1,0,menu);
      }
      var init = function () {Collapse[SETTINGS.autocollapse ? "Enable" : "Disable"]()};
      if (MathJax.Extension.collapse) init();
        else MathJax.Hub.Register.StartupHook("Auto Collapse Ready", init);
    },25);  // after Assistive-Explore
  },25);

})(MathJax.Hub);

/*****************************************************************/
/*
 *  Add methods to the ElementJax and OutputJax to get the
 *  widths of the collapsed elements.
 */

//
//  Add SRE methods to ElementJax.
//
MathJax.ElementJax.Augment({
  sreGetMetrics: function () {
    MathJax.OutputJax[this.outputJax].sreGetMetrics(this,this.root.SRE);
  },
  sreGetRootWidth: function (state) {
    return MathJax.OutputJax[this.outputJax].sreGetRootWidth(this,state);
  },
  sreGetActionWidth: function (state,action) {
    return MathJax.OutputJax[this.outputJax].sreGetActionWidth(this,state,action);
  }
});

//
//  Add default methods to base OutputJax class.
//
MathJax.OutputJax.Augment({
  getMetrics: function () {},  // make sure it is defined
  sreGetMetrics: function (jax,SRE) {SRE.cwidth = 1000000; SRE.width = 0; SRE.em = 12},
  sreGetRootWidth: function (jax,state) {return 0},
  sreGetActionWidth: function (jax,state,action) {return 0}
});

//
//  Specific implementations for HTML-CSS output.
//
MathJax.Hub.Register.StartupHook("HTML-CSS Jax Ready",function () {
  MathJax.OutputJax["HTML-CSS"].Augment({
    sreGetMetrics: function (jax,SRE) {
      SRE.width = jax.root.data[0].HTMLspanElement().parentNode.bbox.w;
      SRE.em = 1 / jax.HTMLCSS.em / jax.HTMLCSS.scale;
    },
    sreGetRootWidth: function (jax,state) {
      var html = jax.root.data[0].HTMLspanElement();
      state.box = html.parentNode;
      return state.box.bbox.w;
    },
    sreGetActionWidth: function (jax,state,action) {
      return jax.root.data[0].toHTML(state.box).bbox.w;
    }
  });
});

//
//  Specific implementations for SVG output.
//
MathJax.Hub.Register.StartupHook("SVG Jax Ready",function () {
  MathJax.OutputJax.SVG.Augment({
    getMetrics: function (jax) {
      this.em = MathJax.ElementJax.mml.mbase.prototype.em = jax.SVG.em; this.ex = jax.SVG.ex;
      this.linebreakWidth = jax.SVG.lineWidth; this.cwidth = jax.SVG.cwidth;
    },
    sreGetMetrics: function (jax,SRE) {
      SRE.width = jax.root.SVGdata.w/1000;
      SRE.em = 1/jax.SVG.em;
    },
    sreGetRootWidth: function (jax,state) {
      state.span = document.getElementById(jax.inputID+"-Frame");
      return jax.root.SVGdata.w/1000;
    },
    sreGetActionWidth: function (jax,state,action) {
      this.mathDiv = state.span;
      state.span.appendChild(this.textSVG);
      try {var svg = jax.root.data[0].toSVG()} catch(err) {var error = err}
      state.span.removeChild(this.textSVG);
      if (error) throw error;  // can happen when a restart is needed
      return jax.root.data[0].SVGdata.w/1000;
    }
  });
});

//
//  Specific implementations for CommonHTML output.
//
MathJax.Hub.Register.StartupHook("CommonHTML Jax Ready",function () {
  MathJax.OutputJax.CommonHTML.Augment({
    sreGetMetrics: function (jax,SRE) {
      SRE.width = jax.root.CHTML.w;
      SRE.em = 1 / jax.CHTML.em / jax.CHTML.scale;
    },
    sreGetRootWidth: function (jax,state) {
      state.span = document.getElementById(jax.inputID+"-Frame").firstChild;
      state.tmp = document.createElement("span");
      state.tmp.className = state.span.className;
      return jax.root.CHTML.w / jax.CHTML.scale;
    },
    sreGetActionWidth: function (jax,state,action) {
      state.span.parentNode.replaceChild(state.tmp,state.span);
      MathJax.OutputJax.CommonHTML.CHTMLnode = state.tmp;
      try {jax.root.data[0].toCommonHTML(state.tmp)} catch (err) {var error = err}
      state.tmp.parentNode.replaceChild(state.span,state.tmp);
      if (error) throw error;  // can happen when a restart is needed
      return jax.root.data[0].CHTML.w / jax.CHTML.scale;
    }
  });
});

//
//  Specific implementations for NativeMML output.
//
MathJax.Hub.Register.StartupHook("NativeMML Jax Ready",function () {
  MathJax.OutputJax.NativeMML.Augment({
    sreGetMetrics: function (jax,SRE) {
      var span = document.getElementById(jax.inputID+"-Frame");
      SRE.width = span.offsetWidth;
      SRE.em = 1; SRE.DOMupdate = true;
    },
    sreGetRootWidth: function (jax,state) {
      state.span = document.getElementById(jax.inputID+"-Frame").firstChild;
      return state.span.offsetWidth;
    },
    sreGetActionWidth: function (jax,state,action) {
      var maction = document.getElementById(action.id);
      maction.setAttribute("selection",1);
      var w = state.span.offsetWidth;
      return w;
    }
  });
});

/*****************************************************************/

//
//  Load the collapsible extension and
//  signal the start up when that has loaded.
//
MathJax.Ajax.Require("[a11y]/collapsible.js");
MathJax.Hub.Register.StartupHook("Collapsible Ready", function () {
  MathJax.Extension["auto-collapse"].Startup(); // Initialize the collapsing process
  MathJax.Hub.Startup.signal.Post("Auto Collapse Ready");
  MathJax.Ajax.loadComplete("[a11y]/auto-collapse.js");
});


text:
package io.micrometer.core.instrument.binder.mongodb;

import com.mongodb.ServerAddress;
import com.mongodb.connection.ClusterId;
import com.mongodb.connection.ConnectionDescription;
import com.mongodb.connection.ServerId;
import com.mongodb.event.CommandStartedEvent;
import com.mongodb.event.CommandSucceededEvent;
import io.micrometer.core.instrument.Tag;
import org.bson.BsonBoolean;
import org.bson.BsonDocument;
import org.bson.BsonElement;
import org.bson.BsonString;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;

import java.util.Arrays;

import static org.assertj.core.api.Assertions.assertThat;

/**
 * Unit test for {@link DefaultMongoCommandTagsProvider}.
 *
 * @author Chris Bono
 */
class DefaultMongoCommandTagsProviderTest {

    private final ConnectionDescription connectionDesc = new ConnectionDescription(
            new ServerId(new ClusterId("cluster1"), new ServerAddress("localhost", 5150)));

    private final DefaultMongoCommandTagsProvider tagsProvider = new DefaultMongoCommandTagsProvider();

    @Test
    void defaultCommandTags() {
        CommandSucceededEvent event = commandSucceededEvent(5150);
        Iterable<Tag> tags = tagsProvider.commandTags(event);
        assertThat(tags).containsExactlyInAnyOrder(Tag.of("command", "find"), Tag.of("collection", "unknown"),
                Tag.of("cluster.id", connectionDesc.getConnectionId().getServerId().getClusterId().getValue()),
                Tag.of("server.address", "localhost:5150"), Tag.of("status", "SUCCESS"));
    }

    @Test
    void handlesCommandsOverLimitGracefully() {
        for (int i = 1; i <= 1000; i++) {
            tagsProvider.commandStarted(commandStartedEvent(i));
        }
        // At this point we have started 1000 commands (the state map is full at the time)

        // 1001 will not be added to state map and therefore will use 'unknown'
        tagsProvider.commandStarted(commandStartedEvent(1001));
        Iterable<Tag> tags = tagsProvider.commandTags(commandSucceededEvent(1001));
        assertThat(tags).contains(Tag.of("collection", "unknown"));

        // Complete 1000 - which will remove previously added entry from state map
        tags = tagsProvider.commandTags(commandSucceededEvent(1000));
        assertThat(tags).contains(Tag.of("collection", "collection-1000"));

        // 1001 will now be put in state map (since 1000 removed and made room for it)
        tagsProvider.commandStarted(commandStartedEvent(1001));

        // 1002 will not be added to state map and therefore will use 'unknown'
        tagsProvider.commandStarted(commandStartedEvent(1002));

        tags = tagsProvider.commandTags(commandSucceededEvent(1001));
        assertThat(tags).contains(Tag.of("collection", "collection-1001"));

        tags = tagsProvider.commandTags(commandSucceededEvent(1002));
        assertThat(tags).contains(Tag.of("collection", "unknown"));
    }

    private CommandStartedEvent commandStartedEvent(int requestId) {
        return new CommandStartedEvent(requestId, connectionDesc, "db1", "find",
                new BsonDocument("find", new BsonString("collection-" + requestId)));
    }

    private CommandSucceededEvent commandSucceededEvent(int requestId) {
        return new CommandSucceededEvent(requestId, connectionDesc, "find", new BsonDocument(), 1200L);
    }

    @Nested
    class DetermineCollectionName {

        @Test
        void withNameInAllowList() {
            assertThat(tagsProvider.determineCollectionName("find", new BsonDocument("find", new BsonString(" bar "))))
                    .hasValue("bar");
        }

        @Test
        void withNameNotInAllowList() {
            assertThat(tagsProvider.determineCollectionName("cmd", new BsonDocument("cmd", new BsonString(" bar "))))
                    .isEmpty();
        }

        @Test
        void withNameNotInCommand() {
            assertThat(tagsProvider.determineCollectionName("find", new BsonDocument())).isEmpty();
        }

        @Test
        void withNonStringCommand() {
            assertThat(tagsProvider.determineCollectionName("find", new BsonDocument("find", BsonBoolean.TRUE)))
                    .isEmpty();
        }

        @Test
        void withEmptyStringCommand() {
            assertThat(tagsProvider.determineCollectionName("find", new BsonDocument("find", new BsonString("  "))))
                    .isEmpty();
        }

        @Test
        void withCollectionFieldOnly() {
            assertThat(tagsProvider.determineCollectionName("find",
                    new BsonDocument("collection", new BsonString(" bar ")))).hasValue("bar");
        }

        @Test
        void withCollectionFieldAndAllowListedCommand() {
            BsonDocument command = new BsonDocument(Arrays.asList(new BsonElement("collection", new BsonString("coll")),
                    new BsonElement("find", new BsonString("bar"))));
            assertThat(tagsProvider.determineCollectionName("find", command)).hasValue("bar");
        }

        @Test
        void withCollectionFieldAndNotAllowListedCommand() {
            BsonDocument command = new BsonDocument(Arrays.asList(new BsonElement("collection", new BsonString("coll")),
                    new BsonElement("cmd", new BsonString("bar"))));
            assertThat(tagsProvider.determineCollectionName("find", command)).hasValue("coll");
        }

    }

}


text:
[![Release](https://jitpack.io/v/nasahapps/Material-Design-Toolbox.svg)](https://jitpack.io/#nasahapps/Material-Design-Toolbox)

*_This library is still a work in progress._*

The main purpose of this library is to provide components and helper methods in implementing [Material Design concepts](http://www.google.com/design/spec/material-design/introduction.html) with little to no effort. This library in particular focuses on components that are not yet included in Google's support libraries, with most widgets adhering very closely to the guidelines Google has set. Links to already-existing components will be provided.

This library supports Android 4.1 (API 16) and up, however, not all components/methods will be supported pre-API 21.

To use, add Jitpack as a repository in your top-level build.gradle file:

```groovy
repositories {
    jcenter()
    maven { url "https://jitpack.io" }
}
```
Then add one (or all) of the following dependencies, depending on what you want specifically:

```groovy
dependencies {
    // For general utility methods/classes
    compile 'com.github.nasahapps.Material-Design-Toolbox:base:{latest_version}'
    // For helper methods pertaining to BottomSheets
    compile 'com.github.nasahapps.Material-Design-Toolbox:bottomsheets:{latest_version}'
}
```

Note that all modules include the `com.github.nasahapps.Material-Design-Toolbox:base` module by default.

* [Components](#components)
  * [Steppers](#steppers)
  * [Tabs](#tabs)
  * [Text Fields](#text-fields)
  * [Toolbars](#toolbars)
  * [Tooltips](#tooltips)

## Components

### [Steppers](http://www.google.com/design/spec/components/steppers.html)

This library provides two stepper layouts:

`StepperProgressLayout`: Displays step progress using plain text (e.g. Step 4 of 6), dots, or with a tinted ProgressBar. The `StepperProgressLayout` provides "Back" and "Next" buttons for going forwards/backwards between steps, with the "Next" button turning into a "Finish" button on the last step. Also, it is a `ViewGroup`, so any views you add to it will automatically be placed accordingly. (TODO: add pictures)

Custom attributes:
* stepperMaxProgress
 * the max number of steps
 * default value: 1
* stepperProgress
 * the current step
 * default value: 1
* stepperBackButtonText
 * default value: "Back"
* stepperNextButtonText
 * default value: "Next"
* stepperFinishButtonText
 * the text to be displayed on the "Next" button when on the last step
 * default value: "Finish"
* stepperProgressType
 * the type of progress to be shown, one of TYPE_TEXT, TYPE_DOTS, or TYPE_BAR
 * default value: TYPE_TEXT
* stepperProgressAccent
 * the accent color to use for the dots/bar progress
 * default value: R.attr.colorPrimary

`HorizontalStepperLayout`: Displays steps using `Stepper` views in either a horizontal or vertical fashion. Steppers have one of four states: `COMPLETED`, `ACTIVE`, `INACTIVE`, or `ERROR`.
Custom attributes:
* stepperLayoutMargin
 * the margin between each Stepper
 * default value: 56dp

Also provided is the `Stepper` widget that should be the only child view used in a `HorizontalStepperLayout`.
Custom attributes:
* stepperTitle
* stepperSubtitle
* stepperAccent
 * the accent color to be used as the step number background
 * default value: R.attr.colorPrimary
* stepperState
 * the initial state of the stepper (`ACTIVE`, `INACTIVE`, `COMPLETED`, or `ERROR`)
 * default value: `ACTIVE`

### [Tabs](https://material.io/guidelines/components/tabs.html)

The [`TabLayout`](https://developer.android.com/reference/android/support/design/widget/TabLayout.html) widget is part of the `design` support library.

### [Text Fields](https://material.io/guidelines/components/text-fields.html)

The [`TextInputLayout`](https://developer.android.com/reference/android/support/design/widget/TextInputLayout.html) widget is part of the `design` support library. It is suggested to use a `TextInputEditText` instead of a regular `EditText` in this layout.

### [Toolbars](https://material.io/guidelines/components/toolbars.html)

The [`Toolbar`](https://developer.android.com/reference/android/support/v7/widget/Toolbar.html) widget is part of the `appcompat-v7` support library.

### [Tooltips](https://material.io/guidelines/components/tooltips.html)

Tooltips (extends `TextView`) are similar to [`Toasts`](https://developer.android.com/reference/android/widget/Toast.html), both in appearance and in function. Creating a `Tooltip` is very similar to creating a `Toast` or `Snackbar`:

```java
Tooltip.makeTooltip(context, "Tooltip text", Tooltip.LENGTH_SHORT, anchorView).show();
```

The arguments passed in are a `Context`, string text (or a string resource), a duration of how long you want the `Tooltip` to appear (`LENGTH_SHORT` or `LENGTH_LONG`), and a `View` to anchor the `Tooltip` on. By default, the `Tooltip` will appear below the anchor, unless the anchor is low enough on the screen, then the `Tooltip` will instead appear above the anchor.

## License

```
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
```


text:
#region MIT License

#endregion

#if UseDouble
using Scalar = System.Double;
#else
using Scalar = System.Single;
#endif
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
using System.Drawing;
using AdvanceMath;
using AdvanceMath.Geometry2D;
using Physics2DDotNet;
using Physics2DDotNet.Shapes;
using Physics2DDotNet.Collections;
using Tao.OpenGl;
using SdlDotNet.Graphics;
using SdlDotNet.Core;
using SdlDotNet.Input;

namespace Graphics2DDotNet
{

    public class Pendable<TParent>
        where TParent : class
    {
        public event EventHandler Pending;
        public event EventHandler Added;
        public event EventHandler<RemovedEventArgs<TParent>> Removed;
        public event EventHandler ZOrderChanged;
        public event EventHandler LifetimeChanged;

        int id;
        int zOrder;
        bool isAdded;
        bool isChecked;
        TParent parent;
        Lifespan lifetime;
        object tag;

        public Pendable(Lifespan lifetime)
        {
            if (lifetime == null) { throw new ArgumentNullException("lifetime"); }
            this.lifetime = lifetime;
        }
        protected Pendable(Pendable<TParent> copy)
        {
            this.lifetime = copy.lifetime.Duplicate();
        }
        public int ID
        {
            get { return id; }
        }
        public int ZOrder
        {
            get
            {
                return zOrder;
            }
            set
            {
                if (zOrder != value)
                {
                    zOrder = value;
                    if (ZOrderChanged != null) { ZOrderChanged(this, EventArgs.Empty); }
                }
            }
        }
        public bool IsPending
        {
            get { return parent != null && !isAdded; }
        }
        public object Tag
        {
            get { return tag; }
            set { tag = value; }
        }
        public Lifespan Lifetime
        {
            get { return lifetime; }
            set
            {
                if (value == null) { throw new ArgumentNullException("value"); }
                if (this.lifetime != value)
                {
                    lifetime = value;
                    if (LifetimeChanged != null) { LifetimeChanged(this, EventArgs.Empty); }
                }
            }
        }
        public TParent Parent
        {
            get { return parent; }
        }
        public bool IsAdded
        {
            get
            {
                return isAdded;
            }
        }

        internal void PreCheckInternal()
        {
            this.isChecked = false;
        }
        internal void CheckInternal()
        {
            if (this.parent != null || this.isChecked)
            {
                throw new InvalidOperationException(String.Format("A {0} cannot be added to more then one {1} or added twice.", this.GetType().Name, typeof(TParent).Name));
            }
            this.isChecked = true;
        }
        internal void OnPendingInternal(TParent parent)
        {
            this.isChecked = false;
            this.parent = parent;
            OnPending(EventArgs.Empty);
        }
        internal void OnAddedInternal(int id)
        {
            this.isAdded = true;
            this.id = id;
            OnAdded(EventArgs.Empty);
        }
        internal void OnRemovedInternal()
        {
            bool isPending = IsPending;
            TParent parent = this.parent;
            bool wasPending = isPending;
            this.isAdded = false;
            this.parent = null;
            this.id = -1;
            OnRemoved(new RemovedEventArgs<TParent>(parent, wasPending));
        }
        protected virtual void OnPending(EventArgs e)
        {
            if (Pending != null)
            {
                Pending(this, e);
            }
        }
        protected virtual void OnAdded(EventArgs e)
        {
            if (Added != null)
            {
                Added(this, e);
            }
        }
        protected virtual void OnRemoved(RemovedEventArgs<TParent> e)
        {
            if (Removed != null)
            {
                Removed(this, e);
            }
        }
    }
}


text:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.anykey.library.progressbutton">

    <application android:allowBackup="true" android:label="@string/app_name">

    </application>

</manifest>


text:
class PoaFileControlTotal < ActiveRecord::Base
  include Updateable

  belongs_to :poa_file

  def self.spec(d)
    d.poa_file_control_total do |l|
      l.trap { |line| line[0, 2] == '91' }
      l.template :poa_defaults
      l.total_line_items_in_file 13
      l.total_pos_acknowledged 5
      l.total_units_acknowledged 10
      l.record_count_01 5
      l.record_count_02 5
      l.record_count_03 5
      l.record_count_04 5
      l.record_count_05 5
      l.record_count_06 5
      l.spacer 10
    end
  end

  def self.populate(p, poa_file)
    p[:poa_file_control_total].each do |data|
      data[:poa_file_id] = poa_file.id
      object = self.find_or_create_by_poa_file_id(data[:poa_file_id])
      object.update_from_hash(data)
    end
  end

end


text:
require 'spec_helper'

describe RapGenius::Line, vcr: { cassette_name: "line-2638695" } do
  let(:line) { described_class.find("2638695") }
  subject { line }

  let(:access_token) { 'my-access-token' }
  before { RapGenius::Client.access_token = access_token }

  its(:id)       { should eq "2638695" }
  its(:song)     { should be_a RapGenius::Song }
  its(:lyric) { should eq "Versace, Versace, Medusa head on me like I'm 'luminati" }
  its("explanations.first") { should include "Versace's logo is the head of Medusa" }
  its(:explanations) { should eq line.annotations }

  context "a non-existent referent ID" do
    let(:line) { described_class.find("bahahaha") }

    it "raises an exception" do
      expect { line }.to raise_exception
    end
  end
end


text:
package org.codehaus.mojo.versions.change;

import javax.xml.stream.XMLStreamException;

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

import org.codehaus.mojo.versions.api.change.VersionChange;

/**
 * Created by IntelliJ IDEA.
 *
 * @author Stephen Connolly
 * @since 15-Sep-2010 16:01:35
 */
public class CompositeVersionChanger
    implements VersionChanger
{
    private final List<VersionChanger> composites;

    public CompositeVersionChanger( VersionChanger[] composites )
    {
        this.composites = new ArrayList<>( Arrays.asList( composites ) );
    }

    public CompositeVersionChanger( List<VersionChanger> composites )
    {
        this.composites = new ArrayList<>( composites );
    }

    public void apply( VersionChange versionChange )
        throws XMLStreamException
    {
        for ( VersionChanger delegate : composites )
        {
            delegate.apply( versionChange );
        }
    }
}


text:
use std::collections::HashMap;

use crate::noisemap::NoiseMapGeneratorBase;
use crate::world::Size;

#[derive(Copy, Clone)]
pub enum ConstraintType {
    /// This constraint is satisfied when the noise value is
    /// lower than the given threshold.
    LT(f64),

    /// This constraint is satisfied when the noise value is
    /// greater than the given threshold.
    GT(f64)
}

/// A constraint that limits when a tile should be chosen for
/// the generated world.
pub struct Constraint {
    nm: Box<dyn NoiseMapGeneratorBase>,
    constraint: ConstraintType
}

#[macro_export]
macro_rules! constraint {
    ($nm:expr, < $v:expr) => (Constraint::new($nm, ConstraintType::LT($v)));
    ($nm:expr, > $v:expr) => (Constraint::new($nm, ConstraintType::GT($v)));
}

impl Constraint {
    pub fn new(nm: Box<dyn NoiseMapGeneratorBase>, constraint: ConstraintType) -> Constraint {
        Constraint {
            nm,
            constraint
        }
    }

    /// Returns true if the given value would satisfy this constraint.
    pub fn satisfied_by(&self, x: i64, y: i64, size: Size, chunk_x: i64, chunk_y: i64, nms: &mut HashMap<u64, Vec<Vec<f64>>>) -> bool {
        let id = self.nm.id();

        let nm = nms.entry(id).or_insert_with(|| self.nm.generate_sized_chunk(size, chunk_x, chunk_y));

        let x = (x as i64).rem_euclid(size.w);
        let y = (y as i64).rem_euclid(size.h);

        match self.constraint {
            ConstraintType::LT(threshold) => nm[y as usize][x as usize] < threshold,
            ConstraintType::GT(threshold) => nm[y as usize][x as usize] > threshold
        }
    }
}