text:
#ifndef OSC_DOUBLE_H_
#define OSC_DOUBLE_H_

#include <osc/reader/types/OscValue.h>

/** Class representing an OSC-double. */
class OSC_API OscDouble : public OscValue
{
public:
	virtual bool toBoolean();
	virtual QByteArray toBytes();
	virtual char toChar();
	virtual double toDouble();
	virtual qint64 toLong();
	virtual Midi toMIDI();
	virtual RGBA toRGBA();
	virtual QString toString();
	virtual QDateTime toTimetag();

#ifndef BUILD_UNITTESTS
private:
#endif
	/**
	 * Build a new OscDouble from the given location in packet.
	 *
	 * @param pos
	 *            the double value position.
	 */
	OscDouble(ByteBuffer* packet, qint32 pos);

	/**
	 * Returns the double value.
	 *
	 * @return a double value.
	 */
	double get();

	friend class OscMessage;
};

#endif // OSC_DOUBLE_H_

redpajama_set_name: RedPajamaGithub


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.eas.client.model.store;

import com.eas.client.metadata.Field;
import com.eas.client.metadata.ForeignKeySpec;
import com.eas.client.metadata.Parameter;
import com.eas.client.metadata.PrimaryKeySpec;
import com.eas.client.model.Entity;
import com.eas.client.model.Model;
import com.eas.client.model.Relation;
import com.eas.client.model.visitors.ModelVisitor;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

/**
 *
 * @author mg
 * @param <E>
 * @param <M>
 */
public abstract class Model2XmlDom<E extends Entity<M, ?, E>, M extends Model<E, ?>> implements ModelVisitor<E, M> {

    protected final static String YES_STRING = "yes";
    protected final static String NO_STRING = "no";
    public final static String DATAMODEL_TAG_NAME = "datamodel";
    public final static String PARAMETER_TAG_NAME = "parameter";
    public final static String PARAMETERS_TAG_NAME = "parameters";
    public final static String ENTITY_TAG_NAME = "entity";
    public final static String FIELDS_ENTITY_TAG_NAME = "fieldsEntity";
    public final static String PARAMETERS_ENTITY_TAG_NAME = "parametersEntity";
    public final static String RELATION_TAG_NAME = "relation";
    public final static String LIGHT_RELATION_TAG_NAME = "lightRelation";
    public final static String PRIMARY_KEYS_TAG_NAME = "primaryKeys";
    public final static String FOREIGN_KEYS_TAG_NAME = "foreignKeys";
    public final static String PRIMARY_KEY_TAG_NAME = "primaryKey";
    public final static String FOREIGN_KEY_TAG_NAME = "foreignKey";
    // setup documents framework
    protected static DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    // declaring documents framework
    protected DocumentBuilder builder;
    protected Document doc;
    protected Node currentNode;

    protected Model2XmlDom() {
        super();
        try {
            // setup documents framework
            builder = factory.newDocumentBuilder();
        } catch (ParserConfigurationException ex) {
            builder = null;
            Logger.getLogger(Model2XmlDom.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    protected Document model2XmlDom(M aModel) {
        if (aModel != null && builder != null) {
            doc = builder.newDocument();
            doc.setXmlStandalone(true);
            currentNode = doc;
            aModel.accept((ModelVisitor<E, Model<E, ?>>)this);
            return doc;
        }
        return null;
    }

    public void reset() {
        doc = null;
        currentNode = null;
    }

    public void writeModel(M aModel) {
        if (aModel != null) {
            Element datamodelNode = doc.createElement(DATAMODEL_TAG_NAME);
            currentNode.appendChild(datamodelNode);
            currentNode = datamodelNode;
            writeEntities(aModel);
            writeRelations(aModel);
        }
    }

    protected void writeRelations(M aModel) {
        if (aModel.getRelations() != null) {
            aModel.getRelations().stream().forEach((relation) -> {
                relation.accept(this);
            });
        }
    }

    protected void writeEntities(M aModel) throws DOMException {
        if (aModel.getEntities() != null) {
            aModel.getEntities().values().stream().forEach((entity) -> {
                entity.accept(this);
            });
        }
    }
    public static final String NAME_ATTR_NAME = "name";
    public static final String DATASOURCE_NAMEE_ATTR_NAME = "Name";
    public static final String DATASOURCE_TITLE_ATTR_NAME = "Title";
    public static final String DESCRIPTION_ATTR_NAME = "description";
    public static final String TYPE_ATTR_NAME = "type";
    public static final String SIZE_ATTR_NAME = "size";
    public static final String SCALE_ATTR_NAME = "scale";
    public static final String PRECISION_ATTR_NAME = "precision";
    public static final String SIGNED_ATTR_NAME = "signed";
    public static final String NULLABLE_ATTR_NAME = "nullable";
    public static final String MODE_ATTR_NAME = "parameterMode";
    public static final String IS_PK_ATTR_NAME = "isPk";
    public static final String FK_TAG_NAME = "fk";
    public static final String SELECTION_FORM_TAG_NAME = "selectionForm";
    public static final String DEFAULT_VALUE_TAG_NAME = "defaultValue";
    public static final String CLASS_HINT_TAG_NAME = "classHint";

    @Override
    public void visit(Field aField) {
        if (aField != null) {
            Element node = doc.createElement(PARAMETER_TAG_NAME);
            currentNode.appendChild(node);

            node.setAttribute(NAME_ATTR_NAME, aField.getName());
            node.setAttribute(DESCRIPTION_ATTR_NAME, aField.getDescription());
            node.setAttribute(TYPE_ATTR_NAME, aField.getType());
            node.setAttribute(NULLABLE_ATTR_NAME, String.valueOf(aField.isNullable()));
            if (aField instanceof Parameter) {
                node.setAttribute(SELECTION_FORM_TAG_NAME, String.valueOf(((Parameter) aField).getSelectionForm()));

                Object ov = ((Parameter) aField).getDefaultValue();
                if (ov != null) {
                    Element dvNode = doc.createElement(DEFAULT_VALUE_TAG_NAME);
                    node.appendChild(dvNode);
                    dvNode.setAttribute(CLASS_HINT_TAG_NAME, ov.getClass().getSimpleName());
                    dvNode.setNodeValue(ov.toString());
                }
                node.setAttribute(MODE_ATTR_NAME, String.valueOf(((Parameter) aField).getMode()));
            }
            if (aField.isPk()) {
                node.setAttribute(IS_PK_ATTR_NAME, String.valueOf(aField.isPk()));
            }
            ForeignKeySpec lfk = aField.getFk();
            if (lfk != null) {
                Node lcurrentNode = currentNode;
                try {
                    currentNode = node;
                    visit(lfk.getReferee());
                } finally {
                    currentNode = lcurrentNode;
                }
            }
        }
    }
    public static final String ENTITY_ID_ATTR_NAME = "entityId";
    public static final String QUERY_ID_ATTR_NAME = "queryId";
    public static final String TABLE_DB_ID_ATTR_NAME = "tableDbId";
    public static final String TABLE_SCHEMA_NAME_ATTR_NAME = "tableSchemaName";
    public static final String TABLE_NAME_ATTR_NAME = "tableName";
    public static final String ENTITY_TABLE_ALIAS = "tableAlias";
    public static final String ENTITY_LOCATION_X = "entityLocationX";
    public static final String ENTITY_LOCATION_Y = "entityLocationY";
    public static final String ENTITY_SIZE_WIDTH = "entityWidth";
    public static final String ENTITY_SIZE_HEIGHT = "entityHeight";
    public static final String ENTITY_ICONIFIED = "entityIconified";

    protected void writeEntityDesignAttributes(Element node, E entity) {
        node.setAttribute(ENTITY_LOCATION_X, String.valueOf(entity.getX()));
        node.setAttribute(ENTITY_LOCATION_Y, String.valueOf(entity.getY()));
        node.setAttribute(ENTITY_SIZE_WIDTH, String.valueOf(entity.getWidth()));
        node.setAttribute(ENTITY_SIZE_HEIGHT, String.valueOf(entity.getHeight()));
        node.setAttribute(ENTITY_ICONIFIED, String.valueOf(entity.isIconified()));
    }
    public static final String LEFT_ENTITY_ID_ATTR_NAME = "leftEntityId";
    public static final String LEFT_ENTITY_FIELD_ATTR_NAME = "leftEntityFieldName";
    public static final String LEFT_ENTITY_PARAMETER_ATTR_NAME = "leftEntityParameterName";
    public static final String RIGHT_ENTITY_ID_ATTR_NAME = "rightEntityId";
    public static final String RIGHT_ENTITY_FIELD_ATTR_NAME = "rightEntityFieldName";
    public static final String RIGHT_ENTITY_PARAMETER_ATTR_NAME = "rightEntityParameterName";
    public static final String POLYLINE_ATTR_NAME = "polyline";

    @Override
    public void visit(Relation<E> aRelation) {
        writeRelation(aRelation, doc.createElement(RELATION_TAG_NAME));
    }

    protected void writeRelation(Relation<E> relation, Element node) {
        if (relation != null && relation.getLeftField() != null && relation.getRightField() != null) {
            currentNode.appendChild(node);
            assert relation.getLeftEntity() != null : " A relation without left side detected";
            node.setAttribute(LEFT_ENTITY_ID_ATTR_NAME, String.valueOf(relation.getLeftEntity().getEntityId()));
            if (relation.isLeftField()) {
                node.setAttribute(LEFT_ENTITY_FIELD_ATTR_NAME, relation.getLeftField().getName());
            } else {
                node.setAttribute(LEFT_ENTITY_PARAMETER_ATTR_NAME, relation.getLeftParameter().getName());
            }

            assert relation.getRightEntity() != null : " A relation without right side detected";
            node.setAttribute(RIGHT_ENTITY_ID_ATTR_NAME, String.valueOf(relation.getRightEntity().getEntityId()));
            if (relation.isRightField()) {
                node.setAttribute(RIGHT_ENTITY_FIELD_ATTR_NAME, relation.getRightField().getName());
            } else {
                node.setAttribute(RIGHT_ENTITY_PARAMETER_ATTR_NAME, relation.getRightParameter().getName());
            }
            if (relation.getXs() != null && relation.getYs() != null && relation.getXs().length == relation.getYs().length) {
                node.setAttribute(POLYLINE_ATTR_NAME, polylineToString(relation));
            }
        }
    }

    private String polylineToString(Relation<E> relation) {
        if (relation.getXs() != null && relation.getYs() != null && relation.getXs().length == relation.getYs().length) {
            StringBuilder sb = new StringBuilder();
            int[] xs = relation.getXs();
            int[] ys = relation.getYs();
            for (int i = 0; i < xs.length; i++) {
                if (i > 0) {
                    sb.append(" ");
                }
                sb.append(xs[i]).append(";").append(ys[i]);
            }
            return sb.toString();
        } else {
            return null;
        }
    }

    private void visit(PrimaryKeySpec pk) {
        if (pk != null) {
            Element node = doc.createElement(PRIMARY_KEY_TAG_NAME);
            currentNode.appendChild(node);
            if (pk.getCName() != null) {
                node.setAttribute(CONSTRAINT_NAME_ATTR_NAME, pk.getCName());
            }
            if (pk.getSchema() != null) {
                node.setAttribute(CONSTRAINT_SCHEMA_ATTR_NAME, pk.getSchema());
            }
            node.setAttribute(CONSTRAINT_TABLE_ATTR_NAME, pk.getTable());
            node.setAttribute(CONSTRAINT_FIELD_ATTR_NAME, pk.getField());
        }
    }
    //public static final String FIELD_NAME_ATTR_NAME = "updateRule";
    public static final String CONSTRAINT_NAME_ATTR_NAME = "name";
    public static final String CONSTRAINT_DBID_ATTR_NAME = "DbId";
    public static final String CONSTRAINT_SCHEMA_ATTR_NAME = "schema";
    public static final String CONSTRAINT_TABLE_ATTR_NAME = "table";
    public static final String CONSTRAINT_FIELD_ATTR_NAME = "field";
    /*
     *
     * WARNING! This is very useful code. It is not used because foreign key
     * information is serialized and deserialized within relations
     * serialization/deserialization.
     *
     *
     * private void visit(ForeignKeySpec fk) { if (fk != null) { Element node =
     * doc.createElement(FOREIGN_KEY_TAG_NAME);
     *
     * node.setAttribute(CONSTRAINT_NAME_ATTR_NAME, fk.getCName());
     * node.setAttribute(CONSTRAINT_SCHEMA_ATTR_NAME, fk.getSchema());
     * node.setAttribute(CONSTRAINT_TABLE_ATTR_NAME, fk.getTable());
     * node.setAttribute(CONSTRAINT_FIELD_ATTR_NAME, fk.getField());
     *
     * node.setAttribute(DEFERRABLE_ATTR_NAME,
     * String.valueOf(fk.getFkDeferrable()));
     * node.setAttribute(DELETE_ATTR_NAME,
     * String.valueOf(fk.getFkDeleteRule()));
     * node.setAttribute(UPDATE_ATTR_NAME,
     * String.valueOf(fk.getFkUpdateRule()));
     *
     * currentNode.appendChild(node); PrimaryKeySpec pk = fk.getReferee(); if
     * (pk != null) { Node lcurrentNode = currentNode; try { currentNode = node;
     * visit(pk); } finally { currentNode = lcurrentNode; } } } }
     */
    public static final String DATAMODEL_DB_ID = "datamodelDbId";
    public static final String DATAMODEL_DB_SCHEMA_NAME = "datamodelSchemaName";
    public static final String DATAMODEL_DATASOURCE = "datasource";
    public static final String DATAMODEL_DATASOURCE_SCHEMA_NAME = "schema";
}


text:
<setup>
    <block title="Welcome to the Flurry App">
        <text><![CDATA[
To start indexing Flurry event logs:

1. Provide Flurry credentials below.

2. For the "Extraction Position", enter the earliest date containing events you
   wish to download.

3. Enable the Flurry scripted input below.

        ]]></text>
    </block>

    <block title="Edit Flurry Account Info" endpoint="configs/conf-extract" entity="auth">
        <input field="email">
            Email
            <type>text</type>
        </input>
        <input field="password">
            Password
            <type>password</type>
        </input>
        <input field="project_id">
            Project ID**
            <type>text</type>
        </input>
    </block>
    <block title="">
        <text><![CDATA[

** The Project ID can be obtained by logging in to the Flurry dashboard, clicking
the name of the application you wish to monitor, and examining the dashboard's
URL. It should look something like:
<tt>https://dev.flurry.com/customDashboard.do?projectID=12345&dashboardId=22</tt>

        ]]></text>
    </block>

    <block title="Edit Extraction Position" endpoint="configs/conf-extract" entity="extract_position">
        <input field="year">
            Year (YYYY)
            <type>text</type>
        </input>
        <input field="month">
            Month (MM)
            <type>text</type>
        </input>
        <input field="day">
            Day (DD)
            <type>text</type>
        </input>
        <input field="offset">
            Offset**
            <type>text</type>
        </input>
        <input field="session">
            Next Session ID [Advanced]
            <type>text</type>
        </input>
    </block>
    <block title="">
        <text><![CDATA[

** When changing the Day, also set the Offset to 0.

        ]]></text>
    </block>

    <block title="Edit Rate Limiting Delays [Advanced]" endpoint="configs/conf-extract" entity="rate_limiting">
        <input field="delay_per_request">
            Delay Between Requests (seconds)
            <type>text</type>
        </input>
        <input field="delay_per_overlimit">
            Delay After "Rate Limited" Warning (seconds)
            <type>text</type>
        </input>
    </block>

    <block title="Enable Flurry Input" endpoint="data/inputs/script" enabled="in-unix" entity=".%252Fbin%252Fextract.py">
        <input field="interval">
            Restart Interval (sec)
            <type>text</type>
        </input>
        <input field="enabled">
            Enable
            <type>bool</type>
        </input>
    </block>

    <block title="Enable Flurry Input" endpoint="data/inputs/script" enabled="in-windows" entity=".%5Cbin%5Cextract.py">
        <input field="interval">
            Restart Interval (sec)
            <type>text</type>
        </input>
        <input field="enabled">
            Enable
            <type>bool</type>
        </input>
    </block>
</setup>


text:
<?php
declare(strict_types = 1);
/**
 * /tests/bootstrap.php
 *
 * Bootstrap for PHPUnit tests, basically we need to do following things:
 *  1) Load test environment variables
 *  2) Boot kernel and create console application with that
 *  3) Drop test environment database
 *  4) Create empty database to test environment
 *  5) Run migrations to test database
 *  6) Load fixture date to database
 *  7) Write cache files about database initialization
 *
 * @package App\Tests
 * @author TLe, Tarmo Leppänen <tarmo.leppanen@protacon.com>
 */

use App\Kernel;
use App\Utils\JSON;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Output\ConsoleOutput;
use Symfony\Component\Dotenv\Dotenv;
use Symfony\Component\Filesystem\Filesystem;

require dirname(__DIR__) . '/vendor/autoload.php';

/**
 * Function to make necessary initialization for `fastest` - This means that we
 * need to set `DATABASE_URL` environment variable, before we initialize `DotEnv`
 * component for testing environment.
 *
 * @throws Throwable
 */
$InitializeFastestEnvironmentVariables = static function (string $readableChannel): void {
    static $cache = [];

    if (!array_key_exists($readableChannel, $cache)) {
        // Parse current environment file
        $variables = (new Dotenv())->parse((string)file_get_contents(dirname(__DIR__) . '/.env.test'));

        $configuration = JSON::decode((string)file_get_contents($variables['APPLICATION_CONFIG']), true);

        if (!is_array($configuration) || !array_key_exists('DATABASE_URL', $configuration)) {
            throw new RuntimeException('Cannot get `DATABASE_URL from specified env file.');
        }

        $originalDatabaseUrl = $configuration['DATABASE_URL'];

        $databaseName = trim(((array)parse_url($originalDatabaseUrl))['path'] ?? '', '/');

        // Replace DATABASE_URL variable with proper database name
        $databaseUrl = str_replace(
            '/' . $databaseName . '?',
            '/' . $databaseName . '_' . $readableChannel . '?',
            $originalDatabaseUrl
        );

        $cache[$readableChannel] = $databaseUrl;
    }

    // And finally populate new variables to current environment
    putenv('DATABASE_URL=' . $cache[$readableChannel]);
};

/**
 * Function to initialize test environment for use
 */
$InitializeEnvironment = static function (): void {
    $localPhpEnvFile = dirname(__DIR__) . '/.env.local.php';

    /** @psalm-suppress UnresolvableInclude */
    $env = is_readable($localPhpEnvFile) ? include $localPhpEnvFile : null;

    // Load cached env vars if the .env.local.php file exists
    // Run "composer dump-env prod" to create it (requires symfony/flex >=1.2)
    if (is_array($env)
        && ($_SERVER['APP_ENV'] ?? $_ENV['APP_ENV'] ?? $env['APP_ENV'] ?? null) === ($env['APP_ENV'] ?? null)
    ) {
        foreach ($env as $k => $v) {
            $_ENV[$k] ??= (isset($_SERVER[$k]) && strncmp($k, 'HTTP_', 5) !== 0 ? $_SERVER[$k] : $v);
        }
    }

    // load all the .env files
    (new Dotenv())->loadEnv(dirname(__DIR__) . '/.env');

    /** @noinspection AdditionOperationOnArraysInspection */
    $_SERVER += $_ENV;
    $_SERVER['APP_ENV'] = $_ENV['APP_ENV'] = ($_SERVER['APP_ENV'] ?? $_ENV['APP_ENV'] ?? null) ?: 'dev';
    $_SERVER['APP_DEBUG'] ??= $_ENV['APP_DEBUG'] ?? $_SERVER['APP_ENV'] !== 'prod';

    $debug = (int)$_SERVER['APP_DEBUG'] || filter_var($_SERVER['APP_DEBUG'], FILTER_VALIDATE_BOOLEAN) ? '1' : '0';

    $_SERVER['APP_DEBUG'] = $_ENV['APP_DEBUG'] = $debug;
};

chdir(dirname(__DIR__));

$readableChannel = (string)getenv('ENV_TEST_CHANNEL_READABLE');

// Application is started against 'fastest' library, so we need to override database name manually
if (strlen($readableChannel) > 0) {
    $InitializeFastestEnvironmentVariables($readableChannel);
}

$InitializeEnvironment();

$databaseCacheFile = sprintf(
    '%s%stest_database_cache%s.json',
    sys_get_temp_dir(),
    DIRECTORY_SEPARATOR,
    (string)getenv('ENV_TEST_CHANNEL_READABLE')
);

// Oh yeah, database is already created we don't want to do any lifting anymore \o/
if (is_readable($databaseCacheFile) && (string)getenv('ENV_TEST_CHANNEL_READABLE') !== '') {
    return;
}

// Create and boot 'test' kernel
$kernel = new Kernel((string)getenv('APP_ENV'), (bool)getenv('APP_DEBUG'));
$kernel->boot();

// Create new application
$application = new Application($kernel);
$application->setAutoExit(false);

// Add the doctrine:database:drop command to the application and run it
$dropDatabaseDoctrineCommand = static function () use ($application): void {
    $input = new ArrayInput([
        'command' => 'doctrine:database:drop',
        '--force' => true,
        '--if-exists' => true,
    ]);

    $input->setInteractive(false);

    $application->run($input, new ConsoleOutput());
};

// Add the doctrine:database:create command to the application and run it
$createDatabaseDoctrineCommand = static function () use ($application): void {
    $input = new ArrayInput([
        'command' => 'doctrine:database:create',
    ]);

    $input->setInteractive(false);

    $application->run($input, new ConsoleOutput());
};

// Add the doctrine:schema:update command to the application and run it
$updateSchemaDoctrineCommand = static function () use ($application): void {
    $input = new ArrayInput([
        'command' => 'doctrine:migrations:migrate',
        '--no-interaction' => true,
    ]);

    $input->setInteractive(false);

    $application->run($input, new ConsoleOutput());
};

// Add the doctrine:fixtures:load command to the application and run it
$loadFixturesDoctrineCommand = static function () use ($application): void {
    $input = new ArrayInput([
        'command' => 'doctrine:fixtures:load',
        '--no-interaction' => true,
    ]);

    $input->setInteractive(false);

    $application->run($input, new ConsoleOutput());
};

// Ensure that we have "clean" JWT auth cache file
$createJwtAuthCache = static function (): void {
    // Specify used cache file
    $filename = sprintf(
        '%s%stest_jwt_auth_cache%s.json',
        sys_get_temp_dir(),
        DIRECTORY_SEPARATOR,
        (string)getenv('ENV_TEST_CHANNEL_READABLE')
    );

    // Remove existing cache if exists
    $fs = new Filesystem();
    $fs->remove($filename);
    unset($fs);

    // Create empty cache file
    file_put_contents($filename, '{}');
};

// Create database cache file
$createDatabaseCreateCache = static function () use ($databaseCacheFile): void {
    // Create database cache file
    file_put_contents($databaseCacheFile, '{"init": ' . (new DateTime())->format(DATE_RFC3339) . '}');
};

// And finally call each of initialize functions to make test environment ready
array_map(
    '\call_user_func',
    [
        $dropDatabaseDoctrineCommand,
        $createDatabaseDoctrineCommand,
        $updateSchemaDoctrineCommand,
        $loadFixturesDoctrineCommand,
        $createJwtAuthCache,
        $createDatabaseCreateCache,
    ]
);


text:
package stroom.monitoring.client;

import stroom.core.client.ContentManager;
import stroom.core.client.MenuKeys;
import stroom.core.client.presenter.MonitoringPlugin;
import stroom.job.client.presenter.JobPresenter;
import stroom.menubar.client.event.BeforeRevealMenubarEvent;
import stroom.security.client.api.ClientSecurityContext;
import stroom.security.shared.PermissionNames;
import stroom.svg.client.SvgPresets;
import stroom.widget.menu.client.presenter.IconMenuItem;

import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.web.bindery.event.shared.EventBus;

import javax.inject.Singleton;

@Singleton
public class JobListPlugin extends MonitoringPlugin<JobPresenter> {

    @Inject
    public JobListPlugin(final EventBus eventBus, final ContentManager eventManager,
                         final Provider<JobPresenter> presenterProvider, final ClientSecurityContext securityContext) {
        super(eventBus, eventManager, presenterProvider, securityContext);
    }

    @Override
    protected void addChildItems(final BeforeRevealMenubarEvent event) {
        if (getSecurityContext().hasAppPermission(PermissionNames.MANAGE_JOBS_PERMISSION)) {
            event.getMenuItems().addMenuItem(MenuKeys.MONITORING_MENU,
                    new IconMenuItem.Builder()
                            .priority(9)
                            .icon(SvgPresets.JOBS)
                            .text("Jobs")
                            .command(this::open)
                            .build());
        }
    }
}


text:
package com.mattvv.tips.auth;

import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.auth.oauth2.TokenResponse;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpTransport;
import com.google.inject.Singleton;
import java.io.IOException;
import java.util.HashMap;
import javax.inject.Inject;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.fasterxml.jackson.databind.ObjectMapper;

// [START example]
@WebServlet(name = "oauth", value = "/oauth")
@Singleton
public class OAuth extends HttpServlet {
  private static final String USERINFO_ENDPOINT
      = "https://www.googleapis.com/plus/v1/people/me/openIdConnect";

  private GoogleAuthorizationCodeFlow flow;
  private HttpTransport transport;

  public OAuth() {
    super();
  }

  @Inject
  OAuth(GoogleAuthorizationCodeFlow flow, HttpTransport transport) {
    super();
    this.flow = flow;
    this.transport = transport;
  }

  @Override
  public void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws IOException, ServletException {

    // Ensure that this is no request forgery going on, and that the user
    // sending us this connect request is the user that was supposed to.
    if (req.getSession().getAttribute("state") == null
        || !req.getParameter("state").equals(req.getSession().getAttribute("state"))) {
      resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
      resp.sendRedirect("/");
      return;
    }

    req.getSession().removeAttribute("state");     // Remove one-time use state.

    final TokenResponse tokenResponse =
        flow.newTokenRequest(req.getParameter("code"))
            .setRedirectUri(getServletContext().getInitParameter("tips.callback"))
            .execute();

    req.getSession().setAttribute("token", tokenResponse.toString()); // Keep track of the token.
    final Credential credential = flow.createAndStoreCredential(tokenResponse, null);
    final HttpRequestFactory requestFactory = transport.createRequestFactory(credential);

    final GenericUrl url = new GenericUrl(USERINFO_ENDPOINT);      // Make an authenticated request.
    final HttpRequest request = requestFactory.buildGetRequest(url);
    request.getHeaders().setContentType("application/json");

    final String jsonIdentity = request.execute().parseAsString();
    @SuppressWarnings("unchecked")
    HashMap<String, String> userIdResult =
        new ObjectMapper().readValue(jsonIdentity, HashMap.class);
    // From this map, extract the relevant profile info and store it in the session.
    req.getSession().setAttribute("userEmail", userIdResult.get("email"));
    req.getSession().setAttribute("userId", userIdResult.get("sub"));
    req.getSession().setAttribute("userImageUrl", userIdResult.get("picture"));
    resp.sendRedirect((String) req.getSession().getAttribute("loginDestination"));
  }
}


text:
> Execute a command with piped arguments.

- Main use:

`{{arguments}} | xargs {{command}}`

- Handle whitespace in arguments:

`{{arguments_null_terminated}} | xargs -0 {{command}}`

- Example: list unneeded packages with deborphan and remove them with apt-get:

`sudo deborphan | xargs sudo apt-get remove`


text:
from __future__ import print_function, division
import collections
from sympy import Matrix, Integer, sympify, Basic

class NDimArray(object):
    """

    Examples
    ========

    Create an N-dim array of zeros:

    >>> from sympy.tensor.array import MutableDenseNDimArray
    >>> a = MutableDenseNDimArray.zeros(2, 3, 4)
    >>> a
    [[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]], [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]]

    Create an N-dim array from a list;

    >>> a = MutableDenseNDimArray([[2, 3], [4, 5]])
    >>> a
    [[2, 3], [4, 5]]

    >>> b = MutableDenseNDimArray([[[1, 2], [3, 4], [5, 6]], [[7, 8], [9, 10], [11, 12]]])
    >>> b
    [[[1, 2], [3, 4], [5, 6]], [[7, 8], [9, 10], [11, 12]]]

    Create an N-dim array from a flat list with dimension shape:

    >>> a = MutableDenseNDimArray([1, 2, 3, 4, 5, 6], (2, 3))
    >>> a
    [[1, 2, 3], [4, 5, 6]]

    Create an N-dim array from a matrix:

    >>> from sympy import Matrix
    >>> a = Matrix([[1,2],[3,4]])
    >>> a
    Matrix([
    [1, 2],
    [3, 4]])
    >>> b = MutableDenseNDimArray(a)
    >>> b
    [[1, 2], [3, 4]]

    Arithmetic operations on N-dim arrays

    >>> a = MutableDenseNDimArray([1, 1, 1, 1], (2, 2))
    >>> b = MutableDenseNDimArray([4, 4, 4, 4], (2, 2))
    >>> c = a + b
    >>> c
    [[5, 5], [5, 5]]
    >>> a - b
    [[-3, -3], [-3, -3]]

    """
    def __new__(cls, *args, **kwargs):
        from sympy.tensor.array import ImmutableDenseNDimArray
        return ImmutableDenseNDimArray(*args, **kwargs)

    def _parse_index(self, index):

        if isinstance(index, (int, Integer)):
            if index >= self._loop_size:
                raise ValueError("index out of range")
            return index

        if len(index) != self._rank:
            raise ValueError('Wrong number of array axes')

        real_index = 0
        # check if input index can exist in current indexing
        for i in range(self._rank):
            if index[i] > self.shape[i]:
                raise ValueError('Index ' + str(index) + ' out of border')
            real_index = real_index*self.shape[i] + index[i]

        return real_index

    def _get_tuple_index(self, integer_index):
        index = []
        for i, sh in enumerate(reversed(self.shape)):
            index.append(integer_index % sh)
            integer_index //= sh
        index.reverse()
        return tuple(index)

    def _setter_iterable_check(self, value):
        if isinstance(value, (collections.Iterable, Matrix, NDimArray)):
            raise NotImplementedError

    @classmethod
    def _scan_iterable_shape(cls, iterable):
        def f(pointer):
            if not isinstance(pointer, collections.Iterable):
                return [pointer], ()

            result = []
            elems, shapes = zip(*[f(i) for i in pointer])
            if len(set(shapes)) != 1:
                raise ValueError("could not determine shape unambiguously")
            for i in elems:
                result.extend(i)
            return result, (len(shapes),)+shapes[0]

        return f(iterable)

    @classmethod
    def _handle_ndarray_creation_inputs(cls, iterable=None, shape=None, **kwargs):

        if shape is None and iterable is None:
            shape = ()
            iterable = ()
        # Construction from another `NDimArray`:
        elif shape is None and isinstance(iterable, NDimArray):
            shape = iterable.shape
            iterable = list(iterable)
        # Construct N-dim array from an iterable (numpy arrays included):
        elif shape is None and isinstance(iterable, collections.Iterable):
            iterable, shape = cls._scan_iterable_shape(iterable)

        # Construct N-dim array from a Matrix:
        elif shape is None and isinstance(iterable, Matrix):
            shape = iterable.shape

        # Construct N-dim array from another N-dim array:
        elif shape is None and isinstance(iterable, NDimArray):
            shape = iterable.shape

        # Construct NDimArray(iterable, shape)
        elif shape is not None:
            pass

        else:
            raise TypeError("Data type not understood")

        if isinstance(shape, (int, Integer)):
            shape = (shape,)

        if any([not isinstance(dim, (int, Integer)) for dim in shape]):
            raise TypeError("Shape should contain integers only.")

        return tuple(shape), iterable

    def __len__(self):
        """Overload common function len(). Returns number of elements in array.

        Examples
        ========

        >>> from sympy.tensor.array.dense_ndim_array import MutableDenseNDimArray
        >>> a = MutableDenseNDimArray.zeros(3, 3)
        >>> a
        [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
        >>> len(a)
        9

        """
        return self._loop_size

    @property
    def shape(self):
        """
        Returns array shape (dimension).

        Examples
        ========

        >>> from sympy.tensor.array.dense_ndim_array import MutableDenseNDimArray
        >>> a = MutableDenseNDimArray.zeros(3, 3)
        >>> a.shape
        (3, 3)

        """
        return self._shape

    def rank(self):
        """
        Returns rank of array.

        Examples
        ========

        >>> from sympy.tensor.array.dense_ndim_array import MutableDenseNDimArray
        >>> a = MutableDenseNDimArray.zeros(3,4,5,6,3)
        >>> a.rank()
        5

        """
        return self._rank

    def diff(self, *args):
        """
        Calculate the derivative of each element in the array.

        Examples
        ========

        >>> from sympy.tensor.array import ImmutableDenseNDimArray
        >>> from sympy.abc import x, y
        >>> M = ImmutableDenseNDimArray([[x, y], [1, x*y]])
        >>> M.diff(x)
        [[1, 0], [0, y]]

        """
        return type(self)(map(lambda x: x.diff(*args), self), self.shape)

    def applyfunc(self, f):
        """Apply a function to each element of the N-dim array.

        Examples
        ========

        >>> from sympy.tensor.array import ImmutableDenseNDimArray
        >>> m = ImmutableDenseNDimArray([i*2+j for i in range(2) for j in range(2)], (2, 2))
        >>> m
        [[0, 1], [2, 3]]
        >>> m.applyfunc(lambda i: 2*i)
        [[0, 2], [4, 6]]
        """
        return type(self)(map(f, self), self.shape)

    def __str__(self):
        """Returns string, allows to use standard functions print() and str().

        Examples
        ========

        >>> from sympy.tensor.array import MutableDenseNDimArray
        >>> a = MutableDenseNDimArray.zeros(2, 2)
        >>> a
        [[0, 0], [0, 0]]

        """
        def f(sh, shape_left, i, j):
            if len(shape_left) == 1:
                return "["+", ".join([str(self[e]) for e in range(i, j)])+"]"

            sh //= shape_left[0]
            return "[" + ", ".join([f(sh, shape_left[1:], i+e*sh, i+(e+1)*sh) for e in range(shape_left[0])]) + "]" # + "\n"*len(shape_left)

        return f(self._loop_size, self.shape, 0, self._loop_size)

        out_str = ''

        # forming output string
        for i, el in enumerate(self):

            out_str += str(el) + '  '
            chidx = i+1
            for sh in reversed(self.shape):
                if chidx % sh == 0:
                    out_str += '\n'
                    chidx //= sh

        return out_str

    def __repr__(self):
        return self.__str__()

    def tolist(self):
        """
        Conveting MutableDenseNDimArray to one-dim list

        Examples
        ========

        >>> from sympy.tensor.array import MutableDenseNDimArray
        >>> a = MutableDenseNDimArray([1, 2, 3, 4], (2, 2))
        >>> a
        [[1, 2], [3, 4]]
        >>> b = a.tolist()
        >>> b
        [[1, 2], [3, 4]]
        """

        def f(sh, shape_left, i, j):
            if len(shape_left) == 1:
                return [self[e] for e in range(i, j)]
            result = []
            sh //= shape_left[0]
            for e in range(shape_left[0]):
                result.append(f(sh, shape_left[1:], i+e*sh, i+(e+1)*sh))
            return result

        return f(self._loop_size, self.shape, 0, self._loop_size)

    def __add__(self, other):
        if not isinstance(other, NDimArray):
            raise TypeError(str(other))

        if self.shape != other.shape:
            raise ValueError("array shape mismatch")
        result_list = [i+j for i,j in zip(self, other)]

        return type(self)(result_list, self.shape)

    def __sub__(self, other):
        if not isinstance(other, NDimArray):
            raise TypeError(str(other))

        if self.shape != other.shape:
            raise ValueError("array shape mismatch")
        result_list = [i-j for i,j in zip(self, other)]

        return type(self)(result_list, self.shape)

    def __mul__(self, other):
        if isinstance(other, (collections.Iterable,NDimArray, Matrix)):
            raise ValueError("scalar expected")
        other = sympify(other)
        result_list = [i*other for i in self]
        return type(self)(result_list, self.shape)

    def __rmul__(self, other):
        if isinstance(other, (collections.Iterable,NDimArray, Matrix)):
            raise ValueError("scalar expected")
        other = sympify(other)
        result_list = [other*i for i in self]
        return type(self)(result_list, self.shape)

    def __div__(self, other):
        if isinstance(other, (collections.Iterable,NDimArray, Matrix)):
            raise ValueError("scalar expected")
        other = sympify(other)
        result_list = [i/other for i in self]
        return type(self)(result_list, self.shape)

    def __rdiv__(self, other):
        raise TypeError('unsupported operation on NDimArray')

    def __eq__(self, other):
        """
        NDimArray instances can be compared to each other.
        Instances equal if they have same shape and data.

        Examples
        ========

        >>> from sympy.tensor.array import MutableDenseNDimArray
        >>> a = MutableDenseNDimArray.zeros(2, 3)
        >>> b = MutableDenseNDimArray.zeros(2, 3)
        >>> a == b
        True
        >>> c = a.reshape(3, 2)
        >>> c == b
        False
        >>> a[0,0] = 1
        >>> b[0,0] = 2
        >>> a == b
        False
        """
        if not isinstance(other, NDimArray):
            return False
        return (self.shape == other.shape) and (list(self) == list(other))

    def __ne__(self, other):
        return not self.__eq__(other)

    __truediv__ = __div__
    __rtruediv__ = __rdiv__

class ImmutableNDimArray(NDimArray, Basic):
    _op_priority = 11.0


text:
// Template Source: BaseMethodParameterSet.java.tt
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All Rights Reserved.  Licensed under the MIT License.  See License in the project root for license information.
// ------------------------------------------------------------------------------

package com.microsoft.graph.models;

import com.microsoft.graph.models.ApplicationServicePrincipal;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import com.google.gson.JsonObject;
import java.util.EnumSet;
import java.util.ArrayList;

// **NOTE** This file was generated by a tool and any changes will be overwritten.

/**
 * The class for the Application Template Instantiate Parameter Set.
 */
public class ApplicationTemplateInstantiateParameterSet {
    /**
     * The display Name.
     *
     */
    @SerializedName(value = "displayName", alternate = {"DisplayName"})
    @Expose
	@Nullable
    public String displayName;

    /**
     * Instiaciates a new ApplicationTemplateInstantiateParameterSet
     */
    public ApplicationTemplateInstantiateParameterSet() {}
    /**
     * Instiaciates a new ApplicationTemplateInstantiateParameterSet
     * @param builder builder bearing the parameters to initialize from
     */
    protected ApplicationTemplateInstantiateParameterSet(@Nonnull final ApplicationTemplateInstantiateParameterSetBuilder builder) {
        this.displayName = builder.displayName;
    }
    /**
     * Gets a new builder for the body
     * @return a new builder
     */
    @Nonnull
    public static ApplicationTemplateInstantiateParameterSetBuilder newBuilder() {
        return new ApplicationTemplateInstantiateParameterSetBuilder();
    }
    /**
     * Fluent builder for the ApplicationTemplateInstantiateParameterSet
     */
    public static final class ApplicationTemplateInstantiateParameterSetBuilder {
        /**
         * The displayName parameter value
         */
        @Nullable
        protected String displayName;
        /**
         * Sets the DisplayName
         * @param val the value to set it to
         * @return the current builder object
         */
        @Nonnull
        public ApplicationTemplateInstantiateParameterSetBuilder withDisplayName(@Nullable final String val) {
            this.displayName = val;
            return this;
        }
        /**
         * Instanciates a new ApplicationTemplateInstantiateParameterSetBuilder
         */
        @Nullable
        protected ApplicationTemplateInstantiateParameterSetBuilder(){}
        /**
         * Buils the resulting body object to be passed to the request
         * @return the body object to pass to the request
         */
        @Nonnull
        public ApplicationTemplateInstantiateParameterSet build() {
            return new ApplicationTemplateInstantiateParameterSet(this);
        }
    }
    /**
     * Gets the functions options from the properties that have been set
     * @return a list of function options for the request
     */
    @Nonnull
    public java.util.List<com.microsoft.graph.options.FunctionOption> getFunctionOptions() {
        final ArrayList<com.microsoft.graph.options.FunctionOption> result = new ArrayList<>();
        if(this.displayName != null) {
            result.add(new com.microsoft.graph.options.FunctionOption("displayName", displayName));
        }
        return result;
    }
}


text:
#ifndef PWN_RENDER_FSE_TARGET_FORMTARGET
#define PWN_RENDER_FSE_TARGET_FORMTARGET

#include <pwn/render/fse/Target.h>

namespace pwn
{
	namespace render
	{
		namespace fse
		{
			/** Render to a form/window.
			 Usually the last one in the fse pipeline.
			 */
			class FormTarget
				: public Target
			{
			public:
				FormTarget();
				~FormTarget();

				void apply(Provider& a, World3* world, const RenderArgs& ra);
				void link(Linker* usr);
				string toString() const;
			};
		}
	}
}

#endif


text:
<?php

  /**
   * New file activity log entry
   *
   * @package activeCollab.modules.files
   * @subpackage models
   */
  class NewFileActivityLog extends ActivityLog {

    /**
     * Action name
     *
     * @var string
     */
    var $action_name = 'Uploaded';

    /**
     * New file uploads have acitivity logs
     *
     * @var boolean
     */
    var $has_body = true;

    /**
     * Flag to render footer
     *
     * @var boolean
     */
    var $has_footer = true;

    /**
     * Return log icon URL
     *
     * @param void
     * @return string
     */
    function getIconUrl() {
      return get_image_url('activity_log/upload.gif', FILES_MODULE);
    } // getIconUrl

    /**
     * Render log details
     *
     * @param ProjectObject $object
     * @param boolean $in_project
     * @return string
     */
    function renderHead($object = null, $in_project = false) {
      if($object === null) {
        $object = $this->getObject();
      } // if

      if(instance_of($object, 'ProjectObject')) {
        $created_by = $this->getCreatedBy();

        $lang_params = array(
          'user_name'     => $created_by->getDisplayName(true),
          'user_url' => $created_by->getViewUrl(),
          'url'      => $object->getViewUrl(),
        );

        if ($in_project) {
          return lang(':user_name uploaded a new file', $lang_params);
        } // if

        $project = $object->getProject();
        $lang_params['project_name'] = $project->getName();
        $lang_params['project_view_url'] = $project->getOverviewUrl();
        return lang(':user_name uploaded a new file to :project_name project', $lang_params);
      } // if

      return '';
    } // render

    /**
     * Render log details
     *
     * @param ProjectObject $object
     * @param boolean $in_project
     * @return string
     */
    function renderBody($object = null, $in_project = false) {
      if($object === null) {
        $object = $this->getObject();
      } // if

      require_once SMARTY_PATH . '/plugins/modifier.filesize.php';
      $result = '
';
      $result .= '
getViewUrl() . '">getThumbnailUrl() . '" alt="" />
';
      $result .= '
getViewUrl() . '">' . clean($object->getName()) . ', ' . smarty_modifier_filesize($object->getSize()) . '
';

      if($object->getBody()) {
        $result .= '
' . nl2br(str_excerpt(strip_tags($object->getBody()), 250)) . '
';
      } // if

      $result .= '
';

      return $result;
    } // renderBody

    /**
     * Render Log Details
     *
     * @param File $object
     * @param boolean $in_project
     */
    function renderFooter($object = null, $in_project = false) {
      if($object === null) {
        $object = $this->getObject();
      } // if

      $links = array();

      if($object->isImage()) {
        $links[] = 'getDownloadUrl() . '" target="_blank">' . lang('View') . '';
      } // if

      $links[] = 'getDownloadUrl(true) . '">' . lang('Download') . '';

      return implode(' · ', $links);
    } // renderFooter

  }

?>


text:
<!---
Copyright 2016 The AMP HTML Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->

# Nativo

## Example

```html
<amp-ad
  type="nativo"
  height="150"
  width="350">
</amp-ad>
```

## Configuration

For semantics of configuration, please [contact Nativo](http://www.nativo.net/#contact-us).

- data-premium: (optional) Will switch to premium


text:
var mongoose = require('mongoose');
var Lifetime = require('../serverModels/lifetimeModel');

module.exports.addnew = function(req, res) {
    console.log(req.body);
    var lifetime = new Lifetime({
        title: req.body.title,
        description: req.body.description,
        status: req.body.status,
        closePercent: req.body.closePercent,
        priority: req.body.priority,
        notes: []

    });
    lifetime.save(function(err) {
        if (err) {
            res.sendStatus(500);
        } else {
            res.sendStatus(200);
            //res.send(user);
        }

    });

};

module.exports.getAll = function(req, res) {

    Lifetime.find({}, function(err, results) {
        if (err) {
            res.sendStatus(500);
        } else {
            res.status(200).send(results);
            //res.send(user);
        }

    });

};
module.exports.delete = function(req, res) {
    console.log(req.body);
    Lifetime.remove({
        _id: req.body._id
    }, function(err, results) {
        if (err) {
            res.sendStatus(500);
        } else {
            res.sendStatus(200);
            //res.send(user);
        }

    });

};
module.exports.update = function(req, res) {
    console.log(req.body);

    Lifetime.findOneAndUpdate({
            _id: req.body._id
        },
        req.body, {
            upsert: true
        },
        function(err, doc) {
            if (err) {
                res.sendStatus(500);
            } else {
                res.sendStatus(200);
            }
        });

};


text:
Initializes the Bear CMS instance.

```php
public void initialize ( array $config )
```

## Parameters

##### config

      A list of configuration variables.

## Details

Class: [BearCMS](bearcms.class.md)

Location: ~/classes/BearCMS.php

---

[back to index](index.md)


text:
package org.codehaus.mojo.unix.maven.plugin;

import org.apache.maven.plugin.*;
import org.codehaus.mojo.unix.*;
import org.codehaus.mojo.unix.core.*;
import org.codehaus.mojo.unix.io.fs.*;
import org.codehaus.mojo.unix.util.*;
import org.codehaus.plexus.util.*;

import java.io.*;

/**
 * @author Trygve Laugstøl
 */
public abstract class AssemblyOp
{
    protected final String operationType;

    protected AssemblyOp( String operationType )
    {
        this.operationType = operationType;
    }

    // -----------------------------------------------------------------------
    //
    // -----------------------------------------------------------------------

    /**
     * TODO: Replace all of these parameters with a context object.
     * TODO: Add timestamp to keep all timestamps consistent.
     */
    public abstract AssemblyOperation createOperation( CreateOperationContext context )
        throws MojoFailureException, UnknownArtifactException, IOException;

    public static class CreateOperationContext {
        public final LocalFs basedir;
        public final FileAttributes defaultFileAttributes;
        public final FileAttributes defaultDirectoryAttributes;
        public final MavenProjectWrapper project;

        public CreateOperationContext( LocalFs basedir,
                                       FileAttributes defaultFileAttributes, FileAttributes defaultDirectoryAttributes,
                                       MavenProjectWrapper project )
        {
            this.basedir = basedir;
            this.defaultFileAttributes = defaultFileAttributes;
            this.defaultDirectoryAttributes = defaultDirectoryAttributes;
            this.project = project;
        }
    }

    // -----------------------------------------------------------------------
    // Utilities
    // -----------------------------------------------------------------------

    protected static String nullIfEmpty(String artifact)
    {
        return StringUtils.clean( artifact ).length() == 0 ? null : artifact;
    }

    protected void validateIsSet( Object valueA, String fieldA )
        throws MojoFailureException
    {
        if ( valueA == null )
        {
            throw new MojoFailureException( "Field '" + fieldA + "' has to be specified on a " + operationType + " operation." );
        }
    }

    protected void validateEitherIsSet( Object valueA, Object valueB, String fieldA, String fieldB )
        throws MojoFailureException
    {
        if ( valueA != null && valueB != null )
        {
            throw new MojoFailureException( "Only one of '" + fieldA + "' and '" + fieldB + "' can be specified on a " + operationType + " operation." );
        }

        if ( valueA == null && valueB == null )
        {
            throw new MojoFailureException( "One of '" + fieldA + "' and '" + fieldB + "' has to be specified on a " + operationType + " operation." );
        }
    }

    protected RelativePath validateAndResolveOutputFile( File artifactFile, RelativePath toDir, RelativePath toFile )
        throws MojoFailureException
    {
        if ( toFile != null )
        {
            if ( toDir != null )
            {
                throw new MojoFailureException( "Can't specify both 'toDir' and 'toFile' on a " + operationType + " operation." );
            }

            return toFile;
        }

        if ( toDir == null )
        {
            toDir = RelativePath.BASE;
        }

        return toDir.add( artifactFile.getName() );
    }

    protected File validateFileIsReadableFile( File file, String fieldName )
        throws MojoFailureException
    {
        if ( !file.isFile() )
        {
            throw new MojoFailureException( "The path specified in field '" + fieldName + "' on an " + operationType +
                " operation is not a file: " + file.getAbsolutePath() );
        }

        if ( !file.canRead() )
        {
            throw new MojoFailureException( "The path specified in field '" + fieldName + " on an " +
                operationType + " operation is not readable " + file.getAbsolutePath() );
        }

        return file;
    }

    protected File validateFileIsDirectory( File file, String fieldName )
        throws MojoFailureException
    {
        if ( !file.isDirectory() )
        {
            throw new MojoFailureException( "The path specified in field '" + fieldName + "' on an " + operationType +
                " is not a directory: " + file.getAbsolutePath() );
        }

        return file;
    }
}


text:
#[=======================================================================[.rst:
CMakePackageConfigHelpers
-------------------------

Helpers functions for creating config files that can be included by other
projects to find and use a package.

Adds the :command:`configure_package_config_file()` and
:command:`write_basic_package_version_file()` commands.

Generating a Package Configuration File
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

.. command:: configure_package_config_file

 Create a config file for a project::

   configure_package_config_file(<input> <output>
     INSTALL_DESTINATION <path>
     [PATH_VARS <var1> <var2> ... <varN>]
     [NO_SET_AND_CHECK_MACRO]
     [NO_CHECK_REQUIRED_COMPONENTS_MACRO]
     [INSTALL_PREFIX <path>]
     )

``configure_package_config_file()`` should be used instead of the plain
:command:`configure_file()` command when creating the ``<PackageName>Config.cmake``
or ``<PackageName>-config.cmake`` file for installing a project or library.
It helps making the resulting package relocatable by avoiding hardcoded paths
in the installed ``Config.cmake`` file.

In a ``FooConfig.cmake`` file there may be code like this to make the install
destinations know to the using project:

.. code-block:: cmake

   set(FOO_INCLUDE_DIR   "@CMAKE_INSTALL_FULL_INCLUDEDIR@" )
   set(FOO_DATA_DIR   "@CMAKE_INSTALL_PREFIX@/@RELATIVE_DATA_INSTALL_DIR@" )
   set(FOO_ICONS_DIR   "@CMAKE_INSTALL_PREFIX@/share/icons" )
   #...logic to determine installedPrefix from the own location...
   set(FOO_CONFIG_DIR  "${installedPrefix}/@CONFIG_INSTALL_DIR@" )

All 4 options shown above are not sufficient, since the first 3 hardcode the
absolute directory locations, and the 4th case works only if the logic to
determine the ``installedPrefix`` is correct, and if ``CONFIG_INSTALL_DIR``
contains a relative path, which in general cannot be guaranteed.  This has the
effect that the resulting ``FooConfig.cmake`` file would work poorly under
Windows and OSX, where users are used to choose the install location of a
binary package at install time, independent from how
:variable:`CMAKE_INSTALL_PREFIX` was set at build/cmake time.

Using ``configure_package_config_file`` helps.  If used correctly, it makes
the resulting ``FooConfig.cmake`` file relocatable.  Usage:

1. write a ``FooConfig.cmake.in`` file as you are used to
2. insert a line containing only the string ``@PACKAGE_INIT@``
3. instead of ``set(FOO_DIR "@SOME_INSTALL_DIR@")``, use
   ``set(FOO_DIR "@PACKAGE_SOME_INSTALL_DIR@")`` (this must be after the
   ``@PACKAGE_INIT@`` line)
4. instead of using the normal :command:`configure_file()`, use
   ``configure_package_config_file()``

The ``<input>`` and ``<output>`` arguments are the input and output file, the
same way as in :command:`configure_file()`.

The ``<path>`` given to ``INSTALL_DESTINATION`` must be the destination where
the ``FooConfig.cmake`` file will be installed to.  This path can either be
absolute, or relative to the ``INSTALL_PREFIX`` path.

The variables ``<var1>`` to ``<varN>`` given as ``PATH_VARS`` are the
variables which contain install destinations.  For each of them the macro will
create a helper variable ``PACKAGE_<var...>``.  These helper variables must be
used in the ``FooConfig.cmake.in`` file for setting the installed location.
They are calculated by ``configure_package_config_file`` so that they are
always relative to the installed location of the package.  This works both for
relative and also for absolute locations.  For absolute locations it works
only if the absolute location is a subdirectory of ``INSTALL_PREFIX``.

If the ``INSTALL_PREFIX`` argument is passed, this is used as base path to
calculate all the relative paths.  The ``<path>`` argument must be an absolute
path.  If this argument is not passed, the :variable:`CMAKE_INSTALL_PREFIX`
variable will be used instead.  The default value is good when generating a
FooConfig.cmake file to use your package from the install tree.  When
generating a FooConfig.cmake file to use your package from the build tree this
option should be used.

By default ``configure_package_config_file`` also generates two helper macros,
``set_and_check()`` and ``check_required_components()`` into the
``FooConfig.cmake`` file.

``set_and_check()`` should be used instead of the normal ``set()`` command for
setting directories and file locations.  Additionally to setting the variable
it also checks that the referenced file or directory actually exists and fails
with a ``FATAL_ERROR`` otherwise.  This makes sure that the created
``FooConfig.cmake`` file does not contain wrong references.
When using the ``NO_SET_AND_CHECK_MACRO``, this macro is not generated
into the ``FooConfig.cmake`` file.

``check_required_components(<PackageName>)`` should be called at the end of
the ``FooConfig.cmake`` file. This macro checks whether all requested,
non-optional components have been found, and if this is not the case, sets
the ``Foo_FOUND`` variable to ``FALSE``, so that the package is considered to
be not found.  It does that by testing the ``Foo_<Component>_FOUND``
variables for all requested required components.  This macro should be
called even if the package doesn't provide any components to make sure
users are not specifying components erroneously.  When using the
``NO_CHECK_REQUIRED_COMPONENTS_MACRO`` option, this macro is not generated
into the ``FooConfig.cmake`` file.

For an example see below the documentation for
:command:`write_basic_package_version_file()`.

Generating a Package Version File
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

.. command:: write_basic_package_version_file

 Create a version file for a project::

   write_basic_package_version_file(<filename>
     [VERSION <major.minor.patch>]
     COMPATIBILITY <AnyNewerVersion|SameMajorVersion|SameMinorVersion|ExactVersion>
     [ARCH_INDEPENDENT] )

Writes a file for use as ``<PackageName>ConfigVersion.cmake`` file to
``<filename>``.  See the documentation of :command:`find_package()` for
details on this.

``<filename>`` is the output filename, it should be in the build tree.
``<major.minor.patch>`` is the version number of the project to be installed.

If no ``VERSION`` is given, the :variable:`PROJECT_VERSION` variable is used.
If this hasn't been set, it errors out.

The ``COMPATIBILITY`` mode ``AnyNewerVersion`` means that the installed
package version will be considered compatible if it is newer or exactly the
same as the requested version.  This mode should be used for packages which
are fully backward compatible, also across major versions.
If ``SameMajorVersion`` is used instead, then the behaviour differs from
``AnyNewerVersion`` in that the major version number must be the same as
requested, e.g.  version 2.0 will not be considered compatible if 1.0 is
requested.  This mode should be used for packages which guarantee backward
compatibility within the same major version.
If ``SameMinorVersion`` is used, the behaviour is the same as
``SameMajorVersion``, but both major and minor version must be the same as
requested, e.g version 0.2 will not be compatible if 0.1 is requested.
If ``ExactVersion`` is used, then the package is only considered compatible if
the requested version matches exactly its own version number (not considering
the tweak version).  For example, version 1.2.3 of a package is only
considered compatible to requested version 1.2.3.  This mode is for packages
without compatibility guarantees.
If your project has more elaborated version matching rules, you will need to
write your own custom ``ConfigVersion.cmake`` file instead of using this
macro.

If ``ARCH_INDEPENDENT`` is given, the installed package version will be
considered compatible even if it was built for a different architecture than
the requested architecture.  Otherwise, an architecture check will be performed,
and the package will be considered compatible only if the architecture matches
exactly.  For example, if the package is built for a 32-bit architecture, the
package is only considered compatible if it is used on a 32-bit architecture,
unless ``ARCH_INDEPENDENT`` is given, in which case the package is considered
compatible on any architecture.

.. note:: ``ARCH_INDEPENDENT`` is intended for header-only libraries or similar
   packages with no binaries.

Internally, this macro executes :command:`configure_file()` to create the
resulting version file.  Depending on the ``COMPATIBILITY``, the corresponding
``BasicConfigVersion-<COMPATIBILITY>.cmake.in`` file is used.
Please note that these files are internal to CMake and you should not call
:command:`configure_file()` on them yourself, but they can be used as starting
point to create more sophisticted custom ``ConfigVersion.cmake`` files.

Example Generating Package Files
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Example using both :command:`configure_package_config_file` and
``write_basic_package_version_file()``:

``CMakeLists.txt``:

.. code-block:: cmake

   set(INCLUDE_INSTALL_DIR include/ ... CACHE )
   set(LIB_INSTALL_DIR lib/ ... CACHE )
   set(SYSCONFIG_INSTALL_DIR etc/foo/ ... CACHE )
   #...
   include(CMakePackageConfigHelpers)
   configure_package_config_file(FooConfig.cmake.in
     ${CMAKE_CURRENT_BINARY_DIR}/FooConfig.cmake
     INSTALL_DESTINATION ${LIB_INSTALL_DIR}/Foo/cmake
     PATH_VARS INCLUDE_INSTALL_DIR SYSCONFIG_INSTALL_DIR)
   write_basic_package_version_file(
     ${CMAKE_CURRENT_BINARY_DIR}/FooConfigVersion.cmake
     VERSION 1.2.3
     COMPATIBILITY SameMajorVersion )
   install(FILES ${CMAKE_CURRENT_BINARY_DIR}/FooConfig.cmake
                 ${CMAKE_CURRENT_BINARY_DIR}/FooConfigVersion.cmake
           DESTINATION ${LIB_INSTALL_DIR}/Foo/cmake )

``FooConfig.cmake.in``:

::

   set(FOO_VERSION x.y.z)
   ...
   @PACKAGE_INIT@
   ...
   set_and_check(FOO_INCLUDE_DIR "@PACKAGE_INCLUDE_INSTALL_DIR@")
   set_and_check(FOO_SYSCONFIG_DIR "@PACKAGE_SYSCONFIG_INSTALL_DIR@")

   check_required_components(Foo)
#]=======================================================================]

include(WriteBasicConfigVersionFile)

macro(WRITE_BASIC_PACKAGE_VERSION_FILE)
  write_basic_config_version_file(${ARGN})
endmacro()

function(CONFIGURE_PACKAGE_CONFIG_FILE _inputFile _outputFile)
  set(options NO_SET_AND_CHECK_MACRO NO_CHECK_REQUIRED_COMPONENTS_MACRO)
  set(oneValueArgs INSTALL_DESTINATION INSTALL_PREFIX)
  set(multiValueArgs PATH_VARS )

  cmake_parse_arguments(CCF "${options}" "${oneValueArgs}" "${multiValueArgs}"  ${ARGN})

  if(CCF_UNPARSED_ARGUMENTS)
    message(FATAL_ERROR "Unknown keywords given to CONFIGURE_PACKAGE_CONFIG_FILE(): \"${CCF_UNPARSED_ARGUMENTS}\"")
  endif()

  if(NOT CCF_INSTALL_DESTINATION)
    message(FATAL_ERROR "No INSTALL_DESTINATION given to CONFIGURE_PACKAGE_CONFIG_FILE()")
  endif()

  if(DEFINED CCF_INSTALL_PREFIX)
    if(IS_ABSOLUTE "${CCF_INSTALL_PREFIX}")
      set(installPrefix "${CCF_INSTALL_PREFIX}")
    else()
      message(FATAL_ERROR "INSTALL_PREFIX must be an absolute path")
    endif()
  elseif(IS_ABSOLUTE "${CMAKE_INSTALL_PREFIX}")
    set(installPrefix "${CMAKE_INSTALL_PREFIX}")
  else()
    get_filename_component(installPrefix "${CMAKE_INSTALL_PREFIX}" ABSOLUTE)
  endif()

  if(IS_ABSOLUTE "${CCF_INSTALL_DESTINATION}")
    set(absInstallDir "${CCF_INSTALL_DESTINATION}")
  else()
    set(absInstallDir "${installPrefix}/${CCF_INSTALL_DESTINATION}")
  endif()

  file(RELATIVE_PATH PACKAGE_RELATIVE_PATH "${absInstallDir}" "${installPrefix}" )

  foreach(var ${CCF_PATH_VARS})
    if(NOT DEFINED ${var})
      message(FATAL_ERROR "Variable ${var} does not exist")
    else()
      if(IS_ABSOLUTE "${${var}}")
        string(REPLACE "${installPrefix}" "\${PACKAGE_PREFIX_DIR}"
                        PACKAGE_${var} "${${var}}")
      else()
        set(PACKAGE_${var} "\${PACKAGE_PREFIX_DIR}/${${var}}")
      endif()
    endif()
  endforeach()

  get_filename_component(inputFileName "${_inputFile}" NAME)

  set(PACKAGE_INIT "
####### Expanded from @PACKAGE_INIT@ by configure_package_config_file() #######
####### Any changes to this file will be overwritten by the next CMake run ####
####### The input file was ${inputFileName}                            ########

get_filename_component(PACKAGE_PREFIX_DIR \"\${CMAKE_CURRENT_LIST_DIR}/${PACKAGE_RELATIVE_PATH}\" ABSOLUTE)
")

  if("${absInstallDir}" MATCHES "^(/usr)?/lib(64)?/.+")
    # Handle "/usr move" symlinks created by some Linux distros.
    string(APPEND PACKAGE_INIT "
# Use original install prefix when loaded through a \"/usr move\"
# cross-prefix symbolic link such as /lib -> /usr/lib.
get_filename_component(_realCurr \"\${CMAKE_CURRENT_LIST_DIR}\" REALPATH)
get_filename_component(_realOrig \"${absInstallDir}\" REALPATH)
if(_realCurr STREQUAL _realOrig)
  set(PACKAGE_PREFIX_DIR \"${installPrefix}\")
endif()
unset(_realOrig)
unset(_realCurr)
")
  endif()

  if(NOT CCF_NO_SET_AND_CHECK_MACRO)
    string(APPEND PACKAGE_INIT "
macro(set_and_check _var _file)
  set(\${_var} \"\${_file}\")
  if(NOT EXISTS \"\${_file}\")
    message(FATAL_ERROR \"File or directory \${_file} referenced by variable \${_var} does not exist !\")
  endif()
endmacro()
")
  endif()

  if(NOT CCF_NO_CHECK_REQUIRED_COMPONENTS_MACRO)
    string(APPEND PACKAGE_INIT "
macro(check_required_components _NAME)
  foreach(comp \${\${_NAME}_FIND_COMPONENTS})
    if(NOT \${_NAME}_\${comp}_FOUND)
      if(\${_NAME}_FIND_REQUIRED_\${comp})
        set(\${_NAME}_FOUND FALSE)
      endif()
    endif()
  endforeach()
endmacro()
")
  endif()

  string(APPEND PACKAGE_INIT "
####################################################################################")

  configure_file("${_inputFile}" "${_outputFile}" @ONLY)

endfunction()


text:
#import <UIKit/UIKit.h>

#import <ParseUI/PFImageView.h>

/*!
 The `PFTableViewCell` class represents a table view cell which can download and display remote images stored on Parse.

 When used in a <PFQueryTableViewController> - downloading and displaying of the remote images
 are automatically managed by the <PFQueryTableViewController>.
 */
@interface PFTableViewCell : UITableViewCell

/*!
 @abstract The imageView of the table view cell.

 @see PFImageView
 */
@property (nonatomic, strong, readonly) PFImageView *imageView;

@end


text:
import javafx.application.Application;
import javafx.stage.Stage;
import org.mcupdater.gui.LoginDialog;
import org.mcupdater.settings.Profile;

/**
 * Created by sbarbour on 1/28/14.
 */
public class TestLogin extends Application
{
	public static void main(String[] args) {
		launch(args);
	}

	@Override
	public void start(Stage stage) throws Exception {
		Profile test = LoginDialog.doLogin(null, "testUser");
		System.out.println(test.getStyle() + " - " + test.getName() + " - " + test.getAccessToken());
	}
}


text:
module AsciiDocWeb
  module ControllerHelpers
    def load_sections_from_cfg(cfg)
      AsciiDocWeb::YamlConfigurator.load_yaml_file(cfg)
    end

    def find_section_and_manual_by_sections(sections)
      section = find_manual_by_sections_and_param(sections, params[:section])
      manual = section ? find_manual_by_sections_and_param(section.manuals, params[:manual]) : nil

      [section, manual]
    end

    def find_manual_by_sections_and_param(sections, manual)
      m = nil
      sections.each do |el|
        m = el if manual == el.dir
        break if m
      end
      m
    end
  end
end


text:
"""Module for Coordinate Search WSGI application."""

from search.common import exceptions
from search.plugin import coordinate_search_handler

class GeCoordinateSearchApp(object):
  """GeCoordinateSearchApp implements the callable method.

  WSGI Application class interfaces with the web server and
  receives the search queries in the form of URL parameters.
  Web server calls the callable method __call__ to start the application.
  """

  def __init__(self):
    """Inits the status and response_headers for the HTTP response."""

    self._status = "%s"
    self._coordinate = coordinate_search_handler.CoordinateSearch()

  def __call__(self, environ, start_response):
    """Callable method for the WSGI application.

    Callable method which performs a coordinate search and returns
    the KML/JSONP format output back in the HTTP response.

    Args:
        environ: A list which contains the WSGI environment information.
        start_response: callable for setting the HTTP headers and status.
    Returns:
        response_body: Search Results sent back to the client wrapped in a list.
    """
    response_headers = []

    content_type = ""
    status = ""
    response_body = ""
    response_type = ""

    try:
      response_body, response_type = self._coordinate.HandleSearchRequest(
          environ)
      content_type = self._coordinate.utils.GetContentType(response_type)
      status = self._status % ("200 OK")
    except exceptions.BadQueryException as e:
      # For empty or incorrect search queries.
      content_type = self._coordinate.utils.content_type % ("text/plain")
      status = self._status % ("400 Bad Request")
      self._coordinate.logger.debug(
          "%s, status %s sent back to client.", e, status)
      response_body = "%s" % e
    except Exception, e:
      # Any kind of Exception/Error occurs,then send "500 Internal Server Error"
      content_type = self._coordinate.utils.content_type % ("text/plain")
      status = self._status % ("500 Internal Server Error")
      self._coordinate.logger.debug(
          "%s, status %s sent back to client.", e, status)
      response_body = "%s" % e

    response_headers.append(tuple(content_type.split(",")))

    start_response(status, response_headers)
    return [response_body.encode("utf-8")]

application = GeCoordinateSearchApp()

def main():
  application()

if __name__ == "__main__":
  main()


text:
var common = require('./common');
var Promise = require('bluebird');
var yfm = require('hexo-front-matter');
var pathFn = require('path');

exports.process = function(file){
  if (this.render.isRenderable(file.path)){
    return processPage.call(this, file);
  } else {
    return processAsset.call(this, file);
  }
};

exports.pattern = common.ignoreTmpAndHiddenFile;

function processPage(file){
  var Page = this.model('Page');
  var path = file.path;
  var doc = Page.findOne({source: path});
  var self = this;

  if (file.type === 'skip' && doc){
    return;
  }

  if (file.type === 'delete'){
    if (doc){
      return doc.remove();
    } else {
      return;
    }
  }

  return Promise.all([
    file.stat(),
    file.read()
  ]).spread(function(stats, content){
    var data = yfm(content);
    var output = self.render.getOutput(path);

    data.source = path;
    data.raw = content;

    data.date = common.toDate(data.date) || stats.ctime;
    data.updated = common.toDate(data.updated) || stats.mtime;

    if (data.permalink){
      data.path = data.permalink;
      delete data.permalink;

      if (data.path[data.path.length - 1] === '/'){
        data.path += 'index';
      }
    } else {
      var extname = pathFn.extname(path);
      data.path = path.substring(0, path.length - extname.length);
    }

    if (!pathFn.extname(data.path)){
      data.path += '.' + output;
    }

    if (!data.layout && output !== 'html' && output !== 'htm'){
      data.layout = false;
    }

    if (doc){
      return doc.replace(data);
    } else {
      return Page.insert(data);
    }
  });
}

function processAsset(file){
  var id = file.source.substring(this.base_dir.length).replace(/\\/g, '/');
  var Asset = this.model('Asset');
  var doc = Asset.findById(id);

  if (file.type === 'delete'){
    if (doc){
      return doc.remove();
    } else {
      return;
    }
  }

  if (doc){
    doc.path = file.path;
    doc.modified = file.type === 'update';

    return doc.save();
  } else {
    return Asset.insert({
      _id: id,
      path: file.path
    });
  }
}


text:
require 'spec_helper'

describe SageoneSdk::Client::ContactTypes do
  before :each do
    SageoneSdk.reset!
  end

  let(:client) { SageoneSdk::Client.new({access_token: "foo", signing_secret: "bar" }) }

  describe "contact_types", :vcr do
    it "returns all contact_types" do
      contact_types = client.contact_types
      expect(contact_types.first.name).not_to be_nil
    end
  end

  describe "contact_types/:id", :vcr do
    before :each do
      VCR.use_cassette('contact_types_index') do
        @contact_type_id = client.contact_types.first.id
      end
    end

    it "returns a specific contact type" do
      contact_type = client.contact_type(@contact_type_id)
      expect(contact_type.name).to eq("Customer")
    end
  end
end


text: export default from './FormControls';