text:
package ec2

import "github.com/timob/javabind"

type ServicesEc2ModelVpcPeeringConnectionStateReasonCodeInterface interface {

	// public static com.amazonaws.services.ec2.model.VpcPeeringConnectionStateReasonCode[] values()
	Values() []*ServicesEc2ModelVpcPeeringConnectionStateReasonCode

	// public static com.amazonaws.services.ec2.model.VpcPeeringConnectionStateReasonCode valueOf(java.lang.String)
	ValueOf(a string) *ServicesEc2ModelVpcPeeringConnectionStateReasonCode

	// public java.lang.String toString()
	ToString() string

	// public static com.amazonaws.services.ec2.model.VpcPeeringConnectionStateReasonCode fromValue(java.lang.String)
	FromValue(a string) *ServicesEc2ModelVpcPeeringConnectionStateReasonCode
}

type ServicesEc2ModelVpcPeeringConnectionStateReasonCode struct {
	*javabind.Callable
}

// public static com.amazonaws.services.ec2.model.VpcPeeringConnectionStateReasonCode[] values()
func (jbobject *ServicesEc2ModelVpcPeeringConnectionStateReasonCode) Values() []*ServicesEc2ModelVpcPeeringConnectionStateReasonCode {
	jret, err := javabind.GetEnv().CallStaticMethod("com/amazonaws/services/ec2/model/VpcPeeringConnectionStateReasonCode", "values", javabind.ObjectArrayType("com/amazonaws/services/ec2/model/VpcPeeringConnectionStateReasonCode"))
	if err != nil {
		panic(err)
	}
	retconv := javabind.NewJavaToGoObjectArray(javabind.NewJavaToGoCallable(), "com/amazonaws/services/ec2/model/VpcPeeringConnectionStateReasonCode")
	dst := new([]*ServicesEc2ModelVpcPeeringConnectionStateReasonCode)
	retconv.Dest(dst)
	if err := retconv.Convert(javabind.ObjectRef(jret)); err != nil {
		panic(err)
	}
	retconv.CleanUp()
	return *dst
}

// public static com.amazonaws.services.ec2.model.VpcPeeringConnectionStateReasonCode valueOf(java.lang.String)
func (jbobject *ServicesEc2ModelVpcPeeringConnectionStateReasonCode) ValueOf(a string) *ServicesEc2ModelVpcPeeringConnectionStateReasonCode {
	conv_a := javabind.NewGoToJavaString()
	if err := conv_a.Convert(a); err != nil {
		panic(err)
	}
	jret, err := javabind.GetEnv().CallStaticMethod("com/amazonaws/services/ec2/model/VpcPeeringConnectionStateReasonCode", "valueOf", "com/amazonaws/services/ec2/model/VpcPeeringConnectionStateReasonCode", conv_a.Value().Cast("java/lang/String"))
	if err != nil {
		panic(err)
	}
	conv_a.CleanUp()
	retconv := javabind.NewJavaToGoCallable()
	dst := &javabind.Callable{}
	retconv.Dest(dst)
	if err := retconv.Convert(javabind.ObjectRef(jret)); err != nil {
		panic(err)
	}
	retconv.CleanUp()
	unique_x := &ServicesEc2ModelVpcPeeringConnectionStateReasonCode{}
	unique_x.Callable = dst
	return unique_x
}

// public java.lang.String toString()
func (jbobject *ServicesEc2ModelVpcPeeringConnectionStateReasonCode) ToString() string {
	jret, err := jbobject.CallMethod(javabind.GetEnv(), "toString", "java/lang/String")
	if err != nil {
		panic(err)
	}
	retconv := javabind.NewJavaToGoString()
	dst := new(string)
	retconv.Dest(dst)
	if err := retconv.Convert(javabind.ObjectRef(jret)); err != nil {
		panic(err)
	}
	retconv.CleanUp()
	return *dst
}

// public static com.amazonaws.services.ec2.model.VpcPeeringConnectionStateReasonCode fromValue(java.lang.String)
func (jbobject *ServicesEc2ModelVpcPeeringConnectionStateReasonCode) FromValue(a string) *ServicesEc2ModelVpcPeeringConnectionStateReasonCode {
	conv_a := javabind.NewGoToJavaString()
	if err := conv_a.Convert(a); err != nil {
		panic(err)
	}
	jret, err := javabind.GetEnv().CallStaticMethod("com/amazonaws/services/ec2/model/VpcPeeringConnectionStateReasonCode", "fromValue", "com/amazonaws/services/ec2/model/VpcPeeringConnectionStateReasonCode", conv_a.Value().Cast("java/lang/String"))
	if err != nil {
		panic(err)
	}
	conv_a.CleanUp()
	retconv := javabind.NewJavaToGoCallable()
	dst := &javabind.Callable{}
	retconv.Dest(dst)
	if err := retconv.Convert(javabind.ObjectRef(jret)); err != nil {
		panic(err)
	}
	retconv.CleanUp()
	unique_x := &ServicesEc2ModelVpcPeeringConnectionStateReasonCode{}
	unique_x.Callable = dst
	return unique_x
}

func (jbobject *ServicesEc2ModelVpcPeeringConnectionStateReasonCode) InitiatingRequest() *ServicesEc2ModelVpcPeeringConnectionStateReasonCode {
	jret, err := javabind.GetEnv().GetStaticField("com/amazonaws/services/ec2/model/VpcPeeringConnectionStateReasonCode", "InitiatingRequest", "com/amazonaws/services/ec2/model/VpcPeeringConnectionStateReasonCode")
	if err != nil {
		panic(err)
	}
	retconv := javabind.NewJavaToGoCallable()
	dst := &javabind.Callable{}
	retconv.Dest(dst)
	if err := retconv.Convert(javabind.ObjectRef(jret)); err != nil {
		panic(err)
	}
	retconv.CleanUp()
	unique_x := &ServicesEc2ModelVpcPeeringConnectionStateReasonCode{}
	unique_x.Callable = dst
	return unique_x
}

func (jbobject *ServicesEc2ModelVpcPeeringConnectionStateReasonCode) SetFieldInitiatingRequest(val ServicesEc2ModelVpcPeeringConnectionStateReasonCodeInterface) {
	conv_val := javabind.NewGoToJavaCallable()
	if err := conv_val.Convert(val); err != nil {
		panic(err)
	}
	err := javabind.GetEnv().SetStaticField("com/amazonaws/services/ec2/model/VpcPeeringConnectionStateReasonCode", "InitiatingRequest", conv_val.Value())
	if err != nil {
		panic(err)
	}
	conv_val.CleanUp()

}

func (jbobject *ServicesEc2ModelVpcPeeringConnectionStateReasonCode) PendingAcceptance() *ServicesEc2ModelVpcPeeringConnectionStateReasonCode {
	jret, err := javabind.GetEnv().GetStaticField("com/amazonaws/services/ec2/model/VpcPeeringConnectionStateReasonCode", "PendingAcceptance", "com/amazonaws/services/ec2/model/VpcPeeringConnectionStateReasonCode")
	if err != nil {
		panic(err)
	}
	retconv := javabind.NewJavaToGoCallable()
	dst := &javabind.Callable{}
	retconv.Dest(dst)
	if err := retconv.Convert(javabind.ObjectRef(jret)); err != nil {
		panic(err)
	}
	retconv.CleanUp()
	unique_x := &ServicesEc2ModelVpcPeeringConnectionStateReasonCode{}
	unique_x.Callable = dst
	return unique_x
}

func (jbobject *ServicesEc2ModelVpcPeeringConnectionStateReasonCode) SetFieldPendingAcceptance(val ServicesEc2ModelVpcPeeringConnectionStateReasonCodeInterface) {
	conv_val := javabind.NewGoToJavaCallable()
	if err := conv_val.Convert(val); err != nil {
		panic(err)
	}
	err := javabind.GetEnv().SetStaticField("com/amazonaws/services/ec2/model/VpcPeeringConnectionStateReasonCode", "PendingAcceptance", conv_val.Value())
	if err != nil {
		panic(err)
	}
	conv_val.CleanUp()

}

func (jbobject *ServicesEc2ModelVpcPeeringConnectionStateReasonCode) Active() *ServicesEc2ModelVpcPeeringConnectionStateReasonCode {
	jret, err := javabind.GetEnv().GetStaticField("com/amazonaws/services/ec2/model/VpcPeeringConnectionStateReasonCode", "Active", "com/amazonaws/services/ec2/model/VpcPeeringConnectionStateReasonCode")
	if err != nil {
		panic(err)
	}
	retconv := javabind.NewJavaToGoCallable()
	dst := &javabind.Callable{}
	retconv.Dest(dst)
	if err := retconv.Convert(javabind.ObjectRef(jret)); err != nil {
		panic(err)
	}
	retconv.CleanUp()
	unique_x := &ServicesEc2ModelVpcPeeringConnectionStateReasonCode{}
	unique_x.Callable = dst
	return unique_x
}

func (jbobject *ServicesEc2ModelVpcPeeringConnectionStateReasonCode) SetFieldActive(val ServicesEc2ModelVpcPeeringConnectionStateReasonCodeInterface) {
	conv_val := javabind.NewGoToJavaCallable()
	if err := conv_val.Convert(val); err != nil {
		panic(err)
	}
	err := javabind.GetEnv().SetStaticField("com/amazonaws/services/ec2/model/VpcPeeringConnectionStateReasonCode", "Active", conv_val.Value())
	if err != nil {
		panic(err)
	}
	conv_val.CleanUp()

}

func (jbobject *ServicesEc2ModelVpcPeeringConnectionStateReasonCode) Deleted() *ServicesEc2ModelVpcPeeringConnectionStateReasonCode {
	jret, err := javabind.GetEnv().GetStaticField("com/amazonaws/services/ec2/model/VpcPeeringConnectionStateReasonCode", "Deleted", "com/amazonaws/services/ec2/model/VpcPeeringConnectionStateReasonCode")
	if err != nil {
		panic(err)
	}
	retconv := javabind.NewJavaToGoCallable()
	dst := &javabind.Callable{}
	retconv.Dest(dst)
	if err := retconv.Convert(javabind.ObjectRef(jret)); err != nil {
		panic(err)
	}
	retconv.CleanUp()
	unique_x := &ServicesEc2ModelVpcPeeringConnectionStateReasonCode{}
	unique_x.Callable = dst
	return unique_x
}

func (jbobject *ServicesEc2ModelVpcPeeringConnectionStateReasonCode) SetFieldDeleted(val ServicesEc2ModelVpcPeeringConnectionStateReasonCodeInterface) {
	conv_val := javabind.NewGoToJavaCallable()
	if err := conv_val.Convert(val); err != nil {
		panic(err)
	}
	err := javabind.GetEnv().SetStaticField("com/amazonaws/services/ec2/model/VpcPeeringConnectionStateReasonCode", "Deleted", conv_val.Value())
	if err != nil {
		panic(err)
	}
	conv_val.CleanUp()

}

func (jbobject *ServicesEc2ModelVpcPeeringConnectionStateReasonCode) Rejected() *ServicesEc2ModelVpcPeeringConnectionStateReasonCode {
	jret, err := javabind.GetEnv().GetStaticField("com/amazonaws/services/ec2/model/VpcPeeringConnectionStateReasonCode", "Rejected", "com/amazonaws/services/ec2/model/VpcPeeringConnectionStateReasonCode")
	if err != nil {
		panic(err)
	}
	retconv := javabind.NewJavaToGoCallable()
	dst := &javabind.Callable{}
	retconv.Dest(dst)
	if err := retconv.Convert(javabind.ObjectRef(jret)); err != nil {
		panic(err)
	}
	retconv.CleanUp()
	unique_x := &ServicesEc2ModelVpcPeeringConnectionStateReasonCode{}
	unique_x.Callable = dst
	return unique_x
}

func (jbobject *ServicesEc2ModelVpcPeeringConnectionStateReasonCode) SetFieldRejected(val ServicesEc2ModelVpcPeeringConnectionStateReasonCodeInterface) {
	conv_val := javabind.NewGoToJavaCallable()
	if err := conv_val.Convert(val); err != nil {
		panic(err)
	}
	err := javabind.GetEnv().SetStaticField("com/amazonaws/services/ec2/model/VpcPeeringConnectionStateReasonCode", "Rejected", conv_val.Value())
	if err != nil {
		panic(err)
	}
	conv_val.CleanUp()

}

func (jbobject *ServicesEc2ModelVpcPeeringConnectionStateReasonCode) Failed() *ServicesEc2ModelVpcPeeringConnectionStateReasonCode {
	jret, err := javabind.GetEnv().GetStaticField("com/amazonaws/services/ec2/model/VpcPeeringConnectionStateReasonCode", "Failed", "com/amazonaws/services/ec2/model/VpcPeeringConnectionStateReasonCode")
	if err != nil {
		panic(err)
	}
	retconv := javabind.NewJavaToGoCallable()
	dst := &javabind.Callable{}
	retconv.Dest(dst)
	if err := retconv.Convert(javabind.ObjectRef(jret)); err != nil {
		panic(err)
	}
	retconv.CleanUp()
	unique_x := &ServicesEc2ModelVpcPeeringConnectionStateReasonCode{}
	unique_x.Callable = dst
	return unique_x
}

func (jbobject *ServicesEc2ModelVpcPeeringConnectionStateReasonCode) SetFieldFailed(val ServicesEc2ModelVpcPeeringConnectionStateReasonCodeInterface) {
	conv_val := javabind.NewGoToJavaCallable()
	if err := conv_val.Convert(val); err != nil {
		panic(err)
	}
	err := javabind.GetEnv().SetStaticField("com/amazonaws/services/ec2/model/VpcPeeringConnectionStateReasonCode", "Failed", conv_val.Value())
	if err != nil {
		panic(err)
	}
	conv_val.CleanUp()

}

func (jbobject *ServicesEc2ModelVpcPeeringConnectionStateReasonCode) Expired() *ServicesEc2ModelVpcPeeringConnectionStateReasonCode {
	jret, err := javabind.GetEnv().GetStaticField("com/amazonaws/services/ec2/model/VpcPeeringConnectionStateReasonCode", "Expired", "com/amazonaws/services/ec2/model/VpcPeeringConnectionStateReasonCode")
	if err != nil {
		panic(err)
	}
	retconv := javabind.NewJavaToGoCallable()
	dst := &javabind.Callable{}
	retconv.Dest(dst)
	if err := retconv.Convert(javabind.ObjectRef(jret)); err != nil {
		panic(err)
	}
	retconv.CleanUp()
	unique_x := &ServicesEc2ModelVpcPeeringConnectionStateReasonCode{}
	unique_x.Callable = dst
	return unique_x
}

func (jbobject *ServicesEc2ModelVpcPeeringConnectionStateReasonCode) SetFieldExpired(val ServicesEc2ModelVpcPeeringConnectionStateReasonCodeInterface) {
	conv_val := javabind.NewGoToJavaCallable()
	if err := conv_val.Convert(val); err != nil {
		panic(err)
	}
	err := javabind.GetEnv().SetStaticField("com/amazonaws/services/ec2/model/VpcPeeringConnectionStateReasonCode", "Expired", conv_val.Value())
	if err != nil {
		panic(err)
	}
	conv_val.CleanUp()

}

func (jbobject *ServicesEc2ModelVpcPeeringConnectionStateReasonCode) Provisioning() *ServicesEc2ModelVpcPeeringConnectionStateReasonCode {
	jret, err := javabind.GetEnv().GetStaticField("com/amazonaws/services/ec2/model/VpcPeeringConnectionStateReasonCode", "Provisioning", "com/amazonaws/services/ec2/model/VpcPeeringConnectionStateReasonCode")
	if err != nil {
		panic(err)
	}
	retconv := javabind.NewJavaToGoCallable()
	dst := &javabind.Callable{}
	retconv.Dest(dst)
	if err := retconv.Convert(javabind.ObjectRef(jret)); err != nil {
		panic(err)
	}
	retconv.CleanUp()
	unique_x := &ServicesEc2ModelVpcPeeringConnectionStateReasonCode{}
	unique_x.Callable = dst
	return unique_x
}

func (jbobject *ServicesEc2ModelVpcPeeringConnectionStateReasonCode) SetFieldProvisioning(val ServicesEc2ModelVpcPeeringConnectionStateReasonCodeInterface) {
	conv_val := javabind.NewGoToJavaCallable()
	if err := conv_val.Convert(val); err != nil {
		panic(err)
	}
	err := javabind.GetEnv().SetStaticField("com/amazonaws/services/ec2/model/VpcPeeringConnectionStateReasonCode", "Provisioning", conv_val.Value())
	if err != nil {
		panic(err)
	}
	conv_val.CleanUp()

}

func (jbobject *ServicesEc2ModelVpcPeeringConnectionStateReasonCode) Deleting() *ServicesEc2ModelVpcPeeringConnectionStateReasonCode {
	jret, err := javabind.GetEnv().GetStaticField("com/amazonaws/services/ec2/model/VpcPeeringConnectionStateReasonCode", "Deleting", "com/amazonaws/services/ec2/model/VpcPeeringConnectionStateReasonCode")
	if err != nil {
		panic(err)
	}
	retconv := javabind.NewJavaToGoCallable()
	dst := &javabind.Callable{}
	retconv.Dest(dst)
	if err := retconv.Convert(javabind.ObjectRef(jret)); err != nil {
		panic(err)
	}
	retconv.CleanUp()
	unique_x := &ServicesEc2ModelVpcPeeringConnectionStateReasonCode{}
	unique_x.Callable = dst
	return unique_x
}

func (jbobject *ServicesEc2ModelVpcPeeringConnectionStateReasonCode) SetFieldDeleting(val ServicesEc2ModelVpcPeeringConnectionStateReasonCodeInterface) {
	conv_val := javabind.NewGoToJavaCallable()
	if err := conv_val.Convert(val); err != nil {
		panic(err)
	}
	err := javabind.GetEnv().SetStaticField("com/amazonaws/services/ec2/model/VpcPeeringConnectionStateReasonCode", "Deleting", conv_val.Value())
	if err != nil {
		panic(err)
	}
	conv_val.CleanUp()

}


text:
package edu.gemini.catalog.api

import edu.gemini.spModel.core.{MagnitudeBand, Coordinates, SiderealTarget}

import scalaz._
import Scalaz._

trait QueryResultsFilter {
  def filter(t: SiderealTarget): Boolean
}

case class RadiusFilter(base: Coordinates, rc: RadiusConstraint) extends QueryResultsFilter {
  def filter(t: SiderealTarget): Boolean = rc.targetsFilter(base)(t)
}

case class MagnitudeQueryFilter(mc: MagnitudeConstraints) extends QueryResultsFilter {
  def filter(t: SiderealTarget): Boolean = mc.filter(t)
}

sealed abstract class CatalogName(val id: String, val displayName: String) {
  def supportedBands: List[MagnitudeBand] = Nil
  // Indicates what is the band used when a generic R band is requried
  def rBand: MagnitudeBand = MagnitudeBand.UC
}

case object SDSS extends CatalogName("sdss9", "SDSS9 @ Gemini")
case object GSC234 extends CatalogName("gsc234", "GSC234 @ Gemini")
case object PPMXL extends CatalogName("ppmxl", "PPMXL @ Gemini") {
  override val supportedBands = List(MagnitudeBand.B, MagnitudeBand.R, MagnitudeBand.I, MagnitudeBand.J, MagnitudeBand.H, MagnitudeBand.K)
  override val rBand: MagnitudeBand = MagnitudeBand.R
}
case object UCAC4 extends CatalogName("ucac4", "UCAC4 @ Gemini") {
  override val  supportedBands = List(MagnitudeBand._g, MagnitudeBand._r, MagnitudeBand._i, MagnitudeBand.B, MagnitudeBand.V, MagnitudeBand.UC, MagnitudeBand.J, MagnitudeBand.H, MagnitudeBand.K)
}
case object TWOMASS_PSC extends CatalogName("twomass_psc", "TwoMass PSC @ Gemini")
case object TWOMASS_XSC extends CatalogName("twomass_xsc", "TwoMass XSC @ Gemini")
case object SIMBAD extends CatalogName("simbad", "Simbad")

object CatalogName {
  implicit val equals = Equal.equal[CatalogName]((a, b) => a.id === b.id)

}

/**
 * Represents a query on a catalog
 */
sealed trait CatalogQuery {
  val id: Option[Int]
  val catalog: CatalogName

  def filter(t: SiderealTarget):Boolean
  def isSuperSetOf(c: CatalogQuery):Boolean
}

/**
 * CatalogQuery using the ConeSearch method with additional constraints on radius and magnitude
 */
case class ConeSearchCatalogQuery(id: Option[Int], base: Coordinates, radiusConstraint: RadiusConstraint, magnitudeConstraints: List[MagnitudeConstraints], catalog: CatalogName) extends CatalogQuery {

  val filters: NonEmptyList[QueryResultsFilter] = NonEmptyList(RadiusFilter(base, radiusConstraint), magnitudeConstraints.map(MagnitudeQueryFilter.apply): _*)
  override def filter(t: SiderealTarget):Boolean = filters.list.forall(_.filter(t))

  override def isSuperSetOf(q: CatalogQuery) = q match {
    case c: ConeSearchCatalogQuery =>

      // Angular separation, or distance between the two.
      val distance = Coordinates.difference(base, c.base).distance

      // Add the given query's outer radius limit to the distance to get the
      // maximum distance from this base position of any potential guide star.
      val max = distance + c.radiusConstraint.maxLimit

      // See whether the other base position falls out of range of our
      // radius limits.
      radiusConstraint.maxLimit >= max && q.catalog === catalog
    case _ => false
  }
}

object ConeSearchCatalogQuery {
  implicit val equals = Equal.equalA[ConeSearchCatalogQuery]
}

/**
 * Name based query, typically without filtering
 */
case class NameCatalogQuery(search: String, catalog: CatalogName) extends CatalogQuery {
  override val id: Option[Int] = None
  def filter(t: SiderealTarget) = true
  def isSuperSetOf(c: CatalogQuery) = false
}

object CatalogQuery {
  // Useful constructors
  def apply(id: Int, base: Coordinates, radiusConstraint: RadiusConstraint, magnitudeConstraints: List[MagnitudeConstraints], catalog: CatalogName):CatalogQuery = ConeSearchCatalogQuery(id.some, base, radiusConstraint, magnitudeConstraints, catalog)

  def apply(base: Coordinates, radiusConstraint: RadiusConstraint, magnitudeConstraints: List[MagnitudeConstraints], catalog: CatalogName):CatalogQuery = ConeSearchCatalogQuery(None, base, radiusConstraint, magnitudeConstraints, catalog)

  def apply(base: Coordinates, radiusConstraint: RadiusConstraint, magnitudeConstraints: MagnitudeConstraints, catalog: CatalogName):CatalogQuery = ConeSearchCatalogQuery(None, base, radiusConstraint, List(magnitudeConstraints), catalog)

  def apply(base: Coordinates, radiusConstraint: RadiusConstraint, catalog: CatalogName):CatalogQuery = ConeSearchCatalogQuery(None, base, radiusConstraint, Nil, catalog)

  def apply(search: String):CatalogQuery = NameCatalogQuery(search, SIMBAD)

  implicit val equals = Equal.equalA[CatalogQuery]
}

redpajama_set_name: RedPajamaGithub


text:
package com.ibm.profiler.mongo;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.Map.Entry;

import org.bson.BsonArray;
import org.bson.BsonDocument;
import org.bson.BsonString;
import org.bson.BsonValue;
import org.bson.conversions.Bson;

import com.ibm.commerce.cache.CacheUtilities;
import com.ibm.commerce.cache.OperationMetric;
import com.ibm.logger.PerformanceLogger;
import com.mongodb.MongoClient;
import com.mongodb.client.model.IndexModel;

/**
 * MongoUtilities
 *
 * @author Steve McDuff
 */
public class MongoUtilities
{

    public static final String MONGO_ALL_OPERATIONS = "Mongo : All operations";

    public MongoUtilities()
    {
        super();
    }

    private static BsonString QUESTION_MARK_BSON = new BsonString("?");

    private static BsonString MULTIPLE_QUESTION_MARK_BSON = new BsonString("*?");

    public static List<BsonDocument> filterParameters(List<? extends Bson> documentListToFilter)
    {
        List<BsonDocument> returnValue = new ArrayList<BsonDocument>();

        for (Bson bsonDocument : documentListToFilter)
        {
            BsonDocument bsonDoc = bsonDocument.toBsonDocument(BsonDocument.class,
                MongoClient.getDefaultCodecRegistry());
            returnValue.add(filterParameters(bsonDoc));
        }

        return returnValue;
    }

    public static BsonDocument filterParameters(BsonDocument documentToFilter)
    {
        BsonDocument returnValue = documentToFilter.clone();

        Set<Entry<String, BsonValue>> entrySet = returnValue.entrySet();
        for (Entry<String, BsonValue> entry : entrySet)
        {

            String key = entry.getKey();
            BsonValue value = entry.getValue();
            if (isParameterlessOperationName(key))
            {
                // nothing to do.
            }
            else if (isArrayOperationName(key) && value instanceof BsonArray)
            {
                BsonArray bsonArray = new BsonArray();
                bsonArray.add(MULTIPLE_QUESTION_MARK_BSON);
                entry.setValue(bsonArray);
            }
            else
            {
                entry.setValue(filterValue(value));
            }
        }

        return returnValue;
    }

    private static boolean isParameterlessOperationName(String key)
    {
        return "$lookup".equalsIgnoreCase(key) || "$group".equalsIgnoreCase(key);
    }

    private static boolean isArrayOperationName(String key)
    {
        return "$in".equalsIgnoreCase(key) || "$nin".equalsIgnoreCase(key) || "$all".equalsIgnoreCase(key);
    }

    public static BsonValue filterValue(BsonValue value)
    {
        BsonValue returnedValue = QUESTION_MARK_BSON;
        if (value instanceof BsonDocument)
        {
            returnedValue = filterParameters((BsonDocument) value);
        }
        else if (value instanceof BsonArray)
        {
            BsonArray array = (BsonArray) value;
            array = array.clone();
            returnedValue = array;
            int length = array.size();
            for (int i = 0; i < length; ++i)
            {
                BsonValue bsonValue = array.get(i);
                array.set(i, filterValue(bsonValue));
            }
        }
        return returnedValue;
    }

    public static List<String> getKeyValuePairs(Bson document)
    {
        List<String> values = new ArrayList<String>();
        addKeyValuePairs(document, values);

        return values;
    }

    public static List<String> getKeyValuePairs(List<? extends Bson> arg0)
    {
        List<String> values = new ArrayList<String>();

        for (Bson bson : arg0)
        {
            addKeyValuePairs(bson, values);

        }

        return values;
    }

    public static void addKeyValuePairs(Bson document, List<String> values)
    {
        if (document != null)
        {
            BsonDocument bsonDocument = document.toBsonDocument(BsonDocument.class,
                MongoClient.getDefaultCodecRegistry());

            addKeyValuePairs(values, bsonDocument);
        }
    }

    private static void addKeyValuePairs(List<String> values, BsonDocument bsonDocument)
    {
        Set<Entry<String, BsonValue>> entrySet = bsonDocument.entrySet();
        for (Entry<String, BsonValue> entry : entrySet)
        {
            values.add(CacheUtilities.safeToString(entry.getKey()));
            values.add(CacheUtilities.safeToString(entry.getValue()));
        }
    }

    public static BsonDocument filterParameters(Bson filter)
    {
        BsonDocument bsonDocument = filter.toBsonDocument(BsonDocument.class, MongoClient.getDefaultCodecRegistry());
        return filterParameters(bsonDocument);
    }

    public static List<String> getIndexModelKeyValuePairs(List<IndexModel> arg0)
    {
        List<String> retVal = new ArrayList<String>();
        for (IndexModel indexModel : arg0)
        {
            retVal.add(indexModel.getKeys().toString());
        }
        return retVal;
    }

    public static void incrementMongoStats(OperationMetric metric)
    {
        String oldName = metric.getOperationName();
        metric.setOperationName(MONGO_ALL_OPERATIONS);
        PerformanceLogger.increase(metric);
        metric.setOperationName(oldName);
    }
}


text:
<!DOCTYPE html>

<meta charset="utf-8">

<svg width="960" height="960"><g transform="translate(1,1)"></g></svg>


text:
'use strict';

//
// Required modules.
//
var ObjectID = require('mongodb').ObjectID
  , backbone = require('backbone')
  , predefine = require('./predefine')
  , Defer = require('./defer');

/**
 * Setup a default model definition for fossa.
 *
 * @param {Fossa} fossa instance
 * @api public
 */
module.exports = function model(fossa) {
  return backbone.Model.extend({
    /**
     * @type {String} proxy id attribute to MongoDB internal `_id`
     * @api private
     */
    idAttribute: '_id',

    /**
     * Override default Model Constructor.
     *
     * @Constructor
     * @param {Object} attributes
     * @param {Object} options
     * @api public
     */
    constructor: function constructor(attributes, options) {
      var hooks = []
        , local = {};

      options = options || {};

      //
      // Set the database name and/or urlRoot if provided in the options.
      //
      if (options.database) this.database = options.database;
      if (options.urlRoot) this.urlRoot = options.urlRoot;

      //
      // Copy attributes to a new object and provide a MongoDB OfbjectID.
      //
      attributes = attributes || {};
      for (var key in attributes) local[key] = attributes[key];

      //
      // If the provided `_id` is an ObjectID assume the model is stored.
      // If it is not an ObjectID, remove it from the provided data.
      // MongoDB will provide an ObjectID by default.
      //
      if ('_id' in local) try {
        local._id = new ObjectID(local._id);
      } catch (error) { delete local._id; }

      //
      // Define restricted non-enumerated properties.
      //
      predefine(this, fossa);

      //
      // Check for presence of before/after hooks and setup.
      //
      if (this.before) hooks.push('before');
      if (this.after) hooks.push('after');
      this.setup(hooks);

      //
      // Call original Backbone Model constructor.
      //
      backbone.Model.call(this, local, options);
    },

    /**
     * Clone this Model.
     *
     * @returns {Model}
     * @api public
     */
    clone: function clone() {
      return new this.constructor(this.attributes, {
        urlRoot: this.urlRoot,
        database: this.database
      });
    },

    /**
     * Update the internal ObjectId reference.
     *
     * @param {ObjectId} id ObjectId reference in MongoDB
     * @returns {Model} fluent interface.
     * @api public
     */
    set stored(id) {
      this.id = this.attributes._id = id;
      return this;
    },

    /**
     * Is the Model stored in the database or not?
     *
     * @returns {Boolean}
     * @api public
     */
    get stored() {
      return !!this.id;
    },

    /**
     * Synchronize the model to MongoDB.
     *
     * @param {String} method CRUD
     * @param {Model} model reference to self
     * @param {Object} options Optional Backbone.JS and MongoDB options.
     * @param {Object} query Optional MongoDB query.
     * @returns {XHR} Promise style success and error callbacks.
     * @api public
     */
    sync: function sync(method, model, options, query) {
      //
      // Method and or model was not provided, set default arguments.
      // Additionally default to CREATE if the method is not a string.
      //
      if (!(model instanceof backbone.Model)) {
        if ('string' !== typeof method) {
          options = method;
          method = 'create';
        } else {
          options = model;
        }

        model = this;
      }

      //
      // If the model was stored before and has reference, use update.
      //
      if ('create' === method && model.id) method = 'update';
      return backbone.sync(method, model, options, query);
    },

    /**
     * Overrule the default save. Normally `save` returns `false` when validation
     * fails. However this does not match the Node.JS callback pattern.
     *
     * @return {Defer} Promise XHR object
     * @api public
     */
    save: function save() {
      var defer = new Defer
        , xhr = backbone.Model.prototype.save.apply(this, arguments);

      if (xhr) return xhr;
      defer.next(new Error('Could not validate model'));

      return defer;
    },

    /**
     * Altered check for isNew, since the id attribute is mapped to ObjectID.
     *
     * @returns {Boolean}
     * @api public
     */
    isNew: function isNew() {
      return !this.id;
    },

    /**
     * Override the default url functionality, MongoDB stores models in
     * instances named after the collections, not a combination of the
     * collection name and ObjectId.
     *
     * @returns {String} Collection reference.
     * @api public
       */
    url: function url() {
      return this.urlRoot;
    }
  });
};


text:
Originally published: 2011-07-15 21:19:16
Last updated: 2011-07-15 21:19:17
Author: Ben Hoyt

Function to get the user's IP address in a web app or CGI script, even when they're behind a web proxy.

We use web.py as our web framework, but change web.ctx.env and web.ctx.get('ip') to whatever the equivalents are for the CGI environment variables and REMOTE_ADDR are in your framework.


text:
weight: 40
title: "Version 6.1"
linkTitle: "6.1"
date: 2020-02-14
description: >
  Key new features and changes present in v6.1 of Stroom and Stroom-Proxy.
---

{{% pageinfo %}}
For a detailed list of the changes in v6.1 see the{{< external-link "changelog" "https://github.com/gchq/stroom/blob/6.1/CHANGELOG.md" >}}
{{% /pageinfo %}}

{{% todo %}}
Version 6.1 release notes need populating.
{{% /todo %}}


text:
<?xml version="1.0" encoding="utf-8" ?>
<DBRevisions xmlns="bb_appfx_dbrevisions">

  <DBRevision ID="5">
    <ExecuteSql>
      <![CDATA[
      select 'Initial revision';
      ]]>
    </ExecuteSql>
  </DBRevision>

  <!-- Template, update the ID -->
  <!--<DBRevision ID="5">
    <ExecuteSql>
      <![CDATA[
      ]]>
    </ExecuteSql>
  </DBRevision>-->
</DBRevisions>


text: execute 'apt-get update' if platform_family?('debian')


text:
<title>Welcome to apex!</title>

Welcome to apex!


text:
class CreateTeams < ActiveRecord::Migration[5.1]
  def change
    create_table :teams do |t|
      t.string :name
      t.string :app_host
      t.timestamps null: false
    end
  end
end


text:
Regression
==========

.. index:: regression

Regression in Orange is from the interface very similar to classification. These both require class-labeled data. Just like in classification, regression is implemented with learners and regression models (regressors). Regression learners are objects that accept data and return regressors. Regression models are given data items to predict the value of continuous class:

.. literalinclude:: code/regression.py

Handful of Regressors
---------------------

.. index::
   single: regression; tree

Let us start with regression trees. Below is an example script that builds the tree from data on housing prices and prints out the tree in textual form:

.. literalinclude:: code/regression-tree.py
   :lines: 3-

The script outputs the tree::

   RM<=6.941: 19.9
   RM>6.941
   |    RM<=7.437
   |    |    CRIM>7.393: 14.4
   |    |    CRIM<=7.393
   |    |    |    DIS<=1.886: 45.7
   |    |    |    DIS>1.886: 32.7
   |    RM>7.437
   |    |    TAX<=534.500: 45.9
   |    |    TAX>534.500: 21.9

Following is initialization of few other regressors and their prediction of the first five data instances in housing price data set:

.. index::
   single: regression; linear

.. literalinclude:: code/regression-other.py
   :lines: 3-

Looks like the housing prices are not that hard to predict::

      y    linreg    rf ridge
      22.2   19.3  21.8  19.5
      31.6   33.2  26.5  33.2
      21.7   20.9  17.0  21.0
      10.2   16.9  14.3  16.8
      14.0   13.6  14.9  13.5

Cross Validation
----------------

Evaluation and scoring methods are available at ``Orange.evaluation``:

.. literalinclude:: code/regression-cv.py
   :lines: 3-

.. index:
   single: regression; root mean squared error

.. index:
   single: regression; R2

We have scored the regression two measures for goodnes of fit: `root-mean-square error <https://en.wikipedia.org/wiki/Root-mean-square_deviation>`_ and `coefficient of determination <https://en.wikipedia.org/wiki/Coefficient_of_determination>`_, or R squared. Random forest has the lowest root mean squared error::

      Learner  RMSE  R2
      linreg   4.88  0.72
      rf       4.70  0.74
      ridge    4.91  0.71
      mean     9.20 -0.00

Not much difference here. Each regression method has a set of parameters. We have been running them with default parameters, and parameter fitting would help. Also, we have included ``MeanLearner`` in a list of our regression; this regressors simply predicts the mean value from the training set, and is used as a baseline.


text:
/*

NOTES
 * Style node must be added to the head element.  Safari does not honor styles
   applied to StyleSheet objects on style nodes in the body.
 * StyleSheet object is created on the style node when the style node is added
   to the head element in Firefox 2 (and maybe 3?)
 * The cssRules collection is replaced after insertRule/deleteRule calls in
   Safari 3.1.  Existing Rules are used in the new collection, so the collection
   cannot be cached, but the rules can be.
 * Opera requires that the index be passed with insertRule.
 * Same-domain restrictions prevent modifying StyleSheet objects attached to
   link elements with remote href (or "about:blank" or "javascript:false")
 * IE names StyleSheet related properties and methods differently (see code)
 * IE converts tag names to upper case in the Rule's selectorText
 * IE converts empty string assignment to complex properties to value settings
   for all child properties.  E.g. style.background = '' sets non-'' values on
   style.backgroundPosition, style.backgroundColor, etc.  All else clear
   style.background and all child properties.
 * IE assignment style.filter = '' will result in style.cssText == 'FILTER:'
 * All browsers support Rule.style.cssText as a read/write property, leaving
   only opacity needing to be accounted for.
 * Benchmarks of style.property = value vs style.cssText += 'property: value'
   indicate cssText is slightly slower for single property assignment.  For
   multiple property assignment, cssText speed stays relatively the same where
   style.property speed decreases linearly by the number of properties set.
   Exception being Opera 9.27, where style.property is always faster than
   style.cssText.
 * Opera 9.5b throws a syntax error when assigning cssText with a syntax error.
 * Stylesheet properties set with !important will trump inline style set on an
   element or in el.style.property.
*/

(function () {

YAHOO.util.StyleSheet = function (node) {
    var head,
        sheet,
        cssRules = {},
        _rules,
        _insertRule,
        _deleteRule;

    head = document.getElementsByTagName('head')[0];
    if (!head) {
        // TODO: do something. Preferably something smart
        YAHOO.log('HEAD element not found to append STYLE node','error','YAHOO.util.StyleSheet');
        throw new Error('HEAD element not found to append STYLE node');
    }

    // If an id or style node is provided, use that node
    // Us of link elements is still subject to same-domain restrictions
    node = node && YAHOO.util.Dom.get(node);

    // Otherwise, create a style node and append to head
    if (!node || node.parentNode !== head && (!node.sheet && !node.styleSheet)) {
        // Generate the style node
        node = document.createElement('style');
        node.type = 'text/css';

        // styleSheet isn't available on the style node in FF2 until appended
        // to the head element.  style nodes appended to body do not affect
        // change in Safari.
        head.appendChild(node);
    }

    // IE stores StyleSheet under the "styleSheet" property
    sheet = node.sheet || node.styleSheet;

    // IE stores the rules collection under the "rules" property
    _rules = ('cssRules' in sheet) ? 'cssRules' : 'rules';

    // IE supports removeRule
    _deleteRule = ('deleteRule' in sheet) ?
        function (i) { sheet.deleteRule(i); } :
        function (i) { sheet.removeRule(i); };

    // IE supports addRule with different signature
    _insertRule = ('insertRule' in sheet) ?
        function (sel,cssText,i) { sheet.insertRule(sel+' '+cssText,i); } :
        function (sel,cssText,i) { sheet.addRule(sel,cssText,i); };

    // Initialize the cssRules map from the node
    var i,r,sel;
    for (i = sheet[_rules].length - 1; i >= 0; --i) {
        r   = sheet[_rules][i];
        sel = r.selectorText;

        if (cssRules[sel]) {
            cssRules[sel].style.cssText += ';' + r.style.cssText;
            _deleteRule(i);
        } else {
            cssRules[sel] = r;
        }
    }

    YAHOO.lang.augmentObject(this,{
        // Enabling/disabling the stylesheet.  Changes may be made to rules
        // while disabled.
        enable : function () { sheet.disabled = false; },

        disable : function () { sheet.disabled = true; },

        isEnabled : function () { return !sheet.disabled; },

        // Normalize opacity assignment and clearing
        setOpacity : (('opacity' in node.style) ?
            function (sel,op) { this.setCSS(sel,'opacity:'+op); } :
            function (sel,op) {
                this.setCSS(sel,'filter: alpha(opacity='+(op*100)+')');
            }),

        unsetOpacity : (('opacity' in node.style) ?
            function (sel) { this.unsetCSS(sel,'opacity'); } :
            function (sel) { this.unsetCSS(sel,'filter'); }),

        // Update cssText for a rule.  Add the rule if it's not present already
        setCSS : function (sel,cssText) {
            var rule = cssRules[sel];

            // Opera throws an error if there's a syntax error in the cssText.
            // Should I do something about it, or let the error happen?
            if (rule) {
                rule.style.cssText += ';'+cssText;
            } else {
                var idx = sheet[_rules].length;
                _insertRule(sel,'{'+cssText+'}',idx);

                // Safari replaces the rules collection, but maintains the rule
                // instances in the new collection when rules are added/removed
                cssRules[sel] = sheet[_rules][idx];
            }
        },

        // remove rule properties or an entire rule
        unsetCSS : function (sel,props) {
            var rule = cssRules[sel],
                rules, i, tmpCssText;

            if (rule) {
                if (!props) { // remove the rule altogether
                    rules = sheet[_rules];
                    for (i = rules.length - 1; i >= 0; --i) {
                        if (rules[i] === rule) {
                            delete cssRules[sel];
                            _deleteRule(i);
                            break;
                        }
                    }
                    return;
                }

                if (!YAHOO.lang.isArray(props)) {
                    props = [props];
                }

                tmpCssText = rule.style.cssText;
                for (i = props.length - 1; i >= 0; --i) {
                    // regex strip properties and any subproperties (e.g. 'font'
                    // also strips line-height, font-weight, font-family etc)
                    tmpCssText = tmpCssText.replace(
                        YAHOO.util.StyleSheet._propertyRE(props[i]),'');
                }

                rule.style.cssText = tmpCssText;
            }
        }
    },true);

};

// Regex collection for unsetting rule properties.  Initialized with the
// properties that have child properties.  Added to from _propertyRE(prop).
YAHOO.util.StyleSheet.PROP_REGEX = {
    'border' : /border(?:-(?:(?:top|right|bottom|left)(?:-(?:color|style|width))?|(?:color|style|width)))?\s*:[^;]*(?:;|$)/gi,
    'font' : /(?:font(?:-(?:size|family|style|variant|weight))?|line-height)\s*:[^;]*(?:;|$)/gi
};

// Memoized regex generator to remove properties from cssText
YAHOO.util.StyleSheet._propertyRE = function (prop) {
    return this.PROP_REGEX[prop] ||
          (this.PROP_REGEX[prop] = new RegExp(prop+'(?:-[a-z\\-]+)?\\s*:[^;]*(?:;|$)','gi'));
};

})();
YAHOO.register("stylesheet", YAHOO.util.Stylesheet, {version: "2.6.0", build: "1321"});


text:
    <md-content>
        <md-card ng-controller="EventsController">
            <md-card-content>

Last event: {{ (lastEvent | date:'yyyy-MM-dd HH:mm:ss') || "Unknown" }}  Type: {{ eventType || 'Unknown' }}

 {{ AssignedDate.now() | date:'yyyy-MM-dd HH:mm:ss' }}   {{ timeZone || 'unknown timezone' }}

                <md-button class="md-raised md-primary" ng-click="clockEvent()">{{ btnText || "Clock In" }}</md-button>
            </md-card-content>
        </md-card>
    </md-content>


text:
<?php

namespace Wind\Http\Controllers;

use Auth;
use JWTAuth;
use Illuminate\Http\Request;
// use Tymon\JWTAuth\JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;

/**
 * 登录控制器.
 *
 * @author scl <scl@winhu.com>
 */
class LoginController extends BaseController
{
    // private $auth;

    public function __construct()
    {
        // $this->auth = $auth;
    }

    /**
     * 用户登录.
     *
     * @param Request $request [description]
     *
     * @return [type] [description]
     */
    public function login(Request $request)
    {
        // grab credentials from the request
        $credentials = $request->only('phone', 'password');

        try {
            // attempt to verify the credentials and create a token for the user
            $token = JWTAuth::attempt($credentials);

            if (!$token) {
                return response_json(0, 'phone或者password有误', '登录失败');
            }
        } catch (JWTException $e) {
            // something went wrong whilst attempting to encode the token
            return response_json(0, '创建TOKEN失败', '登录失败');
        }

        // all good so return the token
        return response_json(1, $token, '登录成功');
    }

    /**
     * 用户注销登录.
     *
     * @param Request $request [description]
     *
     * @return [type] [description]
     */
    public function logout(Request $request)
    {
        $user = $request->user();

        return response_json(1, $user, '注销成功');
    }
}


text:
using System;
using System.Net;
using System.Net.Sockets;
using System.Web;
using Castle.Core.Logging;

namespace Abp.Auditing
{
    public class WebClientInfoProvider : IClientInfoProvider
    {
        public string BrowserInfo => GetBrowserInfo();

        public string ClientIpAddress => GetClientIpAddress();

        public string ComputerName => GetComputerName();

        public ILogger Logger { get; set; }

        private readonly HttpContext _httpContext;

        /// <summary>
        /// Creates a new <see cref="WebClientInfoProvider"/>.
        /// </summary>
        public WebClientInfoProvider()
        {
            _httpContext = HttpContext.Current;
            Logger = NullLogger.Instance;
        }

        protected virtual string GetBrowserInfo()
        {
            var httpContext = HttpContext.Current ?? _httpContext;
            if (httpContext?.Request.Browser == null)
            {
                return null;
            }

            return httpContext.Request.Browser.Browser + " / " +
                   httpContext.Request.Browser.Version + " / " +
                   httpContext.Request.Browser.Platform;
        }

        protected virtual string GetClientIpAddress()
        {
            var httpContext = HttpContext.Current ?? _httpContext;
            if (httpContext?.Request.ServerVariables == null)
            {
                return null;
            }

            var clientIp = httpContext.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] ??
                           httpContext.Request.ServerVariables["REMOTE_ADDR"];

            try
            {
                foreach (var hostAddress in Dns.GetHostAddresses(clientIp))
                {
                    if (hostAddress.AddressFamily == AddressFamily.InterNetwork)
                    {
                        return hostAddress.ToString();
                    }
                }

                foreach (var hostAddress in Dns.GetHostAddresses(Dns.GetHostName()))
                {
                    if (hostAddress.AddressFamily == AddressFamily.InterNetwork)
                    {
                        return hostAddress.ToString();
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Debug(ex.ToString());
            }

            return clientIp;
        }

        protected virtual string GetComputerName()
        {
            var httpContext = HttpContext.Current ?? _httpContext;
            if (httpContext == null || !httpContext.Request.IsLocal)
            {
                return null;
            }

            try
            {
                var clientIp = httpContext.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] ??
                               httpContext.Request.ServerVariables["REMOTE_ADDR"];
                return Dns.GetHostEntry(IPAddress.Parse(clientIp)).HostName;
            }
            catch
            {
                return null;
            }
        }
    }
}


text:
@implementation ILA_MasteryDto

@end


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">NinOne</string>
    <string name="guess">猜数字游戏</string>
    <string name="Rank">排行榜</string>
    <string name="action_settings">Settings</string>
    <string name="input">请猜数字:</string>
    <string name="begin">确定</string>
    <string name="hint">请输入四位数字</string>
    <string name="cont">继续</string>
    <string name="quit">退出</string>
    <string name="rank">排行</string>
    <string name="rett">返回</string>

</resources>


text:
AsteroidField::AsteroidField(SolidObject asteroidTemplate, sf::IntRect area){
    int numberOfAsteroids = _density * ((area.width/1000) * (area.height/1000));
    for(int i = 0 ; i < numberOfAsteroids ; ++i){
        SolidObject * pAst = new SolidObject;
        *pAst = asteroidTemplate;
        bool cont = true;
        unsigned int seed = (unsigned)time(0);
        while(cont){
            int posX =  getRandomIntInRange(area.left, area.left + area.width);
            int posY = getRandomIntInRange(area.top, area.top + area.height);
            seed = posX;
            pAst->setPosition(posX, posY);
            cont = false;
            for(i = 0 ; i < SolidObject::ObList.size() ; ++i){
                if( pAst->getSprite().getGlobalBounds().intersects(SolidObject::ObList[i]->getSprite().getGlobalBounds() )){
                    cont  = true;
                    break;
                }
            }
        }
        SolidObject::ObList.push_back(pAst);
    }
}


text:
// Generated from /POI/java/org/apache/poi/hssf/eventusermodel/HSSFEventFactory.java
#include <org/apache/poi/hssf/eventusermodel/HSSFEventFactory.hpp>

#include <java/io/InputStream.hpp>
#include <java/io/Serializable.hpp>
#include <java/lang/ArrayStoreException.hpp>
#include <java/lang/CharSequence.hpp>
#include <java/lang/Comparable.hpp>
#include <java/lang/NullPointerException.hpp>
#include <java/lang/Object.hpp>
#include <java/lang/String.hpp>
#include <java/util/Set.hpp>
#include <org/apache/poi/hssf/eventusermodel/HSSFRequest.hpp>
#include <org/apache/poi/hssf/eventusermodel/HSSFUserException.hpp>
#include <org/apache/poi/hssf/model/InternalWorkbook.hpp>
#include <org/apache/poi/hssf/record/Record.hpp>
#include <org/apache/poi/hssf/record/RecordFactoryInputStream.hpp>
#include <org/apache/poi/poifs/filesystem/DirectoryNode.hpp>
#include <org/apache/poi/poifs/filesystem/DocumentInputStream.hpp>
#include <org/apache/poi/poifs/filesystem/POIFSFileSystem.hpp>
#include <SubArray.hpp>
#include <ObjectArray.hpp>

template<typename ComponentType, typename... Bases> struct SubArray;
namespace java
{
    namespace io
    {
typedef ::SubArray< ::java::io::Serializable, ::java::lang::ObjectArray > SerializableArray;
    } // io

    namespace lang
    {
typedef ::SubArray< ::java::lang::CharSequence, ObjectArray > CharSequenceArray;
typedef ::SubArray< ::java::lang::Comparable, ObjectArray > ComparableArray;
typedef ::SubArray< ::java::lang::String, ObjectArray, ::java::io::SerializableArray, ComparableArray, CharSequenceArray > StringArray;
    } // lang
} // java

template<typename T>
static T* npc(T* t)
{
    if(!t) throw new ::java::lang::NullPointerException();
    return t;
}

namespace
{
    template<typename F>
    struct finally_
    {
        finally_(F f) : f(f), moved(false) { }
        finally_(finally_ &&x) : f(x.f), moved(false) { x.moved = true; }
        ~finally_() { if(!moved) f(); }
    private:
        finally_(const finally_&); finally_& operator=(const finally_&);
        F f;
        bool moved;
    };

    template<typename F> finally_<F> finally(F f) { return finally_<F>(f); }
}
poi::hssf::eventusermodel::HSSFEventFactory::HSSFEventFactory(const ::default_init_tag&)
    : super(*static_cast< ::default_init_tag* >(0))
{
    clinit();
}

poi::hssf::eventusermodel::HSSFEventFactory::HSSFEventFactory()
    : HSSFEventFactory(*static_cast< ::default_init_tag* >(0))
{
    ctor();
}

void poi::hssf::eventusermodel::HSSFEventFactory::ctor()
{
    super::ctor();
}

void poi::hssf::eventusermodel::HSSFEventFactory::processWorkbookEvents(HSSFRequest* req, ::poi::poifs::filesystem::POIFSFileSystem* fs) /* throws(IOException) */
{
    processWorkbookEvents(req, npc(fs)->getRoot());
}

void poi::hssf::eventusermodel::HSSFEventFactory::processWorkbookEvents(HSSFRequest* req, ::poi::poifs::filesystem::DirectoryNode* dir) /* throws(IOException) */
{
    ::java::lang::String* name = nullptr;
    auto entryNames = npc(dir)->getEntryNames();
    for(auto potentialName : *npc(::poi::hssf::model::InternalWorkbook::WORKBOOK_DIR_ENTRY_NAMES())) {
        if(npc(entryNames)->contains(static_cast< ::java::lang::Object* >(potentialName))) {
            name = potentialName;
            break;
        }
    }
    if(name == nullptr) {
        name = (*::poi::hssf::model::InternalWorkbook::WORKBOOK_DIR_ENTRY_NAMES())[int32_t(0)];
    }
    ::java::io::InputStream* in = npc(dir)->createDocumentInputStream(name);
    {
        auto finally0 = finally([&] {
            npc(in)->close();
        });
        {
            processEvents(req, in);
        }
    }

}

int16_t poi::hssf::eventusermodel::HSSFEventFactory::abortableProcessWorkbookEvents(HSSFRequest* req, ::poi::poifs::filesystem::POIFSFileSystem* fs) /* throws(IOException, HSSFUserException) */
{
    return abortableProcessWorkbookEvents(req, npc(fs)->getRoot());
}

int16_t poi::hssf::eventusermodel::HSSFEventFactory::abortableProcessWorkbookEvents(HSSFRequest* req, ::poi::poifs::filesystem::DirectoryNode* dir) /* throws(IOException, HSSFUserException) */
{
    ::java::io::InputStream* in = npc(dir)->createDocumentInputStream(u"Workbook"_j);
    {
        auto finally1 = finally([&] {
            npc(in)->close();
        });
        {
            return abortableProcessEvents(req, in);
        }
    }

}

void poi::hssf::eventusermodel::HSSFEventFactory::processEvents(HSSFRequest* req, ::java::io::InputStream* in)
{
    try {
        genericProcessEvents(req, in);
    } catch (HSSFUserException* hue) {
    }
}

int16_t poi::hssf::eventusermodel::HSSFEventFactory::abortableProcessEvents(HSSFRequest* req, ::java::io::InputStream* in) /* throws(HSSFUserException) */
{
    return genericProcessEvents(req, in);
}

int16_t poi::hssf::eventusermodel::HSSFEventFactory::genericProcessEvents(HSSFRequest* req, ::java::io::InputStream* in) /* throws(HSSFUserException) */
{
    int16_t userCode = int32_t(0);
    auto recordStream = new ::poi::hssf::record::RecordFactoryInputStream(in, false);
    while (true) {
        auto r = npc(recordStream)->nextRecord();
        if(r == nullptr) {
            break;
        }
        userCode = npc(req)->processRecord(r);
        if(userCode != 0) {
            break;
        }
    }
    return userCode;
}

extern java::lang::Class *class_(const char16_t *c, int n);

java::lang::Class* poi::hssf::eventusermodel::HSSFEventFactory::class_()
{
    static ::java::lang::Class* c = ::class_(u"org.apache.poi.hssf.eventusermodel.HSSFEventFactory", 51);
    return c;
}

java::lang::Class* poi::hssf::eventusermodel::HSSFEventFactory::getClass0()
{
    return class_();
}


text:
import { createSelector } from 'reselect'
import { getProgress, isRequired } from 'react-saga-rest'

export const getTextState = code => (state) => {
  if (state.texts.list && state.texts.list[code]) {
    return state.texts.list[code]
  }
  return null
}

export const getText = code => createSelector(
  getTextState(code),
  (textState) => {
    if (textState && textState.data) {
      return textState.data
    }
    return []
  }
)

export const getTextProgress = (...codes) => getProgress(...codes.map(getTextState))

export const isTextRequired = code => isRequired(getTextState(code))


text: call ela-service-cli.bat -userdelete -userid 1


text:
package bufimagemodify

import (
	"context"
	"path/filepath"
	"testing"

	"github.com/bufbuild/buf/private/bufpkg/bufmodule/bufmoduleref"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"go.uber.org/zap"
)

const testJavaPackagePrefix = "com"

func TestJavaPackageError(t *testing.T) {
	t.Parallel()
	_, err := JavaPackage(zap.NewNop(), NewFileOptionSweeper(), "", nil, nil, nil)
	require.Error(t, err)
}

func TestJavaPackageEmptyOptions(t *testing.T) {
	t.Parallel()
	dirPath := filepath.Join("testdata", "emptyoptions")
	t.Run("with SourceCodeInfo", func(t *testing.T) {
		t.Parallel()
		image := testGetImage(t, dirPath, true)
		assertFileOptionSourceCodeInfoEmpty(t, image, javaPackagePath, true)

		sweeper := NewFileOptionSweeper()
		javaPackageModifier, err := JavaPackage(zap.NewNop(), sweeper, testJavaPackagePrefix, nil, nil, nil)
		require.NoError(t, err)

		modifier := NewMultiModifier(javaPackageModifier, ModifierFunc(sweeper.Sweep))
		err = modifier.Modify(
			context.Background(),
			image,
		)
		require.NoError(t, err)
		assert.Equal(t, testGetImage(t, dirPath, true), image)
	})

	t.Run("without SourceCodeInfo", func(t *testing.T) {
		t.Parallel()
		image := testGetImage(t, dirPath, false)
		assertFileOptionSourceCodeInfoEmpty(t, image, javaPackagePath, false)

		sweeper := NewFileOptionSweeper()
		modifier, err := JavaPackage(zap.NewNop(), sweeper, testJavaPackagePrefix, nil, nil, nil)
		require.NoError(t, err)
		err = modifier.Modify(
			context.Background(),
			image,
		)
		require.NoError(t, err)
		assert.Equal(t, testGetImage(t, dirPath, false), image)
	})

	t.Run("with SourceCodeInfo and per-file overrides", func(t *testing.T) {
		t.Parallel()
		image := testGetImage(t, dirPath, true)
		assertFileOptionSourceCodeInfoEmpty(t, image, javaPackagePath, true)

		sweeper := NewFileOptionSweeper()
		javaPackageModifier, err := JavaPackage(zap.NewNop(), sweeper, testJavaPackagePrefix, nil, nil, map[string]string{"a.proto": "override"})
		require.NoError(t, err)

		modifier := NewMultiModifier(javaPackageModifier, ModifierFunc(sweeper.Sweep))
		err = modifier.Modify(
			context.Background(),
			image,
		)
		require.NoError(t, err)
		require.Equal(t, 1, len(image.Files()))
		descriptor := image.Files()[0].Proto()
		assert.Equal(t, "override", descriptor.GetOptions().GetJavaPackage())
	})

	t.Run("without SourceCodeInfo", func(t *testing.T) {
		t.Parallel()
		image := testGetImage(t, dirPath, false)
		assertFileOptionSourceCodeInfoEmpty(t, image, javaPackagePath, false)

		sweeper := NewFileOptionSweeper()
		modifier, err := JavaPackage(zap.NewNop(), sweeper, testJavaPackagePrefix, nil, nil, map[string]string{"a.proto": "override"})
		require.NoError(t, err)
		err = modifier.Modify(
			context.Background(),
			image,
		)
		require.NoError(t, err)
		require.Equal(t, 1, len(image.Files()))
		descriptor := image.Files()[0].Proto()
		assert.Equal(t, "override", descriptor.GetOptions().GetJavaPackage())
	})
}

func TestJavaPackageAllOptions(t *testing.T) {
	t.Parallel()
	dirPath := filepath.Join("testdata", "alloptions")
	t.Run("with SourceCodeInfo", func(t *testing.T) {
		t.Parallel()
		image := testGetImage(t, dirPath, true)
		assertFileOptionSourceCodeInfoNotEmpty(t, image, javaPackagePath)

		sweeper := NewFileOptionSweeper()
		javaPackageModifier, err := JavaPackage(zap.NewNop(), sweeper, testJavaPackagePrefix, nil, nil, nil)
		require.NoError(t, err)

		modifier := NewMultiModifier(javaPackageModifier, ModifierFunc(sweeper.Sweep))
		err = modifier.Modify(
			context.Background(),
			image,
		)
		require.NoError(t, err)

		for _, imageFile := range image.Files() {
			descriptor := imageFile.Proto()
			assert.Equal(t, "foo", descriptor.GetOptions().GetJavaPackage())
		}
		assertFileOptionSourceCodeInfoNotEmpty(t, image, javaPackagePath)
	})

	t.Run("without SourceCodeInfo", func(t *testing.T) {
		t.Parallel()
		image := testGetImage(t, dirPath, false)
		assertFileOptionSourceCodeInfoEmpty(t, image, javaPackagePath, false)

		sweeper := NewFileOptionSweeper()
		modifier, err := JavaPackage(zap.NewNop(), sweeper, testJavaPackagePrefix, nil, nil, nil)
		require.NoError(t, err)
		err = modifier.Modify(
			context.Background(),
			image,
		)
		require.NoError(t, err)

		for _, imageFile := range image.Files() {
			descriptor := imageFile.Proto()
			assert.Equal(t, "foo", descriptor.GetOptions().GetJavaPackage())
		}
		assertFileOptionSourceCodeInfoEmpty(t, image, javaPackagePath, false)
	})

	t.Run("with SourceCodeInfo and per-file overrides", func(t *testing.T) {
		t.Parallel()
		image := testGetImage(t, dirPath, true)
		assertFileOptionSourceCodeInfoNotEmpty(t, image, javaPackagePath)

		sweeper := NewFileOptionSweeper()
		javaPackageModifier, err := JavaPackage(zap.NewNop(), sweeper, testJavaPackagePrefix, nil, nil, map[string]string{"a.proto": "override"})
		require.NoError(t, err)

		modifier := NewMultiModifier(javaPackageModifier, ModifierFunc(sweeper.Sweep))
		err = modifier.Modify(
			context.Background(),
			image,
		)
		require.NoError(t, err)

		for _, imageFile := range image.Files() {
			descriptor := imageFile.Proto()
			if imageFile.Path() == "a.proto" {
				assert.Equal(t, "override", descriptor.GetOptions().GetJavaPackage())
				continue
			}
			assert.Equal(t, "foo", descriptor.GetOptions().GetJavaPackage())
		}
		assertFileOptionSourceCodeInfoEmpty(t, image, javaPackagePath, true)
	})

	t.Run("without SourceCodeInfo and with per-file overrides", func(t *testing.T) {
		t.Parallel()
		image := testGetImage(t, dirPath, false)
		assertFileOptionSourceCodeInfoEmpty(t, image, javaPackagePath, false)

		sweeper := NewFileOptionSweeper()
		modifier, err := JavaPackage(zap.NewNop(), sweeper, testJavaPackagePrefix, nil, nil, map[string]string{"a.proto": "override"})
		require.NoError(t, err)
		err = modifier.Modify(
			context.Background(),
			image,
		)
		require.NoError(t, err)

		for _, imageFile := range image.Files() {
			descriptor := imageFile.Proto()
			if imageFile.Path() == "a.proto" {
				assert.Equal(t, "override", descriptor.GetOptions().GetJavaPackage())
				continue
			}
			assert.Equal(t, "foo", descriptor.GetOptions().GetJavaPackage())
		}
		assertFileOptionSourceCodeInfoEmpty(t, image, javaPackagePath, false)
	})
}

func TestJavaPackageJavaOptions(t *testing.T) {
	t.Parallel()
	dirPath := filepath.Join("testdata", "javaoptions")
	modifiedJavaPackage := "com.acme.weather"
	t.Run("with SourceCodeInfo", func(t *testing.T) {
		t.Parallel()
		image := testGetImage(t, dirPath, true)
		assertFileOptionSourceCodeInfoNotEmpty(t, image, javaPackagePath)

		sweeper := NewFileOptionSweeper()
		javaPackageModifier, err := JavaPackage(zap.NewNop(), sweeper, testJavaPackagePrefix, nil, nil, nil)
		require.NoError(t, err)

		modifier := NewMultiModifier(javaPackageModifier, ModifierFunc(sweeper.Sweep))
		err = modifier.Modify(
			context.Background(),
			image,
		)
		require.NoError(t, err)
		assert.NotEqual(t, testGetImage(t, dirPath, true), image)

		for _, imageFile := range image.Files() {
			descriptor := imageFile.Proto()
			assert.Equal(t, modifiedJavaPackage, descriptor.GetOptions().GetJavaPackage())
		}
		assertFileOptionSourceCodeInfoEmpty(t, image, javaPackagePath, true)
	})

	t.Run("without SourceCodeInfo", func(t *testing.T) {
		t.Parallel()
		image := testGetImage(t, dirPath, false)
		assertFileOptionSourceCodeInfoEmpty(t, image, javaPackagePath, false)

		sweeper := NewFileOptionSweeper()
		modifier, err := JavaPackage(zap.NewNop(), sweeper, testJavaPackagePrefix, nil, nil, nil)
		require.NoError(t, err)
		err = modifier.Modify(
			context.Background(),
			image,
		)
		require.NoError(t, err)
		assert.NotEqual(t, testGetImage(t, dirPath, false), image)

		for _, imageFile := range image.Files() {
			descriptor := imageFile.Proto()
			assert.Equal(t, modifiedJavaPackage, descriptor.GetOptions().GetJavaPackage())
		}
		assertFileOptionSourceCodeInfoEmpty(t, image, javaPackagePath, false)
	})

	t.Run("with SourceCodeInfo and per-file overrides", func(t *testing.T) {
		t.Parallel()
		image := testGetImage(t, dirPath, true)
		assertFileOptionSourceCodeInfoNotEmpty(t, image, javaPackagePath)

		sweeper := NewFileOptionSweeper()
		javaPackageModifier, err := JavaPackage(zap.NewNop(), sweeper, testJavaPackagePrefix, nil, nil, map[string]string{"override.proto": "override"})
		require.NoError(t, err)

		modifier := NewMultiModifier(javaPackageModifier, ModifierFunc(sweeper.Sweep))
		err = modifier.Modify(
			context.Background(),
			image,
		)
		require.NoError(t, err)
		assert.NotEqual(t, testGetImage(t, dirPath, true), image)

		for _, imageFile := range image.Files() {
			descriptor := imageFile.Proto()
			if imageFile.Path() == "override.proto" {
				assert.Equal(t, "override", descriptor.GetOptions().GetJavaPackage())
				continue
			}
			assert.Equal(t, modifiedJavaPackage, descriptor.GetOptions().GetJavaPackage())
		}
		assertFileOptionSourceCodeInfoEmpty(t, image, javaPackagePath, true)
	})

	t.Run("without SourceCodeInfo and with per-file overrides", func(t *testing.T) {
		t.Parallel()
		image := testGetImage(t, dirPath, false)
		assertFileOptionSourceCodeInfoEmpty(t, image, javaPackagePath, false)

		sweeper := NewFileOptionSweeper()
		modifier, err := JavaPackage(zap.NewNop(), sweeper, testJavaPackagePrefix, nil, nil, map[string]string{"override.proto": "override"})
		require.NoError(t, err)
		err = modifier.Modify(
			context.Background(),
			image,
		)
		require.NoError(t, err)
		assert.NotEqual(t, testGetImage(t, dirPath, false), image)

		for _, imageFile := range image.Files() {
			descriptor := imageFile.Proto()
			if imageFile.Path() == "override.proto" {
				assert.Equal(t, "override", descriptor.GetOptions().GetJavaPackage())
				continue
			}
			assert.Equal(t, modifiedJavaPackage, descriptor.GetOptions().GetJavaPackage())
		}
		assertFileOptionSourceCodeInfoEmpty(t, image, javaPackagePath, false)
	})
}

func TestJavaPackageWellKnownTypes(t *testing.T) {
	t.Parallel()
	dirPath := filepath.Join("testdata", "wktimport")
	javaPackagePrefix := "org"
	modifiedJavaPackage := "org.acme.weather.v1alpha1"
	t.Run("with SourceCodeInfo", func(t *testing.T) {
		t.Parallel()
		image := testGetImage(t, dirPath, true)

		sweeper := NewFileOptionSweeper()
		javaPackageModifier, err := JavaPackage(zap.NewNop(), sweeper, javaPackagePrefix, nil, nil, nil)
		require.NoError(t, err)

		modifier := NewMultiModifier(javaPackageModifier, ModifierFunc(sweeper.Sweep))
		err = modifier.Modify(
			context.Background(),
			image,
		)
		require.NoError(t, err)

		for _, imageFile := range image.Files() {
			descriptor := imageFile.Proto()
			if isWellKnownType(context.Background(), imageFile) {
				assert.NotEmpty(t, descriptor.GetOptions().GetJavaPackage())
				assert.NotEqual(t, modifiedJavaPackage, descriptor.GetOptions().GetJavaPackage())
				continue
			}
			assert.Equal(t,
				modifiedJavaPackage,
				descriptor.GetOptions().GetJavaPackage(),
			)
		}
	})

	t.Run("without SourceCodeInfo", func(t *testing.T) {
		t.Parallel()
		image := testGetImage(t, dirPath, false)

		sweeper := NewFileOptionSweeper()
		modifier, err := JavaPackage(zap.NewNop(), sweeper, javaPackagePrefix, nil, nil, nil)
		require.NoError(t, err)
		err = modifier.Modify(
			context.Background(),
			image,
		)
		require.NoError(t, err)

		for _, imageFile := range image.Files() {
			descriptor := imageFile.Proto()
			if isWellKnownType(context.Background(), imageFile) {
				assert.NotEmpty(t, descriptor.GetOptions().GetJavaPackage())
				assert.NotEqual(t, modifiedJavaPackage, descriptor.GetOptions().GetJavaPackage())
				continue
			}
			assert.Equal(t,
				modifiedJavaPackage,
				descriptor.GetOptions().GetJavaPackage(),
			)
		}
	})
}

func TestJavaPackageWithExcept(t *testing.T) {
	t.Parallel()
	dirPath := filepath.Join("testdata", "javaemptyoptions")
	testModuleIdentity, err := bufmoduleref.NewModuleIdentity(
		testRemote,
		testRepositoryOwner,
		testRepositoryName,
	)
	require.NoError(t, err)

	t.Run("with SourceCodeInfo", func(t *testing.T) {
		t.Parallel()
		image := testGetImage(t, dirPath, true)
		assertFileOptionSourceCodeInfoEmpty(t, image, javaPackagePath, true)

		sweeper := NewFileOptionSweeper()
		javaPackageModifier, err := JavaPackage(
			zap.NewNop(),
			sweeper,
			testJavaPackagePrefix,
			[]bufmoduleref.ModuleIdentity{testModuleIdentity},
			nil,
			nil,
		)
		require.NoError(t, err)

		modifier := NewMultiModifier(javaPackageModifier, ModifierFunc(sweeper.Sweep))
		err = modifier.Modify(
			context.Background(),
			image,
		)
		require.NoError(t, err)
		assert.Equal(t, testGetImage(t, dirPath, true), image)
		assertFileOptionSourceCodeInfoEmpty(t, image, javaPackagePath, true)
	})

	t.Run("without SourceCodeInfo", func(t *testing.T) {
		t.Parallel()
		image := testGetImage(t, dirPath, false)
		assertFileOptionSourceCodeInfoEmpty(t, image, javaPackagePath, false)

		sweeper := NewFileOptionSweeper()
		modifier, err := JavaPackage(
			zap.NewNop(),
			sweeper,
			testJavaPackagePrefix,
			[]bufmoduleref.ModuleIdentity{testModuleIdentity},
			nil,
			nil,
		)
		require.NoError(t, err)
		err = modifier.Modify(
			context.Background(),
			image,
		)
		require.NoError(t, err)
		assert.Equal(t, testGetImage(t, dirPath, false), image)
		assertFileOptionSourceCodeInfoEmpty(t, image, javaPackagePath, false)
	})

	t.Run("with SourceCodeInfo and per-file overrides", func(t *testing.T) {
		t.Parallel()
		image := testGetImage(t, dirPath, true)
		assertFileOptionSourceCodeInfoEmpty(t, image, javaPackagePath, true)

		sweeper := NewFileOptionSweeper()
		javaPackageModifier, err := JavaPackage(
			zap.NewNop(),
			sweeper,
			testJavaPackagePrefix,
			[]bufmoduleref.ModuleIdentity{testModuleIdentity},
			nil,
			map[string]string{"a.proto": "override"},
		)
		require.NoError(t, err)

		modifier := NewMultiModifier(javaPackageModifier, ModifierFunc(sweeper.Sweep))
		err = modifier.Modify(
			context.Background(),
			image,
		)
		require.NoError(t, err)
		assertFileOptionSourceCodeInfoEmpty(t, image, javaPackagePath, true)
	})

	t.Run("without SourceCodeInfo and with per-file overrides", func(t *testing.T) {
		t.Parallel()
		image := testGetImage(t, dirPath, false)
		assertFileOptionSourceCodeInfoEmpty(t, image, javaPackagePath, false)

		sweeper := NewFileOptionSweeper()
		modifier, err := JavaPackage(
			zap.NewNop(),
			sweeper,
			testJavaPackagePrefix,
			[]bufmoduleref.ModuleIdentity{testModuleIdentity},
			nil,
			map[string]string{"a.proto": "override"},
		)
		require.NoError(t, err)
		err = modifier.Modify(
			context.Background(),
			image,
		)
		require.NoError(t, err)
		assertFileOptionSourceCodeInfoEmpty(t, image, javaPackagePath, false)
	})
}

func TestJavaPackageWithOverride(t *testing.T) {
	t.Parallel()
	dirPath := filepath.Join("testdata", "javaemptyoptions")
	overrideJavaPackagePrefix := "foo.bar"
	testModuleIdentity, err := bufmoduleref.NewModuleIdentity(
		testRemote,
		testRepositoryOwner,
		testRepositoryName,
	)
	require.NoError(t, err)

	t.Run("with SourceCodeInfo", func(t *testing.T) {
		t.Parallel()
		image := testGetImage(t, dirPath, true)
		assertFileOptionSourceCodeInfoEmpty(t, image, javaPackagePath, true)

		sweeper := NewFileOptionSweeper()
		javaPackageModifier, err := JavaPackage(
			zap.NewNop(),
			sweeper,
			testJavaPackagePrefix,
			nil,
			map[bufmoduleref.ModuleIdentity]string{
				testModuleIdentity: overrideJavaPackagePrefix,
			},
			nil,
		)
		require.NoError(t, err)

		modifier := NewMultiModifier(javaPackageModifier, ModifierFunc(sweeper.Sweep))
		err = modifier.Modify(
			context.Background(),
			image,
		)
		require.NoError(t, err)
		assert.NotEqual(t, testGetImage(t, dirPath, true), image)

		for _, imageFile := range image.Files() {
			descriptor := imageFile.Proto()
			assert.Equal(t,
				overrideJavaPackagePrefix+"."+descriptor.GetPackage(),
				descriptor.GetOptions().GetJavaPackage(),
			)
		}
		assertFileOptionSourceCodeInfoEmpty(t, image, javaPackagePath, true)
	})

	t.Run("without SourceCodeInfo", func(t *testing.T) {
		t.Parallel()
		image := testGetImage(t, dirPath, false)
		assertFileOptionSourceCodeInfoEmpty(t, image, javaPackagePath, false)

		sweeper := NewFileOptionSweeper()
		modifier, err := JavaPackage(
			zap.NewNop(),
			sweeper,
			testJavaPackagePrefix,
			nil,
			map[bufmoduleref.ModuleIdentity]string{
				testModuleIdentity: overrideJavaPackagePrefix,
			},
			nil,
		)
		require.NoError(t, err)
		err = modifier.Modify(
			context.Background(),
			image,
		)
		require.NoError(t, err)
		assert.NotEqual(t, testGetImage(t, dirPath, false), image)

		for _, imageFile := range image.Files() {
			descriptor := imageFile.Proto()
			assert.Equal(t,
				overrideJavaPackagePrefix+"."+descriptor.GetPackage(),
				descriptor.GetOptions().GetJavaPackage(),
			)
		}
		assertFileOptionSourceCodeInfoEmpty(t, image, javaPackagePath, false)
	})

	t.Run("with SourceCodeInfo and per-file overrides", func(t *testing.T) {
		t.Parallel()
		image := testGetImage(t, dirPath, true)
		assertFileOptionSourceCodeInfoEmpty(t, image, javaPackagePath, true)

		sweeper := NewFileOptionSweeper()
		javaPackageModifier, err := JavaPackage(
			zap.NewNop(),
			sweeper,
			testJavaPackagePrefix,
			nil,
			map[bufmoduleref.ModuleIdentity]string{
				testModuleIdentity: overrideJavaPackagePrefix,
			},
			map[string]string{"a.proto": "override"},
		)
		require.NoError(t, err)

		modifier := NewMultiModifier(javaPackageModifier, ModifierFunc(sweeper.Sweep))
		err = modifier.Modify(
			context.Background(),
			image,
		)
		require.NoError(t, err)
		assert.NotEqual(t, testGetImage(t, dirPath, true), image)

		for _, imageFile := range image.Files() {
			descriptor := imageFile.Proto()
			assert.Equal(t, "override", descriptor.GetOptions().GetJavaPackage())
		}
		assertFileOptionSourceCodeInfoEmpty(t, image, javaPackagePath, true)
	})

	t.Run("without SourceCodeInfo and with per-file overrides", func(t *testing.T) {
		t.Parallel()
		image := testGetImage(t, dirPath, false)
		assertFileOptionSourceCodeInfoEmpty(t, image, javaPackagePath, false)

		sweeper := NewFileOptionSweeper()
		modifier, err := JavaPackage(
			zap.NewNop(),
			sweeper,
			testJavaPackagePrefix,
			nil,
			map[bufmoduleref.ModuleIdentity]string{
				testModuleIdentity: overrideJavaPackagePrefix,
			},
			map[string]string{"a.proto": "override"},
		)
		require.NoError(t, err)
		err = modifier.Modify(
			context.Background(),
			image,
		)
		require.NoError(t, err)
		assert.NotEqual(t, testGetImage(t, dirPath, false), image)

		for _, imageFile := range image.Files() {
			descriptor := imageFile.Proto()
			assert.Equal(t, "override", descriptor.GetOptions().GetJavaPackage())
		}
		assertFileOptionSourceCodeInfoEmpty(t, image, javaPackagePath, false)
	})
}


text:
<?php
/**
 * for test
 */

namespace __Test;

use Ytake\LaravelAspect\Annotation\Cacheable;

/**
 * Class AspectCacheable
 *
 * @package __Test
 */
class AspectCacheable
{
    /**
     * @Cacheable(key="#id",driver="null")
     * @param null $id
     *
     * @return null
     */
    public function singleKey($id = null)
    {
        return $id;
    }

    /**
     * @Cacheable(key={"#id","#value"},driver="array")
     * @param $id
     * @param $value
     *
     * @return mixed
     */
    public function multipleKey($id, $value)
    {
        return $id;
    }

    /**
     * @Cacheable(cacheName="testing1",key={"#id","#value"})
     * @param $id
     * @param $value
     *
     * @return mixed
     */
    public function namedMultipleKey($id, $value)
    {
        return $id;
    }

    /**
     * @Cacheable(tags={"testing1","testing2"},key={"#id","#value"})
     * @param $id
     * @param $value
     *
     * @return mixed
     */
    public function namedMultipleNameAndKey($id, $value)
    {
        return $id;
    }

    /**
     * @Cacheable(tags={"testing1","testing2"},key={"#id","#class"})
     * @param           $id
     * @param \stdClass $class
     *
     * @return mixed
     */
    public function cachingKeyObject($id, \stdClass $class)
    {
        return $id;
    }

    /**
     * @Cacheable(negative=true,cacheName="negative")
     * @return null
     */
    public function negativeCache()
    {
        return null;
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Solution.Base.Interfaces.Model;

namespace Solution.Base.Interfaces.Repository
{
    public interface IBaseJpegMetadataRepository : IBaseJpegMetadataReadOnlyRepository
    {
        void Save(string path, byte[] bytes);

        void Save(string path, string text);

        void Move(string sourcePath, string destinationPath);

        void Rename(string sourcePath, string newName);

        void Delete(string path);
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<doctrine-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping http://doctrine-project.org/schemas/orm/doctrine-mapping.xsd">
  <entity name="MyApp\AquitemBicoBundle\Entity\CandidatoHabilitacao" table="candidato_habilitacao">
    <id name="id" type="integer" column="ID">
      <generator strategy="IDENTITY"/>
    </id>
    <field name="idCandidato" type="integer" column="ID_candidato" nullable="false">
      <options>
        <option name="unsigned"/>
      </options>
    </field>
    <field name="tipohabilitacao" type="string" column="tipoHabilitacao" length="11" nullable="false">
      <options>
        <option name="fixed"/>
      </options>
    </field>
  </entity>
</doctrine-mapping>


text:
package gallery.templates.contentful.lib;

import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Point;

public class Utils {
  private Utils() {
    throw new AssertionError();
  }

  public static String imageUrl(String url) {
    int size = Const.CDN_ASSET_SIZE;
    return imageUrl(url, size, size);
  }

  public static String imageUrl(String url, int width, int height) {
    String prefix = "?";

    if (url.contains("?")) {
      prefix = "&";
    }

    return url + prefix + "w=" + width + "&h=" + height;
  }

  public static boolean isPortrait(Context context) {
    return context.getResources().getConfiguration().orientation ==
        Configuration.ORIENTATION_PORTRAIT;
  }

  public static Point getDisplayDimensions(Activity activity) {
    Point point = new Point();
    activity.getWindowManager().getDefaultDisplay().getSize(point);
    return point;
  }
}


text:
//
// This code was auto-generated by AFNOR StoredProcedureSystem, version 1.0
//

using System;
using System.ComponentModel.DataAnnotations;
using System.Runtime.Serialization;

namespace Bivi.Domaine
{
    public partial class Configuration
    {

        [DataMember]
        public long ID { get; set; }

        [DataMember]
        public virtual TypeRenduBloc TypeRenduBloc { get; set; }

        [DataMember]
        public Nullable<long> TypeRenduBlocID { get; set; }

        [DataMember]
        public virtual Bloc Bloc { get; set; }

        [DataMember]
        public Nullable<long> BlocID { get; set; }

        [DataMember]
        public virtual PersonneSiteConf PersonneSiteConf { get; set; }

        [DataMember]
        public long PersonneSiteConfID { get; set; }

        [DataMember]
        public Nullable<int> Ordre { get; set; }

        [DataMember]
        public virtual ZonePage ZonePage { get; set; }

        [DataMember]
        public long ZonePageID { get; set; }

        [DataMember]
        public bool Checked { get; set; }
    }
}


text:
breeze-client-labs (breeze.js.labs)
===================================

**Breeze Labs** are extensions and utilities for Breeze.js client apps that are not part of core breeze.

See the [**Breeze Labs documentation**](http://www.breezejs.com/documentation/what-are-breeze-labs) for a discussion of the Breeze Labs concept, its limitations, and for description of individual labs.

To install with bower:

```bower install breeze-client-labs```

To install with npm:

```npm install breeze-client-labs```


text:
import { Subscription } from 'expo-modules-core';
import { BatteryLevelEvent, BatteryState, BatteryStateEvent, PowerModeEvent, PowerState } from './Battery.types';
/**
 * Resolves with whether the battery API is available on the current device. The value of this
 * property is `true` on Android and physical iOS devices and `false` on iOS simulators. On web,
 * it depends on whether the browser supports the web battery API.
 */
export declare function isAvailableAsync(): Promise<boolean>;
/**
 * Gets the battery level of the device as a number between `0` and `1`, inclusive. If the device
 * does not support retrieving the battery level, this method returns `-1`. On web, this method
 * always returns `-1`.
 * @return A `Promise` that fulfils with a number between `0` and `1` representing the battery level,
 * or `-1` if the device does not provide it.
 * @example
 * ```ts
 * await Battery.getBatteryLevelAsync();
 * // 0.759999
 * ```
 */
export declare function getBatteryLevelAsync(): Promise<number>;
/**
 * Tells the battery's current state. On web, this always returns `BatteryState.UNKNOWN`.
 * @return Returns a `Promise` which fulfills with a [`Battery.BatteryState`](#batterystate) enum
 * value for whether the device is any of the four states.
 * @example
 * ```ts
 * await Battery.getBatteryStateAsync();
 * // BatteryState.CHARGING
 * ```
 */
export declare function getBatteryStateAsync(): Promise<BatteryState>;
/**
 * Gets the current status of Low Power mode on iOS and Power Saver mode on Android. If a platform
 * doesn't support Low Power mode reporting (like web, older Android devices), the reported low-power
 * state is always `false`, even if the device is actually in low-power mode.
 * @return Returns a `Promise` which fulfills with a `boolean` value of either `true` or `false`,
 * indicating whether low power mode is enabled or disabled, respectively.
 * @example
 * Low Power Mode (iOS) or Power Saver Mode (Android) are enabled.
 * ```ts
 * await Battery.isLowPowerModeEnabledAsync();
 * // true
 * ```
 */
export declare function isLowPowerModeEnabledAsync(): Promise<boolean>;
/**
 * Checks whether battery optimization is enabled for your application.
 * If battery optimization is enabled for your app, background tasks might be affected
 * when your app goes into doze mode state. (only on Android 6.0 or later)
 * @return Returns a `Promise` which fulfills with a `boolean` value of either `true` or `false`,
 * indicating whether the battery optimization is enabled or disabled, respectively. (Android only)
 * @example
 * ```ts
 * await Battery.isBatteryOptimizationEnabledAsync();
 * // true
 * ```
 */
export declare function isBatteryOptimizationEnabledAsync(): Promise<boolean>;
/**
 * Gets the power state of the device including the battery level, whether it is plugged in, and if
 * the system is currently operating in Low Power Mode (iOS) or Power Saver Mode (Android). This
 * method re-throws any errors that occur when retrieving any of the power-state information.
 * @return Returns a `Promise` which fulfills with [`PowerState`](#powerstate) object.
 * @example
 * ```ts
 * await Battery.getPowerStateAsync();
 * // {
 * //   batteryLevel: 0.759999,
 * //   batteryState: BatteryState.UNPLUGGED,
 * //   lowPowerMode: true,
 * // }
 * ```
 */
export declare function getPowerStateAsync(): Promise<PowerState>;
/**
 * Subscribe to the battery level change updates.
 *
 * On iOS devices, the event fires when the battery level drops one percent or more, but is only
 * fired once per minute at maximum.
 *
 * On Android devices, the event fires only when significant changes happens, which is when the
 * battery level drops below [`"android.intent.action.BATTERY_LOW"`](https://developer.android.com/reference/android/content/Intent#ACTION_BATTERY_LOW)
 * or rises above [`"android.intent.action.BATTERY_OKAY"`](https://developer.android.com/reference/android/content/Intent#ACTION_BATTERY_OKAY)
 * from a low battery level. See [here](https://developer.android.com/training/monitoring-device-state/battery-monitoring)
 * to read more from the Android docs.
 *
 * On web, the event never fires.
 * @param listener A callback that is invoked when battery level changes. The callback is provided a
 * single argument that is an object with a `batteryLevel` key.
 * @return A `Subscription` object on which you can call `remove()` to unsubscribe from the listener.s
 */
export declare function addBatteryLevelListener(listener: (event: BatteryLevelEvent) => void): Subscription;
/**
 * Subscribe to the battery state change updates to receive an object with a [`Battery.BatteryState`](#batterystate)
 * enum value for whether the device is any of the four states.
 *
 * On web, the event never fires.
 * @param listener A callback that is invoked when battery state changes. The callback is provided a
 * single argument that is an object with a `batteryState` key.
 * @return A `Subscription` object on which you can call `remove()` to unsubscribe from the listener.
 */
export declare function addBatteryStateListener(listener: (event: BatteryStateEvent) => void): Subscription;
/**
 * Subscribe to Low Power Mode (iOS) or Power Saver Mode (Android) updates. The event fires whenever
 * the power mode is toggled.
 *
 * On web, the event never fires.
 * @param listener A callback that is invoked when Low Power Mode (iOS) or Power Saver Mode (Android)
 * changes. The callback is provided a single argument that is an object with a `lowPowerMode` key.
 * @return A `Subscription` object on which you can call `remove()` to unsubscribe from the listener.
 */
export declare function addLowPowerModeListener(listener: (event: PowerModeEvent) => void): Subscription;
export { BatteryLevelEvent, BatteryState, BatteryStateEvent, PowerModeEvent, PowerState, Subscription, };
//# sourceMappingURL=Battery.d.ts.map


text:
public class Node {

}


text:
class PezDispenser

  def initialize(flavors_given)
    @flavors_inside = flavors_given
  end
  def pez_count()
    @pez_count = @flavors_inside.length
  end
  def see_all_pez()
    @flavors_inside
  end
  def add_pez(new_flavor)
    @flavors_inside = @flavors_inside.push(new_flavor)
  end
  def get_pez()
    @flavors_inside.pop
  end

end

# DRIVER TESTS GO BELOW THIS LINE

flavors = %w(cherry chocolate cola grape lemon orange peppermint raspberry strawberry).shuffle
super_mario = PezDispenser.new(flavors)
puts "A new pez dispenser has been created. You have #{super_mario.pez_count} pez!"
puts "Here's a look inside the dispenser:"
puts super_mario.see_all_pez
puts "Adding a banana pez."
super_mario.add_pez("banana")
puts "Now you have #{super_mario.pez_count} pez!"
puts "Oh, you want one do you?"
puts "The pez flavor you got is: #{super_mario.get_pez}"
puts "Now you have #{super_mario.pez_count} pez!"

# Reflection
# What concepts did you review or learn in this challenge?
# I reviewed .each and .map in the fizzbuzz challenge. I thought I should use a each loop, but the map is the better one for the method and actually overwrites the item appropriately.
# In the Pez challenge, I reviewed how to create a class. I also used instance variables, as well as local variables. However I found the challenge abit frustrating because the driver code doesn't really let us explore the attr abilities of the class. I mean, making flavor an attr: readable is a great example of why you don't want the class to have an accessor attribute.
# What is still confusing to you about Ruby?
# I feel shaky on the docs, but I think that's a matter of practice. I also feel like I scour them for answers and yet still think my ways end up being the faster.
# I also like the attr but I'm still unsure if I'm conceptualizing them correctly. However, I find the driver code fix-as-you go way of writing code to be the most enjoyable? Like. write it, test it fix it test it fix it test it... it feels like a game, and it displays tangible results.
# What are you going to study to get more prepared for Phase 1?
# More methods. I'll probably sit down and actually read some of the assigned books. reading random snippets is sort of useful in spurts, but I will get a better feel for it once I'm actually reading the chapters in order.
# I also think I will really enjoy making my cheat sheet now that I've seen some of what I continue to have to look up. Explaining things to myself [or a loved one lol] always helps me feel better/more confident in my code.


text:
[![Gem Version](https://badge.fury.io/rb/simple-navigation.png)](http://badge.fury.io/rb/simple-navigation)
[![Build Status](https://secure.travis-ci.org/codeplant/simple-navigation.png?branch=master)](http://travis-ci.org/codeplant/simple-navigation)
[![Code Climate](https://codeclimate.com/github/codeplant/simple-navigation.png)](https://codeclimate.com/github/codeplant/simple-navigation)
[![Coverage Status](https://coveralls.io/repos/codeplant/simple-navigation/badge.png)](https://coveralls.io/r/codeplant/simple-navigation)

Simple Navigation is a ruby library for creating navigations (with multiple levels) for your Rails, Sinatra or Padrino applications. It runs with all ruby versions (including ruby 2.x).

## Documentation

For the complete documentation, take a look at the [project's wiki](https://github.com/codeplant/simple-navigation/wiki).

## RDoc

You can consult the project's RDoc on [RubyDoc.info](http://rubydoc.info/github/codeplant/simple-navigation/frames).

If you need to generate the RDoc files locally, check out the repository and simply call the `rake rdoc` in the project's folder.

## Online Demo

You can try simple-navigation with the [online demo](http://simple-navigation-demo.codeplant.ch).

The source code of this online demo is [available on Github](http://github.com/codeplant/simple-navigation-demo).

## Feedback and Questions

Don't hesitate to come talk on the [project's group](http://groups.google.com/group/simple-navigation).

## Contributing

Fork, fix, then send a Pull Request.

To run the test suite locally against all supported frameworks:

    % bundle install
    % rake spec:all

To target the test suite against one framework:

    % rake spec:rails-4-2-stable

You can find a list of supported spec tasks by running rake -T. You may also find it useful to run a specific test for a specific framework. To do so, you'll have to first make sure you have bundled everything for that configuration, then you can run the specific test:

% BUNDLE_GEMFILE='gemfiles/rails-4-2-stable.gemfile' bundle install -j 4
% BUNDLE_GEMFILE='gemfiles/rails-4-2-stable.gemfile' bundle exec rspec ./spec/requests/users_spec.rb

### Rake and Bundler

If you use a shell plugin (like oh-my-zsh:bundler) that auto-prefixes commands with `bundle exec` using the `rake` command will fail.

Get the original command with `type -a rake`:

    % type -a rake
    rake is an alias for bundled_rake
    rake is /Users/username/.rubies/ruby-2.2.3/bin/rake
    rake is /usr/bin/rake

In this situation `/Users/username/.rubies/ruby-2.2.3/bin/rake` is the command you should use.

## License

Copyright (c) 2022 codeplant GmbH, released under the MIT license


text:
package com.vaadin.tests.widgetset.server;

import com.vaadin.tests.widgetset.client.superText.SuperTextAreaState;
import com.vaadin.ui.TextArea;

/**
 * @author artamonov
 */
public class ExtraSuperTextArea extends TextArea {

    @Override
    public SuperTextAreaState getState() {
        return (SuperTextAreaState) super.getState();
    }
}


text:
![alt text](https://github.com/ckanitz/vanirswatch/blob/master/vanirs_watch_assets/vanirswatch_layout.png)

Vanirs Watch is a Third-Party-Tool for Ragnarok Online that shows current data of your Character and the gained base and job EXP per hour.

If you want me to make an INI file for your server open an issue and provide your server admin approval if needed for third party tools! See "INI request template"-Issue for requests.

### Setup
Check INI file and put in your memory-addresses.
Run Vanirswatch.exe as Administrator.

### Current Version
1.0.2 BETA

### Changelog
**1.0.2 BETA**
Restructured code for more readability
Base Level is now shown next to "Base Lv" left of the bar
...same goes with Job Level
Fixed the timer interval (was accidently 500 instead of 1000 which caused in calculating false exp/h)

**1.0.1 BETA**
Made new resolution for GUI
Moved old code to _legacy
Added GUI

**0.2.1 BETA**
Settings will be read from INI file now.
Edit INI file to make VanirsWatch working on your server!

**0.2.0 BETA**
First fully working version!
Console only, run as admin.

**0.0.1**
Initial Function to test if address reading is working :)

**0.0.1d**
Note: d always means "debug version"
temporary deactivated the address reading
added debug test class
added jobclass dictionary class
no main routine at this point, will come with 0.0.2d

License
----

MIT


text:
from __future__ import unicode_literals

from django.db import migrations

class Migration(migrations.Migration):

    dependencies = [
        ('hackerspace', '0018_programming_quiz_verbal'),
    ]

    operations = [
        migrations.DeleteModel(
            name='Batches',
        ),
    ]


text:
require_relative 'resource'

module Contentful
  module Management
    # Resource class for User.
    # @see _ https://www.contentful.com/developers/docs/references/content-management-api/#/reference/users
    class User
      include Contentful::Management::Resource
      include Contentful::Management::Resource::Refresher
      include Contentful::Management::Resource::SystemProperties

      property :email, :string
      property :lastName, :string
      property :firstName, :string
      property :avatarUrl, :string
      property :activated, :boolean
      property :confirmed, :boolean
      property :signInCount, :integer

      # @private
      def self.build_endpoint(endpoint_options)
        endpoint = if endpoint_options[:space_id]
                     "spaces/#{endpoint_options[:space_id]}/users"
                   elsif endpoint_options[:organization_id]
                     "organizations/#{endpoint_options[:organization_id]}/users"
                   else
                     'users'
                   end
        endpoint = "#{endpoint}/#{endpoint_options[:resource_id]}" if endpoint_options[:resource_id]
        endpoint
      end
    end
  end
end


text:
using FreshMvvm.CoreMethods;
using NSubstitute;
using NUnit.Framework;
using Xamarin.Forms;

namespace FreshMvvm.Tests.Fixtures
{
    [TestFixture]
    public class PageModelNotificationsTests
    {
        private Page page = Substitute.For<Page>();

        [SetUp]
        public void Setup()
        {
        }

        [Test]
        public void Given_When_Then()
        {
            var sut = CreateSut();

        }

        private PageModelNotifications CreateSut()
        {
            return new PageModelNotifications(page);
        }
    }
}


text:
import { app, BrowserWindow, dialog } from 'electron'
import { createShellWindow } from './windows'

var darwinMenu = {
  label: 'Beaker',
  submenu: [
    { label: 'About Beaker', role: 'about' },
    { type: 'separator' },
    { label: 'Services', role: 'services', submenu: [] },
    { type: 'separator' },
    { label: 'Hide Beaker', accelerator: 'Command+H', role: 'hide' },
    { label: 'Hide Others', accelerator: 'Command+Alt+H', role: 'hideothers' },
    { label: 'Show All', role: 'unhide' },
    { type: 'separator' },
    { label: 'Quit', accelerator: 'Command+Q', click() { app.quit() } }
  ]
}

var fileMenu = {
  label: 'File',
  submenu: [
    {
      label: 'New Tab',
      accelerator: 'CmdOrCtrl+T',
      click: function (item, win) {
        if (win) win.webContents.send('command', 'file:new-tab')
      }
    },
    {
      label: 'New Window',
      accelerator: 'CmdOrCtrl+N',
      click: function () { createShellWindow() }
    },
    {
      label: 'Reopen Closed Tab',
      accelerator: 'CmdOrCtrl+Shift+T',
      click: function (item, win) {
        if (win) win.webContents.send('command', 'file:reopen-closed-tab')
      }
    },
    {
      label: 'Toggle SAFE Browsing',
      checked: true,
      accelerator: 'CmdOrCtrl+Shift+L',
      click: function (item, win) {
          if (win) win.webContents.send('command', 'window:toggle-safe-mode')
      }
    },
    {
      label: 'Open File',
      accelerator: 'CmdOrCtrl+O',
      click: function (item, win) {
        if (win) {
          dialog.showOpenDialog({ title: 'Open file...', properties: ['openFile', 'createDirectory'] }, files => {
            if (files && files[0])
              win.webContents.send('command', 'file:new-tab', 'file://'+files[0])
          })
        }
      }
    },
    {
      label: 'Open Location',
      accelerator: 'CmdOrCtrl+L',
      click: function (item, win) {
        if (win) win.webContents.send('command', 'file:open-location')
      }
    },
    { type: 'separator' },
    {
      label: 'Close Window',
      accelerator: 'CmdOrCtrl+Shift+W',
      click: function (item, win) {
        if (win) win.close()
      }
    },
    {
      label: 'Close Tab',
      accelerator: 'CmdOrCtrl+W',
      click: function (item, win) {
        if (win) win.webContents.send('command', 'file:close-tab')
      }
    }
  ]
}

var editMenu = {
  label: 'Edit',
  submenu: [
    { label: "Undo", accelerator: "CmdOrCtrl+Z", selector: "undo:" },
    { label: "Redo", accelerator: "Shift+CmdOrCtrl+Z", selector: "redo:" },
    { type: "separator" },
    { label: "Cut", accelerator: "CmdOrCtrl+X", selector: "cut:" },
    { label: "Copy", accelerator: "CmdOrCtrl+C", selector: "copy:" },
    { label: "Paste", accelerator: "CmdOrCtrl+V", selector: "paste:" },
    { label: "Select All", accelerator: "CmdOrCtrl+A", selector: "selectAll:" },
    {
      label: "Find in Page",
      accelerator: "CmdOrCtrl+F",
      click: function (item, win) {
        if (win) win.webContents.send('command', 'edit:find')
      }
    }
  ]
}

var viewMenu = {
  label: 'View',
  submenu: [{
    label: 'Reload',
    accelerator: 'CmdOrCtrl+R',
    click: function (item, win) {
      if (win) win.webContents.send('command', 'view:reload')
    }
  },
  {
    label: 'Hard Reload (Clear Cache)',
    accelerator: 'CmdOrCtrl+Shift+R',
    click: function (item, win) {
      if (win) win.webContents.send('command', 'view:hard-reload')
    }
  },
  { type: "separator" },
  {
    label: 'Zoom In',
    accelerator: 'CmdOrCtrl+=',
    click: function (item, win) {
      if (win) win.webContents.send('command', 'view:zoom-in')
    }
  },
  {
    label: 'Zoom Out',
    accelerator: 'CmdOrCtrl+-',
    click: function (item, win) {
      if (win) win.webContents.send('command', 'view:zoom-out')
    }
  },
  {
    label: 'Actual Size',
    accelerator: 'CmdOrCtrl+0',
    click: function (item, win) {
      if (win) win.webContents.send('command', 'view:zoom-reset')
    }
  },
  { type: "separator" },
  {
    label: 'Toggle DevTools',
    accelerator: 'Alt+CmdOrCtrl+I',
    click: function (item, win) {
      if (win) win.webContents.send('command', 'view:toggle-dev-tools')
    }
  }]
}

var historyMenu = {
  label: 'History',
  role: 'history',
  submenu: [
    {
      label: 'Back',
      accelerator: 'CmdOrCtrl+Left',
      click: function (item, win) {
        if (win) win.webContents.send('command', 'history:back')
      }
    },
    {
      label: 'Forward',
      accelerator: 'CmdOrCtrl+Right',
      click: function (item, win) {
        if (win) win.webContents.send('command', 'history:forward')
      }
    }
  ]
}

var windowMenu = {
  label: 'Window',
  role: 'window',
  submenu: [
    {
      label: 'Minimize',
      accelerator: 'CmdOrCtrl+M',
      role: 'minimize'
    },
    {
      label: 'Close',
      accelerator: 'CmdOrCtrl+Q',
      role: 'close'
    },
    {
      label: 'Next Tab',
      accelerator: 'CmdOrCtrl+]',
      click: function (item, win) {
        if (win) win.webContents.send('command', 'window:next-tab')
      }
    },
    {
      label: 'Previous Tab',
      accelerator: 'CmdOrCtrl+[',
      click: function (item, win) {
        if (win) win.webContents.send('command', 'window:prev-tab')
      }
    }
  ]
}
if (process.platform == 'darwin') {
  windowMenu.submenu.push({
    type: 'separator'
  })
  windowMenu.submenu.push({
    label: 'Bring All to Front',
    role: 'front'
  })
}

var beakerDevMenu = {
  label: 'BeakerDev',
  submenu: [{
    label: 'Reload Shell-Window',
    click: function () {
      BrowserWindow.getFocusedWindow().webContents.reloadIgnoringCache()
    }
  },{
    label: 'Toggle Shell-Window DevTools',
    click: function () {
      BrowserWindow.getFocusedWindow().toggleDevTools()
    }
  },{
    label: 'Toggle WebSecurity for new tabs',
    click: function ( item, win ) {
        if (win) win.webContents.send('command', 'window:disable-web-security' )
    }
  }]
}

export default function buildWindowMenu (env) {
  var menus = [fileMenu, editMenu, viewMenu, historyMenu, windowMenu]
  if (process.platform === 'darwin') menus.unshift(darwinMenu)
  if (env.name !== 'production') menus.push(beakerDevMenu)
  return menus
}