text:
'use strict';

const RAMStorage = require('../cjs/RAMStorage');
const GUNStorage = require('../cjs/GUNStorage');
const MerkleBTree = require(`../cjs/MerkleBTree`);
const IPFSStorage = require(`../cjs/IPFSStorage`);
const IPFSGatewayStorage = require(`../cjs/IPFSGatewayStorage`);
const IpfsLib = require(`ipfs`);
const ipfs = new IpfsLib();
const Gun = require(`gun`);
const expressApp = require('express')();
let rootHash;
const satoshi = {
  name: `Satoshi Nakamoto`,
  email: `satoshin@gmx.com`,
  website: `bitcoin.org`
};

function runTests(testEntryCount, maxChildren, btree) {
  let hash, treeSize;
  it(`can be saved`, () => {
    return btree.save().then(hash => {
      expect(typeof hash).toBe(`string`);
      expect(hash.length).toBeGreaterThan(0);
    });
  });

  it(`inserts a value and returns a hash`, () => {
    return btree.put(`Satoshi`, satoshi)
      .then(hash => {
        expect(typeof hash).toBe(`string`);
        expect(hash.length).toBeGreaterThan(0);
      });
  });

  it(`returns the inserted value`, () => {
    return btree.get(`Satoshi`)
      .then(res => {
        expect(res).toEqual(satoshi);
      });
  });

  it(`should have size of 2`, () => {
    return btree.size()
      .then(function(size) {
        treeSize = size;
        expect(size).toEqual(2);
        //expect(size).toBeLessThanOrEqual(Math.pow(maxChildren, expectedDepth));
      });
  });

  it(`updates the existing value`, () => {
    return btree.put(`Satoshi`, Object.assign({updated:true}, satoshi))
      .then(hash => {
        expect(typeof hash).toBe(`string`);
      });
  });

  it(`returns the updated value`, () => {
    return btree.get(`Satoshi`)
      .then(res => {
        expect(res.updated).toBe(true);
      });
  });

  it(`should still have size of 2`, () => {
    return btree.size()
      .then(function(size) {
        treeSize = size;
        expect(size).toEqual(2);
        //expect(size).toBeLessThanOrEqual(Math.pow(maxChildren, expectedDepth));
      });
  });

  it(`can store lots of keys`, () => {
    /*
      to Martti: your previous test was sequential.
      Mark rewrote it so it writes in parallel.
      Why? GUN only ACKs after disk confirms saved,
      meaning, 1000 * <async op> = test timeout.
      Doing it in parallel is much faster,
      and GUN can easily handle the RAM test
      of 1000 vs 100 for IPFS.
      After the change to parallel though,
      ALL adapters (RAM, GUN, IPFS) failed
      the "btree size" test, I assume this
      is because you were overcalculating
      the size of the tree - shouldn't
      it be the size of entries?
    */
    return new Promise((resolve, reject) => {
      var j = 0;
      function iterate(i) {
        if (i <= 0) {
          return;
        }
        btree.put(`Satoshi ${i}`, Object.assign({}, satoshi, {n: i}))
        .then(function(hash) {
          rootHash = hash;
          if(++j >= testEntryCount){
            resolve();
            return;
          }
        });
        iterate(i - 1); // make parallel, not sequential
      }
      iterate(testEntryCount);
      // console.log(btree.print());
    });
  });
  /*
  it(`can store lots of keys`, () => {
    function iterate(i) {
      //console.log(i);
      if (i <= 0) {
        return;
      }
      return btree.put(`Satoshi ${i}`, Object.assign({}, satoshi, {n: i}))
        .then(function(hash) {
          rootHash = hash;
          return iterate(i - 1);
        });
    }
    return iterate(testEntryCount);
    // console.log(btree.print());
  });*/

  it(`returns null when the value is not found`, () => {
    return btree.get(`Hal`)
      .then(res => {
        expect(res).toBeNull();
      });
  });

  it(`should return tree size`, () => {
    const leafNodeCount = Math.ceil(testEntryCount / (maxChildren - 1)); // leaf nodes have 1 "zero" child
    //const expectedDepth = Math.ceil(Math.log(testEntryCount) / Math.log(maxChildren));

    // TODO: could make a better approximation of tree size
    return btree.size()
      .then(function(size) {
        treeSize = size;
        expect(size).toBeGreaterThanOrEqual(testEntryCount); // Martti: leafNodeCount makes no sense!
        //expect(size).toBeGreaterThanOrEqual(testEntryCount + leafNodeCount);
        //expect(size).toBeLessThanOrEqual(Math.pow(maxChildren, expectedDepth));
      });
  });

  it(`can return the value of all stored keys`, () => {
    function iterate(i) {
      if (i <= 0) {
        return;
      }
      return btree.get(`Satoshi ${i}`)
        .then(function(satoshiN) {
          expect(satoshiN).toEqual(Object.assign({}, satoshi, {n: i}));
          return iterate(i - 1);
        });
    }
    return iterate(testEntryCount);
  });

  it(`can searchText by key`, () => {
    return btree.searchText(`Satoshi 1`)
      .then(res => {
        expect(res.length).toBeGreaterThan(testEntryCount / 20);
      });
  });

  it(`can searchText with a cursor`, () => {
    return btree.searchText(`Satoshi 1`, undefined, `Satoshi 1`)
      .then(res => {
        expect(res[0].key).toEqual(`Satoshi 10`);
      });
  });

  it(`can limit searchText result count`, () => {
    return btree.searchText(`Satoshi 1`, 2)
      .then(res => {
        expect(res.length).toEqual(2);
      });
  });

  describe(`searchRange`, () => {
    let r;
    it(`can search by range`, () => {
      return btree.searchRange(`Satoshi ${testEntryCount / 3}`, `Satoshi ${testEntryCount / 2}`)
        .then(res => {
          r = res;
          expect(res.length).toBeLessThanOrEqual(testEntryCount / 6 + maxChildren * 2);
          expect(res.length).toBeGreaterThan(1);
        });
    });

    it(`can search by range in reverse order`, () => {
      return btree.searchRange(`Satoshi ${testEntryCount / 3}`, `Satoshi ${testEntryCount / 2}`, undefined, undefined, undefined, true)
        .then(res => {
          expect(res.length).toBeLessThanOrEqual(testEntryCount / 6 + maxChildren * 2);
          expect(res.length).toBeGreaterThan(1);
          res.forEach(function(row, i) {
            expect(row).toEqual(r[r.length - 1 - i]);
          });
        });
    });

    it(`can exclude upper & lower bound`, () => {
      return btree.searchRange(`Satoshi ${testEntryCount / 3}`, `Satoshi ${testEntryCount / 2}`, false, false, false)
        .then(res => {
          expect(res.length).toBeLessThanOrEqual(testEntryCount / 6 + maxChildren * 2 - 1);
          expect(res.length).toBeGreaterThan(1);
        });
    });

    it(`returns entryCount - 2 with lower bound 0 and upper bound entryCount`, () => {
      return btree.searchRange(`Satoshi 1`, `Satoshi ${testEntryCount - 1}`, false, false, false)
        .then(res => {
          expect(res.length).toEqual(testEntryCount - 2);
        });
    });

    it(`can be used without upperBound`, () => {
      return btree.searchRange(`Satoshi 1`, undefined, false, false, false)
        .then(res => {
          expect(res.length).toEqual(testEntryCount - 1);
        });
    });

    it(`can be used without lowerBound`, () => {
      return btree.searchRange(undefined, `Satoshi ${testEntryCount - 1}`, false, false, false)
        .then(res => {
          expect(res.length).toEqual(testEntryCount - 1 + 1);
        });
    });
  });

  it(`can delete entries`, () => {
    return btree.delete(`Satoshi 1`)
      .then(res => {
        expect(typeof res).toEqual(`string`);
        return btree.size();
      })
      .then(size => {
        expect(size).toEqual(treeSize - 1);
      });
  });

  it(`does not return deleted entry`, () => {
    return btree.get(`Satoshi 1`)
      .then(res => {
        expect(res).toBeNull();
      });
  });
}

describe(`merkle-btree`, () => {
  const ipfsTestEntryCount = 100;
  const ipfsMaxChildren = 10;

  describe(`RAMStorage`, () => {
    const testEntryCount = 1000;
    const maxChildren = 10;

    runTests(testEntryCount, maxChildren, new MerkleBTree(new RAMStorage(), maxChildren));

    describe(`fromSortedList`, () => {
      let btree;
      const list = [
        {key: 'Alice', value: 'Cooper', targetHash: null},
        {key: 'Bob', value: 'Marley', targetHash: null},
        {key: 'Charles', value: 'Darwin', targetHash: null},
        {key: 'Dean', value: 'Anderson', targetHash: null},
        {key: 'Enoch', value: 'Thompson', targetHash: null},
        {key: 'Ford', value: 'Harrison', targetHash: null},
        {key: 'George', value: 'Michael', targetHash: null},
        {key: 'Henry', value: 'Lee', targetHash: null},
        {key: 'Ivanka', value: 'Trump', targetHash: null},
        {key: 'James', value: 'Oliver', targetHash: null},
        {key: 'Katy', value: 'Perry', targetHash: null},
        {key: 'Larry', value: 'Page', targetHash: null},
        {key: 'Mariah', value: 'Carey', targetHash: null},
        {key: 'Nick', value: 'Cave', targetHash: null},
        {key: 'Orlando', value: 'Bloom', targetHash: null}
      ];
      it(`can create a tree from an empty list`, () => {
        return MerkleBTree.fromSortedList([], maxChildren, new RAMStorage())
          .then(res => {
            expect(res).toBeInstanceOf(MerkleBTree);
          });
      });

      it(`can create a tree from a sorted list`, () => {
        const storage = new RAMStorage();
        return MerkleBTree.fromSortedList(list.slice(), maxChildren, storage)
          .then(res => {
            expect(res).toBeInstanceOf(MerkleBTree);
            btree = res;
          });
      });

      it(`can get tree items normally`, () => {
        return btree.get(`Ford`)
          .then(res => {
            expect(res).toEqual(`Harrison`);
            return btree.searchText(``);
          })
          .then(res => {
            expect(res.length).toEqual(list.length);
          });
      });

      it(`can be converted back with toSortedList`, () => {
        return btree.toSortedList()
          .then(res => {
            console.log(`res`, res);
            expect(res).toBeInstanceOf(Array);
            expect(res.length).toEqual(list.length);
          });
      });
    });
  });

  /*
  describe(`GUNStorage`, () => {
    const testEntryCount = 1000;
    const maxChildren = 10;
    const gun = Gun();

    runTests(testEntryCount, maxChildren, new MerkleBTree(new GUNStorage(gun), maxChildren));

    describe(`fromSortedList`, () => {
      let btree;
      const list = [
        {key: 'Alice', value: 'Cooper', targetHash: null},
        {key: 'Bob', value: 'Marley', targetHash: null},
        {key: 'Charles', value: 'Darwin', targetHash: null},
        {key: 'Dean', value: 'Anderson', targetHash: null},
        {key: 'Enoch', value: 'Thompson', targetHash: null},
        {key: 'Ford', value: 'Harrison', targetHash: null},
        {key: 'George', value: 'Michael', targetHash: null},
        {key: 'Henry', value: 'Lee', targetHash: null},
        {key: 'Ivanka', value: 'Trump', targetHash: null},
        {key: 'James', value: 'Oliver', targetHash: null},
        {key: 'Katy', value: 'Perry', targetHash: null},
        {key: 'Larry', value: 'Page', targetHash: null},
        {key: 'Mariah', value: 'Carey', targetHash: null},
        {key: 'Nick', value: 'Cave', targetHash: null},
        {key: 'Orlando', value: 'Bloom', targetHash: null}
      ];
      it(`can create a tree from an empty list`, () => {
        return MerkleBTree.fromSortedList([], maxChildren, new GUNStorage(gun))
          .then(res => {
            expect(res).toBeInstanceOf(MerkleBTree);
          });
      });

      it(`can create a tree from a sorted list`, () => {
        const storage = new GUNStorage(gun);
        return MerkleBTree.fromSortedList(list.slice(), maxChildren, storage)
          .then(res => {
            expect(res).toBeInstanceOf(MerkleBTree);
            btree = res;
          });
      });

      it(`can get tree items normally`, () => {
        return btree.get(`Ford`)
          .then(res => {
            expect(res).toEqual(`Harrison`);
            return btree.searchText(``);
          })
          .then(res => {
            expect(res.length).toEqual(list.length);
          });
      });
    });
  });
  */

  describe(`IPFSStorage`, () => {
    const storage = new IPFSStorage(ipfs);

    beforeAll(done => {
      function loadIpfs() {
        ipfs.load(function(err) {
          if (err) { throw err; }
          console.log(`IPFS repo was loaded`);
          done();
        });
      }

      ipfs._repo.version.exists(function(err, exists) {
        if (err) { throw err; }
        if (exists) {
          loadIpfs();
        } else {
          ipfs.init({ emptyRepo: true, bits: 2048 }, function(err) {
            console.log(`IPFS repo was initialized`);
            if (err) { throw err; }
            loadIpfs();
          });
        }
      });
    });

    runTests(ipfsTestEntryCount, ipfsMaxChildren, new MerkleBTree(storage, ipfsMaxChildren));
  });

  describe(`IPFSGatewayStorage`, () => {
    let btree, server;
    const storage = new IPFSGatewayStorage('http://localhost:8080');

    beforeAll(done => {
      // Set up ipfs file gateway
      expressApp.get('/ipfs/:hash', function(req, res) {
        ipfs.files.cat(req.params.hash)
        .then(function(stream) {
          stream.pipe(res);
        })
        .catch(function(e) {
          res.status(404).json("not found");
        });
      });
      server = expressApp.listen(8080, 'localhost');
      return MerkleBTree.getByHash(rootHash, storage).then(res => {
        btree = res;
        done();
      });
    });

    it(`supports also /ipfs/:hash format in get`, () => {
      return MerkleBTree.getByHash(`/ipfs/${rootHash}`, storage).then(res => {
        expect(res).toEqual(btree);
      });
    });

    it(`returns null when the value is not found`, () => {
      return btree.get(`Hal`)
        .then(res => {
          expect(res).toBeNull();
        });
    });

    it(`should return tree size`, () => {
      const leafNodeCount = Math.ceil(ipfsTestEntryCount / (ipfsMaxChildren - 1)); // leaf nodes have 1 "zero" child
      //const expectedDepth = Math.ceil(Math.log(testEntryCount) / Math.log(maxChildren));

      // TODO: could make a better approximation of tree size
      return btree.size()
        .then(function(size) {
          expect(size).toBeGreaterThanOrEqual(ipfsTestEntryCount); // Martti: See other comment.
          //expect(size).toBeGreaterThanOrEqual(ipfsTestEntryCount + leafNodeCount);
          //expect(size).toBeLessThanOrEqual(Math.pow(maxChildren, expectedDepth));
        });
    });

    it(`can return the value of all stored keys`, () => {
      function iterate(i) {
        if (i <= 0) {
          return;
        }
        return btree.get(`Satoshi ${i}`)
          .then(function(satoshiN) {
            expect(satoshiN).toEqual(Object.assign({}, satoshi, {n: i}));
            return iterate(i - 1);
          });
      }
      return iterate(ipfsTestEntryCount);
    });

    afterAll(() => {
      server.close();
    });
  });
});

redpajama_set_name: RedPajamaGithub


text:
Implement the classic method for composing secret messages called a square code.

Given an English text, output the encoded version of that text.

First, the input is normalized: the spaces and punctuation are removed
from the English text and the message is downcased.

Then, the normalized characters are broken into rows.  These rows can be
regarded as forming a rectangle when printed with intervening newlines.

For example, the sentence

> If man was meant to stay on the ground, god would have given us roots.

is normalized to:

> ifmanwasmeanttostayonthegroundgodwouldhavegivenusroots

The plaintext should be organized in to a rectangle.  The size of the
rectangle (`r x c`) should be decided by the length of the message,
such that `c >= r` and `c - r <= 1`, where `c` is the number of columns
and `r` is the number of rows.

Our normalized text is 54 characters long, dictating a rectangle with
`c = 8` and `r = 7`:

```text
ifmanwas
meanttos
tayonthe
groundgo
dwouldha
vegivenu
sroots
```

The coded message is obtained by reading down the columns going left to
right.

The message above is coded as:

```text
imtgdvsfearwermayoogoanouuiontnnlvtwttddesaohghnsseoau
```

Output the encoded text in chunks.  Phrases that fill perfect rectangles
`(r X c)` should be output `c` chunks of `r` length, separated by spaces.
Phrases that do not fill perfect rectangles will have `n` empty spaces.
Those spaces should be distributed evenly, added to the end of the last
`n` chunks.

```text
imtgdvs fearwer mayoogo anouuio ntnnlvt wttddes aohghn  sseoau
```

Notice that were we to stack these, we could visually decode the
cyphertext back in to the original message:

```text
imtgdvs
fearwer
mayoogo
anouuio
ntnnlvt
wttddes
aohghn
sseoau
```

## Setup

There are two different methods of getting set up to run the tests with Objective-C:

- Create an Xcode project with a test target which will run the tests.
- Use the ruby gem `objc` as a test runner utility.

Both are described in more detail here: http://exercism.io/languages/objective-c

### Submitting Exercises

When submitting an exercise, make sure your solution file is in the same directory as the test code.

The submit command will look something like:

```shell
exercism submit <path-to-exercism-workspace>/objective-c/crypto-square/CryptoSquare.m
```

You can find the Exercism workspace by running `exercism debug` and looking for the line beginning
with Workspace.

## Source

J Dalbey's Programming Practice problems [http://users.csc.calpoly.edu/~jdalbey/103/Projects/ProgrammingPractice.html](http://users.csc.calpoly.edu/~jdalbey/103/Projects/ProgrammingPractice.html)

## Submitting Incomplete Solutions
It's possible to submit an incomplete solution so you can see how others have completed the exercise.


text:
<?xml version="1.0" encoding="UTF-8"?>
<package xmlns="http://pear.php.net/dtd/package-2.0" xmlns:tasks="http://pear.php.net/dtd/tasks-1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" packagerversion="1.9.0" version="2.0" xsi:schemaLocation="http://pear.php.net/dtd/tasks-1.0
		http://pear.php.net/dtd/tasks-1.0.xsd
		http://pear.php.net/dtd/package-2.0
		http://pear.php.net/dtd/package-2.0.xsd">
	<name>zipdownload</name>
	<channel>pear.roundcube.net</channel>
	<summary>Download multiple attachments or messages in one zip file</summary>
	<description>Adds an option to download all attachments to a message in one zip file, when a message has multiple attachments. Also allows the download of a selection of messages in one zip file and the download of entire folders.</description>
	<lead>
		<name>Philip Weir</name>
		<user>JohnDoh</user>
		<email>roundcube@tehinterweb.co.uk</email>
		<active>no</active>
	</lead>
	<lead>
		<name>Thomas Bruederli</name>
		<user>bruederli</user>
		<email>roundcube@gmail.com</email>
		<active>yes</active>
	</lead>
	<date>2012-09-20</date>
	<time>19:16:00</time>
	<version>
		<release>2.0</release>
		<api>2.0</api>
	</version>
	<stability>
		<release>stable</release>
		<api>stable</api>
	</stability>
	<license uri="http://www.gnu.org/licenses/gpl.html">GNU GPLv3+</license>
	<notes>Repo only</notes>
	<contents>
		<dir baseinstalldir="/" name="/">
			<file name="zipdownload.php" role="php">
				<tasks:replace from="@name@" to="name" type="package-info"/>
				<tasks:replace from="@package_version@" to="version" type="package-info"/>
			</file>
			<file name="zipdownload.js" role="data">
				<tasks:replace from="@name@" to="name" type="package-info"/>
				<tasks:replace from="@package_version@" to="version" type="package-info"/>
			</file>
			<file name="config.inc.php.dist" role="data"/>
			<file name="CHANGELOG" role="data"/>
			<file name="README" role="data"/>
			<file name="localization/ca_ES.inc" role="data"/>
			<file name="localization/cs_CZ.inc" role="data"/>
			<file name="localization/da_DK.inc" role="data"/>
			<file name="localization/de_CH.inc" role="data"/>
			<file name="localization/de_DE.inc" role="data"/>
			<file name="localization/en_GB.inc" role="data"/>
			<file name="localization/en_US.inc" role="data"/>
			<file name="localization/es_AR.inc" role="data"/>
			<file name="localization/es_ES.inc" role="data"/>
			<file name="localization/et_EE.inc" role="data"/>
			<file name="localization/fr_FR.inc" role="data"/>
			<file name="localization/gl_ES.inc" role="data"/>
			<file name="localization/hu_HU.inc" role="data"/>
			<file name="localization/it_IT.inc" role="data"/>
			<file name="localization/nl_NL.inc" role="data"/>
			<file name="localization/pl_PL.inc" role="data"/>
			<file name="localization/pt_BR.inc" role="data"/>
			<file name="localization/ro_RO.inc" role="data"/>
			<file name="localization/ru_RU.inc" role="data"/>
			<file name="localization/tr_TR.inc" role="data"/>
			<file name="skins/classic/zip.png" role="data"/>
			<file name="skins/classic/zipdownload.css" role="data"/>
			<file name="skins/larry/zipdownload.css" role="data"/>
		</dir>
		<!-- / -->
	</contents>
	<dependencies>
		<required>
			<php>
				<min>5.2.1</min>
			</php>
			<pearinstaller>
				<min>1.7.0</min>
			</pearinstaller>
			<extension>
				<name>zip</name>
				<channel>pecl.php.net</channel>
				<providesextension>zip</providesextension>
			</extension>
		</required>
	</dependencies>
	<phprelease/>
</package>


text:
#pragma once
#include <aws/guardduty/GuardDuty_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/guardduty/model/Resource.h>
#include <aws/guardduty/model/Service.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
  class JsonView;
} // namespace Json
} // namespace Utils
namespace GuardDuty
{
namespace Model
{

  /**
   *
Contains information about the finding, which is generated when abnormal or
   * suspicious activity is detected.

See Also:
   AWS
   * API Reference

   */
  class AWS_GUARDDUTY_API Finding
  {
  public:
    Finding();
    Finding(Aws::Utils::Json::JsonView jsonValue);
    Finding& operator=(Aws::Utils::Json::JsonView jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    /**
     *
The ID of the account in which the finding was generated.

     */
    inline const Aws::String& GetAccountId() const{ return m_accountId; }

    /**
     *
The ID of the account in which the finding was generated.

     */
    inline bool AccountIdHasBeenSet() const { return m_accountIdHasBeenSet; }

    /**
     *
The ID of the account in which the finding was generated.

     */
    inline void SetAccountId(const Aws::String& value) { m_accountIdHasBeenSet = true; m_accountId = value; }

    /**
     *
The ID of the account in which the finding was generated.

     */
    inline void SetAccountId(Aws::String&& value) { m_accountIdHasBeenSet = true; m_accountId = std::move(value); }

    /**
     *
The ID of the account in which the finding was generated.

     */
    inline void SetAccountId(const char* value) { m_accountIdHasBeenSet = true; m_accountId.assign(value); }

    /**
     *
The ID of the account in which the finding was generated.

     */
    inline Finding& WithAccountId(const Aws::String& value) { SetAccountId(value); return *this;}

    /**
     *
The ID of the account in which the finding was generated.

     */
    inline Finding& WithAccountId(Aws::String&& value) { SetAccountId(std::move(value)); return *this;}

    /**
     *
The ID of the account in which the finding was generated.

     */
    inline Finding& WithAccountId(const char* value) { SetAccountId(value); return *this;}

    /**
     *
The ARN of the finding.

     */
    inline const Aws::String& GetArn() const{ return m_arn; }

    /**
     *
The ARN of the finding.

     */
    inline bool ArnHasBeenSet() const { return m_arnHasBeenSet; }

    /**
     *
The ARN of the finding.

     */
    inline void SetArn(const Aws::String& value) { m_arnHasBeenSet = true; m_arn = value; }

    /**
     *
The ARN of the finding.

     */
    inline void SetArn(Aws::String&& value) { m_arnHasBeenSet = true; m_arn = std::move(value); }

    /**
     *
The ARN of the finding.

     */
    inline void SetArn(const char* value) { m_arnHasBeenSet = true; m_arn.assign(value); }

    /**
     *
The ARN of the finding.

     */
    inline Finding& WithArn(const Aws::String& value) { SetArn(value); return *this;}

    /**
     *
The ARN of the finding.

     */
    inline Finding& WithArn(Aws::String&& value) { SetArn(std::move(value)); return *this;}

    /**
     *
The ARN of the finding.

     */
    inline Finding& WithArn(const char* value) { SetArn(value); return *this;}

    /**
     *
The confidence score for the finding.

     */
    inline double GetConfidence() const{ return m_confidence; }

    /**
     *
The confidence score for the finding.

     */
    inline bool ConfidenceHasBeenSet() const { return m_confidenceHasBeenSet; }

    /**
     *
The confidence score for the finding.

     */
    inline void SetConfidence(double value) { m_confidenceHasBeenSet = true; m_confidence = value; }

    /**
     *
The confidence score for the finding.

     */
    inline Finding& WithConfidence(double value) { SetConfidence(value); return *this;}

    /**
     *
The time and date when the finding was created.

     */
    inline const Aws::String& GetCreatedAt() const{ return m_createdAt; }

    /**
     *
The time and date when the finding was created.

     */
    inline bool CreatedAtHasBeenSet() const { return m_createdAtHasBeenSet; }

    /**
     *
The time and date when the finding was created.

     */
    inline void SetCreatedAt(const Aws::String& value) { m_createdAtHasBeenSet = true; m_createdAt = value; }

    /**
     *
The time and date when the finding was created.

     */
    inline void SetCreatedAt(Aws::String&& value) { m_createdAtHasBeenSet = true; m_createdAt = std::move(value); }

    /**
     *
The time and date when the finding was created.

     */
    inline void SetCreatedAt(const char* value) { m_createdAtHasBeenSet = true; m_createdAt.assign(value); }

    /**
     *
The time and date when the finding was created.

     */
    inline Finding& WithCreatedAt(const Aws::String& value) { SetCreatedAt(value); return *this;}

    /**
     *
The time and date when the finding was created.

     */
    inline Finding& WithCreatedAt(Aws::String&& value) { SetCreatedAt(std::move(value)); return *this;}

    /**
     *
The time and date when the finding was created.

     */
    inline Finding& WithCreatedAt(const char* value) { SetCreatedAt(value); return *this;}

    /**
     *
The description of the finding.

     */
    inline const Aws::String& GetDescription() const{ return m_description; }

    /**
     *
The description of the finding.

     */
    inline bool DescriptionHasBeenSet() const { return m_descriptionHasBeenSet; }

    /**
     *
The description of the finding.

     */
    inline void SetDescription(const Aws::String& value) { m_descriptionHasBeenSet = true; m_description = value; }

    /**
     *
The description of the finding.

     */
    inline void SetDescription(Aws::String&& value) { m_descriptionHasBeenSet = true; m_description = std::move(value); }

    /**
     *
The description of the finding.

     */
    inline void SetDescription(const char* value) { m_descriptionHasBeenSet = true; m_description.assign(value); }

    /**
     *
The description of the finding.

     */
    inline Finding& WithDescription(const Aws::String& value) { SetDescription(value); return *this;}

    /**
     *
The description of the finding.

     */
    inline Finding& WithDescription(Aws::String&& value) { SetDescription(std::move(value)); return *this;}

    /**
     *
The description of the finding.

     */
    inline Finding& WithDescription(const char* value) { SetDescription(value); return *this;}

    /**
     *
The ID of the finding.

     */
    inline const Aws::String& GetId() const{ return m_id; }

    /**
     *
The ID of the finding.

     */
    inline bool IdHasBeenSet() const { return m_idHasBeenSet; }

    /**
     *
The ID of the finding.

     */
    inline void SetId(const Aws::String& value) { m_idHasBeenSet = true; m_id = value; }

    /**
     *
The ID of the finding.

     */
    inline void SetId(Aws::String&& value) { m_idHasBeenSet = true; m_id = std::move(value); }

    /**
     *
The ID of the finding.

     */
    inline void SetId(const char* value) { m_idHasBeenSet = true; m_id.assign(value); }

    /**
     *
The ID of the finding.

     */
    inline Finding& WithId(const Aws::String& value) { SetId(value); return *this;}

    /**
     *
The ID of the finding.

     */
    inline Finding& WithId(Aws::String&& value) { SetId(std::move(value)); return *this;}

    /**
     *
The ID of the finding.

     */
    inline Finding& WithId(const char* value) { SetId(value); return *this;}

    /**
     *
The partition associated with the finding.

     */
    inline const Aws::String& GetPartition() const{ return m_partition; }

    /**
     *
The partition associated with the finding.

     */
    inline bool PartitionHasBeenSet() const { return m_partitionHasBeenSet; }

    /**
     *
The partition associated with the finding.

     */
    inline void SetPartition(const Aws::String& value) { m_partitionHasBeenSet = true; m_partition = value; }

    /**
     *
The partition associated with the finding.

     */
    inline void SetPartition(Aws::String&& value) { m_partitionHasBeenSet = true; m_partition = std::move(value); }

    /**
     *
The partition associated with the finding.

     */
    inline void SetPartition(const char* value) { m_partitionHasBeenSet = true; m_partition.assign(value); }

    /**
     *
The partition associated with the finding.

     */
    inline Finding& WithPartition(const Aws::String& value) { SetPartition(value); return *this;}

    /**
     *
The partition associated with the finding.

     */
    inline Finding& WithPartition(Aws::String&& value) { SetPartition(std::move(value)); return *this;}

    /**
     *
The partition associated with the finding.

     */
    inline Finding& WithPartition(const char* value) { SetPartition(value); return *this;}

    /**
     *
The Region where the finding was generated.

     */
    inline const Aws::String& GetRegion() const{ return m_region; }

    /**
     *
The Region where the finding was generated.

     */
    inline bool RegionHasBeenSet() const { return m_regionHasBeenSet; }

    /**
     *
The Region where the finding was generated.

     */
    inline void SetRegion(const Aws::String& value) { m_regionHasBeenSet = true; m_region = value; }

    /**
     *
The Region where the finding was generated.

     */
    inline void SetRegion(Aws::String&& value) { m_regionHasBeenSet = true; m_region = std::move(value); }

    /**
     *
The Region where the finding was generated.

     */
    inline void SetRegion(const char* value) { m_regionHasBeenSet = true; m_region.assign(value); }

    /**
     *
The Region where the finding was generated.

     */
    inline Finding& WithRegion(const Aws::String& value) { SetRegion(value); return *this;}

    /**
     *
The Region where the finding was generated.

     */
    inline Finding& WithRegion(Aws::String&& value) { SetRegion(std::move(value)); return *this;}

    /**
     *
The Region where the finding was generated.

     */
    inline Finding& WithRegion(const char* value) { SetRegion(value); return *this;}

    inline const Resource& GetResource() const{ return m_resource; }

    inline bool ResourceHasBeenSet() const { return m_resourceHasBeenSet; }

    inline void SetResource(const Resource& value) { m_resourceHasBeenSet = true; m_resource = value; }

    inline void SetResource(Resource&& value) { m_resourceHasBeenSet = true; m_resource = std::move(value); }

    inline Finding& WithResource(const Resource& value) { SetResource(value); return *this;}

    inline Finding& WithResource(Resource&& value) { SetResource(std::move(value)); return *this;}

    /**
     *
The version of the schema used for the finding.

     */
    inline const Aws::String& GetSchemaVersion() const{ return m_schemaVersion; }

    /**
     *
The version of the schema used for the finding.

     */
    inline bool SchemaVersionHasBeenSet() const { return m_schemaVersionHasBeenSet; }

    /**
     *
The version of the schema used for the finding.

     */
    inline void SetSchemaVersion(const Aws::String& value) { m_schemaVersionHasBeenSet = true; m_schemaVersion = value; }

    /**
     *
The version of the schema used for the finding.

     */
    inline void SetSchemaVersion(Aws::String&& value) { m_schemaVersionHasBeenSet = true; m_schemaVersion = std::move(value); }

    /**
     *
The version of the schema used for the finding.

     */
    inline void SetSchemaVersion(const char* value) { m_schemaVersionHasBeenSet = true; m_schemaVersion.assign(value); }

    /**
     *
The version of the schema used for the finding.

     */
    inline Finding& WithSchemaVersion(const Aws::String& value) { SetSchemaVersion(value); return *this;}

    /**
     *
The version of the schema used for the finding.

     */
    inline Finding& WithSchemaVersion(Aws::String&& value) { SetSchemaVersion(std::move(value)); return *this;}

    /**
     *
The version of the schema used for the finding.

     */
    inline Finding& WithSchemaVersion(const char* value) { SetSchemaVersion(value); return *this;}

    inline const Service& GetService() const{ return m_service; }

    inline bool ServiceHasBeenSet() const { return m_serviceHasBeenSet; }

    inline void SetService(const Service& value) { m_serviceHasBeenSet = true; m_service = value; }

    inline void SetService(Service&& value) { m_serviceHasBeenSet = true; m_service = std::move(value); }

    inline Finding& WithService(const Service& value) { SetService(value); return *this;}

    inline Finding& WithService(Service&& value) { SetService(std::move(value)); return *this;}

    /**
     *
The severity of the finding.

     */
    inline double GetSeverity() const{ return m_severity; }

    /**
     *
The severity of the finding.

     */
    inline bool SeverityHasBeenSet() const { return m_severityHasBeenSet; }

    /**
     *
The severity of the finding.

     */
    inline void SetSeverity(double value) { m_severityHasBeenSet = true; m_severity = value; }

    /**
     *
The severity of the finding.

     */
    inline Finding& WithSeverity(double value) { SetSeverity(value); return *this;}

    /**
     *
The title of the finding.

     */
    inline const Aws::String& GetTitle() const{ return m_title; }

    /**
     *
The title of the finding.

     */
    inline bool TitleHasBeenSet() const { return m_titleHasBeenSet; }

    /**
     *
The title of the finding.

     */
    inline void SetTitle(const Aws::String& value) { m_titleHasBeenSet = true; m_title = value; }

    /**
     *
The title of the finding.

     */
    inline void SetTitle(Aws::String&& value) { m_titleHasBeenSet = true; m_title = std::move(value); }

    /**
     *
The title of the finding.

     */
    inline void SetTitle(const char* value) { m_titleHasBeenSet = true; m_title.assign(value); }

    /**
     *
The title of the finding.

     */
    inline Finding& WithTitle(const Aws::String& value) { SetTitle(value); return *this;}

    /**
     *
The title of the finding.

     */
    inline Finding& WithTitle(Aws::String&& value) { SetTitle(std::move(value)); return *this;}

    /**
     *
The title of the finding.

     */
    inline Finding& WithTitle(const char* value) { SetTitle(value); return *this;}

    /**
     *
The type of finding.

     */
    inline const Aws::String& GetType() const{ return m_type; }

    /**
     *
The type of finding.

     */
    inline bool TypeHasBeenSet() const { return m_typeHasBeenSet; }

    /**
     *
The type of finding.

     */
    inline void SetType(const Aws::String& value) { m_typeHasBeenSet = true; m_type = value; }

    /**
     *
The type of finding.

     */
    inline void SetType(Aws::String&& value) { m_typeHasBeenSet = true; m_type = std::move(value); }

    /**
     *
The type of finding.

     */
    inline void SetType(const char* value) { m_typeHasBeenSet = true; m_type.assign(value); }

    /**
     *
The type of finding.

     */
    inline Finding& WithType(const Aws::String& value) { SetType(value); return *this;}

    /**
     *
The type of finding.

     */
    inline Finding& WithType(Aws::String&& value) { SetType(std::move(value)); return *this;}

    /**
     *
The type of finding.

     */
    inline Finding& WithType(const char* value) { SetType(value); return *this;}

    /**
     *
The time and date when the finding was last updated.

     */
    inline const Aws::String& GetUpdatedAt() const{ return m_updatedAt; }

    /**
     *
The time and date when the finding was last updated.

     */
    inline bool UpdatedAtHasBeenSet() const { return m_updatedAtHasBeenSet; }

    /**
     *
The time and date when the finding was last updated.

     */
    inline void SetUpdatedAt(const Aws::String& value) { m_updatedAtHasBeenSet = true; m_updatedAt = value; }

    /**
     *
The time and date when the finding was last updated.

     */
    inline void SetUpdatedAt(Aws::String&& value) { m_updatedAtHasBeenSet = true; m_updatedAt = std::move(value); }

    /**
     *
The time and date when the finding was last updated.

     */
    inline void SetUpdatedAt(const char* value) { m_updatedAtHasBeenSet = true; m_updatedAt.assign(value); }

    /**
     *
The time and date when the finding was last updated.

     */
    inline Finding& WithUpdatedAt(const Aws::String& value) { SetUpdatedAt(value); return *this;}

    /**
     *
The time and date when the finding was last updated.

     */
    inline Finding& WithUpdatedAt(Aws::String&& value) { SetUpdatedAt(std::move(value)); return *this;}

    /**
     *
The time and date when the finding was last updated.

     */
    inline Finding& WithUpdatedAt(const char* value) { SetUpdatedAt(value); return *this;}

  private:

    Aws::String m_accountId;
    bool m_accountIdHasBeenSet;

    Aws::String m_arn;
    bool m_arnHasBeenSet;

    double m_confidence;
    bool m_confidenceHasBeenSet;

    Aws::String m_createdAt;
    bool m_createdAtHasBeenSet;

    Aws::String m_description;
    bool m_descriptionHasBeenSet;

    Aws::String m_id;
    bool m_idHasBeenSet;

    Aws::String m_partition;
    bool m_partitionHasBeenSet;

    Aws::String m_region;
    bool m_regionHasBeenSet;

    Resource m_resource;
    bool m_resourceHasBeenSet;

    Aws::String m_schemaVersion;
    bool m_schemaVersionHasBeenSet;

    Service m_service;
    bool m_serviceHasBeenSet;

    double m_severity;
    bool m_severityHasBeenSet;

    Aws::String m_title;
    bool m_titleHasBeenSet;

    Aws::String m_type;
    bool m_typeHasBeenSet;

    Aws::String m_updatedAt;
    bool m_updatedAtHasBeenSet;
  };

} // namespace Model
} // namespace GuardDuty
} // namespace Aws


text:
using System;
using System.Collections.Generic;
using System.Text;
using Ganss.XSS;

namespace LearningSystem.Services.Html.Implementations
{
    public class HtmlService : IHtmlService
    {
        private readonly HtmlSanitizer htmlSanitizer;

        public HtmlService()
        {
            this.htmlSanitizer = new HtmlSanitizer();
            this.htmlSanitizer.AllowedAttributes.Add("class");
        }

        public string Sanitize(string htmlContent)
        {
            return this.htmlSanitizer.Sanitize(htmlContent);
        }
    }
}


text:
#pragma once

#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/platform/for_range.h"
#include "paddle/phi/kernels/funcs/math_function.h"

namespace paddle {
namespace operators {

template <typename T>
struct DiagFunctor {
  DiagFunctor(const T* diagonal, int64_t numel, T* output)
      : diagonal_(diagonal), numel_(numel), output_(output) {}

  HOSTDEVICE void operator()(size_t idx) const {
    output_[idx * numel_ + idx] = diagonal_[idx];
  }

  const T* diagonal_;
  int64_t numel_;
  T* output_;
};

template <typename DeviceContext, typename T>
class DiagKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& context) const override {
    auto* diagonal = context.Input<phi::DenseTensor>("Diagonal");
    auto* diag_data = diagonal->data<T>();
    auto numel = diagonal->numel();
    auto* out = context.Output<phi::DenseTensor>("Out");
    T* out_data = out->mutable_data<T>(context.GetPlace());

    phi::funcs::SetConstant<DeviceContext, T> set_zero;
    auto& dev_ctx = context.template device_context<DeviceContext>();
    set_zero(dev_ctx, out, static_cast<T>(0));

    platform::ForRange<DeviceContext> for_range(dev_ctx, numel);
    DiagFunctor<T> functor(diag_data, numel, out_data);
    for_range(functor);
  }
};

}  // namespace operators
}  // namespace paddle


text:
<?php

defined('BASEPATH') OR exit('No direct script access allowed');

class Categories extends CI_Controller {

    function __construct() {
        parent::__construct();
        $this->load->helper('url');
        $this->load->library('session');
        $this->load->library('form_validation');
        $this->load->model(array('categories_model'));
    }

    function Add_categories() {
        $this->load->view('admin_template/Header');
        $this->load->view('categories/Add_categories');
        $this->load->view('admin_template/Footer');
    }

    function list_all_categories() {
        $list_all_categories = $this->categories_model->list_all_categories();
        echo json_encode($list_all_categories);
    }

    function delete_category($cat_id) {
        $delete_category = $this->categories_model->delete_category($cat_id);
        if ($delete_category) {
            echo json_encode(array("err_code" => 1, "status" => "SUCCESS"));
            exit;
        } else {
            echo json_encode(array("err_code" => 0, "status" => "FAILED"));
            exit;
        }
    }
	function create_category(){

		$category_data= array('cat_Name' => $this->input->post('name'));

		$this->categories_model->create_category($category_data);
		echo $this->db->last_query();exit;

	}
	function edit_category(){

		$category_id = $this->uri->segment(3);

		$data['category_data'] = $this->categories_model->get_category($category_id);

		$this->load->view('admin_template/Header');

		$this->load->view('categories/Edit_categories',$data);

        $this->load->view('admin_template/Footer');

	}
	function update_category(){

	$update_category_data= array(
				'cat_Name' => $this->input->post('name'),
				'enable' => $this->input->post('status')

					);
						$category_id = $this->input->post('cat_id');

				$this->categories_model->update_category_table($update_category_data,$category_id);

	}

}


text:
import signature

# The Transaction class contains a piece of data, an author address, and a signature.
# This represents a claim made on the block chain. Transactions will be added to blocks.
class Transaction:
    def __init__(self, data, author, signature):
        self.data = data
        self.author = author
        self.signature = signature

    def get_string(self):
        return '%s (%s)' % (self.data, self.author)

    def get_data(self):
        return self.data

    def get_author(self):
        return self.author

    def get_signature(self):
        return self.signature

# Sign a piece of data as a transaction using a given PyCrypto key
#
# data must be a string claim to be made on the blockchain
# key must be a PyCrypto RSA key
def sign_transaction(data, key):
    return Transaction(data, signature.sign(key, data), signature.public_key_to_address(key.publickey()))


text:
<?php declare(strict_types=1);

namespace DrdPlus\Skills\Physical;

use DrdPlus\Skills\Skill;
use DrdPlus\Skills\SkillPoint;
use DrdPlus\Skills\SkillRank;
use Granam\Integer\PositiveInteger;

class PhysicalSkillRank extends SkillRank
{
    private \DrdPlus\Skills\Skill $physicalSkill;
    private \DrdPlus\Skills\SkillPoint $physicalSkillPoint;

    /**
     * @param PhysicalSkill $physicalSkill
     * @param PhysicalSkillPoint $physicalSkillPoint
     * @param PositiveInteger $requiredRankValue
     * @throws \DrdPlus\Skills\Exceptions\CanNotVerifyOwningSkill
     * @throws \DrdPlus\Skills\Exceptions\CanNotVerifyPaidSkillPoint
     * @throws \DrdPlus\Skills\Exceptions\WastedSkillPoint
     * @throws \DrdPlus\Skills\Exceptions\CanNotUseZeroSkillPointForNonZeroSkillRank
     * @throws \DrdPlus\Skills\Exceptions\UnexpectedRankValue
     */
    public function __construct(
        PhysicalSkill $physicalSkill,
        PhysicalSkillPoint $physicalSkillPoint,
        PositiveInteger $requiredRankValue
    )
    {
        $this->physicalSkill = $physicalSkill;
        $this->physicalSkillPoint = $physicalSkillPoint;
        parent::__construct($physicalSkill, $physicalSkillPoint, $requiredRankValue);
    }

    /**
     * @return Skill|PhysicalSkill
     */
    public function getSkill(): Skill
    {
        return $this->physicalSkill;
    }

    /**
     * @return SkillPoint|PhysicalSkillPoint
     */
    public function getSkillPoint(): SkillPoint
    {
        return $this->physicalSkillPoint;
    }
}


text:
<?php

/**
 * User: Pascal Brewing
 * Date: 15.09.13
 * Time: 18:32
 * @package ${DIR}.MNav
 * Class MNav
 */
class MNav extends CInputWidget
{
    //Types
    const MIDDLE_NAV_R = 'middleNavR';
    const MIDDLE_NAV_A = 'middleNavA';
    const MIDDLE_NAV_S = 'middleNavS';
    const MIDDLE_NAV_FREE = 'middleFree';
    //colors
    /**
     * .bGreen:hover, .bRed:hover, .bBlue:hover, .bGreyish:hover, .bBlack:hover, .bLightBlue:hover, .bGold:hover, .bSea:hover, .bBrown:hover
     */
    const BUTTON_SUCCESS = 'bGreen';
    const BUTTON_DANGER = 'bRed';
    const BUTTON_BLUE = 'bBlue';
    const BUTTON_GREYISH = 'bGreyish';
    const BUTTON_BLACK = 'bBlack';
    const BUTTON_BLUE_BLIGHT = 'bLightBlue';
    const BUTTON_GOLD = 'bGold';
    const BUTTON_SEA = 'bSea';
    const BUTTON_BROWN = 'bBrown';

    public $model;
    public $items = array();
    public $type = MNav::MIDDLE_NAV_R;
    private $viewPath;
    private $_assetsUrl;

    /**
     *
     */
    public function run()
    {
//        CVarDumper::dump($this->items,10,true);
        $path = Yii::getPathOfAlias('bootstrap.extensions.middlenav.views');
        $this->registerAssetCss('middlenav.css');
//        $this->prepareItems();
        $this->renderInternal($path . '/mnav.php', array('items' => $this->prepareItems(), 'type' => $this->type));
    }

    private function prepareItems()
    {
        $option = array();
        foreach ($this->items as $item) {
            $label = '';
            if (isset($item['icon'])) {
                $label .= BSHtml::icon($item['icon'] . ' glyphicon iconb');
            }

//            CVarDumper::dump($htmlOptions,10,true);

            if ($this->type === MNav::MIDDLE_NAV_A || $this->type === MNav::MIDDLE_NAV_FREE && isset($item['label'])) {
                $label .= "<span>{$item['label']} </span>";
            }

            $htmlOptions = array();
            $cssclass = 'tipN ';

//            if(isset($item['icon']))
//                $label .= BSHtml::icon()$item['icon'].' iconb';

            if (isset($item['color']))
                $cssclass .= $item['color'];

            $htmlOptions['class'] = $cssclass;

            if (isset($item['tooltip']))
                $htmlOptions['data-toggle'] = 'tooltip';

            if (isset($item['tooltip']['label']))
                $htmlOptions['data-original-title'] = $item['tooltip']['label'];

            if (isset($item['tooltip']['placement']))
                $htmlOptions['data-placement'] = $item['tooltip']['placement'];

            if (isset($item['badge']))
                $htmlOptions['badge'] = $item['badge'];

            if (isset($item['label']))
                $htmlOptions['title'] = $item['label'];

            $option[] = array(
                $label,
                $item['url'],

                $htmlOptions,

            );
        }
        return $option;
    }

    /**
     * Returns the assets URL.
     * Assets folder has few orphan and very useful utility libraries.
     * @return string
     */
    public function getAssetsUrl()
    {
        if (isset($this->_assetsUrl)) {
            return $this->_assetsUrl;
        } else {
            $forceCopyAssets = true;
            $path = \Yii::getPathOfAlias('bootstrap.extensions.middlenav');
            $assetsUrl = \Yii::app()->assetManager->publish(
                $path . DIRECTORY_SEPARATOR . 'assets',
                false,
                -1,
                $forceCopyAssets
            );

            return $this->_assetsUrl = $assetsUrl;
        }
    }

    /**
     * Register a specific js file in the asset's js folder
     * @param string $jsFile
     * @param int $position the position of the JavaScript code.
     * @see CClientScript::registerScriptFile
     * @return $this
     */
    public function registerAssetJs($jsFile, $position = CClientScript::POS_END)
    {
        \Yii::app()->getClientScript()->registerScriptFile($this->getAssetsUrl() . "/js/{$jsFile}", $position);
        return $this;
    }

    /**
     * Registers a specific css in the asset's css folder
     * @param string $cssFile the css file name to register
     * @param string $media the media that the CSS file should be applied to. If empty, it means all media types.
     * @return $this
     */
    public function registerAssetCss($cssFile, $media = '')
    {
        \Yii::app()->getClientScript()->registerCssFile($this->getAssetsUrl() . "/css/{$cssFile}", $media);
        return $this;
    }
}


text:
<?php

namespace Jowusu837\HubtelMerchantAccount;

class TransactionStatusResponse
{
    protected $ResponseCode;
    protected $StartDate;
    protected $TransactionStatus;
    protected $TransactionId;
    protected $NetworkTransactionId;
    protected $InvoiceToken;
    protected $TransactionType;
    protected $PaymentMethod;
    protected $ClientReference;
    protected $CountryCode;
    protected $CurrencyCode;
    protected $TransactionAmount;
    protected $Fee;
    protected $AmountAfterFees;
    protected $CardSchemeName;
    protected $CardNumber;
    protected $MobileNumber;
    protected $MobileChannelName;
    protected $TransactionCycle;
    protected $RelatedTransactionId;
    protected $RelatedTransactionType;
    protected $Disputed;
    protected $DisputedAmount;
    protected $DisputedAmountFee;
    protected $TotalAmountRefunded;

    public function __construct(array $response)
    {
        $this->ResponseCode = $response['ResponseCode'];
        $this->StartDate = $response['StartDate'];
        $this->TransactionStatus = $response['TransactionStatus'];
        $this->TransactionId = $response['TransactionId'];
        $this->NetworkTransactionId = $response['NetworkTransactionId'];
        $this->InvoiceToken = $response['InvoiceToken'];
        $this->TransactionType = $response['TransactionType'];
        $this->PaymentMethod = $response['PaymentMethod'];
        $this->ClientReference = $response['ClientReference'];
        $this->CountryCode = $response['CountryCode'];
        $this->CurrencyCode = $response['CurrencyCode'];
        $this->TransactionAmount = $response['TransactionAmount'];
        $this->Fee = $response['Fee'];
        $this->AmountAfterFees = $response['AmountAfterFees'];
        $this->CardSchemeName = $response['CardSchemeName'];
        $this->CardNumber = $response['CardNumber'];
        $this->MobileNumber = $response['MobileNumber'];
        $this->MobileChannelName = $response['MobileChannelName'];
        $this->TransactionCycle = $response['TransactionCycle'];
        $this->RelatedTransactionId = $response['RelatedTransactionId'];
        $this->RelatedTransactionType = $response['RelatedTransactionType'];
        $this->Disputed = $response['Disputed'];
        $this->DisputedAmount = $response['DisputedAmount'];
        $this->DisputedAmountFee = $response['DisputedAmountFee'];
        $this->TotalAmountRefunded = $response['TotalAmountRefunded'];
    }

    public function ResponseCode()
    {
        return $this->ResponseCode;
    }

    public function StartDate()
    {
        return $this->StartDate;
    }

    public function TransactionStatus()
    {
        return $this->TransactionStatus;
    }

    public function TransactionId()
    {
        return $this->TransactionId;
    }

    public function NetworkTransactionId()
    {
        return $this->NetworkTransactionId;
    }

    public function InvoiceToken()
    {
        return $this->InvoiceToken;
    }

    public function TransactionType()
    {
        return $this->TransactionType;
    }

    public function PaymentMethod()
    {
        return $this->PaymentMethod;
    }

    public function ClientReference()
    {
        return $this->ClientReference;
    }

    public function CountryCode()
    {
        return $this->CountryCode;
    }

    public function CurrencyCode()
    {
        return $this->CurrencyCode;
    }

    public function TransactionAmount()
    {
        return $this->TransactionAmount;
    }

    public function Fee()
    {
        return $this->Fee;
    }

    public function AmountAfterFees()
    {
        return $this->AmountAfterFees;
    }

    public function CardSchemeName()
    {
        return $this->CardSchemeName;
    }

    public function CardNumber()
    {
        return $this->CardNumber;
    }

    public function MobileNumber()
    {
        return $this->MobileNumber;
    }

    public function MobileChannelName()
    {
        return $this->MobileChannelName;
    }

    public function TransactionCycle()
    {
        return $this->TransactionCycle;
    }

    public function RelatedTransactionId()
    {
        return $this->RelatedTransactionId;
    }

    public function RelatedTransactionType()
    {
        return $this->RelatedTransactionType;
    }

    public function Disputed()
    {
        return $this->Disputed;
    }

    public function DisputedAmount()
    {
        return $this->DisputedAmount;
    }

    public function DisputedAmountFee()
    {
        return $this->DisputedAmountFee;
    }

    public function TotalAmountRefunded()
    {
        return $this->TotalAmountRefunded;
    }
}


text:
package com.intellij.codeInsight.editorActions.wordSelection;

import com.intellij.lang.java.JavaLanguage;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiField;
import com.intellij.psi.PsiIdentifier;
import com.intellij.psi.javadoc.PsiDocComment;
import org.jetbrains.annotations.NotNull;

import java.util.List;

public class FieldSelectioner extends WordSelectioner {
  @Override
  public boolean canSelect(@NotNull PsiElement e) {
    return e instanceof PsiField && e.getLanguage() == JavaLanguage.INSTANCE;
  }

  private static void addRangeElem(final List<TextRange> result,
                                   CharSequence editorText,
                                   final PsiElement first,
                                   final int end) {
    if (first != null) {
      result.addAll(expandToWholeLine(editorText,
                                      new TextRange(first.getTextRange().getStartOffset(), end)));
    }
  }

  @Override
  public List<TextRange> select(@NotNull PsiElement e, @NotNull CharSequence editorText, int cursorOffset, @NotNull Editor editor) {
    List<TextRange> result = super.select(e, editorText, cursorOffset, editor);
    PsiField field = (PsiField)e;
    TextRange fieldRange = field.getTextRange();
    PsiIdentifier nameId = field.getNameIdentifier();
    TextRange nameRange = nameId.getTextRange();
    PsiElement last = field.getInitializer();
    int end = last == null ? nameRange.getEndOffset() : last.getTextRange().getEndOffset();

    PsiDocComment comment = field.getDocComment();
    if (comment != null) {
      TextRange commentTextRange = comment.getTextRange();
      addRangeElem(result, editorText, comment, commentTextRange.getEndOffset());
    }
    addRangeElem(result, editorText, nameId, end);
    addRangeElem(result, editorText, field.getTypeElement(), nameRange.getEndOffset());
    addRangeElem(result, editorText, field.getModifierList(), fieldRange.getEndOffset());
    result.addAll(expandToWholeLine(editorText, fieldRange));
    return result;
  }
}


text:
"""Acts like a Pymongo client to TinyDB"""
# coding: utf-8

from __future__ import absolute_import

import copy
from functools import reduce
import logging
import os
from math import ceil
from operator import itemgetter
from uuid import uuid1

from tinydb import Query, TinyDB, where
from .results import (
    InsertOneResult,
    InsertManyResult,
    UpdateResult,
    DeleteResult
)
from .errors import DuplicateKeyError

try:
  basestring
except NameError:
  basestring = str

logger = logging.getLogger(__name__)

def Q(query, key):
    return reduce(lambda partial_query, field: partial_query[field], key.split('.'), query)

class TinyMongoClient(object):
    """Represents the Tiny `db` client"""
    def __init__(self, foldername=u"tinydb", **kwargs):
        """Initialize container folder"""
        self._foldername = foldername
        try:
            os.mkdir(foldername)
        except OSError as x:
            logger.info('{}'.format(x))

    @property
    def _storage(self):
        """By default return Tiny.DEFAULT_STORAGE and can be overwritten to
        return custom storages and middlewares.

            class CustomClient(TinyMongoClient):
                @property
                def _storage(self):
                    return CachingMiddleware(OtherMiddleware(JSONMiddleware))

        This property is also useful to define Serializers using required
        `tinydb-serialization` module.

            from tinymongo.serializers import DateTimeSerializer
            from tinydb_serialization import SerializationMiddleware
            class CustomClient(TinyMongoClient):
                @property
                def _storage(self):
                    serialization = SerializationMiddleware()
                    serialization.register_serializer(
                        DateTimeSerializer(), 'TinyDate')
                    # register other custom serializers
                    return serialization

        """
        return TinyDB.DEFAULT_STORAGE

    def __getitem__(self, key):
        """Gets a new or existing database based in key"""
        return TinyMongoDatabase(key, self._foldername, self._storage)

    def close(self):
        """Do nothing"""
        pass

    def __getattr__(self, name):
        """Gets a new or existing database based in attribute"""
        return TinyMongoDatabase(name, self._foldername, self._storage)

class TinyMongoDatabase(object):
    """Representation of a Pymongo database"""
    def __init__(self, database, foldername, storage):
        """Initialize a TinyDB file named as the db name in the given folder
        """
        self._foldername = foldername
        self.tinydb = TinyDB(
            os.path.join(foldername, database + u".json"),
            storage=storage
        )

    def __getattr__(self, name):
        """Gets a new or existing collection"""
        return TinyMongoCollection(name, self)

    def __getitem__(self, name):
        """Gets a new or existing collection"""
        return TinyMongoCollection(name, self)

    def collection_names(self):
        """Get a list of all the collection names in this database"""
        return list(self.tinydb.tables())

class TinyMongoCollection(object):
    """
    This class represents a collection and all of the operations that are
    commonly performed on a collection
    """

    def __init__(self, table, parent=None):
        """
        Initilialize the collection

        :param table: the table name
        :param parent: the parent db name
        """
        self.tablename = table
        self.table = None
        self.parent = parent

    def __repr__(self):
        """Return collection name"""
        return self.tablename

    def __getattr__(self, name):
        """
        If attr is not found return self
        :param name:
        :return:
        """
        # if self.table is None:
        #     self.tablename += u"." + name
        if self.table is None:
            self.build_table()
        return self

    def build_table(self):
        """
        Builds a new tinydb table at the parent database
        :return:
        """
        self.table = self.parent.tinydb.table(self.tablename)

    def count(self):
        """
        Counts the documents in the collection.
        :return: Integer representing the number of documents in the collection.
        """
        return self.find().count()

    def drop(self, **kwargs):
        """
        Removes a collection from the database.
        **kwargs only because of the optional "writeConcern" field, but does nothing in the TinyDB database.
        :return: Returns True when successfully drops a collection. Returns False when collection to drop does not
        exist.
        """
        if self.table:
            self.parent.tinydb.purge_table(self.tablename)
            return True
        else:
            return False

    def insert(self, docs, *args, **kwargs):
        """Backwards compatibility with insert"""
        if isinstance(docs, list):
            return self.insert_many(docs, *args, **kwargs)
        else:
            return self.insert_one(docs, *args, **kwargs)

    def insert_one(self, doc, *args, **kwargs):
        """
        Inserts one document into the collection
        If contains '_id' key it is used, else it is generated.
        :param doc: the document
        :return: InsertOneResult
        """
        if self.table is None:
            self.build_table()

        if not isinstance(doc, dict):
            raise ValueError(u'"doc" must be a dict')

        _id = doc[u'_id'] = doc.get('_id') or generate_id()

        bypass_document_validation = kwargs.get('bypass_document_validation')
        if bypass_document_validation is True:
            # insert doc without validation of duplicated `_id`
            eid = self.table.insert(doc)
        else:
            existing = self.find_one({'_id': _id})
            if existing is None:
                eid = self.table.insert(doc)
            else:
                raise DuplicateKeyError(
                    u'_id:{0} already exists in collection:{1}'.format(
                        _id, self.tablename
                    )
                )

        return InsertOneResult(eid=eid, inserted_id=_id)

    def insert_many(self, docs, *args, **kwargs):
        """
        Inserts several documents into the collection
        :param docs: a list of documents
        :return: InsertManyResult
        """
        if self.table is None:
            self.build_table()

        if not isinstance(docs, list):
            raise ValueError(u'"insert_many" requires a list input')

        bypass_document_validation = kwargs.get('bypass_document_validation')

        if bypass_document_validation is not True:
            # get all _id in once, to reduce I/O. (without projection)
            existing = [doc['_id'] for doc in self.find({})]

        _ids = list()
        for doc in docs:

            _id = doc[u'_id'] = doc.get('_id') or generate_id()

            if bypass_document_validation is not True:
                if _id in existing:
                    raise DuplicateKeyError(
                        u'_id:{0} already exists in collection:{1}'.format(
                            _id, self.tablename
                        )
                    )
                existing.append(_id)

            _ids.append(_id)

        results = self.table.insert_multiple(docs)

        return InsertManyResult(
            eids=[eid for eid in results],
            inserted_ids=[inserted_id for inserted_id in _ids]
        )

    def parse_query(self, query):
        """
        Creates a tinydb Query() object from the query dict

        :param query: object containing the dictionary representation of the
        query
        :return: composite Query()
        """
        logger.debug(u'query to parse2: {}'.format(query))

        # this should find all records
        if query == {} or query is None:
            return Query()._id != u'-1'  # noqa

        q = None
        # find the final result of the generator
        for c in self.parse_condition(query):
            if q is None:
                q = c
            else:
                q = q & c

        logger.debug(u'new query item2: {}'.format(q))

        return q

    def parse_condition(self, query, prev_key=None, last_prev_key=None):
        """
        Creates a recursive generator for parsing some types of Query()
        conditions

        :param query: Query object
        :param prev_key: The key at the next-higher level
        :return: generator object, the last of which will be the complete
        Query() object containing all conditions
        """
        # use this to determine gt/lt/eq on prev_query
        logger.debug(u'query: {} prev_query: {}'.format(query, prev_key))

        q = Query()
        conditions = None

        # deal with the {'name': value} case by injecting a previous key
        if not prev_key:
            temp_query = copy.deepcopy(query)
            k, v = temp_query.popitem()
            prev_key = k

        # deal with the conditions
        for key, value in query.items():
            logger.debug(u'conditions: {} {}'.format(key, value))

            if key == u'$gte':
                conditions = (
                    Q(q, prev_key) >= value
                ) if not conditions and prev_key != "$not" \
                else (conditions & (Q(q, prev_key) >= value)) if prev_key != "$not" \
                else (q[last_prev_key] < value)
            elif key == u'$gt':
                conditions = (
                    Q(q, prev_key) > value
                ) if not conditions and prev_key != "$not" \
                else (conditions & (Q(q, prev_key) > value)) if prev_key != "$not" \
                else (q[last_prev_key] <= value)
            elif key == u'$lte':
                conditions = (
                    Q(q, prev_key) <= value
                ) if not conditions and prev_key != "$not" \
                else (conditions & (Q(q, prev_key) <= value)) if prev_key != "$not" \
                else (q[last_prev_key] > value)
            elif key == u'$lt':
                conditions = (
                    Q(q, prev_key) < value
                ) if not conditions and prev_key != "$not" \
                else (conditions & (Q(q, prev_key) < value)) if prev_key != "$not" \
                else (q[last_prev_key] >= value)
            elif key == u'$ne':
                conditions = (
                    Q(q, prev_key) != value
                ) if not conditions and prev_key != "$not" \
                else (conditions & (Q(q, prev_key) != value))if prev_key != "$not" \
                else (q[last_prev_key] == value)
            elif key == u'$not':
                if not isinstance(value, dict) and not isinstance(value, list):
                    conditions = (
                        Q(q, prev_key) != value
                    ) if not conditions and prev_key != "$not" \
                    else (conditions & (Q(q, prev_key) != value)) \
                    if prev_key != "$not" else (q[last_prev_key] >= value)
                else:
                    # let the value's condition be parsed below
                    pass
            elif key == u'$regex':
                value = value.replace('\\\\\\', '|||')
                value = value.replace('\\\\', '|||')
                regex = value.replace('\\', '')
                regex = regex.replace('|||', '\\')
                currCond = (where(prev_key).matches(regex))
                conditions = currCond if not conditions else (conditions & currCond)
            elif key in ['$and', '$or', '$in', '$all']:
                pass
            else:

                # don't want to use the previous key if this is a secondary key
                # (fixes multiple item query that includes $ codes)
                if not isinstance(value, dict) and not isinstance(value, list):
                    conditions = (
                        (Q(q, key) == value) | (Q(q, key).any([value]))
                    ) if not conditions else (conditions & ((Q(q, key) == value) | (Q(q, key).any([value]))))
                    prev_key = key

            logger.debug(u'c: {}'.format(conditions))
            if isinstance(value, dict):
                # yield from self.parse_condition(value, key)
                for parse_condition in self.parse_condition(value, key, prev_key):
                    yield parse_condition
            elif isinstance(value, list):
                if key == '$and':
                    grouped_conditions = None
                    for spec in value:
                        for parse_condition in self.parse_condition(spec):
                            grouped_conditions = (
                                parse_condition
                                if not grouped_conditions
                                else grouped_conditions & parse_condition
                            )
                    yield grouped_conditions
                elif key == '$or':
                    grouped_conditions = None
                    for spec in value:
                        for parse_condition in self.parse_condition(spec):
                            grouped_conditions = (
                                parse_condition
                                if not grouped_conditions
                                else grouped_conditions | parse_condition
                            )
                    yield grouped_conditions
                elif key == '$in':
                    # use `any` to find with list, before comparing to single string
                    grouped_conditions = Q(q, prev_key).any(value)
                    for val in value:
                        for parse_condition in self.parse_condition({prev_key : val}):
                            grouped_conditions = (
                                parse_condition
                                if not grouped_conditions
                                else grouped_conditions | parse_condition
                            )
                    yield grouped_conditions
                elif key == '$all':
                    yield Q(q, prev_key).all(value)
                else:
                    yield Q(q, prev_key).any([value])
            else:
                yield conditions

    def update(self, query, doc, *args, **kwargs):
        """BAckwards compatibility with update"""
        if isinstance(doc, list):
            return [
                self.update_one(query, item, *args, **kwargs)
                for item in doc
            ]
        else:
            return self.update_one(query, doc, *args, **kwargs)

    def update_one(self, query, doc):
        """
        Updates one element of the collection

        :param query: dictionary representing the mongo query
        :param doc: dictionary representing the item to be updated
        :return: UpdateResult
        """
        if self.table is None:
            self.build_table()

        if u"$set" in doc:
            doc = doc[u"$set"]

        allcond = self.parse_query(query)

        try:
            result = self.table.update(doc, allcond)
        except:
            # TODO: check table.update result
            # check what pymongo does in that case
            result = None

        return UpdateResult(raw_result=result)

    def find(self, filter=None, sort=None, skip=None, limit=None,
             *args, **kwargs):
        """
        Finds all matching results

        :param query: dictionary representing the mongo query
        :return: cursor containing the search results
        """
        if self.table is None:
            self.build_table()

        if filter is None:
            result = self.table.all()
        else:
            allcond = self.parse_query(filter)

            try:
                result = self.table.search(allcond)
            except (AttributeError, TypeError):
                result = []

        result = TinyMongoCursor(
            result,
            sort=sort,
            skip=skip,
            limit=limit
        )

        return result

    def find_one(self, filter=None):
        """
        Finds one matching query element

        :param query: dictionary representing the mongo query
        :return: the resulting document (if found)
        """

        if self.table is None:
            self.build_table()

        allcond = self.parse_query(filter)

        return self.table.get(allcond)

    def remove(self, spec_or_id, multi=True, *args, **kwargs):
        """Backwards compatibility with remove"""
        if multi:
            return self.delete_many(spec_or_id)
        return self.delete_one(spec_or_id)

    def delete_one(self, query):
        """
        Deletes one document from the collection

        :param query: dictionary representing the mongo query
        :return: DeleteResult
        """
        item = self.find_one(query)
        result = self.table.remove(where(u'_id') == item[u'_id'])

        return DeleteResult(raw_result=result)

    def delete_many(self, query):
        """
        Removes all items matching the mongo query

        :param query: dictionary representing the mongo query
        :return: DeleteResult
        """
        items = self.find(query)
        result = [
            self.table.remove(where(u'_id') == item[u'_id'])
            for item in items
        ]

        if query == {}:
            # need to reset TinyDB's index for docs order consistency
            self.table._last_id = 0

        return DeleteResult(raw_result=result)

class TinyMongoCursor(object):
    """Mongo iterable cursor"""

    def __init__(self, cursordat, sort=None, skip=None, limit=None):
        """Initialize the mongo iterable cursor with data"""
        self.cursordat = cursordat
        self.cursorpos = -1

        if len(self.cursordat) == 0:
            self.currentrec = None
        else:
            self.currentrec = self.cursordat[self.cursorpos]

        if sort:
            self.sort(sort)

        self.paginate(skip, limit)

    def __getitem__(self, key):
        """Gets record by index or value by key"""
        if isinstance(key, int):
            return self.cursordat[key]
        return self.currentrec[key]

    def paginate(self, skip, limit):
        """Paginate list of records"""
        if not self.count() or not limit:
            return
        skip = skip or 0
        pages = int(ceil(self.count() / float(limit)))
        limits = {}
        last = 0
        for i in range(pages):
            current = limit * i
            limits[last] = current
            last = current
        # example with count == 62
        # {0: 20, 20: 40, 40: 60, 60: 62}
        if limit and limit < self.count():
            limit = limits.get(skip, self.count())
            self.cursordat = self.cursordat[skip: limit]

    def _order(self, value, is_reverse=None):
        """Parsing data to a sortable form
        By giving each data type an ID(int), and assemble with the value
        into a sortable tuple.
        """

        def _dict_parser(dict_doc):
            """ dict ordered by:
            valueType_N -> key_N -> value_N
            """
            result = list()
            for key in dict_doc:
                data = self._order(dict_doc[key])
                res = (data[0], key, data[1])
                result.append(res)
            return tuple(result)

        def _list_parser(list_doc):
            """list will iter members to compare
            """
            result = list()
            for member in list_doc:
                result.append(self._order(member))
            return result

        # (TODO) include more data type
        if value is None or not isinstance(value, (dict,
                                                   list,
                                                   basestring,
                                                   bool,
                                                   float,
                                                   int)):
            # not support/sortable value type
            value = (0, None)

        elif isinstance(value, bool):
            value = (5, value)

        elif isinstance(value, (int, float)):
            value = (1, value)

        elif isinstance(value, basestring):
            value = (2, value)

        elif isinstance(value, dict):
            value = (3, _dict_parser(value))

        elif isinstance(value, list):
            if len(value) == 0:
                # [] less then None
                value = [(-1, [])]
            else:
                value = _list_parser(value)

            if is_reverse is not None:
                # list will firstly compare with other doc by it's smallest
                # or largest member
                value = max(value) if is_reverse else min(value)
            else:
                # if the smallest or largest member is a list
                # then compaer with it's sub-member in list index order
                value = (4, tuple(value))

        return value

    def sort(self, key_or_list, direction=None):
        """
        Sorts a cursor object based on the input

        :param key_or_list: a list/tuple containing the sort specification,
        i.e. ('user_number': -1), or a basestring
        :param direction: sorting direction, 1 or -1, needed if key_or_list
                          is a basestring
        :return:
        """

        # checking input format

        sort_specifier = list()
        if isinstance(key_or_list, list):
            if direction is not None:
                raise ValueError('direction can not be set separately '
                                 'if sorting by multiple fields.')
            for pair in key_or_list:
                if not (isinstance(pair, list) or isinstance(pair, tuple)):
                    raise TypeError('key pair should be a list or tuple.')
                if not len(pair) == 2:
                    raise ValueError('Need to be (key, direction) pair')
                if not isinstance(pair[0], basestring):
                    raise TypeError('first item in each key pair must '
                                    'be a string')
                if not isinstance(pair[1], int) or not abs(pair[1]) == 1:
                    raise TypeError('bad sort specification.')

            sort_specifier = key_or_list

        elif isinstance(key_or_list, basestring):
            if direction is not None:
                if not isinstance(direction, int) or not abs(direction) == 1:
                    raise TypeError('bad sort specification.')
            else:
                # default ASCENDING
                direction = 1

            sort_specifier = [(key_or_list, direction)]

        else:
            raise ValueError('Wrong input, pass a field name and a direction,'
                             ' or pass a list of (key, direction) pairs.')

        # sorting

        _cursordat = self.cursordat

        total = len(_cursordat)
        pre_sect_stack = list()
        for pair in sort_specifier:

            is_reverse = bool(1-pair[1])
            value_stack = list()
            for index, data in enumerate(_cursordat):

                # get field value

                not_found = None
                for key in pair[0].split('.'):
                    not_found = True

                    if isinstance(data, dict) and key in data:
                        data = copy.deepcopy(data[key])
                        not_found = False

                    elif isinstance(data, list):
                        if not is_reverse and len(data) == 1:
                            # MongoDB treat [{data}] as {data}
                            # when finding fields
                            if isinstance(data[0], dict) and key in data[0]:
                                data = copy.deepcopy(data[0][key])
                                not_found = False

                        elif is_reverse:
                            # MongoDB will keep finding field in reverse mode
                            for _d in data:
                                if isinstance(_d, dict) and key in _d:
                                    data = copy.deepcopy(_d[key])
                                    not_found = False
                                    break

                    if not_found:
                        break

                # parsing data for sorting

                if not_found:
                    # treat no match as None
                    data = None

                value = self._order(data, is_reverse)

                # read previous section
                pre_sect = pre_sect_stack[index] if pre_sect_stack else 0
                # inverse if in reverse mode
                # for keeping order as ASCENDING after sort
                pre_sect = (total - pre_sect) if is_reverse else pre_sect
                _ind = (total - index) if is_reverse else index

                value_stack.append((pre_sect, value, _ind))

            # sorting cursor data

            value_stack.sort(reverse=is_reverse)

            ordereddat = list()
            sect_stack = list()
            sect_id = -1
            last_dat = None
            for dat in value_stack:
                # restore if in reverse mode
                _ind = (total - dat[-1]) if is_reverse else dat[-1]
                ordereddat.append(_cursordat[_ind])

                # define section
                # maintain the sorting result in next level sorting
                if not dat[1] == last_dat:
                    sect_id += 1
                sect_stack.append(sect_id)
                last_dat = dat[1]

            # save result for next level sorting
            _cursordat = ordereddat
            pre_sect_stack = sect_stack

        # done

        self.cursordat = _cursordat

        return self

    def hasNext(self):
        """
        Returns True if the cursor has a next position, False if not
        :return:
        """
        cursor_pos = self.cursorpos + 1

        try:
            self.cursordat[cursor_pos]
            return True
        except IndexError:
            return False

    def next(self):
        """
        Returns the next record

        :return:
        """
        self.cursorpos += 1
        return self.cursordat[self.cursorpos]

    def count(self, with_limit_and_skip=False):
        """
        Returns the number of records in the current cursor

        :return: number of records
        """
        return len(self.cursordat)

class TinyGridFS(object):
    """GridFS for tinyDB"""
    def __init__(self, *args, **kwargs):
        self.database = None

    def GridFS(self, tinydatabase):
        """TODO: Must implement yet"""
        self.database = tinydatabase
        return self

def generate_id():
    """Generate new UUID"""
    # TODO: Use six.string_type to Py3 compat
    try:
        return unicode(uuid1()).replace(u"-", u"")
    except NameError:
        return str(uuid1()).replace(u"-", u"")


text:
<?php

namespace Symfony\Component\Messenger\EventListener;

use Psr\Log\LoggerInterface;
use Symfony\Component\Debug\Exception\FlattenException;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Messenger\Event\WorkerMessageFailedEvent;
use Symfony\Component\Messenger\Exception\HandlerFailedException;
use Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Component\Messenger\Stamp\ReceivedStamp;
use Symfony\Component\Messenger\Stamp\RedeliveryStamp;
use Symfony\Component\Messenger\Stamp\SentStamp;
use Symfony\Component\Messenger\Stamp\SentToFailureTransportStamp;
use Symfony\Component\Messenger\Stamp\TransportMessageIdStamp;

/**
 * Sends a rejected message to a "failure transport".
 *
 * @author Ryan Weaver <ryan@symfonycasts.com>
 *
 * @experimental in 4.3
 */
class SendFailedMessageToFailureTransportListener implements EventSubscriberInterface
{
    private $messageBus;
    private $failureSenderAlias;
    private $logger;

    public function __construct(MessageBusInterface $messageBus, string $failureSenderAlias, LoggerInterface $logger = null)
    {
        $this->messageBus = $messageBus;
        $this->failureSenderAlias = $failureSenderAlias;
        $this->logger = $logger;
    }

    public function onMessageFailed(WorkerMessageFailedEvent $event)
    {
        if ($event->willRetry()) {
            return;
        }

        $envelope = $event->getEnvelope();

        // avoid re-sending to the failed sender
        foreach ($envelope->all(SentStamp::class) as $sentStamp) {
            /** @var SentStamp $sentStamp */
            if ($sentStamp->getSenderAlias() === $this->failureSenderAlias) {
                return;
            }
        }

        // remove the received stamp so it's redelivered
        $throwable = $event->getThrowable();
        if ($throwable instanceof HandlerFailedException) {
            $throwable = $throwable->getNestedExceptions()[0];
        }

        $flattenedException = \class_exists(FlattenException::class) ? FlattenException::createFromThrowable($throwable) : null;
        $envelope = $envelope->withoutAll(ReceivedStamp::class)
            ->withoutAll(TransportMessageIdStamp::class)
            ->with(new SentToFailureTransportStamp($throwable->getMessage(), $event->getReceiverName(), $flattenedException))
            ->with(new RedeliveryStamp(0, $this->failureSenderAlias));

        if (null !== $this->logger) {
            $this->logger->info('Rejected message {class} will be sent to the failure transport {transport}.', [
                'class' => \get_class($envelope->getMessage()),
                'transport' => $this->failureSenderAlias,
            ]);
        }

        $this->messageBus->dispatch($envelope);
    }

    public static function getSubscribedEvents()
    {
        return [
            WorkerMessageFailedEvent::class => ['onMessageFailed', -100],
        ];
    }
}


text:
typedef NS_ENUM(NSInteger, HITPSubMenuSortScenario) {
    HITPSubMenuSortScenarioUnavailableWin = 0,
    HITPSubMenuSortScenarioOKWin
};

@interface HITPSubMenu () <NSMenuDelegate>
@property NSArray *content;
@property NSMutableArray *subPluginInstances;
@property NSMutableArray *observedSubPluginInstances;
@property id<HITPluginsManagerProtocol> pluginsManager;
@property HITPSubMenuSortScenario stateSortScenario;
@property BOOL lastCheckWasWithOptionalDisplay;
@end

@implementation HITPSubMenu

+ (id<HITPluginProtocol>)newPlugInInstanceWithSettings:(NSDictionary*)settings {
    id instance = [[self alloc] initWithSettings:settings];
    return instance;
}

- (instancetype)initWithSettings:(NSDictionary*)settings
{
    self = [super initWithSettings:settings];
    if (self) {
        _content = [settings objectForKey:kMenuItemContent];

        NSNumber *selectedScenario = [settings objectForKey:kMenuItemStateSortScenario];
        if (selectedScenario) {
            _stateSortScenario = [selectedScenario integerValue];
        } else {
            _stateSortScenario = HITPSubMenuSortScenarioUnavailableWin;
        }

    }
    return self;
}

-(NSMenuItem *)prepareNewMenuItem {
    NSMenuItem *menuItem = [super prepareNewMenuItem];

    menuItem.action = NULL;
    menuItem.target = nil;

    NSMenu *menu = [[NSMenu alloc] init];
    menu.delegate = self;
    self.subPluginInstances = [NSMutableArray new];
    self.observedSubPluginInstances = [NSMutableArray new];

    asl_log(NULL, NULL, ASL_LEVEL_INFO, "Prepare submenu");

    for (NSDictionary *item in self.content) {
        asl_log(NULL, NULL, ASL_LEVEL_INFO, "Trying to load submenu item for function %s.", [[item objectForKey:kMenuItemFunctionIdentifier] cStringUsingEncoding:NSUTF8StringEncoding]);
        Class<HITPluginProtocol> TargetPlugin = [self.pluginsManager mainClassForPluginWithFunctionIdentifier:[item objectForKey:kMenuItemFunctionIdentifier]];

        asl_log(NULL, NULL, ASL_LEVEL_DEBUG, "Pluing found use %s class.", [NSStringFromClass(TargetPlugin) cStringUsingEncoding:NSUTF8StringEncoding]);

        id<HITPluginProtocol> pluginInstance = [TargetPlugin newPlugInInstanceWithSettings:[item objectForKey:kMenuItemSettings]];
        if (pluginInstance) {
            NSObject<HITPluginProtocol> *observablePluginInstance = pluginInstance;

            if ([pluginInstance respondsToSelector:@selector(setPluginsManager:)]) {
                // Access to plugin manager may be needed to allow plugin to call other plugins,
                // to create a submenu for example
                [pluginInstance setPluginsManager:self.pluginsManager];
            }

            if ([pluginInstance respondsToSelector:@selector(testState)]) {
                BOOL skipForGlobalState = NO;

                if ([pluginInstance respondsToSelector:@selector(skipForGlobalState)]) {
                    skipForGlobalState = [observablePluginInstance skipForGlobalState];
                }

                if (!skipForGlobalState) {
                    asl_log(NULL, NULL, ASL_LEVEL_DEBUG, "Plugin instance of %s has state for global state, start observing it.", [NSStringFromClass(TargetPlugin) cStringUsingEncoding:NSUTF8StringEncoding]);

                    [observablePluginInstance addObserver:self
                                               forKeyPath:@"testState"
                                                  options:0
                                                  context:nil];
                    [self.observedSubPluginInstances addObject:observablePluginInstance];
                }
            }

            if ([pluginInstance respondsToSelector:@selector(isNetworkRelated)]) {
                if ([pluginInstance isNetworkRelated]) {
                    asl_log(NULL, NULL, ASL_LEVEL_DEBUG, "Plugin instance of %s is network related, recording it to the plugins manager.", [NSStringFromClass(TargetPlugin) cStringUsingEncoding:NSUTF8StringEncoding]);
                    [self.pluginsManager registerPluginInstanceAsNetworkRelated:pluginInstance];
                }
            }

            [self.subPluginInstances addObject:pluginInstance];
            [menu addItem:[pluginInstance menuItem]];
        } else {
            asl_log(NULL, NULL, ASL_LEVEL_ERR, "Impossible to instanciate %s (needed for %s).", [NSStringFromClass(TargetPlugin) cStringUsingEncoding:NSUTF8StringEncoding], [[item objectForKey:kMenuItemFunctionIdentifier] cStringUsingEncoding:NSUTF8StringEncoding]);
        }
    }

    [self updateHiddenStateBasedOnRequiredKeysOnIn:menu];

    asl_log(NULL, NULL, ASL_LEVEL_INFO, "Submenu ready");
    menuItem.submenu = menu;
    return menuItem;
}

- (void)updateHiddenStateBasedOnRequiredKeysOnIn:(NSMenu*)menu {
    self.lastCheckWasWithOptionalDisplay = (([NSEvent modifierFlags] & NSDeviceIndependentModifierFlagsMask) == NSAlternateKeyMask);
    [self updateHiddenStateBasedLastCheckResult:menu];
}

- (void)updateHiddenStateBasedLastCheckResult:(NSMenu*)menu {
    for (NSMenuItem *menuItem in menu.itemArray) {
        id <HITPluginProtocol> pluginInstance = menuItem.representedObject;
        if ([pluginInstance respondsToSelector:@selector(optionalDisplay)]) {
            if (pluginInstance.optionalDisplay) {
                if (self.lastCheckWasWithOptionalDisplay) {
                    menuItem.hidden = NO;
                } else {
                    menuItem.hidden = YES;
                }
            }
        }

        if ([pluginInstance isKindOfClass:[HITPSubMenu class]]) {
            ((HITPSubMenu*)pluginInstance).lastCheckWasWithOptionalDisplay = self.lastCheckWasWithOptionalDisplay;
        }
    }
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if ([keyPath isEqualToString:@"testState"]) {
        int substate = 0;
        for (id<HITPluginProtocol> pluginInstance in self.subPluginInstances) {
            if ([pluginInstance respondsToSelector:@selector(testState)]) {
                substate |= [pluginInstance testState];
            }
        }

        if (self.stateSortScenario == HITPSubMenuSortScenarioOKWin) {
            if (substate&HITPluginTestStateError) self.testState = HITPluginTestStateError;
            else if (substate&HITPluginTestStateWarning) self.testState = HITPluginTestStateWarning;
            else if (substate&HITPluginTestStateOK) self.testState = HITPluginTestStateOK;
            else if (substate&HITPluginTestStateUnavailable) self.testState = HITPluginTestStateUnavailable;
        } else if (self.stateSortScenario == HITPSubMenuSortScenarioUnavailableWin) {
            if (substate&HITPluginTestStateError) self.testState = HITPluginTestStateError;
            else if (substate&HITPluginTestStateWarning) self.testState = HITPluginTestStateWarning;
            else if (substate&HITPluginTestStateUnavailable) self.testState = HITPluginTestStateUnavailable;
            else if (substate&HITPluginTestStateOK) self.testState = HITPluginTestStateOK;
        }

        asl_log(NULL, NULL, ASL_LEVEL_INFO, "Submenu state has changed for %lu.", (unsigned long)self.testState);

    }
}

-(void)stopAndPrepareForRelease {
    for (NSObject<HITPluginProtocol> *observablePluginInstance in [self.observedSubPluginInstances reverseObjectEnumerator]) {
        [observablePluginInstance removeObserver:self forKeyPath:@"testState"];
        [self.observedSubPluginInstances removeObject:observablePluginInstance];
    }

    for (id<HITPluginProtocol> pluginInstance in self.subPluginInstances) {
        [pluginInstance stopAndPrepareForRelease];
    }
}

#pragma mark - NSMenuDelegate

- (void)menuWillOpen:(NSMenu *)menu {
    if (!menu.supermenu) {
        [self updateHiddenStateBasedOnRequiredKeysOnIn:menu];
    } else {
        [self updateHiddenStateBasedLastCheckResult:menu];
    }
}

- (void)menuDidClose:(NSMenu *)menu {
}

@end