text:
namespace viz {
namespace {

class CopyOutputScalingPixelTest
    : public VizPixelTest,
      public testing::WithParamInterface<std::tuple<RendererType,
                                                    gfx::Vector2d,
                                                    gfx::Vector2d,
                                                    CopyOutputResult::Format>> {
 public:
  CopyOutputScalingPixelTest() : VizPixelTest(std::get<0>(GetParam())) {}

  DirectRenderer* renderer() { return renderer_.get(); }

  void SetUp() override {
    VizPixelTest::SetUp();
    scale_from_ = std::get<1>(GetParam());
    scale_to_ = std::get<2>(GetParam());
    result_format_ = std::get<3>(GetParam());
  }

  // This tests that copy requests requesting scaled results execute correctly.
  // The test procedure creates a scene similar to the wall art that can be
  // found in the stairwell of a certain Google office building: A white
  // background" (W=white) and four blocks of different colors (r=red, g=green,
  // b=blue, y=yellow).
  //
  //   WWWWWWWWWWWWWWWWWWWWWWWW
  //   WWWWWWWWWWWWWWWWWWWWWWWW
  //   WWWWrrrrWWWWWWWWggggWWWW
  //   WWWWrrrrWWWWWWWWggggWWWW
  //   WWWWWWWWWWWWWWWWWWWWWWWW
  //   WWWWWWWWWWWWWWWWWWWWWWWW
  //   WWWWbbbbWWWWWWWWyyyyWWWW
  //   WWWWbbbbWWWWWWWWyyyyWWWW
  //   WWWWWWWWWWWWWWWWWWWWWWWW
  //   WWWWWWWWWWWWWWWWWWWWWWWW
  //
  // The scene is drawn, which also causes the copy request to execute. Then,
  // the resulting bitmap is compared against an expected bitmap.
  void RunTest() {
    const char* result_format_as_str = "<unknown>";

    // Tests only issue requests for system-memory destinations, no need to
    // take the destination into account:
    if (result_format_ == CopyOutputResult::Format::RGBA)
      result_format_as_str = "RGBA";
    else if (result_format_ == CopyOutputResult::Format::I420_PLANES)
      result_format_as_str = "I420_PLANES";
    else
      NOTIMPLEMENTED();
    SCOPED_TRACE(testing::Message()
                 << "scale_from=" << scale_from_.ToString()
                 << ", scale_to=" << scale_to_.ToString()
                 << ", result_format=" << result_format_as_str);

    // These need to be large enough to prevent odd-valued coordinates when
    // testing I420_PLANES requests. The requests would still work with
    // odd-valued coordinates, but the pixel comparisons at the end of the test
    // will fail due to off-by-one chroma reconstruction. That behavior is WAI,
    // though, since clients making CopyOutputRequests should always align to
    // even-valued coordinates!
    constexpr gfx::Size viewport_size = gfx::Size(48, 20);
    constexpr int x_block = 8;
    constexpr int y_block = 4;
    constexpr SkColor smaller_pass_colors[4] = {SK_ColorRED, SK_ColorGREEN,
                                                SK_ColorBLUE, SK_ColorYELLOW};
    constexpr SkColor root_pass_color = SK_ColorWHITE;

    AggregatedRenderPassList list;

    // Create the render passes drawn on top of the root render pass.
    AggregatedRenderPass* smaller_passes[4];
    gfx::Rect smaller_pass_rects[4];
    AggregatedRenderPassId pass_id{5};
    for (int i = 0; i < 4;
         ++i, pass_id = AggregatedRenderPassId{pass_id.value() - 1}) {
      smaller_pass_rects[i] = gfx::Rect(
          i % 2 == 0 ? x_block : (viewport_size.width() - 2 * x_block),
          i / 2 == 0 ? y_block : (viewport_size.height() - 2 * y_block),
          x_block, y_block);
      smaller_passes[i] =
          AddRenderPass(&list, pass_id, smaller_pass_rects[i], gfx::Transform(),
                        cc::FilterOperations());
      cc::AddQuad(smaller_passes[i], smaller_pass_rects[i],
                  smaller_pass_colors[i]);
    }

    // Create the root render pass and add all the child passes to it.
    auto* root_pass =
        cc::AddRenderPass(&list, pass_id, gfx::Rect(viewport_size),
                          gfx::Transform(), cc::FilterOperations());
    for (int i = 0; i < 4; ++i)
      cc::AddRenderPassQuad(root_pass, smaller_passes[i]);
    cc::AddQuad(root_pass, gfx::Rect(viewport_size), root_pass_color);

    // Make a copy request and execute it by drawing a frame. A subset of the
    // viewport is requested, to test that scaled offsets are being computed
    // correctly as well.
    const gfx::Rect copy_rect(x_block, y_block,
                              viewport_size.width() - 2 * x_block,
                              viewport_size.height() - 2 * y_block);
    std::unique_ptr<CopyOutputResult> result;
    {
      base::RunLoop loop;

      // Add a dummy copy request to be executed when the RED RenderPass is
      // drawn (before the root RenderPass). This is a regression test to
      // confirm GLRenderer state is consistent with the GL context after each
      // copy request executes, and before the next RenderPass is drawn.
      // http://crbug.com/792734
      bool dummy_ran = false;
      auto request = std::make_unique<CopyOutputRequest>(
          result_format_, CopyOutputRequest::ResultDestination::kSystemMemory,
          base::BindOnce(
              [](bool* dummy_ran, std::unique_ptr<CopyOutputResult> result) {
                EXPECT_TRUE(!result->IsEmpty());
                EXPECT_FALSE(*dummy_ran);
                *dummy_ran = true;
              },
              &dummy_ran));
      // Set a 10X zoom, which should be more than sufficient to disturb the
      // results of the main copy request (below) if the GL state is not
      // properly restored.
      request->SetUniformScaleRatio(1, 10);
      // Ensure the result callback is run on test main thread.
      request->set_result_task_runner(base::SequencedTaskRunnerHandle::Get());
      list.front()->copy_requests.push_back(std::move(request));

      // Add a copy request to the root RenderPass, to capture the results of
      // drawing all passes for this frame.
      request = std::make_unique<CopyOutputRequest>(
          result_format_, CopyOutputRequest::ResultDestination::kSystemMemory,
          base::BindOnce(
              [](bool* dummy_ran,
                 std::unique_ptr<CopyOutputResult>* test_result,
                 const base::RepeatingClosure& quit_closure,
                 std::unique_ptr<CopyOutputResult> result_from_renderer) {
                EXPECT_TRUE(*dummy_ran);
                *test_result = std::move(result_from_renderer);
                quit_closure.Run();
              },
              &dummy_ran, &result, loop.QuitClosure()));
      request->set_result_selection(
          copy_output::ComputeResultRect(copy_rect, scale_from_, scale_to_));
      request->SetScaleRatio(scale_from_, scale_to_);
      // Ensure the result callback is run on test main thread.
      request->set_result_task_runner(base::SequencedTaskRunnerHandle::Get());
      list.back()->copy_requests.push_back(std::move(request));

      renderer()->DecideRenderPassAllocationsForFrame(list);
      SurfaceDamageRectList surface_damage_rect_list;
      renderer()->DrawFrame(&list, 1.0f, viewport_size,
                            gfx::DisplayColorSpaces(),
                            std::move(surface_damage_rect_list));
      // Call SwapBuffersSkipped(), so the renderer can release related
      // resources.
      renderer()->SwapBuffersSkipped();
      loop.Run();
    }

    // Check that the result succeeded and provides a bitmap of the expected
    // size.
    const gfx::Rect expected_result_rect =
        copy_output::ComputeResultRect(copy_rect, scale_from_, scale_to_);
    EXPECT_EQ(expected_result_rect, result->rect());
    EXPECT_EQ(result_format_, result->format());
    absl::optional<CopyOutputResult::ScopedSkBitmap> scoped_bitmap;
    SkBitmap result_bitmap;
    if (result_format_ == CopyOutputResult::Format::I420_PLANES) {
      result_bitmap = ReadI420ResultToSkBitmap(*result);
    } else {
      scoped_bitmap = result->ScopedAccessSkBitmap();
      result_bitmap = scoped_bitmap->bitmap();
    }
    ASSERT_TRUE(result_bitmap.readyToDraw());
    ASSERT_EQ(expected_result_rect.width(), result_bitmap.width());
    ASSERT_EQ(expected_result_rect.height(), result_bitmap.height());

    // Create the "expected result" bitmap.
    SkBitmap expected_bitmap;
    expected_bitmap.allocN32Pixels(expected_result_rect.width(),
                                   expected_result_rect.height());
    expected_bitmap.eraseColor(root_pass_color);
    for (int i = 0; i < 4; ++i) {
      gfx::Rect rect = smaller_pass_rects[i] - copy_rect.OffsetFromOrigin();
      rect = copy_output::ComputeResultRect(rect, scale_from_, scale_to_);
      expected_bitmap.erase(
          smaller_pass_colors[i],
          SkIRect{rect.x(), rect.y(), rect.right(), rect.bottom()});
    }

    // Do an approximate comparison of the result bitmap to the expected one to
    // confirm the position and size of the color values in the result is
    // correct. Allow for pixel values to be a bit off for two reasons:
    //
    //   1. The scaler algorithms are not using a naïve box filter, and so will
    //      blend things together at edge boundaries.
    //   2. In the case of an I420 format request, the chroma is at half-
    //      resolution, and so there can be "fuzzy color blending" at the edges
    //      between the color rects.
    int num_bad_pixels = 0;
    gfx::Point first_failure_position;
    for (int y = 0; y < expected_bitmap.height(); ++y) {
      for (int x = 0; x < expected_bitmap.width(); ++x) {
        const SkColor expected = expected_bitmap.getColor(x, y);
        const SkColor actual = result_bitmap.getColor(x, y);
        const bool red_bad =
            (SkColorGetR(expected) < 0x80) != (SkColorGetR(actual) < 0x80);
        const bool green_bad =
            (SkColorGetG(expected) < 0x80) != (SkColorGetG(actual) < 0x80);
        const bool blue_bad =
            (SkColorGetB(expected) < 0x80) != (SkColorGetB(actual) < 0x80);
        const bool alpha_bad =
            (SkColorGetA(expected) < 0x80) != (SkColorGetA(actual) < 0x80);
        if (red_bad || green_bad || blue_bad || alpha_bad) {
          if (num_bad_pixels == 0)
            first_failure_position = gfx::Point(x, y);
          ++num_bad_pixels;
        }
      }
    }
    EXPECT_EQ(0, num_bad_pixels)
        << "First failure position at: " << first_failure_position.ToString()
        << "\nExpected bitmap: " << cc::GetPNGDataUrl(expected_bitmap)
        << "\nActual bitmap: " << cc::GetPNGDataUrl(result_bitmap);
  }

 private:
  // Calls result.ReadI420Planes() and then converts the I420 format back to a
  // SkBitmap for comparison with the expected bitmap.
  static SkBitmap ReadI420ResultToSkBitmap(const CopyOutputResult& result) {
    const int result_width = result.rect().width();
    const int result_height = result.rect().height();

    // Calculate width/height/stride for each plane and allocate temporary
    // buffers to hold the pixels. Note that the strides for each plane are
    // being set differently to test that the arguments are correctly plumbed-
    // through.
    const int y_width = result_width;
    const int y_stride = y_width + 7;
    std::unique_ptr<uint8_t[]> y_data(new uint8_t[y_stride * result_height]);
    const int chroma_width = (result_width + 1) / 2;
    const int u_stride = chroma_width + 11;
    const int v_stride = chroma_width + 17;
    const int chroma_height = (result_height + 1) / 2;
    std::unique_ptr<uint8_t[]> u_data(new uint8_t[u_stride * chroma_height]);
    std::unique_ptr<uint8_t[]> v_data(new uint8_t[v_stride * chroma_height]);

    // Do the read.
    const bool success = result.ReadI420Planes(
        y_data.get(), y_stride, u_data.get(), u_stride, v_data.get(), v_stride);
    CHECK(success);

    // Convert to an SkBitmap.
    SkBitmap bitmap;
    bitmap.allocPixels(SkImageInfo::Make(result_width, result_height,
                                         kBGRA_8888_SkColorType,
                                         kPremul_SkAlphaType));
    const int error_code = libyuv::I420ToARGB(
        y_data.get(), y_stride, u_data.get(), u_stride, v_data.get(), v_stride,
        static_cast<uint8_t*>(bitmap.getPixels()), bitmap.rowBytes(),
        result_width, result_height);
    CHECK_EQ(0, error_code);

    return bitmap;
  }

  gfx::Vector2d scale_from_;
  gfx::Vector2d scale_to_;
  CopyOutputResult::Format result_format_;
};

// Parameters common to all test instantiations. These are tuples consisting of
// {scale_from, scale_to, i420_format}.
const auto kParameters =
    testing::Combine(testing::ValuesIn(GetRendererTypesNoDawn()),
                     testing::Values(gfx::Vector2d(1, 1),
                                     gfx::Vector2d(2, 1),
                                     gfx::Vector2d(1, 2),
                                     gfx::Vector2d(2, 2)),
                     testing::Values(gfx::Vector2d(1, 1),
                                     gfx::Vector2d(2, 1),
                                     gfx::Vector2d(1, 2)),
                     testing::Values(CopyOutputResult::Format::RGBA,
                                     CopyOutputResult::Format::I420_PLANES));

TEST_P(CopyOutputScalingPixelTest, ScaledCopyOfDrawnFrame) {
  RunTest();
}
INSTANTIATE_TEST_SUITE_P(, CopyOutputScalingPixelTest, kParameters);

}  // namespace
}  // namespace viz


text:
using System;
namespace UnitTests
{
    public abstract class UnitTest
    {
        public UnitTest()
        {
        }

        public abstract void Setup();
        public abstract bool Test();
        public abstract void Cleanup();
    }
}

redpajama_set_name: RedPajamaGithub


text:
#include <aws/connect/model/UpdateContactRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Connect::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;

UpdateContactRequest::UpdateContactRequest() :
    m_instanceIdHasBeenSet(false),
    m_contactIdHasBeenSet(false),
    m_nameHasBeenSet(false),
    m_descriptionHasBeenSet(false),
    m_referencesHasBeenSet(false)
{
}

Aws::String UpdateContactRequest::SerializePayload() const
{
  JsonValue payload;

  if(m_nameHasBeenSet)
  {
   payload.WithString("Name", m_name);

  }

  if(m_descriptionHasBeenSet)
  {
   payload.WithString("Description", m_description);

  }

  if(m_referencesHasBeenSet)
  {
   JsonValue referencesJsonMap;
   for(auto& referencesItem : m_references)
   {
     referencesJsonMap.WithObject(referencesItem.first, referencesItem.second.Jsonize());
   }
   payload.WithObject("References", std::move(referencesJsonMap));

  }

  return payload.View().WriteReadable();
}


text:
#if !UNITY_EDITOR
// Extra optimizations when not running in the editor, but less error checking
#define ASTAR_OPTIMIZE_POOLING
#endif

using System;
using System.Collections.Generic;

namespace Pathfinding.Util {
	/** Lightweight Array Pool.
	 * Handy class for pooling arrays of type T.
	 *
	 * Usage:
	 * - Claim a new array using \code SomeClass[] foo = ArrayPool<SomeClass>.Claim (capacity); \endcode
	 * - Use it and do stuff with it
	 * - Release it with \code ArrayPool<SomeClass>.Release (foo); \endcode
	 *
	 * \warning Arrays returned from the Claim method may contain arbitrary data.
	 *  You cannot rely on it being zeroed out.
	 *
	 * After you have released a array, you should never use it again, if you do use it
	 * your code may modify it at the same time as some other code is using it which
	 * will likely lead to bad results.
	 *
	 * \since Version 3.8.6
	 * \see Pathfinding.Util.ListPool
	 */
	public static class ArrayPool<T>{
		/** Internal pool.
		 * The arrays in each bucket have lengths of 2^i
		 */
		static readonly Stack<T[]>[] pool = new Stack<T[]>[31];

		static readonly HashSet<T[]> inPool = new HashSet<T[]>();

		/** Returns an array with at least the specified length */
		public static T[] Claim (int minimumLength) {
			int bucketIndex = 0;

			while ((1 << bucketIndex) < minimumLength && bucketIndex < 30) {
				bucketIndex++;
			}

			if (bucketIndex == 30)
				throw new System.ArgumentException("Too high minimum length");

			lock (pool) {
				if (pool[bucketIndex] == null) {
					pool[bucketIndex] = new Stack<T[]>();
				}

				if (pool[bucketIndex].Count > 0) {
					var array = pool[bucketIndex].Pop();
					inPool.Remove(array);
					return array;
				}
			}
			return new T[1 << bucketIndex];
		}

		public static void Release (ref T[] array) {
			lock (pool) {
				if (!inPool.Add(array)) {
					throw new InvalidOperationException("You are trying to pool an array twice. Please make sure that you only pool it once.");
				}

				int bucketIndex = 0;
				while ((1 << bucketIndex) < array.Length && bucketIndex < 30) {
					bucketIndex++;
				}

				if (array.Length != (1 << bucketIndex)) {
					throw new ArgumentException("Array length is not a power of 2");
				}

				if (pool[bucketIndex] == null) {
					pool[bucketIndex] = new Stack<T[]>();
				}

				pool[bucketIndex].Push(array);
			}
			array = null;
		}
	}
}


text:
package com.github.eventsource.client;

public interface EventSourceHandler {
    void onConnect() throws Exception;
    void onMessage(String event, MessageEvent message) throws Exception;
    void onError(Throwable t);
    void onClosed(boolean willReconnect);
}


text:
package de.fhg.iais.asc.ui.components.panel;

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;

import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;

import org.apache.commons.lang.StringUtils;

import de.fhg.iais.asc.ui.i18n.Messages;
import de.fhg.iais.commons.constants.Serial;

public class LeftLabeledElementJPanel extends JPanel {

    private static final long serialVersionUID = Serial.GLOBAL_DEFAULT_SERIAL_VERSION_UID;

    private static final double WEIGHTX_LABEL = 0.1;
    private static final double WEIGHTX_ELEMENT = 0.3;

    private final String prefix;

    private final GridBagConstraints cLabel = new GridBagConstraints();
    private final GridBagConstraints cElement = new GridBagConstraints();

    private JLabel lastLabel;

    public LeftLabeledElementJPanel(String prefix) {
        super(new GridBagLayout());

        this.prefix = (StringUtils.isEmpty(prefix)) ? "" : (prefix + ".");

        this.cLabel.gridx = 0;
        this.cLabel.gridy = 0;
        this.cLabel.weightx = WEIGHTX_LABEL;
        this.cLabel.fill = GridBagConstraints.HORIZONTAL;

        this.cElement.gridx = 1;
        this.cElement.gridwidth = 2;
        this.cElement.gridy = 0;
        this.cElement.weightx = WEIGHTX_ELEMENT;
        this.cElement.fill = GridBagConstraints.HORIZONTAL;
    }

    public <E extends JComponent> E add(String labelName, E element) {
        String labelText = Messages.getString(this.prefix + "Label." + labelName);
        String tooltipText = Messages.getString(this.prefix + "Tooltip." + labelName, null);

        JLabel label = new JLabel(labelText + " ");
        label.setToolTipText(tooltipText);
        this.add(label, this.cLabel);
        ++this.cLabel.gridy;

        element.setToolTipText(tooltipText);
        this.add(element, this.cElement);
        ++this.cElement.gridy;

        this.lastLabel = label;
        return element;
    }

    public <E extends JComponent> E add(String labelName, E element, JButton button) {
        this.cElement.gridx = 2;
        this.cElement.gridwidth = 1;
        this.cElement.weightx = WEIGHTX_LABEL;
        this.add(button, this.cElement);

        this.cElement.gridx = 1;
        this.cElement.weightx = WEIGHTX_ELEMENT - WEIGHTX_LABEL;
        this.add(labelName, element);

        this.cElement.gridwidth = 2;
        this.cElement.weightx = WEIGHTX_ELEMENT;
        return element;
    }

    public JLabel getLastLabel() {
        return this.lastLabel;
    }

}


text:
using System;
using System.Collections;
using System.Configuration;
using System.Management;

namespace Scour.Util {
    class WMI {
        private ManagementScope _managementScope;
        private ConnectionOptions _connectionOptions;

        public ManagementScope ManagementScope { get { return _managementScope; } }

        /// <summary>
        /// Constructor for local machine, no credentials necessary, requires elevation
        /// </summary>
        /// <param name="computerName"></param>
        public WMI(string computerName) {
            this.CreateManagementScope(computerName);
        }
        /// <summary>
        /// Constructor for remote machine, connection options required
        /// </summary>
        /// <param name="computerName"></param>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <param name="domain"></param>
        public WMI(string computerName, string username, string password, string domain) {
            this.CreateManagementScope(computerName, username, password, domain);
        }
        /// <summary>
        /// Get a query result for any query string
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public ManagementObjectCollection GetQueryResult(string query) {
            var q = new ObjectQuery(query);
            var searcher = new ManagementObjectSearcher(_managementScope, q);
            var information = searcher.Get();
            return information;
        }
        /// <summary>
        /// Create a local management scope
        /// </summary>
        /// <param name="computerName"></param>
        /// <returns></returns>
        private ManagementScope CreateManagementScope(string computerName) {
            this._managementScope = new ManagementScope(@"\\" + computerName + @"\root\cimv2");
            return _managementScope;
        }
        /// <summary>
        /// Create a credentialed management scope for remote connections
        /// </summary>
        /// <param name="computerName"></param>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <param name="domain"></param>
        /// <returns></returns>
        private ManagementScope CreateManagementScope(string computerName, string username, string password, string domain) {
            this._connectionOptions = new ConnectionOptions() {
                Username = username,
                Password = password,
                Authority = "ntlmdomain:" + domain.ToUpper()
            };
            this._managementScope = new ManagementScope(@"\\" + computerName + "." + domain + @"\root\cimv2", _connectionOptions);
            return _managementScope;
        }
    }
}


text:
/*
 * $Id$
 *
 * Helper functions related to fetching process information. Used by _psutil_mswindows
 * module methods.
 */

#include <Python.h>
#include <windows.h>

HANDLE handle_from_pid_waccess(DWORD pid, DWORD dwDesiredAccess);
HANDLE handle_from_pid(DWORD pid);
PVOID GetPebAddress(HANDLE ProcessHandle);
HANDLE handle_from_pid(DWORD pid);
BOOL is_running(HANDLE hProcess);
int pid_in_proclist(DWORD pid);
int pid_is_running(DWORD pid);
PyObject* get_arg_list(long pid);
PyObject* get_ppid(long pid);
PyObject* get_name(long pid);
DWORD* get_pids(DWORD *numberOfReturnedPIDs);


text:
'use strict';

exports.cli               = require('./marly/cli.js');
exports.CosineSimilarity  = require('./marly/CosineSimilarity.js');
exports.MinkowskiDistance = require('./marly/MinkowskiDistance.js');
exports.PCC               = require('./marly/PCC.js');
exports.version           = require('./marly/version.js');


text:
package org.apache.ignite.internal.client.thin.io.gridnioserver;

import java.nio.ByteBuffer;

import org.apache.ignite.failure.FailureType;
import org.apache.ignite.internal.util.nio.GridNioServerListener;
import org.apache.ignite.internal.util.nio.GridNioSession;
import org.jetbrains.annotations.Nullable;

/**
 * Client event listener.
 */
class GridNioClientListener implements GridNioServerListener<ByteBuffer> {
    /** {@inheritDoc} */
    @Override public void onConnected(GridNioSession ses) {
        // No-op.
    }

    /** {@inheritDoc} */
    @Override public void onDisconnected(GridNioSession ses, @Nullable Exception e) {
        GridNioClientConnection conn = ses.meta(GridNioClientConnection.SES_META_CONN);

        // Conn can be null when connection fails during initialization in open method.
        if (conn != null)
            conn.onDisconnected(e);
    }

    /** {@inheritDoc} */
    @Override public void onMessageSent(GridNioSession ses, ByteBuffer msg) {
        // No-op.
    }

    /** {@inheritDoc} */
    @Override public void onMessage(GridNioSession ses, ByteBuffer msg) {
        GridNioClientConnection conn = ses.meta(GridNioClientConnection.SES_META_CONN);

        assert conn != null : "Session must have an associated connection";

        conn.onMessage(msg);
    }

    /** {@inheritDoc} */
    @Override public void onSessionWriteTimeout(GridNioSession ses) {
        // No-op.
    }

    /** {@inheritDoc} */
    @Override public void onSessionIdleTimeout(GridNioSession ses) {
        // No-op.
    }

    /** {@inheritDoc} */
    @Override public void onFailure(FailureType failureType, Throwable failure) {
        // No-op.
    }
}


text:
import io
import sys
import unittest

from ..metric.cyclomatic import CyclomaticComplexity
from ..node import ModuleNode
from ..project import Project
from ..report import Report
from . import get_asset_path

class FakeReport(Report):
    results = None

    def report(self, results):
        self.results = results
        return 'report'

if sys.version_info.major >= 3:
    StringIO = io.StringIO

else:
    StringIO = io.BytesIO

class TestProject(unittest.TestCase):
    def setUp(self):
        self.project = Project(path=(get_asset_path('.'),))
        self.project.add_package('testfile')
        self.project.add_package('testpackage')

        self.metric = CyclomaticComplexity()
        self.project.add_metric(self.metric)

    def __assert_modules(self, expected, packages, path=None):
        path = path or [get_asset_path('.')]

        project = Project(path=path)
        for package in packages:
            project.add_package(package)

        self.assertSetEqual(set(expected), set(project.modules))

    def test_load_module(self):
        self.__assert_modules(['testfile'], ['testfile'])

    def test_load_package(self):
        self.__assert_modules(['testpackage', 'testpackage.testmod'], ['testpackage'])

    def test_load_submodule(self):
        self.__assert_modules(['testpackage.testmod'], ['testpackage.testmod'])

    def test_load_submodule_with_different_import_path(self):
        self.__assert_modules(['testpackage.testmod'], ['testmod'], path=[get_asset_path('testpackage')])

    def test_get_module_node(self):
        node = self.project.get_module_node('testfile')

        self.assertIsInstance(node, ModuleNode)
        self.assertEqual('testfile', node.name)
        self.assertEqual(get_asset_path('testfile.py'), node.filename)

    def test_metrics(self):
        self.assertTupleEqual((self.metric,), self.project.metrics)

    def test_make_report(self):
        report = FakeReport()
        stdout = StringIO()
        self.project.set_report(report)
        self.project.report(stream=stdout)

        self.assertEqual('report', stdout.getvalue())
        self.assertSetEqual(
            {'testfile', 'testpackage', 'testpackage.testmod'},
            set(report.results.keys())
        )

    def test_init_with_default_values(self):
        self.assertTupleEqual(tuple(sys.path), Project().path)


text:
{% block navbar %}

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#header-nav">
                    Toggle navigation

                </button>
                Voltaire

                    {% set navigation_bar = [
                        ('/', 'index', 'Home'),
                        ('/blog/', 'blog', 'Blog'),
                        ('/forum', 'forum', 'Forum'),
                        ('/map', 'map', 'Map'),
                        ('/donate', 'donate', 'Donate'),
                        ('/signup', 'signup', 'Apply')
                    ] -%}
                    {% set active_page = active_page|default('') -%}

                    {% for href, id, caption in navigation_bar %}

{{ caption|e }}

                    {% endfor %}

{% endblock %}


text:
<?php

namespace Drupal\layout_builder\Normalizer;

use Drupal\layout_builder\Entity\LayoutEntityDisplayInterface;
use Drupal\serialization\Normalizer\ConfigEntityNormalizer;

/**
 * Normalizes/denormalizes LayoutEntityDisplay objects into an array structure.
 *
 * @internal
 *   Tagged services are internal.
 */
class LayoutEntityDisplayNormalizer extends ConfigEntityNormalizer {

  /**
   * {@inheritdoc}
   */
  protected $supportedInterfaceOrClass = LayoutEntityDisplayInterface::class;

  /**
   * {@inheritdoc}
   */
  protected static function getDataWithoutInternals(array $data) {
    $data = parent::getDataWithoutInternals($data);
    // Do not expose the actual layout sections in normalization.
    // @todo Determine what to expose here in
    //   https://www.drupal.org/node/2942975.
    unset($data['third_party_settings']['layout_builder']['sections']);
    return $data;
  }

  /**
   * {@inheritdoc}
   */
  public function hasCacheableSupportsMethod(): bool {
    return TRUE;
  }

}


text:
package com.ehmer.usa;

import android.app.Application;
import android.content.Context;

public class UsaApplication extends Application {

    private ApplicationComponent component;

    public static UsaApplication get(Context ctx) {
        //throws RuntimeException if this class isn't named in AndroidManifest.xml
        return (UsaApplication) ctx.getApplicationContext();
    }

    @Override
    public void onCreate() {
        super.onCreate();
        buildComponentAndInject();

    }

    public void buildComponentAndInject() {
        component = ApplicationComponent.Initializer.init(this);
        component.inject(this);
    }

    public ApplicationComponent component() {
        return component;
    }

}


text:
function setup() {
    createCanvas( windowWidth, 600 );
}

// declare an independent variable for x_pos
let x_pos = 0;

function draw() {
    background( 'rgb(33, 66, 62)' );

    // Map the x_pos to an exponential based Y-position
    let y_pos = height - ((x_pos / width) ** 3) * height;
    // expose the value of the x and y loc's variable
    noStroke();
    text( x_pos, 20, 80 );
    text( y_pos, 20, 100 );

    // draw an ellipse
    noStroke();
    fill(255);
    ellipse( x_pos, y_pos, 30 );

    // draw a reference diagonal line
    stroke('red');
    line(0, height, width, 0);

    // update the x_pos, bound it by the screen
    x_pos += 5;
    x_pos %= width;
}


text:
@interface ESSettingController ()
@property (weak) IBOutlet NSButton *btnImpMJExtesion;
@property (weak) IBOutlet NSButton *btnGeneric;
@property (weak) IBOutlet NSButton *btnOutputToFile;
@property (weak) IBOutlet NSButton *btnPropertyPosition;

@end

@implementation ESSettingController

- (void)windowDidLoad {
    [super windowDidLoad];

    self.btnImpMJExtesion.state = (NSCellStateValue)[[ESJsonFormatSetting defaultSetting] impOjbClassInArray];
    self.btnGeneric.state = (NSCellStateValue)[[ESJsonFormatSetting defaultSetting] useGeneric];
    self.btnOutputToFile.state = (NSCellStateValue)[[ESJsonFormatSetting defaultSetting] outputToFiles];
    self.btnPropertyPosition.state = (NSCellStateValue)[[ESJsonFormatSetting defaultSetting] propertyPosition];

    if (![ESUtils isXcode7AndLater]) {
        self.btnGeneric.enabled = NO;
    }

    [self updateSettingState];
}

- (IBAction)btnImpMtdForMJClick:(NSButton *)sender {
    [[ESJsonFormatSetting defaultSetting] setImpOjbClassInArray:sender.state];
}

- (IBAction)btnUseGenericClick:(NSButton *)sender {
    [[ESJsonFormatSetting defaultSetting] setUseGeneric:sender.state];
}

- (IBAction)btnOutputToFilesClick:(NSButton *)sender {
    [[ESJsonFormatSetting defaultSetting] setOutputToFiles:sender.state];
}

- (IBAction)btnUpercaseKeyWordForIdClick:(NSButton *)sender {
    [[ESJsonFormatSetting defaultSetting] setUppercaseKeyWordForId:sender.state];
}

- (IBAction)btnPropertyPosition:(NSButton *)sender {
    [[ESJsonFormatSetting defaultSetting] setPropertyPosition:sender.state];
    [self updateSettingState];
}

- (IBAction)tapGes:(NSClickGestureRecognizer *)sender {
    NSURL* url = [[ NSURL alloc ] initWithString :@"http://t.cn/RLarUfg"];
    [[NSWorkspace sharedWorkspace] openURL:url];
}

- (void)updateSettingState
{
    self.btnPropertyPosition.title = self.btnPropertyPosition.state ?  @"@property (%@, nonatomic)" : @"@property (nonatomic, %@)";
}

@end


text:
module Banzai
  module Filter
    # HTML filter that "fixes" links to pages/files in a wiki.
    # Rewrite rules are documented in the `WikiPipeline` spec.
    #
    # Context options:
    #   :project_wiki
    class WikiLinkFilter < HTML::Pipeline::Filter
      def call
        return doc unless project_wiki?

        doc.search('a:not(.gfm)').each { |el| process_link_attr(el.attribute('href')) }
        doc.search('video').each { |el| process_link_attr(el.attribute('src')) }
        doc.search('img').each do |el|
          attr = el.attribute('data-src') || el.attribute('src')

          process_link_attr(attr)
        end

        doc
      end

      protected

      def project_wiki?
        !context[:project_wiki].nil?
      end

      def process_link_attr(html_attr)
        return if html_attr.blank?

        html_attr.value = apply_rewrite_rules(html_attr.value)
      rescue URI::Error, Addressable::URI::InvalidURIError
        # noop
      end

      def apply_rewrite_rules(link_string)
        Rewriter.new(link_string, wiki: context[:project_wiki], slug: context[:page_slug]).apply_rules
      end
    end
  end
end


text:
import {inject} from 'aurelia-framework';
import {Router} from 'aurelia-router';
import 'bootstrap';
import 'bootstrap/css/bootstrap.css!';
//
//PouchDB.debug.enable('*');
//
@inject(Router)
export class App {
  constructor(router) {
    this.router = router;
    this.router.configure(config => {
      config.title = 'InfoApp';
      config.map([
        { route: ['','login'],  moduleId: './viewmodels/login',      nav: true, title:'Connexion' },
        { route: 'admin-home',  moduleId: './viewmodels/admin-home', nav: false, title:'Accueil' },
        { route: 'prof-home',  moduleId: './viewmodels/prof-home', nav: false, title:'Accueil' },
        { route: 'etud-home',  moduleId: './viewmodels/etud-home', nav: false, title:'Accueil' },
        { route: 'profil',  moduleId: './viewmodels/profil-model', nav: true, title:'Profil' },
        { route: 'admin-router',  moduleId: './viewmodels/admin/admin-router', nav: true, title:'Administration' }
      ]);
    });
  }// constructor
}


text:
import {ViewportRuler} from '@angular/cdk/scrolling';
import {
  CdkTableModule,
  DataSource
} from '@angular/cdk/table';
import {Component, ElementRef, NgModule} from '@angular/core';
import {
  MatAutocompleteModule,
  MatBadgeModule,
  MatButtonModule,
  MatButtonToggleModule,
  MatCardModule,
  MatCheckboxModule,
  MatChipsModule,
  MatDatepickerModule,
  MatDialog,
  MatDialogModule,
  MatDividerModule,
  MatExpansionModule,
  MatFormFieldModule,
  MatGridListModule,
  MatIconModule,
  MatInputModule,
  MatListModule,
  MatMenuModule,
  MatNativeDateModule,
  MatPaginatorModule,
  MatProgressBarModule,
  MatProgressSpinnerModule,
  MatRadioModule,
  MatRippleModule,
  MatSelectModule,
  MatSidenavModule,
  MatSliderModule,
  MatSlideToggleModule,
  MatSnackBar,
  MatSnackBarModule,
  MatSortModule,
  MatStepperModule,
  MatTableModule,
  MatTabsModule,
  MatToolbarModule,
  MatTooltipModule,
} from '@angular/material';
import {BrowserModule} from '@angular/platform-browser';
import {ServerModule} from '@angular/platform-server';
import {FocusMonitor} from '@angular/cdk/a11y';
import {Observable, of as observableOf} from 'rxjs';

export class TableDataSource extends DataSource<any> {
  connect(): Observable<any> {
    return observableOf([{userId: 1}, {userId: 2}]);
  }

  disconnect() {}
}

@Component({
  template: `<button>Do the thing</button>`
})
export class TestDialog {}

@Component({
  selector: 'kitchen-sink',
  templateUrl: './kitchen-sink.html',
  styleUrls: ['./kitchen-sink.css'],
})
export class KitchenSink {

  /** List of columns for the CDK and Material table. */
  tableColumns = ['userId'];

  /** Data source for the CDK and Material table. */
  tableDataSource = new TableDataSource();

  constructor(
    snackBar: MatSnackBar,
    dialog: MatDialog,
    viewportRuler: ViewportRuler,
    focusMonitor: FocusMonitor,
    elementRef: ElementRef<HTMLElement>) {
    focusMonitor.focusVia(elementRef.nativeElement, 'program');
    snackBar.open('Hello there');
    dialog.open(TestDialog);

    // Do a sanity check on the viewport ruler.
    viewportRuler.getViewportRect();
    viewportRuler.getViewportSize();
    viewportRuler.getViewportScrollPosition();
  }
}

@NgModule({
  imports: [
    BrowserModule.withServerTransition({appId: 'kitchen-sink'}),
    MatAutocompleteModule,
    MatBadgeModule,
    MatButtonModule,
    MatButtonToggleModule,
    MatCardModule,
    MatCheckboxModule,
    MatChipsModule,
    MatDatepickerModule,
    MatDialogModule,
    MatDividerModule,
    MatFormFieldModule,
    MatGridListModule,
    MatIconModule,
    MatInputModule,
    MatListModule,
    MatMenuModule,
    MatNativeDateModule,
    MatPaginatorModule,
    MatProgressBarModule,
    MatProgressSpinnerModule,
    MatRadioModule,
    MatRippleModule,
    MatSelectModule,
    MatSidenavModule,
    MatSliderModule,
    MatSlideToggleModule,
    MatSnackBarModule,
    MatTabsModule,
    MatToolbarModule,
    MatTooltipModule,
    MatExpansionModule,
    MatSortModule,
    MatTableModule,
    MatStepperModule,

    // CDK Modules
    CdkTableModule
  ],
  bootstrap: [KitchenSink],
  declarations: [KitchenSink, TestDialog],
  entryComponents: [TestDialog],
})
export class KitchenSinkClientModule { }

@NgModule({
  imports: [KitchenSinkClientModule, ServerModule],
  bootstrap: [KitchenSink],
})
export class KitchenSinkServerModule { }


text:
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.container.logging;

/**
 * @author Tony Vaagenes
 */
public interface RequestLogHandler {
    void log(RequestLogEntry entry);
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using StackExchange.Profiling;

namespace StackExchange.Opserver.Data.Dashboard.Providers
{
    public partial class BosunDataProvider
    {
        private Cache<List<Node>> _nodeCache;
        public Cache<List<Node>> NodeCache => _nodeCache ?? (_nodeCache = ProviderCache(GetAllNodesAsync, 60, 4 * 60 * 60));

        private Cache<Dictionary<string, List<string>>> _nodeMetricCache;

        public Cache<Dictionary<string, List<string>>> NodeMetricCache
            => _nodeMetricCache ?? (_nodeMetricCache = ProviderCache(
                async () =>
                {
                    var response = await GetFromBosunAsync<Dictionary<string, List<string>>>(GetUrl("api/metric/host"))
                        .ConfigureAwait(false);
                    return response.Result ?? new Dictionary<string, List<string>>();
                }, 10*60, 4*60*60));

        public async Task<List<Node>> GetAllNodesAsync()
        {
            using (MiniProfiler.Current.Step("Get Server Nodes"))
            {
                var nodes = new List<Node>();

                var apiResponse = await GetFromBosunAsync<Dictionary<string, BosunHost>>(GetUrl("api/host")).ConfigureAwait(false);
                if (!apiResponse.Success) return nodes;

                var hostsDict = apiResponse.Result;

                foreach (var h in hostsDict.Values)
                {
                    if (Current.Settings.Dashboard.ExcludePatternRegex?.IsMatch(h.Name) ?? false)
                        continue;

                    Version kernelVersion;
                    // Note: we can't follow this pattern, we'll need to refresh existing nodes
                    // not wholesale replace on poll
                    var n = new Node
                    {
                        Id = h.Name,
                        Name = h.Name,
                        Model = h.Model,
                        Ip = "scollector",
                        DataProvider = this,
                        Status = GetNodeStatus(h),
                        // TODO: Add Last Ping time to all providers
                        LastSync = h.CPU?.StatsLastUpdated,
                        CPULoad = (short?)h.CPU?.PercentUsed,
                        MemoryUsed = h.Memory?.UsedBytes,
                        TotalMemory = h.Memory?.TotalBytes,
                        Manufacturer = h.Manufacturer,
                        ServiceTag = h.SerialNumber,
                        MachineType = h.OS?.Caption,
                        KernelVersion = Version.TryParse(h.OS?.Version, out kernelVersion) ? kernelVersion : null,

                        Interfaces = h.Interfaces?.Select(hi => new Interface
                        {
                            Id = hi.Key,
                            NodeId = h.Name,
                            Name = hi.Value.Name.IsNullOrEmptyReturn($"Unknown: {hi.Key}"),
                            FullName = hi.Value.Name,
                            TypeDescription = hi.Value.Type,
                            Caption = hi.Value.Description,
                            PhysicalAddress = hi.Value.MAC,
                            IPs = hi.Value?.IPAddresses?.Select(ip =>
                            {
                                IPNet result;
                                return IPNet.TryParse(ip, out result) ? result : null;
                            }).Where(ip => ip != null).ToList() ?? new List<IPNet>(),
                            LastSync = hi.Value.StatsLastUpdated,
                            InBps = hi.Value.Inbps,
                            OutBps = hi.Value.Outbps,
                            Speed = hi.Value.LinkSpeed * 1000000,
                            Status = NodeStatus.Active, // TODO: Implement
                            TeamMembers = h.Interfaces?.Where(i => i.Value.Master == hi.Value.Name).Select(i => i.Key).ToList()
                        }).ToList(),
                        Volumes = h.Disks?.Select(hd => new Volume
                        {
                            Id = hd.Key,
                            Name = hd.Key,
                            NodeId = h.Name,
                            Caption = hd.Key,
                            Description = $"{hd.Key}",
                            LastSync = hd.Value.StatsLastUpdated,
                            Used = hd.Value.UsedBytes,
                            Size = hd.Value.TotalBytes,
                            Available = hd.Value.TotalBytes - hd.Value.UsedBytes,
                            PercentUsed = 100 * (hd.Value.UsedBytes / hd.Value.TotalBytes),
                        }).ToList(),
                        //Apps = new List<Application>(),
                        //VMs = new List<Node>()
                    };
                    var hs = new HardwareSummary();
                    if (h.CPU?.Processors != null)
                    {
                        foreach (var p in h.CPU.Processors)
                        {
                            hs.Processors.Add(new HardwareSummary.ProcessorInfo
                            {
                                Name = p.Key,
                                Description = p.Value
                            });
                        }
                    }

                    var hw = h.Hardware;
                    if (hw != null)
                    {
                        if (hw.ChassisComponents != null)
                        {
                            foreach (var c in hw.ChassisComponents)
                            {
                                hs.Components.Add(new HardwareSummary.ComponentInfo
                                {
                                    Name = c.Key.Replace("_", " "),
                                    Status = c.Value.Status
                                });
                            }
                        }
                        if (hw.Memory != null)
                        {
                            foreach (var m in hw.Memory)
                            {
                                hs.MemoryModules.Add(new HardwareSummary.MemoryModuleInfo
                                {
                                    Name = m.Key,
                                    Status = m.Value.Status,
                                    Size = m.Value.Size
                                });
                            }
                        }
                        if (hw.Storage != null)
                        {
                            var s = new HardwareSummary.StorageInfo();
                            if (hw.Storage.Controllers != null)
                            {
                                foreach (var c in hw.Storage.Controllers)
                                {
                                    s.Controllers.Add(new HardwareSummary.StorageInfo.ControllerInfo
                                    {
                                        Name = c.Value.Name,
                                        Status = c.Value.Status,
                                        State = c.Value.State,
                                        SlotId = c.Value.SlotId,
                                        FirmwareVersion = c.Value.FirmwareVersion,
                                        DriverVersion = c.Value.DriverVersion
                                    });
                                }
                            }
                            if (hw.Storage.PhysicalDisks != null)
                            {
                                foreach (var d in hw.Storage.PhysicalDisks)
                                {
                                    s.PhysicalDisks.Add(new HardwareSummary.StorageInfo.PhysicalDiskInfo
                                    {
                                        Name = d.Value.Name,
                                        CapableSpeed = d.Value.CapableSpeed,
                                        Capacity = d.Value.Capacity,
                                        Media = d.Value.Media,
                                        NegotatiedSpeed = d.Value.NegotatiedSpeed,
                                        Part = d.Value.Part,
                                        ProductId = d.Value.ProductId,
                                        SectorSize = d.Value.SectorSize,
                                        Serial = d.Value.Serial,
                                        Status = d.Value.Status,
                                        VendorId = d.Value.VendorId
                                    });
                                }
                            }
                            if (hw.Storage.VirtualDisks != null)
                            {
                                foreach (var d in hw.Storage.VirtualDisks)
                                {
                                    s.VirtualDisks.Add(new HardwareSummary.StorageInfo.VirtualDiskInfo
                                    {
                                        Name = d.Key,
                                        Status = d.Value.Status,
                                        // TODO: Add to Bosun
                                        // Size = d.Value.Size
                                    });
                                }
                            }
                            if (hw.Storage.Batteries != null)
                            {
                                foreach (var b in hw.Storage.Batteries)
                                {
                                    s.Batteries.Add(new HardwareSummary.ComponentInfo
                                    {
                                        Name = b.Key,
                                        Status = b.Value.Status
                                    });
                                }
                            }
                            hs.Storage = s;
                        }
                        if (hw.PowerSupplies != null)
                        {
                            foreach (var ps in hw.PowerSupplies)
                            {
                                hs.PowerSupplies.Add(new HardwareSummary.PowerSupplyInfo
                                {
                                    Name = ps.Key,
                                    Amps = ps.Value.Amps,
                                    Status = ps.Value.Status,
                                    Volts = ps.Value.Volts
                                });
                            }
                        }
                        if (hw.Temps != null)
                        {
                            foreach (var t in hw.Temps)
                            {
                                hs.Temps.Add(new HardwareSummary.TemperatureInfo
                                {
                                    Name = t.Key.Replace("_", " "),
                                    Status = t.Value.Status,
                                    Celsius = t.Value.Celsius
                                });
                            }
                        }
                        if (hw.BoardPowerReading != null)
                        {
                            hs.BoardPowerReading = new HardwareSummary.BoardPowerInfo
                            {
                                Watts = hw.BoardPowerReading.Watts
                            };
                        }
                        n.Hardware = hs;
                    }

                    if (h.UptimeSeconds.HasValue) // TODO: Check if online - maybe against ICMP data last?
                    {
                        n.LastBoot = DateTime.UtcNow.AddSeconds(-h.UptimeSeconds.Value);
                    }
                    n.SetReferences();
                    nodes.Add(n);
                }

                return nodes;
            }
        }

        private NodeStatus GetNodeStatus(BosunHost host)
        {
            if (host.OpenIncidents?.Count > 0)
                return NodeStatus.Warning;
            if (host.ICMPData?.Values.All(p => p.TimedOut) == true)
                return NodeStatus.Unreachable;
            return NodeStatus.Active;
        }

        // ReSharper disable ClassNeverInstantiated.Local
        // ReSharper disable CollectionNeverUpdated.Local
        // ReSharper disable UnusedAutoPropertyAccessor.Local
        private class BosunHost
        {
            public string Name { get; set; }
            public string Model { get; set; }
            public string Manufacturer { get; set; }
            public string SerialNumber { get; set; }
            public int? UptimeSeconds { get; set; }

            public CPUInfo CPU { get; set; }
            public MemoryInfo Memory { get; set; }
            public OSInfo OS { get; set; }
            public Dictionary<string, DiskInfo> Disks { get; set; }
            public Dictionary<string, InterfaceInfo> Interfaces { get; set; }
            public List<IncidentInfo> OpenIncidents { get; set; }
            public Dictionary<string, ICMPInfo> ICMPData { get; set; }
            public HardwareInfo Hardware { get; set; }

            public class CPUInfo
            {
                public float? PercentUsed { get; set; }
                public Dictionary<string, string> Processors { get; set; }
                public DateTime? StatsLastUpdated { get; set; }
            }

            public class MemoryInfo
            {
                public Dictionary<string, string> Modules { get; set; }
                public float? UsedBytes { get; set; }
                public float? TotalBytes { get; set; }
            }

            public class OSInfo
            {
                public string Caption { get; set; }
                public string Version { get; set; }
            }

            public class DiskInfo
            {
                public float? UsedBytes { get; set; }
                public float? TotalBytes { get; set; }
                public DateTime StatsLastUpdated { get; set; }
            }

            public class InterfaceInfo
            {
                public string Name { get; set; }
                public string Description { get; set; }
                public string MAC { get; set; }
                public List<string> IPAddresses { get; set; }
                public string Master { get; set; }
                public DateTime? StatsLastUpdated { get; set; }

                public float? Inbps { get; set; }
                public float? Outbps { get; set; }
                public float? LinkSpeed { get; set; }
                // TODO
                public List<string> Members { get; set; }
                public string Type { get; set; }
            }

            public class IncidentInfo
            {
                public int IncidentID { get; set; }
                public string AlertKey { get; set; }
                public string Status { get; set; }
                public string Subject { get; set; }
                public bool Silenced { get; set; }
            }

            public class ICMPInfo
            {
                public bool TimedOut { get; set; }
                public bool DNSResolved { get; set; }
                public float? RTTMS { get; set; }
            }

            public class HardwareInfo
            {
                public Dictionary<string, MemoryModuleInfo> Memory { get; set; }
                public Dictionary<string, ComponentInfo> ChassisComponents { get; set; }
                public StorageInfo Storage { get; set; }
                public Dictionary<string, TemperatureInfo> Temps { get; set; }
                public Dictionary<string, PowerSupplyInfo> PowerSupplies { get; set; }
                public BoardPowerInfo BoardPowerReading { get; set; }

                public class ComponentInfo
                {
                    public string Status { get; set; }
                }

                public class MemoryModuleInfo : ComponentInfo
                {
                    public string Size { get; internal set; }
                }

                public class StorageInfo
                {
                    public Dictionary<string, ControllerInfo> Controllers { get; set; }
                    public Dictionary<string, PhysicalDiskInfo> PhysicalDisks { get; set; }
                    public Dictionary<string, VirtualDiskInfo> VirtualDisks { get; set; }
                    public Dictionary<string, ComponentInfo> Batteries { get; set; }

                    public class ControllerInfo : ComponentInfo
                    {
                        public string Name { get; set; }
                        public string SlotId { get; set; }
                        public string State { get; set; }
                        public string FirmwareVersion { get; set; }
                        public string DriverVersion { get; set; }
                    }

                    public class PhysicalDiskInfo : ComponentInfo
                    {
                        public string Name { get; set; }
                        public string Media { get; set; }
                        public string Capacity { get; set; }
                        public string VendorId { get; set; }
                        public string ProductId { get; set; }
                        public string Serial { get; set; }
                        public string Part { get; set; }
                        public string NegotatiedSpeed { get; set; }
                        public string CapableSpeed { get; set; }
                        public string SectorSize { get; set; }
                    }

                    public class VirtualDiskInfo : ComponentInfo
                    {

                    }
                }

                public class TemperatureInfo : ComponentInfo
                {
                    public double Celsius { get; set; }
                }

                public class PowerSupplyInfo : ComponentInfo
                {
                    public double Amps { get; set; }
                    public double Volts { get; set; }
                }

                public class BoardPowerInfo
                {
                    public double Watts { get; set; }
                }
            }

        }
        // ReSharper restore CollectionNeverUpdated.Local
        // ReSharper restore ClassNeverInstantiated.Local
        // ReSharper restore UnusedAutoPropertyAccessor.Local
    }
}


text:
package net.myacxy.squinch.helpers.tracking.builder;

import net.myacxy.squinch.helpers.tracking.ITracker;
import net.myacxy.squinch.helpers.tracking.TrackingHelper;

public class LogBuilder extends PropertyLogBuilder<LogBuilder> {

    public LogBuilder(TrackingHelper trackingHelper) {
        super(trackingHelper);
    }

    @Override
    public TrackingHelper post() {
        for (ITracker tracker : trackers) {
            tracker.log(properties);
        }
        return trackingHelper;
    }
}


text:
package org.uberfire.java.nio.fs.file;

import java.io.File;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.PatternSyntaxException;

import org.uberfire.java.nio.IOException;
import org.uberfire.java.nio.base.FileSystemId;
import org.uberfire.java.nio.base.GeneralPathImpl;
import org.uberfire.java.nio.file.FileSystem;
import org.uberfire.java.nio.file.InvalidPathException;
import org.uberfire.java.nio.file.Path;
import org.uberfire.java.nio.file.PathMatcher;
import org.uberfire.java.nio.file.WatchService;
import org.uberfire.java.nio.file.attribute.UserPrincipalLookupService;
import org.uberfire.java.nio.file.spi.FileSystemProvider;

import static org.uberfire.commons.validation.Preconditions.*;

public abstract class BaseSimpleFileSystem implements FileSystem,
                                                      FileSystemId {

    private final FileSystemProvider provider;
    private final String defaultDirectory;
    private final Set<String> supportedFileAttributeViews;
    private final File[] roots;

    BaseSimpleFileSystem( final FileSystemProvider provider,
                          final String path ) {
        this( File.listRoots(), provider, path );
    }

    BaseSimpleFileSystem( final File[] roots,
                          final FileSystemProvider provider,
                          final String path ) {
        checkNotNull( "roots", roots );
        checkCondition( "should have at least one root", roots.length > 0 );
        this.roots = roots;
        this.provider = provider;
        this.defaultDirectory = validateDefaultDir( path );
        this.supportedFileAttributeViews = Collections.unmodifiableSet( new HashSet<String>() {{
            add( "basic" );
        }} );
    }

    @Override
    public String id() {
        return "/";
    }

    private String validateDefaultDir( final String path ) throws IllegalArgumentException {
        checkNotEmpty( "path", path );
        if ( !GeneralPathImpl.create( this, path, false ).isAbsolute() ) {
            throw new IllegalArgumentException();
        }
        return path;
    }

    @Override
    public FileSystemProvider provider() {
        return provider;
    }

    @Override
    public boolean isOpen() {
        return true;
    }

    @Override
    public boolean isReadOnly() {
        return false;
    }

    @Override
    public String getSeparator() {
        return System.getProperty( "file.separator", "/" );
    }

    @Override
    public Set<String> supportedFileAttributeViews() {
        return supportedFileAttributeViews;
    }

    @Override
    public Path getPath( String first,
                         String... more ) throws InvalidPathException {
        if ( more == null || more.length == 0 ) {
            return GeneralPathImpl.create( this, removeTrailingSlash( first ), false );
        }
        final StringBuilder sb = new StringBuilder();
        sb.append( first );
        for ( final String segment : more ) {
            if ( segment.length() > 0 ) {
                if ( sb.length() > 0 ) {
                    sb.append( getSeparator() );
                }
                sb.append( segment );
            }
        }
        return GeneralPathImpl.create( this, sb.toString(), false );
    }

    private String removeTrailingSlash( final String path ) {
        for ( final File root : roots ) {
            if ( root.toString().equals( path ) ) {
                return path;
            }
        }
        if ( path.endsWith( getSeparator() ) ) {
            return path.substring( 0, path.length() - getSeparator().length() );
        }

        return path;
    }

    @Override
    public PathMatcher getPathMatcher( String syntaxAndPattern )
            throws IllegalArgumentException, PatternSyntaxException, UnsupportedOperationException {
        throw new UnsupportedOperationException();
    }

    @Override
    public UserPrincipalLookupService getUserPrincipalLookupService()
            throws UnsupportedOperationException {
        throw new UnsupportedOperationException();
    }

    @Override
    public WatchService newWatchService()
            throws UnsupportedOperationException, IOException {
        throw new UnsupportedOperationException();
    }

    @Override
    public void close() throws IOException, UnsupportedOperationException {
        throw new UnsupportedOperationException( "can't close this file system." );
    }

    File[] listRoots() {
        return roots;
    }

    @Override
    public String toString() {
        return "file://" + id();
    }
}


text:
import configureStore from "../configureStore";

const configureDefaultStore = (initialState = {}, history) =>
  configureStore({}, initialState, history);

export default configureDefaultStore;


text:
package org.apache.sysml.runtime.instructions.spark;

import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.function.Function;
import org.apache.sysml.runtime.DMLRuntimeException;
import org.apache.sysml.runtime.controlprogram.context.ExecutionContext;
import org.apache.sysml.runtime.controlprogram.context.SparkExecutionContext;
import org.apache.sysml.runtime.instructions.cp.CPOperand;
import org.apache.sysml.runtime.matrix.data.MatrixBlock;
import org.apache.sysml.runtime.matrix.data.MatrixIndexes;
import org.apache.sysml.runtime.matrix.operators.Operator;
import org.apache.sysml.runtime.matrix.operators.UnaryOperator;

/**
 *
 */
public class MatrixBuiltinSPInstruction extends BuiltinUnarySPInstruction
{

	public MatrixBuiltinSPInstruction(Operator op, CPOperand in, CPOperand out, String opcode, String instr) {
		super(op, in, out, opcode, instr);
	}

	@Override
	public void processInstruction(ExecutionContext ec)
		throws DMLRuntimeException
	{
		SparkExecutionContext sec = (SparkExecutionContext)ec;

		//get input
		JavaPairRDD<MatrixIndexes,MatrixBlock> in = sec.getBinaryBlockRDDHandleForVariable( input1.getName() );

		//execute unary builtin operation
		UnaryOperator uop = (UnaryOperator) _optr;
		JavaPairRDD<MatrixIndexes,MatrixBlock> out = in.mapValues(new RDDMatrixBuiltinUnaryOp(uop));

		//set output RDD
		updateUnaryOutputMatrixCharacteristics(sec);
		sec.setRDDHandleForVariable(output.getName(), out);
		sec.addLineageRDD(output.getName(), input1.getName());
	}

	/**
	 *
	 */
	private static class RDDMatrixBuiltinUnaryOp implements Function<MatrixBlock,MatrixBlock>
	{
		private static final long serialVersionUID = -3128192099832877491L;

		private UnaryOperator _op = null;

		public RDDMatrixBuiltinUnaryOp(UnaryOperator u_op) {
			_op = u_op;
		}

		@Override
		public MatrixBlock call(MatrixBlock arg0)
			throws Exception
		{
			return (MatrixBlock) arg0.unaryOperations(_op, new MatrixBlock());
		}
	}
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Nucleo.Web.ScriptRendering
{
	public partial class ScriptBlockFirstLook : System.Web.UI.Page
	{
		protected void Page_Load(object sender, EventArgs e)
		{

		}
	}
}


text:
package org.ovirt.engine.ui.uicommonweb.models.quota;

import java.util.ArrayList;

import org.ovirt.engine.core.common.businessentities.permissions;
import org.ovirt.engine.core.common.queries.GetPermissionsForObjectParameters;
import org.ovirt.engine.core.common.queries.VdcQueryReturnValue;
import org.ovirt.engine.core.common.queries.VdcQueryType;
import org.ovirt.engine.ui.frontend.AsyncQuery;
import org.ovirt.engine.ui.frontend.Frontend;
import org.ovirt.engine.ui.frontend.INewAsyncCallback;
import org.ovirt.engine.ui.uicommonweb.auth.ApplicationGuids;
import org.ovirt.engine.ui.uicommonweb.models.SearchableListModel;
import org.ovirt.engine.ui.uicommonweb.models.configure.PermissionListModel;
import org.ovirt.engine.ui.uicompat.ConstantsManager;

public class QuotaPermissionListModel extends PermissionListModel {

    public QuotaPermissionListModel() {
        setTitle(ConstantsManager.getInstance().getConstants().permissionsTitle());
        setHashName("permissions"); //$NON-NLS-1$
    }

    @Override
    protected void SyncSearch() {
        GetPermissionsForObjectParameters tempVar = new GetPermissionsForObjectParameters();
        tempVar.setObjectId(getEntityGuid());
        tempVar.setVdcObjectType(getObjectType());
        tempVar.setDirectOnly(false);
        tempVar.setRefresh(getIsQueryFirstTime());

        AsyncQuery _asyncQuery = new AsyncQuery();
        _asyncQuery.setModel(this);
        _asyncQuery.asyncCallback = new INewAsyncCallback() {
            @Override
            public void OnSuccess(Object model, Object ReturnValue)
            {
                SearchableListModel searchableListModel = (SearchableListModel) model;
                ArrayList<permissions> list =
                        (ArrayList<permissions>) ((VdcQueryReturnValue) ReturnValue).getReturnValue();
                ArrayList<permissions> newList = new ArrayList<permissions>();
                for (permissions permission : list) {
                    if (!permission.getrole_id().equals(ApplicationGuids.quotaConsumer.asGuid())) {
                        newList.add(permission);
                    }
                }
                searchableListModel.setItems(newList);
            }
        };

        tempVar.setRefresh(getIsQueryFirstTime());

        Frontend.RunQuery(VdcQueryType.GetPermissionsForObject, tempVar, _asyncQuery);

        setIsQueryFirstTime(false);
    }

    @Override
    protected void OnEntityChanged()
    {
        super.OnEntityChanged();
        getSearchCommand().Execute();
    }

    @Override
    protected String getListName() {
        return "QuotaPermissionListModel"; //$NON-NLS-1$
    }

}


text:
References
==========

.. _reference1:

  1. Navas-Molina, J.A., Peralta-Sánchez, J.M., González, A., McMurdie, P.J., Vázquez-Baeza, Y., Xu, Z., Ursell, L.K., Lauber, C., Zhou, H., Song S.J., Huntley, J., Ackermann, G.L., Berg-Lyons, D., Holmes, S., Caporaso, J.G., Knight, R. (2013). "Advancing Our Understanding of the Human Microbiome Using QIIME". Methods in Enzymology. (531): 371-444

.. _reference2:

  2. Ewing, B., Hillier, L., Wendi, M.C., Green, P. (1998). (1998). "Base-calling of automated sequencer traces using phred. I. Accuracy assessment". Genome Research. 8 (3): 175–185.

.. _reference3:

  3. Golay, Marcel J. E. (1949). "Notes on Digital Coding". Proc. IRE. (37): 657

.. _reference4:

  4. Caporaso, J., Lauber, C.L., Walter, W.A. Berg0Lyons, D., Huntley, J., Fierer, N., Owens, S.M., Betley, J., Fraser, L., Mauer, M., Gormley, N., Gilbert, J.A., Smith, G., Knight, R., (2012) "Ultra-high-throughput microbial community analysis on the Illumina HiSeq and MiSeq platforms". ISME J.

.. _reference5:

  5. Amir, A., McDonald, D., Navas-Molina, J.A., Kopylova, E., Morton, J., Xu, Z.Z., Kightley, E.P.,  Thompson, L.R., Hyde, E.R., Gonzalez, A., Knight, R. (2017) "Deblur rapidly resolves single-nucleotide community sequence patterns." mSystems. 2 (2) e00191-16.

.. _reference6:

  6. Chou, H.H., Holmes, M.H. (2001). "DNA sequence quality trimming and vector removal". Bioinformatics. 17 (12):1093–1104.

.. _reference7:

  7. McDonald, D., Price, M. N., Goodrich, J., Nawrocki, E. P., DeSantis, T. Z., Probst, A., Anderson, G. L., Knight, R.,  Hugenholtz, P. (2012). "An improved Greengenes taxonomy with explicit ranks for ecological and evolutionary analyses of bacteria and archaea." The ISME Journal. 6(3): 610–618.

.. _reference8:

  8. Quast, C., Pruesse, E., Yilmaz, P., Gerken, J., Schweer, T., Yarza, P., Peplies, J., Glöckner, F. O. (2013). "The SILVA ribosomal RNA gene database project: improved data processing and web-based tools". Nucl. Acids Res. 41 (D1): D590-D596.

.. _reference9:

  9. Abarenkov, K., Nilsson, R. H., Larsson, K., Alexander, I. J., Eberhardt, U., Erland, S., Høiland, K., Kjøller, R., Larsson, E., Pennanen, R., Sen, R., Taylor, A. F. S., Tedersoo, L., Ursing, B. M., Vrålstad, T., Liimatainen, K., Peintner, U., Kõljalg, U. (2010). "The UNITE database for molecular identification of fungi - recent updates and future perspectives". New Phytologist. 186(2): 281-285.

.. _reference10:

  10. Kopylova, E., Noe, L., Touzet, H. (2012). "SortMeRNA: fast and accurate filtering of ribosomal RNAs in metatranscriptomic data". Bioinformatics. 28 (24) 3211-7.

.. _reference11:

  11. Heck, K.L., Van Belle, G., Simberloff, D. (1975). "Explicit Calculation of the Rarefaction Diversity Measurement and the Determination of Sufficient Sample Size". Ecology. 56(6): 1459-1461

.. _reference12:

  12. McMurdie, P.J. and Holmes, S. (2014). "Waste not, want not: Why rarefying microbiome data is inadmissible". PLOS Computational Biology 10(4).

.. _reference13:

  13. Whittaker, R.H. (1960). "Vegetation of the Siskiyou Mountains, Oregon and California". Ecological Monographs. (30)" 279–338.

.. _reference14:

  14. Chao, A. (1984). "Non-parametric estimation of the number of classes in a population". Scandinavian Journal of Statistics (11): 265-270.

.. _reference15:

  15. Berger, W.H. and Parker, F.L. (1970). "Diversity of planktonic Foraminifera in deep sea sediments". Science. (168): 1345-1347.

.. _reference16:

  16. Pielou, E.C. (1975). Ecological Diversity. New York, Wiley InterScience.

.. _reference17:

  17. Chase, J.M., and Knight, R. (2013). "Scale-dependent effect sizes of ecological drivers on biodiversity: why standardised sampling is not enough". Ecology Letters (16): 17-26.

.. _reference18:

  18. Faith. D.P. (1992). "Conservation evaluation and phylogenetic diversity". Biological Conservation. (61) 1-10.

.. _reference19:

  19. Fisher, R.A., Corbet, A.S. and Williams, C.B. (1943). "The relation between the number of species and the number of individuals in a random sample of an animal population". Journal of Animal Ecology. (12): 42-58.

.. _reference20:

  20. Gini, C. (1912). "Variability and Mutability". C. Cuppini, Bologna. 156.

.. _reference21:

  21. Good. I.J (1953) "The populations frequency of Species and the Estimation of Populations Parameters". Biometrika. 40(3/4):237-264.

.. _reference22:

  22. Heip, C. (1974). "A new index measuring evenness". J. Mar. Biol. Ass. UK. (54): 555-557.

.. _reference23:

  23. Lladser, M.E., Gouet, R., Reeder, R. (2011). "Extrapolation of Urn Models via Poissonization: Accurate Measurements of the Microbial Unknown". PLoS.

.. _reference24:

  24. Magurran, A.E. (2004). "Measuring biological diversity". Blackwell. 76-77.

.. _reference25:

  25. McIntosh, R.P. (1967). "An index of diversity and the relation of certain concepts to diversity". Ecology. (48): 392-404.

.. _reference26:

  26. Raaijmakers, J.G.W. (1987). "Statistical analysis of the Michaelis-Menten equation". Biometrics. (43): 793-803.

.. _reference27:

  27. DeSantis, T.Z., Hugenholtz, P., Larsen, N., Rojas, M., Brodie, E.L., Keller, K. Huber, T., Davis, D., Hu, P., Andersen, G.L. (2006). "Greengenes, a Chimera-Checked 16S rRNA Gene Database and Workbench Compatible with ARB". Applied and Environmental Microbiology (72): 5069–5072.

.. _reference28:

  28. Pielou, E.C. (1966). "The measurement of diversity in different types of biological collections". J. Theor. Biol. (13): 131-144.

.. _reference29:

  29. Robbins, H.E. (1968). "Estimating the Total Probability of the unobserved outcomes of an experiment". Ann Math. Statist. 39(1): 256-257.

.. _reference30:

  30. Shannon, C.E. and Weaver, W. (1949). "The mathematical theory of communication". University of Illonois Press, Champaign, Illonois.

.. _reference31:

  31. Simpson, E.H. (1949). "Measurement of Diversity". Nature. (163): 688.

.. _reference32:

  32. Strong, W.L. (2002). "Assessing species abundance uneveness within and between plant communities". Community Ecology. (3): 237-246.

.. _reference33:

  33. Chang, Q., Luan, Y., & Sun, F. (2011). "Variance adjusted weighted UniFrac: a powerful beta diversity measure for comparing communities based on phylogeny". BMC Bioinformatics.12(1): 118.

.. _reference34:

  34. Sorenson, T. (1948) "A method of establishing groups of equal amplitude in plant sociology based on similarity of species content." Kongelige Danske Videnskabernes Selskab 5.1-34: 4-7.

.. _reference35:

  35. Lance, Godfrey L.N. and Williams, W.T. (1967). "A general theory of classificatory sorting strategies II. Clustering systems." The computer journal 10 (3):271-277.

.. _reference36:

  36. Cantrell, C.D. (2000). "Modern Mathematical Methods for Physicists and Engineers". Cambridge University Press.

.. _reference37:

  37. Paul, E.B. (2006). "Manhattan distance". Dictionary of Algorithms and Data Structures

.. _reference38:

  38. Galton, F. (1877). "Typical laws of heredity". Nature. 15 (388): 492–495.

.. _reference39:

  39. Ochiai, A. (1957). "Zoogeographical Studies on the Soleoid Fishes Found in Japan and its Neighhouring Regions-II". Nippon Suisan Gakkaishi. 22(9): 526-530.

.. _reference40:

  40. Dice, Lee R. (1945). "Measures of the Amount of Ecologic Association Between Species". Ecology. 26 (3): 297–302.

.. _reference41:

  41. Legendre, P. and Caceres, M. (2013). "Beta diversity as the variance of community data: dissimilarity coefficients and partitioning." Ecology Letters. 16(8): 951-963.

.. _reference42:

  42. Chen, F., Bittinger, K., Charlson, E.S., Hoffmann, C., Lewis, J., Wu, G. D., Collman, R.G., Bushman, R.D., Li,H. (2012). "Associating microbiome composition with environmental covariates using generalized UniFrac distances." Bioinformatics. 28 (16): 2106-2113.

.. _reference43:

  43. Hamming, R.W. (1950) "Error Detecting and Error Connecting Codes". The Bell System Technical Journal. (29): 147-160.

.. _reference44:

  44. Jaccard, P. (1908). "Nouvellesrecherches sur la distribution florale." Bull. Soc. V and. Sci. Nat., (44):223-270.

.. _reference45:

  45. Kulcynski, S. (1927). "Die Pflanzenassoziationen der Pieninen. Bulletin International de l'Academie Polonaise des Sciences et des Lettres". Classe des Sciences Mathematiques et Naturelles. 57-203.

.. _reference46:

  46. Janson, S., and Vegelius, J. (1981). "Measures of ecological association". Oecologia. (49): 371–376.

.. _reference47:

  47. Tanimoto, T. (1958). "An Elementary Mathematical theory of Classification and Prediction". New York: Internal IBM Technical Report.

.. _reference48:

  48. Russell, P.F. and Rao, T.R. (1940). "On habitat and association of species of anopheline larvae in south-eastern Madras". J. Malaria Inst. India. (3): 153-178.

.. _reference49:

  49. Sokal, R.R. and Michener, C.D. (1958). "A statistical method for evaluating systematic relationships". Univ. Kans. Sci. Bull. (38) 1409-1438.

.. _reference50:

  50. Sokal, R.R. and Sneath, P.H.A. (1963). "Principles of Numerical Taxonomy". W. H. Freeman, San Francisco, California.

.. _reference51:

  51. Lozupone, C. and Knight, R. (2005). "UniFrac: a new phylogenetic method for comparing microbial communities." Applied and environmental microbiology 71 (12): 8228-8235.

.. _reference52:

  52. Chan, Y., Ching, W.K., Ng, M.K., Huang, J.Z. (2004). "An optimization algorithm for clustering using weighted dissimilarity measures". Pattern Recognition. 37(5): 943-952.

.. _reference53:

  53. Lozupone, C. A., Hamady, M., Kelley, S. T., Knight, R. (2007). "Quantitative and qualitative beta diversity measures lead to different insights into factors that structure microbial communities". Applied and Environmental Microbiology. 73(5): 1576–85.

.. _reference54:

  54. Ronbach, L.J. (1951). "Coefficient alpha and the internal structure of tests". Psychometrika. 16 (3): 297–334.

.. _reference55:

  55. Spearman, C. (1904). "The proof and measurement of association between two things". American Journal of Psychology. (15): 72–101.

.. _reference56:

  56. Pearson, K. (1895). "Notes on regression and inheritance in the case of two parents". Proceedings of the Royal Society of London. (58): 240–242.

.. _reference57:

  57. Pearson, K. (1901). "On Lines and Planes of Closest Fit to Systems of Points in Space" Philosophical Magazine. 2 (11): 559–572.

.. _reference58:

  58. Vazquez-Baeza, Y., Pirrung, M., Gonzalez, A., Knight, R. (2013). "Emperor: A tool for visualizing high-throughput microbial community data". Gigascience 2(1):16.

.. _reference59:

  59. Clarke, K.R. (1993). "Non-parametric multivariate analyses of changes in community structure". Austral Ecology. 18 (1): 117–143.

.. _reference60:

  60. Anderson, M.J. (2001). "A new method for non-parametric multivariate analysis of variance". Austral Ecology. 26 (1): 32–46

.. _reference61:

  61. Kruskal, W.H. and Wallis, W.A. (1952). "Use of ranks in one-criterion variance analysis". Journal of the American Statistical Association. 47 (260): 583–621.

.. _reference62:

  62. Illumina. (2014, May 21). Illumina MiSeq, 16S rRNA Sequencing and the American Gut Project. Retrieved from https://www.youtube.com/watch?v=1uZtCMY-yEw

.. _reference63:

  63. An Introduction to the Actinobacteria. (2007). Microbiology today, 34(2).

.. _reference64:

  64. Barka, E.A., Vatsa, P., Sanchez, L., Gaveau-Vaillant, N., Jacquard, C., Klenk, H-P., Clément, C., Ouhdouch, Y., and van Wezel, G.P. (2016). Taxonomy, physiology, and natural products of Actinobacteria. Microbiol Mol Biol Rev 80:1–43.

.. _reference65:

  65. Basics of alpha-diversity with fuzzy microbe demo - University of Colorado Boulder, University of Colorado System, University of California, San Diego. (n.d.). Retrieved from https://www.coursera.org/learn/microbiome/lecture/j5bSx/basics-of-alpha-diversity-with-fuzzy-microbe-demo

.. _reference66:

  66. Demo: Tour of the Knight Lab - University of Colorado Boulder, University of Colorado System, University of California, San Diego. (n.d.). Retrieved from https://www.coursera.org/learn/microbiome/lecture/uIYyi/demo-tour-of-the-knight-lab

.. _reference67:

  67. Thomas, F., Hehemann, J., Rebuffet, E., Czjzek, M., & Michel, G. (2011). Environmental and Gut Bacteroidetes: The Food Connection. Frontiers in Microbiology, 2.

.. _reference68:

  68. Beta-diversity, and visualizing differences - University of Colorado Boulder, University of Colorado System, University of California, San Diego. (n.d.). Retrieved from https://www.coursera.org/learn/microbiome/lecture/NOo6W/beta-diversity-and-visualizing-differences

.. _reference69:

  69. Next Generation Sequencing (NGS) - An Introduction. (2015, June 22). Retrieved from https://www.youtube.com/watch?v=jFCD8Q6qSTM

.. _reference70:

  70. Knights, D. (2016, April 01). Microbiome Discovery 19: Compositionality. Retrieved from https://www.youtube.com/watch?v=X60nFYpLWRs

.. _reference71:

  71. Morton, J.T., Sanders, J., Quinn, R.A., Mcdonald, D., Gonzalez, A., Vázquez-Baeza, Y., Navas-Molina, J.A., Song, J.S., Metcalf, J.L., Hyde, E.R., Lladser, M., Dorrestein, P.C., and Knight, R. (2017). Balance Trees Reveal Microbial Niche Differentiation. MSystems, 2(1).

.. _reference72:

  72. Ventura, M., Canchaya, C., Tauch, A., Chandra, G., Fitzgerald, G.F., Chater, K.F., and Sinderen, D.V. (2007). Genomics of Actinobacteria: Tracing the Evolutionary History of an Ancient Phylum. Microbiology and Molecular Biology Reviews, 71(3): 495-548.

.. _reference73:

  73. Ley, R.E., Backhed, F., Turnbaugh, P., Lozupone, C.A., Knight, R.D., and (2005). Obesity alters gut microbial ecology. PNAS. 102 (31): 11070-11075.

.. _reference74:

  74. Low G C Gram Positive Bacteria. (n.d.). Retrieved from https://micro.cornell.edu/research/epulopiscium/low-g-and-c-gram-positive-bacteria

.. _reference75:

  75. Williams, K. P., Gillespie, J. J., Sobral, B. W., Nordberg, E. K., Snyder, E. E., Shallom, J. M., and Dickerman, A. W. (2010). Phylogeny of Gammaproteobacteria. Journal of Bacteriology, 192(9), 2305-2314.

.. _reference76:

  76. NIH Human Microbiome Project. (2009). Microbe Magazine, 4(9), 393-393.

.. _reference77:

  77. The Human Microbiome Consotrium. (2012). Structure, Function and diversity of the healthy human microbiome. 486: 207-214.

.. _reference78:

  78. Yang, B., Wang, Y., & Qian, P. (2016). Sensitivity and correlation of hypervariable regions in 16S rRNA genes in phylogenetic analysis. BMC Bioinformatics. 17(1).

.. _reference79:

  79. Illumina. (2016, October 05). Illumina Sequencing by Synthesis. Retrieved from https://www.youtube.com/watch?v=fCd6B5HRaZ8

.. _reference80:

  80. Lan, Y., Rosen, G., and Hershberg, R. (2016). Marker genes that are less conserved in their sequences are useful for predicting genome-wide similarity levels between closely related prokaryotic strains. Microbiome, 4(1).

.. _reference81:

  81. Isotopes and mass spectrometry (article). (n.d.). Retrieved from https://www.khanacademy.org/science/chemistry/atomic-structure-and-properties/mass-spectrometry/a/isotopes-and-mass-spectrometry

.. _reference82:

  82. How do we identify a microbe? - University of Colorado Boulder, University of Colorado System, University of California, San Diego. (n.d.). Retrieved from https://www.coursera.org/learn/microbiome/lecture/VltJR/how-do-we-identify-a-microbe

.. _reference83:

  83. Nguyen, N., Warnow, T., Pop, M., & White, B. (2016). A perspective on 16S rRNA operational taxonomic unit clustering using sequence similarity. Npj Biofilms and Microbiomes, 2(1).

.. _reference84:

  84. Knights, D. (2016, January 22). Microbiome Discovery 5: Picking OTUs. Retrieved from https://www.youtube.com/watch?v=Ok5h24KZbAE

.. _reference85:

  85. Rideout, J.R., He, Y., Navas-Molina, J.A., Walters, W.A., Ursell, L.K., Gibbons, S.M., Chase, J., McDonald, D., Gonzalez, A., Robbins-Pianka, A., Clemente, J.C., Gilber, J., Huse, S.M., Zhou, H.W., Knight, R., and Caporaso, J.G. (2014). Subsampled open-reference clustering creates consistent, comprehensive OTU definitions and scales to billions of sequences.

.. _reference86:

  86. Griffen, A.L., Beall, C.J., Campbell, J.H., Firestone, N.D., Kumar, P.S., Yang, Z.K., Podar, M., and Leys, E. J. (2011). Distinct and complex bacterial profiles in human periodontitis and health revealed by 16S pyrosequencing. The ISME Journal, 6(6): 1176-1185.

.. _reference87:

  87. Weiss, S., Xu, Z. Z., Peddada, S., Amir, A., Bittinger, K., Gonzalez, A., Lozupone, C., Zaneveld, J.R., Vazquez-Baeza, Y., Birmingham, A., Hyde, E.R., and Knight, R. (2017). Normalization and microbial differential abundance strategies depend upon data characteristics. Microbiome, 5(1).

.. _reference88:

  88. Proteobacteria. (n.d.). Retrieved from https://courses.lumenlearning.com/microbiology/chapter/proteobacteria/

.. _reference89:

  89. Polymerase Chain Reaction (PCR) - Quantitative PCR (qPCR). (2016, April 28). Retrieved from https://www.youtube.com/watch?v=YhXj5Yy4ksQ

.. _reference90:

  90. Basics of high throughput DNA sequencing. (2017, February 11). Retrieved December 19, 2017, from https://www.youtube.com/watch?v=JD3UJYkxdQs

.. _reference91:

  91. Callahan, B.J., Mcmurdie, P.J., Rosen, M.J., Han, A.W., Johnson, A.J., and Holmes, S.P. (2016). DADA2: High-resolution sample inference from Illumina amplicon data. Nature Methods, 13(7), 581-583.

.. _reference92:

  92. Knights, D. (2016, February 12). Microbiome Discovery 10: Statistical testing part 1. Retrieved from https://www.youtube.com/watch?v=_uDv7LRUUsY

.. _reference93:

  93. Knights, D. (2016, March 04). Microbiome Discovery 11: Statistical testing part 2. Retrieved from https://www.youtube.com/watch?v=tNxfYqa5Rtc


text:
package org.apache.kafka.streams.processor.internals;

import org.apache.kafka.common.KafkaException;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.utils.LogContext;
import org.apache.kafka.streams.errors.TaskMigratedException;
import org.apache.kafka.streams.processor.TaskId;

import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

class AssignedStreamsTasks extends AssignedTasks<StreamTask> implements RestoringTasks {
    private final Map<TaskId, StreamTask> restoring = new HashMap<>();
    private final Set<TopicPartition> restoredPartitions = new HashSet<>();
    private final Map<TopicPartition, StreamTask> restoringByPartition = new HashMap<>();

    AssignedStreamsTasks(final LogContext logContext) {
        super(logContext, "stream task");
    }

    @Override
    public StreamTask restoringTaskFor(final TopicPartition partition) {
        return restoringByPartition.get(partition);
    }

    @Override
    List<StreamTask> allTasks() {
        final List<StreamTask> tasks = super.allTasks();
        tasks.addAll(restoring.values());
        return tasks;
    }

    @Override
    Set<TaskId> allAssignedTaskIds() {
        final Set<TaskId> taskIds = super.allAssignedTaskIds();
        taskIds.addAll(restoring.keySet());
        return taskIds;
    }

    @Override
    boolean allTasksRunning() {
        return super.allTasksRunning() && restoring.isEmpty();
    }

    RuntimeException closeAllRestoringTasks() {
        RuntimeException exception = null;

        log.trace("Closing all restoring stream tasks {}", restoring.keySet());
        final Iterator<StreamTask> restoringTaskIterator = restoring.values().iterator();
        while (restoringTaskIterator.hasNext()) {
            final StreamTask task = restoringTaskIterator.next();
            log.debug("Closing restoring task {}", task.id());
            try {
                task.closeStateManager(true);
            } catch (final RuntimeException e) {
                log.error("Failed to remove restoring task {} due to the following error:", task.id(), e);
                if (exception == null) {
                    exception = e;
                }
            } finally {
                restoringTaskIterator.remove();
            }
        }

        restoring.clear();
        restoredPartitions.clear();
        restoringByPartition.clear();

        return exception;
    }

    void updateRestored(final Collection<TopicPartition> restored) {
        if (restored.isEmpty()) {
            return;
        }
        log.trace("Stream task changelog partitions that have completed restoring so far: {}", restored);
        restoredPartitions.addAll(restored);
        for (final Iterator<Map.Entry<TaskId, StreamTask>> it = restoring.entrySet().iterator(); it.hasNext(); ) {
            final Map.Entry<TaskId, StreamTask> entry = it.next();
            final StreamTask task = entry.getValue();
            if (restoredPartitions.containsAll(task.changelogPartitions())) {
                transitionToRunning(task);
                it.remove();
                log.trace("Stream task {} completed restoration as all its changelog partitions {} have been applied to restore state",
                    task.id(),
                    task.changelogPartitions());
            } else {
                if (log.isTraceEnabled()) {
                    final HashSet<TopicPartition> outstandingPartitions = new HashSet<>(task.changelogPartitions());
                    outstandingPartitions.removeAll(restoredPartitions);
                    log.trace("Stream task {} cannot resume processing yet since some of its changelog partitions have not completed restoring: {}",
                        task.id(),
                        outstandingPartitions);
                }
            }
        }
        if (allTasksRunning()) {
            restoredPartitions.clear();
        }
    }

    void addToRestoring(final StreamTask task) {
        restoring.put(task.id(), task);
        for (final TopicPartition topicPartition : task.partitions()) {
            restoringByPartition.put(topicPartition, task);
        }
        for (final TopicPartition topicPartition : task.changelogPartitions()) {
            restoringByPartition.put(topicPartition, task);
        }
    }

    /**
     * @throws TaskMigratedException if committing offsets failed (non-EOS)
     *                               or if the task producer got fenced (EOS)
     */
    int maybeCommitPerUserRequested() {
        int committed = 0;
        RuntimeException firstException = null;

        for (final Iterator<StreamTask> it = running().iterator(); it.hasNext(); ) {
            final StreamTask task = it.next();
            try {
                if (task.commitRequested() && task.commitNeeded()) {
                    task.commit();
                    committed++;
                    log.debug("Committed active task {} per user request in", task.id());
                }
            } catch (final TaskMigratedException e) {
                log.info("Failed to commit {} since it got migrated to another thread already. " +
                        "Closing it as zombie before triggering a new rebalance.", task.id());
                final RuntimeException fatalException = closeZombieTask(task);
                if (fatalException != null) {
                    throw fatalException;
                }
                it.remove();
                throw e;
            } catch (final RuntimeException t) {
                log.error("Failed to commit StreamTask {} due to the following error:",
                        task.id(),
                        t);
                if (firstException == null) {
                    firstException = t;
                }
            }
        }

        if (firstException != null) {
            throw firstException;
        }

        return committed;
    }

    /**
     * Returns a map of offsets up to which the records can be deleted; this function should only be called
     * after the commit call to make sure all consumed offsets are actually committed as well
     */
    Map<TopicPartition, Long> recordsToDelete() {
        final Map<TopicPartition, Long> recordsToDelete = new HashMap<>();
        for (final StreamTask task : running.values()) {
            recordsToDelete.putAll(task.purgableOffsets());
        }

        return recordsToDelete;
    }

    /**
     * @throws TaskMigratedException if the task producer got fenced (EOS only)
     */
    int process(final long now) {
        int processed = 0;

        final Iterator<Map.Entry<TaskId, StreamTask>> it = running.entrySet().iterator();
        while (it.hasNext()) {
            final StreamTask task = it.next().getValue();
            try {
                if (task.isProcessable(now) && task.process()) {
                    processed++;
                }
            } catch (final TaskMigratedException e) {
                log.info("Failed to process stream task {} since it got migrated to another thread already. " +
                        "Closing it as zombie before triggering a new rebalance.", task.id());
                final RuntimeException fatalException = closeZombieTask(task);
                if (fatalException != null) {
                    throw fatalException;
                }
                it.remove();
                throw e;
            } catch (final RuntimeException e) {
                log.error("Failed to process stream task {} due to the following error:", task.id(), e);
                throw e;
            }
        }

        return processed;
    }

    /**
     * @throws TaskMigratedException if the task producer got fenced (EOS only)
     */
    int punctuate() {
        int punctuated = 0;
        final Iterator<Map.Entry<TaskId, StreamTask>> it = running.entrySet().iterator();
        while (it.hasNext()) {
            final StreamTask task = it.next().getValue();
            try {
                if (task.maybePunctuateStreamTime()) {
                    punctuated++;
                }
                if (task.maybePunctuateSystemTime()) {
                    punctuated++;
                }
            } catch (final TaskMigratedException e) {
                log.info("Failed to punctuate stream task {} since it got migrated to another thread already. " +
                        "Closing it as zombie before triggering a new rebalance.", task.id());
                final RuntimeException fatalException = closeZombieTask(task);
                if (fatalException != null) {
                    throw fatalException;
                }
                it.remove();
                throw e;
            } catch (final KafkaException e) {
                log.error("Failed to punctuate stream task {} due to the following error:", task.id(), e);
                throw e;
            }
        }
        return punctuated;
    }

    void clear() {
        super.clear();
        restoring.clear();
        restoringByPartition.clear();
        restoredPartitions.clear();
    }

    public String toString(final String indent) {
        final StringBuilder builder = new StringBuilder();
        builder.append(super.toString(indent));
        describe(builder, restoring.values(), indent, "Restoring:");
        return builder.toString();
    }

    // for testing only

    Collection<StreamTask> restoringTasks() {
        return Collections.unmodifiableCollection(restoring.values());
    }

}


text:
Use extrusion to turn a 2d shape into a 3d mesh. Extrusion is the process of "pulling" a 2d shape through space to make it 3d. This module contains a single function that accepts a collection of 2d points, and returns a 3d mesh in the form of a [`simplicial complex`](https://github.com/mikolalysenko/simplicial-complex), a data structure that works well with the [`stack.gl`](http://stack.gl/) ecosystem. The implementation uses seidel's algorithm to triangulate the top and bottom faces, and  simple triangulated rectangles for the sides.

View a [demo](http://freeman-lab.github.io/extrude).

![hex](gif/triangle.gif)![hex](gif/square.gif)![hex](gif/hexagon.gif)

[![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard)

## install

To use in your project

```javascript
npm install extrude
```

To see an example, clone this repo, then call

```javascript
npm install
npm start
```
and it should open a browser with a floating square. You can also try

```javascript
npm run demo
```
for a demo with several shapes.

## example

Assuming you already have a stack.gl context `gl`, make a cube like this!

```javascript
var extrude = require('extrude')

var points = [[-1, -1], [1, -1], [1, 1], [-1, 1]]
var cube = extrude(points, {bottom: -1, top: 1})

var geometry = require('gl-geometry')(gl)
geometry.attr('position', cube.positions)
geometry.faces(cube.cells)
```

See [`example.js`](example.js) for a complete end-to-end example.

## usage

#### `complex = extrude(points, opts)`

Create a simplicial complex from a set of points.

`points` should be a list in the form `[[x, y], [x, y], ...]`

`complex` has two attributes:
- `complex.position` : array of 3d vertices `[[x, y, z], [x, y, z], ...]`
- `complex.cells` : array of tuples that index into the vertices `[[i, j, k], [i, j, k], ...]`

`opts` can include the following options:
- `opts.bottom` : bottom of the extruded object `default: 0`
- `opts.top` : top of the extruded object `default: 1`
- `opts.closed` : whether to close the top and bottom of the mesh `default: true`

If `top` and `bottom` are equal it will result in a single-sided 3d surface.


text:
//
//  UIBarButtonItem+YYAdd.h
//  YYKit <https://github.com/ibireme/YYKit>
//
//  Created by ibireme on 13/10/15.
//  Copyright (c) 2015 ibireme.
//
//  This source code is licensed under the MIT-style license found in the
//  LICENSE file in the root directory of this source tree.
//

#import <UIKit/UIKit.h>

/**
 Provides extensions for `UIBarButtonItem`.
 */
@interface UIBarButtonItem (YYAdd)

/**
 The block that invoked when the item is selected. The objects captured by block
 will retained by the ButtonItem.

 @discussion This param is conflict with `target` and `action` property.
 Set this will set `target` and `action` property to some internal objects.
 */
@property (nonatomic, copy) void (^actionBlock)(id);

@end