text:
package com.anjlab.eclipse.tapestry5;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.jar.Manifest;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.IJarEntryResource;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.search.IJavaSearchConstants;

import com.anjlab.eclipse.tapestry5.DeclarationReference.NonJavaReference;
import com.anjlab.eclipse.tapestry5.DeclarationReference.ProjectSettingsReference;
import com.anjlab.eclipse.tapestry5.TapestryService.ServiceDefinition;
import com.anjlab.eclipse.tapestry5.internal.CaseInsensitiveMap;
import com.anjlab.eclipse.tapestry5.internal.Orderable;
import com.anjlab.eclipse.tapestry5.internal.Orderer;
import com.anjlab.eclipse.tapestry5.internal.SymbolExpansion;
import com.anjlab.eclipse.tapestry5.templates.ProjectSettings;
import com.anjlab.eclipse.tapestry5.templates.ProjectSettings.TapestryModuleSettings;
import com.anjlab.eclipse.tapestry5.templates.ProjectSettings.TapestryServiceSettings;
import com.anjlab.eclipse.tapestry5.watchdog.WebXmlReader.WebXml;

public class TapestryProject
{
    private IProject project;

    private String tapestryVersion;

    private boolean tapestryVersionResolved;

    private volatile List<TapestryModule> modules;

    public TapestryProject(IProject project)
    {
        this.project = project;
    }

    public IProject getProject()
    {
        return project;
    }

    private static final Pattern VERSION_MAJOR_MINOR_PATTERN = Pattern.compile("^\\d+\\.\\d+");

    public String getTapestryVersionMajorMinor()
    {
        String version = getTapestryVersion();

        if (StringUtils.isEmpty(version))
        {
            return null;
        }

        Matcher matcher = VERSION_MAJOR_MINOR_PATTERN.matcher(version);

        if (matcher.find())
        {
            return matcher.group();
        }

        return null;
    }

    public String getTapestryVersion()
    {
        if (tapestryVersionResolved)
        {
            //  May be null
            return tapestryVersion;
        }

        for (TapestryModule module : modules())
        {
            if (module.isTapestryCoreModule())
            {
                TapestryFile file = module.findClasspathFileCaseInsensitive(
                        "META-INF/gradle/org.apache.tapestry/tapestry-core/project.properties");

                if (file instanceof JarEntryFile)
                {
                    try
                    {
                        Properties properties = new Properties();
                        properties.load(((JarEntryFile) file).getJarEntry().getContents());
                        tapestryVersion = properties.getProperty("version");
                    }
                    catch (Exception e)
                    {
                        Activator.getDefault().logError("Error reading tapestry version string", e);
                    }
                }

                break;
            }
        }

        tapestryVersionResolved = true;

        return tapestryVersion;
    }

    public List<TapestryModule> modules()
    {
        if (modules == null)
        {
            initialize(new NullProgressMonitor());
        }

        return modules;
    }

    public void initialize(IProgressMonitor monitor)
    {
        findModules(monitor);

        // Now when we know tapestry version for this project,
        // try to locate correct version of project settings

        final ProjectSettings projectSettings = TapestryUtils.readProjectSettings(this);

        for (Entry<String, TapestryModuleSettings> moduleEntry : projectSettings.getTapestryModules().entrySet())
        {
            String moduleClassName = moduleEntry.getKey();

            TapestryModule module = addModule(monitor, modules, project, moduleClassName,
                    new ObjectCallback<TapestryModule, RuntimeException>()
                    {
                        @Override
                        public void callback(TapestryModule module)
                        {
                            module.addReference(new TapestryModuleReference(new NonJavaReference(module), true)
                            {
                                @Override
                                public String getLabel()
                                {
                                    return "via " + projectSettings.getReferenceLabel();
                                }
                            });
                        }
                    });

            if (module != null)
            {
                TapestryModuleSettings moduleSettings = moduleEntry.getValue();

                for (Entry<String, TapestryServiceSettings> serviceEntry : moduleSettings.getTapestryServices().entrySet())
                {
                    String serviceLabel = serviceEntry.getKey();
                    TapestryServiceSettings serviceSettings = serviceEntry.getValue();

                    if (StringUtils.isNotEmpty(serviceSettings.getDiscovery()))
                    {
                        //  Support just one discovery rule for now
                        if (serviceSettings.getDiscovery().equals("intf-impl-pattern"))
                        {
                            addServicesViaIntfImplPatternDiscovery(projectSettings, module, serviceLabel, serviceSettings, monitor);
                        }
                        else
                        {
                            Activator.getDefault().logWarning("Unsupported discovery '" + serviceSettings.getDiscovery());
                        }
                    }
                    else
                    {
                        //  Clone and add new service

                        ServiceDefinition definition = serviceSettings.clone();

                        String intfClass;
                        if (StringUtils.isEmpty(serviceSettings.getIntfClass()))
                        {
                            //  Treat serviceLabel as intfClass
                            intfClass = serviceLabel;
                        }
                        else
                        {
                            intfClass = serviceSettings.getIntfClass();
                        }

                        if (StringUtils.isEmpty(definition.getId()))
                        {
                            definition.setId(TapestryUtils.getSimpleName(intfClass));
                        }

                        definition.setIntfClass(intfClass);

                        addService(projectSettings, module, definition);
                    }
                }
            }
            else
            {
                Activator.getDefault().logWarning("Tapestry module '" + moduleClassName + "' not found");
            }
        }

        // TODO Tapestry 5.4: Register javascriptModules as contributions to ModuleManager?

        findSymbols(monitor, projectSettings);

        markJavaScriptStackOverrides();
    }

    private void addServicesViaIntfImplPatternDiscovery(
            final ProjectSettings projectSettings,
            final TapestryModule module,
            final String serviceLabel,
            final TapestryServiceSettings serviceSettings,
            final IProgressMonitor monitor)
    {
        //  Note: This rule can only search between classes that are located
        //  in the same project/JAR as this module class

        if (StringUtils.isEmpty(serviceSettings.getIntfClass())
                || StringUtils.isEmpty(serviceSettings.getImplClass()))
        {
            Activator.getDefault().logError("Both intfClass and implClass must not be null with auto-discovery rule '"
                    + serviceSettings.getDiscovery()
                    + "' (" + projectSettings.getReferenceLabel()
                    + ", tapestryModule: " + module.getName()
                    + ", serviceLabel: " + serviceLabel
                    + ", intfClass: " + serviceSettings.getIntfClass()
                    + ", implClass: " + serviceSettings.getImplClass() + ")");
            return;
        }

        final Pattern intfPattern = Pattern.compile(serviceSettings.getIntfClass());

        module.enumJavaClassesRecursively(monitor, "", new ObjectCallback<Object, RuntimeException>()
        {
            @Override
            public void callback(Object obj) throws RuntimeException
            {
                String className;
                if (obj instanceof IFile)
                {
                    className = EclipseUtils.getClassName((IFile) obj);
                }
                else if (obj instanceof IClassFile)
                {
                    className = ((IClassFile) obj).getElementName();
                }
                else
                {
                    return;
                }

                Matcher matcher = intfPattern.matcher(className);

                if (matcher.find())
                {
                    ServiceDefinition definition = serviceSettings.clone();

                    String intfClass = className;
                    String implClass = matcher.replaceAll(definition.getImplClass());

                    //  Check if implClass actually exists
                    IType implClassType = EclipseUtils
                            .findTypeDeclaration(getProject(), IJavaSearchConstants.CLASS, implClass);

                    if (implClassType == null)
                    {
                        Activator.getDefault().logWarning(
                                "Implementation class '" + implClass
                                + "' not found for service interface '" + intfClass + "'");
                        return;
                    }

                    definition.setIntfClass(intfClass);
                    definition.setImplClass(implClass);

                    definition.setId(StringUtils.isEmpty(definition.getId())
                            ? TapestryUtils.getSimpleName(className)
                            : matcher.replaceAll(definition.getId()));

                    addService(projectSettings, module, definition);
                }
            }
        });
    }

    private void addService(ProjectSettings projectSettings, TapestryModule module, ServiceDefinition definition)
    {
        definition.resolveMarkers(module);

        TapestryService service = new TapestryService(
                module, definition, new ProjectSettingsReference(projectSettings));

        //  TODO Make sure to replace existing service that could be added via config previously
        //  (caching issue)
        module.addService(service);
    }

    private SymbolExpansion expansion;

    public String expandSymbols(String input) throws RuntimeException
    {
        if (expansion == null)
        {
            expansion = new SymbolExpansion(symbols());
        }

        return expansion.expandSymbols(input);
    }

    private Map<String, List<TapestrySymbol>> symbols;

    public Map<String, List<TapestrySymbol>> symbols()
    {
        if (symbols == null)
        {
            findSymbols(new NullProgressMonitor(), TapestryUtils.readProjectSettings(this));
        }

        return symbols;
    }

    private synchronized void findSymbols(IProgressMonitor monitor, ProjectSettings projectSettings)
    {
        if (symbols != null)
        {
            return;
        }

        final List<TapestryModule> modules = modules();

        monitor.beginTask("Resolving symbol providers", modules.size());

        final Orderer<TapestryService> orderer = new Orderer<TapestryService>();

        for (final TapestryModule module : modules)
        {
            monitor.subTask(module.getModuleClass().getFullyQualifiedName());

            List<Orderable<TapestryService>> symbolProviders = module.symbolProviders(monitor);

            for (Orderable<TapestryService> orderable : symbolProviders)
            {
                orderer.add(orderable);
            }

            monitor.worked(1);
        }

        final List<TapestryService> symbolProviders = orderer.getOrdered();

        monitor.beginTask("Resolving symbols", modules.size());

        final Map<TapestryService, List<TapestrySymbol>> providersToSymbols =
                new HashMap<TapestryService, List<TapestrySymbol>>();

        for (final TapestryModule module : modules)
        {
            monitor.subTask(module.getModuleClass().getFullyQualifiedName());

            module.buildProvidersToSymbolsMap(symbolProviders, monitor);

            for (final TapestryService symbolProvider : symbolProviders)
            {
                //  Values from the same provider may override each other

                List<TapestrySymbol> providerSymbols = module.symbolsFrom(symbolProvider, monitor);

                if (providerSymbols != null)
                {
                    for (int i = 0; i < providerSymbols.size(); i++)
                    {
                        TapestrySymbol symbol = providerSymbols.get(i);

                        for (int j = i + 1; j < providerSymbols.size(); j++)
                        {
                            TapestrySymbol other = providerSymbols.get(j);

                            if (StringUtils.equals(symbol.getName(), other.getName()))
                            {
                                if (other.isOverride())
                                {
                                    //  Clone symbol to keep cached version untouched
                                    symbol = symbol.clone();

                                    symbol.setOverridden(true);

                                    providerSymbols.set(i, symbol);
                                }
                            }
                        }
                    }

                    List<TapestrySymbol> symbols = providersToSymbols.get(symbolProvider);

                    if (symbols == null)
                    {
                        symbols = new ArrayList<TapestrySymbol>();
                        providersToSymbols.put(symbolProvider, symbols);
                    }

                    symbols.addAll(providerSymbols);
                }
            }

            monitor.worked(1);
        }

        // Override symbols using values from project settings

        Map<String, TapestryService> symbolProvidersLookup = new CaseInsensitiveMap<TapestryService>();

        for (TapestryService symbolProvider : symbolProviders)
        {
            symbolProvidersLookup.put(symbolProvider.getDefinition().getId(), symbolProvider);
        }

        for (Entry<String, Map<String, String>> additionalProviderSymbols : projectSettings.getSymbols().entrySet())
        {
            String providerName = additionalProviderSymbols.getKey();

            TapestryService symbolProvider = symbolProvidersLookup.get(providerName);

            if (symbolProvider == null)
            {
                Activator.getDefault().logWarning("Symbol provider '" + providerName + "' not found");
                continue;
            }

            List<TapestrySymbol> symbols = providersToSymbols.get(symbolProvider);

            if (symbols == null)
            {
                symbols = new ArrayList<TapestrySymbol>();
                providersToSymbols.put(symbolProvider, symbols);
            }

            Map<String, String> additionalSymbols = additionalProviderSymbols.getValue();

            for (Entry<String, String> symbolEntry : additionalSymbols.entrySet())
            {
                // Add to the top of the list to win during symbol expansion
                symbols.add(0,
                        new TapestrySymbol(
                                symbolEntry.getKey(),
                                symbolEntry.getValue(),
                                false,
                                new ProjectSettingsReference(projectSettings),
                                symbolProvider));
            }
        }

        symbols = new HashMap<String, List<TapestrySymbol>>();

        //  Symbol providers ordered by override rule,
        //  symbols in the first provider override values of the second,
        //  second overrides third, etc.

        for (TapestryService symbolProvider : symbolProviders)
        {
            List<TapestrySymbol> providerSymbols = providersToSymbols.get(symbolProvider);

            if (providerSymbols != null)
            {
                for (TapestrySymbol symbol : providerSymbols)
                {
                    List<TapestrySymbol> values = symbols.get(symbol.getName());

                    if (values == null)
                    {
                        values = new ArrayList<TapestrySymbol>();
                        symbols.put(symbol.getName(), values);
                    }
                    else
                    {
                        for (TapestrySymbol existing : values)
                        {
                            if (!existing.isOverridden()
                                    && !(existing.getReference() instanceof ProjectSettingsReference)
                                    //  Some modules may be added conditionally, like QA/DEV/Production
                                    //  we should treat them all as equal, they souldn't override each other,
                                    //  because usually only one of them enabled at run-time
                                    && !existing.getReference().getTapestryModule().isConditional())
                            {
                                //  Clone symbol to keep cached version untouched
                                symbol = symbol.clone();

                                symbol.setOverridden(true);
                                break;
                            }
                        }
                    }

                    values.add(symbol);
                }
            }
        }
    }

    public TapestryService findService(
            com.anjlab.eclipse.tapestry5.TapestryService.Matcher matcher)
    {
        for (TapestryModule module : modules())
        {
            for (TapestryService service : module.services())
            {
                if (matcher.matches(service))
                {
                    return service;
                }
            }
        }
        return null;
    }

    private void markJavaScriptStackOverrides()
    {
        Map<String, List<JavaScriptStack>> stacks = new HashMap<String, List<JavaScriptStack>>();

        for (TapestryModule module : modules())
        {
            for (JavaScriptStack stack : module.javaScriptStacks())
            {
                List<JavaScriptStack> configs = stacks.get(stack.getName());

                if (configs == null)
                {
                    configs = new ArrayList<JavaScriptStack>();
                    stacks.put(stack.getName(), configs);
                }

                configs.add(stack);
            }
        }

        for (String stackName : stacks.keySet())
        {
            List<JavaScriptStack> configs = stacks.get(stackName);

            boolean hasOverride = false;

            for (JavaScriptStack stack : configs)
            {
                if (stack.isOverride())
                {
                    hasOverride = true;
                }
            }

            if (hasOverride)
            {
                for (JavaScriptStack stack : configs)
                {
                    if (!stack.isOverride())
                    {
                        stack.setOverridden(true);
                    }
                }
            }
        }
    }

    private synchronized void findModules(IProgressMonitor monitor)
    {
        if (modules != null)
        {
            return;
        }

        modules = new ArrayList<TapestryModule>();

        String appPackage = TapestryUtils.getAppPackage(project);

        if (appPackage == null)
        {
            return;
        }

        final WebXml webXml = Activator.getDefault().getWebXml(project);

        if (webXml == null)
        {
            return;
        }

        for (String filterName : webXml.getFilterNames())
        {
            final String localFilterName = filterName;

            TapestryModule appModule = addModule(monitor, modules, project,
                    appPackage + ".services." + StringUtils.capitalize(filterName) + "Module",
                    new ObjectCallback<TapestryModule, RuntimeException>()
                    {
                        @Override
                        public void callback(TapestryModule module)
                        {
                            module.setAppModule(true);
                            module.addReference(new TapestryModuleReference(new NonJavaReference(module), false)
                            {
                                @Override
                                public String getLabel()
                                {
                                    return "Your Application's Module (via " + webXml.getFilterClassName(localFilterName) + " in web.xml)";
                                }
                            });
                        }
            });

            if (appModule != null)
            {
                break;
            }
        }

        for (String paramName : webXml.getParamNames())
        {
            if (paramName.matches("tapestry\\.[^-]+-modules"))
            {
                final String tapestryModeModules = paramName;

                String modeModules = webXml.getParamValue(tapestryModeModules);

                for (String moduleClassName : modeModules.split(","))
                {
                    addModule(monitor, modules, project, moduleClassName.trim(), new ObjectCallback<TapestryModule, RuntimeException>()
                    {
                        @Override
                        public void callback(TapestryModule obj)
                        {
                            obj.addReference(new TapestryModuleReference(new NonJavaReference(obj), true)
                            {
                                @Override
                                public String getLabel()
                                {
                                    return "via " + tapestryModeModules + " in web.xml";
                                }
                            });
                        }
                    });
                }
            }
        }

        // Handle new t5.4 TapestryModule class location
        ObjectCallback<TapestryModule, RuntimeException> coreObjectCallback = new ObjectCallback<TapestryModule, RuntimeException>()
        {
            @Override
            public void callback(TapestryModule module)
            {
                module.setTapestryCoreModule(true);
                module.addReference(new TapestryModuleReference(new NonJavaReference(module), false)
                {
                    @Override
                    public String getLabel()
                    {
                        final String version = TapestryProject.this.getTapestryVersion();

                        return "Tapestry Core Module" + (StringUtils.isEmpty(version) ? "" : " version " + version);
                    }
                });
            }
        };
        // T5.3
        addModule(monitor, modules, project, "org.apache.tapestry5.services.TapestryModule", coreObjectCallback);
        // T5.4
        addModule(monitor, modules, project, "org.apache.tapestry5.modules.TapestryModule", coreObjectCallback);

        final ObjectCallback<TapestryModule, RuntimeException> iocModuleCallback = new ObjectCallback<TapestryModule, RuntimeException>()
        {
            @Override
            public void callback(TapestryModule module)
            {
                module.addReference(new TapestryModuleReference(new NonJavaReference(module), false)
                {
                    @Override
                    public String getLabel()
                    {
                        return "Tapestry IoC Module";
                    }
                });
            }
        };

        //  T5.3
        addModule(monitor, modules, project, "org.apache.tapestry5.ioc.services.TapestryIOCModule", iocModuleCallback);
        //  T5.4
        addModule(monitor, modules, project, "org.apache.tapestry5.ioc.modules.TapestryIOCModule", iocModuleCallback);

        try
        {
            for (IPackageFragmentRoot root : JavaCore.create(project).getAllPackageFragmentRoots())
            {
                findModules(monitor, modules, root);
            }
        }
        catch (CoreException e)
        {
            Activator.getDefault().logError("Error searching tapestry modules", e);
        }
    }

    private void findModules(IProgressMonitor monitor, List<TapestryModule> modules, final IPackageFragmentRoot root)
            throws CoreException
    {
        monitor.subTask("Reading " + root.getElementName() + "...");

        for (Object obj : root.getNonJavaResources())
        {
            if (obj instanceof IJarEntryResource)
            {
                IJarEntryResource jarEntry = (IJarEntryResource) obj;

                if ("META-INF".equals(jarEntry.getName()))
                {
                    for (IJarEntryResource child : jarEntry.getChildren())
                    {
                        if ("MANIFEST.MF".equals(child.getName()))
                        {
                            InputStream contents = child.getContents();

                            try
                            {
                                Manifest manifest = new Manifest(contents);

                                String classes = manifest.getMainAttributes().getValue("Tapestry-Module-Classes");

                                if (classes != null)
                                {
                                    for (String className : classes.split(","))
                                    {
                                        addModule(monitor, modules, project, className,
                                                new ObjectCallback<TapestryModule, RuntimeException>()
                                                {
                                                    @Override
                                                    public void callback(TapestryModule obj)
                                                    {
                                                        obj.addReference(new TapestryModuleReference(new NonJavaReference(obj), false)
                                                        {
                                                            @Override
                                                            public String getLabel()
                                                            {
                                                                return "via " + root.getElementName() + "/META-INF/MANIFEST.MF";
                                                            }
                                                        });
                                                    }
                                                });
                                    }
                                }
                            }
                            catch (IOException e)
                            {
                                if (contents != null)
                                {
                                    try { contents.close(); } catch (IOException t)  { }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    private TapestryModule addModule(IProgressMonitor monitor, List<TapestryModule> modules,
            IProject project, String moduleClassName, ObjectCallback<TapestryModule, RuntimeException> moduleCreated)
    {
        if (monitor.isCanceled())
        {
            return null;
        }

        monitor.subTask("Locating " + moduleClassName + "...");

        IType moduleClass = EclipseUtils.findTypeDeclaration(
                project, IJavaSearchConstants.CLASS, moduleClassName);

        if (moduleClass == null)
        {
            return null;
        }

        TapestryModule module = Activator.getDefault()
                .getTapestryModuleFactory()
                .createTapestryModule(this, moduleClass, moduleCreated);

        addModule(monitor, modules, module, moduleCreated);

        return module;
    }

    private void addModule(IProgressMonitor monitor, List<TapestryModule> modules,
            TapestryModule module, ObjectCallback<TapestryModule, RuntimeException> moduleCreated)
    {
        if (monitor.isCanceled())
        {
            return;
        }

        int index = modules.indexOf(module);

        if (index != -1)
        {
            TapestryModule existingModule = modules.get(index);

            if (existingModule != module)
            {
                for (TapestryModuleReference reference : module.references())
                {
                    existingModule.addReference(reference);
                }
            }
            else
            {
                moduleCreated.callback(existingModule);
            }

            return;
        }

        module.initialize(monitor);

        modules.add(module);

        for (TapestryModule subModule :  module.subModules())
        {
            addModule(monitor, modules, subModule, moduleCreated);
        }
    }

    public boolean contains(IProject project)
    {
        for (TapestryModule module : modules())
        {
            if (project.equals(module.getModuleClass().getJavaProject().getProject()))
            {
                return true;
            }
        }
        return false;
    }

    public TapestryContext findComponentContext(String componentName) throws JavaModelException
    {
        String libraryPrefix = "";
        String componentNameWithoutPrefix = componentName;

        int index = componentName.indexOf('.');
        if (index < 0)
        {
            index = componentName.indexOf('/');
        }
        if (index >= 0)
        {
            libraryPrefix = componentName.substring(0, index);

            if (index + 1 >= componentName.length())
            {
                return null;
            }

            componentNameWithoutPrefix = componentName.substring(index + 1);
        }

        for (TapestryModule module : modules)
        {
            if (module.isAppModule())
            {
                TapestryContext context = findComponentContext(
                        module, TapestryUtils.getComponentsPackage(module.getEclipseProject()), componentName);

                if (context != null)
                {
                    return context;
                }
            }

            for (LibraryMapping mapping : module.libraryMappings())
            {
                if (libraryPrefix.equals(mapping.getPathPrefix()))
                {
                    TapestryContext context = findComponentContext(
                            module, mapping.getRootPackage() + ".components", componentNameWithoutPrefix);

                    if (context != null)
                    {
                        return context;
                    }
                }
            }
        }

        if ("".equals(libraryPrefix))
        {
            return findComponentContext("core/" + componentNameWithoutPrefix);
        }
        return null;
    }

    private TapestryContext findComponentContext(TapestryModule module, String appPackage, String componentNameWithoutPrefix)
    {
        //  subpackage.componentName
        String componentPath = getComponentPath(module, appPackage, componentNameWithoutPrefix);

        //  TODO Look in module.getComponents() instead? It's cached
        TapestryFile file = module.findClasspathFileCaseInsensitive(componentPath);

        if (file == null)
        {
            File parentFile = new File(componentPath).getParentFile();

            if (parentFile != null)
            {
                //  subpackage.componentNameSubpackage
                componentPath = getComponentPath(module, appPackage, componentNameWithoutPrefix + parentFile.getName());

                file = module.findClasspathFileCaseInsensitive(componentPath);

                if (file == null)
                {
                    //  subpackage.subpackageComponentName
                    componentPath = getComponentPath(module, appPackage, prepend(componentNameWithoutPrefix, parentFile.getName()));

                    file = module.findClasspathFileCaseInsensitive(componentPath);
                }
            }
        }

        return file != null ? file.getContext() : null;
    }

    private String prepend(String componentNameWithoutPrefix, String parentName)
    {
        StringBuilder builder = new StringBuilder(componentNameWithoutPrefix);
        int index = componentNameWithoutPrefix.lastIndexOf(".");
        return builder.insert(index + 1, parentName).toString();
    }

    protected String getComponentPath(TapestryModule module, String appPackage,
            String componentNameWithoutPrefix)
    {
        return TapestryUtils.joinPath(appPackage.replace('.', '/'),
                componentNameWithoutPrefix.replace('.', '/')
                    + (module instanceof LocalTapestryModule ? ".java" : ".class"));
    }

    public JavaScriptStack findStack(String stackName)
    {
        List<JavaScriptStack> stacks = new ArrayList<JavaScriptStack>();

        for (TapestryModule module : modules())
        {
            for (JavaScriptStack stack : module.javaScriptStacks())
            {
                if (stackName.equals(stack.getName()))
                {
                    stacks.add(stack);
                }
            }
        }

        //  Find first overridden stack (if any)
        for (JavaScriptStack stack : stacks)
        {
            if (stack.isOverride())
            {
                return stack;
            }
        }

        return stacks.isEmpty()
             ? null
             : stacks.get(0);
    }

    public LibraryMapping findLibraryMapping(String packageName)
    {
        List<LibraryMapping> mappings = new ArrayList<LibraryMapping>();

        for (TapestryModule module : modules())
        {
            for (LibraryMapping mapping : module.libraryMappings())
            {
                if (packageName.startsWith(mapping.getRootPackage()))
                {
                    mappings.add(mapping);
                }
            }
        }

        return mappings.size() > 0 ? mappings.get(0) : null;
    }
}


text:
#ifndef SYS_HELPER_H
#define SYS_HELPER_H

unsigned time_ms();

int arg_parse_freq(const char *str);

#endif /* SYS_HELPER_H */

redpajama_set_name: RedPajamaGithub


text:
include_recipe 'build-essential'

###############################################################################
# Clone our remote repository
###############################################################################
git node['libsodium']['src'] do
  repository node['libsodium']['src_url']
  revision node['libsodium']['version']
  action :sync
end

###############################################################################
# Execute *nix still compile workflow
###############################################################################
libsodium_builder 'libsodium compile and install'

###############################################################################
# Configure ourselves in the library cache
###############################################################################
template '/etc/ld.so.conf.d/libsodium.conf' do
  group 'root'
  mode '0444'
  owner 'root'
  notifies :run, 'execute[ldconfig]', :immediately
end

###############################################################################
# Update library cache
###############################################################################
execute 'ldconfig' do
  action :nothing
  command 'ldconfig'
end


text:
package com.intellij.execution.junit.codeInsight.references;

import com.intellij.patterns.InitialPatternCondition;
import com.intellij.patterns.PlatformPatterns;
import com.intellij.patterns.PsiElementPattern;
import com.intellij.patterns.PsiJavaElementPattern;
import com.intellij.psi.*;
import com.intellij.psi.filters.ElementFilter;
import com.intellij.psi.filters.position.FilterPattern;
import com.intellij.psi.impl.source.resolve.reference.impl.providers.FileReferenceSet;
import com.intellij.util.ObjectUtils;
import com.intellij.util.ProcessingContext;
import com.siyeh.ig.junit.JUnitCommonClassNames;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.uast.*;

final class JUnitReferenceContributor extends PsiReferenceContributor {
  private static PsiElementPattern.Capture<PsiLanguageInjectionHost> getElementPattern(String annotation, String paramName) {
    return PlatformPatterns.psiElement(PsiLanguageInjectionHost.class).and(new FilterPattern(new TestAnnotationFilter(annotation, paramName)));
  }

  private static PsiElementPattern.Capture<PsiLanguageInjectionHost> getEnumSourceNamesPattern() {
    return getElementPattern(JUnitCommonClassNames.ORG_JUNIT_JUPITER_PARAMS_ENUM_SOURCE, "names")
      .withAncestor(4, PlatformPatterns.psiElement(PsiAnnotation.class).and(new PsiJavaElementPattern<>(
        new InitialPatternCondition<>(PsiAnnotation.class) {
          @Override
          public boolean accepts(@Nullable Object o, ProcessingContext context) {
            if (o instanceof PsiAnnotation) {
              PsiAnnotationMemberValue mode = ((PsiAnnotation)o).findAttributeValue("mode");
              if (mode instanceof PsiReferenceExpression) {
                String referenceName = ((PsiReferenceExpression)mode).getReferenceName();
                return "INCLUDE".equals(referenceName) || "EXCLUDE".equals(referenceName);
              }
            }
            return false;
          }
        })));
  }

  @Override
  public void registerReferenceProviders(@NotNull PsiReferenceRegistrar registrar) {
    registrar.registerReferenceProvider(getElementPattern(JUnitCommonClassNames.ORG_JUNIT_JUPITER_PARAMS_PROVIDER_METHOD_SOURCE, "value"), new PsiReferenceProvider() {
      @Override
      public PsiReference @NotNull [] getReferencesByElement(@NotNull PsiElement element, @NotNull final ProcessingContext context) {
        return new MethodSourceReference[]{new MethodSourceReference((PsiLanguageInjectionHost)element)};
      }
    });
    registrar.registerReferenceProvider(getElementPattern(JUnitCommonClassNames.ORG_JUNIT_JUPITER_CONDITION_PROVIDER_ENABLED_IF, "value"), new PsiReferenceProvider() {
      @Override
      public PsiReference @NotNull [] getReferencesByElement(@NotNull PsiElement element, @NotNull final ProcessingContext context) {
        return new DisabledIfEnabledIfReference[]{new DisabledIfEnabledIfReference((PsiLanguageInjectionHost)element)};
      }
    });
    registrar.registerReferenceProvider(getElementPattern(JUnitCommonClassNames.ORG_JUNIT_JUPITER_CONDITION_PROVIDER_DISABLED_IF, "value"), new PsiReferenceProvider() {
      @Override
      public PsiReference @NotNull [] getReferencesByElement(@NotNull PsiElement element, @NotNull final ProcessingContext context) {
        return new DisabledIfEnabledIfReference[]{new DisabledIfEnabledIfReference((PsiLanguageInjectionHost)element)};
      }
    });
    registrar.registerReferenceProvider(getEnumSourceNamesPattern(), new PsiReferenceProvider() {
      @Override
      public PsiReference @NotNull [] getReferencesByElement(@NotNull PsiElement element, @NotNull final ProcessingContext context) {
        return new EnumSourceReference[] {new EnumSourceReference((PsiLiteral)element)};
      }
    });
    registrar.registerReferenceProvider(getElementPattern(JUnitCommonClassNames.ORG_JUNIT_JUPITER_PARAMS_PROVIDER_CSV_FILE_SOURCE, "resources"), new PsiReferenceProvider() {
      @Override
      public PsiReference @NotNull [] getReferencesByElement(@NotNull PsiElement element, @NotNull final ProcessingContext context) {
        return FileReferenceSet.createSet(element, false, false, false).getAllReferences();
      }
    });
  }

  private static class TestAnnotationFilter implements ElementFilter {

    private final String myAnnotation;
    private final String myParameterName;

    TestAnnotationFilter(String annotation, @NotNull @NonNls String parameterName) {
      myAnnotation = annotation;
      myParameterName = parameterName;
    }

    @Override
    public boolean isAcceptable(Object element, PsiElement context) {
      UElement type = UastContextKt.toUElement(context, UElement.class);
      if (type == null) return false;
      UAnnotation annotation = isCheapEnoughToSearch(type);
      if (annotation == null || !myAnnotation.equals(annotation.getQualifiedName())) return false;
      UNamedExpression uPair = UastUtils.getParentOfType(type, UNamedExpression.class);
      if (uPair == null) return false;
      String name = ObjectUtils.notNull(uPair.getName(), PsiAnnotation.DEFAULT_REFERENCED_METHOD_NAME);
      return myParameterName.equals(name);
    }

    private static UAnnotation isCheapEnoughToSearch(UElement element) {
      for (int i = 0; i < 5; i++) {
        if (element instanceof UDeclarationsExpression) {
          return null;
        }
        if (element instanceof UAnnotation) {
          return (UAnnotation)element;
        }
        UElement parent = element.getUastParent();
        if (parent == null) return null;
        element = parent;
      }
      return null;
    }

    @Override
    public boolean isClassAcceptable(Class hintClass) {
      return PsiLanguageInjectionHost.class.isAssignableFrom(hintClass);
    }
  }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
org.tp23.demo Class Hierarchy
</TITLE>

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style">

      Package
      Class
    Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Hierarchy For Package org.tp23.demo

Class Hierarchy

class java.lang.Object

class org.tp23.demo.Demonstration

      Package
      Class
    Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes


text:
<idea-plugin>
    <id>com.stylismo.nullability-annotations-inspection</id>
    <name>nullability-annotations-inspection</name>
    <vendor url="http://github.com/stylismo/nullability-annotations-inspection">stylismo</vendor>

    <description><![CDATA[

nullability-annotations-inspections

    Reports fields, parameters and return values of methods which do not have a nullability annotation,
    like @NotNull or @Nullable.[1]

    Quick fixes are presented to add one of the annotations to the elements with a problem.

    When your project uses 'default' annotations like @ParamsAreNonnulByDefault[1]
    by means of JSR305' javax.annotation.meta.TypeQualifierDefault,
    a quick fix will be presented to apply the annotation to the current package by adding the annotation to the
    package-info.java.
    If a package-info.java doesn't exist yet it will be created automatically.

    Only annotations registered with IntelliJ will be suggested in the quick fixes.
    Go to Preferences | Build | Compiler | Configure annotations ...
    to register your own.

    [1]: Any nullability annotation can be used, like JSR-305, JetBrains'
    or your own as long as you configure them in IDEA.

    ]]></description>

    <change-notes><![CDATA[

Changes in 0.0.10
 (2017-09-12)

    [#11]
    Support nullability annotations on type-parameter-typed declarations

    ]]></change-notes>

    <idea-version since-build="162"/>

    <extensions defaultExtensionNs="com.intellij">
        <localInspection language="JAVA"
                         level="WARNING"
                         enabledByDefault="true"
                         displayName="Missing @NotNull/@Nullable annotation"
                         groupName="Probable bugs"
                         groupPath="Java"
                         implementationClass="com.stylismo.intellij.inspection.NullabilityAnnotationsInspection"/>
    </extensions>

</idea-plugin>


text:
Create a convex hull for a given set of points. The convex hull is a polygon with shortest perimeter that encloses a set of points. As a visual analogy, consider a set of points as nails in a board. The convex hull of the points would be like a rubber band stretched around the outermost nails.

![Create a convex hull](convex-hull.png)

## Use case

A convex hull can be useful in collision detection. For example, when charting the position of two yacht fleets (with each vessel represented by a point), if their convex hulls have been precomputed, it is efficient to first check if their convex hulls intersect before computing their proximity point-by-point.

## How to use the sample

Tap on the map to add points. Tap the "Create" button to generate the convex hull of those points. Tap the "Reset" button to start over.

## How it works

1. Create an input geometry such as an `AGSMultipoint` object.
2. Use `class AGSGeometryEngine.convexHull(for:)` to create a new `AGSGeometry` object representing the convex hull of the input points. The returned geometry will either be a `AGSPoint`, `AGSPolyline`, or `AGSPolygon` based on the number of input points.

## Relevant API

* AGSGeometry
* AGSGeometryEngine

## Tags

convex hull, geometry, geometry engine, spatial analysis


text:
require "json"
require "pathname"

require "google/gax"
require "google/logging/v2/logging_pb"

module Google
  module Cloud
    module Logging
      module V2
        # Service for ingesting and querying logs.
        #
        # @!attribute [r] logging_service_v2_stub
        #   @return [Google::Logging::V2::LoggingServiceV2::Stub]
        class LoggingServiceV2Api
          attr_reader :logging_service_v2_stub

          # The default address of the service.
          SERVICE_ADDRESS = "logging.googleapis.com".freeze

          # The default port of the service.
          DEFAULT_SERVICE_PORT = 443

          CODE_GEN_NAME_VERSION = "gapic/0.1.0".freeze

          DEFAULT_TIMEOUT = 30

          PAGE_DESCRIPTORS = {
            "list_log_entries" => Google::Gax::PageDescriptor.new(
              "page_token",
              "next_page_token",
              "entries"),
            "list_monitored_resource_descriptors" => Google::Gax::PageDescriptor.new(
              "page_token",
              "next_page_token",
              "resource_descriptors")
          }.freeze

          private_constant :PAGE_DESCRIPTORS

          # The scopes needed to make gRPC calls to all of the methods defined in
          # this service.
          ALL_SCOPES = [
            "https://www.googleapis.com/auth/cloud-platform",
            "https://www.googleapis.com/auth/cloud-platform.read-only",
            "https://www.googleapis.com/auth/logging.admin",
            "https://www.googleapis.com/auth/logging.read",
            "https://www.googleapis.com/auth/logging.write"
          ].freeze

          PARENT_PATH_TEMPLATE = Google::Gax::PathTemplate.new(
            "projects/{project}"
          )

          private_constant :PARENT_PATH_TEMPLATE

          LOG_PATH_TEMPLATE = Google::Gax::PathTemplate.new(
            "projects/{project}/logs/{log}"
          )

          private_constant :LOG_PATH_TEMPLATE

          # Returns a fully-qualified parent resource name string.
          # @param project [String]
          # @return [String]
          def self.parent_path project
            PARENT_PATH_TEMPLATE.render(
              :"project" => project
            )
          end

          # Returns a fully-qualified log resource name string.
          # @param project [String]
          # @param log [String]
          # @return [String]
          def self.log_path project, log
            LOG_PATH_TEMPLATE.render(
              :"project" => project,
              :"log" => log
            )
          end

          # Parses the project from a parent resource.
          # @param parent_name [String]
          # @return [String]
          def self.match_project_from_parent_name parent_name
            PARENT_PATH_TEMPLATE.match(parent_name)["project"]
          end

          # Parses the project from a log resource.
          # @param log_name [String]
          # @return [String]
          def self.match_project_from_log_name log_name
            LOG_PATH_TEMPLATE.match(log_name)["project"]
          end

          # Parses the log from a log resource.
          # @param log_name [String]
          # @return [String]
          def self.match_log_from_log_name log_name
            LOG_PATH_TEMPLATE.match(log_name)["log"]
          end

          # @param service_path [String]
          #   The domain name of the API remote host.
          # @param port [Integer]
          #   The port on which to connect to the remote host.
          # @param channel [Channel]
          #   A Channel object through which to make calls.
          # @param chan_creds [Grpc::ChannelCredentials]
          #   A ChannelCredentials for the setting up the RPC client.
          # @param client_config[Hash]
          #   A Hash for call options for each method. See
          #   Google::Gax#construct_settings for the structure of
          #   this data. Falls back to the default config if not specified
          #   or the specified config is missing data points.
          # @param timeout [Numeric]
          #   The default timeout, in seconds, for calls made through this client.
          # @param app_name [String]
          #   The codename of the calling service.
          # @param app_version [String]
          #   The version of the calling service.
          def initialize \
              service_path: SERVICE_ADDRESS,
              port: DEFAULT_SERVICE_PORT,
              channel: nil,
              chan_creds: nil,
              scopes: ALL_SCOPES,
              client_config: {},
              timeout: DEFAULT_TIMEOUT,
              app_name: "gax",
              app_version: Google::Gax::VERSION
            # These require statements are intentionally placed here to initialize
            # the gRPC module only when it's required.
            # See https://github.com/googleapis/toolkit/issues/446
            require "google/gax/grpc"
            require "google/logging/v2/logging_services_pb"

            google_api_client = "#{app_name}/#{app_version} " \
              "#{CODE_GEN_NAME_VERSION} gax/#{Google::Gax::VERSION} " \
              "ruby/#{RUBY_VERSION}".freeze
            headers = { :"x-goog-api-client" => google_api_client }
            client_config_file = Pathname.new(__dir__).join(
              "logging_service_v2_client_config.json"
            )
            defaults = client_config_file.open do |f|
              Google::Gax.construct_settings(
                "google.logging.v2.LoggingServiceV2",
                JSON.parse(f.read),
                client_config,
                Google::Gax::Grpc::STATUS_CODE_NAMES,
                timeout,
                page_descriptors: PAGE_DESCRIPTORS,
                errors: Google::Gax::Grpc::API_ERRORS,
                kwargs: headers
              )
            end
            @logging_service_v2_stub = Google::Gax::Grpc.create_stub(
              service_path,
              port,
              chan_creds: chan_creds,
              channel: channel,
              scopes: scopes,
              &Google::Logging::V2::LoggingServiceV2::Stub.method(:new)
            )

            @delete_log = Google::Gax.create_api_call(
              @logging_service_v2_stub.method(:delete_log),
              defaults["delete_log"]
            )
            @write_log_entries = Google::Gax.create_api_call(
              @logging_service_v2_stub.method(:write_log_entries),
              defaults["write_log_entries"]
            )
            @list_log_entries = Google::Gax.create_api_call(
              @logging_service_v2_stub.method(:list_log_entries),
              defaults["list_log_entries"]
            )
            @list_monitored_resource_descriptors = Google::Gax.create_api_call(
              @logging_service_v2_stub.method(:list_monitored_resource_descriptors),
              defaults["list_monitored_resource_descriptors"]
            )
          end

          # Service calls

          # Deletes a log and all its log entries.
          # The log will reappear if it receives new entries.
          #
          # @param log_name [String]
          #   Required. The resource name of the log to delete.  Example:
          #   +"projects/my-project/logs/syslog"+.
          # @param options [Google::Gax::CallOptions]
          #   Overrides the default settings for this call, e.g, timeout,
          #   retries, etc.
          # @raise [Google::Gax::GaxError] if the RPC is aborted.
          # @example
          #   require "google/cloud/logging/v2/logging_service_v2_api"
          #
          #   LoggingServiceV2Api = Google::Cloud::Logging::V2::LoggingServiceV2Api
          #
          #   logging_service_v2_api = LoggingServiceV2Api.new
          #   formatted_log_name = LoggingServiceV2Api.log_path("[PROJECT]", "[LOG]")
          #   logging_service_v2_api.delete_log(formatted_log_name)

          def delete_log \
              log_name,
              options: nil
            req = Google::Logging::V2::DeleteLogRequest.new(
              log_name: log_name
            )
            @delete_log.call(req, options)
          end

          # Writes log entries to Stackdriver Logging.  All log entries are
          # written by this method.
          #
          # @param log_name [String]
          #   Optional. A default log resource name that is assigned to all log entries
          #   in +entries+ that do not specify a value for +log_name+.  Example:
          #   +"projects/my-project/logs/syslog"+.  See
          #   LogEntry.
          # @param resource [Google::Api::MonitoredResource]
          #   Optional. A default monitored resource object that is assigned to all log
          #   entries in +entries+ that do not specify a value for +resource+. Example:
          #
          #       { "type": "gce_instance",
          #         "labels": {
          #           "zone": "us-central1-a", "instance_id": "00000000000000000000" }}
          #
          #   See LogEntry.
          # @param labels [Hash{String => String}]
          #   Optional. Default labels that are added to the +labels+ field of all log
          #   entries in +entries+. If a log entry already has a label with the same key
          #   as a label in this parameter, then the log entry's label is not changed.
          #   See LogEntry.
          # @param entries [Array<Google::Logging::V2::LogEntry>]
          #   Required. The log entries to write. Values supplied for the fields
          #   +log_name+, +resource+, and +labels+ in this +entries.write+ request are
          #   added to those log entries that do not provide their own values for the
          #   fields.
          #
          #   To improve throughput and to avoid exceeding the
          #   {quota limit}[https://cloud.google.com/logging/quota-policy] for calls to +entries.write+,
          #   you should write multiple log entries at once rather than
          #   calling this method for each individual log entry.
          # @param partial_success [true, false]
          #   Optional. Whether valid entries should be written even if some other
          #   entries fail due to INVALID_ARGUMENT or PERMISSION_DENIED errors. If any
          #   entry is not written, the response status will be the error associated
          #   with one of the failed entries and include error details in the form of
          #   WriteLogEntriesPartialErrors.
          # @param options [Google::Gax::CallOptions]
          #   Overrides the default settings for this call, e.g, timeout,
          #   retries, etc.
          # @return [Google::Logging::V2::WriteLogEntriesResponse]
          # @raise [Google::Gax::GaxError] if the RPC is aborted.
          # @example
          #   require "google/cloud/logging/v2/logging_service_v2_api"
          #
          #   LoggingServiceV2Api = Google::Cloud::Logging::V2::LoggingServiceV2Api
          #
          #   logging_service_v2_api = LoggingServiceV2Api.new
          #   entries = []
          #   response = logging_service_v2_api.write_log_entries(entries)

          def write_log_entries \
              entries,
              log_name: nil,
              resource: nil,
              labels: nil,
              partial_success: nil,
              options: nil
            req = Google::Logging::V2::WriteLogEntriesRequest.new(
              entries: entries
            )
            req.log_name = log_name unless log_name.nil?
            req.resource = resource unless resource.nil?
            req.labels = labels unless labels.nil?
            req.partial_success = partial_success unless partial_success.nil?
            @write_log_entries.call(req, options)
          end

          # Lists log entries.  Use this method to retrieve log entries from Cloud
          # Logging.  For ways to export log entries, see
          # {Exporting Logs}[https://cloud.google.com/logging/docs/export].
          #
          # @param project_ids [Array<String>]
          #   Deprecated. One or more project identifiers or project numbers from which
          #   to retrieve log entries.  Examples: +"my-project-1A"+, +"1234567890"+. If
          #   present, these project identifiers are converted to resource format and
          #   added to the list of resources in +resourceNames+. Callers should use
          #   +resourceNames+ rather than this parameter.
          # @param resource_names [Array<String>]
          #   Optional. One or more cloud resources from which to retrieve log entries.
          #   Example: +"projects/my-project-1A"+, +"projects/1234567890"+.  Projects
          #   listed in +projectIds+ are added to this list.
          # @param filter [String]
          #   Optional. A filter that chooses which log entries to return.  See {Advanced
          #   Logs Filters}[https://cloud.google.com/logging/docs/view/advanced_filters].  Only log entries that
          #   match the filter are returned.  An empty filter matches all log entries.
          # @param order_by [String]
          #   Optional. How the results should be sorted.  Presently, the only permitted
          #   values are +"timestamp asc"+ (default) and +"timestamp desc"+. The first
          #   option returns entries in order of increasing values of
          #   +LogEntry.timestamp+ (oldest first), and the second option returns entries
          #   in order of decreasing timestamps (newest first).  Entries with equal
          #   timestamps are returned in order of +LogEntry.insertId+.
          # @param page_size [Integer]
          #   The maximum number of resources contained in the underlying API
          #   response. If page streaming is performed per-resource, this
          #   parameter does not affect the return value. If page streaming is
          #   performed per-page, this determines the maximum number of
          #   resources in a page.
          # @param options [Google::Gax::CallOptions]
          #   Overrides the default settings for this call, e.g, timeout,
          #   retries, etc.
          # @return [Google::Gax::PagedEnumerable<Google::Logging::V2::LogEntry>]
          #   An enumerable of Google::Logging::V2::LogEntry instances.
          #   See Google::Gax::PagedEnumerable documentation for other
          #   operations such as per-page iteration or access to the response
          #   object.
          # @raise [Google::Gax::GaxError] if the RPC is aborted.
          # @example
          #   require "google/cloud/logging/v2/logging_service_v2_api"
          #
          #   LoggingServiceV2Api = Google::Cloud::Logging::V2::LoggingServiceV2Api
          #
          #   logging_service_v2_api = LoggingServiceV2Api.new
          #   project_ids = []
          #
          #   # Iterate over all results.
          #   logging_service_v2_api.list_log_entries(project_ids).each do |element|
          #     # Process element.
          #   end
          #
          #   # Or iterate over results one page at a time.
          #   logging_service_v2_api.list_log_entries(project_ids).each_page do |page|
          #     # Process each page at a time.
          #     page.each do |element|
          #       # Process element.
          #     end
          #   end

          def list_log_entries \
              project_ids,
              resource_names: nil,
              filter: nil,
              order_by: nil,
              page_size: nil,
              options: nil
            req = Google::Logging::V2::ListLogEntriesRequest.new(
              project_ids: project_ids
            )
            req.resource_names = resource_names unless resource_names.nil?
            req.filter = filter unless filter.nil?
            req.order_by = order_by unless order_by.nil?
            req.page_size = page_size unless page_size.nil?
            @list_log_entries.call(req, options)
          end

          # Lists the monitored resource descriptors used by Stackdriver Logging.
          #
          # @param page_size [Integer]
          #   The maximum number of resources contained in the underlying API
          #   response. If page streaming is performed per-resource, this
          #   parameter does not affect the return value. If page streaming is
          #   performed per-page, this determines the maximum number of
          #   resources in a page.
          # @param options [Google::Gax::CallOptions]
          #   Overrides the default settings for this call, e.g, timeout,
          #   retries, etc.
          # @return [Google::Gax::PagedEnumerable<Google::Api::MonitoredResourceDescriptor>]
          #   An enumerable of Google::Api::MonitoredResourceDescriptor instances.
          #   See Google::Gax::PagedEnumerable documentation for other
          #   operations such as per-page iteration or access to the response
          #   object.
          # @raise [Google::Gax::GaxError] if the RPC is aborted.
          # @example
          #   require "google/cloud/logging/v2/logging_service_v2_api"
          #
          #   LoggingServiceV2Api = Google::Cloud::Logging::V2::LoggingServiceV2Api
          #
          #   logging_service_v2_api = LoggingServiceV2Api.new
          #
          #   # Iterate over all results.
          #   logging_service_v2_api.list_monitored_resource_descriptors.each do |element|
          #     # Process element.
          #   end
          #
          #   # Or iterate over results one page at a time.
          #   logging_service_v2_api.list_monitored_resource_descriptors.each_page do |page|
          #     # Process each page at a time.
          #     page.each do |element|
          #       # Process element.
          #     end
          #   end

          def list_monitored_resource_descriptors \
              page_size: nil,
              options: nil
            req = Google::Logging::V2::ListMonitoredResourceDescriptorsRequest.new
            req.page_size = page_size unless page_size.nil?
            @list_monitored_resource_descriptors.call(req, options)
          end
        end
      end
    end
  end
end


text:
title: TiDB 2.1.14 Release Notes
aliases: ['/docs/dev/releases/release-2.1.14/','/docs/dev/releases/2.1.14/']
---

# TiDB 2.1.14 Release Notes

Release date: July 04, 2019

TiDB version: 2.1.14

TiDB Ansible version: 2.1.14

## TiDB

- Fix wrong query results caused by column pruning in some cases [#11019](https://github.com/pingcap/tidb/pull/11019)
- Fix the wrongly displayed information in `db` and `info` columns of `show processlist` [#11000](https://github.com/pingcap/tidb/pull/11000)
- Fix the issue that `MAX_EXECUTION_TIME` as a SQL hint and global variable does not work in some cases [#10999](https://github.com/pingcap/tidb/pull/10999)
- Support automatically adjust the incremental gap allocated by auto-increment ID based on the load [#10997](https://github.com/pingcap/tidb/pull/10997)
- Fix the issue that the `Distsql` memory information of `MemTracker` is not correctly cleaned when a query ends [#10971](https://github.com/pingcap/tidb/pull/10971)
- Add the `MEM` column in the `information_schema.processlist` table to describe the memory usage of a query [#10896](https://github.com/pingcap/tidb/pull/10896)
- Add the `max_execution_time` global system variable to control the maximum execution time of a query [#10940](https://github.com/pingcap/tidb/pull/10940)
- Fix the panic caused by using unsupported aggregate functions [#10911](https://github.com/pingcap/tidb/pull/10911)
- Add an automatic rollback feature for the last transaction when the `load data` statement fails [#10862](https://github.com/pingcap/tidb/pull/10862)
- Fix the issue that TiDB returns a wrong result in some cases when the `OOMAction` configuration item is set to `Cancel` [#11016](https://github.com/pingcap/tidb/pull/11016)
- Disable the `TRACE` statement to avoid the TiDB panic issue [#11039](https://github.com/pingcap/tidb/pull/11039)
- Add the `mysql.expr_pushdown_blacklist` system table that dynamically enables/disables pushing down specific functions to Coprocessor [#10998](https://github.com/pingcap/tidb/pull/10998)
- Fix the issue that the `ANY_VALUE` function does not work in the `ONLY_FULL_GROUP_BY` mode [#10994](https://github.com/pingcap/tidb/pull/10994)
- Fix the incorrect evaluation caused by not doing a deep copy when evaluating the user variable of the string type [#11043](https://github.com/pingcap/tidb/pull/11043)

## TiKV

- Optimize processing the empty callback when processing the Raftstore message to avoid sending unnecessary message [#4682](https://github.com/tikv/tikv/pull/4682)

## PD

- Adjust the log output level from `Error` to `Warning` when reading an invalid configuration item [#1577](https://github.com/pingcap/pd/pull/1577)

## Tools

TiDB Binlog

- Reparo
    - Add the `safe-mode` configuration item, and support importing duplicated data after this item is enabled [#662](https://github.com/pingcap/tidb-binlog/pull/662)
- Pump
    - Add the `stop-write-at-available-space` configuration item to limit the available binlog space [#659](https://github.com/pingcap/tidb-binlog/pull/659)
    - Fix the issue that Garbage Collector does not work sometimes when the number of LevelDB L0 files is 0 [#648](https://github.com/pingcap/tidb-binlog/pull/648)
    - Optimize the algorithm of deleting log files to speed up releasing the space [#648](https://github.com/pingcap/tidb-binlog/pull/648)
- Drainer
    - Fix the failure to update `BIT` columns in the downstream [#655](https://github.com/pingcap/tidb-binlog/pull/655)

## TiDB Ansible

- Add the precheck feature for the `ansible` command and its `jmespath` and `jinja2` dependency packages [#807](https://github.com/pingcap/tidb-ansible/pull/807)
- Add the `stop-write-at-available-space` parameter (10 GiB by default) in Pump, and stop writing binlog files in Pump when the available disk space is less than the parameter value [#807](https://github.com/pingcap/tidb-ansible/pull/807)


text:
# inside a PowerShell script:
Invoke-RestMethod {{ ping_url }}


text:
namespace Mastersign.Bench.Dashboard
{
    partial class DownloadControl
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Component Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.lblFileName = new System.Windows.Forms.Label();
            this.lblReceived = new System.Windows.Forms.Label();
            this.progressBar = new System.Windows.Forms.ProgressBar();
            this.lblError = new System.Windows.Forms.Label();
            this.SuspendLayout();
            //
            // lblFileName
            //
            this.lblFileName.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
            | System.Windows.Forms.AnchorStyles.Right)));
            this.lblFileName.AutoEllipsis = true;
            this.lblFileName.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.lblFileName.Location = new System.Drawing.Point(2, 3);
            this.lblFileName.Margin = new System.Windows.Forms.Padding(0);
            this.lblFileName.Name = "lblFileName";
            this.lblFileName.Size = new System.Drawing.Size(324, 13);
            this.lblFileName.TabIndex = 0;
            this.lblFileName.Text = "<Dateiname>";
            //
            // lblReceived
            //
            this.lblReceived.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
            this.lblReceived.Location = new System.Drawing.Point(329, 3);
            this.lblReceived.Name = "lblReceived";
            this.lblReceived.Size = new System.Drawing.Size(100, 13);
            this.lblReceived.TabIndex = 1;
            this.lblReceived.Text = "0 KB";
            this.lblReceived.TextAlign = System.Drawing.ContentAlignment.TopRight;
            //
            // progressBar
            //
            this.progressBar.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
            | System.Windows.Forms.AnchorStyles.Right)));
            this.progressBar.Location = new System.Drawing.Point(3, 23);
            this.progressBar.Name = "progressBar";
            this.progressBar.Size = new System.Drawing.Size(425, 13);
            this.progressBar.Style = System.Windows.Forms.ProgressBarStyle.Continuous;
            this.progressBar.TabIndex = 2;
            //
            // lblError
            //
            this.lblError.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
            | System.Windows.Forms.AnchorStyles.Right)));
            this.lblError.AutoEllipsis = true;
            this.lblError.ForeColor = System.Drawing.SystemColors.ControlDarkDark;
            this.lblError.Location = new System.Drawing.Point(15, 23);
            this.lblError.Name = "lblError";
            this.lblError.Padding = new System.Windows.Forms.Padding(2, 0, 2, 0);
            this.lblError.Size = new System.Drawing.Size(410, 13);
            this.lblError.TabIndex = 3;
            this.lblError.Text = "Error Message";
            this.lblError.Visible = false;
            //
            // DownloadControl
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.Controls.Add(this.lblError);
            this.Controls.Add(this.progressBar);
            this.Controls.Add(this.lblFileName);
            this.Controls.Add(this.lblReceived);
            this.Name = "DownloadControl";
            this.Size = new System.Drawing.Size(431, 40);
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.Label lblFileName;
        private System.Windows.Forms.Label lblReceived;
        private System.Windows.Forms.ProgressBar progressBar;
        private System.Windows.Forms.Label lblError;
    }
}


text:
package api

import (
	runtime "k8s.io/apimachinery/pkg/runtime"
)

// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *ImageQualifyConfig) DeepCopyInto(out *ImageQualifyConfig) {
	*out = *in
	out.TypeMeta = in.TypeMeta
	if in.Rules != nil {
		in, out := &in.Rules, &out.Rules
		*out = make([]ImageQualifyRule, len(*in))
		copy(*out, *in)
	}
	return
}

// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ImageQualifyConfig.
func (in *ImageQualifyConfig) DeepCopy() *ImageQualifyConfig {
	if in == nil {
		return nil
	}
	out := new(ImageQualifyConfig)
	in.DeepCopyInto(out)
	return out
}

// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *ImageQualifyConfig) DeepCopyObject() runtime.Object {
	if c := in.DeepCopy(); c != nil {
		return c
	} else {
		return nil
	}
}

// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *ImageQualifyRule) DeepCopyInto(out *ImageQualifyRule) {
	*out = *in
	return
}

// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ImageQualifyRule.
func (in *ImageQualifyRule) DeepCopy() *ImageQualifyRule {
	if in == nil {
		return nil
	}
	out := new(ImageQualifyRule)
	in.DeepCopyInto(out)
	return out
}


text:
package com.mazebert.gateways.disk;

import com.mazebert.gateways.SubmittedGameStorageGateway;
import com.mazebert.plugins.system.mocks.LoggerMock;
import io.github.glytching.junit.extension.folder.TemporaryFolder;
import io.github.glytching.junit.extension.folder.TemporaryFolderExtension;
import org.apache.commons.io.IOUtils;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.jusecase.inject.ComponentTest;
import org.jusecase.inject.Trainer;

import java.io.IOException;
import java.io.PrintWriter;

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

@ExtendWith(TemporaryFolderExtension.class)
public class DiskSubmittedGameStorageGatewayIT implements ComponentTest {
    @Trainer
    LoggerMock logger;

    SubmittedGameStorageGateway gateway;

    @BeforeEach
    void setUp(TemporaryFolder temporaryFolder) {
        gateway = new DiskSubmittedGameStorageGateway(temporaryFolder.createDirectory("games").toPath());
    }

    @Test
    void roundtrip() throws Exception {
        String expected = "hello, i'm a game!";
        try (PrintWriter writer = new PrintWriter(gateway.openOutputStream("test.mbg"))) {
            writer.write(expected);
        }

        String actual = IOUtils.toString(gateway.openInputStream("test.mbg"));

        assertThat(actual).isEqualTo(expected);
    }

    @Test
    void delete() throws IOException {
        gateway.openOutputStream("test.mbg").write((byte)1);

        gateway.delete("test.mbg");

        Throwable throwable = catchThrowable(() -> gateway.openInputStream("test.mbg"));
        assertThat(throwable).hasMessage("Failed to open input stream to game: test.mbg");
    }
}


text:
/**
 * @file   TrajectoryAnalyzer.hpp
 * @author see AUTHORS
 * @brief  TrajectoryAnalyzer header file.
 */

#ifndef TRAJECTORYANALYZER_HPP
#define TRAJECTORYANALYZER_HPP

#include <memory>

#include <plog/Log.h>
#include <Eigen/Dense>

#include "Trajectory.hpp"
#include "ProteinSegment.hpp"
#include "ProteinSegmentEnsemble.hpp"

/*
* @class TrajectoryAnalyzer
*/
class TrajectoryAnalyzer {
public:
    /**
     * @param trajectory
     * @param protein_segments
     * @param temperature
     * @param ensemple_size
     */
    void analyze(Trajectory & trajectory,
                 std::vector<std::shared_ptr<ProteinSegment>> & protein_segments,
                 const double & temperature,
                 const int ensemble_size);

    /**
     * @param nma_covariance
     * @param protein_segments
     * @param temperature
     */
    void analyze(const Eigen::MatrixXd & nma_covariance,
                 std::vector<std::shared_ptr<ProteinSegment>> & protein_segments,
                 const double & temperature);

};

#endif

// vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.qing</groupId>
	<artifactId>rbac</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>rbac</name>
	<description>Demo project for Spring Boot</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.5.9.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
		<thymeleaf.version>3.0.7.RELEASE</thymeleaf.version>
		<thymeleaf-layout-dialect.version>2.2.2</thymeleaf-layout-dialect.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
			<scope>provided</scope>
			<optional>true</optional>
		</dependency>
		<!--添加thymeleaf的弱语法渲染-->
		<dependency>
			<groupId>net.sourceforge.nekohtml</groupId>
			<artifactId>nekohtml</artifactId>
			<version>1.9.22</version>
		</dependency>
		<!--shiro相关-->
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-spring</artifactId>
            <version>1.4.0</version>
        </dependency>
		<dependency>
			<groupId>com.github.theborakompanioni</groupId>
			<artifactId>thymeleaf-extras-shiro</artifactId>
			<version>1.2.1</version>
		</dependency>
		<dependency>
			<groupId>org.crazycake</groupId>
			<artifactId>shiro-redis</artifactId>
			<version>2.4.2.1-RELEASE</version>
		</dependency>
		<!--shiro结束-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
				<!--<dependencies>
					<dependency>
						<groupId>org.springframework</groupId>
						<artifactId>springloaded</artifactId>
						<version>1.2.8.RELEASE</version>
					</dependency>
				</dependencies>-->
                <configuration>
                    <fork>true</fork>
					<!--<mainClass>com.qing.rbac.RbacApplication</mainClass>-->
                </configuration>
			</plugin>
		</plugins>
	</build>

</project>


text:
<mat-card class="player-details-card">
  <mat-card-header>
    <mat-card-title>Player details</mat-card-title>
  </mat-card-header>
  <mat-card-content>
    <mat-list>
      <mat-divider *ngIf="arcadePersonalBest"></mat-divider>
      <mat-list-item *ngIf="arcadePersonalBest">

Arcade PB

{{ arcadePersonalBest | number }}

      </mat-list-item>

      <mat-divider *ngIf="mamePersonalBest"></mat-divider>
      <mat-list-item *ngIf="mamePersonalBest">

MAME PB

{{ mamePersonalBest | number }}

      </mat-list-item>

      <mat-divider *ngIf="firstKillscreenDate"></mat-divider>
      <mat-list-item *ngIf="firstKillscreenDate">

First KS Date

{{ firstKillscreenDate | date }}

      </mat-list-item>

      <mat-divider *ngIf="firstMillionDate"></mat-divider>
      <mat-list-item *ngIf="firstMillionDate">

First Million Date

{{ firstMillionDate | date }}

      </mat-list-item>
    </mat-list>
  </mat-card-content>
</mat-card>


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

    {% block head %}
<title>ForexApp</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<link rel="stylesheet"  type="text/css" href="../static/css/EliteCircle.css"/>

    {% endblock %}

ForexApp

calculate your risk

     {%if user%}

Hello, {{user}}. You can logout here

     {% else %}

          sign in | sign up
     {%endif%}

        User-Name:
 <input type="text" name="userName">

        Password:
 <input type="password"   name="password">

        Login
         Close

        {% block header %}
        {% endblock %}

       {% block main %}
       {% endblock %}

ForexApp©-All Rights Reserved 2015


text:
/**
 * @fileoverview Polyfills included for Emojityper on non-module browsers.
 */

import '../../node_modules/core-js/modules/es6.string.starts-with';
import '../../node_modules/core-js/modules/es6.string.from-code-point';
import '../../node_modules/core-js/modules/es6.array.from';
import '../../node_modules/core-js/modules/es6.promise';
import '../../node_modules/core-js/modules/es6.symbol';

// IE11 CustomEvent
if (typeof window.CustomEvent !== 'function') {
  function CustomEvent(name, params) {
    params = params || {bubbles: false, cancelable: false, detail: undefined};
    const event = document.createEvent('CustomEvent');
    event.initCustomEvent(name, params.bubbles, params.cancelable, params.detail);
    return event;
  }
  CustomEvent.prototype = window.Event.prototype;
  window.CustomEvent = CustomEvent;
}

// IE11 Element.remove
if (!Element.prototype.hasOwnProperty('remove')) {
  Object.defineProperty(Element.prototype, 'remove', {
    configurable: true,
    enumerable: true,
    writable: true,
    value: function remove() {
      this.parentNode && this.parentNode.removeChild(this);
    },
  });
}

// IE11 classList.toggle 2nd arg
const testEl = document.createElement('div');
testEl.classList.toggle('testClass', false);
if (testEl.classList.contains('testClass')) {
  const original = DOMTokenList.prototype.toggle;
  DOMTokenList.prototype.toggle = function(name, force) {
    if (force === undefined) {
      return original.call(this, name);
    } else if (force) {
      this.add(name);
    } else {
      this.remove(name);
    }
    return this.contains(name);
  };
}

// IE11 Element.matches / Element.closest
if (!Element.prototype.matches) {
  Element.prototype.matches = Element.prototype.msMatchesSelector || Element.prototype.webkitMatchesSelector;
}

if (!Element.prototype.closest) {
  Element.prototype.closest = function(s) {
    let el = this;
    if (!document.documentElement.contains(el)) {
      return null;
    }
    do {
      if (el.matches(s)) { return el; }
      el = el.parentElement || el.parentNode;
    } while (el && el.nodeType === 1);
    return null;
  };
}

// non-polyfill for window.fetch
if (!window.fetch) {
  window.fetch = () => Promise.reject('unsupported');
}

// for async/await magic
// nb. this puts regeneratorRuntime into the top-level scope
import '../../node_modules/regenerator-runtime/runtime.js';


text:
package bq.demo.collection;

import java.util.Stack;

/**
 * <b>  </b>
 *
 * <p>   </p>
 *
 * @author Jonathan Q. Bo (jonathan.q.bo@gmail.com)
 *
 * Created at Jun 12, 2015 7:55:55 PM
 *
 */
public class Solution {

	public static boolean isBalanced(String input){
		if(input == null || input.length() == 0)
			return true;

		char[] charArray = input.toCharArray();
		Stack<Character> stack = new Stack<>();
		for(int i = 0; i < charArray.length; i++){
			if(charArray[i] == '(' || charArray[i] == '['){
				stack.push(charArray[i]);
			}
			else if(charArray[i] == ')'){
				if(!stack.isEmpty() && stack.peek() == '(')
					stack.pop();
				else
					return false;
			}
			else if(charArray[i] == ']'){
				if(!stack.isEmpty() && stack.peek() == '[')
					stack.pop();
				else
					return false;
			}
		}

		if(stack.size() == 0)
			return true;
		else
			return false;
	}

	public static class LinkedListNode{
        int val;
        LinkedListNode next;

        LinkedListNode(int node_value) {
            val = node_value;
            next = null;
        }
    };

    public static LinkedListNode _insert_node_into_singlylinkedlist(LinkedListNode head, int val){
        if(head == null) {
            head = new LinkedListNode(val);
        }
        else {
            LinkedListNode end = head;
            while (end.next != null) {
                end = end.next;
            }
            LinkedListNode node = new LinkedListNode(val);
            end.next = node;
        }
        return head;
    }

    static LinkedListNode manipulateList(LinkedListNode root) {

    	if(root == null)
    		return null;

    	// find middle node
    	LinkedListNode node = root;
    	LinkedListNode middleNode = root;
    	while(node != null){
    		node = node.next;
    		middleNode = middleNode.next;
    		if(node != null){
    			node = node.next;
    		}
    	}

    	// merge two linkedlist
    	LinkedListNode newHead = null;
    	LinkedListNode list1 = root;
    	LinkedListNode list2 = middleNode;
    	while(list2 != null){
    		newHead = _insert_node_into_singlylinkedlist(newHead, list1.val);
    		newHead = _insert_node_into_singlylinkedlist(newHead, list2.val);

    		list1 = list1.next;
    		list2 = list2.next;
    	}

    	if(list1 != middleNode)
    		newHead = _insert_node_into_singlylinkedlist(newHead, list1.val);

    	return newHead;
    }

    public static void main(String[] args){
    	LinkedListNode head = null;
    	for(int i = 0; i < 3; i++)
    		head = _insert_node_into_singlylinkedlist(head, i);

    	LinkedListNode node = head;

    	LinkedListNode newlist = manipulateList(head);

    	while(newlist != null){
    		System.out.print(newlist.val + ",");
    		newlist = newlist.next;
    	}

//    	String str1 = "40[23(2([(])3)44]";
//    	System.out.println(isBalanced(str1));

    }
}


text:
let abstract_mapper, adapter_to_name, name_to_adapter, supports;
let path    = require('path');
let fs      = require('fs');
let glob    = require('glob');
let indx    = require('indx');
let resolve = require('resolve');
let semver  = require('semver');

exports.supports = (supports = function(name) {
  name = adapter_to_name(name);
  return !!glob.sync(`${path.join(__dirname, 'adapters', name)}`).length;
});

exports.load = function(name, custom_path, engine_name) {
  name = adapter_to_name(name);
  let engine_path = resolve_engine_path(name, custom_path);
  let version = get_version(engine_path);
  let adapter_name = match_version_to_adapter(name, version);

  if (!adapter_name) {
    throw new Error(`${name} version ${version} is not currently supported`);
  }

  return new (require(adapter_name))(engine_name, engine_path);
};

exports.all = () => indx(path.join(__dirname, 'adapters'));

// Responsible for mapping between adapters where the language name
// does not match the node module name. direction can be "left" or "right",
// "left" being lang name -> adapter name and right being the opposite.
exports.abstract_mapper = (abstract_mapper = function(name, direction) {
  let name_maps = [
    ['markdown', 'marked'],
    ['minify-js', 'uglify-js'],
    ['minify-css', 'clean-css'],
    ['minify-html', 'html-minifier'],
    ['mustache', 'hogan.js'],
    ['scss', 'node-sass'],
    ['haml', 'hamljs'],
    ['escape-html', 'he'],
    ['jsx', 'react-tools'],
    ['cjsx', 'coffee-react-transform'],
    ['babel', 'babel-core'],
    ['typescript', 'typescript']
  ];

  let res = null;
  name_maps.forEach(function(n) {
    if ((direction === 'left') && (n[0] === name)) { res = n[1]; }
    if ((direction === 'right') && (n[1] === name)) { return res = n[0]; }});

  return res || name;
});

exports.adapter_to_name = (adapter_to_name = name => abstract_mapper(name, 'right'));

exports.name_to_adapter = (name_to_adapter = name => abstract_mapper(name, 'left'));

var resolve_engine_path = function(name, custom_path) {
  let filepath = (custom_path != null) ?
    resolve.sync(name_to_adapter(name), {basedir: custom_path})
  :
    require.resolve(name_to_adapter(name));

  while (true) {
    if (filepath === '/') {
      throw new Error(`cannot resolve root of node module ${name}`);
    }
    filepath = path.dirname(filepath); // cut off the last part of the path
    if (fs.existsSync(path.join(filepath, 'package.json'))) {
      // if there's a package.json directly under it, we've found the root of
      // the module
      return filepath;
    }
  }
};

var get_version = function(engine_path) {
  try {
    return require(engine_path + '/package.json').version;
  } catch (err) {}
};

var match_version_to_adapter = function(name, version) {
  let adapters = fs.readdirSync(path.join(__dirname, 'adapters', name));
  for (let adapter of Array.from(adapters)) {
    adapter = adapter.replace(/\.(?:js|coffee)$/, '');
    if (semver.satisfies(version, adapter)) {
      return path.join(__dirname, 'adapters', name, adapter);
    }
  }
};


text:
int unblock_fd(int fd)
{
    int err, flag;

    flag = fcntl(fd, F_GETFL, 0);
    if(flag == -1) {
        ERROR("failed to retrieve file descriptor's flag: %s",
            strerror(errno));
        return err;
    }
    flag |= O_NONBLOCK;
    err = fcntl(fd, F_SETFL, flag);
    if(err) {
        ERROR("failed to set file descriptor's flag: %s",
            strerror(errno));
        return err;
    }
    return 0;
}

int add_epoll_sock(int epoll_fd, int sock_fd)
{
    struct epoll_event evt;
    int err;

    err = unblock_fd(sock_fd);
    if(err) {
        ERROR("unable to unblock file descriptor: %s", strerror(err));
        return err;
    }
    evt.data.fd = sock_fd;
    evt.events = EPOLLIN | EPOLLET;
    err = epoll_ctl(epoll_fd, EPOLL_CTL_ADD, sock_fd, &evt);
    if(err) {
        ERROR("epoll_ctl failed: %s", strerror(err));
        return err;
    }
    return 0;
}

int net_create(async_net_t **asnet, const char *port)
{
    INFO("creating async net interface...");

    struct addrinfo ai, *ret, *iter;
    int err, flag;

    memset(&ai, 0, sizeof(struct addrinfo));
    ai.ai_family = AF_UNSPEC;
    ai.ai_socktype = SOCK_STREAM;
    ai.ai_flags = AI_PASSIVE;

    err = getaddrinfo(NULL, port, &ai, &ret);
    if(err) {
        ERROR("getaddrinfo failed: %s", gai_strerror(err));
        return err;
    }

    int sock_fd = -1, epoll_fd = -1;
    for(iter = ret; iter != NULL; iter = iter->ai_next) {
        DEBUG("enumerating address...");
        sock_fd = socket(
            iter->ai_family, iter->ai_socktype, iter->ai_protocol);
        if(sock_fd == -1) {
            WARNING("failed to create socket: %s", strerror(errno));
            continue;
        }
        err = bind(sock_fd, iter->ai_addr, iter->ai_addrlen);
        if(!err)
            break;
        WARNING("failed to bind: %s", strerror(errno));
        close(sock_fd);
        sock_fd = -1;
    }
    freeaddrinfo(ret);

    if(sock_fd == -1) {
        ERROR("no proper socket available: ", strerror(errno));
        return err;
    }

    int enable = 1;
    setsockopt(sock_fd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int));

    err = unblock_fd(sock_fd);
    if(err) {
        ERROR("cannot unblock socket");
        return err;
    }

    err = listen(sock_fd, SOMAXCONN);
    if(err) {
        ERROR("unable to listen on server socket: %s", strerror(errno));
        return err;
    }

    epoll_fd = epoll_create1(0);
    if(epoll_fd == -1) {
        ERROR("failed to create epoll queue: %s", strerror(errno));
        return errno;
    }

    err = add_epoll_sock(epoll_fd, sock_fd);
    if(err) {
        ERROR("failed to add socket to epoll queue: %s", strerror(errno));
        return err;
    }

    *asnet = (async_net_t *)malloc(sizeof(async_net_t));
    if(!(*asnet)) {
        ERROR("insufficient memory");
        return ENOMEM;
    }

    (*asnet)->sock_fd = sock_fd;
    (*asnet)->epoll_fd = epoll_fd;
    (*asnet)->unrec_err = 0;
    (*asnet)->evt_group = (struct epoll_event *)
        malloc(MAX_EVENTS * sizeof(struct epoll_event));

    if(!(*asnet)->evt_group) {
        ERROR("insufficient memory");
        free(*asnet);
        return ENOMEM;
    }

    (*asnet)->server_sock_err_handler = default_server_sock_err_handler;
    (*asnet)->child_sock_err_handler = default_child_sock_err_handler;
    (*asnet)->sock_hup_handler = default_sock_hup_handler;
    (*asnet)->new_connection_handler = default_new_connection_handler;
    (*asnet)->data_received_handler = default_data_received_handler;

    INFO("async net interface created successfully");
    return 0;
}

void net_accept_connections(async_net_t *asnet)
{
    new_connection_info_t cinfo;
    int fd, err;

    DEBUG("accepting new connections...");
    do {
        cinfo.addr_len = sizeof(cinfo.in_addr);
        fd = accept(asnet->sock_fd, &(cinfo.in_addr), &(cinfo.addr_len));
        if(fd == -1) {
            if(errno == EAGAIN || errno == EWOULDBLOCK)
                return ;
            else {
                ERROR("exception occured when accepting new connections:"
                    " %s", strerror(errno));
                return ;
            }
        }

        err = unblock_fd(fd);
        if(err) {
            ERROR("failed to unblock socket, dropping connection");
            close(fd);
            continue;
        }

        err = add_epoll_sock(asnet->epoll_fd, fd);
        if(err) {
            ERROR("failed to add socket to epoll queue: %s", strerror(err));
            return ;
        }

        asnet->new_connection_handler(asnet, fd, &cinfo);
    } while(1);
}

void net_read_connection(async_net_t *asnet, int fd)
{
    data_received_info_t rxinfo;

    do {
        rxinfo.length = read(fd, rxinfo.buf, BUFFER_SIZE);
        if(rxinfo.length < 0) {
            if(errno == EAGAIN || errno == EWOULDBLOCK)
                return ;
            else {
                ERROR("exception occured when retrieving data:"
                    " %s", strerror(errno));
                close(fd);
                return ;
            }
        } else {
            asnet->data_received_handler(asnet, fd, &rxinfo);
            if(rxinfo.length == 0)
                return ;
        }
    } while(1);
}

int net_process(async_net_t *asnet, int timeout)
{
    DEBUG("processing epoll events...");

    if(asnet->unrec_err) {
        WARNING("processing request was denied due to previous"
            " unrecoverable error.");
        return -1;
    }

    int n = epoll_wait(asnet->epoll_fd, asnet->evt_group, MAX_EVENTS, timeout);
    if(n < 0) {
        ERROR("epoll error: ", strerror(errno));
        return errno;
    }
    DEBUG("%d events received", n);

    int i;
    for(i = 0; i < n; i++) {
        if(asnet->evt_group[i].events & EPOLLERR) {
            if(asnet->evt_group[i].data.fd == asnet->sock_fd) {
                asnet->server_sock_err_handler(
                    asnet, asnet->evt_group[i].data.fd, 0);
                close(asnet->evt_group[i].data.fd);
            } else {
                asnet->child_sock_err_handler(
                    asnet, asnet->evt_group[i].data.fd, 0);
                close(asnet->evt_group[i].data.fd);
            }
        } else if(asnet->evt_group[i].events & EPOLLHUP) {
            asnet->sock_hup_handler(asnet, asnet->evt_group[i].data.fd, 0);
            close(asnet->evt_group[i].data.fd);
        } else if(asnet->evt_group[i].events & EPOLLIN) {
            if(asnet->evt_group[i].data.fd == asnet->sock_fd) {
                net_accept_connections(asnet);
            } else {
                net_read_connection(asnet, asnet->evt_group[i].data.fd);
            }
        }
    }

    return 0;
}

void net_free(async_net_t **asnet)
{
    if(*asnet) {
        close((*asnet)->sock_fd);
        close((*asnet)->epoll_fd);
        free((*asnet)->evt_group);
        free(*asnet);
        *asnet = NULL;
    }
}