text:
"""Tests for the CacheDataset serialization."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import os

from absl.testing import parameterized

from tensorflow.python.data.experimental.kernel_tests.serialization import dataset_serialization_test_base
from tensorflow.python.data.ops import dataset_ops
from tensorflow.python.framework import errors
from tensorflow.python.platform import test

class CacheDatasetSerializationTest(
    dataset_serialization_test_base.DatasetSerializationTestBase,
    parameterized.TestCase):

  def setUp(self):
    self.range_size = 10
    self.num_repeats = 3
    self.num_outputs = self.range_size * self.num_repeats
    self.cache_file_prefix = 'test'

  def make_dataset_fn(self, is_memory):
    if is_memory:
      filename = ''
    else:
      filename = os.path.join(self.get_temp_dir(), self.cache_file_prefix)

    def ds_fn():
      return dataset_ops.Dataset.range(self.range_size).cache(filename).repeat(
          self.num_repeats)

    return ds_fn

  def expected_outputs(self):
    return list(range(self.range_size)) * self.num_repeats

  @parameterized.named_parameters(
      ('Memory', True),
      ('File', False),
  )
  def testCheckpointBeforeOneEpoch(self, is_memory):
    ds_fn = self.make_dataset_fn(is_memory)

    # Generate 5 entries from iterator and save checkpoint.
    outputs = self.gen_outputs(ds_fn, [], 5, verify_exhausted=False)
    self.assertSequenceEqual(outputs, range(5))

    # Restore from checkpoint and produce the rest of the elements from the
    # iterator.
    outputs.extend(
        self.gen_outputs(
            ds_fn, [],
            self.num_outputs - 5,
            ckpt_saved=True,
            verify_exhausted=False))
    self.assertSequenceEqual(outputs, self.expected_outputs())

  @parameterized.named_parameters(
      ('Memory', True),
      ('File', False),
  )
  def testCheckpointBeforeOneEpochThenRunFewSteps(self, is_memory):
    ds_fn = self.make_dataset_fn(is_memory)

    # Generate 8 entries from iterator but save checkpoint after producing 5.
    outputs = self.gen_outputs(
        ds_fn, [5], 8, verify_exhausted=False, save_checkpoint_at_end=False)
    self.assertSequenceEqual(outputs, range(8))

    if is_memory:
      outputs = outputs[:5]
      outputs.extend(
          self.gen_outputs(
              ds_fn, [],
              self.num_outputs - 5,
              ckpt_saved=True,
              verify_exhausted=False))
      self.assertSequenceEqual(outputs, self.expected_outputs())
    else:
      # Restoring from checkpoint and running GetNext should return
      # `AlreadExistsError` now because the lockfile already exists.
      with self.assertRaises(errors.AlreadyExistsError):
        self.gen_outputs(
            ds_fn, [],
            self.num_outputs - 5,
            ckpt_saved=True,
            verify_exhausted=False)

  @parameterized.named_parameters(
      ('Memory', True),
      ('File', False),
  )
  def testCheckpointAfterOneEpoch(self, is_memory):
    ds_fn = self.make_dataset_fn(is_memory)

    # Generate 15 entries from iterator and save checkpoint.
    outputs = self.gen_outputs(ds_fn, [], 15, verify_exhausted=False)
    self.assertSequenceEqual(outputs, list(range(10)) + list(range(5)))

    # Restore from checkpoint and produce the rest of the elements from the
    # iterator.
    outputs.extend(
        self.gen_outputs(
            ds_fn, [],
            self.num_outputs - 15,
            ckpt_saved=True,
            verify_exhausted=False))
    self.assertSequenceEqual(outputs, self.expected_outputs())

  @parameterized.named_parameters(
      ('Memory', True),
      ('File', False),
  )
  def testCheckpointAfterOneEpochThenRunFewSteps(self, is_memory):
    ds_fn = self.make_dataset_fn(is_memory)

    # Generate 18 entries from iterator but save checkpoint after producing 15.
    outputs = self.gen_outputs(
        ds_fn, [15], 18, verify_exhausted=False, save_checkpoint_at_end=False)
    self.assertSequenceEqual(outputs, list(range(10)) + list(range(8)))

    outputs = list(range(10)) + list(range(5)) + self.gen_outputs(
        ds_fn, [],
        self.num_outputs - 15,
        ckpt_saved=True,
        verify_exhausted=False)
    self.assertSequenceEqual(outputs, list(range(10)) * 3)

  @parameterized.named_parameters(
      ('Memory', True),
      ('File', False),
  )
  def testCheckpointBeforeOneEpochButRunCompleteEpoch(self, is_memory):
    ds_fn = self.make_dataset_fn(is_memory)

    # Generate 13 entries from iterator but save checkpoint after producing 5.
    outputs = self.gen_outputs(
        ds_fn, [5], 13, verify_exhausted=False, save_checkpoint_at_end=False)
    self.assertSequenceEqual(outputs, list(range(10)) + list(range(3)))

    # Since we ran for more than one epoch, the cache was completely written.
    # The ckpt was saved when the iterator was in cache-write mode. Test that
    # the iterator falls back to read mode after restoring if the cache has
    # been completely written.

    outputs = list(range(5)) + self.gen_outputs(
        ds_fn, [],
        self.num_outputs - 5,
        ckpt_saved=True,
        verify_exhausted=False)
    self.assertSequenceEqual(outputs, list(range(10)) * 3)

  @parameterized.named_parameters(
      ('Memory', True),
      ('File', False),
  )
  def testCheckpointUnusedWriterIterator(self, is_memory):
    ds_fn = self.make_dataset_fn(is_memory)

    # Checkpoint before get_next is called even once.
    outputs = self.gen_outputs(ds_fn, [], 0, verify_exhausted=False)
    self.assertSequenceEqual(outputs, [])

    outputs = self.gen_outputs(
        ds_fn, [], self.num_outputs, ckpt_saved=True, verify_exhausted=False)
    self.assertSequenceEqual(outputs, list(range(10)) * 3)

  @parameterized.named_parameters(
      ('Memory', True),
      ('File', False),
  )
  def testCheckpointUnusedMidwayWriterIterator(self, is_memory):
    ds_fn = self.make_dataset_fn(is_memory)

    # Produce 5 elements and checkpoint.
    outputs = self.gen_outputs(ds_fn, [], 5, verify_exhausted=False)
    self.assertSequenceEqual(outputs, range(5))

    # Restore from checkpoint, then produce no elements and checkpoint.
    outputs.extend(
        self.gen_outputs(ds_fn, [], 0, ckpt_saved=True, verify_exhausted=False))
    self.assertSequenceEqual(outputs, range(5))

    # Restore from checkpoint and produce rest of the elements.
    outputs.extend(
        self.gen_outputs(
            ds_fn, [],
            self.num_outputs - 5,
            ckpt_saved=True,
            verify_exhausted=False))
    self.assertSequenceEqual(outputs, list(range(10)) * 3)

  @parameterized.named_parameters(
      ('Memory', True),
      ('File', False),
  )
  def testUnusedCheckpointError(self, is_memory):
    ds_fn = self.make_dataset_fn(is_memory)

    # Produce 5 elements and save ckpt.
    outputs = self.gen_outputs(ds_fn, [], 5, verify_exhausted=False)
    self.assertSequenceEqual(outputs, range(5))

    if is_memory:
      outputs = self.gen_outputs(
          ds_fn, [], self.num_outputs, verify_exhausted=False)
      self.assertSequenceEqual(outputs, self.expected_outputs())
    else:
      # Since the complete cache has not been written, a new iterator which does
      # not restore the checkpoint will throw an error since there is a partial
      # cache shard.
      with self.assertRaises(errors.AlreadyExistsError):
        outputs = self.gen_outputs(
            ds_fn, [], self.num_outputs, verify_exhausted=False)

  @parameterized.named_parameters(
      ('Memory', True),
      ('File', False),
  )
  def testIgnoreCheckpointIfCacheWritten(self, is_memory):
    ds_fn = self.make_dataset_fn(is_memory)

    # Produce 15 elements and save ckpt. This will write the complete cache.
    outputs = self.gen_outputs(ds_fn, [], 15, verify_exhausted=False)
    self.assertSequenceEqual(outputs, list(range(10)) + list(range(5)))

    # Build the iterator again but do not restore from ckpt. Since the cache
    # has already been written we should be able to use it.
    outputs = self.gen_outputs(
        ds_fn, [], self.num_outputs, verify_exhausted=False)
    self.assertSequenceEqual(outputs, list(range(10)) * 3)

if __name__ == '__main__':
  test.main()


text:
"""Store custom methods for wrapper class of IOpticalSystemTools Interface, which
   contains methods to run various system-wide tools.
   name := repr(zos_obj).split()[0].split('.')[-1].lower() + '_methods.py'
"""
from __future__ import print_function
from __future__ import division
from win32com.client import CastTo as _CastTo, constants as _constants
from pyzos.zosutils import wrapped_zos_object as _wrapped_zos_object

# Overridden methods
# ------------------
def OpenLocalOptimization(self):
    local_opt = self._iopticalsystemtools.OpenLocalOptimization()
    if local_opt: # local_opt is None if the Local Optimization Tool is already open
        return _wrapped_zos_object(local_opt)

redpajama_set_name: RedPajamaGithub


text:
package org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity;

import org.apache.hadoop.classification.VisibleForTesting;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.hadoop.util.Lists;
import static org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.CapacitySchedulerConfiguration.AUTO_QUEUE_CREATION_V2_PREFIX;
import static org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.CapacitySchedulerConfiguration.ROOT;
import static org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.CapacitySchedulerConfiguration.getQueuePrefix;

/**
 * A handler for storing and setting auto created queue template settings.
 */
public class AutoCreatedQueueTemplate {
  public static final String AUTO_QUEUE_TEMPLATE_PREFIX =
      AUTO_QUEUE_CREATION_V2_PREFIX + "template.";
  public static final String AUTO_QUEUE_LEAF_TEMPLATE_PREFIX =
      AUTO_QUEUE_CREATION_V2_PREFIX + "leaf-template.";
  public static final String AUTO_QUEUE_PARENT_TEMPLATE_PREFIX =
      AUTO_QUEUE_CREATION_V2_PREFIX + "parent-template.";

  private static final String WILDCARD_QUEUE = "*";
  private static final int MAX_WILDCARD_LEVEL = 1;

  private final Map<String, String> templateProperties = new HashMap<>();
  private final Map<String, String> leafOnlyProperties = new HashMap<>();
  private final Map<String, String> parentOnlyProperties = new HashMap<>();

  public AutoCreatedQueueTemplate(CapacitySchedulerConfiguration configuration,
                                  QueuePath queuePath) {
    setTemplateConfigEntries(configuration, queuePath);
  }

  @VisibleForTesting
  public static String getAutoQueueTemplatePrefix(String queue) {
    return CapacitySchedulerConfiguration.getQueuePrefix(queue)
        + AUTO_QUEUE_TEMPLATE_PREFIX;
  }

  /**
   * Get the common template properties specified for a parent queue.
   * @return template property names and values
   */
  public Map<String, String> getTemplateProperties() {
    return templateProperties;
  }

  /**
   * Get the leaf specific template properties specified for a parent queue.
   * @return template property names and values
   */
  public Map<String, String> getLeafOnlyProperties() {
    return leafOnlyProperties;
  }

  /**
   * Get the parent specific template properties specified for a parent queue.
   * @return template property names and values
   */
  public Map<String, String> getParentOnlyProperties() {
    return parentOnlyProperties;
  }

  /**
   * Sets the common template properties and parent specific template
   * properties of a child queue based on its parent template settings.
 * @param conf configuration to set
   * @param childQueuePath child queue path used for prefixing the properties
   */
  public void setTemplateEntriesForChild(CapacitySchedulerConfiguration conf,
                                         String childQueuePath) {
    setTemplateEntriesForChild(conf, childQueuePath, false);
  }

  /**
   * Sets the common template properties and leaf or parent specific template
   * properties of a child queue based on its parent template settings.
   * template settings.
   * @param conf configuration to set
   * @param isLeaf whether to include leaf specific template properties, or
   *               parent specific template properties
   * @param childQueuePath child queue path used for prefixing the properties
   */
  public void setTemplateEntriesForChild(CapacitySchedulerConfiguration conf,
                                         String childQueuePath,
                                         boolean isLeaf) {
    if (childQueuePath.equals(ROOT)) {
      return;
    }

    ConfigurationProperties configurationProperties =
        conf.getConfigurationProperties();

    // Get all properties that are explicitly set
    Set<String> alreadySetProps = configurationProperties
        .getPropertiesWithPrefix(CapacitySchedulerConfiguration
            .getQueuePrefix(childQueuePath)).keySet();

    // Check template properties only set for leaf or parent queues
    Map<String, String> queueTypeSpecificTemplates = parentOnlyProperties;
    if (isLeaf) {
      queueTypeSpecificTemplates = leafOnlyProperties;
    }

    for (Map.Entry<String, String> entry :
        queueTypeSpecificTemplates.entrySet()) {
      // Do not overwrite explicitly configured properties
      if (alreadySetProps.contains(entry.getKey())) {
        continue;
      }
      conf.set(CapacitySchedulerConfiguration.getQueuePrefix(
          childQueuePath) + entry.getKey(), entry.getValue());
    }

    for (Map.Entry<String, String> entry : templateProperties.entrySet()) {
      // Do not overwrite explicitly configured properties or properties set
      // by queue type specific templates (parent-template and leaf-template)
      if (alreadySetProps.contains(entry.getKey())
          || queueTypeSpecificTemplates.containsKey(entry.getKey())) {
        continue;
      }
      conf.set(CapacitySchedulerConfiguration.getQueuePrefix(
          childQueuePath) + entry.getKey(), entry.getValue());
    }
  }

  /**
   * Store the template configuration properties. Explicit templates always take
   * precedence over wildcard values. An example template precedence
   * hierarchy for root.a ParentQueue from highest to lowest:
   * yarn.scheduler.capacity.root.a.auto-queue-creation-v2.template.capacity
   * yarn.scheduler.capacity.root.*.auto-queue-creation-v2.template.capacity
   */
  private void setTemplateConfigEntries(CapacitySchedulerConfiguration configuration,
                                        QueuePath queuePath) {
    ConfigurationProperties configurationProperties =
        configuration.getConfigurationProperties();

    List<String> queuePathParts = Lists.newArrayList(queuePath.iterator());

    if (queuePathParts.size() <= 1 && !queuePath.isRoot()) {
      // This is an invalid queue path
      return;
    }
    int queuePathMaxIndex = queuePathParts.size() - 1;

    // start with the most explicit format (without wildcard)
    int wildcardLevel = 0;
    // root can not be wildcarded
    // MAX_WILDCARD_LEVEL will be configurable in the future
    int supportedWildcardLevel = Math.min(queuePathMaxIndex, MAX_WILDCARD_LEVEL);
    // Allow root to have template properties
    if (queuePath.isRoot()) {
      supportedWildcardLevel = 0;
    }

    // Collect all template entries
    while (wildcardLevel <= supportedWildcardLevel) {
      String templateQueuePath = String.join(".", queuePathParts);
      // Get all configuration entries with
      // yarn.scheduler.capacity.<queuePath> prefix
      Map<String, String> queueProps = configurationProperties
          .getPropertiesWithPrefix(getQueuePrefix(templateQueuePath));

      // Store template, parent-template and leaf-template properties
      for (Map.Entry<String, String> entry : queueProps.entrySet()) {
        storeConfiguredTemplates(entry.getKey(), entry.getValue());
      }

      // Replace a queue part with a wildcard based on the wildcard level
      // eg. root.a -> root.*
      int queuePartToWildcard = queuePathMaxIndex - wildcardLevel;
      queuePathParts.set(queuePartToWildcard, WILDCARD_QUEUE);

      ++wildcardLevel;
    }
  }

  private void storeConfiguredTemplates(
      String templateKey, String templateValue) {
    String prefix = "";
    Map<String, String> properties = templateProperties;

    if (templateKey.startsWith(AUTO_QUEUE_TEMPLATE_PREFIX)) {
      prefix = AUTO_QUEUE_TEMPLATE_PREFIX;
    } else if (templateKey.startsWith(AUTO_QUEUE_LEAF_TEMPLATE_PREFIX)) {
      prefix = AUTO_QUEUE_LEAF_TEMPLATE_PREFIX;
      properties = leafOnlyProperties;
    } else if (templateKey.startsWith(
        AUTO_QUEUE_PARENT_TEMPLATE_PREFIX)) {
      prefix = AUTO_QUEUE_PARENT_TEMPLATE_PREFIX;
      properties = parentOnlyProperties;
    }

    if (!prefix.isEmpty()) {
      // Trim template prefix from key
      String key = templateKey.substring(prefix.length());
      // If an entry is already present, it had a higher precedence
      properties.putIfAbsent(key, templateValue);
    }
  }
}


text:
<!DOCTYPE html>

		<meta charset="utf-8">
		<title>MEST INCUBATOR</title>
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<meta name="description" content="">
		<meta name="author" content="">

		<link href="../scripts/bootstrap/css/bootstrap.css" rel="stylesheet">
		<link href="../scripts/bootstrap/css/bootstrap-responsive.css" rel="stylesheet">
		<link href="../scripts/css/newHome.css" rel="stylesheet" type="text/css">
		<link rel="stylesheet" type="text/css" href="../scripts/css/mentorcaption.css">

						<button type="button" class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">

						</button>
						MEST MENTOR PLATFORM

Home

About

Contact

Mentor Program.

Teach, coach, train and inspire the next generation of software entreprenuers springing out of Africa to take on the world

							Learn more

							<form method="POST" class="sign_up_mentor">
								<button id="mentor-signup-button" class="btn btn-large btn-primary btn-info pull-left" name="action" value="sign_up_mentor">
									Signup
								</button>
							</form>

Senior Fellow

Can you lead, inspire and motivate the next generation of globally successful software entreprenuers? Do you have the passion to see these outliers succeed?

							Learn more
							<form method="POST" class="sign_up_mentor">
								<button id="mentor-signup-button" class="btn btn-large btn-primary btn-info pull-left" name="action" value="sign_up_mentor">
									Signup
								</button>
							</form>

MBA Consultancy.

Are you an MBA student? Why not step out of the classroom and begin making immdiate impact in the real world among entreprenuers destined to succeed?

							Learn more
							<form method="POST" class="sign_up_mentor">
								<button id="mentor-signup-button" class="btn btn-large btn-primary btn-info pull-left" name="action" value="sign_up_mentor">
									Signup
								</button>
							</form>

Trusted Advisor.

I bet you have a ton of experience under your belt. Why keep it all to yourself. Share. Groom these ambitious entraprenuers to maximise thier success potential and aviod rockie pitfalls

							Learn more
							<form method="POST" class="sign_up_mentor">
								<button id="mentor-signup-button" class="btn btn-large btn-info pull-left" name="action" value="sign_up_mentor">
									Signup
								</button>
							</form>

Entreprenuers In Training (EITs).

The next breed of software entreprenuers who will change the world. There are many ways to join this vibrant community.

							Learn more

Job Openings

Apply for a position with one of our fast-growing start-ups.

							Learn more
							<form method="POST" class="sign_up_applicant">
								<button id="applicant-signup-button" class="btn btn-large btn-info pull-left" name="action" value="sign_up_applicant">
									Signup
								</button>
							</form>

			‹
			›

Be a part of the MEST global network.

Donec sed odio dui. Etiam porta sem malesuada magna mollis euismod. Nullam id dolor id nibh ultricies vehicula ut id elit. Morbi leo risus, porta ac consectetur ac, vestibulum at eros. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.

Mentors

Senior Fellow

MBA Consultant

Trusted Advisor

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc eu libero sapien. Quisque nec turpis nec ipsum eleifend tincidunt id ut ante. Etiam eleifend viverra dapibus. Phasellus ut euismod risus, fringilla consequat dui. Nunc in gravida nunc, in rutrum libero. Suspendisse ullamcorper vestibulum felis, non fermentum nisi eleifend et. Curabitur pharetra dui felis, sed tempor neque tincidunt eu. Nulla sodales mollis posuere.

						Pellentesque id dictum sapien. Aliquam quis risus tortor. In hac habitasse platea dictumst. In ipsum mauris, sagittis sed tristique et, semper ut orci. Nam ut tincidunt leo. Aliquam erat volutpat. Mauris eu risus massa. In convallis tortor in ligula gravida suscipit.

In sed semper lectus, ut condimentum diam. Nam id dapibus felis, quis venenatis sapien. Proin id accumsan nibh. Fusce laoreet feugiat justo id lacinia. Sed pulvinar auctor venenatis. Quisque eu metus elementum, ornare risus a, hendrerit velit. Nullam nec elementum velit, at elementum nibh. Nam id lacus vehicula, lobortis enim in, aliquam mauris. Etiam augue sapien, laoreet id lacus convallis, rhoncus viverra eros. Maecenas interdum turpis egestas dolor accumsan, vel suscipit sem convallis. Sed viverra odio quis massa aliquet vulputate. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer purus lectus, malesuada sit amet neque vel, accumsan mattis ipsum.

Nulla mattis, urna nec dapibus hendrerit, libero libero fringilla eros, non placerat massa purus a orci. Aenean velit urna, cursus nec turpis vitae, porttitor scelerisque lacus. Ut diam magna, bibendum in sollicitudin ultrices, volutpat ut nulla. Interdum et malesuada fames ac ante ipsum primis in faucibus. Aliquam mollis ligula eros, ac elementum libero vehicula eu. Duis at congue ligula, sed ornare purus. Nullam gravida ultricies diam, vel ullamcorper quam tempus non. Donec euismod in nibh nec laoreet. Praesent adipiscing diam at urna sagittis, imperdiet vulputate magna volutpat. In hac habitasse platea dictumst. Quisque faucibus rutrum lacinia. Ut viverra mi at ipsum laoreet vulputate. Pellentesque quis tempus orci. Morbi vel vestibulum est, at pharetra urna.

There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition, injected humour, or non-characteristic words etc.

						<form method="POST" class="sign_up_mentor">
								<button id="mentor-signup-button" class="btn btn-medium btn-info pull-right" name="action" value="sign_up_mentor">
									Apply now
								</button>
						</form>

Featured Mentors

Noah Fontes

													Universal University

													Tech Fellow

													MEST

												View profile

												 <spa>
Brooke Cassof

													New York University

													Communications Fellow

													MEST

												View profile

Richard Tanksley

													University of

													Head of Operations

													MEST

												View profile

Patricia Schmiss

													New York University

													Communications Fellow

													MEST

												View profile

Ben Haynor

													New York University

													Communications Fellow

													MEST

												View profile

View complete fetured mentor profile

MEST GLOBAL NETWORK  — shapping the future together!

©2013   meltwater entreprenuerial school of technology


text:
// +build integration

package integration

import (
	"context"
	"fmt"
	"os/exec"
	"strings"
	"testing"
	"time"
)

func TestMultiNode(t *testing.T) {
	if NoneDriver() {
		t.Skip("none driver does not support multinode")
	}

	type validatorFunc func(context.Context, *testing.T, string)
	profile := UniqueProfileName("multinode")
	ctx, cancel := context.WithTimeout(context.Background(), Minutes(30))
	defer CleanupWithLogs(t, profile, cancel)

	t.Run("serial", func(t *testing.T) {
		tests := []struct {
			name      string
			validator validatorFunc
		}{
			{"FreshStart2Nodes", validateMultiNodeStart},
			{"AddNode", validateAddNodeToMultiNode},
			{"StopNode", validateStopRunningNode},
			{"StartAfterStop", validateStartNodeAfterStop},
			{"DeleteNode", validateDeleteNodeFromMultiNode},
			{"StopMultiNode", validateStopMultiNodeCluster},
			{"RestartMultiNode", validateRestartMultiNodeCluster},
		}
		for _, tc := range tests {
			tc := tc
			if ctx.Err() == context.DeadlineExceeded {
				t.Fatalf("Unable to run more tests (deadline exceeded)")
			}
			t.Run(tc.name, func(t *testing.T) {
				defer PostMortemLogs(t, profile)
				tc.validator(ctx, t, profile)
			})
		}
	})
}

func validateMultiNodeStart(ctx context.Context, t *testing.T, profile string) {
	// Start a 2 node cluster with the --nodes param
	startArgs := append([]string{"start", "-p", profile, "--wait=true", "--memory=2200", "--nodes=2", "-v=8", "--alsologtostderr"}, StartArgs()...)
	rr, err := Run(t, exec.CommandContext(ctx, Target(), startArgs...))
	if err != nil {
		t.Fatalf("failed to start cluster. args %q : %v", rr.Command(), err)
	}

	// Make sure minikube status shows 2 nodes
	rr, err = Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "status", "--alsologtostderr"))
	if err != nil {
		t.Fatalf("failed to run minikube status. args %q : %v", rr.Command(), err)
	}

	if strings.Count(rr.Stdout.String(), "host: Running") != 2 {
		t.Errorf("status says both hosts are not running: args %q: %v", rr.Command(), rr.Stdout.String())
	}

	if strings.Count(rr.Stdout.String(), "kubelet: Running") != 2 {
		t.Errorf("status says both kubelets are not running: args %q: %v", rr.Command(), rr.Stdout.String())
	}

}

func validateAddNodeToMultiNode(ctx context.Context, t *testing.T, profile string) {
	// Add a node to the current cluster
	addArgs := []string{"node", "add", "-p", profile, "-v", "3", "--alsologtostderr"}
	rr, err := Run(t, exec.CommandContext(ctx, Target(), addArgs...))
	if err != nil {
		t.Fatalf("failed to add node to current cluster. args %q : %v", rr.Command(), err)
	}

	// Make sure minikube status shows 3 nodes
	rr, err = Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "status", "--alsologtostderr"))
	if err != nil {
		t.Fatalf("failed to run minikube status. args %q : %v", rr.Command(), err)
	}

	if strings.Count(rr.Stdout.String(), "host: Running") != 3 {
		t.Errorf("status says all hosts are not running: args %q: %v", rr.Command(), rr.Stdout.String())
	}

	if strings.Count(rr.Stdout.String(), "kubelet: Running") != 3 {
		t.Errorf("status says all kubelets are not running: args %q: %v", rr.Command(), rr.Stdout.String())
	}
}

func validateStopRunningNode(ctx context.Context, t *testing.T, profile string) {
	// Run minikube node stop on that node
	rr, err := Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "node", "stop", ThirdNodeName))
	if err != nil {
		t.Errorf("node stop returned an error. args %q: %v", rr.Command(), err)
	}

	// Run status again to see the stopped host
	rr, err = Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "status"))
	// Exit code 7 means one host is stopped, which we are expecting
	if err != nil && rr.ExitCode != 7 {
		t.Fatalf("failed to run minikube status. args %q : %v", rr.Command(), err)
	}

	// Make sure minikube status shows 2 running nodes and 1 stopped one
	rr, err = Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "status", "--alsologtostderr"))
	if err != nil && rr.ExitCode != 7 {
		t.Fatalf("failed to run minikube status. args %q : %v", rr.Command(), err)
	}

	if strings.Count(rr.Stdout.String(), "kubelet: Running") != 2 {
		t.Errorf("incorrect number of running kubelets: args %q: %v", rr.Command(), rr.Stdout.String())
	}

	if strings.Count(rr.Stdout.String(), "host: Stopped") != 1 {
		t.Errorf("incorrect number of stopped hosts: args %q: %v", rr.Command(), rr.Stdout.String())
	}

	if strings.Count(rr.Stdout.String(), "kubelet: Stopped") != 1 {
		t.Errorf("incorrect number of stopped kubelets: args %q: %v", rr.Command(), rr.Stdout.String())
	}
}

func validateStartNodeAfterStop(ctx context.Context, t *testing.T, profile string) {
	if DockerDriver() {
		rr, err := Run(t, exec.Command("docker", "version", "-f", "{{.Server.Version}}"))
		if err != nil {
			t.Fatalf("docker is broken: %v", err)
		}
		if strings.Contains(rr.Stdout.String(), "azure") {
			t.Skip("kic containers are not supported on docker's azure")
		}
	}

	// Start the node back up
	rr, err := Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "node", "start", ThirdNodeName, "--alsologtostderr"))
	if err != nil {
		t.Logf(rr.Stderr.String())
		t.Errorf("node start returned an error. args %q: %v", rr.Command(), err)
	}

	// Make sure minikube status shows 3 running hosts
	rr, err = Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "status"))
	if err != nil {
		t.Fatalf("failed to run minikube status. args %q : %v", rr.Command(), err)
	}

	if strings.Count(rr.Stdout.String(), "host: Running") != 3 {
		t.Errorf("status says both hosts are not running: args %q: %v", rr.Command(), rr.Stdout.String())
	}

	if strings.Count(rr.Stdout.String(), "kubelet: Running") != 3 {
		t.Errorf("status says both kubelets are not running: args %q: %v", rr.Command(), rr.Stdout.String())
	}

	// Make sure kubectl can connect correctly
	rr, err = Run(t, exec.CommandContext(ctx, "kubectl", "get", "nodes"))
	if err != nil {
		t.Fatalf("failed to kubectl get nodes. args %q : %v", rr.Command(), err)
	}
}

func validateStopMultiNodeCluster(ctx context.Context, t *testing.T, profile string) {
	// Run minikube stop on the cluster
	rr, err := Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "stop"))
	if err != nil {
		t.Errorf("node stop returned an error. args %q: %v", rr.Command(), err)
	}

	// Run status to see the stopped hosts
	rr, err = Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "status"))
	// Exit code 7 means one host is stopped, which we are expecting
	if err != nil && rr.ExitCode != 7 {
		t.Fatalf("failed to run minikube status. args %q : %v", rr.Command(), err)
	}

	// Make sure minikube status shows 2 stopped nodes
	rr, err = Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "status", "--alsologtostderr"))
	if err != nil && rr.ExitCode != 7 {
		t.Fatalf("failed to run minikube status. args %q : %v", rr.Command(), err)
	}

	if strings.Count(rr.Stdout.String(), "host: Stopped") != 2 {
		t.Errorf("incorrect number of stopped hosts: args %q: %v", rr.Command(), rr.Stdout.String())
	}

	if strings.Count(rr.Stdout.String(), "kubelet: Stopped") != 2 {
		t.Errorf("incorrect number of stopped kubelets: args %q: %v", rr.Command(), rr.Stdout.String())
	}
}

func validateRestartMultiNodeCluster(ctx context.Context, t *testing.T, profile string) {
	if DockerDriver() {
		rr, err := Run(t, exec.Command("docker", "version", "-f", "{{.Server.Version}}"))
		if err != nil {
			t.Fatalf("docker is broken: %v", err)
		}
		if strings.Contains(rr.Stdout.String(), "azure") {
			t.Skip("kic containers are not supported on docker's azure")
		}
	}
	// Restart a full cluster with minikube start
	startArgs := append([]string{"start", "-p", profile, "--wait=true", "-v=8", "--alsologtostderr"}, StartArgs()...)
	rr, err := Run(t, exec.CommandContext(ctx, Target(), startArgs...))
	if err != nil {
		t.Fatalf("failed to start cluster. args %q : %v", rr.Command(), err)
	}

	time.Sleep(Seconds(45))

	// Make sure minikube status shows 2 running nodes
	rr, err = Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "status", "--alsologtostderr"))
	if err != nil {
		t.Fatalf("failed to run minikube status. args %q : %v", rr.Command(), err)
	}

	if strings.Count(rr.Stdout.String(), "host: Running") != 2 {
		t.Errorf("status says both hosts are not running: args %q: %v", rr.Command(), rr.Output())
	}

	if strings.Count(rr.Stdout.String(), "kubelet: Running") != 2 {
		t.Errorf("status says both kubelets are not running: args %q: %v", rr.Command(), rr.Output())
	}

	// Make sure kubectl reports that all nodes are ready
	rr, err = Run(t, exec.CommandContext(ctx, "kubectl", "get", "nodes"))
	if err != nil {
		t.Fatalf("failed to run kubectl get nodes. args %q : %v", rr.Command(), err)
	}
	if strings.Count(rr.Stdout.String(), "NotReady") > 0 {
		t.Errorf("expected 2 nodes to be Ready, got %v", rr.Output())
	}

	rr, err = Run(t, exec.CommandContext(ctx, "kubectl", "get", "nodes", "-o", `go-template='{{range .items}}{{range .status.conditions}}{{if eq .type "Ready"}} {{.status}}{{"\n"}}{{end}}{{end}}{{end}}'`))
	if err != nil {
		t.Fatalf("failed to run kubectl get nodes. args %q : %v", rr.Command(), err)
	}
	if strings.Count(rr.Stdout.String(), "True") != 2 {
		t.Errorf("expected 2 nodes Ready status to be True, got %v", rr.Output())
	}
}

func validateDeleteNodeFromMultiNode(ctx context.Context, t *testing.T, profile string) {

	// Start the node back up
	rr, err := Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "node", "delete", ThirdNodeName))
	if err != nil {
		t.Errorf("node stop returned an error. args %q: %v", rr.Command(), err)
	}

	// Make sure status is back down to 2 hosts
	rr, err = Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "status", "--alsologtostderr"))
	if err != nil {
		t.Fatalf("failed to run minikube status. args %q : %v", rr.Command(), err)
	}

	if strings.Count(rr.Stdout.String(), "host: Running") != 2 {
		t.Errorf("status says both hosts are not running: args %q: %v", rr.Command(), rr.Stdout.String())
	}

	if strings.Count(rr.Stdout.String(), "kubelet: Running") != 2 {
		t.Errorf("status says both kubelets are not running: args %q: %v", rr.Command(), rr.Stdout.String())
	}

	if DockerDriver() {
		rr, err := Run(t, exec.Command("docker", "volume", "ls"))
		if err != nil {
			t.Errorf("failed to run %q : %v", rr.Command(), err)
		}
		if strings.Contains(rr.Stdout.String(), fmt.Sprintf("%s-%s", profile, ThirdNodeName)) {
			t.Errorf("docker volume was not properly deleted: %s", rr.Stdout.String())
		}
	}

	// Make sure kubectl knows the node is gone
	rr, err = Run(t, exec.CommandContext(ctx, "kubectl", "get", "nodes"))
	if err != nil {
		t.Fatalf("failed to run kubectl get nodes. args %q : %v", rr.Command(), err)
	}
	if strings.Count(rr.Stdout.String(), "NotReady") > 0 {
		t.Errorf("expected 2 nodes to be Ready, got %v", rr.Output())
	}

	rr, err = Run(t, exec.CommandContext(ctx, "kubectl", "get", "nodes", "-o", `go-template='{{range .items}}{{range .status.conditions}}{{if eq .type "Ready"}} {{.status}}{{"\n"}}{{end}}{{end}}{{end}}'`))
	if err != nil {
		t.Fatalf("failed to run kubectl get nodes. args %q : %v", rr.Command(), err)
	}
	if strings.Count(rr.Stdout.String(), "True") != 2 {
		t.Errorf("expected 2 nodes Ready status to be True, got %v", rr.Output())
	}
}


text:
package org.connectbot.util;

import android.app.Dialog;
import android.content.Context;
import android.view.View;

import com.thisisnotajoke.SSHades.R;

public class EntropyDialog extends Dialog implements OnEntropyGatheredListener {

	public EntropyDialog(Context context) {
		super(context);

		this.setContentView(R.layout.dia_gatherentropy);
		this.setTitle(R.string.pubkey_gather_entropy);

		((EntropyView) findViewById(R.id.entropy)).addOnEntropyGatheredListener(this);
	}

	public EntropyDialog(Context context, View view) {
		super(context);

		this.setContentView(view);
		this.setTitle(R.string.pubkey_gather_entropy);

		((EntropyView) findViewById(R.id.entropy)).addOnEntropyGatheredListener(this);
	}

	public void onEntropyGathered(byte[] entropy) {
		this.dismiss();
	}

}


text:
package org.tianjyan.pwd.application;

import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONStringer;

import android.util.Log;

/**
 * @author keane
 *
 */
public class JsonHelper {
    private static String TAG = "JSONHelper";

    /**
     * 将对象转换成Json字符串
     * @param obj
     * @return json类型字符串
     */
    public static String toJSON(Object obj) {
        JSONStringer js = new JSONStringer();
        serialize(js, obj);
        return js.toString();
    }

    /**
     * 序列化为JSON
     * @param js json对象
     * @param o	待需序列化的对象
     */
    private static void serialize(JSONStringer js, Object o) {
        if (isNull(o)) {
            try {
                js.value(null);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return;
        }

        Class<?> clazz = o.getClass();
        if (isObject(clazz)) { // 对象
            serializeObject(js, o);
        } else if (isArray(clazz)) { // 数组
            serializeArray(js, o);
        } else if (isCollection(clazz)) { // 集合
            Collection<?> collection = (Collection<?>) o;
            serializeCollect(js, collection);
        }else if (isMap(clazz)) { // 集合
            HashMap<?,?> collection = (HashMap<?,?>) o;
            serializeMap(js, collection);
        } else { // 单个值
            try {
                js.value(o);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 序列化数组
     * @param js	json对象
     * @param array	数组
     */
    private static void serializeArray(JSONStringer js, Object array) {
        try {
            js.array();
            for (int i = 0; i < Array.getLength(array); ++i) {
                Object o = Array.get(array, i);
                serialize(js, o);
            }
            js.endArray();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 序列化集合
     * @param js	json对象
     * @param collection	集合
     */
    private static void serializeCollect(JSONStringer js, Collection<?> collection) {
        try {
            js.array();
            for (Object o : collection) {
                serialize(js, o);
            }
            js.endArray();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 序列化Map
     * @param js	json对象
     * @param map	map对象
     */
    private static void serializeMap(JSONStringer js, Map<?,?> map) {
        try {
            js.object();
            @SuppressWarnings("unchecked")
            Map<String, Object> valueMap = (Map<String, Object>) map;
            for (Map.Entry<String, Object> entry : valueMap.entrySet()) {
                js.key(entry.getKey());
                serialize(js, entry.getValue());
            }
            js.endObject();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 序列化对象
     * @param js	json对象
     * @param obj	待序列化对象
     */
    private static void serializeObject(JSONStringer js, Object obj) {
        try {
            js.object();
            Class<? extends Object> objClazz = obj.getClass();
            Method[] methods = objClazz.getDeclaredMethods();
            Field[] fields = objClazz.getDeclaredFields();
            for (Field field : fields) {
                try {
                    String fieldType = field.getType().getSimpleName();
                    String fieldGetName = parseMethodName(field.getName(),"get");
                    if (!haveMethod(methods, fieldGetName)) {
                        continue;
                    }
                    Method fieldGetMet = objClazz.getMethod(fieldGetName);
                    Object fieldVal = fieldGetMet.invoke(obj);
                    String result = null;
                    if ("Date".equals(fieldType)) {
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",Locale.US);
                        result = sdf.format((Date)fieldVal);

                    } else {
                        if (null != fieldVal) {
                            result = String.valueOf(fieldVal);
                        }
                    }
                    js.key(field.getName());
                    serialize(js, result);
                } catch (Exception e) {
                    continue;
                }
            }
            js.endObject();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 判断是否存在某属性的 get方法
     * @param methods	引用方法的数组
     * @param fieldMethod	方法名称
     * @return true或者false
     */
    public static boolean haveMethod(Method[] methods, String fieldMethod) {
        for (Method met : methods) {
            if (fieldMethod.equals(met.getName())) {
                return true;
            }
        }
        return false;
    }

    /**
     * 拼接某属性的 get或者set方法
     * @param fieldName	字段名称
     * @param methodType	方法类型
     * @return 方法名称
     */
    public static String parseMethodName(String fieldName,String methodType) {
        if (null == fieldName || "".equals(fieldName)) {
            return null;
        }
        return methodType + fieldName.substring(0, 1).toUpperCase(Locale.ENGLISH) + fieldName.substring(1);
    }

    /**
     * 给字段赋值
     * @param obj  实例对象
     * @param valMap  值集合
     */
    public static void setFieldValue(Object obj, Map<String, String> valMap) {
        Class<?> cls = obj.getClass();
        // 取出bean里的所有方法
        Method[] methods = cls.getDeclaredMethods();
        Field[] fields = cls.getDeclaredFields();

        for (Field field : fields) {
            try {
                String setMetodName = parseMethodName(field.getName(),"set");
                if (!haveMethod(methods, setMetodName)) {
                    continue;
                }
                Method fieldMethod = cls.getMethod(setMetodName, field
                        .getType());
                String value = valMap.get(field.getName());
                if (null != value && !"".equals(value)) {
                    String fieldType = field.getType().getSimpleName();
                    if ("String".equals(fieldType)) {
                        fieldMethod.invoke(obj, value);
                    } else if ("Date".equals(fieldType)) {
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",Locale.US);
                        Date temp = sdf.parse(value);
                        fieldMethod.invoke(obj, temp);
                    } else if ("Integer".equals(fieldType)
                            || "int".equals(fieldType)) {
                        Integer intval = Integer.parseInt(value);
                        fieldMethod.invoke(obj, intval);
                    } else if ("Long".equalsIgnoreCase(fieldType)) {
                        Long temp = Long.parseLong(value);
                        fieldMethod.invoke(obj, temp);
                    } else if ("Double".equalsIgnoreCase(fieldType)) {
                        Double temp = Double.parseDouble(value);
                        fieldMethod.invoke(obj, temp);
                    } else if ("Boolean".equalsIgnoreCase(fieldType)) {
                        Boolean temp = Boolean.parseBoolean(value);
                        fieldMethod.invoke(obj, temp);
                    } else {
                        System.out.println("setFieldValue not supper type:" + fieldType);
                    }
                }
            } catch (Exception e) {
                continue;
            }
        }

    }

    /**
     * bean对象转Map
     * @param obj	实例对象
     * @return	map集合
     */
    public static Map<String, String> beanToMap(Object obj) {
        Class<?> cls = obj.getClass();
        Map<String, String> valueMap = new HashMap<>();
        // 取出bean里的所有方法
        Method[] methods = cls.getDeclaredMethods();
        Field[] fields = cls.getDeclaredFields();
        for (Field field : fields) {
            try {
                String fieldType = field.getType().getSimpleName();
                String fieldGetName = parseMethodName(field.getName(),"get");
                if (!haveMethod(methods, fieldGetName)) {
                    continue;
                }
                Method fieldGetMet = cls.getMethod(fieldGetName);
                Object fieldVal = fieldGetMet.invoke(obj);
                String result = null;
                if ("Date".equals(fieldType)) {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",Locale.CHINA);
                    result = sdf.format((Date)fieldVal);

                } else {
                    if (null != fieldVal) {
                        result = String.valueOf(fieldVal);
                    }
                }
                valueMap.put(field.getName(), result);
            } catch (Exception e) {
                continue;
            }
        }
        return valueMap;

    }

    /**
     * 给对象的字段赋值
     * @param obj	类实例
     * @param fieldSetMethod	字段方法
     * @param fieldType	字段类型
     * @param value
     */
    public static void setFiedlValue(Object obj,Method fieldSetMethod,String fieldType,Object value){

        try {
            if (null != value && !"".equals(value)) {
                if ("String".equals(fieldType)) {
                    fieldSetMethod.invoke(obj, value.toString());
                } else if ("Date".equals(fieldType)) {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",Locale.CHINA);
                    Date temp = sdf.parse(value.toString());
                    fieldSetMethod.invoke(obj, temp);
                } else if ("Integer".equals(fieldType)
                        || "int".equals(fieldType)) {
                    Integer intval = Integer.parseInt(value.toString());
                    fieldSetMethod.invoke(obj, intval);
                } else if ("Long".equalsIgnoreCase(fieldType)) {
                    Long temp = Long.parseLong(value.toString());
                    fieldSetMethod.invoke(obj, temp);
                } else if ("Double".equalsIgnoreCase(fieldType)) {
                    Double temp = Double.parseDouble(value.toString());
                    fieldSetMethod.invoke(obj, temp);
                } else if ("Boolean".equalsIgnoreCase(fieldType)) {
                    Boolean temp = Boolean.parseBoolean(value.toString());
                    fieldSetMethod.invoke(obj, temp);
                } else {
                    fieldSetMethod.invoke(obj, value);
                    Log.e(TAG, TAG  + ">>>>setFiedlValue -> not supper type" + fieldType);
                }
            }

        } catch (Exception e) {
//            Log.e(TAG, TAG  + ">>>>>>>>>>set value error.",e);
            e.printStackTrace();
        }

    }

    /**
     * 反序列化简单对象
     * @param jo	json对象
     * @param clazz	实体类类型
     * @return	反序列化后的实例
     * @throws JSONException
     */
    public static <T> T parseObject(JSONObject jo, Class<T> clazz) throws JSONException {
        if (clazz == null || isNull(jo)) {
            return null;
        }

        T obj = newInstance(clazz);
        if (obj == null) {
            return null;
        }
        if(isMap(clazz)){
            setField(obj,jo);
        }else{
            // 取出bean里的所有方法
            Method[] methods = clazz.getDeclaredMethods();
            Field[] fields = clazz.getDeclaredFields();
            for (Field f : fields) {
                String setMetodName = parseMethodName(f.getName(),"set");
                if (!haveMethod(methods, setMetodName)) {
                    continue;
                }
                try {
                    Method fieldMethod = clazz.getMethod(setMetodName, f.getType());
                    setField(obj,fieldMethod,f, jo);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return obj;
    }

    /**
     * 反序列化简单对象
     * @param jsonStr	json字符串
     * @param clazz	实体类类型
     * @return	反序列化后的实例
     * @throws JSONException
     */
    public static <T> T parseObject(String jsonStr, Class<T> clazz) throws JSONException {
        if (clazz == null || jsonStr == null || jsonStr.length() == 0) {
            return null;
        }

        JSONObject jo;
        jo = new JSONObject(jsonStr);
        if (isNull(jo)) {
            return null;
        }

        return parseObject(jo, clazz);
    }

    /**
     * 反序列化数组对象
     * @param ja	json数组
     * @param clazz	实体类类型
     * @return	反序列化后的数组
     */
    public static <T> T[] parseArray(JSONArray ja, Class<T> clazz) {
        if (clazz == null || isNull(ja)) {
            return null;
        }

        int len = ja.length();

        @SuppressWarnings("unchecked")
        T[] array = (T[]) Array.newInstance(clazz, len);

        for (int i = 0; i < len; ++i) {
            try {
                JSONObject jo = ja.getJSONObject(i);
                T o = parseObject(jo, clazz);
                array[i] = o;
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        return array;
    }

    /**
     * 反序列化数组对象
     * @param jsonStr	json字符串
     * @param clazz	实体类类型
     * @return	序列化后的数组
     */
    public static <T> T[] parseArray(String jsonStr, Class<T> clazz) {
        if (clazz == null || jsonStr == null || jsonStr.length() == 0) {
            return null;
        }
        JSONArray jo = null;
        try {
            jo = new JSONArray(jsonStr);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        if (isNull(jo)) {
            return null;
        }

        return parseArray(jo, clazz);
    }

    /**
     * 反序列化泛型集合
     * @param ja	json数组
     * @param collectionClazz	集合类型
     * @param genericType	实体类类型
     * @return
     * @throws JSONException
     */
    @SuppressWarnings("unchecked")
    public static <T> Collection<T> parseCollection(JSONArray ja, Class<?> collectionClazz,
                                                    Class<T> genericType) throws JSONException {

        if (collectionClazz == null || genericType == null || isNull(ja)) {
            return null;
        }

        Collection<T> collection = (Collection<T>) newInstance(collectionClazz);

        for (int i = 0; i < ja.length(); ++i) {
            try {
                JSONObject jo = ja.getJSONObject(i);
                T o = parseObject(jo, genericType);
                collection.add(o);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        return collection;
    }

    /**
     * 反序列化泛型集合
     * @param jsonStr	json字符串
     * @param collectionClazz	集合类型
     * @param genericType	实体类类型
     * @return	反序列化后的数组
     * @throws JSONException
     */
    public static <T> Collection<T> parseCollection(String jsonStr, Class<?> collectionClazz,
                                                    Class<T> genericType) throws JSONException {
        if (collectionClazz == null || genericType == null || jsonStr == null
                || jsonStr.length() == 0) {
            return null;
        }
        JSONArray jo = null;
        try {
            //如果为数组,则此处转化时,需要去掉前面的键,直接后面的[]中的值
            int index = jsonStr.indexOf("[");
            String arrayString=null;

            //获取数组的字符串
            if(-1!=index){
                arrayString = jsonStr.substring(index);
            }

            //如果为数组,使用数组转化
            if(null!=arrayString){
                jo = new JSONArray(arrayString);
            }
            else{
                jo = new JSONArray(jsonStr);
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }

        if (isNull(jo)) {
            return null;
        }

        return parseCollection(jo, collectionClazz, genericType);
    }

    /**
     * 根据类型创建对象
     * @param clazz	待创建实例的类型
     * @return	实例对象
     * @throws JSONException
     */
    @SuppressWarnings({ "unchecked", "rawtypes" })
    private static <T> T newInstance(Class<T> clazz) throws JSONException {
        if (clazz == null)
            return null;
        T obj;
        if (clazz.isInterface()) {
            if (clazz.equals(Map.class)) {
                obj = (T) new HashMap();
            }else if (clazz.equals(List.class)) {
                obj = (T) new ArrayList();
            }else if (clazz.equals(Set.class)) {
                obj = (T) new HashSet();
            }else{
                throw new JSONException("unknown interface: " + clazz);
            }
        }else{
            try {
                obj = clazz.newInstance();
            }catch (Exception e) {
                throw new JSONException("unknown class type: " + clazz);
            }
        }
        return obj;
    }

    /**
     * 设定Map的值
     * @param obj	待赋值字段的对象
     * @param jo	json实例
     */
    private static void setField(Object obj, JSONObject jo) {
        try {
            @SuppressWarnings("unchecked")
            Iterator<String> keyIter = jo.keys();
            String key;
            Object value;
            @SuppressWarnings("unchecked")
            Map<String, Object> valueMap = (Map<String, Object>) obj;
            while (keyIter.hasNext()) {
                key = keyIter.next();
                value = jo.get(key);
                valueMap.put(key, value);

            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 设定字段的值
     * @param obj	待赋值字段的对象
     * @param fieldSetMethod	字段方法名
     * @param field	字段
     * @param jo	json实例
     */
    private static void setField(Object obj, Method fieldSetMethod,Field field, JSONObject jo) {
        String name = field.getName();
        Class<?> clazz = field.getType();
        try {
            if (isArray(clazz)) { // 数组
                Class<?> c = clazz.getComponentType();
                JSONArray ja = jo.optJSONArray(name);
                if (!isNull(ja)) {
                    Object array = parseArray(ja, c);
                    setFiedlValue(obj, fieldSetMethod, clazz.getSimpleName(), array);
                }
            } else if (isCollection(clazz)) { // 泛型集合
                // 获取定义的泛型类型
                Class<?> c = null;
                Type gType = field.getGenericType();
                if (gType instanceof ParameterizedType) {
                    ParameterizedType ptype = (ParameterizedType) gType;
                    Type[] targs = ptype.getActualTypeArguments();
                    if (targs != null && targs.length > 0) {
                        Type t = targs[0];
                        c = (Class<?>) t;
                    }
                }

                JSONArray ja = jo.optJSONArray(name);
                if (!isNull(ja)) {
                    Object o = parseCollection(ja, clazz, c);
                    setFiedlValue(obj, fieldSetMethod, clazz.getSimpleName(), o);
                }
            } else if (isSingle(clazz)) { // 值类型
                Object o = jo.opt(name);
                if (o != null &&  !o.toString().equals("null")) {
                    setFiedlValue(obj, fieldSetMethod, clazz.getSimpleName(), o);
                }
            } else if (isObject(clazz)) { // 对象
                JSONObject j = jo.optJSONObject(name);
                if (!isNull(j)) {
                    Object o = parseObject(j, clazz);
                    setFiedlValue(obj, fieldSetMethod, clazz.getSimpleName(), o);
                }
            } else if (isList(clazz)) { // 列表
//				JSONObject j = jo.optJSONObject(name);
//				if (!isNull(j)) {
//					Object o = parseObject(j, clazz);
//					f.set(obj, o);
//				}
            } else {
                throw new Exception("unknow type!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 设定字段的值
     * @param obj	待赋值字段的对象
     * @param field	字段
     * @param jo	json实例
     */
    @SuppressWarnings("unused")
    private static void setField(Object obj, Field field, JSONObject jo) {
        String name = field.getName();
        Class<?> clazz = field.getType();
        try {
            if (isArray(clazz)) { // 数组
                Class<?> c = clazz.getComponentType();
                JSONArray ja = jo.optJSONArray(name);
                if (!isNull(ja)) {
                    Object array = parseArray(ja, c);
                    field.set(obj, array);
                }
            } else if (isCollection(clazz)) { // 泛型集合
                // 获取定义的泛型类型
                Class<?> c = null;
                Type gType = field.getGenericType();
                if (gType instanceof ParameterizedType) {
                    ParameterizedType ptype = (ParameterizedType) gType;
                    Type[] targs = ptype.getActualTypeArguments();
                    if (targs != null && targs.length > 0) {
                        Type t = targs[0];
                        c = (Class<?>) t;
                    }
                }
                JSONArray ja = jo.optJSONArray(name);
                if (!isNull(ja)) {
                    Object o = parseCollection(ja, clazz, c);
                    field.set(obj, o);
                }
            } else if (isSingle(clazz)) { // 值类型
                Object o = jo.opt(name);
                if (o != null) {
                    field.set(obj, o);
                }
            } else if (isObject(clazz)) { // 对象
                JSONObject j = jo.optJSONObject(name);
                if (!isNull(j)) {
                    Object o = parseObject(j, clazz);
                    field.set(obj, o);
                }
            } else if (isList(clazz)) { // 列表
                JSONObject j = jo.optJSONObject(name);
                if (!isNull(j)) {
                    Object o = parseObject(j, clazz);
                    field.set(obj, o);
                }
            }else {
                throw new Exception("unknow type!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 判断对象是否为空
     * @param obj	实例
     * @return
     */
    private static boolean isNull(Object obj) {
        if (obj instanceof JSONObject) {
            return JSONObject.NULL.equals(obj);
        }
        return obj == null;
    }

    /**
     * 判断是否是值类型
     * @param clazz
     * @return
     */
    private static boolean isSingle(Class<?> clazz) {
        return isBoolean(clazz) || isNumber(clazz) || isString(clazz);
    }

    /**
     * 是否布尔值
     * @param clazz
     * @return
     */
    public static boolean isBoolean(Class<?> clazz) {
        return (clazz != null)
                && ((Boolean.TYPE.isAssignableFrom(clazz)) || (Boolean.class
                .isAssignableFrom(clazz)));
    }

    /**
     * 是否数值
     * @param clazz
     * @return
     */
    public static boolean isNumber(Class<?> clazz) {
        return (clazz != null)
                && ((Byte.TYPE.isAssignableFrom(clazz)) || (Short.TYPE.isAssignableFrom(clazz))
                || (Integer.TYPE.isAssignableFrom(clazz))
                || (Long.TYPE.isAssignableFrom(clazz))
                || (Float.TYPE.isAssignableFrom(clazz))
                || (Double.TYPE.isAssignableFrom(clazz)) || (Number.class
                .isAssignableFrom(clazz)));
    }

    /**
     * 判断是否是字符串
     * @param clazz
     * @return
     */
    public static boolean isString(Class<?> clazz) {
        return (clazz != null)
                && ((String.class.isAssignableFrom(clazz))
                || (Character.TYPE.isAssignableFrom(clazz)) || (Character.class
                .isAssignableFrom(clazz)));
    }

    /**
     * 判断是否是对象
     * @param clazz
     * @return
     */
    private static boolean isObject(Class<?> clazz) {
        return clazz != null && !isSingle(clazz) && !isArray(clazz) && !isCollection(clazz) && !isMap(clazz);
    }

    /**
     * 判断是否是数组
     * @param clazz
     * @return
     */
    public static boolean isArray(Class<?> clazz) {
        return clazz != null && clazz.isArray();
    }

    /**
     * 判断是否是集合
     * @param clazz
     * @return
     */
    public static boolean isCollection(Class<?> clazz) {
        return clazz != null && Collection.class.isAssignableFrom(clazz);
    }

    /**
     * 判断是否是Map
     * @param clazz
     * @return
     */
    public static boolean isMap(Class<?> clazz) {
        return clazz != null && Map.class.isAssignableFrom(clazz);
    }

    /**
     * 判断是否是列表
     * @param clazz
     * @return
     */
    public static boolean isList(Class<?> clazz) {
        return clazz != null && List.class.isAssignableFrom(clazz);
    }

}


text:
Coming soon...Kundera Meetup !
Please cast your vote at https://www.surveymonkey.com/s/QJQBNGV

Overview
=========
Kundera is a "Polyglot Object Mapper" with a JPA interface. The idea behind Kundera is to make working with NoSQL Databases drop-dead simple and fun. Kundera is being developed with following objectives:

* To make working with NoSQL as simple as working with SQL
* To serve as JPA Compliant mapping solution for NoSQL Datastores.
*	To help developers, forget the complexity of NoSQL stores and focus on Domain Model.
*	To make switching across data-stores as easy as changing a configuration.

Supported Datastores
=====================
Kundera currently supports following data stores :
*  Cassandra
*  MongoDB
*  HBase
*  Redis
*  OracleNoSQL
*  Neo4j
*  Couchdb
*  Relational databases

You can find the list of data stores(specific versions) supported by Kundera [here] (https://github.com/impetus-opensource/Kundera/wiki/Datastores-Supported).

Getting Started
===============
The latest stable release of Kundera is 3.1 .
It is a maven based project . You can either download it directly from github and build using following command :

mvn clean install -Dfile src/pom.xml

Or it can be directly added as maven dependency in your project in the following manner :

  * Add the following repository to pom.xml :

   ```
    <repository>
        <id>sonatype-nexus</id>
        <name>Kundera Public Repository</name>
        <url>https://oss.sonatype.org/content/repositories/releases</url>
       <releases>
           <enabled>true</enabled>
       </releases>
       <snapshots>
           <enabled>false</enabled>
       </snapshots>
    </repository>
    <repository>
        <id>kundera-missing</id>
        <name>Kundera Public Missing Resources Repository</name>
        <url>http://kundera.googlecode.com/svn/maven2/maven-missing-resources</url>
        <releases>
           <enabled>true</enabled>
      </releases>
      <snapshots>
          <enabled>true</enabled>
      </snapshots>
    </repository>
   ```

  * Add the data store specific Kundera module as a dependency (e.g. Cassandra below) :

  ```
    <dependency>
          <groupId>com.impetus.kundera.client</groupId>
          <artifactId>kundera-cassandra</artifactId>
          <version>${kundera.version}</version>
    </dependency>
  ```

Build your project with the above changes to your pom.xml and start using Kundera !

Important Links
===============
* [Kundera in 5 minutes] (https://github.com/impetus-opensource/Kundera/wiki/Getting-Started-in-5-minutes)
* [Data Store specific Configurations] (https://github.com/impetus-opensource/Kundera/wiki/Data-store-Specific-Configuration)
* Features :
   * [Polyglot Persistence] (https://github.com/impetus-opensource/Kundera/wiki/Polyglot-Persistence)
   * [JPQL] (https://github.com/impetus-opensource/Kundera/wiki/JPQL) & [Native Query] (https://github.com/impetus-opensource/Kundera/wiki/Native-queries) Support
   * [Schema Generation] (https://github.com/impetus-opensource/Kundera/wiki/Schema-Generation)
   * [Transaction Management] (https://github.com/impetus-opensource/Kundera/wiki/Transaction-Management)
   * [Rest Based Access] (https://github.com/impetus-opensource/Kundera/wiki/REST-Based-Access)
* Tutorials :
   * [Kundera with Openshift] (https://github.com/impetus-opensource/Kundera/wiki/Deploying-Polyglot-(RDBMS---NoSQL)-Applications-on-Openshift)
   * [Kundera with Play Framework] (https://github.com/impetus-opensource/Kundera/wiki/Using-Kundera-with-Play!-Framework)
   * [Kundera with GWT] (https://github.com/impetus-opensource/Kundera/wiki/Using-Kundera-with-GWT)
   * [Kundera with JBoss] (https://github.com/impetus-opensource/Kundera/wiki/Using-Kundera-with-Jboss)
   * [Kundera with Spring] (https://github.com/impetus-opensource/Kundera/wiki/Building-Applications-with-Kundera-and-Spring)
* [Releases] (https://github.com/impetus-opensource/Kundera/blob/trunk/src/README.md)

About Us
========
Kundera is backed by Impetus Labs - iLabs. iLabs is a R&D consulting division of Impetus Technologies (http://www.impetus.com). iLabs focuses on innovations with next generation technologies and creates practice areas and new products around them. iLabs is actively involved working on High Performance computing technologies, ranging from distributed/parallel computing, Erlang, grid softwares, GPU based software, Hadoop, Hbase, Cassandra, CouchDB and related technologies. iLabs is also working on various other Open Source initiatives.

Follow us on [Twitter] (https://twitter.com/kundera_impetus).


text:
(function()
{
    'use strict';

    angular.module('herd').service('UrlBuilderService', UrlBuilderService);

    /**
     * Service which provides logic to create URLs.
     */
    function UrlBuilderService()
    {

    }

    /**
     * @param {Object} buildUrlRequest
     * @param {String} buildUrlRequest.paths[]
     * @returns {Promise} a promise
     */
    UrlBuilderService.prototype.buildUrl = function(buildUrlRequest)
    {
        var builder = [];

        _(buildUrlRequest.paths).each(function(path)
        {
            path = encodeURIComponent(path);
            path = path.replace('%20', '+');
            builder.push('/');
            builder.push(path);
        });

        return builder.join('');
    };
})();


text:
export function waitForImage(img) {
  return new Promise((resolve, reject) => {
    if (img.complete) {
      return img.naturalWidth ? resolve(img) : reject();
    }

    function loadListener() {
      removeListeners();
      resolve(img);
    }

    function errorListener(e) {
      removeListeners();
      reject(e);
    }

    const tOut = setTimeout(errorListener, 5000);

    function removeListeners() {
      clearTimeout(tOut);
      img.removeEventListener('load', loadListener);
      img.removeEventListener('error', errorListener);
    }

    img.addEventListener('load', loadListener);
    img.addEventListener('error', errorListener);

  });
}

export function setSrc(img, src, srcset) {
  if (srcset) {
    img.srcset = srcset;
  } else {
    img.removeAttribute('srcset');
  }
  img.src = src;
}

export function loadImage(img, src, srcset) {
  if (src && img.src !== src || srcset && img.srcset !== srcset) {
    setSrc(img, src, srcset)
  }
  return waitForImage(img);
}


text: Cabbagetown/Reynoldstown 2017 Transportation Survey Data


text:
module Plz
  class CommandBuilder
    SCHEMA_FILE_PATH_PATTERN = "schema.{json,yml}"

    # Builds callable command object from given ARGV
    # @return [Plz::Command, Plz::ErrorCommand]
    # @note This is a shortcut for #call method
    # @example
    #   Plz::CommandBuilder.call(ARGV).call
    def self.call(arguments)
      new(arguments).call
    end

    delegate(
      :action_name,
      :target_name,
      :headers,
      :params,
      :has_invalid_json_input?,
      to: :arguments,
    )

    # @param argv [Array<String>] Raw ARGV
    def initialize(argv)
      @argv = argv
    end

    # @return [Plz::Command] Callable command object
    def call
      case
      when !has_schema_file?
        Commands::SchemaFileNotFound.new
      when !has_decodable_schema_file?
        Commands::UndecodableSchemaFile.new(pathname: schema_file_pathname)
      when !has_valid_schema_file?
        Commands::InvalidSchema.new(pathname: schema_file_pathname, error: @json_schema_error)
      when !has_base_url?
        Commands::BaseUrlNotFound.new(pathname: schema_file_pathname)
      when has_help?
        Commands::Help.new(options: options, schema: json_schema)
      when !has_action_name?
        Commands::NoActionName.new
      when !has_target_name?
        Commands::NoTargetName.new
      when !has_link?
        Commands::LinkNotFound.new(
          pathname: schema_file_pathname,
          action_name: action_name,
          target_name: target_name,
        )
      when has_invalid_json_input?
        Commands::InvalidJsonFromStdin.new
      when has_unparsable_json_param?
        Commands::UnparsableJsonParam.new(error: @json_parse_error)
      else
        Commands::Request.new(
          method: method,
          base_url: base_url,
          path: path,
          headers: headers,
          params: request_params,
          options: options,
        )
      end
    end

    private

    def has_unparsable_json_param?
      params
      false
    rescue UnparsableJsonParam => exception
      @json_parse_error = exception
      true
    end

    # @return [true, false] True if --help or -h given
    def has_help?
      options[:help]
    end

    # @return [true, false] True if given arguments include action name
    def has_action_name?
      !!action_name
    end

    # @return [true, false] True if given arguments include target name
    def has_target_name?
      !!target_name
    end

    # @return [true, false] True if schema file exists
    def has_schema_file?
      !!schema_file_pathname
    end

    # @return [true, false] True if no error occured in parsing schema file as JSON Schema
    def has_valid_schema_file?
      !json_schema.nil?
    end

    # @return [true, false] True if no error occured in decoding schema file
    def has_decodable_schema_file?
      !!schema
    end

    # @return [true, false] True if given JSON Schema has a link of base URL of API
    def has_base_url?
      !!base_url
    end

    # @return [true, false] True if any link for given action and target found
    def has_link?
      !!link
    end

    # @return [Hash]
    def schema
      @schema ||= begin
        case schema_file_pathname.extname
        when ".yml"
          YAML.load(schema_file_body)
        else
          JSON.parse(schema_file_body)
        end
      end
    rescue
    end

    # @return [String]
    def schema_file_body
      @schema_file_body ||= schema_file_pathname.read
    end

    # @return [Pathname, nil] Found schema file path
    def schema_file_pathname
      @schema_file_pathname ||= Pathname.glob(SCHEMA_FILE_PATH_PATTERN).first
    end

    # @return [String]
    # @example
    #   path #=> "/users"
    def path
      path_with_template % path_params.symbolize_keys
    end

    # @return [String]
    # @example
    #   path_with_template #=> "/apps/%{id}"
    def path_with_template
      link.href.gsub(/{(.+?)}/) do |matched|
        key = CGI.unescape($1).gsub(/[()]/, "").split("/").last
        "%{#{key}}"
      end
    end

    # @return [Array<String>] Parameter names required for path
    # @exmaple
    #   path_keys #=> ["id"]
    def path_keys
      link.href.scan(/{(.+?)}/).map do |gr|
        CGI.unescape(gr.first).gsub(/[()]/, "").split("/").last
      end
    end

    # @return [Hash] Params to be embedded into path
    # @example
    #   path_params #=> { "id" => 1 }
    def path_params
      params.slice(*path_keys)
    end

    # @return [Hash] Params to be used for request body or query string
    # @example
    #   request_params #=> { "name" => "example" }
    def request_params
      params.except(*path_keys)
    end

    # @return [String]
    # @example
    #   method #=> "GET"
    def method
      link.method.to_s.upcase
    end

    # @return [String, nil] Base URL of the API
    # @example
    #   base_url #=> "http://localhost:8080"
    def base_url
      @base_url ||= begin
        if url = (options[:host] || base_url_from_schema)
          if url.start_with?("http")
            url
          else
            "http://#{url}"
          end
        end
      end
    end

    # Extracts the base url of the API from JSON Schema
    # @return [String, nil]
    # @example
    #   base_url_from_schema #=> "https://api.example.com/"
    def base_url_from_schema
      json_schema.links.find do |link|
        if link.href && link.rel == "self"
          return link.href
        end
      end
    end

    # @return [JsonSchema::Schema::Link, nil]
    def link
      @link ||= json_schema.properties.find do |key, schema|
        if key == target_name
          schema.links.find do |link|
            if link.href && link.method && link.title.underscore == action_name
              return link
            end
          end
        end
      end
    end

    # @return [JsonSchema::Schema, nil]
    def json_schema
      @json_schema ||= JsonSchema.parse!(@schema).tap(&:expand_references!)
    rescue => exception
      @json_schema_error = exception
      nil
    end

    # @return [Plz::Arguments] Wrapper of Raw ARGV
    def arguments
      @arguments ||= Arguments.new(@argv)
    end

    # @return [Hash] Command line options
    def options
      @options ||= Slop.parse!(@argv) do
        banner Error::USAGE
        on "h", "help", "Display help message"
        on "H", "host=", "API host"
        on "no-color", "Disable coloring output"
        on "no-response-body", "Hide response body"
        on "no-response-header", "Hide response header"
      end
    end
  end
end


text:
url: /appliance/admin
section: appliance
description: >
  This document covers factors PSaaS Appliance administrators should be aware of when working with production PSaaS Appliance.
topics:
    - appliance
    - administration
contentType: index
useCase: appliance
applianceId: appliance4
sitemap: false
---

# PSaaS Appliance: Administrator's Manual

This document covers factors PSaaS Appliance administrators should be aware of when working with production PSaaS Appliance instances.

* [Managing the Dashboard](/appliance/admin/managing-the-dashboard)
* [Disabling Sign-ups](/appliance/admin/disabling-sign-ups)
* [Inviting/Adding Co-Administrators](/appliance/admin/inviting-coadmins)
* [Backing up the PSaaS Appliance](/appliance/admin/backing-up-the-appliance-instances)
* [Monitoring & Performing Health Checks on Load Balancers](/appliance/admin/monitoring)
* [Updating the PSaaS Appliance](/appliance/admin/updating-the-appliance)
  * [Why You Should Update the PSaaS Appliance Regularly](/appliance/admin/importance-of-updates)
* [Configuring Custom Error Pages](/universal-login/custom-error-pages)