text:
using namespace process;

using std::string;
using std::vector;

using mesos::slave::ContainerConfig;
using mesos::slave::ContainerLaunchInfo;
using mesos::slave::ContainerLimitation;
using mesos::slave::ContainerState;
using mesos::slave::Isolator;

namespace mesos {
namespace internal {
namespace slave {

PosixFilesystemIsolatorProcess::PosixFilesystemIsolatorProcess(
    const Flags& _flags,
    VolumeGidManager* _volumeGidManager)
  : ProcessBase(process::ID::generate("posix-filesystem-isolator")),
    flags(_flags),
    volumeGidManager(_volumeGidManager) {}

PosixFilesystemIsolatorProcess::~PosixFilesystemIsolatorProcess() {}

Try<Isolator*> PosixFilesystemIsolatorProcess::create(
    const Flags& flags,
    VolumeGidManager* volumeGidManager)
{
  process::Owned<MesosIsolatorProcess> process(
      new PosixFilesystemIsolatorProcess(flags, volumeGidManager));

  return new MesosIsolator(process);
}

Future<Nothing> PosixFilesystemIsolatorProcess::recover(
    const vector<ContainerState>& states,
    const hashset<ContainerID>& orphans)
{
  foreach (const ContainerState& state, states) {
    infos.put(state.container_id(), Owned<Info>(new Info(state.directory())));
  }

  return Nothing();
}

Future<Option<ContainerLaunchInfo>> PosixFilesystemIsolatorProcess::prepare(
    const ContainerID& containerId,
    const ContainerConfig& containerConfig)
{
  if (infos.contains(containerId)) {
    return Failure("Container has already been prepared");
  }

  const ExecutorInfo& executorInfo = containerConfig.executor_info();

  if (executorInfo.has_container()) {
    CHECK_EQ(executorInfo.container().type(), ContainerInfo::MESOS);

    // Return failure if the container change the filesystem root
    // because the symlinks will become invalid in the new root.
    if (executorInfo.container().mesos().has_image()) {
      return Failure("Container root filesystems not supported");
    }

    if (executorInfo.container().volumes().size() > 0) {
      return Failure("Volumes in ContainerInfo is not supported");
    }
  }

  infos.put(containerId, Owned<Info>(new Info(containerConfig.directory())));

  return update(containerId, executorInfo.resources())
    .then(defer(
        self(),
        [this, containerId, containerConfig]() mutable
            -> Future<Option<ContainerLaunchInfo>> {
          if (!infos.contains(containerId)) {
            return Failure("Unknown container");
          }

          ContainerLaunchInfo launchInfo;
          foreach (gid_t gid, infos[containerId]->gids) {
            // For command task with its own rootfs, the command executor will
            // run as root and the task itself will run as the specified normal
            // user, so here we add the supplementary group for the task and the
            // command executor will set it accordingly when launching the task.
            if (containerConfig.has_task_info() &&
                containerConfig.has_rootfs()) {
              launchInfo.add_task_supplementary_groups(gid);
            } else {
              launchInfo.add_supplementary_groups(gid);
            }
          }

          return launchInfo;
      }));
}

Future<Nothing> PosixFilesystemIsolatorProcess::update(
    const ContainerID& containerId,
    const Resources& resources)
{
  if (!infos.contains(containerId)) {
    return Failure("Unknown container");
  }

  const Owned<Info>& info = infos[containerId];

  // TODO(jieyu): Currently, we only allow non-nested relative
  // container paths for volumes. This is enforced by the master. For
  // those volumes, we create symlinks in the executor directory.
  Resources current = info->resources;

  // We first remove unneeded persistent volumes.
  foreach (const Resource& resource, current.persistentVolumes()) {
    // This is enforced by the master.
    CHECK(resource.disk().has_volume());

    // Ignore absolute and nested paths.
    const string& containerPath = resource.disk().volume().container_path();
    if (strings::contains(containerPath, "/")) {
      LOG(WARNING) << "Skipping updating symlink for persistent volume "
                   << resource << " of container " << containerId
                   << " because the container path '" << containerPath
                   << "' contains slash";
      continue;
    }

    if (resources.contains(resource)) {
      continue;
    }

    string link = path::join(info->directory, containerPath);

    LOG(INFO) << "Removing symlink '" << link << "' for persistent volume "
              << resource << " of container " << containerId;

    Try<Nothing> rm = os::rm(link);
    if (rm.isError()) {
      return Failure(
          "Failed to remove the symlink for the unneeded "
          "persistent volume at '" + link + "'");
    }
  }

  // Get user and group info for this task based on the task's sandbox.
  struct stat s;
  if (::stat(info->directory.c_str(), &s) < 0) {
    return Failure("Failed to get ownership for '" + info->directory +
                   "': " + os::strerror(errno));
  }

  const uid_t uid = s.st_uid;
  const gid_t gid = s.st_gid;

  vector<Future<gid_t>> futures;

  // We then link additional persistent volumes.
  foreach (const Resource& resource, resources.persistentVolumes()) {
    // This is enforced by the master.
    CHECK(resource.disk().has_volume());

    // Ignore absolute and nested paths.
    const string& containerPath = resource.disk().volume().container_path();
    if (strings::contains(containerPath, "/")) {
      LOG(WARNING) << "Skipping updating symlink for persistent volume "
                   << resource << " of container " << containerId
                   << " because the container path '" << containerPath
                   << "' contains slash";
      continue;
    }

    if (current.contains(resource)) {
      continue;
    }

    string original = paths::getPersistentVolumePath(flags.work_dir, resource);

    // If the container's user is root (uid == 0), we do not need to do any
    // changes about the volume's ownership since it has the full permissions
    // to access the volume.
    if (uid != 0) {
      // For persistent volumes not from resource providers, if volume gid
      // manager is enabled, call volume gid manager to allocate a gid to
      // make sure the container has the permission to access the volume.
      //
      // TODO(qianzhang): Support gid allocation for persistent volumes from
      // resource providers.
      if (!Resources::hasResourceProvider(resource) &&
          volumeGidManager) {
  #ifndef __WINDOWS__
        LOG(INFO) << "Invoking volume gid manager to allocate gid to the "
                  << "volume path '" << original << "' for container "
                  << containerId;

        futures.push_back(
            volumeGidManager->allocate(original, VolumeGidInfo::PERSISTENT));
  #endif // __WINDOWS__
      } else {
        bool isVolumeInUse = false;

        // Check if the shared persistent volume is currently used by another
        // container. We do not need to do this check for local persistent
        // volume since it can only be used by one container at a time.
        if (resource.has_shared()) {
          foreachpair (const ContainerID& _containerId,
                       const Owned<Info>& info,
                       infos) {
            // Skip self.
            if (_containerId == containerId) {
              continue;
            }

            if (info->resources.contains(resource)) {
              isVolumeInUse = true;
              break;
            }
          }
        }

        // Set the ownership of the persistent volume to match that of the
        // sandbox directory if the volume is not already in use. If the
        // volume is currently in use by other containers, tasks in this
        // container may fail to read from or write to the persistent volume
        // due to incompatible ownership and file system permissions.
        if (!isVolumeInUse) {
          // TODO(hausdorff): (MESOS-5461) Persistent volumes maintain the
          // invariant that they are used by one task at a time. This is
          // currently enforced by `os::chown`. Windows does not support
          // `os::chown`, we will need to revisit this later.
  #ifndef __WINDOWS__
          LOG(INFO) << "Changing the ownership of the persistent volume at '"
                    << original << "' with uid " << uid << " and gid " << gid;

          Try<Nothing> chown = os::chown(uid, gid, original, false);

          if (chown.isError()) {
            return Failure(
                "Failed to change the ownership of the persistent volume at '" +
                original + "' with uid " + stringify(uid) +
                " and gid " + stringify(gid) + ": " + chown.error());
          }
  #endif // __WINDOWS__
        }
      }
    }

    string link = path::join(info->directory, containerPath);

    if (os::exists(link)) {
      // NOTE: This is possible because 'info->resources' will be
      // reset when slave restarts and recovers. When the slave calls
      // 'containerizer->update' after the executor reregisters,
      // we'll try to relink all the already symlinked volumes.
      Result<string> realpath = os::realpath(link);
      if (!realpath.isSome()) {
        return Failure(
            "Failed to get the realpath of symlink '" + link + "': " +
            (realpath.isError() ? realpath.error() : "No such directory"));
      }

      // A sanity check to make sure the target of the symlink does
      // not change. In fact, this is not supposed to happen.
      // NOTE: Here, we compare the realpaths because 'original' might
      // contain symbolic links.
      Result<string> _original = os::realpath(original);
      if (!_original.isSome()) {
        return Failure(
            "Failed to get the realpath of volume '" + original + "': " +
            (_original.isError() ? _original.error() : "No such directory"));
      }

      if (realpath.get() != _original.get()) {
        return Failure(
            "The existing symlink '" + link + "' points to '" +
            _original.get() + "' and the new target is '" +
            realpath.get() + "'");
      }
    } else {
      LOG(INFO) << "Adding symlink from '" << original << "' to '"
                << link << "' for persistent volume " << resource
                << " of container " << containerId;

      // NOTE: We cannot enforce read-only access given the symlink without
      // changing the source so we just log a warning here.
      if (resource.disk().volume().mode() == Volume::RO) {
        LOG(WARNING) << "Allowing read-write access to read-only volume '"
                     << original << "' of container " << containerId;
      }

      Try<Nothing> symlink = ::fs::symlink(original, link);
      if (symlink.isError()) {
        return Failure(
            "Failed to symlink persistent volume from '" +
            original + "' to '" + link + "'");
      }
    }
  }

  // Store the updated resources.
  info->resources = resources;

  return collect(futures)
    .then(defer(self(), [this, containerId](const vector<gid_t>& gids)
      -> Future<Nothing> {
      if (!infos.contains(containerId)) {
        return Failure("Unknown container");
      }

      infos[containerId]->gids = gids;

      return Nothing();
    }));
}

Future<Nothing> PosixFilesystemIsolatorProcess::cleanup(
    const ContainerID& containerId)
{
  // Symlinks for persistent resources will be removed when the work
  // directory is GC'ed, therefore no need to do explicit cleanup.
  infos.erase(containerId);

  return Nothing();
}

} // namespace slave {
} // namespace internal {
} // namespace mesos {


text:
// Copyright 2017 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.

// This file is autogenerated by
//     java_cpp_enum.py
// From
//     ../../components/location/android/location_settings_dialog_outcome.h

package org.chromium.components.location;

import android.support.annotation.IntDef;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@IntDef({
    LocationSettingsDialogOutcome.GRANTED, LocationSettingsDialogOutcome.DENIED,
    LocationSettingsDialogOutcome.NO_PROMPT
})
@Retention(RetentionPolicy.SOURCE)
public @interface LocationSettingsDialogOutcome {
  /**
   * The user accepted the prompt and the system location setting has been flipped to granted.
   */
  int GRANTED = 1;
  /**
   * The user rejected the prompt and the system location setting has not been flipped.
   */
  int DENIED = 2;
  /**
   * The prompt could not be triggered. When CanPromptToEnableSystemLocationSetting() returns true,
   * this should only happen in exceptional circonstances, e.g. - In the case of a race condition
   * where the system location setting is flipped elsewhere before the prompt could be triggered; -
   * In the case where some of the features required to trigger a system location setting prompt
   * became unavailable or unresponsive after the response from
   * CanPromptToEnableSystemLocationSetting() was received.
   */
  int NO_PROMPT = 3;
}

redpajama_set_name: RedPajamaGithub


text:
require "spec_helper"
require "hotdog/application"
require "hotdog/commands/down"

describe "option parser for down" do
  let(:app) {
    Hotdog::Application.new
  }

  let(:cmd) {
    Hotdog::Commands::Down.new(app)
  }

  before(:each) do
    allow(app).to receive(:get_command).with("down") {
      cmd
    }
  end

  it "cannot handle subcommand options before subcommand" do
    expect {
      app.main(["--downtime", "86400", "down", "foo", "bar", "baz"])
    }.to raise_error(OptionParser::InvalidOption)
  end

  it "can handle subcommand options after subcommand" do
    allow(cmd).to receive(:run).with(["foo", "bar", "baz"], a_hash_including(
      downtime: 12345,
      verbosity: Hotdog::VERBOSITY_NULL,
    ))
    app.main(["down", "--downtime", "12345", "foo", "bar", "baz"])
  end

  it "can handle common options before subcommand" do
    allow(cmd).to receive(:run).with(["foo", "bar", "baz"], a_hash_including(
      downtime: 12345,
      verbosity: Hotdog::VERBOSITY_INFO,
    ))
    app.main(["--verbose", "down", "--downtime", "12345", "foo", "bar", "baz"])
  end

  it "can handle common options after subcommand" do
    allow(cmd).to receive(:run).with(["foo", "bar", "baz"], a_hash_including(
      downtime: 12345,
      verbosity: Hotdog::VERBOSITY_INFO,
    ))
    app.main(["down", "--downtime", "12345", "--verbose", "foo", "bar", "baz"])
  end
end


text:
package org.jdesktop.animation.timing;

import static org.jdesktop.animation.timing.Animator.*;
import static org.junit.Assert.*;
import org.junit.*;

import mockit.*;

public final class AnimatorTimingSourceTest
{
   @Test
   public void setTimer(final TimingSource timingSource)
   {
      final Animator animator = new Animator(500);

      new Expectations() {{
         // Expectations for setTimer:
         timingSource.addEventListener(withInstanceOf(TimingEventListener.class));
         timingSource.setResolution(animator.getResolution());
         timingSource.setStartDelay(animator.getStartDelay());

         // Expectations for notification of events:
         timingSource.start();
         timingSource.stop();
      }};

      animator.setTimer(timingSource);
      animator.start();
      animator.stop();
   }

   @Test
   public void setTimerToCustomTimingSourceThenResetBackToOriginal(final TimingSource timingSource)
   {
      Animator animator = new Animator(50);

      new Expectations() {{
         timingSource.addEventListener(withInstanceOf(TimingEventListener.class));
         timingSource.setResolution(anyInt);
         timingSource.setStartDelay(anyInt);
         timingSource.removeEventListener(withInstanceOf(TimingEventListener.class));
      }};

      animator.setTimer(timingSource);
      animator.setTimer(null);
   }

   private static final class EmptyTimingSource extends TimingSource
   {
      @Override
      public void start() {}

      @Override
      public void stop() {}

      @Override
      public void setResolution(int resolution) {}

      @Override
      public void setStartDelay(int delay) {}
   }

   @Test
   public void timingEventOnTimingSource()
   {
      Animator animator = new Animator(50);
      final TimingSource timingSource = new EmptyTimingSource();

      new Expectations() {
         @Capturing
         private TimingEventListener timingEventTarget;

         {
            timingEventTarget.timingSourceEvent(timingSource);
         }
      };

      animator.setTimer(timingSource);
      timingSource.timingEvent();
   }

   @Test
   public void timingSourceEventOnTimingSourceTargetForNonRunningAnimator()
   {
      final Animator animator = new Animator(50);
      TimingSource timingSource = new EmptyTimingSource();
      animator.setTimer(timingSource);

      new Expectations() {
         TimingTarget timingTarget;

         {
            // Passing mock object into code under test:
            animator.addTarget(timingTarget);

            // Expectations:
            timingTarget.timingEvent(0.0f);
            times = 0; // Animator is not running, so no timing event is expected.
         }
      };

      timingSource.timingEvent();
   }

   @Test
   public void timingSourceEventOnTimingSourceTargetForRunningAnimator()
   {
      final Animator animator = new Animator(50);
      TimingSource timingSource = new EmptyTimingSource();
      animator.setTimer(timingSource);

      new Expectations() {
         TimingTarget timingTarget;

         {
            // Passing mock object into code under test:
            animator.addTarget(timingTarget);

            // Expectations:
            timingTarget.begin();
            timingTarget.timingEvent(withEqual(0.0f, 0.04));
         }
      };

      animator.start();
      timingSource.timingEvent();
   }

   @Test
   public void timingSourceEventOnTimingSourceTargetForRunningAnimatorAtTimeToStop()
   {
      final Animator animator = new Animator(50);
      TimingSource timingSource = new EmptyTimingSource();
      animator.setTimer(timingSource);

      new Expectations() {
         @Mocked("nanoTime") final System system = null;
         @Mocked TimingTarget timingTarget;

         {
            animator.addTarget(timingTarget);

            // For the call to animator.start():
            System.nanoTime(); result = 0L;

            // For the call to timingSource.timingEvent():
            System.nanoTime(); result = 50L * 1000000;

            // Resulting expected interactions:
            timingTarget.begin();
            timingTarget.timingEvent(1.0f);
            timingTarget.end();
         }
      };

      animator.start();
      timingSource.timingEvent();
   }

   @Test
   public void timingSourceEventOnTimingSourceTargetForRunningRepeatingAnimator()
   {
      final Animator animator = new Animator(50, INFINITE, RepeatBehavior.LOOP, null);
      TimingSource timingSource = new EmptyTimingSource();
      animator.setTimer(timingSource);

      new Expectations() {
         @Mocked("nanoTime") final System system = null;
         @Mocked TimingTarget timingTarget;

         {
            animator.addTarget(timingTarget);

            System.nanoTime(); returns(0L, 60L * 1000000);

            timingTarget.begin();
            timingTarget.repeat();
            timingTarget.timingEvent(anyFloat);
            forEachInvocation = new Object() {
               void validate(float item) { assertTrue(item > 0.0f); }
            };
         }
      };

      animator.start();
      timingSource.timingEvent();
   }
}


text:
<?php

//init zend framework
//set_include_path('lib/zf/library' . PATH_SEPARATOR . get_include_path());
//set_include_path('/usr/local/ZendFramework-1.12.3/library' . PATH_SEPARATOR . get_include_path());
set_include_path('app/models' . PATH_SEPARATOR . get_include_path());
set_include_path('app/controls' . PATH_SEPARATOR . get_include_path());
set_include_path('/usr/share/php/Google/src' . PATH_SEPARATOR . get_include_path());
require_once "Zend/Loader/Autoloader.php";
$autoloader = Zend_Loader_Autoloader::getInstance();
$autoloader->setFallbackAutoloader(true);

//check to make sure our site installation is done
if(!file_exists("config.php")) {
    echo "please create site specific config.php";
    exit;
}
if(!file_exists(".htaccess")) {
    echo ".htaccess file doesn't exist. please create";
    exit;
}

//load our stuff
require_once("config.php");
require_once("app/views/helper.php");
require_once("app/base.php");

//bootstrap
try {
    Zend_Session::start();

    //set php config
    ini_set('error_log', config()->error_logfile);
    ini_set('display_errors', 0);
    ini_set('log_errors', 1);
    ini_set('display_startup_errors', 1);
    ini_set('default_charset', 'UTF-8');
    ini_set('default_socket_timeout', 120);
    date_default_timezone_set("UTC");//this will be later modified again (if user has valid timezone)

    remove_quotes();
    setup_logs();
    greet();

    if($_REQUEST["action"]=="logout"){
      //Zend_Session::destroy();
      //  header("locationa: https://ticket-dev.grid.iu.edu");
      //  $oidc->signOut();
      unset($_SESSION['access_token']);

      $_SESSION["signout"]="1";
      //  $oidc->signOut($_SESSION["access_token"],"https://ticket-dev.grid.iu.edu"); \

      header("location: https://ticket-dev.grid.iu.edu");
      exit();
    }

    cert_authenticate();
    /*
    if(!date_default_timezone_set(user()->getTimeZone())) {
        message("WARNING", "Your timezone '".user()->getTimeZone()."' is not valid. Please try updating to location based timezone such as 'America/Chicago' via OIM profile. Reverting to UTC.");
        elog(user()->dn. " who is using ".user()->getTimeZone()." was asked to update to location based timezone");
    }
    */
    error_reporting(E_ALL | E_STRICT);

} catch(exception $e) {
    header("HTTP/1.0 500 Internal Server Error");
    echo "Boot Error";
    echo "<pre>".$e->getMessage()."</pre>";
    elog($e->getMessage());
    exit;
}

//log access
try {
    $data = new Data();
    $data->logAccess();
} catch(exception $e) {
    //continue processing
    wlog("failed to log access - skipping... : ".$e->getMessage());
}

//dispatch
slog("---------dispatching--------");
$frontController = Zend_Controller_Front::getInstance();

//add ticket viewer shortcut
$route = new Zend_Controller_Router_Route_Regex('(\d+)',
    array('controller'=>'viewer', 'action'=>'index'),
    array(1=>'id')
);
$frontController->getRouter()->addRoute('call', $route);

$frontController->setControllerDirectory('app/controls');
$frontController->dispatch();
slog("---------all done-----------");


text:
pushd wc_utils/util/chem/
javac GetMajorMicroSpecies.java
javac DrawMolecule.java
jar -cvf GetMajorMicroSpecies.jar GetMajorMicroSpecies.class
jar -cvf DrawMolecule.jar DrawMolecule.class
popd


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

<title>CellBrowser.Builder (GWT Javadoc)</title>
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Deprecated

Help

GWT 2.8.0-rc1

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

com.google.gwt.user.cellview.client

Class CellBrowser.Builder<T>

java.lang.Object

com.google.gwt.user.cellview.client.CellBrowser.Builder<T>

Type Parameters:

T - the type of data in the root node

Enclosing class:

CellBrowser

public static class CellBrowser.Builder<T>
extends java.lang.Object

Builder object to create CellBrowser.

Constructor Summary

Constructors

Constructor and Description

Builder(TreeViewModel viewModel,
       T rootValue)

Construct a new CellBrowser.Builder.

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

CellBrowser
build()

Creates a new CellBrowser.

CellBrowser.Builder<T>
loadingIndicator(Widget widget)

Set the widget to display when the data is loading.

CellBrowser.Builder<T>
pagerFactory(CellBrowser.PagerFactory factory)

Set the pager factory used to create pagers for each CellList.

CellBrowser.Builder<T>
pageSize(int pageSize)

Set the pager size for each CellList.

CellBrowser.Builder<T>
resources(CellBrowser.Resources resources)

Set resources used for images.

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

Builder

public Builder(TreeViewModel viewModel,
               T rootValue)

Construct a new CellBrowser.Builder.

Parameters:

viewModel - the TreeViewModel that backs the tree

rootValue - the hidden root value of the tree

Method Detail

build

public CellBrowser build()

Creates a new CellBrowser.

Returns:

new CellBrowser

loadingIndicator

public CellBrowser.Builder<T> loadingIndicator(Widget widget)

Set the widget to display when the data is loading.

Parameters:

widget - the loading indicator

Returns:

this

pagerFactory

public CellBrowser.Builder<T> pagerFactory(CellBrowser.PagerFactory factory)

Set the pager factory used to create pagers for each CellList.
 Defaults to PageSizePagerFactory if not set.

 Can be set to null if no pager should be used. You should also set pageSize
 big enough to hold all your data then.

Parameters:

factory - the pager factory

Returns:

this

pageSize

public CellBrowser.Builder<T> pageSize(int pageSize)

Set the pager size for each CellList.

Parameters:

pageSize - the page size

Returns:

this

resources

public CellBrowser.Builder<T> resources(CellBrowser.Resources resources)

Set resources used for images.

Parameters:

resources - the CellBrowser.Resources used for images

Returns:

this

Skip navigation links

Overview

Package

Class

Use

Deprecated

Help

GWT 2.8.0-rc1

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
package com.salesforce.storm.spout.dynamic.buffer;

import com.salesforce.storm.spout.dynamic.Message;
import com.salesforce.storm.spout.dynamic.MessageId;
import com.salesforce.storm.spout.dynamic.DefaultVirtualSpoutIdentifier;
import com.salesforce.storm.spout.dynamic.config.SpoutConfig;
import org.apache.storm.tuple.Values;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

import static org.awaitility.Awaitility.await;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertNull;

/**
 * Generally test the {@link MessageBuffer} interface's surface area.
 */
public class MessageBufferTest {

    private static final Logger logger = LoggerFactory.getLogger(MessageBufferTest.class);

    /**
     * Provides various tuple buffer implementation.
     */
    public static Object[][] provideMessageBuffers() throws InstantiationException, IllegalAccessException {
        return new Object[][]{
                { createInstance(FifoBuffer.class, 10000) },
                { createInstance(RoundRobinBuffer.class, 1000 ) },
        };
    }

    /**
     * Helper method for creating instances and configuring them.
     */
    private static MessageBuffer createInstance(Class clazz, int bufferSize) throws IllegalAccessException, InstantiationException {
        Map<String, Object> topologyConfig = new HashMap<>();
        topologyConfig.put(SpoutConfig.TUPLE_BUFFER_MAX_SIZE, bufferSize);

        MessageBuffer messageBuffer = (MessageBuffer) clazz.newInstance();
        messageBuffer.open(topologyConfig);

        return messageBuffer;
    }

    /**
     * Tests this instance against multiple threads for weirdness.
     */
    @ParameterizedTest
    @MethodSource("provideMessageBuffers")
    public void testConcurrentModification(final MessageBuffer messageBuffer) throws InterruptedException {
        // Settings for test
        final int numberOfVSpoutIds = 10;
        final int numberOfMessagesPer = 100000;
        final int numberOfThreads = 15;

        logger.info("Running test with {}", messageBuffer.getClass().getSimpleName());

        // Create executor service with number of threads = how many we want to run
        final ExecutorService executorService = Executors.newFixedThreadPool(numberOfThreads);

        // Create some threads
        final List<CompletableFuture> futures = new ArrayList<>();
        final CountDownLatch countDownLatch = new CountDownLatch(numberOfThreads);
        for (int threadCount = 0; threadCount < numberOfThreads; threadCount++) {
            futures.add(CompletableFuture.runAsync(() -> {
                final Random random = new Random();
                long longestTimeBlocked = 0L;

                // Use latch so all threads start at roughly the same time.
                countDownLatch.countDown();
                try {
                    countDownLatch.await();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }

                final long startTime = System.currentTimeMillis();
                for (int x = 0; x < (numberOfMessagesPer * numberOfVSpoutIds); x++) {
                    // Generate source spout id
                    final DefaultVirtualSpoutIdentifier sourceSpoutId = new DefaultVirtualSpoutIdentifier(
                        "srcSpoutId" + random.nextInt(numberOfVSpoutIds)
                    );
                    final int partition = random.nextInt(10);

                    Message message = new Message(
                        new MessageId("my namespace", partition, x, sourceSpoutId),
                        new Values("myValue" + x)
                    );

                    try {
                        final long startPutTime = System.currentTimeMillis();
                        messageBuffer.put(message);
                        final long putTime = System.currentTimeMillis() - startPutTime;
                        if (putTime > longestTimeBlocked) {
                            longestTimeBlocked = putTime;
                        }
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
                final long totalTime = System.currentTimeMillis() - startTime;
                logger.info("Thread finished in {} ms with longest blocked time {} ms", totalTime, longestTimeBlocked);
            }, executorService));
        }

        // Create a thread to read from it.
        int totalFound = 0;
        long totalNullsReturned = 0;
        int totalExpected = numberOfMessagesPer * numberOfVSpoutIds * numberOfThreads;
        logger.info("Expecting to find {} messages", totalExpected);
        while (totalFound != totalExpected) {
            if (messageBuffer.poll() != null) {
                totalFound++;
            } else {
                totalNullsReturned++;
            }

            // See if any problems with our futures
            for (CompletableFuture future : futures) {
                if (future.isCompletedExceptionally()) {
                    throw new RuntimeException("Failed to complete due to exception");
                }
            }

        }
        logger.info("Found {} messages with a total of {} nulls returned", totalFound, totalNullsReturned);

        // Wait for futures to be complete, at this point they should already be done tho.
        await()
            .atMost(5, TimeUnit.SECONDS)
            .until(() -> {
                // Validate the futures are completed
                for (Future future : futures) {
                    if (!future.isDone()) {
                        return false;
                    }
                }
                // All futures have completed.
                return true;
            }, equalTo(true));

        // Poll a bunch, validating nothing else returned
        for (int x = 0; x < 1024; x++) {
            assertNull(messageBuffer.poll(), "Should be null");
        }

        // Shutdown executor service
        executorService.shutdown();
        executorService.awaitTermination(3, TimeUnit.SECONDS);
        if (!executorService.isShutdown()) {
            executorService.shutdownNow();
        }
    }
}


text:
Airbase 129

* Checkstyle updates:
  - Require package name to match the source directory
* Dependency updates:
  - spotbugs-annotations 4.7.2 (from 4.3.0)
  - modernizer 2.4.0 (from 2.3.0)
  - joda-time 2.11.1 (from 2.10.13)
  - slf4j 1.7.36 (from 1.7.32)
  - checkstyle 10.3.3 (from 9.2)
  - Jackson 2.13.4 (from 2.13.3)
  - JMH 1.35 (from 1.32)
* Plugin updates:
  - checkstyle 3.2.0 (from 3.1.2)

Airbase 128

* Plugin updates:
  - JaCoCo 0.8.8 (from 0.8.7)
* Always define ``argLine`` property even if Jacoco is disabled, to ensure
  that Surefire configuration does not confuse IntelliJ IDEA

Airbase 127

* Checkstyle updates:
  - Forbid imports of shaded Apache code
* Dependency updates:
  - Logback 1.2.11 (from 1.2.3)

Airbase 126

* Fix the way locale information is passed to maven-surefire-plugin
* Plugin downgrades:
  - Surefire 3.0.0-M5 (from 3.0.0-M6)

Airbase 125

* Checkstyle updates:
  - Allow using "extends" and "implements" in a Java comment.
* Dependency update:
  - Jackson 2.13.3 (from 2.13.1)

Airbase 124

* Dependency updates:
  - Slice 0.42 (from 0.41)
* Plugin updates:
  - Surefire 3.0.0-M6 (from 3.0.0-M5)

Airbase 123

* Add `air.license.skip-existing-headers` property
* Dependency update:
  - Guava 31.1-jre (from 31.0.1-jre)
* Plugin updates:
  - maven-dependency-plugin 3.3.0 (from 3.1.2)

Airbase 122

* Fix enabling check plugins unless `air.check.skip-all` is set.

Airbase 121

* Fix Surefire setup when JaCoCo is disabled

Airbase 120

* Add dependencies:
  - Modernizer annotations 2.3.0
* Checkstyle updates:
  - Add `LCURLY` to `WhitespaceAround` to catch more whitespace issues
* Dependency updates:
  - Guice 5.1.0 (from 5.0.1)
  - Joda-Time 2.10.13 (from 2.10.10)
* Plugin updates:
  - update maven-compiler-plugin 3.9.0 (from 3.8.1)

Airbase 119

* Remove `air.test.skip` property. Use `skipTests` instead.

Airbase 117

* Add `air.test.skip` property for modules without tests
* Remove test providers from Surefire plugin. If a module needs both
  JUnit 5 and TestNG, it will need to add both providers to Surefire.
  Otherwise, the TestNG tests will be silently skipped.
* Dependency updates:
  - Jackson 2.13.1 (from 2.13.0)
* Plugin updates:
  - JaCoCo 0.8.7 (from 0.8.6)

Airbase 116

* Plugin updates:
  - Checkstyle 9.2 (from 9.1)

Airbase 114

* Dependency updates:
  - Guava 31.0.1-jre (from 30.1.1-jre)
  - Jackson 2.13.0 (from 2.12.3)
  - SpotBugs annotations 4.3.0 (from 4.2.3)
  - javax.ws.rs-api 2.1.1 (from 2.1)
  - slf4j 1.7.32 (from 1.7.30)
  - Slice 0.41 (from 0.39)
* Plugin updates:
  - Modernizer 2.3.0 (from 2.2.0)
  - git-commit-id-plugin 4.0.5 (from 4.0.3)
  - JUnit 5.8.1 (from 5.8.0-M1)
  - Checkstyle 9.1 (from 8.41.1)

Airbase 113

* Dependency updates:
  - JMH 1.32 (from 1.20)
* Plugin updates:
  - maven-enforcer-plugin 3.0.0 (from 3.0.0.M3)

Airbase 112

* Remove cglib
* Allow using commas in air.javadoc.lint
* Add JUnit 5.8.0-M1
* Fix build failure when module does not contain JUnit tests
* Fail build if no tests are executed
* Dependency updates:
  - Jackson 2.12.3 (from 2.12.2)
  - Joda-Time 2.10.10 (from 2.10.9)
  - SpotBugs annotations 4.2.3 (from 4.2.2)
* Plugin updates:
  - SpotBugs 4.2.3 (from 4.2.2)

Airbase 111

* Plugin updates:
  - Surefire 3.0.0-M5 (from 2.22.0)
* Checkstyle updates:
  - Enforce method naming

Airbase 110

* Dependency updates:
  - Jackson 2.12.2 (from 2.11.4)
  - SpotBugs annotations 4.2.2 (from 3.1.12)
* Plugin updates:
  - Checkstyle 3.1.2 (from 3.1.1)
* Checkstyle updates:
  - Version 8.41.1 (from 8.32)

Airbase 109

* Plugin updates:
  - Modernizer 2.2.0 (from 2.1.0)

Airbase 108

* Plugin updates:
  - Guava 30.1.1-jre (from 30.1-jre)
  - Guice 5.0.1 (from 4.2.3)
  - JaCoCo 0.8.6 (from 0.8.5)
  - SpotBugs 4.2.2 (from 3.1.12.2)

Airbase 107

* Configure maven-assembly-plugin to use posix tar mode

Airbase 106

* Remove `errorprone-compiler` profile.
* Dependency updates:
  - Apache BVal 2.0.5 (from 2.0.0)
  - Guava 30.1-jre (from 29.0-jre)
  - AssertJ core 3.18.1 (from 3.14.0)
  - Joda-Time 2.10.9 (from 2.10.6)
* Plugin updates:
  - maven-compiler-plugin 3.8.1 (from 3.8.0)
  - maven-resources-plugin 3.2.0 (from 2.6)
  - maven-assembly-plugin 3.3.0 (from 2.4)
  - maven-jar-plugin 3.2.0 (from 2.4)
  - license-maven-plugin 3.0 (from 2.3)
  - duplicate-finder-maven-plugin 1.5.0 (from 1.4.0)

Airbase 105

* Dependency updates:
  - Jackson 2.11.4 (from 2.10.5)
* Checkstyle updates:
  - Allow numbers in first part of package name

Airbase 104

* Speed up build by including only relevant properties in git-commit-id-plugin configuration

* Plugin updates:
  - git-commit-id-plugin 4.0.3 (from 4.0.2)

Airbase 103

* Dependency updates:
  - Jackson 2.10.5 (from 2.10.4)
  - Joda-Time 2.10.6 (from 2.10.5)
* Plugin updates:
  - git-commit-id-plugin 4.0.2 (from 4.0.0)
  - Javadoc 3.2.0 (from 3.0.1)
  - Extra Enforcer Rules 1.3 (from 1.2)
  - Modernizer 2.1.0 (from 1.7.1)
* Checkstyle updates:
  - Forbid imports of shaded Guava and OkHttp classes
  - Require static imports for methods from Preconditions and Verify
  - Require static imports for ImmutableList.toImmutableList method
  - Require static imports for ImmutableMap.toImmutableMap method
  - Require static imports for ImmutableSet.toImmutableSet method

Airbase 102

* Add dependencies:
  - jackson-dataformat-cbor
  - jackson-dataformat-ion
* Dependency updates:
  - Slice 0.39 (from 0.38)
  - Jackson 2.10.4 (from 2.10.3)
* Plugin updates:
  - dependency 3.1.2 (from 3.1.1)
  - Checkstyle 3.1.1 (from 3.1.0)
* Checkstyle updates:
  - Version 8.32 (from 8.25)

Airbase 101

* Set minimum Java version to 11
* Set minimum Maven version to 3.6.3
* Use `--release` option for compiler
* Add `air.compiler.fail-warnings` property

Airbase 100

* Add hook for altering surefire JVM argLine
* Add additional properties for release plugin
* Dependency updates:
  - Guava 29.0 (from 26.0)
* Checkstyle updates:
  - Allow camel case type parameter names

Airbase 99

* Dependency updates:
  - Slf4j 1.7.30 (from 1.7.29)
  - Jackson 2.10.3 (from 2.10.0)
  - Guice 4.2.3 (from 4.2.2)

Airbase 98

* Parameterize distributionManagement
* Plugin updates:
  - git commit id 4.0.0 (from 3.0.1)

Airbase 97

* Plugin updates:
  - Dependency Scope 0.10 (from 0.8)

Airbase 96

* Remove dependency:analyze-dep-mgt check
* Plugin updates:
  - Duplicate Finder 1.4.0 (from 1.2.1)

Airbase 95

* Dependency updates:
  - Joda-Time 2.10.5 (from 2.9.9)
  - Slice 0.38 (from 0.37)

Airbase 94

* Remove all AssertJ dependencies except Core
* Remove Hamcrest
* Remove Mockito
* Remove Objenesis
* Add shade plugin
* Allow specifying README location and type for launcher
* Dependency updates:
  - Slice 0.37 (from 0.34)
  - jmxutils 1.21 (from 1.19)
  - cglib 3.3.0 (from 3.2.5)
  - javax.annotation-api 1.3.2 (from 1.3.1)
  - javax.servlet-api 4.0.1 (from 3.1.0)
  - SLF4J 1.7.29 (from 1.7.28)
  - TestNG 6.10 (from 6.9.6)
  - AssertJ Core 3.14.0 (from 3.5.2)
* Plugin updates:
  - Enforcer 3.0.0-M3 (from 3.0.0-M2)
  - Extra Enforcer Rules 1.2 (from 1.1)

Airbase 93

* Require Maven version 3.3.9
* Dependency updates:
  - SpotBugs annotations 3.1.12 (from 3.1.10)
* Plugin updates:
  - JaCoCo 0.8.5 (from 0.8.2)
  - SpotBugs 3.1.12.2 (from 3.1.10)
  - PMD 3.12.0 (from 3.11.0)
  - git commit id 3.0.1 (from 2.1.13)
* Checkstyle updates:
  - Enforce placement of lambda's opening brace

Airbase 92

* Dependency updates:
  - Jackson 2.10.0 (from 2.9.8)
* Plugin updates:
  - Checkstyle 3.1.0 (from 3.0.0)
* Checkstyle updates:
  - Version 8.25 (from 8.16)
  - Allow multi character type variable names

Airbase 91

* Dependency updates:
  - Jackson 2.9.8 (from 2.9.7)
  - Add jackson-dataformat-yaml 2.9.8
* Plugin updates:
  - Sources 3.0.1 (from 2.2.1)
* Checkstyle updates:
  - Only allow numbers or lowercase letters in package names

Airbase 90

* Add property to configure Modernizer Java version
* Enforce maximum bytecode version for dependencies
* Allow dependency plugin to work with Java 11 bytecode
* Dependency updates:
  - Guava 26.0 (from 24.1)
  - Guice 4.2.2 (from 4.2.0)
  - SpotBugs annotations 3.1.10 (from 3.1.6)
* Plugin updates:
  - JaCoCo 0.8.2 (from 0.8.1)
  - Javadoc 3.0.1 (from 3.0.0)
  - Modernizer 1.7.1 (from 1.5.0)
  - PMD 3.11.0 (from 3.10.0)
  - SpotBugs 3.1.10 (from 3.1.6)

Airbase 89

* Set the default JVM local for Surefire tests to `en-US`
* Dependency updates:
  - validation-api 2.0.1 (from 1.1.0)
  - BVal 2.0.0 (from 1.1.1)
* Plugin updates:
  - Checkstyle 3.0.0 (from 2.17)
  - compiler 3.8.0 (from 3.7.0)
  - dependency 3.1.1 (from 2.10)
* Checkstyle updates:
  - Version 8.16 (from 8.7)
  - Enforce empty lines around program elements

Airbase 88

* Replace dependency-versions-check with Enforcer requireUpperBoundDeps
* Dependency updates:
  - Jackson 2.9.7 (from 2.8.1)

Airbase 87

* Generate parameters names also when compiling in IntelliJ

Airbase 86

* Checkstyle updates:
  - Do not enforce whitespace before array initializers

Airbase 85

* Do not allow duplicate dependencies in POMs

Airbase 84

* Do not trim stack traces for Surefire test failures
* Prevent JVM from omitting stack traces for Surefire
* Checkstyle updates:
  - Forbid static import of Optional's members
  - Enforce whitespace around additional tokens

Airbase 83

* Dependency updates:
  - SpotBugs annotations 3.1.6 (from 3.1.2)
* Plugin updates:
  - SpotBugs 3.1.6 (from 3.1.3)
  - PMD 3.10.0 (from 3.7)
  - JaCoCo 0.8.1 (from 0.7.9)
* Checkstyle updates:
  - Require simplified usages of annotations

Airbase 82

* Plugin updates:
  - Surefire 2.22.0 (from 2.20.1)
  - Enforcer 3.0.0-M2 (from 3.0.0-M1)

Airbase 81

* Guarantee termination of JVM on OOM when running Surefire
* Dependency updates:
  - Slice 0.34 (from 0.10)

Airbase 80

* Add milliseconds and time zone to log format for tests
* Dependency updates:
  - Guava 24.1 (from 21.0)
  - Guice 4.2 (from 4.0)
  - JMH 1.20 (from 1.15)
  - packaging 0.163 (from 0.91)
  - SpotBugs annotations 3.1.2 (from 3.1.0)
* Plugin updates:
  - compiler 3.7.0 (from 3.6.2)
  - Eclipse compiler 2.8.3 (from 2.8.2)
  - Error Prone compiler 2.8.3 (from 2.8.2)
  - SpotBugs 3.1.3 (from 3.1.0-RC8)
* Checkstyle updates:
  - Forbid import of format methods other than String.format

Airbase 79

* Use Apache license header from policy JAR
* Add Checkstyle as an extended checker

Airbase 78

* Prevent Surefire from adding java.se.ee module on Java 9
* Remove Eclipse m2e settings
* Dependency updates:
  - javax.annotation-api 1.3.1 (from 1.2)

Airbase 77

* Fix air.javadoc.lint property for Javadoc 3.0.0 plugin

Airbase 76

* Exclude Java 9 module-info.class from duplicate finder
* Dependency updates:
  - SpotBugs annotations 3.1.0 (from 3.1.0-RC5)
  - cglib 3.2.5 (from 2.2.2)
* Plugin updates:
  - SpotBugs 3.1.0-RC8 (from 3.1.0-RC4)
  - Javadoc 3.0.0 (from 2.9)
  - duplicate-finder 1.2.1 (from 1.0.6)

Airbase 75

* Enable compiled metadata for reflection on method parameters

Airbase 74

* Dependency updates:
  - Logback 1.2.3 (from 1.0.13)

Airbase 73

* Remove support for JUnit 5

Airbase 72

* Revert using Nexus Staging plugin

Airbase 71

* Use Nexus Staging plugin instead maven-deploy-plugin
* Dependency updates:
  - javax.ws.rs-api 2.1 (from 2.0.1)

Airbase 70

* Plugin updates:
  - maven-deploy-plugin 2.8.2 (from 2.7)
  - maven-clean-plugin 3.0.0 (from 2.5)
  - maven-install-plugin 2.5.2 (from 2.4)

Airbase 69

* Plugin updates:
  - Surefire 2.20.1 (from 2.20)
  - JUnit Jupiter Engine 5.0.0 (from 5.0.0-RC2)
  - JUnit Platform Surefire Provider (from 1.0.0-RC2)

Airbase 68

* Add support for JUnit 5
* Add dependency-scope as a basic checker
* Dependency updates:
  - SLF4J 1.7.25 (from 1.7.12)
* Plugin updates:
  - Surefire 2.20 (from 2.19.1)

Airbase 67

* Ban `com.google.code.findbugs:annotations` dependency
* Add dependencies:
  - FindBugs / SpotBugs annotations 3.1.0-RC5
  - JSR-305 annotations 3.0.2

Airbase 66

* Remove deprecated oss-parent POM
* Use `ossrh` as the ID for both deployment repositories
* Migrate from FindBugs to SpotBugs
* Plugin updates:
  - Enforcer 3.0.0-M1 (from 1.2)

Airbase 65

* Add `eclipse-compiler` profile for building with Eclipse compiler
* Add `errorprone-compiler` profile for building with Error Prone compiler
* Plugin updates:
  - compiler 3.6.2 (from 3.0)

Airbase 64

* Dependency updates:
  - Joda-Time 2.9.9 (from 2.8.2)

Airbase 63

* Plugin updates:
  - FindBugs 3.0.4 (from 2.5.2)
  - PMD 3.7 (from 3.0.1)
  - JaCoCo 0.7.9 (from 0.7.5.201505241946)

Airbase 62

* Dependency updates:
  - Guava 21.0 (from 20.0)

Airbase 61

* Add Modernizer as an extended checker

Airbase 60

* Add dependencies:
  - AssertJ Core 3.5.2
  - AssertJ Guava 3.1.0
  - AssertJ Joda-Time 2.0.0
  - AssertJ DB 1.1.1
* Dependency updates:
  - Guava 20.0 (from 18.0)

Airbase 59

* Remove air.test.fork-mode property
* Dependency updates:
  - JMH 1.15 (from 1.13)
* Plugin updates:
  - Surefire 2.19.1 (from 2.14)

Airbase 58

* Plugin updates:
  - dependency-versions-check 2.0.4 (from 2.0.2)

Airbase 57

* Remove dependency for jackson-datatype-jdk7
* Dependency updates:
  - Jackson 2.8.1 (from 2.4.4)

Airbase 56

* Dependency updates:
  - JMH 1.13 (from 1.9.3)
  - BVal 1.1.1 (from 0.5)

Airbase 55

* Remove Jetty dependencies
* Remove Jersey dependencies

Airbase 54

* Dependency updates:
  - Jetty 9.3.9.M1 (from 9.3.9.M0)

Airbase 53

* Add Jetty http2-server dependency

Airbase 52

* Add dependencies:
  - Jetty http2-client
  - Jetty http2-http-client-transport
* Dependency updates:
  - Jetty 9.3.9.M0 (from 9.3.8.v20160314)

Airbase 51

* Add jersey-container-servlet dependency
* Dependency updates:
  - Jersey 2.22.2 (from 2.12)

Airbase 50

* Dependency updates:
  - Jetty 9.3.8.v20160314 (from 9.3.8.RC0)

Airbase 49

* Dependency updates:
  - Jetty 9.3.8.RC0 (from 9.3.7.RC0)

Airbase 48

* Dependency updates:
  - jmxutils 1.19 (from 1.18)

Airbase 47

* Dependency updates:
  - Jetty 9.3.7.RC0 (from Jetty 9.2.11.v20150529)

Airbase 46

* Dependency updates:
    - TestNG, exclude transitive guice dependency

Airbase 45

* Dependency updates:
    - Jacoco 0.7.5.201505241946 (from 0.6.2.201302030002). Fixes a compatibility issue with Java 8

Airbase 44

* Dependency updates:
    - TestNG 6.9.6 (from 6.8.7)
    - Guice 4.0 (from 4.0-beta5)

Airbase 43

* Dependency updates:
    - Joda 2.8.2 (from 2.8). Fixes a compatibility issue with Java 8u60

Airbase 42

* Allow configuring minimum Java version with air.java.version

Airbase 41

* Add dependency for jackson-datatype-jdk7
* Dependency updates:
 - slf4j 1.7.12 (from 1.7.5)

Airbase 40

* Dependency updates:
  - Jetty 9.2.11.v20150529 (from Jetty 9.2.11.M0)
* Add jmh 1.9.3 dependency

Airbase 39

* Dependency updates:
  - Joda 2.8 (from 2.4)

Airbase 38

* JVM size can be configured running tests.
* Configure lint mode for Javadoc.
* Add CI profile that builds Javadoc.

Airbase 37

* Capture Git versioning information in jar manifest.
* Time zone, parallel and thread count can be configured for Surefire.
* Improve JDK logging format used when running tests.

Airbase 36

* Dependency updates:
  - Jetty 9.2.11.M0 (from 9.2.10.v20150310)

Airbase 35

* Dependency updates:
  - Jetty 9.2.10.v20150310 (from 9.2.8.v20150217)

Airbase 34

* Dependency updates:
  - Guice 4.0-beta5 (from 3.0)

Airbase 33

* Dependency updates:
  - Jetty 9.2.8.v20150217 (from 9.2.2.v20140723)

Airbase 32

* Dependency updates:
  - Slice 0.10 (from 0.6)
  - maven-dependency-plugin 2.10 (from 2.9).

Airbase 31

* Fix dependency jackson-module-parameter-names
* Add ANTLR files to license checker

Airbase 30

* Use Java 8 by default
* Add dependencies:
  - jackson-datatype-jdk8
  - jackson-datatype-jsr310
  - jackson-module-parameter-names
* Dependency updates:
  - Jackson 2.4.4 (from 2.4.2)

Airbase 29

* Dependency updates:
  - maven-dependency-plugin 2.9 (from 2.8). This version is compatible with Java 8

Airbase 28

* Dependency updates:
  - Guava 18.0 (from 16.0.1)

Airbase 27

* Set minimum Maven version to 3.2.3
* Exclude .sql files from license checker

Airbase 26

* Dependency updates:
  - Jetty 9.2.2.v20140723 (from 9.1.4.v20140401)
  - Jersey 2.12 (from 2.9.1)
  - Jackson 2.4.2 (from 2.1.4 and 2.1.2)

Airbase 25

* Dependency updates:
  - joda-time 2.4 (from 2.1)

Airbase 24

* Add dependencies for javax.annotation-api and javax.ws.rs-api
* Dependency updates:
  - Jersey 2.9.1 (from 1.17.1)

Airbase 23

* Dependency updates:
  - findbugs-annotations 2.0.3 (from 2.0.2)

Airbase 22

* Dependency updates:
  - jmxutils 1.18 (from 1.16)
  - slice 0.6 (from 0.5)
  - packaging 0.91 (from 0.82)

Airbase 21

* Ignore conflicting THIRD-PARTY in resources

Airbase 20

* Add dependencies for jetty-client and jetty-io

Airbase 19

* Dependency updates:
  - Jetty 9.1.4.v20140401 (from Jetty 9.1.3.v20140225)

Airbase 18

* Add dependency for io.airlift:slice:0.5
* Dependency updates:
  - jmxutils 1.16 (from 1.14)
  - Jetty 9.1.3.v20140225 (from 9.1.2.v20140210)

Airbase 17

* Update release plugin to 2.5

Airbase 16

* Fix dependency checker for Airlift HTTP libraries
* Add OSS snapshots as a plugin repository
* Update OSS base POM to 9
* Dependency updates:
 - javax.servlet 3.1.0 (from 3.0.1)
 - Jetty 9.1.2.v20140210 (from 8.1.9.v20130131)
* Plugin updates:
 - dependency 2.8 (from 2.7)
 - duplicate-finder 1.0.6 (from 1.0.4)

Airbase 15

* Set minimum Maven version to 3.1.1

Airbase 14

* Set memory size for compiler by enabling fork mode
* Remove dependency ban for junit 4.11+
* Dependency updates:
 - findbugs-annotations 2.0.2 (from 2.0.1)
 - jmxutils 1.14 (from 1.13)
 - testng 6.8.7 (from 6.8)
 - guava 16.0.1 (from 15.0)

Airbase 13

* Update airlift version to 0.82 to avoid launcher bug
* Remove parameters from SCM configuration
* Dependency updates:
 - Guava 15.0 (from 14.0.1)
 - slf4j 1.7.5 (from 1.7.2)
 - logback 1.0.13 (from 1.0.8)
 - validation-api 1.1.0.Final (from 1.0.0.GA)

Airbase 12

* Fix building in Eclipse

Airbase 11

* Run checks in the earliest possible phase

Airbase 10

* Update license plugin to 2.3

Airbase 9

* Update airlift version to 0.80 to avoid launcher bug

Airbase 8

* Update build-airlift for launcher rewrite

Airbase 7

* Remove erroneous git commit info from jar versions
* Remove mavanagaiata plugin

Airbase 6

* Dependency updates:
 - Guava 14.0.1 (from 14.0)
* Ban former experimental airlift modules
* Updated release plugin from 2.2.2 to 2.3.2
* Updated surefire plugin from 2.13 to 2.14
* set goal and arguments for release plugin

Airbase 5

* Updated pmd plugin to 3.0.1 from 3.0
* Updated dependency plugin to 2.7 from 2.6
* Added rule to enforce main class property being present when building airlift package.
* Added slf4j-jdk14 to the list of managed dependencies.

Airbase 4

* [BUGFIX] build-airlift profile puts main class and classpath into the main jar.

Airbase 3

* Fork mode can be configured with air.test.fork-mode.
* Re-enable mavanagaiata plugin to add git information to built jars
* Add profile to build a tarball using airlift packaging.

* Dependency updates:
 - Jersey 1.17.1 (from 1.17)
 - Guava 14.0 (from 13.0.1)
 - Jackson core, databind, dataformat-smile 2.1.4 (from 2.1.3)
 - Jackson annotations 2.1.4 (from 2.1.2)

* Plugin updates:
 - dependency plugin 2.7 (from 2.6)

Airbase 2

* Bug fix: air.check.skip-jacoco did not work

Airbase 1

* Initial release


text:
/*!
 * \file
 * \brief Class module::Encoder_RA.
 */
#ifndef ENCODER_RA_HPP_
#define ENCODER_RA_HPP_

#include <vector>
#include <memory>

#include "Module/Interleaver/Interleaver.hpp"
#include "Module/Encoder/Encoder.hpp"

namespace aff3ct
{
namespace module
{
template <typename B = int>
class Encoder_RA : public Encoder<B>
{
protected:
	const int rep_count; // number of repetitions
	std::vector<B> U, tmp_X_N;

	std::shared_ptr<Interleaver<B>> interleaver;

public:
	Encoder_RA(const int& K, const int& N, const Interleaver<B>& interleaver);

	virtual ~Encoder_RA() = default;

	virtual Encoder_RA<B>* clone() const;

	virtual void set_n_frames(const size_t n_frames);

protected:
	virtual void deep_copy(const Encoder_RA<B> &m);
	void _encode(const B *U_K, B *X_N, const size_t frame_id);
};
}
}

#endif // ENCODER_RA_HPP_


text:
NNPID=`ps aux | grep java | grep proc_namenode | grep -v grep | awk '{ print $2; }'`
DNPID=`ps aux | grep java | grep proc_datanode | grep -v grep | awk '{ print $2; }'`
ZKPID=`ps aux | grep java | grep QuorumPeerMain | grep -v grep | awk '{ print $2; }'`
HMASTERPID=`ps aux | grep java | grep HMaster | grep -v grep | awk '{ print $2; }'`
HREGIONPID=`ps aux | grep java | grep HRegionServer | grep -v grep | awk '{ print $2; }'`
RESOURCEMGRPID=`ps aux | grep java | grep ResourceManager | grep -v grep | awk '{ print $2; }'`
NODEMGRPID=`ps aux | grep java | grep NodeManager | grep -v grep | awk '{ print $2; }'`
KAFAKAPID=`ps aux | grep java | grep Kafka | grep -v grep | awk '{ print $2; }'`

echo NNPID:$NNPID
echo DNPID:$DNPID
echo ZKPID:$ZKPID
echo HMASTERPID:$HMASTERPID
echo HREGIONPID:$HREGIONPID
echo RESOURCEMGRPID:$RESOURCEMGRPID
echo NODEMGRPID:$NODEMGRPID
echo KAFAKAPID:$KAFAKAPID

if [ -n $NNPID ]; then
  kill -9 $NNPID
fi

if [ -n $DNPID ]; then
  kill -9 $DNPID
fi

if [ -n $ZKPID ]; then
  kill -9 $ZKPID
fi

if [ -n $HMASTERPID ]; then
  kill -9 $HMASTERPID
fi

if [ -n $HREGIONPID ]; then
  kill -9 $HREGIONPID
fi

if [ -n $RESOURCEMGRPID ]; then
  kill -9 $RESOURCEMGRPID
fi

if [ -n $NODEMGRPID ]; then
  kill -- $NODEMGRPID
fi

if [ -n $KAFAKAPID ]; then
  kill -9 $KAFAKAPID
  rm -rf /data/kafka/queues/*
fi


text:
<?php

class newsletter {

	protected $id;
	protected $email;
	protected $code;
	protected $date;
	protected $date_update;
	protected $state;

	public function __construct() {

	}

	public function setId($i) {
		$this->id = $i;
	}

	public function setEmail($e) {
		$this->email = $e;
	}

	public function setCode($c = null) {
		$this->code = sha1(md5(sha1(md5(time() . "_" . $c))));
	}

	public function setDate() {
		$this->date = date('Y-m-d H:i:s', time());
	}

	public function setDateUpdate() {
		$this->date_update = date('Y-m-d H:i:s', time());
	}

	public function insert() {
		global $configuration, $mysqli;

		$query = sprintf(
			"INSERT INTO %s_newsletters (email, code, date) VALUES ('%s','%s','%s')",
			$configuration['mysql-prefix'], $this->email, $this->code, $this->date
		);

		$toReturn = $mysqli->query($query);

		$this->id = $mysqli->insert_id;

		return $toReturn;
	}

	public function update() {
		global $configuration, $mysqli;

		$query = sprintf(
			"UPDATE %s_newsletters SET email = '%s', code = '%s', date_update = '%s' WHERE id = '%s'",
			$configuration['mysql-prefix'], $this->email, $this->code, $this->date_update, $this->id
		);

		return $mysqli->query($query);
	}

	public function delete() {
		global $configuration, $mysqli;

		$query = sprintf(
			"DELETE FROM %s_newsletters WHERE id = '%s'",
			$configuration['mysql-prefix'], $this->id
		);

		return $mysqli->query($query);
	}

	public function returnObject() {
		return array(
			'email' => $this->email,
			'code' => $this->code,
			'date' => $this->date,
			'date_update' => $this->date_update
		);
	}

	public function returnOneRegistry() {
		global $configuration, $mysqli;

		$query = sprintf(
			"SELECT * FROM %s_newsletters WHERE id = '%s' LIMIT 1",
			$configuration['mysql-prefix'], $this->id
		);
		$source = $mysqli->query($query);

		if ($source->num_rows > 0) {
			return $source->fetch_assoc();
		}

		return false;
	}

	public function returnOneRegistryByEmail() {
		global $configuration, $mysqli;

		$query = sprintf(
			"SELECT * FROM %s_newsletters WHERE email = '%s' LIMIT 1",
			$configuration['mysql-prefix'], $this->email
		);
		$source = $mysqli->query($query);

		if ($source->num_rows > 0) {
			return $source->fetch_assoc();
		}

		return false;
	}

	public function existRegistryByEmail() {
		global $configuration, $mysqli;

		$query = sprintf(
			"SELECT * FROM %s_newsletters WHERE email = '%s' LIMIT 1",
			$configuration['mysql-prefix'], $this->email
		);
		$source = $mysqli->query($query);

		return $source->num_rows;
	}

	public function existRegistryByCode() {
		global $configuration, $mysqli;

		$query = sprintf(
			"SELECT * FROM %s_newsletters WHERE code = '%s' LIMIT 1",
			$configuration['mysql-prefix'], $this->code
		);
		$source = $mysqli->query($query);

		return $source->num_rows;
	}

	public function returnAllRegistries() {
		global $configuration, $mysqli;

		$query = sprintf(
			"SELECT * FROM %s_newsletters WHERE true",
			$configuration['mysql-prefix']
		);
		$source = $mysqli->query($query);

		$toReturn = array();
		$i = 0;

		while ($data = $source->fetch_assoc()) {
			$toReturn[$i] = $data;
			$i++;
		}

		return $toReturn;
	}

	public function enable() {
		global $configuration, $mysqli;

		$query = sprintf(
			"UPDATE %s_newsletters SET active = '%s' WHERE id = '%s'",
			$configuration['mysql-prefix'], true, $this->id
		);
		return $mysqli->query($query);
	}

	public function disable() {
		global $configuration, $mysqli;

		$query = sprintf(
			"UPDATE %s_newsletters SET active = '%s' WHERE id = '%s'",
			$configuration['mysql-prefix'], false, $this->id
		);
		return $mysqli->query($query);
	}

}


text:
import argparse

def ParseEval(p_ev):
    ev_inp = p_ev.add_argument_group('Input options')
    ev_inp.add_argument('-c', dest='chrom', help='Target Chromosome', metavar='<chromosome>')
    ev_inp.add_argument('-b', dest='beg', help='Start Coordinate', type=int, metavar='<int>')
    ev_inp.add_argument('-e', dest='end', help='End Coordinate', type=int, metavar='<int>')
    ev_inp.add_argument('-s', dest='sg', help='sgRNA Information Table', metavar='<sg file>')
    ev_inp.add_argument('-m', dest='sfunc', required=True, help='Evaluation Model (required)', metavar='<pkl file>')

    ev_otp = p_ev.add_argument_group('Output options')
    ev_otp.add_argument('-o', dest='tdir', help='Output Directory, default = .', default='.', metavar='<output directory>')

    ev_par = p_ev.add_argument_group('Parameter options')
    ev_par.add_argument('-g', dest='ref', required=True, help='Reference Genome (required)', metavar='<ref genome>')
    ev_par.add_argument('-d', dest='drct', help='Scan Direction (default = two-sided)', default='two-sided', choices=('two-sided', 'pos', 'neg'), metavar='<two-sided|pos|neg>')
    ev_par.add_argument('-t', dest='thrd', help='Threads for BWA, default = 1', default=1, type=int, metavar='<int>')


text:
Controlled Vocabulary
====================

This project provides tools to control the vocabulary of email and meeting communications so that recipients may implement more effective filtering.

*Are you a member of an email discussion alias which is out of control? Do you battle to filter the messages? Take a look at the solution provided by this project to bring your alias under control again.*

The driving motivation behind this project is that  Controlled Vocabulary is a more effective method of categorizing emails than an open tagging system, which is too subjective.

This project provides an Outlook 2010 and Windows Client to support the adoption of a Controlled Vocabulary, e.g. the Outlook 2010 Add-in is shown below

![](http://download-codeplex.sec.s-msft.com/Download?ProjectName=ControlledVocabulary&DownloadId=112072)

Clicking the selected option would result in an email or meeting to the configured alias with the specific subject line

![](http://download-codeplex.sec.s-msft.com/Download?ProjectName=ControlledVocabulary&DownloadId=112073)


text:
#set( $symbol_pound = '#' )
#set( $symbol_dollar = '$' )
#set( $symbol_escape = '\' )
package ${package}.dao;

import java.util.List;

import org.hibernate.Hibernate;
import org.springframework.stereotype.Repository;
import ${package}.entity.user.User;
import org.springside.modules.orm.hibernate.HibernateDao;

/**
 * 用户对象的泛型DAO.
 *
 * @author calvin
 */
@Repository
public class UserDao extends HibernateDao<User, Long> {
	// 统一定义所有以用户为主体的HQL.
	public static final String QUERY_BY_LNAME_PASSWD = "select count(u) from User u where u.loginName=? and u.password=?";

	/**
	 * 关联对象初始化函数.
	 */
	public void initAllProperties(List<User> userList) {
		for (User user : userList) {
			Hibernate.initialize(user.getRoles());
		}
	}
}


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

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>controllers Package — qikify  documentation</title>

    <link rel="stylesheet" href="_static/default.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />

    <link rel="top" title="qikify  documentation" href="index.html" />
    <link rel="up" title="qikify Package" href="qikify.html" />

Navigation

          index

          modules |

          modules |

qikify  documentation »

qikify Package »

controllers Package¶

<tt class="xref py py-mod docutils literal">KDE</tt> Module¶

class <tt class="descclassname">qikify.controllers.KDE.</tt><tt class="descname">KDE</tt>[source]¶

Bases: <tt class="xref py py-class docutils literal">object</tt>

This class implements non-parametric kernel density estimation.

Methods

<colgroup>
<col width="10%" />
<col width="90%" />
</colgroup>

<tt class="xref py py-obj docutils literal">run</tt>(X[, specs, nSamples, counts, a, bounds])
Primary execution point.

<tt class="descname">run</tt><big>(</big>X, specs=None, nSamples=0, counts=None, a=0, bounds=None<big>)</big>[source]¶

Primary execution point. Run either standard KDE or class-membership based KDE. If
any of the class-membership based KDE arguments are set, it will be run instead of
standard KDE.

<col class="field-name" />
<col class="field-body" />

Parameters :
X : array_like

Contains data stored in a pandas.DataFrame.

nSamples : int

The number of samples to generate.

specs : qikify.models.Specs, optional

If using partitioned sampling, boundaries defining pass/critical/fail subspaces must be provided.

counts : dict, optional

If using partitioned sampling, counts dictionary must be provided, with three keys: nGood, nCritical, nFail.

<tt class="xref py py-mod docutils literal">LSFS</tt> Module¶

class <tt class="descclassname">qikify.controllers.LSFS.</tt><tt class="descname">LSFS</tt>[source]¶

Bases: <tt class="xref py py-class docutils literal">object</tt>

Methods

<colgroup>
<col width="10%" />
<col width="90%" />
</colgroup>

<tt class="xref py py-obj docutils literal">constructS</tt>(X, gnd[, k, t, bLDA, bSelfConnected])

<tt class="xref py py-obj docutils literal">run</tt>(Xin, gnd)
Run Laplacian Score Feature Selection.

<tt class="xref py py-obj docutils literal">threshold</tt>(T_L)

<tt class="descname">constructS</tt><big>(</big>X, gnd, k=0, t=1, bLDA=False, bSelfConnected=True<big>)</big>[source]¶

<tt class="descname">run</tt><big>(</big>Xin, gnd<big>)</big>[source]¶

Run Laplacian Score Feature Selection.

Note

Eventually, it’d be nice to maintain col names with Xin so that we can add a plot method to plot scores vs. column names.

<col class="field-name" />
<col class="field-body" />

Parameters :
Xin : array_like

A numpy.ndarray or pandas.DataFrame, with rows corresponding to observations and columns to features.

gnd : array_like

A numpy.ndarray or pandas.DataFrame pass/fail vector of the same dimension as Xin

Notes

This code is based on the definition from the paper [R1]:

<colgroup><col class="label" /><col /></colgroup>

[R1]	He, X. and Cai, D. and Niyogi, P., “Laplacian Score for Feature Selection”, NIPS 2005.

<tt class="descname">threshold</tt><big>(</big>T_L<big>)</big>[source]¶

<tt class="xref py py-mod docutils literal">OLS</tt> Module¶

class <tt class="descclassname">qikify.controllers.OLS.</tt><tt class="descname">OLS</tt>[source]¶

Bases: <tt class="xref py py-class docutils literal">object</tt>

Ordinary least squares multivariate regression.

Methods

<colgroup>
<col width="10%" />
<col width="90%" />
</colgroup>

<tt class="xref py py-obj docutils literal">JB</tt>()
Calculate residual skewness, kurtosis, and do the JB test for normality

<tt class="xref py py-obj docutils literal">computeStatistics</tt>()

<tt class="xref py py-obj docutils literal">dw</tt>()
Calculates the Durbin-Waston statistic

<tt class="xref py py-obj docutils literal">ll</tt>()
Calculate model log-likelihood and two information criteria

<tt class="xref py py-obj docutils literal">omni</tt>()
Omnibus test for normality

<tt class="xref py py-obj docutils literal">train</tt>(X, y[, useQR, addConstant])
Solve y = Xb.

<tt class="descname">JB</tt><big>(</big><big>)</big>[source]¶

Calculate residual skewness, kurtosis, and do the JB test for normality

<tt class="descname">computeStatistics</tt><big>(</big><big>)</big>[source]¶

<tt class="descname">dw</tt><big>(</big><big>)</big>[source]¶

Calculates the Durbin-Waston statistic

<tt class="descname">ll</tt><big>(</big><big>)</big>[source]¶

Calculate model log-likelihood and two information criteria

<tt class="descname">omni</tt><big>(</big><big>)</big>[source]¶

Omnibus test for normality

<tt class="descname">train</tt><big>(</big>X, y, useQR=True, addConstant=True<big>)</big>[source]¶

Solve y = Xb.

<col class="field-name" />
<col class="field-body" />

Parameters :
x : array, shape (M, N)

y : array, shape (M,)

useQR : boolean

Whether or not to use QR decomposition to fit regression line.

addConstant: boolean :

Whether or not to add a constant column to X

<tt class="xref py py-mod docutils literal">QFFS</tt> Module¶

class <tt class="descclassname">qikify.controllers.QFFS.</tt><tt class="descname">QFFS</tt>[source]¶

Bases: <tt class="xref py py-class docutils literal">object</tt>

Qikify feature selection library. Doesn’t do much yet; right now only implements
correlation coefficient-based feature selection.

Methods

<colgroup>
<col width="10%" />
<col width="90%" />
</colgroup>

<tt class="xref py py-obj docutils literal">computeCorrCoefs</tt>(X, y)
Returns the correlation coefficients between X and y,

<tt class="xref py py-obj docutils literal">run</tt>(X, y[, n_features, intercept, method])
Do feature selection on the basis of correlation coefficients.

<tt class="descname">computeCorrCoefs</tt><big>(</big>X, y<big>)</big>[source]¶

Returns the correlation coefficients between X and y,
along with the arg-sorted indices of ranked most-correlated X-to-y vars.

<tt class="descname">run</tt><big>(</big>X, y, n_features=10, intercept=True, method='corrcoef'<big>)</big>[source]¶

Do feature selection on the basis of correlation coefficients.

<col class="field-name" />
<col class="field-body" />

Parameters :
X : numpy array of shape [n_samples,n_features]

Training data

y : numpy array of shape [n_samples]

Target values

n_features : int, optional

Number of features to retain

intercept : bool, optional

Whether the first column is an all-constant intercept and
should be excluded

method : string, optional

Determines the feature selection method to use.

Returns :
features : The X column indices to retain.

Notes

We typically exclude the first column since it is the intercept
all-constant column.

<tt class="xref py py-mod docutils literal">SVM</tt> Module¶

class <tt class="descclassname">qikify.controllers.SVM.</tt><tt class="descname">SVM</tt>[source]¶

Bases: <tt class="xref py py-class docutils literal">object</tt>

Methods

<colgroup>
<col width="10%" />
<col width="90%" />
</colgroup>

<tt class="xref py py-obj docutils literal">getTEYL</tt>(gnd, predicted)

<tt class="xref py py-obj docutils literal">predict</tt>(X)

<tt class="xref py py-obj docutils literal">train</tt>(X, gnd[, gridSearch])

<tt class="descname">getTEYL</tt><big>(</big>gnd, predicted<big>)</big>[source]¶

<tt class="descname">predict</tt><big>(</big>X<big>)</big>[source]¶

<tt class="descname">train</tt><big>(</big>X, gnd, gridSearch=False<big>)</big>[source]¶

<tt class="xref py py-mod docutils literal">identifyOutliers</tt> Module¶

<tt class="descclassname">qikify.controllers.identifyOutliers.</tt><tt class="descname">identifyOutliers</tt><big>(</big>data, k=3<big>)</big>[source]¶

Compare a dataset against mu +/- k*sigma limits, and
return a boolean vector with False elements denoting outliers.

<col class="field-name" />
<col class="field-body" />

Parameters :	data : Contains data stored in a pandas DataFrame or Series.

<tt class="descclassname">qikify.controllers.identifyOutliers.</tt><tt class="descname">identifyOutliersSpecs</tt><big>(</big>data, specs, ind, k=3<big>)</big>[source]¶

Compare a dataset against expanded spec limits, and
return a boolean vector with False elements denoting outliers.

<col class="field-name" />
<col class="field-body" />

Parameters :	data : Contains data stored in a pandas DataFrame or Series.

<tt class="xref py py-mod docutils literal">interpolate</tt> Module¶

<tt class="descclassname">qikify.controllers.interpolate.</tt><tt class="descname">bilinear_interp</tt><big>(</big>x, y, xlim, ylim, Q<big>)</big>[source]¶

bilinear interpolation of z over 2d surface {x,y}

<tt class="descclassname">qikify.controllers.interpolate.</tt><tt class="descname">cart2polar</tt><big>(</big>x, y<big>)</big>[source]¶

<tt class="descclassname">qikify.controllers.interpolate.</tt><tt class="descname">cart2polar_recenter</tt><big>(</big>x, y, xmax, ymax<big>)</big>[source]¶

<tt class="descclassname">qikify.controllers.interpolate.</tt><tt class="descname">lerp</tt><big>(</big>x, xlim, ylim<big>)</big>[source]¶

linearly interpolate a value of y given ranges for x, y.

arguments:

x: scalar
xlim: array with xmin, xmax
ylim: array with ymin, ymax

<tt class="descclassname">qikify.controllers.interpolate.</tt><tt class="descname">polar2cart</tt><big>(</big>r, theta<big>)</big>[source]¶

<tt class="descclassname">qikify.controllers.interpolate.</tt><tt class="descname">polar2cart_recenter</tt><big>(</big>r, theta, xmax, ymax<big>)</big>[source]¶

<tt class="xref py py-mod docutils literal">slicesample</tt> Module¶

<tt class="descclassname">qikify.controllers.slicesample.</tt><tt class="descname">inside</tt><big>(</big>x, th, pdf<big>)</big>[source]¶

<tt class="descclassname">qikify.controllers.slicesample.</tt><tt class="descname">logpdf</tt><big>(</big>x, pdf<big>)</big>[source]¶

<tt class="descclassname">qikify.controllers.slicesample.</tt><tt class="descname">outside</tt><big>(</big>x, th, pdf<big>)</big>[source]¶

<tt class="descclassname">qikify.controllers.slicesample.</tt><tt class="descname">slicesample</tt><big>(</big>x0, nsamples, pdf, width=10, maxiter=200<big>)</big>[source]¶

Loosely based on slicesample() from MATLAB.

Table Of Contents

controllers Package

<tt class="docutils literal">KDE</tt> Module

<tt class="docutils literal">LSFS</tt> Module

<tt class="docutils literal">OLS</tt> Module

<tt class="docutils literal">QFFS</tt> Module

<tt class="docutils literal">SVM</tt> Module

<tt class="docutils literal">identifyOutliers</tt> Module

<tt class="docutils literal">interpolate</tt> Module

<tt class="docutils literal">slicesample</tt> Module

This Page

Show Source

Quick search

    <form class="search" action="search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

    Enter search terms or a module, class or function name.

Navigation

          index

          modules |

          modules |

qikify  documentation »

qikify Package »

        © Copyright 2012, Author.
      Created using Sphinx 1.1.3.


text:
package org.wso2.carbon.apimgt.impl.template;

import org.apache.velocity.VelocityContext;
import org.wso2.carbon.apimgt.api.model.API;
import org.wso2.carbon.apimgt.api.model.APIProduct;
import org.wso2.carbon.apimgt.api.model.APIProductIdentifier;
import org.wso2.carbon.apimgt.impl.APIConstants;

/**
 * This will initialise a velocity context to used in the template
 * and populate it with api name, version and context and a reference to api
 */
public class APIConfigContext extends ConfigContext {

    private API api;
    private APIProduct apiProduct;
    private static final String PRODUCT_PREFIX = "prod";

    public APIConfigContext(API api) {
        this.api = api;
    }

    public APIConfigContext(APIProduct apiProduct) {
        this.apiProduct = apiProduct;
    }

    @Override
    public void validate() throws APITemplateException {
        //see if api name ,version, context sets
        /*if(this.getAPIName(api) && api.getContext() && api.getId().getVersion()){
            return;
        }
        else{
            this.handleException("Required API mapping not provided");
        }
        */
    }

    @Override
    public VelocityContext getContext() {
        VelocityContext context = new VelocityContext();

        if (api != null) {
            setApiVelocityContext(api, context);
        } else if (apiProduct != null) { // API Product scenario
            setApiProductVelocityContext(apiProduct, context);
        }

        return context;
    }

    private void setApiVelocityContext(API api, VelocityContext context) {
        //set the api name version and context
        context.put("apiName", this.getAPIName(api));
        context.put("apiVersion", api.getId().getVersion());
        context.put("UUID", api.getUUID());

        // We set the context pattern now to support plugable version strategy
        // context.put("apiContext", api.getContext());
        context.put("apiContext", api.getContextTemplate());

        //the api object will be passed on to the template so it properties can be used to
        // customise how the synapse config is generated.
        context.put("apiObj", api);

        if (APIConstants.BLOCKED.equals(api.getStatus())) {
            context.put("apiIsBlocked", Boolean.TRUE);
        } else {
            context.put("apiIsBlocked", Boolean.FALSE);
        }
        String apiSecurity = api.getApiSecurity();
        if (apiSecurity == null || apiSecurity.contains(APIConstants.DEFAULT_API_SECURITY_OAUTH2)) {
            context.put("apiIsOauthProtected", Boolean.TRUE);
        } else {
            context.put("apiIsOauthProtected", Boolean.FALSE);
        }
        if (api.isEnabledSchemaValidation()) {
            context.put("enableSchemaValidation", Boolean.TRUE);
        } else {
            context.put("enableSchemaValidation", Boolean.FALSE);
        }
    }

    private void setApiProductVelocityContext(APIProduct apiProduct, VelocityContext context) {
        APIProductIdentifier id = apiProduct.getId();
        //set the api name version and context
        context.put("apiName", PRODUCT_PREFIX + "--" + id.getName());
        context.put("apiVersion", "1.0.0");

        // We set the context pattern now to support plugable version strategy
        // context.put("apiContext", api.getContext());
        context.put("apiContext", apiProduct.getContext());

        //the api object will be passed on to the template so it properties can be used to
        // customise how the synapse config is generated.
        context.put("apiObj", apiProduct);

        context.put("apiIsBlocked", Boolean.FALSE);

        String apiSecurity = apiProduct.getApiSecurity();
        if (apiSecurity == null || apiSecurity.contains(APIConstants.DEFAULT_API_SECURITY_OAUTH2)) {
            context.put("apiIsOauthProtected", Boolean.TRUE);
        } else {
            context.put("apiIsOauthProtected", Boolean.FALSE);
        }
    }

    public String getAPIName(API api) {
        return api.getId().getProviderName() + "--" + api.getId().getApiName();
    }
}


text:
mysqli_fetch_lengths()
--SKIPIF--
<?php
require_once('skipif.inc');
require_once('skipifemb.inc');
require_once('skipifconnectfailure.inc');
?>
--FILE--
<?php
	require_once("connect.inc");

	if (!$mysqli = new mysqli($host, $user, $passwd, $db, $port, $socket))
		printf("[001] Cannot connect\n");

	if (!is_null($tmp = @mysqli_fetch_lengths()))
		printf("[001] Expecting NULL, got %s/%s\n", gettype($tmp), $tmp);

	if (!is_null($tmp = @mysqli_fetch_lengths($link)))
		printf("[002] Expecting NULL, got %s/%s\n", gettype($tmp), $tmp);

	require('table.inc');
	if (!$res = mysqli_query($link, "SELECT id, label FROM test ORDER BY id LIMIT 1")) {
		printf("[003] [%d] %s\n", mysqli_errno($link), mysqli_error($link));
	}

	var_dump(mysqli_fetch_lengths($res));
	while ($row = mysqli_fetch_assoc($res))
		var_dump(mysqli_fetch_lengths($res));
	var_dump(mysqli_fetch_lengths($res));

	mysqli_free_result($res);

	var_dump(mysqli_fetch_lengths($res));

	mysqli_close($link);
	print "done!";
?>
--CLEAN--
<?php
	require_once("clean_table.inc");
?>
--EXPECTF--
bool(false)
array(2) {
  [0]=>
  int(1)
  [1]=>
  int(1)
}
bool(false)

Warning: mysqli_fetch_lengths(): Couldn't fetch mysqli_result in %s on line %d
NULL
done!


text:
package ${package};

import net.java.html.json.ComputedProperty;
import net.java.html.json.Function;
import net.java.html.json.Model;
import net.java.html.json.Property;

/** Model annotation generates class Data with
 * one message property, boolean property and read only words property
 */
@Model(className = "Data", properties = {
    @Property(name = "message", type = String.class),
    @Property(name = "rotating", type = boolean.class)
})
final class DataModel {
    @ComputedProperty static java.util.List<String> words(String message) {
        String[] arr = new String[6];
        String[] words = message == null ? new String[0] : message.split(" ", 6);
        for (int i = 0; i < 6; i++) {
            arr[i] = words.length > i ? words[i] : "!";
        }
        return java.util.Arrays.asList(arr);
    }

    @Function static void turnAnimationOn(Data model) {
        model.setRotating(true);
    }

    @Function static void turnAnimationOff(final Data model) {
        confirmByUser("Really turn off?", new Runnable() {
            @Override
            public void run() {
                model.setRotating(false);
            }
        });
    }

    @Function static void rotate5s(final Data model) {
        model.setRotating(true);
        java.util.Timer timer = new java.util.Timer("Rotates a while");
        timer.schedule(new java.util.TimerTask() {
            @Override
            public void run() {
                model.setRotating(false);
            }
        }, 5000);
    }

    @Function static void showScreenSize(Data model) {
        model.setMessage(screenSize());
    }

    /** Shows direct interaction with JavaScript */
    @net.java.html.js.JavaScriptBody(
        args = { "msg", "callback" },
        javacall = true,
        body = "if (confirm(msg)) {\n"
             + "  callback.@java.lang.Runnable::run()();\n"
             + "}\n"
    )
    static native void confirmByUser(String msg, Runnable callback);
    @net.java.html.js.JavaScriptBody(
        args = {}, body =
        "var w = window,\n" +
        "    d = document,\n" +
        "    e = d.documentElement,\n" +
        "    g = d.getElementsByTagName('body')[0],\n" +
        "    x = w.innerWidth || e.clientWidth || g.clientWidth,\n" +
        "    y = w.innerHeight|| e.clientHeight|| g.clientHeight;\n" +
        "\n" +
        "return 'Screen size is ' + x + ' times ' + y;\n"
    )
    static native String screenSize();
}


text:
using System;
using System.Collections.Generic;
using System.Security.Claims;
using Thinktecture.IdentityModel.Extensions;

namespace Thinktecture.IdentityServer.Core.Plumbing
{
    public static class IdentityServerPrincipal
    {
        public static ClaimsPrincipal Create(
            string subject,
            string name,
            string authenticationMethod,
            string idp,
            string authenticationType = Constants.PrimaryAuthenticationType,
            long authenticationTime = 0)
        {
            if (String.IsNullOrWhiteSpace(subject)) throw new ArgumentNullException("subject");
            if (String.IsNullOrWhiteSpace(name)) throw new ArgumentNullException("name");
            if (String.IsNullOrWhiteSpace(authenticationMethod)) throw new ArgumentNullException("authenticationMethod");
            if (String.IsNullOrWhiteSpace(idp)) throw new ArgumentNullException("idp");
            if (String.IsNullOrWhiteSpace(authenticationType)) throw new ArgumentNullException("authenticationType");

            if (authenticationTime <= 0) authenticationTime = DateTime.UtcNow.ToEpochTime();

            var claims = new List<Claim>
            {
                new Claim(Constants.ClaimTypes.Subject, subject),
                new Claim(Constants.ClaimTypes.Name, name),
                new Claim(Constants.ClaimTypes.AuthenticationMethod, authenticationMethod),
                new Claim(Constants.ClaimTypes.IdentityProvider, idp),
                new Claim(Constants.ClaimTypes.AuthenticationTime, authenticationTime.ToString(), ClaimValueTypes.Integer)
            };

            var id = new ClaimsIdentity(claims, authenticationType);
            return new ClaimsPrincipal(id);
        }
    }
}


text:
 {{ site.name }}

  <button class="menu-toggle material-icons left" data-svmenu-open>menu</button>

{% include widgets/nav/svmenu.html %}


text:
'use strict';

const chai      = require('chai');
const sinon     = require('sinon');
const sinonChai = require('sinon-chai');
const subset    = require('chai-subset');

global.env = null;
global.sinon = sinon;

chai.should();
chai.use(sinonChai);
chai.use(subset);

beforeEach(() => {
  global.env = sinon.sandbox.create()
});

afterEach(() => {
  global.env.restore()
});


text: You can say Class.


text:
var Food = require('./food');
var SpeedBoost = require('./speed-boost');
var Virus = require('./virus');
var OpenCoordinates = require('./open-coordinates');

function FoodGenerator(width, height) {
  this.canvasWidth = width;
  this.canvasHeight = height;
  this.coordGenerator = new OpenCoordinates(width, height);
}

FoodGenerator.prototype = {
  seedFood: function(players) {
    var food = [];
    for(var i = 0; i < 200; i++) {
      var foodItem = new Food(this.coordGenerator.create(players));
      food.push(foodItem);
    }
    return food;
  },

  seedSpeedBoosts: function(players) {
    var speedBoosts = [];
    for(var i = 0; i < 15; i++) {
      var boost = new SpeedBoost(this.coordGenerator.create(players));
      speedBoosts.push(boost);
    }
    return speedBoosts;
  },

  seedViruses: function(players) {
    var viruses = [];
    for(var i = 0; i < 3; i++) {
      viruses.push(new Virus(this.coordGenerator.create(players)));
    }
    return viruses;
  },

  replaceFood: function(allFood, speedBoosts, players, viruses) {
    if(allFood.length < 200) {
      for(var i = 0; i < 10; i ++) {
        allFood.push(new Food(this.coordGenerator.create(players)));
      }
    }

    if(speedBoosts.length < 15) {
      for(var j = 0; j < 4; j++) {
        speedBoosts.push(new SpeedBoost(this.coordGenerator.create(players)));
      }
    }

    if(viruses.length < 3) {
      viruses.push(new Virus(this.coordGenerator.create(players)));
    }
  },

  shuffleViruses: function(viruses, players){
    for(var i = 0; i < viruses.length; i++) {
      if(viruses[i].birthTime < Date.now() - 300000){
        viruses.splice(i, 1);
        viruses.push(new Virus(this.coordGenerator.create(players)));
      }
    }
  }
};

module.exports = FoodGenerator;


text:
struct StatsNoAccel : Stats {};

class NoAccelStructure : public AccelStructure {
   public:
    NoAccelStructure();
    ~NoAccelStructure();
    void build() override;
    inline const StatsNoAccel& getStatistics() const override {
        return statistics_;
    }
    bool intersect(const Ray& ray, IntersectionRecord& intersection_record, std::size_t& num_intersection_tests,
                   std::size_t& num_intersections) const override;

   private:
    StatsNoAccel statistics_;
};

#endif  // ACCELERATION_NO_ACCEL_STRUCTURE_H


text:
#ifdef HAVE_CONFIG_H
#  include <config.h>
#endif

#include <arrow-glib/compute.hpp>

G_BEGIN_DECLS

/**
 * SECTION: compute
 * @section_id: compute-classes
 * @title: Classes for computation
 * @include: arrow-glib/arrow-glib.h
 *
 * #GArrowCastOptions is a class to custom garrow_array_cast().
 */

typedef struct GArrowCastOptionsPrivate_ {
  arrow::compute::CastOptions options;
} GArrowCastOptionsPrivate;

enum {
  PROP_0,
  PROP_ALLOW_INT_OVERFLOW,
  PROP_ALLOW_TIME_TRUNCATE
};

G_DEFINE_TYPE_WITH_PRIVATE(GArrowCastOptions,
                           garrow_cast_options,
                           G_TYPE_OBJECT)

#define GARROW_CAST_OPTIONS_GET_PRIVATE(object) \
  static_cast<GArrowCastOptionsPrivate *>(      \
    garrow_cast_options_get_instance_private(   \
      GARROW_CAST_OPTIONS(object)))

static void
garrow_cast_options_set_property(GObject *object,
                                 guint prop_id,
                                 const GValue *value,
                                 GParamSpec *pspec)
{
  auto priv = GARROW_CAST_OPTIONS_GET_PRIVATE(object);

  switch (prop_id) {
  case PROP_ALLOW_INT_OVERFLOW:
    priv->options.allow_int_overflow = g_value_get_boolean(value);
    break;
  case PROP_ALLOW_TIME_TRUNCATE:
    priv->options.allow_time_truncate = g_value_get_boolean(value);
    break;
  default:
    G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec);
    break;
  }
}

static void
garrow_cast_options_get_property(GObject *object,
                                 guint prop_id,
                                 GValue *value,
                                 GParamSpec *pspec)
{
  auto priv = GARROW_CAST_OPTIONS_GET_PRIVATE(object);

  switch (prop_id) {
  case PROP_ALLOW_INT_OVERFLOW:
    g_value_set_boolean(value, priv->options.allow_int_overflow);
    break;
  case PROP_ALLOW_TIME_TRUNCATE:
    g_value_set_boolean(value, priv->options.allow_time_truncate);
    break;
  default:
    G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec);
    break;
  }
}

static void
garrow_cast_options_init(GArrowCastOptions *object)
{
}

static void
garrow_cast_options_class_init(GArrowCastOptionsClass *klass)
{
  GParamSpec *spec;

  auto gobject_class = G_OBJECT_CLASS(klass);

  gobject_class->set_property = garrow_cast_options_set_property;
  gobject_class->get_property = garrow_cast_options_get_property;

  /**
   * GArrowCastOptions:allow-int-overflow:
   *
   * Whether integer overflow is allowed or not.
   *
   * Since: 0.7.0
   */
  spec = g_param_spec_boolean("allow-int-overflow",
                              "Allow int overflow",
                              "Whether integer overflow is allowed or not",
                              FALSE,
                              static_cast<GParamFlags>(G_PARAM_READWRITE));
  g_object_class_install_property(gobject_class, PROP_ALLOW_INT_OVERFLOW, spec);

  /**
   * GArrowCastOptions:allow-time-truncate:
   *
   * Whether truncating time value is allowed or not.
   *
   * Since: 0.8.0
   */
  spec = g_param_spec_boolean("allow-time-truncate",
                              "Allow time truncate",
                              "Whether truncating time value is allowed or not",
                              FALSE,
                              static_cast<GParamFlags>(G_PARAM_READWRITE));
  g_object_class_install_property(gobject_class, PROP_ALLOW_TIME_TRUNCATE, spec);
}

/**
 * garrow_cast_options_new:
 *
 * Returns: A newly created #GArrowCastOptions.
 *
 * Since: 0.7.0
 */
GArrowCastOptions *
garrow_cast_options_new(void)
{
  auto cast_options = g_object_new(GARROW_TYPE_CAST_OPTIONS, NULL);
  return GARROW_CAST_OPTIONS(cast_options);
}

G_END_DECLS

GArrowCastOptions *
garrow_cast_options_new_raw(arrow::compute::CastOptions *arrow_cast_options)
{
  auto cast_options =
    g_object_new(GARROW_TYPE_CAST_OPTIONS,
                 "allow-int-overflow", arrow_cast_options->allow_int_overflow,
                 NULL);
  return GARROW_CAST_OPTIONS(cast_options);
}

arrow::compute::CastOptions *
garrow_cast_options_get_raw(GArrowCastOptions *cast_options)
{
  auto priv = GARROW_CAST_OPTIONS_GET_PRIVATE(cast_options);
  return &(priv->options);
}


text:
class Spontaneous::Site
  module Instance
    extend Spontaneous::Concern

    module ClassMethods
      extend Forwardable

      def instantiate(root, env, mode)
        @__instance__ = Spontaneous::Site.new(root, env, mode)
      end

      def instance
        @__instance__
      end

      def_delegators :instance, :config, :database, :database=
    end # ClassMethods
  end # Instance
end


text:
from django.test import TestCase
from django.test import Client

class SimpleTest(TestCase):

    def setUp(self):
        self.client = Client()

    def test_start_page_loads(self):
        response = self.client.get("/skillingtryck/")

        # Check that the response is 200 OK.
        self.assertEqual(response.status_code, 200)

    def test_about_page_loads(self):
        response = self.client.get('/skillingtryck/om/')

        # Check that the response is 200 OK.
        self.assertEqual(response.status_code, 200)


text:
package org.apache.lucene.morphology;

import java.util.ArrayList;

public abstract class BaseLetterDecoderEncoder implements LetterDecoderEncoder {
    public int[] encodeToArray(String s) {
        ArrayList<Integer> integers = new ArrayList<>();
        while (s.length() > 6) {
            integers.add(encode(s.substring(0, 6)));
            s = s.substring(6);
        }
        integers.add(encode(s));
        int[] ints = new int[integers.size()];
        int pos = 0;
        for (Integer i : integers) {
            ints[pos] = i;
            pos++;
        }
        return ints;
    }

    public String decodeArray(int[] array) {
        StringBuilder result = new StringBuilder();
        for (int i : array) {
            result.append(decode(i));
        }
        return result.toString();
    }

    public boolean checkString(String word) {
        for (int i = 0; i < word.length(); i++) {
            if (!checkCharacter(word.charAt(i))) {
                return false;
            }
        }
        return true;
    }
}


text:
package nl.knaw.dans.common.jibx.bean;

import static org.junit.Assert.assertEquals;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Locale;
import java.util.Observer;

import nl.knaw.dans.common.jibx.JiBXObjectFactory;
import nl.knaw.dans.common.lang.ResourceNotFoundException;
import nl.knaw.dans.common.lang.repo.bean.DublinCoreMetadata;
import nl.knaw.dans.common.lang.repo.bean.DublinCoreMetadata.PropertyName;
import nl.knaw.dans.common.lang.test.Tester;
import nl.knaw.dans.common.lang.xml.SchemaCreationException;
import nl.knaw.dans.common.lang.xml.XMLException;
import nl.knaw.dans.common.lang.xml.XMLSerializationException;

import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.SAXException;

public class JiBXDublinCoreMetadataTest
{
    private static final Logger logger = LoggerFactory.getLogger(JiBXDublinCoreMetadataTest.class);

    private boolean verbose = Tester.isVerbose();

    @Test
    public void serializeDeserializeEmpty() throws XMLException
    {
        DublinCoreMetadata dc = new JiBXDublinCoreMetadata();
        if (verbose)
            logger.debug("\n" + dc.asXMLString(4) + "\n");

        DublinCoreMetadata dc2 = (DublinCoreMetadata) JiBXObjectFactory.unmarshal(JiBXDublinCoreMetadata.class, dc.asObjectXML());
        assertEquals(dc.asXMLString(), dc2.asXMLString());
    }

    @Test
    public void serializeDeserializeFull() throws XMLException
    {
        DublinCoreMetadata dc = createFull();
        //if (verbose)
        logger.debug("\n" + dc.asXMLString(4) + "\n");

        DublinCoreMetadata dc2 = (DublinCoreMetadata) JiBXObjectFactory.unmarshal(JiBXDublinCoreMetadata.class, dc.asObjectXML());
        assertEquals(dc.asXMLString(), dc2.asXMLString());
    }

    @Test
    public void serializeToFile() throws IOException, XMLException
    {
        DublinCoreMetadata dc = createFull();
        File tempFile = null;
        try
        {
            tempFile = File.createTempFile("jibx-test-", null);
            dc.serializeTo(tempFile, 4);
            if (verbose)
                logger.debug("Serialized to " + tempFile.getPath());

            DublinCoreMetadata dc2 = (DublinCoreMetadata) JiBXObjectFactory.unmarshal(JiBXDublinCoreMetadata.class, tempFile);
            assertEquals(dc.asXMLString(), dc2.asXMLString());
        }
        finally
        {
            if (tempFile != null && !tempFile.delete())
            {
                logger.warn("Could not remove temporary file: " + tempFile.getName());
                tempFile.deleteOnExit();
            }
        }
    }

    @Test
    public void serializeToInputStream() throws XMLException, IOException
    {
        DublinCoreMetadata dc = createFull();
        InputStream inStream = dc.asXMLInputStream();

        DublinCoreMetadata dc2 = (DublinCoreMetadata) JiBXObjectFactory.unmarshal(JiBXDublinCoreMetadata.class, inStream);

        assertEquals(dc.asXMLString(), dc2.asXMLString());
    }

    @Test
    public void serializeToOutputStream() throws XMLSerializationException
    {
        DublinCoreMetadata dc = createFull();
        if (verbose)
            dc.serializeTo(System.out, 4);
    }

    @Test
    public void serializeToWriter() throws XMLSerializationException
    {
        DublinCoreMetadata dc = createFull();
        dc.add(PropertyName.Type, "K\u2016jihu\u1234");
        PrintWriter out = new PrintWriter(System.out, true);
        if (verbose)
            dc.serializeTo(null, out);
    }

    @Test
    public void deserializeFromFile() throws XMLException, SAXException, SchemaCreationException, ResourceNotFoundException
    {
        DublinCoreMetadata dc = (DublinCoreMetadata) JiBXObjectFactory.unmarshal(JiBXDublinCoreMetadata.class, Tester.getFile("test-files/bean/oai_dc.xml"));
        //assertTrue(DublinCoreMetadataValidator.instance().validate(dc).passed());
        if (verbose)
            logger.debug("\n" + dc.asXMLString(4) + "\n");
    }

    @Test
    public void deserializeFromValidFile() throws XMLException, SAXException, SchemaCreationException, ResourceNotFoundException
    {
        DublinCoreMetadata dc = (DublinCoreMetadata) JiBXObjectFactory.unmarshal(JiBXDublinCoreMetadata.class, Tester
                .getFile("test-files/bean/valid_oai_dc.xml"));
        //assertTrue(DublinCoreMetadataValidator.instance().validate(dc).passed());
        if (verbose)
            logger.debug("\n" + dc.asXMLString(4) + "\n");

        // there are 4 source elements scattered around in the document.
        assertEquals(4, dc.getXl(PropertyName.Source).size());
    }

    public static DublinCoreMetadata createFull()
    {
        DublinCoreMetadata dc = new JiBXDublinCoreMetadata();
        int i = 0;
        for (PropertyName name : PropertyName.values())
        {
            if (i % 2 == 0)
            {
                dc.add(name, name.toString() + " 1", "nl");
                dc.add(name, name.toString() + " 2");
            }
            else
            {
                dc.add(name, name.toString() + " 1");
                dc.add(name, name.toString() + " 2", "nld-NLD");
            }
            i++;
        }
        return dc;
    }

    @Test
    public void Observable() throws Exception
    {
        JiBXDublinCoreMetadata jdc = new JiBXDublinCoreMetadata();
        JDCObserver dcObserver = new JDCObserver();
        jdc.addObserver(dcObserver);

        for (PropertyName name : PropertyName.values())
        {
            jdc.set(name, new ArrayList<String>());
            assertEquals(1, dcObserver.count);
            assertEquals(name, dcObserver.getLatestArgument());
        }

        for (PropertyName name : PropertyName.values())
        {
            jdc.set(name, "foo");
            assertEquals(1, dcObserver.count);
            assertEquals(name, dcObserver.getLatestArgument());
        }

        for (PropertyName name : PropertyName.values())
        {
            jdc.add(name, "bar");
            assertEquals(1, dcObserver.count);
            assertEquals(name, dcObserver.getLatestArgument());
        }

        for (PropertyName name : PropertyName.values())
        {
            jdc.add(name, new JiBXLangString("jazz"));
            assertEquals(1, dcObserver.count);
            assertEquals(name, dcObserver.getLatestArgument());
        }

        for (PropertyName name : PropertyName.values())
        {
            jdc.add(name, "beer", "nl");
            assertEquals(1, dcObserver.count);
            assertEquals(name, dcObserver.getLatestArgument());
        }

        for (PropertyName name : PropertyName.values())
        {
            jdc.add(name, "drunk", new Locale("nl"));
            assertEquals(1, dcObserver.count);
            assertEquals(name, dcObserver.getLatestArgument());
        }

        if (verbose)
            logger.debug("\n" + jdc.asXMLString(4) + "\n");
    }

    class JDCObserver implements Observer
    {

        private Object latestArgument;
        private int count;

        @Override
        public void update(java.util.Observable arg0, Object arg1)
        {
            count++;
            latestArgument = arg1;
        }

        public Object getLatestArgument()
        {
            Object la = latestArgument;
            latestArgument = null;
            count = 0;
            return la;
        }

    }

}