text:
Module to inject python 2-3 compatible features from python-future

I wanted a way to do the following:
- Make new python source files Py2-3 compatible from the start using python-future
- Consistently import (inject) python-future features into all source files in a package
- Avoid having to do multiple imports at the top of each source file - potentially
leading to mistakes or inconsistencies

Dependencies:
------------
    Uses and requires installation of the excellent 'future' package.
    Install with pip install future

    This module has no other external dependencies. You can place it
    anywhere on your PYTHONPATH

    Does not work with Python2 < 2.6 - importing this module or calling
    inject_compat() should have no effect in such cases

Four capabilities, three variables to set and one method:
--------------------------------------------------------
    Capability                              Variable / Method
    ----------                              --------
    Customize features for source files     ALWAYS_AVOID variable
    Customize features for REPL             ALWAYS_AVOID_REPL variable
    Select features by just importing       AUTOLOAD_ALL variable
    Select features on per-file basis       inject_compat method

    AUTOLOAD_ALL versus calling inject_compat:
        If you want to choose different features for different source
        files, you NEED TO:
            Add following TWO lines to the top of each source file
                from py23compat import inject_compat
                inject_compat()
            You can avoid SOME features across ALL source files by
            adding those features to ALWAYS_AVOID, and add ADDITIONAL
            features to avoid on a per-file basis by adding avoid=[...]
            to the inject_compat() call in each source file

            In this model, you NEED to add TWO lines to each source file,
            though you may not need the avoid=[..] in the call to
            inject_compat in all source files.

        If all your source files are in the SAME STAGE of Python-2-3
        compatibility / migration, you can:
            Disable some features across ALL source files using
            ALWAYS_AVOID
            Set AUTOLOAD_ALL = True
            Load remaining features in each source file by JUST importing
            py23compat using a line like:
                import py23compat     # noqa: F401

            '# noqa: F401' asks PEP8 not to complain about an unused import

            In this model, you CANNOT customize features on a per-file
            basis.

    The features avoided in the REPL are separate (ALWAYS_AVOID_REPL).
    Features are ALWAYS injected into the REPL by JUST importing py23compat.

is_int and is_str methods:
-------------------------
    Some modules (such as simplejson, but I am sure there are more), can
    RETURN objects of type 'unicode' or 'long' in Python2. If you have
    disabled 'unicode' and 'long' in Python2 (e.g. by having an empty
    ALWAYS_AVOID list), then you have no way to check if the returned
    valus is an instance of 'unicode' or 'long' respectively. In addition,
    in such cases, the returned variable will NOT be an instance of
    str | int respectively (although it's BEHAVIOR will be similar to those
    respective types).

    In such cases, you can use the is_str and is_int methods by importing
    them from this module. On Python2 is_int will match int and long and
    is_str will match str and unicode, while on Python3 is_int will match
    only int and is_str will match only str.

    You only need these methods if you would have otherwise used isinstance
    for this purpose.

Python version variables:
------------------------
    PY2-->boolean: Whether running in python2 (any minor version)
    PY3-->boolean: Whether running in python3 (any minor version)
    PYPY-->boolean: Whether running in pypy (any minor version)
    PY_MINOR-->int: Python minor version

Variables, imports and what is injected:
---------------------------------------
    REPL    Variable            import          Effect
    -----------------------------------------------------------------------
    YES     ALWAYS_AVOID_REPL   plain import    Except ALWAYS_AVOID_REPL
                                                is_int and is_str automatic

    YES     ALWAYS_AVOID_REPL   import +        Except ALWAYS_AVOID_REPL
            avoid param         inject_compat   avoid param has no effect
                                                is_int, is_str need import

    Source  ALWAYS_AVOID        plain import    Except ALWAYS_AVOID
                                                is_int, is_str need import

    Source  ALWAYS_AVOID        import +        Except ALWAYS_AVOID AND
            avoid param         inject_compat   except avoid param
                                                is_int, is_str need import
    -----------------------------------------------------------------------

    inject_compat ONLY injects compatibility names into:
        Caller's stack frame
        Top-most stack frame ONLY if running in REPL

    Importing this module ONLY injects compatibility names into:
        Top-most stack frame ONLY if running in REPL
        Into caller's (importer's) stack frame if AUTOLOAD_ALL is set

    When using the REPL, if ANY module IMPORTS py23compat, the
    compatibility names will be injected into the TOP-MOST stack
    frame (repeat: ONLY when using the REPL)

    Note the difference between the CALLER (importer) stack frame and
    the TOP-MOST stack frame.

Usage for NEW python packages starting from scratch:
---------------------------------------------------
    A. Make a COPY of this module (file) for EACH package - it has
       variables at the top that you CAN (and SHOULD) change to reflect
       the stage the package is in  (in terms of Python2-3 compatibility)

    B. For a NEW package started from scratch, I recommend:
        1. Keep ALWAYS_AVOID and ALWAYS_AVOID_REPL EMPTY
        2. Set AUTOLOAD_ALL = True
            Allows injecting compatibility code by JUST importing py23compat
            Still obeys ALWAYS_AVOID and ALWAYS_AVOID_REPL
            if you need them
        3. Write your package using (only) Python3 idioms and constructs.
          It should run unchanged in Python2 (need to pip install future)

Usage for making existing Python2 packages compatible with Python2-3:
--------------------------------------------------------------------

    A. Make a COPY of this module (file) for EACH package - it has
       variables at the top that you CAN (and SHOULD) change to reflect
       the stage the package is in  (in terms of Python2-3 compatibility)

    B. Make a list of all the changed features and obsoleted features
       being used by your package.
            See future_imports for NEW behavior in Python3
            See builtins_imports for CHANGED behavior
            See obsolete_imports for OBSOLETED classes, methods

    E. Use one of the following strategies. Note there are MANY possible
       strategies, and the python-future website has a much more robust
       and complete discussion of migration strategies.

        Feature-by-feature
            1. Start by adding ALL the features your package is using that has
               been changed or obsoleted in Python3 to ALWAYS_AVOID.

            2. If you regularly explore your package interactively using a REPL,
                add JUST the changed features (not the obsoleted features) to
                ALWAYS_AVOID_REPL also.

            3. Go through your package feature-by-feature and once a
                feature has been upgraded across your package, remove it
                from ALWAYS_AVOID and ALWAYS_AVOID_REPL.

            4. During this time, you can keep AUTOLOAD_ALL = True and
               JUST import py23compat at the top of each source file

            5. Once you have emptied ALWAYS_AVOID and ALWAYS_AVOID_REPL,
               your package should run unchanged in Python 2 and 3

        File-by-file
            1. Add two lines at the top of each source file:
                   from py23compat import inject_compat
                   inject_compat(avoid=xyz)
               where xyz is a set of features to disable for that file

            2. In each file, upgrade each disabled feature and then
               remove it from the avoid list

            3. Once the avoid list is empty, you can change the two lines
               at the top to be just:
                   import py23compat

            4. Once all files have been upgraded and have an empty avoid list,
               your package should run unchanged in Python 2 and 3

Known bug: interaction with pydoc on Python2:
--------------------------------------------
If using AUTOLOAD_ALL=True, AND 'unicode' is not in ALWAYS_AVOID,
pydoc2 (pydoc on python2) will fail for this module.
To use pydoc on py23compat with AUTOLOAD_ALL=True, do one of the
following:

  - Use pydoc3 in a python3 virtualenv
  - In a REPL, import py23compat and then do help(py23compat)
  - Call pydoc setting (shell) environment var PY23COMPAT_NO_AUTOLOAD)
  - Alias pydoc to 'PY23COMPAT_NO_AUTOLOAD=yes pydoc'

Note that PY23COMPAT_NO_AUTOLOAD disables effect of AUTOLOAD_ALL in
ALL conditions- not just for pydoc - there is no way to effect special
behavior when being imported by pydoc

More information on python-future and Python2-3 compatibility:
-------------------------------------------------------------
    See the python-future site for more information on writing python
    programs that can run in Python 2.x or 3.x, Python 2-->3 migration
    and the python-future package.

    Python-future Quick Start Guide: http://python-future.org/quickstart.html

    Idioms for writing Python 2-3 compatible code:
        http://python-future.org/compatible_idioms.html

    Importing explicitly:
    http://python-future.org/imports.html#explicit-imports


text:
using DOTP.Database;
using DOTP.RaidManager.Threading;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Threading;

namespace DOTP.RaidManager.Repository
{
    public class RaidStore
    {
        private static List<Raid> _cache;
        private bool _loaded;
        private ReaderWriterLock _lock;

        private static string RAID_SELECT = @"
SELECT [Name], [Expansion], [MaxPlayers], [MinimumLevel], [NumberOfBosses]
FROM [Raid]
";

        public RaidStore()
        {
            _loaded = false;
            _cache = new List<Raid>();

            _lock = new ReaderWriterLock();
        }

        public Raid ReadOneOrDefault(Func<Raid, bool> func)
        {
            EnsureLoaded();

            foreach (var spec in _cache)
            {
                if (func(spec))
                    return spec;
            }

            return default(Raid);
        }

        public List<Raid> ReadAll()
        {
            EnsureLoaded();

            var newList = new List<Raid>();

            foreach (var entry in _cache)
            {
                newList.Add(entry);
            }

            return newList.Count > 0 ? newList : null;
        }

        public List<Raid> ReadAll(Func<Raid, bool> func)
        {
            EnsureLoaded();

            var newList = new List<Raid>();

            foreach (var entry in _cache)
            {
                if (func(entry))
                    newList.Add(entry);
            }

            return newList.Count > 0 ? newList : null;
        }

        private void EnsureLoaded()
        {
            using (new ReaderLock(_lock))
            {
                if (_loaded) return;

                using (new WriterLock(_lock))
                {
                    if (_loaded) return;

                    Connection.ExecuteSql(new Query(RAID_SELECT), delegate(SqlDataReader reader)
                    {
                        while (reader.Read())
                        {
                            if (null != _cache.Find(s => reader[0].ToString() == s.Name))
                                return;

                            var newRaid = new Raid()
                            {
                                Name = reader[0].ToString(),
                                Expansion = reader[1].ToString(),
                                MaxPlayers = (int)reader[2],
                                MinimumLevel = (int)reader[3],
                                NumberOfBosses = (int)reader[4]
                            };

                            _cache.Add(newRaid);
                        }
                    });

                    _loaded = true;
                }
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
// Copyright 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////

package com.google.crypto.tink.apps.paymentmethodtoken;

import static java.nio.charset.StandardCharsets.UTF_8;

import com.google.crypto.tink.HybridEncrypt;
import com.google.crypto.tink.PublicKeySign;
import com.google.crypto.tink.apps.paymentmethodtoken.PaymentMethodTokenConstants.ProtocolVersionConfig;
import com.google.crypto.tink.subtle.Base64;
import com.google.crypto.tink.subtle.EcdsaSignJce;
import com.google.crypto.tink.subtle.EllipticCurves.EcdsaEncoding;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonParser;
import com.google.gson.internal.Streams;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.io.StringWriter;
import java.security.GeneralSecurityException;
import java.security.interfaces.ECPrivateKey;
import java.security.interfaces.ECPublicKey;

/**
 * An implementation of the sender side of Google Payment Method
 * Token.
 *
 *
Warning

 *
 *
This implementation supports only versions {@code ECv1} and {@code ECv2}.
 *
 *
Usage

 *
 *
{@code
 * PaymentMethodTokenSender sender = new PaymentMethodTokenSender.Builder()
 *    .senderId(senderId)
 *    .senderSigningKey(senderPrivateKey)
 *    .recipientId(recipientId)
 *    .recipientPublicKey(recipientPublicKey)
 *    .build();
 * String plaintext = "blah";
 * String ciphertext = sender.seal(plaintext);
 * }

 *
 * @see Google Payment
 *     Method Token standard
 * @since 1.0.0
 */
public final class PaymentMethodTokenSender {
  private final String protocolVersion;
  private final ProtocolVersionConfig protocolVersionConfig;
  private final PublicKeySign signer;
  private final String senderIntermediateCert;
  private final String senderId;
  private final String recipientId;

  private HybridEncrypt hybridEncrypter;

  PaymentMethodTokenSender(Builder builder) throws GeneralSecurityException {
    switch (builder.protocolVersion) {
      case PaymentMethodTokenConstants.PROTOCOL_VERSION_EC_V1:
        validateV1(builder);
        break;
      case PaymentMethodTokenConstants.PROTOCOL_VERSION_EC_V2:
        validateV2(builder);
        break;
      case PaymentMethodTokenConstants.PROTOCOL_VERSION_EC_V2_SIGNING_ONLY:
        validateV2SigningOnly(builder);
        break;
      default:
        throw new IllegalArgumentException("invalid version: " + builder.protocolVersion);
    }

    this.protocolVersion = builder.protocolVersion;
    this.protocolVersionConfig = ProtocolVersionConfig.forProtocolVersion(protocolVersion);
    this.signer =
        new EcdsaSignJce(
            builder.senderIntermediateSigningKey != null
                ? builder.senderIntermediateSigningKey
                : builder.senderSigningKey,
            PaymentMethodTokenConstants.ECDSA_HASH_SHA256,
            EcdsaEncoding.DER);
    this.senderId = builder.senderId;
    if (protocolVersionConfig.isEncryptionRequired) {
      this.hybridEncrypter =
          new PaymentMethodTokenHybridEncrypt(builder.recipientPublicKey, protocolVersionConfig);
    }
    if (builder.recipientId == null) {
      throw new IllegalArgumentException("must set recipient Id using Builder.recipientId");
    }
    this.recipientId = builder.recipientId;
    this.senderIntermediateCert = builder.senderIntermediateCert;
  }

  /**
   * Builder for {@link PaymentMethodTokenSender}.
   *
   * @since 1.0.0
   */
  public static class Builder {
    private String protocolVersion = PaymentMethodTokenConstants.PROTOCOL_VERSION_EC_V1;
    private String senderId = PaymentMethodTokenConstants.GOOGLE_SENDER_ID;
    private String recipientId = null;
    private ECPrivateKey senderSigningKey = null;
    private ECPrivateKey senderIntermediateSigningKey = null;
    private String senderIntermediateCert = null;
    private ECPublicKey recipientPublicKey = null;

    public Builder() {}

    /** Sets the protocolVersion. */
    @CanIgnoreReturnValue
    public Builder protocolVersion(String val) {
      protocolVersion = val;
      return this;
    }

    /** Sets the sender Id. */
    @CanIgnoreReturnValue
    public Builder senderId(String val) {
      senderId = val;
      return this;
    }

    /** Sets the recipient Id. */
    @CanIgnoreReturnValue
    public Builder recipientId(String val) {
      recipientId = val;
      return this;
    }

    /**
     * Sets the signing key of the sender.
     *
     *
It must be base64 encoded PKCS8 private key.
     */
    @CanIgnoreReturnValue
    public Builder senderSigningKey(String val) throws GeneralSecurityException {
      senderSigningKey = PaymentMethodTokenUtil.pkcs8EcPrivateKey(val);
      return this;
    }

    @CanIgnoreReturnValue
    public Builder senderSigningKey(ECPrivateKey val) throws GeneralSecurityException {
      senderSigningKey = val;
      return this;
    }

    /**
     * Sets the intermediate signing key of the sender.
     *
     *
It must be base64 encoded PKCS8 private key.
     *
     * @since 1.1.0
     */
    public Builder senderIntermediateSigningKey(String val) throws GeneralSecurityException {
      return senderIntermediateSigningKey(PaymentMethodTokenUtil.pkcs8EcPrivateKey(val));
    }

    /**
     * Sets the intermediate signing key of the sender.
     *
     * @since 1.1.0
     */
    @CanIgnoreReturnValue
    public Builder senderIntermediateSigningKey(ECPrivateKey val) throws GeneralSecurityException {
      senderIntermediateSigningKey = val;
      return this;
    }

    /**
     * JSON containing sender intermediate signing key and a signature of it by the sender signing
     * key.
     *
     *
This can be generated by {@link SenderIntermediateCertFactory}.
     *
     * @since 1.1.0
     */
    @CanIgnoreReturnValue
    public Builder senderIntermediateCert(String val) throws GeneralSecurityException {
      this.senderIntermediateCert = val;
      return this;
    }

    /**
     * Sets the encryption public key of the recipient.
     *
     *
The public key is a base64 (no wrapping, padded) version of the key encoded in ASN.1 type
     * SubjectPublicKeyInfo defined in the X.509 standard.
     */
    @CanIgnoreReturnValue
    public Builder recipientPublicKey(String val) throws GeneralSecurityException {
      recipientPublicKey = PaymentMethodTokenUtil.x509EcPublicKey(val);
      return this;
    }

    @CanIgnoreReturnValue
    public Builder recipientPublicKey(ECPublicKey val) throws GeneralSecurityException {
      recipientPublicKey = val;
      return this;
    }

    /**
     * Sets the encryption public key of the recipient.
     *
     *
The public key must be formatted as base64 encoded uncompressed point format. This format
     * is described in more detail in "Public Key Cryptography For The Financial Services Industry:
     * The Elliptic Curve Digital Signature Algorithm (ECDSA)", ANSI X9.62, 1998
     */
    @CanIgnoreReturnValue
    public Builder rawUncompressedRecipientPublicKey(String val) throws GeneralSecurityException {
      recipientPublicKey = PaymentMethodTokenUtil.rawUncompressedEcPublicKey(val);
      return this;
    }

    public PaymentMethodTokenSender build() throws GeneralSecurityException {
      return new PaymentMethodTokenSender(this);
    }
  }

  /** Seals the input message according to the Payment Method Token specification. */
  public String seal(final String message) throws GeneralSecurityException {
    if (protocolVersion.equals(PaymentMethodTokenConstants.PROTOCOL_VERSION_EC_V1)
        || protocolVersion.equals(PaymentMethodTokenConstants.PROTOCOL_VERSION_EC_V2)
        || protocolVersion.equals(
            PaymentMethodTokenConstants.PROTOCOL_VERSION_EC_V2_SIGNING_ONLY)) {
      return sealV1OrV2(message);
    }
    throw new GeneralSecurityException("Unsupported version: " + protocolVersion);
  }

  private String sealV1OrV2(final String message) throws GeneralSecurityException {
    String signedMessage =
        protocolVersionConfig.isEncryptionRequired
            ? new String(
                hybridEncrypter.encrypt(
                    message.getBytes(UTF_8), PaymentMethodTokenConstants.GOOGLE_CONTEXT_INFO_ECV1),
                UTF_8)
            : message;
    return signV1OrV2(signedMessage);
  }

  static String jsonEncodeSignedMessage(
      String message, String protocolVersion, byte[] signature, String senderIntermediateCert)
      throws GeneralSecurityException {
    try {
      JsonObject result = new JsonObject();
      result.addProperty(PaymentMethodTokenConstants.JSON_SIGNATURE_KEY, Base64.encode(signature));
      if (senderIntermediateCert != null) {
        result.add(
            PaymentMethodTokenConstants.JSON_INTERMEDIATE_SIGNING_KEY,
            JsonParser.parseString(senderIntermediateCert).getAsJsonObject());
      }
      result.addProperty(PaymentMethodTokenConstants.JSON_PROTOCOL_VERSION_KEY, protocolVersion);
      result.addProperty(PaymentMethodTokenConstants.JSON_SIGNED_MESSAGE_KEY, message);
      StringWriter stringWriter = new StringWriter();
      JsonWriter jsonWriter = new JsonWriter(stringWriter);
      jsonWriter.setHtmlSafe(true);
      Streams.write(result, jsonWriter);
      return stringWriter.toString();
    } catch (JsonParseException | IllegalStateException | IOException e) {
      throw new GeneralSecurityException("cannot seal; JSON error", e);
    }
  }

  private String signV1OrV2(String message) throws GeneralSecurityException {
    byte[] toSignBytes =
        PaymentMethodTokenUtil.toLengthValue(
            // The order of the parameters matters.
            senderId, recipientId, protocolVersion, message);
    byte[] signature = signer.sign(toSignBytes);
    return jsonEncodeSignedMessage(message, protocolVersion, signature, senderIntermediateCert);
  }

  private static void validateV1(Builder builder) {
    // ECv1 signed payloads directly.
    if (builder.senderSigningKey == null) {
      throw new IllegalArgumentException(
          "must set sender's signing key using Builder.senderSigningKey");
    }
    if (builder.senderIntermediateSigningKey != null) {
      throw new IllegalArgumentException(
          "must not set sender's intermediate signing key using "
              + "Builder.senderIntermediateSigningKey");
    }
    if (builder.senderIntermediateCert != null) {
      throw new IllegalArgumentException(
          "must not set signed sender's intermediate signing key using "
              + "Builder.senderIntermediateCert");
    }
    if (builder.recipientPublicKey == null) {
      throw new IllegalArgumentException(
          "must set recipient's public key using Builder.recipientPublicKey");
    }
  }

  private static void validateV2(Builder builder) {
    validateIntermediateSigningKeys(builder);
    if (builder.recipientPublicKey == null) {
      throw new IllegalArgumentException(
          "must set recipient's public key using Builder.recipientPublicKey");
    }
  }

  private static void validateV2SigningOnly(Builder builder) {
    validateIntermediateSigningKeys(builder);
    if (builder.recipientPublicKey != null) {
      throw new IllegalArgumentException(
          "must not set recipient's public key using Builder.recipientPublicKey");
    }
  }

  private static void validateIntermediateSigningKeys(Builder builder) {
    // ECv2 and newer protocols use an intermediate signing key.
    if (builder.senderSigningKey != null) {
      throw new IllegalArgumentException(
          "must not set sender's signing key using Builder.senderSigningKey");
    }
    if (builder.senderIntermediateSigningKey == null) {
      throw new IllegalArgumentException(
          "must set sender's intermediate signing key using "
              + "Builder.senderIntermediateSigningKey");
    }
    if (builder.senderIntermediateCert == null) {
      throw new IllegalArgumentException(
          "must set signed sender's intermediate signing key using "
              + "Builder.senderIntermediateCert");
    }
  }
}


text:
<!-- Generated by documentation.js. Update this documentation by updating the source code. -->

## booleanEqual

Determine whether two geometries of the same type have identical X,Y coordinate values.
See [http://edndoc.esri.com/arcsde/9.0/general_topics/understand_spatial_relations.htm][1]

**Parameters**

-   `feature1` **([Geometry][2] \| [Feature][3])** GeoJSON input
-   `feature2` **([Geometry][2] \| [Feature][3])** GeoJSON input

**Examples**

```javascript
var pt1 = turf.point([0, 0]);
var pt2 = turf.point([0, 0]);
var pt3 = turf.point([1, 1]);

turf.booleanEqual(pt1, pt2);
//= true
turf.booleanEqual(pt2, pt3);
//= false
```

Returns **[boolean][4]** true if the objects are equal, false otherwise

[1]: http://edndoc.esri.com/arcsde/9.0/general_topics/understand_spatial_relations.htm

[2]: https://tools.ietf.org/html/rfc7946#section-3.1

[3]: https://tools.ietf.org/html/rfc7946#section-3.2

[4]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean

<!-- This file is automatically generated. Please don't edit it directly:
if you find an error, edit the source file (likely index.js), and re-run
./scripts/generate-readmes in the turf project. -->

---

This module is part of the [Turfjs project](http://turfjs.org/), an open source
module collection dedicated to geographic algorithms. It is maintained in the
[Turfjs/turf](https://github.com/Turfjs/turf) repository, where you can create
PRs and issues.

### Installation

Install this module individually:

```sh
$ npm install @turf/boolean-equal
```

Or install the Turf module that includes it as a function:

```sh
$ npm install @turf/turf
```

### Diagrams

![esri-equals](diagrams/esri-equals.gif)


text:
const config = require('../config.json');

exports.run = function (client, message, args) {
    const numArray = args.map(n => parseInt(n));
    const total = numArray.reduce((p, c) => p + c);

    message.channel.send(total).catch(console.error);
};

exports.conf = {
  enabled: true,
  guildOnly: false,
  aliases: [],
  permLevel: 0
};

exports.help = {
  name: 'add',
  description: 'Adds numbers together.',
  usage: `${config.prefix}add <number 1> <number 2>`
};


text:
import gobject
import xpcom
from xpcom.components import interfaces

class ProgressListener(gobject.GObject):
    _com_interfaces_ = interfaces.nsIWebProgressListener

    __gsignals__ = {
        'location-changed': (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE,
                             ([object])),
        'loading-start':    (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE,
                             ([])),
        'loading-stop':     (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE,
                             ([])),
        'loading-progress': (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE,
                             ([float]))
    }

    def __init__(self):
        gobject.GObject.__init__(self)

        self.total_requests = 0
        self.completed_requests = 0

        self._wrapped_self = xpcom.server.WrapObject( \
                self, interfaces.nsIWebProgressListener)
        weak_ref = xpcom.client.WeakReference(self._wrapped_self)

        self._reset_requests_count()

    def setup(self, browser):
        mask = interfaces.nsIWebProgress.NOTIFY_STATE_NETWORK | \
               interfaces.nsIWebProgress.NOTIFY_STATE_REQUEST | \
               interfaces.nsIWebProgress.NOTIFY_LOCATION

        browser.web_progress.addProgressListener(self._wrapped_self, mask)

    def _reset_requests_count(self):
        self.total_requests = 0
        self.completed_requests = 0

    def onLocationChange(self, webProgress, request, location):
        self.emit('location-changed', location)

    def onProgressChange(self, webProgress, request, curSelfProgress,
                         maxSelfProgress, curTotalProgress, maxTotalProgress):
        pass

    def onSecurityChange(self, webProgress, request, state):
        pass

    def onStateChange(self, webProgress, request, stateFlags, status):
        if stateFlags & interfaces.nsIWebProgressListener.STATE_IS_REQUEST:
            if stateFlags & interfaces.nsIWebProgressListener.STATE_START:
                self.total_requests += 1
            elif stateFlags & interfaces.nsIWebProgressListener.STATE_STOP:
                self.completed_requests += 1

        if stateFlags & interfaces.nsIWebProgressListener.STATE_IS_NETWORK:
            if stateFlags & interfaces.nsIWebProgressListener.STATE_START:
                self.emit('loading-start')
                self._reset_requests_count()
            elif stateFlags & interfaces.nsIWebProgressListener.STATE_STOP:
                self.emit('loading-stop')

        if self.total_requests < self.completed_requests:
            self.emit('loading-progress', 1.0)
        elif self.total_requests > 0:
            self.emit('loading-progress', float(self.completed_requests) /
                                          float(self.total_requests))
        else:
            self.emit('loading-progress', 0.0)

    def onStatusChange(self, webProgress, request, status, message):
        pass


text:
/**
 * @author Toru Nagashima <https://github.com/mysticatea>
 */
"use strict";

/**
 * Check whether a given character is an emoji modifier.
 * @param {number} code The character code to check.
 * @returns {boolean} `true` if the character is an emoji modifier.
 */
module.exports = function isEmojiModifier(code) {
    return code >= 0x1F3FB && code <= 0x1F3FF;
};


text:
<?php

namespace NetSuite\Classes;

class TaxDetailSearchBasic extends SearchRecordBasic {
    /**
     * @var \NetSuite\Classes\SearchMultiSelectField
     */
    public $account;
    /**
     * @var \NetSuite\Classes\SearchLongField
     */
    public $lineNumber;
    /**
     * @var \NetSuite\Classes\SearchDoubleField
     */
    public $taxAmount;
    /**
     * @var \NetSuite\Classes\SearchDoubleField
     */
    public $taxBasis;
    /**
     * @var \NetSuite\Classes\SearchMultiSelectField
     */
    public $taxCode;
    /**
     * @var \NetSuite\Classes\SearchDoubleField
     */
    public $taxRate;
    /**
     * @var \NetSuite\Classes\SearchMultiSelectField
     */
    public $taxType;
    /**
     * @var \NetSuite\Classes\SearchMultiSelectField
     */
    public $tranId;
    static $paramtypesmap = array(
        "account" => "SearchMultiSelectField",
        "lineNumber" => "SearchLongField",
        "taxAmount" => "SearchDoubleField",
        "taxBasis" => "SearchDoubleField",
        "taxCode" => "SearchMultiSelectField",
        "taxRate" => "SearchDoubleField",
        "taxType" => "SearchMultiSelectField",
        "tranId" => "SearchMultiSelectField",
    );
}


text:
package test.java.com.inmobi.monetization.ads;

import static org.junit.Assert.*;

import java.util.ArrayList;

import org.junit.Test;

import main.java.com.inmobi.monetization.ads.Banner;
import main.java.com.inmobi.monetization.api.request.ad.Device;
import main.java.com.inmobi.monetization.api.request.ad.Impression;
import main.java.com.inmobi.monetization.api.request.ad.Property;
import main.java.com.inmobi.monetization.api.request.ad.Request;
import main.java.com.inmobi.monetization.api.request.ad.Slot;
import main.java.com.inmobi.monetization.api.response.ad.BannerResponse;

public class BannerTest {

	@Test
	public void test() {
		Banner banner = new Banner();
		Request request = new Request();
		ArrayList<BannerResponse> ads;

		ads = banner.loadRequest(request);
		assertNull(ads);

		banner = new Banner();
		ads = banner.loadRequest(request);
		assertNull(ads);

		ads = banner.loadRequest(request);
		assertNull(ads);

		Property property = null;
		property = new Property("4028cbff3b187e27013b4d4a431d08f2");
		request.setProperty(property);

		//device
		Device device = new Device("87.84.221.50",null);
		request.setDevice(device);

		ads = banner.loadRequest(request);
		assertNull(ads);

		request.setImpression(new Impression(null));
		ads = banner.loadRequest(request);
		assertNull(ads);

		request.getImpression().setSlot(null);
		ads = banner.loadRequest(request);
		assertNull(ads);

		request.getImpression().setSlot(new Slot(15, null));
		ads = banner.loadRequest(request);
		assertEquals(0, ads.size());
	}

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<coverage generated="1523729445559" clover="3.2.0">
  <project timestamp="1523729445560" name="All files">
    <metrics statements="0" coveredstatements="0" conditionals="0" coveredconditionals="0" methods="0" coveredmethods="0" elements="0" coveredelements="0" complexity="0" loc="0" ncloc="0" packages="0" files="0" classes="0">
    </metrics>
  </project>
</coverage>


text:
name "chef-server-cookbooks"

dependency "rsync"

source :path => File.expand_path("files/chef-server-cookbooks", Omnibus.project_root)

build do
  command "mkdir -p #{install_dir}/embedded/cookbooks"
  command "#{install_dir}/embedded/bin/rsync --delete -a ./ #{install_dir}/embedded/cookbooks/"
  block do
    File.open("#{install_dir}/embedded/cookbooks/pre_upgrade_setup.json", "w") do |f|
      f.puts "{\"run_list\": [ \"recipe[#{project.name}::pre_11.1_upgrade_setup]\" ]}"
    end
  end
end


text:
Pageup blog sauce.

### Running locally

```
gem install jeckyll
jeckyll serve --watch
```

### Original template

Clean Blog by Start Bootstrap - Jekyll Version

The official Jekyll version of the Clean Blog theme by [Start Bootstrap](http://startbootstrap.com/).


text:
#ifndef HDRHELPER_H
#define HDRHELPER_H
#include <stdio.h>

namespace NPHDRHelper{

	typedef struct {
		int valid;            /* indicate which fields are valid */
		char programtype[16]; /* listed at beginning of file to identify it
							  * after "#?".  defaults to "RGBE" */
		float gamma;          /* image has already been gamma corrected with
							  * given gamma.  defaults to 1.0 (no correction) */
		float exposure;       /* a value of 1.0 in an image corresponds to
							  * <exposure> watts/steradian/m^2.
							  * defaults to 1.0 */
	} rgbe_header_info;

	/* flags indicating which fields in an rgbe_header_info are valid */
#define RGBE_VALID_PROGRAMTYPE 0x01
#define RGBE_VALID_GAMMA       0x02
#define RGBE_VALID_EXPOSURE    0x04

	/* return codes for rgbe routines */
#define RGBE_RETURN_SUCCESS 0
#define RGBE_RETURN_FAILURE -1

	/* read or write headers */
	/* you may set rgbe_header_info to null if you want to */
	int RGBE_WriteHeader(FILE *fp, int width, int height, rgbe_header_info *info);
	int RGBE_ReadHeader(FILE *fp, int *width, int *height, rgbe_header_info *info);

	/* read or write pixels */
	/* can read or write pixels in chunks of any size including single pixels*/
	int RGBE_WritePixels(FILE *fp, float *data, int numpixels);
	int RGBE_ReadPixels(FILE *fp, float *data, int numpixels);

	/* read or write run length encoded files */
	/* must be called to read or write whole scanlines */
	int RGBE_WritePixels_RLE(FILE *fp, float *data, int scanline_width,
		int num_scanlines);
	int RGBE_ReadPixels_RLE(FILE *fp, float *data, int scanline_width,
		int num_scanlines);
};

#endif


text:
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.

using Avalonia.Data;
using System;
using System.Reflection;

namespace Avalonia.Markup.Data.Plugins
{
    /// <summary>
    /// Validates properties that report errors by throwing exceptions.
    /// </summary>
    public class ExceptionValidationPlugin : IDataValidationPlugin
    {
        /// <inheritdoc/>
        public bool Match(WeakReference reference, string memberName) => true;

        /// <inheritdoc/>
        public IPropertyAccessor Start(WeakReference reference, string name, IPropertyAccessor inner)
        {
            return new Validator(reference, name, inner);
        }

        private class Validator : DataValidatiorBase
        {
            public Validator(WeakReference reference, string name, IPropertyAccessor inner)
                : base(inner)
            {
            }

            public override bool SetValue(object value, BindingPriority priority)
            {
                try
                {
                    return base.SetValue(value, priority);
                }
                catch (TargetInvocationException ex)
                {
                    Observer.OnNext(new BindingNotification(ex.InnerException, BindingErrorType.DataValidationError));
                }
                catch (Exception ex)
                {
                    Observer.OnNext(new BindingNotification(ex, BindingErrorType.DataValidationError));
                }

                return false;
            }
        }
    }
}


text:
.. code-block:: csharp

  // Not currently supported by this SDK

.. code-block:: go

  // Not currently supported by this SDK

.. code-block:: java

  // Not currently supported by this SDK

.. code-block:: javascript

  // Not currently supported by this SDK

.. code-block:: php

  // Not currently supported

.. code-block:: python

  # Create the export task
  task = imgs.export_task("{imageId}", "receivingSwiftContainer")

  # Wait for the task to complete
  pyrax.utils.wait_for_build(task, verbose=True,
        desired=["success", "failure"])

  # The task's `status` attribute will be either "success" or "failure".
  # In the case of a failure, its `message` attribute will explain why.

.. code-block:: ruby

  # Not currently supported by this SDK

.. code-block:: sh

  curl -s -X POST $ENDPOINT/tasks \
    -H "X-Auth-Token: $TOKEN" \
    -d '{
      "type": "export",
      "input": {
        "image_uuid": "{imageId}",
        "receiving_swift_container": "receivingSwiftContainer"
      }
    }' | python -m json.tool


text:
<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateEndNotesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('end_notes', function ($table) {
            $table->increments('id');
            $table->string('feature');
            $table->text('notes')->nullable();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('end_notes');
    }
}


text:
module AddReceiverStubs

  def successful_add_receiver_response
    StubResponse.succeeded <<-XML
      <receiver>
        <receiver_type>test</receiver_type>
        <token>6SzKN5kR5QSa7JvGFwpjka9zkBA</token>
        <hostnames>http://api.example.com/post</hostnames>
        <state>retained</state>
        <created_at>2014-05-21T21:39:08Z</created_at>
        <updated_at>2014-05-21T21:39:08Z</updated_at>
        <credentials>
          <credential>
            <name>app-id</name>
            <value>1234</value>
            <safe>true</safe>
          </credential>
          <credential>
            <name>app-secret</name>
          </credential>
        </credentials>
      </receiver>
    XML
  end

end


text:
class Invoice < ActiveRecord::Base
  belongs_to :contact

  has_many :line_items
end


text:
package ro.nextreports.designer.ui.sqleditor.syntax;

import java.io.CharArrayReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

import javax.swing.event.UndoableEditEvent;
import javax.swing.event.UndoableEditListener;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;
import javax.swing.text.Segment;
import javax.swing.undo.UndoManager;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * @author Decebal Suiu
 */
public class SyntaxDocument extends PlainDocument {

    private static final Log LOG = LogFactory.getLog(SyntaxDocument.class);

    protected Lexer lexer;
    protected List<Token> tokens;
    protected UndoManager undo = new CompoundUndoManager();

    public SyntaxDocument(Lexer lexer) {
        super();
        putProperty(PlainDocument.tabSizeAttribute, 4); // outside ?!
        this.lexer = lexer;

        // Listen for undo and redo events
        addUndoableEditListener(new UndoableEditListener() {

            public void undoableEditHappened(UndoableEditEvent event) {
                if (event.getEdit().isSignificant()) {
                    undo.addEdit(event.getEdit());
                }
            }

        });
    }

    @Override
    public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
        super.insertString(offs, str, a);
        parse();
    }

    @Override
    public void remove(int offs, int len) throws BadLocationException {
        super.remove(offs, len);
        parse();
    }

    @Override
    public void replace(int offset, int length, String text, AttributeSet attrs)
            throws BadLocationException {
        super.replace(offset, length, text, attrs);
        parse();
    }

    /**
     * Find the token at a given position.  May return null if no token is
     * found (whitespace skipped) or if the position is out of range.
     *
     * @param pos
     * @return
     */
    public Token getTokenAt(int pos) {
        if (tokens == null || tokens.isEmpty() || pos > getLength()) {
            return null;
        }

        Token token = null;
        Token tKey = new Token(TokenType.DEFAULT, pos, 1);
        @SuppressWarnings("unchecked")
        int ndx = Collections.binarySearch((List) tokens, tKey);
        if (ndx < 0) {
            // so, start from one before the token where we should be...
            // -1 to get the location, and another -1 to go back..
            ndx = (-ndx - 1 - 1 < 0) ? 0 : (-ndx - 1 - 1);
            Token t = tokens.get(ndx);
            if ((t.start <= pos) && (pos <= (t.start + t.length))) {
                token = t;
            }
        } else {
            token = tokens.get(ndx);
        }

        return token;
    }

    /**
     * Perform an undo action, if possible
     */
    public void doUndo() {
        if (undo.canUndo()) {
            undo.undo();
            parse();
        }
    }

    /**
     * Perform a redo action, if possible.
     */
    public void doRedo() {
        if (undo.canRedo()) {
            undo.redo();
            parse();
        }
    }

    /**
     * This will discard all undoable edits
     */
    public void clearUndos() {
        undo.discardAllEdits();
    }

    /**
     * Return an iterator of tokens between p0 and p1.
     *
     * @param start
     * @param end
     * @return
     */
    protected Iterator<Token> getTokens(int start, int end) {
        return new TokenIterator(start, end);
    }

    /**
     * Parse the entire document and return list of tokens that do not already
     * exist in the tokens list. There may be overlaps, and replacements,
     * which we will cleanup later.
     *
     * @return list of tokens that do not exist in the tokens field
     */
    private void parse() {
        // if we have no lexer, then we must have no tokens...
        if (lexer == null) {
            tokens = null;
            return;
        }

        List<Token> tokens = new ArrayList<Token>(getLength() / 10);
        long time = System.nanoTime();
        int length = getLength();
        try {
            Segment segment = new Segment();
            getText(0, getLength(), segment);
            CharArrayReader reader = new CharArrayReader(segment.array, segment.offset, segment.count);
            lexer.yyreset(reader);
            Token token;
            while ((token = lexer.yylex()) != null) {
                tokens.add(token);
            }
        } catch (BadLocationException e) {
            LOG.error(e.getMessage(), e);
        } catch (IOException e) {
            // This will not be thrown from the Lexer
            LOG.error(e.getMessage(), e);
        } finally {
            // Benchmarks:
            // Parsed 574038 chars in 81 ms, giving 74584 tokens
//                System.out.printf("Parsed %d in %d ms, giving %d tokens",
//                        len, (System.nanoTime() - ts) / 1000000, toks.size());
            if (LOG.isDebugEnabled()) {
                LOG.debug(String.format("Parsed %d in %d ms, giving %d tokens",
                        length, (System.nanoTime() - time) / 1000000, tokens.size()));
            }
            this.tokens = tokens;
        }
    }

    /**
     * This class is used to iterate over tokens between two positions.
     */
    class TokenIterator implements Iterator<Token> {

        int start;
        int end;
        int ndx = 0;

        @SuppressWarnings("unchecked")
        private TokenIterator(int start, int end) {
            this.start = start;
            this.end = end;
            if (tokens != null && !tokens.isEmpty()) {
                Token token = new Token(TokenType.COMMENT, start, end - start);
                ndx = Collections.binarySearch((List) tokens, token);
                // we will probably not find the exact token...
                if (ndx < 0) {
                    // so, start from one before the token where we should be...
                    // -1 to get the location, and another -1 to go back..
                    ndx = (-ndx - 1 - 1 < 0) ? 0 : (-ndx - 1 - 1);
                    Token t = tokens.get(ndx);
                    // if the prev token does not overlap, then advance one
                    if (t.start + t.length <= start) {
                        ndx++;
                    }

                }
            }
        }

        public boolean hasNext() {
            if (tokens == null) {
                return false;
            }
            if (ndx >= tokens.size()) {
                return false;
            }
            Token t = tokens.get(ndx);
            if (t.start >= end) {
                return false;
            }

            return true;
        }

        public Token next() {
            return tokens.get(ndx++);
        }

        public void remove() {
            throw new UnsupportedOperationException("Not supported yet.");
        }

    }

}


text:
"""A simple interactive demo to illustrate the use of IPython's Demo class.

Any python script can be run as a demo, but that does little more than showing
it on-screen, syntax-highlighted in one shot.  If you add a little simple
markup, you can stop at specified intervals and return to the ipython prompt,
resuming execution later.

This is a unicode test, åäö
"""

print('Hello, welcome to an interactive IPython demo.')
print('Executing this block should require confirmation before proceeding,')
print('unless auto_all has been set to true in the demo object')

# The mark below defines a block boundary, which is a point where IPython will
# stop execution and return to the interactive prompt.
# <demo> --- stop ---

x = 1
y = 2

# <demo> --- stop ---

# the mark below makes this block as silent
# <demo> silent

print('This is a silent block, which gets executed but not printed.')

# <demo> --- stop ---
# <demo> auto
print('This is an automatic block.')
print('It is executed without asking for confirmation, but printed.')
z = x+y

print('z=',x)

# <demo> --- stop ---
# This is just another normal block.
print('z is now:', z)

print('bye!')


text:
<?xml version="1.0"?>
<!DOCTYPE report >
<Report fontSize="20" orientation="landscape" pagesAcross="3">
	<Alternate>
		<NoData>
			<Output>
				<Line fontSize="12">
					<literal>NO DATA</literal>
				</Line>
			</Output>
		</NoData>
	</Alternate>
	<ReportHeader>
		<Output>
			<Line/>
			<Line fontSize="12">
				<literal>Test Report FROM THE PART REPORT HEADER</literal>
			</Line>
			<Line fontsize="4"/>
			<HorizontalLine size="4" bgcolor="'white'"/>
			<HorizontalLine size="2" bgcolor="'black'"/>
			<HorizontalLine size="4" bgcolor="'white'"/>
		</Output>
	</ReportHeader>

	<PageHeader>
		<Output>
			<Line fontSize="11">
				<literal>Test Report (Page Header)</literal>
			</Line>
			<HorizontalLine size="4" bgcolor="'white'"/>
		</Output>
	</PageHeader>
	<Breaks>
		<Break name="break0" newpage="no" headernewpage="yes">
			<BreakHeader>
				<Output>
					<Line>
						<literal col="1">Break Header: </literal>
						<field value="group" width="20" align="left" col="1"/>
					</Line>
				</Output>
			</BreakHeader>
			<BreakFields>
				<BreakField value="group"/>
			</BreakFields>
			<BreakFooter>
				<Output>
					<HorizontalLine size="4" bgcolor="'white'"/>
					<HorizontalLine size="2" bgcolor="'black'"/>
					<HorizontalLine size="4" bgcolor="'white'"/>
					<Line>
						<literal col="1">Break FOOTER: </literal>
						<field value="group" width="20" align="left" col="1"/>
					</Line>
					<HorizontalLine size="4" bgcolor="'white'"/>
					<HorizontalLine size="2" bgcolor="'black'"/>
					<HorizontalLine size="4" bgcolor="'white'"/>
				</Output>
			</BreakFooter>
		</Break>
	</Breaks>
	<Detail>
		<FieldHeaders>
			<Output page="1">
				<HorizontalLine size="1" bgcolor="'black'"/>
				<Line bgcolor="'0xe5e5e5'">
					<literal width="20" col="1">First Name (Page 1)</literal>
					<literal width="1"/>
					<literal width="20" col="2">Last Name</literal>
					<literal width="1"/>
					<literal width="20" col="3">Color</literal>
				</Line>
				<HorizontalLine size="1" bgcolor="'black'"/>
				<HorizontalLine size="4" bgcolor="'white'"/>
			</Output>
			<Output page="2">
				<HorizontalLine size="1" bgcolor="'black'"/>
				<Line bgcolor="'0xe5e5e5'">
					<literal width="20" col="1">First Name (Page 2)</literal>
					<literal width="1"/>
					<literal width="20" col="2">Last Name</literal>
				</Line>
				<HorizontalLine size="1" bgcolor="'black'"/>
				<HorizontalLine size="4" bgcolor="'white'"/>
			</Output>
			<Output page="3">
				<HorizontalLine size="1" bgcolor="'black'"/>
				<Line bgcolor="'0xe5e5e5'">
					<literal width="20" col="1">First Name (Page 3)</literal>
				</Line>
				<HorizontalLine size="1" bgcolor="'black'"/>
				<HorizontalLine size="4" bgcolor="'white'"/>
			</Output>
		</FieldHeaders>
		<FieldDetails>
			<Output>
				<Line bgcolor="iif(r.detailcnt%2,'0xe5e5e5','white')" fontSize="20">
					<field value="first_name" width="20" align="left" col="1"/>
					<literal width="1"/>
					<field value="last_name" width="20" align="left" col="2"/>
					<literal width="1"/>
					<field value="color" width="20" align="left" col="3"/>
				</Line>
				<Line  fontSize="20"/>
			</Output>
		</FieldDetails>
	</Detail>

	<PageFooter>
		<Output>
			<Line>
				<literal>XXPage: </literal>
				<field value="r.pageno" width="3" align="right"/>
			</Line>
		</Output>
	</PageFooter>

	<ReportFooter>
	</ReportFooter>
</Report>


text:
<?xml version="1.0" encoding="UTF-8"?>
<project name="ctlogclient" default="all">
  <property file="local.properties"/>
  <property file="build.properties"/>
  <!-- Compiler options -->
  <property name="compiler.debug" value="on"/>
  <property name="compiler.generate.no.warnings" value="off"/>
  <property name="compiler.args" value="-Xlint:all -Xmaxwarns 10000"/>
  <property name="compiler.max.memory" value="128m"/>
  <patternset id="ignored.files">
    <exclude name="**/CVS/**"/>
    <exclude name="**/SCCS/**"/>
    <exclude name="**/RCS/**"/>
    <exclude name="**/rcs/**"/>
    <exclude name="**/.DS_Store/**"/>
    <exclude name="**/.svn/**"/>
    <exclude name="**/.pyc/**"/>
    <exclude name="**/.pyo/**"/>
    <exclude name="**/*.pyc/**"/>
    <exclude name="**/*.pyo/**"/>
    <exclude name="**/.git/**"/>
    <exclude name="**/*.hprof/**"/>
    <exclude name="**/_svn/**"/>
    <exclude name="**/.hg/**"/>
    <exclude name="**/*.lib/**"/>
    <exclude name="**/*~/**"/>
    <exclude name="**/__pycache__/**"/>
    <exclude name="**/.bundle/**"/>
    <exclude name="**/*.rbc/**"/>
  </patternset>
  <patternset id="library.patterns">
    <include name="*.war"/>
    <include name="*.ear"/>
    <include name="*.apk"/>
    <include name="*.zip"/>
    <include name="*.swc"/>
    <include name="*.ane"/>
    <include name="*.egg"/>
    <include name="*.jar"/>
  </patternset>
  <patternset id="compiler.resources">
    <include name="**/?*.properties"/>
    <include name="**/?*.xml"/>
    <include name="**/?*.gif"/>
    <include name="**/?*.png"/>
    <include name="**/?*.jpeg"/>
    <include name="**/?*.jpg"/>
    <include name="**/?*.html"/>
    <include name="**/?*.dtd"/>
    <include name="**/?*.tld"/>
    <include name="**/?*.ftl"/>
  </patternset>

  <!-- Project Libraries -->
  <!-- jars.* are defined in build.properties -->
  <path id="library.commons-codec">
    <pathelement location="${jars.commons-codec}"/>
  </path>
  <path id="library.commons-logging">
    <pathelement location="${jars.commons-logging}"/>
  </path>
  <path id="library.guava">
    <pathelement location="${jars.guava}"/>
  </path>
  <path id="library.hamcrest">
    <pathelement location="${jars.hamcrest}"/>
  </path>
  <path id="library.httpclient">
    <pathelement location="${jars.httpclient}"/>
  </path>
  <path id="library.httpcore">
    <pathelement location="${jars.httpcore}"/>
  </path>
  <path id="library.json-simple">
    <pathelement location="${jars.json-simple}"/>
  </path>
  <path id="library.junit">
    <pathelement location="${jars.junit}"/>
  </path>
  <path id="library.mockito">
    <pathelement location="${jars.mockito}"/>
  </path>
  <path id="library.protobuf">
    <pathelement location="${jars.protobuf}"/>
  </path>
  <path id="library.bouncycastleprovider">
    <pathelement location="${jars.bouncycastleprovider}"/>
  </path>
  <path id="library.bouncycastlepkix">
    <pathelement location="${jars.bouncycastlepkix}"/>
  </path>

  <!-- CT Log Client -->
  <dirname property="ctlogclient.basedir" file="${ant.file}"/>
  <property name="compiler.args.ctlogclient" value="${compiler.args}"/>
  <property name="ctlogclient.build.dir" value="${ctlogclient.basedir}/java/build"/>
  <property name="ctlogclient.output.dir" value="${ctlogclient.build.dir}/out"/>
  <property name="ctlogclient.generated.dir" value="${ctlogclient.build.dir}/generated"/>
  <property name="ctlogclient.testoutput.dir" value="${ctlogclient.build.dir}/test"/>
  <property name="ctlogclient.testlogs.dir" value="${ctlogclient.build.dir}/test_logs"/>

  <path id="ctlogclient.bootclasspath">
    <!-- Paths to be included in compilation bootclasspath -->
  </path>

  <path id="ctlogclient.compilation.classpath">
    <path refid="library.guava"/>
    <path refid="library.json-simple"/>
    <path refid="library.commons-codec"/>
    <path refid="library.httpcore"/>
    <path refid="library.httpclient"/>
    <path refid="library.commons-logging"/>
    <path refid="library.protobuf"/>
    <path refid="library.hamcrest"/>
    <path refid="library.junit"/>
    <path refid="library.mockito"/>
    <path refid="library.bouncycastleprovider"/>
    <path refid="library.bouncycastlepkix"/>
  </path>

  <path id="ctlogclient.test.compilation.classpath">
    <pathelement location="${ctlogclient.output.dir}"/>
    <path refid="library.guava"/>
    <path refid="library.json-simple"/>
    <path refid="library.commons-codec"/>
    <path refid="library.httpcore"/>
    <path refid="library.httpclient"/>
    <path refid="library.commons-logging"/>
    <path refid="library.protobuf"/>
    <path refid="library.hamcrest"/>
    <path refid="library.junit"/>
    <path refid="library.mockito"/>
    <path refid="library.bouncycastleprovider"/>
    <path refid="library.bouncycastlepkix"/>
  </path>

  <path id="ctlogclient.test.runtime.classpath">
    <pathelement location="${ctlogclient.testoutput.dir}"/>
    <pathelement location="${ctlogclient.output.dir}"/>
    <path refid="library.guava"/>
    <path refid="library.json-simple"/>
    <path refid="library.commons-codec"/>
    <path refid="library.httpcore"/>
    <path refid="library.httpclient"/>
    <path refid="library.commons-logging"/>
    <path refid="library.protobuf"/>
    <path refid="library.hamcrest"/>
    <path refid="library.junit"/>
    <path refid="library.mockito"/>
    <path refid="library.bouncycastleprovider"/>
    <path refid="library.bouncycastlepkix"/>
  </path>

  <patternset id="excluded.from.compilation.ctlogclient">
    <patternset refid="ignored.files"/>
  </patternset>

  <path id="ctlogclient.module.sourcepath">
    <dirset dir="${ctlogclient.basedir}/java">
      <include name="src"/>
    </dirset>
    <dirset dir="${ctlogclient.generated.dir}"/>
  </path>

  <path id="ctlogclient.module.test.sourcepath">
    <dirset dir="${ctlogclient.basedir}/java">
      <include name="test"/>
    </dirset>
  </path>

  <target name="compile.ct.proto" description="Compile CT proto">
    <mkdir dir="${ctlogclient.generated.dir}"/>
    <exec executable="${protoc.bin}">
      <arg value="--java_out=${ctlogclient.generated.dir}"/>
      <arg value="java/ct.proto"/>
    </exec>
  </target>

  <target name="compile.ctlogclient" depends="compile.ctlogclient.production,compile.ctlogclient.tests" description="Compile module ctlogclient"/>

  <target name="compile.ctlogclient.production" depends="compile.ct.proto" description="Compile ctlogclient production classes">
    <mkdir dir="${ctlogclient.output.dir}"/>
    <javac destdir="${ctlogclient.output.dir}" includeantruntime="false" debug="${compiler.debug}" nowarn="${compiler.generate.no.warnings}" memorymaximumsize="${compiler.max.memory}" fork="true">
      <compilerarg line="${compiler.args.ctlogclient}"/>
      <bootclasspath refid="ctlogclient.bootclasspath"/>
      <classpath refid="ctlogclient.compilation.classpath"/>
      <src refid="ctlogclient.module.sourcepath"/>
      <patternset refid="excluded.from.compilation.ctlogclient"/>
    </javac>

    <copy todir="${ctlogclient.output.dir}">
      <fileset dir="${ctlogclient.basedir}/java/src">
        <patternset refid="compiler.resources"/>
        <type type="file"/>
      </fileset>
    </copy>
  </target>

  <target name="compile.ctlogclient.tests" depends="compile.ctlogclient.production" description="compile ctlogclient test classes" unless="skip.tests">
    <mkdir dir="${ctlogclient.testoutput.dir}"/>
    <javac destdir="${ctlogclient.testoutput.dir}" includeantruntime="false" debug="${compiler.debug}" nowarn="${compiler.generate.no.warnings}" memorymaximumsize="${compiler.max.memory}" fork="true">
      <compilerarg line="${compiler.args.ctlogclient}"/>
      <bootclasspath refid="ctlogclient.bootclasspath"/>
      <classpath refid="ctlogclient.test.compilation.classpath"/>
      <src refid="ctlogclient.module.test.sourcepath"/>
      <patternset refid="excluded.from.compilation.ctlogclient"/>
    </javac>

    <copy todir="${ctlogclient.testoutput.dir}">
      <fileset dir="${ctlogclient.basedir}/test">
        <patternset refid="compiler.resources"/>
        <type type="file"/>
      </fileset>
    </copy>
  </target>

  <target name="run.ctlogclient.tests" depends="compile.ctlogclient.tests" description="Run ctlogclient tests." unless="skip.tests">
    <mkdir dir="${ctlogclient.testlogs.dir}"/>
    <junit printsummary="on" fork="true" logfailedtests="true" haltonfailure="true">
      <classpath refid="ctlogclient.test.runtime.classpath"/>
      <formatter type="plain"/>
      <batchtest todir="${ctlogclient.testlogs.dir}">
        <fileset dir="${ctlogclient.testoutput.dir}">
          <type type="file"/>
        </fileset>
      </batchtest>
    </junit>
  </target>

  <target name="test" depends="run.ctlogclient.tests"/>

  <target name="create.ctlogclient.jar" depends="compile.ctlogclient.production" description="Build CT Log client jar.">
    <mkdir dir="${ctlogclient.build.dir}/distrib"/>
    <jar destfile="${ctlogclient.build.dir}/distrib/ctlog.jar" basedir="${ctlogclient.output.dir}"/>
  </target>

  <target name="release" depends="create.ctlogclient.jar"/>

  <target name="clean.module.ctlogclient" description="cleanup module">
    <delete dir="${ctlogclient.output.dir}"/>
    <delete dir="${ctlogclient.testoutput.dir}"/>
    <delete dir="${ctlogclient.testlogs.dir}"/>
    <delete dir="${ctlogclient.build.dir}"/>
  </target>

  <target name="init" description="Build initialization">
    <!-- Perform any build initialization in this target -->
  </target>

  <target name="clean" depends="clean.module.ctlogclient" description="cleanup all"/>

  <target name="build" depends="init, clean, compile.ctlogclient" description="build all modules"/>

  <target name="all" depends="build" description="build all"/>
</project>


text:
@import UIKit;
#import "MEVAppDelegate.h"

int main(int argc, char * argv[])
{
    @autoreleasepool {
        return UIApplicationMain(argc, argv, nil, NSStringFromClass([MEVAppDelegate class]));
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:shadowColor="#000"
        android:shadowDx="1"
        android:shadowDy="1"
        android:text="Large Text"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textColor="#FFF"
        android:textSize="40sp"
        android:typeface="monospace" />

</RelativeLayout>


text:
Basic usage

To derive your own SMTP-Server service with DATA processing simply do:

```rb
# Server class
class MySmtpd < MidiSmtpServer::Smtpd

  # get each message after DATA <message> .
  def on_message_data_event(ctx)
    # Output for debug
    logger.debug("[#{ctx[:envelope][:from]}] for recipient(s): [#{ctx[:envelope][:to]}]...")

    # Just decode message once to make sure, that this message ist readable
    mail = Mail.read_from_string(ctx[:message][:data])

    # handle incoming mail, just show the message subject
    logger.debug(mail.subject)
  end

end
```

Operation purposes

As already introduced, there is an endless field of application for SMTP services. Create your own SMTP Server as a mail gateway to clean up routed emails from spam and virus content or process incoming mails by your proper functions. Create your forwarding service to put messages into a service like Slack, Trello, Redmine, Twitter, Facebook, Instagram and others.

This source code shows the example to receive messages via SMTP and store them to RabbitMQ (Message-Queue-Server) for subsequent processings etc.:

```rb
  # get each message after DATA <message> .
  def on_message_data_event(ctx)
    # Just decode message once to make sure, that this message ist readable
    mail = Mail.read_from_string(ctx[:message])

    # Publish to rabbit
    @bunny_exchange.publish(mail.to_s, :headers => { 'x-smtp' => mail.header.to_s }, :routing_key => "to_queue")
  end
```

Working examples

This is a fully functional starter for a SMTP-Server service with DATA processing:

```rb
# frozen_string_literal: true

require 'midi-smtp-server'

# Server class
class MySmtpd < MidiSmtpServer::Smtpd

  # get each message after DATA <message> .
  def on_message_data_event(ctx)
    # Output for debug
    logger.debug("mail received at: [#{ctx[:server][:local_ip]}:#{ctx[:server][:local_port]}] from: [#{ctx[:envelope][:from]}] for recipient(s): [#{ctx[:envelope][:to]}]...")

    # handle incoming mail, just show the message source
    logger.debug(ctx[:message][:data])
  end

end

# Create a new server instance for listening at localhost interfaces 127.0.0.1:2525
# and accepting a maximum of 4 simultaneous connections per default
server = MySmtpd.new

# save flag for Ctrl-C pressed
flag_status_ctrl_c_pressed = false

# try to gracefully shutdown on Ctrl-C
trap('INT') do
  # print an empty line right after ^C
  puts
  # notify flag about Ctrl-C was pressed
  flag_status_ctrl_c_pressed = true
  # signal exit to app
  exit 0
end

# Output for debug
server.logger.info("Starting MySmtpd [#{MidiSmtpServer::VERSION::STRING}|#{MidiSmtpServer::VERSION::DATE}] (Basic usage) ...")

# setup exit code
at_exit do
  # check to shutdown connection
  if server
    # Output for debug
    server.logger.info('Ctrl-C interrupted, exit now...') if flag_status_ctrl_c_pressed
    # info about shutdown
    server.logger.info('Shutdown MySmtpd...')
    # stop all threads and connections gracefully
    server.stop
  end
  # Output for debug
  server.logger.info('MySmtpd down!')
end

# Start the server
server.start

# Run on server forever
server.join
```

!!! Note

    You will find a number of ready to use examples at [GitHub/MidiSmtpServer/Examples](https://github.com/4commerce-technologies-AG/midi-smtp-server/tree/master/examples).


text:
package me.ilbba.blog.model;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import me.ilbba.blog.model.base.BaseTerm;
import me.ilbba.blog.util.TypeEnum;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Generated by JFinal.
 */
@SuppressWarnings("serial")
public class Term extends BaseTerm<Term> {
	public static final Term dao = new Term();

    private Integer postCount;

    public Integer getPostCount() {
        return postCount;
    }

    public void setPostCount(Integer postCount) {
        this.postCount = postCount;
    }

    public List<Term> queryTermList() {
        return super.find("select * from term order by created desc");
    }

    public Term queryTermDetai(Integer termId) {
        return super.findFirst("select * from term where termId = ?", termId);
    }

    /**
	 * 获取所有分类category列表
	 */
	public List<Term> findAllCategory() {
		return super.find("select * from term where type = ? order by sort asc", TypeEnum.TermType.category.getValue());
	}

    /**
     * 所有分类列表下的帖子数
     */
	public List<Term> findAllCategoryWithPostCount() {
	    List<Term> categoryList = this.findAllCategory();

        StringBuffer termIds = new StringBuffer();
        if (categoryList != null && categoryList.size() > 0) {
            for (int i = 0; i < categoryList.size(); i++) {
                termIds.append("\'").append(categoryList.get(i).getTermId()).append("\'");
                if (i < categoryList.size() - 1) {
                    termIds.append(",");
                }
            }
        }

        Map<Integer, Integer> postCountMap = new HashMap<>();
        if (termIds.length() > 0) {
            String sql = "select count(t1.pid) as count, t2.termId from term_relationship t1, term t2 where t1.termId = t2.termId and t2.termId in(" + termIds.toString() + ")" + "group by t2.termId";
            List<Record> list = Db.find(sql);
            for (Record record : list) {
                Integer termId = record.get("termId");
                Integer count = ((Long)record.get("count")).intValue();
                postCountMap.put(termId, count);
            }
        }

        List<Term> categoryListCopy = new ArrayList<>();
        for (Term category : categoryList) {
            Integer termId = category.getTermId();
            Integer postCount = postCountMap.get(termId) == null ? 0 : postCountMap.get(termId);
            category.setPostCount(postCount);
            categoryListCopy.add(category);
        }
        return categoryListCopy;
    }

	/**
	 * 获取 post下的分类和标签
     */
	public List<Term> getTermListByPostId(int postId) {
		String sql = "select t1.* from term t1 left join term_relationship t2 on t1.termId = t2.termId where t2.pid = ?";
		return super.find(sql, postId);
	}

	/**
	 * 获取 post列表的分类
     */
	public Map<Integer, Term> getCategoryMapByPostIds(String postIds) {
		String sql = "select t1.*, t2.pid from term t1 left join term_relationship t2 on t1.termId = t2.termId where t2.pid in (" + postIds + ") and t1.type = ?";
		List<Term> termList = super.find(sql, TypeEnum.TermType.category.getValue());
        Map<Integer, Term> categoryMap = new HashMap<Integer, Term>();
        if (termList != null && termList.size() > 0) {
			for (Term term : termList) {
				Integer pid = term.get("pid");
				categoryMap.put(pid, term);
			}
		}
		return categoryMap;
	}

    /**
     * 添加或更新
     */
	public void addOrUpdateCategory(Integer pid, Integer categoryId) {
	    Term category = super.findById(categoryId);
        if (category == null) {
            throw new RuntimeException("分类不存在!");
        }

        String sql = "select t1.* from term_relationship t1, term t2 where t1.termId = t2.termId and t1.pid = ? and t2.type=?";
        TermRelationship relation = TermRelationship.dao.findFirst(sql, pid, TypeEnum.TermType.category.getValue());
        if (relation == null) {
            relation = new TermRelationship();
            relation.setPid(pid);
            relation.setTermId(categoryId);
            relation.save();
        } else {
            if (relation.getTermId().intValue() != categoryId.intValue()) {
                Db.update("update term_relationship set termId = ? where pid = ? and termId = ?", categoryId, relation.getPid(), relation.getTermId());
            }
        }
    }
}


text:
<!DOCTYPE html>

    <meta http-equiv="refresh" content="0;URL=../../../../libc/constant.PR_SET_MM_START_BRK.html">

Redirecting to ../../../../libc/constant.PR_SET_MM_START_BRK.html...


text:
// QT includes
#include <QDebug>

// CTK includes
#include "ctkFlatProxyModel.h"

// ----------------------------------------------------------------------------
class ctkFlatProxyModelPrivate
{
  Q_DECLARE_PUBLIC(ctkFlatProxyModel);
protected:
  ctkFlatProxyModel* const q_ptr;
public:
  ctkFlatProxyModelPrivate(ctkFlatProxyModel& object);
  void init();
  int indexLevel(const QModelIndex& index)const;
  int levelRowCount(const QModelIndex& index)const;
  int nextLevelRowCount(const QModelIndex& index)const;
  int rowCount(const QModelIndex& sourceIndex, int depth = 0)const;
  QModelIndex sourceParent(const QModelIndex& index)const;
  QModelIndex grandChild(const QModelIndex& parent, int& row, int depth)const;

  int StartFlattenLevel;
  int EndFlattenLevel;
  int HideLevel;
};

// ----------------------------------------------------------------------------
//  Methods ctkFlatProxyModelPrivate

// ----------------------------------------------------------------------------
ctkFlatProxyModelPrivate::ctkFlatProxyModelPrivate(ctkFlatProxyModel &object)
  : q_ptr(&object)
{
  this->StartFlattenLevel = -1;
  this->EndFlattenLevel = -1;
  this->HideLevel = -1;
}

// ----------------------------------------------------------------------------
void ctkFlatProxyModelPrivate::init()
{
}

// ----------------------------------------------------------------------------
int ctkFlatProxyModelPrivate::indexLevel(const QModelIndex& index)const
{
  int level = -1;
  QModelIndex parent = index;
  while (parent.isValid())
    {
    parent = parent.parent();
    ++level;
    }
  return level;
}

// ----------------------------------------------------------------------------
int ctkFlatProxyModelPrivate::levelRowCount(const QModelIndex& sourceIndex)const
{
  Q_Q(const ctkFlatProxyModel);
  if (!sourceIndex.isValid()
      || this->StartFlattenLevel > this->indexLevel(sourceIndex)
      || this->EndFlattenLevel < this->indexLevel(sourceIndex))
    {
    return 0;
    }
  int previousRows = 0;
  for (int row = 0; row != sourceIndex.row() ; ++row)
    {
    previousRows += q->sourceModel()->rowCount(sourceIndex.sibling(row, sourceIndex.column()));
    }
  return previousRows + this->levelRowCount(sourceIndex.parent());
}

// ----------------------------------------------------------------------------
int ctkFlatProxyModelPrivate::nextLevelRowCount(const QModelIndex& sourceIndex)const
{
  Q_Q(const ctkFlatProxyModel);
  if (!sourceIndex.isValid()
      || this->StartFlattenLevel > this->indexLevel(sourceIndex)
      || this->EndFlattenLevel < this->indexLevel(sourceIndex))
    {
    return q->sourceModel()->rowCount(sourceIndex);
    }
  int rowCount = 0;
  QModelIndex sibling = sourceIndex.sibling(0, sourceIndex.column());
  for (int row = 0; sibling.isValid() ; ++row)
    {
    sibling = sourceIndex.sibling(row, sourceIndex.column());
    rowCount += q->sourceModel()->rowCount(sibling);
    }
  return rowCount;
}

// ----------------------------------------------------------------------------
int ctkFlatProxyModelPrivate::rowCount(const QModelIndex& sourceIndex, int depth)const
{
  Q_Q(const ctkFlatProxyModel);
  int rows = 0;
  if (depth < 0)
    {
    rows = 1;
    }
  else
    {
    --depth;
    for (int row = 0; row < q->sourceModel()->rowCount(sourceIndex); ++row)
      {
      QModelIndex child = q->sourceModel()->index(row, 0, sourceIndex);
      rows += this->rowCount(child, depth);
      }
    }
  return rows;
}

// ----------------------------------------------------------------------------
QModelIndex ctkFlatProxyModelPrivate
::sourceParent(const QModelIndex& index)const
{
  Q_Q(const ctkFlatProxyModel);
  QModelIndexList sourceIndexes;
  sourceIndexes << QModelIndex();
  QMap<int, int> rowCountsPerLevel;
  while (!sourceIndexes.isEmpty())
    {
    QModelIndex sourceIndex = sourceIndexes.takeFirst();
    const int rowCount = q->sourceModel()->rowCount(sourceIndex);
    for (int row = 0; row < rowCount; ++row)
      {
      QModelIndex child = q->sourceModel()->index(row, 0, sourceIndex);
      if (child.internalPointer() == index.internalPointer())
        {
        return sourceIndex;
        }
      else
        {
        sourceIndexes << child;
        }
      }
    }
  Q_ASSERT(false);
  return QModelIndex();
}

// ----------------------------------------------------------------------------
QModelIndex ctkFlatProxyModelPrivate
::grandChild(const QModelIndex& parent, int& row, int depth)const
{
  Q_Q(const ctkFlatProxyModel);
  const int rowCount = q->sourceModel()->rowCount(parent);

  if (depth > 0)
    {
    for (int i = 0; i < rowCount; ++i)
      {
      QModelIndex child = q->sourceModel()->index(i, 0, parent);
      QModelIndex found = this->grandChild(child, row, depth - 1);
      if (found.isValid())
        {
        return found;
        }
      }
    }
  else
    {
    if (row < rowCount)
      {
      QModelIndex sourceIndex = q->sourceModel()->index(
        row, 0, parent);
      return sourceIndex;
      }
    else
      {
      row -= rowCount;
      }
    }
  return QModelIndex();
}

// ----------------------------------------------------------------------------
//  Methods ctkFlatProxyModel

// ----------------------------------------------------------------------------
ctkFlatProxyModel::ctkFlatProxyModel(QObject *parentObject)
  : Superclass(parentObject)
  , d_ptr(new ctkFlatProxyModelPrivate(*this))
{
  Q_D(ctkFlatProxyModel);
  d->init();
}

// ----------------------------------------------------------------------------
ctkFlatProxyModel::~ctkFlatProxyModel()
{
}

// ----------------------------------------------------------------------------
int ctkFlatProxyModel::startFlattenLevel() const
{
  Q_D(const ctkFlatProxyModel);
  return d->StartFlattenLevel;
}

// ----------------------------------------------------------------------------
void ctkFlatProxyModel::setStartFlattenLevel(int level)
{
  Q_D(ctkFlatProxyModel);
  d->StartFlattenLevel = level;
  Q_ASSERT( d->StartFlattenLevel <= d->EndFlattenLevel);
}

// ----------------------------------------------------------------------------
int ctkFlatProxyModel::endFlattenLevel() const
{
  Q_D(const ctkFlatProxyModel);
  return d->EndFlattenLevel;
}

// ----------------------------------------------------------------------------
void ctkFlatProxyModel::setEndFlattenLevel(int level)
{
  Q_D(ctkFlatProxyModel);
  d->EndFlattenLevel = level;
  Q_ASSERT( d->EndFlattenLevel >= d->EndFlattenLevel);
}

// ----------------------------------------------------------------------------
int ctkFlatProxyModel::hideLevel()const
{
  Q_D(const ctkFlatProxyModel);
  return d->HideLevel;
}

// ----------------------------------------------------------------------------
void ctkFlatProxyModel::setHideLevel(int level)
{
  Q_D(ctkFlatProxyModel);
  d->HideLevel = level;
}

// ----------------------------------------------------------------------------
QModelIndex ctkFlatProxyModel::mapFromSource( const QModelIndex& sourceIndex ) const
{
  Q_D(const ctkFlatProxyModel);
  if (!sourceIndex.isValid())
    {
    return QModelIndex();
    }
  int level = d->indexLevel(sourceIndex);
  if (d->HideLevel != -1
      && level >= d->HideLevel)
    {
    return QModelIndex();
    }
  if (d->EndFlattenLevel != -1
      && level <= d->EndFlattenLevel)
    {
    return QModelIndex();
    }
  int row = sourceIndex.row();
  if (d->EndFlattenLevel != -1)
    {
    row += d->levelRowCount(sourceIndex.parent());
    }
  return this->createIndex(row, sourceIndex.column(),
                           sourceIndex.internalPointer());
}

// ----------------------------------------------------------------------------
QModelIndex ctkFlatProxyModel::mapToSource( const QModelIndex& proxyIndex ) const
{
  Q_D(const ctkFlatProxyModel);
  if (!proxyIndex.isValid())
    {
    return QModelIndex();
    }
  QModelIndex sourceParent = d->sourceParent(proxyIndex);
  int level = d->indexLevel(sourceParent);
  int levelRowCount = 0;
  if ((d->StartFlattenLevel != -1 || d->EndFlattenLevel != -1) &&
      (d->StartFlattenLevel != -1 || level >= d->StartFlattenLevel) &&
      (d->EndFlattenLevel != -1 || level <= d->EndFlattenLevel))
    {
    levelRowCount = d->levelRowCount(sourceParent);
    }
  QModelIndex sourceIndex = this->sourceModel()->index(
    proxyIndex.row() - levelRowCount, proxyIndex.column(), sourceParent);
  Q_ASSERT(sourceIndex.isValid());
  return sourceIndex;
}

// ----------------------------------------------------------------------------
QModelIndex ctkFlatProxyModel::index(int row, int column, const QModelIndex &parent) const
{
  Q_D(const ctkFlatProxyModel);
  if (row < 0 || column < 0)
    {
    return QModelIndex();
    }

  QModelIndex sourceParent = this->mapToSource(parent); // parent is already mapped at this point
  int sourceRow = row;
  QModelIndex sourceGrandChild = d->grandChild(
    sourceParent, sourceRow, qMax(0, d->EndFlattenLevel - d->indexLevel(sourceParent)));
  return this->createIndex(row, column, sourceGrandChild.internalPointer());
}

// ----------------------------------------------------------------------------
QModelIndex ctkFlatProxyModel::parent(const QModelIndex &child) const
{
  if (!child.isValid())
    {
    return QModelIndex();
    }
  QModelIndex sourceChild = this->mapToSource(child);
  QModelIndex sourceParent = sourceChild.parent();
  QModelIndex proxyParent = this->mapFromSource(sourceParent);
  return proxyParent;
}

// ----------------------------------------------------------------------------
int ctkFlatProxyModel::rowCount(const QModelIndex &parent) const
{
  Q_D(const ctkFlatProxyModel);
  QModelIndex sourceParent = this->mapToSource(parent);
  int sourceParentLevel = d->indexLevel(sourceParent);
  int depth = 0;
  if (sourceParentLevel >= d->StartFlattenLevel &&
      sourceParentLevel <= d->EndFlattenLevel)
    {
    depth = d->EndFlattenLevel - d->StartFlattenLevel;
    }
  return d->rowCount(sourceParent, depth);
}

// ----------------------------------------------------------------------------
int ctkFlatProxyModel::columnCount(const QModelIndex &parent) const
{
  QModelIndex proxyChild = this->index(0, 0, parent);
  if (parent.isValid() && !proxyChild.internalPointer())
    {
    Q_ASSERT(!parent.isValid() || proxyChild.internalPointer());
    }
  QModelIndex sourceChild = this->mapToSource(proxyChild);
  QModelIndex sourceParent = sourceChild.parent();
  return this->sourceModel()->columnCount(sourceParent);
}


text:
package com.github.slamdev.messageswatcher.storage.dropbox;

import com.github.slamdev.messageswatcher.storage.spi.Storage;
import com.github.slamdev.messageswatcher.storage.spi.StorageModule;
import com.google.inject.AbstractModule;
import com.google.inject.multibindings.Multibinder;

public class DropboxModule extends AbstractModule implements StorageModule {

    @Override
    protected void configure() {
        Multibinder<Storage> binder = Multibinder.newSetBinder(binder(), Storage.class);
        binder.addBinding().to(DropboxStorage.class);
    }
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>edu.uw.zookeeper.lite</groupId>
	<artifactId>zklite-proxy</artifactId>
	<packaging>jar</packaging>
	<name>ZooKeeper-Lite Proxy</name>
	<parent>
		<groupId>edu.uw.zookeeper</groupId>
		<artifactId>lite</artifactId>
		<version>1.0.0-SNAPSHOT</version>
	</parent>
	<properties>
		<main.class>edu.uw.zookeeper.proxy.Main</main.class>
		<main.prefix>ZKPROXY_</main.prefix>
		<main.timestamp>${maven.build.timestamp}</main.timestamp>
	</properties>
	<build>
		<resources>
			<resource>
				<directory>src/main/resources</directory>
				<filtering>true</filtering>
			</resource>
		</resources>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-dependency-plugin</artifactId>
				<executions>
					<execution>
						<id>unpack-resources</id>
						<phase>validate</phase>
						<goals>
							<goal>unpack-dependencies</goal>
						</goals>
						<configuration>
							<classifier>sources</classifier>
							<includeArtifactIds>zkcore</includeArtifactIds>
							<includes>main.py,log4j2.xml</includes>
							<outputDirectory>src/main/resources</outputDirectory>
						</configuration>
					</execution>
					<execution>
						<id>copy-dependencies</id>
						<phase>package</phase>
						<goals>
							<goal>copy-dependencies</goal>
						</goals>
						<configuration>
							<outputDirectory>${project.build.directory}/lib</outputDirectory>
							<overWriteReleases>true</overWriteReleases>
							<overWriteSnapshots>true</overWriteSnapshots>
							<overWriteIfNewer>true</overWriteIfNewer>
							<useSubDirectoryPerScope>true</useSubDirectoryPerScope>
						</configuration>
					</execution>
				</executions>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-source-plugin</artifactId>
				<executions>
					<execution>
						<id>jar-sources</id>
						<goals>
							<goal>jar-no-fork</goal>
						</goals>
					</execution>
				</executions>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-jar-plugin</artifactId>
				<executions>
					<execution>
						<id>default-jar</id>
						<goals>
							<goal>jar</goal>
						</goals>
						<configuration>
							<archive>
								<manifest>
									<mainClass>${main.class}</mainClass>
								</manifest>
							</archive>
							<excludes>
								<exclude>main.py</exclude>
								<exclude>log4j2.xml</exclude>
							</excludes>
						</configuration>
					</execution>
				</executions>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-assembly-plugin</artifactId>
				<configuration>
					<descriptors>
						<descriptor>src/main/assembly/release.xml</descriptor>
					</descriptors>
				</configuration>
				<executions>
					<execution>
						<id>make-assembly</id>
						<phase>package</phase>
						<goals>
							<goal>single</goal>
						</goals>
					</execution>
				</executions>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-clean-plugin</artifactId>
				<configuration>
					<filesets>
						<fileset>
							<directory>src/main/resources</directory>
							<includes>
								<include>log4j2.xml</include>
								<include>main.py</include>
							</includes>
							<followSymlinks>false</followSymlinks>
						</fileset>
					</filesets>
				</configuration>
			</plugin>
		</plugins>
	</build>
	<dependencies>
		<dependency>
			<groupId>${project.groupId}</groupId>
			<artifactId>zklite-clients</artifactId>
			<version>${project.version}</version>
		</dependency>
		<dependency>
			<groupId>${project.groupId}</groupId>
			<artifactId>zkserver</artifactId>
			<version>${project.version}</version>
		</dependency>
	</dependencies>
</project>