text:
/**
 * @fileoverview Utility for executing npm commands.
 * @author Ian VanSchooten
 */

"use strict";

//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------

const fs = require("fs"),
    childProcess = require("child_process"),
    path = require("path"),
    log = require("../logging");

//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------

/**
 * Find the closest package.json file, starting at process.cwd (by default),
 * and working up to root.
 *
 * @param   {string} [startDir=process.cwd()] Starting directory
 * @returns {string}                          Absolute path to closest package.json file
 */
function findPackageJson(startDir) {
    let dir = path.resolve(startDir || process.cwd());

    do {
        const pkgFile = path.join(dir, "package.json");

        if (!fs.existsSync(pkgFile) || !fs.statSync(pkgFile).isFile()) {
            dir = path.join(dir, "..");
            continue;
        }
        return pkgFile;
    } while (dir !== path.resolve(dir, ".."));
    return null;
}

//------------------------------------------------------------------------------
// Private
//------------------------------------------------------------------------------

/**
 * Install node modules synchronously and save to devDependencies in package.json
 * @param   {string|string[]} packages Node module or modules to install
 * @returns {void}
 */
function installSyncSaveDev(packages) {
    if (Array.isArray(packages)) {
        packages = packages.join(" ");
    }
    childProcess.execSync(`npm i --save-dev ${packages}`, { stdio: "inherit", encoding: "utf8" });
}

/**
 * Fetch `peerDependencies` of the given package by `npm show` command.
 * @param {string} packageName The package name to fetch peerDependencies.
 * @returns {string[]} Gotten peerDependencies.
 */
function fetchPeerDependencies(packageName) {
    const fetchedText = childProcess.execSync(
        `npm show --json ${packageName} peerDependencies`,
        { encoding: "utf8" }
    ).trim();

    return JSON.parse(fetchedText || "{}");
}

/**
 * Check whether node modules are include in a project's package.json.
 *
 * @param   {string[]} packages           Array of node module names
 * @param   {Object}  opt                 Options Object
 * @param   {boolean} opt.dependencies    Set to true to check for direct dependencies
 * @param   {boolean} opt.devDependencies Set to true to check for development dependencies
 * @param   {boolean} opt.startdir        Directory to begin searching from
 * @returns {Object}                      An object whose keys are the module names
 *                                        and values are booleans indicating installation.
 */
function check(packages, opt) {
    let deps = [];
    const pkgJson = (opt) ? findPackageJson(opt.startDir) : findPackageJson();
    let fileJson;

    if (!pkgJson) {
        throw new Error("Could not find a package.json file. Run 'npm init' to create one.");
    }

    try {
        fileJson = JSON.parse(fs.readFileSync(pkgJson, "utf8"));
    } catch (e) {
        log.info("Could not read package.json file. Please check that the file contains valid JSON.");
        throw new Error(e);
    }

    if (opt.devDependencies && typeof fileJson.devDependencies === "object") {
        deps = deps.concat(Object.keys(fileJson.devDependencies));
    }
    if (opt.dependencies && typeof fileJson.dependencies === "object") {
        deps = deps.concat(Object.keys(fileJson.dependencies));
    }
    return packages.reduce((status, pkg) => {
        status[pkg] = deps.indexOf(pkg) !== -1;
        return status;
    }, {});
}

/**
 * Check whether node modules are included in the dependencies of a project's
 * package.json.
 *
 * Convienience wrapper around check().
 *
 * @param   {string[]} packages  Array of node modules to check.
 * @param   {string}   rootDir   The directory contianing a package.json
 * @returns {Object}             An object whose keys are the module names
 *                               and values are booleans indicating installation.
 */
function checkDeps(packages, rootDir) {
    return check(packages, { dependencies: true, startDir: rootDir });
}

/**
 * Check whether node modules are included in the devDependencies of a project's
 * package.json.
 *
 * Convienience wrapper around check().
 *
 * @param   {string[]} packages  Array of node modules to check.
 * @returns {Object}             An object whose keys are the module names
 *                               and values are booleans indicating installation.
 */
function checkDevDeps(packages) {
    return check(packages, { devDependencies: true });
}

/**
 * Check whether package.json is found in current path.
 *
 * @param   {string=} startDir Starting directory
 * @returns {boolean} Whether a package.json is found in current path.
 */
function checkPackageJson(startDir) {
    return !!findPackageJson(startDir);
}

//------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------

module.exports = {
    installSyncSaveDev,
    fetchPeerDependencies,
    checkDeps,
    checkDevDeps,
    checkPackageJson
};


text:
# Webservice

[![Build Status](https://img.shields.io/travis/UseMuffin/Webservice/master.svg?style=flat-square)](https://github.com/UseMuffin/Webservice/actions?query=workflow%3ACI+branch%3Amaster)
[![Coverage](https://img.shields.io/codecov/c/github/UseMuffin/Webservice/master.svg?style=flat-square)](https://codecov.io/github/UseMuffin/Webservice)
[![Total Downloads](https://img.shields.io/packagist/dt/muffin/webservice.svg?style=flat-square)](https://packagist.org/packages/muffin/webservice)
[![License](https://img.shields.io/badge/license-MIT-blue.svg?style=flat-square)](LICENSE)

Bringing the power of the CakePHP ORM to your favourite webservices.

## Install

Using [Composer][composer]:

```
composer require muffin/webservice
```

You then need to load the plugin. You can use the shell command:

```
bin/cake plugin load Muffin/Webservice
```

## Usage

### Datasource Configuration

In your `app.php`, add a new `webservice` config under `Datasources`:

```php
    'Datasources' => [
        // Other db config here
        'webservice' => [
            'className' => \Muffin\Webservice\Datasource\Connection::class,
            'service' => 'Articles',
            // Any additional keys will be set as Driver's config.
        ],
    ],
```

If you are making a plugin then conventionally the datasource config key name
should be underscored version of plugin name.

### As an ORM

#### Create driver

```php
<?php
namespace App\Webservice\Driver;

use Cake\Http\Client;
use Muffin\Webservice\Driver\AbstractDriver;

class Articles extends AbstractDriver
{
    /**
     * Initialize is used to easily extend the constructor.
     */
    public function initialize(): void
    {
        $this->setClient(new Client([
            'host' => 'example.com'
        ]));
    }
}
```

#### Create a webservice

```php
<?php
namespace App\Webservice;

use Muffin\Webservice\Datasource\Query;
use Muffin\Webservice\Datasource\ResultSet;
use Muffin\Webservice\Webservice\Webservice;

class ArticlesWebservice extends Webservice
{
    /**
     * Executes a query with the read action using the Cake HTTP Client
     */
    protected function _executeReadQuery(Query $query, array $options = [])
    {
        $response = $this->getDriver()->getClient()->get('/articles.json');

        if (!$response->isOk()) {
            return false;
        }

        $resources = $this->_transformResults($query->endpoint(), $response->json['articles']);

        return new ResultSet($resources, count($resources));
    }
}
```

#### Create an endpoint (optional)

```php
<?php
namespace App\Model\Endpoint;

use Muffin\Webservice\Model\Endpoint;

class ArticlesEndpoint extends Endpoint
{
}
```

#### Create a resource (optional)

```php
<?php
namespace App\Model\Resource;

use Muffin\Webservice\Model\Resource;

class Article extends Resource
{
}
```

#### Use it

```php
<?php
namespace App\Controller;

use Muffin\Webservice\Model\EndpointLocator;

class ArticlesController extends AppController
{
    // Either set the default model type to "Endpoint" or explicitly specify
    // model type in loadModel() call as shown below.
    protected $_modelType = 'Endpoint';

    public function index()
    {
        // This is required only if you haven't set `$_modelType` property to
        // "Endpoint" as shown above.
        $this->loadModel('Articles', 'Endpoint');

        $articles = $this->Articles->find();
    }
}
```

### As base for a driver

You can also use this plugin as a base to a separate plugin or to manage custom webservice
drivers connections.

Until official documentation is written, [David Yell][1] wrote a good [post to get you started][2].

[1]:https://github.com/davidyell
[2]:https://github.com/davidyell/davidyell.github.com/blob/source/_posts/2015-09-11-connecting-to-a-web-service.markdown

## Implementations of webservices

### As an ORM

The following plugins use the Webservice ORM to give you easy access to all kinds of webservices:

- [GitHub plugin](https://github.com/cvo-technologies/cakephp-github) - Provides access to the GitHub REST APIs.
- [NS plugin](https://github.com/Qarox/cakephp-nsapi) - Provides access to the NS (Nederlandse Spoorwegen) APIs.
- [Stagemarkt plugin](https://github.com/ICT-College/cakephp-stagemarkt) - Provides access to the SBB Stagemarkt REST APIs.
- [Twitter plugin](https://github.com/cvo-technologies/cakephp-twitter) - Provides access to the Twitter REST and streaming APIs.

### As a driver

The following plugins implement a Webservice driver with their own methods:

- [GitHub plugin](https://github.com/UseMuffin/Github) - Provides access to the GitHub REST APIs.
- [Pusher plugin](https://github.com/UseMuffin/Pusher) - Provides access to the Pusher APIs.
- [TMDB plugin](https://github.com/drmonkeyninja/cakephp-tmdb) - Provides access to the TMDB APIs.

## Patches & Features

* Fork
* Mod, fix
* Test - this is important, so it's not unintentionally broken
* Commit - do not mess with license, todo, version, etc. (if you do change any, bump them into commits of
their own that I can ignore when I pull)
* Pull request - bonus point for topic branches

To ensure your PRs are considered for upstream, you MUST follow the CakePHP coding standards.

## Bugs & Feedback

http://github.com/usemuffin/webservice/issues

## License

Copyright (c) 2015-Present, [Use Muffin] and licensed under [The MIT License][mit].

[cakephp]:http://cakephp.org
[composer]:http://getcomposer.org
[mit]:http://www.opensource.org/licenses/mit-license.php
[muffin]:http://usemuffin.com

redpajama_set_name: RedPajamaGithub


text:
package net.kemitix.itunes.medialibrary;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

@Repository
class ItemDao extends LibraryDao<Item> {

    private final String SELECT_ALL_SQL = "select * from item";
    private final String SELECT_BY_ID = "select * from item where item_pid = ?";

    @Autowired
    public ItemDao(JdbcTemplate jdbcTemplate, RowMapper<Item> rowMapper) {
        super(jdbcTemplate, rowMapper);
    }

    @Override
    String getSelectAllSql() {
        return SELECT_ALL_SQL;
    }

    @Override
    String getSelectByIdSql() {
        return SELECT_BY_ID;
    }

}


text:
<?php

namespace Magento\Payment\Gateway;

use Magento\Payment\Gateway\Command\CommandException;

/**
 * Interface CommandInterface
 * @package Magento\Payment\Gateway
 * @api
 */
interface CommandInterface
{
    /**
     * Executes command basing on business object
     *
     * @param array $commandSubject
     * @return null|Command\ResultInterface
     * @throws CommandException
     */
    public function execute(array $commandSubject);
}


text:
package net.floodlightcontroller.storage;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import net.floodlightcontroller.core.annotations.LogMessageCategory;
import net.floodlightcontroller.core.annotations.LogMessageDoc;
import net.floodlightcontroller.core.module.FloodlightModuleContext;
import net.floodlightcontroller.core.module.FloodlightModuleException;
import net.floodlightcontroller.core.module.IFloodlightModule;
import net.floodlightcontroller.core.module.IFloodlightService;
import net.floodlightcontroller.counter.ICounter;
import net.floodlightcontroller.counter.CounterStore;
import net.floodlightcontroller.counter.ICounterStoreService;
import net.floodlightcontroller.counter.CounterValue.CounterType;
import net.floodlightcontroller.restserver.IRestApiService;
import net.floodlightcontroller.storage.web.StorageWebRoutable;

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

@LogMessageCategory("System Database")
public abstract class AbstractStorageSource
    implements IStorageSourceService, IFloodlightModule {
    protected static Logger logger = LoggerFactory.getLogger(AbstractStorageSource.class);

    // Shared instance of the executor to use to execute the storage tasks.
    // We make this a single threaded executor, because if we used a thread pool
    // then storage operations could be executed out of order which would cause
    // problems in some cases (e.g. delete and update of a row getting reordered).
    // If we wanted to make this more multi-threaded we could have multiple
    // worker threads/executors with affinity of operations on a given table
    // to a single worker thread. But for now, we'll keep it simple and just have
    // a single thread for all operations.
    protected static ExecutorService defaultExecutorService = Executors.newSingleThreadExecutor();

    protected final static String STORAGE_QUERY_COUNTER_NAME = "StorageQuery";
    protected final static String STORAGE_UPDATE_COUNTER_NAME = "StorageUpdate";
    protected final static String STORAGE_DELETE_COUNTER_NAME = "StorageDelete";

    protected Set<String> allTableNames = new CopyOnWriteArraySet<String>();
    protected ICounterStoreService counterStore;
    protected ExecutorService executorService = defaultExecutorService;
    protected IStorageExceptionHandler exceptionHandler;

    private Map<String, Set<IStorageSourceListener>> listeners =
        new ConcurrentHashMap<String, Set<IStorageSourceListener>>();

    // Our dependencies
    protected IRestApiService restApi = null;

    protected static final String DB_ERROR_EXPLANATION =
            "An unknown error occurred while executing asynchronous " +
            "database operation";

    @LogMessageDoc(level="ERROR",
            message="Failure in asynchronous call to executeQuery",
            explanation=DB_ERROR_EXPLANATION,
            recommendation=LogMessageDoc.GENERIC_ACTION)
    abstract class StorageCallable<V> implements Callable<V> {
        public V call() {
            try {
                return doStorageOperation();
            }
            catch (StorageException e) {
                logger.error("Failure in asynchronous call to executeQuery", e);
                if (exceptionHandler != null)
                    exceptionHandler.handleException(e);
                throw e;
            }
        }
        abstract protected V doStorageOperation();
    }

    @LogMessageDoc(level="ERROR",
            message="Failure in asynchronous call to updateRows",
            explanation=DB_ERROR_EXPLANATION,
            recommendation=LogMessageDoc.GENERIC_ACTION)
    abstract class StorageRunnable implements Runnable {
        public void run() {
            try {
                doStorageOperation();
            }
            catch (StorageException e) {
                logger.error("Failure in asynchronous call to updateRows", e);
                if (exceptionHandler != null)
                    exceptionHandler.handleException(e);
                throw e;
            }
        }
        abstract void doStorageOperation();
    }

    public AbstractStorageSource() {
        this.executorService = defaultExecutorService;
    }

    public void setExecutorService(ExecutorService executorService) {
        this.executorService = (executorService != null) ?
                executorService : defaultExecutorService;
    }

    @Override
    public void setExceptionHandler(IStorageExceptionHandler exceptionHandler) {
        this.exceptionHandler = exceptionHandler;
    }

    @Override
    public abstract void setTablePrimaryKeyName(String tableName, String primaryKeyName);

    @Override
    public void createTable(String tableName, Set<String> indexedColumns) {
        allTableNames.add(tableName);
    }

    @Override
    public Set<String> getAllTableNames() {
        return allTableNames;
    }

    public void setCounterStore(CounterStore counterStore) {
        this.counterStore = counterStore;
    }

    protected void updateCounters(String baseName, String tableName) {
        if (counterStore != null) {
            String counterName;
            if (tableName != null) {
                updateCounters(baseName, null);
                counterName = baseName + CounterStore.TitleDelimitor + tableName;
            } else {
                counterName = baseName;
            }
            ICounter counter = counterStore.getCounter(counterName);
            if (counter == null) {
                counter = counterStore.createCounter(counterName, CounterType.LONG);
            }
            counter.increment();
        }
    }

    @Override
    public abstract IQuery createQuery(String tableName, String[] columnNames,
            IPredicate predicate, RowOrdering ordering);

    @Override
    public IResultSet executeQuery(IQuery query) {
        updateCounters(STORAGE_QUERY_COUNTER_NAME, query.getTableName());
        return executeQueryImpl(query);
    }

    protected abstract IResultSet executeQueryImpl(IQuery query);

    @Override
    public IResultSet executeQuery(String tableName, String[] columnNames,
            IPredicate predicate, RowOrdering ordering) {
        IQuery query = createQuery(tableName, columnNames, predicate, ordering);
        IResultSet resultSet = executeQuery(query);
        return resultSet;
    }

    @Override
    public Object[] executeQuery(String tableName, String[] columnNames,
            IPredicate predicate, RowOrdering ordering, IRowMapper rowMapper) {
        List<Object> objectList = new ArrayList<Object>();
        IResultSet resultSet = executeQuery(tableName, columnNames, predicate, ordering);
        while (resultSet.next()) {
            Object object = rowMapper.mapRow(resultSet);
            objectList.add(object);
        }
        return objectList.toArray();
    }

    @Override
    public Future<IResultSet> executeQueryAsync(final IQuery query) {
        Future<IResultSet> future = executorService.submit(
            new StorageCallable<IResultSet>() {
                public IResultSet doStorageOperation() {
                    return executeQuery(query);
                }
            });
        return future;
    }

    @Override
    public Future<IResultSet> executeQueryAsync(final String tableName,
            final String[] columnNames,  final IPredicate predicate,
            final RowOrdering ordering) {
        Future<IResultSet> future = executorService.submit(
            new StorageCallable<IResultSet>() {
                public IResultSet doStorageOperation() {
                    return executeQuery(tableName, columnNames,
                            predicate, ordering);
                }
            });
        return future;
    }

    @Override
    public Future<Object[]> executeQueryAsync(final String tableName,
            final String[] columnNames,  final IPredicate predicate,
            final RowOrdering ordering, final IRowMapper rowMapper) {
        Future<Object[]> future = executorService.submit(
            new StorageCallable<Object[]>() {
                public Object[] doStorageOperation() {
                    return executeQuery(tableName, columnNames, predicate,
                            ordering, rowMapper);
                }
            });
        return future;
    }

    @Override
    public Future<?> insertRowAsync(final String tableName,
            final Map<String,Object> values) {
        Future<?> future = executorService.submit(
            new StorageRunnable() {
                public void doStorageOperation() {
                    insertRow(tableName, values);
                }
            }, null);
        return future;
    }

    @Override
    public Future<?> updateRowsAsync(final String tableName, final List<Map<String,Object>> rows) {
        Future<?> future = executorService.submit(
            new StorageRunnable() {
                public void doStorageOperation() {
                    updateRows(tableName, rows);
                }
            }, null);
        return future;
    }

    @Override
    public Future<?> updateMatchingRowsAsync(final String tableName,
            final IPredicate predicate, final Map<String,Object> values) {
        Future<?> future = executorService.submit(
            new StorageRunnable() {
                public void doStorageOperation() {
                    updateMatchingRows(tableName, predicate, values);
                }
            }, null);
        return future;
    }

    @Override
    public Future<?> updateRowAsync(final String tableName,
            final Object rowKey, final Map<String,Object> values) {
        Future<?> future = executorService.submit(
            new StorageRunnable() {
                public void doStorageOperation() {
                    updateRow(tableName, rowKey, values);
                }
            }, null);
        return future;
    }

    @Override
    public Future<?> updateRowAsync(final String tableName,
            final Map<String,Object> values) {
        Future<?> future = executorService.submit(
            new StorageRunnable() {
                public void doStorageOperation() {
                    updateRow(tableName, values);
                }
            }, null);
        return future;
    }

    @Override
    public Future<?> deleteRowAsync(final String tableName, final Object rowKey) {
        Future<?> future = executorService.submit(
            new StorageRunnable() {
                public void doStorageOperation() {
                    deleteRow(tableName, rowKey);
                }
            }, null);
        return future;
    }

    @Override
    public Future<?> deleteRowsAsync(final String tableName, final Set<Object> rowKeys) {
        Future<?> future = executorService.submit(
                new StorageRunnable() {
                    public void doStorageOperation() {
                        deleteRows(tableName, rowKeys);
                    }
                }, null);
        return future;
    }

    @Override
    public Future<?> deleteMatchingRowsAsync(final String tableName, final IPredicate predicate) {
        Future<?> future = executorService.submit(
                new StorageRunnable() {
                    public void doStorageOperation() {
                        deleteMatchingRows(tableName, predicate);
                    }
                }, null);
        return future;
    }

    @Override
    public Future<?> getRowAsync(final String tableName, final Object rowKey) {
        Future<?> future = executorService.submit(
            new StorageRunnable() {
                public void doStorageOperation() {
                    getRow(tableName, rowKey);
                }
            }, null);
        return future;
    }

    @Override
    public Future<?> saveAsync(final IResultSet resultSet) {
        Future<?> future = executorService.submit(
            new StorageRunnable() {
                public void doStorageOperation() {
                    resultSet.save();
                }
            }, null);
        return future;
    }

    @Override
    public void insertRow(String tableName, Map<String, Object> values) {
        updateCounters(STORAGE_UPDATE_COUNTER_NAME, tableName);
        insertRowImpl(tableName, values);
    }

    protected abstract void insertRowImpl(String tableName, Map<String, Object> values);

    @Override
    public void updateRows(String tableName, List<Map<String,Object>> rows) {
        updateCounters(STORAGE_UPDATE_COUNTER_NAME, tableName);
        updateRowsImpl(tableName, rows);
    }

    protected abstract void updateRowsImpl(String tableName, List<Map<String,Object>> rows);

    @Override
    public void updateMatchingRows(String tableName, IPredicate predicate,
            Map<String, Object> values) {
        updateCounters(STORAGE_UPDATE_COUNTER_NAME, tableName);
        updateMatchingRowsImpl(tableName, predicate, values);
    }

    protected abstract void updateMatchingRowsImpl(String tableName, IPredicate predicate,
                                    Map<String, Object> values);

    @Override
    public void updateRow(String tableName, Object rowKey,
            Map<String, Object> values) {
        updateCounters(STORAGE_UPDATE_COUNTER_NAME, tableName);
        updateRowImpl(tableName, rowKey, values);
    }

    protected abstract void updateRowImpl(String tableName, Object rowKey,
                                   Map<String, Object> values);

    @Override
    public void updateRow(String tableName, Map<String, Object> values) {
        updateCounters(STORAGE_UPDATE_COUNTER_NAME, tableName);
        updateRowImpl(tableName, values);
    }

    protected abstract void updateRowImpl(String tableName, Map<String, Object> values);

    @Override
    public void deleteRow(String tableName, Object rowKey) {
        updateCounters(STORAGE_DELETE_COUNTER_NAME, tableName);
        deleteRowImpl(tableName, rowKey);
    }

    protected abstract void deleteRowImpl(String tableName, Object rowKey);

    @Override
    public void deleteRows(String tableName, Set<Object> rowKeys) {
        updateCounters(STORAGE_DELETE_COUNTER_NAME, tableName);
        deleteRowsImpl(tableName, rowKeys);
    }

    protected abstract void deleteRowsImpl(String tableName, Set<Object> rowKeys);

    @Override
    public void deleteMatchingRows(String tableName, IPredicate predicate) {
        IResultSet resultSet = null;
        try {
            resultSet = executeQuery(tableName, null, predicate, null);
            while (resultSet.next()) {
                resultSet.deleteRow();
            }
            resultSet.save();
        }
        finally {
            if (resultSet != null)
                resultSet.close();
        }
    }

    @Override
    public IResultSet getRow(String tableName, Object rowKey) {
        updateCounters(STORAGE_QUERY_COUNTER_NAME, tableName);
        return getRowImpl(tableName, rowKey);
    }

    protected abstract IResultSet getRowImpl(String tableName, Object rowKey);

    @Override
    public synchronized void addListener(String tableName, IStorageSourceListener listener) {
        Set<IStorageSourceListener> tableListeners = listeners.get(tableName);
        if (tableListeners == null) {
            tableListeners = new CopyOnWriteArraySet<IStorageSourceListener>();
            listeners.put(tableName, tableListeners);
        }
        tableListeners.add(listener);
    }

    @Override
    public synchronized void removeListener(String tableName, IStorageSourceListener listener) {
        Set<IStorageSourceListener> tableListeners = listeners.get(tableName);
        if (tableListeners != null) {
            tableListeners.remove(listener);
        }
    }

    @LogMessageDoc(level="ERROR",
            message="Exception caught handling storage notification",
            explanation="An unknown error occured while trying to notify" +
            		" storage listeners",
            recommendation=LogMessageDoc.GENERIC_ACTION)
    protected synchronized void notifyListeners(StorageSourceNotification notification) {
        String tableName = notification.getTableName();
        Set<Object> keys = notification.getKeys();
        Set<IStorageSourceListener> tableListeners = listeners.get(tableName);
        if (tableListeners != null) {
            for (IStorageSourceListener listener : tableListeners) {
                try {
                    switch (notification.getAction()) {
                        case MODIFY:
                            listener.rowsModified(tableName, keys);
                            break;
                        case DELETE:
                            listener.rowsDeleted(tableName, keys);
                            break;
                    }
                }
                catch (Exception e) {
                    logger.error("Exception caught handling storage notification", e);
                }
            }
        }
    }

    @Override
    public void notifyListeners(List<StorageSourceNotification> notifications) {
        for (StorageSourceNotification notification : notifications)
            notifyListeners(notification);
    }

    // IFloodlightModule

    @Override
    public Collection<Class<? extends IFloodlightService>> getModuleServices() {
        Collection<Class<? extends IFloodlightService>> l =
                new ArrayList<Class<? extends IFloodlightService>>();
        l.add(IStorageSourceService.class);
        return l;
    }

    @Override
    public Map<Class<? extends IFloodlightService>,
               IFloodlightService> getServiceImpls() {
        Map<Class<? extends IFloodlightService>,
            IFloodlightService> m =
                new HashMap<Class<? extends IFloodlightService>,
                            IFloodlightService>();
        m.put(IStorageSourceService.class, this);
        return m;
    }

    @Override
    public Collection<Class<? extends IFloodlightService>> getModuleDependencies() {
        Collection<Class<? extends IFloodlightService>> l =
                new ArrayList<Class<? extends IFloodlightService>>();
        l.add(IRestApiService.class);
        l.add(ICounterStoreService.class);
        return l;
    }

    @Override
    public void init(FloodlightModuleContext context)
            throws FloodlightModuleException {
        restApi =
           context.getServiceImpl(IRestApiService.class);
        counterStore =
            context.getServiceImpl(ICounterStoreService.class);
    }

    @Override
    public void startUp(FloodlightModuleContext context) {
        restApi.addRestletRoutable(new StorageWebRoutable());
    }
}


text:
import { RadarWeather24 } from "../../";

export = RadarWeather24;


text:
#pragma once

#include <vector>
#include <set>

struct FlowEdge {
	int from;
	int to;
	int capacity;

    int getCost() const {
        return 0;
    }
};

struct CostFlowEdge {
	int from;
	int to;
	int capacity;
    int cost;

    int getCost() const {
        return cost;
    }
};

struct FlowResult {
	int flow;
    std::vector<FlowEdge> edges;
};

struct MinCostMaxFlowResult {
    int flow;
    int cost;
    std::vector<CostFlowEdge> edges;
};

struct MinCutEdgesResult {
	int cost;
    std::vector<FlowEdge> edges;
};

/*
 * Solve a flow problem using the Edmonds-Karp version of the Ford-Fulkerson algorithm.
 *
 * Runs in time O(|N|*|V|^2)
 */
FlowResult maxFlow(const std::vector<FlowEdge> &edges, int nr_of_nodes, int source, int sink);

/**
 * Finds the maximum flow between the source and the sink, using the cheapest possible edges to achieve this.
 *
 * Note that the total cost of the edges may not exceed 1000000, if they do, the solution is not guarenteed
 * to be correct.
 */
MinCostMaxFlowResult minCostMaxFlow(const std::vector<CostFlowEdge> &edges, int nr_of_nodes, int source, int sink);

/*
 * Find a minimal subset of edges that separates the source from the sink. The subset will be minimal
 * in respect to the sum of the weights of the edges.
 *
 * Runs in time O(|N|*|V|^2)
 */
MinCutEdgesResult minCutEdges(const std::vector<FlowEdge> &edges, int nr_of_nodes, int source, int sink);

/*
 * Find a subset of nodes that separates the source from the sink such that the sum of the edges
 * from the subset to the nodes not in the set is minimal.
 *
 * Runs in time O(|N|*|V|^2)
 */
std::set<int> minCutNodes(const std::vector<FlowEdge> &edges, int nr_of_nodes, int source, int sink);


text:
from typing import Dict, List, Optional, Union

import msrest.serialization

from ._azure_red_hat_open_shift4_client_enums import *

class APIServerProfile(msrest.serialization.Model):
    """APIServerProfile represents an API server profile.

    :ivar visibility: API server visibility (immutable). Possible values include: "Private",
     "Public".
    :vartype visibility: str or ~azure.mgmt.redhatopenshift.v2020_04_30.models.Visibility
    :ivar url: The URL to access the cluster API server (immutable).
    :vartype url: str
    :ivar ip: The IP of the cluster API server (immutable).
    :vartype ip: str
    """

    _attribute_map = {
        'visibility': {'key': 'visibility', 'type': 'str'},
        'url': {'key': 'url', 'type': 'str'},
        'ip': {'key': 'ip', 'type': 'str'},
    }

    def __init__(
        self,
        *,
        visibility: Optional[Union[str, "Visibility"]] = None,
        url: Optional[str] = None,
        ip: Optional[str] = None,
        **kwargs
    ):
        """
        :keyword visibility: API server visibility (immutable). Possible values include: "Private",
         "Public".
        :paramtype visibility: str or ~azure.mgmt.redhatopenshift.v2020_04_30.models.Visibility
        :keyword url: The URL to access the cluster API server (immutable).
        :paramtype url: str
        :keyword ip: The IP of the cluster API server (immutable).
        :paramtype ip: str
        """
        super(APIServerProfile, self).__init__(**kwargs)
        self.visibility = visibility
        self.url = url
        self.ip = ip

class CloudErrorBody(msrest.serialization.Model):
    """CloudErrorBody represents the body of a cloud error.

    :ivar code: An identifier for the error. Codes are invariant and are intended to be consumed
     programmatically.
    :vartype code: str
    :ivar message: A message describing the error, intended to be suitable for display in a user
     interface.
    :vartype message: str
    :ivar target: The target of the particular error. For example, the name of the property in
     error.
    :vartype target: str
    :ivar details: A list of additional details about the error.
    :vartype details: list[~azure.mgmt.redhatopenshift.v2020_04_30.models.CloudErrorBody]
    """

    _attribute_map = {
        'code': {'key': 'code', 'type': 'str'},
        'message': {'key': 'message', 'type': 'str'},
        'target': {'key': 'target', 'type': 'str'},
        'details': {'key': 'details', 'type': '[CloudErrorBody]'},
    }

    def __init__(
        self,
        *,
        code: Optional[str] = None,
        message: Optional[str] = None,
        target: Optional[str] = None,
        details: Optional[List["CloudErrorBody"]] = None,
        **kwargs
    ):
        """
        :keyword code: An identifier for the error. Codes are invariant and are intended to be consumed
         programmatically.
        :paramtype code: str
        :keyword message: A message describing the error, intended to be suitable for display in a user
         interface.
        :paramtype message: str
        :keyword target: The target of the particular error. For example, the name of the property in
         error.
        :paramtype target: str
        :keyword details: A list of additional details about the error.
        :paramtype details: list[~azure.mgmt.redhatopenshift.v2020_04_30.models.CloudErrorBody]
        """
        super(CloudErrorBody, self).__init__(**kwargs)
        self.code = code
        self.message = message
        self.target = target
        self.details = details

class ClusterProfile(msrest.serialization.Model):
    """ClusterProfile represents a cluster profile.

    :ivar pull_secret: The pull secret for the cluster (immutable).
    :vartype pull_secret: str
    :ivar domain: The domain for the cluster (immutable).
    :vartype domain: str
    :ivar version: The version of the cluster (immutable).
    :vartype version: str
    :ivar resource_group_id: The ID of the cluster resource group (immutable).
    :vartype resource_group_id: str
    """

    _attribute_map = {
        'pull_secret': {'key': 'pullSecret', 'type': 'str'},
        'domain': {'key': 'domain', 'type': 'str'},
        'version': {'key': 'version', 'type': 'str'},
        'resource_group_id': {'key': 'resourceGroupId', 'type': 'str'},
    }

    def __init__(
        self,
        *,
        pull_secret: Optional[str] = None,
        domain: Optional[str] = None,
        version: Optional[str] = None,
        resource_group_id: Optional[str] = None,
        **kwargs
    ):
        """
        :keyword pull_secret: The pull secret for the cluster (immutable).
        :paramtype pull_secret: str
        :keyword domain: The domain for the cluster (immutable).
        :paramtype domain: str
        :keyword version: The version of the cluster (immutable).
        :paramtype version: str
        :keyword resource_group_id: The ID of the cluster resource group (immutable).
        :paramtype resource_group_id: str
        """
        super(ClusterProfile, self).__init__(**kwargs)
        self.pull_secret = pull_secret
        self.domain = domain
        self.version = version
        self.resource_group_id = resource_group_id

class ConsoleProfile(msrest.serialization.Model):
    """ConsoleProfile represents a console profile.

    :ivar url: The URL to access the cluster console (immutable).
    :vartype url: str
    """

    _attribute_map = {
        'url': {'key': 'url', 'type': 'str'},
    }

    def __init__(
        self,
        *,
        url: Optional[str] = None,
        **kwargs
    ):
        """
        :keyword url: The URL to access the cluster console (immutable).
        :paramtype url: str
        """
        super(ConsoleProfile, self).__init__(**kwargs)
        self.url = url

class Display(msrest.serialization.Model):
    """Display represents the display details of an operation.

    :ivar provider: Friendly name of the resource provider.
    :vartype provider: str
    :ivar resource: Resource type on which the operation is performed.
    :vartype resource: str
    :ivar operation: Operation type: read, write, delete, listKeys/action, etc.
    :vartype operation: str
    :ivar description: Friendly name of the operation.
    :vartype description: str
    """

    _attribute_map = {
        'provider': {'key': 'provider', 'type': 'str'},
        'resource': {'key': 'resource', 'type': 'str'},
        'operation': {'key': 'operation', 'type': 'str'},
        'description': {'key': 'description', 'type': 'str'},
    }

    def __init__(
        self,
        *,
        provider: Optional[str] = None,
        resource: Optional[str] = None,
        operation: Optional[str] = None,
        description: Optional[str] = None,
        **kwargs
    ):
        """
        :keyword provider: Friendly name of the resource provider.
        :paramtype provider: str
        :keyword resource: Resource type on which the operation is performed.
        :paramtype resource: str
        :keyword operation: Operation type: read, write, delete, listKeys/action, etc.
        :paramtype operation: str
        :keyword description: Friendly name of the operation.
        :paramtype description: str
        """
        super(Display, self).__init__(**kwargs)
        self.provider = provider
        self.resource = resource
        self.operation = operation
        self.description = description

class IngressProfile(msrest.serialization.Model):
    """IngressProfile represents an ingress profile.

    :ivar name: The ingress profile name.  Must be "default" (immutable).
    :vartype name: str
    :ivar visibility: Ingress visibility (immutable). Possible values include: "Private", "Public".
    :vartype visibility: str or ~azure.mgmt.redhatopenshift.v2020_04_30.models.Visibility
    :ivar ip: The IP of the ingress (immutable).
    :vartype ip: str
    """

    _attribute_map = {
        'name': {'key': 'name', 'type': 'str'},
        'visibility': {'key': 'visibility', 'type': 'str'},
        'ip': {'key': 'ip', 'type': 'str'},
    }

    def __init__(
        self,
        *,
        name: Optional[str] = None,
        visibility: Optional[Union[str, "Visibility"]] = None,
        ip: Optional[str] = None,
        **kwargs
    ):
        """
        :keyword name: The ingress profile name.  Must be "default" (immutable).
        :paramtype name: str
        :keyword visibility: Ingress visibility (immutable). Possible values include: "Private",
         "Public".
        :paramtype visibility: str or ~azure.mgmt.redhatopenshift.v2020_04_30.models.Visibility
        :keyword ip: The IP of the ingress (immutable).
        :paramtype ip: str
        """
        super(IngressProfile, self).__init__(**kwargs)
        self.name = name
        self.visibility = visibility
        self.ip = ip

class MasterProfile(msrest.serialization.Model):
    """MasterProfile represents a master profile.

    :ivar vm_size: The size of the master VMs (immutable). Possible values include:
     "Standard_D2s_v3", "Standard_D4s_v3", "Standard_D8s_v3".
    :vartype vm_size: str or ~azure.mgmt.redhatopenshift.v2020_04_30.models.VMSize
    :ivar subnet_id: The Azure resource ID of the master subnet (immutable).
    :vartype subnet_id: str
    """

    _attribute_map = {
        'vm_size': {'key': 'vmSize', 'type': 'str'},
        'subnet_id': {'key': 'subnetId', 'type': 'str'},
    }

    def __init__(
        self,
        *,
        vm_size: Optional[Union[str, "VMSize"]] = None,
        subnet_id: Optional[str] = None,
        **kwargs
    ):
        """
        :keyword vm_size: The size of the master VMs (immutable). Possible values include:
         "Standard_D2s_v3", "Standard_D4s_v3", "Standard_D8s_v3".
        :paramtype vm_size: str or ~azure.mgmt.redhatopenshift.v2020_04_30.models.VMSize
        :keyword subnet_id: The Azure resource ID of the master subnet (immutable).
        :paramtype subnet_id: str
        """
        super(MasterProfile, self).__init__(**kwargs)
        self.vm_size = vm_size
        self.subnet_id = subnet_id

class NetworkProfile(msrest.serialization.Model):
    """NetworkProfile represents a network profile.

    :ivar pod_cidr: The CIDR used for OpenShift/Kubernetes Pods (immutable).
    :vartype pod_cidr: str
    :ivar service_cidr: The CIDR used for OpenShift/Kubernetes Services (immutable).
    :vartype service_cidr: str
    """

    _attribute_map = {
        'pod_cidr': {'key': 'podCidr', 'type': 'str'},
        'service_cidr': {'key': 'serviceCidr', 'type': 'str'},
    }

    def __init__(
        self,
        *,
        pod_cidr: Optional[str] = None,
        service_cidr: Optional[str] = None,
        **kwargs
    ):
        """
        :keyword pod_cidr: The CIDR used for OpenShift/Kubernetes Pods (immutable).
        :paramtype pod_cidr: str
        :keyword service_cidr: The CIDR used for OpenShift/Kubernetes Services (immutable).
        :paramtype service_cidr: str
        """
        super(NetworkProfile, self).__init__(**kwargs)
        self.pod_cidr = pod_cidr
        self.service_cidr = service_cidr

class Resource(msrest.serialization.Model):
    """Common fields that are returned in the response for all Azure Resource Manager resources.

    Variables are only populated by the server, and will be ignored when sending a request.

    :ivar id: Fully qualified resource ID for the resource. Ex -
     /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}.
    :vartype id: str
    :ivar name: The name of the resource.
    :vartype name: str
    :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or
     "Microsoft.Storage/storageAccounts".
    :vartype type: str
    """

    _validation = {
        'id': {'readonly': True},
        'name': {'readonly': True},
        'type': {'readonly': True},
    }

    _attribute_map = {
        'id': {'key': 'id', 'type': 'str'},
        'name': {'key': 'name', 'type': 'str'},
        'type': {'key': 'type', 'type': 'str'},
    }

    def __init__(
        self,
        **kwargs
    ):
        """
        """
        super(Resource, self).__init__(**kwargs)
        self.id = None
        self.name = None
        self.type = None

class TrackedResource(Resource):
    """The resource model definition for an Azure Resource Manager tracked top level resource which has 'tags' and a 'location'.

    Variables are only populated by the server, and will be ignored when sending a request.

    All required parameters must be populated in order to send to Azure.

    :ivar id: Fully qualified resource ID for the resource. Ex -
     /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}.
    :vartype id: str
    :ivar name: The name of the resource.
    :vartype name: str
    :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or
     "Microsoft.Storage/storageAccounts".
    :vartype type: str
    :ivar tags: A set of tags. Resource tags.
    :vartype tags: dict[str, str]
    :ivar location: Required. The geo-location where the resource lives.
    :vartype location: str
    """

    _validation = {
        'id': {'readonly': True},
        'name': {'readonly': True},
        'type': {'readonly': True},
        'location': {'required': True},
    }

    _attribute_map = {
        'id': {'key': 'id', 'type': 'str'},
        'name': {'key': 'name', 'type': 'str'},
        'type': {'key': 'type', 'type': 'str'},
        'tags': {'key': 'tags', 'type': '{str}'},
        'location': {'key': 'location', 'type': 'str'},
    }

    def __init__(
        self,
        *,
        location: str,
        tags: Optional[Dict[str, str]] = None,
        **kwargs
    ):
        """
        :keyword tags: A set of tags. Resource tags.
        :paramtype tags: dict[str, str]
        :keyword location: Required. The geo-location where the resource lives.
        :paramtype location: str
        """
        super(TrackedResource, self).__init__(**kwargs)
        self.tags = tags
        self.location = location

class OpenShiftCluster(TrackedResource):
    """OpenShiftCluster represents an Azure Red Hat OpenShift cluster.

    Variables are only populated by the server, and will be ignored when sending a request.

    All required parameters must be populated in order to send to Azure.

    :ivar id: Fully qualified resource ID for the resource. Ex -
     /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}.
    :vartype id: str
    :ivar name: The name of the resource.
    :vartype name: str
    :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or
     "Microsoft.Storage/storageAccounts".
    :vartype type: str
    :ivar tags: A set of tags. Resource tags.
    :vartype tags: dict[str, str]
    :ivar location: Required. The geo-location where the resource lives.
    :vartype location: str
    :ivar provisioning_state: The cluster provisioning state (immutable). Possible values include:
     "AdminUpdating", "Creating", "Deleting", "Failed", "Succeeded", "Updating".
    :vartype provisioning_state: str or
     ~azure.mgmt.redhatopenshift.v2020_04_30.models.ProvisioningState
    :ivar cluster_profile: The cluster profile.
    :vartype cluster_profile: ~azure.mgmt.redhatopenshift.v2020_04_30.models.ClusterProfile
    :ivar console_profile: The console profile.
    :vartype console_profile: ~azure.mgmt.redhatopenshift.v2020_04_30.models.ConsoleProfile
    :ivar service_principal_profile: The cluster service principal profile.
    :vartype service_principal_profile:
     ~azure.mgmt.redhatopenshift.v2020_04_30.models.ServicePrincipalProfile
    :ivar network_profile: The cluster network profile.
    :vartype network_profile: ~azure.mgmt.redhatopenshift.v2020_04_30.models.NetworkProfile
    :ivar master_profile: The cluster master profile.
    :vartype master_profile: ~azure.mgmt.redhatopenshift.v2020_04_30.models.MasterProfile
    :ivar worker_profiles: The cluster worker profiles.
    :vartype worker_profiles: list[~azure.mgmt.redhatopenshift.v2020_04_30.models.WorkerProfile]
    :ivar apiserver_profile: The cluster API server profile.
    :vartype apiserver_profile: ~azure.mgmt.redhatopenshift.v2020_04_30.models.APIServerProfile
    :ivar ingress_profiles: The cluster ingress profiles.
    :vartype ingress_profiles: list[~azure.mgmt.redhatopenshift.v2020_04_30.models.IngressProfile]
    """

    _validation = {
        'id': {'readonly': True},
        'name': {'readonly': True},
        'type': {'readonly': True},
        'location': {'required': True},
    }

    _attribute_map = {
        'id': {'key': 'id', 'type': 'str'},
        'name': {'key': 'name', 'type': 'str'},
        'type': {'key': 'type', 'type': 'str'},
        'tags': {'key': 'tags', 'type': '{str}'},
        'location': {'key': 'location', 'type': 'str'},
        'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
        'cluster_profile': {'key': 'properties.clusterProfile', 'type': 'ClusterProfile'},
        'console_profile': {'key': 'properties.consoleProfile', 'type': 'ConsoleProfile'},
        'service_principal_profile': {'key': 'properties.servicePrincipalProfile', 'type': 'ServicePrincipalProfile'},
        'network_profile': {'key': 'properties.networkProfile', 'type': 'NetworkProfile'},
        'master_profile': {'key': 'properties.masterProfile', 'type': 'MasterProfile'},
        'worker_profiles': {'key': 'properties.workerProfiles', 'type': '[WorkerProfile]'},
        'apiserver_profile': {'key': 'properties.apiserverProfile', 'type': 'APIServerProfile'},
        'ingress_profiles': {'key': 'properties.ingressProfiles', 'type': '[IngressProfile]'},
    }

    def __init__(
        self,
        *,
        location: str,
        tags: Optional[Dict[str, str]] = None,
        provisioning_state: Optional[Union[str, "ProvisioningState"]] = None,
        cluster_profile: Optional["ClusterProfile"] = None,
        console_profile: Optional["ConsoleProfile"] = None,
        service_principal_profile: Optional["ServicePrincipalProfile"] = None,
        network_profile: Optional["NetworkProfile"] = None,
        master_profile: Optional["MasterProfile"] = None,
        worker_profiles: Optional[List["WorkerProfile"]] = None,
        apiserver_profile: Optional["APIServerProfile"] = None,
        ingress_profiles: Optional[List["IngressProfile"]] = None,
        **kwargs
    ):
        """
        :keyword tags: A set of tags. Resource tags.
        :paramtype tags: dict[str, str]
        :keyword location: Required. The geo-location where the resource lives.
        :paramtype location: str
        :keyword provisioning_state: The cluster provisioning state (immutable). Possible values
         include: "AdminUpdating", "Creating", "Deleting", "Failed", "Succeeded", "Updating".
        :paramtype provisioning_state: str or
         ~azure.mgmt.redhatopenshift.v2020_04_30.models.ProvisioningState
        :keyword cluster_profile: The cluster profile.
        :paramtype cluster_profile: ~azure.mgmt.redhatopenshift.v2020_04_30.models.ClusterProfile
        :keyword console_profile: The console profile.
        :paramtype console_profile: ~azure.mgmt.redhatopenshift.v2020_04_30.models.ConsoleProfile
        :keyword service_principal_profile: The cluster service principal profile.
        :paramtype service_principal_profile:
         ~azure.mgmt.redhatopenshift.v2020_04_30.models.ServicePrincipalProfile
        :keyword network_profile: The cluster network profile.
        :paramtype network_profile: ~azure.mgmt.redhatopenshift.v2020_04_30.models.NetworkProfile
        :keyword master_profile: The cluster master profile.
        :paramtype master_profile: ~azure.mgmt.redhatopenshift.v2020_04_30.models.MasterProfile
        :keyword worker_profiles: The cluster worker profiles.
        :paramtype worker_profiles: list[~azure.mgmt.redhatopenshift.v2020_04_30.models.WorkerProfile]
        :keyword apiserver_profile: The cluster API server profile.
        :paramtype apiserver_profile: ~azure.mgmt.redhatopenshift.v2020_04_30.models.APIServerProfile
        :keyword ingress_profiles: The cluster ingress profiles.
        :paramtype ingress_profiles:
         list[~azure.mgmt.redhatopenshift.v2020_04_30.models.IngressProfile]
        """
        super(OpenShiftCluster, self).__init__(tags=tags, location=location, **kwargs)
        self.provisioning_state = provisioning_state
        self.cluster_profile = cluster_profile
        self.console_profile = console_profile
        self.service_principal_profile = service_principal_profile
        self.network_profile = network_profile
        self.master_profile = master_profile
        self.worker_profiles = worker_profiles
        self.apiserver_profile = apiserver_profile
        self.ingress_profiles = ingress_profiles

class OpenShiftClusterCredentials(msrest.serialization.Model):
    """OpenShiftClusterCredentials represents an OpenShift cluster's credentials.

    :ivar kubeadmin_username: The username for the kubeadmin user.
    :vartype kubeadmin_username: str
    :ivar kubeadmin_password: The password for the kubeadmin user.
    :vartype kubeadmin_password: str
    """

    _attribute_map = {
        'kubeadmin_username': {'key': 'kubeadminUsername', 'type': 'str'},
        'kubeadmin_password': {'key': 'kubeadminPassword', 'type': 'str'},
    }

    def __init__(
        self,
        *,
        kubeadmin_username: Optional[str] = None,
        kubeadmin_password: Optional[str] = None,
        **kwargs
    ):
        """
        :keyword kubeadmin_username: The username for the kubeadmin user.
        :paramtype kubeadmin_username: str
        :keyword kubeadmin_password: The password for the kubeadmin user.
        :paramtype kubeadmin_password: str
        """
        super(OpenShiftClusterCredentials, self).__init__(**kwargs)
        self.kubeadmin_username = kubeadmin_username
        self.kubeadmin_password = kubeadmin_password

class OpenShiftClusterList(msrest.serialization.Model):
    """OpenShiftClusterList represents a list of OpenShift clusters.

    :ivar value: The list of OpenShift clusters.
    :vartype value: list[~azure.mgmt.redhatopenshift.v2020_04_30.models.OpenShiftCluster]
    :ivar next_link: The link used to get the next page of operations.
    :vartype next_link: str
    """

    _attribute_map = {
        'value': {'key': 'value', 'type': '[OpenShiftCluster]'},
        'next_link': {'key': 'nextLink', 'type': 'str'},
    }

    def __init__(
        self,
        *,
        value: Optional[List["OpenShiftCluster"]] = None,
        next_link: Optional[str] = None,
        **kwargs
    ):
        """
        :keyword value: The list of OpenShift clusters.
        :paramtype value: list[~azure.mgmt.redhatopenshift.v2020_04_30.models.OpenShiftCluster]
        :keyword next_link: The link used to get the next page of operations.
        :paramtype next_link: str
        """
        super(OpenShiftClusterList, self).__init__(**kwargs)
        self.value = value
        self.next_link = next_link

class OpenShiftClusterUpdate(msrest.serialization.Model):
    """OpenShiftCluster represents an Azure Red Hat OpenShift cluster.

    :ivar tags: A set of tags. The resource tags.
    :vartype tags: dict[str, str]
    :ivar provisioning_state: The cluster provisioning state (immutable). Possible values include:
     "AdminUpdating", "Creating", "Deleting", "Failed", "Succeeded", "Updating".
    :vartype provisioning_state: str or
     ~azure.mgmt.redhatopenshift.v2020_04_30.models.ProvisioningState
    :ivar cluster_profile: The cluster profile.
    :vartype cluster_profile: ~azure.mgmt.redhatopenshift.v2020_04_30.models.ClusterProfile
    :ivar console_profile: The console profile.
    :vartype console_profile: ~azure.mgmt.redhatopenshift.v2020_04_30.models.ConsoleProfile
    :ivar service_principal_profile: The cluster service principal profile.
    :vartype service_principal_profile:
     ~azure.mgmt.redhatopenshift.v2020_04_30.models.ServicePrincipalProfile
    :ivar network_profile: The cluster network profile.
    :vartype network_profile: ~azure.mgmt.redhatopenshift.v2020_04_30.models.NetworkProfile
    :ivar master_profile: The cluster master profile.
    :vartype master_profile: ~azure.mgmt.redhatopenshift.v2020_04_30.models.MasterProfile
    :ivar worker_profiles: The cluster worker profiles.
    :vartype worker_profiles: list[~azure.mgmt.redhatopenshift.v2020_04_30.models.WorkerProfile]
    :ivar apiserver_profile: The cluster API server profile.
    :vartype apiserver_profile: ~azure.mgmt.redhatopenshift.v2020_04_30.models.APIServerProfile
    :ivar ingress_profiles: The cluster ingress profiles.
    :vartype ingress_profiles: list[~azure.mgmt.redhatopenshift.v2020_04_30.models.IngressProfile]
    """

    _attribute_map = {
        'tags': {'key': 'tags', 'type': '{str}'},
        'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
        'cluster_profile': {'key': 'properties.clusterProfile', 'type': 'ClusterProfile'},
        'console_profile': {'key': 'properties.consoleProfile', 'type': 'ConsoleProfile'},
        'service_principal_profile': {'key': 'properties.servicePrincipalProfile', 'type': 'ServicePrincipalProfile'},
        'network_profile': {'key': 'properties.networkProfile', 'type': 'NetworkProfile'},
        'master_profile': {'key': 'properties.masterProfile', 'type': 'MasterProfile'},
        'worker_profiles': {'key': 'properties.workerProfiles', 'type': '[WorkerProfile]'},
        'apiserver_profile': {'key': 'properties.apiserverProfile', 'type': 'APIServerProfile'},
        'ingress_profiles': {'key': 'properties.ingressProfiles', 'type': '[IngressProfile]'},
    }

    def __init__(
        self,
        *,
        tags: Optional[Dict[str, str]] = None,
        provisioning_state: Optional[Union[str, "ProvisioningState"]] = None,
        cluster_profile: Optional["ClusterProfile"] = None,
        console_profile: Optional["ConsoleProfile"] = None,
        service_principal_profile: Optional["ServicePrincipalProfile"] = None,
        network_profile: Optional["NetworkProfile"] = None,
        master_profile: Optional["MasterProfile"] = None,
        worker_profiles: Optional[List["WorkerProfile"]] = None,
        apiserver_profile: Optional["APIServerProfile"] = None,
        ingress_profiles: Optional[List["IngressProfile"]] = None,
        **kwargs
    ):
        """
        :keyword tags: A set of tags. The resource tags.
        :paramtype tags: dict[str, str]
        :keyword provisioning_state: The cluster provisioning state (immutable). Possible values
         include: "AdminUpdating", "Creating", "Deleting", "Failed", "Succeeded", "Updating".
        :paramtype provisioning_state: str or
         ~azure.mgmt.redhatopenshift.v2020_04_30.models.ProvisioningState
        :keyword cluster_profile: The cluster profile.
        :paramtype cluster_profile: ~azure.mgmt.redhatopenshift.v2020_04_30.models.ClusterProfile
        :keyword console_profile: The console profile.
        :paramtype console_profile: ~azure.mgmt.redhatopenshift.v2020_04_30.models.ConsoleProfile
        :keyword service_principal_profile: The cluster service principal profile.
        :paramtype service_principal_profile:
         ~azure.mgmt.redhatopenshift.v2020_04_30.models.ServicePrincipalProfile
        :keyword network_profile: The cluster network profile.
        :paramtype network_profile: ~azure.mgmt.redhatopenshift.v2020_04_30.models.NetworkProfile
        :keyword master_profile: The cluster master profile.
        :paramtype master_profile: ~azure.mgmt.redhatopenshift.v2020_04_30.models.MasterProfile
        :keyword worker_profiles: The cluster worker profiles.
        :paramtype worker_profiles: list[~azure.mgmt.redhatopenshift.v2020_04_30.models.WorkerProfile]
        :keyword apiserver_profile: The cluster API server profile.
        :paramtype apiserver_profile: ~azure.mgmt.redhatopenshift.v2020_04_30.models.APIServerProfile
        :keyword ingress_profiles: The cluster ingress profiles.
        :paramtype ingress_profiles:
         list[~azure.mgmt.redhatopenshift.v2020_04_30.models.IngressProfile]
        """
        super(OpenShiftClusterUpdate, self).__init__(**kwargs)
        self.tags = tags
        self.provisioning_state = provisioning_state
        self.cluster_profile = cluster_profile
        self.console_profile = console_profile
        self.service_principal_profile = service_principal_profile
        self.network_profile = network_profile
        self.master_profile = master_profile
        self.worker_profiles = worker_profiles
        self.apiserver_profile = apiserver_profile
        self.ingress_profiles = ingress_profiles

class Operation(msrest.serialization.Model):
    """Operation represents an RP operation.

    :ivar name: Operation name: {provider}/{resource}/{operation}.
    :vartype name: str
    :ivar display: The object that describes the operation.
    :vartype display: ~azure.mgmt.redhatopenshift.v2020_04_30.models.Display
    :ivar origin: Sources of requests to this operation.  Comma separated list with valid values
     user or system, e.g. "user,system".
    :vartype origin: str
    """

    _attribute_map = {
        'name': {'key': 'name', 'type': 'str'},
        'display': {'key': 'display', 'type': 'Display'},
        'origin': {'key': 'origin', 'type': 'str'},
    }

    def __init__(
        self,
        *,
        name: Optional[str] = None,
        display: Optional["Display"] = None,
        origin: Optional[str] = None,
        **kwargs
    ):
        """
        :keyword name: Operation name: {provider}/{resource}/{operation}.
        :paramtype name: str
        :keyword display: The object that describes the operation.
        :paramtype display: ~azure.mgmt.redhatopenshift.v2020_04_30.models.Display
        :keyword origin: Sources of requests to this operation.  Comma separated list with valid values
         user or system, e.g. "user,system".
        :paramtype origin: str
        """
        super(Operation, self).__init__(**kwargs)
        self.name = name
        self.display = display
        self.origin = origin

class OperationList(msrest.serialization.Model):
    """OperationList represents an RP operation list.

    :ivar value: List of operations supported by the resource provider.
    :vartype value: list[~azure.mgmt.redhatopenshift.v2020_04_30.models.Operation]
    :ivar next_link: The link used to get the next page of operations.
    :vartype next_link: str
    """

    _attribute_map = {
        'value': {'key': 'value', 'type': '[Operation]'},
        'next_link': {'key': 'nextLink', 'type': 'str'},
    }

    def __init__(
        self,
        *,
        value: Optional[List["Operation"]] = None,
        next_link: Optional[str] = None,
        **kwargs
    ):
        """
        :keyword value: List of operations supported by the resource provider.
        :paramtype value: list[~azure.mgmt.redhatopenshift.v2020_04_30.models.Operation]
        :keyword next_link: The link used to get the next page of operations.
        :paramtype next_link: str
        """
        super(OperationList, self).__init__(**kwargs)
        self.value = value
        self.next_link = next_link

class ServicePrincipalProfile(msrest.serialization.Model):
    """ServicePrincipalProfile represents a service principal profile.

    :ivar client_id: The client ID used for the cluster (immutable).
    :vartype client_id: str
    :ivar client_secret: The client secret used for the cluster (immutable).
    :vartype client_secret: str
    """

    _attribute_map = {
        'client_id': {'key': 'clientId', 'type': 'str'},
        'client_secret': {'key': 'clientSecret', 'type': 'str'},
    }

    def __init__(
        self,
        *,
        client_id: Optional[str] = None,
        client_secret: Optional[str] = None,
        **kwargs
    ):
        """
        :keyword client_id: The client ID used for the cluster (immutable).
        :paramtype client_id: str
        :keyword client_secret: The client secret used for the cluster (immutable).
        :paramtype client_secret: str
        """
        super(ServicePrincipalProfile, self).__init__(**kwargs)
        self.client_id = client_id
        self.client_secret = client_secret

class WorkerProfile(msrest.serialization.Model):
    """WorkerProfile represents a worker profile.

    :ivar name: The worker profile name.  Must be "worker" (immutable).
    :vartype name: str
    :ivar vm_size: The size of the worker VMs (immutable). Possible values include:
     "Standard_D2s_v3", "Standard_D4s_v3", "Standard_D8s_v3".
    :vartype vm_size: str or ~azure.mgmt.redhatopenshift.v2020_04_30.models.VMSize
    :ivar disk_size_gb: The disk size of the worker VMs.  Must be 128 or greater (immutable).
    :vartype disk_size_gb: int
    :ivar subnet_id: The Azure resource ID of the worker subnet (immutable).
    :vartype subnet_id: str
    :ivar count: The number of worker VMs.  Must be between 3 and 20 (immutable).
    :vartype count: int
    """

    _attribute_map = {
        'name': {'key': 'name', 'type': 'str'},
        'vm_size': {'key': 'vmSize', 'type': 'str'},
        'disk_size_gb': {'key': 'diskSizeGB', 'type': 'int'},
        'subnet_id': {'key': 'subnetId', 'type': 'str'},
        'count': {'key': 'count', 'type': 'int'},
    }

    def __init__(
        self,
        *,
        name: Optional[str] = None,
        vm_size: Optional[Union[str, "VMSize"]] = None,
        disk_size_gb: Optional[int] = None,
        subnet_id: Optional[str] = None,
        count: Optional[int] = None,
        **kwargs
    ):
        """
        :keyword name: The worker profile name.  Must be "worker" (immutable).
        :paramtype name: str
        :keyword vm_size: The size of the worker VMs (immutable). Possible values include:
         "Standard_D2s_v3", "Standard_D4s_v3", "Standard_D8s_v3".
        :paramtype vm_size: str or ~azure.mgmt.redhatopenshift.v2020_04_30.models.VMSize
        :keyword disk_size_gb: The disk size of the worker VMs.  Must be 128 or greater (immutable).
        :paramtype disk_size_gb: int
        :keyword subnet_id: The Azure resource ID of the worker subnet (immutable).
        :paramtype subnet_id: str
        :keyword count: The number of worker VMs.  Must be between 3 and 20 (immutable).
        :paramtype count: int
        """
        super(WorkerProfile, self).__init__(**kwargs)
        self.name = name
        self.vm_size = vm_size
        self.disk_size_gb = disk_size_gb
        self.subnet_id = subnet_id
        self.count = count


text:
============
Installation
============

At the command line::

    pip install mongoql-conv


text:
namespace Articulate.Controllers
{
    //TODO: http://issues.umbraco.org/issue/U4-2565
    public class ArticulateRichTextController : BlogPostControllerBase
    {
    }
}


text:
@class ANStorageModel;
@class ANStorageSectionModel;

@interface ANStorageLoader : NSObject

+ (id)itemAtIndexPath:(NSIndexPath*)indexPath inStorage:(ANStorageModel*)storage;
+ (NSIndexPath*)indexPathForItem:(id)item inStorage:(ANStorageModel*)storage;

+ (NSArray*)itemsInSection:(NSUInteger)sectionNumber inStorage:(ANStorageModel*)storage;
+ (NSArray*)indexPathArrayForItems:(NSArray*)items inStorage:(ANStorageModel*)storage;

+ (ANStorageSectionModel*)sectionAtIndex:(NSUInteger)sectionIndex inStorage:(ANStorageModel*)storage;

@end


text:
export const SUM='SUM';
export const PROGRESS='PROGRESS';


text:
package org.mamute.search;

import static org.apache.commons.lang.StringUtils.isEmpty;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.annotation.Nullable;
import javax.enterprise.inject.Vetoed;

import com.google.common.base.Joiner;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrInputDocument;
import org.mamute.model.Answer;
import org.mamute.model.Question;
import org.mamute.model.Tag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.base.Function;
import com.google.common.collect.Lists;

@Vetoed
public class SolrQuestionIndex implements QuestionIndex {
	private static final Logger LOGGER = LoggerFactory.getLogger(SolrQuestionIndex.class);
	private static final String SEARCH_QUERY = "(title:?)^5 OR (solution:?)^4 OR (description:?)^3 OR (answers:?)^2 OR (tags:?)";

	private SolrServer server;

	public SolrQuestionIndex(SolrServer server) {
		this.server = server;
	}

	@Override
	public void indexQuestion(Question question) {
		try {
			SolrInputDocument doc = toDoc(question);
			server.add(doc);
			server.commit();
			LOGGER.info("Question synced or updated: " + question);
		} catch (IOException | SolrServerException e) {
			throw new IndexException("Could not index Question [" + question.getId() + "]", e);
		}
	}

	@Override
	public void indexQuestionBatch(Collection<Question> questions) {
		try {
			List<SolrInputDocument> docs = new ArrayList<>();
			for (Question question : questions) {
				docs.add(toDoc(question));
				LOGGER.info("Question synced or updated(trying to): " + question);
			}
			server.add(docs);
			server.commit();
			LOGGER.info("Questions synced or updated with success");

		} catch (IOException | SolrServerException e) {
			List<Long> ids = Lists.transform(new ArrayList<Question>(questions), new Function<Question, Long>() {
				public Long apply(Question input) {
					return input.getId();
				}
			});
			throw new IndexException("Could not index a Question in the following list: " + ids, e);
		}
	}

	@Override
	public List<Long> find(String query, int maxResults) {
		try {
			if (isEmpty(query)) return new ArrayList<>();

			query = URLEncoder.encode(query.trim(), "utf-8");
			return query(SEARCH_QUERY.replaceAll("\\?", query), maxResults);
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException("Could not encode query " + query, e);
		}
	}

	@Override
	public void delete(Question question) {
		try {
			this.server.deleteById(question.getId().toString());
			this.server.commit();
		} catch (SolrServerException e) {
			throw new RuntimeException(e);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	private SolrInputDocument toDoc(Question q) {
		List<String> tagNames = Lists.transform(q.getTags(), new Function<Tag, String>() {
			@Nullable
			@Override
			public String apply(@Nullable Tag tag) {
				return tag.getName();
			}
		});

		SolrInputDocument doc = new SolrInputDocument();
		doc.addField("id", q.getId());
		doc.addField("title", q.getTitle());
		doc.addField("description", q.getMarkedDescription());
		doc.addField("tags", join(tagNames));

		String solution = null;
		List<String> answers = new ArrayList<>();
		for (Answer a : q.getAnswers()) {
			if (a.isSolution()) {
				solution = a.getDescription();
			} else {
				answers.add(a.getDescription());
			}
		}

		if (solution != null) {
			doc.addField("solution", solution);
		}
		if (answers.size() > 0) {
			doc.addField("answers", join(answers));
		}

		return doc;
	}

	private String join(List<String> list) {
		return Joiner.on(",").join(list);
	}

	private List<Long> query(String queryString, int maxResults) {
		LOGGER.debug(queryString);
		SolrQuery query = new SolrQuery(queryString).setRows(maxResults);
		QueryResponse rsp;
		try {
			rsp = server.query(query);
		} catch (SolrServerException e) {
			throw new IndexException("Could not query from index", e);
		}
		SolrDocumentList docs = rsp.getResults();

		List<Long> ids = new ArrayList<>();
		for (SolrDocument doc : docs) {
			ids.add(Long.parseLong((String) doc.getFieldValue("id")));
		}
		return ids;
	}

}


text:
#ifndef IVW_SYNC_CL_GL_H
#define IVW_SYNC_CL_GL_H

#include <modules/opencl/openclmoduledefine.h>
#include <modules/opencl/inviwoopencl.h>
#include <modules/opencl/buffer/bufferclgl.h>
#include <modules/opencl/image/imageclgl.h>
#include <modules/opencl/image/layerclgl.h>
#include <modules/opencl/volume/volumeclgl.h>

#ifdef CL_VERSION_1_1
#ifdef __APPLE__
#include <OpenCL/cl_gl_ext.h>
#else
#include <CL/cl_gl_ext.h>
#endif
#endif

namespace inviwo {

class IVW_MODULE_OPENCL_API SyncCLGL {
public:
    SyncCLGL(const cl::Context& context= OpenCL::getPtr()->getContext(), const cl::CommandQueue& queue = OpenCL::getPtr()->getQueue());
    ~SyncCLGL();

    /**
     * Added object will be enquired when calling aquireAllObject.
     * The added object will be released upon destruction of this SyncCLGL object.
     * @note aquireAllObjects need to be called to actually enquire the added object.
     * @param const BufferCLGL * object
     */
    void addToAquireGLObjectList(const BufferCLGL* object);
    /**
     * Added object will be enquired when calling aquireAllObject.
     * The added object will be released upon destruction of this SyncCLGL object.
     * @note aquireAllObjects need to be called to actually enquire the added object.
     * @param const LayerCLGL * object
     */
    void addToAquireGLObjectList(const LayerCLGL* object);
    /**
     * Currently only adds the color layer to the list of objects that
     * will be enquired when calling aquireAllObject.
     * The added object will be released upon destruction of this SyncCLGL object.
     * @note aquireAllObjects need to be called to actually enquire the added object.
     * @param const ImageCLGL * object
     */
    void addToAquireGLObjectList(const ImageCLGL* object);
    /**
     * Added object will be enquired when calling aquireAllObject.
     * The added object will be released upon destruction of this SyncCLGL object.
     * @note aquireAllObjects need to be called to actually enquire the added object.
     * @param const VolumeCLGL * object
     */
    void addToAquireGLObjectList(const VolumeCLGL* object);

    /**
     * Calls enqueueAcquireGLObjects on all previously added objects
     *
     * @note Do not call enqueueReleaseGLObjects on an added object as this
     * will be done upon destruction of this object.
     */
    void aquireAllObjects() const;

    /**
     * Release all added objects. Done automatically at destruction.
     * Will wait for provided events.
     */
    void releaseAllGLObjects(const std::vector<cl::Event>* waitForEvents = nullptr, cl::Event* event = nullptr);

protected:

    std::vector<cl::Memory> syncedObjects_;
#if defined(CL_VERSION_1_1)
    // TODO: Fix support for faster synchronization. See constructor
    //GLsync glFenceSync_;
    //cl::Event glSync_;
#endif
    std::unique_ptr< std::vector<cl::Event> > syncEvents_;
    const cl::Context& context_;
    const cl::CommandQueue& queue_;
};

}

#endif // IVW_SYNC_CL_GL_H


text:
package org.apache.jackrabbit.oak.jcr.security.user;

import java.security.Principal;
import java.util.Iterator;
import javax.jcr.RepositoryException;
import javax.jcr.Value;

import org.apache.jackrabbit.api.security.user.Authorizable;
import org.apache.jackrabbit.api.security.user.Group;
import org.apache.jackrabbit.api.security.user.UserManager;
import org.apache.jackrabbit.test.NotExecutableException;
import org.junit.Test;

/**
 * Tests for the query API exposed by {@link UserManager}.
 */
public class FindAuthorizablesRelativePathTest extends AbstractUserTest {

    private Principal p;
    private Group gr;

    private String relPath;
    private String relPath2;
    private String relPath3;

    @Override
    protected void setUp() throws Exception {
        super.setUp();

        p = getTestPrincipal();
        gr = userMgr.createGroup(p);

        Value[] vs = new Value[]{
                superuser.getValueFactory().createValue("v1"),
                superuser.getValueFactory().createValue("v2")
        };
        relPath = "relPath/" + propertyName1;
        relPath2 = "another/" + propertyName1;
        relPath3 = "relPath/child/" + propertyName1;
        gr.setProperty(relPath, vs);
        gr.setProperty(relPath2, vs);
        gr.setProperty(relPath3, superuser.getValueFactory().createValue("v3"));
        superuser.save();
    }

    @Override
    protected void tearDown() throws Exception {
        try {
            if (gr != null) {
                gr.remove();
                superuser.save();
            }
        } finally{
            super.tearDown();
        }
    }

    private static void assertSingleResult(Iterator<Authorizable> result, String expectedId) throws RepositoryException {
        assertTrue("expected result", result.hasNext());
        assertEquals(expectedId, result.next().getID());
        assertFalse("expected no more results", result.hasNext());
    }

    @Test
    public void testFindV1ByName() throws NotExecutableException, RepositoryException {
        // relPath = "prop1", v = "v1" -> should find the target group
        Iterator<Authorizable> result = userMgr.findAuthorizables(propertyName1, "v1");
        assertSingleResult(result, gr.getID());
    }

    @Test
    public void testFindV3ByName() throws NotExecutableException, RepositoryException {
        // relPath = "prop1", v = "v3" -> should find the target group
        Iterator<Authorizable> result = userMgr.findAuthorizables(propertyName1, "v3");
        assertSingleResult(result, gr.getID());
    }

    @Test
    public void testFindV1ByRelativePath() throws NotExecutableException, RepositoryException {
        // relPath = "relPath/prop1", v = "v1" -> should find the target group
        Iterator<Authorizable> result = userMgr.findAuthorizables(relPath, "v1");
        assertSingleResult(result, gr.getID());
    }

    @Test
    public void testFindV1ByAltRelativePath() throws NotExecutableException, RepositoryException {
        // relPath = "another/prop1", v = "v1" -> should find the target group
        Iterator<Authorizable> result = userMgr.findAuthorizables(relPath2, "v1");
        assertSingleResult(result, gr.getID());
    }

    @Test
    public void testFindV1AtGroupNode() throws NotExecutableException, RepositoryException {
        // relPath : "./prop1", v = "v1" -> should not find the target group
        Iterator<Authorizable> result = userMgr.findAuthorizables("./" + propertyName1, "v1");
        assertFalse("expected result", result.hasNext());
    }

    @Test
    public void testFindV3AtGroupNode() throws NotExecutableException, RepositoryException {
        // relPath : "./prop1", v = "v3" -> should not find the target group
        Iterator<Authorizable> result = userMgr.findAuthorizables("./" + propertyName1, "v3");
        assertFalse("expected result", result.hasNext());
    }
}


text:
/**
 * Autogenerated by renren-api2-generator 2013-07-05 11:01:59
 *
 * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
 *  @generated
 */
package com.renren.api.service;
import java.util.*;
/**
 *
 * 家乡
 */
public class HomeTown {

	/**
	 * 所在省份
	 */
	private String province;
	/**
	 * 所在城市
	 */
	private String city;
	public void setProvince(String province) {
		this.province = province;
	}
	public String getProvince() {
		return this.province;
	}
	public void setCity(String city) {
		this.city = city;
	}
	public String getCity() {
		return this.city;
	}
}


text:
<?php

if ( !is_loggedin() )
    header('location: /ce/login');

session_destroy();
header('location: /ce/login');


text:
class TestStructArray < Test::Unit::TestCase
  include Helper::Buildable

  def test_new
    fields = [
      Arrow::Field.new("score", Arrow::Int8DataType.new),
      Arrow::Field.new("enabled", Arrow::BooleanDataType.new),
    ]
    structs = [
      {
        "score" => -29,
        "enabled" => true,
      },
      {
        "score" => 2,
        "enabled" => false,
      },
      nil,
    ]
    struct_array1 = build_struct_array(fields, structs)

    data_type = Arrow::StructDataType.new(fields)
    nulls = Arrow::Buffer.new([0b11].pack("C*"))
    children = [
      Arrow::Int8Array.new(2, Arrow::Buffer.new([-29, 2].pack("C*")), nulls, 0),
      Arrow::BooleanArray.new(2, Arrow::Buffer.new([0b01].pack("C*")), nulls, 0),
    ]
    assert_equal(struct_array1,
                 Arrow::StructArray.new(data_type,
                                        3,
                                        children,
                                        Arrow::Buffer.new([0b011].pack("C*")),
                                        -1))
  end

  def test_fields
    fields = [
      Arrow::Field.new("score", Arrow::Int8DataType.new),
      Arrow::Field.new("enabled", Arrow::BooleanDataType.new),
    ]
    data_type = Arrow::StructDataType.new(fields)
    builder = Arrow::StructArrayBuilder.new(data_type)

    builder.append
    builder.get_field_builder(0).append(-29)
    builder.get_field_builder(1).append(true)

    builder.append
    builder.field_builders[0].append(2)
    builder.field_builders[1].append(false)

    array = builder.finish
    values = array.length.times.collect do |i|
      if i.zero?
        [
          array.get_field(0).get_value(i),
          array.get_field(1).get_value(i),
        ]
      else
        array.fields.collect do |field|
          field.get_value(i)
        end
      end
    end
    assert_equal([
                   [-29, true],
                   [2, false],
                 ],
                 values)
  end
end


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
	 "http://www.w3.org/TR/html4/strict.dtd">

	<meta http-equiv="content-type" content="text/html;charset=utf-8">

	<title>Example</title>

	<canvas id="example" width="800" height="500"></canvas>


text:
#import <Foundation/Foundation.h>

//! Project version number for Kanna.
FOUNDATION_EXPORT double KannaVersionNumber;

//! Project version string for Kanna.
FOUNDATION_EXPORT const unsigned char KannaVersionString[];

// In this header, you should import all the public headers of your framework using statements like #import <Kanna/PublicHeader.h>
#import "HTMLtree.h"
#import "xpath.h"
#import "xpathInternals.h"


text:
<?php

namespace dataBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\BirthdayType;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class periodeType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add(
                'dateDebut',
                BirthdayType::class,
                [
                    'widget'=> 'single_text',
                    'attr'=>[
                        'class'=>'datepicker'
                    ]
                ]
            )
            ->add(
                'dateFin',
                BirthdayType::class ,
                [
                    'widget'=> 'single_text',
                    'attr'=>[
                        'class'=>'datepicker'
                    ]
                ]
            )
        ;
    }

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'dataBundle\Entity\periode'
        ));
    }

    /**
     * {@inheritdoc}
     */
    public function getBlockPrefix()
    {
        return 'databundle_periode';
    }

}


text:
package org.codemucker.jmutate.generate.bean;

import org.apache.commons.configuration.Configuration;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.codemucker.jmutate.JMutateContext;
import org.codemucker.jmutate.SourceTemplate;
import org.codemucker.jmutate.ast.JType;
import org.codemucker.jmutate.generate.SmartConfig;
import org.codemucker.jmutate.generate.bean.CloneGenerator.CloneOptions;
import org.codemucker.jmutate.generate.model.pojo.PojoModel;
import org.codemucker.jmutate.generate.model.pojo.PropertyModel;
import org.codemucker.jpattern.bean.CloneMethod;
import org.codemucker.jpattern.generate.GenerateCloneMethod;

import com.google.inject.Inject;

/**
 * Generates the 'clone' method on pojos
 */
public class CloneGenerator extends AbstractBeanGenerator<GenerateCloneMethod,CloneOptions> {

	private static final Logger LOG = LogManager.getLogger(CloneGenerator.class);

	@Inject
	public CloneGenerator(JMutateContext ctxt) {
		super(ctxt,GenerateCloneMethod.class);
	}

	protected void generate(JType bean, SmartConfig config, PojoModel model,CloneOptions options) {

		if(options.isEnabled() && !bean.isAbstract()){
			String methodName = options.methodName;

			LOG.debug("adding method '" + methodName + "'");

			SourceTemplate clone = newSourceTemplate()
				.var("method.name", methodName)
				.var("b.type", options.getType().getSimpleName())
				.var("b.genericPart", options.getType().getGenericPartOrEmpty())
				.var("b.typeBounds", options.getType().getTypeBoundsOrEmpty())

				.pl("@" + CloneMethod.class.getName())
				.pl("public static ${b.typeBounds} ${b.type} ${method.name}(${b.type} bean){")
				.pl("if(bean == null){ return null;}")
				.pl("final ${b.type} clone = new ${b.type}();");

			for (PropertyModel property : model.getAllProperties()) {
				if(property.isSuperClassProperty() && !property.hasSetter() && !property.hasGetter()){
					continue;
				}
				if(!property.hasField() && (!property.hasSetter() || !property.hasGetter())){
					continue;
				}

				SourceTemplate t = clone
					.child()
				//	.var("p.name",property.getPropertyName())
					.var("f.name",property.getFieldName())
					.var("p.getter",property.getGetterName())
					.var("p.setter",property.getSetterName())
					.var("p.type",property.getType().getFullName())
					.var("p.concreteType",property.getConcreteType())
					.var("p.rawType",property.getType().getFullNameRaw())
					.var("p.genericPart",property.getType().getGenericPartOrEmpty());

				if(property.getType().isImmutable()){
					if(property.hasSetter() || property.hasField()){
						if(property.isSuperClassProperty()){
							t.pl("	clone.${p.setter}(bean.${p.getter}());");
						} else {
							if(property.hasField()){
								t.pl("	clone.${f.name} = bean.${f.name};");
							} else {
								t.pl("	clone.${p.setter}(bean.${p.getter}());");
							}
						}
					}
				} else if(property.getType().isArray()){
					if(property.isSuperClassProperty()){
						t.pl("	if(bean.${p.getter}() == null){");
						t.pl("		clone.${p.setter}(null);");
						t.pl("	} else {");
						t.pl("		${p.rawType}[] src = bean.${p.getter}();");
						t.pl("		${p.rawType}[] copy = new ${p.rawType}[src.length];");
						t.pl("		System.arraycopy(src,0,copy,0,src.length);");
						t.pl("		clone.${p.setter}(copy);");
						t.pl("	}");
					} else {
						t.pl("	if(bean.${f.name} == null){");
						t.pl("		clone.${f.name} = null;");
						t.pl("	} else {");
						t.pl("		clone.${f.name} = new ${p.rawType}[bean.${f.name}.length];");
						t.pl("		System.arraycopy(bean.${f.name},0,clone.${f.name},0,bean.${f.name}.length);");
						t.pl("	}");
					}
				} else if(property.getType().isIndexed()){
					if(property.isSuperClassProperty()){
						//TODO:add a safe copy util in here. codemucker.lang?
						t.pl("	clone.${p.setter}(bean.${p.getter}()} == null?null:new ${p.concreteType}${p.genericPart}(bean.${p.getter}());");
					} else {
						t.pl("	clone.${f.name} = bean.${f.name} == null?null:new ${p.concreteType}${p.genericPart}(bean.${f.name});");
					}
				} else {
			//		if(hasClassGotMethod(property.propertyTypeRaw, AString.matchingAntPattern("*newInstanceOf"))){
					//	t.pl("	clone.${f.name} = bean.${f.name} == null?null:${p.rawType}.newInstanceOf(bean.${f.name});");
				//	} else {
					if(property.isSuperClassProperty()){
						t.pl("	clone.${p.setter}(bean.${p.getter}());");
					} else {
						t.pl("	clone.${f.name} = bean.${f.name};");
					}
					//}
				}

				clone.add(t);
			}
			clone.pl("return clone;");

			clone.pl("}");

			addMethod(bean, clone.asMethodNodeSnippet(),options.isMarkGenerated());
		}
	}

	protected CloneOptions createOptionsFrom(Configuration config, JType type){
		return new CloneOptions(config,type);
	}

	public static class CloneOptions extends AbstractBeanOptions<GenerateCloneMethod> {

		public String methodName;

		public CloneOptions(Configuration config,JType type) {
			super(config,GenerateCloneMethod.class,type);
		}
	}
}


text:
function writemda32(X,fname)
writemda(X,fname,'float32');
end


text:
from instagram.client import InstagramAPI
import json
from datetime import datetime
import web
import urlparse

def get_insta():
    parameters = urlparse.parse_qs(web.ctx.query[1:])
    CLIENT_ID = 'something secret'
    CLIENT_SECRET = 'should have been in env variables'
    latitude = float(parameters['lat'][0])
    longitude = float(parameters['lng'][0])
    distance = int(parameters['distance'][0])
    count = int(parameters['count'][0])

    api = InstagramAPI(client_id=CLIENT_ID, client_secret=CLIENT_SECRET)
    results = api.media_search(
        lat=latitude, lng=longitude, count=count, distance=distance)

    total_pre_json = []

    for picture in results:
        pre_json = {}
        pre_json['created_time'] = (
            datetime.today().utcnow() - picture.created_time).days
        pre_json['username'] = picture.user.username
        pre_json['location_name'] = picture.location.name
        pre_json['latlng'] = {
            'lat': picture.location.point.latitude, 'lng': picture.location.point.longitude}
        pre_json['photo_url'] = picture.images['standard_resolution'].url
        pre_json['tags'] = [x.name for x in picture.tags]
        pre_json['comments'] = [
            ':'.join([x.user.username, x.text]) for x in picture.comments]
        total_pre_json.append(pre_json)

    return json.dumps(total_pre_json)


text:
export const goLogin=({commit},info)=>{
    commit('login',info)
}

export const goRegister=({commit},info)=>{
    commit('register',info);
}

export const logOut=({commit})=>{
    commit('logout');
    commit('clearList');
}

export const updateTitle=({commit},e)=>{
    commit('updateTitle',e.target.value);
}

export const updateContent=({commit},e)=>{
    commit('updateContent',e.target.value);
}

export const initList=({commit})=>{
    commit('initList');
}

export const addItem=({commit})=>{
    commit('addItem');
}

export const deleteItem=({commit},index)=>{
    commit('deleteItem',index);
}

export const completeItem=({commit},index)=>{
    commit('completeItem',index);
}

export const changeFilter=({commit},type)=>{
    commit('changeFilter',type);
}

export const goSearch=({commit},keywords)=>{
    commit('goSearch',keywords);
}

export const addTag=({commit},itemId)=>{
    commit('addTag',itemId)
}

export const updateTag=({commit},e)=>{
    commit('updateTag',e.target.value);
}