text:
"""Tests for roc.py."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import itertools
from absl.testing import absltest
from absl.testing import parameterized
import numpy as np
import sklearn.metrics
import roc

def generate_test_data(rng, num_scores=1, scale_factor=1):
  num_positives = int(100 * scale_factor)
  num_negatives = int(200 * scale_factor)
  y_true = [0] * num_negatives + [1] * num_positives

  y_scores = []
  for _ in range(num_scores):
    y_score = np.concatenate(
        (rng.randn(num_negatives), 1.0 + rng.randn(num_positives)))
    y_scores.append(y_score)
  if num_scores == 1:
    y_scores = y_scores[0]

  y_ordinal = rng.randint(20, size=num_positives + num_negatives)
  sample_weight = rng.rand(num_positives + num_negatives) > 0.1
  return y_true, y_scores, y_ordinal, sample_weight

class DeLongIntervalTest(parameterized.TestCase):

  def setUp(self):
    super(DeLongIntervalTest, self).setUp()
    rng = np.random.RandomState(1987)
    self.y_true, self.y_score, self.y_ordinal, self.weights = (
        generate_test_data(rng))
    self.rng = rng

  def testFullCoverage(self):
    """When the coverage is 100% the CI should be (0.0, 1.0)."""
    ci = roc.delong_interval(self.y_true, self.y_score, coverage=1.0)
    np.testing.assert_allclose((0.0, 1.0), ci)

  def testPerfectDiscriminator(self):
    """When the classifier is perfect, the CI should be (1.0, 1.0)."""
    ci = roc.delong_interval(self.y_true, self.y_true)
    np.testing.assert_allclose((1.0, 1.0), ci)

  @parameterized.parameters(
      itertools.product((0.5, 0.75, 0.95, 0.99), (True, False)))
  def testMidpointMatchesSklearn(self, coverage, ordinals):
    """The midpoint of the CI should be equal to sklearn's AUC.

    Args:
      coverage: The coverage of the confidence interval. Note that if coverage
        is 1.0, the resulting confidence interval will be (0, 1), so the
        midpoint will be the meaningless value of 0.5.
      ordinals: whether to use an ordinal score or not. These types of scores
        tend to have "ties"; multiple observations share the same score.
    """
    if ordinals:
      y_score = self.y_ordinal
    else:
      y_score = self.y_score

    lower, upper = roc.delong_interval(
        self.y_true, y_score, sample_weight=self.weights, coverage=coverage)
    midpoint = 0.5 * (lower + upper)
    sklearn_auc = sklearn.metrics.roc_auc_score(
        self.y_true, y_score, sample_weight=self.weights)
    np.testing.assert_allclose(sklearn_auc, midpoint)

  def testMatchesRPackage(self):
    """Benchmark against a reference implementation in the R language.

    Xavier Robin, Natacha Turck, Alexandre Hainard, et al. (2011)
    pROC: an open-source package for R and S+ to analyze and compare ROC curves
    BMC Bioinformatics, 7, 77. DOI: 10.1186/1471-2105-12-77.

    R code:
    ```
    > library(pROC)
    > x <- c(seq(0, 98, 2), seq(1, 99, 2))
    > y <- c(rep(0, 50), rep(1, 50))
    > ci(roc(response=y, predictor=x))
    95% CI: 0.3957-0.6243 (DeLong)
    ```
    """
    y_true = 50 * [0] + 50 * [1]
    y_score = list(range(0, 100, 2)) + list(range(1, 100, 2))
    ci = roc.delong_interval(y_true, y_score, coverage=0.95)
    np.testing.assert_allclose((0.3957154, 0.6242846), ci, atol=1e-6)

  def testNoWeights(self):
    """No nonzero weights."""
    with self.assertRaises(ValueError):
      roc.delong_interval(
          self.y_true, self.y_score, sample_weight=np.zeros_like(self.y_true))

  def testBadLabels(self):
    """Outcome labels are not binary."""
    y_true = self.rng.randint(3, size=len(self.y_true))
    with self.assertRaises(ValueError):
      roc.delong_interval(y_true, self.y_score, sample_weight=self.weights)

class DeLongTestTest(absltest.TestCase):

  def setUp(self):
    super(DeLongTestTest, self).setUp()
    rng = np.random.RandomState(1987)
    num_positives = 50
    num_negatives = 100
    self.y_true = [0] * num_negatives + [1] * num_positives
    self.y_score_1 = np.concatenate((rng.randn(num_negatives),
                                     1.0 + rng.randn(num_positives)))
    self.y_score_2 = np.concatenate((rng.randn(num_negatives),
                                     2.0 + rng.randn(num_positives)))

    self.weights = rng.rand(num_positives + num_negatives) > 0.1
    self.y_ordinal = rng.randint(20, size=num_positives + num_negatives)
    self.rng = rng

  def testOneSidedPValue(self):
    # Compare to a pre-computed table from
    # https://www.medcalc.org/manual/values_of_the_normal_distribution.php
    np.testing.assert_allclose(
        0.05, roc._one_sided_p_value(1.644854), atol=1e-6)

  def testTwoSidedPValue(self):
    # Compare to a pre-computed table from
    # https://www.medcalc.org/manual/values_of_the_normal_distribution.php
    np.testing.assert_allclose(
        0.05, roc._two_sided_p_value(1.959964), atol=1e-6)

  def testMarginTrend(self):
    """Tests that a larger margin leads to a smaller p-value."""
    result1 = roc.delong_test(
        self.y_true, self.y_score_1, self.y_score_2, margin=0.01)
    result2 = roc.delong_test(
        self.y_true, self.y_score_1, self.y_score_2, margin=0.05)
    self.assertLess(result2.pvalue, result1.pvalue)

  def testCoverageTrend(self):
    """Tests that higher coverage leads to a wider interval."""
    result98 = roc.delong_test(
        self.y_true, self.y_score_1, self.y_score_2, coverage=0.98)
    result99 = roc.delong_test(
        self.y_true, self.y_score_1, self.y_score_2, coverage=0.99)
    lower99, upper99 = result99.ci
    lower98, upper98 = result98.ci
    self.assertLess(lower99, lower98)
    self.assertGreater(upper99, upper98)

  def testMatchesRPackage(self):
    """Benchmark against a reference implementation in the R language.

    Xavier Robin, Natacha Turck, Alexandre Hainard, et al. (2011)
    pROC: an open-source package for R and S+ to analyze and compare ROC curves
    BMC Bioinformatics, 7, 77. DOI: 10.1186/1471-2105-12-77.

    R code:
    ```
    > library(pROC)
    > roc.test(response = c(rep(0, 20), rep(1, 30)),
    +          predictor1 = (1:50 %% 4),
    +          predictor2 = (1:50 %% 8),
    +          method = "delong")
    Z = -0.27058646, p-value = 0.7867091
    sample estimates:
    AUC of roc1  AUC of roc2
    0.5000000000 0.5233333333
    """
    result = roc.delong_test(20 * [0] + 30 * [1],
                             np.arange(1, 51) % 4,
                             np.arange(1, 51) % 8)
    np.testing.assert_allclose(result.effect, 0.02333333333)
    np.testing.assert_allclose(result.pvalue, 0.7867091)
    np.testing.assert_allclose(result.statistic, 0.27058646)
    lower, upper = result.ci
    self.assertGreaterEqual(lower, -1.0)
    self.assertLessEqual(upper, 1.0)

class LrocTest(absltest.TestCase):

  def testMatchesSklearn(self):
    """Tests that values match the ROC curve when localization is perfect."""
    rng = np.random.RandomState(1999)
    y_true, y_score, _, sample_weight = generate_test_data(rng)

    fpr, tpr, threshes = sklearn.metrics.roc_curve(
        y_true, y_score, sample_weight=sample_weight)

    localization_success = np.ones_like(y_true)
    fpr_loc, tpr_loc, threshes_loc = roc.lroc_curve(
        y_true, y_score, localization_success, sample_weight=sample_weight)

    np.testing.assert_allclose(fpr, fpr_loc, atol=1e-4)
    np.testing.assert_allclose(tpr, tpr_loc, atol=1e-4)
    np.testing.assert_allclose(threshes, threshes_loc, atol=1e-4)

  def testNoWeights(self):
    """Tests that an error is raised when no positives have nonzero weight."""
    rng = np.random.RandomState(2000)
    y_true, y_score, _, sample_weight = generate_test_data(rng)

    localization_success = np.ones_like(y_true)
    zero_weight = np.zeros_like(sample_weight)
    with self.assertRaises(ValueError):
      roc.lroc_curve(
          y_true, y_score, localization_success, sample_weight=zero_weight)

  def testToyExample(self):
    """Tests that FPR saturates due to localization error."""
    y_true = [1, 1, 1, 1]
    y_score = [1, 2, 3, 4]
    localization_success = [1, 1, 0, 1]
    sample_weight = [1, 1, 1, 1]
    _, tpr, _ = roc.lroc_curve(y_true, y_score, localization_success,
                               sample_weight)
    np.testing.assert_allclose(tpr.max(), 0.75, atol=1e-6)

  def testNullValues(self):
    """Confirms that null localization results are disallowed on positives."""
    y_true = [1, 1, 1, 1]
    y_score = [1, 2, 3, 4]
    localization_success = [None, 1, 0, 1]
    sample_weight = [1, 1, 1, 1]

    with self.assertRaises(TypeError):
      roc.lroc_curve(y_true, y_score, localization_success, sample_weight)

class BinarizationTest(parameterized.TestCase):

  def testBinarizationFailure(self):
    with self.assertRaisesRegex(ValueError, 'integers must be in {0, 1}'):
      roc._binarize([1, 2, 3], 'integers')

    with self.assertRaises(Exception):
      roc._binarize([1, False, np.nan])

  @parameterized.named_parameters(
      ('Integers', [1, 0, 0, 1]), ('Floats', [1.0, 0.0, 0.0, 1.0]),
      ('Bools', [True, False, False, True]), ('MixedType', [True, 0, 0.0, 1]))
  def testBinarization(self, values):
    np.testing.assert_equal(roc._binarize(values), [1, 0, 0, 1])

class AverageROCTest(parameterized.TestCase):

  @parameterized.named_parameters(
      ('Identity', 0.0, [[1, 0], [0, 1]]),
      ('NinetyDegrees', np.pi / 2, [[0, -1], [1, 0]]))
  def testRotationMatrix(self, angle, expected):
    matrix = roc._rotation_matrix(angle)
    np.testing.assert_allclose(matrix, expected, atol=1e-5)

  @parameterized.parameters('sense', 'speck')
  def testBadMethodRaises(self, method):
    y_true, y_score, _, sample_weight = generate_test_data(
        np.random.RandomState(200))
    with self.assertRaisesRegex(ValueError, 'method'):
      roc.average_roc_curves(y_true, [y_score], sample_weight, method=method)

  def assertUniformSpacing(self, array):
    # Skip endpoints because they may be redundant due to padding with {0, 1}.
    self.assertLen(np.unique(np.round(np.diff(array[1:-1]), decimals=4)), 1)

  def testFprSpacing(self):
    """Averaging along vertical lines results in uniform spacing on y-axis."""
    y_true, y_scores, _, sample_weight = generate_test_data(
        np.random.RandomState(201), num_scores=5)
    fpr, unused_tpr = roc.average_roc_curves(
        y_true, y_scores, sample_weight, method='sens')
    self.assertUniformSpacing(fpr)

  def testTprSpacing(self):
    """Averaging along horizontal lines results in uniform spacing on y-axis."""
    y_true, y_scores, _, sample_weight = generate_test_data(
        np.random.RandomState(202), num_scores=5)
    unused_fpr, tpr = roc.average_roc_curves(
        y_true, y_scores, sample_weight, method='spec')
    self.assertUniformSpacing(tpr)

  def testEndpoints(self):
    y_true, y_scores, _, sample_weight = generate_test_data(
        np.random.RandomState(203), num_scores=5)
    fpr, tpr = roc.average_roc_curves(
        y_true, y_scores, sample_weight, method='diagonal')
    self.assertEqual(fpr[0], 0.0)
    self.assertEqual(fpr[-1], 1.0)
    self.assertEqual(tpr[0], 0.0)
    self.assertEqual(tpr[-1], 1.0)

  @parameterized.parameters('sens', 'spec', 'diagonal')
  def testAUCs(self, method):
    """Tests that average of AUCs is roughly the AUC of the average curve."""
    y_true, y_scores, _, sample_weight = generate_test_data(
        np.random.RandomState(203), num_scores=12, scale_factor=10)
    fpr, tpr = roc.average_roc_curves(
        y_true,
        y_scores,
        sample_weight=sample_weight,
        method=method,
        num_samples=500)
    average_of_aucs = np.mean([
        sklearn.metrics.roc_auc_score(
            y_true, y_score, sample_weight=sample_weight)
        for y_score in y_scores
    ])
    auc_of_average = sklearn.metrics.auc(fpr, tpr)
    np.testing.assert_allclose(average_of_aucs, auc_of_average, atol=1e-4)

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


text:
package com.alexstyl.specialdates.date;

import com.alexstyl.specialdates.JavaStrings;
import com.alexstyl.specialdates.Strings;
import com.alexstyl.specialdates.Optional;
import com.alexstyl.specialdates.contact.Contact;
import com.alexstyl.specialdates.contact.ContactFixture;
import com.alexstyl.specialdates.events.peopleevents.StandardEventType;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;

import static com.alexstyl.specialdates.date.Months.JANUARY;
import static org.fest.assertions.api.Assertions.assertThat;

@RunWith(MockitoJUnitRunner.class)
public class ContactEventTest {

    private static final Optional<Long> NO_DEVICE_ID = Optional.absent();
    private static final Date SOME_DATE = Date.Companion.on(1, JANUARY, 1990);
    private static final Date SOME_DATE_WITHOUT_YEAR = Date.Companion.on(1, JANUARY);
    private static final int CURRENT_YEAR = Date.Companion.getCURRENT_YEAR();

    private Contact ANY_CONTACT = ContactFixture.aContact();

    private Strings strings = new JavaStrings();

    @Test
    public void labelForNameday() {
        ContactEvent contactEvent = new ContactEvent(NO_DEVICE_ID, StandardEventType.NAMEDAY, SOME_DATE, ANY_CONTACT);
        String label = contactEvent.getLabel(SOME_DATE, strings);
        assertThat(label).isEqualTo("Nameday");
    }

    @Test
    public void labelForBirthdayWithoutYear() {
        ContactEvent contactEvent = new ContactEvent(NO_DEVICE_ID, StandardEventType.BIRTHDAY, SOME_DATE_WITHOUT_YEAR, ANY_CONTACT);
        String label = contactEvent.getLabel(SOME_DATE, strings);
        assertThat(label).isEqualTo("Birthday");
    }

    @Test
    public void labelForBirthdayWithYearAfterDate() {
        Date eventDate = Date.Companion.on(1, JANUARY, CURRENT_YEAR + 50);
        ContactEvent contactEvent = new ContactEvent(NO_DEVICE_ID, StandardEventType.BIRTHDAY, eventDate, ANY_CONTACT);
        String label = contactEvent.getLabel(SOME_DATE, strings);
        assertThat(label).isEqualTo("Birthday");
    }

    @Test
    public void labelForBirthdayWithYearOnDate() {
        Date eventDate = Date.Companion.on(1, JANUARY, CURRENT_YEAR);
        ContactEvent contactEvent = new ContactEvent(NO_DEVICE_ID, StandardEventType.BIRTHDAY, eventDate, ANY_CONTACT);
        String label = contactEvent.getLabel(SOME_DATE, strings);
        assertThat(label).isEqualTo("Birthday");
    }

    @Test
    public void labelForBirthdayWithYearBeforeDate() {
        Date eventDate = Date.Companion.on(1, JANUARY, CURRENT_YEAR - 10);

        ContactEvent contactEvent = new ContactEvent(NO_DEVICE_ID, StandardEventType.BIRTHDAY, eventDate, ANY_CONTACT);
        String label = contactEvent.getLabel(Date.Companion.on(1, JANUARY, Date.Companion.today().getYear()), strings);
        assertThat(label).isEqualTo("Turns 10");
    }

}

redpajama_set_name: RedPajamaGithub


text:
layout:     post
title:      "Carrie and Lowell: Revisited"
subtitle:   "Valentine, spurn my sorrow."
date:       2015-06-19
author:     "Brennan"
header-img: "img/carrie2.png"
---

Sufjan Stevens is a sad man who has—reportedly—whispered praise to his banjos at his concerts.

In celebrating the month since our first post, I decided to take a second glace at the first album that Dawson decided to review, one that he didn't actually like. Which was odd since *Carrie and Lowell* is widely considered one of Sufjan's best record so far. (Or maybe taking a purposefully controversial stance is intelligent for clickbait? I don't actually know, I'm not an expert in audience dick-sucking.)

At first, I mostly agreed with Dawson's review. But I confess that was mainly because I didn't *try* to figure out Sufjan. I didn't attempt to read into the lyrics, or realize that the album wasn't just a portrait of experiemental nhilistic elder photography1. But then I did, and then I cried. I sincerely cried, reading up on *Genius* everything that I plainly missed.2

Ephinany can be brutal, like a sudden stomach ulcer or a crowded broken elevator. Our *eurekras* shroud themselves, they sometimes tease the edges of our minds.

Something hit home hard for me within this album, and that's the actual reason I decided to write this review.

### The Strongest Clan

It is the sentimentalist in me, I cannot help but feel that the synecdoche of family within art. It is the most powerful way to represent our humanity. More often than not, we cannot relate to the nuclear family, for most of us there is no feeling of empathy when we view parent and child in merry discussion at the dinner-table. This is not, in spite of popular belief, what family is.

What then, is family? Family is where we find solace and cathatrisis, it's the perseverance of those we are forced to love and choose to hate. Family is those who are close enough to us to shape us as people. Family is a mother, bipolar and schizophrenic, and suffering from drug addiction and substance abuse.

> When I was three, three maybe four,

> She left us at that video store.

> Be my rest, be my fantasy.

It is difficult to come anywhere close to imagining how Sufjan actually feels, here; to have your pre-determined caretaker abandon you at such a young age. To have a parent that is so irrepairably difficult, that's a burden.

### Fireworks and Forests

And yet, in this album is not anger. In this album is not bitterness or betrayal. Instead we here pleas of forgiveness and attempts at understanding.

The climax of this record is *Fourth of July*, where Stevens has a discussion with his passed mother. It's where my player revolves to everytime I attempt to listen to the album in full.

There's the seemingly blunt mantra, depicting how Carrie retells Sufjan that he needs to learn about the fleeting and fragile nature of the world by comparing it to the massive devistation of Tillamook, as well as the ephemeral beauty of the fireworks on Independence Day. In addition to this, it is difficult to say the last line doesn't sound like the bleeding pessimism of a defeated woman:

> Tell me what did you learn from the Tillamook burn?

> Or the Fourth of July?

> We're all gonna die.

But, ultimately, this isn't what *gets* you. You don't feel a chill down your spine at the futile hopelessness of Carrie's lament. You instead bawl hard at the contrast, at how heartwarming she is when speaking to him.

>My little hawk, why do you cry?

The maudlin is so powerful—how deep the corny pet-names will carve into you. You cannot help but buy into the image of a deathbed filled with a broken past dressed in a pure white dress and smiling.

### Verdict

This, to me, is the most spectacular thing about *Carrie and Lowell*. Sufjan somehow takes in such a horrific aspect of his life, and delicately lays out it's most beautiful aspects and then appreciates them.

Having terrible parents is perhaps one of the most stress-inducing and heartbreaking situations someone can be placed into. It can sometimes feel as though loving them is a choice and hating them isn't, but the opposite is true.

For such a situation, Stevens goes on throughout this album searching for the remedy. His answer is to forgive and love them, regardless.

This is the ephinany that comes through, since you wouldn't be around if it weren't for them, would you?

#### Notes

1: I think it's a problem to instantly buy into the concept that an album is 'wallpaper' music, because it completely changes your listening experiencing. Stevens is soothing and soft, his strings are always well places and never danceable. This can create the illusion that nothing exciting is being summoned. Within this album, you couldn't be further from the truth

2: I contemplate the trickiness and hypocrisy of using other people's opinions and interpretations to influence how one feels about something. Is it truly an ephinany if you need somebody to spoonfeed it to you? How shallow does this make me?

(*Listen to the album [**here**](https://www.youtube.com/watch?v=iGeeboRPZ4s)*)


text:
extern "C" {

    // =-=-=-=-=-=-=-
    // 1. Write a standard issue microservice
    int irods_hello( msParam_t* _out, ruleExecInfo_t* _rei ) {
        std::string my_str = "Hello World!";
        fillStrInMsParam( _out, my_str.c_str() );

        return 0;
    }

    // =-=-=-=-=-=-=-
    // 2.  Create the plugin factory function which will return a microservice
    //     table entry
    irods::ms_table_entry*  plugin_factory() {
        // =-=-=-=-=-=-=-
        // 3. allocate a microservice plugin which takes the number of function
        //    params as a parameter to the constructor
        irods::ms_table_entry* msvc = new irods::ms_table_entry( 1 );

        // =-=-=-=-=-=-=-
        // 4. add the microservice function as an operation to the plugin
        //    the first param is the name / key of the operation, the second
        //    is the name of the function which will be the microservice
        msvc->add_operation( "irods_hello", "irods_hello" );

        // =-=-=-=-=-=-=-
        // 5. return the newly created microservice plugin
        return msvc;
    }

}; // extern "C"


text:
package org.jboss.as.quickstarts.greeter.web;

import javax.enterprise.context.RequestScoped;
import javax.enterprise.inject.Produces;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;

import org.jboss.as.quickstarts.greeter.domain.User;
import org.jboss.as.quickstarts.greeter.domain.UserDao;

@Named
@RequestScoped
public class CreateController {

   @Inject
   private FacesContext facesContext;

   @Inject
   private UserDao userDao;

   @Named
   @Produces
   @RequestScoped
   private User newUser = new User();

   public void create() {
      try {
         userDao.createUser(newUser);
         facesContext.addMessage(null, new FacesMessage("A new user with id " + newUser.getId() + " has been created successfully"));
      } catch (Exception e) {
         facesContext.addMessage(null, new FacesMessage("An error has occured while creating the user (see log for details)"));
      }
   }
}


text:
#include "fileAttrChanged.h"
#include "messages/fuse/fileAttr.h"

#include "messages.pb.h"

#include <sstream>

namespace one {
namespace client {
namespace events {

FileAttrChanged::FileAttrChanged(const ProtocolMessage &msg)
    : m_fileAttr{std::make_unique<FileAttr>(msg.file_attr())}
    , m_aggregationKey{m_fileAttr->uuid().toStdString()}
{
}

StreamKey FileAttrChanged::streamKey() const
{
    return StreamKey::FILE_ATTR_CHANGED;
}

const AggregationKey &FileAttrChanged::aggregationKey() const
{
    return m_aggregationKey;
}

const FileAttr &FileAttrChanged::fileAttr() const { return *m_fileAttr; }

std::string FileAttrChanged::toString() const
{
    std::stringstream stream;
    stream << "type: 'FileAttrChanged', file attr: " << m_fileAttr->toString();
    return stream.str();
}

void FileAttrChanged::aggregate(EventPtr<FileAttrChanged> event)
{
    m_fileAttr = std::move(event->m_fileAttr);
}

} // namespace events
} // namespace client
} // namespace one


text:
#ifndef FATAL_INCLUDE_fatal_type_operation_h
#define FATAL_INCLUDE_fatal_type_operation_h

#include <fatal/type/transform.h>

namespace fatal {
namespace detail {
namespace operation_impl {

template <template <typename...> class, typename, typename>
struct cartesian_product;

template <template <typename...> class, typename...> struct flatten;

template <typename T, template <typename, T...> class, typename U, U>
struct to_sequence;

template <typename T, typename TChar, TChar, TChar...> struct parse_sequence;

template <typename, typename> struct from_sequence;

} // namespace operation_impl {
} // namespace detail {

/**
 * Computes the cartesian product between two lists.
 *
 * Parameters:
 *
 * Example:
 *
 *  template <typename, typename> struct pair {};
 *  template <typename...> struct list {};
 *
 *  // yields `list<
 *  //   pair<int, double>,
 *  //   pair<int, bool>,
 *  //   pair<void, double>,
 *  //   pair<void, bool>
 *  // >
 *  using result = cartesian_product<list, pair>::apply<
 *    list<int, void>,
 *    list<double, bool>,
 *  >;
 *
 * @author: Marcelo Juchem <marcelo@fb.com>
 */
template <
  template <typename...> class TList,
  template <typename...> class TPair
>
struct cartesian_product {
  template <typename TLHS, typename TRHS>
  using apply = typename detail::operation_impl::cartesian_product<
    TPair, TLHS, TRHS
  >::template apply<TList>;
};

/**
  * Flattens the arguments of a specific template into a topmost list.
  *
  * Only a single level will be flattened.
  *
  * Parameters:
  *
  *  - TList: the template for the topmost list to be returned
  *  - TWhich: which template to flatten
  *  - Args...: the list of types to be flattened
  *
  * Example:
  *
  *  template <typename...> struct list {};
  *
  *  // yields `list<
  *  //   int,
  *  //   double,
  *  //   float,
  *  //   list<short>,
  *  //   bool
  *  // >`
  *  using result1 = fatal::flatten<list, list>::apply<
  *    int,
  *    list<
  *      double,
  *      float,
  *      list<short>
  *    >,
  *    bool
  *  >;
  *
  *  // yields `std::tuple<
  *  //   int,
  *  //   double,
  *  //   float,
  *  //   list<short>,
  *  //   bool
  *  // >`
  *  using result2 = list::flatten<std::tuple, list>::apply<
  *    int,
  *    list<
  *      double,
  *      float,
  *      list<short>
  *    >,
  *    bool
  *  >;
  *
  * @author: Marcelo Juchem <marcelo@fb.com>
  */
template <
  template <typename...> class TList,
  template <typename...> class TWhich
>
struct flatten {
  template <typename... Args>
  using apply = typename detail::operation_impl::flatten<TWhich, Args...>
  ::template apply<TList>;
};

/////////////////
// to_sequence //
/////////////////

/**
 * Converts an integral value to its string representation,
 * as a sequence of characters.
 *
 * Parameters:
 *
 *  - T: the type of the integral value
 *  - Value: the value to be converted
 *  - TChar: the type of the characters in the sequence. Defaults to `char`.
 *
 * Example:
 *
 *  // yields `std::integer_sequence<char, '4', '2'>`
 *  using result1 = to_sequence<std::size_t, std::integer_sequence, 42>;
 *
 *  // yields `std::integer_sequence<wchar_t, L'-', L'5', L'6'>`
 *  using result2 = to_sequence<int, -56, std::integer_sequence, wchar_t>;
 *
 * @author: Marcelo Juchem <marcelo@fb.com>
 */
template <
  typename T, T Value,
  template <typename U, U...> class TSequence,
  typename TChar = char
>
using to_sequence = typename detail::operation_impl::to_sequence<
  TChar, TSequence, T, Value
>::type;

////////////////////
// parse_sequence //
////////////////////

/**
 * Provides mechanisms to parse the integral value of type `T`
 * represented by a sequence of characters.
 *
 * Parameters:
 *
 *  - T: the type of the integral value that will be parsed.
 *
 * @author: Marcelo Juchem <marcelo@fb.com>
 */
template <typename T>
struct parse_sequence {
  /**
   * Provides mechanisms to parse the integral value represented
   * by a sequence of characters of type `TChar`.
   *
   * Parameters:
   *
   *  - TChar: the type of the characters in the sequence to be parsed.
   *
   * @author: Marcelo Juchem <marcelo@fb.com>
   */
  template <typename TChar>
  struct bind {
    /**
     * Parses the integral value represented by the
     * given sequence of characters.
     *
     * Parameters:
     *
     *  - Chars: the sequence of characters to be parsed.
     *
     * Example:
     *
     *  // yields `std::integral_constant<int, -56>`
     *  using result = parse_sequence<int>::bind<char>::apply<'-', '5', '6'>;
     *
     * @author: Marcelo Juchem <marcelo@fb.com>
     */
    template <TChar... Chars>
    using apply = typename detail::operation_impl::parse_sequence<
      T, TChar, Chars...
    >::type;
  };

  /**
   * Parses the integral value represented by the
   * given sequence of `characters.
   *
   * Parameters:
   *
   *  - TChar: the type of the characters in the sequence.
   *  - Chars: the sequence of characters to be parsed.
   *
   * Example:
   *
   *  // yields `std::integral_constant<int, -56>`
   *  using result = parse_sequence<int>::bind<char>::apply<'-', '5', '6'>;
   *
   * @author: Marcelo Juchem <marcelo@fb.com>
   */
  template <typename TChar, TChar... Chars>
  using apply = typename bind<TChar>::template apply<Chars...>;

  /**
   * Parses the given sequence as an integral value.
   *
   * Parameters:
   *
   *  - TSequence: the sequence to be parsed.
   *
   * Example:
   *
   *  using str = std::integer_sequence<char, '-', '5', '6'>;
   *
   *  // yields `std::integral_constant<int, -56>`
   *  using result = parse_sequence<int>::from<str>;
   *
   * @author: Marcelo Juchem <marcelo@fb.com>
   */
  template <typename TSequence>
  using from = typename detail::operation_impl::from_sequence<
    T, TSequence
  >::type;
};

////////////////////////////
// IMPLEMENTATION DETAILS //
////////////////////////////

namespace detail {
namespace operation_impl {

template <typename...> struct list;

///////////////////////
// cartesian_product //
///////////////////////

template <
  template <typename...> class TPair,
  template <typename...> class T,
  typename... TArgs,
  template <typename...> class U,
  typename... UArgs
>
struct cartesian_product<TPair, T<TArgs...>, U<UArgs...>> {
template <typename V>
  using impl = list<TPair<V, UArgs>...>;

  template <template <typename...> class TList>
  using apply = typename fatal::flatten<TList, list>
    ::template apply<impl<TArgs>...>;
};

/////////////
// flatten //
/////////////

template <
  template <typename...> class T,
  typename... Args,
  typename... UArgs
>
struct flatten<T, T<Args...>, UArgs...> {
  template <template <typename...> class U, typename... VArgs>
  using apply = typename flatten<T, UArgs...>
    ::template apply<U, VArgs..., Args...>;
};

template <template <typename...> class T, typename THead, typename... Args>
struct flatten<T, THead, Args...> {
  template <template <typename...> class U, typename... VArgs>
  using apply = typename flatten<T, Args...>::template apply<
    U, VArgs..., THead
  >;
};

template <template <typename...> class T>
struct flatten<T> {
  template <template <typename...> class U, typename... Args>
  using apply = U<Args...>;
};

/////////////////
// to_sequence //
/////////////////

template <
  bool Negative, typename TChar, template <typename, TChar...> class TSequence,
  typename T, T Value, bool Done = (Value == 0)
>
struct to_sequence_impl {
  template <TChar... Suffix>
  using apply = typename to_sequence_impl<
    Negative, TChar, TSequence, T, Value / 10
  >::template apply<
    static_cast<TChar>("9876543210123456789"[(Value % 10) + 9]), Suffix...
  >;
};

template <
  bool Negative, typename TChar, template <typename, TChar...> class TSequence,
  typename T, T Value
>
struct to_sequence_impl<Negative, TChar, TSequence, T, Value, true> {
  template <TChar... Chars>
  using apply = typename std::conditional<
    Negative,
    TSequence<TChar, static_cast<TChar>('-'), Chars...>,
    TSequence<TChar, Chars...>
  >::type;
};

template <
  typename TChar, template <typename, TChar...> class TSequence,
  typename T, T Value
>
struct to_sequence {
  using type = typename std::conditional<
    Value == 0,
    TSequence<TChar, static_cast<TChar>('0')>,
    typename to_sequence_impl<
      (Value < 0), TChar, TSequence, T, Value
    >::template apply<>
  >::type;
};

////////////////////
// parse_sequence //
////////////////////

template <typename T, typename TChar, TChar Char>
struct parse_type_char {
  static_assert(
    Char == static_cast<TChar>('0')
    || Char == static_cast<TChar>('1')
    || Char == static_cast<TChar>('2')
    || Char == static_cast<TChar>('3')
    || Char == static_cast<TChar>('4')
    || Char == static_cast<TChar>('5')
    || Char == static_cast<TChar>('6')
    || Char == static_cast<TChar>('7')
    || Char == static_cast<TChar>('8')
    || Char == static_cast<TChar>('9'),
    "character is not a valid digit"
  );

  using type = std::integral_constant<
    T,
    Char == static_cast<TChar>('0') ? static_cast<T>(0)
    : Char == static_cast<TChar>('1') ? static_cast<T>(1)
    : Char == static_cast<TChar>('2') ? static_cast<T>(2)
    : Char == static_cast<TChar>('3') ? static_cast<T>(3)
    : Char == static_cast<TChar>('4') ? static_cast<T>(4)
    : Char == static_cast<TChar>('5') ? static_cast<T>(5)
    : Char == static_cast<TChar>('6') ? static_cast<T>(6)
    : Char == static_cast<TChar>('7') ? static_cast<T>(7)
    : Char == static_cast<TChar>('8') ? static_cast<T>(8)
    : Char == static_cast<TChar>('9') ? static_cast<T>(9)
    : 10
  >;

  static_assert(
    type::value >= 0 && type::value <= 9,
    "character is not a valid digit"
  );
};

template <typename T>
struct parse_sequence_add_tail {
  template <T Value, T Next>
  using positive = std::integral_constant<T, Value + Next>;

  template <T Value, T Next>
  using negative = std::integral_constant<T, Value - Next>;
};

template <typename T, T, template <T, T> class, typename TChar, TChar...>
struct parse_sequence_recursion;

template <
  typename T, T Value, template <T, T> class TAddTail,
  typename TChar, TChar Head, TChar... Tail
>
struct parse_sequence_recursion<T, Value, TAddTail, TChar, Head, Tail...> {
  using type = typename parse_sequence_recursion<
    T,
    TAddTail<Value * 10, parse_type_char<T, TChar, Head>::type::value>::value,
    TAddTail, TChar, Tail...
  >::type;
};

template <typename T, T Value, template <T, T> class TAddTail, typename TChar>
struct parse_sequence_recursion<T, Value, TAddTail, TChar> {
  using type = std::integral_constant<T, Value>;
};

template <bool, typename T, typename TChar, TChar Head, TChar... Tail>
struct parse_sequence_selector {
  using head = typename parse_type_char<T, TChar, Head>::type;

  static_assert(
    sizeof...(Tail) == 0 || head::value > 0,
    "integral can't have a leading zero"
  );

  using type = typename parse_sequence_recursion<
    T, head::value,
    parse_sequence_add_tail<T>::template positive,
    TChar, Tail...
  >::type;
};

template <typename T, typename TChar, TChar Sign, TChar Head, TChar... Tail>
struct parse_sequence_selector<true, T, TChar, Sign, Head, Tail...> {
  static_assert(Sign == static_cast<TChar>('-'), "unrecognized sign");

  using head = typename parse_type_char<T, TChar, Head>::type;

  static_assert(head::value > 0, "negative integral can't have a leading zero");

  using type = typename parse_sequence_recursion<
    T, -head::value,
    parse_sequence_add_tail<T>::template negative,
    TChar, Tail...
  >::type;
};

template <typename T, typename TChar, TChar Head, TChar... Tail>
struct parse_sequence {
  using is_sign = std::integral_constant<bool, Head == static_cast<TChar>('-')>;

  static_assert(
    std::is_signed<T>::value || !is_sign::value,
    "unsigned integral can't have a sign"
  );

  using type = typename parse_sequence_selector<
    is_sign::value, T, TChar, Head, Tail...
  >::type;
};

///////////////////
// from_sequence //
///////////////////

template <
  typename T,
  typename TChar,
  template <typename, TChar...> class U,
  TChar... Chars
>
struct from_sequence<T, U<TChar, Chars...>> {
  using type = typename parse_sequence<T, TChar, Chars...>::type;
};

} // namespace operation_impl {
} // namespace detail {
} // namespace fatal {

#endif // FATAL_INCLUDE_fatal_type_operation_h


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

    <artifactId>vertx-guice-examples</artifactId>
    <packaging>pom</packaging>

    <parent>
        <artifactId>vertx-guice-parent</artifactId>
        <groupId>com.englishtown.vertx</groupId>
        <version>2.4.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <modules>
        <module>vertx-guice-simple</module>
        <module>vertx-guice-config</module>
    </modules>

    <dependencies>
        <dependency>
            <groupId>com.englishtown.vertx</groupId>
            <artifactId>vertx-guice</artifactId>
            <version>${project.version}</version>
        </dependency>
        <dependency>
            <groupId>io.vertx</groupId>
            <artifactId>vertx-core</artifactId>
            <version>${vertx.version}</version>
            <type>test-jar</type>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <artifactId>maven-deploy-plugin</artifactId>
                <configuration>
                    <skip>true</skip>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>


text:
require 'epa/client'
require 'epa/client/connection'
require 'epa/client/request'
require 'epa/client/rad_info'
require 'epa/client/pcs'

module EPA
  class Client
    include EPA::Client::Connection
    include EPA::Client::Request
    #include EPA::Client::RadInfo

  end
end


text:
package io.spine.server.aggregate.given.importado;

import io.spine.server.aggregate.Aggregate;
import io.spine.server.aggregate.Apply;
import io.spine.server.aggregate.given.importado.command.Move;
import io.spine.server.aggregate.given.importado.event.Moved;
import io.spine.server.command.Assign;

import static io.spine.util.Exceptions.newIllegalArgumentException;

/**
 * An object moving in a 2-D space.
 */
final class Dot extends Aggregate<ObjectId, Point, Point.Builder> {

    @Assign
    Moved on(Move command) {
        return Moved.newBuilder()
                .setObject(command.getObject())
                .setDirection(command.getDirection())
                .setCurrentPosition(move(id(), state(), command.getDirection()))
                .build();
    }

    @Apply(allowImport = true)
    private void event(Moved event) {
        var newPosition = move(id(), state(), event.getDirection());

        builder().setId(event.getObject())
                 .setX(newPosition.getX())
                 .setY(newPosition.getY());
    }

    private static Point move(ObjectId id, Point p, Direction direction) {
        var result = Point.newBuilder()
                .setId(id)
                .setX(p.getX())
                .setY(p.getY());
        switch (direction) {
            case NORTH:
                result.setY(p.getY() + 1);
                break;
            case EAST:
                result.setX(p.getX() + 1);
                break;
            case SOUTH:
                result.setY(p.getY() - 1);
                break;
            case WEST:
                result.setX(p.getX() - 1);
                break;
            default:
                throw newIllegalArgumentException("Invalid direction passed `%s`.", direction);
        }
        return result.build();
    }
}


text:
title: "caffe"
description: "tools"
layout: post
date: 2017-12-05 03:23:44 +0800
categories: [tools]
tags: [tools, ml, github]
comments: yes
---

https://www.jianshu.com/p/cc16e2977e27

http://nbviewer.jupyter.org/github/joyofdata/joyofdata-articles/blob/master/deeplearning-with-caffe/Neural-Networks-with-Caffe-on-the-GPU.ipynb

http://blog.csdn.net/whiteinblue/article/details/45330801

刘备
"/home/ubuntu/caffe/build/tools/caffe","train","--solver=config.prototxt"


text:
<?php

class Ess_M2ePro_Block_Adminhtml_Amazon_Listing_View_ModeSwitcher
    extends Ess_M2ePro_Block_Adminhtml_Listing_View_ModeSwitcher_Abstract
{
    //########################################

    public function __construct()
    {
        parent::__construct();

        // Initialization block
        // ---------------------------------------
        $this->setId('amazonListingViewModeSwitcher');
        // ---------------------------------------

        $this->setData('component_nick', 'amazon');
        $this->setData('component_label', 'Amazon');
    }

    protected function getMenuItems()
    {
        return array(
            array(
                'value' => Ess_M2ePro_Block_Adminhtml_Amazon_Listing_View::VIEW_MODE_AMAZON,
                'label' => Mage::helper('M2ePro')->__($this->getComponentLabel())
            ),
            array(
                'value' => Ess_M2ePro_Block_Adminhtml_Amazon_Listing_View::VIEW_MODE_SETTINGS,
                'label' => Mage::helper('M2ePro')->__('Settings')
            ),
            array(
                'value' => Ess_M2ePro_Block_Adminhtml_Amazon_Listing_View::VIEW_MODE_SELLERCENTRAL,
                'label' => Mage::helper('M2ePro')->__('Seller Сentral')
            ),
            array(
                'value' => Ess_M2ePro_Block_Adminhtml_Amazon_Listing_View::VIEW_MODE_MAGENTO,
                'label' => Mage::helper('M2ePro')->__('Magento')
            )
        );
    }

    //########################################
}


text:
package org.apache.solr.cluster.placement.impl;

import java.util.Set;
import org.apache.solr.cluster.Node;
import org.apache.solr.cluster.Replica;
import org.apache.solr.cluster.SolrCollection;
import org.apache.solr.cluster.placement.PlacementPlan;
import org.apache.solr.cluster.placement.PlacementPlanFactory;
import org.apache.solr.cluster.placement.PlacementRequest;
import org.apache.solr.cluster.placement.ReplicaPlacement;

/** Simple implementation of {@link PlacementPlanFactory}. */
public class PlacementPlanFactoryImpl implements PlacementPlanFactory {
  @Override
  public PlacementPlan createPlacementPlan(
      PlacementRequest request, Set<ReplicaPlacement> replicaPlacements) {
    return new PlacementPlanImpl(request, replicaPlacements);
  }

  @Override
  public ReplicaPlacement createReplicaPlacement(
      SolrCollection solrCollection, String shardName, Node node, Replica.ReplicaType replicaType) {
    return new ReplicaPlacementImpl(solrCollection, shardName, node, replicaType);
  }
}


text:
## Installation instructions

1. unzip 1.5.10.7z to your plugin folder
2. put the following code line as first line in your application level python code

`import cast_upgrade_1_5_10 # @UnusedImport`

## What's new

### Features

* load_violations on objects by sub-query loading
* postgresql get_size on schema
* faster table reflection (by embedding statically the schema)
* managment : lazy loading
* ObjectQuery :
  * in_projects() : restrict the projects to search into
  * in_set(<setid>/<set name>)
  * not_in_set()
  * is_web_service_call()
  * not_has_type(..)
  * not_in(query)
  * count() : return the number of objects
* Project.objects()
* Application.get_analyzer_technologies()
* LinkQuery : finer grain on DLM links queries
  * is_to_be_reviewed()
  * is_ignored()
  * is_not_ignored()
  * is_validated()
  * count() : return the number of links

### Bug corrections

* corrects issue on save_violation
* better ms connection support
* save_property : also clean external objects (caused bug on html5, ...)
* several calls to update csv on sql server crash
* sqlserver issue on raw saving
* log level based on CMS option : corrects a bug on take a snapshot
* exception during CastSchem.get_events()
* ObjectQuery.is_external() was giving objects external to one project but internal for others
* postgresql cache too cachy

See full doc http://cast-projects.github.io/Extension-SDK/doc/application_level.html


text: Rails.application.config.session_store :cookie_store, key: '_ComediaMundial_session'


text:
using System;
using System.IO;
using OSGeo.GDAL;

namespace MngImg
{
    public class KMLBuildOptions
    {
        private Action<string> _showStatus;

        // int Min, int Max, int Step, int id
        private Action<int, int, int, int> _progressed;

        public int TileSize { get; private set; }

        public string OutPath { get; private set; }

        public int[] BandsOrder { get; private set; }
        public bool HaveBandsOrder { get { return BandsOrder != null && BandsOrder.Length > 0; } }

        public int StretchStardDesvNum { get; private set; }
        public bool HaveStretchStardDesv { get { return StretchStardDesvNum > 0; } }

        public int NullDataValue { get; private set; }
        public bool HaveNullData { get { return NullDataValue >= 0; } }

        public byte AlphaBandValue { get; private set; }
        public bool HaveAlphaBand { get { return AlphaBandValue >= 0; } }

        public KMLBuildOptions(string outPath, int tileSize = 256, int[] bandsOrder = null, int stretchStardDesv = int.MinValue, int nullDataValue = int.MinValue, byte alphaBandValue = byte.MinValue, Action<string> funcST = null, Action<int, int, int, int> funcSPB = null)
        {
            if (!Directory.Exists(outPath))
                Directory.CreateDirectory(outPath);
            OutPath = outPath;
            _showStatus = funcST;
            _progressed = funcSPB;
            TileSize = tileSize;
            BandsOrder = bandsOrder;
            StretchStardDesvNum = stretchStardDesv;
            NullDataValue = nullDataValue;
            AlphaBandValue = alphaBandValue;
        }

        public bool IsOriginal()
        {
            return !HaveBandsOrder && !HaveStretchStardDesv && !HaveNullData && !HaveAlphaBand;
        }

        public void ShowStatus(string message)
        {
            if (_showStatus != null)
                _showStatus(message);
        }

        public void Progressed(int min, int max, int step, int id)
        {
            if (_progressed != null)
                _progressed(min, max, step, id);
        }
    }

    public class KMLBuilder
    {
        private Dataset _ds;

        #region Public Methods

        public KMLBuilder(string filename)
        {
            _ds = Gdal.Open(filename, Access.GA_Update);
        }

        public void Write(KMLBuildOptions options)
        {
            int nLevel = GlobalMercator.GetTotalLevel(options.TileSize, _ds.RasterXSize, _ds.RasterYSize);
            _SetOverviewSameLevel(nLevel);

            // Original: idOverview = -1 and Level is Max
            _WriteTiles(nLevel, -1, options);
            // int Level, int idOverview, int[] Order, int SizeTile, string sNameDirTile

            // Next Levels
            for (int i = 0; i < nLevel; i++)
                _WriteTiles(nLevel - (i + 1), i, options);
        }

        #endregion Public Methods

        #region Private Methods

        private void _SetOverviewSameLevel(int nLevel)
        {
            if (_ds.GetRasterBand(1).GetOverviewCount() < 1)
            {
                int[] aryOverview = new int[nLevel];
                for (int i = 0; i < nLevel; i++)
                    aryOverview[i] = (int)Math.Pow(2.0, (double)(i + 1));

                // Example:
                // Level = 3
                // aryOverview = { 2, 4, 8 }
                // Common resolutions are 2 4 8 16, meaning an overview at 1/2, 1/4, 1/8, and 1/16 resolution are created.
                _ds.BuildOverviews("NEAREST", aryOverview);
            }
            else
                if (_ds.GetRasterBand(1).GetOverviewCount() != nLevel)
                {
                    string sMsg = string.Format(
                        "{0}/{1}: Number overview({2}) in image is different for Level({3})",
                        this.ToString(), "_SetOverviewSameLevel", _ds.GetRasterBand(1).GetOverviewCount(), nLevel);

                    throw (new Exception(sMsg));
                }
        }

        private void _WriteTiles(int Level, int idOverview, KMLBuildOptions options)
        {
            int nTileX = 0, nTileY = 0, nPixelRemTileX, nPixelRemTileY;

            // nTile          -> number of tile with value
            // nPixelRemTileX -> Remainder pixel before nTile

            if (idOverview == -1) // Original
            {
                nTileX = Math.DivRem(_ds.RasterXSize, options.TileSize, out nPixelRemTileX);
                nTileY = Math.DivRem(_ds.RasterYSize, options.TileSize, out nPixelRemTileY);
            }
            else
            {
                nTileX = Math.DivRem(_ds.GetRasterBand(1).GetOverview(idOverview).XSize, options.TileSize, out nPixelRemTileX);
                nTileY = Math.DivRem(_ds.GetRasterBand(1).GetOverview(idOverview).YSize, options.TileSize, out nPixelRemTileY);
            }

            options.ShowStatus(string.Format("Level {0} TileX 0->{1} TileY 0->{2} ...", Level, nTileX, nTileY));
            options.Progressed(0, nTileX, 1, 0);

            // Pixels with full values in TileSize
            for (int idGridX = 0; idGridX < nTileX; idGridX++)
            {
                options.Progressed(0, 0, 0, idGridX);
                for (int idGridY = 0; idGridY < nTileY; idGridY++)
                    WriteTileEach(Level, idOverview, idGridX, idGridY, options.TileSize, options.TileSize, options);
            }

            // Pixels without full values in TileSize
            if (nPixelRemTileX > 0)
            {
                options.ShowStatus(string.Format("Level {0} Remainder TileX 0->{1} ...", Level, nTileY));
                options.Progressed(0, nTileY, 1, 0);
                for (int idGridY = 0; idGridY < nTileY; idGridY++)
                {
                    options.Progressed(0, 0, 0, idGridY);
                    WriteTileEach(Level, idOverview, nTileX, idGridY, nPixelRemTileX, options.TileSize, options);
                }
            }

            if (nPixelRemTileY > 0)
            {
                options.ShowStatus(string.Format("Level {0} Remainder TileY 0->{1} ...", Level, nTileX));
                options.Progressed(0, nTileX, 1, 0);
                for (int idGridX = 0; idGridX < nTileX; idGridX++)
                {
                    options.Progressed(0, 0, 0, idGridX);
                    WriteTileEach(Level, idOverview, idGridX, nTileY, options.TileSize, nPixelRemTileY, options);
                }
            }

            if (nPixelRemTileX > 0 && nPixelRemTileY > 0)
            {
                options.ShowStatus("Remainder TileX & TileY ...");
                WriteTileEach(Level, idOverview, nTileX, nTileY, nPixelRemTileX, nPixelRemTileY, options);
            }
        }

        private void WriteTileEach(int Level, int idOverview, int idGridX, int idGridY, int nPixelX, int nPixelY, KMLBuildOptions options)
        {
            int xoff = idGridX * options.TileSize;
            int yoff = idGridY * options.TileSize;

            Dataset dsOut = CreatePngDataset(idOverview, xoff, yoff, options.TileSize, options.HaveAlphaBand);

            WriteTileEachDS(idOverview, ref dsOut, xoff, yoff, nPixelX, nPixelY, options);

            if (options.HaveNullData)
                _SetNullDataImage(dsOut, options.NullDataValue);

            // Tiles: sPath\$[level]_$[y]_$[x].png
            string sPathNameTile = string.Format("{0}\\{1}_{2}_{3}.png", options.OutPath, Level, idGridX, idGridY);
            _DatasetPng2File(dsOut, sPathNameTile);

            dsOut.FlushCache();
            dsOut.Dispose();
        }

        private Dataset CreatePngDataset(int idOverview, int xoff, int yoff, int tileSize, bool hasAlpha)
        {
            string[] aryOption = { "" };
            OSGeo.GDAL.Driver drv = Gdal.GetDriverByName("MEM");

            int nBand = hasAlpha ? _ds.RasterCount + 1 : _ds.RasterCount;
            Dataset dsReturn = drv.Create("filememory", tileSize, tileSize, nBand, _ds.GetRasterBand(1).DataType, aryOption);

            dsReturn.SetProjection(_ds.GetProjection());

            double[] _gt = new double[6];
            _ds.GetGeoTransform(_gt);

            if (idOverview != -1)
            {
                _gt[1] *= Math.Pow(2, (double)(idOverview + 1));
                _gt[5] *= Math.Pow(2, (double)(idOverview + 1));
            }

            _gt[0] += xoff * _gt[1]; // X origin
            _gt[3] += yoff * _gt[5]; // Y origin
            dsReturn.SetGeoTransform(_gt);

            return dsReturn;
        }

        private void WriteTileEachDS(int idOverview, ref Dataset dsOut, int xoff, int yoff, int xsize, int ysize, KMLBuildOptions options)
        {
            byte[] pixelsTile = new byte[options.TileSize * options.TileSize];

            byte[] pixelsAlpha = new byte[0];
            if (options.HaveAlphaBand)
            {
                pixelsAlpha = null;
                pixelsAlpha = new byte[options.TileSize * options.TileSize];
            }

            int idOrder = 0;

            for (int id = 0; id < _ds.RasterCount; id++)
            {
                Band bdOut = dsOut.GetRasterBand(id + 1);

                idOrder = options.HaveBandsOrder ? options.BandsOrder[id] : id + 1;

                Band bdIn = (idOverview != -1) ? _ds.GetRasterBand(idOrder).GetOverview(idOverview) : _ds.GetRasterBand(idOrder);

                if (xsize == options.TileSize)
                {
                    bdIn.ReadRaster(xoff, yoff, xsize, ysize, pixelsTile, xsize, ysize, 0, 0);
                    if (options.HaveStretchStardDesv)
                        ImageProcessing.SetStretchStardDevi(bdIn, ref pixelsTile, options.StretchStardDesvNum);
                }
                else
                {
                    byte[] pixels = new byte[xsize * ysize];
                    bdIn.ReadRaster(xoff, yoff, xsize, ysize, pixels, xsize, ysize, 0, 0);
                    if (options.HaveStretchStardDesv)
                        ImageProcessing.SetStretchStardDevi(bdIn, ref pixels, options.StretchStardDesvNum);

                    for (int iy = 0; iy < ysize; iy++)
                        System.Buffer.BlockCopy(pixels, iy * xsize, pixelsTile, iy * options.TileSize, xsize);
                }
                bdOut.WriteRaster(0, 0, options.TileSize, options.TileSize, pixelsTile, options.TileSize, options.TileSize, 0, 0);

                if (options.HaveAlphaBand)
                    ImageProcessing.PopulateAlphaPixels(ref pixelsTile, ref pixelsAlpha);

                bdOut.FlushCache(); bdIn.FlushCache();
                bdIn.Dispose(); bdOut.Dispose();
            }

            if (options.HaveAlphaBand)
            {
                Band bdAlpha = dsOut.GetRasterBand(_ds.RasterCount + 1);
                bdAlpha.WriteRaster(0, 0, options.TileSize, options.TileSize, pixelsAlpha, options.TileSize, options.TileSize, 0, 0);
                bdAlpha.FlushCache();
                bdAlpha.Dispose();
            }
        }

        private void _SetNullDataImage(Dataset dsOut, int nullValue)
        {
            for (int nBand = 1; nBand < dsOut.RasterCount; nBand++)
                dsOut.GetRasterBand(nBand).SetNoDataValue(nullValue);
        }

        private void _DatasetPng2File(Dataset ds, string sFileName)
        {
            OSGeo.GDAL.Driver drv = Gdal.GetDriverByName("PNG");
            string[] aryOption = { "" };

            Dataset dsOut = drv.CreateCopy(sFileName, ds, 0, aryOption, null, null);
            dsOut.FlushCache(); dsOut.Dispose();
        }

        #endregion Private Methods
    }
}


text:
package org.apache.flink.runtime.metrics.util;

import org.apache.flink.annotation.VisibleForTesting;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.configuration.MetricOptions;
import org.apache.flink.metrics.Gauge;
import org.apache.flink.metrics.MetricGroup;
import org.apache.flink.runtime.clusterframework.BootstrapTools;
import org.apache.flink.runtime.clusterframework.types.ResourceID;
import org.apache.flink.runtime.metrics.MetricNames;
import org.apache.flink.runtime.metrics.MetricRegistry;
import org.apache.flink.runtime.metrics.groups.JobManagerMetricGroup;
import org.apache.flink.runtime.metrics.groups.TaskManagerMetricGroup;
import org.apache.flink.runtime.rpc.RpcService;
import org.apache.flink.runtime.rpc.akka.AkkaRpcServiceUtils;
import org.apache.flink.util.Preconditions;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.management.AttributeNotFoundException;
import javax.management.InstanceNotFoundException;
import javax.management.MBeanException;
import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import javax.management.ReflectionException;

import java.lang.management.ClassLoadingMXBean;
import java.lang.management.GarbageCollectorMXBean;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryUsage;
import java.lang.management.ThreadMXBean;
import java.util.List;
import java.util.Optional;
import java.util.function.Supplier;

import static org.apache.flink.runtime.metrics.util.SystemResourcesMetricsInitializer.instantiateSystemMetrics;

/**
 * Utility class to register pre-defined metric sets.
 */
public class MetricUtils {
	private static final Logger LOG = LoggerFactory.getLogger(MetricUtils.class);
	private static final String METRIC_GROUP_STATUS_NAME = "Status";
	private static final String METRICS_ACTOR_SYSTEM_NAME = "flink-metrics";

	static final String METRIC_GROUP_HEAP_NAME = "Heap";
	static final String METRIC_GROUP_NONHEAP_NAME = "NonHeap";

	private MetricUtils() {
	}

	public static JobManagerMetricGroup instantiateJobManagerMetricGroup(
			final MetricRegistry metricRegistry,
			final String hostname,
			final Optional<Time> systemResourceProbeInterval) {
		final JobManagerMetricGroup jobManagerMetricGroup = new JobManagerMetricGroup(
			metricRegistry,
			hostname);

		MetricGroup statusGroup = jobManagerMetricGroup.addGroup(METRIC_GROUP_STATUS_NAME);

		// initialize the JM metrics
		instantiateStatusMetrics(statusGroup);

		if (systemResourceProbeInterval.isPresent()) {
			instantiateSystemMetrics(jobManagerMetricGroup, systemResourceProbeInterval.get());
		}
		return jobManagerMetricGroup;
	}

	public static Tuple2<TaskManagerMetricGroup, MetricGroup> instantiateTaskManagerMetricGroup(
			MetricRegistry metricRegistry,
			String hostName,
			ResourceID resourceID,
			Optional<Time> systemResourceProbeInterval) {
		final TaskManagerMetricGroup taskManagerMetricGroup = new TaskManagerMetricGroup(
			metricRegistry,
			hostName,
			resourceID.toString());

		MetricGroup statusGroup = taskManagerMetricGroup.addGroup(METRIC_GROUP_STATUS_NAME);

		// Initialize the TM metrics
		instantiateStatusMetrics(statusGroup);

		if (systemResourceProbeInterval.isPresent()) {
			instantiateSystemMetrics(taskManagerMetricGroup, systemResourceProbeInterval.get());
		}
		return Tuple2.of(taskManagerMetricGroup, statusGroup);
	}

	public static void instantiateStatusMetrics(
			MetricGroup metricGroup) {
		MetricGroup jvm = metricGroup.addGroup("JVM");

		instantiateClassLoaderMetrics(jvm.addGroup("ClassLoader"));
		instantiateGarbageCollectorMetrics(jvm.addGroup("GarbageCollector"));
		instantiateMemoryMetrics(jvm.addGroup("Memory"));
		instantiateThreadMetrics(jvm.addGroup("Threads"));
		instantiateCPUMetrics(jvm.addGroup("CPU"));
	}

	public static RpcService startMetricsRpcService(Configuration configuration, String hostname) throws Exception {
		final String portRange = configuration.getString(MetricOptions.QUERY_SERVICE_PORT);
		final int threadPriority = configuration.getInteger(MetricOptions.QUERY_SERVICE_THREAD_PRIORITY);

		return AkkaRpcServiceUtils.createRpcService(
			hostname,
			portRange,
			configuration,
			METRICS_ACTOR_SYSTEM_NAME,
			new BootstrapTools.FixedThreadPoolExecutorConfiguration(1, 1, threadPriority));
	}

	private static void instantiateClassLoaderMetrics(MetricGroup metrics) {
		final ClassLoadingMXBean mxBean = ManagementFactory.getClassLoadingMXBean();
		metrics.<Long, Gauge<Long>>gauge("ClassesLoaded", mxBean::getTotalLoadedClassCount);
		metrics.<Long, Gauge<Long>>gauge("ClassesUnloaded", mxBean::getUnloadedClassCount);
	}

	private static void instantiateGarbageCollectorMetrics(MetricGroup metrics) {
		List<GarbageCollectorMXBean> garbageCollectors = ManagementFactory.getGarbageCollectorMXBeans();

		for (final GarbageCollectorMXBean garbageCollector: garbageCollectors) {
			MetricGroup gcGroup = metrics.addGroup(garbageCollector.getName());

			gcGroup.<Long, Gauge<Long>>gauge("Count", garbageCollector::getCollectionCount);
			gcGroup.<Long, Gauge<Long>>gauge("Time", garbageCollector::getCollectionTime);
		}
	}

	private static void instantiateMemoryMetrics(MetricGroup metrics) {
		instantiateHeapMemoryMetrics(metrics.addGroup(METRIC_GROUP_HEAP_NAME));
		instantiateNonHeapMemoryMetrics(metrics.addGroup(METRIC_GROUP_NONHEAP_NAME));

		final MBeanServer con = ManagementFactory.getPlatformMBeanServer();

		final String directBufferPoolName = "java.nio:type=BufferPool,name=direct";

		try {
			final ObjectName directObjectName = new ObjectName(directBufferPoolName);

			MetricGroup direct = metrics.addGroup("Direct");

			direct.<Long, Gauge<Long>>gauge("Count", new AttributeGauge<>(con, directObjectName, "Count", -1L));
			direct.<Long, Gauge<Long>>gauge("MemoryUsed", new AttributeGauge<>(con, directObjectName, "MemoryUsed", -1L));
			direct.<Long, Gauge<Long>>gauge("TotalCapacity", new AttributeGauge<>(con, directObjectName, "TotalCapacity", -1L));
		} catch (MalformedObjectNameException e) {
			LOG.warn("Could not create object name {}.", directBufferPoolName, e);
		}

		final String mappedBufferPoolName = "java.nio:type=BufferPool,name=mapped";

		try {
			final ObjectName mappedObjectName = new ObjectName(mappedBufferPoolName);

			MetricGroup mapped = metrics.addGroup("Mapped");

			mapped.<Long, Gauge<Long>>gauge("Count", new AttributeGauge<>(con, mappedObjectName, "Count", -1L));
			mapped.<Long, Gauge<Long>>gauge("MemoryUsed", new AttributeGauge<>(con, mappedObjectName, "MemoryUsed", -1L));
			mapped.<Long, Gauge<Long>>gauge("TotalCapacity", new AttributeGauge<>(con, mappedObjectName, "TotalCapacity", -1L));
		} catch (MalformedObjectNameException e) {
			LOG.warn("Could not create object name {}.", mappedBufferPoolName, e);
		}
	}

	@VisibleForTesting
	static void instantiateHeapMemoryMetrics(final MetricGroup metricGroup) {
		instantiateMemoryUsageMetrics(metricGroup, () -> ManagementFactory.getMemoryMXBean().getHeapMemoryUsage());
	}

	@VisibleForTesting
	static void instantiateNonHeapMemoryMetrics(final MetricGroup metricGroup) {
		instantiateMemoryUsageMetrics(metricGroup, () -> ManagementFactory.getMemoryMXBean().getNonHeapMemoryUsage());
	}

	private static void instantiateMemoryUsageMetrics(final MetricGroup metricGroup, final Supplier<MemoryUsage> memoryUsageSupplier) {
		metricGroup.<Long, Gauge<Long>>gauge(MetricNames.MEMORY_USED, () -> memoryUsageSupplier.get().getUsed());
		metricGroup.<Long, Gauge<Long>>gauge(MetricNames.MEMORY_COMMITTED, () -> memoryUsageSupplier.get().getCommitted());
		metricGroup.<Long, Gauge<Long>>gauge(MetricNames.MEMORY_MAX, () -> memoryUsageSupplier.get().getMax());
	}

	private static void instantiateThreadMetrics(MetricGroup metrics) {
		final ThreadMXBean mxBean = ManagementFactory.getThreadMXBean();

		metrics.<Integer, Gauge<Integer>>gauge("Count", mxBean::getThreadCount);
	}

	private static void instantiateCPUMetrics(MetricGroup metrics) {
		try {
			final com.sun.management.OperatingSystemMXBean mxBean = (com.sun.management.OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();

			metrics.<Double, Gauge<Double>>gauge("Load", mxBean::getProcessCpuLoad);
			metrics.<Long, Gauge<Long>>gauge("Time", mxBean::getProcessCpuTime);
		} catch (Exception e) {
			LOG.warn("Cannot access com.sun.management.OperatingSystemMXBean.getProcessCpuLoad()" +
				" - CPU load metrics will not be available.", e);
		}
	}

	private static final class AttributeGauge<T> implements Gauge<T> {
		private final MBeanServer server;
		private final ObjectName objectName;
		private final String attributeName;
		private final T errorValue;

		private AttributeGauge(MBeanServer server, ObjectName objectName, String attributeName, T errorValue) {
			this.server = Preconditions.checkNotNull(server);
			this.objectName = Preconditions.checkNotNull(objectName);
			this.attributeName = Preconditions.checkNotNull(attributeName);
			this.errorValue = errorValue;
		}

		@SuppressWarnings("unchecked")
		@Override
		public T getValue() {
			try {
				return (T) server.getAttribute(objectName, attributeName);
			} catch (MBeanException | AttributeNotFoundException | InstanceNotFoundException | ReflectionException e) {
				LOG.warn("Could not read attribute {}.", attributeName, e);
				return errorValue;
			}
		}
	}
}


text:
/**
 * Created by IntelliJ IDEA.
 * User: mingzhang
 * Date: 5/24/11
 * Time: 10:28 PM
 * To change this template use File | Settings | File Templates.
 */

ZaSignature =
function(name, id, content, type) {
    this.id = id;
    this.name = name;
    this.content = content;
    this.type = type ? type: "text/plain";
}

ZaSignature.prototype.constructor = ZaSignature;
ZaSignature.prototype.toString =
function() {
    return this.name;
}

ZaSignature.compareObject =
function(t1, t2){
    for(var i in t1){
        if(t1[i] != t2[i]){
            return false;
        }
    }
    return true;
}

ZaSignature.A2_name = "name";
ZaSignature.A2_id = "id";
ZaSignature.A2_content = "content";
ZaSignature.A2_type = "type";

ZaSignature.myXModel = {
    items:[
        {id:ZaSignature.A2_id, type:_STRING_, ref:ZaSignature.A2_id},
        {id:ZaSignature.A2_name, type:_STRING_, ref:ZaSignature.A2_name},
        {id:ZaSignature.A2_content, type:_STRING_, ref:ZaSignature.A2_content},
        {id:ZaSignature.A2_type, type:_STRING_, ref:ZaSignature.A2_type}
    ]
}

ZaSignature.signatureTypeChoices = [
    {value:"text/plain", label:ZaMsg.resSignaturePlainType},
    {value:"text/html", label:ZaMsg.resSignatureHTMLType}
];

ZaSignature.getSignatureChoices =
function (arr) {
    var result = [];
    result.push({name:ZaMsg.VALUE_NOT_SET, id:""});
    var i = 0;
    for(i = 0; i < arr.length; i++){
       result.push({name:arr[i].name, id:arr[i].id});
    }
    return result;
}

ZaSignature.getNewSignatureChoices =
function (arr) {
    var result = [];
    result.push({name:ZaMsg.VALUE_NOT_SET, id:""});
    var i = 0;
    for(i = 0; i < arr.length; i++){
        if(arr[i].name)
            result.push({name:arr[i].name, id:arr[i].name});
    }
    return result;
}

ZaSignature.GetSignatures =
function(by, val) {
    var soapDoc = AjxSoapDoc.create("GetSignaturesRequest", "urn:zimbraAccount", null);

    var params = new Object();
    params.soapDoc = soapDoc;
    params.skipAuthCheck = false;
    if(by == "id"){
        params.accountId = val;
    } else {
        params.accountName = val;
    }

    try{
        var reqMgrParams = {
            controller : ZaApp.getInstance().getCurrentController(),
            busyMsg : ZaMsg.BUSY_GET_RESOURCE
        };

        this[ZaResource.A2_signatureList] = [];
        var resp = ZaRequestMgr.invoke(params, reqMgrParams).Body.GetSignaturesResponse;
        if( resp.signature) {
            for (var i in resp.signature) {
                var _content;
                var _type;
                if(resp.signature[i].content && resp.signature[i].content[0]){
                    _content =  resp.signature[i].content[0]._content;
                    _type = resp.signature[i].content[0].type;
                }
                var currentSignature = new ZaSignature(resp.signature[i].name,
                                            resp.signature[i].id,
                                            _content,
                                            _type);
                this[ZaResource.A2_signatureList].push(currentSignature);
            }

        }

    } catch(ex) {
        throw ex;
        return null;
    }
}

ZaSignature.CreateSignature =
function(by, val) {
    var soapDoc = AjxSoapDoc.create("CreateSignatureRequest", "urn:zimbraAccount", null);
    var signBy = soapDoc.set("signature", null);
    signBy.setAttribute("name", this[ZaSignature.A2_name]);
    var contentBy;
    if(this[ZaSignature.A2_type] == "text/plain"){
        contentBy = soapDoc.set("content", this[ZaSignature.A2_content], signBy);
        contentBy.setAttribute("type", "text/plain");

        contentBy = soapDoc.set("content", null, signBy);
        contentBy.setAttribute("type", "text/html");
    } else {
        contentBy = soapDoc.set("content", this[ZaSignature.A2_content], signBy);
        contentBy.setAttribute("type", "text/html");

        contentBy = soapDoc.set("content", null, signBy);
        contentBy.setAttribute("type", "text/plain");
    }
    var params = new Object();
    params.soapDoc = soapDoc;
    params.skipAuthCheck = false;
    if(by == "id"){
        params.accountId = val;
    } else {
        params.accountName = val;
    }

    try{
        var reqMgrParams = {
            controller : ZaApp.getInstance().getCurrentController(),
            busyMsg : ZaMsg.BUSY_GET_RESOURCE
        };

        var resp = ZaRequestMgr.invoke(params, reqMgrParams).Body.CreateSignatureResponse;
        if( resp.signature && resp.signature[0]) {
            this.id = resp.signature[0].id;
        }
        return this;
    } catch(ex) {
        throw ex;
        return null;
    }
}

ZaSignature.CreateAccountSignature =
function(tmpObj, resource){
    if (!AjxUtil.isEmpty(tmpObj[ZaResource.A2_signatureList])) {
        for(var i = 0; i < tmpObj[ZaResource.A2_signatureList].length; i++) {
            var current = tmpObj[ZaResource.A2_signatureList][i];
            var newSign;
            if (current[ZaSignature.A2_name] && current[ZaSignature.A2_content]){
                newSign = new ZaSignature(current[ZaSignature.A2_name], "",
                                          current[ZaSignature.A2_content],
                                          current[ZaSignature.A2_type]);
                ZaSignature.CreateSignature.call(newSign, "id", resource.id);
                tmpObj[ZaResource.A2_signatureList][i] = newSign;
            }
        }
        var mods = {};
        var index;
        if (tmpObj.attrs[ZaResource.A_zimbraPrefCalendarAutoAcceptSignatureId]) {
            index = ZaUtil.findValueInObjArrByPropertyName(tmpObj[ZaResource.A2_signatureList],
                        tmpObj.attrs[ZaResource.A_zimbraPrefCalendarAutoAcceptSignatureId]);
            if (index != -1 && tmpObj[ZaResource.A2_signatureList][index].id) {
                mods[ZaResource.A_zimbraPrefCalendarAutoAcceptSignatureId] = tmpObj[ZaResource.A2_signatureList][index].id;
            }
        }

        if (tmpObj.attrs[ZaResource.A_zimbraPrefCalendarAutoDenySignatureId]) {
            index = ZaUtil.findValueInObjArrByPropertyName(tmpObj[ZaResource.A2_signatureList],
                        tmpObj.attrs[ZaResource.A_zimbraPrefCalendarAutoDenySignatureId]);
            if (index != -1 && tmpObj[ZaResource.A2_signatureList][index].id) {
                mods[ZaResource.A_zimbraPrefCalendarAutoDenySignatureId] = tmpObj[ZaResource.A2_signatureList][index].id;
            }
        }

        if (tmpObj.attrs[ZaResource.A_zimbraPrefCalendarAutoDeclineSignatureId]) {
            index = ZaUtil.findValueInObjArrByPropertyName(tmpObj[ZaResource.A2_signatureList],
                        tmpObj.attrs[ZaResource.A_zimbraPrefCalendarAutoDeclineSignatureId]);
            if (index != -1 && tmpObj[ZaResource.A2_signatureList][index].id) {
                mods[ZaResource.A_zimbraPrefCalendarAutoDeclineSignatureId] = tmpObj[ZaResource.A2_signatureList][index].id;
            }
        }

        if(!AjxUtil.isEmpty(mods))
            ZaResource.modifyMethod.call(resource, mods);
    }

    return resource;
}

ZaSignature.ModifySignature =
function(by, val) {
    var soapDoc = AjxSoapDoc.create("ModifySignatureRequest", "urn:zimbraAccount", null);
    var signBy = soapDoc.set("signature", null);
    signBy.setAttribute("name", this[ZaSignature.A2_name]);
    signBy.setAttribute("id", this[ZaSignature.A2_id]);
    var contentBy;
    if(this[ZaSignature.A2_type] == "text/plain"){
        contentBy = soapDoc.set("content", this[ZaSignature.A2_content], signBy);
        contentBy.setAttribute("type", "text/plain");

        contentBy = soapDoc.set("content", null, signBy);
        contentBy.setAttribute("type", "text/html");
    } else {
        contentBy = soapDoc.set("content", this[ZaSignature.A2_content], signBy);
        contentBy.setAttribute("type", "text/html");

        contentBy = soapDoc.set("content", null, signBy);
        contentBy.setAttribute("type", "text/plain");
    }

    var params = new Object();
    params.soapDoc = soapDoc;
    params.skipAuthCheck = false;
    if(by == "id"){
        params.accountId = val;
    } else {
        params.accountName = val;
    }

    try{
        var reqMgrParams = {
            controller : ZaApp.getInstance().getCurrentController(),
            busyMsg : ZaMsg.BUSY_GET_RESOURCE
        };

        ZaRequestMgr.invoke(params, reqMgrParams).Body.ModifySignatureResponse;

    } catch(ex) {
        throw ex;
        return null;
    }
}

ZaSignature.DeleteSignature =
function(by, val) {
    var soapDoc = AjxSoapDoc.create("DeleteSignatureRequest", "urn:zimbraAccount", null);
    var signBy = soapDoc.set("signature", null);
    signBy.setAttribute("id", this[ZaSignature.A2_id]);

    var params = new Object();
    params.soapDoc = soapDoc;
    params.skipAuthCheck = false;
    if(by == "id"){
        params.accountId = val;
    } else {
        params.accountName = val;
    }

    try{
        var reqMgrParams = {
            controller : ZaApp.getInstance().getCurrentController(),
            busyMsg : ZaMsg.BUSY_GET_RESOURCE
        };

        var resp = ZaRequestMgr.invoke(params, reqMgrParams).Body.DeleteSignatureResponse;

    } catch(ex) {
        throw ex;
        return null;
    }
}


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _pure = require('recompose/pure');

var _pure2 = _interopRequireDefault(_pure);

var _SvgIcon = require('../../SvgIcon');

var _SvgIcon2 = _interopRequireDefault(_SvgIcon);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var AvGames = function AvGames(props) {
  return _react2.default.createElement(
    _SvgIcon2.default,
    props,
    _react2.default.createElement('path', { d: 'M15 7.5V2H9v5.5l3 3 3-3zM7.5 9H2v6h5.5l3-3-3-3zM9 16.5V22h6v-5.5l-3-3-3 3zM16.5 9l-3 3 3 3H22V9h-5.5z' })
  );
};
AvGames = (0, _pure2.default)(AvGames);
AvGames.displayName = 'AvGames';

exports.default = AvGames;


text:
package org.keycloak.models.jpa;

import org.keycloak.models.ClientModel;
import org.keycloak.models.CredentialValidationOutput;
import org.keycloak.models.FederatedIdentityModel;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.ProtocolMapperModel;
import org.keycloak.models.RealmModel;
import org.keycloak.models.RoleModel;
import org.keycloak.models.UserCredentialModel;
import org.keycloak.models.UserFederationProviderModel;
import org.keycloak.models.UserModel;
import org.keycloak.models.UserProvider;
import org.keycloak.models.jpa.entities.FederatedIdentityEntity;
import org.keycloak.models.jpa.entities.UserEntity;
import org.keycloak.models.utils.CredentialValidation;
import org.keycloak.models.utils.KeycloakModelUtils;

import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author Bill Burke
 * @version $Revision: 1 $
 */
public class JpaUserProvider implements UserProvider {

    private static final String EMAIL = "email";
    private static final String USERNAME = "username";
    private static final String FIRST_NAME = "firstName";
    private static final String LAST_NAME = "lastName";

    private final KeycloakSession session;
    protected EntityManager em;

    public JpaUserProvider(KeycloakSession session, EntityManager em) {
        this.session = session;
        this.em = em;
    }

    @Override
    public UserModel addUser(RealmModel realm, String id, String username, boolean addDefaultRoles) {
        if (id == null) {
            id = KeycloakModelUtils.generateId();
        }

        UserEntity entity = new UserEntity();
        entity.setId(id);
        entity.setUsername(username.toLowerCase());
        entity.setRealmId(realm.getId());
        em.persist(entity);
        em.flush();
        UserModel userModel = new UserAdapter(realm, em, entity);

        if (addDefaultRoles) {
            for (String r : realm.getDefaultRoles()) {
                userModel.grantRole(realm.getRole(r));
            }

            for (ClientModel application : realm.getClients()) {
                for (String r : application.getDefaultRoles()) {
                    userModel.grantRole(application.getRole(r));
                }
            }
        }

        return userModel;
    }

    @Override
    public UserModel addUser(RealmModel realm, String username) {
        return addUser(realm, KeycloakModelUtils.generateId(), username.toLowerCase(), true);
    }

    @Override
    public boolean removeUser(RealmModel realm, UserModel user) {
        UserEntity userEntity = em.find(UserEntity.class, user.getId());
        if (userEntity == null) return false;
        removeUser(userEntity);
        return true;
    }

    private void removeUser(UserEntity user) {
        String id = user.getId();
        em.createNamedQuery("deleteUserRoleMappingsByUser").setParameter("user", user).executeUpdate();
        em.createNamedQuery("deleteFederatedIdentityByUser").setParameter("user", user).executeUpdate();
        em.createNamedQuery("deleteUserConsentRolesByUser").setParameter("user", user).executeUpdate();
        em.createNamedQuery("deleteUserConsentProtMappersByUser").setParameter("user", user).executeUpdate();
        em.createNamedQuery("deleteUserConsentsByUser").setParameter("user", user).executeUpdate();
        em.flush();
        // not sure why i have to do a clear() here.  I was getting some messed up errors that Hibernate couldn't
        // un-delete the UserEntity.
        em.clear();
        user = em.find(UserEntity.class, id);
        if (user != null) {
            em.remove(user);
        }
        em.flush();
    }

    @Override
    public void addFederatedIdentity(RealmModel realm, UserModel user, FederatedIdentityModel identity) {
        FederatedIdentityEntity entity = new FederatedIdentityEntity();
        entity.setRealmId(realm.getId());
        entity.setIdentityProvider(identity.getIdentityProvider());
        entity.setUserId(identity.getUserId());
        entity.setUserName(identity.getUserName().toLowerCase());
        entity.setToken(identity.getToken());
        UserEntity userEntity = em.getReference(UserEntity.class, user.getId());
        entity.setUser(userEntity);
        em.persist(entity);
        em.flush();
    }

    @Override
    public void updateFederatedIdentity(RealmModel realm, UserModel federatedUser, FederatedIdentityModel federatedIdentityModel) {
        FederatedIdentityEntity federatedIdentity = findFederatedIdentity(federatedUser, federatedIdentityModel.getIdentityProvider());

        federatedIdentity.setToken(federatedIdentityModel.getToken());

        em.persist(federatedIdentity);
        em.flush();
    }

    @Override
    public boolean removeFederatedIdentity(RealmModel realm, UserModel user, String identityProvider) {
        FederatedIdentityEntity entity = findFederatedIdentity(user, identityProvider);
        if (entity != null) {
            em.remove(entity);
            em.flush();
            return true;
        } else {
            return false;
        }
    }

    @Override
    public void preRemove(RealmModel realm) {
        int num = em.createNamedQuery("deleteUserConsentRolesByRealm")
                .setParameter("realmId", realm.getId()).executeUpdate();
        num = em.createNamedQuery("deleteUserConsentProtMappersByRealm")
                .setParameter("realmId", realm.getId()).executeUpdate();
        num = em.createNamedQuery("deleteUserConsentsByRealm")
                .setParameter("realmId", realm.getId()).executeUpdate();
        num = em.createNamedQuery("deleteUserRoleMappingsByRealm")
                .setParameter("realmId", realm.getId()).executeUpdate();
        num = em.createNamedQuery("deleteUserRequiredActionsByRealm")
                .setParameter("realmId", realm.getId()).executeUpdate();
        num = em.createNamedQuery("deleteFederatedIdentityByRealm")
                .setParameter("realmId", realm.getId()).executeUpdate();
        num = em.createNamedQuery("deleteCredentialsByRealm")
                .setParameter("realmId", realm.getId()).executeUpdate();
        num = em.createNamedQuery("deleteUserAttributesByRealm")
                .setParameter("realmId", realm.getId()).executeUpdate();
        num = em.createNamedQuery("deleteUsersByRealm")
                .setParameter("realmId", realm.getId()).executeUpdate();
    }

    @Override
    public void preRemove(RealmModel realm, UserFederationProviderModel link) {
        int num = em.createNamedQuery("deleteUserRoleMappingsByRealmAndLink")
                .setParameter("realmId", realm.getId())
                .setParameter("link", link.getId())
                .executeUpdate();
        num = em.createNamedQuery("deleteUserRequiredActionsByRealmAndLink")
                .setParameter("realmId", realm.getId())
                .setParameter("link", link.getId())
                .executeUpdate();
        num = em.createNamedQuery("deleteFederatedIdentityByRealmAndLink")
                .setParameter("realmId", realm.getId())
                .setParameter("link", link.getId())
                .executeUpdate();
        num = em.createNamedQuery("deleteCredentialsByRealmAndLink")
                .setParameter("realmId", realm.getId())
                .setParameter("link", link.getId())
                .executeUpdate();
        num = em.createNamedQuery("deleteUserAttributesByRealmAndLink")
                .setParameter("realmId", realm.getId())
                .setParameter("link", link.getId())
                .executeUpdate();
        num = em.createNamedQuery("deleteUsersByRealmAndLink")
                .setParameter("realmId", realm.getId())
                .setParameter("link", link.getId())
                .executeUpdate();
    }

    @Override
    public void preRemove(RealmModel realm, RoleModel role) {
        em.createNamedQuery("deleteUserConsentRolesByRole").setParameter("roleId", role.getId()).executeUpdate();
        em.createNamedQuery("deleteUserRoleMappingsByRole").setParameter("roleId", role.getId()).executeUpdate();
    }

    @Override
    public void preRemove(RealmModel realm, ClientModel client) {
        em.createNamedQuery("deleteUserConsentProtMappersByClient").setParameter("clientId", client.getId()).executeUpdate();
        em.createNamedQuery("deleteUserConsentRolesByClient").setParameter("clientId", client.getId()).executeUpdate();
        em.createNamedQuery("deleteUserConsentsByClient").setParameter("clientId", client.getId()).executeUpdate();
    }

    @Override
    public void preRemove(ClientModel client, ProtocolMapperModel protocolMapper) {
        em.createNamedQuery("deleteUserConsentProtMappersByProtocolMapper")
                .setParameter("protocolMapperId", protocolMapper.getId())
                .executeUpdate();
    }

    @Override
    public UserModel getUserById(String id, RealmModel realm) {
        TypedQuery<UserEntity> query = em.createNamedQuery("getRealmUserById", UserEntity.class);
        query.setParameter("id", id);
        query.setParameter("realmId", realm.getId());
        List<UserEntity> entities = query.getResultList();
        if (entities.size() == 0) return null;
        return new UserAdapter(realm, em, entities.get(0));
    }

    @Override
    public UserModel getUserByUsername(String username, RealmModel realm) {
        TypedQuery<UserEntity> query = em.createNamedQuery("getRealmUserByUsername", UserEntity.class);
        query.setParameter("username", username.toLowerCase());
        query.setParameter("realmId", realm.getId());
        List<UserEntity> results = query.getResultList();
        if (results.size() == 0) return null;
        return new UserAdapter(realm, em, results.get(0));
    }

    @Override
    public UserModel getUserByEmail(String email, RealmModel realm) {
        TypedQuery<UserEntity> query = em.createNamedQuery("getRealmUserByEmail", UserEntity.class);
        query.setParameter("email", email.toLowerCase());
        query.setParameter("realmId", realm.getId());
        List<UserEntity> results = query.getResultList();
        return results.isEmpty() ? null : new UserAdapter(realm, em, results.get(0));
    }

     @Override
    public void close() {
    }

    @Override
    public UserModel getUserByFederatedIdentity(FederatedIdentityModel identity, RealmModel realm) {
        TypedQuery<UserEntity> query = em.createNamedQuery("findUserByFederatedIdentityAndRealm", UserEntity.class);
        query.setParameter("realmId", realm.getId());
        query.setParameter("identityProvider", identity.getIdentityProvider());
        query.setParameter("userId", identity.getUserId());
        List<UserEntity> results = query.getResultList();
        if (results.isEmpty()) {
            return null;
        } else if (results.size() > 1) {
            throw new IllegalStateException("More results found for identityProvider=" + identity.getIdentityProvider() +
                    ", userId=" + identity.getUserId() + ", results=" + results);
        } else {
            UserEntity user = results.get(0);
            return new UserAdapter(realm, em, user);
        }
    }

    @Override
    public List<UserModel> getUsers(RealmModel realm) {
        return getUsers(realm, -1, -1);
    }

    @Override
    public int getUsersCount(RealmModel realm) {
        // TODO: named query?
        Object count = em.createNamedQuery("getRealmUserCount")
                .setParameter("realmId", realm.getId())
                .getSingleResult();
        return ((Number)count).intValue();
    }

    @Override
    public List<UserModel> getUsers(RealmModel realm, int firstResult, int maxResults) {
        TypedQuery<UserEntity> query = em.createNamedQuery("getAllUsersByRealm", UserEntity.class);
        query.setParameter("realmId", realm.getId());
        if (firstResult != -1) {
            query.setFirstResult(firstResult);
        }
        if (maxResults != -1) {
            query.setMaxResults(maxResults);
        }
        List<UserEntity> results = query.getResultList();
        List<UserModel> users = new ArrayList<UserModel>();
        for (UserEntity entity : results) users.add(new UserAdapter(realm, em, entity));
        return users;
    }

    @Override
    public List<UserModel> searchForUser(String search, RealmModel realm) {
        return searchForUser(search, realm, -1, -1);
    }

    @Override
    public List<UserModel> searchForUser(String search, RealmModel realm, int firstResult, int maxResults) {
        TypedQuery<UserEntity> query = em.createNamedQuery("searchForUser", UserEntity.class);
        query.setParameter("realmId", realm.getId());
        query.setParameter("search", "%" + search.toLowerCase() + "%");
        if (firstResult != -1) {
            query.setFirstResult(firstResult);
        }
        if (maxResults != -1) {
            query.setMaxResults(maxResults);
        }
        List<UserEntity> results = query.getResultList();
        List<UserModel> users = new ArrayList<UserModel>();
        for (UserEntity entity : results) users.add(new UserAdapter(realm, em, entity));
        return users;
    }

    @Override
    public List<UserModel> searchForUserByAttributes(Map<String, String> attributes, RealmModel realm) {
        return searchForUserByAttributes(attributes, realm, -1, -1);
    }

    @Override
    public List<UserModel> searchForUserByAttributes(Map<String, String> attributes, RealmModel realm, int firstResult, int maxResults) {
        StringBuilder builder = new StringBuilder("select u from UserEntity u where u.realmId = :realmId");
        for (Map.Entry<String, String> entry : attributes.entrySet()) {
            String attribute = null;
            String parameterName = null;
            if (entry.getKey().equals(UserModel.USERNAME)) {
                attribute = "lower(u.username)";
                parameterName = JpaUserProvider.USERNAME;
            } else if (entry.getKey().equalsIgnoreCase(UserModel.FIRST_NAME)) {
                attribute = "lower(u.firstName)";
                parameterName = JpaUserProvider.FIRST_NAME;
            } else if (entry.getKey().equalsIgnoreCase(UserModel.LAST_NAME)) {
                attribute = "lower(u.lastName)";
                parameterName = JpaUserProvider.LAST_NAME;
            } else if (entry.getKey().equalsIgnoreCase(UserModel.EMAIL)) {
                attribute = "lower(u.email)";
                parameterName = JpaUserProvider.EMAIL;
            }
            if (attribute == null) continue;
            builder.append(" and ");
            builder.append(attribute).append(" like :").append(parameterName);
        }
        builder.append(" order by u.username");
        String q = builder.toString();
        TypedQuery<UserEntity> query = em.createQuery(q, UserEntity.class);
        query.setParameter("realmId", realm.getId());
        for (Map.Entry<String, String> entry : attributes.entrySet()) {
            String parameterName = null;
            if (entry.getKey().equals(UserModel.USERNAME)) {
                parameterName = JpaUserProvider.USERNAME;
            } else if (entry.getKey().equalsIgnoreCase(UserModel.FIRST_NAME)) {
                parameterName = JpaUserProvider.FIRST_NAME;
            } else if (entry.getKey().equalsIgnoreCase(UserModel.LAST_NAME)) {
                parameterName = JpaUserProvider.LAST_NAME;
            } else if (entry.getKey().equalsIgnoreCase(UserModel.EMAIL)) {
                parameterName = JpaUserProvider.EMAIL;
            }
            if (parameterName == null) continue;
            query.setParameter(parameterName, "%" + entry.getValue().toLowerCase() + "%");
        }
        if (firstResult != -1) {
            query.setFirstResult(firstResult);
        }
        if (maxResults != -1) {
            query.setMaxResults(maxResults);
        }
        List<UserEntity> results = query.getResultList();
        List<UserModel> users = new ArrayList<UserModel>();
        for (UserEntity entity : results) users.add(new UserAdapter(realm, em, entity));
        return users;
    }

    private FederatedIdentityEntity findFederatedIdentity(UserModel user, String identityProvider) {
        TypedQuery<FederatedIdentityEntity> query = em.createNamedQuery("findFederatedIdentityByUserAndProvider", FederatedIdentityEntity.class);
        UserEntity userEntity = em.getReference(UserEntity.class, user.getId());
        query.setParameter("user", userEntity);
        query.setParameter("identityProvider", identityProvider);
        List<FederatedIdentityEntity> results = query.getResultList();
        return results.size() > 0 ? results.get(0) : null;
    }

    @Override
    public Set<FederatedIdentityModel> getFederatedIdentities(UserModel user, RealmModel realm) {
        TypedQuery<FederatedIdentityEntity> query = em.createNamedQuery("findFederatedIdentityByUser", FederatedIdentityEntity.class);
        UserEntity userEntity = em.getReference(UserEntity.class, user.getId());
        query.setParameter("user", userEntity);
        List<FederatedIdentityEntity> results = query.getResultList();
        Set<FederatedIdentityModel> set = new HashSet<FederatedIdentityModel>();
        for (FederatedIdentityEntity entity : results) {
            set.add(new FederatedIdentityModel(entity.getIdentityProvider(), entity.getUserId(), entity.getUserName(), entity.getToken()));
        }
        return set;
    }

    @Override
    public FederatedIdentityModel getFederatedIdentity(UserModel user, String identityProvider, RealmModel realm) {
        FederatedIdentityEntity entity = findFederatedIdentity(user, identityProvider);
        return (entity != null) ? new FederatedIdentityModel(entity.getIdentityProvider(), entity.getUserId(), entity.getUserName(), entity.getToken()) : null;
    }

    @Override
    public boolean validCredentials(RealmModel realm, UserModel user, List<UserCredentialModel> input) {
        return CredentialValidation.validCredentials(realm, user, input);
    }

    @Override
    public boolean validCredentials(RealmModel realm, UserModel user, UserCredentialModel... input) {
        return CredentialValidation.validCredentials(realm, user, input);
    }

    @Override
    public CredentialValidationOutput validCredentials(RealmModel realm, UserCredentialModel... input) {
        // Not supported yet
        return null;
    }
}


text:
var get = Ember.get;
var Person, env, store, adapter;
var run = Ember.run;

module("integration/adapter/queries - Queries", {
  setup: function() {
    Person = DS.Model.extend({
      updatedAt: DS.attr('string'),
      name: DS.attr('string'),
      firstName: DS.attr('string'),
      lastName: DS.attr('string')
    });

    env = setupStore({ person: Person });
    store = env.store;
    adapter = env.adapter;
  },

  teardown: function() {
    run(env.container, 'destroy');
  }
});

test("When a query is made, the adapter should receive a record array it can populate with the results of the query.", function() {
  adapter.findQuery = function(store, type, query, recordArray) {
    equal(type, Person, "the find method is called with the correct type");

    return Ember.RSVP.resolve([{ id: 1, name: "Peter Wagenet" }, { id: 2, name: "Brohuda Katz" }]);
  };

  store.query('person', { page: 1 }).then(async(function(queryResults) {
    equal(get(queryResults, 'length'), 2, "the record array has a length of 2 after the results are loaded");
    equal(get(queryResults, 'isLoaded'), true, "the record array's `isLoaded` property should be true");

    equal(queryResults.objectAt(0).get('name'), "Peter Wagenet", "the first record is 'Peter Wagenet'");
    equal(queryResults.objectAt(1).get('name'), "Brohuda Katz", "the second record is 'Brohuda Katz'");
  }));
});


text:
FROM python:3.7-slim

ENV GRPC_PYTHON_VERSION 1.13.0
RUN python -m pip install --upgrade pip
RUN pip install grpcio==${GRPC_PYTHON_VERSION} grpcio-tools==${GRPC_PYTHON_VERSION} grpcio-reflection==${GRPC_PYTHON_VERSION} grpcio-health-checking==${GRPC_PYTHON_VERSION} grpcio-testing==${GRPC_PYTHON_VERSION}


text:
/**
 * Created by antons on 4/24/15.
 */
angular.module('ui.bootstrap.demo', ['speedup.modal']);
angular.module('ui.bootstrap.demo').controller('ModalDemoCtrl', function ($scope, $modal, $log) {

    $scope.items = ['item1', 'item2', 'item3'];

    $scope.open = function () {

        var modalInstance = $modal.open({
            templateUrl: 'myModalContent.html',
            controller: 'ModalInstanceCtrl',
            settings:{
                width: 600,
                actions: ['close'],
                title: 'Super-druper',
                modal: true
            },
            resolve: {
                items: function () {
                    return $scope.items;
                }
            }
        });

        modalInstance.result.then(function (selectedItem) {
            $scope.selected = selectedItem;
        }, function () {
            $log.info('Modal dismissed at: ' + new Date());
        });
    };
});

// Please note that $modalInstance represents a modal window (instance) dependency.
// It is not the same as the $modal service used above.

angular.module('ui.bootstrap.demo').controller('ModalInstanceCtrl', function ($scope, $modalInstance, items) {

    $scope.items = items;
    $scope.selected = {
        item: $scope.items[0]
    };

    $scope.ok = function () {
        $modalInstance.close($scope.selected.item);
    };

    $scope.cancel = function () {
        $modalInstance.dismiss('cancel');
    };
});


text:
import sys

_ver = sys.version_info
#: Python 2.x?
is_py2 = (_ver[0] == 2)

#: Python 3.x?
is_py3 = (_ver[0] == 3)

if is_py2:
  from urllib import quote

elif is_py3:
  from urllib.parse import quote

class UnsupportedParameterClassException(Exception):
  def __init__(self, value, obj):
    self.value = value
    self.obj = obj
  def __str__(self):
    return repr(self.value) + " <" + repr(self.obj.__class__.__name__) +":" + repr(self.obj) +">"

class NestedQueryString:

  @classmethod
  def encode(cls, value, key = None):
    class_name = value.__class__
    if class_name == dict:
      result = []
      for k, v in value.items():
        result.append(cls.encode(v, cls.__append_key(key, k)))
      result = '&'.join(result)
      return result
    elif class_name == list:
      result = []
      for v in value:
        result.append(cls.encode(v, key+'[]'))
      result = '&'.join(result)
      return result
    elif class_name == str:
      return key + "=" + cls.__escape(value)
    elif class_name == int:
      return key + "=" + str(value)
    elif class_name == None:
      return ''
    else:
      raise UnsupportedParameterClassException('Unknown value class', value)

  @classmethod
  def __escape(cls, value):
    return quote(value)

  @classmethod
  def __append_key(cls, root_key, key):
    if root_key is None:
      return key
    else:
      return root_key + "["+key+"]"