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

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>Overview List (cloudsim 3.0.3 API)</title>
<meta name="date" content="2013-05-02">
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">

All Classes

Packages

org.cloudbus.cloudsim

org.cloudbus.cloudsim.core

org.cloudbus.cloudsim.core.predicates

org.cloudbus.cloudsim.distributions

org.cloudbus.cloudsim.lists

org.cloudbus.cloudsim.network

org.cloudbus.cloudsim.network.datacenter

org.cloudbus.cloudsim.power

org.cloudbus.cloudsim.power.lists

org.cloudbus.cloudsim.power.models

org.cloudbus.cloudsim.provisioners

org.cloudbus.cloudsim.util

redpajama_set_name: RedPajamaGithub


text:
<!doctype html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=1000">

    <title>BackgroundCheck</title>
    <meta name="description" content="Automatically switch to a darker or a lighter version of an element depending on the brightness of images behind it.">

    <link href='http://fonts.googleapis.com/css?family=Open+Sans:400italic,400,700' rel='stylesheet' type='text/css'>

    <link rel="stylesheet" href="normalize.css">
    <link rel="stylesheet" href="examples.css" >

BackgroundCheck

Automatically switch to a darker or a lighter version of an element depending on the brightness of images behind it.

Drag and Release elements over images

Text

        Github Project
        Download

Demos

Project Page

Slider

Fixed Nav

How it works

If an element overlaps any of the images, either .background--dark or .background--light is added to it. BackgroundCheck does not change an element's style — you must do so using CSS.

            More Info

Original Style

.label {
  color: blue;
}

Additional Styles

.label.background--light {
  color: black;
}

.label.background--dark {
  color: white;
}

How to use

BackgroundCheck.init({
  targets: '.ui'
});

Check all elements with a .ui class against all images on the page.

              More Info

BackgroundCheck.init({
  targets: '.ui',
  images: '.thumbnail'
});

Check all elements with a .ui class against all images with a .thumbnail class.

// All targets
BackgroundCheck.refresh();

// Specific target
BackgroundCheck.refresh(e.target);

Reprocess all or specific targets.

        Tweet

      @kennethcachia


text:
div.content {
  /* the display of content is enabled using jQuery so that the slideshow content won't display unless javascript is enabled. */
  display: none;
  float: right;
  width: 450px;}

div.content a:focus, div.content a:hover, div.content a:active {
  text-decoration: underline;}

div.controls {
  height: 23px;
  padding: 30px 0;
  width: 440px;
  float: left;}

div.controls a {
  padding: 5px 2px 5px 2px;}

div.ss-controls {
  float: left;}

div.nav-controls {
  float: right;}

div.slideshow-container {
  position: relative;
  clear: both;
  height: 450px; /* this should be set to be at least the height of the largest image in the slideshow */
  padding: 0;}

div.loader {
  position: absolute;
  top: 0;
  left: 0;
  background: url(loader_white.gif) no-repeat center;
  width: 450px;
  height: 450px; /* this should be set to be at least the height of the largest image in the slideshow */}

div.slideshow span.image-wrapper {
  display: block;
  position: absolute;
  top: 0;
  left: 0;}

div.slideshow a.advance-link {
  display: block;
  width: 450px;
  height: 450px; /* this should be set to be at least the height of the largest image in the slideshow */
  line-height: 0px; /* this should be set to be at least the height of the largest image in the slideshow */}

div.slideshow a.advance-link:hover, div.slideshow a.advance-link:active, div.slideshow a.advance-link:visited {
  text-decoration: none;}

div.slideshow img {
    height: 300px;
    width: 300px;
    vertical-align: top;}

div.caption-container {
  position: relative;
  clear: left;
  height: 75px;}

span.image-caption {
  display: block;
  position: absolute;
  width: 550px;
  top: 0;
  left: 0;}

div.caption {
  padding: 10px 0;
  width: 410px;}

div.image-title {
  font: normal 130% arial, sans-serif;}

div.navigation {
  /* the navigation style is set using jQuery so that the javascript specific styles won't be applied unless javascript is enabled. */}

#thumb-container {
  padding: 20px 0 0 25px;}

ul.thumbs {
  clear: both;
  margin: 0;
  padding: 0;}

ul.thumbs li {
  float: left;
  padding: 0;
  margin: 5px 10px 5px 0;
  list-style: none;}

a.thumb {
  padding: 2px;
  display: block;}

a.thumb:focus {
  outline: none;}

ul.thumbs img {
  border: none;
  display: block;}

div.pagination {
  float: left;
  clear: both;}

div.navigation div.top {
  margin-bottom: 12px;
  height: 11px;}

div.navigation div.bottom {
  margin-top: 12px;}

div.pagination a, div.pagination span.current, div.pagination span.ellipsis {
  display: block;
  float: left;
  margin-right: 2px;
  padding: 4px 10px 4px 10px;}

div.pagination a:hover {
  text-decoration: none;}

div.pagination span.current {
  font-weight: bold;}

div.pagination span.ellipsis {
  border: none;
  padding: 5px 0 3px 2px;}


text:
package org.elasticsearch.indices;

import org.elasticsearch.action.admin.indices.alias.Alias;
import org.elasticsearch.action.admin.indices.forcemerge.ForceMergeResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.client.Client;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.index.cache.request.RequestCacheStats;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.bucket.histogram.DateHistogramInterval;
import org.elasticsearch.search.aggregations.bucket.histogram.Histogram;
import org.elasticsearch.search.aggregations.bucket.histogram.Histogram.Bucket;
import org.elasticsearch.test.ESIntegTestCase;
import org.elasticsearch.test.hamcrest.ElasticsearchAssertions;
import org.joda.time.DateTimeZone;

import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;

import static org.elasticsearch.search.aggregations.AggregationBuilders.dateHistogram;
import static org.elasticsearch.search.aggregations.AggregationBuilders.dateRange;
import static org.elasticsearch.search.aggregations.AggregationBuilders.filter;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertSearchResponse;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThan;

public class IndicesRequestCacheIT extends ESIntegTestCase {

    // One of the primary purposes of the query cache is to cache aggs results
    public void testCacheAggs() throws Exception {
        Client client = client();
        assertAcked(client.admin().indices().prepareCreate("index")
                .addMapping("type", "f", "type=date")
                .setSettings(Settings.builder().put(IndicesRequestCache.INDEX_CACHE_REQUEST_ENABLED_SETTING.getKey(), true)).get());
        indexRandom(true,
                client.prepareIndex("index", "type").setSource("f", "2014-03-10T00:00:00.000Z"),
                client.prepareIndex("index", "type").setSource("f", "2014-05-13T00:00:00.000Z"));
        ensureSearchable("index");

        // This is not a random example: serialization with time zones writes shared strings
        // which used to not work well with the query cache because of the handles stream output
        // see #9500
        final SearchResponse r1 = client.prepareSearch("index").setSize(0).setSearchType(SearchType.QUERY_THEN_FETCH)
                .addAggregation(dateHistogram("histo").field("f").timeZone(DateTimeZone.forID("+01:00")).minDocCount(0)
                        .dateHistogramInterval(DateHistogramInterval.MONTH))
                .get();
        assertSearchResponse(r1);

        // The cached is actually used
        assertThat(client.admin().indices().prepareStats("index").setRequestCache(true).get().getTotal().getRequestCache()
            .getMemorySizeInBytes(), greaterThan(0L));

        for (int i = 0; i < 10; ++i) {
            final SearchResponse r2 = client.prepareSearch("index").setSize(0)
                    .setSearchType(SearchType.QUERY_THEN_FETCH).addAggregation(dateHistogram("histo").field("f")
                            .timeZone(DateTimeZone.forID("+01:00")).minDocCount(0).dateHistogramInterval(DateHistogramInterval.MONTH))
                    .get();
            assertSearchResponse(r2);
            Histogram h1 = r1.getAggregations().get("histo");
            Histogram h2 = r2.getAggregations().get("histo");
            final List<? extends Bucket> buckets1 = h1.getBuckets();
            final List<? extends Bucket> buckets2 = h2.getBuckets();
            assertEquals(buckets1.size(), buckets2.size());
            for (int j = 0; j < buckets1.size(); ++j) {
                final Bucket b1 = buckets1.get(j);
                final Bucket b2 = buckets2.get(j);
                assertEquals(b1.getKey(), b2.getKey());
                assertEquals(b1.getDocCount(), b2.getDocCount());
            }
        }
    }

    public void testQueryRewrite() throws Exception {
        Client client = client();
        assertAcked(client.admin().indices().prepareCreate("index").addMapping("type", "s", "type=date")
                .setSettings(Settings.builder().put(IndicesRequestCache.INDEX_CACHE_REQUEST_ENABLED_SETTING.getKey(), true)
                    .put(IndexMetaData.SETTING_NUMBER_OF_SHARDS, 5).put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, 0)).get());
        indexRandom(true, client.prepareIndex("index", "type", "1").setRouting("1").setSource("s", "2016-03-19"),
                client.prepareIndex("index", "type", "2").setRouting("1").setSource("s", "2016-03-20"),
                client.prepareIndex("index", "type", "3").setRouting("1").setSource("s", "2016-03-21"),
                client.prepareIndex("index", "type", "4").setRouting("2").setSource("s", "2016-03-22"),
                client.prepareIndex("index", "type", "5").setRouting("2").setSource("s", "2016-03-23"),
                client.prepareIndex("index", "type", "6").setRouting("2").setSource("s", "2016-03-24"),
                client.prepareIndex("index", "type", "7").setRouting("3").setSource("s", "2016-03-25"),
                client.prepareIndex("index", "type", "8").setRouting("3").setSource("s", "2016-03-26"),
                client.prepareIndex("index", "type", "9").setRouting("3").setSource("s", "2016-03-27"));
        ensureSearchable("index");
        assertCacheState(client, "index", 0, 0);

        // Force merge the index to ensure there can be no background merges during the subsequent searches that would invalidate the cache
        ForceMergeResponse forceMergeResponse = client.admin().indices().prepareForceMerge("index").setFlush(true).get();
        ElasticsearchAssertions.assertAllSuccessful(forceMergeResponse);
        refresh();
        ensureSearchable("index");

        assertCacheState(client, "index", 0, 0);

        final SearchResponse r1 = client.prepareSearch("index").setSearchType(SearchType.QUERY_THEN_FETCH).setSize(0)
                .setQuery(QueryBuilders.rangeQuery("s").gte("2016-03-19").lte("2016-03-25")).setPreFilterShardSize(Integer.MAX_VALUE).get();
        ElasticsearchAssertions.assertAllSuccessful(r1);
        assertThat(r1.getHits().getTotalHits(), equalTo(7L));
        assertCacheState(client, "index", 0, 5);

        final SearchResponse r2 = client.prepareSearch("index").setSearchType(SearchType.QUERY_THEN_FETCH).setSize(0)
                .setQuery(QueryBuilders.rangeQuery("s").gte("2016-03-20").lte("2016-03-26"))
            .setPreFilterShardSize(Integer.MAX_VALUE).get();
        ElasticsearchAssertions.assertAllSuccessful(r2);
        assertThat(r2.getHits().getTotalHits(), equalTo(7L));
        assertCacheState(client, "index", 3, 7);

        final SearchResponse r3 = client.prepareSearch("index").setSearchType(SearchType.QUERY_THEN_FETCH).setSize(0)
                .setQuery(QueryBuilders.rangeQuery("s").gte("2016-03-21").lte("2016-03-27")).setPreFilterShardSize(Integer.MAX_VALUE)
            .get();
        ElasticsearchAssertions.assertAllSuccessful(r3);
        assertThat(r3.getHits().getTotalHits(), equalTo(7L));
        assertCacheState(client, "index", 6, 9);
    }

    public void testQueryRewriteMissingValues() throws Exception {
        Client client = client();
        assertAcked(client.admin().indices().prepareCreate("index").addMapping("type", "s", "type=date")
                .setSettings(Settings.builder().put(IndicesRequestCache.INDEX_CACHE_REQUEST_ENABLED_SETTING.getKey(), true)
                    .put(IndexMetaData.SETTING_NUMBER_OF_SHARDS, 1).put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, 0)).get());
        indexRandom(true, client.prepareIndex("index", "type", "1").setSource("s", "2016-03-19"),
                client.prepareIndex("index", "type", "2").setSource("s", "2016-03-20"),
                client.prepareIndex("index", "type", "3").setSource("s", "2016-03-21"),
                client.prepareIndex("index", "type", "4").setSource("s", "2016-03-22"),
                client.prepareIndex("index", "type", "5").setSource("s", "2016-03-23"),
                client.prepareIndex("index", "type", "6").setSource("s", "2016-03-24"),
                client.prepareIndex("index", "type", "7").setSource("other", "value"),
                client.prepareIndex("index", "type", "8").setSource("s", "2016-03-26"),
                client.prepareIndex("index", "type", "9").setSource("s", "2016-03-27"));
        ensureSearchable("index");
        assertCacheState(client, "index", 0, 0);

        // Force merge the index to ensure there can be no background merges during the subsequent searches that would invalidate the cache
        ForceMergeResponse forceMergeResponse = client.admin().indices().prepareForceMerge("index").setFlush(true).get();
        ElasticsearchAssertions.assertAllSuccessful(forceMergeResponse);
        refresh();
        ensureSearchable("index");

        assertCacheState(client, "index", 0, 0);

        final SearchResponse r1 = client.prepareSearch("index").setSearchType(SearchType.QUERY_THEN_FETCH).setSize(0)
                .setQuery(QueryBuilders.rangeQuery("s").gte("2016-03-19").lte("2016-03-28")).get();
        ElasticsearchAssertions.assertAllSuccessful(r1);
        assertThat(r1.getHits().getTotalHits(), equalTo(8L));
        assertCacheState(client, "index", 0, 1);

        final SearchResponse r2 = client.prepareSearch("index").setSearchType(SearchType.QUERY_THEN_FETCH).setSize(0)
                .setQuery(QueryBuilders.rangeQuery("s").gte("2016-03-19").lte("2016-03-28")).get();
        ElasticsearchAssertions.assertAllSuccessful(r2);
        assertThat(r2.getHits().getTotalHits(), equalTo(8L));
        assertCacheState(client, "index", 1, 1);

        final SearchResponse r3 = client.prepareSearch("index").setSearchType(SearchType.QUERY_THEN_FETCH).setSize(0)
                .setQuery(QueryBuilders.rangeQuery("s").gte("2016-03-19").lte("2016-03-28")).get();
        ElasticsearchAssertions.assertAllSuccessful(r3);
        assertThat(r3.getHits().getTotalHits(), equalTo(8L));
        assertCacheState(client, "index", 2, 1);
    }

    public void testQueryRewriteDates() throws Exception {
        Client client = client();
        assertAcked(client.admin().indices().prepareCreate("index").addMapping("type", "d", "type=date")
                .setSettings(Settings.builder().put(IndicesRequestCache.INDEX_CACHE_REQUEST_ENABLED_SETTING.getKey(), true)
                        .put(IndexMetaData.SETTING_NUMBER_OF_SHARDS, 1).put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, 0)).get());
        indexRandom(true, client.prepareIndex("index", "type", "1").setSource("d", "2014-01-01T00:00:00"),
                client.prepareIndex("index", "type", "2").setSource("d", "2014-02-01T00:00:00"),
                client.prepareIndex("index", "type", "3").setSource("d", "2014-03-01T00:00:00"),
                client.prepareIndex("index", "type", "4").setSource("d", "2014-04-01T00:00:00"),
                client.prepareIndex("index", "type", "5").setSource("d", "2014-05-01T00:00:00"),
                client.prepareIndex("index", "type", "6").setSource("d", "2014-06-01T00:00:00"),
                client.prepareIndex("index", "type", "7").setSource("d", "2014-07-01T00:00:00"),
                client.prepareIndex("index", "type", "8").setSource("d", "2014-08-01T00:00:00"),
                client.prepareIndex("index", "type", "9").setSource("d", "2014-09-01T00:00:00"));
        ensureSearchable("index");
        assertCacheState(client, "index", 0, 0);

        // Force merge the index to ensure there can be no background merges during the subsequent searches that would invalidate the cache
        ForceMergeResponse forceMergeResponse = client.admin().indices().prepareForceMerge("index").setFlush(true).get();
        ElasticsearchAssertions.assertAllSuccessful(forceMergeResponse);
        refresh();
        ensureSearchable("index");

        assertCacheState(client, "index", 0, 0);

        final SearchResponse r1 = client.prepareSearch("index").setSearchType(SearchType.QUERY_THEN_FETCH).setSize(0)
                .setQuery(QueryBuilders.rangeQuery("d").gte("2013-01-01T00:00:00").lte("now"))
                .get();
        ElasticsearchAssertions.assertAllSuccessful(r1);
        assertThat(r1.getHits().getTotalHits(), equalTo(9L));
        assertCacheState(client, "index", 0, 1);

        final SearchResponse r2 = client.prepareSearch("index").setSearchType(SearchType.QUERY_THEN_FETCH).setSize(0)
                .setQuery(QueryBuilders.rangeQuery("d").gte("2013-01-01T00:00:00").lte("now"))
                .get();
        ElasticsearchAssertions.assertAllSuccessful(r2);
        assertThat(r2.getHits().getTotalHits(), equalTo(9L));
        assertCacheState(client, "index", 1, 1);

        final SearchResponse r3 = client.prepareSearch("index").setSearchType(SearchType.QUERY_THEN_FETCH).setSize(0)
                .setQuery(QueryBuilders.rangeQuery("d").gte("2013-01-01T00:00:00").lte("now"))
                .get();
        ElasticsearchAssertions.assertAllSuccessful(r3);
        assertThat(r3.getHits().getTotalHits(), equalTo(9L));
        assertCacheState(client, "index", 2, 1);
    }

    public void testQueryRewriteDatesWithNow() throws Exception {
        Client client = client();
        Settings settings = Settings.builder().put(IndicesRequestCache.INDEX_CACHE_REQUEST_ENABLED_SETTING.getKey(), true)
            .put(IndexMetaData.SETTING_NUMBER_OF_SHARDS, 1).put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, 0).build();
        assertAcked(client.admin().indices().prepareCreate("index-1").addMapping("type", "d", "type=date")
                .setSettings(settings).get());
        assertAcked(client.admin().indices().prepareCreate("index-2").addMapping("type", "d", "type=date")
                .setSettings(settings).get());
        assertAcked(client.admin().indices().prepareCreate("index-3").addMapping("type", "d", "type=date")
                .setSettings(settings).get());
        ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC);
        indexRandom(true, client.prepareIndex("index-1", "type", "1").setSource("d", now),
                client.prepareIndex("index-1", "type", "2").setSource("d", now.minusDays(1)),
                client.prepareIndex("index-1", "type", "3").setSource("d", now.minusDays(2)),
                client.prepareIndex("index-2", "type", "4").setSource("d", now.minusDays(3)),
                client.prepareIndex("index-2", "type", "5").setSource("d", now.minusDays(4)),
                client.prepareIndex("index-2", "type", "6").setSource("d", now.minusDays(5)),
                client.prepareIndex("index-3", "type", "7").setSource("d", now.minusDays(6)),
                client.prepareIndex("index-3", "type", "8").setSource("d", now.minusDays(7)),
                client.prepareIndex("index-3", "type", "9").setSource("d", now.minusDays(8)));
        ensureSearchable("index-1", "index-2", "index-3");
        assertCacheState(client, "index-1", 0, 0);
        assertCacheState(client, "index-2", 0, 0);
        assertCacheState(client, "index-3", 0, 0);

        // Force merge the index to ensure there can be no background merges during the subsequent searches that would invalidate the cache
        ForceMergeResponse forceMergeResponse = client.admin().indices().prepareForceMerge("index-1", "index-2", "index-3").setFlush(true)
                .get();
        ElasticsearchAssertions.assertAllSuccessful(forceMergeResponse);
        refresh();
        ensureSearchable("index-1", "index-2", "index-3");

        assertCacheState(client, "index-1", 0, 0);
        assertCacheState(client, "index-2", 0, 0);
        assertCacheState(client, "index-3", 0, 0);

        final SearchResponse r1 = client.prepareSearch("index-*").setSearchType(SearchType.QUERY_THEN_FETCH).setSize(0)
                .setQuery(QueryBuilders.rangeQuery("d").gte("now-7d/d").lte("now")).get();
        ElasticsearchAssertions.assertAllSuccessful(r1);
        assertThat(r1.getHits().getTotalHits(), equalTo(8L));
        assertCacheState(client, "index-1", 0, 1);
        assertCacheState(client, "index-2", 0, 1);
        // Because the query will INTERSECT with the 3rd index it will not be
        // rewritten and will still contain `now` so won't be recorded as a
        // cache miss or cache hit since queries containing now can't be cached
        assertCacheState(client, "index-3", 0, 0);

        final SearchResponse r2 = client.prepareSearch("index-*").setSearchType(SearchType.QUERY_THEN_FETCH).setSize(0)
                .setQuery(QueryBuilders.rangeQuery("d").gte("now-7d/d").lte("now")).get();
        ElasticsearchAssertions.assertAllSuccessful(r2);
        assertThat(r2.getHits().getTotalHits(), equalTo(8L));
        assertCacheState(client, "index-1", 1, 1);
        assertCacheState(client, "index-2", 1, 1);
        assertCacheState(client, "index-3", 0, 0);

        final SearchResponse r3 = client.prepareSearch("index-*").setSearchType(SearchType.QUERY_THEN_FETCH).setSize(0)
                .setQuery(QueryBuilders.rangeQuery("d").gte("now-7d/d").lte("now")).get();
        ElasticsearchAssertions.assertAllSuccessful(r3);
        assertThat(r3.getHits().getTotalHits(), equalTo(8L));
        assertCacheState(client, "index-1", 2, 1);
        assertCacheState(client, "index-2", 2, 1);
        assertCacheState(client, "index-3", 0, 0);
    }

    public void testCanCache() throws Exception {
        Client client = client();
        Settings settings = Settings.builder().put(IndicesRequestCache.INDEX_CACHE_REQUEST_ENABLED_SETTING.getKey(), true)
            .put(IndexMetaData.SETTING_NUMBER_OF_SHARDS, 2).put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, 0).build();
        assertAcked(client.admin().indices().prepareCreate("index").addMapping("type", "s", "type=date")
                .setSettings(settings)
                .get());
        indexRandom(true, client.prepareIndex("index", "type", "1").setRouting("1").setSource("s", "2016-03-19"),
                client.prepareIndex("index", "type", "2").setRouting("1").setSource("s", "2016-03-20"),
                client.prepareIndex("index", "type", "3").setRouting("1").setSource("s", "2016-03-21"),
                client.prepareIndex("index", "type", "4").setRouting("2").setSource("s", "2016-03-22"),
                client.prepareIndex("index", "type", "5").setRouting("2").setSource("s", "2016-03-23"),
                client.prepareIndex("index", "type", "6").setRouting("2").setSource("s", "2016-03-24"),
                client.prepareIndex("index", "type", "7").setRouting("3").setSource("s", "2016-03-25"),
                client.prepareIndex("index", "type", "8").setRouting("3").setSource("s", "2016-03-26"),
                client.prepareIndex("index", "type", "9").setRouting("3").setSource("s", "2016-03-27"));
        ensureSearchable("index");
        assertCacheState(client, "index", 0, 0);

        // Force merge the index to ensure there can be no background merges during the subsequent searches that would invalidate the cache
        ForceMergeResponse forceMergeResponse = client.admin().indices().prepareForceMerge("index").setFlush(true).get();
        ElasticsearchAssertions.assertAllSuccessful(forceMergeResponse);
        refresh();
        ensureSearchable("index");

        assertCacheState(client, "index", 0, 0);

        // If size > 0 we should no cache by default
        final SearchResponse r1 = client.prepareSearch("index").setSearchType(SearchType.QUERY_THEN_FETCH).setSize(1)
                .setQuery(QueryBuilders.rangeQuery("s").gte("2016-03-19").lte("2016-03-25")).get();
        ElasticsearchAssertions.assertAllSuccessful(r1);
        assertThat(r1.getHits().getTotalHits(), equalTo(7L));
        assertCacheState(client, "index", 0, 0);

        // If search type is DFS_QUERY_THEN_FETCH we should not cache
        final SearchResponse r2 = client.prepareSearch("index").setSearchType(SearchType.DFS_QUERY_THEN_FETCH).setSize(0)
                .setQuery(QueryBuilders.rangeQuery("s").gte("2016-03-20").lte("2016-03-26")).get();
        ElasticsearchAssertions.assertAllSuccessful(r2);
        assertThat(r2.getHits().getTotalHits(), equalTo(7L));
        assertCacheState(client, "index", 0, 0);

        // If search type is DFS_QUERY_THEN_FETCH we should not cache even if
        // the cache flag is explicitly set on the request
        final SearchResponse r3 = client.prepareSearch("index").setSearchType(SearchType.DFS_QUERY_THEN_FETCH).setSize(0)
                .setRequestCache(true).setQuery(QueryBuilders.rangeQuery("s").gte("2016-03-20").lte("2016-03-26")).get();
        ElasticsearchAssertions.assertAllSuccessful(r3);
        assertThat(r3.getHits().getTotalHits(), equalTo(7L));
        assertCacheState(client, "index", 0, 0);

        // If the request has an non-filter aggregation containing now we should not cache
        final SearchResponse r5 = client.prepareSearch("index").setSearchType(SearchType.QUERY_THEN_FETCH).setSize(0)
                .setRequestCache(true).setQuery(QueryBuilders.rangeQuery("s").gte("2016-03-20").lte("2016-03-26"))
                .addAggregation(dateRange("foo").field("s").addRange("now-10y", "now")).get();
        ElasticsearchAssertions.assertAllSuccessful(r5);
        assertThat(r5.getHits().getTotalHits(), equalTo(7L));
        assertCacheState(client, "index", 0, 0);

        // If size > 1 and cache flag is set on the request we should cache
        final SearchResponse r6 = client.prepareSearch("index").setSearchType(SearchType.QUERY_THEN_FETCH).setSize(1)
                .setRequestCache(true).setQuery(QueryBuilders.rangeQuery("s").gte("2016-03-21").lte("2016-03-27")).get();
        ElasticsearchAssertions.assertAllSuccessful(r6);
        assertThat(r6.getHits().getTotalHits(), equalTo(7L));
        assertCacheState(client, "index", 0, 2);

        // If the request has a filter aggregation containing now we should cache since it gets rewritten
        final SearchResponse r4 = client.prepareSearch("index").setSearchType(SearchType.QUERY_THEN_FETCH).setSize(0)
                .setRequestCache(true).setQuery(QueryBuilders.rangeQuery("s").gte("2016-03-20").lte("2016-03-26"))
                .addAggregation(filter("foo", QueryBuilders.rangeQuery("s").from("now-10y").to("now"))).get();
        ElasticsearchAssertions.assertAllSuccessful(r4);
        assertThat(r4.getHits().getTotalHits(), equalTo(7L));
        assertCacheState(client, "index", 0, 4);
    }

    public void testCacheWithFilteredAlias() {
        Client client = client();
        Settings settings = Settings.builder().put(IndicesRequestCache.INDEX_CACHE_REQUEST_ENABLED_SETTING.getKey(), true)
            .put(IndexMetaData.SETTING_NUMBER_OF_SHARDS, 1).put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, 0).build();
        assertAcked(client.admin().indices().prepareCreate("index").addMapping("type", "created_at", "type=date")
            .setSettings(settings)
            .addAlias(new Alias("last_week").filter(QueryBuilders.rangeQuery("created_at").gte("now-7d/d")))
            .get());
        ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC);
        client.prepareIndex("index", "type", "1").setRouting("1").setSource("created_at",
            DateTimeFormatter.ISO_LOCAL_DATE.format(now)).get();
        // Force merge the index to ensure there can be no background merges during the subsequent searches that would invalidate the cache
        ForceMergeResponse forceMergeResponse = client.admin().indices().prepareForceMerge("index").setFlush(true).get();
        ElasticsearchAssertions.assertAllSuccessful(forceMergeResponse);
        refresh();

        assertCacheState(client, "index", 0, 0);

        SearchResponse r1 = client.prepareSearch("index").setSearchType(SearchType.QUERY_THEN_FETCH).setSize(0)
            .setQuery(QueryBuilders.rangeQuery("created_at").gte("now-7d/d")).get();
        ElasticsearchAssertions.assertAllSuccessful(r1);
        assertThat(r1.getHits().getTotalHits(), equalTo(1L));
        assertCacheState(client, "index", 0, 1);

        r1 = client.prepareSearch("index").setSearchType(SearchType.QUERY_THEN_FETCH).setSize(0)
            .setQuery(QueryBuilders.rangeQuery("created_at").gte("now-7d/d")).get();
        ElasticsearchAssertions.assertAllSuccessful(r1);
        assertThat(r1.getHits().getTotalHits(), equalTo(1L));
        assertCacheState(client, "index", 1, 1);

        r1 = client.prepareSearch("last_week").setSearchType(SearchType.QUERY_THEN_FETCH).setSize(0).get();
        ElasticsearchAssertions.assertAllSuccessful(r1);
        assertThat(r1.getHits().getTotalHits(), equalTo(1L));
        assertCacheState(client, "index", 1, 2);

        r1 = client.prepareSearch("last_week").setSearchType(SearchType.QUERY_THEN_FETCH).setSize(0).get();
        ElasticsearchAssertions.assertAllSuccessful(r1);
        assertThat(r1.getHits().getTotalHits(), equalTo(1L));
        assertCacheState(client, "index", 2, 2);
    }

    private static void assertCacheState(Client client, String index, long expectedHits, long expectedMisses) {
        RequestCacheStats requestCacheStats = client.admin().indices().prepareStats(index).setRequestCache(true).get().getTotal()
                .getRequestCache();
        // Check the hit count and miss count together so if they are not
        // correct we can see both values
        assertEquals(Arrays.asList(expectedHits, expectedMisses),
                Arrays.asList(requestCacheStats.getHitCount(), requestCacheStats.getMissCount()));
    }

}


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Syll. fung. (Abellini) 3: 173 (1884)

#### Original name
Melanomma fuscidulum Sacc., 1878

### Remarks
null


text:
require 'rex/text'
require 'rex/arch'
require 'msf/core/framework'

module Rex
module Exploitation

class CmdStagerBourne < CmdStagerBase

  def initialize(exe)
    super

    @var_encoded = Rex::Text.rand_text_alpha(5)
    @var_decoded = Rex::Text.rand_text_alpha(5)
  end

  def generate(opts = {})
    opts[:temp] = opts[:temp] || '/tmp/'
    opts[:temp] = opts[:temp].gsub(/'/, "\\\\'")
    opts[:temp] = opts[:temp].gsub(/ /, "\\ ")
    super
  end

  #
  # Override just to set the extra byte count
  #
  def generate_cmds(opts)
    # Set the start/end of the commands here (vs initialize) so we have @tempdir
    @cmd_start = "echo -n "
    @cmd_end   = ">>#{@tempdir}#{@var_encoded}.b64"
    xtra_len = @cmd_start.length + @cmd_end.length + 1
    opts.merge!({ :extra => xtra_len })
    super
  end

  #
  # Simple base64...
  #
  def encode_payload(opts)
    Rex::Text.encode_base64(@exe)
  end

  #
  # Combine the parts of the encoded file with the stuff that goes
  # before / after it.
  #
  def parts_to_commands(parts, opts)

    cmds = []
    parts.each do |p|
      cmd = ''
      cmd << @cmd_start
      cmd << p
      cmd << @cmd_end
      cmds << cmd
    end

    cmds
  end

  #
  # Generate the commands that will decode the file we just created
  #
  def generate_cmds_decoder(opts)
    decoders = [
      "base64 --decode -",
      "openssl enc -d -A -base64 -in /dev/stdin",
      "python -c 'import sys, base64; print base64.standard_b64decode(sys.stdin.read());'",
      "perl -MMIME::Base64 -ne 'print decode_base64($_)'"
    ]
    decoder_cmd = []
    decoders.each do |cmd|
      binary = cmd.split(' ')[0]
      decoder_cmd << "(which #{binary} >&2 && #{cmd})"
    end
    decoder_cmd = decoder_cmd.join(" || ")
    decoder_cmd = "(" << decoder_cmd << ") 2> /dev/null > #{@tempdir}#{@var_decoded}.bin < #{@tempdir}#{@var_encoded}.b64"
    [ decoder_cmd ]
  end

  def compress_commands(cmds, opts)
    # Make it all happen
    cmds << "chmod +x #{@tempdir}#{@var_decoded}.bin"
    cmds << "#{@tempdir}#{@var_decoded}.bin"

    # Clean up after unless requested not to..
    if (not opts[:nodelete])
      cmds << "rm -f #{@tempdir}#{@var_decoded}.bin"
      cmds << "rm -f #{@tempdir}#{@var_encoded}.b64"
    end

    super
  end

  def cmd_concat_operator
    " ; "
  end

end
end
end


text:
require 'rspec/core'
require 'generator-spec'
# require 'spec_helper'

RSpec::Generator::Require.root_dir = 'generator_spec/fixtures'

require_generator :model

describe 'model_generator' do
  use_orm :mongoid

  # before do
  #   setup_generator :model do
  #     tests ModelGenerator
  #   end
  # end
  #
  # before :each do
  #   remove_model :account
  # end
  #
  # after :each do
  #   remove_model :account
  # end
  #
  it "should not work without an Account model file" do
    1.should == 1
    # with_generator do |g|
    #   g.run_generator :account.args
    #   g.should_not generate_model_file :account
    # end
  end
  #
  # it "should decorate an existing Account model file with include Canable:Ables" do
  #   create_model :account do
  #     'hello'
  #   end
  #   with_generator do |g|
  #     # g.run_generator :account.args
  #
  #     g.should_not generate_model_file :user
  #     g.should_not generate_controller_file :user
  #
  #     g.should generate_model_file :account do |content|
  #       content.should include_module 'Canable::Ables'
  #     end
  #   end
  # end
  #
  # it "should not have generated other things!" do
  #   with_generator do |g|
  #     g.should_not generate_model_file :user
  #     g.should_not generate_controller_file :user
  #   end
  # end
end


text:
package org.apache.activemq.artemis.tests.integration.server;

import javax.jms.ConnectionFactory;
import javax.jms.JMSContext;
import java.util.UUID;

import org.apache.activemq.artemis.api.core.RoutingType;
import org.apache.activemq.artemis.api.core.SimpleString;
import org.apache.activemq.artemis.core.server.ActiveMQServer;
import org.apache.activemq.artemis.core.server.AddressQueryResult;
import org.apache.activemq.artemis.core.server.impl.AddressInfo;
import org.apache.activemq.artemis.core.settings.impl.AddressSettings;
import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory;
import org.apache.activemq.artemis.tests.util.ActiveMQTestBase;
import org.junit.Before;
import org.junit.Test;

public class AddressQueryTest extends ActiveMQTestBase {

   private ActiveMQServer server;

   @Override
   @Before
   public void setUp() throws Exception {
      super.setUp();
      server = createServer(false);
      server.start();
   }

   @Test
   public void testAddressQueryDefaultsOnStaticAddress() throws Exception {
      SimpleString addressName = SimpleString.toSimpleString(UUID.randomUUID().toString());
      server.addAddressInfo(new AddressInfo(addressName));
      AddressQueryResult addressQueryResult = server.addressQuery(addressName);
      assertTrue(addressQueryResult.isExists());
      assertFalse(addressQueryResult.getRoutingTypes().contains(RoutingType.ANYCAST));
      assertFalse(addressQueryResult.getRoutingTypes().contains(RoutingType.MULTICAST));
      assertEquals(addressName, addressQueryResult.getName());
      assertTrue(addressQueryResult.isAutoCreateAddresses());
      assertEquals(-1, addressQueryResult.getDefaultMaxConsumers());
      assertFalse(addressQueryResult.isAutoCreated());
      assertFalse(addressQueryResult.isDefaultPurgeOnNoConsumers());
   }

   @Test
   public void testAddressQueryOnStaticAddressWithFQQN() throws Exception {
      SimpleString addressName = SimpleString.toSimpleString(UUID.randomUUID().toString());
      SimpleString fqqn = addressName.concat("::").concat(SimpleString.toSimpleString(UUID.randomUUID().toString()));
      server.addAddressInfo(new AddressInfo(fqqn));
      assertEquals(addressName, server.addressQuery(addressName).getName());
      assertEquals(addressName, server.addressQuery(fqqn).getName());
   }

   @Test
   public void testAddressQueryNonExistentAddress() throws Exception {
      SimpleString addressName = SimpleString.toSimpleString(UUID.randomUUID().toString());
      AddressQueryResult addressQueryResult = server.addressQuery(addressName);
      assertFalse(addressQueryResult.isExists());
      assertEquals(addressName, addressQueryResult.getName());
   }

   @Test
   public void testAddressQueryNonExistentAddressWithFQQN() throws Exception {
      SimpleString addressName = SimpleString.toSimpleString(UUID.randomUUID().toString());
      SimpleString fqqn = addressName.concat("::").concat(SimpleString.toSimpleString(UUID.randomUUID().toString()));
      AddressQueryResult addressQueryResult = server.addressQuery(fqqn);
      assertFalse(addressQueryResult.isExists());
      assertEquals(addressName, addressQueryResult.getName());
   }

   @Test
   public void testAddressQueryNonDefaultsOnStaticAddress() throws Exception {
      SimpleString addressName = SimpleString.toSimpleString(UUID.randomUUID().toString());
      server.getAddressSettingsRepository().addMatch(addressName.toString(), new AddressSettings().setAutoCreateAddresses(false).setDefaultMaxConsumers(1).setDefaultPurgeOnNoConsumers(true));
      server.addAddressInfo(new AddressInfo(addressName).addRoutingType(RoutingType.ANYCAST));
      AddressQueryResult addressQueryResult = server.addressQuery(addressName);
      assertTrue(addressQueryResult.isExists());
      assertTrue(addressQueryResult.getRoutingTypes().contains(RoutingType.ANYCAST));
      assertFalse(addressQueryResult.getRoutingTypes().contains(RoutingType.MULTICAST));
      assertEquals(addressName, addressQueryResult.getName());
      assertFalse(addressQueryResult.isAutoCreateAddresses());
      assertEquals(1, addressQueryResult.getDefaultMaxConsumers());
      assertFalse(addressQueryResult.isAutoCreated());
      assertTrue(addressQueryResult.isDefaultPurgeOnNoConsumers());
   }

   @Test
   public void testAddressQueryDefaultsOnAutoCreatedAddress() throws Exception {
      SimpleString addressName = SimpleString.toSimpleString(UUID.randomUUID().toString());
      server.getAddressSettingsRepository().addMatch(addressName.toString(), new AddressSettings());
      ConnectionFactory cf = new ActiveMQConnectionFactory("vm://0");
      JMSContext c = cf.createContext();
      c.createProducer().send(c.createTopic(addressName.toString()), c.createMessage());
      AddressQueryResult addressQueryResult = server.addressQuery(addressName);
      assertTrue(addressQueryResult.isExists());
      assertFalse(addressQueryResult.getRoutingTypes().contains(RoutingType.ANYCAST));
      assertTrue(addressQueryResult.getRoutingTypes().contains(RoutingType.MULTICAST));
      assertEquals(addressName, addressQueryResult.getName());
      assertTrue(addressQueryResult.isAutoCreateAddresses());
      assertEquals(-1, addressQueryResult.getDefaultMaxConsumers());
      assertTrue(addressQueryResult.isAutoCreated());
      assertFalse(addressQueryResult.isDefaultPurgeOnNoConsumers());
   }

   @Test
   public void testAddressQueryOnAutoCreatedAddressWithFQQN() throws Exception {
      SimpleString addressName = SimpleString.toSimpleString(UUID.randomUUID().toString());
      SimpleString fqqn = addressName.concat("::").concat(SimpleString.toSimpleString(UUID.randomUUID().toString()));
      ConnectionFactory cf = new ActiveMQConnectionFactory("vm://0");
      JMSContext c = cf.createContext();
      c.createProducer().send(c.createTopic(fqqn.toString()), c.createMessage());
      assertEquals(addressName, server.addressQuery(addressName).getName());
      assertEquals(addressName, server.addressQuery(fqqn).getName());
   }

   @Test
   public void testAddressQueryNonDefaultsOnAutoCreatedAddress() throws Exception {
      SimpleString addressName = SimpleString.toSimpleString(UUID.randomUUID().toString());
      server.getAddressSettingsRepository().addMatch(addressName.toString(), new AddressSettings().setAutoCreateAddresses(true).setDefaultMaxConsumers(1).setDefaultPurgeOnNoConsumers(true));
      ConnectionFactory cf = new ActiveMQConnectionFactory("vm://0");
      JMSContext c = cf.createContext();
      c.createProducer().send(c.createTopic(addressName.toString()), c.createMessage());
      AddressQueryResult addressQueryResult = server.addressQuery(addressName);
      assertTrue(addressQueryResult.isExists());
      assertTrue(addressQueryResult.getRoutingTypes().contains(RoutingType.MULTICAST));
      assertEquals(addressName, addressQueryResult.getName());
      assertTrue(addressQueryResult.isAutoCreateAddresses());
      assertEquals(1, addressQueryResult.getDefaultMaxConsumers());
      assertTrue(addressQueryResult.isAutoCreated());
      assertTrue(addressQueryResult.isDefaultPurgeOnNoConsumers());
   }
}


text:
@interface NSString (Utils)

+ (NSString*) stringFromDeviceToken:(NSData*) deviceToken;

- (NSString*) trim;

- (BOOL) isEmail;

-(NSString*) urlEncode;
-(NSString*) urlEncodeUsingEncoding;
-(NSString*) urlEncodeUsingEncoding:(NSStringEncoding)encoding;

@end


text:
PAD.TextBlock = function(insert_index) {
    PAD.Block.call(this, insert_index);
    // Position of the caret, this is needed for splitting a text block
    // when inserting new blocks.
    this.caret = 0;
}
PAD.TextBlock.prototype = Object.create(PAD.Block.prototype);
PAD.TextBlock.prototype.constructor = PAD.TextBlock;
PAD.TextBlock.block_name = "Text";
PAD.TextBlock.document_block = false;
PAD.block_types['text'] = PAD.TextBlock;

PAD.TextBlock.from_json = function(json) {
    var text_block = new PAD.TextBlock(json['position']);
    text_block.id = json['id'];
    text_block.dom.innerHTML = json['content'];
    return text_block;
}

PAD.TextBlock.prototype.create_dom = function() {
    this.dom = document.createElement('div');
    this.dom.setAttribute('class', 'block text');
    this.dom.setAttribute('contenteditable', true);
    this.dom.onfocus = this.focus.bind(this);
    this.dom.onblur = this.onblur.bind(this);
}

PAD.TextBlock.prototype.serialize = function () {
    var data = {
        'id': this.id,
        'type': 'text',
        'content': this.dom.innerHTML,
        'position': this.getIndex()
    }
    return data;
}

PAD.TextBlock.prototype.focus = function() {
    if (PAD.current_block == this) {
        // Call came in from on_focus event while block was already
        // focused.
        return;
    }

    // Grab index of previously focused block.
    var prev_index = 0;
    if (typeof PAD.current_block !== 'undefined') {
        prev_index = PAD.current_block.getIndex();
    }
    PAD.Block.prototype.focus.bind(this)(); // super
    this.dom.focus();

    if (prev_index > this.getIndex()) {
        // If coming from a block below this one, place the caret at the end
        // of the input.
        var range = document.createRange();
        var sel = window.getSelection();
        range.setStart(this.dom, 1);
        range.collapse(true);
        sel.removeAllRanges();
        sel.addRange(range);
    }
}

PAD.TextBlock.prototype.blur = function() {
    this.dom.blur();
}

PAD.TextBlock.prototype.onblur = function() {
    // Grab the position of the caret before the selection gets destroyed.
    var sel = window.getSelection();
    this.caret = sel.baseOffset;
}

PAD.TextBlock.prototype.on_key_down = function(e) {
    switch (e.which) {
    case PAD.RETURN_KEY:
        // Insert newline
        var height = this.dom.clientHeight;
        document.execCommand('insertHTML', false, '\n');
        if (height == this.dom.clientHeight) {
            // Sometimes we need to insert two newlines
            document.execCommand('insertHTML', false, '\n');
        }
        e.preventDefault();
        break;

    case PAD.UP_KEY:
        var sel = window.getSelection();
        if (sel.type == "Caret" && sel.baseOffset == 0) {
            // Make the above block active
            if (this.getIndex() != 0) {
                PAD.blocks[this.getIndex()-1].focus();
            }
            e.preventDefault();
        }
        break;

    case PAD.DOWN_KEY:
        var sel = window.getSelection();
        if (sel.type == "Caret" &&
                this.getIndex() != PAD.blocks.length-1 &&
                (sel.baseOffset == this.dom.innerText.length ||
                (sel.baseOffset == this.dom.innerText.length-1 &&
                this.dom.innerText[sel.baseOffset] == '\n'))) {
            // Make the block below active
            PAD.blocks[this.getIndex()+1].focus();
            e.preventDefault();
            break;
        }
    }
}


text: http_load -parallel 10 -s 10 url.list.txt


text:
Install-VisualStudio `
    -PackageName 'visualstudio2017testcontroller' `
    -ApplicationName 'Microsoft Visual Studio Test Controller 2017' `
    -Url 'https://download.visualstudio.microsoft.com/download/pr/473f1a59-e5bc-4332-8f76-5ff45df9cd24/84db284c6c9cb1ec8b22781e89d1b1712e3ef878012316caf08358dfc3cceebe/vs_TestController.exe' `
    -Checksum '84DB284C6C9CB1EC8B22781E89D1B1712E3EF878012316CAF08358DFC3CCEEBE' `
    -ChecksumType 'SHA256' `
    -InstallerTechnology 'WillowVS2017OrLater' `
    -Product 'TestController' `
    -VisualStudioYear '2017' `
    -Preview $false


text:
from typing import TYPE_CHECKING, Dict, List, Optional

import numpy as np

from pandas._typing import FilePathOrBuffer, Scalar, StorageOptions
from pandas.compat._optional import import_optional_dependency

from pandas.io.excel._base import BaseExcelReader, ExcelWriter
from pandas.io.excel._util import validate_freeze_panes

if TYPE_CHECKING:
    from openpyxl.descriptors.serialisable import Serialisable

class OpenpyxlWriter(ExcelWriter):
    engine = "openpyxl"
    supported_extensions = (".xlsx", ".xlsm")

    def __init__(
        self,
        path,
        engine=None,
        mode: str = "w",
        storage_options: StorageOptions = None,
        **engine_kwargs,
    ):
        # Use the openpyxl module as the Excel writer.
        from openpyxl.workbook import Workbook

        super().__init__(
            path, mode=mode, storage_options=storage_options, **engine_kwargs
        )

        # ExcelWriter replaced "a" by "r+" to allow us to first read the excel file from
        # the file and later write to it
        if "r+" in self.mode:  # Load from existing workbook
            from openpyxl import load_workbook

            self.book = load_workbook(self.handles.handle)
        else:
            # Create workbook object with default optimized_write=True.
            self.book = Workbook()

            if self.book.worksheets:
                self.book.remove(self.book.worksheets[0])

    def save(self):
        """
        Save workbook to disk.
        """
        self.book.save(self.handles.handle)

    @classmethod
    def _convert_to_style_kwargs(cls, style_dict: dict) -> Dict[str, "Serialisable"]:
        """
        Convert a style_dict to a set of kwargs suitable for initializing
        or updating-on-copy an openpyxl v2 style object.

        Parameters
        ----------
        style_dict : dict
            A dict with zero or more of the following keys (or their synonyms).
                'font'
                'fill'
                'border' ('borders')
                'alignment'
                'number_format'
                'protection'

        Returns
        -------
        style_kwargs : dict
            A dict with the same, normalized keys as ``style_dict`` but each
            value has been replaced with a native openpyxl style object of the
            appropriate class.
        """
        _style_key_map = {"borders": "border"}

        style_kwargs: Dict[str, Serialisable] = {}
        for k, v in style_dict.items():
            if k in _style_key_map:
                k = _style_key_map[k]
            _conv_to_x = getattr(cls, f"_convert_to_{k}", lambda x: None)
            new_v = _conv_to_x(v)
            if new_v:
                style_kwargs[k] = new_v

        return style_kwargs

    @classmethod
    def _convert_to_color(cls, color_spec):
        """
        Convert ``color_spec`` to an openpyxl v2 Color object.

        Parameters
        ----------
        color_spec : str, dict
            A 32-bit ARGB hex string, or a dict with zero or more of the
            following keys.
                'rgb'
                'indexed'
                'auto'
                'theme'
                'tint'
                'index'
                'type'

        Returns
        -------
        color : openpyxl.styles.Color
        """
        from openpyxl.styles import Color

        if isinstance(color_spec, str):
            return Color(color_spec)
        else:
            return Color(**color_spec)

    @classmethod
    def _convert_to_font(cls, font_dict):
        """
        Convert ``font_dict`` to an openpyxl v2 Font object.

        Parameters
        ----------
        font_dict : dict
            A dict with zero or more of the following keys (or their synonyms).
                'name'
                'size' ('sz')
                'bold' ('b')
                'italic' ('i')
                'underline' ('u')
                'strikethrough' ('strike')
                'color'
                'vertAlign' ('vertalign')
                'charset'
                'scheme'
                'family'
                'outline'
                'shadow'
                'condense'

        Returns
        -------
        font : openpyxl.styles.Font
        """
        from openpyxl.styles import Font

        _font_key_map = {
            "sz": "size",
            "b": "bold",
            "i": "italic",
            "u": "underline",
            "strike": "strikethrough",
            "vertalign": "vertAlign",
        }

        font_kwargs = {}
        for k, v in font_dict.items():
            if k in _font_key_map:
                k = _font_key_map[k]
            if k == "color":
                v = cls._convert_to_color(v)
            font_kwargs[k] = v

        return Font(**font_kwargs)

    @classmethod
    def _convert_to_stop(cls, stop_seq):
        """
        Convert ``stop_seq`` to a list of openpyxl v2 Color objects,
        suitable for initializing the ``GradientFill`` ``stop`` parameter.

        Parameters
        ----------
        stop_seq : iterable
            An iterable that yields objects suitable for consumption by
            ``_convert_to_color``.

        Returns
        -------
        stop : list of openpyxl.styles.Color
        """
        return map(cls._convert_to_color, stop_seq)

    @classmethod
    def _convert_to_fill(cls, fill_dict):
        """
        Convert ``fill_dict`` to an openpyxl v2 Fill object.

        Parameters
        ----------
        fill_dict : dict
            A dict with one or more of the following keys (or their synonyms),
                'fill_type' ('patternType', 'patterntype')
                'start_color' ('fgColor', 'fgcolor')
                'end_color' ('bgColor', 'bgcolor')
            or one or more of the following keys (or their synonyms).
                'type' ('fill_type')
                'degree'
                'left'
                'right'
                'top'
                'bottom'
                'stop'

        Returns
        -------
        fill : openpyxl.styles.Fill
        """
        from openpyxl.styles import GradientFill, PatternFill

        _pattern_fill_key_map = {
            "patternType": "fill_type",
            "patterntype": "fill_type",
            "fgColor": "start_color",
            "fgcolor": "start_color",
            "bgColor": "end_color",
            "bgcolor": "end_color",
        }

        _gradient_fill_key_map = {"fill_type": "type"}

        pfill_kwargs = {}
        gfill_kwargs = {}
        for k, v in fill_dict.items():
            pk = gk = None
            if k in _pattern_fill_key_map:
                pk = _pattern_fill_key_map[k]
            if k in _gradient_fill_key_map:
                gk = _gradient_fill_key_map[k]
            if pk in ["start_color", "end_color"]:
                v = cls._convert_to_color(v)
            if gk == "stop":
                v = cls._convert_to_stop(v)
            if pk:
                pfill_kwargs[pk] = v
            elif gk:
                gfill_kwargs[gk] = v
            else:
                pfill_kwargs[k] = v
                gfill_kwargs[k] = v

        try:
            return PatternFill(**pfill_kwargs)
        except TypeError:
            return GradientFill(**gfill_kwargs)

    @classmethod
    def _convert_to_side(cls, side_spec):
        """
        Convert ``side_spec`` to an openpyxl v2 Side object.

        Parameters
        ----------
        side_spec : str, dict
            A string specifying the border style, or a dict with zero or more
            of the following keys (or their synonyms).
                'style' ('border_style')
                'color'

        Returns
        -------
        side : openpyxl.styles.Side
        """
        from openpyxl.styles import Side

        _side_key_map = {"border_style": "style"}

        if isinstance(side_spec, str):
            return Side(style=side_spec)

        side_kwargs = {}
        for k, v in side_spec.items():
            if k in _side_key_map:
                k = _side_key_map[k]
            if k == "color":
                v = cls._convert_to_color(v)
            side_kwargs[k] = v

        return Side(**side_kwargs)

    @classmethod
    def _convert_to_border(cls, border_dict):
        """
        Convert ``border_dict`` to an openpyxl v2 Border object.

        Parameters
        ----------
        border_dict : dict
            A dict with zero or more of the following keys (or their synonyms).
                'left'
                'right'
                'top'
                'bottom'
                'diagonal'
                'diagonal_direction'
                'vertical'
                'horizontal'
                'diagonalUp' ('diagonalup')
                'diagonalDown' ('diagonaldown')
                'outline'

        Returns
        -------
        border : openpyxl.styles.Border
        """
        from openpyxl.styles import Border

        _border_key_map = {"diagonalup": "diagonalUp", "diagonaldown": "diagonalDown"}

        border_kwargs = {}
        for k, v in border_dict.items():
            if k in _border_key_map:
                k = _border_key_map[k]
            if k == "color":
                v = cls._convert_to_color(v)
            if k in ["left", "right", "top", "bottom", "diagonal"]:
                v = cls._convert_to_side(v)
            border_kwargs[k] = v

        return Border(**border_kwargs)

    @classmethod
    def _convert_to_alignment(cls, alignment_dict):
        """
        Convert ``alignment_dict`` to an openpyxl v2 Alignment object.

        Parameters
        ----------
        alignment_dict : dict
            A dict with zero or more of the following keys (or their synonyms).
                'horizontal'
                'vertical'
                'text_rotation'
                'wrap_text'
                'shrink_to_fit'
                'indent'
        Returns
        -------
        alignment : openpyxl.styles.Alignment
        """
        from openpyxl.styles import Alignment

        return Alignment(**alignment_dict)

    @classmethod
    def _convert_to_number_format(cls, number_format_dict):
        """
        Convert ``number_format_dict`` to an openpyxl v2.1.0 number format
        initializer.

        Parameters
        ----------
        number_format_dict : dict
            A dict with zero or more of the following keys.
                'format_code' : str

        Returns
        -------
        number_format : str
        """
        return number_format_dict["format_code"]

    @classmethod
    def _convert_to_protection(cls, protection_dict):
        """
        Convert ``protection_dict`` to an openpyxl v2 Protection object.

        Parameters
        ----------
        protection_dict : dict
            A dict with zero or more of the following keys.
                'locked'
                'hidden'

        Returns
        -------
        """
        from openpyxl.styles import Protection

        return Protection(**protection_dict)

    def write_cells(
        self, cells, sheet_name=None, startrow=0, startcol=0, freeze_panes=None
    ):
        # Write the frame cells using openpyxl.
        sheet_name = self._get_sheet_name(sheet_name)

        _style_cache: Dict[str, Dict[str, Serialisable]] = {}

        if sheet_name in self.sheets:
            wks = self.sheets[sheet_name]
        else:
            wks = self.book.create_sheet()
            wks.title = sheet_name
            self.sheets[sheet_name] = wks

        if validate_freeze_panes(freeze_panes):
            wks.freeze_panes = wks.cell(
                row=freeze_panes[0] + 1, column=freeze_panes[1] + 1
            )

        for cell in cells:
            xcell = wks.cell(
                row=startrow + cell.row + 1, column=startcol + cell.col + 1
            )
            xcell.value, fmt = self._value_with_fmt(cell.val)
            if fmt:
                xcell.number_format = fmt

            style_kwargs: Optional[Dict[str, Serialisable]] = {}
            if cell.style:
                key = str(cell.style)
                style_kwargs = _style_cache.get(key)
                if style_kwargs is None:
                    style_kwargs = self._convert_to_style_kwargs(cell.style)
                    _style_cache[key] = style_kwargs

            if style_kwargs:
                for k, v in style_kwargs.items():
                    setattr(xcell, k, v)

            if cell.mergestart is not None and cell.mergeend is not None:

                wks.merge_cells(
                    start_row=startrow + cell.row + 1,
                    start_column=startcol + cell.col + 1,
                    end_column=startcol + cell.mergeend + 1,
                    end_row=startrow + cell.mergestart + 1,
                )

                # When cells are merged only the top-left cell is preserved
                # The behaviour of the other cells in a merged range is
                # undefined
                if style_kwargs:
                    first_row = startrow + cell.row + 1
                    last_row = startrow + cell.mergestart + 1
                    first_col = startcol + cell.col + 1
                    last_col = startcol + cell.mergeend + 1

                    for row in range(first_row, last_row + 1):
                        for col in range(first_col, last_col + 1):
                            if row == first_row and col == first_col:
                                # Ignore first cell. It is already handled.
                                continue
                            xcell = wks.cell(column=col, row=row)
                            for k, v in style_kwargs.items():
                                setattr(xcell, k, v)

class OpenpyxlReader(BaseExcelReader):
    def __init__(
        self,
        filepath_or_buffer: FilePathOrBuffer,
        storage_options: StorageOptions = None,
    ) -> None:
        """
        Reader using openpyxl engine.

        Parameters
        ----------
        filepath_or_buffer : string, path object or Workbook
            Object to be parsed.
        storage_options : dict, optional
            passed to fsspec for appropriate URLs (see ``_get_filepath_or_buffer``)
        """
        import_optional_dependency("openpyxl")
        super().__init__(filepath_or_buffer, storage_options=storage_options)

    @property
    def _workbook_class(self):
        from openpyxl import Workbook

        return Workbook

    def load_workbook(self, filepath_or_buffer: FilePathOrBuffer):
        from openpyxl import load_workbook

        return load_workbook(
            filepath_or_buffer, read_only=True, data_only=True, keep_links=False
        )

    def close(self):
        # https://stackoverflow.com/questions/31416842/
        #  openpyxl-does-not-close-excel-workbook-in-read-only-mode
        self.book.close()
        super().close()

    @property
    def sheet_names(self) -> List[str]:
        return self.book.sheetnames

    def get_sheet_by_name(self, name: str):
        return self.book[name]

    def get_sheet_by_index(self, index: int):
        return self.book.worksheets[index]

    def _convert_cell(self, cell, convert_float: bool) -> Scalar:

        from openpyxl.cell.cell import TYPE_BOOL, TYPE_ERROR, TYPE_NUMERIC

        if cell.is_date:
            return cell.value
        elif cell.data_type == TYPE_ERROR:
            return np.nan
        elif cell.data_type == TYPE_BOOL:
            return bool(cell.value)
        elif cell.value is None:
            return ""  # compat with xlrd
        elif cell.data_type == TYPE_NUMERIC:
            # GH5394
            if convert_float:
                val = int(cell.value)
                if val == cell.value:
                    return val
            else:
                return float(cell.value)

        return cell.value

    def get_sheet_data(self, sheet, convert_float: bool) -> List[List[Scalar]]:
        data: List[List[Scalar]] = []
        for row in sheet.rows:
            data.append([self._convert_cell(cell, convert_float) for cell in row])

        return data


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">
    <parent>
        <artifactId>rure-demo</artifactId>
        <groupId>com.bdth</groupId>
        <version>0.0.1</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <packaging>war</packaging>

    <artifactId>rure-demo-test</artifactId>
    <name>rure-demo-test</name>
    <url>http://www.bdth.cn</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

        <maven.compiler.source>1.7</maven.compiler.source>
        <maven.compiler.target>1.7</maven.compiler.target>
        <maven.compiler.compilerVersion>1.7</maven.compiler.compilerVersion>

        <spring.version>4.3.10.RELEASE</spring.version>

    </properties>

    <dependencies>
        <dependency>
            <groupId>com.bdth</groupId>
            <artifactId>rure-demo-api</artifactId>
            <version>0.0.1</version>
        </dependency>
        <!-- spring -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!-- 格式化对象,方便输出日志 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.1.41</version>
        </dependency>
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-mapper-asl</artifactId>
            <version>1.9.8</version>
            <type>jar</type>
            <scope>compile</scope>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
    </dependencies>

    <build>
        <finalName>rure-demo-test</finalName>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
            </resource>
        </resources>
        <plugins>
            <!-- jetty插件 -->
            <plugin>
                <groupId>org.eclipse.jetty</groupId>
                <artifactId>jetty-maven-plugin</artifactId>
                <!--<version>9.0.0.v20130308</version>-->
                <version>9.2.7.v20150116</version>
                <configuration>
                    <scanIntervalSeconds>3</scanIntervalSeconds>
                    <webApp>
                        <contextPath>/</contextPath>
                    </webApp>
                    <httpConnector>
                        <port>2222</port>
                    </httpConnector>
                    <reload>automatic</reload>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.18.1</version>
                <configuration>
                    <skipTests>true</skipTests>
                    <testFailureIgnore>true</testFailureIgnore>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Antonie van Leeuwenhoek Ned. Tijdschr. Hyg. 44: 440 (1978)

#### Original name
Sporopachydermia Rodr. Mir.

### Remarks
null


text:
package com.voxela.chat;

import org.bukkit.event.Listener;
import org.bukkit.plugin.RegisteredServiceProvider;
import org.bukkit.plugin.java.JavaPlugin;

import com.voxela.chat.commands.GlobalChatCommand;

import net.md_5.bungee.api.ChatColor;
import net.milkbowl.vault.chat.Chat;

public class Main extends JavaPlugin implements Listener {

	private static Main instance;
    private static Chat chat = null;

	public static String consolePrefix = "[VoxelaChat] ";
	public static String gamePrefix = ChatColor.DARK_GRAY + "[" + ChatColor.AQUA + "Voxela" + ChatColor.DARK_GRAY + "] ";

	@Override
	public void onEnable() {
		System.out.print(consolePrefix + "Chat has been enabled.");
		instance = this;

		this.getCommand("g").setExecutor(new GlobalChatCommand(this));
        this.getServer().getPluginManager().registerEvents(new AsyncPlayerChatListener(), getInstance());

		setupChat();
	}

	public void onDisable() {
		System.out.print(consolePrefix + "Chat has been disabled.");
	}

	public static Main getInstance() {
		return instance;
	}

    private boolean setupChat() {
        RegisteredServiceProvider<Chat> rsp = getServer().getServicesManager().getRegistration(Chat.class);
        chat = rsp.getProvider();
        return chat != null;
    }

    public static Chat getChat() {
        return chat;
    }

}


text:
layout: page
title: Aeon Foundation Award Ceremony
date: 2016-05-24
author: Gerald Nichols
tags: weekly links, java
status: published
summary: Proin rhoncus, metus at porttitor bibendum.
banner: images/banner/leisure-02.jpg
booking:
  startDate: 05/16/2019
  endDate: 05/18/2019
  ctyhocn: LPKMDHX
  groupCode: AFAC
published: true
---
Nunc non nisl a nisi bibendum faucibus eu sit amet dolor. Nam sed viverra nisi. Integer varius, nisl sed vulputate fringilla, ante ipsum luctus nisl, eget rutrum nulla elit quis arcu. Donec placerat dictum mauris, ut dapibus magna auctor vitae. Nullam dapibus laoreet mi, sed fringilla ante imperdiet a. Sed vitae rutrum tortor. Vestibulum eget nunc nec justo convallis mattis. Duis lobortis lacus sit amet purus eleifend tempor.

* Morbi id turpis placerat, fermentum metus ac, vestibulum nunc
* Cras sed justo nec purus consequat consequat
* Pellentesque non lorem quis nulla tincidunt pharetra
* Praesent ut leo ultrices nunc maximus dapibus.

Vivamus non diam sagittis, placerat dui ac, faucibus erat. Donec a pharetra sapien. Maecenas non pretium velit. Pellentesque consectetur turpis a lorem laoreet, sit amet ornare risus vestibulum. Donec mauris augue, molestie id tristique vitae, pharetra at enim. Pellentesque scelerisque nulla velit. Proin tempor non nunc vitae aliquet. Nunc at tellus nec tellus tincidunt fringilla. Vestibulum scelerisque velit a mauris lacinia, et laoreet tortor tristique. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Suspendisse semper, neque vel tempor convallis, orci nunc lacinia urna, id gravida quam purus non lorem. Pellentesque faucibus viverra accumsan. Praesent ligula leo, maximus ac velit tincidunt, facilisis placerat risus.


text:
from __future__ import unicode_literals
from __future__ import print_function
from FTModuleClass import *

#----------------------------------------------------------------
# Documentation for the user:

docs = {FTM_Name       : "Generate Reversal Index Sort Field Only",
        FTM_Version    : "4.0",
        FTM_ModifiesDB : True,
        FTM_Synopsis   : "Generates the Chinese sort field in the Chinese Reversal Index. Sorts by pronunciation.",
        FTM_Help       : r"Doc\Chinese Utilities Help.pdf",
        FTM_Description:
"""
This module sets the sort field in the Chinese Reversal Index ('Chinese, Mandarin (China)' (zh-CN))

The sort field (zh-CN-x-zhsort) is generated from the Chinese Hanzi (zh-CN) field and
Pinyin Numbered (zh-CN-x-pyn) field.

The three writing systems mentioned above must be configured in FLEx
under Tools | Configure | Setup Writing Systems. Note that fields using
the old 'cmn' locale are also supported, but this locale code should not be used in
new databases.

This Module generates the Pinyin tone number field from the Hanzi
field and then generates the Sort field from those two. The sort field will be left
blank for any entries with ambiguities in the tone number field .

The sort field produced by this Module orders Chinese by pronunciation, then
by stroke count, and finally by stroke order. This follows the ordering in
现代汉语词典 (XianDai HanYu CiDian). Thus:

 - san < sen < shan < sheng < si < song: 三 < 森 < 山 < 生 < 四 < 送

 - lu < lü < luan < lüe: 路 < 绿 < 乱 < 掠

 - (stroke count) 录 < 录音 < 路 < 路口

 - (stroke order) zhi4 with 8 strokes: 郅 < 制 < 质 < 治

See Chinese Utilities Help.pdf for detailed information on configuration and usage.
""" }

from ChineseUtilities import ChineseParser
from ChineseUtilities import SortStringDB, ChineseWritingSystems

#----------------------------------------------------------------
# Configurables:

# Ambiguous Chinese parses are common, and need to be manually resolved in
# the tone number field. However, if anyone wants to bypass the manual
# work, two levels of hacks are provided to force a sort string calculation
# even though it might produce a slightly wrong sort order:
# HACK_FIRST_WORD_NOT_AMBIGUOUS:
#       If the first word is not ambiguous for parse or pronunciation then
#       a sort string will be generated using as many characters as aren't
#       ambiguous. These entries will sort in the right place by at least
#       the first character.
# HACK_FIRST_WORD_IGNORE_TONE:
#       Generates the sort string for the above, AND if the pronunciation
#       matches, but the tone doesn't. These entries will sort in the right
#       place by the first character, although they might be in the wrong
#       place by tone.
# Note: all sort strings that are hacked like this will have '(...)' appended.

HACK_NONE = 0
HACK_FIRST_WORD_NOT_AMBIGUOUS = 1
HACK_FIRST_WORD_IGNORE_TONE = 2

HACK_LEVEL = 0

#----------------------------------------------------------------
import chin_utils
import itertools
from os.path import commonprefix

HACK_ENDING = "()"
HACK_FULLWIDTH_ENDING = "\N{FULLWIDTH LEFT PARENTHESIS}\N{FULLWIDTH RIGHT PARENTHESIS}"

def HACK_Tonenum (hz, tn):

    def __trim_ambiguities(s):
        words = s.split()
        i = 0
        for w in words:
            if "|" in w: break
            i += 1
        return " ".join(words[:i])

    hacked_tn = None
    if "|" in tn: # Hack away...
        parses = tn.lower().split(" | ")
        # 2 cases:
        if len(parses) > 1: # ambiguous parse
            #print("    Ambiguous parse:")
            parses = map(__trim_ambiguities, parses)
            parses = map(chin_utils.get_tone_syls, parses)
            longest = commonprefix(parses)
            hacked_tn = " ".join(longest)
        else:               # single parse
            #print("    Single parse")
            words = tn.split()
            firstword = words[0]
            if "|" in firstword:    # ambiguous word
                #print("    First word ambiguous:", firstword)
                if HACK_LEVEL == HACK_FIRST_WORD_IGNORE_TONE:
                    segments = firstword.split("|")
                    stripped_segs = []
                    for seg in segments:
                        stripped = [syl.rstrip("12345") for syl in chin_utils.get_tone_syls(seg.lower())]
                        stripped_segs.append("".join(stripped))
                    if len(set(stripped_segs)) == 1:    # All pronunciations the same
                        hacked_tn = segments[0]         # Arbitrarily use the first option
                    #else - different pronunciations: no hack
                #else - ambiguous first word: no hack
            else:
                # firstword not ambiguous - grab longest unambiguous sequence
                #print("    First word not ambiguous:", words)
                hacked_tn = __trim_ambiguities(tn)

    if hacked_tn:
        #print(" >>", hacked_tn)
        syls = chin_utils.get_tone_syls(hacked_tn)
        # Trim hz to match tonenum length
        hz = "".join(chin_utils.get_chars(hz)[:len(syls)])
        # Mark hacked entries
        tn = hacked_tn + HACK_ENDING
        hz = hz + HACK_FULLWIDTH_ENDING

    return hz, tn

#----------------------------------------------------------------
# The main processing function

UpdatedTonenums = 0
UpdatedSortStrings = 0
HackedSortStrings = 0

def GenerateReversalSortFields(project, report, modifyAllowed=False):

    def __WriteReversalTonenumAndSortString(entry):
        global UpdatedTonenums
        global UpdatedSortStrings
        global HackedSortStrings

        hz = project.ReversalGetForm(entry, ChineseWS)
        tn = project.ReversalGetForm(entry, ChineseTonenumWS)
        ss = project.ReversalGetForm(entry, ChineseSortWS)

        # Tone number
        newTonenum, msg = Parser.CalculateTonenum(hz, tn)
        if msg:
            report.Warning("    %s" % msg,
                           project.BuildGotoURL(entry))
        if newTonenum is not None:
            report.Info(("    Updating %s > %s" if modifyAllowed else
                         "    %s needs updating > %s") \
                         % (hz, newTonenum))
            if modifyAllowed:
                project.ReversalSetForm(entry, newTonenum, ChineseTonenumWS)
            UpdatedTonenums += 1
            tn = newTonenum

        if HACK_LEVEL:
            hacked_hz, hacked_tn = HACK_Tonenum(hz, tn)
            if tn != hacked_tn:
                HackedSortStrings += 1
                report.Warning("    Hacked %s" % hz,
                               project.BuildGotoURL(entry))
                hz = hacked_hz
                tn = hacked_tn

        # Sort string
        newSortString, msg = SortDB.CalculateSortString(hz, tn, ss)
        if msg:
            report.Warning("    %s: %s" % (hz, msg),
                           project.BuildGotoURL(entry))

        if newSortString is not None:
            report.Info(("    Updating %s: (%s + %s) > %s" if modifyAllowed else
                         "    %s needs updating: (%s + %s) > %s") \
                         % (hz, hz, tn, newSortString))
            if modifyAllowed:
                project.ReversalSetForm(entry, newSortString, ChineseSortWS)
            UpdatedSortStrings += 1

        # (Subentries don't need the sort string)

    ChineseWS,\
    ChineseTonenumWS,\
    ChineseSortWS = ChineseWritingSystems(project, report, Hanzi=True, Tonenum=True, Sort=True)

    if not ChineseWS or not ChineseTonenumWS or not ChineseSortWS:
        report.Error("Please read the instructions and configure the necessary writing systems")
        return
    else:
        report.Info("Using writing systems:")
        report.Info("    Hanzi: %s" % project.WSUIName(ChineseWS))
        report.Info("    Tone number Pinyin: %s" % project.WSUIName(ChineseTonenumWS))
        report.Info("    Chinese sort field: %s" % project.WSUIName(ChineseSortWS))

    Parser = ChineseParser()
    SortDB = SortStringDB()

    index = project.ReversalIndex(ChineseWS)
    if index:
        report.ProgressStart(index.AllEntries.Count)
        report.Info("Updating sort strings for '%s' reversal index"
                    % project.WSUIName(ChineseWS))
        for entryNumber, entry in enumerate(project.ReversalEntries(ChineseWS)):
            report.ProgressUpdate(entryNumber)
            __WriteReversalTonenumAndSortString(entry)

    report.Info(("  %d %s updated" if modifyAllowed else
                 "  %d %s to update") \
                 % (UpdatedTonenums, "tone number" if (UpdatedTonenums==1) else "tone numbers"))

    report.Info(("  %d %s updated" if modifyAllowed else
                 "  %d %s to update") \
                 % (UpdatedSortStrings, "sort string" if (UpdatedSortStrings==1) else "sort strings"))
    if HACK_LEVEL:
        report.Info("  %d %s hacked" \
                 % (HackedSortStrings, "sort string" if (HackedSortStrings==1) else "sort strings"))

#----------------------------------------------------------------

FlexToolsModule = FlexToolsModuleClass(runFunction = GenerateReversalSortFields,
                                       docs = docs)

#----------------------------------------------------------------
if __name__ == '__main__':
    FlexToolsModule.Help()


text:
var vnd_hmh_api_key = '<KEY>';
var api_base_url = '<URL>';
// ---

var express = require('express');
var passport = require('passport');
var request = require('request');
var refresh = require('passport-oauth2-refresh');
var router = express.Router();

router.get('/', function(req, res, next) {
  if (req.user){
    res.render('users', {user: req.user});
  }else{
    res.send("sign in first.");
  }
});

router.get('/me', function(req, res, next) { // call to HMH api
  if (req.user){

    // prepare request
    var retries = 2;
    var makeRequest = function(){
      retries--;
      if(!retries){
        return sendErrorResponse();
      }
      var requestPath = api_base_url + '/me';
      var options = {
        url: requestPath,
        headers: {
          "Vnd-HMH-Api-Key": vnd_hmh_api_key,
          "Authorization": req.user.accessToken,
          "Accept": "application/json"
        }
      }

      // send request
      request(options, function (error, response, body) {
        if (!error && response.statusCode == 200) {
          var resp = JSON.parse(body);
          var data = JSON.stringify(resp.data, null, 2)
          res.render('me', {data: data});
        }else{
          if (response.statusCode == 401){
            // unauthorized, try refresh and go.
            refresh.requestNewAccessToken('oauth2', req.user.refreshToken, function(err, accessToken) {
              if(err || !accessToken) { sendErrorResponse(); }

              req.user.accessToken = accessToken;
              makeRequest();
            });
          }else{
            res.send("error fetching data; " + response.statusCode);
          }
        }
      });
    };

    makeRequest();

  }else{
    res.send("sign in first.");
  }
});

function send401Response() {
  return res.status(401).end();
};

module.exports = router;


text:
Initial version, with support for px calculations and unit stripping in
declaration values.


text:
#include "SerializableEnum.h"

namespace PhysX
{
	public ref class Serializable
	{
	private:
		PxBase* _serializable;

	internal:
		Serializable(PxBase* serializable);
	public:
		~Serializable();
	protected:
		!Serializable();

	public:
		property String^ ConcreteTypeName
		{
			String^ get();
		}

		property PhysX::ConcreteType ConcreteType
		{
			PhysX::ConcreteType get();
		}
	};
};


text:
title: WEB Reports API content structure
---

{% section %}

The Web Reports API is based on HTML and XML, with a new interface based on
SOAP.

![WEB reports panel 2](/static/img/web_reports_2.png)

The XML defines hooks into the console or Web Reports and it has a single primary section that holds HTML.

{% endsection %}

The HTML section in turn can contain anything that a browser can render.
In addition to the basic browser environment, there is a library of JavaScript
hooks available to provide access to various functions.

The content that is embedded in the HTML section is typically a mix of JavaScript,
HTML, Flex, and Relevance expressions that are evaluated with the JavaScript
function **EvaluateRelevance**. As soon as they are received, the results of the
evaluation are embedded directly into the page and shown in the custom Web Report.

![WEB reports graphics](/static/img/webreports_graphic.png)

Web Reports markup is passed through a pre-processor that recognizes Relevance
tags. The Relevance language uses a special class of inspectors called [Datastore Inspectors](../../relevance/guide/session/datastoreinspectors.html)
that can help you query and aggregate statistics on your data. These
Relevance expressions are evaluated and the tag is then replaced by those results.
You can also use JavaScript to evaluate Relevance and for other document object
model manipulations.


text:
package com.hazelcast.sql.impl.expression.predicate;

import com.hazelcast.nio.ObjectDataInput;
import com.hazelcast.nio.ObjectDataOutput;
import com.hazelcast.nio.serialization.IdentifiedDataSerializable;
import com.hazelcast.sql.impl.QueryException;
import com.hazelcast.sql.impl.SqlDataSerializerHook;
import com.hazelcast.sql.impl.expression.BiExpression;
import com.hazelcast.sql.impl.expression.Expression;
import com.hazelcast.sql.impl.expression.ExpressionEvalContext;
import com.hazelcast.sql.impl.row.Row;
import com.hazelcast.sql.impl.type.QueryDataType;
import com.hazelcast.sql.impl.type.QueryDataTypeFamily;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;

import java.io.IOException;
import java.util.Objects;

/**
 * Implements evaluation of SQL comparison predicates.
 *
 * @see ComparisonMode
 */
public final class ComparisonPredicate extends BiExpression<Boolean> implements IdentifiedDataSerializable {

    private ComparisonMode mode;

    public ComparisonPredicate() {
        // No-op.
    }

    private ComparisonPredicate(Expression<?> left, Expression<?> right, ComparisonMode mode) {
        super(left, right);
        this.mode = mode;
    }

    public static ComparisonPredicate create(Expression<?> left, Expression<?> right, ComparisonMode comparisonMode) {
        assert left.getType().equals(right.getType());
        return new ComparisonPredicate(left, right, comparisonMode);
    }

    @Override
    public int getFactoryId() {
        return SqlDataSerializerHook.F_ID;
    }

    @Override
    public int getClassId() {
        return SqlDataSerializerHook.EXPRESSION_COMPARISON;
    }

    @SuppressWarnings({"rawtypes", "unchecked"})
    @SuppressFBWarnings(value = "NP_BOOLEAN_RETURN_NULL", justification = "Any SQL expression may return null")
    @Override
    public Boolean eval(Row row, ExpressionEvalContext context) {
        Object left = operand1.eval(row, context);
        if (left == null) {
            return null;
        }

        Object right = operand2.eval(row, context);
        if (right == null) {
            return null;
        }

        if (this.operand1.getType().getTypeFamily() == QueryDataTypeFamily.OBJECT) {
            Class<?> leftClass = left.getClass();
            Class<?> rightClass = right.getClass();

            if (!leftClass.equals(rightClass)) {
                throw QueryException.error(
                        "Cannot compare two OBJECT values, because "
                                + "left operand has " + leftClass + " type and "
                                + "right operand has " + rightClass + " type");
            }

            if (!(left instanceof Comparable)) {
                throw QueryException.error(
                        "Cannot compare OBJECT value because " + leftClass + " doesn't implement Comparable interface");
            }

        }

        Comparable leftComparable = (Comparable) left;
        Comparable rightComparable = (Comparable) right;

        int order = leftComparable.compareTo(rightComparable);

        switch (mode) {
            case EQUALS:
                return order == 0;

            case NOT_EQUALS:
                return order != 0;

            case GREATER_THAN:
                return order > 0;

            case GREATER_THAN_OR_EQUAL:
                return order >= 0;

            case LESS_THAN:
                return order < 0;

            case LESS_THAN_OR_EQUAL:
                return order <= 0;

            default:
                throw new IllegalStateException("unexpected comparison mode: " + mode);
        }
    }

    @Override
    public QueryDataType getType() {
        return QueryDataType.BOOLEAN;
    }

    @Override
    public void writeData(ObjectDataOutput out) throws IOException {
        super.writeData(out);
        out.writeInt(mode.getId());
    }

    @Override
    public void readData(ObjectDataInput in) throws IOException {
        super.readData(in);
        mode = ComparisonMode.getById(in.readInt());
    }

    @Override
    public int hashCode() {
        return Objects.hash(operand1, operand2, mode);
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }

        if (o == null || getClass() != o.getClass()) {
            return false;
        }

        ComparisonPredicate that = (ComparisonPredicate) o;

        return Objects.equals(operand1, that.operand1) && Objects.equals(operand2, that.operand2) && mode == that.mode;
    }

    @Override
    public String toString() {
        return getClass().getSimpleName() + "{mode=" + mode + ", operand1=" + operand1 + ", operand2=" + operand2 + '}';
    }

}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<TITLE
>Partial Indexes</TITLE
><META
NAME="GENERATOR"
CONTENT="Modular DocBook HTML Stylesheet Version 1.79"><LINK
REV="MADE"
HREF="mailto:pgsql-docs@postgresql.org"><LINK
REL="HOME"
TITLE="PostgreSQL 9.0.5 Documentation"
HREF="index.html"><LINK
REL="UP"
TITLE="Indexes"
HREF="indexes.html"><LINK
REL="PREVIOUS"
TITLE="Indexes on Expressions"
HREF="indexes-expressional.html"><LINK
REL="NEXT"
TITLE="Operator Classes and Operator Families"
HREF="indexes-opclass.html"><LINK
REL="STYLESHEET"
TYPE="text/css"
HREF="stylesheet.css"><META
HTTP-EQUIV="Content-Type"
CONTENT="text/html; charset=ISO-8859-1"><META
NAME="creation"
CONTENT="2011-09-22T22:21:03">

PostgreSQL 9.0.5 Documentation

Prev	Fast Backward	Chapter 11. Indexes	Fast Forward	Next

11.8. Partial Indexes

   A partial index is an index built over a
   subset of a table; the subset is defined by a conditional
   expression (called the predicate of the
   partial index).  The index contains entries only for those table
   rows that satisfy the predicate.  Partial indexes are a specialized
   feature, but there are several situations in which they are useful.

   One major reason for using a partial index is to avoid indexing common
   values.  Since a query searching for a common value (one that
   accounts for more than a few percent of all the table rows) will not
   use the index anyway, there is no point in keeping those rows in the
   index at all.  This reduces the size of the index, which will speed
   up those queries that do use the index.  It will also speed up many table
   update operations because the index does not need to be
   updated in all cases.  Example 11-1 shows a
   possible application of this idea.

Example 11-1. Setting up a Partial Index to Exclude Common Values

    Suppose you are storing web server access logs in a database.
    Most accesses originate from the IP address range of your organization but
    some are from elsewhere (say, employees on dial-up connections).
    If your searches by IP are primarily for outside accesses,
    you probably do not need to index the IP range that corresponds to your
    organization's subnet.

    Assume a table like this:

CREATE TABLE access_log (
    url varchar,
    client_ip inet,
    ...
);

    To create a partial index that suits our example, use a command
    such as this:

CREATE INDEX access_log_client_ip_ix ON access_log (client_ip)
WHERE NOT (client_ip > inet '192.168.100.0' AND
           client_ip < inet '192.168.100.255');

    A typical query that can use this index would be:

SELECT *
FROM access_log
WHERE url = '/index.html' AND client_ip = inet '212.78.10.32';

    A query that cannot use this index is:

SELECT *
FROM access_log
WHERE client_ip = inet '192.168.100.23';

    Observe that this kind of partial index requires that the common
    values be predetermined, so such partial indexes are best used for
    data distributions that do not change.  The indexes can be recreated
    occasionally to adjust for new data distributions, but this adds
    maintenance effort.

   Another possible use for a partial index is to exclude values from the
   index that the
   typical query workload is not interested in; this is shown in Example 11-2.  This results in the same
   advantages as listed above, but it prevents the
   "uninteresting" values from being accessed via that
   index, even if an index scan might be profitable in that
   case.  Obviously, setting up partial indexes for this kind of
   scenario will require a lot of care and experimentation.

Example 11-2. Setting up a Partial Index to Exclude Uninteresting Values

    If you have a table that contains both billed and unbilled orders,
    where the unbilled orders take up a small fraction of the total
    table and yet those are the most-accessed rows, you can improve
    performance by creating an index on just the unbilled rows.  The
    command to create the index would look like this:

CREATE INDEX orders_unbilled_index ON orders (order_nr)
    WHERE billed is not true;

    A possible query to use this index would be:

SELECT * FROM orders WHERE billed is not true AND order_nr < 10000;

    However, the index can also be used in queries that do not involve
    <TT
CLASS="STRUCTFIELD"
>order_nr</TT
> at all, e.g.:

SELECT * FROM orders WHERE billed is not true AND amount > 5000.00;

    This is not as efficient as a partial index on the
    <TT
CLASS="STRUCTFIELD"
>amount</TT
> column would be, since the system has to
    scan the entire index.  Yet, if there are relatively few unbilled
    orders, using this partial index just to find the unbilled orders
    could be a win.

    Note that this query cannot use this index:

SELECT * FROM orders WHERE order_nr = 3501;

    The order 3501 might be among the billed or unbilled
    orders.

   Example 11-2 also illustrates that the
   indexed column and the column used in the predicate do not need to
   match.  PostgreSQL supports partial
   indexes with arbitrary predicates, so long as only columns of the
   table being indexed are involved.  However, keep in mind that the
   predicate must match the conditions used in the queries that
   are supposed to benefit from the index.  To be precise, a partial
   index can be used in a query only if the system can recognize that
   the <TT
CLASS="LITERAL"
>WHERE</TT
> condition of the query mathematically implies
   the predicate of the index.
   PostgreSQL does not have a sophisticated
   theorem prover that can recognize mathematically equivalent
   expressions that are written in different forms.  (Not
   only is such a general theorem prover extremely difficult to
   create, it would probably be too slow to be of any real use.)
   The system can recognize simple inequality implications, for example
   "x < 1" implies "x < 2"; otherwise
   the predicate condition must exactly match part of the query's
   <TT
CLASS="LITERAL"
>WHERE</TT
> condition
   or the index will not be recognized as usable. Matching takes
   place at query planning time, not at run time. As a result,
   parameterized query clauses do not work with a partial index. For
   example a prepared query with a parameter might specify
   "x < ?" which will never imply
   "x < 2" for all possible values of the parameter.

   A third possible use for partial indexes does not require the
   index to be used in queries at all.  The idea here is to create
   a unique index over a subset of a table, as in Example 11-3.  This enforces uniqueness
   among the rows that satisfy the index predicate, without constraining
   those that do not.

Example 11-3. Setting up a Partial Unique Index

    Suppose that we have a table describing test outcomes.  We wish
    to ensure that there is only one "successful" entry for
    a given subject and target combination, but there might be any number of
    "unsuccessful" entries.  Here is one way to do it:

CREATE TABLE tests (
    subject text,
    target text,
    success boolean,
    ...
);

CREATE UNIQUE INDEX tests_success_constraint ON tests (subject, target)
    WHERE success;

    This is a particularly efficient approach when there are few
    successful tests and many unsuccessful ones.

   Finally, a partial index can also be used to override the system's
   query plan choices.  Also, data sets with peculiar
   distributions might cause the system to use an index when it really
   should not.  In that case the index can be set up so that it is not
   available for the offending query.  Normally,
   PostgreSQL makes reasonable choices about index
   usage (e.g., it avoids them when retrieving common values, so the
   earlier example really only saves index size, it is not required to
   avoid index usage), and grossly incorrect plan choices are cause
   for a bug report.

   Keep in mind that setting up a partial index indicates that you
   know at least as much as the query planner knows, in particular you
   know when an index might be profitable.  Forming this knowledge
   requires experience and understanding of how indexes in
   PostgreSQL work.  In most cases, the advantage of a
   partial index over a regular index will be minimal.

   More information about partial indexes can be found in     The case for partial indexes
    , Partial indexing in POSTGRES: research project, and Generalized Partial Indexes
    (cached version)
    .

Prev	Home	Next

Indexes on Expressions	Up	Operator Classes and Operator Families


text:
using Stove.Configuration;

namespace Stove.RabbitMQ
{
    public interface IStoveRabbitMQConfiguration
    {
        string HostAddress { get; set; }

        string Username { get; set; }

        string Password { get; set; }

        string QueueName { get; set; }

        bool UseRetryMechanism { get; set; }

        int MaxRetryCount { get; set; }

        int? PrefetchCount { get; set; }

        int? ConcurrencyLimit { get; set; }

        IStoveStartupConfiguration StoveConfiguration { get; }
    }
}


text:
package org.guvnor.ala.util;

import org.guvnor.ala.config.RuntimeConfig;

/**
 * Utility class for holding helper operations related to runtimes.
 */
public class RuntimeConfigHelper {

    /**
     * Gets the runtime to be used given a runtime configuration.
     * @param config a runtime configuration.
     * @param defaultName the by default name to be used in cases where no name was provided in the runtime configuration.
     * @return the proper runtime name that must be used for the runtime.
     */
    public static final String buildRuntimeName(RuntimeConfig config,
                                                String defaultName) {
        if (config.getRuntimeName() == null || config.getRuntimeName().isEmpty()) {
            return defaultName;
        } else {
            return config.getRuntimeName();
        }
    }
}