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

import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Multimap;
import com.google.devtools.build.lib.analysis.RedirectChaser;
import com.google.devtools.build.lib.analysis.config.BuildConfiguration;
import com.google.devtools.build.lib.analysis.config.BuildConfiguration.EmptyToNullLabelConverter;
import com.google.devtools.build.lib.analysis.config.BuildConfiguration.Fragment;
import com.google.devtools.build.lib.analysis.config.BuildConfiguration.LabelConverter;
import com.google.devtools.build.lib.analysis.config.BuildConfiguration.StrictDepsConverter;
import com.google.devtools.build.lib.analysis.config.BuildConfiguration.StrictDepsMode;
import com.google.devtools.build.lib.analysis.config.BuildOptions;
import com.google.devtools.build.lib.analysis.config.ConfigurationEnvironment;
import com.google.devtools.build.lib.analysis.config.ConfigurationFragmentFactory;
import com.google.devtools.build.lib.analysis.config.FragmentOptions;
import com.google.devtools.build.lib.analysis.config.InvalidConfigurationException;
import com.google.devtools.build.lib.cmdline.Label;
import com.google.devtools.build.lib.concurrent.ThreadSafety.Immutable;
import com.google.devtools.build.lib.packages.Attribute.SplitTransition;
import com.google.devtools.common.options.Converter;
import com.google.devtools.common.options.Converters;
import com.google.devtools.common.options.EnumConverter;
import com.google.devtools.common.options.Option;
import com.google.devtools.common.options.OptionsParsingException;

import java.util.List;
import java.util.Set;

/**
 * Configuration fragment for Android rules.
 */
@Immutable
public class AndroidConfiguration extends BuildConfiguration.Fragment {

  /**
   * Converter for {@link com.google.devtools.build.lib.rules.android.AndroidConfiguration.ConfigurationDistinguisher}
   */
  public static final class ConfigurationDistinguisherConverter
      extends EnumConverter<ConfigurationDistinguisher> {
    public ConfigurationDistinguisherConverter() {
      super(ConfigurationDistinguisher.class, "Android configuration distinguisher");
    }
  }

  /**
   * Converter for {@link IncrementalDexing}.
   */
  public static final class IncrementalDexingConverter extends EnumConverter<IncrementalDexing> {
    public IncrementalDexingConverter() {
      super(IncrementalDexing.class, "incremental dexing option");
    }
  }

  /**
   * Converter for a set of {@link AndroidBinaryType}s.
   */
  public static final class AndroidBinaryTypesConverter
      implements Converter<Set<AndroidBinaryType>> {

    private final EnumConverter<AndroidBinaryType> elementConverter =
        new EnumConverter<AndroidBinaryType>(AndroidBinaryType.class, "Android binary type") {};
    private final Splitter splitter = Splitter.on(',').omitEmptyStrings().trimResults();

    public AndroidBinaryTypesConverter() {}

    @Override
    public ImmutableSet<AndroidBinaryType> convert(String input) throws OptionsParsingException {
      if ("all".equals(input)) {
        return ImmutableSet.copyOf(AndroidBinaryType.values());
      }
      ImmutableSet.Builder<AndroidBinaryType> result = ImmutableSet.builder();
      for (String opt : splitter.split(input)) {
        result.add(elementConverter.convert(opt));
      }
      return result.build();
    }

    @Override
    public String getTypeDescription() {
      return "comma-separated list of: " + elementConverter.getTypeDescription();
    }
  }

  /**
   * Converter for {@link AndroidManifestMerger}
   */
  public static final class AndroidManifestMergerConverter
      extends EnumConverter<AndroidManifestMerger> {
    public AndroidManifestMergerConverter() {
      super(AndroidManifestMerger.class, "android manifest merger");
    }
  }

  /**
   * Value used to avoid multiple configurations from conflicting.
   *
   *
This is set to {@code ANDROID} in Android configurations and to {@code MAIN} otherwise. This
   * influences the output directory name: if it didn't, an Android and a non-Android configuration
   * would conflict if they had the same toolchain identifier.
   *
   *
Note that this is not just a theoretical concern: even if {@code --crosstool_top} and
   * {@code --android_crosstool_top} point to different labels, they may end up being redirected to
   * the same thing, and this is exactly what happens on OSX X.
   */
  public enum ConfigurationDistinguisher {
    MAIN(null),
    ANDROID("android");

    private final String suffix;

    private ConfigurationDistinguisher(String suffix) {
      this.suffix = suffix;
    }
  }

  /** Types of android binaries as {@link AndroidBinary#dex} distinguishes them. */
  public enum AndroidBinaryType {
    MONODEX, MULTIDEX_UNSHARDED, MULTIDEX_SHARDED
  }

  /** When to use incremental dexing (using {@link DexArchiveProvider}). */
  private enum IncrementalDexing {
    OFF(),
    WITH_DEX_SHARDS(AndroidBinaryType.MULTIDEX_SHARDED),
    WITH_MULTIDEX(AndroidBinaryType.MULTIDEX_UNSHARDED, AndroidBinaryType.MULTIDEX_SHARDED),
    WITH_MONODEX_OR_DEX_SHARDS(AndroidBinaryType.MONODEX, AndroidBinaryType.MULTIDEX_SHARDED),
    AS_PERMITTED(AndroidBinaryType.values());

    private ImmutableSet<AndroidBinaryType> binaryTypes;

    private IncrementalDexing(AndroidBinaryType... binaryTypes) {
      this.binaryTypes = ImmutableSet.copyOf(binaryTypes);
    }
  }

  /** Types of android manifest mergers. */
  public enum AndroidManifestMerger {
    LEGACY,
    ANDROID;

    public static List<String> getAttributeValues() {
      return ImmutableList.of(LEGACY.name().toLowerCase(), ANDROID.name().toLowerCase(),
          getRuleAttributeDefault());
    }

    public static String getRuleAttributeDefault() {
      return "auto";
    }

    public static AndroidManifestMerger fromString(String value) {
      for (AndroidManifestMerger merger : AndroidManifestMerger.values()) {
        if (merger.name().equalsIgnoreCase(value)) {
          return merger;
        }
      }
      return null;
    }
  }

  /**
   * Android configuration options.
   */
  public static class Options extends FragmentOptions {
    // Spaces make it impossible to specify this on the command line
    @Option(name = "Android configuration distinguisher",
        defaultValue = "MAIN",
        converter = ConfigurationDistinguisherConverter.class,
        category = "undocumented")
    public ConfigurationDistinguisher configurationDistinguisher;

    // For deploying incremental installation of native libraries. Do not use on the command line.
    // The idea is that once this option works, we'll flip the default value in a config file, then
    // once it is proven that it works, remove it from Bazel and said config file.
    @Option(name = "android_incremental_native_libs",
        defaultValue = "false",
        category = "undocumented")
    public boolean incrementalNativeLibs;

    @Option(name = "android_crosstool_top",
        defaultValue = "//external:android/crosstool",
        category = "semantics",
        converter = EmptyToNullLabelConverter.class,
        help = "The location of the C++ compiler used for Android builds.")
    public Label androidCrosstoolTop;

    @Option(name = "android_cpu",
        defaultValue = "armeabi",
        category = "semantics",
        help = "The Android target CPU.")
    public String cpu;

    @Option(
      name = "android_compiler",
      defaultValue = "null",
      category = "semantics",
      help = "The Android target compiler."
    )
    public String cppCompiler;

    @Option(name = "strict_android_deps",
        allowMultiple = false,
        defaultValue = "default",
        converter = StrictDepsConverter.class,
        category = "semantics",
        help = "If true, checks that an Android target explicitly declares all directly used "
            + "targets as dependencies.")
    public StrictDepsMode strictDeps;

    // Label of filegroup combining all Android tools used as implicit dependencies of
    // android_* rules
    @Option(name = "android_sdk",
            defaultValue = "@bazel_tools//tools/android:sdk",
            category = "version",
            converter = LabelConverter.class,
            help = "Specifies Android SDK/platform that is used to build Android applications.")
    public Label sdk;

    @Option(name = "legacy_android_native_support",
        defaultValue = "true",
        category = "semantics",
        help = "Switches back to old native support for android_binaries. Disable to link together "
            + "native deps of android_binaries into a single .so by default.")
    public boolean legacyNativeSupport;

    // TODO(bazel-team): Maybe merge this with --android_cpu above.
    @Option(name = "fat_apk_cpu",
            converter = Converters.CommaSeparatedOptionListConverter.class,
            defaultValue = "armeabi-v7a",
            category = "undocumented",
            help = "Setting this option enables fat APKs, which contain native binaries for all "
                + "specified target architectures, e.g., --fat_apk_cpu=x86,armeabi-v7a. Note that "
                + "you will also at least need to select an Android-compatible crosstool. "
                + "If this flag is specified, then --android_cpu is ignored for dependencies of "
                + "android_binary rules.")
    public List<String> fatApkCpus;

    @Option(name = "experimental_android_use_jack_for_dexing",
        defaultValue = "false",
        category = "semantics",
        help = "Switches to the Jack and Jill toolchain for dexing instead of javac and dx.")
    public boolean useJackForDexing;

    @Option(name = "experimental_android_jack_sanity_checks",
        defaultValue = "false",
        category = "semantics",
        help = "Enables sanity checks for Jack and Jill compilation.")
    public boolean jackSanityChecks;

    @Option(name = "experimental_incremental_dexing",
        defaultValue = "off",
        category = "undocumented",
        converter = IncrementalDexingConverter.class,
        deprecationWarning = "Use --incremental_dexing instead to turn on incremental dexing.",
        help = "Does most of the work for dexing separately for each Jar file.  Incompatible with "
            + "Jack and Jill.")
    public IncrementalDexing dexingStrategy;

    @Option(name = "incremental_dexing",
        defaultValue = "false",
        category = "semantics",
        implicitRequirements = "--noexperimental_android_use_jack_for_dexing",
        help = "Does most of the work for dexing separately for each Jar file.  Incompatible with "
            + "Jack and Jill.")
    public boolean incrementalDexing;

    // Do not use on the command line.
    // The idea is that this option lets us gradually turn on incremental dexing for different
    // binaries.  Users should rely on --noincremental_dexing to turn it off.
    @Option(name = "incremental_dexing_binary_types",
        defaultValue = "multidex_sharded",
        category = "undocumented",
        converter = AndroidBinaryTypesConverter.class,
        implicitRequirements = "--incremental_dexing",
        help = "Kinds of binaries to incrementally dex if --incremental_dexing is true.")
    public Set<AndroidBinaryType> incrementalDexingBinaries;

    @Option(name = "non_incremental_per_target_dexopts",
        converter = Converters.CommaSeparatedOptionListConverter.class,
        defaultValue = "--no-locals",
        category = "semantics",
        help = "dx flags that that prevent incremental dexing for binary targets that list any of "
            + "the flags listed here in their 'dexopts' attribute, which are ignored with "
            + "incremental dexing (superseding --dexopts_supported_in_incremental_dexing).  "
            + "Defaults to --no-locals for safety but can in general be used "
            + "to make sure the listed dx flags are honored, with additional build latency.  "
            + "Please notify us if you find yourself needing this flag.")
    public List<String> nonIncrementalPerTargetDexopts;

    // Do not use on the command line.
    // This flag is intended to be updated as we add supported flags to the incremental dexing tools
    @Option(name = "dexopts_supported_in_incremental_dexing",
        converter = Converters.CommaSeparatedOptionListConverter.class,
        defaultValue = "",
        category = "hidden",
        help = "dx flags supported in incremental dexing.")
    public List<String> dexoptsSupportedInIncrementalDexing;

    @Option(name = "experimental_allow_android_library_deps_without_srcs",
        defaultValue = "true",
        category = "undocumented",
        help = "Flag to help transition from allowing to disallowing srcs-less android_library"
            + " rules with deps. The depot needs to be cleaned up to roll this out by default.")
    public boolean allowAndroidLibraryDepsWithoutSrcs;

    @Option(name = "experimental_android_resource_shrinking",
        defaultValue = "false",
        category = "undocumented",
        help = "Enables resource shrinking for android_binary APKs that use proguard.")
    public boolean useAndroidResourceShrinking;

    // TODO(jimbrooks): Remove this flag after it is removed from the global blazerc.
    @Option(name = "experimental_use_proguard_previous_obfuscation_map",
        defaultValue = "false",
        category = "undocumented",
        help = "Does nothing (obsolete).")
    public boolean useProguardPreviousObfuscationMap;

    @Option(name = "android_manifest_merger",
        defaultValue = "legacy",
        category = "semantics",
        converter = AndroidManifestMergerConverter.class,
        help = "Selects the manifest merger to use for android_binary rules. Flag to help the"
            + "transition to the Android manifest merger from the legacy merger.")
    public AndroidManifestMerger manifestMerger;

    // Do not use on the command line.
    // The idea is that once this option works, we'll flip the default value in a config file, then
    // once it is proven that it works, remove it from Bazel and said config file.
    @Option(name = "experimental_use_rclass_generator",
        defaultValue = "false",
        category = "undocumented",
        help = "Use the specialized R class generator to build the final app and lib R classes.")
    public boolean useRClassGenerator;

    @Override
    public void addAllLabels(Multimap<String, Label> labelMap) {
      if (androidCrosstoolTop != null) {
        labelMap.put("android_crosstool_top", androidCrosstoolTop);
      }

      labelMap.put("android_sdk", sdk);
    }

    @Override
    public FragmentOptions getHost(boolean fallback) {
      Options host = (Options) super.getHost(fallback);
      host.androidCrosstoolTop = androidCrosstoolTop;
      host.sdk = sdk;
      return host;
    }

    @Override
    public ImmutableList<String> getDefaultsRules() {
      return ImmutableList.of("android_tools_defaults_jar(name = 'android_jar')");
    }

    @Override
    public List<SplitTransition<BuildOptions>> getPotentialSplitTransitions() {
      return ImmutableList.of(AndroidRuleClasses.ANDROID_SPLIT_TRANSITION);
    }
  }

  /**
   * Configuration loader for the Android fragment.
   */
  public static class Loader implements ConfigurationFragmentFactory {
    @Override
    public Fragment create(ConfigurationEnvironment env, BuildOptions buildOptions)
        throws InvalidConfigurationException {
      AndroidConfiguration.Options androidOptions =
          buildOptions.get(AndroidConfiguration.Options.class);
      Label androidSdk = RedirectChaser.followRedirects(env, androidOptions.sdk, "android_sdk");
      if (androidSdk == null) {
        return null;
      }
      return new AndroidConfiguration(buildOptions.get(Options.class), androidSdk);
    }

    @Override
    public Class<? extends Fragment> creates() {
      return AndroidConfiguration.class;
    }

    @Override
    public ImmutableSet<Class<? extends FragmentOptions>> requiredOptions() {
      return ImmutableSet.<Class<? extends FragmentOptions>>of(Options.class);
    }
  }

  private final Label sdk;
  private final StrictDepsMode strictDeps;
  private final boolean legacyNativeSupport;
  private final String cpu;
  private final boolean incrementalNativeLibs;
  private final boolean usesAndroidCrosstool;
  private final ConfigurationDistinguisher configurationDistinguisher;
  private final boolean useJackForDexing;
  private final boolean jackSanityChecks;
  private final ImmutableSet<AndroidBinaryType> incrementalDexingBinaries;
  private final ImmutableList<String> dexoptsSupportedInIncrementalDexing;
  private final ImmutableList<String> targetDexoptsThatPreventIncrementalDexing;
  private final boolean allowAndroidLibraryDepsWithoutSrcs;
  private final boolean useAndroidResourceShrinking;
  private final boolean useRClassGenerator;
  private final AndroidManifestMerger manifestMerger;

  AndroidConfiguration(Options options, Label androidSdk) {
    this.sdk = androidSdk;
    this.incrementalNativeLibs = options.incrementalNativeLibs;
    this.strictDeps = options.strictDeps;
    this.legacyNativeSupport = options.legacyNativeSupport;
    this.cpu = options.cpu;
    this.usesAndroidCrosstool = (options.androidCrosstoolTop != null);
    this.configurationDistinguisher = options.configurationDistinguisher;
    this.useJackForDexing = options.useJackForDexing;
    this.jackSanityChecks = options.jackSanityChecks;
    if (options.incrementalDexing) {
      this.incrementalDexingBinaries = ImmutableSet.copyOf(options.incrementalDexingBinaries);
    } else {
      this.incrementalDexingBinaries = options.dexingStrategy.binaryTypes;
    }
    this.dexoptsSupportedInIncrementalDexing =
        ImmutableList.copyOf(options.dexoptsSupportedInIncrementalDexing);
    this.targetDexoptsThatPreventIncrementalDexing =
        ImmutableList.copyOf(options.nonIncrementalPerTargetDexopts);
    this.allowAndroidLibraryDepsWithoutSrcs = options.allowAndroidLibraryDepsWithoutSrcs;
    this.useAndroidResourceShrinking = options.useAndroidResourceShrinking;
    this.useRClassGenerator = options.useRClassGenerator;
    this.manifestMerger = options.manifestMerger;
  }

  public String getCpu() {
    return cpu;
  }

  public Label getSdk() {
    return sdk;
  }

  public boolean getLegacyNativeSupport() {
    return legacyNativeSupport;
  }

  public StrictDepsMode getStrictDeps() {
    return strictDeps;
  }

  public boolean usesAndroidCrosstool() {
    return usesAndroidCrosstool;
  }

  /**
   * Returns true if Jack should be used in place of javac/dx for Android compilation.
   */
  public boolean isJackUsedForDexing() {
    return useJackForDexing;
  }

  /**
   * Returns true if Jack sanity checks should be enabled. Only relevant if isJackUsedForDexing()
   * also returns true.
   */
  public boolean isJackSanityChecked() {
    return jackSanityChecks;
  }

  public boolean useIncrementalNativeLibs() {
    return incrementalNativeLibs;
  }

  /**
   * Returns when to use incremental dexing using {@link DexArchiveProvider}.  Note this is disabled
   * if {@link #isJackUsedForDexing()}.
   */
  public ImmutableSet<AndroidBinaryType> getIncrementalDexingBinaries() {
    return isJackUsedForDexing() ? ImmutableSet.<AndroidBinaryType>of() : incrementalDexingBinaries;
  }

  /**
   * dx flags supported in incremental dexing actions.
   */
  public ImmutableList<String> getDexoptsSupportedInIncrementalDexing() {
    return dexoptsSupportedInIncrementalDexing;
  }

  /**
   * Regardless of {@link #getIncrementalDexingBinaries}, incremental dexing must not be used for
   * binaries that list any of these flags in their {@code dexopts} attribute.
   */
  public ImmutableList<String> getTargetDexoptsThatPreventIncrementalDexing() {
    return targetDexoptsThatPreventIncrementalDexing;
  }

  public boolean allowSrcsLessAndroidLibraryDeps() {
    return allowAndroidLibraryDepsWithoutSrcs;
  }

  public boolean useAndroidResourceShrinking() {
    return useAndroidResourceShrinking;
  }

  public boolean useRClassGenerator() {
    return useRClassGenerator;
  }

  public AndroidManifestMerger getManifestMerger() {
    return manifestMerger;
  }

  @Override
  public void addGlobalMakeVariables(ImmutableMap.Builder<String, String> globalMakeEnvBuilder) {
    globalMakeEnvBuilder.put("ANDROID_CPU", cpu);
  }

  @Override
  public String getOutputDirectoryName() {
    return configurationDistinguisher.suffix;
  }
}


text:
<?php

namespace PDepend\Source\ASTVisitor;

use PDepend\Source\AST\AbstractASTArtifact;

/**
 * Simple test node visitor implementation.
 *
 * @copyright 2008-2013 Manuel Pichler. All rights reserved.
 * @license http://www.opensource.org/licenses/bsd-license.php BSD License
 */
class StubAbstractASTVisitListener extends AbstractASTVisitListener
{
    public $nodes = array();

    public function startVisitNode(AbstractASTArtifact $node)
    {
        $this->nodes[$node->getName() . '#start'] = true;

        parent::startVisitNode($node);
    }

    public function endVisitNode(AbstractASTArtifact $node)
    {
        $this->nodes[$node->getName() . '#end'] = true;

        parent::endVisitNode($node);
    }
}

redpajama_set_name: RedPajamaGithub


text:
package Server;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 Created by ${Ruslan} on 01.02.17.
 */
public class ServerApp {
    private String dirName, way;
    public static void main(String []args){
        int port = 1300;
        try{
//connection
            ServerSocket serverSocket = new ServerSocket(port);
            System.out.println("Waiting for connection...");
            Socket socket = serverSocket.accept();
            System.out.println("We've got connection");
//streams
            InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream();
            DataInputStream in = new DataInputStream(inputStream);
            DataOutputStream out = new DataOutputStream(outputStream);
//variables
            ServerApp app = new ServerApp();
            BufferedReader br = new BufferedReader(new FileReader("ini.txt"));
            app.dirName = br.readLine();
            br.close();
//get root folder list--------------------------------------------------------------------------------------------------
            app.getList(app.dirName, out);
            out.flush();
//----------------------------------------------------------------------------------------------------------------------
            int key;
            while ((key = in.readInt()) != 0){
                if (key == 1){
                    app.way = app.dirName.concat("/").concat(in.readUTF());
                    app.getList(app.way, out);
                    System.out.println(app.way);
                    out.flush();
                }
                if (key == 2){
                    app.getParentList(app.way, out);
                    System.out.println(app.way);
                }
            }
/*
//get child folder list
            app.way = app.dirName.concat("/").concat(in.readUTF());
            app.getList(app.way, out);
            System.out.println(app.way);
            out.flush();*/
/*
//back to parent
            app.getParentList(app.way, out);
            System.out.println(app.way);*/
        }
        catch (Exception e){
            e.printStackTrace();
        }
    }

    private void getList(String folder, DataOutput out) throws IOException {
        File file = new File(folder);
        String []listFiles = file.list();
        if (listFiles != null) {
            way = file.getAbsolutePath();
            out.writeUTF(way);
            String list = listFiles[0];
            if (listFiles.length > 1){
                for (int i = 1; i < listFiles.length; i++) {
                    list = list.concat(" ").concat(listFiles[i]);
                }
            }
            out.writeUTF(list);
        }
        else {
            out.writeInt(0);
        }
    }

    private void getParentList(String folder, DataOutput out) throws IOException {
        File file = new File(folder);
        String []listFiles = file.getParentFile().list();
        if (listFiles != null) {
            way = file.getParentFile().getAbsolutePath();
            out.writeUTF(way);
            String list = listFiles[0];
            if (listFiles.length > 1){
                for (int i = 1; i < listFiles.length; i++) {
                    list = list.concat(" ").concat(listFiles[i]);
                }
            }
            out.writeUTF(list);
        }
        else {
            out.writeInt(0);
        }
    }

    private void downladFile(String folder, DataOutput out) throws IOException {
        File file = new File(folder);
        BufferedReader br = new BufferedReader(new FileReader(file));
        String line;
        while ((line = br.readLine()) != null){
            out.writeUTF(line);
        }
        br.close();
    }

    private void uploadFile(String folder, DataInput in) throws IOException {
        File file = new File(folder);
        BufferedWriter bw = new BufferedWriter(new FileWriter(file));
        String line;
        while ((line = in.readUTF()) != null){
            bw.write(line);
        }
    }
}


text:
import { ShippingTestQueryRawResponse } from "v2/__generated__/ShippingTestQuery.graphql"
import { cloneDeep } from "lodash"

import { RadioGroup } from "@artsy/palette"
import {
  UntouchedBuyOrder,
  UntouchedOfferOrder,
} from "v2/Apps/__tests__/Fixtures/Order"
import {
  fillAddressForm,
  fillIn,
  fillInPhoneNumber,
  validAddress,
} from "v2/Components/__tests__/Utils/addressForm"
import { CountrySelect } from "v2/Components/CountrySelect"
import Input from "v2/Components/Input"
import { Input as paletteInput } from "@artsy/palette"
import { createTestEnv } from "v2/DevTools/createTestEnv"
import { commitMutation as _commitMutation, graphql } from "react-relay"
import {
  settingOrderShipmentFailure,
  settingOrderShipmentMissingCountryFailure,
  settingOrderShipmentMissingRegionFailure,
  settingOrderShipmentSuccess,
} from "../__fixtures__/MutationResults"
import { ShippingFragmentContainer, ShippingRoute } from "../Shipping"
import { OrderAppTestPage } from "./Utils/OrderAppTestPage"
import {
  saveAddressSuccess,
  updateAddressSuccess,
} from "../__fixtures__/MutationResults/saveAddress"

jest.unmock("react-relay")

const testOrder: ShippingTestQueryRawResponse["order"] = {
  ...UntouchedBuyOrder,
  internalID: "1234",
  id: "1234",
}

const pageInfo = {
  startCursor: "aaa",
  endCursor: "bbb",
  hasNextPage: false,
  hasPreviousPage: false,
}

const emptyTestMe: ShippingTestQueryRawResponse["me"] = {
  name: "Test Name",
  email: "test@gmail.com",
  id: "4321",
  addressConnection: {
    edges: [],
    pageInfo,
  },
}

const testMe: ShippingTestQueryRawResponse["me"] = {
  name: "Test Name",
  email: "test@gmail.com",
  id: "4321",
  addressConnection: {
    edges: [
      {
        node: {
          __typename: "UserAddress",
          internalID: "1",
          addressLine1: "1 Main St",
          addressLine2: "",
          addressLine3: "",
          city: "Madrid",
          country: "Spain",
          isDefault: false,
          name: "Test Name",
          phoneNumber: "555-555-5555",
          postalCode: "28001",
          region: "",
          id: "addressID1",
        },
        cursor: "aaa",
      },
      {
        node: {
          __typename: "UserAddress",
          internalID: "2",
          addressLine1: "401 Broadway",
          addressLine2: "Floor 25",
          addressLine3: "",
          city: "New York",
          country: "USA",
          isDefault: true,
          name: "Test Name",
          phoneNumber: "422-424-4242",
          postalCode: "10013",
          region: "NY",
          id: "addressID2",
        },
        cursor: "aaa",
      },
    ],
    pageInfo,
  },
}

class ShippingTestPage extends OrderAppTestPage {
  async selectPickupOption() {
    this.find(`[data-test="pickupOption"]`).last().simulate("click")
    await this.update()
  }
}

describe("Shipping", () => {
  const { mutations, buildPage, routes } = createTestEnv({
    Component: ShippingFragmentContainer,
    defaultData: { order: testOrder, me: emptyTestMe },
    defaultMutationResults: {
      ...settingOrderShipmentSuccess,
      ...saveAddressSuccess,
      ...updateAddressSuccess,
    },
    query: graphql`
      query ShippingTestQuery @raw_response_type {
        order: commerceOrder(id: "unused") {
          ...Shipping_order
        }
        me {
          ...Shipping_me
        }
      }
    `,
    TestPage: ShippingTestPage,
  })
  describe("with no saved addresses", () => {
    it("removes radio group if pickup_available flag is false", async () => {
      const pickupAvailableOrder = cloneDeep(testOrder) as any
      pickupAvailableOrder.lineItems.edges[0].node.artwork.pickup_available = false
      const page = await buildPage({
        mockData: { order: pickupAvailableOrder },
      })
      expect(page.find(RadioGroup).length).toEqual(0)
    })

    it("disables country select when onlyShipsDomestically is true and artwork is not in EU local zone", async () => {
      const domesticShippingOnlyOrder = cloneDeep(testOrder) as any
      domesticShippingOnlyOrder.lineItems.edges[0].node.artwork.onlyShipsDomestically = true
      domesticShippingOnlyOrder.lineItems.edges[0].node.artwork.euShippingOrigin = false
      const page = await buildPage({
        mockData: { order: domesticShippingOnlyOrder },
      })
      expect(page.find(CountrySelect).props().disabled).toBe(true)
    })

    it("does not disable select when onlyShipsDomestically is true but artwork is located in EU local zone", async () => {
      const domesticShippingEUOrder = cloneDeep(testOrder) as any
      domesticShippingEUOrder.lineItems.edges[0].node.artwork.onlyShipsDomestically = true
      domesticShippingEUOrder.lineItems.edges[0].node.artwork.euShippingOrigin = true
      const page = await buildPage({
        mockData: { order: domesticShippingEUOrder },
      })
      expect(page.find(CountrySelect).props().disabled).toBe(false)
    })

    it("commits set shipping mutation with the orderId and save address", async () => {
      const page = await buildPage()

      fillAddressForm(page.root, validAddress)

      expect(mutations.mockFetch).not.toHaveBeenCalled()

      await page.clickSubmit()

      expect(mutations.mockFetch).toHaveBeenCalledTimes(2)
      expect(mutations.mockFetch.mock.calls.map(call => call[0].name)).toEqual([
        "SetShippingMutation",
        "CreateUserAddressMutation",
      ])
      expect(mutations.mockFetch.mock.calls).toMatchSnapshot()
    })

    it("commits the mutation with the orderId when save address is not selected", async () => {
      const page = await buildPage()

      fillAddressForm(page.root, validAddress)

      expect(mutations.mockFetch).not.toHaveBeenCalled()

      page.find(`[data-test="save-address-checkbox"]`).first().simulate("click")

      expect(page.find(ShippingRoute).state().saveAddress).toEqual(false)

      await page.clickSubmit()

      expect(mutations.mockFetch).toHaveBeenCalledTimes(1)
      expect(mutations.lastFetchVariables).toMatchInlineSnapshot(`
              Object {
                "input": Object {
                  "fulfillmentType": "SHIP",
                  "id": "1234",
                  "phoneNumber": "8475937743",
                  "shipping": Object {
                    "addressLine1": "14 Gower's Walk",
                    "addressLine2": "Suite 2.5, The Loom",
                    "city": "Whitechapel",
                    "country": "UK",
                    "name": "Artsy UK Ltd",
                    "phoneNumber": "",
                    "postalCode": "E1 8PY",
                    "region": "London",
                  },
                },
              }
          `)
    })

    it("commits the mutation with shipping option", async () => {
      const page = await buildPage()

      fillAddressForm(page.root, {
        ...validAddress,
        region: "New Brunswick",
        country: "US",
      })

      await page.clickSubmit()
      expect(mutations.mockFetch.mock.calls.map(call => call[1].input))
        .toMatchInlineSnapshot(`
        Array [
          Object {
            "fulfillmentType": "SHIP",
            "id": "1234",
            "phoneNumber": "8475937743",
            "shipping": Object {
              "addressLine1": "14 Gower's Walk",
              "addressLine2": "Suite 2.5, The Loom",
              "city": "Whitechapel",
              "country": "US",
              "name": "Artsy UK Ltd",
              "phoneNumber": "",
              "postalCode": "E1 8PY",
              "region": "New Brunswick",
            },
          },
          Object {
            "attributes": Object {
              "addressLine1": "14 Gower's Walk",
              "addressLine2": "Suite 2.5, The Loom",
              "city": "Whitechapel",
              "country": "US",
              "name": "Artsy UK Ltd",
              "phoneNumber": "8475937743",
              "postalCode": "E1 8PY",
              "region": "New Brunswick",
            },
          },
        ]
      `)
    })

    it("commits the mutation with pickup option", async () => {
      const page = await buildPage()
      await page.selectPickupOption()
      fillInPhoneNumber(page.root, { isPickup: true, value: "2813308004" })
      expect(mutations.mockFetch).not.toHaveBeenCalled()
      await page.clickSubmit()
      expect(mutations.mockFetch).toHaveBeenCalledTimes(1)
      expect(mutations.lastFetchVariables.input.fulfillmentType).toBe("PICKUP")
    })

    describe("mutation", () => {
      let page: ShippingTestPage
      beforeEach(async () => {
        page = await buildPage()
      })

      it("routes to payment screen after mutation completes", async () => {
        fillAddressForm(page.root, validAddress)
        await page.clickSubmit()
        expect(routes.mockPushRoute).toHaveBeenCalledWith(
          "/orders/1234/payment"
        )
      })

      it("shows the button spinner while loading the mutation", async () => {
        fillAddressForm(page.root, validAddress)
        await page.expectButtonSpinnerWhenSubmitting()
      })

      it("shows an error modal when there is an error from the server", async () => {
        mutations.useResultsOnce(settingOrderShipmentFailure)
        fillAddressForm(page.root, validAddress)
        await page.clickSubmit()
        await page.expectAndDismissDefaultErrorDialog()
      })

      it("shows an error modal when there is a network error", async () => {
        fillAddressForm(page.root, validAddress)
        mutations.mockNetworkFailureOnce()
        await page.clickSubmit()
        await page.expectAndDismissDefaultErrorDialog()
      })

      it("shows a validation error modal when there is a missing_country error from the server", async () => {
        mutations.useResultsOnce(settingOrderShipmentMissingCountryFailure)
        fillAddressForm(page.root, validAddress)
        await page.clickSubmit()
        await page.expectAndDismissErrorDialogMatching(
          "Invalid address",
          "There was an error processing your address. Please review and try again."
        )
      })

      it("shows a validation error modal when there is a missing_region error from the server", async () => {
        mutations.useResultsOnce(settingOrderShipmentMissingRegionFailure)
        fillAddressForm(page.root, validAddress)
        await page.clickSubmit()
        await page.expectAndDismissErrorDialogMatching(
          "Invalid address",
          "There was an error processing your address. Please review and try again."
        )
      })
    })

    describe("with previously filled-in data", () => {
      let page: ShippingTestPage
      beforeEach(async () => {
        page = await buildPage({
          mockData: {
            order: {
              ...testOrder,
              requestedFulfillment: {
                ...validAddress,
                __typename: "CommerceShip",
                name: "Dr Collector",
              },
            },
          },
        })
      })

      it("includes already-filled-in data if available", () => {
        const input = page
          .find(Input)
          .filterWhere(wrapper => wrapper.props().title === "Full name")

        expect(input.props().value).toBe("Dr Collector")
      })

      it("includes already-filled-in data in mutation if re-sent", async () => {
        await page.clickSubmit()
        expect(mutations.mockFetch).toBeCalled()
        expect(
          mutations.mockFetch.mock.calls[0][1].input.shipping.name
        ).toEqual("Dr Collector")
        expect(
          mutations.mockFetch.mock.calls[1][1].input.attributes.name
        ).toEqual("Dr Collector")
      })
    })

    describe("Validations", () => {
      let page: ShippingTestPage
      beforeEach(async () => {
        page = await buildPage()
      })

      describe("for Ship orders", () => {
        it("does not submit an empty form for a SHIP order", async () => {
          await page.clickSubmit()
          expect(mutations.mockFetch).not.toBeCalled()
        })

        it("does not submit the mutation with an incomplete form for a SHIP order", async () => {
          fillIn(page.root, { title: "Full name", value: "Air Bud" })
          await page.clickSubmit()
          expect(mutations.mockFetch).not.toBeCalled()
        })

        it("does submit the mutation with a complete form for a SHIP order", async () => {
          fillAddressForm(page.root, validAddress)
          await page.clickSubmit()
          expect(mutations.mockFetch).toBeCalled()
        })

        it("says a required field is required for a SHIP order", async () => {
          await page.clickSubmit()
          const input = page
            .find(Input)
            .filterWhere(wrapper => wrapper.props().title === "Full name")
          expect(input.props().error).toEqual("This field is required")
        })

        it("allows a missing postal code if the selected country is not US or Canada", async () => {
          const address = {
            name: "Erik David",
            addressLine1: "401 Broadway",
            addressLine2: "",
            city: "New York",
            region: "NY",
            postalCode: "",
            phoneNumber: "5555937743",
            country: "AQ",
          }
          fillAddressForm(page.root, address)
          await page.clickSubmit()

          const input = page
            .find(Input)
            .filterWhere(wrapper => wrapper.props().title === "Postal code")
          expect(input.props().error).toBeFalsy()

          expect(mutations.mockFetch).toBeCalled()
        })

        it("before submit, only shows a validation error on inputs that have been touched", async () => {
          fillIn(page.root, { title: "Full name", value: "Erik David" })
          fillIn(page.root, { title: "Address line 1", value: "" })

          await page.update()

          const [addressInput, cityInput] = [
            "Address line 1",
            "City",
          ].map(label =>
            page
              .find(Input)
              .filterWhere(wrapper => wrapper.props().title === label)
          )

          expect(addressInput.props().error).toBeTruthy()
          expect(cityInput.props().error).toBeFalsy()
        })

        it("after submit, shows all validation errors on inputs that have been touched", async () => {
          fillIn(page.root, { title: "Full name", value: "Erik David" })

          await page.clickSubmit()

          const cityInput = page.root
            .find(Input)
            .filterWhere(wrapper => wrapper.props().title === "City")

          expect(cityInput.props().error).toBeTruthy()
        })

        it("does not submit the mutation without a phone number", async () => {
          const address = {
            name: "Erik David",
            addressLine1: "401 Broadway",
            addressLine2: "",
            city: "New York",
            region: "",
            postalCode: "7Z",
            phoneNumber: "",
            country: "AQ",
          }
          fillAddressForm(page.root, address)
          await page.clickSubmit()
          expect(mutations.mockFetch).not.toBeCalled()
        })

        it("allows a missing state/province if the selected country is not US or Canada", async () => {
          const address = {
            name: "Erik David",
            addressLine1: "401 Broadway",
            addressLine2: "",
            city: "New York",
            region: "",
            postalCode: "7Z",
            phoneNumber: "5555937743",
            country: "AQ",
          }
          fillAddressForm(page.root, address)
          await page.clickSubmit()
          expect(mutations.mockFetch).toBeCalled()
        })
      })

      it("does submit the mutation with a non-ship order", async () => {
        await page.selectPickupOption()
        fillInPhoneNumber(page.root, { isPickup: true, value: "2813308004" })
        await page.clickSubmit()
        expect(mutations.mockFetch).toBeCalled()
      })

      it("does not submit the mutation with an incomplete form for a PICKUP order", async () => {
        await page.selectPickupOption()
        await page.clickSubmit()
        expect(mutations.mockFetch).not.toBeCalled()
      })
    })

    describe("Offer-mode orders", () => {
      it("shows an active offer stepper if the order is an Offer Order", async () => {
        const page = await buildPage({
          mockData: {
            order: UntouchedOfferOrder,
          },
        })
        expect(page.orderStepper.text()).toMatchInlineSnapshot(
          `"CheckOfferNavigate rightShippingNavigate rightPaymentNavigate rightReview"`
        )
        expect(page.orderStepperCurrentStep).toBe("Shipping")
      })
    })
  })
  describe("with saved addresses", () => {
    let page
    beforeEach(async () => {
      page = await buildPage({
        mockData: {
          me: testMe,
        },
      })
    })
    it("does not show the new address form", async () => {
      expect(
        page.find(`[data-test="addressFormCollapse"]`).props().open
      ).toEqual(false)
    })
    it("opens the empty pick-up phone number input", async () => {
      await page.selectPickupOption()
      expect(
        page.find(`[data-test="phoneNumberCollapse"]`).props().open
      ).toEqual(true)
      expect(
        page.find(`[data-test="pickupPhoneNumberForm"]`).props().value
      ).toEqual("")
    })

    it("lists the addresses and renders the add address option", async () => {
      expect(
        page
          .find('[role="radio"]')
          .hostNodes()
          .map(node => node.text())
      ).toEqual([
        "Shipping",
        "Arrange for pickup (free)After your order is confirmed, a specialist will contact you within 2 business days to coordinate pickup.",
        "Test Name1 Main StMadrid, Spain, 28001555-555-5555Edit",
        "Test NameDefault401 BroadwayFloor 25New York, NY, USA, 10013422-424-4242Edit",
      ])

      expect(page.text()).toContain(
        "Test Name1 Main StMadrid, Spain, 28001555-555-5555Edit"
      )
      expect(page.text()).toContain(
        "Test NameDefault401 BroadwayFloor 25New York, NY, USA, 10013422-424-4242Edit"
      )
    })

    it("saves the default address selection into state", async () => {
      expect(page.find(ShippingRoute).state().selectedSavedAddress).toEqual("1")
    })
    it("commits the mutation with selected address and phone number", async () => {
      await page.clickSubmit()

      expect(mutations.mockFetch).toHaveBeenCalledTimes(1)
      expect(mutations.lastFetchVariables).toMatchInlineSnapshot(`
        Object {
          "input": Object {
            "fulfillmentType": "SHIP",
            "id": "1234",
            "phoneNumber": "422-424-4242",
            "shipping": Object {
              "addressLine1": "401 Broadway",
              "addressLine2": "Floor 25",
              "city": "New York",
              "country": "USA",
              "name": "Test Name",
              "phoneNumber": "422-424-4242",
              "postalCode": "10013",
              "region": "NY",
            },
          },
        }
      `)
    })
    it("when another saved address is selected commits mutation with selected address and phone number", async () => {
      page.find(`[data-test="savedAddress"]`).first().simulate("click")
      await page.update()
      expect(page.find(ShippingRoute).state().selectedSavedAddress).toEqual("0")
      await page.clickSubmit()

      expect(mutations.mockFetch).toHaveBeenCalledTimes(1)
      expect(mutations.mockFetch.mock.calls[0][0].name).toEqual(
        "SetShippingMutation"
      )
      expect(mutations.lastFetchVariables).toMatchInlineSnapshot(`
        Object {
          "input": Object {
            "fulfillmentType": "SHIP",
            "id": "1234",
            "phoneNumber": "555-555-5555",
            "shipping": Object {
              "addressLine1": "1 Main St",
              "addressLine2": "",
              "city": "Madrid",
              "country": "Spain",
              "name": "Test Name",
              "phoneNumber": "555-555-5555",
              "postalCode": "28001",
              "region": "",
            },
          },
        }
      `)
    })
    describe("editing address", () => {
      it("opens modal with correct title and action properties", async () => {
        await page
          .find(`[data-test="editAddressInShipping"]`)
          .first()
          .simulate("click")
        expect(page.find(ShippingRoute).state().editAddressIndex).toBe(0)
        expect(
          page.find("AddressModal").at(0).props().modalDetails
        ).toStrictEqual({
          addressModalTitle: "Edit address",
          addressModalAction: "editUserAddress",
        })
      })

      it("opens modal with current address values", async () => {
        expect(page.find(ShippingRoute).state().editAddressIndex).toBe(-1)
        await page
          .find(`[data-test="editAddressInShipping"]`)
          .first()
          .simulate("click")
        expect(page.find(ShippingRoute).state().editAddressIndex).toBe(0)

        expect(page.find("AddressModal").length).toBe(1)
        expect(
          page
            .find("AddressModal")
            .find(paletteInput)
            .map(input => input.props().value)
        ).toMatchInlineSnapshot(`
          Array [
            "Test Name",
            "1 Main St",
            "Madrid",
            "28001",
            "",
            "",
            "555-555-5555",
          ]
        `)
      })
      it("sends mutation with updated values when modal form is submitted", async () => {
        page
          .find(`[data-test="editAddressInShipping"]`)
          .first()
          .simulate("click")
        const inputs = page.find("AddressModal").find("input")
        inputs.forEach(input => {
          input.instance().value = `Test input '${input.props().name}'`
          input.simulate("change")
        })
        const countrySelect = page.find("AddressModal").find("select")
        countrySelect.instance().value = `US`
        countrySelect.simulate("change")

        const form = page.find("form").first()
        form.props().onSubmit()

        await page.update()
        expect(mutations.mockFetch.mock.calls[0][1]).toMatchInlineSnapshot(`
          Object {
            "input": Object {
              "attributes": Object {
                "addressLine1": "Test input 'addressLine1'",
                "addressLine2": "Test input 'addressLine2'",
                "addressLine3": "",
                "city": "Test input 'city'",
                "country": "US",
                "name": "Test input 'name'",
                "phoneNumber": "Test input 'phoneNumber'",
                "postalCode": "Test input 'postalCode'",
                "region": "Test input 'region'",
              },
              "userAddressID": "1",
            },
          }
        `)
      })
    })
  })
})


text:
package headfirst.factory.pizzas;

public class PizzaStore {
    SimplePizzaFactory factory;

    public PizzaStore(SimplePizzaFactory factory) {
        this.factory = factory;
    }

    public Pizza orderPizza(String type) {
        Pizza pizza;

        pizza = factory.createPizza(type);

        pizza.prepare();
        pizza.bake();
        pizza.cut();
        pizza.box();

        return pizza;
    }

}


text:
using OneEvil.OneEvilCoinGUI.Windows;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using Image = System.Drawing.Image;

namespace OneEvil.OneEvilCoinGUI
{
    static class Helper
    {
        public static readonly CultureInfo InvariantCulture = CultureInfo.InvariantCulture;
        public static readonly CultureInfo DefaultUiCulture = CultureInfo.InstalledUICulture;

        public static readonly string NewLineString = Environment.NewLine;

        public static string UppercaseFirst(this string input)
        {
            return char.ToUpper(input[0], InvariantCulture) + input.Substring(1);
        }

        public static string ReWrap(this string input)
        {
            return Regex.Replace(input.TrimEnd(), " (\r\n|\n)", " ");
        }

        public static string ToStringReadable(this TimeSpan timeSpan)
        {
            var days = timeSpan.Days;
            if (days > 0) {
                if (days == 1) return "1 " + Properties.Resources.StatusBarSyncTextDaySingular;
                return days + " " + Properties.Resources.StatusBarSyncTextDayPlural;
            }

            var hours = timeSpan.Hours;
            if (hours > 0) {
                if (hours == 1) return "1 " + Properties.Resources.StatusBarSyncTextHourSingular;
                return hours + " " + Properties.Resources.StatusBarSyncTextHourPlural;
            }

            var minutes = timeSpan.Minutes;
            if (minutes == 1) return "1 " + Properties.Resources.StatusBarSyncTextMinuteSingular;
            return minutes + " " + Properties.Resources.StatusBarSyncTextMinutePlural;
        }

        public static void SetFocusedElement(this Control control, FrameworkElement element)
        {
            control.Dispatcher.BeginInvoke(new Action(() => element.Focus()), DispatcherPriority.ContextIdle);
        }

        public static void SetFocusToParent(this Control control)
        {
            control.SetFocusedElement((FrameworkElement)control.Parent);
        }

        public static void SetDefaultFocusedElement(this Control control, FrameworkElement element)
        {
            control.IsVisibleChanged += ((sender, e) => {
                if ((bool)e.NewValue) {
                    control.SetFocusedElement(element);
                }
            });
        }

        public static void SetDefaultFocusToParent(this Control control)
        {
            control.IsVisibleChanged += ((sender, e) => {
                if ((bool)e.NewValue) {
                    control.SetFocusToParent();
                }
            });
        }

        public static void ActivateWindowOrLastChild(this Window window)
        {
            var ownedWindows = window.OwnedWindows;
            if (ownedWindows.Count == 0) {
                if (window.Visibility == Visibility.Visible) window.Activate();

            } else {
                var lastOwnedWindow = ownedWindows[ownedWindows.Count - 1];

                Debug.Assert(lastOwnedWindow != null, "lastOwnedWindow != null");
                lastOwnedWindow.Activate();
            }
        }

        public static ImageSource ToImageSource(this Icon icon)
        {
            return Imaging.CreateBitmapSourceFromHIcon(icon.Handle, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
        }

        public static BitmapImage ToBitmapImage(this Image image, bool isTransparent)
        {
            var bitmapImage = new BitmapImage();
            bitmapImage.BeginInit();

            var stream = new MemoryStream();
            image.Save(stream, isTransparent ? ImageFormat.Png : ImageFormat.Bmp);

            bitmapImage.StreamSource = stream;
            bitmapImage.EndInit();
            return bitmapImage;
        }

        public static Bitmap ToBitmap(this BitmapSource bitmapSource)
        {
            using (var stream = new MemoryStream()) {
                var encoder = new BmpBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(bitmapSource));
                encoder.Save(stream);
                return new Bitmap(stream);
            }
        }

        public static int IndexOfLabel(this IList<SettingsManager.ConfigElementContact> collection, string label)
        {
            for (var i = collection.Count - 1; i >= 0; i--) {
                if (collection[i].Label == label) {
                    return i;
                }
            }

            return -1;
        }

        public static int IndexOfAddress(this IList<SettingsManager.ConfigElementContact> collection, string address)
        {
            for (var i = collection.Count - 1; i >= 0; i--) {
                if (collection[i].Address == address) {
                    return i;
                }
            }

            return -1;
        }

        public static string EncodeUrl(string value)
        {
            if (value == null) {
                return null;
            }

            var length = value.Length;
            var stringBuilder = new StringBuilder(length);

            for (var i = 0; i < length; i++) {
                var ch = value[i];

                if ((ch & 0xff80) == 0) {
                    if (IsUrlSafeChar(ch)) {
                        stringBuilder.Append(ch);
                    } else if (ch == ' ') {
                        stringBuilder.Append("%20");
                    } else {
                        stringBuilder.Append(
                            "%" +
                            IntToHex((ch >> 4) & 0xf) +
                            IntToHex((ch) & 0xf)
                        );
                    }

                } else {
                    // Unicode character encoding
                    stringBuilder.Append(
                        "%u" +
                        IntToHex((ch >> 12) & 0xf) +
                        IntToHex((ch >> 8) & 0xf) +
                        IntToHex((ch >> 4) & 0xf) +
                        IntToHex((ch) & 0xf)
                    );
                }
            }

            return stringBuilder.ToString();
        }

        internal static string DecodeUrl(string value)
        {
            if (value == null) {
                return null;
            }

            var length = value.Length;
            var stringBuilder = new StringBuilder(length);

            // Go through the string's chars collapsing %XX and %uXXXX, and appending each
            // char as char, with exception of %XX constructs that are appended as bytes

            for (var i = 0; i < length; i++) {
                var ch = value[i];

                if (ch == '%' && i < length - 2) {
                    if (value[i + 1] == 'u' && i < length - 5) {
                        var h1 = HexToInt(value[i + 2]);
                        var h2 = HexToInt(value[i + 3]);
                        var h3 = HexToInt(value[i + 4]);
                        var h4 = HexToInt(value[i + 5]);

                        if (h1 >= 0 && h2 >= 0 && h3 >= 0 && h4 >= 0) {
                            // Valid 4 hexadecimal chars
                            i += 5;
                            stringBuilder.Append((char)((h1 << 12) | (h2 << 8) | (h3 << 4) | h4));
                            continue;
                        }

                    } else {
                        var h1 = HexToInt(value[i + 1]);
                        var h2 = HexToInt(value[i + 2]);

                        if (h1 >= 0 && h2 >= 0) {
                            // Valid 2 hexadecimal chars
                            i += 2;
                            stringBuilder.Append((char)((h1 << 4) | h2));
                            continue;
                        }
                    }
                }

                stringBuilder.Append(ch);
            }

            return stringBuilder.ToString();
        }

        private static bool IsUrlSafeChar(char input) {
            if ((input >= 'a' && input <= 'z') || (input >= 'A' && input <= 'Z') || (input >= '0' && input <= '9')) {
                return true;
            }

            switch (input) {
                case '-':
                case '_':
                case '.':
                case '!':
                case '*':
                case '(':
                case ')':
                    return true;
            }

            return false;
        }

        private static char IntToHex(int input) {
            if (input <= 9) return (char)(input + '0');
            return (char)(input - 10 + 'a');
        }

        public static int HexToInt(char h) {
            return (h >= '0' && h <= '9') ? h - '0' :
            (h >= 'a' && h <= 'f') ? h - 'a' + 10 :
            (h >= 'A' && h <= 'F') ? h - 'A' + 10 :
            -1;
        }

        private static string GetPathLastPart(string path)
        {
            var lastSlashIndex = path.LastIndexOf('\\');
            if (lastSlashIndex >= 0) return path.Substring(lastSlashIndex + 1);

            return string.Empty;
        }

        public static string GetDirectoryOfFile(string path)
        {
            var lastSlashIndex = path.LastIndexOf('\\');
            if (lastSlashIndex < 0) return StaticObjects.ApplicationBaseDirectory;

            return path.Substring(0, lastSlashIndex);
        }

        public static string GetRelativePath(string path)
        {
            var uriBase = new Uri(StaticObjects.ApplicationBaseDirectory, UriKind.Absolute);
            var uriPath = new Uri(path);

            var decodedUrl = DecodeUrl(uriBase.MakeRelativeUri(uriPath).ToString());
            return decodedUrl != null ? decodedUrl.Replace('/', '\\') : string.Empty;
        }

        public static string GetFileExtension(string input)
        {
            var fileName = GetPathLastPart(input);
            var firstDotIndex = fileName.IndexOf('.');
            return firstDotIndex >= 0 ? fileName.Substring(firstDotIndex) : string.Empty;
        }

        public static string GetFileNameWithoutExtension(string input)
        {
            var fileName = GetPathLastPart(input);
            var firstDotIndex = fileName.IndexOf('.');
            return firstDotIndex >= 0 ? fileName.Substring(0, firstDotIndex) : fileName;
        }

        public static object GetBoundValue(object value)
        {
            var bindingExpression = value as BindingExpression;
            if (bindingExpression != null) {
                var dataItem = bindingExpression.DataItem;
                var propertyName = bindingExpression.ParentBinding.Path.Path;

                var propertyValue = dataItem.GetType().GetProperty(propertyName).GetValue(dataItem, null);
                return propertyValue;
            }

            return value;
        }

        public static T GetAssemblyAttribute<T>() where T : Attribute
        {
            return (T)Attribute.GetCustomAttribute(StaticObjects.ApplicationAssembly, typeof(T), false);
        }

        public static void ShowInformation(this Window window, string message)
        {
            MessageBoxEx.Show(window, Properties.Resources.TextInformation, message, SystemIcons.Information, Properties.Resources.TextOk);
        }

        public static byte ShowQuestion(this Window window, string message, string title)
        {
            return MessageBoxEx.Show(window, title, message, SystemIcons.Question, Properties.Resources.TextYes, Properties.Resources.TextNo);
        }

        public static void ShowWarning(this Window window, string message)
        {
            MessageBoxEx.Show(window, Properties.Resources.TextWarning, message, SystemIcons.Warning, Properties.Resources.TextOk);
        }

        public static void ShowError(this Window window, string message)
        {
            MessageBoxEx.Show(window, Properties.Resources.TextError, message, SystemIcons.Error, Properties.Resources.TextOk);
        }
    }

    static class NativeMethods
    {
        [DllImport("User32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool ShowWindow(IntPtr hWnd, ShowWindowCommands nCmdShow);

        public enum ShowWindowCommands
        {
            Restore = 9
        }

        public static void RestoreWindowStateFromMinimized(this Window window)
        {
            // Restore the window's state
            if (window.WindowState == WindowState.Minimized) {
                ShowWindow(new WindowInteropHelper(window).Handle, ShowWindowCommands.Restore);
            }

            // Activate the window or its last child
            window.ActivateWindowOrLastChild();
        }

        private const int GWL_STYLE = -16,
                          WS_MAXIMIZEBOX = 0x10000,
                          WS_MINIMIZEBOX = 0x20000;

        [DllImport("User32.dll")]
        private static extern int GetWindowLong(IntPtr hWnd, int index);

        [DllImport("User32.dll")]
        private static extern int SetWindowLong(IntPtr hWnd, int index, int value);

        public static void SetWindowButtons(this Window window, bool isMinimizable, bool isMaximizable)
        {
            var hWnd = new WindowInteropHelper(window).Handle;
            var style = GetWindowLong(hWnd, GWL_STYLE);

            if (isMaximizable) {
                style |= WS_MAXIMIZEBOX;
            } else {
                style &= ~WS_MAXIMIZEBOX;
            }

            if (isMinimizable) {
                style |= WS_MINIMIZEBOX;
            } else {
                style &= ~WS_MINIMIZEBOX;
            }

            SetWindowLong(hWnd, GWL_STYLE, style);
        }

        [DllImport("user32.dll")]
        private static extern IntPtr GetSystemMenu(IntPtr hWnd, [MarshalAs(UnmanagedType.Bool)] bool bRevert);
        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool EnableMenuItem(IntPtr hMenu, uint uIdEnableItem, uint uEnable);

        const uint MF_BYCOMMAND = 0x00000000;
        const uint MF_GRAYED = 0x00000001;
        const uint MF_ENABLED = 0x00000000;

        const uint SC_CLOSE = 0xF060;

        public static void SetWindowButtonClose(this Window window, bool isEnabled)
        {
            var hMenu = GetSystemMenu(new WindowInteropHelper(window).Handle, false);
            if (hMenu != IntPtr.Zero) {
                if (isEnabled) {
                    EnableMenuItem(hMenu, SC_CLOSE, MF_BYCOMMAND | MF_ENABLED);
                } else {
                    EnableMenuItem(hMenu, SC_CLOSE, MF_BYCOMMAND | MF_GRAYED);
                }
            }
        }
    }
}


text:
layout: "enterprise"
page_title: "Authentication Policy - Organizations - Terraform Enterprise"
sidebar_current: "docs-enterprise-organizations-policy"
description: |-
  Owners can set organization-wide authentication policy in Terraform Enterprise.
---

# Set an Organization Authentication Policy

Because organization membership affords members access to potentially sensitive
resources, owners can set organization-wide authentication policy in Terraform
Enterprise.

## Requiring Two-Factor Authentication

Organization owners can require that all organization team members use
[two-factor authentication](/docs/enterprise/user-accounts/authentication.html).
Those that lack two-factor authentication will be locked out of the web
interface until they enable it or leave the organization.

Visit your organization's configuration page to enable this feature. All
organization owners must have two-factor authentication enabled to require the
practice organization-wide. Note: locked-out users are still be able to interact
with Terraform Enterprise using their `ATLAS_TOKEN`.

## Disabling Two-Factor Authentication Requirement

Organization owners can disable the two-factor authentication requirement from
their organization's configuration page. Locked-out team members (those who have
not enabled two-factor authentication) will have their memberships reinstated.


text:
namespace world {
class WORLDAPI_EXPORT BoundingBox {
public:
    BoundingBox();
    BoundingBox(const vec3d &b);
    BoundingBox(const vec3d &b1, const vec3d &b2);

    void reset(const vec3d &b);
    void reset(const vec3d &b1, const vec3d &b2);

    vec3d getLowerBound() const;
    vec3d getUpperBound() const;

    vec3d getDimensions() const;

    bool contains(const vec3d &c) const;

    void translate(const vec3d &vec);
    void addPoint(const vec3d &vec);

private:
    vec3d _lower;
    vec3d _upper;
};
} // namespace world

#endif // WORLD_BOUNDINGBOX_H


text:
"""BIG-IP® Advanced Firewall Manager™ (AFM®) module.

REST URI
    ``http://localhost/mgmt/tm/security/shared-objects``

GUI Path
    ``Security --> Network Address Translation``

REST Kind
    ``tm:security:shared-objects:*``
"""
from distutils.version import LooseVersion
from f5.bigip.resource import Collection
from f5.bigip.resource import OrganizingCollection
from f5.bigip.resource import Resource

class Shared_Objects(OrganizingCollection):
    """BIG-IP® AFM® Nat organizing collection."""

    def __init__(self, security):
        super(Shared_Objects, self).__init__(security)
        self._meta_data['minimum_version'] = '14.0.0'
        self._meta_data['allowed_lazy_attributes'] = [
            Address_Lists,
            Port_Lists]

class Address_Lists(Collection):
    """BIG-IP® AFM® Address List collection"""
    def __init__(self, shared_objects):
        super(Address_Lists, self).__init__(shared_objects)
        self._meta_data['allowed_lazy_attributes'] = [Address_List]
        self._meta_data['attribute_registry'] = \
            {'tm:security:shared-objects:address-list:address-liststate':
                Address_List}

class Address_List(Resource):
    """BIG-IP® Address List resource"""
    def __init__(self, address_lists):
        super(Address_List, self).__init__(address_lists)
        self._meta_data['required_json_kind'] = \
            'tm:security:shared-objects:address-list:address-liststate'
        self._meta_data['required_creation_parameters'].update(('partition',))
        self._meta_data['required_load_parameters'].update(('partition',))
        self.tmos_ver = self._meta_data['bigip'].tmos_version
        if LooseVersion(self.tmos_ver) < LooseVersion('12.0.0'):
            self._meta_data['minimum_additional_parameters'] = {
                'addressLists', 'addresses', 'geo'}
        else:
            self._meta_data['minimum_additional_parameters'] = {
                'addressLists', 'addresses', 'geo', 'fqdns'}

class Port_Lists(Collection):
    """BIG-IP® AFM® Port List collection"""
    def __init__(self, shared_objects):
        super(Port_Lists, self).__init__(shared_objects)
        self._meta_data['allowed_lazy_attributes'] = [Port_List]
        self._meta_data['attribute_registry'] = \
            {'tm:security:shared-objects:port-list:port-liststate':
                Port_List}

class Port_List(Resource):
    """BIG-IP® Port List resource"""
    def __init__(self, port_lists):
        super(Port_List, self).__init__(port_lists)
        self._meta_data['required_json_kind'] = \
            'tm:security:shared-objects:port-list:port-liststate'
        self._meta_data['required_creation_parameters'].update(('partition',))
        self._meta_data['required_load_parameters'].update(('partition',))
        self._meta_data['minimum_additional_parameters'] = {'ports',
                                                            'portLists'}


text:
require 'torch'
require 'nn'

torch.setdefaulttensortype('torch.FloatTensor')

input = torch.Tensor(6,64,96,96)
net = nn.SpatialBatchNormalization(64)
net:evaluate()

output = net:forward(input)

--print(output:size())

torch.save(arg[1], input)
torch.save(arg[2], output)

net:clearState()
torch.save(arg[3], net)


text:
package org.apache.commons.io.input;

import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.Provider;

/**
 * This class is an example for using an {@link ObservableInputStream}. It creates its own
 * {@link org.apache.commons.io.input.ObservableInputStream.Observer}, which calculates a checksum using a
 * MessageDigest, for example an MD5 sum.
 *

 * See the MessageDigest section in the
 *  Java
 * Cryptography Architecture Standard Algorithm Name Documentation for information about standard algorithm names.
 *

 *

 * Note: Neither {@link ObservableInputStream}, nor {@link MessageDigest}, are thread safe. So is
 * {@link MessageDigestCalculatingInputStream}.
 *

 */
public class MessageDigestCalculatingInputStream extends ObservableInputStream {

    /**
     * Maintains the message digest.
     */
    public static class MessageDigestMaintainingObserver extends Observer {
        private final MessageDigest messageDigest;

        /**
         * Creates an MessageDigestMaintainingObserver for the given MessageDigest.
         * @param messageDigest the message digest to use
         */
        public MessageDigestMaintainingObserver(final MessageDigest messageDigest) {
            this.messageDigest = messageDigest;
        }

        @Override
        public void data(final byte[] input, final int offset, final int length) throws IOException {
            messageDigest.update(input, offset, length);
        }

        @Override
        public void data(final int input) throws IOException {
            messageDigest.update((byte) input);
        }
    }

    /**
     * The default message digest algorithm.
     *

     * The MD5 cryptographic algorithm is weak and should not be used.
     *

     */
    private static final String DEFAULT_ALGORITHM = "MD5";

    /**
     * Gets a MessageDigest object that implements the default digest algorithm.
     *
     * @return a Message Digest object that implements the default algorithm.
     * @throws NoSuchAlgorithmException if no Provider supports a MessageDigestSpi implementation.
     * @see Provider
     */
    static MessageDigest getDefaultMessageDigest() throws NoSuchAlgorithmException {
        return MessageDigest.getInstance(DEFAULT_ALGORITHM);
    }

    private final MessageDigest messageDigest;

    /**
     * Creates a new instance, which calculates a signature on the given stream, using a {@link MessageDigest} with the
     * "MD5" algorithm.
     *

     * The MD5 algorithm is weak and should not be used.
     *

     *
     * @param inputStream the stream to calculate the message digest for
     * @throws NoSuchAlgorithmException if no Provider supports a MessageDigestSpi implementation for the specified
     *         algorithm.
     */
    public MessageDigestCalculatingInputStream(final InputStream inputStream) throws NoSuchAlgorithmException {
        this(inputStream, getDefaultMessageDigest());
    }

    /**
     * Creates a new instance, which calculates a signature on the given stream,
     * using the given {@link MessageDigest}.
     * @param inputStream the stream to calculate the message digest for
     * @param messageDigest the message digest to use
     */
    public MessageDigestCalculatingInputStream(final InputStream inputStream, final MessageDigest messageDigest) {
        super(inputStream, new MessageDigestMaintainingObserver(messageDigest));
        this.messageDigest = messageDigest;
    }

    /**
     * Creates a new instance, which calculates a signature on the given stream, using a {@link MessageDigest} with the
     * given algorithm.
     *
     * @param inputStream the stream to calculate the message digest for
     * @param algorithm the name of the algorithm requested. See the MessageDigest section in the
     *
     *        Java Cryptography Architecture Standard Algorithm Name Documentation for information about standard
     *        algorithm names.
     * @throws NoSuchAlgorithmException if no Provider supports a MessageDigestSpi implementation for the specified
     *         algorithm.
     */
    public MessageDigestCalculatingInputStream(final InputStream inputStream, final String algorithm)
        throws NoSuchAlgorithmException {
        this(inputStream, MessageDigest.getInstance(algorithm));
    }

    /**
     * Gets the {@link MessageDigest}, which is being used for generating the
     * checksum.
     *

     * Note: The checksum will only reflect the data, which has been read so far.
     * This is probably not, what you expect. Make sure, that the complete data has been
     * read, if that is what you want. The easiest way to do so is by invoking
     * {@link #consume()}.
     *

     *
     * @return the message digest used
     */
    public MessageDigest getMessageDigest() {
        return messageDigest;
    }
}


text:
source /etc/profile
source ~/.bash_profile

receivers=$1
host=$2
tablename=$3
authorization=$4
projectname=$5
cubename=$6
sh ${KYLIN_HOME}/bin/kylin.sh monitor -receivers ${receivers} -host ${host} -tableName ${tablename} -authorization ${authorization} -cubeName ${cubename} -projectName ${projectname}


text:
#include <aws/medialive/model/ArchiveS3Settings.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

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

namespace Aws
{
namespace MediaLive
{
namespace Model
{

ArchiveS3Settings::ArchiveS3Settings() :
    m_cannedAcl(S3CannedAcl::NOT_SET),
    m_cannedAclHasBeenSet(false)
{
}

ArchiveS3Settings::ArchiveS3Settings(JsonView jsonValue) :
    m_cannedAcl(S3CannedAcl::NOT_SET),
    m_cannedAclHasBeenSet(false)
{
  *this = jsonValue;
}

ArchiveS3Settings& ArchiveS3Settings::operator =(JsonView jsonValue)
{
  if(jsonValue.ValueExists("cannedAcl"))
  {
    m_cannedAcl = S3CannedAclMapper::GetS3CannedAclForName(jsonValue.GetString("cannedAcl"));

    m_cannedAclHasBeenSet = true;
  }

  return *this;
}

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

  if(m_cannedAclHasBeenSet)
  {
   payload.WithString("cannedAcl", S3CannedAclMapper::GetNameForS3CannedAcl(m_cannedAcl));
  }

  return payload;
}

} // namespace Model
} // namespace MediaLive
} // namespace Aws


text:
require 'spec_helper'

describe TimetableEntry do
end


text:
/**
 * Adds an ellipsis or clips the text
 * Options are "ellipsis" or "clip"
 * @see http://www.css3.info/preview/text-overflow/
 */
=text-overflow(!type = "ellipsis")
{
	text-overflow:!type;
	-o-text-overflow:!type;
}


text:
require 'twilio-ruby'

# Get your Account SID and Auth Token from twilio.com/console
# To set up environmental variables, see http://twil.io/secure
account_sid = ENV['TWILIO_ACCOUNT_SID']
auth_token = ENV['TWILIO_AUTH_TOKEN']

@client = Twilio::REST::Client.new(account_sid, auth_token)

# Get an object from its sid. If you do not have a sid,
# check out the list resource examples on this page
@account = @client.api.v2010.accounts(account_sid).fetch

@account.update(status: 'active')

puts @account.status


text:
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * @param {!HTMLElement} element
 * @param {!SingleFileDetailsPanel} singlePanel
 * @param {!MultiFileDetailsPanel} multiPanel
 * @param {!Element} splitter
 * @param {!Element} button
 * @param {!FilesToggleRipple} toggleRipple
 * @constructor
 * @struct
 */
function DetailsContainer(element, singlePanel, multiPanel, splitter, button,
    toggleRipple) {
  /**
   * Container element.
   * @private {!HTMLElement}
   * @const
   */
  this.element_ = element;
  /**
   * Splitter element between the file list and the details panel.
   * @private {!Element}
   * @const
   */
  this.splitter_ = splitter;
  /**
   * "View details" button element.
   * @private {!Element}
   * @const
   */
  this.button_ = button;
  /**
   * Ripple element of "View details" button.
   * @private {!Element}
   * @const
   */
  this.toggleRipple_ = toggleRipple;
  /**
   * Details panel for a single file.
   * @private {!SingleFileDetailsPanel}
   * @const
   */
  this.singlePanel_ = singlePanel;
  /**
   * Details panel for a multiple files.
   * @private {!MultiFileDetailsPanel}
   * @const
   */
  this.multiPanel_ = multiPanel;
  /**
   * @type {boolean}
   */
  this.visible = false;
  /**
   * @private {Array<!FileEntry>}
   */
  this.pendingEntries_ = null;
  this.setVisibility(false);
}

DetailsContainer.prototype.onFileSelectionChanged = function(event) {
  var entries = event.target.selection.entries;
  if (this.visible) {
    this.pendingEntries_ = null;
    this.display_(entries);
  } else {
    this.pendingEntries_ = entries;
  }
};

/**
 * Disply details of entries
 * @param {!Array<!FileEntry>} entries
 */
DetailsContainer.prototype.display_ = function(entries) {
  if (entries.length === 0) {
    this.singlePanel_.removeAttribute('activated');
    this.multiPanel_.removeAttribute('activated');
    // TODO(ryoh): make a panel for empty selection
  } else if (entries.length === 1) {
    this.singlePanel_.setAttribute('activated', '');
    this.multiPanel_.removeAttribute('activated');
    this.singlePanel_.onFileSelectionChanged(entries[0]);
    this.multiPanel_.cancelLoading();
  } else {
    this.singlePanel_.removeAttribute('activated');
    this.multiPanel_.setAttribute('activated', '');
    this.multiPanel_.onFileSelectionChanged(entries);
    this.singlePanel_.cancelLoading();
  }
};

/**
 * Sets the details panel visibility
 * @param {boolean} visibility True if the details panel is visible.
 */
DetailsContainer.prototype.setVisibility = function(visibility) {
  this.visible = visibility;
  if (visibility) {
    this.splitter_.setAttribute('activated', '');
    this.element_.setAttribute('activated', '');
    if (this.pendingEntries_) {
      this.display_(this.pendingEntries_);
    }
  } else {
    this.splitter_.removeAttribute('activated');
    this.element_.removeAttribute('activated');
  }
  this.toggleRipple_.activated = visibility;
  this.singlePanel_.onVisibilityChanged(visibility);
};

/**
 * Sets date and time format.
 * @param {boolean} use12hourClock True if 12 hours clock, False if 24 hours.
 */
DetailsContainer.prototype.setDateTimeFormat = function(use12hourClock) {
  this.singlePanel_.setDateTimeFormat(use12hourClock);
};


text:
package upnp

import (
	"encoding/xml"
	"github.com/ninjasphere/go-sonos/didl"
	_ "log"
)

var (
	ContentDirectory_EventType = registerEventType("ContentDirectory")
)

type ContentDirectoryState struct {
	SystemUpdateID          uint32
	ContainerUpdateIDs      string
	ShareListRefreshState   string
	ShareIndexInProgress    bool
	ShareIndexLastError     string
	UserRadioUpdateID       string
	SavedQueuesUpdateID     string
	ShareListUpdateID       string
	RecentlyPlayedUpdateID  string
	Browseable              bool
	RadioFavoritesUpdateID  uint32
	RadioLocationUpdateID   uint32
	FavoritesUpdateID       string
	FavoritePresetsUpdateID string
}

type ContentDirectoryEvent struct {
	ContentDirectoryState
	Svc *Service
}

func (this ContentDirectoryEvent) Service() *Service {
	return this.Svc
}

func (this ContentDirectoryEvent) Type() int {
	return ContentDirectory_EventType
}

type ContentDirectory struct {
	ContentDirectoryState
	Svc *Service
}

func (this *ContentDirectory) BeginSet(svc *Service, channel chan Event) {
}

type contentDirectoryUpdate_XML struct {
	XMLName xml.Name `xml:"ContentDirectoryState"`
	Value   string   `xml:",innerxml"`
}

func (this *ContentDirectory) HandleProperty(svc *Service, value string, channel chan Event) error {
	update := contentDirectoryUpdate_XML{
		Value: value,
	}
	if bytes, err := xml.Marshal(update); nil != err {
		return err
	} else {
		xml.Unmarshal(bytes, &this.ContentDirectoryState)
	}
	return nil
}

func (this *ContentDirectory) EndSet(svc *Service, channel chan Event) {
	evt := ContentDirectoryEvent{ContentDirectoryState: this.ContentDirectoryState, Svc: svc}
	channel <- evt
}

func (this *ContentDirectory) GetSearchCapabilities() (searchCaps string, err error) {
	type Response struct {
		XMLName    xml.Name
		SearchCaps string
		ErrorResponse
	}
	response := this.Svc.CallVa("GetSearchCapabilities")
	doc := Response{}
	xml.Unmarshal([]byte(response), &doc)
	searchCaps = doc.SearchCaps
	err = doc.Error()
	return
}

func (this *ContentDirectory) GetSortCapabilities() (sortCaps string, err error) {
	type Response struct {
		XMLName  xml.Name
		SortCaps string
		ErrorResponse
	}
	response := this.Svc.CallVa("GetSortCapabilities")
	doc := Response{}
	xml.Unmarshal([]byte(response), &doc)
	sortCaps = doc.SortCaps
	err = doc.Error()
	return
}

func (this *ContentDirectory) GetSystemUpdateID() (id uint32, err error) {
	type Response struct {
		XMLName xml.Name
		Id      uint32
		ErrorResponse
	}
	response := this.Svc.CallVa("GetSystemUpdateID")
	doc := Response{}
	xml.Unmarshal([]byte(response), &doc)
	id = doc.Id
	err = doc.Error()
	return
}

func (this *ContentDirectory) GetAlbumArtistDisplayOption() (albumArtistDisplayOption string, err error) {
	type Response struct {
		XMLName                  xml.Name
		AlbumArtistDisplayOption string
		ErrorResponse
	}
	response := this.Svc.CallVa("GetAlbumArtistDisplayOption")
	doc := Response{}
	xml.Unmarshal([]byte(response), &doc)
	albumArtistDisplayOption = doc.AlbumArtistDisplayOption
	err = doc.Error()
	return
}

func (this *ContentDirectory) GetLastIndexChange() (lastIndexChange string, err error) {
	type Response struct {
		XMLName         xml.Name
		LastIndexChange string
		ErrorResponse
	}
	response := this.Svc.CallVa("GetLastIndexChange")
	doc := Response{}
	xml.Unmarshal([]byte(response), &doc)
	lastIndexChange = doc.LastIndexChange
	err = doc.Error()
	return
}

const (
	BrowseObjectID_Root = "0"
)

const (
	BrowseFlag_BrowseMetadata       = "BrowseMetadata"
	BrowseFlag_BrowseDirectChildren = "BrowseDirectChildren"
)

const (
	BrowseFilter_All = "*"
)

const (
	BrowseSortCriteria_None = ""
)

type BrowseRequest struct {
	ObjectID      string
	BrowseFlag    string
	Filter        string
	StartingIndex uint32
	RequestCount  uint32
	SortCriteria  string
}

type BrowseResult struct {
	NumberReturned int32
	TotalMatches   int32
	UpdateID       int32
	Doc            *didl.Lite
}

func (this *ContentDirectory) Browse(req *BrowseRequest) (browseResult *BrowseResult, err error) {
	type Response struct {
		XMLName xml.Name
		Result  string
		BrowseResult
		ErrorResponse
	}
	args := []Arg{
		{"ObjectID", req.ObjectID},
		{"BrowseFlag", req.BrowseFlag},
		{"Filter", req.Filter},
		{"StartingIndex", req.StartingIndex},
		{"RequestedCount", req.RequestCount},
		{"SortCriteria", req.SortCriteria},
	}
	response := this.Svc.Call("Browse", args)
	doc := Response{}
	xml.Unmarshal([]byte(response), &doc)
	doc.Doc = &didl.Lite{}
	// log.Printf("%s", doc.Result)
	xml.Unmarshal([]byte(doc.Result), doc.Doc)
	browseResult = &doc.BrowseResult
	err = doc.Error()
	return
}

func (this *ContentDirectory) FindPrefix(objectId, prefix string) (startingIndex, updateId uint32, err error) {
	type Response struct {
		XMLName       xml.Name
		StartingIndex uint32
		UpdateID      uint32
		ErrorResponse
	}
	args := []Arg{
		{"ObjectID", objectId},
		{"StartingIndex", startingIndex},
		{"UpdateID", updateId},
	}
	response := this.Svc.Call("FindPrefix", args)
	doc := Response{}
	xml.Unmarshal([]byte(response), &doc)
	startingIndex = doc.StartingIndex
	updateId = doc.UpdateID
	err = doc.Error()
	return
}

type PrefixLocations struct {
	TotalPrefixes     uint32
	PrefixAndIndexCSV string
	UpdateID          uint32
}

func (this *ContentDirectory) GetAllPrefixLocations(objectId string) (prefixLocations *PrefixLocations, err error) {
	type Response struct {
		XMLName xml.Name
		PrefixLocations
		ErrorResponse
	}
	args := []Arg{
		{"ObjectID", objectId},
	}
	response := this.Svc.Call("GetAllPrefixLocations", args)
	doc := Response{}
	xml.Unmarshal([]byte(response), &doc)
	prefixLocations = &doc.PrefixLocations
	err = doc.Error()
	return
}

func (this *ContentDirectory) CreateObject(container, elements string) (objectId, result string, err error) {
	type Response struct {
		XMLName  xml.Name
		ObjectID string
		Result   string
		ErrorResponse
	}
	args := []Arg{
		{"Container", container},
		{"Elements", elements},
	}
	response := this.Svc.Call("CreateObject", args)
	doc := Response{}
	xml.Unmarshal([]byte(response), &doc)
	objectId = doc.ObjectID
	result = doc.Result
	err = doc.Error()
	return
}

func (this *ContentDirectory) UpdateObject(objectId, currentTagValue, newTagValue string) (err error) {
	type Response struct {
		XMLName xml.Name
		ErrorResponse
	}
	args := []Arg{
		{"ObjectID", objectId},
		{"CurrentTagValue", currentTagValue},
		{"NewTagValue", newTagValue},
	}
	response := this.Svc.Call("UpdateObject", args)
	doc := Response{}
	xml.Unmarshal([]byte(response), &doc)
	err = doc.Error()
	return
}

//
// Remove the directory object given by @objectId (e.g. "SQ:11", to
// remove a saved queue). A 701 error is returned if an invalid @objectId
// is specified.
//
func (this *ContentDirectory) DestroyObject(objectId string) error {
	type Response struct {
		XMLName xml.Name
		ErrorResponse
	}
	args := []Arg{
		{"ObjectID", objectId},
	}
	response := this.Svc.Call("DestroyObject", args)
	doc := Response{}
	xml.Unmarshal([]byte(response), &doc)
	return doc.Error()
}

func (this *ContentDirectory) RefreshShareList() (err error) {
	type Response struct {
		XMLName xml.Name
		ErrorResponse
	}
	response := this.Svc.CallVa("RefreshShareList")
	doc := Response{}
	xml.Unmarshal([]byte(response), &doc)
	err = doc.Error()
	return
}

func (this *ContentDirectory) RefreshShareIndex(albumArtistDisplayOption string) (err error) {
	type Response struct {
		XMLName xml.Name
		ErrorResponse
	}
	args := []Arg{
		{"AlbumArtistDisplayOption", albumArtistDisplayOption},
	}
	response := this.Svc.Call("RefreshShareIndex", args)
	doc := Response{}
	xml.Unmarshal([]byte(response), &doc)
	err = doc.Error()
	return
}

func (this *ContentDirectory) RequestResort(sortOrder string) (err error) {
	type Response struct {
		XMLName xml.Name
		ErrorResponse
	}
	args := []Arg{
		{"SortOrder", sortOrder},
	}
	response := this.Svc.Call("RequestResort", args)
	doc := Response{}
	xml.Unmarshal([]byte(response), &doc)
	err = doc.Error()
	return
}

func (this *ContentDirectory) GetShareIndexInProgress() (isIndexing bool, err error) {
	type Response struct {
		XMLName    xml.Name
		IsIndexing bool
		ErrorResponse
	}
	response := this.Svc.CallVa("GetShareIndexInProgress")
	doc := Response{}
	xml.Unmarshal([]byte(response), &doc)
	isIndexing = doc.IsIndexing
	err = doc.Error()
	return
}

func (this *ContentDirectory) GetBrowseable() (isBrowseable bool, err error) {
	type Response struct {
		XMLName      xml.Name
		IsBrowseable bool
		ErrorResponse
	}
	response := this.Svc.CallVa("GetBrowseable")
	doc := Response{}
	xml.Unmarshal([]byte(response), &doc)
	isBrowseable = doc.IsBrowseable
	err = doc.Error()
	return
}

func (this *ContentDirectory) SetBrowseable(browseable bool) (err error) {
	type Response struct {
		XMLName xml.Name
		ErrorResponse
	}
	args := []Arg{
		{"Browseable", browseable},
	}
	response := this.Svc.Call("SetBrowseable", args)
	doc := Response{}
	xml.Unmarshal([]byte(response), &doc)
	err = doc.Error()
	return
}


text:
function PrepQueriesCorpus(NoQueries::Int,QueryFile::String)
    f = open(QueryFile,"r+")
    cnt = 0
    DocCount = 1
    newDoc = true
    Queries = Array(Any,NoQueries)
    for line in eachline(f)
        if length(line) != 1
            if newDoc == true
                Queries[DocCount] = line
                newDoc = false
            elseif newDoc == false
                Queries[DocCount] = join([Queries[DocCount],line]," ")
            end
        elseif length(line) == 1
            cnt=cnt+1
            if cnt == 1
                #println("firstline")
            elseif cnt == 2
                cnt = 0
                DocCount = DocCount +1
                newDoc = true
            end
        end
    end
    m=size(Queries)
    SDArr=Array{Any,1}
    for i=1:m[1]
        SDArr=vcat(SDArr,StringDocument(Queries[i]))
    end
    return Corpus(SDArr[2:m[1]+1])
end

#This function returns a standardized corpus,to the DocType parameter.
#The documents in form of variousl text files are picked from location dirname.

function PrepDocCorpus(dirname::String,DocType::Type)
    crps = DirectoryCorpus(dirname)
    #Standardize all the documents to DocType
    standardize!(crps,DocType)
    return crps
end

#This function does the pre-processing tasks from TextAnalysis.jl

function PreProcess!(crps::Corpus)#,words::Array{String})
    remove_articles!(crps)
    remove_indefinite_articles!(crps)
    remove_definite_articles!(crps)
    remove_pronouns!(crps)
    remove_prepositions!(crps)
    remove_stop_words!(crps)
    #remove_words!(crps,words)
end

#The following functions prepares the Test data

function PrepTest(path::ASCIIString)
    temp=readdlm(path,' ';has_header=false)
    T=hcat(temp[:,1],temp[:,4])
    return T
end

function PrepTest()
    temp=readdlm("./test/data/Test.txt",' ';has_header=false)
    #temp=readdlm("./Test.txt",' ';has_header=false)
    T=hcat(temp[:,1],temp[:,4])
    return T
end


text:
"""Unit test for roman81.py

This program is part of "Dive Into Python", a free Python book for
experienced programmers.  Visit http://diveintopython.org/ for the
latest version.
"""

__author__ = "Mark Pilgrim (mark@diveintopython.org)"
__version__ = "$Revision: 1.3 $"
__date__ = "$Date: 2004/05/05 21:57:20 $"
__copyright__ = "Copyright (c) 2001 Mark Pilgrim"
__license__ = "Python"

import roman81
import unittest

class KnownValues(unittest.TestCase):
    knownValues = ( (1, 'I'),
                    (2, 'II'),
                    (3, 'III'),
                    (4, 'IV'),
                    (5, 'V'),
                    (6, 'VI'),
                    (7, 'VII'),
                    (8, 'VIII'),
                    (9, 'IX'),
                    (10, 'X'),
                    (50, 'L'),
                    (100, 'C'),
                    (500, 'D'),
                    (1000, 'M'),
                    (31, 'XXXI'),
                    (148, 'CXLVIII'),
                    (294, 'CCXCIV'),
                    (312, 'CCCXII'),
                    (421, 'CDXXI'),
                    (528, 'DXXVIII'),
                    (621, 'DCXXI'),
                    (782, 'DCCLXXXII'),
                    (870, 'DCCCLXX'),
                    (941, 'CMXLI'),
                    (1043, 'MXLIII'),
                    (1110, 'MCX'),
                    (1226, 'MCCXXVI'),
                    (1301, 'MCCCI'),
                    (1485, 'MCDLXXXV'),
                    (1509, 'MDIX'),
                    (1607, 'MDCVII'),
                    (1754, 'MDCCLIV'),
                    (1832, 'MDCCCXXXII'),
                    (1993, 'MCMXCIII'),
                    (2074, 'MMLXXIV'),
                    (2152, 'MMCLII'),
                    (2212, 'MMCCXII'),
                    (2343, 'MMCCCXLIII'),
                    (2499, 'MMCDXCIX'),
                    (2574, 'MMDLXXIV'),
                    (2646, 'MMDCXLVI'),
                    (2723, 'MMDCCXXIII'),
                    (2892, 'MMDCCCXCII'),
                    (2975, 'MMCMLXXV'),
                    (3051, 'MMMLI'),
                    (3185, 'MMMCLXXXV'),
                    (3250, 'MMMCCL'),
                    (3313, 'MMMCCCXIII'),
                    (3408, 'MMMCDVIII'),
                    (3501, 'MMMDI'),
                    (3610, 'MMMDCX'),
                    (3743, 'MMMDCCXLIII'),
                    (3844, 'MMMDCCCXLIV'),
                    (3888, 'MMMDCCCLXXXVIII'),
                    (3940, 'MMMCMXL'),
                    (3999, 'MMMCMXCIX'),
                    (4000, 'MMMM'),
                    (4500, 'MMMMD'),
                    (4888, 'MMMMDCCCLXXXVIII'),
                    (4999, 'MMMMCMXCIX'))

    def testToRomanKnownValues(self):
        """toRoman should give known result with known input"""
        for integer, numeral in self.knownValues:
            result = roman81.toRoman(integer)
            self.assertEqual(numeral, result)

    def testFromRomanKnownValues(self):
        """fromRoman should give known result with known input"""
        for integer, numeral in self.knownValues:
            result = roman81.fromRoman(numeral)
            self.assertEqual(integer, result)

class ToRomanBadInput(unittest.TestCase):
    def testTooLarge(self):
        """toRoman should fail with large input"""
        self.assertRaises(roman81.OutOfRangeError, roman81.toRoman, 5000)

    def testZero(self):
        """toRoman should fail with 0 input"""
        self.assertRaises(roman81.OutOfRangeError, roman81.toRoman, 0)

    def testNegative(self):
        """toRoman should fail with negative input"""
        self.assertRaises(roman81.OutOfRangeError, roman81.toRoman, -1)

    def testNonInteger(self):
        """toRoman should fail with non-integer input"""
        self.assertRaises(roman81.NotIntegerError, roman81.toRoman, 0.5)

class FromRomanBadInput(unittest.TestCase):
    def testTooManyRepeatedNumerals(self):
        """fromRoman should fail with too many repeated numerals"""
        for s in ('MMMMM', 'DD', 'CCCC', 'LL', 'XXXX', 'VV', 'IIII'):
            self.assertRaises(roman81.InvalidRomanNumeralError, roman81.fromRoman, s)

    def testRepeatedPairs(self):
        """fromRoman should fail with repeated pairs of numerals"""
        for s in ('CMCM', 'CDCD', 'XCXC', 'XLXL', 'IXIX', 'IVIV'):
            self.assertRaises(roman81.InvalidRomanNumeralError, roman81.fromRoman, s)

    def testMalformedAntecedent(self):
        """fromRoman should fail with malformed antecedents"""
        for s in ('IIMXCC', 'VX', 'DCM', 'CMM', 'IXIV',
                  'MCMC', 'XCX', 'IVI', 'LM', 'LD', 'LC'):
            self.assertRaises(roman81.InvalidRomanNumeralError, roman81.fromRoman, s)

    def testBlank(self):
        """fromRoman should fail with blank string"""
        self.assertRaises(roman81.InvalidRomanNumeralError, roman81.fromRoman, "")

class SanityCheck(unittest.TestCase):
    def testSanity(self):
        """fromRoman(toRoman(n))==n for all n"""
        for integer in range(1, 5000):
            numeral = roman81.toRoman(integer)
            result = roman81.fromRoman(numeral)
            self.assertEqual(integer, result)

class CaseCheck(unittest.TestCase):
    def testToRomanCase(self):
        """toRoman should always return uppercase"""
        for integer in range(1, 5000):
            numeral = roman81.toRoman(integer)
            self.assertEqual(numeral, numeral.upper())

    def testFromRomanCase(self):
        """fromRoman should only accept uppercase input"""
        for integer in range(1, 5000):
            numeral = roman81.toRoman(integer)
            roman81.fromRoman(numeral.upper())
            self.assertRaises(roman81.InvalidRomanNumeralError,
                              roman81.fromRoman, numeral.lower())

if __name__ == "__main__":
    unittest.main()


text:
import _ from 'underscore';

import { menu } from '../../../ui-utils';

window.addEventListener('resize', _.debounce((() => {
	let lastState = window.matchMedia('(min-width: 780px)').matches ? 'mini' : 'large';
	menu.close();
	return () => {
		const futureState = window.matchMedia('(min-width: 780px)').matches ? 'mini' : 'large';
		if (lastState !== futureState) {
			lastState = futureState;
			menu.close();
		}
	};
})(), 100));


text:
class OtherWorker
  include SneakersPacker::CommonWorker

  from_queue "demo.other", routing_key: "demo.suprise"

  def call(data)
    logger.info "data is #{data.inspect}"
  end
end


text:
<md-toolbar md-scroll-shrink class="md-hue-2">

Organization Configuration

</md-toolbar>
<md-content layout-padding>
    <form>
        <md-content layout-gt-sm="column">
            <input ng-hide="true" ng-model="organization.id" value="{{organization.id}}" />
            <md-input-container class="md-block">
                <input ng-model="organization.name" value="{{organization.name}}" type="text" required placeholder="Name" id="reginput" />
            </md-input-container>
            <md-input-container class="md-block">
                <input ng-model="organization.address" value="{{organization.address}}" type="text" required placeholder="Address" id="reginput" />
            </md-input-container>
            <md-input-container class="md-block">
                <input ng-model="organization.email" value="{{organization.email}}" type="email" placeholder="Email" required id="reginput" />
            </md-input-container>
            <md-input-container class="md-block">
                TimeZone
                <md-select ng-model="organization.timezone" id="reginput">
                    <md-option ng-repeat="timezone in TimeZones">
                        {{timezone.text}}
                    </md-option>
                </md-select>
            </md-input-container>

                <md-button type="submit" class="md-raised md-primary" ng-show="organization.id==null" ng-click="setOrgDetail()">Submit</md-button>

                <md-button type="submit" class="md-raised md-primary" ng-show="organization.id!=null" ng-click="EditOrgDetail()">Submit</md-button>

        </md-content>
    </form>
</md-content>