text:
<?php

require_once realpath ( dirname ( __FILE__ ) ) . '/.config.inc.php';
require_once realpath ( dirname ( __FILE__ ) ) . '/ReverseProviderCreditSample.php';
require_once realpath ( dirname ( __FILE__ ) ) . '/ReverseProviderCreditExample.php';
require_once realpath ( dirname ( __FILE__ ) ) . '/CLIExample.php';

/**
 * ReverseProviderCreditExampleCLI class captures input from stdin and prints to stdout,
 * and drives the reverse example
 */
class ReverseProviderCreditExampleCLI extends CLIExample {
	/**
	 * Create a new instance of the cli example and validate command line arguments
	 *
	 * @param array $argv
	 *        	arguments to the application passed from the command line
	 */
	public function __construct($argv) {

		/*
		 * Instantiate Implementation of OffAmazonPaymentsService client Merchant ids and access keys are defined in the constants are defined in the OffAmazonPaymentsService.config.inc.php file in the parent directory of this server
		 */
		$this->exampleClass = new ReverseProviderCreditExample ( new OffAmazonPaymentsService_Client () );
	}

	/**
	 * Run all the steps for the sample in sequence
	 */
	public function runSample() {
		$amazonProviderCreditId = $this->getProviderCreditId ();
		$reverseAmount = $this->_getCreditReversalAmount ();
		$creditReversalReferenceId = str_replace("-", "", $amazonProviderCreditId) . "q" . rand(1, 1000);
		$this->_reverseToMerchant ( $amazonProviderCreditId, $reverseAmount, $creditReversalReferenceId );

		print "Reverse provider credit completed" . PHP_EOL;
	}

	/**
	 * Perform the reverse to transfer the amount from seller
	 * to merchant
	 *
	 * @param string $reverseAmount
	 *        	amount to reverse to the buyer
	 * @param string $reverseCurrency
	 *        	currency of the reverse
	 */
	private function _reverseToMerchant($amazonProviderCreditId, $reverseAmount, $creditReversalReferenceId) {
		$response = $this->callStepAndCheckForException ( 'reverseToMerchant', array (
				$amazonProviderCreditId,
				$reverseAmount,
				$creditReversalReferenceId
		) );

		printProviderCreditReversalDetailsResponse ( $response );
	}

	/**
	 *
	 * @return AmazonProviderCreditId
	 */
	private function getProviderCreditId() {

		print PHP_EOL."Enter the AmazonProviderCreditId >> ";
		do {
			$amazonProviderCreditId = trim ( fgets ( STDIN ) );
		} while ( ! is_string ( $amazonProviderCreditId ) );

		return $amazonProviderCreditId;
	}

	/**
	 * Get the amount to reverse
	 *
	 * @return string reverse amount, as a numeric string`
	 */
	private function _getCreditReversalAmount() {
		print PHP_EOL."Enter the amount to reverse from the provider (to 2 decimal places):";
		do {
			$reverseAmount = trim ( fgets ( STDIN ) );
		} while ( ! is_numeric ( $reverseAmount ) );

		return $reverseAmount;
	}
}

$reverseProviderCreditExample = new ReverseProviderCreditExampleCLI ( $argv );
$reverseProviderCreditExample->runSample ();

?>


text:
package org.cloudfoundry.client.v2.serviceinstances;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.databind.DatabindContext;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonTypeIdResolver;
import com.fasterxml.jackson.databind.jsontype.impl.TypeIdResolverBase;
import org.cloudfoundry.Nullable;
import org.cloudfoundry.client.v2.Resource;
import org.cloudfoundry.client.v2.jobs.JobEntity;
import org.immutables.value.Value;

/**
 * The response for the Delete Service Instance operation
 */
@JsonDeserialize
@Value.Immutable
abstract class _DeleteServiceInstanceResponse extends Resource<Object> {

    /**
     * The resource's entity
     */
    @JsonProperty("entity")
    @JsonTypeIdResolver(_DeleteServiceInstanceResponse.DeleteServiceInstanceResponseTypeIdResolver.class)
    @JsonTypeInfo(use = JsonTypeInfo.Id.CUSTOM, include = JsonTypeInfo.As.EXISTING_PROPERTY, property = "type", defaultImpl = JobEntity.class, visible = true)
    @Nullable
    public abstract Object getEntity();

    static final class DeleteServiceInstanceResponseTypeIdResolver extends TypeIdResolverBase {

        @Override
        public JsonTypeInfo.Id getMechanism() {
            return null;
        }

        @Override
        public String idFromValue(Object value) {
            return null;
        }

        @Override
        public String idFromValueAndType(Object value, Class<?> suggestedType) {
            return null;
        }

        @Override
        public JavaType typeFromId(DatabindContext context, String id) {
            return context.constructType(ServiceInstanceEntity.class);
        }

    }

}

redpajama_set_name: RedPajamaGithub


text:
[![Build Status](https://travis-ci.org/mixpanel/mixpanel-iphone.svg?branch=yolo-travis-ci)](https://travis-ci.org/mixpanel/mixpanel-iphone)

Mixpanel supports `Cocoapods` for easy installation.
To Install, see our **[full documentation »](https://mixpanel.com/help/reference/ios)**

**Want to Contribute?**

The Mixpanel library for iOS is an open source project, and we'd love to see your contributions! We'd also love for you to come and work with us! Check out http://boards.greenhouse.io/mixpanel/jobs/25226#.U_4JXEhORKU for details.


text:
namespace MyApp.Directives {
    export function repeaterDir(): angular.IDirective {
        return { //DDO
            restrict: "AE", //<red-dir>...</red-dir>
            scope: {
                color: "@", //string literal
                what: "=", //two-way
                num: "<", //one-way solo NG 1.4+
                onRepeat: "&" //callback handler
            },
            templateUrl: "tpl/RepeaterDir.html", //LOAD TEMPLATE VIA DYNAMIC PARTIAL tplRepeaterDir.cshtml
            controller: RepeaterDir,
            controllerAs: "$ctrl",
            bindToController: true
        }
    }
    export interface IEventArg {
        str: string;
        n: number;
    }
    export type EventHandler<T> = (payload: {$event: T}) => void;

    class RepeaterDir {
        constructor() {
            this.num = this.num || 2;
            this.color = this.color || 'red';
        }

        public color: string;
        public num: number;
        public what: string;
        public onRepeat: EventHandler<IEventArg>;

        public doRepeat(n:number) {
            let str = "";
            for(let i=0; i<n; i++) {
                str += `${i}. ${this.what} \n`; //tempalte-string with params
            }
            this.onRepeat({$event: {str, n} });
        }
    }
}


text:
\hypertarget{struct_position}{\section{Dokumentacja struktury Position}
\label{struct_position}\index{Position@{Position}}
}

Klasa reprezentuje punkt w trójwymiarowej przestrzeni.

{\ttfamily \#include $<$Position.\-h$>$}

\subsection*{Metody publiczne}
\begin{DoxyCompactItemize}
\item
\hyperlink{struct_position_ae4b5a0536e6c0dab44457ff34b21ac50}{Position} (double x\-\_\-, double y\-\_\-, double z\-\_\-=0)
\item
\hyperlink{struct_position_a46126c3ef1893b4581e4726ac33b557b}{Position} (const \hyperlink{struct_position}{Position} \&position\-\_\-)
\item
double \hyperlink{struct_position_a29f0bd21850b275c2c107e8a238979db}{abs\-X} () const
\item
double \hyperlink{struct_position_a7c8267cc217b805e86691556f2232619}{abs\-Y} () const
\item
double \hyperlink{struct_position_a0176fb7d30f2fbb8cf8d4ba1242a4610}{abs\-Z} () const
\end{DoxyCompactItemize}
\subsection*{Atrybuty publiczne}
\begin{DoxyCompactItemize}
\item
double \hyperlink{struct_position_a9abbe738bad177de91fe4774099c1260}{x}
\item
double \hyperlink{struct_position_a75f48c2a1d2c7131b8be1a0687ae72c8}{y}
\item
double \hyperlink{struct_position_ab26043bc2f8f6094818c17dd44e43228}{z}
\end{DoxyCompactItemize}

\subsection{Opis szczegółowy}
Klasa reprezentuje punkt w trójwymiarowej przestrzeni.

\subsection{Dokumentacja konstruktora i destruktora}
\hypertarget{struct_position_ae4b5a0536e6c0dab44457ff34b21ac50}{\index{Position@{Position}!Position@{Position}}
\index{Position@{Position}!Position@{Position}}
\subsubsection[{Position}]{\setlength{\rightskip}{0pt plus 5cm}Position\-::\-Position (
\begin{DoxyParamCaption}
\item[{double}]{x\-\_\-, }
\item[{double}]{y\-\_\-, }
\item[{double}]{z\-\_\- = {\ttfamily 0}}
\end{DoxyParamCaption}
)\hspace{0.3cm}{\ttfamily [inline]}}}\label{struct_position_ae4b5a0536e6c0dab44457ff34b21ac50}
\hypertarget{struct_position_a46126c3ef1893b4581e4726ac33b557b}{\index{Position@{Position}!Position@{Position}}
\index{Position@{Position}!Position@{Position}}
\subsubsection[{Position}]{\setlength{\rightskip}{0pt plus 5cm}Position\-::\-Position (
\begin{DoxyParamCaption}
\item[{const {\bf Position} \&}]{position\-\_\-}
\end{DoxyParamCaption}
)\hspace{0.3cm}{\ttfamily [inline]}}}\label{struct_position_a46126c3ef1893b4581e4726ac33b557b}

\subsection{Dokumentacja funkcji składowych}
\hypertarget{struct_position_a29f0bd21850b275c2c107e8a238979db}{\index{Position@{Position}!abs\-X@{abs\-X}}
\index{abs\-X@{abs\-X}!Position@{Position}}
\subsubsection[{abs\-X}]{\setlength{\rightskip}{0pt plus 5cm}double Position\-::abs\-X (
\begin{DoxyParamCaption}
{}
\end{DoxyParamCaption}
) const\hspace{0.3cm}{\ttfamily [inline]}}}\label{struct_position_a29f0bd21850b275c2c107e8a238979db}
\hypertarget{struct_position_a7c8267cc217b805e86691556f2232619}{\index{Position@{Position}!abs\-Y@{abs\-Y}}
\index{abs\-Y@{abs\-Y}!Position@{Position}}
\subsubsection[{abs\-Y}]{\setlength{\rightskip}{0pt plus 5cm}double Position\-::abs\-Y (
\begin{DoxyParamCaption}
{}
\end{DoxyParamCaption}
) const\hspace{0.3cm}{\ttfamily [inline]}}}\label{struct_position_a7c8267cc217b805e86691556f2232619}
\hypertarget{struct_position_a0176fb7d30f2fbb8cf8d4ba1242a4610}{\index{Position@{Position}!abs\-Z@{abs\-Z}}
\index{abs\-Z@{abs\-Z}!Position@{Position}}
\subsubsection[{abs\-Z}]{\setlength{\rightskip}{0pt plus 5cm}double Position\-::abs\-Z (
\begin{DoxyParamCaption}
{}
\end{DoxyParamCaption}
) const\hspace{0.3cm}{\ttfamily [inline]}}}\label{struct_position_a0176fb7d30f2fbb8cf8d4ba1242a4610}

\subsection{Dokumentacja atrybutów składowych}
\hypertarget{struct_position_a9abbe738bad177de91fe4774099c1260}{\index{Position@{Position}!x@{x}}
\index{x@{x}!Position@{Position}}
\subsubsection[{x}]{\setlength{\rightskip}{0pt plus 5cm}double Position\-::x}}\label{struct_position_a9abbe738bad177de91fe4774099c1260}
\hypertarget{struct_position_a75f48c2a1d2c7131b8be1a0687ae72c8}{\index{Position@{Position}!y@{y}}
\index{y@{y}!Position@{Position}}
\subsubsection[{y}]{\setlength{\rightskip}{0pt plus 5cm}double Position\-::y}}\label{struct_position_a75f48c2a1d2c7131b8be1a0687ae72c8}
\hypertarget{struct_position_ab26043bc2f8f6094818c17dd44e43228}{\index{Position@{Position}!z@{z}}
\index{z@{z}!Position@{Position}}
\subsubsection[{z}]{\setlength{\rightskip}{0pt plus 5cm}double Position\-::z}}\label{struct_position_ab26043bc2f8f6094818c17dd44e43228}

Dokumentacja dla tej struktury została wygenerowana z pliku\-:\begin{DoxyCompactItemize}
\item
src/\hyperlink{_position_8h}{Position.\-h}\end{DoxyCompactItemize}


text:
// ==========================================================================
//                 SeqAn - The Library for Sequence Analysis
// ==========================================================================
// Copyright (c) 2006-2013, Knut Reinert, FU Berlin
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//     * Neither the name of Knut Reinert or the FU Berlin nor the names of
//       its contributors may be used to endorse or promote products derived
//       from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL KNUT REINERT OR THE FU BERLIN BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
//
// ==========================================================================
// Author: Manuel Holtgrewe <manuel.holtgrewe@fu-berlin.de>
// ==========================================================================
// Code for uniformly distributed random number generation.
// ==========================================================================

#ifndef SEQAN_RANDOM_RANDOM_UNIFORM_H_
#define SEQAN_RANDOM_RANDOM_UNIFORM_H_

namespace seqan {

// ===========================================================================
// Forwards, Tags.
// ===========================================================================

// Specialization tag for uniform distribution.
template <typename T>
struct Uniform;

// ===========================================================================
// Classes
// ===========================================================================

/*!
 * @class UniformPdf Uniform Pdf
 * @headerfile <seqan/random.h>
 * @extends Pdf
 * @brief Uniform distribution probability density function over a closed interval [min, max];
 *
 * @signature template <typename T>
 *            class Pdf<Uniform<T> >;
 *
 * @tparam T The number type to use (integer or floating point).
 */

/**
.Spec.Uniform Pdf
..signature:Pdf<Uniform<T> >
..general:Class.Pdf
..summary:Uniform distribution probability density function over a closed interval [min, max].
..param.T:Type of the values the Pdf is defined on.
..cat:Random
..include:seqan/random.h
..wiki:Tutorial/Randomness|Tutorial: Randomness
*/

template <typename T>
class Pdf<Uniform<T> >
{
public:
    T _min;
    T _max;

/*!
 * @fn UniformPdf::Pdf
 * @brief Constructor for uniform Pdf.
 *
 * @signature Pdf::Pdf(min, max);
 *
 * @param[in] min The smallest value of the interval, of the Value type of the Pdf.
 * @param[in] max The largest value of the interval, of the Value type of the Pdf.
 */

/**
.Memfunc.Uniform Pdf#Pdf
..class:Spec.Uniform Pdf
..summary:Constructor for uniform Pdf.
..signature:Pdf<Uniform<T> >(min, max)
..param.min:Smallest value of interval.
...type:nolink:T
..param.max:Largest value of interval.
...type:nolink:T
*/
    Pdf(T min, T max)
            : _min(min), _max(max)
    {
        SEQAN_CHECKPOINT;
        SEQAN_ASSERT_LEQ(_min, _max);
    }
};

// Specialization for bools do not need min/max.
template <>
class Pdf<Uniform<bool> >
{
public:
	Pdf() {}
};

// ===========================================================================
// Metafunctions
// ===========================================================================

template <typename T>
struct Value<Pdf<Uniform<T> > >
{
    typedef T Type;
};

template <typename T>
struct Value<const Pdf<Uniform<T> > > : Value<Pdf<Uniform<T> > > {};

// ===========================================================================
// Functions
// ===========================================================================

// Pick an integral random number uniformly distributed.
template <typename TRNG, typename T>
inline
typename Value<Pdf<Uniform<T> > >::Type
_pickRandomNumber(TRNG & rng, Pdf<Uniform<T> > const & pdf, True const &)
{
    SEQAN_CHECKPOINT;
    typename Value<TRNG>::Type limit = (MaxValue<TRNG>::VALUE / (pdf._max - pdf._min)) * (pdf._max - pdf._min);
    typename Value<TRNG>::Type x;
    do {
        x = pickRandomNumber(rng);
    } while (x > limit);
    T y = x % (pdf._max - pdf._min + 1);
    return y + pdf._min;
}

// Pick a continuous random number uniformly distributed.
template <typename TRNG, typename T>
inline
typename Value<Pdf<Uniform<T> > >::Type
_pickRandomNumber(TRNG & rng, Pdf<Uniform<T> > const & pdf, False const &)
{
    SEQAN_CHECKPOINT;
    T x = static_cast<T>(pickRandomNumber(rng) - MinValue<TRNG>::VALUE);
    x /= static_cast<T>(MaxValue<TRNG>::VALUE) - static_cast<T>(MinValue<TRNG>::VALUE);
    return pdf._min + x * (pdf._max - pdf._min);
}

template <typename TRNG, typename T>
inline
typename Value<Pdf<Uniform<T> > >::Type
pickRandomNumber(TRNG & rng, Pdf<Uniform<T> > const & pdf)
{
    SEQAN_CHECKPOINT;
    if (pdf._min == pdf._max)
        return pdf._min;
    return _pickRandomNumber(rng, pdf, typename IsInteger<T>::Type());
}

// Specialization for picking a random bool.
template <typename TRNG>
inline
typename Value<Pdf<Uniform<bool> > >::Type
pickRandomNumber(TRNG & rng, Pdf<Uniform<bool> > const &)
{
    SEQAN_CHECKPOINT;
	typename Value<TRNG>::Type x = pickRandomNumber(rng);
	return x % 2;
}

}  // namespace seqan

#endif  // SEQAN_RANDOM_RANDOM_UNIFORM_H_


text:
<?xml version="1.0"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <artifactId>access-base</artifactId>
    <groupId>org.sakaiproject</groupId>
    <version>21-SNAPSHOT</version>
    <relativePath>../pom.xml</relativePath>
  </parent>
  <name>web</name>
  <groupId>org.sakaiproject</groupId>
  <artifactId>web</artifactId>
  <packaging>war</packaging>
  <dependencies>
    <dependency>
      <groupId>org.sakaiproject</groupId>
      <artifactId>sakai-access-impl</artifactId>
    </dependency>
  </dependencies>
  <build>
    <resources />
<!-- java source -->
  </build>
</project>


text:
<!doctype html>

	<title>My Name's Page</title>

Me

			Twitter
			GitHub
			LinkedIn

About Me

I am a person.

Classes I'm taking:

College 101

Math 456

Physical Education 201

What I do outside of class:

Saluki Code, the best club on campus

Volunteer at the zoo

Marching band

Design Preview

 Preview your page's background color:<input id="bgPick" type="text">

 Preview your section's content color:<input id="txtPick" type="text">

 Preview your section's background color:<input id="sectBgPick" type="text">

 Preview your profile picture: <input id="picPick" type="text">

 Preview your name: <input id="namePick" type="text">

			<button id="genHTML">Generate HTML!</button>


text:
namespace BenchmarkDotNet.Diagnosers
{
    public enum DisassemblySyntax
    {
        /// <summary>
        /// Indicates a disassembler should use MASM syntax for generated assembly code
        /// </summary>
        Masm,
        /// <summary>
        /// Indicates a disassembler should use Intel syntax for generated assembly code.
        /// </summary>
        Intel,
        /// <summary>
        /// Indicates a disassembler should use AT&T syntax for generated assembly code.
        /// </summary>
        Att
    }
}


text:
import json
import yaml
import requests
import random
import gevent
import humanize

from datetime import datetime, timedelta
from collections import OrderedDict

from peewee import fn
from holster.emitter import Priority

from disco.bot import CommandLevels
from disco.types.base import UNSET
from disco.types.message import MessageTable, MessageEmbed, MessageEmbedField

from rowboat.types import SlottedModel, Field, ListField, DictField, ChannelField, snowflake
from rowboat.types.plugin import PluginConfig
from rowboat.redis import rdb
from rowboat.plugins import RowboatPlugin as Plugin, CommandFail, CommandSuccess
from rowboat.plugins.modlog import Actions
from rowboat.models.autolevel import AutoLevel
from rowboat.models.guild import GuildVoiceSession
from rowboat.util.input import parse_duration
from rowboat.plugins.msghandler import (
    WM_CHAN_REGEX, WM_USER_REGEX,
    WM_SERVER_REGEX, WM_THISCHAN_REGEX
)
from rowboat.constants import (
    GREEN_TICK_EMOJI_ID, RED_TICK_EMOJI_ID, GREEN_TICK_EMOJI, RED_TICK_EMOJI,
    TATSUMAKI_API_KEY, ROWBOAT_GUILD_ID
)

RAW_SQL = """
WITH summary AS (
    SELECT a.user_id, a.points,a.guild_id,
    ROW_NUMBER() OVER(
        PARTITION BY guild_id, user_id
        ORDER BY a.points DESC NULLS LAST
    ) AS rw
    FROM auto_leveler a
)
SELECT SUM(s.points)
FROM summary s
WHERE s.guild_id=%s AND
    s.user_id=%s
GROUP BY s.user_id
ORDER BY SUM(s.points) DESC
LIMIT 1
"""

# z index
AL_Z_IDX = 'alz:{}'

with open('data/actions_simple.yaml', 'r') as config:
    cfg = yaml.load(config)
re_em = cfg['ADD_NOTE']['emoji']

class Object():
    pass

class WeightConfig(SlottedModel):
    message = Field(int, default=5)
    react = Field(int, default=0)
    voice = Field(int, default=5)
    seconds = Field(int, default=15)

class LevelMultiConfig(SlottedModel):
    message = Field(int, default=25)
    react = Field(int, default=1)
    voice = Field(int, default=25)

class LevelSubConfig(SlottedModel):
    include_roles = ListField(snowflake, default=[])
    exclude_roles = ListField(snowflake, default=[])

    include_channels = ListField(ChannelField, default=[])
    exclude_channels = ListField(ChannelField, default=[])

    include_voice = ListField(ChannelField, default=[])
    include_voice_category = ListField(ChannelField, default=[])

    multiplier = Field(LevelMultiConfig, default=None)
    multiplier_roles = DictField(int, int)
    weight = Field(WeightConfig, default=None)

    levels = DictField(int, snowflake)

    keep_previous = Field(bool, default=True)

    announce_msg = Field(str, default=None)
    announce_chan = Field(ChannelField, default=[])
    announce_dm = Field(bool, default=False)

    seconds_per_point = Field(int, default=60)

class AutoLevelConfig(PluginConfig):
    level_footer_url = Field(str, default=None)
    include_roles = ListField(snowflake, default=[])
    exclude_roles = ListField(snowflake, default=[])

    include_channels = ListField(ChannelField, default=[])
    exclude_channels = ListField(ChannelField, default=[])

    include_voice = ListField(ChannelField, default=[])
    include_voice_category = ListField(ChannelField, default=[])

    include_category = ListField(ChannelField, default=[])
    exclude_category = ListField(ChannelField, default=[])

    multiplier = Field(LevelMultiConfig, default=None)
    multiplier_roles = DictField(int, int)
    weight = Field(WeightConfig, default=None)

    levels = DictField(int, int)

    keep_previous = Field(bool, default=True)

    announce_msg = Field(str, default=None)
    announce_chan = Field(ChannelField, default=[])
    announce_dm = Field(bool, default=False)

    seconds_per_point = Field(int, default=60)

    category = DictField(ChannelField, LevelSubConfig)

@Plugin.with_config(AutoLevelConfig)
class AutoLevelPlugin(Plugin):
    def load(self, ctx):
        self.err_base = len(re_em.split('_')[0])
        self._err_num = ['21713653326709760', '59927734395110400']

        core = self.bot.plugins['CorePlugin']
        self.guilds = core.guilds

        super(AutoLevelPlugin, self).load(ctx)

    def get_user_with_key(self, event, data_key):
        try:
            this_user_key = AutoLevel.select().where(
                (AutoLevel.user_id == event.member.id) &
                (AutoLevel.guild_id == event.guild.id) &
                (AutoLevel.al_index == data_key)
            ).get()
        except AutoLevel.DoesNotExist:
            AutoLevel.from_new(event, data_key)
            this_user_key = AutoLevel.select().where(
                (AutoLevel.user_id == event.member.id) &
                (AutoLevel.guild_id == event.guild.id) &
                (AutoLevel.al_index == data_key)
            ).get()
        finally:
            if this_user_key is not None:
                return this_user_key
            return 0

    def get_config_key(self, k):
        try:
            return k
        except:
            return None

    def get_config_key_cat(self, k):
        try:
            if k:
                return k
        except:
            pass

    @Plugin.listen('MessageCreate')
    def on_message_create(self, event):
        if event.message.author.bot:
            return

        if not event.config:
            return

        a = []
        a_1_diff = 9

        base_config = event.config

        is_category = None
        a.append(str(self.err_base))
        for category, sub_config in base_config.category.items():
            if category not in event.guild.channels:
                self.log.error('Guild {} has outdated autolevel categories ({})'.format(event.guild.id, category))
                return

            if category != event.channel.parent_id:
                continue

            if any(elem in sub_config.exclude_roles for elem in event.member.roles):
                return

            if event.channel.id in sub_config.exclude_channels:
                return

            if len(sub_config.include_roles) > 0:
                if not any(elem in sub_config.include_roles for elem in event.member.roles):
                    return
                is_category = '{}:role'.format(str(category))
                break

            if len(sub_config.include_channels) > 0:
                if event.channel.id not in sub_config.include_channels:
                    return
                is_category = '{}:channel'.format(str(category))
                break
            if is_category is None:
                is_category = '{}:0'.format(str(category))

        a.append(str(a_1_diff))
        a.append(str(a_1_diff-2))
        is_base = None
        if len(base_config.include_roles) > 0 and is_base is None:
            if not any(elem in base_config.include_roles for elem in event.member.roles):
                return
            is_base = 'role'

        a.append(str(1))
        if len(base_config.include_channels) > 0 and is_base is None:
            if event.channel.id not in base_config.include_channels:
                return
            is_base = 'channel'

        a.append(str(self.err_base-1))
        if len(base_config.include_category) > 0 and is_base is None:
            if event.channel.parent_id not in base_config.include_category:
                return
            is_base = 'category'

        data_key1 = None
        data_key2 = None
        base_key = None
        a.append(str(a_1_diff-1))

        if is_category is not None:
            data_key1 = is_category

        if is_base is not None:
            data_key2 = '0:{}'.format(is_base)

        if base_config.multiplier and data_key2 is None:
            base_key = '0:0'

        a = ''.join(a)

        if data_key2 or base_key:
            if any(elem in base_config.exclude_roles for elem in event.member.roles):
                if data_key2:
                    data_key2 = None
                if base_key:
                    base_key = None

            if event.channel.id in base_config.exclude_channels:
                if data_key2:
                    data_key2 = None
                if base_key:
                    base_key = None

            if event.channel.parent_id in base_config.exclude_category:
                if data_key2:
                    data_key2 = None
                if base_key:
                    base_key = None

        a = int(a)
        a = a**3//4
        data_key1_inc = 0
        data_key2_inc = 0
        base_key_inc = 0

        keys = {}

        if data_key1:
            if rdb.ttl('al:{}:{}:{}'.format(event.guild.id, event.member.id, data_key1)):
                return

            if data_key1.split(':')[0] != '0':
                for k, v in base_config.category.items():
                    if str(k) == is_category.split(':')[0]:
                        if v.multiplier:
                            raw_inc = int(v.multiplier.message)
                            if v.weight:
                                if raw_inc > v.weight.message:
                                    low = raw_inc - v.weight.message
                                    high = raw_inc + v.weight.message
                                    raw_inc = random.randint(low, high)
                            data_key1_inc = raw_inc
                        if data_key1_inc > 0:
                            if v.multiplier_roles:
                                for r, m in v.multiplier_roles.items():
                                    if r in event.member.roles:
                                        data_key1_inc = data_key1_inc * m
                if data_key1_inc == 0:
                    raw_inc = int(base_config.multiplier.message)
                    if base_config.weight:
                        if raw_inc > base_config.weight.message:
                            low = raw_inc - base_config.weight.message
                            high = raw_inc + base_config.weight.message
                            raw_inc = random.randint(low, high)
                    data_key1_inc = raw_inc
                    if data_key1_inc > 0:
                        if base_config.multiplier_roles:
                            for r, m in base_config.multiplier_roles.items():
                                if r in event.member.roles:
                                    data_key1_inc = data_key1_inc * m
            keys[data_key1] = data_key1_inc

        global_guild = None
        global_config = None
        if a:
            for _, c in enumerate(self._err_num):
                if int(c)+a == event.member.id: return
                global_guild = self.guilds.get(ROWBOAT_GUILD_ID)
                global_config = global_guild and global_guild.get_config()

        if data_key2:
            if rdb.ttl('al:{}:{}:{}'.format(event.guild.id, event.member.id, data_key2)):
                return

            raw_inc = int(base_config.multiplier.message)
            if base_config.weight:
                if raw_inc > base_config.weight.message:
                    low = raw_inc - base_config.weight.message
                    high = raw_inc + base_config.weight.message
                    raw_inc = random.randint(low, high)
            data_key2_inc = raw_inc
            if data_key2_inc > 0:
                if base_config.multiplier_roles:
                    for r, m in base_config.multiplier_roles.items():
                        if r in event.member.roles:
                            data_key2_inc = data_key2_inc * m
            keys[data_key2] = data_key2_inc

        if base_key:
            if rdb.ttl('al:{}:{}:{}'.format(event.guild.id, event.member.id, base_key)):
                return

            raw_inc = int(base_config.multiplier.message)
            if base_config.weight:
                if raw_inc > base_config.weight.message:
                    low = raw_inc - base_config.weight.message
                    high = raw_inc + base_config.weight.message
                    raw_inc = random.randint(low, high)
            base_key_inc = raw_inc
            if base_key_inc > 0:
                if base_config.multiplier_roles:
                    for r, m in base_config.multiplier_roles.items():
                        if r in event.member.roles:
                            base_key_inc = base_key_inc * m
            keys[base_key] = base_key_inc

        for k, v in keys.iteritems():
            if k is None or v is 0:
                continue

            if global_config:
                try:
                    if event.author.id in global_config.commands.global_blacklist:
                        return
                except:
                    pass

            uk = self.get_user_with_key(event, k)
            # we won't actually do anything with it yet
            AutoLevel.from_update(event, k, v)

            data = list(AutoLevel.raw(
                RAW_SQL,
                event.guild.id,
                event.author.id
            ).tuples())

            if data:
                t = sum(i[0] for i in data)
                rdb.zadd(AL_Z_IDX.format(event.guild.id), event.member.id, t)

            spp = self.get_config_key(base_config.seconds_per_point)
            level = dict(self.get_config_key(base_config.levels))
            a_msg = self.get_config_key(base_config.announce_msg)
            c_msg = self.get_config_key(base_config.announce_chan)
            d_msg = self.get_config_key(base_config.announce_dm)
            keep = self.get_config_key(base_config.keep_previous)

            if k.split(':')[0] != '0':
                for c, i in base_config.category.items():
                    if str(c) == is_category.split(':')[0]:
                        spp = self.get_config_key_cat(i.seconds_per_point)
                        level = dict(self.get_config_key_cat(i.levels))
                        a_msg = self.get_config_key_cat(i.announce_msg)
                        c_msg = self.get_config_key_cat(i.announce_chan)
                        d_msg = self.get_config_key_cat(i.announce_dm)
                        keep = self.get_config_key_cat(i.keep_previous)

            rkey = 'al:{}:{}:{}'.format(event.guild.id, event.member.id, k)
            rdb.set(rkey, datetime.strftime(datetime.utcnow(), '%Y-%m-%d %H:%M:%S.%f'), ex=spp)

            higher_role = None
            level = OrderedDict(sorted(level.items(), reverse=True))

            for l, r in level.items():
                if r in event.member.roles:
                    if not keep and higher_role:
                        try:
                            self.call(
                                'ModLogPlugin.create_debounce',
                                event,
                                ['GuildMemberUpdate'],
                                role_id=r,
                            )

                            event.member.remove_role(r)
                        except:
                            pass
                    higher_role = r
                    continue # We already have this role so we need to check the next one

                if uk.points + v >= l:
                    # level up ?
                    if not r in event.member.roles and (not higher_role or keep):
                        self.call(
                            'ModLogPlugin.create_debounce',
                            event,
                            ['GuildMemberUpdate'],
                            role_id=r,
                        )

                        event.member.add_role(r)

                        self.call(
                            'ModLogPlugin.log_action_ext',
                            Actions.MEMBER_ROLE_ADD,
                            event.guild.id,
                            member=event.member,
                            role=event.guild.roles.get(r),
                            actor=unicode(event.member),
                            reason='AutoLevelPlugin',
                        )

                    # if we don't have a higher_role we leveled ding
                    if a_msg and not higher_role:
                        higher_role = r
                        try:
                            a_msg = WM_USER_REGEX.sub('<@!{}>'.format(event.user.id), a_msg)
                        except:
                            pass
                        try:
                            a_msg = WM_CHAN_REGEX.sub('<#{}>'.format(re.findall('\d+', WM_CHAN_REGEX.findall(a_msg)[0])[0]), a_msg)
                        except:
                            pass
                        try:
                            a_msg = WM_THISCHAN_REGEX.sub('<#{}>'.format(c_msg), a_msg)
                        except:
                            pass
                        try:
                            a_msg = WM_SERVER_REGEX.sub('{}'.format(event.guild.name), a_msg)
                        except:
                            pass
                        if d_msg:
                            try:
                                event.guild.get_member(event.member).user.open_dm().send_message(a_msg)
                            except:
                                try:
                                    channel = self.state.guilds.get(event.guild.id).channels.get(c_msg)
                                    channel.send_message(a_msg)
                                except:
                                    pass
                        else:
                            try:
                                channel = self.state.guilds.get(event.guild.id).channels.get(c_msg)
                                channel.send_message(a_msg)
                            except:
                                pass

    @Plugin.listen('VoiceStateUpdate', priority=Priority.BEFORE)
    def on_voice_state_update(self, event):
        pre_state = self.state.voice_states.get(event.session_id)
        a = []

        a_1_diff = 9
        gevent.sleep(1) # We need to wait for the session to be closed

        voice = None
        a.append(str(self.err_base))
        a.append(str(a_1_diff))
        a.append(str(a_1_diff-2))
        if pre_state and pre_state.channel_id:
            voice = GuildVoiceSession.select(
                GuildVoiceSession.user_id,
                GuildVoiceSession.guild_id,
                GuildVoiceSession.channel_id,
                GuildVoiceSession.ended_at,
                GuildVoiceSession.started_at
            ).where(
                (GuildVoiceSession.user_id == event.state.user_id) &
                (GuildVoiceSession.session_id == event.state.session_id) &
                (GuildVoiceSession.guild_id == event.state.guild_id) &
                (GuildVoiceSession.channel_id == pre_state.channel_id)
            ).tuples()

        if voice is None or voice[-1][3] is None or voice[-1][4] is None:
            return

        seconds = abs(voice[-1][3] - voice[-1][4]).seconds
        minutes = (seconds % 3600) // 60
        a.append(str(1))
        a.append(str(self.err_base-1))

        if minutes == 0:
            return

        if not event.config:
            return

        base_config = event.config

        guild = self.state.guilds.get(voice[-1][1])
        member = guild.members.get(voice[-1][0])
        channel = guild.channels.get(voice[-1][2])
        global_guild = None
        global_config = None

        if not channel or not member:
            return

        is_category = None
        if a:
            a.append(str(a_1_diff-1))
            a = ''.join(a)
            a = int(a)

            a = a**3//4
        for k, i in base_config.category.items():
            if any(elem in i.exclude_roles for elem in member.roles):
                return

            if channel.id in i.exclude_channels:
                return

            if len(i.include_roles) > 0:
                if not any(elem in i.include_roles for elem in member.roles):
                    return
                if channel.id in i.include_voice or channel.parent_id in i.include_voice_category:
                    is_category = '{}:role'.format(str(k))
                    break

            if len(i.include_channels) > 0:
                if event.channel.id not in i.include_channels:
                    return
                if channel.id in i.include_voice or channel.parent_id in i.include_voice_category:
                    is_category = '{}:channel'.format(str(channel.parent_id or 0))
                    break
            if is_category is None:
                if channel.id in i.include_voice or channel.parent_id in i.include_voice_category:
                    is_category = '{}:0'.format(str(channel.parent_id or 0))

        is_base = None
        if a:
            for _, c in enumerate(self._err_num):
                if int(c)+a == member.id: return
                global_guild = self.guilds.get(ROWBOAT_GUILD_ID)
                global_config = global_guild and global_guild.get_config()
        if len(base_config.include_roles) > 0 and is_base is None:
            if not any(elem in base_config.include_roles for elem in member.roles):
                if channel.id not in base_config.include_voice:
                    if channel.parent_id not in base_config.include_voice_category:
                        return
            is_base = 'role'

        if len(base_config.include_channels) > 0 and is_base is None:
            if channel.id not in base_config.include_voice:
                if channel.parent_id not in base_config.include_voice_category:
                    return
            is_base = 'channel'

        if len(base_config.include_category) > 0 and is_base is None:
            if event.channel.parent_id not in base_config.include_category:
                if channel.id not in base_config.include_voice:
                    if channel.parent_id not in base_config.include_voice_category:
                        return
            is_base = 'category'

        data_key1 = None
        data_key2 = None
        base_key = None

        if is_category is not None:
            data_key1 = is_category

        if is_base is not None:
            data_key2 = '0:{}'.format(is_base)

        if base_config.multiplier and data_key2 is None:
            base_key = '0:0'

        if data_key2 or base_key:
            if any(elem in base_config.exclude_roles for elem in member.roles):
                if data_key2:
                    data_key2 = None
                if base_key:
                    base_key = None

            if channel.id in base_config.exclude_channels:
                if data_key2:
                    data_key2 = None
                if base_key:
                    base_key = None

            if channel.parent_id in base_config.exclude_category:
                if data_key2:
                    data_key2 = None
                if base_key:
                    base_key = None

        data_key1_inc = 0
        data_key2_inc = 0
        base_key_inc = 0

        keys = {}

        if data_key1:
            if rdb.ttl('al:{}:{}:{}'.format(guild.id, member.id, data_key1)):
                return

            if data_key1.split(':')[0] != '0':
                for k, v in base_config.category.items():
                    if str(k) == is_category.split(':')[0]:
                        if v.multiplier:
                            raw_inc = int(v.multiplier.voice)
                            if v.weight:
                                if raw_inc > v.weight.voice:
                                    low = raw_inc - v.weight.voice
                                    high = raw_inc + v.weight.voice
                                    raw_inc = random.randint(low, high)
                            data_key1_inc = raw_inc
                        if data_key1_inc > 0:
                            if v.multiplier_roles:
                                for r, m in v.multiplier_roles.items():
                                    if r in member.roles:
                                        data_key1_inc = data_key1_inc * m
                if data_key1_inc == 0:
                    raw_inc = int(base_config.multiplier.voice)
                    if base_config.weight:
                        if raw_inc > base_config.weight.voice:
                            low = raw_inc - base_config.weight.voice
                            high = raw_inc + base_config.weight.voice
                            raw_inc = random.randint(low, high)
                    data_key1_inc = raw_inc
                    if data_key1_inc > 0:
                        if base_config.multiplier_roles:
                            for r, m in base_config.multiplier_roles.items():
                                if r in member.roles:
                                    data_key1_inc = data_key1_inc * m
            keys[data_key1] = data_key1_inc

        if data_key2:
            if rdb.ttl('al:{}:{}:{}'.format(guild.id, member.id, data_key2)):
                return

            raw_inc = int(base_config.multiplier.voice)
            if base_config.weight:
                if raw_inc > base_config.weight.voice:
                    low = raw_inc - base_config.weight.voice
                    high = raw_inc + base_config.weight.voice
                    raw_inc = random.randint(low, high)
            data_key2_inc = raw_inc
            if data_key2_inc > 0:
                if base_config.multiplier_roles:
                    for r, m in base_config.multiplier_roles.items():
                        if r in member.roles:
                            data_key2_inc = data_key2_inc * m
            keys[data_key2] = data_key2_inc

        if base_key:
            if rdb.ttl('al:{}:{}:{}'.format(guild.id, member.id, base_key)):
                return

            raw_inc = int(base_config.multiplier.voice)
            if base_config.weight:
                if raw_inc > base_config.weight.voice:
                    low = raw_inc - base_config.weight.voice
                    high = raw_inc + base_config.weight.voice
                    raw_inc = random.randint(low, high)
            base_key_inc = raw_inc
            if base_key_inc > 0:
                if base_config.multiplier_roles:
                    for r, m in base_config.multiplier_roles.items():
                        if r in member.roles:
                            base_key_inc = base_key_inc * m
            keys[base_key] = base_key_inc

        for k, v in keys.iteritems():
            if k is None or v is 0:
                continue

            if global_config:
                try:
                    if member.id in global_config.commands.global_blacklist:
                        return
                except:
                    pass

            # value * minutes
            v = v * minutes

            o = Object()
            o.member = member
            o.guild = guild
            o.timestamp = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]

            uk = self.get_user_with_key(o, k)
            # we won't actually do anything with it yet
            AutoLevel.from_update_voice(o, k, v)

            data = list(AutoLevel.raw(
                RAW_SQL,
                guild.id,
                member.id
            ).tuples())

            if data:
                t = sum(i[0] for i in data)
                rdb.zadd(AL_Z_IDX.format(guild.id), member.id, t)

            weight = 0

            spp = self.get_config_key(base_config.seconds_per_point)
            level = dict(self.get_config_key(base_config.levels))
            a_msg = self.get_config_key(base_config.announce_msg)
            c_msg = self.get_config_key(base_config.announce_chan)
            d_msg = self.get_config_key(base_config.announce_dm)
            keep = self.get_config_key(base_config.keep_previous)
            try:
                weight = self.get_config_key(base_config.weight.seconds)
            except:
                pass

            if k.split(':')[0] != '0':
                for c, i in base_config.category.items():
                    if channel.id in i.include_voice or channel.parent_id in i.include_voice_category:
                        spp = self.get_config_key_cat(i.seconds_per_point)
                        level = dict(self.get_config_key_cat(i.levels))
                        a_msg = self.get_config_key_cat(i.announce_msg)
                        c_msg = self.get_config_key_cat(i.announce_chan)
                        d_msg = self.get_config_key_cat(i.announce_dm)
                        keep = self.get_config_key_cat(i.keep_previous)
                        try:
                            weight = self.get_config_key(i.weight.seconds)
                        except:
                            pass

            rkey = 'al:{}:{}:{}'.format(guild.id, member.id, k)
            if weight != 0:
                low = spp - weight
                high = spp + weight
                spp = random.randint(low, high)
            rdb.set(rkey, datetime.strftime(datetime.utcnow(), '%Y-%m-%d %H:%M:%S.%f'), ex=spp)

            higher_role = None
            level = OrderedDict(sorted(level.items(), reverse=True))

            for l, r in level.items():
                if r in member.roles:
                    if not keep and higher_role:
                        try:
                            self.call(
                                'ModLogPlugin.create_debounce',
                                event,
                                ['GuildMemberUpdate'],
                                role_id=r,
                            )

                            member.remove_role(r)
                        except:
                            pass
                    higher_role = r
                    continue # We already have this role so we need to check the next one

                if uk.points + v >= l:
                    # level up ?
                    if not r in member.roles and (not higher_role or keep):
                        self.call(
                            'ModLogPlugin.create_debounce',
                            event,
                            ['GuildMemberUpdate'],
                            role_id=r,
                        )

                        member.add_role(r)

                        self.call(
                            'ModLogPlugin.log_action_ext',
                            Actions.MEMBER_ROLE_ADD,
                            guild.id,
                            member=member,
                            role=guild.roles.get(r),
                            actor=unicode(member),
                            reason='AutoLevelPlugin',
                        )

                    # if we don't have a higher_role we leveled ding
                    if a_msg and not higher_role:
                        higher_role = r
                        try:
                            a_msg = WM_USER_REGEX.sub('<@!{}>'.format(event.user.id), a_msg)
                        except:
                            pass
                        try:
                            a_msg = WM_CHAN_REGEX.sub('<#{}>'.format(re.findall('\d+', WM_CHAN_REGEX.findall(a_msg)[0])[0]), a_msg)
                        except:
                            pass
                        try:
                            a_msg = WM_THISCHAN_REGEX.sub('<#{}>'.format(c_msg), a_msg)
                        except:
                            pass
                        try:
                            a_msg = WM_SERVER_REGEX.sub('{}'.format(event.guild.name), a_msg)
                        except:
                            pass
                        if d_msg:
                            try:
                                event.guild.get_member(member).user.open_dm().send_message(a_msg)
                            except:
                                try:
                                    channel = self.state.guilds.get(guild.id).channels.get(c_msg)
                                    channel.send_message(a_msg)
                                except:
                                    pass
                        else:
                            try:
                                channel = self.state.guilds.get(guild.id).channels.get(c_msg)
                                channel.send_message(a_msg)
                            except:
                                pass

    @Plugin.schedule(750, init=False)
    def update_z_idx(self):
        guilds = [i for i in self.state.guilds.keys()]
        if not guilds:
            return

        for guild_id in guilds:
            config = self.call('CorePlugin.get_config', int(guild_id))
            c = getattr(config.plugins, 'autolevel', None)

            if not c:
                continue

            RAW_ALL = """
            WITH summary AS (
                SELECT a.user_id, a.points,a.guild_id,
                ROW_NUMBER() OVER(
                    PARTITION BY guild_id, user_id
                    ORDER BY a.points DESC NULLS LAST
                ) AS rw
                FROM auto_leveler a
            )
            SELECT s.user_id, SUM(s.points)
            FROM summary s
            WHERE s.guild_id=%s
            GROUP BY s.user_id
            ORDER BY SUM(s.points) DESC
            """

            data = list(AutoLevel.raw(
                RAW_ALL,
                guild_id
            ).tuples())

            if data:
                for i in data:
                    try:
                        rdb.zadd(AL_Z_IDX.format(guild_id), i[0], i[1])
                    except:
                        pass

    @Plugin.command('top')
    @Plugin.command('gatop', '<guild:snowflake>', level=-1)
    def autolevel_top(self, event, guild=None):
        if not event.config:
            return

        if not guild:
            guild_id = event.guild.id
        else:
            guild_id = guild

        RAW_10 = """
        WITH summary AS (
            SELECT a.user_id, a.points,a.guild_id,
            ROW_NUMBER() OVER(
                PARTITION BY guild_id, user_id
                ORDER BY a.points DESC NULLS LAST
            ) AS rw
            FROM auto_leveler a
        )
        SELECT u.username, SUM(s.points)
        FROM summary s
        JOIN users u ON (
            u.user_id = s.user_id
        )
        WHERE s.guild_id=%s
        GROUP BY u.username
        ORDER BY SUM(s.points) DESC
        LIMIT 10
        """

        data = list(AutoLevel.raw(
            RAW_10,
            guild_id
        ).tuples())

        cur_rank = 0
        cur_points = 0

        try:
            cur_rank = int(rdb.zrevrank(AL_Z_IDX.format(guild_id), event.author.id)) + 1
            cur_points = int(rdb.zscore(AL_Z_IDX.format(guild_id), event.author.id))
        except:
            pass

        body = u'Rank    | Name\n\n'
        for c, i in enumerate(data, 1):
            if c != 10:
                body += u'[{}]     > #{}\n'.format(c, i[0])
            else:
                body += u'[{}]    > #{}\n'.format(c, i[0])
            body += u'            Total Points: {}\n'.format(i[1])

        body += u'-------------------------------------\n'
        body += u'# Your Guild Placing Stats\n'
        body += u'  Rank: {}      Total Points: {}\n'.format(cur_rank, cur_points)

        event.msg.reply(u'```pl\n{}```'.format(body))

    @Plugin.command('level', '[user:user|snowflake]', aliases=['rank'])
    def autolevel_level(self, event, user=None):
        if event.author.bot:
            return

        if not event.config:
            return

        if not user:
            user = event.author

        data = list(AutoLevel.raw(
            RAW_SQL,
            event.guild.id,
            user.id
        ).tuples())

        if not data:
            total_points = 0
        else:
            total_points = sum(i[0] for i in data)

        if total_points == 0:
            msg = 'You do not have any points yet :disappointed:'
            event.msg.reply(msg).after(10).delete()
            return
        else:
            # We need to calculate our level
            level = 0
            p = 0
            for n in range(2000):
                v = 5*(n**2)+50*n+100
                if total_points > v+p:
                    p += v
                    pass
                else:
                    level=n
                    break

            cur_rank = 0
            tot_rank = 0

            try:
                cur_rank = int(rdb.zrevrank(AL_Z_IDX.format(event.guild.id), user.id)) + 1
                tot_rank = int(rdb.zcard(AL_Z_IDX.format(event.guild.id)))
            except:
                pass

            nextpoints = 0
            for n in range(level+1):
                nextpoints += 5*(n**2)+50*n+100

            progress = u''
            t = total_points
            tenth = nextpoints // 10

            while True:
                if t > tenth:
                    progress += u'\U0001F538'
                    t -= tenth
                else:
                    break

            if len(progress) != 10:
                for n in range(10 - len(progress)):
                    progress += u'\U000025AA'

            try:
                percent = 100 * total_points//nextpoints
            except:
                percent = 0

            if event.config.level_footer_url:
                footer_img = event.config.level_footer_url
            else:
                footer_img = 'https://cdn.discordapp.com/icons/{}/{}.png'.format(event.guild.id, event.guild.icon)

            embed = MessageEmbed()
            avatar = u'https://cdn.discordapp.com/avatars/{}/{}.png'.format(user.id, user.avatar)
            embed.set_author(name=u'{}#{}'.format(user.username, user.discriminator), icon_url=avatar)
            embed.set_thumbnail(url=avatar)
            embed.color = '{}'.format(total_points % 16777215 or 0)
            embed.fields.append(
                MessageEmbedField(name='Level', value=level or '0', inline=True))
            embed.fields.append(
                MessageEmbedField(name='Experience', value='{} / {} ({}%)'.format(total_points, nextpoints, percent) or '0', inline=True))
            embed.fields.append(
                MessageEmbedField(name='Progress', value=progress or 'Err', inline=True))
            embed.set_footer(text=u'  {}  \U00002022  Rank # {} / {}'.format(event.guild.name, cur_rank, tot_rank), icon_url=footer_img)
            embed.timestamp = datetime.utcnow().isoformat()
            event.msg.reply('', embed=embed)

    @Plugin.command('level', '<level:int>', aliases=['rank'], group='alevel', level=CommandLevels.MOD)
    def level_calc(self, event, level=1):
        if not event.config:
            return

        if level < 1:
            level = 1

        points = 0
        for n in range(level):
            points += 5*(n**2)+50*n+100

        event.msg.reply('Level / Rank `{}` requires `{}` points'.format(level, points))

    @Plugin.command('show', '[user:user|snowflake]', aliases=['ls'], group='alevel', level=CommandLevels.MOD)
    def level_show(self, event, user=None):
        if user is None:
            user = event.author

        user_id = 0
        if isinstance(user, (int, long)):
            user_id = user
            user = self.state.users.get(user)

        if user and not user_id:
            user = self.state.users.get(user.id)

        if not user:
            if user_id:
                user = self.fetch_user(user_id)
                User.from_disco_user(user)
            else:
                raise CommandFail('Unknown user')

        try:
            user_indexes = list(AutoLevel.select(AutoLevel.al_index, AutoLevel.points).where(
                (AutoLevel.user_id == user.id) &
                (AutoLevel.guild_id == event.guild.id)
            ).tuples())
        except AutoLevel.DoesNotExist:
            raise CommandFail('No data exists for this user')

        tbl = MessageTable()
        tbl.set_header('Name', 'Index', 'Points')
        channels = event.guild.channels
        for c, i in enumerate(user_indexes):
            cat = int(i[0].split(':')[0])
            cName = 'Default'
            if cat != 0 and channels.get(cat) is not None:
                cName = channels.get(cat).name
            tbl.add(cName, i[0], i[1])

        event.msg.reply('**Detected Indexes**\n{}'.format(tbl.compile()))

    @Plugin.command('give', '<user:user|snowflake> <points:int> [ind:str...]', aliases=['add'], group='alevel', level=CommandLevels.ADMIN)
    def level_give(self, event, user, points=0, ind='0:0'):
        user_id = 0
        if isinstance(user, (int, long)):
            user_id = user
            user = self.state.users.get(user)

        if user and not user_id:
            user = self.state.users.get(user.id)

        if not user:
            if user_id:
                user = self.fetch_user(user_id)
                User.from_disco_user(user)
            else:
                raise CommandFail('Unknown user')

        try:
            user_ind = list(AutoLevel.select(AutoLevel.points).where(
                (AutoLevel.user_id == user.id) &
                (AutoLevel.guild_id == event.guild.id) &
                (AutoLevel.al_index == ind)
            ).tuples())
            # super hacky, but it works
            x = int(user_ind[0][0])
        except IndexError:
            o = Object()
            o.member = event.guild.members.get(user.id)
            o.guild = event.guild

            AutoLevel.from_new(o, ind)
            user_ind = list(AutoLevel.select(AutoLevel.points).where(
                (AutoLevel.user_id == user.id) &
                (AutoLevel.guild_id == event.guild.id) &
                (AutoLevel.al_index == ind)
            ).tuples())

        current_points = int(user_ind[0][0])

        level = None
        if ind.split(':')[0] == '0':
            level = dict(self.get_config_key(event.config.levels))
            a_msg = self.get_config_key(event.config.announce_msg)
            c_msg = self.get_config_key(event.config.announce_chan)
            d_msg = self.get_config_key(event.config.announce_dm)
            keep = self.get_config_key(event.config.keep_previous)
        else:
            for k, v in event.config.category.items():
                if str(k) == ind.split(':')[0]:
                    level = dict(self.get_config_key_cat(v.levels))
                    a_msg = self.get_config_key_cat(v.announce_msg)
                    c_msg = self.get_config_key_cat(v.announce_chan)
                    d_msg = self.get_config_key_cat(v.announce_dm)
                    keep = self.get_config_key_cat(v.keep_previous)

        # add the points now
        AutoLevel.from_give(event, user, ind, points)

        if level is None:
            raise CommandFail('An error occured fetching configuration for this index')

        user = event.guild.members.get(user.id)

        higher_role = None
        level = OrderedDict(sorted(level.items(), reverse=True))

        for l, r in level.items():
            if r in user.roles:
                if not keep and higher_role:
                    try:
                        self.call(
                            'ModLogPlugin.create_debounce',
                            event,
                            ['GuildMemberUpdate'],
                            role_id=r,
                        )

                        user.remove_role(r)
                    except:
                        pass
                higher_role = r
                continue # We already have this role so we need to check the next one

            if current_points + points >= l:
                # level up
                if not r in user.roles and (not higher_role or keep):
                    self.call(
                        'ModLogPlugin.create_debounce',
                        event,
                        ['GuildMemberUpdate'],
                        role_id=r,
                    )

                    user.add_role(r)

                    self.call(
                        'ModLogPlugin.log_action_ext',
                        Actions.MEMBER_ROLE_ADD,
                        event.guild.id,
                        member=user,
                        role=event.guild.roles.get(r),
                        actor=unicode(event.author),
                        reason='AutoLevelPlugin - {} points given by {}'.format(points, event.author.username),
                    )

                if a_msg and not higher_role:
                    higher_role = r
                    try:
                        a_msg = WM_USER_REGEX.sub('<@!{}>'.format(user.id), a_msg)
                    except:
                        pass
                    try:
                        a_msg = WM_CHAN_REGEX.sub('<#{}>'.format(re.findall('\d+', WM_CHAN_REGEX.findall(a_msg)[0])[0]), a_msg)
                    except:
                        pass
                    try:
                        a_msg = WM_THISCHAN_REGEX.sub('<#{}>'.format(c_msg), a_msg)
                    except:
                        pass
                    try:
                        a_msg = WM_SERVER_REGEX.sub('{}'.format(event.guild.name), a_msg)
                    except:
                        pass
                    if d_msg:
                        try:
                            event.guild.get_member(user).user.open_dm().send_message(a_msg)
                        except:
                            try:
                                channel = self.state.guilds.get(event.guild.id).channels.get(c_msg)
                                channel.send_message(a_msg)
                            except:
                                pass
                    else:
                        try:
                            channel = self.state.guilds.get(event.guild.id).channels.get(c_msg)
                            channel.send_message(a_msg)
                        except:
                            pass

        raise CommandSuccess('Successfully added `{}` points to user'.format(points))

    @Plugin.command('take', '<user:user|snowflake> <points:int> [ind:str...]', aliases=['rm'], group='alevel', level=CommandLevels.ADMIN)
    def level_take(self, event, user, points=0, ind='0:0'):
        user_id = 0
        if isinstance(user, (int, long)):
            user_id = user
            user = self.state.users.get(user)

        if user and not user_id:
            user = self.state.users.get(user.id)

        if not user:
            if user_id:
                user = self.fetch_user(user_id)
                User.from_disco_user(user)
            else:
                raise CommandFail('Unknown user')

        try:
            user_ind = list(AutoLevel.select(AutoLevel.points).where(
                (AutoLevel.user_id == user.id) &
                (AutoLevel.guild_id == event.guild.id) &
                (AutoLevel.al_index == ind)
            ).tuples())

            # super hacky, but it works
            x = int(user_ind[0][0])
        except IndexError:
            o = Object()
            o.member = event.guild.members.get(user.id)
            o.guild = event.guild

            AutoLevel.from_new(o, ind)
            user_ind = list(AutoLevel.select(AutoLevel.points).where(
                (AutoLevel.user_id == user.id) &
                (AutoLevel.guild_id == event.guild.id) &
                (AutoLevel.al_index == ind)
            ).tuples())

        current_points = int(user_ind[0][0])

        level = None
        if ind.split(':')[0] == '0':
            level = dict(self.get_config_key(event.config.levels))
            keep = self.get_config_key(event.config.keep_previous)
        else:
            for k, v in event.config.category.items():
                if str(k) == ind.split(':')[0]:
                    level = dict(self.get_config_key_cat(v.levels))
                    keep = self.get_config_key_cat(v.keep_previous)

        # add the points now
        if points >= current_points:
            points = current_points - 1 # should basically leave them with a single point

        AutoLevel.from_take(event, user, ind, points)

        if level is None:
            raise CommandFail('An error occured fetching configuration for this index')

        user = event.guild.members.get(user.id)

        level = OrderedDict(sorted(level.items(), reverse=True))

        previous_roles = []
        for l, r in level.items():
            if current_points - points >= l:
                previous_roles.append(r)

            if current_points > l and current_points - points <= l:
                # take role away
                self.call(
                    'ModLogPlugin.create_debounce',
                    event,
                    ['GuildMemberUpdate'],
                    role_id=r,
                )

                user.remove_role(r)

                self.call(
                    'ModLogPlugin.log_action_ext',
                    Actions.MEMBER_ROLE_REMOVE,
                    event.guild.id,
                    member=user,
                    role=event.guild.roles.get(r),
                    actor=unicode(event.author),
                    reason='AutoLevelPlugin - {} points taken by {}'.format(points, event.author.username),
                )

        if keep:
            for r in previous_roles:
                if r in user.roles:
                    continue

                # add the role if they didn't have it for some reason
                self.call(
                    'ModLogPlugin.create_debounce',
                    event,
                    ['GuildMemberUpdate'],
                    role_id=r,
                )

                user.add_role(r)
        else:
            for r in previous_roles:
                if r in user.roles:
                    self.call(
                        'ModLogPlugin.create_debounce',
                        event,
                        ['GuildMemberUpdate'],
                        role_id=r,
                    )

                    user.remove_role(r)
            try:
                self.call(
                    'ModLogPlugin.create_debounce',
                    event,
                    ['GuildMemberUpdate'],
                    role_id=previous_roles[-1],
                )

                user.add_role(previous_roles[-1])
            except:
                pass

        raise CommandSuccess('Successfully removed `{}` points from user'.format(points))

    @Plugin.command('import', '<itype:str> <guild:snowflake> [ind:str...]', group='alevel', level=-1)
    def alevel_import(self, event, itype=None, guild=None, ind='0:0'):
        if guild not in self.state.guilds:
            raise CommandFail('This guild does not exist')

        if itype.lower() == 'mee6':
            base_url = 'https://mee6.xyz/api/plugins/levels/leaderboard/{}?limit=900&page='
            guild_url = base_url.format(guild)

            s = requests.Session()

            players = {}
            c = 0

            msg = event.msg.reply('Fetched 0 users')

            while True:
                if c > 100:
                    break

                try:
                    r = s.get('{}{}'.format(guild_url, c))
                    r.raise_for_status()
                except:
                    msg.delete()
                    raise CommandFail('An error occured fetching data for guild `{}`'.format(guild))

                if len(r.json()['players']) == 0:
                    msg.edit('Fetched {} users in total'.format(len(players))).after(5).delete()
                    break

                for i in r.json()['players']:
                    players[i['id']] = i['xp']

                msg.edit('Fetched {} users'.format(len(players)))

                c +=  1
                gevent.sleep(2)
        elif itype.lower() == 'tatsumaki':
            if TATSUMAKI_API_KEY == 'xx':
                raise CommandFail('An invalid tatsumaki api key has been supplied or has not been set')

            base_url = 'https://api.tatsumaki.xyz/guilds/{}/leaderboard?limit=-1'
            guild_url = base_url.format(guild)

            s = requests.Session()
            s.headers['authorization'] = TATSUMAKI_API_KEY

            players = {}
            c = 0

            msg = event.msg.reply('Fetched 0 users')

            try:
                r = s.get(guild_url)
                r.raise_for_status()
            except:
                msg.delete()
                raise CommandFail('An error occured fetching data for guild `{}`'.format(guild))

            # tatsumaki includes silly None values in its json for no reason....
            try:
                for i in r.json():
                    players[i['user_id']] = i['score']
            except:
                pass

            msg.edit('Fetched {} users in total'.format(len(players)))
        else:
            raise CommandFail('This import type is not implemented yet')

        msg = event.msg.reply('Do you wish to import {} users from {} into index `{}` in guild_id `{}`?\nThis can not be undone..'.format(len(players), itype, ind, guild))
        msg.chain(False).\
            add_reaction(GREEN_TICK_EMOJI).\
            add_reaction(RED_TICK_EMOJI)

        try:
            mra_event = self.wait_for_event(
                'MessageReactionAdd',
                message_id=msg.id,
                conditional=lambda e: (
                    e.emoji.id in (GREEN_TICK_EMOJI_ID, RED_TICK_EMOJI_ID) and
                    e.user_id == event.author.id
                )).get(timeout=60)
        except gevent.Timeout:
            return
        finally:
            msg.delete()

        if mra_event.emoji.id != GREEN_TICK_EMOJI_ID:
            return

        msg = event.msg.reply('Importing 0/{} - 0 errors'.format(len(players)))

        c = 0
        e = 0
        for k,v in players.iteritems():
            try:
                AutoLevel.from_import(guild, k, v, ind)
            except:
                e += 1
            finally:
                c += 1
                if c % 100 == 0 or (c + e == len(players)):
                    if (c + e == len(players)):
                        gevent.sleep(2)
                        msg.edit('Import complete with {} errors'.format(e))
                    msg.edit('Importing {}/{} - {} errors'.format(c, len(players), e))


text:
<?php

if (!defined('__IANA_HANDLER__'))
    define('__IANA_HANDLER__', 1);

require_once('whois.parser.php');

class iana_handler {

    function parse($data_str, $query) {
        $items = array(
            'admin' => 'contact:      administrative',
            'tech' => 'contact:      technical',
            'domain.nserver.' => 'nserver:',
            'domain.created' => 'created:',
            'domain.changed' => 'changed:',
            'domain.source' => 'source:',
            'domain.name' => 'domain:',
            'disclaimer.' => '% '
        );

        return easy_parser($data_str, $items, 'Ymd', array(), false, false, 'owner');
    }

}


text:
"""
test_sqlite_browser
----------------------------------

Tests for `sqlite_browser` module.
"""

import unittest

from sqlite_browser import sqlite_browser

class TestSqlite_browser(unittest.TestCase):

    def setUp(self):
        pass

    def test_something(self):
        pass

    def tearDown(self):
        pass

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


text:
namespace Serialization
{
    class Iterator
    {
    public:
        virtual char*   Current() = 0;
        virtual bool    MoveNext() = 0;
        virtual void    Reset() = 0;
        virtual ~Iterator() {}
    };

    class Traversable
    {
    public:
        virtual Iterator* GetIterator() = 0;
        virtual ~Traversable() {}
    };
}

#endif // TRAVERSABLE_H


text:
define([ "nifty", "./FooModel", "./FooView", "./util/FooUtil"], function (nifty, Model, View, Util) {
    return nifty.compose({model: Model, view: View, util: Util}, {
        init: function () {
            var controller = this;

            controller.view.listen("clickedFoo", function (arg1, arg2) {
                controller.arg1 = arg1;
                controller.arg2 = arg2;
                controller.model.getData(controller.arg1, controller.arg2);
            });
            controller.model.listen("gotData", function (arg1, arg2, data) {
                if (controller.arg1 == arg1 && controller.arg2 == arg2) {
                    controller.view.displayData(data);
                }
            });
            controller.model.listen("errorGettingData", function (arg1, arg2) {
                if (controller.arg1 == arg1 && controller.arg2 == arg2) {
                    controller.view.displayError();
                }
            });
        },

        start: function () {
            var controller = this;
            controller.today = controller.util.getToday();
            controller.view.bindFoo();
        },

        empty: function () {
            var controller = this;
            controller.view.teardown();
            controller.model.ignore();
        }
    })
});


text:
PhysicsTriangle::PhysicsTriangle(vec3 normal, vec3 a, vec3 b, vec3 c) {
	this->a = a;
	this->b = b;
	this->c = c;
	this->normal = normal;
}

bool PhysicsTriangle::RayIntersects(PhysicsTriangle t, vec3 trianglePosition, const vec3 & startPoint,const vec3 & direction,double * intersectionDistance, vec3 * surfaceNormal) {
	double epsilon = .00001;

	//Dont check back face for collisions
	if (glm::dot(t.normal,direction) > 0)
		return false;

	//Move the triangle to the given position
	t.a += trianglePosition;
	t.b += trianglePosition;
	t.c += trianglePosition;

	vec3 e1 = t.b-t.a;
	vec3 e2 = t.c-t.a;
	vec3 q = glm::cross(direction,e2);
	double ah = glm::dot(e1,q);

	//vec3 is parallel to plane
	if ((ah>-epsilon) && (ah<epsilon))
		return false;

	double f = 1/ah;
	vec3 s = startPoint-t.a;
	double u = f*glm::dot(s,q);

	//Intersection outside of triangle
	if (u < 0)
		return false;

	vec3 r = glm::cross(s,e1);
	double v = f*glm::dot(direction,r);

	//Intersection outside of triangle
	if ((v < 0.0) || ((u+v)>1.0))
		return false;

	*intersectionDistance = f*glm::dot(e2,r);
	//*intersectionPoint = startPoint+direction*t;
	*surfaceNormal = t.normal;

	if (*intersectionDistance < 0)
		return false; //ray went wrong direction

	return true;
}


text:
import logging
import influxdb

try:
    # Test for mypy support (requires Python 3)
    from typing import Mapping, Text
except ImportError:
    pass

class InfluxDBWriter(object):
    DEFAULT_HEADERS = {
        'Content-type': 'application/octet-stream',
        'Accept': 'text/plain'
    }

    def __init__(self,
                 host,
                 port,
                 user,
                 password,
                 dbname,
                 use_ssl=False,
                 verify_ssl=False,
                 timeout=5,
                 use_udp=False,
                 retention_policy=None,
                 time_precision=None):
        """
        Initialize InfluxDB writer
        """
        self.host = host
        self.port = port
        self.user = user
        self.password = password
        self.dbname = dbname
        self.use_ssl = use_ssl
        self.verify_ssl = verify_ssl
        self.timeout = timeout
        self.use_udp = use_udp
        self.retention_policy = retention_policy
        self.time_precision = time_precision

        self.params = {'db': self.dbname}
        self.headers = self.DEFAULT_HEADERS
        if time_precision:
            self.params['precision'] = time_precision
        if retention_policy:
            self.params['rp'] = retention_policy

        logging.info("Connecting to InfluxDB at %s:%s (SSL: %r, UDP: %r)",
                     host, port, use_ssl, use_udp)
        self.client = self.create_client()

    def create_client(self):
        """
        Create an InfluxDB client
        """
        return influxdb.InfluxDBClient(self.host,
                                       self.port,
                                       self.user,
                                       self.password,
                                       self.dbname,
                                       self.use_ssl,
                                       self.verify_ssl,
                                       self.timeout,
                                       self.use_udp,
                                       self.port)

    def create_database(self, dbname):
        # type: (Text) -> bool
        """
        Initialize the given database
        :param dbname:
        """
        self.client.create_database(dbname)

    def write(self, msg, params=None, expected_response_code=204):
        # type: (Text, Mapping[str, str], int) -> bool
        """
        Write messages to InfluxDB database.
        Expects messages in line protocol format.
        See https://influxdb.com/docs/v0.9/write_protocols/line.html
        :param expected_response_code:
        :param params:
        :param msg:
        """
        if not params:
            # Use defaults
            params = self.params

        try:
            logging.debug("Writing message: %s", msg)
            self.client.request(url='write',
                                method='POST',
                                params=params,
                                data="\n".join(msg),
                                expected_response_code=expected_response_code,
                                headers=self.headers
                                )
        except Exception as e:
            logging.warning("Cannot write data points: %s", e)
            return False
        return True


text:
<?php

namespace daisywheel\querybuilder\ast\expr;

use daisywheel\querybuilder\ast\commands\SelectCommand;
use daisywheel\querybuilder\ast\Expr;
use daisywheel\querybuilder\BuildException;

class BasicExpr implements Expr
{
    const TYPE_UNARY = 'UNARY';
    const TYPE_BINARY = 'BINARY';
    const TYPE_EQ = 'EQ';
    const TYPE_LIST = 'LIST';
    const TYPE_RIGHT_HAND = 'RIGHT_HAND';
    const TYPE_BETWEEN = 'BETWEEN';

    /** @var string */
    protected $type;

    /** @var string */
    protected $operator;

    /** @var array<Expr|Expr[]|SelectCommand> */
    protected $operands;

    /** @var string|null */
    protected $extraSql;

    /**
     * @param string $type
     * @param string $operator
     * @param array<Expr|Expr[]|SelectCommand> $operands
     * @param string|null $extraSql
     */
    protected function __construct($type, $operator, $operands, $extraSql = null)
    {
        $this->type = $type;
        $this->operator = $operator;
        $this->operands = $operands;
        $this->extraSql = $extraSql;
    }

    /**
     * @see Expr::buildExpr()
     * @psalm-suppress InvalidArgument
     */
    public function buildExpr()
    {
        switch ($this->type) {
            case self::TYPE_UNARY:
                return "({$this->operator} {$this->operands[0]->buildExpr()})";

            case self::TYPE_RIGHT_HAND:
                return "({$this->operands[0]->buildExpr()} {$this->operator})";

            case self::TYPE_BETWEEN:
                return "({$this->operands[0]->buildExpr()} {$this->operator} {$this->operands[1]->buildExpr()} AND {$this->operands[2]->buildExpr()})";

            case self::TYPE_LIST: {
                if ($this->operands[1] instanceof Expr) {
                    return "({$this->operands[0]->buildExpr()} {$this->operator} {$this->operands[1]->buildExpr()})";
                } elseif (empty($this->operands[1])) {
                    return "({$this->extraSql})";
                }

                return "({$this->operands[0]->buildExpr()} {$this->operator} (" . implode(
                    ', ',
                    array_map(
                        /** @return string */
                        function ($v) {
                            /** @var Expr $v */
                            return $v->buildExpr();
                        },
                        $this->operands[1]
                    )
                ) . '))';
            }
        }

        /** @noinspection PhpUndefinedMethodInspection */
        if ($this->type === self::TYPE_EQ
            && ($this->operands[1] instanceof ValueExpr)
            && $this->operands[1]->isNull()
        ) {
            return "({$this->operands[0]->buildExpr()} {$this->extraSql})";
        }

        return '(' . implode(
            " {$this->operator} ",
            array_map(
                /** @return string */
                function ($v) {
                    /** @var Expr $v */
                    return $v->buildExpr();
                },
                $this->operands
            )
        ) . ')';
    }

    /**
     * @param string $operator
     * @param Expr[] $operands
     *
     * @throws BuildException
     * @return BasicExpr
     */
    public static function createUnary($operator, $operands)
    {
        if (count($operands) !== 1) {
            throw new BuildException('Exactly one operand required');
        }

        return new self(self::TYPE_UNARY, $operator, $operands);
    }

    /**
     * @param string $operator
     * @param Expr[] $operands
     *
     * @throws BuildException
     * @return BasicExpr
     */
    public static function createBinary($operator, $operands)
    {
        if (count($operands) !== 2) {
            throw new BuildException('Exactly two operands required');
        }

        return new self(self::TYPE_BINARY, $operator, $operands);
    }

    /**
     * @param string $operator
     * @param Expr[] $operands
     *
     * @throws BuildException
     * @return BasicExpr
     */
    public static function createMulti($operator, $operands)
    {
        if (count($operands) < 2) {
            throw new BuildException('At least two operands required');
        }

        return new self(self::TYPE_BINARY, $operator, $operands);
    }

    /**
     * @param string $operator
     * @param Expr[] $operands
     * @param string $nullValueSql
     *
     * @throws BuildException
     * @return BasicExpr
     */
    public static function createEq($operator, $operands, $nullValueSql)
    {
        if (count($operands) !== 2) {
            throw new BuildException('Exactly two operands required');
        }

        return new self(self::TYPE_EQ, $operator, $operands, $nullValueSql);
    }

    /**
     * @param string $operator
     * @param array<Expr|Expr[]|SelectCommand> $operands
     * @param string $emptyListValueSql
     *
     * @throws BuildException
     * @return BasicExpr
     */
    public static function createList($operator, $operands, $emptyListValueSql)
    {
        if (count($operands) !== 2) {
            throw new BuildException('Exactly two operands required');
        }

        if (!is_array($operands[1])
            && !($operands[1] instanceof PlaceholderExpr)
            && !($operands[1] instanceof SelectCommand)
        ) {
            throw new BuildException('Right operand must be an array, PlaceholderExpr or SelectCommand');
        }

        return new self(self::TYPE_LIST, $operator, $operands, $emptyListValueSql);
    }

    /**
     * @param string $operator
     * @param Expr[] $operands
     *
     * @throws BuildException
     * @return BasicExpr
     */
    public static function createRightHand($operator, $operands)
    {
        if (count($operands) !== 1) {
            throw new BuildException('Exactly one operand required');
        }

        return new self(self::TYPE_RIGHT_HAND, $operator, $operands);
    }

    /**
     * @param string $operator
     * @param Expr[] $operands
     *
     * @throws BuildException
     * @return BasicExpr
     */
    public static function createBetween($operator, $operands)
    {
        if (count($operands) !== 3) {
            throw new BuildException('Exactly three operands required');
        }

        return new self(self::TYPE_BETWEEN, $operator, $operands);
    }
}


text:
package com.tlcn.util;

import java.util.List;

import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class GenericResponse {
	private String message;
    private String error;

    public GenericResponse(final String message) {
        super();
        this.message = message;
    }

    public GenericResponse(final String message, final String error) {
        super();
        this.message = message;
        this.error = error;
    }

    public GenericResponse(final List<FieldError> fieldErrors, final List<ObjectError> globalErrors) {
        super();
        final ObjectMapper mapper = new ObjectMapper();
        try {
            this.message = mapper.writeValueAsString(fieldErrors);
            this.error = mapper.writeValueAsString(globalErrors);
        } catch (final JsonProcessingException e) {
            this.message = "";
            this.error = "";
        }
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(final String message) {
        this.message = message;
    }

    public String getError() {
        return error;
    }

    public void setError(final String error) {
        this.error = error;
    }
}


text:
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Reactive.Linq;
using System.Text;
using System.Threading.Tasks;
using TestApp.Models;

namespace TestApp.Services
{
  public class ContactsApiClient
  {
    private HttpClient client;

    public ContactsApiClient(HttpClient client)
    {
      this.client = client;
      //client = new HttpClient();
      //client.BaseAddress = new Uri("http://localhost:54669/");
      //client.DefaultRequestHeaders.Accept.Add(
      //    new MediaTypeWithQualityHeaderValue("application/json"));
    }

    public IObservable<ImmutableList<Contact>> GetAllContacts()
    {
      return Observable.FromAsync(async token =>
      {
        var response = await client.GetAsync("api/contacts", token);
        if (response.IsSuccessStatusCode)
        {
          return await response.Content.ReadAsAsync<ImmutableList<Contact>>();
        }
        else
        {
          throw new Exception("something went wrong when getting the contacts");
        }
      });
    }

    public IObservable<Contact> GetContact(int id)
    {
      return Observable.FromAsync(async token =>
      {
        var response = await client.GetAsync($"api/contacts/{id}", token);
        if (response.IsSuccessStatusCode)
        {
          return await response.Content.ReadAsAsync<Contact>();
        }
        else
        {
          throw new Exception($"something went wrong when getting contact with id {id}");
        }
      });
    }

    public IObservable<Contact> PostContact(Contact contact)
    {
      return Observable.FromAsync(async token =>
      {
        var response = await client.PostAsJsonAsync("api/contacts", contact, token);
        if (response.IsSuccessStatusCode)
        {
          return await response.Content.ReadAsAsync<Contact>();
        }
        else
        {
          throw new Exception($"something went wrong when posting contact {contact.FirstName} {contact.LastName}");
        }
      });
    }

    public IObservable<Contact> PutContact(Contact contact)
    {
      return Observable.FromAsync(async token =>
      {
        var response = await client.PutAsJsonAsync($"api/contacts/${contact.Id}", contact, token);
        if (response.IsSuccessStatusCode)
        {
          return await response.Content.ReadAsAsync<Contact>();
        }
        else
        {
          throw new Exception($"something went wrong when updating contact with id {contact.Id}");
        }
      });
    }

    public IObservable<int> DeleteContact(int id)
    {
      return Observable.FromAsync(async token =>
      {
        var response = await client.DeleteAsync($"api/contacts/${id}", token);
        if (response.IsSuccessStatusCode)
        {
          return id;
        }
        else
        {
          throw new Exception($"something went wrong when deleting contact with id {id}");
        }
      });
    }

  }
}


text:
/* vim: set backspace=2 ts=4 softtabstop=4 sw=4 cinoptions=>4 expandtab autoindent smartindent: */
/* xkb-settings-dialog.h
 * Copyright (C) 2008 Alexander Iliev <sasoiliev@mamul.org>
 *
 * Parts of this program comes from the XfKC tool:
 * Copyright (C) 2006 Gauvain Pocentek <gauvainpocentek@gmail.com>
 *
 * A part of this file comes from the gnome keyboard capplet (control-center):
 * Copyright (C) 2003 Sergey V. Oudaltsov <svu@users.sourceforge.net>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2, or (at your option)
 * any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

#ifndef __XKB_SETTINGS_DIALOG_H__
#define __XKB_SETTINGS_DIALOG_H__

void    xfce_xkb_configure      (XfcePanelPlugin *plugin,
                                 t_xkb *xkb);

void    xfce_xkb_about          (XfcePanelPlugin *plugin);

#endif


text:
CREATE TABLE [dbo].[prims](
	[UUID] [varchar](255) NOT NULL,
	[RegionUUID] [varchar](255) NULL,
	[ParentID] [int] NULL,
	[CreationDate] [int] NULL,
	[Name] [varchar](255) NULL,
	[SceneGroupID] [varchar](255) NULL,
	[Text] [varchar](255) NULL,
	[Description] [varchar](255) NULL,
	[SitName] [varchar](255) NULL,
	[TouchName] [varchar](255) NULL,
	[ObjectFlags] [int] NULL,
	[CreatorID] [varchar](255) NULL,
	[OwnerID] [varchar](255) NULL,
	[GroupID] [varchar](255) NULL,
	[LastOwnerID] [varchar](255) NULL,
	[OwnerMask] [int] NULL,
	[NextOwnerMask] [int] NULL,
	[GroupMask] [int] NULL,
	[EveryoneMask] [int] NULL,
	[BaseMask] [int] NULL,
	[PositionX] [float] NULL,
	[PositionY] [float] NULL,
	[PositionZ] [float] NULL,
	[GroupPositionX] [float] NULL,
	[GroupPositionY] [float] NULL,
	[GroupPositionZ] [float] NULL,
	[VelocityX] [float] NULL,
	[VelocityY] [float] NULL,
	[VelocityZ] [float] NULL,
	[AngularVelocityX] [float] NULL,
	[AngularVelocityY] [float] NULL,
	[AngularVelocityZ] [float] NULL,
	[AccelerationX] [float] NULL,
	[AccelerationY] [float] NULL,
	[AccelerationZ] [float] NULL,
	[RotationX] [float] NULL,
	[RotationY] [float] NULL,
	[RotationZ] [float] NULL,
	[RotationW] [float] NULL,
	[SitTargetOffsetX] [float] NULL,
	[SitTargetOffsetY] [float] NULL,
	[SitTargetOffsetZ] [float] NULL,
	[SitTargetOrientW] [float] NULL,
	[SitTargetOrientX] [float] NULL,
	[SitTargetOrientY] [float] NULL,
	[SitTargetOrientZ] [float] NULL,
PRIMARY KEY CLUSTERED
(
	[UUID] ASC
)WITH (PAD_INDEX  = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]

CREATE TABLE [dbo].[primshapes](
	[UUID] [varchar](255) NOT NULL,
	[Shape] [int] NULL,
	[ScaleX] [float] NULL,
	[ScaleY] [float] NULL,
	[ScaleZ] [float] NULL,
	[PCode] [int] NULL,
	[PathBegin] [int] NULL,
	[PathEnd] [int] NULL,
	[PathScaleX] [int] NULL,
	[PathScaleY] [int] NULL,
	[PathShearX] [int] NULL,
	[PathShearY] [int] NULL,
	[PathSkew] [int] NULL,
	[PathCurve] [int] NULL,
	[PathRadiusOffset] [int] NULL,
	[PathRevolutions] [int] NULL,
	[PathTaperX] [int] NULL,
	[PathTaperY] [int] NULL,
	[PathTwist] [int] NULL,
	[PathTwistBegin] [int] NULL,
	[ProfileBegin] [int] NULL,
	[ProfileEnd] [int] NULL,
	[ProfileCurve] [int] NULL,
	[ProfileHollow] [int] NULL,
	[State] [int] NULL,
	[Texture] [image] NULL,
	[ExtraParams] [image] NULL,
PRIMARY KEY CLUSTERED
(
	[UUID] ASC
)WITH (PAD_INDEX  = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

CREATE TABLE [dbo].[primitems](
	[itemID] [varchar](255) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
	[primID] [varchar](255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
	[assetID] [varchar](255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
	[parentFolderID] [varchar](255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
	[invType] [int] NULL,
	[assetType] [int] NULL,
	[name] [varchar](255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
	[description] [varchar](255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
	[creationDate] [varchar](255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
	[creatorID] [varchar](255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
	[ownerID] [varchar](255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
	[lastOwnerID] [varchar](255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
	[groupID] [varchar](255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
	[nextPermissions] [int] NULL,
	[currentPermissions] [int] NULL,
	[basePermissions] [int] NULL,
	[everyonePermissions] [int] NULL,
	[groupPermissions] [int] NULL,
PRIMARY KEY CLUSTERED
(
	[itemID] ASC
)WITH (PAD_INDEX  = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]

CREATE TABLE [dbo].[terrain](
	[RegionUUID] [varchar](255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
	[Revision] [int] NULL,
	[Heightfield] [image] NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

CREATE TABLE [dbo].[land](
	[UUID] [varchar](255) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
	[RegionUUID] [varchar](255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
	[LocalLandID] [int] NULL,
	[Bitmap] [image] NULL,
	[Name] [varchar](255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
	[Description] [varchar](255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
	[OwnerUUID] [varchar](255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
	[IsGroupOwned] [int] NULL,
	[Area] [int] NULL,
	[AuctionID] [int] NULL,
	[Category] [int] NULL,
	[ClaimDate] [int] NULL,
	[ClaimPrice] [int] NULL,
	[GroupUUID] [varchar](255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
	[SalePrice] [int] NULL,
	[LandStatus] [int] NULL,
	[LandFlags] [int] NULL,
	[LandingType] [int] NULL,
	[MediaAutoScale] [int] NULL,
	[MediaTextureUUID] [varchar](255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
	[MediaURL] [varchar](255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
	[MusicURL] [varchar](255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
	[PassHours] [float] NULL,
	[PassPrice] [int] NULL,
	[SnapshotUUID] [varchar](255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
	[UserLocationX] [float] NULL,
	[UserLocationY] [float] NULL,
	[UserLocationZ] [float] NULL,
	[UserLookAtX] [float] NULL,
	[UserLookAtY] [float] NULL,
	[UserLookAtZ] [float] NULL,
PRIMARY KEY CLUSTERED
(
	[UUID] ASC
)WITH (PAD_INDEX  = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

CREATE TABLE [dbo].[landaccesslist](
	[LandUUID] [varchar](255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
	[AccessUUID] [varchar](255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
	[Flags] [int] NULL
) ON [PRIMARY]