text:
/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package org.netbeans.modules.sampler;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.SwingUtilities;
import org.netbeans.api.annotations.common.CheckForNull;
import org.netbeans.api.annotations.common.NonNull;

/**
 * Sampler class provides API for self-sampling of NetBeans
 * platform application. The self-sampling should be used for
 * diagnostic purposes and should help NetBeans platform developers
 * with solving CPU related performance problems. Sampled data are
 * stored in NPSS file, which can be opened by NetBeans Profiler or
 * Java VisualVM for later analysis of sampled data.
 *
 * @author Jaroslav Bachorik, Tomas Hurka, Jaroslav Tulach
 */
public abstract class Sampler {
    private static final int SAMPLER_RATE = 10;
    private static final double MAX_AVERAGE = SAMPLER_RATE * 3;
    private static final double MAX_STDDEVIATION = SAMPLER_RATE * 4;
    private static final int MAX_SAMPLING_TIME = 5*60;  // 5 minutes
    private static final int MIN_SAMPLES = 50;
    private static final int MAX_SAMPLES = MAX_SAMPLING_TIME * (1000/SAMPLER_RATE);

    private final String name;
    private Timer timer;
    private ByteArrayOutputStream out;
    private SamplesOutputStream samplesStream;
    private long startTime;
    private long nanoTimeCorrection;
    private long samples;
    private long laststamp;
    private double max;
    private double min = Long.MAX_VALUE;
    private double sum;
    private double devSquaresSum;
    private volatile boolean stopped;
    private volatile boolean running;

    /**
     * Factory method for creating Sampler suitable for automatic reporting
     * of the slow operation (i.e. AWT blocked for some time). This method can
     * return null if the sampled application is in nonstandard mode
     * which will produce unrealistic data - for example application is
     * running under debugger or profiler. It can return null if it
     * is running on some exotic variant of JDK, where sampling is not supported.
     * @param name which identifies the sampler thread
     * @return instance of the {@link Sampler} or null if application
     * is in nonstandard mode or sampling is not supported.
     */
    public static @CheckForNull Sampler createSampler(@NonNull String name) {
        if (SamplesOutputStream.isSupported()) {
            try {
                return InternalSampler.createInternalSampler(name);
            } catch (LinkageError ex) {
                return new StandaloneSampler(name);
            }
        }
        return null;
    }

    /**
     * Factory method for creating Sampler suitable for manual or user invoked
     * scanning. This method can return null if it is running on
     * some exotic variant of JDK, where sampling is not supported.
     * @param name which identifies the sampler thread
     * @return instance of the {@link Sampler} or null if sampling
     * is not supported.
     */
    public static @CheckForNull Sampler createManualSampler(@NonNull String name) {
        if (SamplesOutputStream.isSupported()) {
            try {
                return new InternalSampler(name);
            } catch (LinkageError ex) {
                return new StandaloneSampler(name);
            }
        }
        return null;
    }

    Sampler(String n) {
        name = n;
    }

    /** Returns the bean to use for sampling.
     * @return instance of the bean to take thread dumps from
     */
    abstract ThreadMXBean getThreadMXBean();

    /** Allows subclasses to handle created snapshot
     * @param arr the content of the snapshot
     * @throws IOException thrown in case of I/O error
     */
    abstract void saveSnapshot(byte[] arr) throws IOException;

    /** How to report an exception.
     *
     * @param ex exception
     */
    abstract void printStackTrace(Throwable ex);

    /** Methods for displaying progress.
     */
    abstract void openProgress(int steps);
    abstract void closeProgress();
    abstract void progress(int i);

    private void updateStats(long timestamp) {
        if (laststamp != 0) {
            double diff = (timestamp - laststamp) / 1000000.0;
            samples++;
            sum += diff;
            devSquaresSum += (diff - SAMPLER_RATE) * (diff - SAMPLER_RATE);
            if (diff > max) {
                max = diff;
            } else if (diff < min) {
                min = diff;
            }
        }
        laststamp = timestamp;
    }

    /**
     * Start self-sampling. This method starts timer identified by name
     * for actual sampling and returns immediately.
     */
    public final synchronized void start() {
        if (running) throw new IllegalStateException("sampling is already running");    // NOI18N
        if (stopped) throw new IllegalStateException("it is not possible to restart sampling");   // NOI18N
        running = true;
        final ThreadMXBean threadBean = getThreadMXBean();
        out = new ByteArrayOutputStream(64 * 1024);
        try {
            samplesStream = new SamplesOutputStream(out, this, MAX_SAMPLES);
        } catch (IOException ex) {
            printStackTrace(ex);
            return;
        }
        startTime = System.currentTimeMillis();
        nanoTimeCorrection = startTime * 1000000 - System.nanoTime();
        // make sure that the sampler thread can be detected in a thread dump - add prefix
        timer = new Timer("sampler-"+name);   // NOI18N
        timer.schedule(new TimerTask() {

            @Override
            public void run() {
                synchronized (Sampler.this) {
                    if (stopped) {
                        return;
                    }
                    try {
                        ThreadInfo[] infos = threadBean.dumpAllThreads(false, false);
                        long timestamp = System.nanoTime() + nanoTimeCorrection;
                        samplesStream.writeSample(infos, timestamp, Thread.currentThread().getId());
                        updateStats(timestamp);
                    } catch (Throwable ex) {
                        printStackTrace(ex);
                    }
                }
            }
        }, SAMPLER_RATE, SAMPLER_RATE);
    }

    /**
     * Cancels the self-sampling. All sampled data are discarded.
     */
    public final void cancel() {
        stopSampling(true, null);
    }

    /**
     * Stop the self-sampling started by {@link #start()} method and writes the data to
     * {@link DataOutputStream}. If the internal sampling logic detects that
     * the data are distorted for example due to heavy system I/O, collected
     * samples are discarded and nothing is written to {@link DataOutputStream}.
     *

     * This method can take a long time and should not be invoked from EDT.
     * @param dos {@link DataOutputStream} where sampled data is written to.
     */
    public final void stopAndWriteTo(@NonNull DataOutputStream dos) {
        stopSampling(false, dos);
    }

    /**
     * Stop the self-sampling, save and open gathered data. If there is no
     * sampled data, this method does nothing and returns immediately.
     *

     * This method can take a long time and should not be invoked from EDT.
     */
    public final void stop() {
        stopSampling(false, null);
    }

    private synchronized void stopSampling(boolean cancel, DataOutputStream dos) {
        try {
            if (!running) throw new IllegalStateException("sampling was not started"); // NOI18N
            if (stopped) throw new IllegalStateException("sampling is not running");    // NOI18N
            stopped = true;
            timer.cancel();
            if (cancel || samples < 1) {
                return;
            }
            if (SwingUtilities.isEventDispatchThread()) throw new IllegalStateException("sampling cannot be stopped from EDT");  //NOI18N
            double average = sum / samples;
            double std_deviation = Math.sqrt(devSquaresSum / samples);
            boolean writeCommand = dos != null;
            if (writeCommand) {
                Object[] params = new Object[]{startTime, "Samples", samples, "Average", average, "Minimum", min, "Maximum", max, "Std. deviation", std_deviation};  // NOI18N
                Logger.getLogger("org.netbeans.ui.performance").log(Level.CONFIG, "Snapshot statistics", params); // NOI18N
                if (average > MAX_AVERAGE || std_deviation > MAX_STDDEVIATION || samples < MIN_SAMPLES) {
                    // do not take snapshot if the sampling was not regular enough
                    return;
                }
            }
            samplesStream.close();
            samplesStream = null;
            if (writeCommand) {
                dos.write(out.toByteArray());
                dos.close();
                return;
            }
            saveSnapshot(out.toByteArray());
        } catch (IOException ex) {
            printStackTrace(ex);
        } finally {
            // just to be sure
            out = null;
            samplesStream = null;
        }
    }
}


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

package pt.up.fe.specs.clava.ast.decl;

import java.util.Collection;

import org.suikasoft.jOptions.Interfaces.DataStore;

import pt.up.fe.specs.clava.ClavaNode;

public class VarTemplateDecl extends RedeclarableTemplateDecl {

    public VarTemplateDecl(DataStore data, Collection<? extends ClavaNode> children) {
        super(data, children);
    }

    // public VarTemplateDecl(RedeclarableTemplateDecl redeclarableTemplateDecl) {
    // this(redeclarableTemplateDecl.getDeclName(), redeclarableTemplateDecl.getSpecializations(),
    // redeclarableTemplateDecl.getDeclData(), redeclarableTemplateDecl.getInfo(),
    // redeclarableTemplateDecl.getChildren());
    // }
    //
    // protected VarTemplateDecl(String declName, List<Decl> specializations, DeclData declData, ClavaNodeInfo info,
    // Collection<? extends ClavaNode> children) {
    //
    // super(declName, specializations, declData, info, children);
    // }
    //
    // @Override
    // protected ClavaNode copyPrivate() {
    // return new VarTemplateDecl(getDeclName(), getSpecializations(), getDeclData(), getInfo(),
    // Collections.emptyList());
    // }
}

domain: java


text:
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.apache.naming;

import java.util.HashMap;
import java.util.Hashtable;
import java.util.Enumeration;
import javax.naming.Context;
import javax.naming.Name;
import javax.naming.LinkRef;
import javax.naming.CompositeName;
import javax.naming.NameParser;
import javax.naming.Referenceable;
import javax.naming.Reference;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.NameAlreadyBoundException;
import javax.naming.NameNotFoundException;
import javax.naming.NotContextException;
import javax.naming.InitialContext;
import javax.naming.OperationNotSupportedException;
import javax.naming.spi.NamingManager;

/**
 * Catalina JNDI Context implementation.
 *
 * @author Remy Maucherat
 * @version $Revision: 467222 $ $Date: 2006-10-24 05:17:11 +0200 (Tue, 24 Oct 2006) $
 */
public class NamingContext implements Context {

    // -------------------------------------------------------------- Constants

    /**
     * Name parser for this context.
     */
    protected static final NameParser nameParser = new NameParserImpl();

    private static org.apache.juli.logging.Log log =
        org.apache.juli.logging.LogFactory.getLog(NamingContext.class);

    // ----------------------------------------------------------- Constructors

    /**
     * Builds a naming context using the given environment.
     */
    public NamingContext(Hashtable env, String name)
        throws NamingException {
        this.bindings = new HashMap();
        this.env = new Hashtable();
        // FIXME ? Could be put in the environment ?
        this.name = name;
        // Populating the environment hashtable
        if (env != null ) {
            Enumeration envEntries = env.keys();
            while (envEntries.hasMoreElements()) {
                String entryName = (String) envEntries.nextElement();
                addToEnvironment(entryName, env.get(entryName));
            }
        }
    }

    /**
     * Builds a naming context using the given environment.
     */
    public NamingContext(Hashtable env, String name, HashMap bindings)
        throws NamingException {
        this(env, name);
        this.bindings = bindings;
    }

    // ----------------------------------------------------- Instance Variables

    /**
     * Environment.
     */
    protected Hashtable env;

    /**
     * The string manager for this package.
     */
    protected StringManager sm = StringManager.getManager(Constants.Package);

    /**
     * Bindings in this Context.
     */
    protected HashMap bindings;

    /**
     * Name of the associated Catalina Context.
     */
    protected String name;

    // --------------------------------------------------------- Public Methods

    // -------------------------------------------------------- Context Methods

    /**
     * Retrieves the named object. If name is empty, returns a new instance
     * of this context (which represents the same naming context as this
     * context, but its environment may be modified independently and it may
     * be accessed concurrently).
     *
     * @param name the name of the object to look up
     * @return the object bound to name
     * @exception NamingException if a naming exception is encountered
     */
    public Object lookup(Name name)
        throws NamingException {
        return lookup(name, true);
    }

    /**
     * Retrieves the named object.
     *
     * @param name the name of the object to look up
     * @return the object bound to name
     * @exception NamingException if a naming exception is encountered
     */
    public Object lookup(String name)
        throws NamingException {
        return lookup(new CompositeName(name), true);
    }

    /**
     * Binds a name to an object. All intermediate contexts and the target
     * context (that named by all but terminal atomic component of the name)
     * must already exist.
     *
     * @param name the name to bind; may not be empty
     * @param obj the object to bind; possibly null
     * @exception NameAlreadyBoundException if name is already bound
     * @exception InvalidAttributesException if object did not supply all
     * mandatory attributes
     * @exception NamingException if a naming exception is encountered
     */
    public void bind(Name name, Object obj)
        throws NamingException {
        bind(name, obj, false);
    }

    /**
     * Binds a name to an object.
     *
     * @param name the name to bind; may not be empty
     * @param obj the object to bind; possibly null
     * @exception NameAlreadyBoundException if name is already bound
     * @exception InvalidAttributesException if object did not supply all
     * mandatory attributes
     * @exception NamingException if a naming exception is encountered
     */
    public void bind(String name, Object obj)
        throws NamingException {
        bind(new CompositeName(name), obj);
    }

    /**
     * Binds a name to an object, overwriting any existing binding. All
     * intermediate contexts and the target context (that named by all but
     * terminal atomic component of the name) must already exist.
     *

     * If the object is a DirContext, any existing attributes associated with
     * the name are replaced with those of the object. Otherwise, any
     * existing attributes associated with the name remain unchanged.
     *
     * @param name the name to bind; may not be empty
     * @param obj the object to bind; possibly null
     * @exception InvalidAttributesException if object did not supply all
     * mandatory attributes
     * @exception NamingException if a naming exception is encountered
     */
    public void rebind(Name name, Object obj)
        throws NamingException {
        bind(name, obj, true);
    }

    /**
     * Binds a name to an object, overwriting any existing binding.
     *
     * @param name the name to bind; may not be empty
     * @param obj the object to bind; possibly null
     * @exception InvalidAttributesException if object did not supply all
     * mandatory attributes
     * @exception NamingException if a naming exception is encountered
     */
    public void rebind(String name, Object obj)
        throws NamingException {
        rebind(new CompositeName(name), obj);
    }

    /**
     * Unbinds the named object. Removes the terminal atomic name in name
     * from the target context--that named by all but the terminal atomic
     * part of name.
     *

     * This method is idempotent. It succeeds even if the terminal atomic
     * name is not bound in the target context, but throws
     * NameNotFoundException if any of the intermediate contexts do not exist.
     *
     * @param name the name to bind; may not be empty
     * @exception NameNotFoundException if an intermediate context does not
     * exist
     * @exception NamingException if a naming exception is encountered
     */
    public void unbind(Name name)
        throws NamingException {
        checkWritable();

        while ((!name.isEmpty()) && (name.get(0).length() == 0))
            name = name.getSuffix(1);
        if (name.isEmpty())
            throw new NamingException
                (sm.getString("namingContext.invalidName"));

        NamingEntry entry = (NamingEntry) bindings.get(name.get(0));

        if (entry == null) {
            throw new NameNotFoundException
                (sm.getString("namingContext.nameNotBound", name.get(0)));
        }

        if (name.size() > 1) {
            if (entry.type == NamingEntry.CONTEXT) {
                ((Context) entry.value).unbind(name.getSuffix(1));
            } else {
                throw new NamingException
                    (sm.getString("namingContext.contextExpected"));
            }
        } else {
            bindings.remove(name.get(0));
        }

    }

    /**
     * Unbinds the named object.
     *
     * @param name the name to bind; may not be empty
     * @exception NameNotFoundException if an intermediate context does not
     * exist
     * @exception NamingException if a naming exception is encountered
     */
    public void unbind(String name)
        throws NamingException {
        unbind(new CompositeName(name));
    }

    /**
     * Binds a new name to the object bound to an old name, and unbinds the
     * old name. Both names are relative to this context. Any attributes
     * associated with the old name become associated with the new name.
     * Intermediate contexts of the old name are not changed.
     *
     * @param oldName the name of the existing binding; may not be empty
     * @param newName the name of the new binding; may not be empty
     * @exception NameAlreadyBoundException if newName is already bound
     * @exception NamingException if a naming exception is encountered
     */
    public void rename(Name oldName, Name newName)
        throws NamingException {
        Object value = lookup(oldName);
        bind(newName, value);
        unbind(oldName);
    }

    /**
     * Binds a new name to the object bound to an old name, and unbinds the
     * old name.
     *
     * @param oldName the name of the existing binding; may not be empty
     * @param newName the name of the new binding; may not be empty
     * @exception NameAlreadyBoundException if newName is already bound
     * @exception NamingException if a naming exception is encountered
     */
    public void rename(String oldName, String newName)
        throws NamingException {
        rename(new CompositeName(oldName), new CompositeName(newName));
    }

    /**
     * Enumerates the names bound in the named context, along with the class
     * names of objects bound to them. The contents of any subcontexts are
     * not included.
     *

     * If a binding is added to or removed from this context, its effect on
     * an enumeration previously returned is undefined.
     *
     * @param name the name of the context to list
     * @return an enumeration of the names and class names of the bindings in
     * this context. Each element of the enumeration is of type NameClassPair.
     * @exception NamingException if a naming exception is encountered
     */
    public NamingEnumeration list(Name name)
        throws NamingException {
        // Removing empty parts
        while ((!name.isEmpty()) && (name.get(0).length() == 0))
            name = name.getSuffix(1);
        if (name.isEmpty()) {
            return new NamingContextEnumeration(bindings.values().iterator());
        }

        NamingEntry entry = (NamingEntry) bindings.get(name.get(0));

        if (entry == null) {
            throw new NameNotFoundException
                (sm.getString("namingContext.nameNotBound", name.get(0)));
        }

        if (entry.type != NamingEntry.CONTEXT) {
            throw new NamingException
                (sm.getString("namingContext.contextExpected"));
        }
        return ((Context) entry.value).list(name.getSuffix(1));
    }

    /**
     * Enumerates the names bound in the named context, along with the class
     * names of objects bound to them.
     *
     * @param name the name of the context to list
     * @return an enumeration of the names and class names of the bindings in
     * this context. Each element of the enumeration is of type NameClassPair.
     * @exception NamingException if a naming exception is encountered
     */
    public NamingEnumeration list(String name)
        throws NamingException {
        return list(new CompositeName(name));
    }

    /**
     * Enumerates the names bound in the named context, along with the
     * objects bound to them. The contents of any subcontexts are not
     * included.
     *

     * If a binding is added to or removed from this context, its effect on
     * an enumeration previously returned is undefined.
     *
     * @param name the name of the context to list
     * @return an enumeration of the bindings in this context.
     * Each element of the enumeration is of type Binding.
     * @exception NamingException if a naming exception is encountered
     */
    public NamingEnumeration listBindings(Name name)
        throws NamingException {
        // Removing empty parts
        while ((!name.isEmpty()) && (name.get(0).length() == 0))
            name = name.getSuffix(1);
        if (name.isEmpty()) {
            return new NamingContextBindingsEnumeration(bindings.values().iterator(), this);
        }

        NamingEntry entry = (NamingEntry) bindings.get(name.get(0));

        if (entry == null) {
            throw new NameNotFoundException
                (sm.getString("namingContext.nameNotBound", name.get(0)));
        }

        if (entry.type != NamingEntry.CONTEXT) {
            throw new NamingException
                (sm.getString("namingContext.contextExpected"));
        }
        return ((Context) entry.value).listBindings(name.getSuffix(1));
    }

    /**
     * Enumerates the names bound in the named context, along with the
     * objects bound to them.
     *
     * @param name the name of the context to list
     * @return an enumeration of the bindings in this context.
     * Each element of the enumeration is of type Binding.
     * @exception NamingException if a naming exception is encountered
     */
    public NamingEnumeration listBindings(String name)
        throws NamingException {
        return listBindings(new CompositeName(name));
    }

    /**
     * Destroys the named context and removes it from the namespace. Any
     * attributes associated with the name are also removed. Intermediate
     * contexts are not destroyed.
     *

     * This method is idempotent. It succeeds even if the terminal atomic
     * name is not bound in the target context, but throws
     * NameNotFoundException if any of the intermediate contexts do not exist.
     *
     * In a federated naming system, a context from one naming system may be
     * bound to a name in another. One can subsequently look up and perform
     * operations on the foreign context using a composite name. However, an
     * attempt destroy the context using this composite name will fail with
     * NotContextException, because the foreign context is not a "subcontext"
     * of the context in which it is bound. Instead, use unbind() to remove
     * the binding of the foreign context. Destroying the foreign context
     * requires that the destroySubcontext() be performed on a context from
     * the foreign context's "native" naming system.
     *
     * @param name the name of the context to be destroyed; may not be empty
     * @exception NameNotFoundException if an intermediate context does not
     * exist
     * @exception NotContextException if the name is bound but does not name
     * a context, or does not name a context of the appropriate type
     */
    public void destroySubcontext(Name name)
        throws NamingException {

        checkWritable();

        while ((!name.isEmpty()) && (name.get(0).length() == 0))
            name = name.getSuffix(1);
        if (name.isEmpty())
            throw new NamingException
                (sm.getString("namingContext.invalidName"));

        NamingEntry entry = (NamingEntry) bindings.get(name.get(0));

        if (entry == null) {
            throw new NameNotFoundException
                (sm.getString("namingContext.nameNotBound", name.get(0)));
        }

        if (name.size() > 1) {
            if (entry.type == NamingEntry.CONTEXT) {
                ((Context) entry.value).unbind(name.getSuffix(1));
            } else {
                throw new NamingException
                    (sm.getString("namingContext.contextExpected"));
            }
        } else {
            if (entry.type == NamingEntry.CONTEXT) {
                ((Context) entry.value).close();
                bindings.remove(name.get(0));
            } else {
                throw new NotContextException
                    (sm.getString("namingContext.contextExpected"));
            }
        }

    }

    /**
     * Destroys the named context and removes it from the namespace.
     *
     * @param name the name of the context to be destroyed; may not be empty
     * @exception NameNotFoundException if an intermediate context does not
     * exist
     * @exception NotContextException if the name is bound but does not name
     * a context, or does not name a context of the appropriate type
     */
    public void destroySubcontext(String name)
        throws NamingException {
        destroySubcontext(new CompositeName(name));
    }

    /**
     * Creates and binds a new context. Creates a new context with the given
     * name and binds it in the target context (that named by all but
     * terminal atomic component of the name). All intermediate contexts and
     * the target context must already exist.
     *
     * @param name the name of the context to create; may not be empty
     * @return the newly created context
     * @exception NameAlreadyBoundException if name is already bound
     * @exception InvalidAttributesException if creation of the subcontext
     * requires specification of mandatory attributes
     * @exception NamingException if a naming exception is encountered
     */
    public Context createSubcontext(Name name)
        throws NamingException {
        checkWritable();

        Context newContext = new NamingContext(env, this.name);
        bind(name, newContext);

        return newContext;
    }

    /**
     * Creates and binds a new context.
     *
     * @param name the name of the context to create; may not be empty
     * @return the newly created context
     * @exception NameAlreadyBoundException if name is already bound
     * @exception InvalidAttributesException if creation of the subcontext
     * requires specification of mandatory attributes
     * @exception NamingException if a naming exception is encountered
     */
    public Context createSubcontext(String name)
        throws NamingException {
        return createSubcontext(new CompositeName(name));
    }

    /**
     * Retrieves the named object, following links except for the terminal
     * atomic component of the name. If the object bound to name is not a
     * link, returns the object itself.
     *
     * @param name the name of the object to look up
     * @return the object bound to name, not following the terminal link
     * (if any).
     * @exception NamingException if a naming exception is encountered
     */
    public Object lookupLink(Name name)
        throws NamingException {
        return lookup(name, false);
    }

    /**
     * Retrieves the named object, following links except for the terminal
     * atomic component of the name.
     *
     * @param name the name of the object to look up
     * @return the object bound to name, not following the terminal link
     * (if any).
     * @exception NamingException if a naming exception is encountered


text:
/*
 * Copyright 2017-2020 original authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.micronaut.security.oauth2.client.clientcredentials.propagation;

import io.micronaut.core.annotation.NonNull;
import io.micronaut.context.annotation.EachBean;
import io.micronaut.context.annotation.Requires;
import io.micronaut.core.annotation.Internal;
import io.micronaut.http.HttpHeaders;
import io.micronaut.http.HttpRequest;
import io.micronaut.http.MutableHttpRequest;
import io.micronaut.security.oauth2.client.clientcredentials.ClientCredentialsEnabled;
import io.micronaut.security.oauth2.configuration.OauthClientConfiguration;

import java.util.Optional;

/**
 * Propagates a token obtained via client credentials based off of a header.
 *
 * @author Sergio del Amo
 * @since 2.2.0
 */
@Internal
@EachBean(OauthClientConfiguration.class)
@Requires(condition = ClientCredentialsEnabled.class)
@Requires(condition = ClientCredentialsHeaderPropagatorEnabled.class)
public class ClientCredentialsHeaderTokenPropagator implements ClientCredentialsTokenPropagator {

    public static final String SPACE = " ";
    protected final ClientCredentialsHeaderTokenPropagatorConfiguration configuration;

    /**
     * @param configuration The token propagator configuration
     */
    public ClientCredentialsHeaderTokenPropagator(ClientCredentialsHeaderTokenPropagatorConfiguration configuration) {
        this.configuration = configuration;
    }

    /**
     * Writes the token to the request.
     * @param request The {@link MutableHttpRequest} instance
     * @param token A token ( e.g. JWT token, basic auth token...)
     */
    @Override
    public void writeToken(@NonNull MutableHttpRequest<?> request, @NonNull String token) {
        request.header(configuration.getHeaderName(), headerValue(token));
    }

    /**
     * Search for a JWT token in a HTTP request.
     * @param request The request to look for the token in
     * @return if the JWT token is found it is returned, empty if not
     */
    @Override
    public Optional<String> findToken(@NonNull HttpRequest<?> request) {
        HttpHeaders headers = request.getHeaders();
        Optional<String> authorizationHeader = headers.findFirst(configuration.getHeaderName());
        return authorizationHeader.flatMap(this::extractTokenFromAuthorization);
    }

    /**
     * @param token the token being written
     * @return the value which will be written to an HTTP Header
     */
    protected String headerValue(String token) {
        StringBuilder sb = prefix();
        sb.append(token);
        return sb.toString();
    }

    /**
     * @param authorization Authorization header value
     * @return If prefix is 'Bearer' for 'Bearer XXX' it returns 'XXX'
     */
    protected Optional<String> extractTokenFromAuthorization(String authorization) {
        StringBuilder sb = prefix();
        String str = sb.toString();
        if (authorization.startsWith(str)) {
            return Optional.of(authorization.substring(str.length()));
        }
        return Optional.empty();
    }

    @NonNull
    private StringBuilder prefix() {
        StringBuilder sb = new StringBuilder();
        final String prefix = configuration.getPrefix();
        if (prefix != null && !prefix.isEmpty()) {
            sb.append(prefix);
            if (!prefix.endsWith(SPACE)) {
                sb.append(SPACE);
            }
        }
        return sb;
    }

    /**
     *
     * @return The HttpHeaderTokenPropagator Configuration
     */
    public ClientCredentialsHeaderTokenPropagatorConfiguration getConfiguration() {
        return configuration;
    }
}


text:
/*-
 * #%L
 * ImgLib2: a general-purpose, multidimensional image processing library.
 * %%
 * Copyright (C) 2009 - 2022 Tobias Pietzsch, Stephan Preibisch, Stephan Saalfeld,
 * John Bogovic, Albert Cardona, Barry DeZonia, Christian Dietz, Jan Funke,
 * Aivar Grislis, Jonathan Hale, Grant Harris, Stefan Helfrich, Mark Hiner,
 * Martin Horn, Steffen Jaensch, Lee Kamentsky, Larry Lindsey, Melissa Linkert,
 * Mark Longair, Brian Northan, Nick Perry, Curtis Rueden, Johannes Schindelin,
 * Jean-Yves Tinevez and Michael Zinsmaier.
 * %%
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 * #L%
 */
package net.imglib2.loops;

import net.imglib2.img.Img;
import net.imglib2.img.array.ArrayImgs;
import net.imglib2.type.numeric.integer.IntType;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import org.openjdk.jmh.runner.options.TimeValue;

import java.util.List;
import java.util.function.IntSupplier;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

@State( Scope.Benchmark )
public class SyncedPositionablesBenchmark
{
	private long[] dims = { 100, 100, 100 };

	private List< Img< IntType > > array = sixTimes(() -> ArrayImgs.ints( dims ));

	private < T > List< T > sixTimes( Supplier< T > supplier )
	{
		return IntStream.range( 0, 6 ).mapToObj( ignore -> supplier.get() ).collect( Collectors.toList());
	}

	@Benchmark
	public void benchmark2() {
		LoopBuilder.setImages( array.get( 0 ), array.get( 1 ) )
				.forEachPixel( (a, r) -> r.setReal( a.getRealDouble() ) );
	}

	@Benchmark
	public void benchmark3() {
		LoopBuilder.setImages( array.get( 0 ), array.get( 1 ), array.get( 2 ) )
				.forEachPixel( (a, b, r) -> r.setReal( a.getRealDouble() + b.getRealDouble() ) );
	}

	@Benchmark
	public void benchmark4() {
		LoopBuilder.setImages( array.get( 0 ), array.get( 1 ), array.get( 2 ), array.get( 3 ) )
				.forEachPixel( (a, b, c, r) -> r.setReal( a.getRealDouble() + b.getRealDouble() + c.getRealDouble() ) );
	}

	@Benchmark
	public void benchmark5() {
		LoopBuilder.setImages( array.get( 0 ), array.get( 1 ), array.get( 2 ), array.get( 3 ), array.get( 4) )
				.forEachPixel( (a, b, c, d, r) -> r.setReal( a.getRealDouble() + b.getRealDouble() + c.getRealDouble() + d.getRealDouble() ) );
	}

	@Benchmark
	public void benchmark6() {
		LoopBuilder.setImages( array.get( 0 ), array.get( 1 ), array.get( 2 ), array.get( 3 ), array.get( 4 ), array.get( 5) )
				.forEachPixel( (a, b, c, d, e, r) -> r.setReal( a.getRealDouble() + b.getRealDouble() + c.getRealDouble() + d.getRealDouble() + e.getRealDouble() ) );
	}

	public static void main( final String... args ) throws RunnerException
	{
		final Options opt = new OptionsBuilder()
				.include( SyncedPositionables.class.getSimpleName() )
				.forks( 0 )
				.warmupIterations( 10 )
				.measurementIterations( 8 )
				.warmupTime( TimeValue.milliseconds( 100 ) )
				.measurementTime( TimeValue.milliseconds( 100 ) )
				.build();
		new Runner( opt ).run();
	}
}


text:
package com.vaadin.example;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Queue;

import com.vaadin.flow.component.Key;
import com.vaadin.flow.component.UI;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.combobox.ComboBox;
import com.vaadin.flow.component.contextmenu.MenuItem;
import com.vaadin.flow.component.contextmenu.SubMenu;
import com.vaadin.flow.component.dialog.Dialog;
import com.vaadin.flow.component.html.Div;
import com.vaadin.flow.component.html.H1;
import com.vaadin.flow.component.html.Label;

import com.vaadin.flow.component.icon.Icon;
import com.vaadin.flow.component.icon.VaadinIcon;
import com.vaadin.flow.component.menubar.MenuBar;
import com.vaadin.flow.component.orderedlayout.HorizontalLayout;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.component.select.Select;
import com.vaadin.flow.component.tabs.Tab;
import com.vaadin.flow.component.tabs.Tabs;
import com.vaadin.flow.component.textfield.TextArea;
import com.vaadin.flow.component.textfield.TextField;
import com.vaadin.flow.dom.ThemeList;
import com.vaadin.flow.router.Route;
import com.vaadin.flow.theme.Theme;
import com.vaadin.flow.theme.lumo.Lumo;
import com.vaadin.flow.component.notification.Notification;
import com.vaadin.flow.component.notification.Notification.Position;

import org.vaadin.pekkam.Canvas;
import org.vaadin.pekkam.CanvasRenderingContext2D;

@Route
public class MainView extends VerticalLayout {

    /**
     *
     */
    private static final long serialVersionUID = 1125267260411033039L;
    // TODO:
    // private static ArrayList<String> continentColourList = new ArrayList<>();
    // 存储大陆和国家的数据
    private ArrayList<ArrayList<String>> continentsData = new ArrayList<>();
    private ArrayList<ArrayList<String>> countriesData = new ArrayList<>();
    private ArrayList<ArrayList<String>> neighborsData = new ArrayList<>();

    // 存储是否包含这个大陆或者国家
    private HashMap<String, Integer> continentsMap = new HashMap<>();
    private HashMap<String, String> countriesMap = new HashMap<>();
    private HashMap<String, Integer> neighborsMap = new HashMap<>();

    private TextArea continents = new TextArea(); // (2)
    private TextArea countries = new TextArea(); // (2)
    private TextArea neighbors = new TextArea();
    private TextArea outputLog = new TextArea(); // (2)
    private TextField commandLine = new TextField(); // (2)

    private TextArea mapSize = new TextArea();

    private Tab tab1 = new Tab("Output Log");
    private Tab tab2 = new Tab(new Icon(VaadinIcon.GLOBE));
    private Tab tab3 = new Tab("Tab three");
    Tabs tabs = new Tabs(tab1, tab2, tab3);

    private Div page1 = new Div();
    private Div page2 = new Div();
    private Div page3 = new Div();
    Div pages = new Div(page1, page2, page3);

    // private Image image = new Image("https://dummyimage.com/600x400/000/fff",
    // "DummyImage");

    // private MemoryBuffer buffer = new MemoryBuffer();
    // private Upload upload = new Upload(buffer);

    private String x_coor = "";
    private String y_coor = "";

    private int map_width = 0;
    private int map_height = 0;

    // private boolean hasMapSize = false;

    // if value == true, this color could be used in a new continent
    private HashMap<String, Boolean> colorAvailable = new HashMap<>();

    private Canvas canvas = new Canvas(2000, 1000);
    private CanvasRenderingContext2D ctx = canvas.getContext();
    private Button runButton;
    private MenuBar menuBar = new MenuBar();

    private ArrayList<String> map_list = new ArrayList<>();

    // private void updateMapList() {
    // map_list = getFile();
    // }

    private void init() {
        // add all maps in map folder to map_list
        map_list.addAll(getFile());

        String[] continent_data_list = { "Asia", "Europe", "North-America", "South-America", "Africa", "Oceania" };
        String[] country_data_list = { "Afghanistan", "Alaska", "Alberta", "Argentina", "Brazil", "Central-America",
                "China", "Congo", "East-Africa", "Eastern-United-States", "Egypt", "Great-Britain", "Greenland",
                "Iceland", "India", "Indonesia", "Madagascar", "North-Africa", "North-West-Territory", "Northern-Europe", "Ontario", "Peru",
                "Quebec", "Scandinavia", "Siam", "Siberia", "South-Africa", "Southern-Europe", "Ukraine", "Ural", "Venezuela",
                "Western-Europe", "Western-United-States" };

        MenuItem editcontinent_menu = menuBar.addItem("editcontinent");
        MenuItem editcountry_menu = menuBar.addItem("editcountry");
        MenuItem editneighbor_menu = menuBar.addItem("editneighbor");
        MenuItem map_menu = menuBar.addItem("map operations");
        MenuItem data_menu = menuBar.addItem("data");

        // menuBar.addItem("Sign Out", e -> selected.setText("Sign Out"));

        SubMenu editcontinent_submenu = editcontinent_menu.getSubMenu();
        editcontinent_submenu.addItem("-add", e -> commandLine.setValue("editcontinent -add"));
        editcontinent_submenu.addItem("-remove", e -> commandLine.setValue("editcontinent -remove"));

        SubMenu editcountry_submenu = editcountry_menu.getSubMenu();
        editcountry_submenu.addItem("-add", e -> commandLine.setValue("editcountry -add"));
        editcountry_submenu.addItem("-remove", e -> commandLine.setValue("editcountry -remove"));

        SubMenu editneighbor_submenu = editneighbor_menu.getSubMenu();
        editneighbor_submenu.addItem("-add", e -> commandLine.setValue("editneighbor -add"));
        editneighbor_submenu.addItem("-remove", e -> commandLine.setValue("editneighbor -remove"));

        SubMenu map_submenu = map_menu.getSubMenu();
        map_submenu.addItem("showmap", e -> showmap());
        map_submenu.addItem("validatemap", e -> validateMap());
        map_submenu.addItem("savemap", e -> commandLine.setValue("savemap"));

        MenuItem editmap_submenu = map_submenu.addItem("editmap");
        SubMenu editmap_data_submenu = editmap_submenu.getSubMenu();
        for (String map_name : map_list) {
            editmap_data_submenu.addItem(map_name, e -> editMap(map_name));
        }

        SubMenu data_submenu = data_menu.getSubMenu();
        MenuItem continent_data_menu = data_submenu.addItem("continent list");
        MenuItem country_data_menu = data_submenu.addItem("country list");
        // MenuItem integer_data_menu = data_submenu.addItem("integer list");

        SubMenu continent_data_submenu = continent_data_menu.getSubMenu();
        for (String continent_data_name : continent_data_list) {
            continent_data_submenu.addItem(continent_data_name,
                    e -> commandLine.setValue(commandLine.getValue() + " " + continent_data_name));
        }
        SubMenu country_data_submenu = country_data_menu.getSubMenu();
        for (String country_data_name : country_data_list) {
            country_data_submenu.addItem(country_data_name,
                    e -> commandLine.setValue(commandLine.getValue() + " " + country_data_name));
        }
        // SubMenu integer_data_menu = continent_data_menu.getSubMenu();
        // for {
        // continent_data_submenu.addItem(continent_data_name, e ->
        // commandLine.setValue(commandLine.getValue() + " " + continent_data_name));
        // }

        // TODO:

        // SubMenu country_data_list_submenu = country_data_list.getSubMenu();
        // MenuItem continent_data_list = country_data_list_submenu.addItem("continent
        // list");
        // MenuItem country_data_list = country_data_list_submenu.addItem("country
        // list");

        // page1.setText("Page#1");

        // page2.setText("Page#2");
        // page2.setVisible(false);

        // page3.setText("Page#3");
        // page3.setVisible(false);

        // Map<Tab, Component> tabsToPages = new HashMap<>();
        // tabsToPages.put(tab1, outputLog);
        // tabsToPages.put(tab2, new VerticalLayout(mapSize, canvas));
        // tabsToPages.put(tab3, page3);

        // Set<Component> pagesShown = Stream.of(page1).collect(Collectors.toSet());
        mapSize.setVisible(false);
        mapSize.setReadOnly(true);
        mapSize.setMaxHeight("200px");
        mapSize.setMaxWidth("200px");
        canvas.setVisible(false);
        outputLog.setVisible(true);

        tabs.addSelectedChangeListener(event -> {
            if (tabs.getSelectedTab() == tab1) {
                mapSize.setVisible(false);
                canvas.setVisible(false);
                outputLog.setVisible(true);
                continents.setVisible(true);
                countries.setVisible(true);
                neighbors.setVisible(true);
                commandLine.setVisible(true);
                runButton.setVisible(true);
                menuBar.setVisible(true);
            } else if (tabs.getSelectedTab() == tab2) {
                mapSize.setVisible(true);
                canvas.setVisible(true);
                outputLog.setVisible(false);
                continents.setVisible(false);
                countries.setVisible(false);
                neighbors.setVisible(false);
                commandLine.setVisible(false);
                runButton.setVisible(false);
                menuBar.setVisible(false);
            } else if (tabs.getSelectedTab() == tab3) {
                mapSize.setVisible(false);
                canvas.setVisible(false);
                outputLog.setVisible(false);
                continents.setVisible(false);
                countries.setVisible(false);
                neighbors.setVisible(false);
                commandLine.setVisible(false);
                runButton.setVisible(false);
                menuBar.setVisible(false);
            }
        });

        tabs.setSelectedTab(tab1);
        tab3.add(outputLog);

        // Draw an image located in src/main/webapp/resources:
        // ctx.drawImage("https://dummyimage.com/600x400/FCFAF2/000000&text=+", 0, 0);

        // TODO:
        // ctx.setStrokeStyle("#373C38");
        // ctx.strokeRect(1, 1, 699, 399);

        // for (int i = 0; i < 6; i++) {
        // for (int j = 0; j < 6; j++) {
        // ctx.setFillStyle(String.format("rgb(%s, %s, 0)", i * 50, j * 50));
        // ctx.fillRect(j * 25, i * 25, 25, 25);
        // }
        // }
        // ctx.setFillStyle(String.format("rgb(%s, %s, %s)", 100, 111, 99));
        // ctx.fillRect(200, 200, 100, 100);

        // // Draw a red line from point (10,10) to (100,100):
        // ctx.setStrokeStyle("red");
        // ctx.beginPath();
        // ctx.moveTo(10, 10);
        // ctx.lineTo(100, 100);
        // ctx.closePath();
        // ctx.stroke();

        // continents color set
        colorAvailable.put("yellow", true);
        colorAvailable.put("red", true);
        colorAvailable.put("blue", true);
        colorAvailable.put("orange", true);
        colorAvailable.put("magenta", true);
        colorAvailable.put("green", true);
        colorAvailable.put("pink", true);

        continents.setValue("continents shows here\n");
        continents.setLabel("Continents");
        continents.setReadOnly(true);
        continents.setWidth("350px");
        continents.getStyle().set("maxHeight", "300px");
        continents.getStyle().set("minHeight", "200px");

        countries.setValue("countries shows here\n");
        countries.setLabel("Countries");
        countries.setReadOnly(true);
        countries.setWidth("500px");
        countries.getStyle().set("maxHeight", "300px");
        countries.getStyle().set("minHeight", "200px");

        neighbors.setValue("neighbors shows here\n");
        neighbors.setLabel("Neighbors");
        neighbors.setReadOnly(true);
        neighbors.setWidth("800px");
        neighbors.getStyle().set("maxHeight", "300px");
        neighbors.getStyle().set("minHeight", "200px");

        String defaultOutput = "editcontinent -add Asia 10\n" + "editcontinent -remove Asia\n"
                + "editcountry -add China Asia\n" + "editcountry -add India Asia\n" + "editcountry -remove China\n"
                + "editneighbor -add China India\n" + "editneighbor -remove China India\n"
                + "editneighbor -remove India China\n" + "editmap risk\n" + "savemap map_1\n" + "validatemap\n"
                + "editneighbor -remove Siam Indonesia\n" + "editneighbor -add Siam Indonesia\n" + "showmap\n";
        outputLog.setValue("output shows here\n" + defaultOutput);
        outputLog.setLabel("Output Log");
        outputLog.setReadOnly(true);
        outputLog.setWidth("600px");
        outputLog.getStyle().set("maxHeight", "400px");
        outputLog.getStyle().set("minHeight", "300px");

        commandLine.setPlaceholder("Command Line");
        commandLine.setWidth("600px");
        commandLine.setClearButtonVisible(true);
        commandLine.setErrorMessage("invalid");
    }

    private ArrayList<String> getFile() {
        String path = "D:/Projects/GitProjects/APPmapeditor/map"; // 要遍历的路径
        File file = new File(path); // 获取其file对象
        File[] fs = file.listFiles(); // 遍历path下的文件和目录，放在File数组中
        ArrayList<String> file_list = new ArrayList<>();
        for (File f : fs) { // 遍历File[]数组
            if (!f.isDirectory()) { // 若非目录(即文件)，则加入list
                // TODO:
                String temp = f.getName();
                if (temp.substring(temp.length() - 4).equals(".map")) {
                    file_list.add(temp.substring(0, temp.length() - 4));
                }
            }
        }
        addOutputLog("Find maps in map folder: " + file_list);
        return file_list;
    }

    public void addOutputLog(String addtext) {
        outputLog.setValue(outputLog.getValue() + addtext + "\n");
        Notification notification = new Notification(addtext, 3000, Position.TOP_START);
        notification.open();
    }

    public void coordinatesDialog(String countryname, String continentname) {
        Dialog dialog = new Dialog();
        dialog.setCloseOnEsc(false);
        dialog.setCloseOnOutsideClick(false);

        TextField coordinatesText = new TextField(); // (2)
        coordinatesText.setPlaceholder("input coordinates seperate with space");
        coordinatesText.setWidth("300px");
        coordinatesText.setClearButtonVisible(true);

        Button confirmButton = new Button("Confirm", event -> {
            x_coor = coordinatesText.getValue().split(" ")[0];
            y_coor = coordinatesText.getValue().split(" ")[1];
            dialog.close();

            if (x_coor.matches("\\d+") && y_coor.matches("\\d+")) {
                if (Integer.valueOf(x_coor) > 0 && Integer.valueOf(x_coor) < map_width && Integer.valueOf(y_coor) > 0
                        && Integer.valueOf(y_coor) < map_width) {
                    addCountry(countryname, continentname, Integer.valueOf(x_coor), Integer.valueOf(y_coor));
                } else {
                    createAlert("Wrong coordiantes. You can not place a country outside the map.");
                }
            } else {
                createAlert("Country coordiantes should be integers!");
            }

        });
        confirmButton.addClickShortcut(Key.ENTER);
        // TODO:
        // invalid coordinates

        dialog.add(coordinatesText, confirmButton);
        dialog.open();
        coordinatesText.focus();
    }

    public void setMapSize() {
        Dialog dialog = new Dialog();
        dialog.setCloseOnEsc(false);
        dialog.setCloseOnOutsideClick(false);

        TextField mapSizeText = new TextField(); // (2)
        mapSizeText.setPlaceholder("input map width and height seperate with space");
        mapSizeText.setWidth("400px");
        mapSizeText.setClearButtonVisible(true);

        Button confirmButton = new Button("Confirm", event -> {
            map_width = Integer.valueOf(mapSizeText.getValue().split(" ")[0]);
            map_height = Integer.valueOf(mapSizeText.getValue().split(" ")[1]);
            dialog.close();

            if ((mapSizeText.getValue().split(" ")[0].matches("\\d+")
                    && Integer.valueOf(mapSizeText.getValue().split(" ")[0]) > 0)
                    && (mapSizeText.getValue().split(" ")[1].matches("\\d+")
                            && Integer.valueOf(mapSizeText.getValue().split(" ")[1]) > 0)) {
                addOutputLog("set map width to: " + map_width + "; set map height to: " + map_height);
                mapSize.setValue("map width: " + map_width + "\nmap height: " + map_height);

                // TODO:
                canvas.setMaxHeight(String.valueOf(map_height));
                canvas.setMinHeight(String.valueOf(map_height));
                canvas.setMaxWidth(String.valueOf(map_width));
                canvas.setMinWidth(String.valueOf(map_width));
                ctx.setStrokeStyle("#373C38");
                ctx.strokeRect(2, 2, map_width - 2, map_height - 2);
            } else {
                createAlert("Invalid map size.");
                setMapSize();
            }
        });
        confirmButton.addClickShortcut(Key.ENTER);

        dialog.add(mapSizeText, confirmButton);
        dialog.open();
        mapSizeText.focus();
    }

    public void testCases() {
        // ArrayList<String> tempAL = new ArrayList<>();
        // tempAL.add("China");
        // tempAL.add("India");
        // countriesMap.add(tempAL);
        // countriesMap.put(continentname, Integer.valueOf(continentvalue));
    }

    public MainView() {
        init();

        // testCases();

        setMapSize();

        commandLine.addKeyDownListener(event -> {
            commandLine.setInvalid(false);
        });

        // TODO:
        runButton = new Button("Run", event -> {
            String temp = commandLine.getValue();
            String[] tempArr = temp.split(" ");

            if (tempArr.length == 4) {
                // editcontinent
                if (tempArr[0].equals("editcontinent")) {
                    if (tempArr[1].equals("-add")) {
                        // TODO closed
                        if (tempArr[3].matches("\\d+") && Integer.valueOf(tempArr[3]) > 0)
                            addContinent(tempArr[2], tempArr[3]);
                        else {
                            createAlert("Continent value is not an positive integer!");
                        }
                    } else {
                        // TODO closed
                        // invalid input alert
                        // invalidInputAlert();
                        commandLine.setInvalid(true);
                    }
                }
                // editcountry
                else if (tempArr[0].equals("editcountry")) {
                    // TODO closed
                    if (tempArr[1].equals("-add")) {
                        // open dialog for the input of coordinates

                        coordinatesDialog(tempArr[2], tempArr[3]);

                        // TODO closed
                        // addCountry(tempArr[2], tempArr[3], Integer.valueOf(x_coor),
                        // Integer.valueOf(y_coor));
                    } else {
                        // TODO closed
                        // invalid input alert
                        invalidInputAlert();
                    }
                }
                // editneighbor
                else if (tempArr[0].equals("editneighbor")) {
                    // TODO:
                    if (tempArr[1].equals("-add")) {
                        addNeighbor(tempArr[2], tempArr[3]);
                    } else if (tempArr[1].equals("-remove")) {
                        removeNeighbor(tempArr[2], tempArr[3]);
                    } else {


text:
package algo.lc;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * @Author: sunhaijian
 * @Date: 2020/8/24
 * @Description:
Shuffle a set of numbers without duplicates.

Example:

// Init an array with set 1, 2, and 3.
int[] nums = {1,2,3};
Solution solution = new Solution(nums);

// Shuffle the array [1,2,3] and return its result. Any permutation of [1,2,3] must equally likely to be returned.
solution.shuffle();

// Resets the array back to its original configuration [1,2,3].
solution.reset();

// Returns the random shuffling of array [1,2,3].
solution.shuffle();

 **/

@RunWith(Parameterized.class)
public class Shuffle_An_Array_384 {

    private int [] array;
    private int[] originNum;

    Random rand=new Random();

//    public Shuffle_An_Array_384 (){ }

    public Shuffle_An_Array_384(int[] nums) {
        array=nums;
        originNum=nums.clone();

    }

    /** Resets the array to its original configuration and return it. */
    public int[] reset() {
        array=originNum;
        originNum=originNum.clone();
        return array;
    }

    /** Returns a random shuffling of the array. */
    public int[] shuffle() {
        for(int i=0;i<array.length;i++){
            swap(i,rand(i,array.length));
        }
        return array;
    }

    private int rand(int min,int max){
        return rand.nextInt(max-min)+min;
    }

    private void swap(int i,int j){
        int temp=array[i];
        array[i]=array[j];
        array[j]=temp;
    }
//
//    @Test
//     void test(){
//
//        check();
//        System.out.println(1);
//    }

    public static void main(String[] args) {
        check2();
//        System.out.println(1);
    }

    public static void check(){
        int N=1000000;
        Map<String,Integer> map=new HashMap();
        map.put("123",0);
        map.put("132",0);
        map.put("321",0);
        map.put("312",0);
        map.put("213",0);
        map.put("231",0);

        for (int i = 0; i < N; i++) {
            int [] arr={1,2,3};

            Shuffle_An_Array_384 shuf=new Shuffle_An_Array_384(arr);
            int []res=shuf.shuffle();
            String str=""+res[0]+res[1]+res[2];
            map.put(str,map.get(str)+1);
        }
        for (String key:map.keySet()) {
            System.out.println(key+":"+map.get(key));
        }
    }
    public static void check2(){
        int N=1000000;

        int []count=new int [5];

        for (int i = 0; i < N; i++) {
            int [] arr={1,0,0,0,0};

            Shuffle_An_Array_384 shuf=new Shuffle_An_Array_384(arr);
            int []res=shuf.shuffle();
            for (int j = 0; j <res.length ; j++) {
                if(res[j]==1){
                    count[j]++;
                }
            }
        }
        for (int i = 0; i <count.length ; i++) {
            System.out.println(i+":"+count[i]);
        }
    }

}


text:
/*
 * Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 *
 */
package org.maxkey.authn.realm.ldap;

import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;

import org.maxkey.authn.realm.IAuthenticationServer;
import org.maxkey.persistence.ldap.LdapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Crystal.Sea
 *
 */
public final class StandardLdapServer implements IAuthenticationServer {
	private final static Logger _logger = LoggerFactory.getLogger(StandardLdapServer.class);

	LdapUtils ldapUtils;

	String filterAttribute;

	boolean mapping;

	/* (non-Javadoc)
	 * @see com.connsec.web.authentication.realm.IAuthenticationServer#authenticate(java.lang.String, java.lang.String)
	 */
	@Override
	public boolean authenticate(String username, String password) {
		String queryFilter = String.format(filterAttribute, username);
		_logger.info(" filter : " + queryFilter);
		String dn="";
		SearchControls constraints = new SearchControls();
		constraints.setSearchScope(ldapUtils.getSearchScope());
		try {
			NamingEnumeration<SearchResult> results = ldapUtils.getConnection()
					.search(ldapUtils.getBaseDN(), queryFilter, constraints);

			if (results == null || !results.hasMore()) {
				_logger.error("Ldap user "+username +" not found . ");
				return false;
			}else{
				while (results != null && results.hasMore()) {
					SearchResult sr = (SearchResult) results.next();
					//String rdn = sr.getName();
					dn = sr.getNameInNamespace();
					_logger.debug("Directory user dn is "+dn+" .");
				}
			}
		} catch (NamingException e) {
			_logger.error("query throw NamingException:" + e.getMessage());
		} finally {
			//ldapUtils.close();
		}

		LdapUtils ldapPassWordValid=new LdapUtils(ldapUtils.getProviderUrl(),dn,password);
		ldapPassWordValid.openConnection();
		if(ldapPassWordValid.getCtx()!=null){
			_logger.debug("Directory user " + username + "  is validate .");
			ldapPassWordValid.close();
			return true;
		}
		return false;
	}

	public LdapUtils getLdapUtils() {
		return ldapUtils;
	}
	public void setLdapUtils(LdapUtils ldapUtils) {
		this.ldapUtils = ldapUtils;
	}
	public String getFilterAttribute() {
		return filterAttribute;
	}
	public void setFilterAttribute(String filterAttribute) {
		this.filterAttribute = filterAttribute;
	}

	public boolean isMapping() {
		return mapping;
	}

	public void setMapping(boolean mapping) {
		this.mapping = mapping;
	}

}


text:
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.java.psi.formatter.performance;

import com.intellij.application.options.CodeStyle;
import com.intellij.formatting.FormatterEx;
import com.intellij.formatting.FormatterImpl;
import com.intellij.formatting.FormattingModel;
import com.intellij.ide.highlighter.JavaFileType;
import com.intellij.java.psi.formatter.java.JavaFormatterTestCase;
import com.intellij.lang.LanguageFormatting;
import com.intellij.lang.java.JavaLanguage;
import com.intellij.openapi.application.ex.PathManagerEx;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.PsiFile;
import com.intellij.psi.codeStyle.CodeStyleSettings;
import com.intellij.psi.codeStyle.CommonCodeStyleSettings;
import com.intellij.psi.impl.source.SourceTreeToPsiMap;
import com.intellij.testFramework.PlatformTestUtil;

import java.io.File;
import java.nio.charset.StandardCharsets;

import static com.intellij.psi.SyntaxTraverser.astTraverser;

/**
 * @author Maxim.Mossienko
 */
public class JavaFormatterPerformanceTest extends JavaFormatterTestCase {
  private static final String BASE_PATH = "psi/formatter/java";

  @Override
  protected String getBasePath() {
    return BASE_PATH;
  }

  public void testPerformance1() throws Exception {
    File testFile = new File(PathManagerEx.getTestDataPath(), BASE_PATH + "/performance.java");
    String text = StringUtil.convertLineSeparators(FileUtil.loadFile(testFile, StandardCharsets.UTF_8));
    PsiFile file = createFile(testFile.getName(), text);
    astTraverser(SourceTreeToPsiMap.psiElementToTree(file)).forEach(node -> {});

    CodeStyleSettings settings = CodeStyle.createTestSettings();
    FormatterImpl formatter = (FormatterImpl)FormatterEx.getInstanceEx();
    CommonCodeStyleSettings.IndentOptions options = settings.getIndentOptions(JavaFileType.INSTANCE);

    PlatformTestUtil.startPerformanceTest("Java Formatting [1]", 5000, () -> {
      FormattingModel model = LanguageFormatting.INSTANCE.forContext(file).createModel(file, settings);
      formatter.formatWithoutModifications(model.getDocumentModel(), model.getRootBlock(), settings, options, file.getTextRange());
    }).assertTiming();
  }

  public void testPerformance2() {
    getSettings().setDefaultRightMargin(120);
    PlatformTestUtil.startPerformanceTest("Java Formatting [2]", 8000, () -> doTest()).assertTiming();
  }

  public void testPerformance3() {
    CommonCodeStyleSettings settings = getSettings(JavaLanguage.INSTANCE);
    settings.RIGHT_MARGIN = 80;
    settings.METHOD_PARAMETERS_WRAP = 1;
    settings.SPACE_BEFORE_METHOD_PARENTHESES = true;
    settings.SPACE_BEFORE_METHOD_CALL_PARENTHESES = true;
    settings.ALIGN_MULTILINE_PARAMETERS = false;
    CommonCodeStyleSettings.IndentOptions indentOptions = settings.getRootSettings().getIndentOptions(JavaFileType.INSTANCE);
    indentOptions.USE_TAB_CHARACTER = true;
    indentOptions.TAB_SIZE = 4;

    PlatformTestUtil.startPerformanceTest("Java Formatting [3]", 3000, () -> doTest()).assertTiming();
  }

  @Override
  protected boolean doCheckDocumentUpdate() {
    return true;
  }
}


text:
package dev.ant04x.pruebatecnicateralco.configurations;

import dev.ant04x.pruebatecnicateralco.controllers.interceptors.Logger;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

@Configuration
public class InterceptorsConfig extends WebMvcConfigurationSupport {

    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new Logger(1)).addPathPatterns("/price/**");
        registry.addInterceptor(new Logger(2)).addPathPatterns("/cars/**");
        super.addInterceptors(registry);
    }
}


text:
package com.cjmalloy.torrentfs.editor.ui.swing.skin;

import javax.swing.ImageIcon;

public class IconBundle {
  private static IconBundle instance = null;

  public final ImageIcon exportIcon = new ImageIcon(IconBundle.class.getResource("icons/document-save.png"));
  public final ImageIcon openIcon = new ImageIcon(IconBundle.class.getResource("icons/document-open.png"));

  public final ImageIcon treeClosedFolderIcon = new ImageIcon(IconBundle.class.getResource("icons/tree/folder.png"));
  public final ImageIcon treeOpenFolderIcon = new ImageIcon(IconBundle.class.getResource("icons/tree/folder-open.png"));
  public final ImageIcon treeRootIcon = new ImageIcon(IconBundle.class.getResource("icons/tree/user-home.png"));
  public final ImageIcon treeNestedIcon = new ImageIcon(IconBundle.class.getResource("icons/tree/emblem-symbolic-link.png"));
  public final ImageIcon treeTfsIcon = new ImageIcon(IconBundle.class.getResource("icons/tree/package-x-generic.png"));
  public final ImageIcon treeReadOnlyIcon = new ImageIcon(IconBundle.class.getResource("icons/tree/emblem-readonly.png"));
  public final ImageIcon treeFileDefaultIcon = new ImageIcon(IconBundle.class.getResource("icons/tree/text-x-generic.png"));
  public final ImageIcon treeFileImageIcon = new ImageIcon(IconBundle.class.getResource("icons/tree/image-x-generic.png"));
  public final ImageIcon treeFileAudioIcon = new ImageIcon(IconBundle.class.getResource("icons/tree/audio-x-generic.png"));
  public final ImageIcon treeFileVideoIcon = new ImageIcon(IconBundle.class.getResource("icons/tree/video-x-generic.png"));
  public final ImageIcon treeFileExecIcon = new ImageIcon(IconBundle.class.getResource("icons/tree/application-x-executable.png"));
  public final ImageIcon treeFileHtmlIcon = new ImageIcon(IconBundle.class.getResource("icons/tree/text-html.png"));
  public final ImageIcon treeFileScriptIcon = new ImageIcon(IconBundle.class.getResource("icons/tree/text-x-script.png"));

  private IconBundle() {
  }

  public static IconBundle get() {
    if (instance == null) {
      instance = new IconBundle();
    }
    return instance;
  }
}


text:
package dev.wilix.ldap.facade.groovy;

/**
 * Runtime wrapper for exceptions, thrown during Groovy class loading.
 */
public class GroovyClassLoadException extends RuntimeException {
    public GroovyClassLoadException() {
    }

    public GroovyClassLoadException(String message) {
        super(message);
    }

    public GroovyClassLoadException(String message, Throwable cause) {
        super(message, cause);
    }

    public GroovyClassLoadException(Throwable cause) {
        super(cause);
    }
}


text:
package net.minecraft.entity.monster;

import com.google.common.base.Predicate;
import javax.annotation.Nullable;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.SharedMonsterAttributes;
import net.minecraft.entity.ai.EntityAIAttackMelee;
import net.minecraft.entity.ai.EntityAIDefendVillage;
import net.minecraft.entity.ai.EntityAIHurtByTarget;
import net.minecraft.entity.ai.EntityAILookAtVillager;
import net.minecraft.entity.ai.EntityAILookIdle;
import net.minecraft.entity.ai.EntityAIMoveThroughVillage;
import net.minecraft.entity.ai.EntityAIMoveTowardsRestriction;
import net.minecraft.entity.ai.EntityAIMoveTowardsTarget;
import net.minecraft.entity.ai.EntityAINearestAttackableTarget;
import net.minecraft.entity.ai.EntityAIWanderAvoidWater;
import net.minecraft.entity.ai.EntityAIWatchClosest;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.SoundEvents;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.datasync.DataParameter;
import net.minecraft.network.datasync.DataSerializers;
import net.minecraft.network.datasync.EntityDataManager;
import net.minecraft.util.DamageSource;
import net.minecraft.util.EnumParticleTypes;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.SoundEvent;
import net.minecraft.util.datafix.DataFixer;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.MathHelper;
import net.minecraft.village.Village;
import net.minecraft.world.World;
import net.minecraft.world.storage.loot.LootTableList;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;

public class EntityIronGolem extends EntityGolem
{
    protected static final DataParameter<Byte> PLAYER_CREATED = EntityDataManager.<Byte>createKey(EntityIronGolem.class, DataSerializers.BYTE);
    /** deincrements, and a distance-to-home check is done at 0 */
    private int homeCheckTimer;
    @Nullable
    Village village;
    private int attackTimer;
    private int holdRoseTick;

    public EntityIronGolem(World worldIn)
    {
        super(worldIn);
        this.setSize(1.4F, 2.7F);
    }

    protected void initEntityAI()
    {
        this.tasks.addTask(1, new EntityAIAttackMelee(this, 1.0D, true));
        this.tasks.addTask(2, new EntityAIMoveTowardsTarget(this, 0.9D, 32.0F));
        this.tasks.addTask(3, new EntityAIMoveThroughVillage(this, 0.6D, true));
        this.tasks.addTask(4, new EntityAIMoveTowardsRestriction(this, 1.0D));
        this.tasks.addTask(5, new EntityAILookAtVillager(this));
        this.tasks.addTask(6, new EntityAIWanderAvoidWater(this, 0.6D));
        this.tasks.addTask(7, new EntityAIWatchClosest(this, EntityPlayer.class, 6.0F));
        this.tasks.addTask(8, new EntityAILookIdle(this));
        this.targetTasks.addTask(1, new EntityAIDefendVillage(this));
        this.targetTasks.addTask(2, new EntityAIHurtByTarget(this, false, new Class[0]));
        this.targetTasks.addTask(3, new EntityAINearestAttackableTarget(this, EntityLiving.class, 10, false, true, new Predicate<EntityLiving>()
        {
            public boolean apply(@Nullable EntityLiving p_apply_1_)
            {
                return p_apply_1_ != null && IMob.VISIBLE_MOB_SELECTOR.apply(p_apply_1_) && !(p_apply_1_ instanceof EntityCreeper);
            }
        }));
    }

    protected void entityInit()
    {
        super.entityInit();
        this.dataManager.register(PLAYER_CREATED, Byte.valueOf((byte)0));
    }

    protected void updateAITasks()
    {
        if (--this.homeCheckTimer <= 0)
        {
            this.homeCheckTimer = 70 + this.rand.nextInt(50);
            this.village = this.world.getVillageCollection().getNearestVillage(new BlockPos(this), 32);

            if (this.village == null)
            {
                this.detachHome();
            }
            else
            {
                BlockPos blockpos = this.village.getCenter();
                this.setHomePosAndDistance(blockpos, (int)((float)this.village.getVillageRadius() * 0.6F));
            }
        }

        super.updateAITasks();
    }

    protected void applyEntityAttributes()
    {
        super.applyEntityAttributes();
        this.getEntityAttribute(SharedMonsterAttributes.MAX_HEALTH).setBaseValue(100.0D);
        this.getEntityAttribute(SharedMonsterAttributes.MOVEMENT_SPEED).setBaseValue(0.25D);
        this.getEntityAttribute(SharedMonsterAttributes.KNOCKBACK_RESISTANCE).setBaseValue(1.0D);
    }

    /**
     * Decrements the entity's air supply when underwater
     */
    protected int decreaseAirSupply(int air)
    {
        return air;
    }

    protected void collideWithEntity(Entity entityIn)
    {
        if (entityIn instanceof IMob && !(entityIn instanceof EntityCreeper) && this.getRNG().nextInt(20) == 0)
        {
            this.setAttackTarget((EntityLivingBase)entityIn);
        }

        super.collideWithEntity(entityIn);
    }

    /**
     * Called frequently so the entity can update its state every tick as required. For example, zombies and skeletons
     * use this to react to sunlight and start to burn.
     */
    public void onLivingUpdate()
    {
        super.onLivingUpdate();

        if (this.attackTimer > 0)
        {
            --this.attackTimer;
        }

        if (this.holdRoseTick > 0)
        {
            --this.holdRoseTick;
        }

        if (this.motionX * this.motionX + this.motionZ * this.motionZ > 2.500000277905201E-7D && this.rand.nextInt(5) == 0)
        {
            int i = MathHelper.floor(this.posX);
            int j = MathHelper.floor(this.posY - 0.20000000298023224D);
            int k = MathHelper.floor(this.posZ);
            IBlockState iblockstate = this.world.getBlockState(new BlockPos(i, j, k));

            if (iblockstate.getMaterial() != Material.AIR)
            {
                this.world.spawnParticle(EnumParticleTypes.BLOCK_CRACK, this.posX + ((double)this.rand.nextFloat() - 0.5D) * (double)this.width, this.getEntityBoundingBox().minY + 0.1D, this.posZ + ((double)this.rand.nextFloat() - 0.5D) * (double)this.width, 4.0D * ((double)this.rand.nextFloat() - 0.5D), 0.5D, ((double)this.rand.nextFloat() - 0.5D) * 4.0D, Block.getStateId(iblockstate));
            }
        }
    }

    /**
     * Returns true if this entity can attack entities of the specified class.
     */
    public boolean canAttackClass(Class <? extends EntityLivingBase > cls)
    {
        if (this.isPlayerCreated() && EntityPlayer.class.isAssignableFrom(cls))
        {
            return false;
        }
        else
        {
            return cls == EntityCreeper.class ? false : super.canAttackClass(cls);
        }
    }

    public static void registerFixesIronGolem(DataFixer fixer)
    {
        EntityLiving.registerFixesMob(fixer, EntityIronGolem.class);
    }

    /**
     * (abstract) Protected helper method to write subclass entity data to NBT.
     */
    public void writeEntityToNBT(NBTTagCompound compound)
    {
        super.writeEntityToNBT(compound);
        compound.setBoolean("PlayerCreated", this.isPlayerCreated());
    }

    /**
     * (abstract) Protected helper method to read subclass entity data from NBT.
     */
    public void readEntityFromNBT(NBTTagCompound compound)
    {
        super.readEntityFromNBT(compound);
        this.setPlayerCreated(compound.getBoolean("PlayerCreated"));
    }

    public boolean attackEntityAsMob(Entity entityIn)
    {
        this.attackTimer = 10;
        this.world.setEntityState(this, (byte)4);
        boolean flag = entityIn.attackEntityFrom(DamageSource.causeMobDamage(this), (float)(7 + this.rand.nextInt(15)));

        if (flag)
        {
            entityIn.motionY += 0.4000000059604645D;
            this.applyEnchantments(this, entityIn);
        }

        this.playSound(SoundEvents.ENTITY_IRONGOLEM_ATTACK, 1.0F, 1.0F);
        return flag;
    }

    /**
     * Handler for {@link World#setEntityState}
     */
    @SideOnly(Side.CLIENT)
    public void handleStatusUpdate(byte id)
    {
        if (id == 4)
        {
            this.attackTimer = 10;
            this.playSound(SoundEvents.ENTITY_IRONGOLEM_ATTACK, 1.0F, 1.0F);
        }
        else if (id == 11)
        {
            this.holdRoseTick = 400;
        }
        else if (id == 34)
        {
            this.holdRoseTick = 0;
        }
        else
        {
            super.handleStatusUpdate(id);
        }
    }

    public Village getVillage()
    {
        return this.village;
    }

    @SideOnly(Side.CLIENT)
    public int getAttackTimer()
    {
        return this.attackTimer;
    }

    public void setHoldingRose(boolean p_70851_1_)
    {
        if (p_70851_1_)
        {
            this.holdRoseTick = 400;
            this.world.setEntityState(this, (byte)11);
        }
        else
        {
            this.holdRoseTick = 0;
            this.world.setEntityState(this, (byte)34);
        }
    }

    protected SoundEvent getHurtSound(DamageSource p_184601_1_)
    {
        return SoundEvents.ENTITY_IRONGOLEM_HURT;
    }

    protected SoundEvent getDeathSound()
    {
        return SoundEvents.ENTITY_IRONGOLEM_DEATH;
    }

    protected void playStepSound(BlockPos pos, Block blockIn)
    {
        this.playSound(SoundEvents.ENTITY_IRONGOLEM_STEP, 1.0F, 1.0F);
    }

    @Nullable
    protected ResourceLocation getLootTable()
    {
        return LootTableList.ENTITIES_IRON_GOLEM;
    }

    public int getHoldRoseTick()
    {
        return this.holdRoseTick;
    }

    public boolean isPlayerCreated()
    {
        return (((Byte)this.dataManager.get(PLAYER_CREATED)).byteValue() & 1) != 0;
    }

    public void setPlayerCreated(boolean playerCreated)
    {
        byte b0 = ((Byte)this.dataManager.get(PLAYER_CREATED)).byteValue();

        if (playerCreated)
        {
            this.dataManager.set(PLAYER_CREATED, Byte.valueOf((byte)(b0 | 1)));
        }
        else
        {
            this.dataManager.set(PLAYER_CREATED, Byte.valueOf((byte)(b0 & -2)));
        }
    }

    /**
     * Called when the mob's health reaches 0.
     */
    public void onDeath(DamageSource cause)
    {
        if (!this.isPlayerCreated() && this.attackingPlayer != null && this.village != null)
        {
            this.village.modifyPlayerReputation(this.attackingPlayer.getUniqueID(), -5);
        }

        super.onDeath(cause);
    }
}


text:
/*
 * Zed Attack Proxy (ZAP) and its related class files.
 *
 * ZAP is an HTTP/HTTPS proxy for assessing web application security.
 *
 * Copyright 2014 The ZAP Development Team
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.zaproxy.zap.extension.zest.dialogs;

import java.awt.Dimension;
import java.awt.Frame;
import org.mozilla.zest.core.v1.ZestClientElement;
import org.mozilla.zest.core.v1.ZestStatement;
import org.parosproxy.paros.Constant;
import org.zaproxy.zap.extension.script.ScriptNode;
import org.zaproxy.zap.extension.zest.ExtensionZest;
import org.zaproxy.zap.extension.zest.ZestScriptWrapper;

public class ZestClientElementClickDialog extends ZestClientElementDialog implements ZestDialog {

    private static final long serialVersionUID = 1L;

    public ZestClientElementClickDialog(ExtensionZest ext, Frame owner, Dimension dim) {
        super(ext, owner, "zest.dialog.clientElementClick.add.title", dim);
    }

    @Override
    public void init(
            ZestScriptWrapper script,
            ScriptNode parent,
            ScriptNode child,
            ZestStatement req,
            ZestClientElement client,
            boolean add) {
        super.init(script, parent, child, req, client, add);

        if (add) {
            this.setTitle(Constant.messages.getString("zest.dialog.clientElementClick.add.title"));
        } else {
            this.setTitle(Constant.messages.getString("zest.dialog.clientElementClick.edit.title"));
        }
    }

    @Override
    public void saveFields() {
        // Nothing extra to do
    }

    @Override
    public String validateFields() {
        // Nothing extra to do
        return super.validateFields();
    }
}


text:
package fr.free.nrw.commons.LocationPicker;

import android.app.Application;
import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.MutableLiveData;
import com.mapbox.mapboxsdk.camera.CameraPosition;
import org.jetbrains.annotations.NotNull;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import timber.log.Timber;

/**
 * Observes live camera position data
 */
public class LocationPickerViewModel extends AndroidViewModel implements Callback<CameraPosition> {

    /**
     * Wrapping CameraPosition with MutableLiveData
     */
    private final MutableLiveData<CameraPosition> result = new MutableLiveData<>();

    /**
     * Constructor for this class
     *
     * @param application Application
     */
    public LocationPickerViewModel(@NonNull final Application application) {
        super(application);
    }

    /**
     * Responses on camera position changing
     *
     * @param call     Call<CameraPosition>
     * @param response Response<CameraPosition>
     */
    @Override
    public void onResponse(final @NotNull Call<CameraPosition> call,
        final Response<CameraPosition> response) {
        if (response.body() == null) {
            result.setValue(null);
            return;
        }
        result.setValue(response.body());
    }

    @Override
    public void onFailure(final @NotNull Call<CameraPosition> call, final @NotNull Throwable t) {
        Timber.e(t);
    }

    /**
     * Gets live CameraPosition
     *
     * @return MutableLiveData<CameraPosition>
     */
    public MutableLiveData<CameraPosition> getResult() {
        return result;
    }

}


text:
package draconictransmutation.impl.capability;

import javax.annotation.Nonnull;

import draconictransmutation.api.capabilities.item.IItemEmcHolder;
import draconictransmutation.api.capabilities.tile.IEmcStorage.EmcAction;
import draconictransmutation.gameObjs.items.ItemPE;
import net.minecraft.item.ItemStack;

public final class EmcHolderItemDefaultImpl implements IItemEmcHolder {

	@Override
	public long insertEmc(@Nonnull ItemStack stack, long toInsert, EmcAction action) {
		if (toInsert < 0) {
			return extractEmc(stack, -toInsert, action);
		}
		long toAdd = Math.min(getNeededEmc(stack), toInsert);
		if (action.execute()) {
			ItemPE.addEmcToStack(stack, toAdd);
		}
		return toAdd;
	}

	@Override
	public long extractEmc(@Nonnull ItemStack stack, long toExtract, EmcAction action) {
		if (toExtract < 0) {
			return insertEmc(stack, -toExtract, action);
		}
		long storedEmc = getStoredEmc(stack);
		long toRemove = Math.min(storedEmc, toExtract);
		if (action.execute()) {
			ItemPE.setEmc(stack, storedEmc - toRemove);
		}
		return toRemove;
	}

	@Override
	public long getStoredEmc(@Nonnull ItemStack stack) {
		return ItemPE.getEmc(stack);
	}

	@Override
	public long getMaximumEmc(@Nonnull ItemStack stack) {
		return 1;
	}
}


text:
/*
 * The Alluxio Open Foundation licenses this work under the Apache License, version 2.0
 * (the "License"). You may not use this work except in compliance with the License, which is
 * available at www.apache.org/licenses/LICENSE-2.0
 *
 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied, as more fully set forth in the License.
 *
 * See the NOTICE file distributed with this work for information regarding copyright ownership.
 */

package alluxio.client.keyvalue;

import alluxio.AbstractClient;
import alluxio.Constants;
import alluxio.exception.AlluxioException;
import alluxio.thrift.AlluxioService;
import alluxio.thrift.AlluxioTException;
import alluxio.thrift.GetNextKeysTOptions;
import alluxio.thrift.GetSizeTOptions;
import alluxio.thrift.GetTOptions;
import alluxio.thrift.KeyValueWorkerClientService;
import alluxio.util.network.NetworkAddressUtils;
import alluxio.wire.WorkerNetAddress;

import org.apache.thrift.TException;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.List;

import javax.annotation.concurrent.ThreadSafe;

/**
 * Client for talking to a key-value worker server.
 *
 * Since {@link alluxio.thrift.KeyValueWorkerClientService.Client} is not thread safe, this class
 * has to guarantee thread safety.
 */
@ThreadSafe
public final class KeyValueWorkerClient extends AbstractClient {
  private KeyValueWorkerClientService.Client mClient = null;

  /**
   * Creates a {@link KeyValueWorkerClient}.
   *
   * @param workerNetAddress location of the worker to connect to
   */
  public KeyValueWorkerClient(WorkerNetAddress workerNetAddress) {
    super(null, NetworkAddressUtils.getRpcPortSocketAddress(workerNetAddress));
  }

  @Override
  protected AlluxioService.Client getClient() {
    return mClient;
  }

  @Override
  protected String getServiceName() {
    return Constants.KEY_VALUE_WORKER_CLIENT_SERVICE_NAME;
  }

  @Override
  protected long getServiceVersion() {
    return Constants.KEY_VALUE_WORKER_SERVICE_VERSION;
  }

  @Override
  protected void afterConnect() throws IOException {
    mClient = new KeyValueWorkerClientService.Client(mProtocol);
  }

  /**
   * Gets the value of a given {@code key} from a specific key-value block.
   *
   * @param blockId The id of the block
   * @param key the key to get the value for
   * @return ByteBuffer of value, or null if not found
   */
  public synchronized ByteBuffer get(final long blockId, final ByteBuffer key)
      throws IOException, AlluxioException {
    return retryRPC(() -> mClient.get(blockId, key, new GetTOptions()).bufferForData());
  }

  /**
   * Gets a batch of keys next to the current key in the partition.
   * <p>
   * If current key is null, it means get the initial batch of keys.
   * If there are no more next keys, an empty list is returned.
   *
   * @param blockId the id of the partition
   * @param key the current key
   * @param numKeys maximum number of next keys to fetch
   * @return the next batch of keys
   */
  public synchronized List<ByteBuffer> getNextKeys(final long blockId, final ByteBuffer key,
      final int numKeys) throws IOException, AlluxioException {
    return retryRPC(new RpcCallable<List<ByteBuffer>>() {
      @Override
      public List<ByteBuffer> call() throws AlluxioTException, TException {
        return mClient.getNextKeys(blockId, key, numKeys, new GetNextKeysTOptions()).getKeys();
      }
    });
  }

  /**
   * @param blockId the id of the partition
   * @return the number of key-value pairs in the partition
   */
  public synchronized int getSize(final long blockId) throws IOException, AlluxioException {
    return retryRPC(new RpcCallable<Integer>() {
      @Override
      public Integer call() throws AlluxioTException, TException {
        return mClient.getSize(blockId, new GetSizeTOptions()).getSize();
      }
    });
  }
}