text:
module ManagerTypes
  import Creature
  import Server
  import Client
  import Config
  import World
  import Event

  export Plugin
  export ManagerData
  export OrganismTask
  export Connections

  export orgAmount
  #
  # Abstraction for plugin type. All plugins should be inherited
  # from this type like this:
  #
  # type MyPlugin <: Plugin ... end
  #
  abstract Plugin
  #
  # One task related to one organism
  #
  type OrganismTask
    #
    # Organism unique id
    #
    id::UInt
    #
    # Task object. With it we may use green
    #
    task::Task
    #
    # One organism
    #
    organism::Creature.Organism
  end
  #
  # Current Manager connection objects. They are: server and
  # all four clients. "frozen" field is used for storing "frozen"
  # organisms (which are transfserring from current Manager to
  # another one by network). "streaming" flag means, that streaming
  # mode is on or off. Here streaming is a world dots streaming.
  #
  type Connections
    streamInit::Bool
    server    ::Server.ServerConnection
    fastServer::Server.ServerConnection
    left      ::Client.ClientConnection
    right     ::Client.ClientConnection
    up        ::Client.ClientConnection
    down      ::Client.ClientConnection
    frozen    ::Dict{UInt, Creature.Organism}
    Connections() = new()
    Connections(
      streamInit::Bool,
      server    ::Server.ServerConnection,
      fastServer::Server.ServerConnection,
      left      ::Client.ClientConnection,
      right     ::Client.ClientConnection,
      up        ::Client.ClientConnection,
      down      ::Client.ClientConnection,
      frozen    ::Dict{UInt, Creature.Organism}
    ) = new(streamInit, server, fastServer, left, right, up, down, frozen)
  end
  #
  # Manager's related type. Contains world, command line parameters,
  # organisms map and so on... If some fields will be changed, don't
  # forget to change them in recover() function.
  #
  type ManagerData
    #
    # Application wide configuration
    #
    cfg::Config.ConfigData
    #
    # Instance of the world
    #
    world::World.Plane
    #
    # Positions map, which stores positions of all organisms. Is used
    # for fast access to the organism by it's coordinates.
    #
    positions::Dict{Int, Creature.Organism}
    #
    # Map of organisms by id
    #
    organisms::Dict{UInt, Creature.Organism}
    #
    # All available organism's tasks
    #
    tasks::Array{OrganismTask, 1}
    #
    # Parameters passed through command line
    #
    params::Dict{String, String}
    #
    # Unique id of organism. It's increased every time, when new
    # organism will be created
    #
    organismId::UInt
    #
    # Total amount of organisms: alive + dead
    #
    totalOrganisms::UInt
    #
    # If true, then minimum terminal messages will be posted
    #
    quiet::Bool
    #
    # Callback, which is called when at least one dot in a
    # world has changed it's color
    #
    dotCallback::Function
    #
    # Callback, which is called when one dot in a
    # world has changed it's position (moves from one
    # position to another).
    #
    moveCallback::Function
    #
    # Manager's task (main task)
    #
    task::Task
    #
    # Energy of maximum energetic organism
    #
    maxEnergy::Int
    #
    # Amount of iterations per second
    #
    ips::Float64
    #
    # Stack of killed organism id's
    #
    killed::Array{Int, 1}
    #
    # All available(compiled) Manager's plugins. Key is a plugin string
    # name (filename). Value - plugin related data type.
    #
    plugins::Dict{String, Plugin}
    #
    # Manager observer
    #
    obs::Event.Observer
    #
    # Manager connections (with other managers, terminals, visualizer etc...)
    #
    cons::Connections
    #
    # Short constructor
    #
    ManagerData(
      cfg::Config.ConfigData,
      world::World.Plane,
      positions::Dict{Int, Creature.Organism},
      organisms::Dict{UInt, Creature.Organism},
      tasks::Array{OrganismTask, 1},
      params::Dict{String, String},
      organismId::UInt,
      totalOrganisms::UInt,
      quiet::Bool,
      dotCallback::Function,
      moveCallback::Function,
      task::Task,
      maxEnergy::Int,
      ips::Float64,
      killed::Array{Int, 1},
      plugins::Dict{String, Plugin},
      obs::Event.Observer
    ) = new(
      cfg,
      world,
      positions,
      organisms,
      tasks,
      params,
      organismId,
      totalOrganisms,
      quiet,
      dotCallback,
      moveCallback,
      task,
      maxEnergy,
      ips,
      killed,
      plugins,
      obs
    )
  end

  #
  # Returns amount of alive organisms at the moment. This function is Here
  # and not in Manager module, because it's used in different other modules.
  # In case if you need some function, which work with manager's data and is
  # called only within Manager module and it's sub modules you have to add
  # it there.
  # @return {Int}
  #
  function orgAmount(man::ManagerTypes.ManagerData)
    length(man.tasks) - length(man.killed)
  end
end


text:
"""Command line tool for creating test data for Ceilometer.

Usage:

Generate testing data for e.g. for default time span

source .tox/py27/bin/activate
./tools/make_test_data.py --user 1 --project 1 1 cpu_util 20
"""
from __future__ import print_function

import argparse
import datetime
import logging
import random
import sys
import time
import threading

from oslo.config import cfg
from oslo.utils import timeutils

from ceilometer.publisher import utils
from ceilometer import sample
from ceilometer import storage
from sqlalchemy import func
from ceilometer.storage.sqlalchemy.models import Sample as DBSample
from ceilocommandthread import CeiloCommandThread

def make_test_data(conn, name, meter_type, unit, volume, random_min,
                   random_max, user_id, project_id, resource_id, start,
                   end, interval, resource_metadata={}, source='artificial',):

    # Compute start and end timestamps for the new data.
    if isinstance(start, datetime.datetime):
        timestamp = start
    else:
        timestamp = timeutils.parse_strtime(start)

    if not isinstance(end, datetime.datetime):
        end = timeutils.parse_strtime(end)

    increment = datetime.timedelta(minutes=interval)

    print('Adding new events for meter %s.' % (name))
    # Generate events
    n = 0
    total_volume = volume
    meter_names = ["meter" + name + str(i) for i in range(1, 50, 1)]
    resource_ids = ["resource" + resource_id + str(i) for i in range(1, 500, 1)]

    id = threading.current_thread().ident

    print("id, curr_sampl_count, avg, s")

    t0 = time.time()
    while timestamp <= end:
        if (random_min >= 0 and random_max >= 0):
            # If there is a random element defined, we will add it to
            # user given volume.
            if isinstance(random_min, int) and isinstance(random_max, int):
                total_volume += random.randint(random_min, random_max)
            else:
                total_volume += random.uniform(random_min, random_max)

        c = sample.Sample(name=random.choice(meter_names),
                          type=meter_type,
                          unit=unit,
                          volume=total_volume,
                          user_id=user_id,
                          project_id=project_id,
                          resource_id=random.choice(resource_ids),
                          timestamp=timestamp,
                          resource_metadata=resource_metadata,
                          source=source,
                          )
        data = utils.meter_message_from_counter(
            c,
            cfg.CONF.publisher.metering_secret)
        conn.record_metering_data(data)
        n += 1
        timestamp = timestamp + increment
        t1 = time.time()
        if not n % 1000:
            print ("%d, %d, %f, %f" % (id, get_current_sample_count(conn), (n / (t1 - t0)), t1))

        if (meter_type == 'gauge' or meter_type == 'delta'):
            # For delta and gauge, we don't want to increase the value
            # in time by random element. So we always set it back to
            # volume.
            total_volume = volume

    t1 = time.time()
    totaltime = t1 - t0
    print ("%d, %d, %f, %f" % (id, get_current_sample_count(conn), (n / (t1 - t0)), t1))

    print('Id %d Added %d samples total time %f sec avg: %f samples/sec ts: %f' % (id, n, totaltime, (n / totaltime), t1))

def get_current_sample_count(conn):
    session = conn._engine_facade.get_session()
    return session.query(func.count(DBSample.id)).scalar()

def main():
    cfg.CONF([], project='ceilometer')

    parser = argparse.ArgumentParser(
        description='generate metering data',
    )
    parser.add_argument(
        '--interval',
        default=10,
        type=int,
        help='The period between events, in minutes.',
    )
    parser.add_argument(
        '--start',
        default=31,
        type=int,
        help='The number of days in the past to start timestamps.',
    )
    parser.add_argument(
        '--end',
        default=2,
        type=int,
        help='The number of days into the future to continue timestamps.',
    )
    parser.add_argument(
        '--type',
        choices=('gauge', 'cumulative'),
        default='gauge',
        help='Counter type.',
    )
    parser.add_argument(
        '--unit',
        default=None,
        help='Counter unit.',
    )
    parser.add_argument(
        '--project',
        help='Project id of owner.',
    )
    parser.add_argument(
        '--user',
        help='User id of owner.',
    )
    parser.add_argument(
        '--random_min',
        help='The random min border of amount for added to given volume.',
        type=int,
        default=0,
    )
    parser.add_argument(
        '--random_max',
        help='The random max border of amount for added to given volume.',
        type=int,
        default=0,
    )
    parser.add_argument(
        '--num-threads',
        help='Number of parallel threads',
        type=int,
        default=1,
    )
    parser.add_argument(
        'resource',
        help='The resource id for the meter data.',
    )
    parser.add_argument(
        'counter',
        help='The counter name for the meter data.',
    )
    parser.add_argument(
        'volume',
        help='The amount to attach to the meter.',
        type=int,
        default=1,
    )
    args = parser.parse_args()

    # Set up logging to use the console
    console = logging.StreamHandler(sys.stderr)
    console.setLevel(logging.DEBUG)
    formatter = logging.Formatter('%(message)s')
    console.setFormatter(formatter)
    root_logger = logging.getLogger('')
    root_logger.addHandler(console)
    root_logger.setLevel(logging.DEBUG)

    # Connect to the metering database
    conn = storage.get_connection_from_config(cfg.CONF)
    start_sample_rows = get_current_sample_count(conn)

    # Find the user and/or project for a real resource
    if not (args.user or args.project):
        for r in conn.get_resources():
            if r.resource_id == args.resource:
                args.user = r.user_id
                args.project = r.project_id
                break

    # Compute the correct time span
    start = datetime.datetime.utcnow() - datetime.timedelta(days=args.start)
    end = datetime.datetime.utcnow() + datetime.timedelta(days=args.end)

    kwargs = dict(conn=conn,
                  name=args.counter,
                  meter_type=args.type,
                  unit=args.unit,
                  volume=args.volume,
                  random_min=args.random_min,
                  random_max=args.random_max,
                  user_id=args.user,
                  project_id=args.project,
                  resource_id=args.resource,
                  start=start,
                  end=end,
                  interval=args.interval,
                  resource_metadata={},
                  source='artificial')

    threads = []
    for _ in range(args.num_threads):
        #New connection for each thread
        kwargs['conn'] = storage.get_connection_from_config(cfg.CONF)
        t = CeiloCommandThread(1, make_test_data, **kwargs)
        threads.append(t)
        t.start()

    total_runtimes = []
    for i, t in enumerate(threads):
        t.join()
        total_runtimes = total_runtimes + t.run_times

    end_sample_rows = get_current_sample_count(conn)
    print ("Samples count in DB beginning: %d end: %d" % (start_sample_rows, end_sample_rows))

    #print ("numthreads, ave, min, max = %d\t%f\t%f\t%f" % \
    #          (len(threads), sum(total_runtimes)/len(total_runtimes),
    #          min(total_runtimes), max(total_runtimes)))

    return 0

if __name__ == '__main__':
    main()

redpajama_set_name: RedPajamaGithub


text:
package org.apache.geode.internal.admin.remote;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.List;

import org.apache.geode.distributed.internal.AdminMessageType;
import org.apache.geode.distributed.internal.ClusterDistributionManager;
import org.apache.geode.distributed.internal.HighPriorityDistributionMessage;
import org.apache.geode.distributed.internal.membership.InternalDistributedMember;
import org.apache.geode.internal.serialization.DeserializationContext;
import org.apache.geode.internal.serialization.SerializationContext;

/**
 * A message that is sent as a reply to a {@link AdminRequest}.
 */
public abstract class AdminResponse extends HighPriorityDistributionMessage
    implements AdminMessageType {

  // instance variables

  private int msgId; // message id of request this is a response to

  // instance methods

  int getMsgId() {
    return this.msgId;
  }

  public void setMsgId(int msgId) {
    this.msgId = msgId;
  }

  @Override
  public boolean sendViaUDP() {
    return true;
  }

  /**
   * This method is invoked on the side that sent the original AdminRequest.
   */
  @Override
  protected void process(ClusterDistributionManager dm) {
    AdminWaiters.sendResponse(this);
  }

  @Override
  public void toData(DataOutput out,
      SerializationContext context) throws IOException {
    // System.out.println("BEGIN AdminResponse toData");
    super.toData(out, context);
    out.writeInt(this.msgId);
    // System.out.println("END AdminResponse toData");
  }

  @Override
  public void fromData(DataInput in,
      DeserializationContext context) throws IOException, ClassNotFoundException {
    super.fromData(in, context);
    this.msgId = in.readInt();
  }

  public InternalDistributedMember getRecipient() {
    List<InternalDistributedMember> recipients = getRecipients();
    int size = recipients.size();
    if (size == 0) {
      return null;
    } else if (size > 1) {
      throw new IllegalStateException(String
          .format("Could not return one recipient because this message has %s recipients", size));
    } else {
      return recipients.get(0);
    }
  }
}


text:
*By [Jack Dougherty](../../introduction/who.md), last updated December 8, 2016*

GitBook offers different ways to compose your books, and each method has its own advantages. Typically, I compose text using the GitBook web editor or desktop editor, or modify files with the Atom text editor and push these changes to my GitHub repository with GitHub Desktop. None of these steps require using Git on the command line.

## Compose with GitBook WEB Editor:

Advantages: WYSIWYG preview, Markdown menu, proofreader toggle, branch control

1. Check GitHub repo for any pull requests from contributors: https://github.com/JackDougherty/
2. Startup browser editor, temporarily create a new branch (dev) to avoid continually building master branch
3. Write and save edits on each page
4. When done, merge branches (push dev branch into master branch)
5. When done, delete the dev branch to avoid confusion in future

## Compose with GitBook DESKTOP Editor

Advantages: WYSIWYG preview, Markdown menu, proofreader toggle, branch and sync control

Disadvantage: links and images appear, but requires clicking on Markdown version to edit

1. Check GitHub repo for any pull requests from contributors: https://github.com/JackDougherty/
2. Startup Desktop Editor app and CLONE current book from GitHub to local computer
3. Create a temporary new branch (dev)
4. Write and save edits on each page
5. When done, merge branches (push dev into master) and sync
6. Delete the dev branch to avoid confusion
7. Delete the CLONE of the book from my local computer to avoid confusion

## Compose with Atom Editor and GitHub Desktop

Advantages: This method works best when making major changes to the book, such as reorganizing the folder-file structure, rethinking the table of contents, and adding images into specific folders.

Disadvantages: For novice users, requires basic knowledge of GitHub web interface, GitHub Desktop, and a text editor (such as Atom Editor)

1. Check GitHub repo for any pull requests from contributors: https://github.com/JackDougherty/
3. Use GitHub Desktop to sync repo to my local computer
4. Use Atom editor to edit, upload, restructure files
5. Use GitHub Desktop to commit changes to online repo master branch

## My Settings
- TO DO: explain GitBook-GitHub link; custom domain

{% footer %}
{% endfooter %}


text:
import os
import re
import setuptools
import sys

# Find the directory where the source distribution was unpacked.
source_directory = os.path.dirname(os.path.abspath(__file__))

# Add the directory with the source distribution to the search path.
sys.path.append(source_directory)

# Import the module to find the version number (this is safe to do because we
# don't import any external dependencies from preview_markup/__init__.py).
from preview_markup import __version__ as version_string

# Fill in the long description (for the benefit of PyPI)
# with the contents of README.rst (rendered by GitHub).
readme_file = os.path.join(source_directory, 'README.rst')
readme_text = open(readme_file, 'r').read()

# Fill in the installation requirements based on requirements.txt.
requirements_file = os.path.join(source_directory, 'requirements.txt')
requirements = list(filter(None, (re.sub('^\s*#.*|\s#.*', '', line).strip() for line in open(requirements_file))))

setuptools.setup(
    name='preview-markup',
    version=version_string,
    description="Live preview Markdown and reStructuredText files as HTML in a web browser",
    long_description=readme_text,
    url='https://github.com/xolox/python-preview-markup',
    author="Peter Odding",
    author_email='peter@peterodding.com',
    packages=setuptools.find_packages(),
    include_package_data=True,
    entry_points=dict(console_scripts=['preview-markup = preview_markup.cli:main']),
    install_requires=requirements,
    classifiers=[
        'Development Status :: 4 - Beta',
        'Environment :: Console',
        'Environment :: Web Environment',
        'Framework :: Flask',
        'Intended Audience :: Developers',
        'Intended Audience :: Information Technology',
        'Intended Audience :: System Administrators',
        'License :: OSI Approved :: MIT License',
        'Programming Language :: Python :: 2.6',
        'Programming Language :: Python :: 2.7',
        'Topic :: Documentation',
        'Topic :: Internet :: WWW/HTTP :: Browsers',
        'Topic :: Software Development :: Documentation',
        'Topic :: Text Processing',
        'Topic :: Text Processing :: Filters',
        'Topic :: Text Processing :: Markup :: HTML',
        'Topic :: Utilities'])


text:
NAMESPACE=epizza
NAME=order-ui
TAG=latest
IMAGE=${NAMESPACE}/${NAME}:${TAG}

docker build --no-cache -t ${IMAGE} .
#docker push ${IMAGE}


text:
namespace SeoCash.Web.Classes.Navigation
{
    /// <summary>
    /// Элемент навигационной цепочки
    /// </summary>
    public class NavigationChainItem
    {
        /// <summary>
        /// Заголовок ссылки
        /// </summary>
        public string Title { get; set; }

        /// <summary>
        /// Описание - всплывающая подсказка
        /// </summary>
        public string Description { get; set; }

        /// <summary>
        /// Адрес куда она ведет
        /// </summary>
        public string Url { get; set; }

        /// <summary>
        /// Элемент доступен для кликанья и перехода по ссылке
        /// </summary>
        public bool Active { get; set; }
    }
}


text:
import { connect } from 'react-redux';
import cx from 'classnames';
import { defineMessages, FormattedMessage, injectIntl } from 'react-intl';
import ImmutablePropTypes from 'react-immutable-proptypes';
import PropTypes from 'prop-types';
import React from 'react';

import { addActiveFilter } from '../../actions/FiltersActions';
import BlankSlate from '../ui/BlankSlate';
import { getCurrentPlanName } from '../../selectors/plans';
import { InlineLoader, Loader } from '../ui/Loader';
import {
  fetchValidations,
  runValidation
} from '../../actions/ValidationsActions';
import ValidationsToolbar from './ValidationsToolbar';
import Validation from './Validation';
import ValidationDetail from './ValidationDetail';
import {
  fetchWorkflowExecutions,
  updateWorkflowExecution
} from '../../actions/WorkflowExecutionsActions';
import { getFilteredValidations } from '../../selectors/validations';

const messages = defineMessages({
  loadingValidations: {
    id: 'ValidationsList.loadingValidations',
    defaultMessage: 'Loading Validations...'
  },
  noValidations: {
    id: 'ValidationsList.noValidations',
    defaultMessage: 'No Validations'
  },
  noValidationsMessage: {
    id: 'ValidationsList.noValidationsMessage',
    defaultMessage: 'There are no validations at this time.'
  },
  refresh: {
    id: 'ValidationsList.refresh',
    defaultMessage: 'Refresh'
  },
  validations: {
    id: 'ValidationsList.validations',
    defaultMessage: 'Validations'
  }
});

class ValidationsList extends React.Component {
  constructor() {
    super();
    this.state = {
      showDetail: null
    };
  }

  componentDidMount() {
    this.props.fetchValidations();
  }

  refreshValidations() {
    this.props.fetchValidations();
    this.props.fetchWorkflowExecutions();
  }

  showValidationDetail(uuid) {
    this.setState({ showDetail: uuid });
  }

  hideValidationDetail() {
    this.setState({ showDetail: null });
  }

  rendervalidationDetail() {
    if (this.state.showDetail) {
      const validation = this.props.validations.get(this.state.showDetail);
      return (
        <ValidationDetail
          description={validation.description}
          groups={validation.groups}
          hideValidationDetail={this.hideValidationDetail.bind(this)}
          name={validation.name}
          results={validation.results}
          runValidation={this.props.runValidation.bind(
            this,
            validation.id,
            this.props.currentPlanName
          )}
          status={validation.status}
          stopValidation={this.props.stopValidation.bind(this)}
        />
      );
    }
  }

  renderValidations() {
    const { validations, currentPlanName } = this.props;

    if (validations.isEmpty()) {
      return (
        <BlankSlate
          iconClass="pficon pficon-flag"
          title={this.props.intl.formatMessage(messages.noValidations)}
        >

            <FormattedMessage {...messages.noValidationsMessage} />

        </BlankSlate>
      );
    } else {
      return validations
        .toList()
        .map(validation => (
          <Validation
            key={validation.id}
            name={validation.name}
            results={validation.results}
            status={validation.status}
            groups={validation.groups}
            showValidationDetail={this.showValidationDetail.bind(
              this,
              validation.id
            )}
            runValidation={this.props.runValidation.bind(
              this,
              validation.id,
              currentPlanName
            )}
            stopValidation={this.props.stopValidation.bind(this)}
            description={validation.description}
            id={validation.id}
            addActiveFilter={this.props.addActiveFilter}
          />
        ));
    }
  }

  render() {
    const { intl: { formatMessage }, showValidations } = this.props;

    return (

              <FormattedMessage {...messages.validations} />

                <InlineLoader
                  loaded={
                    !(
                      this.props.validationsLoaded &&
                      this.props.isFetchingValidations
                    )
                  }
                  component="small"
                  content={formatMessage(messages.loadingValidations)}
                >

                    {' '}
                    <FormattedMessage {...messages.refresh} />

                </InlineLoader>

          <ValidationsToolbar />
          <Loader
            loaded={this.props.validationsLoaded && this.props.executionsLoaded}
            content={formatMessage(messages.loadingValidations)}
            component={({ children }) => (

{children}

            )}
            height={80}
          >

              {this.renderValidations()}

          </Loader>

        {this.rendervalidationDetail()}

    );
  }
}

ValidationsList.propTypes = {
  addActiveFilter: PropTypes.func.isRequired,
  currentPlanName: PropTypes.string,
  executionsLoaded: PropTypes.bool.isRequired,
  fetchValidations: PropTypes.func.isRequired,
  fetchWorkflowExecutions: PropTypes.func.isRequired,
  intl: PropTypes.object,
  isFetchingValidations: PropTypes.bool.isRequired,
  runValidation: PropTypes.func.isRequired,
  showValidations: PropTypes.bool.isRequired,
  stopValidation: PropTypes.func.isRequired,
  validations: ImmutablePropTypes.map.isRequired,
  validationsLoaded: PropTypes.bool.isRequired
};

const mapDispatchToProps = dispatch => ({
  addActiveFilter: data =>
    dispatch(addActiveFilter('validationsToolbar', data)),
  fetchValidations: () => dispatch(fetchValidations()),
  fetchWorkflowExecutions: () => dispatch(fetchWorkflowExecutions()),
  runValidation: (id, currentPlanName) => {
    dispatch(runValidation(id, currentPlanName));
  },
  stopValidation: executionId => {
    dispatch(
      updateWorkflowExecution(executionId, {
        state: 'PAUSED'
      })
    );
  }
});

const mapStateToProps = state => ({
  executionsLoaded: state.executions.get('executionsLoaded'),
  isFetchingValidations: state.validations.get('isFetching'),
  validations: getFilteredValidations(state),
  validationsLoaded: state.validations.get('validationsLoaded'),
  currentPlanName: getCurrentPlanName(state),
  showValidations: state.validations.showValidations
});

export default injectIntl(
  connect(mapStateToProps, mapDispatchToProps)(ValidationsList)
);


text:
package com.instructure.canvasapi.api;

import com.instructure.canvasapi.model.CanvasContext;
import com.instructure.canvasapi.model.FileFolder;
import com.instructure.canvasapi.utilities.APIHelpers;
import com.instructure.canvasapi.utilities.CanvasCallback;
import com.instructure.canvasapi.utilities.LinkHeaders;

import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;
import retrofit.http.DELETE;
import retrofit.http.GET;
import retrofit.http.Path;

public class FileFolderAPI extends BuildInterfaceAPI {

    interface FilesFoldersInterface {
        @GET("/{context_id}/folders/root")
        void getRootFolderForContext(@Path("context_id") long context_id, Callback<FileFolder> callback);

        @GET("/self/folders/root")
        void getRootUserFolder(Callback<FileFolder> callback);

        @GET("/folders/{folderid}/folders")
        void getFirstPageFolders(@Path("folderid") long folder_id, Callback<FileFolder[]> callback);

        @GET("/folders/{folderid}/files")
        void getFirstPageFiles(@Path("folderid") long folder_id, Callback<FileFolder[]> callback);

        @GET("/{fileurl}")
        void getFileFolderFromURL(@Path(value = "fileurl", encode = false) String fileURL, Callback<FileFolder> callback);

        @GET("/{next}")
        void getNextPageFileFoldersList(@Path(value = "next", encode = false) String nextURL, Callback<FileFolder[]> callback);

        @DELETE("/files/{fileid}")
        void deleteFile(@Path("fileid")long fileId, Callback<Response> callback);
    }

    /////////////////////////////////////////////////////////////////////////
    // API Calls
    /////////////////////////////////////////////////////////////////////////

    public static void getFirstPageFoldersRoot(CanvasContext canvasContext, final CanvasCallback<FileFolder[]> callback) {
        if (APIHelpers.paramIsNull(callback, canvasContext)) {
            return;
        }

        // Build a callback bridge. Use a CanvasCallback instead of a regular callback so we can use caching appropriately and
        // not have to make more API calls than necessary
        Callback<FileFolder> bridgeCallback = new CanvasCallback<FileFolder>(callback.getStatusDelegate()) {

            @Override
            public void cache(FileFolder fileFolder, LinkHeaders linkHeaders, Response response) {
                buildCacheInterface(FilesFoldersInterface.class, callback, null).getFirstPageFolders(fileFolder.getId(), callback);
            }

            @Override
            public void firstPage(FileFolder fileFolder, LinkHeaders linkHeaders, Response response) {

                //Handle if the fragment becomes detached. This isn't a CanvasCallback, so it's not automatic.
                if(callback == null || callback.getContext() == null) {return;}

                buildInterface(FilesFoldersInterface.class, callback, null).getFirstPageFolders(fileFolder.getId(), callback);
            }

            @Override
            public void failure(RetrofitError retrofitError) {
                callback.failure(retrofitError);
            }
        };

        // get from cache
        getRootFolder(canvasContext, true, callback, bridgeCallback);

        // get from network
        getRootFolder(canvasContext, false, callback, bridgeCallback);

    }

    public static void getFirstPageFilesRoot(CanvasContext canvasContext, final CanvasCallback<FileFolder[]> callback) {
        getFirstPageFilesRootChained(canvasContext, false, callback);
    }

    public static void getFirstPageFilesRootChained(CanvasContext canvasContext, boolean isCached, final CanvasCallback<FileFolder[]> callback) {
        if (APIHelpers.paramIsNull(callback, canvasContext)) {
            return;
        }

        // Build a callback bridge. Use a CanvasCallback instead of a regular callback so we can use caching appropriately and
        // not have to make more API calls than necessary
        Callback<FileFolder> bridgeCallback = new CanvasCallback<FileFolder>(callback.getStatusDelegate()) {

            @Override
            public void cache(FileFolder fileFolder, LinkHeaders linkHeaders, Response response) {
                buildCacheInterface(FilesFoldersInterface.class, callback, null).getFirstPageFiles(fileFolder.getId(), callback);
            }

            @Override
            public void firstPage(FileFolder fileFolder, LinkHeaders linkHeaders, Response response) {

                //Handle if the fragment becomes detached. This isn't a CanvasCallback, so it's not automatic.
                if(callback == null || callback.getContext() == null) {return;}

                buildInterface(FilesFoldersInterface.class, callback, null).getFirstPageFiles(fileFolder.getId(), callback);
            }

            @Override
            public void failure(RetrofitError retrofitError) {
                callback.failure(retrofitError);
            }
        };

        getRootFolder(canvasContext, isCached, callback, bridgeCallback);
    }

    private static void getRootFolder(CanvasContext canvasContext, boolean isCached, CanvasCallback callback, Callback<FileFolder> bridgeCallback) {
        FilesFoldersInterface foldersInterface = buildInterface(FilesFoldersInterface.class, callback, canvasContext);

        if (canvasContext.getType() == CanvasContext.Type.USER) {
            if(isCached) {
                buildCacheInterface(FilesFoldersInterface.class, callback, canvasContext).getRootUserFolder(bridgeCallback);
            } else {
                foldersInterface.getRootUserFolder(bridgeCallback);
            }
        } else {
            if(isCached) {
                buildCacheInterface(FilesFoldersInterface.class, callback, canvasContext).getRootFolderForContext(canvasContext.getId(), bridgeCallback);
            } else {
                foldersInterface.getRootFolderForContext(canvasContext.getId(), bridgeCallback);
            }
        }
    }

    public static void getFirstPageFolders(long folderid, CanvasCallback<FileFolder[]> callback) {
        if (APIHelpers.paramIsNull(callback) || folderid <= 0) {
            return;
        }

        buildCacheInterface(FilesFoldersInterface.class, callback, null).getFirstPageFolders(folderid, callback);
        buildInterface(FilesFoldersInterface.class, callback, null).getFirstPageFolders(folderid, callback);
    }

    public static void getFirstPageFiles(long folderid, CanvasCallback<FileFolder[]> callback) {
        if (APIHelpers.paramIsNull(callback) || folderid <= 0) {
            return;
        }

        buildCacheInterface(FilesFoldersInterface.class, callback, null).getFirstPageFiles(folderid, callback);
        buildInterface(FilesFoldersInterface.class, callback, null).getFirstPageFiles(folderid, callback);
    }

    public static void getFirstPageFilesChained(long folderid, boolean isCached, CanvasCallback<FileFolder[]> callback) {
        if (APIHelpers.paramIsNull(callback) || folderid <= 0) {
            return;
        }

        if(isCached) {
            buildCacheInterface(FilesFoldersInterface.class, callback, null).getFirstPageFiles(folderid, callback);
        } else {
            buildInterface(FilesFoldersInterface.class, callback, null).getFirstPageFiles(folderid, callback);
        }
    }

    public static void getNextPageFileFolders(String nextURL, CanvasCallback<FileFolder[]> callback) {
        if (APIHelpers.paramIsNull(callback, nextURL)) {
            return;
        }

        callback.setIsNextPage(true);
        buildCacheInterface(FilesFoldersInterface.class, callback, false).getNextPageFileFoldersList(nextURL, callback);
        buildInterface(FilesFoldersInterface.class, callback, false).getNextPageFileFoldersList(nextURL, callback);
    }

    public static void getFileFolderFromURL(String url, CanvasCallback<FileFolder> callback) {
        if (APIHelpers.paramIsNull(callback, url)) {
            return;
        }

        buildCacheInterface(FilesFoldersInterface.class, callback, null).getFileFolderFromURL(url, callback);
        buildInterface(FilesFoldersInterface.class, callback, null).getFileFolderFromURL(url, callback);
    }

    public static void deleteFile(long fileId, CanvasCallback<Response> callback) {
        if (APIHelpers.paramIsNull(callback)) {
            return;
        }

        buildInterface(FilesFoldersInterface.class, callback, null).deleteFile(fileId,callback);
    }
}


text:
package org.apereo.cas.web.support;

import org.springframework.web.servlet.AsyncHandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Collection;
import java.util.List;

/**
 * This is {@link ThrottledSubmissionHandlerInterceptor}.
 *
 * @author Misagh Moayyed
 * @since 5.0.0
 */
public interface ThrottledSubmissionHandlerInterceptor extends AsyncHandlerInterceptor {

    /**
     * No op throttled submission handler interceptor.
     *
     * @return the throttled submission handler interceptor
     */
    static ThrottledSubmissionHandlerInterceptor noOp() {
        return new ThrottledSubmissionHandlerInterceptor() {
        };
    }

    /**
     * Record submission failure.
     *
     * @param request the request
     */
    default void recordSubmissionFailure(final HttpServletRequest request) {
    }

    /**
     * Determine whether threshold has been exceeded.
     *
     * @param request the request
     * @return true, if successful
     */
    default boolean exceedsThreshold(final HttpServletRequest request) {
        return false;
    }

    /**
     * Gets name.
     *
     * @return the name
     */
    default String getName() {
        return getClass().getSimpleName();
    }

    /**
     * Decrement the the throttle so authentication can resume.
     */
    default void decrement() {
    }

    /**
     * Gets all records.
     *
     * @return the all records
     */
    default Collection getRecords() {
        return List.of();
    }

    @Override
    default boolean preHandle(final HttpServletRequest request,
        final HttpServletResponse response,
        final Object handler) throws Exception {
        return true;
    }

    @Override
    default void postHandle(final HttpServletRequest request,
        final HttpServletResponse response,
        final Object handler,
        final ModelAndView modelAndView) {
    }

    @Override
    default void afterCompletion(final HttpServletRequest request,
        final HttpServletResponse response,
        final Object handler,
        final Exception e) throws Exception {
    }

    @Override
    default void afterConcurrentHandlingStarted(final HttpServletRequest request,
        final HttpServletResponse response,
        final Object handler) throws Exception {
    }
}


text:
package org.ovirt.engine.core.common.action;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;

import org.ovirt.engine.core.compat.Guid;

public class RemoveNetworkAttachmentParameters extends VdsActionParameters {

    private static final long serialVersionUID = -5132029941161321131L;

    @Valid
    @NotNull
    private Guid networkAttachmentId;

    public RemoveNetworkAttachmentParameters() {
    }

    public RemoveNetworkAttachmentParameters(Guid hostId, Guid networkAttachmentId) {
        super(hostId);
        this.networkAttachmentId = networkAttachmentId;
    }

    public Guid getNetworkAttachmentId() {
        return networkAttachmentId;
    }
}


text:
include ../Makefile.aws_byte_buf

UNWINDSET += aws_array_eq_ignore_case.0:$(shell echo $$(($(MAX_BUFFER_SIZE) + 1)))

CBMCFLAGS +=

DEPENDENCIES += $(HELPERDIR)/source/make_common_data_structures.c
DEPENDENCIES += $(HELPERDIR)/source/proof_allocators.c
DEPENDENCIES += $(HELPERDIR)/source/utils.c
DEPENDENCIES += $(HELPERDIR)/stubs/error.c
DEPENDENCIES += $(HELPERDIR)/stubs/memcmp_override.c
DEPENDENCIES += $(SRCDIR)/source/byte_buf.c
DEPENDENCIES += $(SRCDIR)/source/common.c

ENTRY = aws_array_eq_ignore_case_harness
###########

include ../Makefile.common


text:
export class StringToggle {
  private _stringValue: string;
  private _isActive: boolean;
  private _jsStringsCollection: Set<string> = null;

  constructor(stringValue: string);
  constructor(stringValue: string, isActive: boolean);
  constructor(jsStringsCollection: Set<string>, stringValue: string);
  constructor(jsStringsCollection: Set<string>, stringValue: string, isActive: boolean);
  constructor(jsStringsCollectionOrStringValue: Set<string> | string,
    stringValueOrIsActive?: string | boolean, isActive?: boolean) {
    this._jsStringsCollection = jsStringsCollectionOrStringValue &&
      typeof jsStringsCollectionOrStringValue !== 'string' ?
      jsStringsCollectionOrStringValue : null;
    this._stringValue = jsStringsCollectionOrStringValue &&
      typeof jsStringsCollectionOrStringValue === 'string' ? jsStringsCollectionOrStringValue :
      typeof stringValueOrIsActive && typeof stringValueOrIsActive === 'string' ?
        stringValueOrIsActive : null;
    this._isActive = stringValueOrIsActive && typeof stringValueOrIsActive === 'boolean' ?
      stringValueOrIsActive : isActive;
  }

  get value(): boolean {
    return this._isActive;
  }
  set value(value: boolean) {
    if (this._isActive !== value) {
      if (this._jsStringsCollection && this._isActive)
        this._jsStringsCollection.delete(this._stringValue);

      this._isActive = value;

      if (this._jsStringsCollection && this._isActive)
        this._jsStringsCollection.delete(this._stringValue);
    }
  }

  attachJSStringsCollection(jsStringsCollection: Set<string>): void {
    this._jsStringsCollection = jsStringsCollection;
  }
  detachJSStringsCollection(): void {
    this._jsStringsCollection = null;
  }
}


text:
<?php

namespace api\models;

use Yii;

class TimerCounter extends \common\models\TimerCounterBase {

}


text:
describe('TODO <ArticleBlongCommunity />', () => {
  it('Expect to have unit tests specified', () => {
    expect(true).toEqual(true)
  })
})


text:
package org.durid.sql.dialect.mysql.ast.statement;

import java.util.ArrayList;
import java.util.List;

import org.durid.sql.ast.SQLExpr;
import org.durid.sql.dialect.mysql.ast.MySqlObjectImpl;
import org.durid.sql.dialect.mysql.visitor.MySqlASTVisitor;

public class MySqlRenameTableStatement extends MySqlStatementImpl {

    private static final long serialVersionUID = 1L;

    private List<Item>        items            = new ArrayList<Item>(2);

    public List<Item> getItems() {
        return items;
    }

    public void setItems(List<Item> items) {
        this.items = items;
    }

    public void accept0(MySqlASTVisitor visitor) {
        if (visitor.visit(this)) {
            acceptChild(visitor, items);
        }
        visitor.endVisit(this);
    }

    public static class Item extends MySqlObjectImpl {

        private static final long serialVersionUID = 1L;
        private SQLExpr           name;
        private SQLExpr           to;

        public SQLExpr getName() {
            return name;
        }

        public void setName(SQLExpr name) {
            this.name = name;
        }

        public SQLExpr getTo() {
            return to;
        }

        public void setTo(SQLExpr to) {
            this.to = to;
        }

        @Override
        public void accept0(MySqlASTVisitor visitor) {
            if (visitor.visit(this)) {
                acceptChild(visitor, name);
                acceptChild(visitor, to);
            }
            visitor.endVisit(this);
        }

    }
}


text:
package com.aldebaran.demo;

import java.util.ArrayList;
import java.util.List;

import com.aldebaran.qi.Application;
import com.aldebaran.qi.CallError;
import com.aldebaran.qi.helper.EventCallback;
import com.aldebaran.qi.helper.proxies.ALMemory;
import com.aldebaran.qi.helper.proxies.ALMotion;
import com.aldebaran.qi.helper.proxies.ALSpeechRecognition;
import com.aldebaran.qi.helper.proxies.ALTextToSpeech;

/**
 * This example shows how the robot can obey to voice commands: 'wake up',
 * 'come' and 'stop'. The application will be stopped when touching the middle
 * tactile head sensor.
 */
public class ExReactToVoice {

    private static boolean isAwake = false;
    private static Application application;

    private static ALMemory alMemory;
    private static ALMotion motion;
    private static ALSpeechRecognition alSpeechRecognition;
    private static ALTextToSpeech tts;
    private static String APP_NAME = "DemoVoiceReaction";

    public static void main(String[] args) {

        application = new Application(args, RobotInfo.URL);

        try {
            application.start();

            alMemory = new ALMemory(application.session());
            motion = new ALMotion(application.session());
            alSpeechRecognition = new ALSpeechRecognition(application.session());
            tts = new ALTextToSpeech(application.session());

            ArrayList<String> listOfWords = new ArrayList<String>();
            listOfWords.add("wake up");
            listOfWords.add("come");
            listOfWords.add("stop");

            alSpeechRecognition.setVocabulary(listOfWords, false);

            alSpeechRecognition.subscribe(APP_NAME);
            alMemory.subscribeToEvent("WordRecognized",
                    new EventCallback<List<Object>>() {

                        @Override
                        public void onEvent(List<Object> words)
                                throws InterruptedException, CallError {
                            String word = (String) words.get(0);
                            System.out.println("Word " + word);

                            if (word.equals("wake") && !isAwake) {
                                tts.say("hi");
                                alSpeechRecognition.pause(true);
                                motion.wakeUp();
                                alSpeechRecognition.pause(false);
                                isAwake = true;
                            } else if (word.equals("come") && isAwake) {
                                motion.moveToward(0.6f, 0f, 0f);
                            } else if (word.equals("stop") && isAwake) {
                                motion.moveToward(0f, 0f, 0f);
                            }
                        }
                    });
            alMemory.subscribeToEvent("MiddleTactilTouched",
                    new EventCallback<Float>() {

                        @Override
                        public void onEvent(Float touch)
                                throws InterruptedException, CallError {
                            if (touch == 1.0) {
                                tts.say("Application is stopping");
                                motion.rest();
                                alSpeechRecognition.unsubscribe(APP_NAME);
                                application.stop();

                            }
                        }
                    });
            application.run();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


text:
<!DOCTYPE html>

        <meta charset="UTF-8"/>
        <meta name="viewport" content="width=device-width, initial-scale=1.0"/>

        <title>Marinating Madness</title>
        <link rel="stylesheet" href="styles.css"/>

Pre Experiment Questions

Tofu is a relatively bland food, and so people frequently marinate it to spice it up. This is exactly what you will do today. But first, some questions.

Have you ever marinated any kind of meat or tofu before? If you have, what happened when it was marinated? Try to relate what you observed to the concept of diffusion.

        <textarea class="input" rows="4" id="question_whathappenedM"></textarea>

Connect diffusion to taste. Why do people marinate meat or tofu instead of eating it plain? How does the food taste different after it was marinated? Why does the food have more flavor?

		<textarea class="input" rows="4" id="question_foodTasteDifs"></textarea>

What do you expect will happen when you add the tofu to the marinade? Will it look different? Taste different? Write down your predictions, and remember to take a photograph of the unmarinated tofu.

		<textarea class="input" rows="4" id="question_hypothesis"></textarea>

Back

Continue...


text:
namespace spvtools {
namespace fuzz {

FuzzerPassAdjustBranchWeights::FuzzerPassAdjustBranchWeights(
    opt::IRContext* ir_context, TransformationContext* transformation_context,
    FuzzerContext* fuzzer_context,
    protobufs::TransformationSequence* transformations)
    : FuzzerPass(ir_context, transformation_context, fuzzer_context,
                 transformations) {}

FuzzerPassAdjustBranchWeights::~FuzzerPassAdjustBranchWeights() = default;

void FuzzerPassAdjustBranchWeights::Apply() {
  // For all OpBranchConditional instructions,
  // randomly applies the transformation.
  GetIRContext()->module()->ForEachInst([this](opt::Instruction* instruction) {
    if (instruction->opcode() == SpvOpBranchConditional &&
        GetFuzzerContext()->ChoosePercentage(
            GetFuzzerContext()->GetChanceOfAdjustingBranchWeights())) {
      ApplyTransformation(TransformationAdjustBranchWeights(
          MakeInstructionDescriptor(GetIRContext(), instruction),
          GetFuzzerContext()->GetRandomBranchWeights()));
    }
  });
}

}  // namespace fuzz
}  // namespace spvtools


text:
  'use strict';
  function Article() {}
  Article.prototype = {
    preload: function(){
      this.game.load.json('instruction', '/assets/js/instruction.json');
    },
    create: function() {

      this.instruction = this.game.cache.getJSON('instruction').instructions;
       // console.log(this.instruction[0]);
      this.page = 0;
      this.instructionTitle  = this.game.add.text(this.game.stage.width/2, 100, this.instruction[this.page].title, {fontSize: '33px', fill: '#fff'} );
      this.instructionTitle.anchor.set(0.5);
      this.instructionBody  = this.game.add.text(this.game.stage.width/2, 200, this.instruction[this.page].body, {fontSize: '25px', fill: '#ddd', align: 'center'});
      this.instructionBody.anchor.set(0.5, 0);
      this.instructionBody.wordWrap = true;
      this.instructionBody.wordWrapWidth = this.game.stage.width - 80;
      this.pageUp = this.game.add.text(20, this.game.height - 40, "< Previous",{fontSize: '15px', fill: '#fff'});
      this.pageUp.inputEnabled = true;
      this.pageUp.input.useHandCursor = true;
      this.pageUp.events.onInputDown.add(this.prevPage, this);

      this.pageDown = this.game.add.text(this.game.width - 80, this.game.height - 40, "next >",{fontSize: '15px', fill: '#fff'});
      this.pageDown.inputEnabled = true;
      this.pageDown.input.useHandCursor = true;
      this.pageDown.events.onInputDown.add(this.nextPage, this);
      this.page++;
    },
    update: function() {

    },
    nextPage: function(){

      if(this.page < this.instruction.length){
        this.instructionTitle.setText(this.instruction[this.page].title);
        this.instructionBody.setText(this.instruction[this.page].body);
        this.page++;
      }else{
        this.clickListener();
      }
    },
    prevPage: function(){
      if(this.page != 0){
        this.instructionTitle.setText(this.instruction[this.page].title);
        this.instructionBody.setText(this.instruction[this.page].body);
        this.page--;
      }else{
        this.page = this.page;
      }

    },
    clickListener: function() {
      this.game.state.start('interminent');
    }
  };


text:
package com.reflectoring.library.util;

public class Constants {

    public static final String SUCCESS = "Success";

    public static final String ERROR = "Error";
}


text:
\section{File List}
Here is a list of all documented files with brief descriptions:\begin{DoxyCompactList}
\item\contentsline{section}{src/tmcl/{\bfseries config.h} }{\pageref{config_8h}}{}
\item\contentsline{section}{src/tmcl/{\bfseries convenience.c} }{\pageref{convenience_8c}}{}
\item\contentsline{section}{src/tmcl/\hyperlink{convenience_8h}{convenience.h} }{\pageref{convenience_8h}}{}
\item\contentsline{section}{src/tmcl/{\bfseries debug.h} }{\pageref{debug_8h}}{}
\item\contentsline{section}{src/tmcl/{\bfseries interface.c} }{\pageref{interface_8c}}{}
\item\contentsline{section}{src/tmcl/\hyperlink{interface_8h}{interface.h} }{\pageref{interface_8h}}{}
\item\contentsline{section}{src/tmcl/{\bfseries motor.c} }{\pageref{motor_8c}}{}
\item\contentsline{section}{src/tmcl/\hyperlink{motor_8h}{motor.h} }{\pageref{motor_8h}}{}
\item\contentsline{section}{src/tmcl/{\bfseries rsXXX.c} }{\pageref{rsXXX_8c}}{}
\item\contentsline{section}{src/tmcl/\hyperlink{rsXXX_8h}{rsXXX.h} }{\pageref{rsXXX_8h}}{}
\item\contentsline{section}{src/tmcl/\hyperlink{tmcl_8h}{tmcl.h} }{\pageref{tmcl_8h}}{}
\item\contentsline{section}{src/tmcl/\hyperlink{tmcldefs_8c}{tmcldefs.c} }{\pageref{tmcldefs_8c}}{}
\item\contentsline{section}{src/tmcl/\hyperlink{tmcldefs_8h}{tmcldefs.h} }{\pageref{tmcldefs_8h}}{}
\end{DoxyCompactList}


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

import com.facebook.presto.Session;
import com.facebook.presto.SessionRepresentation;
import com.facebook.presto.spi.ErrorCode;
import com.facebook.presto.spi.ErrorType;
import com.facebook.presto.spi.PrestoWarning;
import com.facebook.presto.spi.QueryId;
import com.facebook.presto.spi.memory.MemoryPoolId;
import com.facebook.presto.spi.resourceGroups.QueryType;
import com.facebook.presto.spi.resourceGroups.ResourceGroupId;
import com.facebook.presto.spi.security.SelectedRole;
import com.facebook.presto.transaction.TransactionId;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;

import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;

import java.net.URI;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;

import static com.facebook.presto.execution.QueryState.FAILED;
import static com.facebook.presto.execution.QueryStats.immediateFailureQueryStats;
import static com.facebook.presto.execution.StageInfo.getAllStages;
import static com.facebook.presto.memory.LocalMemoryManager.GENERAL_POOL;
import static com.google.common.base.MoreObjects.toStringHelper;
import static java.util.Objects.requireNonNull;

@Immutable
public class QueryInfo
{
    private final QueryId queryId;
    private final SessionRepresentation session;
    private final QueryState state;
    private final MemoryPoolId memoryPool;
    private final boolean scheduled;
    private final URI self;
    private final List<String> fieldNames;
    private final String query;
    private final QueryStats queryStats;
    private final Optional<String> setCatalog;
    private final Optional<String> setSchema;
    private final Map<String, String> setSessionProperties;
    private final Set<String> resetSessionProperties;
    private final Map<String, SelectedRole> setRoles;
    private final Map<String, String> addedPreparedStatements;
    private final Set<String> deallocatedPreparedStatements;
    private final Optional<TransactionId> startedTransactionId;
    private final boolean clearTransactionId;
    private final String updateType;
    private final Optional<StageInfo> outputStage;
    private final ExecutionFailureInfo failureInfo;
    private final ErrorType errorType;
    private final ErrorCode errorCode;
    private final List<PrestoWarning> warnings;
    private final Set<Input> inputs;
    private final Optional<Output> output;
    private final boolean completeInfo;
    private final Optional<ResourceGroupId> resourceGroupId;
    private final Optional<QueryType> queryType;
    // failedTasks is only available for final query info because the construction is expensive.
    private final Optional<List<TaskId>> failedTasks;
    // RuntimeOptimizedStages is only available for final query info, because it is appended during runtime.
    private final Optional<List<StageId>> runtimeOptimizedStages;

    @JsonCreator
    public QueryInfo(
            @JsonProperty("queryId") QueryId queryId,
            @JsonProperty("session") SessionRepresentation session,
            @JsonProperty("state") QueryState state,
            @JsonProperty("memoryPool") MemoryPoolId memoryPool,
            @JsonProperty("scheduled") boolean scheduled,
            @JsonProperty("self") URI self,
            @JsonProperty("fieldNames") List<String> fieldNames,
            @JsonProperty("query") String query,
            @JsonProperty("queryStats") QueryStats queryStats,
            @JsonProperty("setCatalog") Optional<String> setCatalog,
            @JsonProperty("setSchema") Optional<String> setSchema,
            @JsonProperty("setSessionProperties") Map<String, String> setSessionProperties,
            @JsonProperty("resetSessionProperties") Set<String> resetSessionProperties,
            @JsonProperty("setRoles") Map<String, SelectedRole> setRoles,
            @JsonProperty("addedPreparedStatements") Map<String, String> addedPreparedStatements,
            @JsonProperty("deallocatedPreparedStatements") Set<String> deallocatedPreparedStatements,
            @JsonProperty("startedTransactionId") Optional<TransactionId> startedTransactionId,
            @JsonProperty("clearTransactionId") boolean clearTransactionId,
            @JsonProperty("updateType") String updateType,
            @JsonProperty("outputStage") Optional<StageInfo> outputStage,
            @JsonProperty("failureInfo") ExecutionFailureInfo failureInfo,
            @JsonProperty("errorCode") ErrorCode errorCode,
            @JsonProperty("warnings") List<PrestoWarning> warnings,
            @JsonProperty("inputs") Set<Input> inputs,
            @JsonProperty("output") Optional<Output> output,
            @JsonProperty("completeInfo") boolean completeInfo,
            @JsonProperty("resourceGroupId") Optional<ResourceGroupId> resourceGroupId,
            @JsonProperty("queryType") Optional<QueryType> queryType,
            @JsonProperty("failedTasks") Optional<List<TaskId>> failedTasks,
            @JsonProperty("runtimeOptimizedStages") Optional<List<StageId>> runtimeOptimizedStages)
    {
        requireNonNull(queryId, "queryId is null");
        requireNonNull(session, "session is null");
        requireNonNull(state, "state is null");
        requireNonNull(self, "self is null");
        requireNonNull(fieldNames, "fieldNames is null");
        requireNonNull(queryStats, "queryStats is null");
        requireNonNull(setCatalog, "setCatalog is null");
        requireNonNull(setSchema, "setSchema is null");
        requireNonNull(setSessionProperties, "setSessionProperties is null");
        requireNonNull(resetSessionProperties, "resetSessionProperties is null");
        requireNonNull(addedPreparedStatements, "addedPreparedStatemetns is null");
        requireNonNull(deallocatedPreparedStatements, "deallocatedPreparedStatements is null");
        requireNonNull(startedTransactionId, "startedTransactionId is null");
        requireNonNull(query, "query is null");
        requireNonNull(outputStage, "outputStage is null");
        requireNonNull(inputs, "inputs is null");
        requireNonNull(output, "output is null");
        requireNonNull(resourceGroupId, "resourceGroupId is null");
        requireNonNull(warnings, "warnings is null");
        requireNonNull(queryType, "queryType is null");
        requireNonNull(failedTasks, "failedTasks is null");
        requireNonNull(runtimeOptimizedStages, "runtimeOptimizedStages is null");

        this.queryId = queryId;
        this.session = session;
        this.state = state;
        this.memoryPool = requireNonNull(memoryPool, "memoryPool is null");
        this.scheduled = scheduled;
        this.self = self;
        this.fieldNames = ImmutableList.copyOf(fieldNames);
        this.query = query;
        this.queryStats = queryStats;
        this.setCatalog = setCatalog;
        this.setSchema = setSchema;
        this.setSessionProperties = ImmutableMap.copyOf(setSessionProperties);
        this.resetSessionProperties = ImmutableSet.copyOf(resetSessionProperties);
        this.setRoles = ImmutableMap.copyOf(setRoles);
        this.addedPreparedStatements = ImmutableMap.copyOf(addedPreparedStatements);
        this.deallocatedPreparedStatements = ImmutableSet.copyOf(deallocatedPreparedStatements);
        this.startedTransactionId = startedTransactionId;
        this.clearTransactionId = clearTransactionId;
        this.updateType = updateType;
        this.outputStage = outputStage;
        this.failureInfo = failureInfo;
        this.errorType = errorCode == null ? null : errorCode.getType();
        this.errorCode = errorCode;
        this.warnings = ImmutableList.copyOf(warnings);
        this.inputs = ImmutableSet.copyOf(inputs);
        this.output = output;
        this.completeInfo = completeInfo;
        this.resourceGroupId = resourceGroupId;
        this.queryType = queryType;
        this.failedTasks = failedTasks;
        this.runtimeOptimizedStages = runtimeOptimizedStages;
    }

    public static QueryInfo immediateFailureQueryInfo(Session session, String query, URI self, Optional<ResourceGroupId> resourceGroupId, ExecutionFailureInfo failureCause)
    {
        QueryInfo queryInfo = new QueryInfo(
                session.getQueryId(),
                session.toSessionRepresentation(),
                FAILED,
                GENERAL_POOL,
                false,
                self,
                ImmutableList.of(),
                query,
                immediateFailureQueryStats(),
                Optional.empty(),
                Optional.empty(),
                ImmutableMap.of(),
                ImmutableSet.of(),
                ImmutableMap.of(),
                ImmutableMap.of(),
                ImmutableSet.of(),
                Optional.empty(),
                false,
                null,
                Optional.empty(),
                failureCause.getCause(),
                failureCause.getErrorCode(),
                ImmutableList.of(),
                ImmutableSet.of(),
                Optional.empty(),
                false,
                resourceGroupId,
                Optional.empty(),
                Optional.empty(),
                Optional.empty());

        return queryInfo;
    }

    @JsonProperty
    public QueryId getQueryId()
    {
        return queryId;
    }

    @JsonProperty
    public SessionRepresentation getSession()
    {
        return session;
    }

    @JsonProperty
    public QueryState getState()
    {
        return state;
    }

    @JsonProperty
    public MemoryPoolId getMemoryPool()
    {
        return memoryPool;
    }

    @JsonProperty
    public boolean isScheduled()
    {
        return scheduled;
    }

    @JsonProperty
    public URI getSelf()
    {
        return self;
    }

    @JsonProperty
    public List<String> getFieldNames()
    {
        return fieldNames;
    }

    @JsonProperty
    public String getQuery()
    {
        return query;
    }

    @JsonProperty
    public QueryStats getQueryStats()
    {
        return queryStats;
    }

    @JsonProperty
    public Optional<String> getSetCatalog()
    {
        return setCatalog;
    }

    @JsonProperty
    public Optional<String> getSetSchema()
    {
        return setSchema;
    }

    @JsonProperty
    public Map<String, String> getSetSessionProperties()
    {
        return setSessionProperties;
    }

    @JsonProperty
    public Set<String> getResetSessionProperties()
    {
        return resetSessionProperties;
    }

    @JsonProperty
    public Map<String, SelectedRole> getSetRoles()
    {
        return setRoles;
    }

    @JsonProperty
    public Map<String, String> getAddedPreparedStatements()
    {
        return addedPreparedStatements;
    }

    @JsonProperty
    public Set<String> getDeallocatedPreparedStatements()
    {
        return deallocatedPreparedStatements;
    }

    @JsonProperty
    public Optional<TransactionId> getStartedTransactionId()
    {
        return startedTransactionId;
    }

    @JsonProperty
    public boolean isClearTransactionId()
    {
        return clearTransactionId;
    }

    @Nullable
    @JsonProperty
    public String getUpdateType()
    {
        return updateType;
    }

    @JsonProperty
    public Optional<StageInfo> getOutputStage()
    {
        return outputStage;
    }

    @Nullable
    @JsonProperty
    public ExecutionFailureInfo getFailureInfo()
    {
        return failureInfo;
    }

    @Nullable
    @JsonProperty
    public ErrorType getErrorType()
    {
        return errorType;
    }

    @Nullable
    @JsonProperty
    public ErrorCode getErrorCode()
    {
        return errorCode;
    }

    @JsonProperty
    public List<PrestoWarning> getWarnings()
    {
        return warnings;
    }

    @JsonProperty
    public boolean isFinalQueryInfo()
    {
        return state.isDone() && getAllStages(outputStage).stream().allMatch(StageInfo::isFinalStageInfo);
    }

    @JsonProperty
    public Set<Input> getInputs()
    {
        return inputs;
    }

    @JsonProperty
    public Optional<Output> getOutput()
    {
        return output;
    }

    @JsonProperty
    public Optional<ResourceGroupId> getResourceGroupId()
    {
        return resourceGroupId;
    }

    @JsonProperty
    public Optional<QueryType> getQueryType()
    {
        return queryType;
    }

    @JsonProperty
    public Optional<List<TaskId>> getFailedTasks()
    {
        return failedTasks;
    }

    @JsonProperty
    public Optional<List<StageId>> getRuntimeOptimizedStages()
    {
        return runtimeOptimizedStages;
    }

    @Override
    public String toString()
    {
        return toStringHelper(this)
                .add("queryId", queryId)
                .add("state", state)
                .add("fieldNames", fieldNames)
                .toString();
    }

    public boolean isCompleteInfo()
    {
        return completeInfo;
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.lleggieri</groupId>
    <artifactId>java-concurrent-lock</artifactId>
    <version>1.0-SNAPSHOT</version>

    <scm>
        <url>https://github.com/lukiano/java-concurrent-lock</url>
        <connection>scm:git:git://github.com/lukiano/java-concurrent-lock.git</connection>
        <developerConnection>scm:git:git@github.com:lukiano/java-concurrent-lock.git</developerConnection>
    </scm>

    <developers>
        <developer>
            <email>230980@gmail.com</email>
            <name>Luciano Leggieri</name>
            <url>https://github.com/lukiano</url>
        </developer>
    </developers>

    <licenses>
        <license>
            <name>Apache 2</name>
            <distribution>repo</distribution>
            <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
        </license>
    </licenses>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>com.google.code.findbugs</groupId>
            <artifactId>jsr305</artifactId>
            <version>3.0.0</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>net.javacrumbs.completion-stage</groupId>
            <artifactId>completion-stage</artifactId>
            <version>0.0.5</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.3</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>


text:
layout: page
title: Seattle Police Officer 6742 Samuel R. Byrd
permalink: /information/agencies/city_of_seattle/seattle_police_department/copbook/6742/
---

**Age as of Feb. 24, 2016:** 44


text:
My Incredibly Unhealthy Obsession With Success

<time>Apr 30, 2017</time>

Self-Awareness: The Two-Step Tango

<time>Apr 16, 2017</time>

Success Is A Verifiable System

<time>Mar 31, 2017</time>

Non-Postal

<time>Mar 16, 2017</time>

What It Means To Be An Effective Adult

<time>Feb 19, 2017</time>

An Intuitive And Simple Guide To Understanding Your Depression

<time>Feb 8, 2017</time>

Why Young Men Resort To Pick Up

<time>Jan 22, 2017</time>

Have You An Effective Communication With You And Me

<time>Jan 8, 2017</time>

Please Don't Tell Me You're Sorry

<time>Dec 25, 2016</time>

Smart People Don't Think. They Plan Ahead

<time>Dec 11, 2016</time>

Why Obtaining A Full-time Job Should Be Your Number One Priority

<time>Nov 27, 2016</time>

What It Means To Be A Porn Addict

<time>Nov 13, 2016</time>

Intuitive Explanations Make You Dizzyingly Smart

<time>Oct 30, 2016</time>


text:
require_relative '../../migration_helpers'

module RuboCop
  module Cop
    module Migration
      # Cop that checks if `add_column_with_default` is used with `up`/`down` methods
      # and not `change`.
      class ReversibleAddColumnWithDefault < RuboCop::Cop::Cop
        include MigrationHelpers

        def_node_matcher :add_column_with_default?, <<~PATTERN
          (send nil? :add_column_with_default $...)
        PATTERN

        def_node_matcher :defines_change?, <<~PATTERN
          (def :change ...)
        PATTERN

        MSG = '`add_column_with_default` is not reversible so you must manually define ' \
          'the `up` and `down` methods in your migration class, using `remove_column` in `down`'.freeze

        def on_send(node)
          return unless in_migration?(node)
          return unless add_column_with_default?(node)

          node.each_ancestor(:def) do |def_node|
            next unless defines_change?(def_node)

            add_offense(def_node, location: :name)
          end
        end
      end
    end
  end
end


text:
require 'test_helper'

class BigosEventsReservationBoxTest < ActiveSupport::TestCase
  test "truth" do
    assert_kind_of Module, BigosEventsReservationBox
  end
end


text:
<?php
require_once (__DIR__ . '/../internals/website.php');

/** @var PageFrameOptions $FRAME_OPTIONS */ global $FRAME_OPTIONS;
/** @var URLRoute $ROUTE */ global $ROUTE;
/** @var Website $SITE */ global $SITE;
?>

<?php
$redirect = $ROUTE->parameter['logout_target'];
$SITE->clearLoginCookie();
?>

You have been logged out
<script>  setTimeout(function () { window.location.href = "<?php echo $redirect; ?>"; }, 1000);  </script>


text:
SQLALCHEMY_DATABASE_URI = 'sqlite:///../database.db'

# The folder where uploaded images should be put into. Remember that on
# production files from inside there should be served by web server on
# static files URL (by default /files, see initialization of Flask class in
# tsserver/__init__.py for that)
PHOTOS_UPLOAD_FOLDER = '../files'

# Allowed extensions for photos
PHOTOS_ALLOWED_EXTENSIONS = {'jpg', 'jpeg'}

# User credentials required to add data
USERNAME = 'client'
# Remember to change this (preferably to long random string) on production!
PASSWORD = 'secret'


text:
@implementation BCHRefreshConfig

NSString *const BCHRefreshKeyPathContentOffset = @"contentOffset";
NSString *const BCHRefreshKeyPathContentSize = @"contentSize";

CGFloat const BCHRefreshHeaderHeight = 45;
CGFloat const BCHRefreshFooterHeight = 45;

CGFloat const BCHRefreshHeaderTipLableWidth = 150;

CGFloat const BCHRefreshFastAnimalDuring = 0.25;
CGFloat const BCHRefreshSlowAnimalDuring = 0.4;

@end


text:
package org.xcolab.service.utils.db.jooq.config;

import org.jooq.ExecuteContext;
import org.jooq.SQLDialect;
import org.jooq.impl.DefaultExecuteListener;
import org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator;
import org.springframework.jdbc.support.SQLExceptionTranslator;
import org.springframework.jdbc.support.SQLStateSQLExceptionTranslator;

public class JooqToSpringExceptionTransformer extends DefaultExecuteListener {

    private static final long serialVersionUID = 112390128309L;

    @Override
    public void exception(ExecuteContext ctx) {
        SQLDialect dialect = ctx.configuration().dialect();
        SQLExceptionTranslator translator = (dialect != null)
                ? new SQLErrorCodeSQLExceptionTranslator(dialect.name())
                : new SQLStateSQLExceptionTranslator();

        ctx.exception(translator.translate("jOOQ", ctx.sql(), ctx.sqlException()));
    }
}


text:
var MongoClient = require('mongodb').MongoClient;

// Connect to the db
MongoClient.connect("mongodb://localhost:27017/cal", function(err, db) {
  if(!err) {
    alert("mongodb connected!");
  }
});

document.write("{\"name\": \"forman\"}");


text:
using System.Collections;
using System.Diagnostics.CodeAnalysis;

namespace Xunit.Sdk
{
    /// <summary>
    /// Exception thrown when a set is not a superset of another set.
    /// </summary>
    [SuppressMessage("Microsoft.Design", "CA1032:ImplementStandardExceptionConstructors")]
    public class SupersetException : AssertActualExpectedException
    {
        /// <summary>
        /// Creates a new instance of the <see cref="SupersetException"/> class.
        /// </summary>
        public SupersetException(IEnumerable expected, IEnumerable actual)
            : base(expected, actual, "Assert.Superset() Failure") { }
    }
}


text:
script_name=$(basename -- "$0")

if ! [ $(id -u) = 0 ]; then
   echo "usage: sudo ./$script_name"
   exit 1
fi

# create jupyter.sh in /home/pi and make it executable
cat << 'ONE' > /home/pi/jupyter_start.sh && chmod a+x /home/pi/jupyter_start.sh
#!/bin/bash
. /home/pi/.venv/jns/bin/activate
jupyter lab
#jupyter notebook
ONE

cat << 'TWO' | sudo tee /etc/systemd/system/jupyter.service
[Unit]
Description=Jupyter

[Service]
Type=simple
ExecStart=/home/pi/jupyter_start.sh
User=pi
Group=pi
WorkingDirectory=/home/pi/notebooks
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target
TWO

# start jupyter
systemctl daemon-reload
systemctl start jupyter
systemctl enable jupyter


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

Classes for combining tool outputs into consolidated FITS output.


text:
require  'spec_helper'

describe Admin::Generic::DealsController do
  # fixtures :all
  render_views

  before(:each) do
    activate_authlogic
    @user = create_admin_user
    login_as(@user)
  end

  it "index action should render index template" do
    deal = create(:deal)
    get :index
    response.should render_template(:index)
  end

  it "show action should render show template" do
    deal = create(:deal)
    get :show, :id => deal.id
    response.should render_template(:show)
  end

  it "new action should render new template" do
    get :new
    response.should render_template(:new)
  end

  it "create action should render new template when model is invalid" do
    deal = FactoryGirl.build(:deal)
    Deal.any_instance.stubs(:valid?).returns(false)
    post :create, :deal => deal.attributes.except('id', 'deleted_at', 'created_at', 'updated_at')
    response.should render_template(:new)
  end

  it "create action should redirect when model is valid" do
    deal = FactoryGirl.build(:deal)
    Deal.any_instance.stubs(:valid?).returns(true)
    post :create, :deal => deal.attributes.except('id', 'deleted_at', 'created_at', 'updated_at')
    response.should redirect_to(admin_generic_deal_url(assigns[:deal]))
  end

  it "edit action should render edit template" do
    deal = create(:deal)
    get :edit, :id => deal.id
    response.should render_template(:edit)
  end

  it "update action should render edit template when model is invalid" do
    deal = create(:deal)
    Deal.any_instance.stubs(:valid?).returns(false)
    put :update, :id => deal.id, :deal => deal.attributes.except('id', 'deleted_at', 'created_at', 'updated_at')
    response.should render_template(:edit)
  end

  it "update action should redirect when model is valid" do
    deal = create(:deal)
    Deal.any_instance.stubs(:valid?).returns(true)
    put :update, :id => deal.id, :deal => deal.attributes.except('id', 'deleted_at', 'created_at', 'updated_at')
    response.should redirect_to(admin_generic_deal_url(assigns[:deal]))
  end

  it "destroy action should destroy model and redirect to index action" do
    deal = create(:deal)
    delete :destroy, :id => deal.id
    response.should redirect_to(admin_generic_deals_url)
    Deal.find(deal.id).deleted_at.should_not be_nil
  end
end


text:
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.

using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Web.Mvc.Async;
using System.Web.Mvc.Properties;
using System.Web.Routing;

namespace System.Web.Mvc.Routing
{
    /// <remarks>
    /// Corresponds to the Web API implementation of attribute routing in
    /// System.Web.Http.Routing.AttributeRoutingMapper.
    /// </remarks>
    internal static class AttributeRoutingMapper
    {
        /// <summary>
        /// Maps the attribute-defined routes for the application.
        /// </summary>
        /// <param name="routes">The route collection.</param>
        /// <param name="constraintResolver">
        /// The <see cref="IInlineConstraintResolver"/> to use for resolving inline constraints in route templates.
        /// </param>
        public static void MapAttributeRoutes(RouteCollection routes, IInlineConstraintResolver constraintResolver)
        {
            if (routes == null)
            {
                throw new ArgumentNullException("routes");
            }

            if (constraintResolver == null)
            {
                throw new ArgumentNullException("constraintResolver");
            }

            MapAttributeRoutes(routes, constraintResolver, new DefaultDirectRouteProvider());
        }

        /// <summary>
        /// Maps the attribute-defined routes for the application.
        /// </summary>
        /// <param name="routes">The route collection.</param>
        /// <param name="constraintResolver">
        /// The <see cref="IInlineConstraintResolver"/> to use for resolving inline constraints in route templates.
        /// </param>
        /// <param name="directRouteProvider">
        /// The <see cref="IDirectRouteProvider"/> to use for mapping routes from controller types.
        /// </param>
        public static void MapAttributeRoutes(
            RouteCollection routes,
            IInlineConstraintResolver constraintResolver,
            IDirectRouteProvider directRouteProvider)
        {
            if (routes == null)
            {
                throw new ArgumentNullException("routes");
            }

            if (constraintResolver == null)
            {
                throw new ArgumentNullException("constraintResolver");
            }

            if (directRouteProvider == null)
            {
                throw new ArgumentNullException("directRouteProvider");
            }

            DefaultControllerFactory typesLocator =
                DependencyResolver.Current.GetService<IControllerFactory>() as DefaultControllerFactory
                ?? ControllerBuilder.Current.GetControllerFactory() as DefaultControllerFactory
                ?? new DefaultControllerFactory();

            IReadOnlyList<Type> controllerTypes = typesLocator.GetControllerTypes();

            MapAttributeRoutes(routes, controllerTypes, constraintResolver, directRouteProvider);
        }

        /// <summary>
        /// Maps the attribute-defined routes for the application.
        /// </summary>
        /// <param name="routes">The route collection.</param>
        /// <param name="controllerTypes">The controller types to scan.</param>
        public static void MapAttributeRoutes(RouteCollection routes, IEnumerable<Type> controllerTypes)
        {
            MapAttributeRoutes(routes, controllerTypes, new DefaultInlineConstraintResolver());
        }

        /// <summary>
        /// Maps the attribute-defined routes for the application.
        /// </summary>
        /// <param name="routes">The route collection.</param>
        /// <param name="controllerTypes">The controller types to scan.</param>
        /// <param name="constraintResolver">
        /// The <see cref="IInlineConstraintResolver"/> to use for resolving inline constraints in route templates.
        /// </param>
        public static void MapAttributeRoutes(RouteCollection routes, IEnumerable<Type> controllerTypes,
            IInlineConstraintResolver constraintResolver)
        {
            MapAttributeRoutes(routes, controllerTypes, constraintResolver, new DefaultDirectRouteProvider());
        }

        /// <summary>
        /// Maps the attribute-defined routes for the application.
        /// </summary>
        /// <param name="routes">The route collection.</param>
        /// <param name="controllerTypes">The controller types to scan.</param>
        /// <param name="constraintResolver">
        /// The <see cref="IInlineConstraintResolver"/> to use for resolving inline constraints in route templates.
        /// </param>
        /// <param name="directRouteProvider">
        /// The <see cref="IDirectRouteProvider"/> to use for mapping routes from controller types.
        /// </param>
        public static void MapAttributeRoutes(RouteCollection routes, IEnumerable<Type> controllerTypes,
            IInlineConstraintResolver constraintResolver, IDirectRouteProvider directRouteProvider)
        {
            if (routes == null)
            {
                throw new ArgumentNullException("routes");
            }

            if (controllerTypes == null)
            {
                throw new ArgumentNullException("controllerTypes");
            }

            if (constraintResolver == null)
            {
                throw new ArgumentNullException("constraintResolver");
            }

            if (directRouteProvider == null)
            {
                throw new ArgumentNullException("directRouteProvider");
            }

            SubRouteCollection subRoutes = new SubRouteCollection();
            AddRouteEntries(subRoutes, controllerTypes, constraintResolver, directRouteProvider);
            IReadOnlyCollection<RouteEntry> entries = subRoutes.Entries;

            if (entries.Count > 0)
            {
                RouteCollectionRoute aggregrateRoute = new RouteCollectionRoute(subRoutes);
                routes.Add(aggregrateRoute);

                // This sort is here to enforce a static ordering for link generation using these routes.
                // We don't apply dynamic criteria like ActionSelectors on link generation, but we can use the static
                // ones.
                //
                // Routes to actions are placed first because they are considered more specific. A route to an action
                // will only match for link generation if the action name was supplied, so this is essential for
                // correctness. Without this a controller-level route could be 'greedy' and generate a link when
                // the action-level route was intended.
                RouteEntry[] sorted = entries
                    .OrderBy(r => r.Route.GetOrder())
                    .ThenBy(r => r.Route.GetTargetIsAction() ? 0 : 1)
                    .ThenBy(r => r.Route.GetPrecedence())
                    .ToArray();

                AddGenerationHooksForSubRoutes(routes, sorted);
            }
        }

        // just for testing
        internal static IReadOnlyCollection<RouteEntry> GetAttributeRoutes(Type controllerType)
        {
            SubRouteCollection collector = new SubRouteCollection();
            AddRouteEntries(
                collector,
                new Type[] { controllerType },
                new DefaultInlineConstraintResolver(),
                new DefaultDirectRouteProvider());

            return collector.Entries;
        }

        // Add generation hooks for the Attribute-routing subroutes.
        // This lets us generate urls for routes supplied by attr-based routing.
        private static void AddGenerationHooksForSubRoutes(RouteCollection routeTable, IList<RouteEntry> entries)
        {
            Contract.Assert(entries != null);

            foreach (RouteEntry entry in entries)
            {
                Contract.Assert(entry != null);
                Route route = entry.Route;
                Contract.Assert(route != null);
                RouteBase linkGenerationRoute = new LinkGenerationRoute(route);
                string name = entry.Name;

                if (name == null)
                {
                    routeTable.Add(linkGenerationRoute);
                }
                else
                {
                    routeTable.Add(name, linkGenerationRoute);
                }
            }
        }

        internal static void AddRouteEntries(SubRouteCollection collector, IEnumerable<Type> controllerTypes,
            IInlineConstraintResolver constraintResolver, IDirectRouteProvider directRouteProvider)
        {
            IEnumerable<ReflectedAsyncControllerDescriptor> controllers = GetControllerDescriptors(controllerTypes);

            foreach (ReflectedAsyncControllerDescriptor controller in controllers)
            {
                List<ActionDescriptor> actions = GetActionDescriptors(controller);

                IReadOnlyCollection<RouteEntry> entries = directRouteProvider.GetDirectRoutes(controller, actions, constraintResolver);
                if (entries == null)
                {
                    throw Error.InvalidOperation(
                        MvcResources.TypeMethodMustNotReturnNull,
                        typeof(IDirectRouteProvider).Name,
                        "GetDirectRoutes");
                }

                foreach (RouteEntry entry in entries)
                {
                    if (entry == null)
                    {
                        throw Error.InvalidOperation(
                            MvcResources.TypeMethodMustNotReturnNull,
                            typeof(IDirectRouteProvider).Name,
                            "GetDirectRoutes");
                    }

                    DirectRouteBuilder.ValidateRouteEntry(entry);

                    // This marks the action/controller as unreachable via traditional routing.
                    if (entry.Route.GetTargetIsAction())
                    {
                        var actionDescriptors = entry.Route.GetTargetActionDescriptors();
                        Contract.Assert(actionDescriptors != null && actionDescriptors.Any());

                        foreach (var actionDescriptor in actionDescriptors.OfType<IMethodInfoActionDescriptor>())
                        {
                            var methodInfo = actionDescriptor.MethodInfo;
                            if (methodInfo != null)
                            {
                                controller.Selector.StandardRouteMethods.Remove(methodInfo);
                            }
                        }
                    }
                    else
                    {
                        // This is a controller-level route - no actions in this controller are reachable via
                        // traditional routes.
                        controller.Selector.StandardRouteMethods.Clear();
                    }
                }

                collector.AddRange(entries);
            }
        }

        private static IEnumerable<ReflectedAsyncControllerDescriptor> GetControllerDescriptors(IEnumerable<Type> controllerTypes)
        {
            Contract.Assert(controllerTypes != null);

            Func<Type, ControllerDescriptor> descriptorFactory = ReflectedAsyncControllerDescriptor.DefaultDescriptorFactory;
            ControllerDescriptorCache descriptorsCache = new AsyncControllerActionInvoker().DescriptorCache;

            return
                controllerTypes
                .Select(type => descriptorsCache.GetDescriptor(type, descriptorFactory, type))
                .Cast<ReflectedAsyncControllerDescriptor>();
        }

        private static List<ActionDescriptor> GetActionDescriptors(ReflectedAsyncControllerDescriptor controller)
        {
            Contract.Assert(controller != null);

            AsyncActionMethodSelector actionSelector = controller.Selector;

            var actions = new List<ActionDescriptor>();
            foreach (MethodInfo method in actionSelector.ActionMethods)
            {
                string actionName = actionSelector.GetActionName(method);
                ActionDescriptorCreator creator = actionSelector.GetActionDescriptorDelegate(method);
                Debug.Assert(creator != null);

                ActionDescriptor action = creator(actionName, controller);
                actions.Add(action);
            }

            return actions;
        }
    }
}


text:
<?php
namespace Concrete\Controller\Dialog\File\Bulk;

use Concrete\Controller\Backend\UserInterface as BackendInterfaceController;
use Concrete\Core\Http\ResponseAssetGroup;
use Concrete\Core\File\EditResponse as FileEditResponse;
use FileAttributeKey;
use Permissions;
use Loader;
use File;

class Properties extends BackendInterfaceController
{
    protected $viewPath = '/dialogs/file/bulk/properties';
    protected $controllerActionPath = '/ccm/system/dialogs/file/bulk/properties';
    protected $files;
    protected $canEdit = false;

    protected function canAccess()
    {
        return $this->canEdit;
    }

    protected function setFiles($files)
    {
        $this->files = $files;
    }

    public function on_start()
    {
        parent::on_start();
        if (!isset($this->files)) {
            $this->files = array();
        }

        if (is_array($_REQUEST['fID'])) {
            foreach ($_REQUEST['fID'] as $fID) {
                $f = File::getByID($fID);
                if (is_object($f) && !$f->isError()) {
                    $this->files[] = $f;
                }
            }
        }

        if (count($this->files) > 0) {
            $this->canEdit = true;
            foreach ($this->files as $f) {
                $fp = new Permissions($f);
                if (!$fp->canEditFileProperties()) {
                    $this->canEdit = false;
                }
            }
        } else {
            $this->canEdit = false;
        }
    }

    public function view()
    {
        $r = ResponseAssetGroup::get();
        $r->requireAsset('core/app/editable-fields');
        $form = Loader::helper('form');
        $attribs = FileAttributeKey::getList();
        $this->set('files', $this->files);
        $this->set('attributes', $attribs);
    }

    public function updateAttribute()
    {
        $fr = new FileEditResponse();
        $ak = FileAttributeKey::get($_REQUEST['name']);
        if ($this->validateAction()) {
            if ($this->canEdit) {
                foreach ($this->files as $f) {
                    $fv = $f->getVersionToModify();
                    $controller = $ak->getController();
                    $value = $controller->createAttributeValueFromRequest();
                    $fv->setAttribute($ak, $value);
                    $f->reindex();
                }

                $fr->setFiles($this->files);
                $val = $f->getAttributeValueObject($ak);
                $fr->setAdditionalDataAttribute('value',  $val->getValue('displaySanitized', 'display'));
                $fr->setMessage(t('Files updated successfully.'));
            }
        }
        $fr->outputJSON();
    }

    public function clearAttribute()
    {
        $fr = new FileEditResponse();
        $ak = FileAttributeKey::get($_REQUEST['akID']);
        if ($this->validateAction()) {
            if ($this->canEdit) {
                foreach ($this->files as $f) {
                    $fv = $f->getVersionToModify();
                    $fv->clearAttribute($ak);
                    $f->reindex();
                }
                $fr->setFiles($this->files);
                $fr->setAdditionalDataAttribute('value',  false);
                $fr->setMessage(t('Attributes cleared successfully.'));
            }
        }
        $fr->outputJSON();
    }
}


text:
package pitchfork

import (
	"bufio"
	"encoding/json"
	"errors"
	"net"
	"os"
	"strings"
)

type PfConfig struct {
	Conf_root       string       ``                  /* From command line option or default setting */
	File_roots      []string     `json:"file_roots"` /* Where we look for files */
	Var_root        string       `json:"var_root"`   /* Where variable files are stored */
	Tmp_roots       []string     `json:"tmp_roots"`  /* Templates */
	LogFile         string       `json:"logfile"`    /* Where to write our log file (with logrotate support) */
	Token_prv       interface{}  ``
	Token_pub       interface{}  ``
	UserAgent       string       `json:"useragent"`
	CSS             []string     `json:"css"`
	Javascript      []string     `json:"javascript"`
	CSP             string       `json:"csp"`
	XFF             []string     `json:"xff_trusted_cidr"`
	XFFc            []*net.IPNet ``
	Db_host         string       `json:"db_host"`
	Db_port         string       `json:"db_port"`
	Db_name         string       `json:"db_name"`
	Db_user         string       `json:"db_user"`
	Db_pass         string       `json:"db_pass"`
	Db_ssl_mode     string       `json:"db_ssl_mode"`
	Db_admin_db     string       `json:"db_admin_db"`
	Db_admin_user   string       `json:"db_admin_user"`
	Db_admin_pass   string       `json:"db_admin_pass"`
	Nodename        string       `json:"nodename"`
	Http_host       string       `json:"http_host"`
	Http_port       string       `json:"http_port"`
	JWT_prv         string       `json:"jwt_key_prv"`
	JWT_pub         string       `json:"jwt_key_pub"`
	Application     interface{}  `json:"application"`
	Username_regexp string       `json:"username_regexp"`
	UserHomeLinks   bool         `json:"user_home_links"`
	SMTP_host       string       `json:"smtp_host"`
	SMTP_port       string       `json:"smtp_port"`
	SMTP_SSL        string       `json:"smtp_ssl"`
	Msg_mon_from    string       `json:"msg_monitor_from"`
	Msg_mon_to      string       `json:"msg_monitor_to"`
	TimeFormat      string       `json:"timeformat"`
	DateFormat      string       `json:"dateformat"`
	PW_WeakDicts    []string     `json:"pw_weakdicts"`
	CFG_UserMinLen  string       `json:"username_min_length"`
	CFG_UserExample string       `json:"username_example"`
	TransDefault    string       `json:"translation_default"`
	TransLanguages  []string     `json:"translation_languages"`
}

/* SMTP_SSL = ignore | require */

var Config PfConfig

func (cfg *PfConfig) GetAppConfig(varname string) (out string) {
	out = ""

	a, ok := cfg.Application.(map[string]interface{})
	if !ok {
		Errf("No string application configuration variable '%s' found", varname)
		return
	}

	out, ok = a[varname].(string)
	if !ok {
		Errf("Application configuration variable '%s' is not a string", varname)
		return
	}

	return
}

func (cfg *PfConfig) GetAppConfigBool(varname string) (out bool) {
	out = false

	a, ok := cfg.Application.(map[string]interface{})
	if !ok {
		Errf("No boolean application configuration variable '%s' found", varname)
		return
	}

	out, ok = a[varname].(bool)
	if !ok {
		Errf("Application configuration variable '%s' is not a bool", varname)
		return
	}

	return
}

func (cfg *PfConfig) Load(toolname string, confroot string) (err error) {
	wd, err := os.Getwd()
	if err != nil {
		Errf("Could not determine working directory: %s", err.Error())
		return
	}
	Dbgf("Running from: %s", wd)

	if confroot == "" {
		confroot = "/etc/" + toolname + "/"
	}

	/* Defaults */
	Config.Conf_root = confroot
	Config.UserHomeLinks = true

	/* Open the configuration file */
	fn := Config.Conf_root + toolname + ".conf"

	file, err := os.Open(fn)
	if err != nil {
		err = errors.New("Failed to open configuration file " + fn + ": " + err.Error())
		return
	}
	defer file.Close()

	txt := ""

	scanner := bufio.NewScanner(file)
	for scanner.Scan() {
		s := strings.TrimSpace(scanner.Text())
		if len(s) == 0 || s[0] != '#' {
			txt += s
		}
	}

	err = scanner.Err()
	if err != nil {
		err = errors.New("Configuration file " + fn + " read error: " + err.Error())
		return
	}

	err = json.Unmarshal([]byte(txt), &cfg)
	if err != nil {
		err = errors.New("Configuration file " + fn + " JSON error: " + err.Error())
		return
	}

	/* When not specified use the system configured name */
	if Config.Nodename == "" {
		Config.Nodename, err = os.Hostname()
		if err != nil {
			return
		}
	}

	/*
	 * Default to IPv4 loopback only
	 * As we live behind nginx most of the time
	 * This option is thus mostly for testing purposes
	 * or if a front-end loadbalancer is listening on
	 * another host. Adjust XFF settings too then.
	 */
	if Config.Http_host == "" {
		Config.Http_host = "127.0.0.1"
	}

	if Config.Http_port == "" {
		Config.Http_port = "8333"
	}

	/* Default User Agent */
	if Config.UserAgent == "" {
		Config.UserAgent = "Trident/Pitchfork (https://trident.li)"
	}

	if Config.Var_root == "" {
		err = errors.New("Missing var_root, please define in " + fn)
		return
	}

	if len(Config.File_roots) == 0 {
		err = errors.New("Missing file_roots, require at least one file root")
		return
	}

	if Config.Db_name == "" {
		Config.Db_name = toolname
	}

	if Config.Db_user == "" {
		Config.Db_user = toolname
	}

	if Config.JWT_prv == "" {
		Config.JWT_prv = "jwt.prv"
	}

	if Config.JWT_pub == "" {
		Config.JWT_pub = "jwt.pub"
	}

	if len(Config.CSS) == 0 {
		Config.CSS = []string{"style", "form"}
	}

	if Config.CSP == "" {
		Config.CSP = "default-src 'self'; img-src 'self' data:"
	}

	if Config.Username_regexp == "" {
		Config.Username_regexp = "^[a-z][a-z0-9]*$"
	}

	if Config.SMTP_host == "" || Config.SMTP_port == "" || Config.SMTP_SSL == "" {
		err = errors.New("Please configure the SMTP parameters (smtp_host, smtp_port, smtp_ssl)")
		return
	}

	if Config.SMTP_SSL != "require" && Config.SMTP_SSL != "ignore" {
		err = errors.New("Configuration variable 'smtp_ssl' is not set to 'require' or 'ignore' but '" + Config.SMTP_SSL + "'")
		return
	}

	if Config.TimeFormat == "" {
		Config.TimeFormat = "2006-01-02 15:04"
	}

	if Config.DateFormat == "" {
		Config.DateFormat = "2006-01-02"
	}

	/* Check that the configuration is sane */
	for _, x := range Config.XFF {
		var xc *net.IPNet

		_, xc, err = net.ParseCIDR(x)
		if err != nil {
			err = errors.New("Trusted XFF IP " + x + " is invalid: " + err.Error())
			return
		}

		/* Add it to the pre-parsed list */
		Config.XFFc = append(Config.XFFc, xc)
	}

	err = cfg.Token_LoadPrv()
	if err != nil {
		return
	}

	err = cfg.Token_LoadPub()
	if err != nil {
		return
	}

	return
}