text:
package com.ullink.gerrit.coverage.db;

import com.google.gerrit.extensions.annotations.PluginData;
import com.google.gerrit.reviewdb.client.Patch;
import com.google.gerrit.reviewdb.client.PatchSet;
import com.google.gerrit.server.change.FileResource;
import com.google.gerrit.server.change.RevisionResource;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.ullink.gerrit.coverage.FileCoverageInfo;
import com.ullink.gerrit.coverage.PatchCoverageInput;
import com.ullink.gerrit.coverage.FileCoverageInput;
import org.mapdb.DB;
import org.mapdb.DBMaker;

import java.io.File;
import java.util.Collections;
import java.util.Map;

@Singleton
public class CoverageDb {
    private final Map<Patch.Key, Map<Integer, Integer>> hits;
    private final Map<Patch.Key, Map<Integer, Integer>> conditions;
    private final Map<Patch.Key, Map<Integer, Integer>> coveredConditions;
    private final DB db;

    @Inject
    public CoverageDb(@PluginData File dataDir) {
        db = DBMaker.newFileDB(new File(dataDir, "coverage.db"))
                .closeOnJvmShutdown()
                .make();
        hits = db.createHashMap("hits").makeOrGet();
        conditions = db.createHashMap("conditions").makeOrGet();
        coveredConditions = db.createHashMap("coveredConditions").makeOrGet();
    }

    public void registerCoverage(RevisionResource revision, PatchCoverageInput input) {
        PatchSet.Id patchSetId = revision.getPatchSet().getId();
        if (input.coverage == null) {
            return;
        }
        for (Map.Entry<String, FileCoverageInput> coverageEntry : input.coverage.entrySet()) {
            Patch.Key patchKey = new Patch.Key(patchSetId, coverageEntry.getKey());
            FileCoverageInput coverage = coverageEntry.getValue();
            hits.put(patchKey, coverage.hits);
            if (!coverage.conditions.isEmpty()) {
                conditions.put(patchKey, coverage.conditions);
            }
            if (!coverage.coveredConditions.isEmpty()) {
                coveredConditions.put(patchKey, coverage.coveredConditions);
            }
        }
        db.commit();
    }

    public FileCoverageInfo getCoverage(FileResource resource) {
        FileCoverageInfo fileCoverageInfo = new FileCoverageInfo();
        fileCoverageInfo.hits = getOrEmpty(hits, resource);
        fileCoverageInfo.conditions = getOrEmpty(conditions, resource);
        fileCoverageInfo.coveredConditions = getOrEmpty(coveredConditions, resource);
        return fileCoverageInfo;
    }

    private Map<Integer, Integer> getOrEmpty(Map<Patch.Key, Map<Integer, Integer>> map, FileResource resource) {
        Map<Integer, Integer> coverage = map.get(resource.getPatchKey());
        if (coverage == null) {
            return Collections.emptyMap();
        }
        return coverage;
    }
}


text:
/*--- formatted by Jindent 2.1, (www.c-lab.de/~jindent) ---*/

/**
 * ***************************************************************
 * JADE - Java Agent DEvelopment Framework is a framework to develop
 * multi-agent systems in compliance with the FIPA specifications.
 * Copyright (C) 2000 CSELT S.p.A.
 * GNU Lesser General Public License
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation,
 * version 2.1 of the License.
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA  02111-1307, USA.
 * **************************************************************
 */
package jade.core;

//#APIDOC_EXCLUDE_FILE

import jade.util.WrapperException;

/**
 * This exception is thrown when an error occurs in the
 * communication with a remote object
 * @author Giovanni Caire - TILAB
 * @author Nicolas Lhuillier - Motorola
 */
 public class IMTPException extends WrapperException {

  /**
   * Constructs an IMTPException with the specified detail message.
   * @param msg The detail message.
   */
  public IMTPException(String msg) {
    super(msg);
  }

  /**
   * Constructs an IMTPException with the specified detail message,
   * wrapping the given Throwableobject.
   * @param msg The detail message.
   * @param t The exception to wrap.
   */
  public IMTPException(String msg, Throwable t) {
    super(msg, t);
  }

}

redpajama_set_name: RedPajamaGithub


text:
' Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

Imports System.Composition
Imports System.Linq
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.CodeFixes
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax

Namespace Microsoft.ApiDesignGuidelines.Analyzers
    ''' <summary>
    ''' CA1028: Enum Storage should be Int32
    ''' </summary>
    <ExportCodeFixProvider(LanguageNames.VisualBasic), [Shared]>
    Public NotInheritable Class BasicEnumStorageShouldBeInt32Fixer
        Inherits EnumStorageShouldBeInt32Fixer

    End Class
End Namespace


text:
package org.lcmanager.gdb.base.health;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.lcmanager.gdb.base.BaseAspect;
import org.lcmanager.gdb.base.MathUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.Status;
import org.springframework.stereotype.Component;

/**
 * The aspect for {@link HealthRelevant}.
 *
 * @see org.lcmanager.gdb.base.health.HealthRelevant
 */
@Component
@Aspect
public class HealthAspect extends BaseAspect {
    /**
     * Represents the an UNSTABLE health status.
     *
     */
    private static final Status UNSTABLE = new Status("UNSTABLE");

    /**
     * The threshold, in percentages, when to switch from UP to
     * UNSTABLE.
     *
     */
    @Value("${health.unstable-threshold}")
    private int unstableThreshold;

    /**
     * Contains the count of the total invocations.
     *
     */
    private final Map<Integer, Integer> total = new ConcurrentHashMap<>();
    /**
     * Contains the count of the failed invocations.
     *
     */
    private final Map<Integer, Integer> error = new ConcurrentHashMap<>();

    /**
     * Wraps around all public methods of {@link HealthRelevant health-relevant}
     * classes that are not marked with {@link NoHealthTrace}.
     *
     *

     * This increments {@link #total} and {@link #error}.
     *

     *
     * @param joinPoint
     *            The proceeding join point.
     * @return The result object of the join point.
     * @throws Throwable
     *             If the join point throws an error.
     */
    @Around("within(org.lcmanager.gdb.base.health.HealthRelevant+) " //
            + "&& execution(public * *(..)) " //
            + "&& !execution(@org.lcmanager.gdb.base.health.NoHealthTrace * *(..))")
    public Object aroundHealthRelevant(final ProceedingJoinPoint joinPoint) throws Throwable {
        final Class<?> clazz = joinPoint.getTarget().getClass();

        this.incrementTotal(clazz);

        try {
            return joinPoint.proceed();
        } catch (final Throwable error) {
            this.incrementError(clazz);

            throw error;
        }
    }

    /**
     * Wraps around the {@link HealthRelevant#health()} method and provides its
     * implementation.
     *
     * @param joinPoint
     *            The join point that is only used to retrieve the implementing
     *            class.
     * @return The resulting health depending on the total invocations and the
     *         failed invocations.
     */
    @Around("execution(* org.lcmanager.gdb.base.health.HealthRelevant+ .health())")
    public Health aroundHealth(final ProceedingJoinPoint joinPoint) {
        final Class<?> clazz = joinPoint.getTarget().getClass();
        final int totalCount = this.nullOrZero(this.total.get(this.makeCountKey(clazz)));
        final int errorCount = this.nullOrZero(this.error.get(this.makeCountKey(clazz)));
        final Health.Builder healthBuilder;
        if (MathUtil.calulatePercentage(totalCount, errorCount) < this.unstableThreshold) {
            healthBuilder = Health.up();
        } else {
            healthBuilder = Health.status(HealthAspect.UNSTABLE);
        }
        healthBuilder.withDetail("total", totalCount);
        healthBuilder.withDetail("error", errorCount);
        return healthBuilder.build();
    }

    /**
     * Increments {@link #total}.
     *
     * @param clazz
     *            The key of {@link #total}.
     */
    private void incrementTotal(final Class<?> clazz) {
        this.total.put(this.makeCountKey(clazz), this.nullOrZero(this.total.get(this.makeCountKey(clazz))) + 1);
    }

    /**
     * Increments {@link #error}.
     *
     * @param clazz
     *            The key of {@link #error}.
     */
    private void incrementError(final Class<?> clazz) {
        this.error.put(this.makeCountKey(clazz), this.nullOrZero(this.error.get(this.makeCountKey(clazz))) + 1);
    }

    /**
     * Creates the key for both {@link #total} and {@link #error} from the given
     * class.
     *
     * @param clazz
     *            The class to create the key for.
     * @return The created key.
     */
    private int makeCountKey(final Class<?> clazz) {
        return clazz.hashCode();
    }

    /**
     * Converts the given {@link Integer} to and int by converting
     * null values to 0.
     *
     * @param x
     *            The number.
     * @return 0 if the given number is null.
     *         Otherwise the number.
     */
    private int nullOrZero(final Integer x) {
        return x == null ? 0 : x;
    }
}


text:
package com.uwetrottmann.trakt.v2.entities;

import org.joda.time.DateTime;

/**
 * Type to use for parsing check in error response (call {@link retrofit.RetrofitError#getBodyAs(java.lang.reflect.Type)}
 * with this class) if you get a 409 HTTP status code when checking in.
 */
public class CheckinError {

    /** Timestamp which is when the user can check in again. */
    public DateTime expires_at;

}


text:
package org.apache.commons.jexl;

import java.io.File;
import java.net.URL;
import org.apache.commons.jexl2.JexlEngine;
import org.apache.commons.jexl2.Interpreter;
import org.apache.commons.jexl2.JexlException;
import org.apache.commons.jexl2.parser.JexlNode;
import org.apache.commons.jexl2.parser.ASTJexlScript;

/**
 * This implements Jexl-1.x (Jelly) compatible behaviors on top of Jexl-2.0.
 * @since 2.0
 * @version $Id$
 */
public class JexlOne {
    /**
     * Default cache size.
     */
    private static final int CACHE_SIZE = 256;

    /**
     * Private constructor, ensure no instance.
     */
    protected JexlOne() {}

    /**
     * Lazy JexlEngine singleton through on demand holder idiom.
     */
    private static final class EngineHolder {
        /** The shared instance. */
        static final JexlOneEngine JEXL10 = new JexlOneEngine();
        /**
         * Non-instantiable.
         */
        private EngineHolder() {}
    }

    /**
     * A Jexl1.x context wrapped into a Jexl2 context.
     */
    private static final class ContextAdapter implements org.apache.commons.jexl2.JexlContext {
        /** The Jexl1.x context. */
        private final JexlContext legacy;

        /**
         * Creates a jexl2.JexlContext from a jexl.JexlContext.
         * @param ctxt10
         */
        ContextAdapter(JexlContext ctxt10) {
            legacy = ctxt10;
        }

        /**
         * {@inheritDoc}
         */
        public Object get(String name) {
            return legacy.getVars().get(name);
        }

        /**
         * {@inheritDoc}
         */
        public void set(String name, Object value) {
            legacy.getVars().put(name, value);
        }

        /**
         * {@inheritDoc}
         */
        public boolean has(String name) {
            return legacy.getVars().containsKey(name);
        }

        /**
         * Adapts a Jexl-1.x context to a Jexl-2.0 context.
         * @param aContext a oac.jexl context
         * @return an oac.jexl2 context
         */
        static final org.apache.commons.jexl2.JexlContext adapt(JexlContext aContext) {
            return aContext == null ? JexlOneEngine.EMPTY_CONTEXT : new ContextAdapter(aContext);
        }
    }

    /**
     * An interpreter made compatible with v1.1 behavior (at least Jelly's expectations).
     */
    private static final class JexlOneInterpreter extends Interpreter {
        /**
         * Creates an instance.
         * @param jexl the jexl engine
         * @param aContext the jexl context
         */
        public JexlOneInterpreter(JexlEngine jexl, JexlContext aContext) {
            super(jexl, ContextAdapter.adapt(aContext), false, false);
        }

        /**{@inheritDoc}*/
        @Override
        public Object interpret(JexlNode node) {
            try {
                return node.jjtAccept(this, null);
            } catch (JexlException xjexl) {
                Throwable e = xjexl.getCause();
                if (e instanceof RuntimeException) {
                    throw (RuntimeException) e;
                }
                if (e instanceof IllegalStateException) {
                    throw (IllegalStateException) e;
                }
                throw new IllegalStateException(e.getMessage(), e);
            }
        }

        /**{@inheritDoc}*/
        @Override
        protected Object invocationFailed(JexlException xjexl) {
            throw xjexl;
        }

        /**{@inheritDoc}*/
        @Override
        protected Object unknownVariable(JexlException xjexl) {
            return null;
        }
    }

    /**
     * An engine that uses a JexlOneInterpreter.
     */
    private static final class JexlOneEngine extends JexlEngine {
        /**
         * Default ctor, creates a cache and sets instance to verbose (ie non-silent).
         */
        private JexlOneEngine() {
            super();
            setCache(CACHE_SIZE);
            setSilent(false);
        }

        /**{@inheritDoc}*/
        protected Interpreter createInterpreter(JexlContext context) {
            return new JexlOneInterpreter(this, context);
        }

        /** {@inheritDoc} */
        @Override
        protected Script createScript(ASTJexlScript tree, String text) {
            return new JexlOneExpression(this, text, tree);
        }

        /** {@inheritDoc} */
        @Override
        protected Expression createExpression(ASTJexlScript tree, String text) {
            return new JexlOneExpression(this, text, tree);
        }
    }

    /**
     * The specific Jexl-1.x expressions implementation.
     */
    private static final class JexlOneExpression
            extends org.apache.commons.jexl2.ExpressionImpl
            implements Expression, Script {
        /**
         * Default local ctor.
         *
         * @param engine the interpreter to evaluate the expression
         * @param expr the expression.
         * @param ref the parsed expression.
         */
        private JexlOneExpression(JexlOne.JexlOneEngine engine, String expr, ASTJexlScript ref) {
            super(engine, expr, ref);
        }

        /**
         * {@inheritDoc}
         */
        public Object evaluate(JexlContext context) {
            return super.evaluate(ContextAdapter.adapt(context));
        }

        /**
         * {@inheritDoc}
         */
        public Object execute(JexlContext context) {
            return super.execute(ContextAdapter.adapt(context));
        }
    }

    /**
     * Creates a Script from a String containing valid JEXL syntax.
     * This method parses the script which validates the syntax.
     *
     * @param scriptText A String containing valid JEXL syntax
     * @return A {@link Script} which can be executed with a
     *      {@link JexlContext}.
     * @throws Exception An exception can be thrown if there is a
     *      problem parsing the script.
     * @deprecated Create a JexlEngine and use the createScript method on that instead.
     */
    @Deprecated
    public static Script createScript(String scriptText) throws Exception {
        return (Script) EngineHolder.JEXL10.createScript(scriptText);
    }

    /**
     * Creates a Script from a {@link File} containing valid JEXL syntax.
     * This method parses the script and validates the syntax.
     *
     * @param scriptFile A {@link File} containing valid JEXL syntax.
     *      Must not be null. Must be a readable file.
     * @return A {@link Script} which can be executed with a
     *      {@link JexlContext}.
     * @throws Exception An exception can be thrown if there is a problem
     *      parsing the script.
     * @deprecated Create a JexlEngine and use the createScript method on that instead.
     */
    @Deprecated
    public static Script createScript(File scriptFile) throws Exception {
        return (Script) EngineHolder.JEXL10.createScript(scriptFile);
    }

    /**
     * Creates a Script from a {@link URL} containing valid JEXL syntax.
     * This method parses the script and validates the syntax.
     *
     * @param scriptUrl A {@link URL} containing valid JEXL syntax.
     *      Must not be null. Must be a readable file.
     * @return A {@link Script} which can be executed with a
     *      {@link JexlContext}.
     * @throws Exception An exception can be thrown if there is a problem
     *      parsing the script.
     * @deprecated Create a JexlEngine and use the createScript method on that instead.
     */
    @Deprecated
    public static Script createScript(URL scriptUrl) throws Exception {
        return (Script) EngineHolder.JEXL10.createScript(scriptUrl);
    }

    /**
     * Creates an Expression from a String containing valid
     * JEXL syntax.  This method parses the expression which
     * must contain either a reference or an expression.
     * @param expression A String containing valid JEXL syntax
     * @return An Expression object which can be evaluated with a JexlContext
     * @throws JexlException An exception can be thrown if there is a problem
     *      parsing this expression, or if the expression is neither an
     *      expression or a reference.
     * @deprecated Create a JexlEngine and use createExpression() on that
     */
    @Deprecated
    public static Expression createExpression(String expression) {
        return (Expression) EngineHolder.JEXL10.createExpression(expression);
    }
}


text:
ifdef GAMMADIR
  ifndef ALT_OUTPUTDIR
    ALT_OUTPUTDIR := $(shell pwd)
  endif
  include $(GAMMADIR)/make/defs.make
else
  include defs.make
endif

include $(GAMMADIR)/make/altsrc.make

ifneq ($(ALT_OUTPUTDIR),)
  ALT_OUT=ALT_OUTPUTDIR=$(ALT_OUTPUTDIR)
else
  ALT_OUT=
endif

# Typical C1/C2 targets made available with this Makefile
C1_VM_TARGETS=product1 fastdebug1 optimized1 jvmg1
C2_VM_TARGETS=product  fastdebug  optimized  jvmg
ZERO_VM_TARGETS=productzero fastdebugzero optimizedzero jvmgzero
SHARK_VM_TARGETS=productshark fastdebugshark optimizedshark jvmgshark

COMMON_VM_PRODUCT_TARGETS=product product1 docs export_product
COMMON_VM_FASTDEBUG_TARGETS=fastdebug fastdebug1 docs export_fastdebug
COMMON_VM_DEBUG_TARGETS=jvmg jvmg1 docs export_debug

# JDK directory list
JDK_DIRS=bin include jre lib demo

all:           all_product all_fastdebug

ifdef BUILD_CLIENT_ONLY
all_product:   product1 docs export_product
all_fastdebug: fastdebug1 docs export_fastdebug
all_debug:     jvmg1 docs export_debug
else
ifeq ($(MACOSX_UNIVERSAL),true)
all_product:   universal_product
all_fastdebug: universal_fastdebug
all_debug:     universal_debug
else
all_product:   $(COMMON_VM_PRODUCT_TARGETS)
all_fastdebug: $(COMMON_VM_FASTDEBUG_TARGETS)
all_debug:     $(COMMON_VM_DEBUG_TARGETS)
endif
endif

all_optimized: optimized optimized1 docs export_optimized

allzero:           all_productzero all_fastdebugzero
all_productzero:   productzero docs export_product
all_fastdebugzero: fastdebugzero docs export_fastdebug
all_debugzero:     jvmgzero docs export_debug
all_optimizedzero: optimizedzero docs export_optimized

allshark:           all_productshark all_fastdebugshark
all_productshark:   productshark docs export_product
all_fastdebugshark: fastdebugshark docs export_fastdebug
all_debugshark:     jvmgshark docs export_debug
all_optimizedshark: optimizedshark docs export_optimized

# Do everything
world:         all create_jdk

#$(error ABS_OS_MAKEFILE=$(ABS_OS_MAKEFILE))

# Build or export docs
docs:
ifeq ($(OSNAME),windows)
	@$(ECHO) "No docs ($(VM_TARGET)) for windows"
else
# We specify 'BUILD_FLAVOR=product' so that the proper
# ENABLE_FULL_DEBUG_SYMBOLS value is used.
	$(CD) $(OUTPUTDIR); \
	    $(MAKE) -f $(ABS_OS_MAKEFILE) \
		      $(MAKE_ARGS) BUILD_FLAVOR=product docs
endif

# Build variation of hotspot
$(C1_VM_TARGETS):
	$(CD) $(GAMMADIR)/make; \
	$(MAKE) BUILD_FLAVOR=$(@:%1=%) VM_TARGET=$@ generic_build1 $(ALT_OUT)

$(C2_VM_TARGETS):
	$(CD) $(GAMMADIR)/make; \
	$(MAKE) BUILD_FLAVOR=$@ VM_TARGET=$@ generic_build2 $(ALT_OUT)

$(ZERO_VM_TARGETS):
	$(CD) $(GAMMADIR)/make; \
	$(MAKE) BUILD_FLAVOR=$(@:%zero=%) VM_TARGET=$@ \
	  generic_buildzero $(ALT_OUT)

$(SHARK_VM_TARGETS):
	$(CD) $(GAMMADIR)/make; \
	$(MAKE) BUILD_FLAVOR=$(@:%shark=%) VM_TARGET=$@ \
	  generic_buildshark $(ALT_OUT)

# Build compiler1 (client) rule, different for platforms
generic_build1:
	$(MKDIR) -p $(OUTPUTDIR)
ifeq ($(OSNAME),windows)
  ifeq ($(ARCH_DATA_MODEL), 32)
	$(CD) $(OUTPUTDIR); \
	    $(NMAKE) -f $(ABS_OS_MAKEFILE) \
		      Variant=compiler1 \
                      WorkSpace=$(ABS_GAMMADIR) \
		      BootStrapDir=$(ABS_BOOTDIR) \
                      BuildUser=$(USERNAME) \
		      $(MAKE_ARGS) $(VM_TARGET:%1=%)
  else
	@$(ECHO) "No compiler1 ($(VM_TARGET)) for ARCH_DATA_MODEL=$(ARCH_DATA_MODEL)"
  endif
else
  ifeq ($(ARCH_DATA_MODEL), 32)
	$(CD) $(OUTPUTDIR); \
	    $(MAKE) -f $(ABS_OS_MAKEFILE) \
		      $(MAKE_ARGS) $(VM_TARGET)
  else
	@$(ECHO) "No compiler1 ($(VM_TARGET)) for ARCH_DATA_MODEL=$(ARCH_DATA_MODEL)"
  endif
endif

# Build compiler2 (server) rule, different for platforms
generic_build2:
	$(MKDIR) -p $(OUTPUTDIR)
ifeq ($(OSNAME),windows)
	$(CD) $(OUTPUTDIR); \
	    $(NMAKE) -f $(ABS_OS_MAKEFILE) \
		      Variant=compiler2 \
                      WorkSpace=$(ABS_GAMMADIR) \
		      BootStrapDir=$(ABS_BOOTDIR) \
                      BuildUser=$(USERNAME) \
		      $(MAKE_ARGS) $(VM_TARGET)
else
	$(CD) $(OUTPUTDIR); \
	    $(MAKE) -f $(ABS_OS_MAKEFILE) \
		      $(MAKE_ARGS) $(VM_TARGET)
endif

generic_buildzero:
	$(MKDIR) -p $(OUTPUTDIR)
	$(CD) $(OUTPUTDIR); \
		$(MAKE) -f $(ABS_OS_MAKEFILE) \
			$(MAKE_ARGS) $(VM_TARGET)

generic_buildshark:
	$(MKDIR) -p $(OUTPUTDIR)
	$(CD) $(OUTPUTDIR); \
		$(MAKE) -f $(ABS_OS_MAKEFILE) \
			$(MAKE_ARGS) $(VM_TARGET)

# Export file rule
generic_export: $(EXPORT_LIST)
export_product:
	$(MAKE) BUILD_FLAVOR=$(@:export_%=%) VM_SUBDIR=$(@:export_%=%) \
          generic_export
export_fastdebug:
	$(MAKE) BUILD_FLAVOR=$(@:export_%=%) VM_SUBDIR=$(@:export_%=%) \
	  EXPORT_SUBDIR=/$(@:export_%=%) \
	  generic_export
export_debug:
	$(MAKE) BUILD_FLAVOR=$(@:export_%=%) VM_SUBDIR=${VM_DEBUG} \
	  EXPORT_SUBDIR=/$(@:export_%=%) \
	  generic_export
export_optimized:
	$(MAKE) BUILD_FLAVOR=$(@:export_%=%) VM_SUBDIR=$(@:export_%=%) \
	  EXPORT_SUBDIR=/$(@:export_%=%) \
	  generic_export
export_product_jdk::
	$(MAKE) BUILD_FLAVOR=$(@:export_%_jdk=%) \
	  VM_SUBDIR=$(@:export_%_jdk=%) ALT_EXPORT_PATH=$(JDK_IMAGE_DIR) \
	  generic_export
export_optimized_jdk::
	$(MAKE) BUILD_FLAVOR=$(@:export_%_jdk=%) \
	  VM_SUBDIR=$(@:export_%_jdk=%) ALT_EXPORT_PATH=$(JDK_IMAGE_DIR) \
	  generic_export
export_fastdebug_jdk::
	$(MAKE) BUILD_FLAVOR=$(@:export_%_jdk=%) \
	  VM_SUBDIR=$(@:export_%_jdk=%)  \
	  ALT_EXPORT_PATH=$(JDK_IMAGE_DIR)/$(@:export_%_jdk=%) \
	  generic_export
export_debug_jdk::
	$(MAKE) BUILD_FLAVOR=$(@:export_%_jdk=%) VM_SUBDIR=${VM_DEBUG} \
	  ALT_EXPORT_PATH=$(JDK_IMAGE_DIR)/$(@:export_%_jdk=%) \
	  generic_export

# Export file copy rules
XUSAGE=$(HS_SRC_DIR)/share/vm/Xusage.txt
DOCS_DIR=$(OUTPUTDIR)/$(VM_PLATFORM)_docs
C1_BASE_DIR=$(OUTPUTDIR)/$(VM_PLATFORM)_compiler1
C2_BASE_DIR=$(OUTPUTDIR)/$(VM_PLATFORM)_compiler2
ZERO_BASE_DIR=$(OUTPUTDIR)/$(VM_PLATFORM)_zero
SHARK_BASE_DIR=$(OUTPUTDIR)/$(VM_PLATFORM)_shark
C1_DIR=$(C1_BASE_DIR)/$(VM_SUBDIR)
C2_DIR=$(C2_BASE_DIR)/$(VM_SUBDIR)
ZERO_DIR=$(ZERO_BASE_DIR)/$(VM_SUBDIR)
SHARK_DIR=$(SHARK_BASE_DIR)/$(VM_SUBDIR)

ifeq ($(JVM_VARIANT_SERVER), true)
    MISC_DIR=$(C2_DIR)
    GEN_DIR=$(C2_BASE_DIR)/generated
endif
ifeq ($(JVM_VARIANT_CLIENT), true)
    MISC_DIR=$(C1_DIR)
    GEN_DIR=$(C1_BASE_DIR)/generated
endif
ifeq ($(JVM_VARIANT_ZEROSHARK), true)
    MISC_DIR=$(SHARK_DIR)
    GEN_DIR=$(SHARK_BASE_DIR)/generated
endif
ifeq ($(JVM_VARIANT_ZERO), true)
    MISC_DIR=$(ZERO_DIR)
    GEN_DIR=$(ZERO_BASE_DIR)/generated
endif

# Bin files (windows)
ifeq ($(OSNAME),windows)

# Get jvm.lib
$(EXPORT_LIB_DIR)/%.lib:  $(MISC_DIR)/%.lib
	$(install-file)

# Other libraries (like SA)
$(EXPORT_JRE_BIN_DIR)/%.diz: $(MISC_DIR)/%.diz
	$(install-file)
$(EXPORT_JRE_BIN_DIR)/%.dll: $(MISC_DIR)/%.dll
	$(install-file)
$(EXPORT_JRE_BIN_DIR)/%.pdb: $(MISC_DIR)/%.pdb
	$(install-file)
$(EXPORT_JRE_BIN_DIR)/%.map: $(MISC_DIR)/%.map
	$(install-file)

# Client files always come from C1 area
$(EXPORT_CLIENT_DIR)/%.diz:  $(C1_DIR)/%.diz
	$(install-file)
$(EXPORT_CLIENT_DIR)/%.dll:  $(C1_DIR)/%.dll
	$(install-file)
$(EXPORT_CLIENT_DIR)/%.pdb:  $(C1_DIR)/%.pdb
	$(install-file)
$(EXPORT_CLIENT_DIR)/%.map:  $(C1_DIR)/%.map
	$(install-file)

# Server files always come from C2 area
$(EXPORT_SERVER_DIR)/%.diz:  $(C2_DIR)/%.diz
	$(install-file)
$(EXPORT_SERVER_DIR)/%.dll:  $(C2_DIR)/%.dll
	$(install-file)
$(EXPORT_SERVER_DIR)/%.pdb:  $(C2_DIR)/%.pdb
	$(install-file)
$(EXPORT_SERVER_DIR)/%.map:  $(C2_DIR)/%.map
	$(install-file)
endif

# Shared Library
ifneq ($(OSNAME),windows)
    ifeq ($(JVM_VARIANT_SERVER), true)
        $(EXPORT_JRE_LIB_ARCH_DIR)/%.$(LIBRARY_SUFFIX): $(C2_DIR)/%.$(LIBRARY_SUFFIX)
		$(install-file)
        $(EXPORT_SERVER_DIR)/%.$(LIBRARY_SUFFIX):       $(C2_DIR)/%.$(LIBRARY_SUFFIX)
		$(install-file)
        $(EXPORT_SERVER_DIR)/64/%.$(LIBRARY_SUFFIX):    $(C2_DIR)/%.$(LIBRARY_SUFFIX)
		$(install-file)
        $(EXPORT_JRE_LIB_ARCH_DIR)/%.debuginfo: 		$(C2_DIR)/%.debuginfo
		$(install-file)
        $(EXPORT_SERVER_DIR)/%.debuginfo:       		$(C2_DIR)/%.debuginfo
		$(install-file)
        $(EXPORT_SERVER_DIR)/64/%.debuginfo:    		$(C2_DIR)/%.debuginfo
		$(install-file)
        $(EXPORT_JRE_LIB_ARCH_DIR)/%.diz: 			$(C2_DIR)/%.diz
		$(install-file)
        $(EXPORT_SERVER_DIR)/%.diz:       			$(C2_DIR)/%.diz
		$(install-file)
        $(EXPORT_SERVER_DIR)/64/%.diz:    			$(C2_DIR)/%.diz
		$(install-file)
    endif
    ifeq ($(JVM_VARIANT_CLIENT), true)
        $(EXPORT_JRE_LIB_ARCH_DIR)/%.$(LIBRARY_SUFFIX): $(C1_DIR)/%.$(LIBRARY_SUFFIX)
		$(install-file)
        $(EXPORT_CLIENT_DIR)/%.$(LIBRARY_SUFFIX):       $(C1_DIR)/%.$(LIBRARY_SUFFIX)
		$(install-file)
        $(EXPORT_CLIENT_DIR)/64/%.$(LIBRARY_SUFFIX):    $(C1_DIR)/%.$(LIBRARY_SUFFIX)
		$(install-file)
        $(EXPORT_JRE_LIB_ARCH_DIR)/%.debuginfo: 		$(C1_DIR)/%.debuginfo
		$(install-file)
        $(EXPORT_CLIENT_DIR)/%.debuginfo:       		$(C1_DIR)/%.debuginfo
		$(install-file)
        $(EXPORT_CLIENT_DIR)/64/%.debuginfo:    		$(C1_DIR)/%.debuginfo
		$(install-file)
        $(EXPORT_JRE_LIB_ARCH_DIR)/%.diz: 			$(C1_DIR)/%.diz
		$(install-file)
        $(EXPORT_CLIENT_DIR)/%.diz:       			$(C1_DIR)/%.diz
		$(install-file)
        $(EXPORT_CLIENT_DIR)/64/%.diz:    			$(C1_DIR)/%.diz
		$(install-file)
    endif
    ifeq ($(JVM_VARIANT_ZEROSHARK), true)
        $(EXPORT_JRE_LIB_ARCH_DIR)/%.$(LIBRARY_SUFFIX): $(SHARK_DIR)/%.$(LIBRARY_SUFFIX)
		$(install-file)
        $(EXPORT_JRE_LIB_ARCH_DIR)/%.debuginfo:	$(SHARK_DIR)/%.debuginfo
		$(install-file)
        $(EXPORT_JRE_LIB_ARCH_DIR)/%.diz:		$(SHARK_DIR)/%.diz
		$(install-file)
        $(EXPORT_SERVER_DIR)/%.$(LIBRARY_SUFFIX):       $(SHARK_DIR)/%.$(LIBRARY_SUFFIX)
		$(install-file)
        $(EXPORT_SERVER_DIR)/%.debuginfo:		$(SHARK_DIR)/%.debuginfo
		$(install-file)
        $(EXPORT_SERVER_DIR)/%.diz:			$(SHARK_DIR)/%.diz
		$(install-file)
    endif
    ifeq ($(JVM_VARIANT_ZERO), true)
        $(EXPORT_JRE_LIB_ARCH_DIR)/%.$(LIBRARY_SUFFIX): $(ZERO_DIR)/%.$(LIBRARY_SUFFIX)
		$(install-file)
        $(EXPORT_JRE_LIB_ARCH_DIR)/%.debuginfo:		$(ZERO_DIR)/%.debuginfo
		$(install-file)
        $(EXPORT_JRE_LIB_ARCH_DIR)/%.diz:		$(ZERO_DIR)/%.diz
		$(install-file)
        $(EXPORT_SERVER_DIR)/%.$(LIBRARY_SUFFIX):       $(ZERO_DIR)/%.$(LIBRARY_SUFFIX)
		$(install-file)
        $(EXPORT_SERVER_DIR)/%.debuginfo:		$(ZERO_DIR)/%.debuginfo
		$(install-file)
        $(EXPORT_SERVER_DIR)/%.diz:			$(ZERO_DIR)/%.diz
		$(install-file)
    endif
endif

# Jar file (sa-jdi.jar)
$(EXPORT_LIB_DIR)/%.jar: $(GEN_DIR)/%.jar
	$(install-file)

# Include files (jvmti.h, jvmticmlr.h, jni.h, $(JDK_INCLUDE_SUBDIR)/jni_md.h, jmm.h, jfr.h)
$(EXPORT_INCLUDE_DIR)/%: $(GEN_DIR)/jvmtifiles/%
	$(install-file)

$(EXPORT_INCLUDE_DIR)/%: $(HS_SRC_DIR)/share/vm/code/%
	$(install-file)

$(EXPORT_INCLUDE_DIR)/%: $(HS_SRC_DIR)/share/vm/prims/%
	$(install-file)

HS_JNI_ARCH_SRC=$(call altsrc-replace,$(HS_COMMON_SRC)/cpu/$(HS_ARCH)/vm/jni_$(HS_ARCH).h)
$(EXPORT_INCLUDE_DIR)/$(JDK_INCLUDE_SUBDIR)/jni_md.h: $(HS_JNI_ARCH_SRC)
	$(install-file)

$(EXPORT_INCLUDE_DIR)/%: $(HS_SRC_DIR)/share/vm/services/%
	$(install-file)

JFR_EXISTS=$(shell if [ -d $(HS_ALT_SRC) ]; then echo 1; else echo 0; fi)
# export jfr.h
ifeq ($JFR_EXISTS,1)
$(EXPORT_INCLUDE_DIR)/%: $(HS_ALT_SRC)/share/vm/jfr/%
	$(install-file)
else
$(EXPORT_INCLUDE_DIR)/jfr.h:
endif

# Doc files (jvmti.html)
$(EXPORT_DOCS_DIR)/platform/jvmti/%: $(DOCS_DIR)/%
	$(install-file)

# Xusage file
$(EXPORT_SERVER_DIR)/Xusage.txt $(EXPORT_CLIENT_DIR)/Xusage.txt: $(XUSAGE)
	$(prep-target)
	$(RM) $@.temp
	$(SED) 's/\(separated by \)[;:]/\1$(PATH_SEP)/g' $< > $@.temp
	$(MV) $@.temp $@

#
# Clean rules
#
clobber clean: clean_build clean_export clean_jdk
clean_build:
	$(RM) -r $(C1_DIR)
	$(RM) -r $(C2_DIR)
	$(RM) -r $(ZERO_DIR)
	$(RM) -r $(SHARK_DIR)
clean_export:
	$(RM) -r $(EXPORT_PATH)
clean_jdk:
	$(RM) -r $(JDK_IMAGE_DIR)

#
# Create JDK and place this build into it
#
create_jdk: copy_jdk update_jdk

update_jdk: export_product_jdk export_fastdebug_jdk test_jdk

copy_jdk: $(JDK_IMAGE_DIR)/jre/lib/rt.jar

$(JDK_IMAGE_DIR)/jre/lib/rt.jar:
	$(RM) -r $(JDK_IMAGE_DIR)
	$(MKDIR) -p $(JDK_IMAGE_DIR)
	($(CD) $(JDK_IMPORT_PATH) && \
	 $(TAR) -cf - *) | \
	 ($(CD) $(JDK_IMAGE_DIR) && $(TAR) -xf -)

test_jdk:
  ifeq ($(JVM_VARIANT_CLIENT), true)
	$(JDK_IMAGE_DIR)/bin/java -d$(ARCH_DATA_MODEL) -client -Xinternalversion
	$(JDK_IMAGE_DIR)/bin/java -d$(ARCH_DATA_MODEL) -client -version
  endif
  ifeq ($(findstring true, $(JVM_VARIANT_SERVER)\
		$(JVM_VARIANT_ZERO)$(JVM_VARIANT_ZEROSHARK)), true)
	$(JDK_IMAGE_DIR)/bin/java -d$(ARCH_DATA_MODEL) -server -Xinternalversion
	$(JDK_IMAGE_DIR)/bin/java -d$(ARCH_DATA_MODEL) -server -version
  endif

copy_product_jdk::
	$(RM) -r $(JDK_IMAGE_DIR)
	$(MKDIR) -p $(JDK_IMAGE_DIR)
	($(CD) $(JDK_IMPORT_PATH) && \
	 $(TAR) -cf - $(JDK_DIRS)) | \
	 ($(CD) $(JDK_IMAGE_DIR) && $(TAR) -xf -)

copy_fastdebug_jdk::
	$(RM) -r $(JDK_IMAGE_DIR)/fastdebug
	$(MKDIR) -p $(JDK_IMAGE_DIR)/fastdebug
	if [ -d $(JDK_IMPORT_PATH)/fastdebug ] ; then \
	  ($(CD) $(JDK_IMPORT_PATH)/fastdebug && \
	   $(TAR) -cf - $(JDK_DIRS)) | \
	   ($(CD) $(JDK_IMAGE_DIR)/fastdebug && $(TAR) -xf -) ; \
	else \
	  ($(CD) $(JDK_IMPORT_PATH) && \
	   $(TAR) -cf - $(JDK_DIRS)) | \
	   ($(CD) $(JDK_IMAGE_DIR)/fastdebug && $(TAR) -xf -) ; \
	fi

copy_debug_jdk::
	$(RM) -r $(JDK_IMAGE_DIR)/debug
	$(MKDIR) -p $(JDK_IMAGE_DIR)/debug
	if [ -d $(JDK_IMPORT_PATH)/debug ] ; then \
	  ($(CD) $(JDK_IMPORT_PATH)/debug && \
	   $(TAR) -cf - $(JDK_DIRS)) | \
	   ($(CD) $(JDK_IMAGE_DIR)/debug && $(TAR) -xf -) ; \
	elif [ -d $(JDK_IMPORT_PATH)/fastdebug ] ; then \
	  ($(CD) $(JDK_IMPORT_PATH)/fastdebug && \
	   $(TAR) -cf - $(JDK_DIRS)) | \
	   ($(CD) $(JDK_IMAGE_DIR)/debug && $(TAR) -xf -) ; \
	else \
	  ($(CD) $(JDK_IMPORT_PATH) && \
	   $(TAR) -cf - $(JDK_DIRS)) | \
	   ($(CD) $(JDK_IMAGE_DIR)/debug && $(TAR) -xf -) ; \
	fi

#
# Check target
#
check: variable_check

#
# Help target
#
help: intro_help target_help variable_help notes_help examples_help

# Intro help message
intro_help:
	@$(ECHO) \
"Makefile for the Hotspot workspace."
	@$(ECHO) \
"Default behavior is to build and create an export area for the j2se builds."

# Target help
target_help:
	@$(ECHO) "help:             This help message"
	@$(ECHO) "all:              Same as: all_product all_fastdebug"
	@$(ECHO) "world:            Same as: all create_jdk"
	@$(ECHO) "all_product:      Same as: product product1 export_product"
	@$(ECHO) "all_fastdebug:    Same as: fastdebug fastdebug1 export_fastdebug"
	@$(ECHO) "all_debug:        Same as: jvmg jvmg1 export_debug"
	@$(ECHO) "all_optimized:    Same as: optimized optimized1 export_optimized"
	@$(ECHO) "clean:            Clean all areas"
	@$(ECHO) "export_product:   Export product files to EXPORT_PATH"
	@$(ECHO) "export_fastdebug: Export fastdebug files to EXPORT_PATH"
	@$(ECHO) "export_debug:     Export debug files to EXPORT_PATH"
	@$(ECHO) "export_optimized: Export optimized files to EXPORT_PATH"
	@$(ECHO) "create_jdk:       Create JDK image, export all files into it"
	@$(ECHO) "update_jdk:       Update JDK image with fresh exported files"
	@$(ECHO) " "
	@$(ECHO) "Others targets are:"
	@$(ECHO) "   $(C1_VM_TARGETS)"
	@$(ECHO) "   $(C2_VM_TARGETS)"

# Variable help (only common ones used by this workspace)
variable_help: variable_help_intro variable_list variable_help_end
variable_help_intro:
	@$(ECHO) "--- Common Variables ---"
variable_help_end:
	@$(ECHO) " "
	@$(ECHO) "--- Make Arguments ---"
	@$(ECHO) "MAKE_ARGS=$(MAKE_ARGS)"

# One line descriptions for the variables
SLASH_JAVA.desc            = Root of all build tools, e.g. /java or J:
OUTPUTDIR.desc             = Output directory, default is build/<osname>
BOOTDIR.desc               = JDK used to compile agent java source and test with
JDK_IMPORT_PATH.desc       = Promoted JDK to copy for 'create_jdk'
JDK_IMAGE_DIR.desc         = Directory to place JDK to copy
EXPORT_PATH.desc           = Directory to place files to export for JDK build

# Make variables to print out (description and value)
VARIABLE_PRINTVAL_LIST +=       \
    SLASH_JAVA                  \
    OUTPUTDIR                   \
    BOOTDIR                     \
    JDK_IMPORT_PATH             \
    JDK_IMAGE_DIR               \
    EXPORT_PATH

# Make variables that should refer to directories that exist
VARIABLE_CHECKDIR_LIST +=       \
    SLASH_JAVA                  \
    BOOTDIR                     \
    JDK_IMPORT_PATH

# For pattern rules below, so all are treated the same
DO_PRINTVAL_LIST=$(VARIABLE_PRINTVAL_LIST:%=%.printval)
DO_CHECKDIR_LIST=$(VARIABLE_CHECKDIR_LIST:%=%.checkdir)

# Complete variable check
variable_check: $(DO_CHECKDIR_LIST)
variable_list: $(DO_PRINTVAL_LIST) variable_check

# Pattern rule for printing out a variable
%.printval:
	@$(ECHO) "  ALT_$* - $($*.desc)"
	@$(ECHO) "        $*=$($*)"

# Pattern rule for checking to see if a variable with a directory exists
%.checkdir:
	@if [ ! -d $($*) ] ; then \
	    $(ECHO) "WARNING: $* does not exist, try $(MAKE) sanity"; \
	fi

# Pattern rule for checking to see if a variable with a file exists
%.checkfil:
	@if [ ! -f $($*) ] ; then \
	    $(ECHO) "WARNING: $* does not exist, try $(MAKE) sanity"; \
	fi

# Misc notes on help
notes_help:
	@$(ECHO) \
"--- Notes --- "
	@$(ECHO) \
"- JDK_IMPORT_PATH must refer to a compatible build, not all past promoted"
	@$(ECHO) \
"        builds or previous release JDK builds will work."
	@$(ECHO) \
"- The fastest builds have been when the workspace and the BOOTDIR are on"
	@$(ECHO) \
"        local disk."

examples_help:
	@$(ECHO) \
"--- Examples --- "
	@$(ECHO) \
"  $(MAKE) all"
	@$(ECHO) \
"  $(MAKE) world"
	@$(ECHO) \
"  $(MAKE) ALT_BOOTDIR=/opt/java/jdk$(PREVIOUS_JDK_VERSION)"
	@$(ECHO) \
"  $(MAKE) ALT_JDK_IMPORT_PATH=/opt/java/jdk$(JDK_VERSION)"

# Universal build support
ifeq ($(OS_VENDOR), Darwin)
ifeq ($(MACOSX_UNIVERSAL),true)
include $(GAMMADIR)/make/$(OSNAME)/makefiles/universal.gmk
endif
endif

# JPRT rule to build this workspace
include $(GAMMADIR)/make/jprt.gmk

.PHONY: all world clobber clean help $(C1_VM_TARGETS) $(C2_VM_TARGETS) \
	generic_build1 generic_build2 generic_export \
	export_product export_fastdebug export_debug export_optimized \
	export_jdk_product export_jdk_fastdebug export_jdk_debug \
	create_jdk copy_jdk update_jdk test_jdk \
	copy_product_jdk copy_fastdebug_jdk copy_debug_jdk


text:
export const FETCH_MESSAGES_REQUEST  = 'FETCH_MESSAGES_REQUEST';
export const FETCH_MESSAGES_SUCCESS  = 'FETCH_MESSAGES_SUCCESS';
export const FETCH_MESSAGES_ERROR    = 'FETCH_MESSAGES_ERROR';
export const CREATE_MESSAGE_REQUEST  = 'CREATE_MESSAGE_REQUEST';
export const CREATE_MESSAGE_SUCCESS  = 'CREATE_MESSAGE_SUCCESS';
export const CREATE_MESSAGE_ERROR    = 'CREATE_MESSAGE_ERROR';
export const UPDATE_MESSAGE_REQUEST  = 'UPDATE_MESSAGE_REQUEST';
export const UPDATE_MESSAGE_SUCCESS  = 'UPDATE_MESSAGE_SUCCESS';
export const UPDATE_MESSAGE_ERROR    = 'UPDATE_MESSAGE_ERROR';
export const DELETE_MESSAGE_REQUEST  = 'DELETE_MESSAGE_REQUEST';
export const DELETE_MESSAGE_SUCCESS  = 'DELETE_MESSAGE_SUCCESS';
export const DELETE_MESSAGE_ERROR    = 'DELETE_MESSAGE_ERROR';


text:
// -----------------------------------------------------
// Init routines
// -----------------------------------------------------
require( "./init" );

/**
 * Module dependencies.
 */

var valise = require( "valise" )
	, express = require( "express" )
  , routes = require( "./routes" )
  , http = require( "http" )
  , path = require( "path" )
  , nconf = valise( "lib:config-util" ).nconf
	, app = express()
  , appio = express()
  , socketio = require( "socket.io" )
  , socketUtil = valise( "lib:socket-util" )
  , monitorUtil = valise( "lib:monitor-util" )
  , envConf = nconf.get( "env" )
  , monitorConf = nconf.get( "monitor" )
  , ioserver
  , io
	;

// -----------------------------------------------------
// General app configuration
// -----------------------------------------------------
app.configure(function(){
  app.set( "port", process.env.PORT || envConf.port );
  app.set( "views", __dirname + "/views" );
  app.set( "view engine", "jade" );
  app.use( express.favicon() );
  app.use( express.logger("dev") );
  app.use( express.bodyParser() );
  app.use( express.methodOverride() );
  app.use( require("less-middleware")({ src: __dirname + "/public" }) );
  app.use( express["static"](path.join(__dirname, "public")) );
	app.use( valise( "lib:middleware" ).markdown );
  app.use( app.router );
});

// -----------------------------------------------------
// Development specific configs
// -----------------------------------------------------
app.configure( "development", function() {
  app.use( express.errorHandler() );
});

// ---------------------------------------------
// Set up environment variables
// ---------------------------------------------

process.env.CHECK_BADNESS = true; // Enable badness checking

// ---------------------------------------------
// Socket.io server
// ---------------------------------------------
ioserver = http.createServer( appio );
io = socketio.listen(ioserver);
io.set('log level', 2); // log error, warn, and info
ioserver.listen(envConf.socketPort);
io.sockets.on('connection', function(socket) {
  socketUtil.pool.push(socket);
  // Let this one socket know the current value of the CHECK_BADNESS variable
  socket.emit('checkBadness', process.env.CHECK_BADNESS);
});

// -----------------------------------------------------
// Offload our routing setup... could get longish
// -----------------------------------------------------
require( "./routes/_map" )( app );

// ---------------------------------------------
// Create a server listening on the specified port
// ---------------------------------------------
http.createServer( app ).listen( app.get( "port" ), function(){
  console.log( "Express server listening on port " + app.get( "port" ) );
});

// ---------------------------------------------
// Start the watchdog if 4dmon is configured to
// start the monitor on startup
// ---------------------------------------------
if(monitorConf.runOnStartup) {
  monitorUtil.startMonitor();
}


text:
package main

import (
	"log"
	"strconv"
	"strings"

	"github.com/gocolly/colly"
)

func defaultCmd(config *Config) {
	scrapeGames(config)

	config.InitialCollector.OnHTML("#main_content", func(e *colly.HTMLElement) {
		pages := config.GetTotalPages()
		if pages == 0 {
			lastPageText := e.DOM.Find(`div.infobox a[title="last page"]`).Text()
			pages, err := strconv.Atoi(strings.Trim(lastPageText, "[]"))
			if err != nil {
				log.Printf("Couldn't parse page total: %s", err)
				return
			}
			config.SetTotalPages(pages)
			for i := 1; i <= coalesceInt(config.LimitFlag, pages); i++ {
				config.MainCollector.Visit(config.GeekURL(i))
			}
		}
	})

	log.Println("First visit", config.GeekURL(1))
	config.InitialCollector.Visit(config.GeekURL(1))
}

func coalesceInt(nums ...int) int {
	for _, num := range nums {
		if num != 0 {
			return num
		}
	}
	return 0
}


text:
require 'active_support/inflector'
require 'active_support/core_ext/array'

module YARD::Handlers::Ruby::ActiveRecord::Validate

  # Links with a value of nil will be link to
  # the Rails Validations guide.
  # Other projects can add to the
  STANDARD_LINKS = [
    :acceptance,
    :validates_associated,
    :confirmation,
    :exclusion,
    :format,
    :inclusion,
    :length,
    :numericality,
    :presence,
    :absence,
    :uniqueness,
    :validates_with,
    :validates_each
  ]

  def self.add_validation_type( type, link )
    @custom_types ||= {}
    @custom_types[type.to_sym] = link
  end

  def self.link_for_validation( type )
    type = type.downcase.to_sym
    if STANDARD_LINKS.include?( type )
      "http://edgeguides.rubyonrails.org/active_record_validations.html##{type}"
    elsif @custom_types && link = @custom_types[ type ]
      link
    else
      nil
    end
  end

  # Define validations tag for later use
  YARD::Tags::Library.define_tag("Validations", :validates )

  # Document ActiveRecord validations.
  # This handler handles the validates statement.
  # It will parse the list of fields, the validation types and their options,
  # and the optional :if/:unless clause.
  # It only handles the newer Rails ":validates" syntax and does not
  # recognize the older "validates_presence_of" type methods.
  class ValidatesHandler < YARD::Handlers::Ruby::MethodHandler
    namespace_only
    handles method_call(:validates)
    def process

      validations = {}
      attributes  = []
      conditions  = {}

      # Read each parameter to the statement and parse out
      # it's type and intent
      statement.parameters(false).compact.map do |param|
        # list types are options
        if param.type == :list
          param.each do | n |
            kw = n.jump(:label, :symbol_literal ).source.gsub(/:/,'')
            # if/unless are conditions that apply to all the validations
            if ['if','unless','on'].include?(kw)
              conditions[ kw ] = n.children.last.source
            else # otherwise it's type specific
              opts = n.jump(:hash)
              validations[ kw ] = if opts.type == :assoc
                opts.jump(:var_ref).source
              else
                opts.source
              end
            end
          end
        elsif param.type == :symbol_literal
          attributes << param.jump(:ident, :kw, :tstring_content).source
        end
      end

      # abort in case we didn't parse anything
      return if validations.empty?

      # Loop through each attribute and set a tag on each
      attributes.each do | attribute |
        method_definition = namespace.instance_attributes[attribute.to_sym] || {}
        method = method_definition[:read]
        if ! method
          meths = namespace.meths(:all => true)
          method = meths.find {|m| m.name == attribute.to_sym }
        end
        # If the method isn't defined yet, go ahead and create one
        if ! method
          method = register YARD::CodeObjects::MethodObject.new(namespace, attribute )
          method.scope = :instance
          method.explicit = false
          method_definition[:read] = method
          namespace.instance_attributes[attribute.to_sym] = method_definition
        end
        tag = YARD::Tags::OptionTag.new(:validates, '', conditions ) #, [] )
        tag.types = {} #[]
        validations.each{ |arg,options|
          tag.types[ arg ] = options
        }
        method.docstring.add_tag tag
      end

    end
  end

end


text:
package com.facebook.buck.log;

import com.facebook.buck.testutil.ProcessResult;
import com.facebook.buck.testutil.TemporaryPaths;
import com.facebook.buck.testutil.integration.ProjectWorkspace;
import com.facebook.buck.testutil.integration.TestDataHelper;
import com.google.common.collect.ImmutableMap;
import java.io.IOException;
import java.util.Map;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;

public class VerbosityTest {

  private ProjectWorkspace workspace;

  @Rule public TemporaryPaths tmp = new TemporaryPaths();

  @Before
  public void setUp() throws IOException {
    workspace = TestDataHelper.createProjectWorkspaceForScenario(this, "log", tmp);
    workspace.addBuckConfigLocalOption("ui", "warn_on_config_file_overrides", "false");
    workspace.setUp();
  }

  @Test
  public void noOutputOnNormalBuildWithVerboseZero() {
    ProcessResult result = workspace.runBuckCommand("build", "--verbose", "0", "//:foo");
    result.assertSuccess();
    Assert.assertEquals("", result.getStderr());
    Assert.assertEquals("", result.getStdout());
  }

  @Test
  public void noOutputOnConfigChangeWithVerboseZero() throws IOException {
    workspace.runBuckCommand("build", "//:foo").assertSuccess();
    Map<String, ? extends Map<String, String>> override =
        ImmutableMap.<String, ImmutableMap<String, String>>builder()
            .put(
                "somesection",
                ImmutableMap.<String, String>builder().put("somekey", "somevalue").build())
            .build();
    TestDataHelper.overrideBuckconfig(workspace, override);
    ProcessResult result = workspace.runBuckCommand("build", "--verbose", "0", "//:foo");
    result.assertSuccess();
    Assert.assertEquals("", result.getStderr());
    Assert.assertEquals("", result.getStdout());
  }
}


text:
/*jshint node: true */
'use strict';

var QUnit = require('qunit-cli');
var bonjsql = require('..');

QUnit.test('Loading queries from folder', function(assert){
	var dbAdapterStub = {
		query:function(){ return null; }
	};
	var queries = bonjsql.getQueries(dbAdapterStub, __dirname + '/' + 'fixtures');
	assert.equal(queries.hasOwnProperty('getUserByID'), true, 'getUserByID loaded successfully');
	assert.equal(queries.hasOwnProperty('getUserByName'), true, 'getUserByName loaded successfully');
});

QUnit.test('Successful query', function(assert){
	var done = assert.async();
	var dbAdapterStub = {
		query:function(strSql, fn){
			//This query takes 200ms.
			setTimeout(function(){
				fn(null, [{id: 1}, {id: 2}]);
			}, 200);
		}
	};

	var queries = bonjsql.getQueries(dbAdapterStub, __dirname + '/' + 'fixtures');

	queries.getUserByID()
		 .then(function(rows){
		 		assert.deepEqual(rows, [{id: 1}, {id: 2}], 'Correct result in promise');
		 		done();
		 });
});

QUnit.test('Failed query', function(assert){
	var done = assert.async();
	var dbAdapterStub = {
		query:function(strSql, fn){
			//This query takes 500ms.
			setTimeout(function(){
				fn('No connection to database', []);
			}, 500);
		}
	};

	var queries = bonjsql.getQueries(dbAdapterStub, __dirname + '/' + 'fixtures');

	queries.getUserByName()
		 .then(function(){
		 		assert.ok(false, 'This callback should not be executed');
		 })
		 .catch(function(err){
		 		assert.equal(err, 'No connection to database', 'Query should fail.');
		 		done();
		 });
});

QUnit.test('Query parameters', function(assert){
	var doneQueryCb = assert.async();
	var donePromise = assert.async();
	var dbAdapterStub = {
		query:function(strSql, params, fn){
			//This query takes 500ms.
			setTimeout(function(){
				assert.deepEqual(params, {name: 'John Doe'}, 'DB Adapter received correct params');
				fn(null, [{id: 22, name: 'John Richard Doe'}]);
				doneQueryCb();
			}, 500);
		}
	};

	var queries = bonjsql.getQueries(dbAdapterStub, __dirname + '/' + 'fixtures');

	queries.getUserByName({name: 'John Doe'})
				 .then(function(rows){
				 		assert.deepEqual(rows, [{id: 22, name: 'John Richard Doe'}], 'Correct rows returned by query using params');
				 		donePromise();
				 });
});

QUnit.test('Multiple queries sequence - success', function(assert){
	assert.expect(3);
	var doneSpread = assert.async();
	var doneThen = assert.async();

	var dbAdapterStub = {
		query:function(strSql, fn){
			//This query takes 500ms.
			var res = /name/g.test(strSql) ? [{name: 'John Doe', id: 1}] : [{name: 'Foo Bar', id: 2}];
			setTimeout(function(){
				fn(null, res);
				//Each time the queries can take anywhere between 0 - 300 ms
			}, Math.floor( Math.random() * 300 ));
		}
	};
	var queries = bonjsql.getQueries(dbAdapterStub, __dirname + '/' + 'fixtures');

	bonjsql.run(
		queries.getUserByName(),
		queries.getUserByID()
	)
	.spread(function(nameRow, idRow){
		assert.deepEqual(nameRow, [{id: 1, name: 'John Doe'}], 'Result received using spread() First param matches (getUserByName) query row result');
		assert.deepEqual(idRow, [{id: 2, name: 'Foo Bar'}], 'Result received using spread() Second param matches (getUserByID) query row result');
		doneSpread();
	});

	bonjsql.run(
		queries.getUserByName(),
		queries.getUserByID()
	)
	.then(function(result){
		assert.deepEqual(result, [
			[{id: 1, name: 'John Doe'}],
			[{id: 2, name: 'Foo Bar'}]
		], 'Result received using then() Array of Arrays.');
		doneThen();
	});
});


text:
<?php

final class DifferentialDiffViewPolicyFieldSpecification
  extends DifferentialFieldSpecification {

  public function shouldAppearOnDiffView() {
    return true;
  }

  public function renderLabelForDiffView() {
    return pht('Visible To');
  }

  public function renderValueForDiffView() {
    $user = $this->getUser();
    $diff = $this->getDiff();

    $descriptions = PhabricatorPolicyQuery::renderPolicyDescriptions(
      $user,
      $diff);

    return idx($descriptions, PhabricatorPolicyCapability::CAN_VIEW);
  }

}


text:
namespace Gameboy {
    namespace Memory {
        class MemoryMappedIO
            : public General::IReadableWritable
        {
        public:

            MemoryMappedIO(Cartridge::MemoryBankController& p_mbc);

            std::uint8_t read(std::uint16_t address) const override;
            void write(std::uint16_t address, std::uint8_t datum) override;

            void setInput(Input::Joypad &p_joypad);

            void setGpu(GPU::GPU &p_gpu);
            void setTimer(Timer::Timer &p_timer);

        private:
            // has rom and its own ram
            Memory::ReadableMemory bios;
            Cartridge::MemoryBankController& mbc;
            Memory::ReadableWritableMemory internalRam;

            Input::Joypad * joypad;
            GPU::GPU * gpu;
            Timer::Timer * timer;
            Memory::ReadableWritableMemory ioPorts;
            Memory::ReadableWritableMemory zeroPageRam;
            uint8_t interruptEnableRegister;
            bool lowMemoryIsCartridge;
            // Contiguous Physical Addressing
            // 0x0000 - 0x1FFF = Video RAM (8KB)
            // 0x2000 - 0x3FFF = Internal RAM (8KB)
            // 0x4000 - 0x409F = Sprite RAM (160 bytes)
            // 0x40A0 - 0x40EB = I/O (Usable) (76 bytes)
            // 0x40EC - 0x416A = Zero Page (127 bytes)
            // 0x416B - 0x416B = Interrupt Enable Register (1 byte)
        };
    }
}

#endif //GAMEBOY_MEMORYMAPPEDIO_H


text:
class ConcourseAuthenticator
  def initialize(requester)
    @requester = requester
  end

  # Yields PollState, status code, session token or error message
  def authenticate(url, username, password)
    request_options = {}

    request_options[:head] = {'authorization' => [username, password]}

    request = @requester.initiate_request(url, request_options)
    if request
      request.callback do |client|
        case client.response_header.status
          when 200..299
            body = client.response
            json = JSON.parse(body)
            yield PollState::SUCCEEDED, client.response_header.status, json['value']
          else
            yield PollState::FAILED, client.response_header.status, 'authorization failed'
        end
      end

      request.errback do |client|
        yield PollState::FAILED, -1, 'network error'
      end
    else
      puts 'Error: Is your Concourse project set up correctly?'
      yield PollState::FAILED, -1, 'failed'
    end
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  Openbizx Cubi Application Platform
  LICENSE http://code.google.com/p/openbiz-cubi/wiki/CubiLicense
  Copyright (c) 2005-2011, Openbiz Technology LLC
  Version $Id: AttachmentEditForm.xml 3350 2012-05-31 05:29:38Z rockyswen@gmail.com $
-->
<EasyForm Name="AttachmentEditForm" Class="AttachmentForm" Icon="{OPENBIZ_RESOURCE_URL}/attachment/images/icon_attachment.png" FormType="Detail" jsClass="jbForm" Title="Attachment Detail" Description="You can edit title and description for a uploaded attachment." BizDataObj="attachment.do.AttachmentPickDO" PageSize="10" DefaultForm="Y" TemplateEngine="Smarty" TemplateFile="form_attachment_quick_edit.tpl.html"  Access="attachment.access">
    <DataPanel>
    	<Element Name="fld_Id" ElementSet="General" Hidden="Y" Class="LabelText" FieldName="Id" Label="Id" AllowURLParam="Y"/>
        <Element Name="fld_title" Class="InputText" FieldName="title" Label="Title"   />
        <Element Name="fld_description" Class="Textarea" FieldName="description" Label="Description"   />
        <Element Name="fld_filename" Class="LabelText" FieldName="filename" Label="Filename"   />
        <Element Name="fld_filesize" Class="LabelText" FieldName="filesize" Text="{@util:format_bytes(@:Elem[fld_filesize].Value)}" Label="Filesize"   />
        <Element Name="fld_md5" Class="LabelText" FieldName="md5" Label="MD5"   />
        <Element Name="fld_sha256" Class="LabelText" FieldName="sha256" Label="SHA256"   />
    </DataPanel>
    <ActionPanel>

		<Element Name="btn_edit" Class="Button" Text="Save" CssClass="button_gray_m">
            <EventHandler Name="btn_close_onclick" Event="onclick" Function="UpdateRecord()" RedirectPage="form=attachment.widget.AttachmentDetailForm&fld:Id={@attachment.do.AttachmentDO:Field[Id].Value}" />
        </Element>

        <Element Name="btn_close" Class="Button" Text="Close" CssClass="button_gray_m">
            <EventHandler Name="btn_close_onclick" Event="onclick" Function="js:Openbizx.Window.closeDialog()"/>
        </Element>
    </ActionPanel>
    <NavPanel>
    </NavPanel>
    <SearchPanel>
    </SearchPanel>
</EasyForm>


text:
using Classifier.Interfaces.Helpers;
using NUnit.Framework;

namespace myoddweb.classifierUnitTest
{
  [TestFixture]
  public class TestLogEntry
  {
    [Test]
    public void ctor_default_values()
    {
      var logEntry = new LogEntry();
      Assert.That(logEntry.Id == -1);
      Assert.That(logEntry.Unixtime == 0);
      Assert.That(logEntry.Source == "");
      Assert.That(logEntry.Entry == "");
    }

    [Test]
    public void Id_ValueSetProperly_inConstructor()
    {
      var id = TestCommon.RandomInt();
      var logEntry = new LogEntry
      {
        Id = id
      };
      Assert.That(logEntry.Id == id);
      Assert.That(logEntry.Unixtime == 0);
      Assert.That(logEntry.Source == "");
      Assert.That(logEntry.Entry == "");
    }

    [Test]
    public void Id_ValueSetProperly()
    {
      var id = TestCommon.RandomInt();
      var logEntry = new LogEntry();
      logEntry.Id = id;
      Assert.That(logEntry.Id == id);
      Assert.That(logEntry.Unixtime == 0);
      Assert.That(logEntry.Source == "");
      Assert.That(logEntry.Entry == "");
    }

    [Test]
    public void Unixtime_ValueSetProperly_inConstructor()
    {
      var unixtime = TestCommon.RandomInt();
      var logEntry = new LogEntry
      {
        Unixtime = unixtime
      };
      Assert.That(logEntry.Id == -1);
      Assert.That(logEntry.Unixtime == unixtime);
      Assert.That(logEntry.Source == "");
      Assert.That(logEntry.Entry == "");
    }

    [Test]
    public void Unixtime_ValueSetProperly()
    {
      var unixtime = TestCommon.RandomInt();
      var logEntry = new LogEntry();
      logEntry.Unixtime = unixtime;
      Assert.That(logEntry.Id == -1);
      Assert.That(logEntry.Unixtime == unixtime);
      Assert.That(logEntry.Source == "");
      Assert.That(logEntry.Entry == "");
    }

    [Test]
    public void Source_ValueSetProperly_inConstructor()
    {
      var source = TestCommon.RandomString(10);
      var logEntry = new LogEntry
      {
        Source = source
      };
      Assert.That(logEntry.Id == -1);
      Assert.That(logEntry.Unixtime == 0);
      Assert.That(logEntry.Source == source);
      Assert.That(logEntry.Entry == "");
    }

    [Test]
    public void Source_ValueSetProperly()
    {
      var source = TestCommon.RandomString(10);
      var logEntry = new LogEntry();
      logEntry.Source = source;
      Assert.That(logEntry.Id == -1);
      Assert.That(logEntry.Unixtime == 0);
      Assert.That(logEntry.Source == source);
      Assert.That(logEntry.Entry == "");
    }

    [Test]
    public void Entry_ValueSetProperly_inConstructor()
    {
      var entry = TestCommon.RandomString(10);
      var logEntry = new LogEntry
      {
        Entry = entry
      };
      Assert.That(logEntry.Id == -1);
      Assert.That(logEntry.Unixtime == 0);
      Assert.That(logEntry.Source == "");
      Assert.That(logEntry.Entry == entry);
    }

    [Test]
    public void Entry_ValueSetProperly()
    {
      var entry = TestCommon.RandomString(10);
      var logEntry = new LogEntry();
      logEntry.Entry = entry;
      Assert.That(logEntry.Id == -1);
      Assert.That(logEntry.Unixtime == 0);
      Assert.That(logEntry.Source == "");
      Assert.That(logEntry.Entry == entry);
    }
  }
}


text:
"""Support for powerwall sensors."""
from __future__ import annotations

from typing import Any

from tesla_powerwall import Meter, MeterType

from homeassistant.components.sensor import (
    SensorDeviceClass,
    SensorEntity,
    SensorStateClass,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import ENERGY_KILO_WATT_HOUR, PERCENTAGE, POWER_KILO_WATT
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback

from .const import (
    ATTR_FREQUENCY,
    ATTR_INSTANT_AVERAGE_VOLTAGE,
    ATTR_INSTANT_TOTAL_CURRENT,
    ATTR_IS_ACTIVE,
    DOMAIN,
    POWERWALL_COORDINATOR,
)
from .entity import PowerWallEntity
from .models import PowerwallData, PowerwallRuntimeData

_METER_DIRECTION_EXPORT = "export"
_METER_DIRECTION_IMPORT = "import"

async def async_setup_entry(
    hass: HomeAssistant,
    config_entry: ConfigEntry,
    async_add_entities: AddEntitiesCallback,
) -> None:
    """Set up the powerwall sensors."""
    powerwall_data: PowerwallRuntimeData = hass.data[DOMAIN][config_entry.entry_id]
    coordinator = powerwall_data[POWERWALL_COORDINATOR]
    assert coordinator is not None
    data: PowerwallData = coordinator.data
    entities: list[
        PowerWallEnergySensor
        | PowerWallImportSensor
        | PowerWallExportSensor
        | PowerWallChargeSensor
    ] = [PowerWallChargeSensor(powerwall_data)]

    for meter in data.meters.meters:
        entities.extend(
            [
                PowerWallEnergySensor(powerwall_data, meter),
                PowerWallExportSensor(powerwall_data, meter),
                PowerWallImportSensor(powerwall_data, meter),
            ]
        )

    async_add_entities(entities)

class PowerWallChargeSensor(PowerWallEntity, SensorEntity):
    """Representation of an Powerwall charge sensor."""

    _attr_name = "Powerwall Charge"
    _attr_state_class = SensorStateClass.MEASUREMENT
    _attr_native_unit_of_measurement = PERCENTAGE
    _attr_device_class = SensorDeviceClass.BATTERY

    @property
    def unique_id(self) -> str:
        """Device Uniqueid."""
        return f"{self.base_unique_id}_charge"

    @property
    def native_value(self) -> int:
        """Get the current value in percentage."""
        return round(self.data.charge)

class PowerWallEnergySensor(PowerWallEntity, SensorEntity):
    """Representation of an Powerwall Energy sensor."""

    _attr_state_class = SensorStateClass.MEASUREMENT
    _attr_native_unit_of_measurement = POWER_KILO_WATT
    _attr_device_class = SensorDeviceClass.POWER

    def __init__(self, powerwall_data: PowerwallRuntimeData, meter: MeterType) -> None:
        """Initialize the sensor."""
        super().__init__(powerwall_data)
        self._meter = meter
        self._attr_name = f"Powerwall {self._meter.value.title()} Now"
        self._attr_unique_id = (
            f"{self.base_unique_id}_{self._meter.value}_instant_power"
        )

    @property
    def native_value(self) -> float:
        """Get the current value in kW."""
        return self.data.meters.get_meter(self._meter).get_power(precision=3)

    @property
    def extra_state_attributes(self) -> dict[str, Any]:
        """Return the device specific state attributes."""
        meter = self.data.meters.get_meter(self._meter)
        return {
            ATTR_FREQUENCY: round(meter.frequency, 1),
            ATTR_INSTANT_AVERAGE_VOLTAGE: round(meter.average_voltage, 1),
            ATTR_INSTANT_TOTAL_CURRENT: meter.get_instant_total_current(),
            ATTR_IS_ACTIVE: meter.is_active(),
        }

class PowerWallEnergyDirectionSensor(PowerWallEntity, SensorEntity):
    """Representation of an Powerwall Direction Energy sensor."""

    _attr_state_class = SensorStateClass.TOTAL_INCREASING
    _attr_native_unit_of_measurement = ENERGY_KILO_WATT_HOUR
    _attr_device_class = SensorDeviceClass.ENERGY

    def __init__(
        self,
        powerwall_data: PowerwallRuntimeData,
        meter: MeterType,
        meter_direction: str,
    ) -> None:
        """Initialize the sensor."""
        super().__init__(powerwall_data)
        self._meter = meter
        self._attr_name = f"Powerwall {meter.value.title()} {meter_direction.title()}"
        self._attr_unique_id = f"{self.base_unique_id}_{meter.value}_{meter_direction}"

    @property
    def available(self) -> bool:
        """Check if the reading is actually available.

        The device reports 0 when something goes wrong which
        we do not want to include in statistics and its a
        transient data error.
        """
        return super().available and self.native_value != 0

    @property
    def meter(self) -> Meter:
        """Get the meter for the sensor."""
        return self.data.meters.get_meter(self._meter)

class PowerWallExportSensor(PowerWallEnergyDirectionSensor):
    """Representation of an Powerwall Export sensor."""

    def __init__(
        self,
        powerwall_data: PowerwallRuntimeData,
        meter: MeterType,
    ) -> None:
        """Initialize the sensor."""
        super().__init__(powerwall_data, meter, _METER_DIRECTION_EXPORT)

    @property
    def native_value(self) -> float:
        """Get the current value in kWh."""
        return abs(self.meter.get_energy_exported())

class PowerWallImportSensor(PowerWallEnergyDirectionSensor):
    """Representation of an Powerwall Import sensor."""

    def __init__(
        self,
        powerwall_data: PowerwallRuntimeData,
        meter: MeterType,
    ) -> None:
        """Initialize the sensor."""
        super().__init__(powerwall_data, meter, _METER_DIRECTION_IMPORT)

    @property
    def native_value(self) -> float:
        """Get the current value in kWh."""
        return abs(self.meter.get_energy_imported())


text: A higher-level flow control on top of formal workflow patterns


text:
import numpy as np

# set default value of tolerance of block average unless argparse does not support default
# input: tol is a float or integer
#		 deafult is default value you want to set (depends on your program)
# output: convert to a float value of tolerance, otherwise default value
# Example: args.tol = default_value(args.tol, 0.0)
def default(tol, default):
	print("blockavg.default: ")
	print(" Must remove this function!!")
	if tol is None:
		return float(default)
	else:
		return float(tol)

# print settings
# input: tol is a setting for printing
def print_init(tol):
	print("blockavg.print: ")
	if tol == 0.0:
		print(" Set no bloack average")
	elif tol <= 1.0:
		print(" Tolerance for block average = %f" %tol)
	else: # for tol > 1.0
		print(" Set block length in frames = %d" %(int(tol)))
	return

def check(tol):
	print("blockavg.check: ")
	if tol < 0.0:
		raise ValueError(" Wrong input of tolerance, %f" %tol)
	elif tol > 1.0:
		print(" The tolerance %f is assigned to the block_size, %d" %(tol, int(tol)))
		return int(tol)
	return tol

# main program of block average of a data using tolerance of std of self or another data
# all averages of blocks should be less than (average of total data +- tolerance*std)
# (x1(t0)+x1(t1)+x1(t2)+....)/block_length = block average
# input: opt_data_t is array along time (t1, t2, ...)
#		[[x1(t0), x2(t0), x3(t0), ...], [x1(t1), x2(t1), x3(t1)], ...]
#			block_length is block length you want
# output: new_data_t is averaged block array and block_length
# Example: number_t_1d, block_length = hjung.blockavg.main_1d(number_t_1d, unit_cells_1d, args.tol)
# Assume: opt_data_t matrix size is homogeneous. In other words, all element array in opt_data_t is the same size
def main_1d(opt_data_1d_t, ref_data_1d, tolerance):
	print("blockavg.main_1d: ")
	tolerance = check(tolerance)

	# determine block_length
	block_length = -1
	if tolerance <= 1 and tolerance > 0:
		if ref_data_1d is None:
			print(" use itself to optimize block length")
			print(" find the max. optimal length of each x1, x2, x3, etc")
			data_t_1d = opt_data_1d_t.transpose()
			opt_lengths = []
			for data_t in data_t_1d:
				temp = opt_length_1d(data_t,tolerance)
				opt_lengths.append(temp)
			block_length = np.amax(opt_lengths)
		else:
			block_length = opt_length_1d(ref_data_t,tolerance)

		if block_length == 1:
			return opt_data_1d_t, block_length

	elif tolerance > 1:
		block_length = int(tolerance)

	elif tolerance == 0:
		block_length = 1
		print(" no block averaged")
		return opt_data_1d_t, block_length

	else:
		raise ValueError(" tolerance error. Please check again!")

	if block_length <= 1:
		raise ValueError(" block length error, %d. Please check again!" %block_length)

	# run block average with block_length
	nitems = len(opt_data_1d_t[0])
	nframes, remain = divmod(len(opt_data_1d_t),block_length)
	print(" set block length, %d" %block_length)
	print(" uses %d blocks" %nframes)
	new_data_t = np.zeros((nframes,nitems)) # new data to store average
	temp = np.zeros(nitems) # temporary data set
	i = 0
	j = 0
	for iframe in range(remain,len(opt_data_1d_t)):
		temp = np.add(temp,opt_data_1d_t[iframe])
		i += 1
		if np.mod(i,block_length) == 0:
			new_data_t[j] = temp/float(block_length)
			j += 1
			temp = np.zeros(nitems) # reset temp
	return new_data_t, block_length

# get the optimum block length for block average using tolerance of std of data
# all averages of blocks should be less than (average of total data +- tolerance*std)
# input: data_1d is 1D-data trajectory
#		[x_t1, x_t2, x_t3...]
#			tolerance is what you want to set acceptance line
# output: opt_block_length (integer) is the optimal block length. If not found, zero.
# Example: opt_block_length = opt_length_1d(unit_cell_1d, tolerance)
# Assume: if mod(length of data, block_length) != 0, only last trajectory is considered, not beginning.
def opt_length_1d(data_1d, tolerance):
	print("opt_length_1d: ")
	print(" To optimize, we use unit cell length on the axis you select.")
	# info before block average
	ref_avg = np.mean(data_1d)
	ref_std = np.std(data_1d)
	ref_high = ref_avg + ref_std*tolerance
	ref_low = ref_avg - ref_std*tolerance
	#print("(before block avg) Total data = %f +- %f" %(ref_avg,ref_std))
	if (100*float(ref_std)/ref_avg) < 0.05: # std is very small (<0.05%)
		print(" original std value is less than 5%. block average not necessary.\n")
		return 1

	# make list of possible block lengths
	data_size = len(data_1d)
	quot, remain = divmod(data_size,2)
	if remain != 0: # if odd frame, force to make even frame
		data_size -= 1
	poss_block_length = divisors(data_size) # make all list of divisors of #frames
	poss_block_length = poss_block_length[1:-3] # remove 1 and itself
	if len(poss_block_length) == 0: # if the list is small, return no average
		return 2

	# determine optimal block length using the list
	opt_block_length = int(0)
	for block_length in poss_block_length:
		quot, remain = divmod(data_size,block_length)
		last_data = data_1d[remain:]
		list_bavg = []
		for i in range(0,len(last_data),block_length):
			#  arithmetic mean of each block
			bavg = np.mean(last_data[i:i+block_length-1])
			list_bavg.append(bavg)
		# assume all blocks have the same weight
		pass_blength = True
		for j in range(0,len(list_bavg)):
			#print("list_bavg[%d] = %f, ref_high, %f, ref_low, %f" %(j, list_bavg[j], ref_high, ref_low))
			if list_bavg[j] > ref_high or list_bavg[j] < ref_low:
				#print("The value, %d, does not fit within %f +- %f.\n"
				#	%(block_length, ref_avg, ref_std*tolerance))
				pass_blength = False
				break
			else:
				continue
		if pass_blength is False:
			continue
		else: # pass above check condition
			opt_block_length = block_length
			out_avg = np.mean(list_bavg)
			out_std = np.std(list_bavg)
			break

	if opt_block_length == 0:
		print(" Not found optimal block length.")
		return 2
	else:
		print(" Found optimal block length, %d." %opt_block_length)
		print(" Before bloack average = %f +- %f " %(ref_avg,ref_std))
		print(" -> After bloack average = %f +- %f " %(out_avg,out_std))
		return opt_block_length


text:
package com.alibaba.com.caucho.hessian.io;

import java.io.IOException;

/**
 * Deserializing an object.
 */
public interface Deserializer {
  public Class getType();

  public Object readObject(AbstractHessianInput in)
    throws IOException;

  public Object readList(AbstractHessianInput in, int length)
    throws IOException;

  public Object readLengthList(AbstractHessianInput in, int length)
    throws IOException;

  public Object readMap(AbstractHessianInput in)
    throws IOException;

  public Object readObject(AbstractHessianInput in, String []fieldNames)
    throws IOException;
}


text:
package com.ticketwala.controller.servlet;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.ticketwala.command.api.Result;
import com.ticketwala.command.impl.CreateMovieShowCommand;
import com.ticketwala.command.impl.DeleteAllMovieShowsCommand;
import com.ticketwala.command.input.CreateMovieShowInput;
import com.ticketwala.model.MovieShow;
import com.ticketwala.service.api.TicketWalaService;

@RestController
public class TicketWalaController {

	@Autowired
	TicketWalaService ticketWalaService;

	@RequestMapping(value = "/movie_shows", method = RequestMethod.GET)
	public List<MovieShow> getMovieAllShows() {
		return this.ticketWalaService.getMovieShows();
	}

	@RequestMapping(value = "/movie_show/{id}", method = RequestMethod.GET)
	public ResponseEntity<MovieShow> getMovieShow(@PathVariable("id") String id) {
		MovieShow movieShow = this.ticketWalaService.getMovieShow(id);
		HttpStatus s = movieShow == null ? HttpStatus.NOT_FOUND : HttpStatus.OK;
		return new ResponseEntity<MovieShow>(movieShow, s);
	}

	@RequestMapping(value = "/movie_show", method = RequestMethod.POST)
	public ResponseEntity<Result> createMovieShow(@RequestBody CreateMovieShowInput movieShowInput) {
		CreateMovieShowCommand cmd = new CreateMovieShowCommand(movieShowInput, this.ticketWalaService);
		return new ResponseEntity<Result>(cmd.execute(), HttpStatus.CREATED);
	}

	@RequestMapping(value = "/movie_shows", method = RequestMethod.DELETE)
	public ResponseEntity<Result> deleteAllMovieShows(){
		DeleteAllMovieShowsCommand cmd = new DeleteAllMovieShowsCommand(null, this.ticketWalaService);
		return new ResponseEntity<Result>(cmd.execute(), HttpStatus.OK);
	}
}


text:
  <route-header></route-header>

Resume

Cloud Software Architect

34 years old, French nationality, based in Zurich, Switzerland 🇨🇭.
Languages: French (native language), English (Fluent), and German (A2)

Technologies

Front-end : React, Angular, CSS3 Responsive, Html5. Redux, IndexedDB, web/service workers. Webpack, Npm. Test environment with jasmine, Moka, Karma.

Back-end : Python Django, Flask, Restful API, Unitary test, Web services, Continuous integration, Sphinx (technical documentation).

Devops, Monitoring, Server skills, Open source advocate, Git, Scrum.

Work experience

              {{ experience.company.name}}  : {{ experience.title}}, {{ experience.company.location }}.

              {{ experience.date }}

              {{ experience.description }}

Education

2011 - Master degree in computer science - Distributed systems and networks

« University of Franche-Comté, Science and technology » - Besançon, France 🇫🇷 - magna cum laude

Internship 3 months: Nav6 Laboratory - Penang, Malaysia 🇲🇾. Developed C# application using Google API in a real time collaborative space. Integrated to a video chat
application in purpose to have real time document edition.

2009 - Bachelor degree in computer science

« University of Franche-Comté, Science and technology » - Besançon, France 🇫🇷 - cum laude

Internship 3 months: MagicLabVision Laboratory - Adelaide, Australia 🇦🇺. Joined a research team on an augmented reality application based on Python.

2008 - "Final year in computer science"

« University of Portsmouth » - ERASMUS exchange, England 🇬🇧

2007 - HNC, Computer Science

« IUT of Belfort » - Belfort, France 🇫🇷

Internship 3 months: Thales Avionics Electrical Systems - Chatou, France 🇫🇷. PHP Developer, using Oracle databases, access archives from a previous ERP.

Additional informations

Have side-projects, like Seven23 which keep track of my expenses (open source - work in progress). Big use of twitter to follow tech news. Have fun with photography and would like to spend more time and progress.

I like to attend conferences

{{ conference.date }} - {{ conference.name }}, {{ conference.location }}


text:
<input type="hidden" name="attr_sheet" value="character">

Written by Brian Tyrrell

Edited by Vi Huntsman

Roll20 by Wes Baker

Copyright © Dungeons on a Dime 2020

Your Adventurer

Adventurer's Abilities

            My name is
            <input type="text" name="attr_character_name" />
            and I am:

              <input readonly type="text" name="attr_cunning_characteristic" />

Cunning

                Base
                <select name="attr_cunning_base">
                  <option>D4</option>
                  <option>D6</option>
                  <option>D8</option>
                  <option>D10</option>
                  <option>D12</option>
                </select>

                Current
                <select name="attr_cunning_current">
                  <option>D4</option>
                  <option>D6</option>
                  <option>D8</option>
                  <option>D10</option>
                  <option>D12</option>
                </select>
                <button type="roll"
                  value="&{template:ability} {{ability=Cunning}} {{name=@{character_name}}} {{roll=[[@{cunning_current}]]}}"></button>

              <input readonly type="text" name="attr_vigour_characteristic" />

Vigour

                Base
                <select name="attr_vigour_base">
                  <option>D4</option>
                  <option>D6</option>
                  <option>D8</option>
                  <option>D10</option>
                  <option>D12</option>
                </select>

                Current
                <select name="attr_vigour_current">
                  <option>D4</option>
                  <option>D6</option>
                  <option>D8</option>
                  <option>D10</option>
                  <option>D12</option>
                </select>
                <button type="roll"
                  value="&{template:ability} {{ability=Vigour}} {{name=@{character_name}}} {{roll=[[@{vigour_current}]]}}"></button>

              <input readonly type="text" name="attr_willpower_characteristic" />

Willpower

                Base
                <select name="attr_willpower_base">
                  <option>D4</option>
                  <option>D6</option>
                  <option>D8</option>
                  <option>D10</option>
                  <option>D12</option>
                </select>

                Current
                <select name="attr_willpower_current">
                  <option>D4</option>
                  <option>D6</option>
                  <option>D8</option>
                  <option>D10</option>
                  <option>D12</option>
                </select>
                <button type="roll"
                  value="&{template:ability} {{ability=Willpower}} {{name=@{character_name}}} {{roll=[[@{willpower_current}]]}}"></button>

Injuries

          <input type="text" name="attr_injuries" />

Inventory

Standard Gear

              <input type="text" name="attr_tool_1" placeholder="Tool 1" data-i18n-placeholder="tool-1">
              <input type="text" name="attr_tool_2" placeholder="Tool 2" data-i18n-placeholder="tool-2">
              <input type="text" name="attr_tool_3" placeholder="Tool 3" data-i18n-placeholder="tool-3">
              <input type="text" name="attr_tool_4" placeholder="Tool 4" data-i18n-placeholder="tool-4">
              <input type="text" name="attr_weapon" placeholder="Weapon" data-i18n-placeholder="weapon">
              <input type="text" name="attr_packed lunch" placeholder="Packed Lunch"
                data-i18n-placeholder="packed-lunch">
              <input type="text" name="attr_money" placeholder="Money" data-i18n-placeholder="money">
              <input type="text" name="attr_light_source" placeholder="Light Source"
                data-i18n-placeholder="light-source">
              <input type="text" name="attr_backpack" placeholder="Backpack" data-i18n-placeholder="backpack">

Carried Items

                Max:
                <input readonly type="text" name="attr_max_carried_items" value="4" />

              <fieldset class="repeating_carrieditems">
                <input type="text" name="attr_carried_item" placeholder="Carried Item"
                  data-i18n-placeholder="carried-item">
              </fieldset>

Pocket Items

              <fieldset class="repeating_pocketitems">
                <input type="text" name="attr_pocket_item" placeholder="Pocket Item"
                  data-i18n-placeholder="pocket-item">
              </fieldset>

Jobs and Features

        <fieldset class="repeating_jobfeature">

            <select name="attr_job_or_feature">
              <option data-i18n="job">Job</option>
              <option data-i18n="feature">Feature</option>
            </select>

              <input type="hidden" name="attr_job_or_feature_toggle" value="job" class="job-or-feature-toggle">

                <input type="text" name="attr_job_title" placeholder="Job Title" data-i18n-placeholder="job-title">
                <input type="text" name="attr_job_skill_1" placeholder="Skill 1" data-i18n-placeholder="skill-1">
                <input type="text" name="attr_job_skill_2" placeholder="Skill 2" data-i18n-placeholder="skill-2">
                <input type="text" name="attr_job_skill_3" placeholder="Skill 3" data-i18n-placeholder="skill-3">
                <input type="text" name="attr_job_trait" placeholder="Trait" data-i18n-placeholder="trait">
                <input type="text" name="attr_job_flaw" placeholder="Flaw" data-i18n-placeholder="flaw">

                  <select name="attr_feature_1_type">
                    <option data-i18n="skill">Skill</option>
                    <option data-i18n="trait">Trait</option>
                    <option data-i18n="flaw">Flaw</option>
                  </select>
                  <input type="text" name="attr_feature_1" placeholder="Feature 1" data-i18n-placeholder="Feature 1">

                  <select name="attr_feature_2_type">
                    <option data-i18n="skill">Skill</option>
                    <option data-i18n="trait">Trait</option>
                    <option data-i18n="flaw">Flaw</option>
                  </select>
                  <input type="text" name="attr_feature_2" placeholder="Feature 2" data-i18n-placeholder="Feature 2">

                  <select name="attr_feature_3_type">
                    <option data-i18n="skill">Skill</option>
                    <option data-i18n="trait">Trait</option>
                    <option data-i18n="flaw">Flaw</option>
                  </select>
                  <input type="text" name="attr_feature_3" placeholder="Feature 3" data-i18n-placeholder="Feature 3">

                  <select name="attr_feature_4_type">
                    <option data-i18n="skill">Skill</option>
                    <option data-i18n="trait">Trait</option>
                    <option data-i18n="flaw">Flaw</option>
                  </select>
                  <input type="text" name="attr_feature_4" placeholder="Feature 4" data-i18n-placeholder="Feature 4">

                  <select name="attr_feature_5_type">
                    <option data-i18n="skill">Skill</option>
                    <option data-i18n="trait">Trait</option>
                    <option data-i18n="flaw">Flaw</option>
                  </select>
                  <input type="text" name="attr_feature_5" placeholder="Feature 5" data-i18n-placeholder="Feature 5">

                  <select name="attr_feature_6_type">
                    <option data-i18n="skill">Skill</option>
                    <option data-i18n="trait">Trait</option>
                    <option data-i18n="flaw">Flaw</option>
                  </select>
                  <input type="text" name="attr_feature_6" placeholder="Feature 6" data-i18n-placeholder="Feature 6">

        </fieldset>

Training

Desired Job

              <input type="text" name="attr_desired_job_skill_1" placeholder="New Skill 1"
                data-i18n-placeholder="new-skill-1">
              <input type="text" name="attr_desired_job_skill_2" placeholder="New Skill 2"
                data-i18n-placeholder="new-skill-2">
              <input type="text" name="attr_desired_job_skill_3" placeholder="New Skill 3"
                data-i18n-placeholder="new-skill-3">
              <input type="text" name="attr_desired_job_trait" placeholder="New Trait"
                data-i18n-placeholder="new-trait">
              <input type="text" name="attr_desired_job_flaw" placeholder="New Flaw" data-i18n-placeholder="new-flaw">

Sessions without Skills

During each sessionof play of AOAD, you should get the
            chance to learn a new Skill for a Job you are
            training to get.

Mark sessions played where you haven't learnt a skill
            below, which you can make up for later with the
            Narrator.

            <input type="checkbox" name="attr_session_without_skill_1" />
            <input type="checkbox" name="attr_session_without_skill_2" />
            <input type="checkbox" name="attr_session_without_skill_3" />
            <input type="checkbox" name="attr_session_without_skill_4" />
            <input type="checkbox" name="attr_session_without_skill_5" />
            <input type="checkbox" name="attr_session_without_skill_6" />
            <input type="checkbox" name="attr_session_without_skill_7" />
            <input type="checkbox" name="attr_session_without_skill_8" />
            <input type="checkbox" name="attr_session_without_skill_9" />
            <input type="checkbox" name="attr_session_without_skill_10" />

<rolltemplate class="sheet-rolltemplate-ability">

{{name}} / {{ability}}

Roll

{{roll}}

Result

        {{#rollGreater() roll 3}}

          {{#rollWasCrit() roll}}Critical{{/rollWasCrit() roll}}
          Success

        {{/rollGreater() roll 3}}

        {{#rollBetween() roll 2 3}}

Complication

        {{/rollBetween() roll 2 3}}

        {{#rollLess() roll 2}}

Hijinx

        {{/rollLess() roll 2}}

      {{#rollGreater() roll 3}}

You do as well as you can. The Narrator describes how successful you are.

      {{/rollGreater() roll 3}}

      {{#rollBetween() roll 2 3}}

You barely manage to pull it off, but not without consequence. The
          Narrator describes how the situation
          becomes more complicated.

      {{/rollBetween() roll 2 3}}

      {{#rollLess() roll 2}}

Something goes terribly wrong. The Narrator describes how things go awry, and
          hijinx may follow.

      {{/rollLess() roll 2}}

      {{#rollWasCrit() roll}}

You do better than expected! The Narrator describes how things go in
          your favor.

      {{/rollWasCrit() roll}}

</rolltemplate>


text:
namespace Umbraco.Cms.Core.Models.Blocks;

public interface IBlockLayoutItem
{
    public Udi? ContentUdi { get; set; }

    public Udi? SettingsUdi { get; set; }
}


text:
@class NSString;

@interface _DVTDelayedInvocationNotificationHandlerNotificationKey : NSObject <NSCopying>
{
    NSString *_notificationName;
    id _object;
}

@property(readonly, nonatomic) id object; // @synthesize object=_object;
@property(readonly, nonatomic) NSString *notificationName; // @synthesize notificationName=_notificationName;
- (id)description;
- (id)copyWithZone:(struct _NSZone *)arg1;
- (unsigned long long)hash;
- (BOOL)isEqualToNotificationKey:(id)arg1;
- (BOOL)isEqual:(id)arg1;
- (id)initWithNotificationName:(id)arg1 object:(id)arg2;

@end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Xamarin.Forms;
using XamlCSS.Dom;

namespace XamlCSS.XamarinForms.Dom
{
    public class TreeNodeProvider : TreeNodeProviderBase<BindableObject, Style, BindableProperty>
    {
        public TreeNodeProvider(IDependencyPropertyService<BindableObject, Style, BindableProperty> BindablePropertyService)
            : base(BindablePropertyService)
        {
        }

        public override IDomElement<BindableObject, BindableProperty> CreateTreeNode(BindableObject BindableObject)
        {
            return new DomElement(BindableObject, GetDomElement(GetParent(BindableObject, SelectorType.VisualTree)), GetDomElement(GetParent(BindableObject, SelectorType.LogicalTree)), this);
        }

        public override IEnumerable<BindableObject> GetChildren(BindableObject element, SelectorType type)
        {
            var list = GetLogicalChildren(element as Element)
                .Cast<BindableObject>()
                .ToList();

            return list;
        }

        private static List<BindableObject> GetLogicalChildren(Element element)
        {
            var list = new List<BindableObject>();

            if (element is ILayoutController lc)
            {
                foreach (var item in lc.Children)
                {
                    list.Add(item);
                }
            }
            else if (element is IPageController pc)
            {
                foreach (var item in pc.InternalChildren)
                {
                    list.Add(item);
                }
            }
            else if (element is Application a)
            {
                list.Add(a.MainPage);
            }
            else if (element is IElementController ec)
            {
                foreach (var item in ec.LogicalChildren)
                {
                    list.Add(item);
                }
            }

            var additionalChildren = Css.GetAdditionalChildren(element);
            if (additionalChildren != null)
            {
                foreach (var child in additionalChildren)
                {
                    list.Add(child);
                }
            }

            return list;
        }

        static bool IsSubclassOfRawGeneric(Type generic, Type toCheck)
        {
            while (toCheck != null &&
                toCheck != typeof(object))
            {
                var cur = toCheck.GetTypeInfo().IsGenericType ? toCheck.GetGenericTypeDefinition() : toCheck;
                if (generic == cur)
                {
                    return true;
                }

                toCheck = toCheck.GetTypeInfo().BaseType;
            }

            return false;
        }

        public override BindableObject GetParent(BindableObject element, SelectorType type)
        {
            var p = (element as Element)?.Parent;

            return p;
        }

        public override bool IsInTree(BindableObject dependencyObject, SelectorType type)
        {
            var p = GetParent(dependencyObject, type);

            if (p == null)
            {
                return IsTopMost(dependencyObject, type);
            }

            var children = GetChildren(p, type);

            return children.Contains(dependencyObject);
        }

        public override bool IsTopMost(BindableObject dependencyObject, SelectorType type)
        {
            return dependencyObject is Application;
        }
    }
}


text:
module FirewoodsCommon
  extend ActiveSupport::Concern

  included do
    before_action :touch_user
  end

  def touch_user
    current_user.update_login_info(Time.zone.now.to_i)
  end

  def fws_data(limit)
    scope = Firewood.fetch_scope_for_type(params[:type])
    Firewood
      .includes(:favorites)
      .before(params[:before])
      .after(params[:after])
      .send(scope, current_user, limit)
      .map { |fw| fw.serialize(current_user) }
  end
end


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

    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>simple_rl.agents.RandomAgentClass — simple_rl v0.801 documentation</title>
    <link rel="stylesheet" href="../../../static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../../../static/pygments.css" type="text/css" />

    <link rel="index" title="Index" href="../../../genindex.html" />
    <link rel="search" title="Search" href="../../../search.html" />

Navigation

          index

          modules |

simple_rl v0.801 documentation »

Module code »

Source code for simple_rl.agents.RandomAgentClass

''' RandomAgentClass.py: Class for a randomly acting RL Agent '''

# Python imports.
import random

# Other imports
from simple_rl.agents.AgentClass import Agent

[docs]class RandomAgent(Agent):
    ''' Class for a random decision maker. '''

    def __init__(self, actions, name=""):
        name = "Random" if name is "" else name
        Agent.__init__(self, name=name, actions=actions)

[docs]    def act(self, state, reward):
        return random.choice(self.actions)

Quick search

    <form class="search" action="../../../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

Navigation

          index

          modules |

simple_rl v0.801 documentation »

Module code »

        © Copyright 2018, David Abel.
      Created using Sphinx 1.7.8.


text:
NSString *SaveToPath()
{
    NSArray *path_list =NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory,NSUserDomainMask,YES);
    return [[path_list objectAtIndex:0]stringByAppendingPathComponent:@"data.txt"];
}

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    NSArray *plist = [NSArray arrayWithContentsOfFile:SaveToPath()];
    if(plist)
    {
        tasks = [plist mutableCopy];
    }
    else
    {
        tasks = [[NSMutableArray alloc]init];
    }

    //创建应用程序的主窗口
    CGRect window_frame = [[UIScreen mainScreen] bounds];
    UIWindow *the_window =[[UIWindow alloc] initWithFrame:window_frame];
    [self setWindow:the_window];

    //设置三个UI对象的frame属性
    CGRect table_frame = CGRectMake(0, 80, 320, 380);
    CGRect field_frame = CGRectMake(20, 40, 200, 31);
    CGRect button_frame =CGRectMake(228, 40, 72, 31);

    //创建并设置表格UITableView
    task_table = [[UITableView alloc]initWithFrame:table_frame
                                             style:UITableViewStylePlain];
    [task_table setSeparatorStyle:UITableViewCellSeparatorStyleNone];

    //将AppDelegate设置为UITableView的数据源
    [task_table setDataSource:self];

    //创建并设置文本框(UITextField)
    task_field = [[UITextField alloc]initWithFrame:field_frame];
    [task_field setBorderStyle:UITextBorderStyleRoundedRect];
    [task_field setPlaceholder:@"Type a task,tap Insert"];

    //创建并设置按钮(UIButton)
    insert_button= [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [insert_button setFrame:button_frame];
    [insert_button setTitle:@"Insert" forState:UIControlStateNormal];

    //为按钮设置回调
    [insert_button addTarget:self action:@selector(AddTask:) forControlEvents:UIControlEventTouchUpInside];

    //将三个UI对象加入UIWindow中
    [[self view] addSubview:task_table];
    [[self view] addSubview:task_field];
    [[self view] addSubview:insert_button];

    //设置UIWindow的背景颜色,并放到屏幕上
    [[self view] setBackgroundColor:[UIColor whiteColor]];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)AddTask:(id)sender
{
    NSString *text = [task_field text];
    if([text isEqualToString:@""])
    {
        return;
    }
    [tasks addObject:text];
    [task_table reloadData];
    [task_field setText:@""];
    [task_field resignFirstResponder];
}
//}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if([tasks count]==0)
    {
        [tasks addObject:@"Walk the dog"];
        [tasks addObject:@"Get oil changed"];
        [tasks addObject:@"Wrangle some cows"];
    }
    return [tasks count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [task_table dequeueReusableCellWithIdentifier:@"Cell"];
    if(!cell)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                      reuseIdentifier:@"Cell"];
    }
    NSString *item = [tasks objectAtIndex:[indexPath row]];
    [[cell textLabel] setText:item];
    return cell;
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    [tasks writeToFile:SaveToPath() atomically:YES];
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end