text:
package org.wso2.andes.client.handler;

import org.wso2.andes.AMQException;
import org.wso2.andes.client.protocol.AMQProtocolSession;
import org.wso2.andes.client.security.AMQCallbackHandler;
import org.wso2.andes.client.security.CallbackHandlerRegistry;
import org.wso2.andes.client.state.AMQState;
import org.wso2.andes.client.state.StateAwareMethodListener;
import org.wso2.andes.common.ClientProperties;
import org.wso2.andes.common.QpidProperties;
import org.wso2.andes.framing.AMQShortString;
import org.wso2.andes.framing.ConnectionStartBody;
import org.wso2.andes.framing.ConnectionStartOkBody;
import org.wso2.andes.framing.FieldTable;
import org.wso2.andes.framing.FieldTableFactory;
import org.wso2.andes.framing.ProtocolVersion;

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

import javax.security.sasl.Sasl;
import javax.security.sasl.SaslClient;
import javax.security.sasl.SaslException;

import java.io.UnsupportedEncodingException;
import java.util.HashSet;
import java.util.StringTokenizer;

public class ConnectionStartMethodHandler implements StateAwareMethodListener<ConnectionStartBody>
{
    private static final Logger _log = LoggerFactory.getLogger(ConnectionStartMethodHandler.class);

    private static final ConnectionStartMethodHandler _instance = new ConnectionStartMethodHandler();

    public static ConnectionStartMethodHandler getInstance()
    {
        return _instance;
    }

    private ConnectionStartMethodHandler()
    { }

    public void methodReceived(AMQProtocolSession session, ConnectionStartBody body, int channelId)
            throws AMQException
    {
        _log.debug("public void methodReceived(AMQStateManager stateManager, AMQProtocolSession protocolSession, "
            + "AMQMethodEvent evt): called");

        ProtocolVersion pv = new ProtocolVersion((byte) body.getVersionMajor(), (byte) body.getVersionMinor());

        // 0-9-1 is indistinguishable from 0-9 using only major and minor ... if we established the connection as 0-9-1
        // and now get back major = 0 , minor = 9 then we can assume it means 0-9-1

        if(pv.equals(ProtocolVersion.v0_9) && session.getProtocolVersion().equals(ProtocolVersion.v0_91))
        {
            pv = ProtocolVersion.v0_91;
        }

        // For the purposes of interop, we can make the client accept the broker's version string.
        // If it does, it then internally records the version as being the latest one that it understands.
        // It needs to do this since frame lookup is done by version.
        if (Boolean.getBoolean("qpid.accept.broker.version") && !pv.isSupported())
        {

            pv = ProtocolVersion.getLatestSupportedVersion();
        }

        if (pv.isSupported())
        {
            session.setProtocolVersion(pv);

            try
            {
                // Used to hold the SASL mechanism to authenticate with.
                String mechanism;

                if (body.getMechanisms()== null)
                {
                    throw new AMQException(null, "mechanism not specified in ConnectionStart method frame", null);
                }
                else
                {
                    mechanism = chooseMechanism(body.getMechanisms());
                    _log.debug("mechanism = " + mechanism);
                }

                if (mechanism == null)
                {
                    throw new AMQException(null, "No supported security mechanism found, passed: " + new String(body.getMechanisms()), null);
                }

                byte[] saslResponse;
                try
                {
                    SaslClient sc =
                        Sasl.createSaslClient(new String[] { mechanism }, null, "AMQP", "localhost", null,
                            createCallbackHandler(mechanism, session));
                    if (sc == null)
                    {
                        throw new AMQException(null, "Client SASL configuration error: no SaslClient could be created for mechanism " + mechanism
                            + ". Please ensure all factories are registered. See DynamicSaslRegistrar for "
                            + " details of how to register non-standard SASL client providers.", null);
                    }

                    session.setSaslClient(sc);
                    saslResponse = (sc.hasInitialResponse() ? sc.evaluateChallenge(new byte[0]) : null);
                }
                catch (SaslException e)
                {
                    session.setSaslClient(null);
                    throw new AMQException(null, "Unable to create SASL client: " + e, e);
                }

                if (body.getLocales() == null)
                {
                    throw new AMQException(null, "Locales is not defined in Connection Start method", null);
                }

                final String locales = new String(body.getLocales(), "utf8");
                final StringTokenizer tokenizer = new StringTokenizer(locales, " ");
                if (tokenizer.hasMoreTokens())
                {
                    tokenizer.nextToken();
                }
                else
                {
                    throw new AMQException(null, "No locales sent from server, passed: " + locales, null);
                }

                session.getStateManager().changeState(AMQState.CONNECTION_NOT_TUNED);
                FieldTable clientProperties = FieldTableFactory.newFieldTable();

                clientProperties.setString(new AMQShortString(ClientProperties.instance.toString()),
                    session.getClientID());
                clientProperties.setString(new AMQShortString(ClientProperties.product.toString()),
                    QpidProperties.getProductName());
                clientProperties.setString(new AMQShortString(ClientProperties.version.toString()),
                    QpidProperties.getReleaseVersion());
                clientProperties.setString(new AMQShortString(ClientProperties.platform.toString()), getFullSystemInfo());

                ConnectionStartOkBody connectionStartOkBody = session.getMethodRegistry().createConnectionStartOkBody(clientProperties,new AMQShortString(mechanism),saslResponse,new AMQShortString(locales));
                // AMQP version change: Hardwire the version to 0-8 (major=8, minor=0)
                // TODO: Connect this to the session version obtained from ProtocolInitiation for this session.
                // Be aware of possible changes to parameter order as versions change.
                session.writeFrame(connectionStartOkBody.generateFrame(channelId));

            }
            catch (UnsupportedEncodingException e)
            {
                throw new AMQException(null, "Unable to decode data: " + e, e);
            }
        }
        else
        {
            _log.error("Broker requested Protocol [" + body.getVersionMajor() + "-" + body.getVersionMinor()
                + "] which is not supported by this version of the client library");

            session.closeProtocolSession();
        }
    }

    private String getFullSystemInfo()
    {
        StringBuffer fullSystemInfo = new StringBuffer();
        fullSystemInfo.append(System.getProperty("java.runtime.name"));
        fullSystemInfo.append(", " + System.getProperty("java.runtime.version"));
        fullSystemInfo.append(", " + System.getProperty("java.vendor"));
        fullSystemInfo.append(", " + System.getProperty("os.arch"));
        fullSystemInfo.append(", " + System.getProperty("os.name"));
        fullSystemInfo.append(", " + System.getProperty("os.version"));
        fullSystemInfo.append(", " + System.getProperty("sun.os.patch.level"));

        return fullSystemInfo.toString();
    }

    private String chooseMechanism(byte[] availableMechanisms) throws UnsupportedEncodingException
    {
        final String mechanisms = new String(availableMechanisms, "utf8");
        StringTokenizer tokenizer = new StringTokenizer(mechanisms, " ");
        HashSet mechanismSet = new HashSet();
        while (tokenizer.hasMoreTokens())
        {
            mechanismSet.add(tokenizer.nextToken());
        }

        String preferredMechanisms = CallbackHandlerRegistry.getInstance().getMechanisms();
        StringTokenizer prefTokenizer = new StringTokenizer(preferredMechanisms, " ");
        while (prefTokenizer.hasMoreTokens())
        {
            String mech = prefTokenizer.nextToken();
            if (mechanismSet.contains(mech))
            {
                return mech;
            }
        }

        return null;
    }

    private AMQCallbackHandler createCallbackHandler(String mechanism, AMQProtocolSession protocolSession)
        throws AMQException
    {
        Class mechanismClass = CallbackHandlerRegistry.getInstance().getCallbackHandlerClass(mechanism);
        try
        {
            Object instance = mechanismClass.newInstance();
            AMQCallbackHandler cbh = (AMQCallbackHandler) instance;
            cbh.initialise(protocolSession.getAMQConnection().getConnectionURL());

            return cbh;
        }
        catch (Exception e)
        {
            throw new AMQException(null, "Unable to create callback handler: " + e, e);
        }
    }

}


text:
using System;
using System.Globalization;

namespace Haushaltsbuch.Objects
{
    /// <summary>
    /// Klasse, die einen Eintrag repräsentiert.
    /// </summary>
    public class Transaction
    {
        #region Methoden

        /// <summary>
        /// Initialisiert eine neue Instanz der <see cref="Transaction" /> Klasse.
        /// </summary>
        /// <param name="dateTime">Datum des Eintrags.</param>
        public Transaction(DateTime dateTime)
        {
            Date = dateTime;
        }

        #endregion

        #region Eigenschaften

        /// <summary>
        /// Holt oder setzt Art des Eintrags.
        /// </summary>
        public Helper.TransactionType TransactionType
        {
            get;
            set;
        }

        /// <summary>
        /// Holt oder setzt Beschreibung des Eintrags.
        /// </summary>
        public string Description
        {
            get;
            set;
        }

        /// <summary>
        /// Holt oder setzt Betrag des Eintrags.
        /// </summary>
        public string Amount
        {
            get;
            set;
        }

        /// <summary>
        /// Formatierter Betrag des Eintrags.
        /// </summary>
        public string AmountString
            => Convert.ToDecimal(Amount, new CultureInfo("de-DE")).ToString("F", CultureInfo.CurrentCulture);

        /// <summary>
        /// Holt oder setzt Kategorie des Eintrags.
        /// </summary>
        public string Category
        {
            get;
            set;
        }

        /// <summary>
        /// Holt Datum des Eintrags.
        /// </summary>
        public DateTime Date
        {
            get;
        }

        /// <summary>
        /// Formatiertes Datum des Eintrags.
        /// </summary>
        public string DateString => Date.ToShortDateString();

        /// <summary>
        /// Tag des Datums.
        /// </summary>
        public string Day => Date.Day.ToString("D2", CultureInfo.InvariantCulture);

        /// <summary>
        /// Monat des Datums.
        /// </summary>
        public string Month => Date.Month.ToString("D2", CultureInfo.InvariantCulture);

        /// <summary>
        /// Jahr des Datums.
        /// </summary>
        public string Year => Date.Year.ToString("D4", CultureInfo.InvariantCulture);

        #endregion
    }
}

redpajama_set_name: RedPajamaGithub


text:
- `h` ←
- `l` →
- `k` ↑
- `j` ↓
- `0` Go to the first character of the line
- `^` Go to the first non-blank charater of the line
- `$` Go to the end of the line
- `gg` Go to the first line
- `G` Go to the last line

## Buffers
- `:ls` List buffers
- `:e` Reload current bufffer
- `:bd!|e [file]` Open `file` in current buffer
- `:N,Mbd` Delete buffers from `N` to `M`

## Windows
- `:q` Quit the current window
- `:q!` Quit the current window, discard any changes
- `:clo` Close the current window, unless it is the last one
- `:on` Make the current window the only one
- `Ctrl-W s` Create a horizontal split
- `Ctrl-W v` Create a vertical split
- `Ctrl-W h` Go to left window
- `Ctrl-W l` Go to right window
- `Ctrl-W k` Go to up window
- `Ctrl-W j` Go to down window

## Scrolling

- `z<CR>` or `zt` Put current line to top of screen (`<CR>` == Enter)
- `z.` or `zz` Put current line to center of screen
- `z-` or `zb` Put current line to bottom of screen

## Commands
To search through command history, enter the prefix of your previous command and push \<Up\>.

To configure command history size
```
:set history=1000
```

## Folds
- `zo` Open one fold
- `zc` Close one fold
- `zr` Reduce folding
- `zm` Fold more
- `zR` Open all folds
- `zM` Close all folds

## Diff mode
- `[c` Jump to the previous conflict
- `]c` Jump to the next conflict
- `:diffg [bufspec]` Copy change from `[bufspec]` the current buffer
- `:diffp [bufspec]` Copy change from the current buffer to `[bufspec]`
- `:'<,'>diffg` `:'<,'>diffp` Copy change in the selected region

### Config

Use the same config for both Vim and Neovim:

```sh
mkdir -p ~/.config/
ln -s ~/.vim ~/.config/nvim
ln -s ~/.vimrc ~/.config/nvim/init.vim
````


text:
import json
import sys
import os
import re
import inspect
import docutils

import sphinx_rtd_theme

# To avoid needing to maintain a working sphinx install for the matrix
# of Gaffer python versions, we dump out version information into a
# generic form, so we can read it here.
with open( "./gafferVars.json" ) as f :
	gaffer = json.load( f )

# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))

# -- General configuration ------------------------------------------------

# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'

# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = []

# Add any paths that contain templates here, relative to this directory.
templates_path = []

# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
source_suffix = ['.rst', '.md']

# The encoding of source files.
#source_encoding = 'utf-8-sig'

# The master toctree document.
master_doc = 'index'

# General information about the project.
project = gaffer["name"]
copyright = gaffer["copyright"].replace( "Copyright (c) ", "" )
author = u'John Haddon'

# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = gaffer["versionString"]
# The full version, including alpha/beta/rc tags.
release = gaffer["versionString"]

# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None

# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'

# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This patterns also effect to html_static_path and html_extra_path
exclude_patterns = []

# The reST default role (used for this markup: `text`) to use for all
# documents.
#default_role = None

# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True

# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True

# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False

# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'

# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []

# If true, keep warnings as "system message" paragraphs in the built documents.
#keep_warnings = False

# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = False

# -- Options for HTML output ----------------------------------------------

# The theme to use for HTML and HTML Help pages.  See the documentation for
# a list of builtin themes.
html_theme = "sphinx_rtd_theme"

# Theme options are theme-specific and customize the look and feel of a theme
# further.  For a list of options available for each theme, see the
# documentation.
html_theme_options = {
	'logo_only': True,
	'collapse_navigation': False
}

# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []

# The name for this set of Sphinx documents.
# "<project> v<release> documentation" by default.
#html_title = u'Gaffer v0.24.0.0'

# A shorter title for the navigation bar.  Default is the same as html_title.
#html_short_title = None

# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
html_logo = "_static/GafferLogoMini.svg"

# The name of an image file (relative to this directory) to use as a favicon of
# the docs.  This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
html_favicon = "_static/favicon.ico"

# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = [ "_static" ]

# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
#html_extra_path = []

# If not None, a 'Last updated on:' timestamp is inserted at every page
# bottom, using the given strftime format.
# The empty string is equivalent to '%b %d, %Y'.
#html_last_updated_fmt = None

# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
html_use_smartypants = True

# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}

# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}

# If false, no module index is generated.
#html_domain_indices = True

# If false, no index is generated.
#html_use_index = True

# If true, the index is split into individual pages for each letter.
#html_split_index = False

# If true, links to the reST sources are added to the pages.
html_show_sourcelink = False

# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True

# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True

# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it.  The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''

# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None

# Language to be used for generating the HTML full-text search index.
# Sphinx supports the following languages:
#   'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja'
#   'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr', 'zh'
#html_search_language = 'en'

# A dictionary with options for the search language support, empty by default.
# 'ja' uses this config value.
# 'zh' user can custom change `jieba` dictionary path.
#html_search_options = {'type': 'default'}

# The name of a javascript file (relative to the configuration directory) that
# implements a search results scorer. If empty, the default will be used.
#html_search_scorer = 'scorer.js'

# Output file base name for HTML help builder.
htmlhelp_basename = 'Gafferdoc'

# -- Options for LaTeX output ---------------------------------------------

latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',

# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',

# Additional stuff for the LaTeX preamble.
#'preamble': '',

# Latex figure (float) alignment
#'figure_align': 'htbp',
}

# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
#  author, documentclass [howto, manual, or own class]).
latex_documents = [
	(master_doc, 'Gaffer.tex', u'Gaffer Documentation',
	u'John Haddon', 'manual'),
]

# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None

# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False

# If true, show page references after internal links.
#latex_show_pagerefs = False

# If true, show URL addresses after external links.
#latex_show_urls = False

# Documents to append as an appendix to all manuals.
#latex_appendices = []

# If false, no module index is generated.
#latex_domain_indices = True

# -- Options for manual page output ---------------------------------------

# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
	(master_doc, 'gaffer', u'Gaffer Documentation',
	[author], 1)
]

# If true, show URL addresses after external links.
#man_show_urls = False

# -- Options for Texinfo output -------------------------------------------

# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
#  dir menu entry, description, category)
texinfo_documents = [
	(master_doc, 'Gaffer', u'Gaffer Documentation',
	author, 'Gaffer', 'One line description of project.',
	'Miscellaneous'),
]

# Documents to append as an appendix to all manuals.
#texinfo_appendices = []

# If false, no module index is generated.
#texinfo_domain_indices = True

# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'

# If true, do not generate a @detailmenu in the "Top" node's menu.
#texinfo_no_detailmenu = False

# Variables for string replacement functions

arnold_version = '7.1.1.1'
arnold_path_linux = '/opt/solidangle/arnold-{0}'.format( arnold_version )
arnold_path_osx = '/opt/solidangle/arnold-{0}'.format( arnold_version )

delight_version = '13.0.18'
delight_path_linux = '/opt/3delight-{0}'.format( delight_version )
delight_path_osx = '/opt/3delight-{0}'.format( delight_version )

tractor_version = '2.2'
tractor_path_linux = '/opt/pixar/Tractor-{0}'.format( tractor_version )
tractor_path_osx = '/Applications/pixar/Tractor-{0}'.format( tractor_version )

# Add the `myst_parser` extension, which adds a parser
# for MarkDown files with a `.md` extension.
extensions = [ "myst_parser" ]
myst_enable_extensions = [ "substitution" ]

class GafferTransform( docutils.transforms.Transform ) :

	default_priority = 1
	suffix_set = { "md" }

	def apply( self, *kw ) :

		for node in self.document.traverse( docutils.nodes.block_quote ) :

			# Convert block quotes beginning with "admonitionType :" to real
			# admonitions. This allows us to create admonitions in pure
			# Markdown, without resorting to `{eval-rst}` directives.

			if not len( node ) :
				continue

			if not isinstance( node[0], docutils.nodes.paragraph ) :
				continue

			if not isinstance( node[0][0], docutils.nodes.Text ) :
				continue

			partition = node[0][0].partition( ":" )
			if not partition[1] :
				continue

			admonitions = dict( inspect.getmembers( docutils.nodes, lambda x : inspect.isclass( x ) and issubclass( x, docutils.nodes.Admonition ) ) )

			admonition = partition[0].strip().lower()
			if admonition not in admonitions :
				continue

			node[0][0] = docutils.nodes.Text( partition[2] ) # Remove "admonition : " prefix
			node.replace_self( admonitions[admonition]( "", *node.children ) )

def gafferSourceSubstitutions( app, docName, source ) :

	source[0] = source[0].replace( "!GAFFER_VERSION!", gaffer["versionString"] )
	source[0] = source[0].replace( "!GAFFER_MILESTONE_VERSION!", str( gaffer["milestoneVersion"] ) )
	source[0] = source[0].replace( "!GAFFER_MAJOR_VERSION!", str( gaffer["majorVersion"] ) )
	source[0] = source[0].replace( "!GAFFER_MINOR_VERSION!", str( gaffer["minorVersion"] ) )
	source[0] = source[0].replace( "!GAFFER_PATCH_VERSION!", str( gaffer["patchVersion"] ) )

def thirdPartySourceSubtitutions( app, docName, source) :

	source[0] = source[0].replace( "!ARNOLD_VERSION!", arnold_version )
	source[0] = source[0].replace( "!ARNOLD_PATH_LINUX!", arnold_path_linux )
	source[0] = source[0].replace( "!ARNOLD_PATH_OSX!", arnold_path_osx )
	source[0] = source[0].replace( "!DELIGHT_VERSION!", delight_version )
	source[0] = source[0].replace( "!DELIGHT_PATH_LINUX!", delight_path_linux )
	source[0] = source[0].replace( "!DELIGHT_PATH_OSX!", delight_path_osx )
	source[0] = source[0].replace( "!TRACTOR_VERSION!", tractor_version )
	source[0] = source[0].replace( "!TRACTOR_PATH_LINUX!", tractor_path_linux )
	source[0] = source[0].replace( "!TRACTOR_PATH_OSX!", tractor_path_osx )

def setup( app ) :

	app.add_transform( GafferTransform )

	app.connect( "source-read", gafferSourceSubstitutions )
	app.connect( "source-read", thirdPartySourceSubtitutions )

	# Add the custom stylesheet; used in all .md and .rst files in source
	app.add_css_file( 'gaffer.css' )
	app.add_js_file( 'scrollspy.js' )


text:
require 'active_record/test_in_memory'
require 'enumerated_attribute'
require 'active_record'
require 'active_record/inheritance_classes'

def one_to_four; [:one, :two, :three, :four]; end
def gear1; [:reverse, :neutral, :first, :second, :over_drive]; end
def gear2; [:reverse, :neutral, :first, :second, :third, :over_drive]; end
def choke; [:none, :medium, :full]; end

describe "SubRaceCar" do
	it "should have :gear init to :neutral" do
		o=SubRaceCar.new
		o.gear.should == :neutral
		o.enums(:gear).should == gear1
		o.gear_previous.should == :reverse
	end
	it "should have :choke init to :none" do
		o=SubRaceCar.new
		o.choke.should == :none
		o.enums(:choke).should == choke
		o.choke_previous.should == :full
	end
	it "should have :extra init to :one" do
		o=SubRaceCar.new
		o.extra.should == :one
		o.enums(:extra).should == one_to_four
		o.extra_previous.should == :four
	end
end

describe "SubRaceCar2" do
	it "should have :gear init to :neutral" do
		o=SubRaceCar2.new
		o.gear.should == :neutral
		o.enums(:gear).should == gear1
		o.gear_previous.should == :reverse
	end
	it "should have :choke init to :none" do
		o=SubRaceCar2.new
		o.choke.should == :none
		o.enums(:choke).should == choke
		o.choke_previous.should == :full
	end
end

describe "SubRaceCar3" do
	it "should have overridden :gear init to :first" do
		o=SubRaceCar3.new
		o.gear.should == :first
		o.enums(:gear).should == gear2
		o.gear_previous.should == :neutral
	end
	it "should have :choke init to :none" do
		o=SubRaceCar3.new
		o.choke.should == :none
		o.enums(:choke).should == choke
		o.choke_previous.should == :full
	end
end


text:
package org.elasticsearch.index.mapper;

import org.elasticsearch.common.compress.CompressedXContent;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.index.MapperTestUtils;
import org.elasticsearch.test.ESTestCase;

import java.io.IOException;

import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;

public class MultiFieldIncludeInAllMapperTests extends ESTestCase {
    public void testExceptionForIncludeInAllInMultiFields() throws IOException {
        XContentBuilder mapping = createMappingWithIncludeInAllInMultiField();

        // first check that for newer versions we throw exception if include_in_all is found within multi field
        MapperService mapperService = MapperTestUtils.newMapperService(xContentRegistry(), createTempDir(), Settings.EMPTY);
        mapperService.parse("type", new CompressedXContent(mapping.string()), true);
        assertWarnings("include_in_all in multi fields is deprecated because it doesn't do "
                + "anything. Found the include_in_all in field [c] which is within a multi field.");
    }

    private static XContentBuilder createMappingWithIncludeInAllInMultiField() throws IOException {
        XContentBuilder mapping = jsonBuilder();
        mapping.startObject()
                .startObject("type")
                .startObject("properties")
                .startObject("a")
                .field("type", "text")
                .endObject()
                .startObject("b")
                .field("type", "text")
                .startObject("fields")
                .startObject("c")
                .field("type", "text")
                .field("include_in_all", false)
                .endObject()
                .endObject()
                .endObject()
                .endObject()
                .endObject()
                .endObject();
        return mapping;
    }
}


text:
using System;
using Windows.UI.Xaml.Data;

namespace BooksSample.Converters
{
    public class ObjectToObjectConverter : IValueConverter
    {
        // TODO: expression bodied member

        public object Convert(object value, Type targetType, object parameter, string language)
        {
            return value;
        }

        public object ConvertBack(object value, Type targetType, object parameter, string language)
        {
            return value;
        }

    }
}


text:
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes       #-}
{-# LANGUAGE TemplateHaskell   #-}

module Dupes.Index.Internal.SQLite (
    FileCacheEntry(..),
    WorkingDirectoryPath(..),
    updateEntry,
    initialize,
    listDuplicates,
    listHashesWithDuplicates,
    listFilesWithHash,
    testGroup,
    deleteEntryByPath,
    ) where

import           Data.Maybe
import           Data.String.Interpolate
import qualified Data.Text                        as T
import           Database.SQLite.Simple           as SQLite
import           Database.SQLite.Simple.FromField
import           Database.SQLite.Simple.ToField
import           Dupes.FileHash                   (FileHash)
import qualified Dupes.FileHash                   as FileHash
import           Dupes.FileStat                   as FileStat
import           Pipes
import qualified Pipes.Prelude                    as P
import           Pipes.Safe
import qualified Pipes.SQLite.Simple              as PSQLite
import           Test.Tasty.HUnit
import           Test.Tasty.TH

newtype WorkingDirectoryPath = WorkingDirectoryPath FilePath
  deriving (Eq, Show)

instance FromField WorkingDirectoryPath where
  fromField field = WorkingDirectoryPath <$> fromField field

instance ToField WorkingDirectoryPath where
  toField (WorkingDirectoryPath path) = toField path

data FileCacheEntry = FileCacheEntry WorkingDirectoryPath FileStat FileHash
  deriving (Eq, Show)

instance FromRow FileCacheEntry where
  fromRow = FileCacheEntry <$> field <*> field <*> field

instance ToRow FileCacheEntry where
  toRow (FileCacheEntry path stat hash) = [toField path, toField stat, toField hash]

tableName :: String
tableName = "FileCache"

initialize :: Connection -> IO ()
initialize connection = SQLite.execute_ connection createTableQuery
  where
    createTableQuery :: Query
    createTableQuery =
      queryString
        [i|
        CREATE TABLE IF NOT EXISTS #{tableName} (
            path TEXT PRIMARY KEY ASC,
            stat BLOB,
            hash BLOB)
                WITHOUT ROWID;
        CREATE INDEX hash_idx ON Index (hash);|]

queryString :: String -> Query
queryString = Query . T.pack

listDuplicates :: Connection -> Producer (FilePath, FileHash) (SafeT IO) ()
listDuplicates connection = PSQLite.query connection query ()
  where
    query :: Query
    query =
      queryString
        [i|
        SELECT entry.path, grouping.hash
        FROM (SELECT hash
              FROM #{tableName}
              GROUP BY hash
              HAVING count() > 1) AS grouping
        JOIN #{tableName} as entry ON entry.hash = grouping.hash
        ORDER BY grouping.hash|]

listHashesWithDuplicates :: Connection -> Producer FileHash (SafeT IO) ()
listHashesWithDuplicates connection = PSQLite.query connection query () >-> P.map unOnly
  where
    query :: Query
    query =
      queryString
        [i|
        SELECT hash
        FROM #{tableName}
        GROUP BY hash
        HAVING count() > 1|]

listFilesWithHash :: Connection -> FileHash -> Producer FilePath (SafeT IO) ()
listFilesWithHash connection hash = PSQLite.query connection query (Only hash) >-> P.map unOnly
  where
    query :: Query
    query =
      queryString
        [i|
        SELECT path
        FROM #{tableName}
        WHERE hash = ?|]

unOnly :: Only x -> x
unOnly (Only x) = x

containsPathWithStat :: Connection -> WorkingDirectoryPath -> FileStat -> IO Bool
containsPathWithStat connection path stat = do
  maybeEntry <- getEntryByPath connection path
  return $
    case maybeEntry of
      Just (FileCacheEntry _ stat' _) -> stat == stat'
      Nothing                         -> False

updateEntry :: Connection -> FileCacheEntry -> IO ()
updateEntry connection entry@(FileCacheEntry path stat hash) = do
  maybeEntry <- getEntryByPath connection path
  case maybeEntry of
    Just _  -> SQLite.execute connection updateQuery (stat, hash, path)
    Nothing -> addEntry connection entry

  where
    updateQuery = queryString
                    [i|
        UPDATE #{tableName}
        SET stat = ?, hash = ?
        WHERE path = ?|]

deleteEntryByPath :: Connection -> WorkingDirectoryPath -> IO ()
deleteEntryByPath connection path =
  SQLite.execute connection query (Only path)
  where
    query =
      queryString
        [i|
          DELETE
          FROM #{tableName}
          WHERE path = ?|]

getEntryByPath :: Connection -> WorkingDirectoryPath -> IO (Maybe FileCacheEntry)
getEntryByPath connection path =
  listToMaybe <$> SQLite.query connection query (Only path)
  where
    query =
      queryString
        [i|
        SELECT path, stat, hash
        FROM #{tableName}
        WHERE path = ?|]

addEntry :: Connection -> FileCacheEntry -> IO ()
addEntry connection = execute connection query
  where
    query :: Query
    query = Query $ T.pack [i|INSERT INTO #{tableName} (path, stat, hash) VALUES (?, ?, ?)|]

case_add_then_get = SQLite.withConnection ":memory:" $ \connection -> do
  initialize connection
  addEntry connection entry
  maybeEntry' <- getEntryByPath connection path
  Just entry @=? maybeEntry'
  where
    path = WorkingDirectoryPath "file"
    entry = FileCacheEntry path FileStat.create FileHash.nullHash

case_add_then_contains = SQLite.withConnection ":memory:" $ \connection -> do
  initialize connection
  addEntry connection entry
  contained <- containsPathWithStat connection path stat
  assertBool "Contains should be true after add" contained
  where
    path = WorkingDirectoryPath "file"
    stat = FileStat.create
    entry = FileCacheEntry path stat FileHash.nullHash

case_add_dupes_then_list = SQLite.withConnection ":memory:" $ \connection -> do
  initialize connection
  addEntry connection entry1
  addEntry connection entry2
  dupes <- runSafeT $ P.toListM (listDuplicates connection)
  2 @=? length dupes
  where
    path1 = WorkingDirectoryPath "file1"
    path2 = WorkingDirectoryPath "file2"
    stat = FileStat.create
    entry1 = FileCacheEntry path1 stat FileHash.nullHash
    entry2 = FileCacheEntry path2 stat FileHash.nullHash

case_update_with_no_previous_entry_adds = SQLite.withConnection ":memory:" $ \connection -> do
  initialize connection
  updateEntry connection entry
  maybeEntry' <- getEntryByPath connection path
  Just entry @=? maybeEntry'
  where
    path = WorkingDirectoryPath "file"
    entry = FileCacheEntry path FileStat.create FileHash.nullHash

case_update_with_previous_entry_updates = SQLite.withConnection ":memory:" $ \connection -> do
  initialize connection
  addEntry connection entryPrevious
  updateEntry connection entryNew
  maybeEntry' <- getEntryByPath connection path
  Just entryNew @=? maybeEntry'
  where
    path = WorkingDirectoryPath "file"
    entryPrevious = FileCacheEntry path FileStat.create (FileHash.hashByteString "0")
    entryNew = FileCacheEntry path FileStat.create (FileHash.hashByteString "1")

testGroup = $(testGroupGenerator)


text:
from .device import Device, WorkflowException
from .msgtypes import *

RED = [62978, 65535, 65535, 3500]
ORANGE = [5525, 65535, 65535, 3500]
YELLOW = [7615, 65535, 65535, 3500]
GREEN = [16173, 65535, 65535, 3500]
CYAN = [29814, 65535, 65535, 3500]
BLUE = [43634, 65535, 65535, 3500]
PURPLE = [50486, 65535, 65535, 3500]
PINK = [58275, 65535, 47142, 3500]
WHITE = [58275, 0, 65535, 5500]
COLD_WHTE = [58275, 0, 65535, 9000]
WARM_WHITE = [58275, 0, 65535, 3200]
GOLD = [58275, 0, 65535, 2500]

class Light(Device):
    def __init__(self, mac_addr, service, port, source_id, ip_addr, verbose=False):
        super(Light, self).__init__(mac_addr, service, port, source_id, ip_addr, verbose)
        self.color = None

    ############################################################################
    #                                                                          #
    #                            Light API Methods                             #
    #                                                                          #
    ############################################################################

    # GetPower - power level
    def get_power(self):
        try:
            response = self.req_with_resp(LightGetPower, LightStatePower)
            self.power_level = response.power_level
        except WorkflowException as e:
            print(e)
        return self.power_level

    def set_power(self, power, duration=0, rapid=False):
        on = [True, 1, 'on', 65535]
        off = [False, 0, 'off']
        try:
            if power in on and not rapid:
                self.req_with_ack(LightSetPower, {'power_level': 65535, 'duration': duration})
            elif power in on and rapid:
                self.fire_and_forget(LightSetPower, {'power_level': 65535, 'duration': duration}, num_repeats=5)
            elif power in off and not rapid:
                self.req_with_ack(LightSetPower, {'power_level': 0, 'duration': duration})
            elif power in off and rapid:
                self.fire_and_forget(LightSetPower, {'power_level': 0, 'duration': duration}, num_repeats=5)
            else:
                print('{} is not a valid power level.'.format(power))
        except WorkflowException as e:
            print(e)

    # color is [Hue, Saturation, Brightness, Kelvin], duration in ms
    def set_color(self, color, duration=0, rapid=False):
        if len(color) == 4:
            try:
                if rapid:
                    self.fire_and_forget(LightSetColor, {'color': color, 'duration': duration}, num_repeats=5)
                else:
                    self.req_with_ack(LightSetColor, {'color': color, 'duration': duration})
            except WorkflowException as e:
                print(e)

    # LightGet, color, power_level, label
    def get_color(self):
        try:
            response = self.req_with_resp(LightGet, LightState)
            self.color = response.color
            self.power_level = response.power_level
            self.label = response.label
        except WorkflowException as e:
            print(e)
        return self.color

    ############################################################################
    #                                                                          #
    #                            String Formatting                             #
    #                                                                          #
    ############################################################################

    def __str__(self):
        self.refresh()
        indent = '  '
        s = self.device_characteristics_str(indent)
        s += indent + 'Color (HSBK): {}\n'.format(self.get_color())
        s += indent + self.device_firmware_str(indent)
        s += indent + self.device_product_str(indent)
        s += indent + self.device_time_str(indent)
        s += indent + self.device_radio_str(indent)
        return s


text:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { CommonModule } from '@angular/common';
import { MatButtonModule } from '@angular/material/button';
import { MatToolbarModule } from '@angular/material/toolbar';
import { MatSidenavModule } from '@angular/material/sidenav';
import { MatExpansionModule } from '@angular/material/expansion';
import { MatListModule } from '@angular/material/list';
import { MatDividerModule } from '@angular/material/divider';
import { MatIconModule } from '@angular/material/icon';
import { NgxsModule } from '@ngxs/store';
import { NgxsRouterPluginModule } from '@ngxs/router-plugin';
import { NgxsLoggerPluginModule } from '@ngxs/logger-plugin';
import { NgxsReduxDevtoolsPluginModule } from '@ngxs/devtools-plugin';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

@NgModule({
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    CommonModule,
    MatButtonModule,
    MatToolbarModule,
    MatSidenavModule,
    MatExpansionModule,
    MatListModule,
    MatDividerModule,
    MatIconModule,
    NgxsModule.forRoot([]),
    NgxsRouterPluginModule.forRoot(),
    NgxsLoggerPluginModule.forRoot(),
    NgxsReduxDevtoolsPluginModule.forRoot(),

    AppRoutingModule,
  ],
  declarations: [AppComponent],
  providers: [],
  bootstrap: [AppComponent],
})
export class AppModule {}


text:
<mods xmlns="http://www.loc.gov/mods/v3" xmlns:exslt="http://exslt.org/common" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xlink="http://www.w3.org/1999/xlink" xsi:schemaLocation="http://www.loc.gov/mods/v3 http://www.loc.gov/standards/mods/v3/mods-3-3.xsd" version="3.3" ID="P0b002ee1815c862d">
<name type="corporate">
 <namePart>United States Government Printing Office</namePart>
 <role>
  <roleTerm type="text" authority="marcrelator">printer</roleTerm>
  <roleTerm type="code" authority="marcrelator">prt</roleTerm>
</role>
 <role>
  <roleTerm type="text" authority="marcrelator">distributor</roleTerm>
  <roleTerm type="code" authority="marcrelator">dst</roleTerm>
</role>
</name>
<name type="corporate">
 <namePart>United States</namePart>
 <namePart>United States District Court Northern District of Ohio</namePart>
 <role>
  <roleTerm type="text" authority="marcrelator">author</roleTerm>
  <roleTerm type="code" authority="marcrelator">aut</roleTerm>
</role>
 <description>Government Organization</description>
</name>
<typeOfResource>text</typeOfResource>
<genre authority="marcgt">government publication</genre>
<language>
 <languageTerm authority="iso639-2b" type="code">eng</languageTerm>
</language>
<extension>
 <collectionCode>USCOURTS</collectionCode>
 <category>Judicial Publications</category>
 <branch>judicial</branch>
 <dateIngested>2012-01-03</dateIngested>
</extension>
<originInfo>
 <publisher>Administrative Office of the United States Courts</publisher>
 <dateIssued encoding="w3cdtf">2010-01-26</dateIssued>
 <issuance>monographic</issuance>
</originInfo>
<physicalDescription>
 <note type="source content type">deposited</note>
 <digitalOrigin>born digital</digitalOrigin>
</physicalDescription>
<classification authority="sudocs">JU 4.15</classification>
<identifier type="uri">http://www.gpo.gov/fdsys/pkg/USCOURTS-ohnd-1_09-cr-00154</identifier>
<identifier type="local">P0b002ee1815c862d</identifier>
<recordInfo>
 <recordContentSource authority="marcorg">DGPO</recordContentSource>
 <recordCreationDate encoding="w3cdtf">2012-01-03</recordCreationDate>
 <recordChangeDate encoding="w3cdtf">2012-01-03</recordChangeDate>
 <recordIdentifier source="DGPO">USCOURTS-ohnd-1_09-cr-00154</recordIdentifier>
 <recordOrigin>machine generated</recordOrigin>
 <languageOfCataloging>
  <languageTerm authority="iso639-2b" type="code">eng</languageTerm>
</languageOfCataloging>
</recordInfo>
<accessCondition type="GPO scope determination">fdlp</accessCondition>
<extension>
 <docClass>USCOURTS</docClass>
 <accessId>USCOURTS-ohnd-1_09-cr-00154</accessId>
 <courtType>District</courtType>
 <courtCode>ohnd</courtCode>
 <courtCircuit>6th</courtCircuit>
 <courtState>Ohio</courtState>
 <courtSortOrder>2392</courtSortOrder>
 <caseNumber>1:09-cr-00154</caseNumber>
 <caseOffice>Cleveland</caseOffice>
 <caseType>criminal</caseType>
 <party firstName="Thomas" fullName="Thomas Cunningham" lastName="Cunningham" role="Defendant"></party>
 <party fullName="United States of America" lastName="United States of America" role="Plaintiff"></party>
</extension>
<titleInfo>
 <title>United States of America v. Cunningham</title>
 <partNumber>1:09-cr-00154</partNumber>
</titleInfo>
<location>
 <url access="object in context" displayLabel="Content Detail">http://www.gpo.gov/fdsys/pkg/USCOURTS-ohnd-1_09-cr-00154/content-detail.html</url>
</location>
<classification authority="sudocs">JU 4.15</classification>
<identifier type="preferred citation">1:09-cr-00154;09-154</identifier>
<name type="corporate">
 <namePart>United States District Court Northern District of Ohio</namePart>
 <namePart>6th Circuit</namePart>
 <namePart>Cleveland</namePart>
 <affiliation>U.S. Courts</affiliation>
 <role>
  <roleTerm authority="marcrelator" type="text">author</roleTerm>
  <roleTerm authority="marcrelator" type="code">aut</roleTerm>
</role>
</name>
<name type="personal">
 <displayForm>Thomas Cunningham</displayForm>
 <namePart type="family">Cunningham</namePart>
 <namePart type="given">Thomas</namePart>
 <namePart type="termsOfAddress"></namePart>
 <description>Defendant</description>
</name>
<name type="personal">
 <displayForm>United States of America</displayForm>
 <namePart type="family">United States of America</namePart>
 <namePart type="given"></namePart>
 <namePart type="termsOfAddress"></namePart>
 <description>Plaintiff</description>
</name>
<extension>
 <docClass>USCOURTS</docClass>
 <accessId>USCOURTS-ohnd-1_09-cr-00154</accessId>
 <courtType>District</courtType>
 <courtCode>ohnd</courtCode>
 <courtCircuit>6th</courtCircuit>
 <courtState>Ohio</courtState>
 <courtSortOrder>2392</courtSortOrder>
 <caseNumber>1:09-cr-00154</caseNumber>
 <caseOffice>Cleveland</caseOffice>
 <caseType>criminal</caseType>
 <party firstName="Thomas" fullName="Thomas Cunningham" lastName="Cunningham" role="Defendant"></party>
 <party fullName="United States of America" lastName="United States of America" role="Plaintiff"></party>
 <state>Ohio</state>
</extension>
<relatedItem type="constituent" ID="id-USCOURTS-ohnd-1_09-cr-00154-0" xlink:href="http://www.gpo.gov/fdsys/granule/USCOURTS-ohnd-1_09-cr-00154/USCOURTS-ohnd-1_09-cr-00154-0/mods.xml">
 <titleInfo>
  <title>United States of America v. Cunningham</title>
  <subTitle>Sentencing Memorandum as to Thomas Cunningham. Judge John R. Adams on 1/26/10. (K,C)</subTitle>
  <partNumber>0</partNumber>
</titleInfo>
 <originInfo>
  <dateIssued>2010-01-26</dateIssued>
</originInfo>
 <relatedItem xlink:href="http://www.gpo.gov/fdsys/pkg/pdf/USCOURTS-ohnd-1_09-cr-00154-0.pdf" type="otherFormat">
  <identifier type="FDsys Unique ID">D09002ee181691507</identifier>
</relatedItem>
 <identifier type="uri">http://www.gpo.gov/fdsys/granule/USCOURTS-ohnd-1_09-cr-00154/USCOURTS-ohnd-1_09-cr-00154-0</identifier>
 <identifier type="former granule identifier">ohnd-1_09-cr-00154_0.pdf</identifier>
 <location>
  <url access="object in context" displayLabel="Content Detail">http://www.gpo.gov/fdsys/granule/USCOURTS-ohnd-1_09-cr-00154/USCOURTS-ohnd-1_09-cr-00154-0/content-detail.html</url>
  <url access="raw object" displayLabel="PDF rendition">http://www.gpo.gov/fdsys/pkg/USCOURTS-ohnd-1_09-cr-00154/pdf/USCOURTS-ohnd-1_09-cr-00154-0.pdf</url>
</location>
 <extension>
  <searchTitle>USCOURTS 1:09-cr-00154; United States of America v. Cunningham; </searchTitle>
  <courtName>United States District Court Northern District of Ohio</courtName>
  <state>Ohio</state>
  <accessId>USCOURTS-ohnd-1_09-cr-00154-0</accessId>
  <sequenceNumber>0</sequenceNumber>
  <dateIssued>2010-01-26</dateIssued>
  <docketText>Sentencing Memorandum as to Thomas Cunningham. Judge John R. Adams on 1/26/10. (K,C)</docketText>
</extension>
</relatedItem>
</mods>


text:
import sys, random
from PyQt4 import QtGui, QtCore

class withSlot(QtGui.QWidget):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)

        self.setWindowTitle(self.trUtf8('Свой слот в PyQt'))
        self.resize(300, 50)
        self.button=QtGui.QPushButton('Get!', self)
        self.button.show()

        vbox = QtGui.QVBoxLayout()
        vbox.addWidget(self.button)
        self.setLayout(vbox)
        self.connect(self.button, QtCore.SIGNAL('clicked()'), self.getIt)

    def getIt(self):
        self.button.setText(str(random.randint(1, 10)))

app = QtGui.QApplication(sys.argv)
qb = withSlot()
qb.show()
sys.exit(app.exec_())


text:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var ScoreSchema = new Schema({
  user_id: { type: String, required: true },
  problem_id: { type: String, required: true },
  score: { type: Number }
});

module.exports.Score = mongoose.model('Score', ScoreSchema);


text:
const std::size_t maxlen = 1024;

class MASize {
	std::size_t _size;
public:
//	MASize(std::size_t);	// implicit constructor: size from int
//	MASize(const char *);	// implicit constructor: size from c-string
	explicit MASize(std::size_t);	// explicit constructor: size from int
	explicit MASize(const char *);	// explicit constructor: size from c-string
	std::size_t size() const;
};

MASize::MASize(const std::size_t n)
{
	std::cout << "Constructor: MASize from int" << std::endl;
	_size = (n <= maxlen) ? n : 0;
}

MASize::MASize(const char * s)
{
	std::cout << "Constructor: MASize from c-string" << std::endl;
	for(std::size_t i = 0;i < maxlen;i++){
		if(s[i] == '\0'){
			_size = i;
			return;
		}
	}
	_size = 0;
}

std::size_t MASize::size() const
{
	return _size;
}

using namespace std;

void func(const MASize & s)
{
	cout << "s.size() is " << s.size() << endl;

}

int main(int argc, char *argv[])
{
	//	implicit call
//	MASize s = 'x'; // assign with assignment instead of rantesis means thsis is implicit calling constructor
//	cout << "s.size() is " << s.size() << endl;
//	MASize s2('x');
//	cout << "s2.size() is " << s2.size() << endl;
//	func('x');

	//	explicit call
	MASize s2((size_t) 125); // explicit call
	cout << "s2.size() is " << s2.size() << endl;
	func(MASize("xxxxxx"));
	return 0;
}


text:
package org.hibernate.test.jpa.cascade;

/**
 * Parent, but with an assigned identifier.
 *
 * @author Steve Ebersole
 */
public class ParentAssigned {
	private Long id;
	private String name;
	private ParentInfoAssigned info;

	public ParentAssigned() {
	}

	public ParentAssigned(Long id, String name) {
		this.id = id;
		this.name = name;
	}

	public Long getId() {
		return id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public ParentInfoAssigned getInfo() {
		return info;
	}

	public void setInfo(ParentInfoAssigned info) {
		this.info = info;
	}
}


text:
from configobj import ConfigObj
from insalata.builder import *
import os
import importlib
import pkgutil
import sys
import types

BUILD_MODULE = "insalata.builder"

class Builder:
    def __init__(self, builderConfPath, logger):
        """
        Search for a function that solves the given action for an object that specifies
        a certain hypervisor, template or service.

        :param builderConfPath: Path to the builder config for this Environment.
        :type builderConfPath: str
        """
        self.logger = logger

        self.builderConf = None
        if not os.path.isfile(builderConfPath):
            self.logger.warning("No builder.conf found.")
        else:
            self.builderConf = ConfigObj(builderConfPath)
        self.functions = self.loadFunctions(BUILD_MODULE)

    def loadFunctions(self, packageName):
        """
        Import all functions of all functions of a module, recursively, including subpackages

        :param packageName: Name of the package to load functions of.
        :type packageName: str

        :returns: A dictionary with all functions under the given main module.
        :rtype: dict[str, types.Function]
        """
        package = importlib.import_module(packageName)

        results = {}
        for _, name, is_pkg in pkgutil.walk_packages(package.__path__):
            fullName = package.__name__ + '.' + name
            module = importlib.import_module(fullName)

            #get all functions of module
            functionNames = [f for f in dir(module) if not f.startswith('_')]
            for fn in functionNames:
                f = getattr(module, fn)
                if isinstance(f, types.FunctionType):
                    results[fullName + '.' + fn] = getattr(module, fn)

            #load submodules if any
            if is_pkg:
                results.update(self.loadFunctions(fullName))
        return results

    def findFunction(self, objId, forAction, forHypervisor=None, forTemplate=None, forService=None):
        """
        Search for a function that solves the given action for an object that specifies
        a certain hypervisor, template or service.

        :param objId: The global ID of the affected object.
        :type objId: str

        :param forAction: The name of the action to find a function for.
        :type forAction: str

        :param forHypervisor: The name of the action to find a function for.
        :type forHypervisor: str

        :param forTemplate: A list of template properties to find a function for.
        :type forTemplate: str

        :param forService: The name of the service to find a function for.
        :type forService: str

        :returns: A reference to a function that can be called based on the given parameters.
        :rtype: function
        """
        #look at the builder.conf in order to find a possible exception given for this object and action specifically
        if objId in self.builderConf:
            if forAction in self.builderConf[objId]:
                function = self.builderConf[objId][forAction]
                return self.functions[BUILD_MODULE + "." + function]

        #else
        #find a suitable method by looking at the forHypervisor/forTemplate/forServicesplitted

        #get all functions for the specified action (list comprehension for readability)
        functionForAction = [f for _, f in self.functions.items() if hasattr(f, 'action') and f.action == forAction]

        #the decorator adds all attributes, possibly with None
        suitableActions = [f for f in functionForAction
            if (not f.hypervisor or f.hypervisor == forHypervisor)
            and (not f.template or (forTemplate and len(set(forTemplate).intersection(set(f.template))) > 0))
            and (not f.service or f.service == forService)
        ]

        #order by not-None attributes in order to find the most suitable match
        suitableActions = sorted(suitableActions, reverse=True, key=lambda f:
            (1 if f.hypervisor else 0)
            + (len(set(forTemplate).intersection(set(f.template))) if f.template else 0)
            + (1 if f.service else 0)
        )

        if len(suitableActions) > 0:
            return suitableActions[0]
        else:
            self.logger.error("No builder found for object '{0}' and action '{1}'.".format(objId, forAction))

###################################################################################################
#  Functions for all steps defined in the planners domain which will then call the right builder  #
###################################################################################################

    def createNetwork(self, config, network):
        f = self.findFunction(network.getGlobalID(), "createNetwork", network.getLocation().getType())
        f(self.logger, network)

    def createHost(self, config, host):
        f = self.findFunction(host.getGlobalID(), "createHost", host.getLocation().getType(), host.getTemplate().getMetadata())
        f(self.logger, host)

    def createInterface(self, config, interface):
        f = self.findFunction(interface.getGlobalID(), "createInterface", interface.getHost().getLocation().getType(), interface.getHost().getTemplate().getMetadata())
        f(self.logger, interface)

    def boot(self, config, host):
        f = self.findFunction(host.getGlobalID(), "boot", host.getLocation().getType(), host.getTemplate().getMetadata())
        f(self.logger, host)

    def bootAndNamed(self, config, host):
        host.setNameApplied(True)
        self.boot(config, host)

    def reboot(self, config, host):
        f = self.findFunction(host.getGlobalID(), "reboot", host.getLocation().getType(), host.getTemplate().getMetadata())
        f(self.logger, host)

    def rebootAndNamed(self, config, host):
        host.setNameApplied(True)
        self.reboot(config, host)

    def bootUnnamed(self, config, host):
        host.setNameApplied(False)
        self.boot(config, host)

    def shutdown(self, config, host):
        f = self.findFunction(host.getGlobalID(), "shutdown", host.getLocation().getType(), host.getTemplate().getMetadata())
        f(self.logger, host)

    def name(self, config, host):
        f = self.findFunction(host.getGlobalID(), "name", host.getLocation().getType(), host.getTemplate().getMetadata())
        f(self.logger, host)

    def configureService(self, config, service):
        serviceTypeOrProduct = service.getProduct() if service.getProduct() else service.getType()
        f = self.findFunction(service.getGlobalID(), "configureService", forTemplate=service.getHost().getTemplate().getMetadata(), forService=serviceTypeOrProduct)
        f(self.logger, service, config)

    def configureDns(self, config, service):
        serviceTypeOrProduct = service.getProduct() if service.getProduct() else service.getType()
        f = self.findFunction(service.getGlobalID(), "configureDns", forTemplate=service.getHost().getTemplate().getMetadata(), forService=serviceTypeOrProduct)
        f(self.logger, service, config)

    def configureDhcp(self, config, service):
        serviceTypeOrProduct = service.getProduct() if service.getProduct() else service.getType()
        f = self.findFunction(service.getGlobalID(), "configureDhcp", forTemplate=service.getHost().getTemplate().getMetadata(), forService=serviceTypeOrProduct)
        f(self.logger, service, config)

    def configureRouting(self, config, host):
        f = self.findFunction(host.getGlobalID(), "configureRouting", forTemplate=host.getTemplate().getMetadata())
        f(self.logger, host)

    def configureFirewall(self, config, host):
        f = self.findFunction(host.getGlobalID(), "configureFirewall", forTemplate=host.getTemplate().getMetadata())
        f(self.logger, host)

    def configureCpus(self, config, host):
        f = self.findFunction(host.getGlobalID(), "configureCpus", host.getLocation().getType(), host.getTemplate().getMetadata())
        f(self.logger, host)

    def configureMemory(self, config, host):
        f = self.findFunction(host.getGlobalID(), "configureMemory", host.getLocation().getType(), host.getTemplate().getMetadata())
        f(self.logger, host)

    def configureInterface(self, config, interface):
        f = self.findFunction(interface.getGlobalID(), "configureInterface", interface.getHost().getLocation().getType(), interface.getHost().getTemplate().getMetadata())
        f(self.logger, interface)

    def unconfigureInterface(self, config, interface):
        f = self.findFunction(interface.getGlobalID(), "unconfigureInterface", interface.getHost().getLocation().getType(), interface.getHost().getTemplate().getMetadata())
        f(self.logger, interface)

    def configureNetwork(self, config, interface):
        f = self.findFunction(interface.getGlobalID(), "configureNetwork", interface.getHost().getLocation().getType(), interface.getHost().getTemplate().getMetadata())
        f(self.logger, interface)

    def configureMtu(self, config, interface):
        f = self.findFunction(interface.getGlobalID(), "configureMtu", interface.getHost().getLocation().getType(), interface.getHost().getTemplate().getMetadata())
        f(self.logger, interface)

    def configureRate(self, config, interface):
        f = self.findFunction(interface.getGlobalID(), "configureRate", interface.getHost().getLocation().getType(), interface.getHost().getTemplate().getMetadata())
        f(self.logger, interface)

    def addConfigNameNetwork(self, config, network):
        f = self.findFunction(network.getGlobalID(), "addConfigNameNetwork", network.getLocation().getType())
        f(self.logger, network, config.getID())

    def addConfigNameHost(self, config, host):
        f = self.findFunction(host.getGlobalID(), "addConfigNameHost", host.getLocation().getType())
        f(self.logger, host, config.getID())

    def addConfigNameDisk(self, config, disk):
        f = self.findFunction(disk.getGlobalID(), "addConfigNameDisk", disk.getHost().getLocation().getType())
        f(self.logger, disk, config.getID())

    def addDisk(self, config, disk, host):
        f = self.findFunction(disk.getGlobalID(), "addDisk", host.getLocation().getType())
        f(self.logger, disk, host)

    def removeDisk(self, config, disk):
        f1 = self.findFunction(disk.getGlobalID(), "removeConfigNameDisk", disk.getHost().getLocation().getType())
        remaining = f1(self.logger, disk, config.getID())
        #destroy if there are no remaining configs referencing this disk
        if remaining == []:
            f2 = self.findFunction(disk.getGlobalID(), "removeDisk", disk.getHost().getLocation().getType(), disk.getHost.getTemplate().getMetadata())
            f2(self.logger, disk)

    def removeNetwork(self, config, network):
        f1 = self.findFunction(network.getGlobalID(), "removeConfigNameNetwork", network.getLocation().getType())
        remaining = f1(self.logger, network, config.getID())
        #destroy if there are no remaining configs referencing this network
        if remaining == []:
            f2 = self.findFunction(disk.getGlobalID(), "removeNetwork", network.getLocation().getType())
            f2(self.logger, network)

    def removeHost(self, config, host):
        f1 = self.findFunction(host.getGlobalID(), "removeConfigNameHost", host.getLocation().getType())
        remaining = f1(self.logger, host, config.getID())
        #destroy if there are no remaining configs referencing this host
        if remaining == []:
            f2 = self.findFunction(host.getGlobalID(), "removeHost", host.getLocation().getType())
            f2(self.logger, host)

    def removeInterface(self, config, interface):
        f = self.findFunction(host.getGlobalID(), "removeInterface", interface.getHost().getLocation().getType())
        f(self.logger, interface)

    def deleteHost(self, config, host):
        pass


text:
package org.pac4j.play;

import org.pac4j.core.config.Config;
import org.pac4j.core.context.WebContext;
import org.pac4j.core.context.session.SessionStore;
import org.pac4j.core.engine.DefaultLogoutLogic;
import org.pac4j.core.engine.LogoutLogic;
import org.pac4j.core.http.adapter.HttpActionAdapter;
import org.pac4j.core.util.FindBest;
import org.pac4j.play.context.PlayContextFactory;
import org.pac4j.play.http.PlayHttpActionAdapter;
import play.mvc.Controller;
import play.mvc.Http;
import play.mvc.Result;
import play.libs.concurrent.HttpExecutionContext;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;

import javax.inject.Inject;

/**
 *
This filter handles the (application + identity provider) logout process.

 *
 * @author Jerome Leleu
 * @since 2.0.0
 */
public class LogoutController extends Controller {

    private LogoutLogic logoutLogic;

    private String defaultUrl;

    private String logoutUrlPattern;

    private Boolean localLogout;

    private Boolean destroySession;

    private Boolean centralLogout;

    @Inject
    protected Config config;
    @Inject
    protected SessionStore sessionStore;
    @Inject
    protected HttpExecutionContext ec;

    public CompletionStage<Result> logout(final Http.Request request) {

        final HttpActionAdapter bestAdapter = FindBest.httpActionAdapter(null, config, PlayHttpActionAdapter.INSTANCE);
        final LogoutLogic bestLogic = FindBest.logoutLogic(logoutLogic, config, DefaultLogoutLogic.INSTANCE);

        final WebContext context = FindBest.webContextFactory(null, config, PlayContextFactory.INSTANCE).newContext(request);

        return CompletableFuture.supplyAsync(() -> (Result) bestLogic.perform(context, sessionStore, config, bestAdapter, this.defaultUrl,
                this.logoutUrlPattern, this.localLogout, this.destroySession, this.centralLogout), ec.current());
    }

    public String getDefaultUrl() {
        return this.defaultUrl;
    }

    public void setDefaultUrl(final String defaultUrl) {
        this.defaultUrl = defaultUrl;
    }

    public String getLogoutUrlPattern() {
        return logoutUrlPattern;
    }

    public void setLogoutUrlPattern(final String logoutUrlPattern) {
        this.logoutUrlPattern = logoutUrlPattern;
    }

    public Config getConfig() {
        return config;
    }

    public void setConfig(final Config config) {
        this.config = config;
    }

    public Boolean getLocalLogout() {
        return localLogout;
    }

    public void setLocalLogout(final Boolean localLogout) {
        this.localLogout = localLogout;
    }

    public Boolean getDestroySession() {
        return destroySession;
    }

    public void setDestroySession(final Boolean destroySession) {
        this.destroySession = destroySession;
    }

    public Boolean getCentralLogout() {
        return centralLogout;
    }

    public void setCentralLogout(final Boolean centralLogout) {
        this.centralLogout = centralLogout;
    }

    public LogoutLogic getLogoutLogic() {
        return logoutLogic;
    }

    public SessionStore getSessionStore() {
        return sessionStore;
    }

    public void setLogoutLogic(final LogoutLogic logoutLogic) {
        this.logoutLogic = logoutLogic;
    }
}


text:
package org.camunda.bpm.engine.impl.calendar;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Map;

import org.camunda.bpm.engine.ProcessEngineException;
import org.camunda.bpm.engine.impl.util.ClockUtil;
import org.camunda.bpm.engine.task.Task;

/**
 * @author Tom Baeyens
 */
public class DefaultBusinessCalendar implements BusinessCalendar {

  private static Map<String, Integer> units = new HashMap<>();
  static {
    units.put("millis", Calendar.MILLISECOND);
    units.put("seconds", Calendar.SECOND);
    units.put("second", Calendar.SECOND);
    units.put("minute", Calendar.MINUTE);
    units.put("minutes", Calendar.MINUTE);
    units.put("hour", Calendar.HOUR);
    units.put("hours", Calendar.HOUR);
    units.put("day", Calendar.DAY_OF_YEAR);
    units.put("days", Calendar.DAY_OF_YEAR);
    units.put("week", Calendar.WEEK_OF_YEAR);
    units.put("weeks", Calendar.WEEK_OF_YEAR);
    units.put("month", Calendar.MONTH);
    units.put("months", Calendar.MONTH);
    units.put("year", Calendar.YEAR);
    units.put("years", Calendar.YEAR);
  }

  public Date resolveDuedate(String duedate, Task task) {
    return resolveDuedate(duedate);
  }

  public Date resolveDuedate(String duedate) {
    return resolveDuedate(duedate, (Date)null);
  }

  public Date resolveDuedate(String duedate, Date startDate) {
    Date resolvedDuedate = startDate == null ? ClockUtil.getCurrentTime() : startDate;

    String[] tokens = duedate.split(" and ");
    for (String token : tokens) {
      resolvedDuedate = addSingleUnitQuantity(resolvedDuedate, token);
    }

    return resolvedDuedate;
  }

  protected Date addSingleUnitQuantity(Date startDate, String singleUnitQuantity) {
    int spaceIndex = singleUnitQuantity.indexOf(" ");
    if (spaceIndex==-1 || singleUnitQuantity.length() < spaceIndex+1) {
      throw new ProcessEngineException("invalid duedate format: "+singleUnitQuantity);
    }

    String quantityText = singleUnitQuantity.substring(0, spaceIndex);
    Integer quantity = new Integer(quantityText);

    String unitText = singleUnitQuantity
      .substring(spaceIndex+1)
      .trim()
      .toLowerCase();

    int unit = units.get(unitText);

    GregorianCalendar calendar = new GregorianCalendar();
    calendar.setTime(startDate);
    calendar.add(unit, quantity);

    return calendar.getTime();
  }
}


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
The Penicillia 368 (1930)

#### Original name
Penicillium putterillii Thom

### Remarks
null


text:
// Code generated by go-swagger; DO NOT EDIT.

package security

// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command

import (
	"context"
	"net/http"
	"time"

	"github.com/go-openapi/errors"
	"github.com/go-openapi/runtime"
	cr "github.com/go-openapi/runtime/client"
	"github.com/go-openapi/strfmt"
	"github.com/go-openapi/swag"
)

// NewSecurityAuditLogCollectionGetParams creates a new SecurityAuditLogCollectionGetParams object,
// with the default timeout for this client.
//
// Default values are not hydrated, since defaults are normally applied by the API server side.
//
// To enforce default values in parameter, use SetDefaults or WithDefaults.
func NewSecurityAuditLogCollectionGetParams() *SecurityAuditLogCollectionGetParams {
	return &SecurityAuditLogCollectionGetParams{
		timeout: cr.DefaultTimeout,
	}
}

// NewSecurityAuditLogCollectionGetParamsWithTimeout creates a new SecurityAuditLogCollectionGetParams object
// with the ability to set a timeout on a request.
func NewSecurityAuditLogCollectionGetParamsWithTimeout(timeout time.Duration) *SecurityAuditLogCollectionGetParams {
	return &SecurityAuditLogCollectionGetParams{
		timeout: timeout,
	}
}

// NewSecurityAuditLogCollectionGetParamsWithContext creates a new SecurityAuditLogCollectionGetParams object
// with the ability to set a context for a request.
func NewSecurityAuditLogCollectionGetParamsWithContext(ctx context.Context) *SecurityAuditLogCollectionGetParams {
	return &SecurityAuditLogCollectionGetParams{
		Context: ctx,
	}
}

// NewSecurityAuditLogCollectionGetParamsWithHTTPClient creates a new SecurityAuditLogCollectionGetParams object
// with the ability to set a custom HTTPClient for a request.
func NewSecurityAuditLogCollectionGetParamsWithHTTPClient(client *http.Client) *SecurityAuditLogCollectionGetParams {
	return &SecurityAuditLogCollectionGetParams{
		HTTPClient: client,
	}
}

/*
SecurityAuditLogCollectionGetParams contains all the parameters to send to the API endpoint

	for the security audit log collection get operation.

	Typically these are written to a http.Request.
*/
type SecurityAuditLogCollectionGetParams struct {

	/* Application.

	   Filter by application
	*/
	ApplicationQueryParameter *string

	/* CommandID.

	   Filter by command_id
	*/
	CommandIDQueryParameter *string

	/* Fields.

	   Specify the fields to return.
	*/
	FieldsQueryParameter []string

	/* Index.

	   Filter by index
	*/
	IndexQueryParameter *int64

	/* Input.

	   Filter by input
	*/
	InputQueryParameter *string

	/* Location.

	   Filter by location
	*/
	LocationQueryParameter *string

	/* MaxRecords.

	   Limit the number of records returned.
	*/
	MaxRecordsQueryParameter *int64

	/* Message.

	   Filter by message
	*/
	MessageQueryParameter *string

	/* NodeName.

	   Filter by node.name
	*/
	NodeNameQueryParameter *string

	/* NodeUUID.

	   Filter by node.uuid
	*/
	NodeUUIDQueryParameter *string

	/* OrderBy.

	   Order results by specified fields and optional [asc|desc] direction. Default direction is 'asc' for ascending.
	*/
	OrderByQueryParameter []string

	/* ReturnRecords.

	   The default is true for GET calls.  When set to false, only the number of records is returned.

	   Default: true
	*/
	ReturnRecordsQueryParameter *bool

	/* ReturnTimeout.

	   The number of seconds to allow the call to execute before returning.  When iterating over a collection, the default is 15 seconds.  ONTAP returns earlier if either max records or the end of the collection is reached.

	   Default: 15
	*/
	ReturnTimeoutQueryParameter *int64

	/* Scope.

	   Filter by scope
	*/
	ScopeQueryParameter *string

	/* SessionID.

	   Filter by session_id
	*/
	SessionIDQueryParameter *string

	/* State.

	   Filter by state
	*/
	StateQueryParameter *string

	/* SvmName.

	   Filter by svm.name
	*/
	SVMNameQueryParameter *string

	/* Timestamp.

	   Filter by timestamp
	*/
	TimestampQueryParameter *string

	/* User.

	   Filter by user
	*/
	UserQueryParameter *string

	timeout    time.Duration
	Context    context.Context
	HTTPClient *http.Client
}

// WithDefaults hydrates default values in the security audit log collection get params (not the query body).
//
// All values with no default are reset to their zero value.
func (o *SecurityAuditLogCollectionGetParams) WithDefaults() *SecurityAuditLogCollectionGetParams {
	o.SetDefaults()
	return o
}

// SetDefaults hydrates default values in the security audit log collection get params (not the query body).
//
// All values with no default are reset to their zero value.
func (o *SecurityAuditLogCollectionGetParams) SetDefaults() {
	var (
		returnRecordsQueryParameterDefault = bool(true)

		returnTimeoutQueryParameterDefault = int64(15)
	)

	val := SecurityAuditLogCollectionGetParams{
		ReturnRecordsQueryParameter: &returnRecordsQueryParameterDefault,
		ReturnTimeoutQueryParameter: &returnTimeoutQueryParameterDefault,
	}

	val.timeout = o.timeout
	val.Context = o.Context
	val.HTTPClient = o.HTTPClient
	*o = val
}

// WithTimeout adds the timeout to the security audit log collection get params
func (o *SecurityAuditLogCollectionGetParams) WithTimeout(timeout time.Duration) *SecurityAuditLogCollectionGetParams {
	o.SetTimeout(timeout)
	return o
}

// SetTimeout adds the timeout to the security audit log collection get params
func (o *SecurityAuditLogCollectionGetParams) SetTimeout(timeout time.Duration) {
	o.timeout = timeout
}

// WithContext adds the context to the security audit log collection get params
func (o *SecurityAuditLogCollectionGetParams) WithContext(ctx context.Context) *SecurityAuditLogCollectionGetParams {
	o.SetContext(ctx)
	return o
}

// SetContext adds the context to the security audit log collection get params
func (o *SecurityAuditLogCollectionGetParams) SetContext(ctx context.Context) {
	o.Context = ctx
}

// WithHTTPClient adds the HTTPClient to the security audit log collection get params
func (o *SecurityAuditLogCollectionGetParams) WithHTTPClient(client *http.Client) *SecurityAuditLogCollectionGetParams {
	o.SetHTTPClient(client)
	return o
}

// SetHTTPClient adds the HTTPClient to the security audit log collection get params
func (o *SecurityAuditLogCollectionGetParams) SetHTTPClient(client *http.Client) {
	o.HTTPClient = client
}

// WithApplicationQueryParameter adds the application to the security audit log collection get params
func (o *SecurityAuditLogCollectionGetParams) WithApplicationQueryParameter(application *string) *SecurityAuditLogCollectionGetParams {
	o.SetApplicationQueryParameter(application)
	return o
}

// SetApplicationQueryParameter adds the application to the security audit log collection get params
func (o *SecurityAuditLogCollectionGetParams) SetApplicationQueryParameter(application *string) {
	o.ApplicationQueryParameter = application
}

// WithCommandIDQueryParameter adds the commandID to the security audit log collection get params
func (o *SecurityAuditLogCollectionGetParams) WithCommandIDQueryParameter(commandID *string) *SecurityAuditLogCollectionGetParams {
	o.SetCommandIDQueryParameter(commandID)
	return o
}

// SetCommandIDQueryParameter adds the commandId to the security audit log collection get params
func (o *SecurityAuditLogCollectionGetParams) SetCommandIDQueryParameter(commandID *string) {
	o.CommandIDQueryParameter = commandID
}

// WithFieldsQueryParameter adds the fields to the security audit log collection get params
func (o *SecurityAuditLogCollectionGetParams) WithFieldsQueryParameter(fields []string) *SecurityAuditLogCollectionGetParams {
	o.SetFieldsQueryParameter(fields)
	return o
}

// SetFieldsQueryParameter adds the fields to the security audit log collection get params
func (o *SecurityAuditLogCollectionGetParams) SetFieldsQueryParameter(fields []string) {
	o.FieldsQueryParameter = fields
}

// WithIndexQueryParameter adds the index to the security audit log collection get params
func (o *SecurityAuditLogCollectionGetParams) WithIndexQueryParameter(index *int64) *SecurityAuditLogCollectionGetParams {
	o.SetIndexQueryParameter(index)
	return o
}

// SetIndexQueryParameter adds the index to the security audit log collection get params
func (o *SecurityAuditLogCollectionGetParams) SetIndexQueryParameter(index *int64) {
	o.IndexQueryParameter = index
}

// WithInputQueryParameter adds the input to the security audit log collection get params
func (o *SecurityAuditLogCollectionGetParams) WithInputQueryParameter(input *string) *SecurityAuditLogCollectionGetParams {
	o.SetInputQueryParameter(input)
	return o
}

// SetInputQueryParameter adds the input to the security audit log collection get params
func (o *SecurityAuditLogCollectionGetParams) SetInputQueryParameter(input *string) {
	o.InputQueryParameter = input
}

// WithLocationQueryParameter adds the location to the security audit log collection get params
func (o *SecurityAuditLogCollectionGetParams) WithLocationQueryParameter(location *string) *SecurityAuditLogCollectionGetParams {
	o.SetLocationQueryParameter(location)
	return o
}

// SetLocationQueryParameter adds the location to the security audit log collection get params
func (o *SecurityAuditLogCollectionGetParams) SetLocationQueryParameter(location *string) {
	o.LocationQueryParameter = location
}

// WithMaxRecordsQueryParameter adds the maxRecords to the security audit log collection get params
func (o *SecurityAuditLogCollectionGetParams) WithMaxRecordsQueryParameter(maxRecords *int64) *SecurityAuditLogCollectionGetParams {
	o.SetMaxRecordsQueryParameter(maxRecords)
	return o
}

// SetMaxRecordsQueryParameter adds the maxRecords to the security audit log collection get params
func (o *SecurityAuditLogCollectionGetParams) SetMaxRecordsQueryParameter(maxRecords *int64) {
	o.MaxRecordsQueryParameter = maxRecords
}

// WithMessageQueryParameter adds the message to the security audit log collection get params
func (o *SecurityAuditLogCollectionGetParams) WithMessageQueryParameter(message *string) *SecurityAuditLogCollectionGetParams {
	o.SetMessageQueryParameter(message)
	return o
}

// SetMessageQueryParameter adds the message to the security audit log collection get params
func (o *SecurityAuditLogCollectionGetParams) SetMessageQueryParameter(message *string) {
	o.MessageQueryParameter = message
}

// WithNodeNameQueryParameter adds the nodeName to the security audit log collection get params
func (o *SecurityAuditLogCollectionGetParams) WithNodeNameQueryParameter(nodeName *string) *SecurityAuditLogCollectionGetParams {
	o.SetNodeNameQueryParameter(nodeName)
	return o
}

// SetNodeNameQueryParameter adds the nodeName to the security audit log collection get params
func (o *SecurityAuditLogCollectionGetParams) SetNodeNameQueryParameter(nodeName *string) {
	o.NodeNameQueryParameter = nodeName
}

// WithNodeUUIDQueryParameter adds the nodeUUID to the security audit log collection get params
func (o *SecurityAuditLogCollectionGetParams) WithNodeUUIDQueryParameter(nodeUUID *string) *SecurityAuditLogCollectionGetParams {
	o.SetNodeUUIDQueryParameter(nodeUUID)
	return o
}

// SetNodeUUIDQueryParameter adds the nodeUuid to the security audit log collection get params
func (o *SecurityAuditLogCollectionGetParams) SetNodeUUIDQueryParameter(nodeUUID *string) {
	o.NodeUUIDQueryParameter = nodeUUID
}

// WithOrderByQueryParameter adds the orderBy to the security audit log collection get params
func (o *SecurityAuditLogCollectionGetParams) WithOrderByQueryParameter(orderBy []string) *SecurityAuditLogCollectionGetParams {
	o.SetOrderByQueryParameter(orderBy)
	return o
}

// SetOrderByQueryParameter adds the orderBy to the security audit log collection get params
func (o *SecurityAuditLogCollectionGetParams) SetOrderByQueryParameter(orderBy []string) {
	o.OrderByQueryParameter = orderBy
}

// WithReturnRecordsQueryParameter adds the returnRecords to the security audit log collection get params
func (o *SecurityAuditLogCollectionGetParams) WithReturnRecordsQueryParameter(returnRecords *bool) *SecurityAuditLogCollectionGetParams {
	o.SetReturnRecordsQueryParameter(returnRecords)
	return o
}

// SetReturnRecordsQueryParameter adds the returnRecords to the security audit log collection get params
func (o *SecurityAuditLogCollectionGetParams) SetReturnRecordsQueryParameter(returnRecords *bool) {
	o.ReturnRecordsQueryParameter = returnRecords
}

// WithReturnTimeoutQueryParameter adds the returnTimeout to the security audit log collection get params
func (o *SecurityAuditLogCollectionGetParams) WithReturnTimeoutQueryParameter(returnTimeout *int64) *SecurityAuditLogCollectionGetParams {
	o.SetReturnTimeoutQueryParameter(returnTimeout)
	return o
}

// SetReturnTimeoutQueryParameter adds the returnTimeout to the security audit log collection get params
func (o *SecurityAuditLogCollectionGetParams) SetReturnTimeoutQueryParameter(returnTimeout *int64) {
	o.ReturnTimeoutQueryParameter = returnTimeout
}

// WithScopeQueryParameter adds the scope to the security audit log collection get params
func (o *SecurityAuditLogCollectionGetParams) WithScopeQueryParameter(scope *string) *SecurityAuditLogCollectionGetParams {
	o.SetScopeQueryParameter(scope)
	return o
}

// SetScopeQueryParameter adds the scope to the security audit log collection get params
func (o *SecurityAuditLogCollectionGetParams) SetScopeQueryParameter(scope *string) {
	o.ScopeQueryParameter = scope
}

// WithSessionIDQueryParameter adds the sessionID to the security audit log collection get params
func (o *SecurityAuditLogCollectionGetParams) WithSessionIDQueryParameter(sessionID *string) *SecurityAuditLogCollectionGetParams {
	o.SetSessionIDQueryParameter(sessionID)
	return o
}

// SetSessionIDQueryParameter adds the sessionId to the security audit log collection get params
func (o *SecurityAuditLogCollectionGetParams) SetSessionIDQueryParameter(sessionID *string) {
	o.SessionIDQueryParameter = sessionID
}

// WithStateQueryParameter adds the state to the security audit log collection get params
func (o *SecurityAuditLogCollectionGetParams) WithStateQueryParameter(state *string) *SecurityAuditLogCollectionGetParams {
	o.SetStateQueryParameter(state)
	return o
}

// SetStateQueryParameter adds the state to the security audit log collection get params
func (o *SecurityAuditLogCollectionGetParams) SetStateQueryParameter(state *string) {
	o.StateQueryParameter = state
}

// WithSVMNameQueryParameter adds the svmName to the security audit log collection get params
func (o *SecurityAuditLogCollectionGetParams) WithSVMNameQueryParameter(svmName *string) *SecurityAuditLogCollectionGetParams {
	o.SetSVMNameQueryParameter(svmName)
	return o
}

// SetSVMNameQueryParameter adds the svmName to the security audit log collection get params
func (o *SecurityAuditLogCollectionGetParams) SetSVMNameQueryParameter(svmName *string) {
	o.SVMNameQueryParameter = svmName
}

// WithTimestampQueryParameter adds the timestamp to the security audit log collection get params
func (o *SecurityAuditLogCollectionGetParams) WithTimestampQueryParameter(timestamp *string) *SecurityAuditLogCollectionGetParams {
	o.SetTimestampQueryParameter(timestamp)
	return o
}

// SetTimestampQueryParameter adds the timestamp to the security audit log collection get params
func (o *SecurityAuditLogCollectionGetParams) SetTimestampQueryParameter(timestamp *string) {
	o.TimestampQueryParameter = timestamp
}

// WithUserQueryParameter adds the user to the security audit log collection get params
func (o *SecurityAuditLogCollectionGetParams) WithUserQueryParameter(user *string) *SecurityAuditLogCollectionGetParams {
	o.SetUserQueryParameter(user)
	return o
}

// SetUserQueryParameter adds the user to the security audit log collection get params
func (o *SecurityAuditLogCollectionGetParams) SetUserQueryParameter(user *string) {
	o.UserQueryParameter = user
}

// WriteToRequest writes these params to a swagger request
func (o *SecurityAuditLogCollectionGetParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error {

	if err := r.SetTimeout(o.timeout); err != nil {
		return err
	}
	var res []error

	if o.ApplicationQueryParameter != nil {

		// query param application
		var qrApplication string

		if o.ApplicationQueryParameter != nil {
			qrApplication = *o.ApplicationQueryParameter
		}
		qApplication := qrApplication
		if qApplication != "" {

			if err := r.SetQueryParam("application", qApplication); err != nil {
				return err
			}
		}
	}

	if o.CommandIDQueryParameter != nil {

		// query param command_id
		var qrCommandID string

		if o.CommandIDQueryParameter != nil {
			qrCommandID = *o.CommandIDQueryParameter
		}
		qCommandID := qrCommandID
		if qCommandID != "" {

			if err := r.SetQueryParam("command_id", qCommandID); err != nil {
				return err
			}
		}
	}

	if o.FieldsQueryParameter != nil {

		// binding items for fields
		joinedFields := o.bindParamFields(reg)

		// query array param fields
		if err := r.SetQueryParam("fields", joinedFields...); err != nil {
			return err
		}
	}

	if o.IndexQueryParameter != nil {

		// query param index
		var qrIndex int64

		if o.IndexQueryParameter != nil {
			qrIndex = *o.IndexQueryParameter
		}
		qIndex := swag.FormatInt64(qrIndex)
		if qIndex != "" {

			if err := r.SetQueryParam("index", qIndex); err != nil {
				return err
			}
		}
	}

	if o.InputQueryParameter != nil {

		// query param input
		var qrInput string

		if o.InputQueryParameter != nil {
			qrInput = *o.InputQueryParameter
		}
		qInput := qrInput
		if qInput != "" {

			if err := r.SetQueryParam("input", qInput); err != nil {
				return err
			}
		}
	}

	if o.LocationQueryParameter != nil {

		// query param location
		var qrLocation string

		if o.LocationQueryParameter != nil {
			qrLocation = *o.LocationQueryParameter
		}
		qLocation := qrLocation
		if qLocation != "" {

			if err := r.SetQueryParam("location", qLocation); err != nil {
				return err
			}
		}
	}

	if o.MaxRecordsQueryParameter != nil {

		// query param max_records
		var qrMaxRecords int64

		if o.MaxRecordsQueryParameter != nil {
			qrMaxRecords = *o.MaxRecordsQueryParameter
		}
		qMaxRecords := swag.FormatInt64(qrMaxRecords)
		if qMaxRecords != "" {

			if err := r.SetQueryParam("max_records", qMaxRecords); err != nil {
				return err
			}
		}
	}

	if o.MessageQueryParameter != nil {

		// query param message
		var qrMessage string

		if o.MessageQueryParameter != nil {
			qrMessage = *o.MessageQueryParameter
		}
		qMessage := qrMessage
		if qMessage != "" {

			if err := r.SetQueryParam("message", qMessage); err != nil {
				return err
			}
		}
	}

	if o.NodeNameQueryParameter != nil {

		// query param node.name
		var qrNodeName string

		if o.NodeNameQueryParameter != nil {
			qrNodeName = *o.NodeNameQueryParameter
		}
		qNodeName := qrNodeName
		if qNodeName != "" {

			if err := r.SetQueryParam("node.name", qNodeName); err != nil {
				return err
			}
		}
	}

	if o.NodeUUIDQueryParameter != nil {

		// query param node.uuid
		var qrNodeUUID string

		if o.NodeUUIDQueryParameter != nil {
			qrNodeUUID = *o.NodeUUIDQueryParameter
		}
		qNodeUUID := qrNodeUUID
		if qNodeUUID != "" {

			if err := r.SetQueryParam("node.uuid", qNodeUUID); err != nil {
				return err
			}
		}
	}

	if o.OrderByQueryParameter != nil {

		// binding items for order_by
		joinedOrderBy := o.bindParamOrderBy(reg)

		// query array param order_by
		if err := r.SetQueryParam("order_by", joinedOrderBy...); err != nil {
			return err
		}
	}

	if o.ReturnRecordsQueryParameter != nil {

		// query param return_records
		var qrReturnRecords bool

		if o.ReturnRecordsQueryParameter != nil {
			qrReturnRecords = *o.ReturnRecordsQueryParameter
		}
		qReturnRecords := swag.FormatBool(qrReturnRecords)
		if qReturnRecords != "" {

			if err := r.SetQueryParam("return_records", qReturnRecords); err != nil {
				return err
			}
		}
	}

	if o.ReturnTimeoutQueryParameter != nil {

		// query param return_timeout
		var qrReturnTimeout int64

		if o.ReturnTimeoutQueryParameter != nil {
			qrReturnTimeout = *o.ReturnTimeoutQueryParameter
		}
		qReturnTimeout := swag.FormatInt64(qrReturnTimeout)
		if qReturnTimeout != "" {

			if err := r.SetQueryParam("return_timeout", qReturnTimeout); err != nil {
				return err
			}
		}
	}

	if o.ScopeQueryParameter != nil {

		// query param scope
		var qrScope string

		if o.ScopeQueryParameter != nil {
			qrScope = *o.ScopeQueryParameter
		}
		qScope := qrScope
		if qScope != "" {

			if err := r.SetQueryParam("scope", qScope); err != nil {
				return err
			}
		}
	}

	if o.SessionIDQueryParameter != nil {

		// query param session_id
		var qrSessionID string

		if o.SessionIDQueryParameter != nil {
			qrSessionID = *o.SessionIDQueryParameter
		}
		qSessionID := qrSessionID
		if qSessionID != "" {

			if err := r.SetQueryParam("session_id", qSessionID); err != nil {
				return err
			}
		}
	}

	if o.StateQueryParameter != nil {

		// query param state
		var qrState string

		if o.StateQueryParameter != nil {
			qrState = *o.StateQueryParameter
		}
		qState := qrState
		if qState != "" {

			if err := r.SetQueryParam("state", qState); err != nil {
				return err
			}
		}
	}

	if o.SVMNameQueryParameter != nil {

		// query param svm.name
		var qrSvmName string

		if o.SVMNameQueryParameter != nil {
			qrSvmName = *o.SVMNameQueryParameter
		}
		qSvmName := qrSvmName
		if qSvmName != "" {

			if err := r.SetQueryParam("svm.name", qSvmName); err != nil {
				return err
			}
		}
	}

	if o.TimestampQueryParameter != nil {

		// query param timestamp
		var qrTimestamp string

		if o.TimestampQueryParameter != nil {
			qrTimestamp = *o.TimestampQueryParameter
		}
		qTimestamp := qrTimestamp
		if qTimestamp != "" {

			if err := r.SetQueryParam("timestamp", qTimestamp); err != nil {
				return err
			}
		}
	}

	if o.UserQueryParameter != nil {

		// query param user
		var qrUser string

		if o.UserQueryParameter != nil {
			qrUser = *o.UserQueryParameter
		}
		qUser := qrUser
		if qUser != "" {

			if err := r.SetQueryParam("user", qUser); err != nil {
				return err
			}
		}
	}

	if len(res) > 0 {
		return errors.CompositeValidationError(res...)
	}
	return nil
}

// bindParamSecurityAuditLogCollectionGet binds the parameter fields
func (o *SecurityAuditLogCollectionGetParams) bindParamFields(formats strfmt.Registry) []string {
	fieldsIR := o.FieldsQueryParameter

	var fieldsIC []string
	for _, fieldsIIR := range fieldsIR { // explode []string

		fieldsIIV := fieldsIIR // string as string
		fieldsIC = append(fieldsIC, fieldsIIV)
	}

	// items.CollectionFormat: "csv"
	fieldsIS := swag.JoinByFormat(fieldsIC, "csv")

	return fieldsIS
}

// bindParamSecurityAuditLogCollectionGet binds the parameter order_by
func (o *SecurityAuditLogCollectionGetParams) bindParamOrderBy(formats strfmt.Registry) []string {
	orderByIR := o.OrderByQueryParameter

	var orderByIC []string
	for _, orderByIIR := range orderByIR { // explode []string

		orderByIIV := orderByIIR // string as string
		orderByIC = append(orderByIC, orderByIIV)
	}

	// items.CollectionFormat: "csv"
	orderByIS := swag.JoinByFormat(orderByIC, "csv")

	return orderByIS
}


text:
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
#if (UseSerilog)
using OrchardCore.Logging;
#endif

namespace OrchardCore.Templates.Cms.Web
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddOrchardCms();
        }

        public void Configure(IApplicationBuilder app, IHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseStaticFiles();
#if (UseSerilog)
            app.UseOrchardCore(c => c.UseSerilogTenantNameLogging());
#else
            app.UseOrchardCore();
#endif
        }
    }
}


text:
from django.conf.urls import url, include

from core.views import views

from core.views import experiment

urlpatterns = [

    url(
        r'^$',
        experiment.experiments,
        name='experiments-list'
    ),
    url(
        r'^json$',
        experiment.list_experiments_as_json,
        name='experiments-json'
    ),

    url(
        r'^create',
        experiment.ExperimentCreateView.as_view(template_name="core/experiments/create.html"),
        name='experiments-create'
    ),

    url(
        r'^(?P<id>[-_\w]+)/delete$',
        experiment.experiment_delete,
        name='experiments-delete'
    ),
    url(
        r'^(?P<pk>[-_\w]+)/edit$',
        experiment.ExperimentUpdateView.as_view(template_name="core/experiments/edit.html"),
        name='experiments-edit'
    ),
    url(
        r'^(?P<id>[-_\w]+)/lock$',
        experiment.lock_experiment,
        name='experiments-lock'
    ),
    url(
        r'^(?P<id>[-_\w]+)/unlock$',
        experiment.unlock_experiment,
        name='experiment-unlock'
    ),
    url(
        r'^(?P<pk>[-_\w]+)/json$',
        experiment.experiment_detail_as_json,
        name='experiments-detail-json'
    ),

    url(
        r'^(?P<pk>[-_\w]+)$',
        experiment.ExperimentDetailView.as_view(template_name="core/experiments/detail.html"),
        name='experiments-detail'
    ),

]


text:
try:
    from django.conf.urls.defaults import include, patterns
except ImportError:
    from django.conf.urls import include, patterns

from django.contrib import admin
admin.autodiscover()

import object_tools
object_tools.autodiscover()

urlpatterns = patterns('',
    (r'^admin/', include(admin.site.urls)),
    (r'^object-tools/', include(object_tools.tools.urls)),
)