text:
/**
 * language definition file for detailing where item is structurally used
 * @module lib/lang/defs/def_usedin
 */

var _       = require("lodash"),
	_sd = require('../../env/const'),
	definitionBase = require('./_def').definitionBase;

/**
 * @constuctor
 */
function _lang_def() {

	/* implement base */
	definitionBase.call(this, {
		type_def: 'usedin',
		canHaveName: _sd.VALIDATION.REQUIRED,
		canHaveValue: _sd.VALIDATION.OPTIONAL,
		canHaveDescription: _sd.VALIDATION.OPTIONAL,
		canHaveMeta:  _sd.VALIDATION.OPTIONAL
	});

	/* definitions must implement validate */
	this.validate = function(doc, item) {
		var errs = this.isValidItem(doc,item);

		if(errs.length > 0) {
			// handle errors
		}

		/* custom validatation */
		var result = [];
		_.each(item.name.trim().split(','), function(str){
			result.push(str.trim());
		});

		doc.usedin = result;

	};

}

/** exports */
module.exports = new _lang_def();

redpajama_set_name: RedPajamaGithub


text:
package org.apache.log4j.pattern;

import org.apache.log4j.spi.LoggingEvent;

/**
 * Formats a logger name.
 *
 * @author Ceki Gülcü
 *
 */
public final class LoggerPatternConverter extends NamePatternConverter {
  /**
   * Singleton.
   */
  private static final LoggerPatternConverter INSTANCE =
    new LoggerPatternConverter(null);

  /**
   * Private constructor.
   * @param options options, may be null.
   */
  private LoggerPatternConverter(final String[] options) {
    super("Logger", "logger", options);
  }

  /**
   * Obtains an instance of pattern converter.
   * @param options options, may be null.
   * @return instance of pattern converter.
   */
  public static LoggerPatternConverter newInstance(
    final String[] options) {
    if ((options == null) || (options.length == 0)) {
      return INSTANCE;
    }

    return new LoggerPatternConverter(options);
  }

  /**
   * {@inheritDoc}
   */
  public void format(final LoggingEvent event, final StringBuffer toAppendTo) {
    final int initialLength = toAppendTo.length();
    toAppendTo.append(event.getLoggerName());
    abbreviate(initialLength, toAppendTo);
  }
}


text:
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>{% if page.title %}{{ page.title }}{% else %}{{ site.title }}{% endif %}</title>
    <meta name="viewport" content="width=device-width">
    <meta name="description" content="{{ site.description }}">
    <link rel="canonical" href="{{ page.url | replace:'index.html','' | prepend: site.url }}">
    <link rel="alternate" type="application/rss+xml" title="RSS" href="/feed.xml">

    <!-- Custom CSS & Bootstrap Core CSS - Uses Bootswatch Flatly Theme: http://bootswatch.com/flatly/ -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
    <link rel="stylesheet" href="{{ "/style.css" }}">

    <!-- Custom Fonts -->
    <link rel="stylesheet" href="{{ "/css/font-awesome/css/font-awesome.min.css" }}">
    <link href="//fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css">
    <link href="//fonts.googleapis.com/css?family=Lato:400,700,400italic,700italic" rel="stylesheet" type="text/css">

    <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
        <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
        <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->

    <!--Start of Zopim Live Chat Script-->
    <script type="text/javascript">
    window.$zopim||(function(d,s){var z=$zopim=function(c){z._.push(c)},$=z.s=
    d.createElement(s),e=d.getElementsByTagName(s)[0];z.set=function(o){z.set.
    _.push(o)};z._=[];z.set._=[];$.async=!0;$.setAttribute("charset","utf-8");
    $.src="//v2.zopim.com/?3JFSyXWSAuvdKBRcEpFqRll7gyB5Lumd";z.t=+new Date;$.
    type="text/javascript";e.parentNode.insertBefore($,e)})(document,"script");
    </script>
    <!--End of Zopim Live Chat Script-->
</head>


text:
package jsoniter

import (
	"testing"
	"github.com/stretchr/testify/require"
)

func Test_decode_one_field_struct(t *testing.T) {
	should := require.New(t)
	type TestObject struct {
		Field1 string
	}
	obj := TestObject{}
	should.Nil(UnmarshalFromString(`{}`, &obj))
	should.Equal("", obj.Field1)
	should.Nil(UnmarshalFromString(`{"field1": "hello"}`, &obj))
	should.Equal("hello", obj.Field1)
}

func Test_decode_two_fields_struct(t *testing.T) {
	should := require.New(t)
	type TestObject struct {
		Field1 string
		Field2 string
	}
	obj := TestObject{}
	should.Nil(UnmarshalFromString(`{}`, &obj))
	should.Equal("", obj.Field1)
	should.Nil(UnmarshalFromString(`{"Field1": "a", "Field2": "stream"}`, &obj))
	should.Equal("a", obj.Field1)
	should.Equal("stream", obj.Field2)
}

func Test_decode_three_fields_struct(t *testing.T) {
	should := require.New(t)
	type TestObject struct {
		Field1 string
		Field2 string
		Field3 string
	}
	obj := TestObject{}
	should.Nil(UnmarshalFromString(`{}`, &obj))
	should.Equal("", obj.Field1)
	should.Nil(UnmarshalFromString(`{"Field1": "a", "Field2": "stream", "Field3": "c"}`, &obj))
	should.Equal("a", obj.Field1)
	should.Equal("stream", obj.Field2)
	should.Equal("c", obj.Field3)
}

func Test_decode_four_fields_struct(t *testing.T) {
	should := require.New(t)
	type TestObject struct {
		Field1 string
		Field2 string
		Field3 string
		Field4 string
	}
	obj := TestObject{}
	should.Nil(UnmarshalFromString(`{}`, &obj))
	should.Equal("", obj.Field1)
	should.Nil(UnmarshalFromString(`{"Field1": "a", "Field2": "stream", "Field3": "c", "Field4": "d"}`, &obj))
	should.Equal("a", obj.Field1)
	should.Equal("stream", obj.Field2)
	should.Equal("c", obj.Field3)
	should.Equal("d", obj.Field4)
}

func Test_decode_five_fields_struct(t *testing.T) {
	should := require.New(t)
	type TestObject struct {
		Field1 string
		Field2 string
		Field3 string
		Field4 string
		Field5 string
	}
	obj := TestObject{}
	should.Nil(UnmarshalFromString(`{}`, &obj))
	should.Equal("", obj.Field1)
	should.Nil(UnmarshalFromString(`{"Field1": "a", "Field2": "stream", "Field3": "c", "Field4": "d", "Field5": "e"}`, &obj))
	should.Equal("a", obj.Field1)
	should.Equal("stream", obj.Field2)
	should.Equal("c", obj.Field3)
	should.Equal("d", obj.Field4)
	should.Equal("e", obj.Field5)
}

func Test_decode_six_fields_struct(t *testing.T) {
	should := require.New(t)
	type TestObject struct {
		Field1 string
		Field2 string
		Field3 string
		Field4 string
		Field5 string
		Field6 string
	}
	obj := TestObject{}
	should.Nil(UnmarshalFromString(`{}`, &obj))
	should.Equal("", obj.Field1)
	should.Nil(UnmarshalFromString(`{"Field1": "a", "Field2": "stream", "Field3": "c", "Field4": "d", "Field5": "e", "Field6": "x"}`, &obj))
	should.Equal("a", obj.Field1)
	should.Equal("stream", obj.Field2)
	should.Equal("c", obj.Field3)
	should.Equal("d", obj.Field4)
	should.Equal("e", obj.Field5)
	should.Equal("x", obj.Field6)
}

func Test_decode_seven_fields_struct(t *testing.T) {
	should := require.New(t)
	type TestObject struct {
		Field1 string
		Field2 string
		Field3 string
		Field4 string
		Field5 string
		Field6 string
		Field7 string
	}
	obj := TestObject{}
	should.Nil(UnmarshalFromString(`{}`, &obj))
	should.Equal("", obj.Field1)
	should.Nil(UnmarshalFromString(`{"Field1": "a", "Field2": "stream", "Field3": "c", "Field4": "d", "Field5": "e", "Field6": "x", "Field7":"y"}`, &obj))
	should.Equal("a", obj.Field1)
	should.Equal("stream", obj.Field2)
	should.Equal("c", obj.Field3)
	should.Equal("d", obj.Field4)
	should.Equal("e", obj.Field5)
	should.Equal("x", obj.Field6)
	should.Equal("y", obj.Field7)
}

func Test_decode_eight_fields_struct(t *testing.T) {
	should := require.New(t)
	type TestObject struct {
		Field1 string
		Field2 string
		Field3 string
		Field4 string
		Field5 string
		Field6 string
		Field7 string
		Field8 string
	}
	obj := TestObject{}
	should.Nil(UnmarshalFromString(`{}`, &obj))
	should.Equal("", obj.Field1)
	should.Nil(UnmarshalFromString(`{"Field8":"1", "Field1": "a", "Field2": "stream", "Field3": "c", "Field4": "d", "Field5": "e", "Field6": "x", "Field7":"y"}`, &obj))
	should.Equal("a", obj.Field1)
	should.Equal("stream", obj.Field2)
	should.Equal("c", obj.Field3)
	should.Equal("d", obj.Field4)
	should.Equal("e", obj.Field5)
	should.Equal("x", obj.Field6)
	should.Equal("y", obj.Field7)
	should.Equal("1", obj.Field8)
}

func Test_decode_nine_fields_struct(t *testing.T) {
	should := require.New(t)
	type TestObject struct {
		Field1 string
		Field2 string
		Field3 string
		Field4 string
		Field5 string
		Field6 string
		Field7 string
		Field8 string
		Field9 string
	}
	obj := TestObject{}
	should.Nil(UnmarshalFromString(`{}`, &obj))
	should.Equal("", obj.Field1)
	should.Nil(UnmarshalFromString(`{"Field8" : "zzzzzzzzzzz", "Field7": "zz", "Field6" : "xx", "Field1": "a", "Field2": "stream", "Field3": "c", "Field4": "d", "Field5": "e", "Field9":"f"}`, &obj))
	should.Equal("a", obj.Field1)
	should.Equal("stream", obj.Field2)
	should.Equal("c", obj.Field3)
	should.Equal("d", obj.Field4)
	should.Equal("e", obj.Field5)
	should.Equal("xx", obj.Field6)
	should.Equal("zz", obj.Field7)
	should.Equal("zzzzzzzzzzz", obj.Field8)
	should.Equal("f", obj.Field9)
}

func Test_decode_ten_fields_struct(t *testing.T) {
	should := require.New(t)
	type TestObject struct {
		Field1  string
		Field2  string
		Field3  string
		Field4  string
		Field5  string
		Field6  string
		Field7  string
		Field8  string
		Field9  string
		Field10 string
	}
	obj := TestObject{}
	should.Nil(UnmarshalFromString(`{}`, &obj))
	should.Equal("", obj.Field1)
	should.Nil(UnmarshalFromString(`{"Field10":"x", "Field9": "x", "Field8":"x", "Field7":"x", "Field6":"x", "Field1": "a", "Field2": "stream", "Field3": "c", "Field4": "d", "Field5": "e"}`, &obj))
	should.Equal("a", obj.Field1)
	should.Equal("stream", obj.Field2)
	should.Equal("c", obj.Field3)
	should.Equal("d", obj.Field4)
	should.Equal("e", obj.Field5)
	should.Equal("x", obj.Field6)
	should.Equal("x", obj.Field7)
	should.Equal("x", obj.Field8)
	should.Equal("x", obj.Field9)
	should.Equal("x", obj.Field10)
}

func Test_decode_more_than_ten_fields_struct(t *testing.T) {
	should := require.New(t)
	type TestObject struct {
		Field1  string
		Field2  string
		Field3  string
		Field4  string
		Field5  string
		Field6  string
		Field7  string
		Field8  string
		Field9  string
		Field10 string
		Field11 int
	}
	obj := TestObject{}
	should.Nil(UnmarshalFromString(`{}`, &obj))
	should.Equal("", obj.Field1)
	should.Nil(UnmarshalFromString(`{"field11":1, "field1": "a", "Field2": "stream", "Field3": "c", "Field4": "d", "Field5": "e"}`, &obj))
	should.Equal("a", obj.Field1)
	should.Equal("stream", obj.Field2)
	should.Equal("c", obj.Field3)
	should.Equal("d", obj.Field4)
	should.Equal("e", obj.Field5)
	should.Equal(1, obj.Field11)
}

func Test_decode_struct_field_with_tag(t *testing.T) {
	should := require.New(t)
	type TestObject struct {
		Field1 string `json:"field-1"`
		Field2 string `json:"-"`
		Field3 int    `json:",string"`
	}
	obj := TestObject{Field2: "world"}
	UnmarshalFromString(`{"field-1": "hello", "field2": "", "Field3": "100"}`, &obj)
	should.Equal("hello", obj.Field1)
	should.Equal("world", obj.Field2)
	should.Equal(100, obj.Field3)
}

func Test_decode_struct_field_with_tag_string(t *testing.T) {
	should := require.New(t)
	type TestObject struct {
		Field1 int `json:",string"`
	}
	obj := TestObject{Field1: 100}
	should.Nil(UnmarshalFromString(`{"Field1": "100"}`, &obj))
	should.Equal(100, obj.Field1)
}


text:
#include "Environment.hpp"
#include "ArgParser.hpp"
#include "Builder.hpp"
#include <fstream>

Environment::Ptr env(new Environment);
ArgParser::Ptr argp;

void clean(std::string const& dir) {
    for(File::Iterator i(dir);i;++i) {
        std::string const path = dir + FILE_SEPARATOR + (*i);
        if((*i) == "." || (*i) == "..") {
            // Do nothing
        } else if(File::is_dir(path)) {
            clean(path);
        } else {
            if (env->verbose()) {
                std::cout << "Removing " << path << std::endl;
            }
            File::unlink(path);
        }
    }
}

void parse_option(std::string const& flag) {
    if ("library" == flag) {
        env->lib(argp->required_arg());
    } else if ("include" == flag) {
        env->include(argp->required_arg());
    } else if ("generator" == flag) {
        env->generator(argp->required_arg());
    } else if ("debug" == flag) {
        env->debug(true);
    } else if ("optimize" == flag) {
        env->optimize(true);
    } else if ("verbose" == flag) {
        env->verbose(true);
    } else if ("clean" == flag) {
        clean(env->build_dir());
        clean("bin");
        clean("lib");
        exit(0);
    } else if ("reset" == flag) {
        File::unlink(".jgmake");
        exit(0);
    } else {
        argp->bad_option(flag);
    }
}

void parse_short_option(std::string const& flag) {
    // Parses a short-form option ('-x')
    switch (flag[0]) {
    case 'l': parse_option("library"); break;
    case 'i': parse_option("include"); break;
    case 'g': parse_option("generator"); break;
    case 'd': parse_option("debug"); break;
    case 'o': parse_option("optimize"); break;
    case 'v': parse_option("verbose"); break;
    case 'c': parse_option("clean"); break;
    case 'r': parse_option("reset"); break;
    default: argp->bad_short_option(flag); break;
    }
}

void parse_options() {
    // Parse command line options, and update the environment to match the
    // specified options.
    argp->usage(
        "Usage: jgmake [OPTIONS] PACKAGE...\n\n"
        "Builds a Jogo project from the current working directory.  Source files should\n"
        "be under ./src; output files go to ./build, ./lib, ./bin, and ./doc.  Options\n"
        "given to jgmake are recorded.  After an option is set, it will remain set the\n"
        "next time jgmake is run.\n\n"
        "   -l, --library LIB    Compile and link with native library LIB.\n"
        "   -i, --include DIR    Add the directory DIR to the search path.\n"
        "   -d, --debug          Emit debug information.\n"
        "   -o, --optimize       Enable compiler optimizations.\n"
        "   -g, --generator GEN  Use code generator GEN.\n"
        "   -h, --help           Print this help message.\n"
        "   -v, --verbose        Print extra information during compilation.\n"
        "   -r, --reset          Erase all build options.\n"
        "   -c, --clean          Remove all output directories.\n"
        "   --version            Print the program version number.\n");

    for (ArgToken tok = argp->next(); tok; tok = argp->next()) {
        // Convert abbreviated flags into the longer descriptive form (e.g.,
        // convert -p to --path)
        if (ArgToken::SHORT == tok.type()) {
            parse_short_option(tok.value());
        } else if (ArgToken::LONG == tok.type()) {
            parse_option(tok.value());
        } else {
            env->input(tok.value());
        }
    }

    std::string gen = env->generator();
    if (gen != "Intel64" && gen != "C" && gen != "Nasm64") {
        argp->error("Invalid code generator (options: Intel64, Nasm64, C)");
    }
}

void load_options() {
    // Loads options from the options file.  FIXME: This settings file loader
    // is pretty haggard.  It should be replaced with JSON.
    std::ifstream opts(".jgmake");
    int c = opts.get();
    while (c != '\n' && !opts.fail()) {
        std::string include;
        while (c != ',' && c != '\n' && !opts.fail()) {
            include += c;
            c = opts.get();
        }
        env->include(include);
        c = opts.get();
    }
    c = opts.get();
    while (c != '\n' && !opts.fail()) {
        std::string lib;
        while (c != ',' && c != '\n' && !opts.fail()) {
            lib += c;
            c = opts.get();
        }
        env->lib(lib);
        c = opts.get();
    }
}

void save_options() {
    // Saves options to the options file.
    std::ofstream opts(".jgmake");
    for (int i = 0; i < env->includes(); ++i) {
        opts << env->include(i) << ",";
    }
    opts << std::endl;
    for (int i = 0; i < env->libs(); ++i) {
        opts << env->lib(i) << ",";
    }
    opts << std::endl;
}

int main(int argc, char** argv) {
    // This program recursively finds and builds all files in the source
    // directory, and then generates the output in the lib/bin directory.
    env->workspace_load();
    env->output(".");
    env->make(true);
    env->monolithic_build(false);

    argp = new ArgParser(env, argc, argv);
    load_options();
    parse_options();
    save_options();

    Builder::Ptr builder(new Builder(env));
    return builder->errors();
}


text:
from zope.interface import implements
from zope.component.factory import Factory
import os.path
from csv import DictReader

from sparc.cache.interfaces import ICachableSource

from sparc.logging import logging
logger = logging.getLogger(__name__)

class CSVSource(object):

    implements(ICachableSource)

    def __init__(self, source, factory, key = None):
        """Initialize the CSV data source

        The CSV data source, where the first data row in the represented file
        contains the field headers (names).

        Args:
            source: This can be a String, a csv.DictReader, or a generic object
                 that supports the iterator protocol (see csv.reader).  If
                 this is a String, it should point to either a CSV file,
                 or a directory containing CSV files.  If it is a
                 object supporting the iterator protocol, each call to next()
                 should return a valid csv line.
            factory: A callable that implements zope.component.factory.IFactory
                 that generates instances of ICachableItem.
            key: String name of CSV header field that acts as the unique key for each
                 CSV item entry (i.e. the primary key field)

        Raises:
            ValueError: if string source parameter does not point a referencable file or directory

        """
        # TODO: This class current has more methods than ICachableSource.  We either
        #       need to update the interface, or create a new one for the extra methods
        self._key = key
        self.source = source
        self.factory = factory
        self._files = list()
        self._csv_dictreader_list = list()

        if isinstance(source, str):
            if os.path.isfile(source):
                _file = open(source,'rb')
                self._files.append(_file)
                self._csv_dictreader_list.append(DictReader(_file))
            elif os.path.isdir(source):
                for _entry in os.listdir(source):
                    _file = open(_entry,'rb')
                    self._files.append(_file)
                    self._csv_dictreader_list.append(DictReader(_file))
            else:
                raise ValueError("expected string source parameter to reference a valid file or directory: " + str(source))
        elif isinstance(source, DictReader):
            self._csv_dictreader_list.append(source)
        else:
            self._csv_dictreader_list.append(DictReader(source))

    def __del__(self):
        """Object cleanup

        This will close all open file handles held by the object.
        """
        for f in self._files:
            f.close()

    def key(self):
        """Returns string identifier key that marks unique item entries (e.g. primary key field name)"""
        return self._key if self._key else self.factory().key

    def items(self):
        """Returns a generator of available ICachableItem in the ICachableSource
        """
        for dictreader in self._csv_dictreader_list:
            for entry in dictreader:
                item = self.factory()
                item.key = self.key()
                item.attributes = entry
                try:
                    item.validate()
                except Exception as e:
                    logger.debug("skipping entry due to item validation exception: %s", str(e))
                    continue
                logger.debug("found validated item in CSV source, key: %s", str(item.attributes[self.key()]))
                yield item

    def getById(self, Id):
        """Returns ICachableItem that matches id

        Args:
            id: String that identifies the item to return whose key matches
        """
        # we need to create a new object to insure we don't corrupt the generator count
        csvsource = CSVSource(self.source, self.factory, self.key())
        try:
            for item in csvsource.items():
                if Id == item.getId():
                    return item
        except StopIteration:
            return None

    def first(self):
        """Returns the first ICachableItem in the ICachableSource"""
        # we need to create a new object to insure we don't corrupt the generator count
        csvsource = CSVSource(self.source, self.factory, self.key())
        try:
            item = csvsource.items().next()
            return item
        except StopIteration:
            return None

CSVSourceFactory = Factory(CSVSource, 'CSVSourceFactory', 'generates CSVSource objects')


text:
package KTOptPrs;

import java.util.ArrayList;
import java.util.List;

public class AlternatingString {

	boolean allMasking = true;
	boolean startRule = false;
	List<String> nonTerminal = new ArrayList<>();
	List<String> terminal = new ArrayList<>();

	public AlternatingString (String input){

		if (input.equals("S")){
			startRule = true;
			nonTerminal.add("S");
			allMasking = false;
			return;
		}

		boolean capital = true;
		for (int i = 0; i<input.length(); i++){
			if (capital){
				if (input.charAt(i) >= 'a' && input.charAt(i) <= 'z'){
					nonTerminal.add(null);
					i--;
				} else {
					nonTerminal.add(input.charAt(i) + "");
					if (input.charAt(i) != 'M')
						allMasking = false;
				}
				capital = false;
			} else {
				terminal.add(input.charAt(i) + "");
				capital = true;
			}
		}
		if (capital)
			nonTerminal.add(null);
	}

	public boolean isAllMasking() {
		return allMasking;
	}

	public void setAllMasking(boolean allMasking) {
		this.allMasking = allMasking;
	}

	public boolean isStartRule() {
		return startRule;
	}

	public void setStartRule(boolean startRule) {
		this.startRule = startRule;
	}

	public List<String> getNonTerminal() {
		return nonTerminal;
	}

	public void setNonTerminal(List<String> nonTerminal) {
		this.nonTerminal = nonTerminal;
	}

	public List<String> getTerminal() {
		return terminal;
	}

	public void setTerminal(List<String> terminal) {
		this.terminal = terminal;
	}

	@Override
	public String toString() {
		String result = "";
		int i = 0;
		while (true){
			if (i >= nonTerminal.size() || i >= terminal.size()){
				break;
			}

			if (nonTerminal.get(i) != null){
				result = result + nonTerminal.get(i);
			}
			result = result + terminal.get(i);

			i++;
		}

		if (nonTerminal.get(i) != null)
			result = result + nonTerminal.get(i);

		return result;
	}

	@Override
	public boolean equals(Object obj) {
		AlternatingString input = (AlternatingString) obj;

		if (input.nonTerminal.size() != nonTerminal.size()){
			return false;
		}

		if (input.terminal.size() != terminal.size()){
			return false;
		}

		for (int i = 0; i < this.terminal.size(); i++) {
			if (!input.terminal.get(i).equals(this.terminal.get(i)))
				return false;
		}

		for (int i = 0; i < this.nonTerminal.size(); i++) {
			if (	(input.nonTerminal.get(i) == null && this.nonTerminal.get(i) != null) ||
					(input.nonTerminal.get(i) != null && this.nonTerminal.get(i) == null) ||
					(!input.nonTerminal.get(i).equals(this.nonTerminal.get(i)))
				)
			{
				return false;
			}
		}

		return true;
	}

}


text:
Our production server at www.anyway.co.il is hosted on DigitalOcean.
It is managed by Yehuda Deutsch.

To load new data from the CBS,

1. Request to be added to DigitalOcean of the Public Knowledge Workshop
2. Find the IP address of web1.anyway.co.il
3. Copy the new zip file to the server using SCP
4. Connect to the server using SSH
5. Clone the ANYWAY repository in your home directory and `cd` to it
6. Set `DATABASE_URL` to the URL for the production DB
7. Unzip the new zip file to `static/data/new/Accident Type 3`
8. Run `python process.py --path static/data/new`


text:
package Libs.FrameHandle;

public interface IResizeObject
{
    public void onResize(int viewWidth, int viewHeight);
}


text:
import re
import os.path

from django.test import TestCase
from django.test.client import Client
from django.template import TemplateDoesNotExist
from django.conf import settings

from maintenancemode import middleware as mw

class MaintenanceModeMiddlewareTestCase(TestCase):
    def setUp(self):
        # Reset config options adapted in the individual tests
        mw.MAINTENANCE_MODE = False
        settings.TEMPLATE_DIRS = ()
        settings.INTERNAL_IPS = ()

    def test_implicitly_disabled_middleware(self):
        "Middleware should default to being disabled"
        response = self.client.get('/')
        self.assertContains(response, text='Rendered response page', count=1, status_code=200)

    def test_disabled_middleware(self):
        "Explicitly disabling the MAINTENANCE_MODE should work"
        mw.MAINTENANCE_MODE = False

        response = self.client.get('/')
        self.assertContains(response, text='Rendered response page', count=1, status_code=200)

    def test_enabled_middleware_without_template(self):
        "Enabling the middleware without a proper 503 template should raise a template error"
        mw.MAINTENANCE_MODE = True

        self.assertRaises(TemplateDoesNotExist, self.client.get, '/')

    def test_enabled_middleware_with_template(self):
        "Enabling the middleware having a 503.html in any of the template locations should return the rendered template"
        mw.MAINTENANCE_MODE = True
        settings.TEMPLATE_DIRS = (settings.TEST_TEMPLATE_DIR,)

        response = self.client.get('/')
        self.assertContains(response, text='Temporary unavailable', count=1, status_code=503)
        self.assertContains(response, text='You requested: /', count=1, status_code=503)

    def test_middleware_with_non_staff_user(self):
        "A logged in user that is not a staff user should see the 503 message"
        mw.MAINTENANCE_MODE = True
        settings.TEMPLATE_DIRS = (settings.TEST_TEMPLATE_DIR,)

        from django.contrib.auth.models import User
        User.objects.create_user(username='maintenance', email='maintenance@example.org', password='maintenance_pw')

        self.client.login(username='maintenance', password='maintenance_pw')

        response = self.client.get('/')
        self.assertContains(response, text='Temporary unavailable', count=1, status_code=503)

    def test_middleware_with_staff_user(self):
        "A logged in user that _is_ a staff user should be able to use the site normally"
        mw.MAINTENANCE_MODE = True
        settings.TEMPLATE_DIRS = (settings.TEST_TEMPLATE_DIR,)

        from django.contrib.auth.models import User
        user = User.objects.create_user(username='maintenance', email='maintenance@example.org', password='maintenance_pw')
        user.is_staff = True
        user.save()

        self.client.login(username='maintenance', password='maintenance_pw')

        response = self.client.get('/')
        self.assertContains(response, text='Rendered response page', count=1, status_code=200)

    def test_middleware_with_internal_ips(self):
        "A user that visits the site from an IP in INTERNAL_IPS should be able to use the site normally"
        mw.MAINTENANCE_MODE = True
        settings.INTERNAL_IPS = ('127.0.0.1', )

        # Use a new Client instance to be able to set the REMOTE_ADDR used by INTERNAL_IPS
        client = Client(REMOTE_ADDR='127.0.0.1')

        response = client.get('/')
        self.assertContains(response, text='Rendered response page', count=1, status_code=200)

    def test_ignored_path(self):
        "A path is ignored when applying the maintanance mode and should be reachable normally"
        mw.MAINTENANCE_MODE = True
        mw.IGNORE_URLS = (
            re.compile(r'^/ignored.*'),
        )
        settings.TEMPLATE_DIRS = (settings.TEST_TEMPLATE_DIR,)

        response = self.client.get('/ignored/')
        self.assertContains(response, text='Rendered response page', count=1, status_code=200)


text:
Shiny.addCustomMessageHandler("generalErrorMessage",
	function(message){
		alert(JSON.stringify(message));
	}
);


text:
<!DOCTYPE HTML>

        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <title>0.2.0 | ScalaCSS</title>
        <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
        <meta name="description" content="">
        <meta name="generator" content="GitBook 2.1.0">

        <meta name="HandheldFriendly" content="true"/>
        <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
        <meta name="apple-mobile-web-app-capable" content="yes">
        <meta name="apple-mobile-web-app-status-bar-style" content="black">
        <link rel="apple-touch-icon-precomposed" sizes="152x152" href="../gitbook/images/apple-touch-icon-precomposed-152.png">
        <link rel="shortcut icon" href="../gitbook/images/favicon.ico" type="image/x-icon">

    <link rel="stylesheet" href="../gitbook/style.css">

        <link rel="stylesheet" href="../styles/website.css">

    <link rel="prev" href="../history/0.3.html" />

        <input type="text" placeholder="Type to search" class="form-control" />

                        Introduction

                            1.

                        Quick Start

                            1.1.

                        Standalone

                            1.2.

                        Inline

                            2.

                        Features

                            2.1.

                        Getting Started

                            2.2.

                        Conditional CSS

                            2.3.

                        Functions

                            2.4.

                        Composite/Nested Styles

                            2.5.

                        Typed CSS Values

                            2.6.

                        Browser Prefixes

                            2.7.

                        Conflict Detection

                            2.8.

                        Reusable Styles

                            2.9.

                        Global Registry

                            2.10.

                        External CSS Libraries

            3. Extensions

                            3.1.

                        scalajs-react

                            3.2.

                        Scalatags

                            4.

                        Gotchas

                            5.

                        Requirements

                            6.

                        Developing

                            7.

                        History

                            7.1.

                        0.3.0

                            7.2.

                        0.2.0

                Published with GitBook

        <button type="button" id="reduce-font-size" class="button size-2">A</button>
        <button type="button" id="enlarge-font-size" class="button size-2">A</button>

        <button type="button" data-font="0" class="button">Serif</button>
        <button type="button" data-font="1" class="button">Sans</button>

        <button type="button" id="color-theme-preview-0" class="button size-3" data-theme="0">White</button>
        <button type="button" id="color-theme-preview-1" class="button size-3" data-theme="1">Sepia</button>
        <button type="button" id="color-theme-preview-2" class="button size-3" data-theme="2">Night</button>

                <button type="button" data-sharing="twitter" class="button">
                    Share on Twitter
                </button>
                <button type="button" data-sharing="google-plus" class="button">
                    Share on Google
                </button>
                <button type="button" data-sharing="facebook" class="button">
                    Share on Facebook
                </button>
                <button type="button" data-sharing="weibo" class="button">
                    Share on Weibo
                </button>
                <button type="button" data-sharing="instapaper" class="button">
                    Share on Instapaper
                </button>

        ScalaCSS

0.2.0 (commit log)

Changed package to just scalacss. Many projects already do this.

Automate the transition with this:
find . -type f -name '*.scala' -exec perl -pi -e 's/japgolly\.(?=scalacss)//g' {} +

Reduced JS output size to less than half. (#17)

Style composition now handles compatable duplicates without warning. (#28)

Style composition warnings gained more detail.

// Before
[CSS WARNING] .scalacss-0001 -- margin overridden by marginLeft.
[CSS WARNING] .scalacss-0002 -- cursor overridden by cursor.

// After
[CSS WARNING] .MyStyles-0001 -- {margin-left: 6px} conflicts with {margin: 12px}
[CSS WARNING] .MyStyles-0002 -- {cursor: zoom-in} conflicts with {cursor: pointer}

Manually-specified className no longer propagated in style composition. (#25)

CSS no longer generated for empty styles,
including styles consisting solely of addClassNames.

Added DevDefaults and ProdDefaults with Defaults choosing between the two.

StyleSheets

Changes to generated CSS class names:

In prod-mode, each StyleSheet gets a different prefix.

In dev-mode, class names are prefixed by the StyleSheet class/object name.

You can specify your own class name prefix by adding this to your StyleSheet:
override implicit val classNameHint = ClassNameHint("TEST")

This means that separate, unrelated StyleSheets can be used in the same process without overlap.

Added mutable.GlobalRegistry as an optional convenience for managing shared stylesheets.

See Global Registry feature doc.

Added .styles and .css to StyleSheet.

StyleSheet now warn if new styles are registered after .render, .css, .styles called.

(Yep, that's why it's in the mutable package.)

DSL

Attribute aliases in DSL were missing Scaladoc.

New DSL: mixin(…).
(The difference between style() which registers, and styleS() which doesn't, was too fine.)

New DSL: mixinIf(bool)(…).

New DSL: mixinIfElse(bool)(…)(…).

New DSL: <String>.color. Example: borderColor("#080".color).

Add literals to DSL auto-import: inherit,initial, unset.

Renamed literal each_line to eachLine.

Typed CSS

Four-edge CSS attributes had vertical/horizontal around the wrong way.
// These correctly generate {margin: 4px 1ex}
margin(4 px, 1 ex)
margin(h = 1.ex, v = 4.px)

Four-edge CSS attributes learned .vertical and .horizontal.
margin.vertical(4 px)
// ↑ is a shortcut for ↓
marginTop(4 px) compose marginBottom(4 px)

clear learned inlineStart and inlineEnd values.

float learned inlineStart and inlineEnd values.

Browser prefixes

Added browser prefixes for...

captionSide block/inline start/end values.

display flex and grid values.

fontSizeAdjust keys.

order keys.

textAlign start/end values.


text:
define(['./module'],function(services){
    'use strict';
    services.factory('windowWidth', function(){
    	return {
    		getWindowDimensions: function() {
    			return window.innerWidth;
    		}
    	};
    });
});


text:
        Details

        Images

        Urls

        To-Do

        Activities

        Scheduled Activities

        Itineraries

Second div


text:
/* (c) 2014 LinkedIn Corp. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use
 * this file except in compliance with the License. You may obtain a copy of the
 * License at  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed
 * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
 * CONDITIONS OF ANY KIND, either express or implied.
 */

package com.linkedin.cubert.functions;

import java.io.IOException;
import java.util.List;

import org.apache.pig.data.Tuple;

import com.linkedin.cubert.block.Block;
import com.linkedin.cubert.block.BlockSchema;
import com.linkedin.cubert.block.ColumnType;
import com.linkedin.cubert.operator.PreconditionException;

/**
 * Abstract class for defining user-defined functions for the GENERATE operator.
 *

 * The UDF class is responsible for:
 *

 *
generating the output column type ({@code getCacheFile} method).

 *
 *
evaluating the input tuple and generating the output ({@code eval} method)

 *
 *
[Optionally] listing the files that must be stored in the distributed cache (
 * {@code getCacheFiles} method)

 *

 *

 * The UDF has access to the current block using the protected {@code setBlock} method.
 *

 * Note: the {@code outputSchema} and {@code getCacheFiles} methods will be called at the
 * compile time, as well as the run time.
 *

 * At run time, the {@code outputSchema} method is called before calling the {@code eval}
 * method (so it okay to initialize object variables in the outputSchema method).
 *
 * @author Maneesh Varshney
 *
 */
public abstract class Function
{
    /**
     * Optionally override this method to perform setup operations.
     *
     * @param block
     */
    protected void setBlock(Block block) throws PreconditionException
    {

    }

    /**
     * Evaluate the input tuple to generate output object.
     *
     * @param tuple
     *            the input tuple
     * @return evaluated output
     * @throws IOException
     */
    public abstract Object eval(Tuple tuple) throws IOException;

    /**
     * Generate the ColumnType of the output.
     *
     * @param inputSchema
     *            Schema of the input tuple
     * @return Output object ColumnType
     * @throws PreconditionException
     */
    public abstract ColumnType outputSchema(BlockSchema inputSchema) throws PreconditionException;

    /**
     * Returns a list of files that must be stored in distributed cache.
     *
     * @return a list of file names
     */
    public List<String> getCacheFiles()
    {
        return null;
    }
}


text:
<?xml version='1.0' encoding='UTF-8'?>
<Document>
  <Header>
    <SchemaName>Location</SchemaName>
    <Identifier>location_geonames_2745314</Identifier>
    <DocumentState>public</DocumentState>
    <TimeStamp>1390753461862</TimeStamp>
    <SummaryFields>
      <Title>NL > North Brabant > Gemeente Reusel-De Mierden > Vooreind</Title>
    </SummaryFields>
  </Header>
  <Body>
    <Location>
      <GeopoliticalHierarchy>NL,North Brabant,Gemeente Reusel-De Mierden,Vooreind</GeopoliticalHierarchy>
      <LocationName>
        <Appelation>Vooreind</Appelation>
        <LocationNameType>populated place</LocationNameType>
        <Comments></Comments>
      </LocationName>
      <Coordinates>
        <Longitude>5.16528</Longitude>
        <Latitude>51.39083</Latitude>
      </Coordinates>
      <GeonamesURI>http://www.geonames.org/2745314</GeonamesURI>
      <WikipediaLink/>
      <DbpediaLink/>
    </Location>
  </Body>
</Document>


text:
<?php

namespace Interop\Injector;

interface InjectorInterface
{
    /**
     * Define constructor arguments for a class or alias
     *
     * @param string $spec
     * @param array $args
     *
     * @return self
     */
    public function define($spec, array $args);

    /**
     * Register a invokable to prepare an object instance
     *
     * The invokable may be a PHP callable, the name of a class that has an
     * `__invoke` method, or the name of a class with a non-static method.
     *
     * The invokable must take two arguments: the instantiated object and the
     * current injector.
     *
     * If the invokable returns an object of the same type, it will replace the
     * current instance, to allow immutable objects to be mutated.
     *
     * @param string $spec
     * @param callable|string $invokable
     *
     * @return self
     */
    public function prepare($spec, $invokable);

    /**
     * Register a invokable to create an object instance
     *
     * The invokable may be a PHP callable, the name of a class that has an
     * `__invoke` method, or the name of a class with a non-static method.
     *
     * The invokable must take one argument: the injector.
     *
     * The invokable must return an instance of the specified class.
     *
     * @param string $spec
     * @param callable|string $invokable
     *
     * @return self
     */
    public function delegate($spec, $invokable);

    /**
     * Define an alias for a class
     *
     * @param string $spec
     * @param string $alias
     *
     * @return self
     */
    public function alias($spec, $alias);

    /**
     * Create a new instance of a class and provision it
     *
     * @param string $spec
     *
     * @return object
     */
    public function make($spec);

    /**
     * Share the specified class/instance within the injector context
     *
     * @param string|object $specOrInstance
     *
     * @return self
     */
    public function share($specOrInstance);
}


text:
package com.streever.hadoop.hive.percent.honey;

/**
 * Created by dstreev on 2016-10-30.
 */
public class ConvertPercent {
    public static String convert(String value) {

        String working = value;
        if (value.contains("%")) {
            working = working.replaceAll("%","");
            Double wrkDbl = Double.parseDouble(working);
            wrkDbl = wrkDbl / 100;
            working = wrkDbl.toString();
        }
        return working;
    }
}


text:
#include "NDG2D.h"

//---------------------------------------------------------
class Euler2D : public NDG2D
//---------------------------------------------------------
{
public:
  Euler2D();
  virtual ~Euler2D();
  virtual void Driver();

protected:

  virtual void Run();

  virtual void Resize();        // resize system arrays
  virtual void Resize_cub();    // resize cubature arrays
  virtual void SetIC();
  virtual void SetStepSize();
  virtual void InitRun();
  virtual void Report(bool bForce=false);
  virtual void DisplaySolution(bool bForce=false);

  // define pointers to functions
  typedef void (Euler2D::*fp_IC)(const DVec& xi, const DVec& yi, double ti, DMat& Qo);
  typedef void (Euler2D::*fp_ES)(const DVec& xi, const DVec& yi, double ti, DMat& Qo);
  typedef void (Euler2D::*fp_BC)(const DVec& xi, const DVec& yi, double ti, DMat& Qio);

  fp_IC InitialSolution;  // function pointer to initial solution
  fp_ES ExactSolution;    // function pointer to exact solution
  fp_BC BCSolution;       // function pointer to boundary conditions

  // functions for initial/exact solutions
//void IsentropicVortex2D(const DVec& xi, const DVec& yi, double ti, DMat& Qo);
//void PlaneFlow2D       (const DVec& xi, const DVec& yi, double ti, DMat& Qo);
  void BumpFlowIC2D      (const DVec& xi, const DVec& yi, double ti, DMat& Qo);
  void ForwardStepIC2D   (const DVec& xi, const DVec& yi, double ti, DMat& Qo);
  void ShockBubbleIC2D   (const DVec& xi, const DVec& yi, double ti, DMat& Qo);

  // functions for boundary solutions
//void IsentropicVortexBC2D(const DVec& xi, const DVec& yi, double ti, DMat& Qio);
//void ChannelBC2D         (const DVec& xi, const DVec& yi, double ti, DMat& Qio);
  void BumpFlowBC2D        (const DVec& xi, const DVec& yi, double ti, DMat& Qio);
  void ForwardStepBC2D     (const DVec& xi, const DVec& yi, double ti, DMat& Qio);
  void ShockBubbleBC2D     (const DVec& xi, const DVec& yi, double ti, DMat& Qio);

  void MapGaussFaceData();
  void RHS(DMat& Qin, double ti, fp_BC SolutionBC);

  void Fluxes(DMat& Qin, DMat& F, DMat& G);
  void Fluxes(DMat& Qin, double gamma, DMat& F, DMat& G, DVec& rho, DVec& u, DVec& v, DVec& p);

  void LF2D   (const DVec& lnx, const DVec& lny, DMat& QM, DMat& QP, double gamma, DMat& FLUX);
  void Roe2D  (const DVec& lnx, const DVec& lny, DMat& QM, DMat& QP, double gamma, DMat& FLUX);
  void Eigen2D(const DVec& lnx, const DVec& lny, DMat& QM, DMat& QP, double gamma, DMat& FLUX, bool b=false);
  void HLLC2D (const DVec& lnx, const DVec& lny, DMat& QM, DMat& QP, double gamma, DMat& flux);

  void  EvalSmoothness();
  void  LimitWaves(DMat wave[5], const DMat& s);
  DMat& Limit2D(const DMat& Qin);

  void  Eval_SrcEXP();
  void  Eval_SrcIMP();
  void  Load_Aux();

protected:

  //-------------------------------------
  // member data
  //-------------------------------------

  // select simulation mode
  enum {
    eIsentropicVortex = 0,
    eChannelFlow      = 1,
    eBumpFlow         = 2,
    eForwardStep      = 3,
    eShockBubble      = 4
  };

  int sim_mode;
  double gamma,gamma1;

  DMat  m_Q, rhsQ, resQ;
  DMat  QsrcEXP,QsrcIMP;  // explicit/implicit source terms

  DMat  Q1, limQ;
  DMat  QM, QP, Qbc;
  DMat  cQ, cF,  cG;      // Q evaluated at cubature nodes
  DMat  gQ, gQM, gQP;     // Q, {Q+, Q-}, evaluated at gauss nodes
  DMat  flux;             // calculated flux
  DMat  aux;              // auxillary data (e.g. for geometric source terms)

  DVec  phi;              // smoothness indicator
  DVec  C1, C2, C3, C4;   // characteristic variables ("strengths")
                          // (coefficients in eigenvector sums)
  DMat  wave[5];          // waves using characteristic recomposition
  DMat  ws;               // wave speeds
  DMat  CP, CM, CR;       // coefficients at QP, QM and Roe average

  DVec LimAVE;

  int m_nExplicit, m_nImplicit;

  // monitor range of primitive variables
  double rmin,rmax,umin,umax,vmin,vmax,pmin,pmax;

  // NBN: OPTIMIZE DEBUG
  double rhs_dt, rhs_time;
  double flux_time, flux_dt;

  // initial conditions routines
  // common/fsscorn/ xc0,yc0,xc1,yc1
  double xc0,yc0,xc1,yc1;
  double x0, y0, r0;

  double cellave(const DVec& xk, const DVec& yk);
  double fdisc(const double x, const double y);
  double fss(double s);
  double zeroin(const double x1, const double x2,double tol);

  void   RefineDisk(IMat& flags, double x0, double y0, double r0, double tol);

  DVec qin;     // initial state inside bubble
  DVec qout;    // initial state outside bubble

  double rhoin; // density in bubble:

  double rinf;  // density behind shock
  double vinf;  // velocity behind shock
  double einf;  // energy behind shock
  double pinf;  // pressure behind shock:

  double m_lambda;

};

#endif  // NDG__Euler2D_H__INCLUDED


text: Common interface wrapper around arbitary KVP-based data stores


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN">

<title>About</title>
<meta http-equiv=Content-Type content="text/html; charset=ISO-8859-1">

About This Content

(c) 2010 JBoss by Red Hat

License

Licensed under the Apache License, Version 2.0 (the "License");

you may not use this file except in compliance with the License.

You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software

distributed under the License is distributed on an "AS IS" BASIS,

WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

See the License for the specific language governing permissions

and limitations under the License.


text:
[![Build Status](https://travis-ci.org/joshmcarthur/mail-logger.png?branch=master)](https://travis-ci.org/joshmcarthur/mail-logger)

You know how you're looking through your logs to see how your mailing is doing, and after all that request rubbish, you just can't see that **Sent mail** stuff? Annoying, right?

MailLogger to the rescue! It lodges a callback with `Mail`, capturing all of the mail being sent, and logging it to it's own file, so you can simply look back through that file to see what's up. Easy peasy!

I could be a pain and require Rails here, but I don't. If you are using Rails, then this gem should put things in the right place: `#{Rails.root}/log/mail_{development,etc}.log` - no extra work necessary. If you are not using Rails, then the gem will place the log file in `./log` - wherever that may be.

Default paths getting you down? Not to worry, this gem is configurable!

``` ruby
Mail::Logger.configure do |config|
  config.log_path = "Whatever you want"
  config.log_file_name = "all my emails.log"
end
```

(If you're using Rails, this belongs in `config/initializers/mail_logger.rb`)

## Installation

Add this line to your application's Gemfile:

    gem 'mail-logger'

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install mail-logger

> Please note: There's another project around called [**mail_logger**](https://rubygems.org/gems/mail_logger), which records details of mail to the database via ActiveRecord, instead of a log file (which is what this project does). While I certainly didn't intend to infringe, the other project hasn't been updated in a few years, so I'm sticking with this name.

## Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request


text:
.. _utils_auto:

``utils`` API Reference
=======================

.. automodule:: tidegates.utils
   :members:
   :undoc-members:


text:
#include "envoy/config/bootstrap/v3/bootstrap.pb.h"
#include "envoy/extensions/transport_sockets/alts/v3/alts.pb.h"

#include "common/common/thread.h"

#include "extensions/transport_sockets/alts/config.h"

#include "test/core/tsi/alts/fake_handshaker/fake_handshaker_server.h"
#include "test/integration/http_integration.h"
#include "test/integration/integration.h"
#include "test/integration/server.h"
#include "test/integration/utility.h"
#include "test/mocks/server/mocks.h"
#include "test/test_common/network_utility.h"
#include "test/test_common/utility.h"

#include "absl/strings/match.h"
#include "absl/strings/str_cat.h"
#include "gmock/gmock.h"
#include "grpcpp/grpcpp.h"
#include "grpcpp/impl/codegen/service_type.h"
#include "gtest/gtest.h"

using ::testing::ReturnRef;

namespace Envoy {
namespace Extensions {
namespace TransportSockets {
namespace Alts {
namespace {

class AltsIntegrationTestBase : public testing::TestWithParam<Network::Address::IpVersion>,
                                public HttpIntegrationTest {
public:
  AltsIntegrationTestBase(const std::string& server_peer_identity,
                          const std::string& client_peer_identity, bool server_connect_handshaker,
                          bool client_connect_handshaker)
      : HttpIntegrationTest(Http::CodecClient::Type::HTTP1, GetParam()),
        server_peer_identity_(server_peer_identity), client_peer_identity_(client_peer_identity),
        server_connect_handshaker_(server_connect_handshaker),
        client_connect_handshaker_(client_connect_handshaker) {}

  void initialize() override {
    config_helper_.addConfigModifier([this](envoy::config::bootstrap::v3::Bootstrap& bootstrap) {
      auto* transport_socket = bootstrap.mutable_static_resources()
                                   ->mutable_listeners(0)
                                   ->mutable_filter_chains(0)
                                   ->mutable_transport_socket();
      transport_socket->set_name("envoy.transport_sockets.alts");
      envoy::extensions::transport_sockets::alts::v3::Alts alts_config;
      if (!server_peer_identity_.empty()) {
        alts_config.add_peer_service_accounts(server_peer_identity_);
      }
      alts_config.set_handshaker_service(fakeHandshakerServerAddress(server_connect_handshaker_));
      transport_socket->mutable_typed_config()->PackFrom(alts_config);
    });
    HttpIntegrationTest::initialize();
    registerTestServerPorts({"http"});
  }

  void SetUp() override {
    fake_handshaker_server_thread_ = api_->threadFactory().createThread([this]() {
      std::unique_ptr<grpc::Service> service = grpc::gcp::CreateFakeHandshakerService();

      std::string server_address = Network::Test::getLoopbackAddressUrlString(version_) + ":0";
      grpc::ServerBuilder builder;
      builder.AddListeningPort(server_address, grpc::InsecureServerCredentials(),
                               &fake_handshaker_server_port_);
      builder.RegisterService(service.get());

      fake_handshaker_server_ = builder.BuildAndStart();
      fake_handshaker_server_ci_.setReady();
      fake_handshaker_server_->Wait();
    });

    fake_handshaker_server_ci_.waitReady();

    NiceMock<Server::Configuration::MockTransportSocketFactoryContext> mock_factory_ctx;
    // We fake the singleton manager for the client, since it doesn't need to manage ALTS global
    // state, this is done by the test server instead.
    // TODO(htuch): Make this a proper mock.
    class FakeSingletonManager : public Singleton::Manager {
    public:
      Singleton::InstanceSharedPtr get(const std::string&, Singleton::SingletonFactoryCb) override {
        return nullptr;
      }
    };
    FakeSingletonManager fsm;
    ON_CALL(mock_factory_ctx, singletonManager()).WillByDefault(ReturnRef(fsm));
    UpstreamAltsTransportSocketConfigFactory factory;

    envoy::extensions::transport_sockets::alts::v3::Alts alts_config;
    alts_config.set_handshaker_service(fakeHandshakerServerAddress(client_connect_handshaker_));
    if (!client_peer_identity_.empty()) {
      alts_config.add_peer_service_accounts(client_peer_identity_);
    }
    ProtobufTypes::MessagePtr config = factory.createEmptyConfigProto();
    TestUtility::jsonConvert(alts_config, *config);
    ENVOY_LOG_MISC(info, "{}", config->DebugString());

    client_alts_ = factory.createTransportSocketFactory(*config, mock_factory_ctx);
  }

  void TearDown() override {
    HttpIntegrationTest::cleanupUpstreamAndDownstream();
    dispatcher_->clearDeferredDeleteList();
    if (fake_handshaker_server_ != nullptr) {
      fake_handshaker_server_->Shutdown();
    }
    fake_handshaker_server_thread_->join();
  }

  Network::ClientConnectionPtr makeAltsConnection() {
    Network::Address::InstanceConstSharedPtr address = getAddress(version_, lookupPort("http"));
    return dispatcher_->createClientConnection(address, Network::Address::InstanceConstSharedPtr(),
                                               client_alts_->createTransportSocket(nullptr),
                                               nullptr);
  }

  std::string fakeHandshakerServerAddress(bool connect_to_handshaker) {
    if (connect_to_handshaker) {
      return absl::StrCat(Network::Test::getLoopbackAddressUrlString(version_), ":",
                          std::to_string(fake_handshaker_server_port_));
    }
    return wrongHandshakerServerAddress();
  }

  std::string wrongHandshakerServerAddress() { return " "; }

  Network::Address::InstanceConstSharedPtr getAddress(const Network::Address::IpVersion& version,
                                                      int port) {
    std::string url =
        "tcp://" + Network::Test::getLoopbackAddressUrlString(version) + ":" + std::to_string(port);
    return Network::Utility::resolveUrl(url);
  }

  const std::string server_peer_identity_;
  const std::string client_peer_identity_;
  bool server_connect_handshaker_;
  bool client_connect_handshaker_;
  Thread::ThreadPtr fake_handshaker_server_thread_;
  std::unique_ptr<grpc::Server> fake_handshaker_server_;
  ConditionalInitializer fake_handshaker_server_ci_;
  int fake_handshaker_server_port_{};
  Network::TransportSocketFactoryPtr client_alts_;
};

class AltsIntegrationTestValidPeer : public AltsIntegrationTestBase {
public:
  // FakeHandshake server sends "peer_identity" as peer service account. Set this
  // information into config to pass validation.
  AltsIntegrationTestValidPeer()
      : AltsIntegrationTestBase("peer_identity", "",
                                /* server_connect_handshaker */ true,
                                /* client_connect_handshaker */ true) {}
};

INSTANTIATE_TEST_SUITE_P(IpVersions, AltsIntegrationTestValidPeer,
                         testing::ValuesIn(TestEnvironment::getIpVersionsForTest()),
                         TestUtility::ipTestParamsToString);

// Verifies that when received peer service account passes validation, the alts
// handshake succeeds.
TEST_P(AltsIntegrationTestValidPeer, RouterRequestAndResponseWithBodyNoBuffer) {
  ConnectionCreationFunction creator = [this]() -> Network::ClientConnectionPtr {
    return makeAltsConnection();
  };
  testRouterRequestAndResponseWithBody(1024, 512, false, &creator);
}

class AltsIntegrationTestEmptyPeer : public AltsIntegrationTestBase {
public:
  AltsIntegrationTestEmptyPeer()
      : AltsIntegrationTestBase("", "",
                                /* server_connect_handshaker */ true,
                                /* client_connect_handshaker */ true) {}
};

INSTANTIATE_TEST_SUITE_P(IpVersions, AltsIntegrationTestEmptyPeer,
                         testing::ValuesIn(TestEnvironment::getIpVersionsForTest()),
                         TestUtility::ipTestParamsToString);

// Verifies that when peer service account is not set into config, the alts
// handshake succeeds.
TEST_P(AltsIntegrationTestEmptyPeer, RouterRequestAndResponseWithBodyNoBuffer) {
  ConnectionCreationFunction creator = [this]() -> Network::ClientConnectionPtr {
    return makeAltsConnection();
  };
  testRouterRequestAndResponseWithBody(1024, 512, false, &creator);
}

class AltsIntegrationTestClientInvalidPeer : public AltsIntegrationTestBase {
public:
  AltsIntegrationTestClientInvalidPeer()
      : AltsIntegrationTestBase("", "invalid_client_identity",
                                /* server_connect_handshaker */ true,
                                /* client_connect_handshaker */ true) {}
};

INSTANTIATE_TEST_SUITE_P(IpVersions, AltsIntegrationTestClientInvalidPeer,
                         testing::ValuesIn(TestEnvironment::getIpVersionsForTest()),
                         TestUtility::ipTestParamsToString);

// Verifies that when client receives peer service account which does not match
// any account in config, the handshake will fail and client closes connection.
TEST_P(AltsIntegrationTestClientInvalidPeer, clientValidationFail) {
  initialize();
  codec_client_ = makeRawHttpConnection(makeAltsConnection());
  EXPECT_FALSE(codec_client_->connected());
}

class AltsIntegrationTestServerInvalidPeer : public AltsIntegrationTestBase {
public:
  AltsIntegrationTestServerInvalidPeer()
      : AltsIntegrationTestBase("invalid_server_identity", "",
                                /* server_connect_handshaker */ true,
                                /* client_connect_handshaker */ true) {}
};

INSTANTIATE_TEST_SUITE_P(IpVersions, AltsIntegrationTestServerInvalidPeer,
                         testing::ValuesIn(TestEnvironment::getIpVersionsForTest()),
                         TestUtility::ipTestParamsToString);

// Verifies that when Envoy receives peer service account which does not match
// any account in config, the handshake will fail and Envoy closes connection.
TEST_P(AltsIntegrationTestServerInvalidPeer, ServerValidationFail) {
  initialize();

  testing::NiceMock<Network::MockConnectionCallbacks> client_callbacks;
  Network::ClientConnectionPtr client_conn = makeAltsConnection();
  client_conn->addConnectionCallbacks(client_callbacks);
  EXPECT_CALL(client_callbacks, onEvent(Network::ConnectionEvent::Connected));
  client_conn->connect();

  EXPECT_CALL(client_callbacks, onEvent(Network::ConnectionEvent::RemoteClose))
      .WillOnce(Invoke([&](Network::ConnectionEvent) -> void { dispatcher_->exit(); }));
  dispatcher_->run(Event::Dispatcher::RunType::Block);
}

class AltsIntegrationTestClientWrongHandshaker : public AltsIntegrationTestBase {
public:
  AltsIntegrationTestClientWrongHandshaker()
      : AltsIntegrationTestBase("", "",
                                /* server_connect_handshaker */ true,
                                /* client_connect_handshaker */ false) {}
};

INSTANTIATE_TEST_SUITE_P(IpVersions, AltsIntegrationTestClientWrongHandshaker,
                         testing::ValuesIn(TestEnvironment::getIpVersionsForTest()),
                         TestUtility::ipTestParamsToString);

// Verifies that when client connects to the wrong handshaker server, handshake fails
// and connection closes.
TEST_P(AltsIntegrationTestClientWrongHandshaker, ConnectToWrongHandshakerAddress) {
  initialize();
  codec_client_ = makeRawHttpConnection(makeAltsConnection());
  EXPECT_FALSE(codec_client_->connected());
}

} // namespace
} // namespace Alts
} // namespace TransportSockets
} // namespace Extensions
} // namespace Envoy


text:
var Guacamole = Guacamole || {};

/**
 * A description of the format of raw PCM audio, such as that used by
 * Guacamole.RawAudioPlayer and Guacamole.RawAudioRecorder. This object
 * describes the number of bytes per sample, the number of channels, and the
 * overall sample rate.
 *
 * @constructor
 * @param {Guacamole.RawAudioFormat|Object} template
 *     The object whose properties should be copied into the corresponding
 *     properties of the new Guacamole.RawAudioFormat.
 */
Guacamole.RawAudioFormat = function RawAudioFormat(template) {

    /**
     * The number of bytes in each sample of audio data. This value is
     * independent of the number of channels.
     *
     * @type {Number}
     */
    this.bytesPerSample = template.bytesPerSample;

    /**
     * The number of audio channels (ie: 1 for mono, 2 for stereo).
     *
     * @type {Number}
     */
    this.channels = template.channels;

    /**
     * The number of samples per second, per channel.
     *
     * @type {Number}
     */
    this.rate = template.rate;

};

/**
 * Parses the given mimetype, returning a new Guacamole.RawAudioFormat
 * which describes the type of raw audio data represented by that mimetype. If
 * the mimetype is not a supported raw audio data mimetype, null is returned.
 *
 * @param {String} mimetype
 *     The audio mimetype to parse.
 *
 * @returns {Guacamole.RawAudioFormat}
 *     A new Guacamole.RawAudioFormat which describes the type of raw
 *     audio data represented by the given mimetype, or null if the given
 *     mimetype is not supported.
 */
Guacamole.RawAudioFormat.parse = function parseFormat(mimetype) {

    var bytesPerSample;

    // Rate is absolutely required - if null is still present later, the
    // mimetype must not be supported
    var rate = null;

    // Default for both "audio/L8" and "audio/L16" is one channel
    var channels = 1;

    // "audio/L8" has one byte per sample
    if (mimetype.substring(0, 9) === 'audio/L8;') {
        mimetype = mimetype.substring(9);
        bytesPerSample = 1;
    }

    // "audio/L16" has two bytes per sample
    else if (mimetype.substring(0, 10) === 'audio/L16;') {
        mimetype = mimetype.substring(10);
        bytesPerSample = 2;
    }

    // All other types are unsupported
    else
        return null;

    // Parse all parameters
    var parameters = mimetype.split(',');
    for (var i = 0; i < parameters.length; i++) {

        var parameter = parameters[i];

        // All parameters must have an equals sign separating name from value
        var equals = parameter.indexOf('=');
        if (equals === -1)
            return null;

        // Parse name and value from parameter string
        var name  = parameter.substring(0, equals);
        var value = parameter.substring(equals+1);

        // Handle each supported parameter
        switch (name) {

            // Number of audio channels
            case 'channels':
                channels = parseInt(value);
                break;

            // Sample rate
            case 'rate':
                rate = parseInt(value);
                break;

            // All other parameters are unsupported
            default:
                return null;

        }

    };

    // The rate parameter is required
    if (rate === null)
        return null;

    // Return parsed format details
    return new Guacamole.RawAudioFormat({
        bytesPerSample : bytesPerSample,
        channels       : channels,
        rate           : rate
    });

};


text: "# ethersummary.github.io"


text:
import * as React from 'react';

import Box from '@material-ui/core/Box';
import Grid from '@material-ui/core/Grid';
import Container from '@material-ui/core/Container';
import Typography from '../components/Typography';

const item = {
  display: 'flex',
  flexDirection: 'column',
  alignItems: 'center',
  px: 5,
};

function ProductValues() {
  return (
    <Box
      component="section"
      sx={{ display: 'flex', overflow: 'hidden', bgcolor: 'secondary.light' }}
    >
      <Container sx={{ mt: 15, mb: 30, display: 'flex', position: 'relative' }}>
        <Box
          component="img"
          src="/static/themes/onepirate/productCurvyLines.png"
          alt="curvy lines"
          sx={{ pointerEvents: 'none', position: 'absolute', top: -180 }}
        />
        <Grid container spacing={5}>
          <Grid item xs={12} md={4}>
            <Box sx={item}>
              <Box
                component="img"
                src="/static/themes/onepirate/productValues1.svg"
                alt="suitcase"
                sx={{ height: 55 }}
              />
              <Typography variant="h6" sx={{ my: 5 }}>
                The best luxury hotels
              </Typography>
              <Typography variant="h5">
                {
                  'From the latest trendy boutique hotel to the iconic palace with XXL pool'
                }

                {
                  ', go for a mini-vacation just a few subway stops away from your home.'
                }
              </Typography>
            </Box>
          </Grid>
          <Grid item xs={12} md={4}>
            <Box sx={item}>
              <Box
                component="img"
                src="/static/themes/onepirate/productValues2.svg"
                alt="graph"
                sx={{ height: 55 }}
              />
              <Typography variant="h6" sx={{ my: 5 }}>
                New experiences
              </Typography>
              <Typography variant="h5">
                {
                  'Privatize a pool, take a Japanese bath or wake up in 900m2 of garden… '
                }

                {'your Sundays will not be alike.'}
              </Typography>
            </Box>
          </Grid>
          <Grid item xs={12} md={4}>
            <Box sx={item}>
              <Box
                component="img"
                src="/static/themes/onepirate/productValues3.svg"
                alt="clock"
                sx={{ height: 55 }}
              />
              <Typography variant="h6" sx={{ my: 5 }}>
                Exclusive rates
              </Typography>
              <Typography variant="h5">
                {'By registering, you will access specially negotiated rates '}
                {'that you will not find anywhere else.'}
              </Typography>
            </Box>
          </Grid>
        </Grid>
      </Container>
    </Box>
  );
}

export default ProductValues;


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
null

#### Original name
Sclerospora northi W. Weston

### Remarks
null


text:
import * as IconContents from "./generated/iconContents";
import * as IconNames from "./generated/iconNames";

export { IconContents, IconNames };
export { IconSvgPaths20 } from "./generated/iconSvgPaths";
export { IconName } from "./iconName";


text:
> see https://aka.ms/autorest

This is the AutoRest configuration file for ServerManagement.

---
## Getting Started
To build the SDK for ServerManagement, simply [Install AutoRest](https://aka.ms/autorest/install) and in this folder, run:

> `autorest`

To see additional help and options, run:

> `autorest --help`
---

## Configuration

### Basic Information
These are the global settings for the ServerManagement API.

``` yaml
openapi-type: arm
tag: package-2016-07-preview
```

### Tag: package-2016-07-preview

These settings apply only when `--tag=package-2016-07-preview` is specified on the command line.

``` yaml $(tag) == 'package-2016-07-preview'
input-file:
- Microsoft.ServerManagement/preview/2016-07-01-preview/servermanagement.json
```

### Tag: package-2015-07-preview

These settings apply only when `--tag=package-2015-07-preview` is specified on the command line.

``` yaml $(tag) == 'package-2015-07-preview'
input-file:
- Microsoft.ServerManagement/preview/2015-07-01-preview/servermanagement.json
```

---
# Code Generation

## Swagger to SDK

This section describes what SDK should be generated by the automatic system.
This is not used by Autorest itself.

``` yaml $(swagger-to-sdk)
swagger-to-sdk:
  - repo: azure-sdk-for-python
  - repo: azure-sdk-for-java
  - repo: azure-sdk-for-go
  - repo: azure-sdk-for-node
  - repo: azure-sdk-for-ruby
    after_scripts:
      - bundle install && rake arm:regen_all_profiles['azure_mgmt_server_management']
```

## C#

These settings apply only when `--csharp` is specified on the command line.
Please also specify `--csharp-sdks-folder=<path to "SDKs" directory of your azure-sdk-for-net clone>`.

``` yaml $(csharp)
csharp:
  azure-arm: true
  license-header: MICROSOFT_MIT_NO_VERSION
  namespace: Microsoft.Azure.Management.ServerManagement
  output-folder: $(csharp-sdks-folder)/ServerManagement/Management.ServerManagement/Generated
  clear-output-folder: true
```

## Python

These settings apply only when `--python` is specified on the command line.
Please also specify `--python-sdks-folder=<path to the root directory of your azure-sdk-for-python clone>`.
Use `--python-mode=update` if you already have a setup.py and just want to update the code itself.

``` yaml $(python)
python-mode: create
python:
  azure-arm: true
  license-header: MICROSOFT_MIT_NO_VERSION
  payload-flattening-threshold: 2
  namespace: azure.mgmt.servermanager
  package-name: azure-mgmt-servermanager
  clear-output-folder: true
```
``` yaml $(python) && $(python-mode) == 'update'
python:
  no-namespace-folders: true
  output-folder: $(python-sdks-folder)/azure-mgmt-servermanager/azure/mgmt/servermanager
```
``` yaml $(python) && $(python-mode) == 'create'
python:
  basic-setup-py: true
  output-folder: $(python-sdks-folder)/azure-mgmt-servermanager
```

## Go

These settings apply only when `--go` is specified on the command line.

``` yaml $(go)
go:
  license-header: MICROSOFT_APACHE_NO_VERSION
  namespace: servermanagement
  clear-output-folder: true
```

### Go multi-api

``` yaml $(go) && $(multiapi)
batch:
  - tag: package-2016-07-preview
  - tag: package-2015-07-preview
```

### Tag: package-2016-07-preview and go

These settings apply only when `--tag=package-2016-07-preview --go` is specified on the command line.
Please also specify `--go-sdk-folder=<path to the root directory of your azure-sdk-for-go clone>`.

``` yaml $(tag) == 'package-2016-07-preview' && $(go)
output-folder: $(go-sdk-folder)/services/preview/servermanagement/mgmt/2016-07-01-preview/servermanagement
```

### Tag: package-2015-07-preview and go

These settings apply only when `--tag=package-2015-07-preview --go` is specified on the command line.
Please also specify `--go-sdk-folder=<path to the root directory of your azure-sdk-for-go clone>`.

``` yaml $(tag) == 'package-2015-07-preview' && $(go)
output-folder: $(go-sdk-folder)/services/preview/servermanagement/mgmt/2015-07-01-preview/servermanagement
```

## Java

These settings apply only when `--java` is specified on the command line.
Please also specify `--azure-libraries-for-java-folder=<path to the root directory of your azure-libraries-for-java clone>`.

``` yaml $(java)
azure-arm: true
fluent: true
namespace: com.microsoft.azure.management.servermanagement
license-header: MICROSOFT_MIT_NO_CODEGEN
payload-flattening-threshold: 1
output-folder: $(azure-libraries-for-java-folder)/azure-mgmt-servermanagement
```

### Java multi-api

``` yaml $(java) && $(multiapi)
batch:
  - tag: package-2015-07-preview
  - tag: package-2016-07-preview
```

### Tag: package-2015-07-preview and java

These settings apply only when `--tag=package-2015-07-preview --java` is specified on the command line.
Please also specify `--azure-libraries-for-java=<path to the root directory of your azure-sdk-for-java clone>`.

``` yaml $(tag) == 'package-2015-07-preview' && $(java) && $(multiapi)
java:
  namespace: com.microsoft.azure.management.servermanagement.v2015_07_01_preview
  output-folder: $(azure-libraries-for-java-folder)/servermanagement/resource-manager/v2015_07_01_preview
regenerate-manager: true
generate-interface: true
```

### Tag: package-2016-07-preview and java

These settings apply only when `--tag=package-2016-07-preview --java` is specified on the command line.
Please also specify `--azure-libraries-for-java=<path to the root directory of your azure-sdk-for-java clone>`.

``` yaml $(tag) == 'package-2016-07-preview' && $(java) && $(multiapi)
java:
  namespace: com.microsoft.azure.management.servermanagement.v2016_07_01_preview
  output-folder: $(azure-libraries-for-java-folder)/servermanagement/resource-manager/v2016_07_01_preview
regenerate-manager: true
generate-interface: true
```


text:
"""Add LocalSite.public.

Version Added:
    1.7.21
"""

from django_evolution.mutations import AddField
from django.db import models

MUTATIONS = [
    AddField('LocalSite', 'public', models.BooleanField, initial=False)
]