text:
package com.android.build.gradle.internal;

import static com.android.SdkConstants.DOT_JAR;
import static com.android.SdkConstants.EXT_ANDROID_PACKAGE;
import static com.android.SdkConstants.EXT_JAR;
import static com.android.builder.core.BuilderConstants.EXT_LIB_ARCHIVE;
import static com.android.builder.core.EvaluationErrorReporter.EvaluationMode.STANDARD;
import static com.android.builder.model.AndroidProject.FD_INTERMEDIATES;

import com.android.annotations.NonNull;
import com.android.annotations.Nullable;
import com.android.build.gradle.internal.dependency.JarInfo;
import com.android.build.gradle.internal.dependency.LibInfo;
import com.android.build.gradle.internal.dependency.LibraryDependencyImpl;
import com.android.build.gradle.internal.dependency.ManifestDependencyImpl;
import com.android.build.gradle.internal.dependency.VariantDependencies;
import com.android.build.gradle.internal.model.MavenCoordinatesImpl;
import com.android.build.gradle.internal.tasks.PrepareDependenciesTask;
import com.android.build.gradle.internal.tasks.PrepareLibraryTask;
import com.android.build.gradle.internal.variant.BaseVariantData;
import com.android.build.gradle.internal.variant.BaseVariantOutputData;
import com.android.builder.dependency.DependencyContainer;
import com.android.builder.dependency.JarDependency;
import com.android.builder.dependency.LibraryDependency;
import com.android.builder.model.MavenCoordinates;
import com.android.builder.model.SyncIssue;
import com.android.utils.ILogger;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;
import com.google.common.collect.Sets;

import org.gradle.api.Project;
import org.gradle.api.Task;
import org.gradle.api.UnknownProjectException;
import org.gradle.api.artifacts.Configuration;
import org.gradle.api.artifacts.Dependency;
import org.gradle.api.artifacts.ModuleVersionIdentifier;
import org.gradle.api.artifacts.ProjectDependency;
import org.gradle.api.artifacts.ResolvedArtifact;
import org.gradle.api.artifacts.SelfResolvingDependency;
import org.gradle.api.artifacts.component.ComponentIdentifier;
import org.gradle.api.artifacts.component.ComponentSelector;
import org.gradle.api.artifacts.component.ProjectComponentIdentifier;
import org.gradle.api.artifacts.result.DependencyResult;
import org.gradle.api.artifacts.result.ResolvedComponentResult;
import org.gradle.api.artifacts.result.ResolvedDependencyResult;
import org.gradle.api.artifacts.result.UnresolvedDependencyResult;
import org.gradle.api.logging.Logging;
import org.gradle.api.plugins.JavaBasePlugin;
import org.gradle.api.specs.Specs;
import org.gradle.util.GUtil;

import java.io.File;
import java.util.Collection;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;

/**
 * A manager to resolve configuration dependencies.
 */
public class DependencyManager {
    protected static final boolean DEBUG_DEPENDENCY = false;

    private Project project;
    private ExtraModelInfo extraModelInfo;
    private ILogger logger;

    final Map<LibraryDependencyImpl, PrepareLibraryTask> prepareTaskMap = Maps.newHashMap();

    public DependencyManager(Project project, ExtraModelInfo extraModelInfo) {
        this.project = project;
        this.extraModelInfo = extraModelInfo;
        logger = new LoggerWrapper(Logging.getLogger(DependencyManager.class));
    }

    /**
     * Returns the list of packaged local jars.
     */
    public static List<File> getPackagedLocalJarFileList(DependencyContainer dependencyContainer) {
        List<JarDependency> jarDependencyList = dependencyContainer.getLocalDependencies();
        Set<File> files = Sets.newHashSetWithExpectedSize(jarDependencyList.size());
        for (JarDependency jarDependency : jarDependencyList) {
            if (jarDependency.isPackaged()) {
                files.add(jarDependency.getJarFile());
            }
        }

        return Lists.newArrayList(files);
    }

    public void addDependencyToPrepareTask(
            @NonNull BaseVariantData<? extends BaseVariantOutputData> variantData,
            @NonNull PrepareDependenciesTask prepareDependenciesTask,
            @NonNull LibraryDependencyImpl lib) {
        PrepareLibraryTask prepareLibTask = prepareTaskMap.get(lib.getNonTransitiveRepresentation());
        if (prepareLibTask != null) {
            prepareDependenciesTask.dependsOn(prepareLibTask);
            prepareLibTask.dependsOn(variantData.preBuildTask);
        }

        for (LibraryDependency childLib : lib.getDependencies()) {
            addDependencyToPrepareTask(
                    variantData,
                    prepareDependenciesTask,
                    (LibraryDependencyImpl) childLib);
        }
    }

    public void resolveDependencies(
            @NonNull VariantDependencies variantDeps,
            @Nullable VariantDependencies testedVariantDeps,
            @Nullable String testedProjectPath) {
        Multimap<LibraryDependency, VariantDependencies> reverseMap = ArrayListMultimap.create();

        resolveDependencyForConfig(variantDeps, testedVariantDeps, testedProjectPath, reverseMap);
        processLibraries(variantDeps.getLibraries(), reverseMap);
    }

    private void processLibraries(
            @NonNull Collection<LibraryDependencyImpl> libraries,
            @NonNull Multimap<LibraryDependency, VariantDependencies> reverseMap) {
        for (LibraryDependencyImpl lib : libraries) {
            setupPrepareLibraryTask(lib, reverseMap);
            //noinspection unchecked
            processLibraries(
                    (Collection<LibraryDependencyImpl>) (List<?>) lib.getDependencies(),
                    reverseMap);
        }
    }

    private void setupPrepareLibraryTask(
            @NonNull LibraryDependencyImpl libDependency,
            @NonNull Multimap<LibraryDependency, VariantDependencies> reverseMap) {
        Task task = maybeCreatePrepareLibraryTask(libDependency, project);

        // Use the reverse map to find all the configurations that included this android
        // library so that we can make sure they are built.
        // TODO fix, this is not optimum as we bring in more dependencies than we should.
        Collection<VariantDependencies> configDepList = reverseMap.get(libDependency);
        if (configDepList != null && !configDepList.isEmpty()) {
            for (VariantDependencies configDependencies: configDepList) {
                task.dependsOn(configDependencies.getCompileConfiguration().getBuildDependencies());
            }
        }

        // check if this library is created by a parent (this is based on the
        // output file.
        // TODO Fix this as it's fragile
            /*
            This is a somewhat better way but it doesn't work in some project with
            weird setups...
            Project parentProject = DependenciesImpl.getProject(library.getBundle(), projects)
            if (parentProject != null) {
                String configName = library.getProjectVariant()
                if (configName == null) {
                    configName = "default"
                }

                prepareLibraryTask.dependsOn parentProject.getPath() + ":assemble${configName.capitalize()}"
            }
*/

    }

    /**
     * Handles the library and returns a task to "prepare" the library (ie unarchive it). The task
     * will be reused for all projects using the same library.
     *
     * @param library the library.
     * @param project the project
     * @return the prepare task.
     */
    private PrepareLibraryTask maybeCreatePrepareLibraryTask(
            @NonNull LibraryDependencyImpl library,
            @NonNull Project project) {

        // create proper key for the map. library here contains all the dependencies which
        // are not relevant for the task (since the task only extract the aar which does not
        // include the dependencies.
        // However there is a possible case of a rewritten dependencies (with resolution strategy)
        // where the aar here could have different dependencies, in which case we would still
        // need the same task.
        // So we extract a LibraryBundle (no dependencies) from the LibraryDependencyImpl to
        // make the map key that doesn't take into account the dependencies.
        LibraryDependencyImpl key = library.getNonTransitiveRepresentation();

        PrepareLibraryTask prepareLibraryTask = prepareTaskMap.get(key);

        if (prepareLibraryTask == null) {
            String bundleName = GUtil.toCamelCase(library.getName().replaceAll("\\:", " "));

            prepareLibraryTask = project.getTasks().create(
                    "prepare" + bundleName + "Library", PrepareLibraryTask.class);

            prepareLibraryTask.setDescription("Prepare " + library.getName());
            prepareLibraryTask.setBundle(library.getBundle());
            prepareLibraryTask.setExplodedDir(library.getBundleFolder());

            prepareTaskMap.put(key, prepareLibraryTask);
        }

        return prepareLibraryTask;
    }

    private void resolveDependencyForConfig(
            @NonNull VariantDependencies variantDeps,
            @Nullable VariantDependencies testedVariantDeps,
            @Nullable String testedProjectPath,
            @NonNull Multimap<LibraryDependency, VariantDependencies> reverseMap) {

        Configuration compileClasspath = variantDeps.getCompileConfiguration();
        Configuration packageClasspath = variantDeps.getPackageConfiguration();

        // TODO - shouldn't need to do this - fix this in Gradle
        ensureConfigured(compileClasspath);
        ensureConfigured(packageClasspath);

        if (DEBUG_DEPENDENCY) {
            System.out.println(">>>>>>>>>>");
            System.out.println(
                    project.getName() + ":" +
                            compileClasspath.getName() + "/" +
                            packageClasspath.getName());
        }

        Set<String> currentUnresolvedDependencies = Sets.newHashSet();

        // TODO - defer downloading until required -- This is hard to do as we need the info to build the variant config.
        Map<ModuleVersionIdentifier, List<ResolvedArtifact>> artifacts = Maps.newHashMap();
        collectArtifacts(compileClasspath, artifacts);
        collectArtifacts(packageClasspath, artifacts);

        // --- Handle the external/module dependencies ---
        // keep a map of modules already processed so that we don't go through sections of the
        // graph that have been seen elsewhere.
        Map<ModuleVersionIdentifier, List<LibInfo>> foundLibraries = Maps.newHashMap();
        Map<ModuleVersionIdentifier, List<JarInfo>> foundJars = Maps.newHashMap();

        // first get the compile dependencies. Note that in both case the libraries and the
        // jars are a graph. The list only contains the first level of dependencies, and
        // they themselves contain transitive dependencies (libraries can contain both, jars only
        // contains jars)
        List<LibInfo> compiledAndroidLibraries = Lists.newArrayList();
        List<JarInfo> compiledJars = Lists.newArrayList();

        Set<? extends DependencyResult> dependencyResultSet = compileClasspath.getIncoming()
                .getResolutionResult().getRoot().getDependencies();

        for (DependencyResult dependencyResult : dependencyResultSet) {
            if (dependencyResult instanceof ResolvedDependencyResult) {
                addDependency(
                        ((ResolvedDependencyResult) dependencyResult).getSelected(),
                        variantDeps,
                        compiledAndroidLibraries,
                        compiledJars,
                        foundLibraries,
                        foundJars,
                        artifacts,
                        reverseMap,
                        currentUnresolvedDependencies,
                        testedProjectPath,
                        0);
            } else if (dependencyResult instanceof UnresolvedDependencyResult) {
                ComponentSelector attempted = ((UnresolvedDependencyResult) dependencyResult).getAttempted();
                if (attempted != null) {
                    currentUnresolvedDependencies.add(attempted.toString());
                }
            }
        }

        // then the packaged ones.
        List<LibInfo> packagedAndroidLibraries = Lists.newArrayList();
        List<JarInfo> packagedJars = Lists.newArrayList();

        dependencyResultSet = packageClasspath.getIncoming()
                .getResolutionResult().getRoot().getDependencies();

        for (DependencyResult dependencyResult : dependencyResultSet) {
            if (dependencyResult instanceof ResolvedDependencyResult) {
                addDependency(
                        ((ResolvedDependencyResult) dependencyResult).getSelected(),
                        variantDeps,
                        packagedAndroidLibraries,
                        packagedJars,
                        foundLibraries,
                        foundJars,
                        artifacts,
                        reverseMap,
                        currentUnresolvedDependencies,
                        testedProjectPath,
                        0);
            } else if (dependencyResult instanceof UnresolvedDependencyResult) {
                ComponentSelector attempted = ((UnresolvedDependencyResult) dependencyResult)
                        .getAttempted();
                if (attempted != null) {
                    currentUnresolvedDependencies.add(attempted.toString());
                }
            }
        }

        // now look through both results.
        // 1. Handle the compile and package list of Libraries.
        // For Libraries:
        // Only library projects can support provided aar.
        // However, package(publish)-only are still not supported (they don't make sense).
        // For now, provided only dependencies will be kept normally in the compile-graph.
        // However we'll want to not include them in the resource merging.
        // For Applications:
        // All Android libraries must be in both lists.
        // ---
        // Since we reuse the same instance of LibInfo for identical modules
        // we can simply run through each list and look for libs that are in only one.
        // While the list of library is actually a graph, it's fine to look only at the
        // top level ones since the transitive ones are in the same scope as the direct libraries.
        List<LibInfo> copyOfPackagedLibs = Lists.newArrayList(packagedAndroidLibraries);
        boolean isLibrary = extraModelInfo.isLibrary();

        for (LibInfo lib : compiledAndroidLibraries) {
            if (!copyOfPackagedLibs.contains(lib)) {
                if (isLibrary || lib.isOptional()) {
                    lib.setIsOptional(true);
                } else {
                    //noinspection ConstantConditions
                    variantDeps.getChecker().addSyncIssue(extraModelInfo.handleSyncError(
                            lib.getResolvedCoordinates().toString(),
                            SyncIssue.TYPE_NON_JAR_PROVIDED_DEP,
                            String.format(
                                    "Project %s: provided dependencies can only be jars. %s is an Android Library.",
                                    project.getName(), lib.getResolvedCoordinates())));
                }
            } else {
                copyOfPackagedLibs.remove(lib);
            }
        }
        // at this stage copyOfPackagedLibs should be empty, if not, error.
        for (LibInfo lib : copyOfPackagedLibs) {
            //noinspection ConstantConditions
            variantDeps.getChecker().addSyncIssue(extraModelInfo.handleSyncError(
                    lib.getResolvedCoordinates().toString(),
                    SyncIssue.TYPE_NON_JAR_PACKAGE_DEP,
                    String.format(
                            "Project %s: apk dependencies can only be jars. %s is an Android Library.",
                            project.getName(), lib.getResolvedCoordinates())));
        }

        // 2. merge jar dependencies with a single list where items have packaged/compiled properties.
        // since we reuse the same instance of a JarInfo for identical modules, we can use an
        // Identity set (ie both compiledJars and packagedJars will contain the same instance
        // if it's both compiled and packaged)
        Set<JarInfo> jarInfoSet = Sets.newIdentityHashSet();

        // go through the graphs of dependencies (jars and libs) and gather all the transitive
        // jar dependencies.
        // At the same this we set the compiled/packaged properties.
        gatherJarDependencies(jarInfoSet, compiledJars, true /*compiled*/, false /*packaged*/);
        gatherJarDependencies(jarInfoSet, packagedJars, false /*compiled*/, true /*packaged*/);
        // at this step, we know that libraries have been checked and libraries can only
        // be in both compiled and packaged scope.
        gatherJarDependenciesFromLibraries(jarInfoSet, compiledAndroidLibraries);

        // the final list of JarDependency, created from the list of JarInfo.
        List<JarDependency> jars = Lists.newArrayListWithCapacity(jarInfoSet.size());

        // if this is a test dependencies (ie tested dependencies is non null), override
        // packaged attributes for jars that are already in the tested dependencies in order to
        // not package them twice (since the VM loads the classes of both APKs in the same
        // classpath and refuses to load the same class twice)
        if (testedVariantDeps != null) {
            List<JarDependency> jarDependencies = testedVariantDeps.getJarDependencies();

            // gather the tested dependencies
            Map<String, String> testedDeps = Maps.newHashMapWithExpectedSize(jarDependencies.size());

            for (JarDependency jar : jarDependencies) {
                if (jar.isPackaged()) {
                    MavenCoordinates coordinates = jar.getResolvedCoordinates();
                    //noinspection ConstantConditions
                    testedDeps.put(
                            computeVersionLessCoordinateKey(coordinates),
                            coordinates.getVersion());
                }
            }

            // now go through all the test dependencies and check we don't have the same thing.
            // Skip the ones that are already in the tested variant, and convert the rest
            // to the final immutable instance
            for (JarInfo jar : jarInfoSet) {
                if (jar.isPackaged()) {
                    MavenCoordinates coordinates = jar.getResolvedCoordinates();

                    String testedVersion = testedDeps.get(
                            computeVersionLessCoordinateKey(coordinates));
                    if (testedVersion != null) {
                        // same artifact, skip packaging of the dependency in the test app,
                        // whether the version is a match or not.

                        // if the dependency is present in both tested and test artifact,
                        // verify that they are the same version
                        if (!testedVersion.equals(coordinates.getVersion())) {
                            String artifactInfo =  coordinates.getGroupId() + ":" + coordinates.getArtifactId();
                            variantDeps.getChecker().addSyncIssue(extraModelInfo.handleSyncError(
                                    artifactInfo,
                                    SyncIssue.TYPE_MISMATCH_DEP,
                                    String.format(
                                            "Conflict with dependency '%s'. Resolved versions for app (%s) and test app (%s) differ.",
                                            artifactInfo,
                                            testedVersion,
                                            coordinates.getVersion())));

                        } else {
                            logger.info(String.format(
                                    "Removed '%s' from packaging of %s: Already in tested package.",
                                    coordinates,
                                    variantDeps.getName()));
                        }
                    } else {
                        // new artifact, convert it.
                        jars.add(jar.createJarDependency());
                    }
                }
            }
        } else {
            // just convert all of them to JarDependency
            for (JarInfo jarInfo : jarInfoSet) {
                jars.add(jarInfo.createJarDependency());
            }
        }

        // --- Handle the local jar dependencies ---

        // also need to process local jar files, as they are not processed by the
        // resolvedConfiguration result. This only includes the local jar files for this project.
        Set<File> localCompiledJars = Sets.newHashSet();
        for (Dependency dependency : compileClasspath.getAllDependencies()) {
            if (dependency instanceof SelfResolvingDependency &&
                    !(dependency instanceof ProjectDependency)) {
                Set<File> files = ((SelfResolvingDependency) dependency).resolve();
                for (File f : files) {
                    if (DEBUG_DEPENDENCY) {
                        System.out.println("LOCAL compile: " + f.getName());
                    }
                    // only accept local jar, no other types.
                    if (!f.getName().toLowerCase(Locale.getDefault()).endsWith(DOT_JAR)) {
                        variantDeps.getChecker().addSyncIssue(extraModelInfo.handleSyncError(
                                f.getAbsolutePath(),
                                SyncIssue.TYPE_NON_JAR_LOCAL_DEP,
                                String.format(
                                        "Project %s: Only Jar-type local dependencies are supported. Cannot handle: %s",
                                        project.getName(), f.getAbsolutePath())));
                    } else {
                        localCompiledJars.add(f);
                    }
                }
            }
        }

        Set<File> localPackagedJars = Sets.newHashSet();
        for (Dependency dependency : packageClasspath.getAllDependencies()) {
            if (dependency instanceof SelfResolvingDependency &&
                    !(dependency instanceof ProjectDependency)) {
                Set<File> files = ((SelfResolvingDependency) dependency).resolve();
                for (File f : files) {
                    if (DEBUG_DEPENDENCY) {
                        System.out.println("LOCAL package: " + f.getName());
                    }
                    // only accept local jar, no other types.
                    if (!f.getName().toLowerCase(Locale.getDefault()).endsWith(DOT_JAR)) {
                        variantDeps.getChecker().addSyncIssue(extraModelInfo.handleSyncError(
                                f.getAbsolutePath(),
                                SyncIssue.TYPE_NON_JAR_LOCAL_DEP,
                                String.format(
                                        "Project %s: Only Jar-type local dependencies are supported. Cannot handle: %s",
                                        project.getName(), f.getAbsolutePath())));
                    } else {
                        localPackagedJars.add(f);
                    }
                }
            }
        }

        // loop through both the compiled and packaged jar to compute the list
        // of jars that are: compile-only, package-only, or both.
        Map<File, JarDependency> localJars = Maps.newHashMap();
        for (File file : localCompiledJars) {
            localJars.put(file, new JarDependency(
                    file,
                    true /*compiled*/,
                    localPackagedJars.contains(file) /*packaged*/,
                    null /*resolvedCoordinates*/,
                    null /*projectPath*/));
        }

        for (File file : localPackagedJars) {
            if (!localCompiledJars.contains(file)) {
                localJars.put(file, new JarDependency(
                        file,
                        false /*compiled*/,
                        true /*packaged*/,
                        null /*resolvedCoordinates*/,
                        null /*projectPath*/));
            }
        }

        if (extraModelInfo.getMode() != STANDARD &&
                compileClasspath.getResolvedConfiguration().hasError()) {
            for (String dependency : currentUnresolvedDependencies) {
                extraModelInfo.handleSyncError(
                        dependency,
                        SyncIssue.TYPE_UNRESOLVED_DEPENDENCY,
                        String.format(
                                "Unable to resolve dependency '%s'",
                                dependency));
            }
        }

        // convert the LibInfo in LibraryDependencyImpl and update the reverseMap
        // with the converted keys
        List<LibraryDependencyImpl> libList = convertLibraryInfoIntoDependency(
                compiledAndroidLibraries, reverseMap);

        if (DEBUG_DEPENDENCY) {
            for (LibraryDependency lib : libList) {
                System.out.println("LIB: " + lib);
            }
            for (JarDependency jar : jars) {
                System.out.println("JAR: " + jar);
            }
            for (JarDependency jar : localJars.values()) {
                System.out.println("LOCAL-JAR: " + jar);
            }
        }

        variantDeps.addLibraries(libList);
        variantDeps.addJars(jars);
        variantDeps.addLocalJars(localJars.values());

        configureBuild(variantDeps);

        if (DEBUG_DEPENDENCY) {
            System.out.println(project.getName() + ":" + compileClasspath.getName() + "/" +packageClasspath.getName());
            System.out.println("<<<<<<<<<<");
        }

    }

    private static List<LibraryDependencyImpl> convertLibraryInfoIntoDependency(
            @NonNull List<LibInfo> libInfos,
            @NonNull Multimap<LibraryDependency, VariantDependencies> reverseMap) {
        List<LibraryDependencyImpl> list = Lists.newArrayListWithCapacity(libInfos.size());

        // since the LibInfos is a graph and the previous "foundLibraries" map ensure we reuse
        // instance where applicable, we'll create a map to keep track of what we have already
        // converted.
        Map<LibInfo, LibraryDependencyImpl> convertedMap = Maps.newIdentityHashMap();

        for (LibInfo libInfo : libInfos) {
            list.add(convertLibInfo(libInfo, reverseMap, convertedMap));
        }

        return list;
    }

    private static LibraryDependencyImpl convertLibInfo(
            @NonNull LibInfo libInfo,
            @NonNull Multimap<LibraryDependency, VariantDependencies> reverseMap,
            @NonNull Map<LibInfo, LibraryDependencyImpl> convertedMap) {
        LibraryDependencyImpl convertedLib = convertedMap.get(libInfo);
        if (convertedLib == null) {
            // first, convert the children.
            @SuppressWarnings("unchecked")
            List<LibInfo> children = (List<LibInfo>) (List<?>) libInfo.getDependencies();
            List<LibraryDependency> convertedChildren = Lists.newArrayListWithCapacity(children.size());

            for (LibInfo child : children) {
                convertedChildren.add(convertLibInfo(child, reverseMap, convertedMap));
            }

            // now convert the libInfo
            convertedLib = new LibraryDependencyImpl(
                    libInfo.getBundle(),
                    libInfo.getFolder(),
                    convertedChildren,
                    libInfo.getName(),
                    libInfo.getProjectVariant(),
                    libInfo.getProject(),
                    libInfo.getRequestedCoordinates(),
                    libInfo.getResolvedCoordinates(),
                    libInfo.isOptional());

            // add it to the map
            convertedMap.put(libInfo, convertedLib);

            // and update the reversemap
            // get the items associated with the libInfo. Put in a fresh list as the returned
            // collection is backed by the content of the map.
            Collection<VariantDependencies> values = Lists.newArrayList(reverseMap.get(libInfo));
            reverseMap.removeAll(libInfo);
            reverseMap.putAll(convertedLib, values);
        }

        return convertedLib;
    }

    private static void gatherJarDependencies(
            Set<JarInfo> outJarInfos,
            Collection<JarInfo> inJarInfos,
            boolean compiled,
            boolean packaged) {
        for (JarInfo jarInfo : inJarInfos) {
            if (!outJarInfos.contains(jarInfo)) {
                outJarInfos.add(jarInfo);
            }

            if (compiled) {
                jarInfo.setCompiled(true);
            }
            if (packaged) {
                jarInfo.setPackaged(true);
            }

            gatherJarDependencies(outJarInfos, jarInfo.getDependencies(), compiled, packaged);
        }
    }

    private static void gatherJarDependenciesFromLibraries(
            Set<JarInfo> outJarInfos,
            Collection<LibInfo> inLibraryDependencies) {
        for (LibInfo libInfo : inLibraryDependencies) {
            gatherJarDependencies(outJarInfos, libInfo.getJarDependencies(),
                    true, !libInfo.isOptional());

            gatherJarDependenciesFromLibraries(
                    outJarInfos,
                    libInfo.getLibInfoDependencies());
        }
    }

    private void ensureConfigured(Configuration config) {
        for (Dependency dependency : config.getAllDependencies()) {
            if (dependency instanceof ProjectDependency) {
                ProjectDependency projectDependency = (ProjectDependency) dependency;
                project.evaluationDependsOn(projectDependency.getDependencyProject().getPath());
                try {
                    ensureConfigured(projectDependency.getProjectConfiguration());
                } catch (Throwable e) {
                    throw new UnknownProjectException(String.format(
                            "Cannot evaluate module %s : %s",
                            projectDependency.getName(), e.getMessage()),
                            e);
                }
            }
        }
    }

    private void collectArtifacts(
            Configuration configuration,
            Map<ModuleVersionIdentifier,
                    List<ResolvedArtifact>> artifacts) {

        Set<ResolvedArtifact> allArtifacts;
        if (extraModelInfo.getMode() != STANDARD) {
            allArtifacts = configuration.getResolvedConfiguration().getLenientConfiguration().getArtifacts(
                    Specs.satisfyAll());
        } else {
            allArtifacts = configuration.getResolvedConfiguration().getResolvedArtifacts();
        }

        for (ResolvedArtifact artifact : allArtifacts) {
            ModuleVersionIdentifier id = artifact.getModuleVersion().getId();
            List<ResolvedArtifact> moduleArtifacts = artifacts.get(id);

            if (moduleArtifacts == null) {
                moduleArtifacts = Lists.newArrayList();
                artifacts.put(id, moduleArtifacts);
            }

            if (!moduleArtifacts.contains(artifact)) {
                moduleArtifacts.add(artifact);
            }
        }
    }

    private static void printIndent(int indent, @NonNull String message) {
        for (int i = 0 ; i < indent ; i++) {
            System.out.print("\t");
        }

        System.out.println(message);
    }

    private void addDependency(
            @NonNull ResolvedComponentResult resolvedComponentResult,
            @NonNull VariantDependencies configDependencies,
            @NonNull Collection<LibInfo> outLibraries,
            @NonNull List<JarInfo> outJars,
            @NonNull Map<ModuleVersionIdentifier, List<LibInfo>> alreadyFoundLibraries,
            @NonNull Map<ModuleVersionIdentifier, List<JarInfo>> alreadyFoundJars,
            @NonNull Map<ModuleVersionIdentifier, List<ResolvedArtifact>> artifacts,
            @NonNull Multimap<LibraryDependency, VariantDependencies> reverseMap,
            @NonNull Set<String> currentUnresolvedDependencies,
            @Nullable String testedProjectPath,
            int indent) {

        ModuleVersionIdentifier moduleVersion = resolvedComponentResult.getModuleVersion();
        if (configDependencies.getChecker().excluded(moduleVersion)) {
            return;
        }

        if (moduleVersion.getName().equals("support-annotations") &&
                moduleVersion.getGroup().equals("com.android.support")) {
            configDependencies.setAnnotationsPresent(true);
        }

        List<LibInfo> libsForThisModule = alreadyFoundLibraries.get(moduleVersion);
        List<JarInfo> jarsForThisModule = alreadyFoundJars.get(moduleVersion);

        if (libsForThisModule != null) {
            if (DEBUG_DEPENDENCY) {
                printIndent(indent, "FOUND LIB: " + moduleVersion.getName());
            }
            outLibraries.addAll(libsForThisModule);

            for (LibInfo lib : libsForThisModule) {
                reverseMap.put(lib, configDependencies);
            }

        } else if (jarsForThisModule != null) {
            if (DEBUG_DEPENDENCY) {
                printIndent(indent, "FOUND JAR: " + moduleVersion.getName());
            }
            outJars.addAll(jarsForThisModule);
        }
        else {
            if (DEBUG_DEPENDENCY) {
                printIndent(indent, "NOT FOUND: " + moduleVersion.getName());
            }
            // new module! Might be a jar or a library

            // get the nested components first.
            List<LibInfo> nestedLibraries = Lists.newArrayList();
            List<JarInfo> nestedJars = Lists.newArrayList();

            Set<? extends DependencyResult> dependencies = resolvedComponentResult.getDependencies();
            for (DependencyResult dependencyResult : dependencies) {
                if (dependencyResult instanceof ResolvedDependencyResult) {
                    addDependency(
                            ((ResolvedDependencyResult) dependencyResult).getSelected(),
                            configDependencies,
                            nestedLibraries,
                            nestedJars,
                            alreadyFoundLibraries,
                            alreadyFoundJars,
                            artifacts,
                            reverseMap,
                            currentUnresolvedDependencies,
                            testedProjectPath,
                            indent+1);
                } else if (dependencyResult instanceof UnresolvedDependencyResult) {
                    ComponentSelector attempted = ((UnresolvedDependencyResult) dependencyResult).getAttempted();
                    if (attempted != null) {
                        currentUnresolvedDependencies.add(attempted.toString());
                    }
                }
            }

            if (DEBUG_DEPENDENCY) {
                printIndent(indent, "BACK2: " + moduleVersion.getName());
                printIndent(indent, "NESTED LIBS: " + nestedLibraries.size());
                printIndent(indent, "NESTED JARS: " + nestedJars.size());
            }

            // now loop on all the artifact for this modules.
            List<ResolvedArtifact> moduleArtifacts = artifacts.get(moduleVersion);

            ComponentIdentifier id = resolvedComponentResult.getId();
            String gradlePath = (id instanceof ProjectComponentIdentifier) ?
                    ((ProjectComponentIdentifier) id).getProjectPath() : null;

            if (moduleArtifacts != null) {
                for (ResolvedArtifact artifact : moduleArtifacts) {
                    if (EXT_LIB_ARCHIVE.equals(artifact.getExtension())) {
                        if (DEBUG_DEPENDENCY) {
                            printIndent(indent, "TYPE: AAR");
                        }
                        if (libsForThisModule == null) {
                            libsForThisModule = Lists.newArrayList();
                            alreadyFoundLibraries.put(moduleVersion, libsForThisModule);
                        }

                        String path = computeArtifactPath(moduleVersion, artifact);
                        String name = computeArtifactName(moduleVersion, artifact);

                        if (DEBUG_DEPENDENCY) {
                            printIndent(indent, "NAME: " + name);
                            printIndent(indent, "PATH: " + path);
                        }

                        //def explodedDir = project.file("$project.rootProject.buildDir/${FD_INTERMEDIATES}/exploded-aar/$path")
                        File explodedDir = project.file(project.getBuildDir() + "/" + FD_INTERMEDIATES + "/exploded-aar/" + path);
                        @SuppressWarnings("unchecked")
                        LibInfo libInfo = new LibInfo(
                                artifact.getFile(),
                                explodedDir,
                                (List<LibraryDependency>) (List<?>) nestedLibraries,
                                nestedJars,
                                name,
                                artifact.getClassifier(),
                                gradlePath,
                                null /*requestedCoordinates*/,
                                new MavenCoordinatesImpl(artifact));

                        libsForThisModule.add(libInfo);
                        outLibraries.add(libInfo);
                        reverseMap.put(libInfo, configDependencies);

                    } else if (EXT_JAR.equals(artifact.getExtension())) {
                        if (DEBUG_DEPENDENCY) {
                            printIndent(indent, "TYPE: JAR");
                        }
                        // check this jar does not have a dependency on an library, as this would not work.
                        if (!nestedLibraries.isEmpty()) {
                            if (testedProjectPath != null && testedProjectPath.equals(gradlePath)) {
                                // TODO: make sure this is a direct dependency and not a transitive one.
                                // add nested libs as optional somehow...
                                for (LibInfo lib : nestedLibraries) {
                                    lib.setIsOptional(true);
                                }
                                outLibraries.addAll(nestedLibraries);

                            } else {
                                configDependencies.getChecker()
                                        .addSyncIssue(extraModelInfo.handleSyncError(
                                                new MavenCoordinatesImpl(artifact).toString(),
                                                SyncIssue.TYPE_JAR_DEPEND_ON_AAR,
                                                String.format(
                                                        "Module '%s' depends on one or more Android Libraries but is a jar",
                                                        moduleVersion)));
                            }
                        }

                        if (jarsForThisModule == null) {
                            jarsForThisModule = Lists.newArrayList();
                            alreadyFoundJars.put(moduleVersion, jarsForThisModule);
                        }

                        JarInfo jarInfo = new JarInfo(
                                artifact.getFile(),
                                new MavenCoordinatesImpl(artifact),
                                gradlePath,
                                nestedJars);
                        if (DEBUG_DEPENDENCY) {
                            printIndent(indent, "JAR-INFO: " + jarInfo.toString());
                        }

                        jarsForThisModule.add(jarInfo);
                        outJars.add(jarInfo);

                    } else if (EXT_ANDROID_PACKAGE.equals(artifact.getExtension())) {
                        String name = computeArtifactName(moduleVersion, artifact);

                        configDependencies.getChecker().addSyncIssue(extraModelInfo.handleSyncError(
                                name,
                                SyncIssue.TYPE_DEPENDENCY_IS_APK,
                                String.format(
                                        "Dependency %s on project %s resolves to an APK archive " +
                                        "which is not supported as a compilation dependency. File: %s",
                                        name, project.getName(), artifact.getFile())));
                    } else if ("apklib".equals(artifact.getExtension())) {
                        String name = computeArtifactName(moduleVersion, artifact);

                        configDependencies.getChecker().addSyncIssue(extraModelInfo.handleSyncError(
                                name,
                                SyncIssue.TYPE_DEPENDENCY_IS_APKLIB,
                                String.format(
                                        "Packaging for dependency %s is 'apklib' and is not supported. " +
                                        "Only 'aar' libraries are supported.", name)));
                    } else {
                        String name = computeArtifactName(moduleVersion, artifact);

                        logger.warning(String.format(
                                        "Unrecognized dependency: '%s' (type: '%s', extension: '%s')",
                                        name, artifact.getType(), artifact.getExtension()));
                    }
                }
            }

            if (DEBUG_DEPENDENCY) {
                printIndent(indent, "DONE: " + moduleVersion.getName());
            }
        }
    }

    @NonNull
    private String computeArtifactPath(
            @NonNull ModuleVersionIdentifier moduleVersion,
            @NonNull ResolvedArtifact artifact) {
        StringBuilder pathBuilder = new StringBuilder();

        pathBuilder.append(normalize(logger, moduleVersion, moduleVersion.getGroup()))
                .append('/')
                .append(normalize(logger, moduleVersion, moduleVersion.getName()))
                .append('/')
                .append(normalize(logger, moduleVersion,
                        moduleVersion.getVersion()));

        if (artifact.getClassifier() != null && !artifact.getClassifier().isEmpty()) {
            pathBuilder.append('/').append(normalize(logger, moduleVersion,
                    artifact.getClassifier()));
        }

        return pathBuilder.toString();
    }

    @NonNull
    private static String computeArtifactName(
            @NonNull ModuleVersionIdentifier moduleVersion,
            @NonNull ResolvedArtifact artifact) {
        StringBuilder nameBuilder = new StringBuilder();

        nameBuilder.append(moduleVersion.getGroup())
                .append(':')
                .append(moduleVersion.getName())
                .append(':')
                .append(moduleVersion.getVersion());

        if (artifact.getClassifier() != null && !artifact.getClassifier().isEmpty()) {
            nameBuilder.append(':').append(artifact.getClassifier());
        }

        return nameBuilder.toString();
    }

    /**
     * Normalize a path to remove all illegal characters for all supported operating systems.
     * {@see http://en.wikipedia.org/wiki/Filename#Comparison%5Fof%5Ffile%5Fname%5Flimitations}
     *
     * @param id the module coordinates that generated this path
     * @param path the proposed path name
     * @return the normalized path name
     */
    static String normalize(ILogger logger, ModuleVersionIdentifier id, String path) {
        if (path == null || path.isEmpty()) {
            logger.info(String.format(
                    "When unzipping library '%s:%s:%s, either group, name or version is empty",
                    id.getGroup(), id.getName(), id.getVersion()));
            return path;
        }
        // list of illegal characters
        String normalizedPath = path.replaceAll("[%<>:\"/?*\\\\]", "@");
        if (normalizedPath == null || normalizedPath.isEmpty()) {
            // if the path normalization failed, return the original path.
            logger.info(String.format(
                    "When unzipping library '%s:%s:%s, the normalized '%s' is empty",
                    id.getGroup(), id.getName(), id.getVersion(), path));
            return path;
        }
        try {
            int pathPointer = normalizedPath.length() - 1;
            // do not end your path with either a dot or a space.
            String suffix = "";
            while (pathPointer >= 0 && (normalizedPath.charAt(pathPointer) == '.'
                    || normalizedPath.charAt(pathPointer) == ' ')) {
                pathPointer--;
                suffix += "@";
            }
            if (pathPointer < 0) {
                throw new RuntimeException(String.format(
                        "When unzipping library '%s:%s:%s, " +
                        "the path '%s' cannot be transformed into a valid directory name",
                        id.getGroup(), id.getName(), id.getVersion(), path));
            }
            return normalizedPath.substring(0, pathPointer + 1) + suffix;
        } catch (Exception e) {
            logger.error(e, String.format(
                    "When unzipping library '%s:%s:%s', " +
                    "Path normalization failed for input %s",
                    id.getGroup(), id.getName(), id.getVersion(), path));
            return path;
        }
    }

    private void configureBuild(VariantDependencies configurationDependencies) {
        addDependsOnTaskInOtherProjects(
                project.getTasks().getByName(JavaBasePlugin.BUILD_NEEDED_TASK_NAME), true,
                JavaBasePlugin.BUILD_NEEDED_TASK_NAME, "compile");
        addDependsOnTaskInOtherProjects(
                project.getTasks().getByName(JavaBasePlugin.BUILD_DEPENDENTS_TASK_NAME), false,
                JavaBasePlugin.BUILD_DEPENDENTS_TASK_NAME, "compile");
    }

    @NonNull
    public static List<ManifestDependencyImpl> getManifestDependencies(
            List<LibraryDependency> libraries) {

        List<ManifestDependencyImpl> list = Lists.newArrayListWithCapacity(libraries.size());

        for (LibraryDependency lib : libraries) {
            // get the dependencies
            List<ManifestDependencyImpl> children = getManifestDependencies(lib.getDependencies());
            list.add(new ManifestDependencyImpl(lib.getName(), lib.getManifest(), children));
        }

        return list;
    }

    /**
     * Adds a dependency on tasks with the specified name in other projects.  The other projects
     * are determined from project lib dependencies using the specified configuration name.
     * These may be projects this project depends on or projects that depend on this project
     * based on the useDependOn argument.
     *
     * @param task Task to add dependencies to
     * @param useDependedOn if true, add tasks from projects this project depends on, otherwise
     * use projects that depend on this one.
     * @param otherProjectTaskName name of task in other projects
     * @param configurationName name of configuration to use to find the other projects
     */
    private static void addDependsOnTaskInOtherProjects(final Task task, boolean useDependedOn,
            String otherProjectTaskName,
            String configurationName) {
        Project project = task.getProject();
        final Configuration configuration = project.getConfigurations().getByName(
                configurationName);
        task.dependsOn(configuration.getTaskDependencyFromProjectDependency(
                useDependedOn, otherProjectTaskName));
    }

    /**
     * Compute a version-less key representing the given coordinates.
     * @param coordinates the coordinate
     * @return the key.
     */
    @NonNull
    private static String computeVersionLessCoordinateKey(@NonNull MavenCoordinates coordinates) {
        StringBuilder sb = new StringBuilder(coordinates.getGroupId());
        sb.append(':').append(coordinates.getArtifactId());
        if (coordinates.getClassifier() != null) {
            sb.append(':').append(coordinates.getClassifier());
        }
        return sb.toString();
    }
}


text:
using NUnit.Framework;

using System;
using System.Data;

using GHTUtils;
using GHTUtils.Base;

namespace tests.system_data_dll.System_Data
{
[TestFixture] public class DataRow_IsNull_DD : GHTBase
{
	[Test] public void Main()
	{
		DataRow_IsNull_DD tc = new DataRow_IsNull_DD();
		Exception exp = null;
		try
		{
			tc.BeginTest("DataRow_IsNull_DD");
			tc.run();
		}
		catch(Exception ex)
		{
			exp = ex;
		}
		finally
		{
			tc.EndTest(exp);
		}
	}

	//Activate This Construntor to log All To Standard output
	//public TestClass():base(true){}

	//Activate this constructor to log Failures to a log file
	//public TestClass(System.IO.TextWriter tw):base(tw, false){}

	//Activate this constructor to log All to a log file
	//public TestClass(System.IO.TextWriter tw):base(tw, true){}

	//BY DEFAULT LOGGING IS DONE TO THE STANDARD OUTPUT ONLY FOR FAILURES

	public void run()
	{
		Exception exp = null;

		DataTable dt = new DataTable();
		DataColumn dc0 = new DataColumn("Col0",typeof(int));
		DataColumn dc1 = new DataColumn("Col1",typeof(int));
		dt.Columns.Add(dc0);
		dt.Columns.Add(dc1);
		dt.Rows.Add(new object[] {1234});
		DataRow dr = dt.Rows[0];

		try
		{
			BeginCase("IsNull - col0 Current");
			Compare(dr.IsNull(dc0,DataRowVersion.Current) , false);
		}
		catch(Exception ex)	{exp = ex;}
		finally	{EndCase(exp); exp = null;}

		try
		{
			BeginCase("IsNull - col1 Current");
			Compare(dr.IsNull(dc1,DataRowVersion.Current) , true);
		}
		catch(Exception ex)	{exp = ex;}
		finally	{EndCase(exp); exp = null;}

		try
		{
			BeginCase("IsNull - col0 Default");
			Compare(dr.IsNull(dc0,DataRowVersion.Default) , false);
		}
		catch(Exception ex)	{exp = ex;}
		finally	{EndCase(exp); exp = null;}
		try
		{
			BeginCase("IsNull - col1 Default");
			Compare(dr.IsNull(dc1,DataRowVersion.Default) , true);
		}
		catch(Exception ex)	{exp = ex;}
		finally	{EndCase(exp); exp = null;}

		dr.BeginEdit();
		dr[0] = 9; //Change value, Create RowVersion Proposed

		try
		{
			BeginCase("IsNull - col0 Proposed");
			Compare(dr.IsNull(dc0,DataRowVersion.Proposed) , false);
		}
		catch(Exception ex)	{exp = ex;}
		finally	{EndCase(exp); exp = null;}
		try
		{
			BeginCase("IsNull - col1 Proposed");
			Compare(dr.IsNull(dc1,DataRowVersion.Proposed) , true);
		}
		catch(Exception ex)	{exp = ex;}
		finally	{EndCase(exp); exp = null;}

		dr.AcceptChanges();
		dr.Delete();

		try
		{
			BeginCase("IsNull - col0 Original");
			Compare(dr.IsNull(dc0,DataRowVersion.Original) , false);
		}
		catch(Exception ex)	{exp = ex;}
		finally	{EndCase(exp); exp = null;}

	}
}
}

redpajama_set_name: RedPajamaGithub


text:
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { findDOMNode } from 'react-dom';
import Box from '../Box';
import SocialShare from '../SocialShare';
import Form from '../Form';
import FormField from '../FormField';
import CSSClassnames from '../../utils/CSSClassnames';

const CLASS_ROOT = CSSClassnames.VIDEO;
const BUTTON_CLASS = `${CLASS_ROOT}__button`;

export default class Overlay extends Component {

  constructor () {
    super();

    this._onClickShareLink = this._onClickShareLink.bind(this);
  }

  _onClickShareLink () {
    findDOMNode(this.shareLinkRef).select();
  }

  render() {
    const { shareLink, shareHeadline, shareText } = this.props;

    // this has to be null to be a valid react children
    let shareContent = null;
    if (shareLink) {
      shareContent = (
        <Box align='center'>
          <Form pad={{vertical: 'small'}}>
            <FormField strong={true}>
              <input ref={ref => this.shareLinkRef = ref}
                className='share-link' type='text' value={shareLink}
                onClick={this._onClickShareLink} readOnly />
            </FormField>
          </Form>
          <Box direction='row' className={BUTTON_CLASS}>
            <SocialShare type='email' link={shareLink} colorIndex='brand'
              className={`${BUTTON_CLASS}__icon`}
              title={shareHeadline} text={shareText} />
            <SocialShare type='twitter' colorIndex='brand'
              className={`${BUTTON_CLASS}__icon`}
              link={shareLink} text={shareHeadline} />
            <SocialShare type='facebook' colorIndex='brand'
              className={`${BUTTON_CLASS}__icon`}
              link={shareLink} />
            <SocialShare type='linkedin' colorIndex='brand'
              className={`${BUTTON_CLASS}__icon`}
              link={shareLink} title={shareHeadline} text={shareText} />
          </Box>
        </Box>
      );
    }

    return shareContent;
  }
}

Overlay.propTypes = {
  shareLink: PropTypes.string,
  shareHeadline: PropTypes.string,
  shareText: PropTypes.string
};

Overlay.defaultProps = {
  shareHeadline: '',
  shareText: ''
};


text:
@class MCSettingsController;
@class MCTrayViewController;

namespace message_center {

// Bridge class between C++ and Cocoa world.
class NotifierSettingsObserverMac : public NotifierSettingsObserver {
 public:
  NotifierSettingsObserverMac(MCSettingsController* settings_controller)
      : settings_controller_(settings_controller) {}
  virtual ~NotifierSettingsObserverMac();

  // Overridden from NotifierSettingsObserver:
  void UpdateIconImage(const NotifierId& notifier_id,
                       const gfx::Image& icon) override;
  void NotifierGroupChanged() override;
  void NotifierEnabledChanged(const NotifierId& notifier_id,
                              bool enabled) override;

 private:
  MCSettingsController* settings_controller_;  // weak, owns this

  DISALLOW_COPY_AND_ASSIGN(NotifierSettingsObserverMac);
};

}  // namespace message_center

// The view controller responsible for the settings sheet in the center.
MESSAGE_CENTER_EXPORT
@interface MCSettingsController : NSViewController {
 @private
  scoped_ptr<message_center::NotifierSettingsObserverMac> observer_;
  message_center::NotifierSettingsProvider* provider_;
  MCTrayViewController* trayViewController_;  // Weak. Owns us.

  // The "Settings" text at the top.
  base::scoped_nsobject<NSTextField> settingsText_;

  // The smaller text below the "Settings" text.
  base::scoped_nsobject<NSTextField> detailsText_;

  // The profile switcher.
  base::scoped_nsobject<MCDropDown> groupDropDownButton_;

  // Container for all the checkboxes.
  base::scoped_nsobject<NSScrollView> scrollView_;

  std::vector<message_center::Notifier*> notifiers_;
}

// Designated initializer.
- (id)initWithProvider:(message_center::NotifierSettingsProvider*)provider
    trayViewController:(MCTrayViewController*)trayViewController;

// Returns whether |provider_| has an advanced settings handler for the given
// notifier; i.e. we should show the "Learn More" button.
- (BOOL)notifierHasAdvancedSettings:(const message_center::NotifierId&)id;

// Handler when a checkbox is enabled/disabled.
- (void)setSettingsNotifier:(message_center::Notifier*)notifier
                    enabled:(BOOL)enabled;

// Handler when the learn more link is clicked.
- (void)learnMoreClicked:(message_center::Notifier*)notifier;

@end

// Testing API /////////////////////////////////////////////////////////////////

@interface MCSettingsController (TestingAPI)
- (NSPopUpButton*)groupDropDownButton;
- (NSScrollView*)scrollView;
@end

#endif  // UI_MESSAGE_CENTER_COCOA_SETTINGS_CONTROLLER_H_


text:
Ti.include('contact.js');
Ti.include('programs.js');
Ti.include('about.js');
Ti.include('landing.js');

Titanium.UI.setBackgroundColor('#000');

// create tab group
var tabGroup = Titanium.UI.createTabGroup({
	barColor:'#d9bd61',
	tabsBackgroundColor:'#f4f4f4',
	activeTabIconTint:'#292929'
});

//
// create base UI tab and root window
//
var win1 = Titanium.UI.createWindow({
    title:'Home',
    backgroundColor:'#F2EDCB'
});
var tab1 = Titanium.UI.createTab({
    icon:'home.png',
    title:'Welcome!',
    window:win1
});

var win2 = Titanium.UI.createWindow({
    title:'Info',
    backgroundColor:'#F2EDCB'
});
var tab2 = Titanium.UI.createTab({
    icon:'info.png',
    title:'Info',
    fontWeight:'bold',
    window:win2
});

var win3 = Ti.UI.createWindow({
	title:'Programs',
	backgroundColor:'#F2EDCB'
});
var tab3 = Titanium.UI.createTab({
	icon:'airport.png',
	title:'Programs',
	window: win3
});

var win4 = Ti.UI.createWindow({
	title:'Contact Us!',
	backgroundColor:'#F2EDCB'
});
var tab4 = Titanium.UI.createTab({
	icon:'message.png',
	title:'Contact Us!',
	window: win4
});

//win1: Landing Page
win1.add(scrollViewLanding);

//win2: About
win2.add(scrollView);

//win3: List of Programs
win3.add(programView());

//win4: Contact Info
win4.add(labelInfo);
win4.add(imageMap);

//
//  add tabs
//
tabGroup.addTab(tab1);
tabGroup.addTab(tab2);
tabGroup.addTab(tab3);
tabGroup.addTab(tab4);

// open tab group
tabGroup.open();


text:
This document will go over everything that is needed to generate Challenges with tasks in various ways through the API. Although the API is quite powerful it can be difficult to navigate at times due to the various options that are available to the user of the API. The MapRoulette UI will usually hide all these options from the user and provide a clean interface to build challenges from. This document will describe all the various options and how to use them through the API.

For more information and more advanced options on building projects using the API see the swagger documentation. The swagger documentation can be found on any instance of MapRoulette with the following url: ```/docs/swagger-ui/index.html```. To see the swagger documentation for maproulette.org follow this [link](https://maproulette.org/docs/swagger-ui/index.html).

## Creating a Project

The first thing that is required for any Challenge is a Project. The hierarchy for objects in MapRoulette look as follows:

```Project -> Challenge -> Task```

Creating a Project is fairly simple using the API. A basic example is as follows:

```
POST /api/v2/project
HEADER apiKey = <USER_API_KEY>
BODY {
    "name":"Example Project",
    "description":"Example project for documentation.",
    "enabled":true
}
```

## Creating a Challenge

Challenges and their children Tasks can be created in a multitude of ways using the Challenge API. In this document we will be going over the following methods:

- [Manually building a Challenge](#manually-building-a-challenge)
- [Manually building a Task](#manually-building-a-task)
- [Batched Task creation](#batched-task-creation)
- [Task creation within a Challenge](#task-creation-within-a-challenge)
- [Task creation from Overpass Query](#task-creation-from-overpass-query)
- [Task creation from GeoJSON](#task-creation-from-geojson)

#### Manually Building a Challenge

Building a Challenge through the API is fairly trivial and at the very basic level can be completed with the following API request:

```
POST /api/v2/challenge
HEADER apiKey = <USER_API_KEY>
BODY {
    "name":"Example Challenge",
    "parent":<PROJECT_ID>,
    "instruction":"Instruction for the example challenge"
}
```

As shown in the example there are 3 basic options that are required to create a challenge. However there are many more options that are available that can be used when building a challenge:

- **description** - A basic description for the challenge
- **infoLink** - A link to a page that has information about the challenge
- **difficulty** - The difficulty of the challenge, 1 - EASY; 2 - NORMAL; 3 - EXPERT. Default is NORMAL.
- **blurb** - A small blurb about the challenge
- **enabled** - Whether the challenge will be available in searches and on the main MapRoulette page. By default is set to false.
- **featured** - Whether the challenge will be featured in MapRoulette or not. By default is set to false.
- **checkinComment** - The default comment that would be used when fixing a task.
- **overpassQL** - By default empty, if set it assumes that the tasks to be created will be based off the provided overpass query in this field.
- **remoteGeoJSON** - By default empty, if set it assumes that the tasks to be created will be based off the geoJSON found at the URL provided in this field. If overpassQL has been provided it will be used instead of this value.
- **defaultPriority** - The default priority of any tasks that are not matched with any of the priority rules.
- **highPriorityRule** - Any tasks that match the priority rule will be set to high, ie. viewed first.
- **mediumPriorityRule** - Any tasks that match the priority rule will be set to medium, ie. viewed after all high priority tasks have been viewed.
- **lowPriorityRule** - Any tasks that match the priority rule will be set to low, ie. viewed after all the medium priority tasks have been viewed.
- **defaultZoom** - The default zoom level for the challenge, which defaults to 13.
- **minZoom** - The minimum zoom level allowed for the challenge, which defaults to 1.
- **maxZoom** - The maximum zoom level allowed for the challenge, which defaults to 19.
- **defaultBasemap** -
- **customBasemap** - URL for a custom basemap to be applied to the map for a specific challenge.
- **updateTasks** - Whether to update the tasks on a periodic basis. This will also delete stale tasks.

#### Manually Building a Task

Building a task through the API can be done using the following API request:

```
POST /api/v2/task
HEADER apiKey = <USER_API_KEY>
BODY {
    "name":"Example Task",
    "parent": <PARENT_CHALLENGE_ID>,
    "instruction":"Example Task instruction",
    "geometries":{"type":"FeatureCollection","features":[{"type":"Feature","geometry":{"type":"Point","coordinates":[102.1,0.6]},"properties":{"id": "test2"}},{"type":"Feature","geometry":{"type":"Point","coordinates":[102.2,0.7]},"properties":{ "identifier":{"value":1111} }}]}
}
```

This is to create a single task for a challenge, the id of the challenge is provided in the body of the Task. Generally speaking, using this is not super efficient. Better options (which will be described later) would be to create the tasks immediately with the Challenge or to create the tasks in batches.

#### Batched Task Creation

All objects in MapRoulette can be created in batches using this style of API, in the POST functions for Project, Challenge or Task. Batched Task creation is the most useful, as generally speaking the number of tasks being created will be much higher compared to the number of projects or challenges being created. Here is the API request:

```
POST /api/v2/tasks
HEADER apiKey = <USER_API_KEY>
BODY [
    {
        "name":"Task1",
        "parent":1,
        "instruction":"Task1 instruction",
        "geometries":{"type":"FeatureCollection","features":[{"type":"Feature","geometry":{"type":"Point","coordinates":[102.1,0.6]},"properties":{"id": "test2"}},{"type":"Feature","geometry":{"type":"Point","coordinates":[102.2,0.7]},"properties":{ "identifier":{"value":1111} }}]}
    },
    {
        "name":"Task2",
        "parent":1,
        "instruction":"Task2 instruction",
        "geometries":{"type":"FeatureCollection","features":[{"type":"Feature","geometry":{"type":"Point","coordinates":[102.1,0.6]},"properties":{"id": "test2"}},{"type":"Feature","geometry":{"type":"Point","coordinates":[102.2,0.7]},"properties":{ "identifier":{"value":1111} }}]}
    },
    ...
]
```

For challenges you would use the API ```/api/v2/challenges``` and for projects you would use the API ```/api/v2/projects```.

#### Task Creation within a Challenge

Another option is to create the tasks directly within the challenge. This can be done using the "children" key in the Challenge object as follows:

```
POST /api/v2/challenge
HEADER apiKey = <USER_API_KEY>
BODY {
    "name":"Example Challenge",
    "parent":<PROJECT_ID>,
    "instruction":"Instruction for the example challenge",
    "children":[
        ...
        <BATCHED TASK OBJECTS>
        ...
    ]
}
```

This approach can be done at the project level as well. So in a single API request you can potentially create the entire hierarchy down to the task using the children key like so

```
    {
        <PROJECT PARAMS>,
        "children": [
            {
                <CHALLENGE PARAMS>,
                "children": [
                    {
                        <TASK PARAMS>
                    },
                    ...
                ]
            },
            ...
        ]
    }
```

#### Task creation from Overpass Query

A challenge can be created with an overpass query. If an overpass query is supplied the status of the challenge will immediately go into "BUILDING" and then will execute the overpass query request to the overpass servers and with the results of the query build tasks from it. Once all tasks have been successfully completed the status of the Challenge will move to "COMPLETED". If any tasks failed to be created from the query, the status of the Challenge will go to "PARTIALLY_LOADED" indicating that not all tasks could be created. If there is a complete failure, for instance if the overpass servers are unavailable then it will go to status "FAILED" and push the reason for failure into the "statusMessage" field of the challenge. When you request the challenge it will always return with "status" and "statusMessage" fields which can be used to evaluate the current state of the Challenge.

An example of creating a Challenge using the overpass query option is show in the [**Examples**](#examples) section.

#### Task creation from GeoJSON

Creating tasks for a challenge using GeoJSON can be done in several different ways.

The first option is simply to include a URL to the geoJSON in the "remoteGeoJSON" field during Challenge creation. This will then create the Challenge and run through a similar workflow that is used during task and challenge creation for overpass queries.

The second option is to use the github API Challenge creation method. This allows you to store everything needed in Github that will then be used to creation the Challenge. More information about this including an example can be found in the [**Examples**](#examples) section.

The third option is to provide the GeoJSON directly through the API. This can be done in three different ways:
1. Using the "localGeoJSON" key during the creation of the challenge
    ```
        POST /api/v2/challenge
        HEADER apiKey = <USER_API_KEY>
        BODY {
            "name":"Example Project",
            "parent":<PROJECT_ID>,
            "instruction":"Instruction for the example challenge",
            "localGeoJSON":<VALID GEOJSON>
        }
    ```
2. Using the API ```PUT /api/v2/challenge/{id}/addTasks``` where the body of the request is the GeoJSON that you wish to use to create the tasks.

3. Using the API ```PUT /api/v2/challenge/{id}/addFileTasks?lineByLine=false```. This is a multipart HTTP request where the body is essentially a binary file. That file is the GeoJSON that you want to use to create the files. If you set the "lineByLine" query string parameter to true you can upload file that contains GeoJSON line delimited. The usefulness of this is that you can control the task creation cleaner, as each line will equate to a single task.

##### GeoJSON Structure

The GeoJSON provided in any of the above usages must conform to the GeoJSON standards found in [RFC 7946](https://tools.ietf.org/html/rfc7946), you can also find out further information at [geojson.org](http://geojson.org). There is one caveat to this, in that you can also provide LineByLine GeoJSON. That is GeoJSON that as a whole is not valid, as each line in a file contains valid GeoJSON, but each line is a separate GeoJSON entity. The LineByLine GeoJSON is only an option when using files, and cannot be used when supplying the GeoJSON in the body of a Challenge. You can however use the LineByLine GeoJSON when supplying it as the body of the API ```PUT /api/v2/challenge/{id}/addTasks```.

## Examples

The following sections contains full working examples of challenge and tasks creation. All examples are fairly straight forward and do not contain any advanced options like priorities.
All the examples where created using the GeoJSON provided [here](example.geojson) or the LineByLine GeoJSON provided [here](linebyLine.geojson).

All examples also assume it is executing against a local MapRoulette instance. Changing the example to run against another server would simply mean modifying the server name and port to match the desired server name and port. We also assume that the header apiKey field will be "user1_apikey".

#### Create Challenge using GeoJSON

In this example we are going to create a Challenge with tasks based on the example geojson file provided [here](example.geojson). We will give examples of all three ways that the challenge can be created.

###### Create by "LocalGeoJSON"
```
POST http://localhost:9000/api/v2/challenge
HEADER apiKey = user1_apiKey
BODY {
    "name":"Local GeoJSON Challenge",
    "parent":<PROJECT_ID>,
    "instruction":"Instruction for local GeoJSON challenge",
    "localGeoJSON":<PASTE example.geojson CONTENTS HERE>
}
```

###### Create by addTasks API
```
POST http://localhost:9000/api/v2/challenge/<CHALLENGE_ID>/addTasks
HEADER apiKey = user1_apiKey
BODY <CONTENTS of example.geojson>
```

#### Create Challenge using Overpass

To create a challenge with tasks you execute the following API:
```
POST http://localhost:9000/api/v2/challenge
HEADER apiKey = user1_apikey
BODY {
     "name":"Overpass Challenge",
     "parent":<PROJECT_ID>,
     "instruction":"Instruction for the overpass challenge",
     "overpassQL":"[out:xml[timeout:250];(way[\"highway\"~\"motorway|trunk|primary|secondary|tertiary|motorway_link|trunk_link|primary_link|secondary_link|tertiary_link|residential|unclassified\"][\"name\"~\"National Forest\"](47.148633511301426,-121.90567016601562,47.95774347215711,-120.45684814453124););out meta;>;out meta qt;"
 }
```

This will create a challenge containing tasks match the following criteria:
1. Within the bounding box 47.148633511301426,-121.90567016601562,47.95774347215711,-120.45684814453124
2. Has a highway with a tag value of motorway, trunk, primary, secondary, tertiary, motorway_link, trunk_link, primary_link, secondary_link, tertiary_link, residential or unclassified.
3. The name of the feature is contains "National Forest"

#### [Create Challenge using Github](github_example.md)


text:
#include <aws/shield/model/AttackStatisticsDataItem.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Utils::Json;
using namespace Aws::Utils;

namespace Aws
{
namespace Shield
{
namespace Model
{

AttackStatisticsDataItem::AttackStatisticsDataItem() :
    m_attackVolumeHasBeenSet(false),
    m_attackCount(0),
    m_attackCountHasBeenSet(false)
{
}

AttackStatisticsDataItem::AttackStatisticsDataItem(JsonView jsonValue) :
    m_attackVolumeHasBeenSet(false),
    m_attackCount(0),
    m_attackCountHasBeenSet(false)
{
  *this = jsonValue;
}

AttackStatisticsDataItem& AttackStatisticsDataItem::operator =(JsonView jsonValue)
{
  if(jsonValue.ValueExists("AttackVolume"))
  {
    m_attackVolume = jsonValue.GetObject("AttackVolume");

    m_attackVolumeHasBeenSet = true;
  }

  if(jsonValue.ValueExists("AttackCount"))
  {
    m_attackCount = jsonValue.GetInt64("AttackCount");

    m_attackCountHasBeenSet = true;
  }

  return *this;
}

JsonValue AttackStatisticsDataItem::Jsonize() const
{
  JsonValue payload;

  if(m_attackVolumeHasBeenSet)
  {
   payload.WithObject("AttackVolume", m_attackVolume.Jsonize());

  }

  if(m_attackCountHasBeenSet)
  {
   payload.WithInt64("AttackCount", m_attackCount);

  }

  return payload;
}

} // namespace Model
} // namespace Shield
} // namespace Aws


text:
import App from './App.vue'
import loginLayout from './components/loginLayout.vue'
import postLayout from './components/postLayout.vue'

export default [{
    path: '/',
    name: 'home',
    redirect: 'meeting',
    meta: {
        requiresAuth: true,
    },
}, {
    path: '/login',
    name: 'login',
    component: loginLayout,
    meta: {
        requiresAuth: false,
    },
}, {
    path: '/meeting',
    name: 'meeting',
    component: postLayout,
    meta: {
        requiresAuth: true,
    },
}, {
    path: '/fee',
    name: 'fee',
    component: postLayout,
    meta: {
        requiresAuth: true,
    },
}, {
    path: '/goodStudent',
    name: 'goodStudent',
    component: postLayout,
    meta: {
        requiresAuth: true,
    },
}, {
    path: '/checkIn',
    name: 'checkIn',
    component: postLayout,
    meta: {
        requiresAuth: true,
    },
}]


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System.Collections.Generic;

namespace Azure.Storage.Files.DataLake.Models
{
    /// <summary>
    /// An enumeration of paths.
    /// </summary>
    internal class PathSegment
    {
        /// <summary>
        /// If the number of paths to be listed exceeds the maxResults limit, a continuation token is returned.
        /// When a continuation token is returned in the response, it must be specified in a subsequent invocation
        /// of the list operation to continue listing the paths.
        /// </summary>
        public string Continuation { get; internal set; }

        /// <summary>
        /// PathItems
        /// </summary>
        public IEnumerable<PathItem> Paths { get; internal set; }

        /// <summary>
        /// Prevent direct instantiation of PathSegment instances.
        /// You can use DataLakeModelFactory.PathSegment instead.
        /// </summary>
        internal PathSegment() { }
    }
}


text:
THREE.ProcessStep = function(fn, options){

	this.process = {
		active: options.active || true,
		runOnce: options.runOnce || false
	};

	this.create = function(){};
	this.render = fn;

};


text:
title:  Kršenje duha zakona
date:   26/10/2019
---

>

> "Vratite im i vi još danas njihova polja, vinograde, maslinike i kuće njihove, i oprostite im postotak u novcu, u žitu, u vinu, u ulju, što ste im ga nametnuli." (Nehemija 5,11)

### Biblijski tekstovi
Nehemija 5,1-5; Izlazak 21,2-7; Mihej 6,8; Nehemija 5,7-12; Ponovljeni zakon 23,21-23; Nehemija 5,14-19.

Mi ljudi se do današnjeg dana borimo s pitanjem bogatstva i siromaštva, jazom između bogatih i siromašnih i onim što može biti učinjeno u vezi s tim. Da, Isus je rekao: "Siromaha ćete uvijek imati sa sobom" (Matej 26,11), ali to nije izgovor da im ne pomognemo. Naprotiv, Pismo nas opominje da učinimo svoj dio u pružanju pomoći. U suprotnom sebe teško možemo nazvati kršćanima.

Zanimljivo je da se ova tema javlja usred nevolja i muka povratnika tijekom ponovne gradnje Jeruzalema: ne samo tema o siromaštvu i siromašnima, već i o mnogo problematičnijem pitanju koje se tiče tlačenja siromašnih od strane bogatih. Ovaj problem postojao je i prije izgnanstva, i sada, kada su se vratili u svoju zemlju, ponovno je prisutan.

Ovoga tjedna vidjet ćemo još jedno pojavljivanje ove stare teme, kao i to kako se Nehemija s tim suočio. Kao što ćemo vidjeti, ono što je ovo tlačenje činilo još gorim bilo je što se vršilo u okviru "slova zakona", što je snažan primjer koliko trebamo paziti da pravila i propisi ne postanu sami sebi cilj, već sredstvo postizanja cilja, cilj da odražavamo Isusov karakter.

**Oikos:** Ovog tjedna čitamo iz knjige Ellen G. White, Velika borba, Znaci vremena, 2010., poglavlje 7


text:
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.

package com.microsoft.azure.management.websites.models;

import com.microsoft.windowsazure.core.LazyArrayList;
import java.util.ArrayList;

/**
* The List Web Sites operation parameters.
*/
public class WebSiteListParameters {
    private ArrayList<String> propertiesToInclude;

    /**
    * Optional. Specifies a list of the names of any addtional parameters to
    * return.
    * @return The PropertiesToInclude value.
    */
    public ArrayList<String> getPropertiesToInclude() {
        return this.propertiesToInclude;
    }

    /**
    * Optional. Specifies a list of the names of any addtional parameters to
    * return.
    * @param propertiesToIncludeValue The PropertiesToInclude value.
    */
    public void setPropertiesToInclude(final ArrayList<String> propertiesToIncludeValue) {
        this.propertiesToInclude = propertiesToIncludeValue;
    }

    /**
    * Initializes a new instance of the WebSiteListParameters class.
    *
    */
    public WebSiteListParameters() {
        this.setPropertiesToInclude(new LazyArrayList<String>());
    }
}


text:
import clr
from System.Collections.Generic import *
clr.AddReference('RevitAPI')
from Autodesk.Revit.DB import *
import Autodesk

clr.AddReference("RevitNodes")
import Revit
clr.ImportExtensions(Revit.Elements)
clr.ImportExtensions(Revit.GeometryConversion)

clr.AddReference("RevitServices")
import RevitServices
from RevitServices.Persistence import DocumentManager
from RevitServices.Transactions import TransactionManager

doc = DocumentManager.Instance.CurrentDBDocument
items = UnwrapElement(IN[0])
xyz = UnwrapElement(IN[1]).ToXyz()
rehost = IN[2]

ids = list()
for item in items:
	ids.append(item.Id)
itemlist = List[ElementId](ids)

TransactionManager.Instance.EnsureInTransaction(doc)
if rehost:
	newitems = ElementTransformUtils.CopyElements(doc,itemlist,doc,Transform.CreateTranslation(xyz),None)
else:
	newitems = ElementTransformUtils.CopyElements(doc,itemlist,xyz)
TransactionManager.Instance.TransactionTaskDone()

elementlist = list()
for item in newitems:
	elementlist.append(doc.GetElement(item).ToDSType(False))

OUT = elementlist


text:
import { h, Component, ComponentProps } from 'preact';
import styled from 'styled-components';
import { font, palette } from 'styled-theme';

const Label = styled.label`
  font-family: ${font('primary')};
  color: ${palette('grayscale', 1)};
  font-size: 1em;
  line-height: 2em;
`;

export default Label;


text:
    In this example we are loading many items but only ~30 of them are rendered in the DOM.
    This allows to load as big data as you want.

<ng-select [items]="photosBuffer"
           [virtualScroll]="true"
           [loading]="loading"
           bindLabel="title"
           bindValue="thumbnailUrl"
           placeholder="Select photo"
           appendTo="body"
           (scroll)="onScroll($event)"
           (scrollToEnd)="onScrollToEnd()">
    <ng-template ng-header-tmp>
        Loaded {{photosBuffer.length}} of {{photos.length}}
    </ng-template>
    <ng-template ng-option-tmp let-item="item" let-index="index">
        {{index}} {{item.title}}
    </ng-template>
</ng-select>


text:
use std::cmp;
use rustbox::{RustBox, Color, Style};

use super::wrap::StringWrap;

/// Extension trait for `RustBox` utils.
pub trait RustBoxExt : Sized {
    /// Checks how wide the given text would be in the terminal.
    fn text_width(&self, s: &str) -> usize;

    /// Renders blank spaces of the given style across the line at `y`.
    fn blank_line(&mut self, y: usize, style: Style, fgcolor: Color, bgcolor: Color);
}

impl RustBoxExt for RustBox {
    fn text_width(&self, s: &str) -> usize {
        // FIXME: This isn't even remotely accurate, especially not for
        // multi-byte unicode chars, but RustBox doesn't handle those correctly
        // anyway, so we won't worry about it for now.
        s.len()
    }

    fn blank_line(&mut self, y: usize, style: Style, fgcolor: Color, bgcolor: Color) {
        let w = self.width();
        // Generate 'w' many blank spaces
        let blank = String::from_utf8(vec![b' '; w]).unwrap();
        self.print(0, y, style, fgcolor, bgcolor, &blank);
    }
}

/// Builder pattern type for rendering with columns and line wrapping.
pub struct LineBuilder {
    cols: Vec<ColBuilder>,
}

impl LineBuilder {
    pub fn new() -> LineBuilder {
        LineBuilder {
            cols: vec![],
        }
    }

    /// Adds a column and returns a `&mut` reference to it.
    pub fn add_column(&mut self, text: String) -> &mut ColBuilder {
        use rustbox::RB_NORMAL;
        self.cols.push(ColBuilder {
            text: text,
            wrap: false,
            wrapping: None,
            pad: None,
            style: RB_NORMAL,
            fgcolor: Color::Default,
            bgcolor: Color::Default,
        });
        let idx = self.cols.len()-1;
        &mut self.cols[idx]
    }

    /// Skips a space of the given width.
    pub fn skip(&mut self, w: usize) {
        self.add_column(String::new()).pad_right(w);
    }

    /// Calculates the line's height after line wrapping in the given terminal.
    pub fn height(&mut self, rb: &mut RustBox) -> usize {
        let term_w = rb.width();
        let mut x = 0;

        let mut max_h = 1;
        for mut col in self.cols.iter_mut() {
            let w = if x < term_w {
                col.pad.clone().map(|p| p.width()).unwrap_or(term_w - x)
            } else { 0 };

            if col.wrap {
                let wrap = col.wrap_to(w);
                let h = wrap.line_count();
                max_h = cmp::max(h, max_h);
            }

            x += w;
            if x > term_w { break; }
        }
        max_h
    }

    /// Prints this line in the given terminal.
    pub fn print(self, y: usize, rb: &mut RustBox) {
        use self::PadText::*;

        let term_w = rb.width();
        let mut x = 0;
        for mut col in self.cols {
            let w = if x < term_w {
                col.pad.clone().map(|p| p.width()).unwrap_or(term_w - x)
            } else { 0 };

            if col.wrap {
                let wrap = col.wrap_to(w);
                for (i, line) in wrap.iter_lines(&col.text).enumerate() {
                    rb.print(x, y + i - 1, col.style, col.fgcolor, col.bgcolor, line);
                }
            } else {
                let text = match col.pad {
                    Some(Left(w))  => { format!("{0: >1$}", col.text, w) },
                    Some(Right(w)) => { format!("{0: <1$}", col.text, w) },
                    None => col.text,
                };
                rb.print(x, y, col.style, col.fgcolor, col.bgcolor, &text);
            }
            x += w;
        }
    }
}

/// Column within a `LineBuilder`.
#[derive(Debug, Clone)]
pub struct ColBuilder {
    text: String,
    /// If true, text will be wrapped onto subsequent lines.
    wrap: bool,
    wrapping: Option<StringWrap>,
    /// The column's width and padding. If `None`, the column will expand to
    /// fill the entire remaining width of the screen.
    pad: Option<PadText>,

    style: Style,
    fgcolor: Color,
    bgcolor: Color,
}

impl ColBuilder {
    /// Enables word wrapping for this column.
    pub fn wrap(&mut self) -> &mut Self {
        self.wrap = true;
        self
    }

    /// Left-pads text to the given width.
    pub fn pad_left(&mut self, w: usize) -> &mut Self {
        self.pad = Some(PadText::Left(w));
        self
    }

    /// Right-pads text to the given width.
    pub fn pad_right(&mut self, w: usize) -> &mut Self {
        self.pad = Some(PadText::Right(w));
        self
    }

    /// Sets the style for text in this column.
    pub fn style(&mut self, style: Style) -> &mut Self {
        self.style = style;
        self
    }

    /// Sets the fgcolor for text in this column.
    pub fn fgcolor(&mut self, color: Color) -> &mut Self {
        self.fgcolor = color;
        self
    }

    /// Sets the bgcolor for text in this column.
    pub fn bgcolor(&mut self, color: Color) -> &mut Self {
        self.bgcolor = color;
        self
    }
}

impl ColBuilder {
    /// Calculates line wrapping for this column.
    fn wrap_to(&mut self, width: usize) -> StringWrap {
        StringWrap::new(&self.text, width)
    }
}

#[derive(Debug, Clone)]
pub enum PadText {
    /// left-pad with given width
    Left(usize),
    /// right-pad with given width
    Right(usize),
}

impl PadText {
    pub fn width(&self) -> usize {
        match *self {
            PadText::Left(w) => w,
            PadText::Right(w) => w,
        }
    }
}


text:
using Microsoft.AspNetCore.Authorization;

namespace AlpineSkiHouse.Security
{
    public class EditSkiCardAuthorizationRequirement : IAuthorizationRequirement
    {
    }
}


text:
package route

import (
	"errors"
	"github.com/fuxiaohei/purine/src/mapi"
	"github.com/fuxiaohei/purine/src/model"
	"github.com/fuxiaohei/purine/src/route/base"
	"github.com/lunny/tango"
)

type Rss struct {
	base.BaseSetting
	tango.Ctx
}

func (r *Rss) Get() {
	res := mapi.Call(mapi.Article.ListArchive, nil)
	if !res.Status {
		panic(errors.New(res.Error))
		return
	}
	opt := &mapi.RssOption{
		Setting:  r.GetGeneral(),
		Articles: res.Data["articles"].([]*model.Article),
	}

	res = mapi.Call(mapi.Rss.ListRSS, opt)
	rss := res.Data["rss"].(*model.Rss)
	r.WriteHeader(200)
	r.Header().Set("Content-Type", "application/rss+xml;charset=UTF-8")
	r.Write([]byte(rss.String()))
}

type Sitemap struct {
	base.BaseSetting
	tango.Ctx
}

func (s *Sitemap) Get() {
	res := mapi.Call(mapi.Article.ListArchive, nil)
	if !res.Status {
		panic(errors.New(res.Error))
		return
	}
	opt := &mapi.SiteMapOption{
		Setting:  s.GetGeneral(),
		Articles: res.Data["articles"].([]*model.Article),
	}

	res = mapi.Call(mapi.Rss.ListSitemap, opt)
	rss := res.Data["sitemap"].(*model.SiteMapGroup)
	s.WriteHeader(200)
	s.Header().Set("Content-Type", "text/xml; charset=utf-8")
	s.Write([]byte(rss.String()))
}


text:
module Palindromes.A249642 (a249642) where
import Helpers.PalindromeCounter (countPalindromes)

a249642 :: Int -> Integer
a249642 = (!!) a249642_list

a249642_list :: [Integer]
a249642_list = countPalindromes 9


text:
using System;
using System.Linq;
using System.Linq.Expressions;
using NinjaNye.SearchExtensions.Helpers.ExpressionBuilders.EqualsExpressionBuilder;

namespace NinjaNye.SearchExtensions
{
    public class QueryableStructSearch<TSource, TProperty> : QueryableSearchBase<TSource, TProperty>
        where TProperty : struct
    {
        public QueryableStructSearch(IQueryable<TSource> source, Expression<Func<TSource, TProperty>>[] properties)
            : base(source, properties)
        {
        }

        public IQueryable<TSource> Include(string path)
        {
            QueryInclude(path);
            return this;
        }

        /// <summary>
        /// Retrieves items where any of the defined properties
        /// equal any of the supplied values
        /// </summary>
        /// <param name="values">Values to search for</param>
        public QueryableStructSearch<TSource, TProperty> EqualTo(params TProperty[] values)
        {
            var equalsExpression = ExpressionBuilder.EqualsExpression(Properties, values);
            BuildExpression(equalsExpression);
            return this;
        }

        /// <summary>
        /// Retrieves items where any of the defined properties
        /// are greater than any of the supplied value
        /// </summary>
        /// <param name="value">Value to search for</param>
        public QueryableStructSearch<TSource, TProperty> GreaterThan(TProperty value)
        {
            var greaterThanExpression = ExpressionBuilder.GreaterThanExpression(Properties, value);
            BuildExpression(greaterThanExpression);
            return this;
        }

        /// <summary>
        /// Retrieves items where any of the defined properties
        /// are less than any of the supplied value
        /// </summary>
        /// <param name="value">Value to search for</param>
        public QueryableStructSearch<TSource, TProperty> LessThan(TProperty value)
        {
            var greaterThanExpression = ExpressionBuilder.LessThanExpression(Properties, value);
            BuildExpression(greaterThanExpression);
            return this;
        }

        /// <summary>
        /// Retrieves items where any of the defined properties
        /// are less than or equal to any of the supplied value
        /// </summary>
        /// <param name="value">Value to search for</param>
        public QueryableStructSearch<TSource, TProperty> LessThanOrEqualTo(TProperty value)
        {
            var lessThanOrEqualExpression = ExpressionBuilder.LessThanOrEqualExpression(Properties, value);
            BuildExpression(lessThanOrEqualExpression);
            return this;
        }

        /// <summary>
        /// Retrieves items where any of the defined properties
        /// are greater than or equal to any of the supplied value
        /// </summary>
        /// <param name="value">Value to search for</param>
        public QueryableStructSearch<TSource, TProperty> GreaterThanOrEqualTo(TProperty value)
        {
            var greaterThanOrEqualExpression = ExpressionBuilder.GreaterThanOrEqualExpression(Properties, value);
            BuildExpression(greaterThanOrEqualExpression);
            return this;
        }

        /// <summary>
        /// Retrieves items where any of the defined properties
        /// are greater than <paramref name="minValue">minValue</paramref>
        /// AND less than <paramref name="maxValue">maxValue</paramref>
        /// </summary>
        public QueryableStructSearch<TSource, TProperty> Between(TProperty minValue, TProperty maxValue)
        {
            var betweenExpression = ExpressionBuilder.BetweenExpression(Properties, minValue, maxValue);
            BuildExpression(betweenExpression);
            return this;
        }
    }
}


text:
/**
 *
 */
package com.akh.algorithms.sorting.practice;

import java.util.List;

import com.akh.utils.Utils;

/**
 * @author Akhash Ramamurthy
 *
 * Apr 3, 2016 7:44:26 PM
 * AbstractSorter.java
 */
public abstract class AbstractSorter implements Sorter {

	@Override
	public abstract int[] sortArray(int[] array);

	@Override
	public List<Integer> sortList(List<Integer> list) {
		return null;
	}

	@Override
	public List<Comparable> sortComparableList(List<Comparable> comparableList) {
		return null;
	}

	void printArray(String message, int[] array){
		Utils.printArray(message, array);
	}

}


text:
import { blobToBase64, request, Response } from "../api";

export type SupportedLanguage = {
  name: string;
  code: string;
};

type GetLanguagesResponse = {
  languages: SupportedLanguage[];
};

const getLanguages = async (): Promise<Response<GetLanguagesResponse>> =>
  await request<GetLanguagesResponse>(
    "/simultaneousInterpreter/languages",
    "GET"
  );

type TranslateSpeechResponse = {
  languageCode: string;
  translations: { [key: string]: string };
};

const translateSpeech = async (
  lang: string,
  blob: Blob
): Promise<Response<TranslateSpeechResponse>> => {
  const data = {
    audio: {
      content: await blobToBase64(blob),
    },
    config: {
      languageCode: lang,
    },
  };

  return await request<TranslateSpeechResponse>(
    "/simultaneousInterpreter/speech:translate",
    "POST",
    data
  );
};

export { getLanguages, translateSpeech };


text:
package event_test

import (
	"fmt"
	"net/http"
	"net/http/httptest"
	"reflect"
	"testing"

	. "github.com/daikikohara/enotify-slack/event"
)

func TestGetEventbrite(t *testing.T) {
	SetTimezone("Asia/Tokyo")
	// success
	tsSuccess := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		fmt.Fprintln(w, `{"events": [{"name":{"text":"example#1","html":"DockerConSFHackathon"},"description":{"text":"summary123","html":""},"id":"123","url":"http://example.connpass.com/event/123/","start":{"timezone":"America/Los_Angeles","local":"2015-06-20T09:30:00","utc":"2015-09-30T10:00:00Z"},"venue":{"address":{"address_1":"address123","address_2":null,"city":"place123","region":"CA","postal_code":"94103","country":"US","latitude":37.7850596,"longitude":-122.40419989999998},"resource_uri":"https://www.eventbriteapi.com/v3/venues/9687712/","id":"9687712","name":"SanFranciscoMarriottMarquis","latitude":"37.7850596","longitude":"-122.40419989999998"}}]}`)
	}))
	defer tsSuccess.Close()
	eventbrite := new(Eventbrite)
	events, err := eventbrite.Get(tsSuccess.URL+"?", keyword, nickname, place)
	if err != nil {
		t.Error(err.Error())
	}
	if !reflect.DeepEqual(eventbriteok, events[0]) {
		t.Error("eventbrite event is not ok!")
	}

	// different timezone
	SetTimezone("America/Los_Angeles")
	events, err = eventbrite.Get(tsSuccess.URL+"?", keyword, nickname, place)
	if err != nil {
		t.Error(err.Error())
	}
	e := eventbriteok
	e.Started_at = "2015-09-30 02:00"
	if !reflect.DeepEqual(e, events[0]) {
		// daylight saving
		e.Started_at = "2015-09-30 03:00"
		if !reflect.DeepEqual(e, events[0]) {
			t.Error("eventbrite event is not ok!")
		}
	}

	// invalid url
	events, err = eventbrite.Get("", keyword, nickname, place)
	if err == nil {
		t.Error(err.Error())
	}
}


text:
require 'faker'

Deck.create!(name: "World Capitals", description: "Learn the capital for each country in the world.")

Card.create(deck_id: 1, question: "China" , answer: "Beijing" )
Card.create(deck_id: 1, question: "India" , answer: "New Delhi" )
Card.create(deck_id: 1, question: "Japan", answer: "Tokyo" )
Card.create(deck_id: 1, question: "Russia", answer: "Moscow" )
Card.create(deck_id: 1, question: "South Korea", answer: "Seoul" )
Card.create(deck_id: 1, question: "Tajikistan", answer: "Dushanbe")

User.create(name: "Nodira", password: "corgi")
User.create(name: "Nirag", password:"taco")
User.create(name: "Armando", password:"pretzelburrito")
User.create(name: "Vianney", password:"insectmaster")


text:
require 'as_deprecation_tracker/receiver'

module ASDeprecationTracker
  # Railtie to register for deprecation notifications
  class Railtie < ::Rails::Railtie
    initializer 'as_deprecation_tracker.deprecation_notifications', after: :load_environment_config, if: -> { ASDeprecationTracker.active? } do
      Receiver.attach_to :rails, ASDeprecationTracker.receiver
      ActiveSupport::Deprecation.behavior = :notify if ASDeprecationTracker.config.register_behavior?

      whitelist = ASDeprecationTracker.config.whitelist_file
      ([Rails.root] + engine_roots).each do |root|
        engine_whitelist = File.join(root, whitelist)
        ASDeprecationTracker.whitelist.load_file(engine_whitelist) if File.exist?(engine_whitelist)
      end
    end

    private

    def engine_roots
      ::Rails::Engine.descendants.map { |engine| engine.root rescue nil }.compact.uniq # rubocop:disable Style/RescueModifier
    end
  end
end


text:
require 'spec_helper'

describe CSI::Plugins::Jenkins do
  it 'should display information for authors' do
    authors_response = CSI::Plugins::Jenkins
    expect(authors_response).to respond_to :authors
  end

  it 'should display information for existing help method' do
    help_response = CSI::Plugins::Jenkins
    expect(help_response).to respond_to :help
  end
end


text:
<?php
/**
 * Cart viewing controller
 *
 * @author Steve Guidetti <sguidetti@ultramegatech.com>
 * @license http://sguidetti.mit-license.org/ The MIT License (MIT)
 * @package UMCart
 * @subpackage Controller
 */

/**
 * View Cart Command
 */
class Command_ViewCart extends Command_Common {
    /**
     * Execute command
     */
    public function exec() {
        $this->data['products'] = array();
        if(isset($this->session->cart_id) && $cart = new Model_Cart($this->session->cart_id)) {
            $this->loadProducts($cart);
            $this->data['cart'] = array(
                'num_items'         => $cart->get('num_items'),
                'total'             => String::formatMoney($cart->get('total')),
                'discount'          => String::formatMoney($cart->get('discount')),
                'total_adjusted'    => String::formatMoney($cart->get('total_adjusted')),
                'coupon_code'       => String::safeHTMLText($cart->get('coupon_code'))
            );
        }

        $this->loadView('cart');
    }
    /**
     * Load product data into output data
     *
     * @param Model_Cart $cart
     */
    private function loadProducts(Model_Cart $cart) {
        $cart->loadProducts();

        $products = array();
        foreach($cart->products as $key => $product) {
            $products[$key] = array(
                'product'           => $product['product']->getAll(),
                'quantity'          => $product['quantity'],
                'price'             => String::formatMoney($product['price']),
                'discount'          => String::formatMoney($product['discount']),
                'price_adjusted'    => String::formatMoney($product['price_adjusted'])
            );
        }

        $this->data['products'] = $products;
    }
}