text:
using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static int visitedSum = 0;
    static int maxRow;
    static int maxCol;
    static int maxDep;
    static int Max;
    static int secondBestMax;

    static bool isInside(int[, ,] cuboid, int startRow, int startCol, int startDep)
    {
        if (startRow < 0 || startRow >= cuboid.GetLength(0)) return false;
        if (startCol < 0 || startCol >= cuboid.GetLength(1)) return false;
        if (startDep < 0 || startDep >= cuboid.GetLength(2)) return false;
        return true;
    }

    static void GetMaxValue(int[, ,] cuboid, int startRow, int startCol, int startDep)
    {
        int curRow = startRow + 1;
        int curCol = startCol;
        int curDep = startDep;

        for (; isInside(cuboid, curRow, curCol, curDep); curRow++)
        {
            if (cuboid[curRow, curCol, curDep] > Max)
            {
                secondBestMax = Max;
                maxCol = curCol;
                maxRow = curRow;
                maxDep = curDep;
                Max = cuboid[curRow, curCol, curDep];
            }
            else if(cuboid[curRow, curCol, curDep] == Max)
            {
                secondBestMax = cuboid[curRow, curCol, curDep];
            }
        }
        curRow = startRow - 1;
        curCol = startCol;
        curDep = startDep;
        for (; isInside(cuboid, curRow, curCol, curDep); curRow--)
        {
            if (cuboid[curRow, curCol, curDep] > Max)
            {
                secondBestMax = Max;
                maxCol = curCol;
                maxRow = curRow;
                maxDep = curDep;
                Max = cuboid[curRow, curCol, curDep];
            }
            else if (cuboid[curRow, curCol, curDep] == Max)
            {
                secondBestMax = cuboid[curRow, curCol, curDep];
            }
        }
        curRow = startRow;
        curCol = startCol + 1;
        curDep = startDep;
        for (; isInside(cuboid, curRow, curCol, curDep); curCol++)
        {
            if (cuboid[curRow, curCol, curDep] > Max)
            {
                secondBestMax = Max;
                maxCol = curCol;
                maxRow = curRow;
                maxDep = curDep;
                Max = cuboid[curRow, curCol, curDep];
            }
            else if (cuboid[curRow, curCol, curDep] == Max)
            {
                secondBestMax = cuboid[curRow, curCol, curDep];
            }
        }
        curRow = startRow;
        curCol = startCol - 1;
        curDep = startDep;
        for (; isInside(cuboid, curRow, curCol, curDep); curCol--)
        {
            if (cuboid[curRow, curCol, curDep] > Max)
            {
                secondBestMax = Max;
                maxCol = curCol;
                maxRow = curRow;
                maxDep = curDep;
                Max = cuboid[curRow, curCol, curDep];
            }
            else if (cuboid[curRow, curCol, curDep] == Max)
            {
                secondBestMax = cuboid[curRow, curCol, curDep];
            }
        }
        curRow = startRow;
        curCol = startCol;
        curDep = startDep + 1;
        for (; isInside(cuboid, curRow, curCol, curDep); curDep++)
        {
            if (cuboid[curRow, curCol, curDep] > Max)
            {
                secondBestMax = Max;
                maxCol = curCol;
                maxRow = curRow;
                maxDep = curDep;
                Max = cuboid[curRow, curCol, curDep];
            }
            else if (cuboid[curRow, curCol, curDep] == Max)
            {
                secondBestMax = cuboid[curRow, curCol, curDep];
            }
        }
        curRow = startRow;
        curCol = startCol;
        curDep = startDep - 1;
        for (; isInside(cuboid, curRow, curCol, curDep); curDep--)
        {
            if (cuboid[curRow, curCol, curDep] > Max)
            {
                secondBestMax = Max;
                maxCol = curCol;
                maxRow = curRow;
                maxDep = curDep;
                Max = cuboid[curRow, curCol, curDep];
            }
            else if (cuboid[curRow, curCol, curDep] == Max)
            {
                secondBestMax = cuboid[curRow, curCol, curDep];
            }
        }
    }

    static void Main()
    {
        string input = Console.ReadLine();
        string[] splittedInput = input.Split(' ');
        int w = int.Parse(splittedInput[0]);
        int h = int.Parse(splittedInput[1]);
        int d = int.Parse(splittedInput[2]);
        int[, ,] cuboid = new int[h, w, d];
        bool[, ,] isVisited = new bool[h, w, d];
        for (int r = 0; r < h; r++)
        {
            input = Console.ReadLine();
            splittedInput = input.Split('|');
            for (int l = 0; l < d; l++)
            {
                string[] doubleSplitted = splittedInput[l].Trim().Split(' ');
                for (int c = 0; c < w; c++)
                {
                    cuboid[r, c, l] = int.Parse(doubleSplitted[c]);
                }
            }
        }
        CubeMaxWalk(cuboid, isVisited, h / 2, w / 2, d / 2);
    }

    static void CubeMaxWalk(int[, ,] cuboid, bool[, ,] isVisited, int startRow, int startCol, int startDep)
    {
        isVisited[startRow, startCol, startDep] = true;
        visitedSum += cuboid[startRow, startCol, startDep];
        GetMaxValue(cuboid, startRow, startCol, startDep);
        if (secondBestMax == Max || isVisited[maxRow, maxCol, maxDep])
        {
            Console.WriteLine(visitedSum);
            Environment.Exit(0);
        }
        Max = secondBestMax = int.MinValue;
        CubeMaxWalk(cuboid, isVisited, maxRow, maxCol, maxDep);
    }
}


text:
"use strict";

/* jshint maxlen: false */
const apirequest_1 = require("../../lib/apirequest");
/**
 * Google Compute Engine Instance Group Manager API
 *
 * [Deprecated. Please use Instance Group Manager in Compute API] Provides groups of homogenous Compute Engine instances.
 *
 * @example
 * const google = require('googleapis');
 * const replicapool = google.replicapool('v1beta2');
 *
 * @namespace replicapool
 * @type {Function}
 * @version v1beta2
 * @variation v1beta2
 * @param {object=} options Options for Replicapool
 */
function Replicapool(options) {
    const self = this;
    self._options = options || {};
    self.instanceGroupManagers = {
        /**
         * replicapool.instanceGroupManagers.abandonInstances
         *
         * @desc Removes the specified instances from the managed instance group, and from any target pools of which they were members, without deleting the instances.
         *
         * @alias replicapool.instanceGroupManagers.abandonInstances
         * @memberOf! replicapool(v1beta2)
         *
         * @param {object} params Parameters for request
         * @param {string} params.instanceGroupManager The name of the instance group manager.
         * @param {string} params.project The Google Developers Console project name.
         * @param {string} params.zone The name of the zone in which the instance group manager resides.
         * @param {replicapool(v1beta2).InstanceGroupManagersAbandonInstancesRequest} params.resource Request body data
         * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
         * @param {callback} callback The callback that handles the response.
         * @return {object} Request object
         */
        abandonInstances: function (params, options, callback) {
            if (typeof options === 'function') {
                callback = options;
                options = {};
            }
            options || (options = {});
            const rootUrl = options.rootUrl || 'https://www.googleapis.com/';
            const parameters = {
                options: Object.assign({
                    url: (rootUrl + '/replicapool/v1beta2/projects/{project}/zones/{zone}/instanceGroupManagers/{instanceGroupManager}/abandonInstances').replace(/([^:]\/)\/+/g, '$1'),
                    method: 'POST'
                }, options),
                params: params,
                requiredParams: ['project', 'zone', 'instanceGroupManager'],
                pathParams: ['instanceGroupManager', 'project', 'zone'],
                context: self
            };
            return apirequest_1.default(parameters, callback);
        },
        /**
         * replicapool.instanceGroupManagers.delete
         *
         * @desc Deletes the instance group manager and all instances contained within. If you'd like to delete the manager without deleting the instances, you must first abandon the instances to remove them from the group.
         *
         * @alias replicapool.instanceGroupManagers.delete
         * @memberOf! replicapool(v1beta2)
         *
         * @param {object} params Parameters for request
         * @param {string} params.instanceGroupManager Name of the Instance Group Manager resource to delete.
         * @param {string} params.project The Google Developers Console project name.
         * @param {string} params.zone The name of the zone in which the instance group manager resides.
         * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
         * @param {callback} callback The callback that handles the response.
         * @return {object} Request object
         */
        delete: function (params, options, callback) {
            if (typeof options === 'function') {
                callback = options;
                options = {};
            }
            options || (options = {});
            const rootUrl = options.rootUrl || 'https://www.googleapis.com/';
            const parameters = {
                options: Object.assign({
                    url: (rootUrl + '/replicapool/v1beta2/projects/{project}/zones/{zone}/instanceGroupManagers/{instanceGroupManager}').replace(/([^:]\/)\/+/g, '$1'),
                    method: 'DELETE'
                }, options),
                params: params,
                requiredParams: ['project', 'zone', 'instanceGroupManager'],
                pathParams: ['instanceGroupManager', 'project', 'zone'],
                context: self
            };
            return apirequest_1.default(parameters, callback);
        },
        /**
         * replicapool.instanceGroupManagers.deleteInstances
         *
         * @desc Deletes the specified instances. The instances are deleted, then removed from the instance group and any target pools of which they were a member. The targetSize of the instance group manager is reduced by the number of instances deleted.
         *
         * @alias replicapool.instanceGroupManagers.deleteInstances
         * @memberOf! replicapool(v1beta2)
         *
         * @param {object} params Parameters for request
         * @param {string} params.instanceGroupManager The name of the instance group manager.
         * @param {string} params.project The Google Developers Console project name.
         * @param {string} params.zone The name of the zone in which the instance group manager resides.
         * @param {replicapool(v1beta2).InstanceGroupManagersDeleteInstancesRequest} params.resource Request body data
         * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
         * @param {callback} callback The callback that handles the response.
         * @return {object} Request object
         */
        deleteInstances: function (params, options, callback) {
            if (typeof options === 'function') {
                callback = options;
                options = {};
            }
            options || (options = {});
            const rootUrl = options.rootUrl || 'https://www.googleapis.com/';
            const parameters = {
                options: Object.assign({
                    url: (rootUrl + '/replicapool/v1beta2/projects/{project}/zones/{zone}/instanceGroupManagers/{instanceGroupManager}/deleteInstances').replace(/([^:]\/)\/+/g, '$1'),
                    method: 'POST'
                }, options),
                params: params,
                requiredParams: ['project', 'zone', 'instanceGroupManager'],
                pathParams: ['instanceGroupManager', 'project', 'zone'],
                context: self
            };
            return apirequest_1.default(parameters, callback);
        },
        /**
         * replicapool.instanceGroupManagers.get
         *
         * @desc Returns the specified Instance Group Manager resource.
         *
         * @alias replicapool.instanceGroupManagers.get
         * @memberOf! replicapool(v1beta2)
         *
         * @param {object} params Parameters for request
         * @param {string} params.instanceGroupManager Name of the instance resource to return.
         * @param {string} params.project The Google Developers Console project name.
         * @param {string} params.zone The name of the zone in which the instance group manager resides.
         * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
         * @param {callback} callback The callback that handles the response.
         * @return {object} Request object
         */
        get: function (params, options, callback) {
            if (typeof options === 'function') {
                callback = options;
                options = {};
            }
            options || (options = {});
            const rootUrl = options.rootUrl || 'https://www.googleapis.com/';
            const parameters = {
                options: Object.assign({
                    url: (rootUrl + '/replicapool/v1beta2/projects/{project}/zones/{zone}/instanceGroupManagers/{instanceGroupManager}').replace(/([^:]\/)\/+/g, '$1'),
                    method: 'GET'
                }, options),
                params: params,
                requiredParams: ['project', 'zone', 'instanceGroupManager'],
                pathParams: ['instanceGroupManager', 'project', 'zone'],
                context: self
            };
            return apirequest_1.default(parameters, callback);
        },
        /**
         * replicapool.instanceGroupManagers.insert
         *
         * @desc Creates an instance group manager, as well as the instance group and the specified number of instances.
         *
         * @alias replicapool.instanceGroupManagers.insert
         * @memberOf! replicapool(v1beta2)
         *
         * @param {object} params Parameters for request
         * @param {string} params.project The Google Developers Console project name.
         * @param {integer} params.size Number of instances that should exist.
         * @param {string} params.zone The name of the zone in which the instance group manager resides.
         * @param {replicapool(v1beta2).InstanceGroupManager} params.resource Request body data
         * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
         * @param {callback} callback The callback that handles the response.
         * @return {object} Request object
         */
        insert: function (params, options, callback) {
            if (typeof options === 'function') {
                callback = options;
                options = {};
            }
            options || (options = {});
            const rootUrl = options.rootUrl || 'https://www.googleapis.com/';
            const parameters = {
                options: Object.assign({
                    url: (rootUrl + '/replicapool/v1beta2/projects/{project}/zones/{zone}/instanceGroupManagers').replace(/([^:]\/)\/+/g, '$1'),
                    method: 'POST'
                }, options),
                params: params,
                requiredParams: ['project', 'zone', 'size'],
                pathParams: ['project', 'zone'],
                context: self
            };
            return apirequest_1.default(parameters, callback);
        },
        /**
         * replicapool.instanceGroupManagers.list
         *
         * @desc Retrieves the list of Instance Group Manager resources contained within the specified zone.
         *
         * @alias replicapool.instanceGroupManagers.list
         * @memberOf! replicapool(v1beta2)
         *
         * @param {object} params Parameters for request
         * @param {string=} params.filter Optional. Filter expression for filtering listed resources.
         * @param {integer=} params.maxResults Optional. Maximum count of results to be returned. Maximum value is 500 and default value is 500.
         * @param {string=} params.pageToken Optional. Tag returned by a previous list request truncated by maxResults. Used to continue a previous list request.
         * @param {string} params.project The Google Developers Console project name.
         * @param {string} params.zone The name of the zone in which the instance group manager resides.
         * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
         * @param {callback} callback The callback that handles the response.
         * @return {object} Request object
         */
        list: function (params, options, callback) {
            if (typeof options === 'function') {
                callback = options;
                options = {};
            }
            options || (options = {});
            const rootUrl = options.rootUrl || 'https://www.googleapis.com/';
            const parameters = {
                options: Object.assign({
                    url: (rootUrl + '/replicapool/v1beta2/projects/{project}/zones/{zone}/instanceGroupManagers').replace(/([^:]\/)\/+/g, '$1'),
                    method: 'GET'
                }, options),
                params: params,
                requiredParams: ['project', 'zone'],
                pathParams: ['project', 'zone'],
                context: self
            };
            return apirequest_1.default(parameters, callback);
        },
        /**
         * replicapool.instanceGroupManagers.recreateInstances
         *
         * @desc Recreates the specified instances. The instances are deleted, then recreated using the instance group manager's current instance template.
         *
         * @alias replicapool.instanceGroupManagers.recreateInstances
         * @memberOf! replicapool(v1beta2)
         *
         * @param {object} params Parameters for request
         * @param {string} params.instanceGroupManager The name of the instance group manager.
         * @param {string} params.project The Google Developers Console project name.
         * @param {string} params.zone The name of the zone in which the instance group manager resides.
         * @param {replicapool(v1beta2).InstanceGroupManagersRecreateInstancesRequest} params.resource Request body data
         * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
         * @param {callback} callback The callback that handles the response.
         * @return {object} Request object
         */
        recreateInstances: function (params, options, callback) {
            if (typeof options === 'function') {
                callback = options;
                options = {};
            }
            options || (options = {});
            const rootUrl = options.rootUrl || 'https://www.googleapis.com/';
            const parameters = {
                options: Object.assign({
                    url: (rootUrl + '/replicapool/v1beta2/projects/{project}/zones/{zone}/instanceGroupManagers/{instanceGroupManager}/recreateInstances').replace(/([^:]\/)\/+/g, '$1'),
                    method: 'POST'
                }, options),
                params: params,
                requiredParams: ['project', 'zone', 'instanceGroupManager'],
                pathParams: ['instanceGroupManager', 'project', 'zone'],
                context: self
            };
            return apirequest_1.default(parameters, callback);
        },
        /**
         * replicapool.instanceGroupManagers.resize
         *
         * @desc Resizes the managed instance group up or down. If resized up, new instances are created using the current instance template. If resized down, instances are removed in the order outlined in Resizing a managed instance group.
         *
         * @alias replicapool.instanceGroupManagers.resize
         * @memberOf! replicapool(v1beta2)
         *
         * @param {object} params Parameters for request
         * @param {string} params.instanceGroupManager The name of the instance group manager.
         * @param {string} params.project The Google Developers Console project name.
         * @param {integer} params.size Number of instances that should exist in this Instance Group Manager.
         * @param {string} params.zone The name of the zone in which the instance group manager resides.
         * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
         * @param {callback} callback The callback that handles the response.
         * @return {object} Request object
         */
        resize: function (params, options, callback) {
            if (typeof options === 'function') {
                callback = options;
                options = {};
            }
            options || (options = {});
            const rootUrl = options.rootUrl || 'https://www.googleapis.com/';
            const parameters = {
                options: Object.assign({
                    url: (rootUrl + '/replicapool/v1beta2/projects/{project}/zones/{zone}/instanceGroupManagers/{instanceGroupManager}/resize').replace(/([^:]\/)\/+/g, '$1'),
                    method: 'POST'
                }, options),
                params: params,
                requiredParams: ['project', 'zone', 'instanceGroupManager', 'size'],
                pathParams: ['instanceGroupManager', 'project', 'zone'],
                context: self
            };
            return apirequest_1.default(parameters, callback);
        },
        /**
         * replicapool.instanceGroupManagers.setInstanceTemplate
         *
         * @desc Sets the instance template to use when creating new instances in this group. Existing instances are not affected.
         *
         * @alias replicapool.instanceGroupManagers.setInstanceTemplate
         * @memberOf! replicapool(v1beta2)
         *
         * @param {object} params Parameters for request
         * @param {string} params.instanceGroupManager The name of the instance group manager.
         * @param {string} params.project The Google Developers Console project name.
         * @param {string} params.zone The name of the zone in which the instance group manager resides.
         * @param {replicapool(v1beta2).InstanceGroupManagersSetInstanceTemplateRequest} params.resource Request body data
         * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
         * @param {callback} callback The callback that handles the response.
         * @return {object} Request object
         */
        setInstanceTemplate: function (params, options, callback) {
            if (typeof options === 'function') {
                callback = options;
                options = {};
            }
            options || (options = {});
            const rootUrl = options.rootUrl || 'https://www.googleapis.com/';
            const parameters = {
                options: Object.assign({
                    url: (rootUrl + '/replicapool/v1beta2/projects/{project}/zones/{zone}/instanceGroupManagers/{instanceGroupManager}/setInstanceTemplate').replace(/([^:]\/)\/+/g, '$1'),
                    method: 'POST'
                }, options),
                params: params,
                requiredParams: ['project', 'zone', 'instanceGroupManager'],
                pathParams: ['instanceGroupManager', 'project', 'zone'],
                context: self
            };
            return apirequest_1.default(parameters, callback);
        },
        /**
         * replicapool.instanceGroupManagers.setTargetPools
         *
         * @desc Modifies the target pools to which all new instances in this group are assigned. Existing instances in the group are not affected.
         *
         * @alias replicapool.instanceGroupManagers.setTargetPools
         * @memberOf! replicapool(v1beta2)
         *
         * @param {object} params Parameters for request
         * @param {string} params.instanceGroupManager The name of the instance group manager.
         * @param {string} params.project The Google Developers Console project name.
         * @param {string} params.zone The name of the zone in which the instance group manager resides.
         * @param {replicapool(v1beta2).InstanceGroupManagersSetTargetPoolsRequest} params.resource Request body data
         * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
         * @param {callback} callback The callback that handles the response.
         * @return {object} Request object
         */
        setTargetPools: function (params, options, callback) {
            if (typeof options === 'function') {
                callback = options;
                options = {};
            }
            options || (options = {});
            const rootUrl = options.rootUrl || 'https://www.googleapis.com/';
            const parameters = {
                options: Object.assign({
                    url: (rootUrl + '/replicapool/v1beta2/projects/{project}/zones/{zone}/instanceGroupManagers/{instanceGroupManager}/setTargetPools').replace(/([^:]\/)\/+/g, '$1'),
                    method: 'POST'
                }, options),
                params: params,
                requiredParams: ['project', 'zone', 'instanceGroupManager'],
                pathParams: ['instanceGroupManager', 'project', 'zone'],
                context: self
            };
            return apirequest_1.default(parameters, callback);
        }
    };
    self.zoneOperations = {
        /**
         * replicapool.zoneOperations.get
         *
         * @desc Retrieves the specified zone-specific operation resource.
         *
         * @alias replicapool.zoneOperations.get
         * @memberOf! replicapool(v1beta2)
         *
         * @param {object} params Parameters for request
         * @param {string} params.operation Name of the operation resource to return.
         * @param {string} params.project Name of the project scoping this request.
         * @param {string} params.zone Name of the zone scoping this request.
         * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
         * @param {callback} callback The callback that handles the response.
         * @return {object} Request object
         */
        get: function (params, options, callback) {
            if (typeof options === 'function') {
                callback = options;
                options = {};
            }
            options || (options = {});
            const rootUrl = options.rootUrl || 'https://www.googleapis.com/';
            const parameters = {
                options: Object.assign({
                    url: (rootUrl + '/replicapool/v1beta2/projects/{project}/zones/{zone}/operations/{operation}').replace(/([^:]\/)\/+/g, '$1'),
                    method: 'GET'
                }, options),
                params: params,
                requiredParams: ['project', 'zone', 'operation'],
                pathParams: ['operation', 'project', 'zone'],
                context: self
            };
            return apirequest_1.default(parameters, callback);
        },
        /**
         * replicapool.zoneOperations.list
         *
         * @desc Retrieves the list of operation resources contained within the specified zone.
         *
         * @alias replicapool.zoneOperations.list
         * @memberOf! replicapool(v1beta2)
         *
         * @param {object} params Parameters for request
         * @param {string=} params.filter Optional. Filter expression for filtering listed resources.
         * @param {integer=} params.maxResults Optional. Maximum count of results to be returned. Maximum value is 500 and default value is 500.
         * @param {string=} params.pageToken Optional. Tag returned by a previous list request truncated by maxResults. Used to continue a previous list request.
         * @param {string} params.project Name of the project scoping this request.
         * @param {string} params.zone Name of the zone scoping this request.
         * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
         * @param {callback} callback The callback that handles the response.
         * @return {object} Request object
         */
        list: function (params, options, callback) {
            if (typeof options === 'function') {
                callback = options;
                options = {};
            }
            options || (options = {});
            const rootUrl = options.rootUrl || 'https://www.googleapis.com/';
            const parameters = {
                options: Object.assign({
                    url: (rootUrl + '/replicapool/v1beta2/projects/{project}/zones/{zone}/operations').replace(/([^:]\/)\/+/g, '$1'),
                    method: 'GET'
                }, options),
                params: params,
                requiredParams: ['project', 'zone'],
                pathParams: ['project', 'zone'],
                context: self
            };
            return apirequest_1.default(parameters, callback);
        }
    };
}
module.exports = Replicapool;
//# sourceMappingURL=v1beta2.js.map

redpajama_set_name: RedPajamaGithub


text:
{-# LANGUAGE OverloadedStrings #-}

module Area.Calculate
  ( markCalculateASD
  ) where

import TimeSeriesData
import Database.Persist.Postgresql
import qualified Database.Esqueleto as E
import Control.Monad.Reader
import Control.Monad.Logger
import Control.Concurrent
import Data.Maybe
import Data.ByteString.Char8 (ByteString)
import AppM
import Config
import Area.Types
import Time
import Area.Queries.IntervalsDuring

data CalcOpts = CalcOpts String Int UTCTime UTCTime

-- | Marking on just the target is sufficient,
--   this will get the entire tree (ancestors, self, and descendants)
markCalculateASD :: UTCTime -> UTCTime -> Key Area -> AppM ()
markCalculateASD start end aid = do
  qsemn    <- asks getQSemN
  counter  <- asks getCounter
  src      <- asks getSrcUrl
  port     <- asks getSrcPort
  connStr  <- asks getPoolConnStr
  maxQSemN <- asks getMaxQSemN
  let calcOpts = CalcOpts src port start end
  orderedTargetAreas <- getASD aid
  _ <- liftIO $ forkIO $ do
    waitQSemN qsemn maxQSemN
    modifyMVar_ counter (return . (+) 1)
    forM_ orderedTargetAreas $ \ area -> calculate calcOpts connStr area
    modifyMVar_ counter (return . (flip (-)) 1)
    signalQSemN qsemn maxQSemN
  return ()

-- | Gets ancestors, self, and descendants, in that order
getASD :: Key Area -> AppM [Entity Area]
getASD area = runDb $ rawSql
  "  with recursive t1 as (                                   \
  \    select (0) as level,* from area where id = ?           \
  \    union select level+1,area.* from area                  \
  \          inner join t1 on area.parent = t1.id),           \
  \  t2 as (                                                  \
  \    select (0) as level,* from area where id = ?           \
  \    union select level-1,area.* from area                  \
  \          inner join t2 on area.id = t2.parent)            \
  \  select * from t1 union select * from t2 order by level;  "
  [PersistInt64 $ fromSqlKey area, PersistInt64 $ fromSqlKey area]
  >>= return .
      map (\ (Single l, Single i, Single n, Single d, Single p, Single dc) ->
             let ll = l :: Int in Entity i (Area n d p dc))

calculate :: CalcOpts -> ByteString -> Entity Area -> IO ()
calculate calcOpts connStr (Entity aid area) = do
  -- Perform the (partial) calculation
  demand' <- runReaderT (calcInterval $ areaDemandCond area) calcOpts
  -- Get parent result, AND, then write to database
  let filterCounts n = map fst . filter ((== n) . snd)
  let CalcOpts _ _ start end = calcOpts
  runNoLoggingT $ withPostgresqlConn connStr $ lift . runReaderT (do
    demand <- case areaParent area of
      Nothing -> return demand'
      Just parent -> do
        parentDemand <- intervalsDuring start end parent
        return $ filterCounts 2 $ counts [parentDemand, demand']
    cleanRange start end aid
    writeIntervals start end aid demand
    )

calcInterval :: String -> ReaderT CalcOpts IO [TSInterval]
calcInterval condition = case parseExpression condition of
  Left  _          -> return []
  Right condition' -> do
    CalcOpts src port start end <- ask
    tsData <- lift $ getTSData src port (listTags condition') start end
    return (evaluate condition' tsData)

cleanRange :: UTCTime -> UTCTime -> Key Area -> SqlPersistT IO ()
cleanRange start end aid = do
  -- Between start and end
  deleteWhere [ AreaIntervalArea     ==. aid
              , AreaIntervalStart    >=. start
              , AreaIntervalEnd      <=. end ]
  -- Overlap start
  updateWhere [ AreaIntervalArea     ==. aid
              , AreaIntervalEnd      >.  start
              , AreaIntervalEnd      <=. end ]
              [ AreaIntervalEnd      =.  start ]
  -- Overlap end
  updateWhere [ AreaIntervalArea     ==. aid
              , AreaIntervalStart    >=. start
              , AreaIntervalStart    <.  end ]
              [ AreaIntervalStart    =.  end ]
  -- Overlap both start and end
  exceedRanges <- selectList [ AreaIntervalArea      ==. aid
                             , AreaIntervalStart    <.  start
                             , AreaIntervalEnd      >.  end ] []
  forM_ exceedRanges (\ (Entity kr r) -> do
    update kr [ AreaIntervalEnd =. start ]
    insert_ $
      AreaInterval (areaIntervalArea r) end (areaIntervalEnd r) )

writeIntervals :: UTCTime -> UTCTime -> Key Area -> [TSInterval]
               -> SqlPersistT IO ()
writeIntervals start end aid intervals =
  forM_ (fmap g intervals) f where
    g (s, e) = ( max (addUTCTime s refTime) start
               , min (addUTCTime e refTime) end   )
    insert_' s e = insert_ $ AreaInterval aid s e
    f (s, e)
      | s == start && e < end = do
        numAffected <- E.updateCount $ \ u -> do
          E.set u [ AreaIntervalEnd E.=. E.val e ]
          E.where_ (       (u E.^. AreaIntervalArea)     E.==. E.val aid
                     E.&&. (u E.^. AreaIntervalEnd)      E.==. E.val start )
        when (numAffected == 0) (insert_' s e)
      | e == end && s > start = do
        numAffected <- E.updateCount $ \ u -> do
          E.set u [ AreaIntervalStart E.=. E.val s ]
          E.where_ (       (u E.^. AreaIntervalArea)     E.==. E.val aid
                     E.&&. (u E.^. AreaIntervalStart)    E.==. E.val end )
        when (numAffected == 0) (insert_' s e)
      | s == start && e == end = do
          atEnd <- selectFirst [ AreaIntervalArea     ==. aid
                               , AreaIntervalStart    ==. end ] []
          let latestE = maybe e (areaIntervalEnd . entityVal) atEnd
          when (isJust atEnd) (delete $ entityKey $ fromJust atEnd)
          numAffected <- E.updateCount $ \ u -> do
            E.set u [ AreaIntervalEnd E.=. E.val latestE ]
            E.where_ (      (u E.^. AreaIntervalArea)     E.==. E.val aid
                      E.&&. (u E.^. AreaIntervalEnd)      E.==. E.val start)
          when (numAffected == 0) (insert_' s latestE)
      | otherwise = insert_' s e


text:
[#]: collector: (lujun9972)
[#]: translator: ( )
[#]: reviewer: ( )
[#]: publisher: ( )
[#]: url: ( )
[#]: subject: (How I prioritize tasks on my to-do list)
[#]: via: (https://opensource.com/article/21/1/prioritize-tasks)
[#]: author: (Kevin Sonney https://opensource.com/users/ksonney)

How I prioritize tasks on my to-do list
======
Use the Eisenhower Matrix to better organize and prioritize your to-do
lists.
![Team checklist and to dos][1]

In prior years, this annual series covered individual apps. This year, we are looking at all-in-one solutions in addition to strategies to help in 2021. Welcome to day 4 of 21 Days of Productivity in 2021. In this article, I'll examine a strategy for prioritizing tasks on a to-do list. To find the open source tool that suits your routine, check out [this list][2].

It is easy to add things to a task or to-do list. Almost too easy, really. And once on the list, the challenge becomes figuring out what to do first. Do we do the thing at the top of the list? Is the top of the list the most important thing? How do we figure out what the most important thing is?

![To-do list][3]

To-do. Today? Tomorrow? Who knows? (Kevin Sonney, [CC BY-SA 4.0][4])

[Much like email][5], we can prioritize tasks based on a couple of things, and this lets us figure out what needs to be done first and what can wait until later.

I use a method commonly known as the _Eisenhower Matrix_ since it was taken from a quote by US President Dwight D. Eisenhower. Draw a box split horizontally and vertically. Label the columns "Urgent" and "Not Urgent," and the rows "Important" and "Not Important."

![Eisenhower matrix][6]

An Eisenhower Matrix. (Kevin Sonney, [CC BY-SA 4.0][4])

You can typically put all of the things on a to-do list in one of the boxes. But how do we know what to put where? Urgency and importance are often subjective. So the first step is to decide what is important to you. My family (including my pets), my work, and my hobbies are all important. If something on my to-do list isn't related to those three things, I can immediately put it into the "Not Important" row.

Urgency is a little more cut and dry. Is it something that needs to be done today or tomorrow? Then it is probably "Urgent." Does it have a deadline that is approaching, but there are days/weeks/months until that time, or perhaps it doesn't have a deadline at all? Certainly "Not Urgent."

Now we can translate the boxes into priorities. "Urgent/Important" is the highest priority (i.e., Priority 1) and needs to be done first. "Not Urgent/Important" comes next (Priority 2), then "Urgent/Not Important" (Priority 3), and finally "Not Urgent/Not Important" (Priority 4 or no priority at all).

Notice that "Urgent/Not Important" is third, not second. This is because people spend a lot of time on things that are important because they are urgent, not because they are _actually_ important. When I look at these, I ask myself some questions. Are these tasks that need to be done by me specifically? Are these tasks I can ask other people to do? Are they important and urgent for someone else? Does that change their importance for me? Maybe they need to be re-classified, or perhaps they are things I can ask someone else to do and remove them from my list.

![After prioritizing][7]

After prioritizing. (Kevin Sonney, [CC BY-SA 4.0][4])

There is a single question to ask about the items in the "Not Urgent/Not Important" box, and that is "Do these need to even be on my list at all?" In all honesty, we often clog up our to-do lists with things that are not urgent or important, and we can remove them from our list altogether. I know it is hard to admit that "This is never going to get done," but after I accept that, it is a relief to take that item off my list and not worry about it anymore.

After all that, it is pretty easy to look at my list and say, "This is what I need to work on now," and get it done, which is what my to-do list is for: Providing guidance and focus to my day.

--------------------------------------------------------------------------------

via: https://opensource.com/article/21/1/prioritize-tasks

作者:[Kevin Sonney][a]
选题:[lujun9972][b]
译者:[译者ID](https://github.com/译者ID)
校对:[校对者ID](https://github.com/校对者ID)

本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出

[a]: https://opensource.com/users/ksonney
[b]: https://github.com/lujun9972
[1]: https://opensource.com/sites/default/files/styles/image-full-size/public/lead-images/todo_checklist_team_metrics_report.png?itok=oB5uQbzf (Team checklist and to dos)
[2]: https://opensource.com/article/20/5/alternatives-list
[3]: https://opensource.com/sites/default/files/pictures/to-do-list.png (To-do list)
[4]: https://creativecommons.org/licenses/by-sa/4.0/
[5]: https://opensource.com/article/21/1/email-rules
[6]: https://opensource.com/sites/default/files/pictures/eisenhower-matrix.png (Eisenhower matrix)
[7]: https://opensource.com/sites/default/files/pictures/after-prioritizing.png (After prioritizing)


text:
package cuchaz.enigma.analysis;

import java.util.List;

import javax.swing.tree.DefaultMutableTreeNode;

import com.google.common.collect.Lists;

import cuchaz.enigma.mapping.ClassEntry;
import cuchaz.enigma.mapping.MethodEntry;
import cuchaz.enigma.mapping.Translator;

public class ClassImplementationsTreeNode extends DefaultMutableTreeNode {

	private static final long serialVersionUID = 3112703459157851912L;

	private Translator m_deobfuscatingTranslator;
	private ClassEntry m_entry;

	public ClassImplementationsTreeNode(Translator deobfuscatingTranslator, ClassEntry entry) {
		m_deobfuscatingTranslator = deobfuscatingTranslator;
		m_entry = entry;
	}

	public ClassEntry getClassEntry() {
		return m_entry;
	}

	public String getDeobfClassName() {
		return m_deobfuscatingTranslator.translateClass(m_entry.getClassName());
	}

	@Override
	public String toString() {
		String className = getDeobfClassName();
		if (className == null) {
			className = m_entry.getClassName();
		}
		return className;
	}

	public void load(JarIndex index) {
		// get all method implementations
		List<ClassImplementationsTreeNode> nodes = Lists.newArrayList();
		for (String implementingClassName : index.getImplementingClasses(m_entry.getClassName())) {
			nodes.add(new ClassImplementationsTreeNode(m_deobfuscatingTranslator, new ClassEntry(implementingClassName)));
		}

		// add them to this node
		for (ClassImplementationsTreeNode node : nodes) {
			this.add(node);
		}
	}

	public static ClassImplementationsTreeNode findNode(ClassImplementationsTreeNode node, MethodEntry entry) {
		// is this the node?
		if (node.m_entry.equals(entry)) {
			return node;
		}

		// recurse
		for (int i = 0; i < node.getChildCount(); i++) {
			ClassImplementationsTreeNode foundNode = findNode((ClassImplementationsTreeNode)node.getChildAt(i), entry);
			if (foundNode != null) {
				return foundNode;
			}
		}
		return null;
	}
}


text:
require 'player'

class Human < Player
  def initialize game
    @game = game
  end

  def get_move position, moves
    game = @game.class.new
    game.reload_position moves
    print game.show_board
    move = gets.chop
  end
end


text:
<?php /* Smarty version 2.6.20, created on 2012-09-13 10:30:50
         compiled from aocEdit.html.tpl */ ?>
<meta charset="utf-8" />
<link href='css/style.css' rel='stylesheet' type="text/css" />
<link href='css/admin.css' rel='stylesheet' type="text/css" />

<form name="aoc" id="aoc" method="post" action="cambiosOc.php ">
	<input type="button" name="cancel" id="cancel" value="" class="boton-cancel-menu" onclick="mimensaje()" style='font-size: 13px;'/>
	<input type="submit" name="enviar" id="enviar" value="" class="boton-guardar-oc" style='font-size: 13px;' />

Datos Generales

OC_ID: <?php echo $this->_tpl_vars['id']; ?>

Descripción: <?php echo $this->_tpl_vars['desc']; ?>

    			<input type="hidden" name="ocid" id="ocid" value="<?php echo $this->_tpl_vars['id']; ?>
"/>
    			<input type="hidden" name="idp" id="idp" value="<?php echo $this->_tpl_vars['idp']; ?>
"/>

			Formato
			<select name="tf" id="tf">
    		<?php unset($this->_sections['catf']);
$this->_sections['catf']['name'] = 'catf';
$this->_sections['catf']['loop'] = is_array($_loop=$this->_tpl_vars['cf']) ? count($_loop) : max(0, (int)$_loop); unset($_loop);
$this->_sections['catf']['show'] = true;
$this->_sections['catf']['max'] = $this->_sections['catf']['loop'];
$this->_sections['catf']['step'] = 1;
$this->_sections['catf']['start'] = $this->_sections['catf']['step'] > 0 ? 0 : $this->_sections['catf']['loop']-1;
if ($this->_sections['catf']['show']) {
    $this->_sections['catf']['total'] = $this->_sections['catf']['loop'];
    if ($this->_sections['catf']['total'] == 0)
        $this->_sections['catf']['show'] = false;
} else
    $this->_sections['catf']['total'] = 0;
if ($this->_sections['catf']['show']):

            for ($this->_sections['catf']['index'] = $this->_sections['catf']['start'], $this->_sections['catf']['iteration'] = 1;
                 $this->_sections['catf']['iteration'] <= $this->_sections['catf']['total'];
                 $this->_sections['catf']['index'] += $this->_sections['catf']['step'], $this->_sections['catf']['iteration']++):
$this->_sections['catf']['rownum'] = $this->_sections['catf']['iteration'];
$this->_sections['catf']['index_prev'] = $this->_sections['catf']['index'] - $this->_sections['catf']['step'];
$this->_sections['catf']['index_next'] = $this->_sections['catf']['index'] + $this->_sections['catf']['step'];
$this->_sections['catf']['first']      = ($this->_sections['catf']['iteration'] == 1);
$this->_sections['catf']['last']       = ($this->_sections['catf']['iteration'] == $this->_sections['catf']['total']);
?>
    		<option
    		<?php unset($this->_sections['datos']);
$this->_sections['datos']['name'] = 'datos';
$this->_sections['datos']['show'] = true;
$this->_sections['datos']['loop'] = 1;
$this->_sections['datos']['max'] = $this->_sections['datos']['loop'];
$this->_sections['datos']['step'] = 1;
$this->_sections['datos']['start'] = $this->_sections['datos']['step'] > 0 ? 0 : $this->_sections['datos']['loop']-1;
if ($this->_sections['datos']['show']) {
    $this->_sections['datos']['total'] = $this->_sections['datos']['loop'];
    if ($this->_sections['datos']['total'] == 0)
        $this->_sections['datos']['show'] = false;
} else
    $this->_sections['datos']['total'] = 0;
if ($this->_sections['datos']['show']):

            for ($this->_sections['datos']['index'] = $this->_sections['datos']['start'], $this->_sections['datos']['iteration'] = 1;
                 $this->_sections['datos']['iteration'] <= $this->_sections['datos']['total'];
                 $this->_sections['datos']['index'] += $this->_sections['datos']['step'], $this->_sections['datos']['iteration']++):
$this->_sections['datos']['rownum'] = $this->_sections['datos']['iteration'];
$this->_sections['datos']['index_prev'] = $this->_sections['datos']['index'] - $this->_sections['datos']['step'];
$this->_sections['datos']['index_next'] = $this->_sections['datos']['index'] + $this->_sections['datos']['step'];
$this->_sections['datos']['first']      = ($this->_sections['datos']['iteration'] == 1);
$this->_sections['datos']['last']       = ($this->_sections['datos']['iteration'] == $this->_sections['datos']['total']);
?>
    		<?php if ($this->_tpl_vars['forma'][$this->_sections['datos']['index']]['id_formatoSi'] == $this->_tpl_vars['cf'][$this->_sections['catf']['index']]['id_formatoSi']): ?>
    		selected="selected"
    		<?php endif; ?>
    		<?php endfor; endif; ?>
    		value="<?php echo $this->_tpl_vars['cf'][$this->_sections['catf']['index']]['id_formatoSi']; ?>
"
    		><?php echo $this->_tpl_vars['cf'][$this->_sections['catf']['index']]['formatoVc']; ?>
</option>
    		<?php endfor; endif; ?>
    		</select>

    			<?php unset($this->_sections['pm']);
$this->_sections['pm']['name'] = 'pm';
$this->_sections['pm']['loop'] = is_array($_loop=$this->_tpl_vars['promo']) ? count($_loop) : max(0, (int)$_loop); unset($_loop);
$this->_sections['pm']['show'] = true;
$this->_sections['pm']['max'] = $this->_sections['pm']['loop'];
$this->_sections['pm']['step'] = 1;
$this->_sections['pm']['start'] = $this->_sections['pm']['step'] > 0 ? 0 : $this->_sections['pm']['loop']-1;
if ($this->_sections['pm']['show']) {
    $this->_sections['pm']['total'] = $this->_sections['pm']['loop'];
    if ($this->_sections['pm']['total'] == 0)
        $this->_sections['pm']['show'] = false;
} else
    $this->_sections['pm']['total'] = 0;
if ($this->_sections['pm']['show']):

            for ($this->_sections['pm']['index'] = $this->_sections['pm']['start'], $this->_sections['pm']['iteration'] = 1;
                 $this->_sections['pm']['iteration'] <= $this->_sections['pm']['total'];
                 $this->_sections['pm']['index'] += $this->_sections['pm']['step'], $this->_sections['pm']['iteration']++):
$this->_sections['pm']['rownum'] = $this->_sections['pm']['iteration'];
$this->_sections['pm']['index_prev'] = $this->_sections['pm']['index'] - $this->_sections['pm']['step'];
$this->_sections['pm']['index_next'] = $this->_sections['pm']['index'] + $this->_sections['pm']['step'];
$this->_sections['pm']['first']      = ($this->_sections['pm']['iteration'] == 1);
$this->_sections['pm']['last']       = ($this->_sections['pm']['iteration'] == $this->_sections['pm']['total']);
?>

    				<?php echo $this->_tpl_vars['promo'][$this->_sections['pm']['index']]['descripcionVc']; ?>

    			<input type="checkbox" name="c<?php echo $this->_tpl_vars['promo'][$this->_sections['pm']['index']]['id_promocionIn']; ?>
" id="c<?php echo $this->_tpl_vars['promo'][$this->_sections['pm']['index']]['id_promocionIn']; ?>
"
    			<?php if ($this->_tpl_vars['promo'][$this->_sections['pm']['index']]['publicadoBi'] == '1'): ?>
                 checked
                 <?php else: ?>
                 <?php endif; ?>
                 />
				<div id="d<?php echo $this->_tpl_vars['promo'][$this->_sections['pm']['index']]['id_promocionIn']; ?>
"
				<?php if ($this->_tpl_vars['promo'][$this->_sections['pm']['index']]['publicadoBi'] == '1'): ?>
								 class="checkbox_selected"
								 <?php else: ?>
								 class="checkbox_no_selected"
								 <?php endif; ?>
				>

				<input type="hidden" name="pe[]" id="pe[]" value="<?php echo $this->_tpl_vars['promo'][$this->_sections['pm']['index']]['id_promocionIn']; ?>
">

			<?php endfor; endif; ?>

Secciones descriptivas

				Titulo de sección
				Contenido

				<input type="text" name="ts[]" id="ts[]" value="<?php echo $this->_tpl_vars['aThink'][0]['tituloVc']; ?>
" />
				<textarea name="cont[]" id="cont[]"><?php echo $this->_tpl_vars['aThink'][0]['descripcionVc']; ?>
</textarea>

				<input type="text" name="ts[]" id="ts[]" value="<?php echo $this->_tpl_vars['aThink'][1]['tituloVc']; ?>
" />
				<textarea name="cont[]" id="cont[]"><?php echo $this->_tpl_vars['aThink'][1]['descripcionVc']; ?>
</textarea>

				<input type="text" name="ts[]" id="ts[]" value="<?php echo $this->_tpl_vars['aThink'][2]['tituloVc']; ?>
" />
				<textarea name="cont[]" id="cont[]"><?php echo $this->_tpl_vars['aThink'][2]['descripcionVc']; ?>
</textarea>

	<input type="button" name="cancel" id="cancel" value="" class="boton-cancel-menu" onclick="mimensaje()" style='font-size: 13px;' />
	<input type="submit" name="enviar" id="enviar" value="" class="boton-guardar-oc"  style='font-size: 13px;'/>
</form>


text:
	define([
		'underscore',
		'backbone'
	], function(_, Backbone){
		var projectModel = Backbone.Model.extend({
			defaults: {

			}
		});

		return projectModel;
	});


text:
#include <config.h>

#ident "$Id$"

#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "prototypes.h"
#include "defines.h"
/*
 * NEWENVP_STEP must be a power of two.  This is the number
 * of (char *) pointers to allocate at a time, to avoid using
 * realloc() too often.
 */
#define NEWENVP_STEP 16
size_t newenvc = 0;
/*@null@*/char **newenvp = NULL;
extern char **environ;

static const char *forbid[] = {
	"_RLD_=",
	"BASH_ENV=",		/* GNU creeping featurism strikes again... */
	"ENV=",
	"HOME=",
	"IFS=",
	"KRB_CONF=",
	"LD_",			/* anything with the LD_ prefix */
	"LIBPATH=",
	"MAIL=",
	"NLSPATH=",
	"PATH=",
	"SHELL=",
	"SHLIB_PATH=",
	(char *) 0
};

/* these are allowed, but with no slashes inside
   (to work around security problems in GNU gettext) */
static const char *noslash[] = {
	"LANG=",
	"LANGUAGE=",
	"LC_",			/* anything with the LC_ prefix */
	(char *) 0
};

/*
 * initenv() must be called once before using addenv().
 */
void initenv (void)
{
	newenvp = (char **) xmalloc (NEWENVP_STEP * sizeof (char *));
	*newenvp = NULL;
}

void addenv (const char *string, /*@null@*/const char *value)
{
	char *cp, *newstring;
	size_t i;
	size_t n;

	if (NULL != value) {
		size_t len = strlen (string) + strlen (value) + 2;
		int wlen;
		newstring = xmalloc (len);
		wlen = snprintf (newstring, len, "%s=%s", string, value);
		assert (wlen == (int) len -1);
	} else {
		newstring = xstrdup (string);
	}

	/*
	 * Search for a '=' character within the string and if none is found
	 * just ignore the whole string.
	 */

	cp = strchr (newstring, '=');
	if (NULL == cp) {
		free (newstring);
		return;
	}

	n = (size_t) (cp - newstring);

	/*
	 * If this environment variable is already set, change its value.
	 */
	for (i = 0; i < newenvc; i++) {
		if (   (strncmp (newstring, newenvp[i], n) == 0)
		    && (('=' == newenvp[i][n]) || ('\0' == newenvp[i][n]))) {
			break;
		}
	}

	if (i < newenvc) {
		free (newenvp[i]);
		newenvp[i] = newstring;
		return;
	}

	/*
	 * Otherwise, save the new environment variable
	 */
	newenvp[newenvc++] = newstring;

	/*
	 * And extend the environment if needed.
	 */

	/*
	 * Check whether newenvc is a multiple of NEWENVP_STEP.
	 * If so we have to resize the vector.
	 * the expression (newenvc & (NEWENVP_STEP - 1)) == 0
	 * is equal to    (newenvc %  NEWENVP_STEP) == 0
	 * as long as NEWENVP_STEP is a power of 2.
	 */

	if ((newenvc & (NEWENVP_STEP - 1)) == 0) {
		char **__newenvp;
		size_t newsize;

		/*
		 * If the resize operation succeeds we can
		 * happily go on, else print a message.
		 */

		newsize = (newenvc + NEWENVP_STEP) * sizeof (char *);
		__newenvp = (char **) realloc (newenvp, newsize);

		if (NULL != __newenvp) {
			/*
			 * If this is our current environment, update
			 * environ so that it doesn't point to some
			 * free memory area (realloc() could move it).
			 */
			if (environ == newenvp) {
				environ = __newenvp;
			}
			newenvp = __newenvp;
		} else {
			(void) fputs (_("Environment overflow\n"), stderr);
			newenvc--;
			free (newenvp[newenvc]);
		}
	}

	/*
	 * The last entry of newenvp must be NULL
	 */

	newenvp[newenvc] = NULL;
}

/*
 * set_env - copy command line arguments into the environment
 */
void set_env (int argc, char *const *argv)
{
	int noname = 1;
	char variable[1024];
	char *cp;

	for (; argc > 0; argc--, argv++) {
		if (strlen (*argv) >= sizeof variable) {
			continue;	/* ignore long entries */
		}

		cp = strchr (*argv, '=');
		if (NULL == cp) {
			int wlen;
			wlen = snprintf (variable, sizeof variable, "L%d", noname);
			assert (wlen < (int) sizeof(variable));
			noname++;
			addenv (variable, *argv);
		} else {
			const char **p;

			for (p = forbid; NULL != *p; p++) {
				if (strncmp (*argv, *p, strlen (*p)) == 0) {
					break;
				}
			}

			if (NULL != *p) {
				strncpy (variable, *argv, (size_t)(cp - *argv));
				variable[cp - *argv] = '\0';
				printf (_("You may not change $%s\n"),
					variable);
				continue;
			}

			addenv (*argv, NULL);
		}
	}
}

/*
 * sanitize_env - remove some nasty environment variables
 * If you fall into a total paranoia, you should call this
 * function for any root-setuid program or anything the user
 * might change the environment with. 99% useless as almost
 * all modern Unixes will handle setuid executables properly,
 * but... I feel better with that silly precaution. -j.
 */

void sanitize_env (void)
{
	char **envp = environ;
	const char **bad;
	char **cur;
	char **move;

	for (cur = envp; NULL != *cur; cur++) {
		for (bad = forbid; NULL != *bad; bad++) {
			if (strncmp (*cur, *bad, strlen (*bad)) == 0) {
				for (move = cur; NULL != *move; move++) {
					*move = *(move + 1);
				}
				cur--;
				break;
			}
		}
	}

	for (cur = envp; NULL != *cur; cur++) {
		for (bad = noslash; NULL != *bad; bad++) {
			if (strncmp (*cur, *bad, strlen (*bad)) != 0) {
				continue;
			}
			if (strchr (*cur, '/') == NULL) {
				continue;	/* OK */
			}
			for (move = cur; NULL != *move; move++) {
				*move = *(move + 1);
			}
			cur--;
			break;
		}
	}
}


text:
int linuxkit_aexec(
        char *program_name,
        char *args,
        char *stdin_path,
        char *stdout_path,
        char *stderr_path,
        char *pid_file_path,
        char *return_value_path,
        size_t program_name_len,
        size_t args_len,
        size_t stdin_len,
        size_t stdout_len,
        size_t stderr_len,
        size_t pid_file_len,
        size_t return_value_len
);

pid_t lock_pid(char * filename);

#endif //LINUXKIT_UTILS_LINUXKIT_H


text:
package org.bisso.hr.employee;

public class Secretaria extends Funcionario {

	@Override
	public double getPlr() {
		// TODO Auto-generated method stub
		return 0;
	}

}


text:
@interface BrowerLocalListViewController : BaseViewController

@property(nonatomic,strong)PHAssetCollection *assetCollection;
@property(nonatomic,strong)PHFetchResult *fetResult;

@end


text:
        Target File:

<fieldset style="padding: 5px; border: 1px solid gray">
    <legend>
        Options
    </legend>
    <input id="GitUntrackCacheCheckbox" data-dojo-type="dijit/form/CheckBox" data-dojo-props="checked: true"/>
    Cache
</fieldset>


text:
package com.psddev.dari.util.sa;

import com.psddev.dari.util.asm.Opcodes;

public class JvmObjectUnary extends JvmObject {

    private final int operatorOpcode;
    private final JvmObject object;

    public JvmObjectUnary(int operatorOpcode, JvmObject object) {
        super(object.type);

        this.operatorOpcode = operatorOpcode;
        this.object = object;
    }

    @Override
    protected Object doResolve() {
        Object object = this.resolve();

        switch (operatorOpcode) {
            case Opcodes.INEG :
                if (object instanceof Integer) {
                    return -((Integer) object);
                }
                break;

            case Opcodes.LNEG :
                if (object instanceof Long) {
                    return -((Long) object);
                }
                break;

            case Opcodes.FNEG :
                if (object instanceof Float) {
                    return -((Float) object);
                }
                break;

            case Opcodes.DNEG :
                if (object instanceof Double) {
                    return -((Double) object);
                }
                break;

            default :
                throw new IllegalArgumentException();
        }

        return null;
    }

    @Override
    public JvmObjectUnary clone() {
        return updateClone(new JvmObjectUnary(operatorOpcode, object.clone()));
    }

    @Override
    protected void appendTo(StringBuilder sb) {
        switch (operatorOpcode) {
            case Opcodes.INEG :
            case Opcodes.LNEG :
            case Opcodes.FNEG :
            case Opcodes.DNEG :
                sb.append('-');
                break;

            default :
                throw new IllegalArgumentException();
        }

        sb.append(object);
    }
}


text:
[Live Demo](https://adaptive-loading.web.app/cra-network-aware-loading)

A demo showing how to use network-aware resource loading in React.js.

This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).

## Installation
```
git clone https://github.com/GoogleChromeLabs/adaptive-loading
cd cra-network-aware-loading
npm install
npm start
npm run build
```


text:
@interface REDlibTests : SenTestCase

@end


text:
@(repository: gitbucket.core.service.RepositoryService.RepositoryInfo, large: Boolean)(implicit context: gitbucket.core.controller.Context)
@import gitbucket.core.service.RepositoryService
@import context._
@import gitbucket.core.view.helpers._
@if(repository.repository.isPrivate){

} else {
  @if(repository.repository.originUserName.isDefined){

  } else {

  }
}


text:
@implementation REEmailValidator

+ (NSString *)name
{
    return @"email";
}

+ (NSError *)validateObject:(NSString *)object variableName:(NSString *)name parameters:(NSDictionary *)parameters
{
    NSString *string = object ? object : @"";
    if (string.length == 0)
        return nil;

    NSError *error = NULL;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}" options:NSRegularExpressionCaseInsensitive error:&error];
    NSTextCheckingResult *match = [regex firstMatchInString:string options:0 range:NSMakeRange(0, string.length)];

    if (!match)
        return [NSError re_validationErrorForDomain:@"com.REValidation.email", name];

    return nil;
}

@end


text:
#include <common.h>
#include <charset.h>
#include <dm/device.h>
#include <efi_loader.h>
#include <stdio_dev.h>
#include <video_console.h>

static bool console_size_queried;

#define EFI_COUT_MODE_2 2
#define EFI_MAX_COUT_MODE 3

struct cout_mode {
	unsigned long columns;
	unsigned long rows;
	int present;
};

static struct cout_mode efi_cout_modes[] = {
	/* EFI Mode 0 is 80x25 and always present */
	{
		.columns = 80,
		.rows = 25,
		.present = 1,
	},
	/* EFI Mode 1 is always 80x50 */
	{
		.columns = 80,
		.rows = 50,
		.present = 0,
	},
	/* Value are unknown until we query the console */
	{
		.columns = 0,
		.rows = 0,
		.present = 0,
	},
};

const efi_guid_t efi_guid_console_control = CONSOLE_CONTROL_GUID;
const efi_guid_t efi_guid_text_output_protocol =
			EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL_GUID;
const efi_guid_t efi_guid_text_input_protocol =
			EFI_SIMPLE_TEXT_INPUT_PROTOCOL_GUID;

#define cESC '\x1b'
#define ESC "\x1b"

static efi_status_t EFIAPI efi_cin_get_mode(
			struct efi_console_control_protocol *this,
			int *mode, char *uga_exists, char *std_in_locked)
{
	EFI_ENTRY("%p, %p, %p, %p", this, mode, uga_exists, std_in_locked);

	if (mode)
		*mode = EFI_CONSOLE_MODE_TEXT;
	if (uga_exists)
		*uga_exists = 0;
	if (std_in_locked)
		*std_in_locked = 0;

	return EFI_EXIT(EFI_SUCCESS);
}

static efi_status_t EFIAPI efi_cin_set_mode(
			struct efi_console_control_protocol *this, int mode)
{
	EFI_ENTRY("%p, %d", this, mode);
	return EFI_EXIT(EFI_UNSUPPORTED);
}

static efi_status_t EFIAPI efi_cin_lock_std_in(
			struct efi_console_control_protocol *this,
			uint16_t *password)
{
	EFI_ENTRY("%p, %p", this, password);
	return EFI_EXIT(EFI_UNSUPPORTED);
}

struct efi_console_control_protocol efi_console_control = {
	.get_mode = efi_cin_get_mode,
	.set_mode = efi_cin_set_mode,
	.lock_std_in = efi_cin_lock_std_in,
};

/* Default to mode 0 */
static struct simple_text_output_mode efi_con_mode = {
	.max_mode = 1,
	.mode = 0,
	.attribute = 0,
	.cursor_column = 0,
	.cursor_row = 0,
	.cursor_visible = 1,
};

static int term_read_reply(int *n, int maxnum, char end_char)
{
	char c;
	int i = 0;

	c = getc();
	if (c != cESC)
		return -1;
	c = getc();
	if (c != '[')
		return -1;

	n[0] = 0;
	while (1) {
		c = getc();
		if (c == ';') {
			i++;
			if (i >= maxnum)
				return -1;
			n[i] = 0;
			continue;
		} else if (c == end_char) {
			break;
		} else if (c > '9' || c < '0') {
			return -1;
		}

		/* Read one more decimal position */
		n[i] *= 10;
		n[i] += c - '0';
	}

	return 0;
}

static efi_status_t EFIAPI efi_cout_reset(
			struct efi_simple_text_output_protocol *this,
			char extended_verification)
{
	EFI_ENTRY("%p, %d", this, extended_verification);
	return EFI_EXIT(EFI_UNSUPPORTED);
}

static efi_status_t EFIAPI efi_cout_output_string(
			struct efi_simple_text_output_protocol *this,
			const efi_string_t string)
{
	struct simple_text_output_mode *con = &efi_con_mode;
	struct cout_mode *mode = &efi_cout_modes[con->mode];

	EFI_ENTRY("%p, %p", this, string);

	unsigned int n16 = utf16_strlen(string);
	char buf[MAX_UTF8_PER_UTF16 * n16 + 1];
	char *p;

	*utf16_to_utf8((u8 *)buf, string, n16) = '\0';

	fputs(stdout, buf);

	for (p = buf; *p; p++) {
		switch (*p) {
		case '\r':   /* carriage-return */
			con->cursor_column = 0;
			break;
		case '\n':   /* newline */
			con->cursor_column = 0;
			con->cursor_row++;
			break;
		case '\t':   /* tab, assume 8 char align */
			break;
		case '\b':   /* backspace */
			con->cursor_column = max(0, con->cursor_column - 1);
			break;
		default:
			con->cursor_column++;
			break;
		}
		if (con->cursor_column >= mode->columns) {
			con->cursor_column = 0;
			con->cursor_row++;
		}
		con->cursor_row = min(con->cursor_row, (s32)mode->rows - 1);
	}

	return EFI_EXIT(EFI_SUCCESS);
}

static efi_status_t EFIAPI efi_cout_test_string(
			struct efi_simple_text_output_protocol *this,
			const efi_string_t string)
{
	EFI_ENTRY("%p, %p", this, string);
	return EFI_EXIT(EFI_SUCCESS);
}

static bool cout_mode_matches(struct cout_mode *mode, int rows, int cols)
{
	if (!mode->present)
		return false;

	return (mode->rows == rows) && (mode->columns == cols);
}

static int query_console_serial(int *rows, int *cols)
{
	/* Ask the terminal about its size */
	int n[3];
	u64 timeout;

	/* Empty input buffer */
	while (tstc())
		getc();

	printf(ESC"[18t");

	/* Check if we have a terminal that understands */
	timeout = timer_get_us() + 1000000;
	while (!tstc())
		if (timer_get_us() > timeout)
			return -1;

	/* Read {depth,rows,cols} */
	if (term_read_reply(n, 3, 't'))
		return -1;

	*cols = n[2];
	*rows = n[1];

	return 0;
}

static efi_status_t EFIAPI efi_cout_query_mode(
			struct efi_simple_text_output_protocol *this,
			unsigned long mode_number, unsigned long *columns,
			unsigned long *rows)
{
	EFI_ENTRY("%p, %ld, %p, %p", this, mode_number, columns, rows);

	if (!console_size_queried) {
		const char *stdout_name = env_get("stdout");
		int rows, cols;

		console_size_queried = true;

		if (stdout_name && !strcmp(stdout_name, "vidconsole") &&
		    IS_ENABLED(CONFIG_DM_VIDEO)) {
			struct stdio_dev *stdout_dev =
				stdio_get_by_name("vidconsole");
			struct udevice *dev = stdout_dev->priv;
			struct vidconsole_priv *priv =
				dev_get_uclass_priv(dev);
			rows = priv->rows;
			cols = priv->cols;
		} else if (query_console_serial(&rows, &cols)) {
			goto out;
		}

		/* Test if we can have Mode 1 */
		if (cols >= 80 && rows >= 50) {
			efi_cout_modes[1].present = 1;
			efi_con_mode.max_mode = 2;
		}

		/*
		 * Install our mode as mode 2 if it is different
		 * than mode 0 or 1 and set it  as the currently selected mode
		 */
		if (!cout_mode_matches(&efi_cout_modes[0], rows, cols) &&
		    !cout_mode_matches(&efi_cout_modes[1], rows, cols)) {
			efi_cout_modes[EFI_COUT_MODE_2].columns = cols;
			efi_cout_modes[EFI_COUT_MODE_2].rows = rows;
			efi_cout_modes[EFI_COUT_MODE_2].present = 1;
			efi_con_mode.max_mode = EFI_MAX_COUT_MODE;
			efi_con_mode.mode = EFI_COUT_MODE_2;
		}
	}

	if (mode_number >= efi_con_mode.max_mode)
		return EFI_EXIT(EFI_UNSUPPORTED);

	if (efi_cout_modes[mode_number].present != 1)
		return EFI_EXIT(EFI_UNSUPPORTED);

out:
	if (columns)
		*columns = efi_cout_modes[mode_number].columns;
	if (rows)
		*rows = efi_cout_modes[mode_number].rows;

	return EFI_EXIT(EFI_SUCCESS);
}

static efi_status_t EFIAPI efi_cout_set_mode(
			struct efi_simple_text_output_protocol *this,
			unsigned long mode_number)
{
	EFI_ENTRY("%p, %ld", this, mode_number);

	if (mode_number > efi_con_mode.max_mode)
		return EFI_EXIT(EFI_UNSUPPORTED);

	efi_con_mode.mode = mode_number;
	efi_con_mode.cursor_column = 0;
	efi_con_mode.cursor_row = 0;

	return EFI_EXIT(EFI_SUCCESS);
}

static const struct {
	unsigned int fg;
	unsigned int bg;
} color[] = {
	{ 30, 40 },     /* 0: black */
	{ 34, 44 },     /* 1: blue */
	{ 32, 42 },     /* 2: green */
	{ 36, 46 },     /* 3: cyan */
	{ 31, 41 },     /* 4: red */
	{ 35, 45 },     /* 5: magenta */
	{ 33, 43 },     /* 6: brown, map to yellow as edk2 does*/
	{ 37, 47 },     /* 7: light grey, map to white */
};

/* See EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL.SetAttribute(). */
static efi_status_t EFIAPI efi_cout_set_attribute(
			struct efi_simple_text_output_protocol *this,
			unsigned long attribute)
{
	unsigned int bold = EFI_ATTR_BOLD(attribute);
	unsigned int fg = EFI_ATTR_FG(attribute);
	unsigned int bg = EFI_ATTR_BG(attribute);

	EFI_ENTRY("%p, %lx", this, attribute);

	if (attribute)
		printf(ESC"[%u;%u;%um", bold, color[fg].fg, color[bg].bg);
	else
		printf(ESC"[0;37;40m");

	return EFI_EXIT(EFI_SUCCESS);
}

static efi_status_t EFIAPI efi_cout_clear_screen(
			struct efi_simple_text_output_protocol *this)
{
	EFI_ENTRY("%p", this);

	printf(ESC"[2J");

	return EFI_EXIT(EFI_SUCCESS);
}

static efi_status_t EFIAPI efi_cout_set_cursor_position(
			struct efi_simple_text_output_protocol *this,
			unsigned long column, unsigned long row)
{
	EFI_ENTRY("%p, %ld, %ld", this, column, row);

	printf(ESC"[%d;%df", (int)row, (int)column);
	efi_con_mode.cursor_column = column;
	efi_con_mode.cursor_row = row;

	return EFI_EXIT(EFI_SUCCESS);
}

static efi_status_t EFIAPI efi_cout_enable_cursor(
			struct efi_simple_text_output_protocol *this,
			bool enable)
{
	EFI_ENTRY("%p, %d", this, enable);

	printf(ESC"[?25%c", enable ? 'h' : 'l');

	return EFI_EXIT(EFI_SUCCESS);
}

struct efi_simple_text_output_protocol efi_con_out = {
	.reset = efi_cout_reset,
	.output_string = efi_cout_output_string,
	.test_string = efi_cout_test_string,
	.query_mode = efi_cout_query_mode,
	.set_mode = efi_cout_set_mode,
	.set_attribute = efi_cout_set_attribute,
	.clear_screen = efi_cout_clear_screen,
	.set_cursor_position = efi_cout_set_cursor_position,
	.enable_cursor = efi_cout_enable_cursor,
	.mode = (void*)&efi_con_mode,
};

static efi_status_t EFIAPI efi_cin_reset(
			struct efi_simple_input_interface *this,
			bool extended_verification)
{
	EFI_ENTRY("%p, %d", this, extended_verification);
	return EFI_EXIT(EFI_UNSUPPORTED);
}

static efi_status_t EFIAPI efi_cin_read_key_stroke(
			struct efi_simple_input_interface *this,
			struct efi_input_key *key)
{
	struct efi_input_key pressed_key = {
		.scan_code = 0,
		.unicode_char = 0,
	};
	char ch;

	EFI_ENTRY("%p, %p", this, key);

	/* We don't do interrupts, so check for timers cooperatively */
	efi_timer_check();

	if (!tstc()) {
		/* No key pressed */
		return EFI_EXIT(EFI_NOT_READY);
	}

	ch = getc();
	if (ch == cESC) {
		/* Escape Sequence */
		ch = getc();
		switch (ch) {
		case cESC: /* ESC */
			pressed_key.scan_code = 23;
			break;
		case 'O': /* F1 - F4 */
			pressed_key.scan_code = getc() - 'P' + 11;
			break;
		case 'a'...'z':
			ch = ch - 'a';
			break;
		case '[':
			ch = getc();
			switch (ch) {
			case 'A'...'D': /* up, down right, left */
				pressed_key.scan_code = ch - 'A' + 1;
				break;
			case 'F': /* End */
				pressed_key.scan_code = 6;
				break;
			case 'H': /* Home */
				pressed_key.scan_code = 5;
				break;
			case '1': /* F5 - F8 */
				pressed_key.scan_code = getc() - '0' + 11;
				getc();
				break;
			case '2': /* F9 - F12 */
				pressed_key.scan_code = getc() - '0' + 19;
				getc();
				break;
			case '3': /* DEL */
				pressed_key.scan_code = 8;
				getc();
				break;
			}
			break;
		}
	} else if (ch == 0x7f) {
		/* Backspace */
		ch = 0x08;
	}
	pressed_key.unicode_char = ch;
	*key = pressed_key;

	return EFI_EXIT(EFI_SUCCESS);
}

struct efi_simple_input_interface efi_con_in = {
	.reset = efi_cin_reset,
	.read_key_stroke = efi_cin_read_key_stroke,
	.wait_for_key = NULL,
};

static struct efi_event *console_timer_event;

static void EFIAPI efi_key_notify(struct efi_event *event, void *context)
{
}

static void EFIAPI efi_console_timer_notify(struct efi_event *event,
					    void *context)
{
	EFI_ENTRY("%p, %p", event, context);
	if (tstc()) {
		efi_con_in.wait_for_key->is_signaled = true;
		efi_signal_event(efi_con_in.wait_for_key);
		}
	EFI_EXIT(EFI_SUCCESS);
}

/* This gets called from do_bootefi_exec(). */
int efi_console_register(void)
{
	efi_status_t r;
	struct efi_object *efi_console_control_obj;
	struct efi_object *efi_console_output_obj;
	struct efi_object *efi_console_input_obj;

	/* Create handles */
	r = efi_create_handle((void **)&efi_console_control_obj);
	if (r != EFI_SUCCESS)
		goto out_of_memory;
	r = efi_add_protocol(efi_console_control_obj->handle,
			     &efi_guid_console_control, &efi_console_control);
	if (r != EFI_SUCCESS)
		goto out_of_memory;
	r = efi_create_handle((void **)&efi_console_output_obj);
	if (r != EFI_SUCCESS)
		goto out_of_memory;
	r = efi_add_protocol(efi_console_output_obj->handle,
			     &efi_guid_text_output_protocol, &efi_con_out);
	if (r != EFI_SUCCESS)
		goto out_of_memory;
	r = efi_create_handle((void **)&efi_console_input_obj);
	if (r != EFI_SUCCESS)
		goto out_of_memory;
	r = efi_add_protocol(efi_console_input_obj->handle,
			     &efi_guid_text_input_protocol, &efi_con_in);
	if (r != EFI_SUCCESS)
		goto out_of_memory;

	/* Create console events */
	r = efi_create_event(EVT_NOTIFY_WAIT, TPL_CALLBACK,
			     efi_key_notify, NULL, &efi_con_in.wait_for_key);
	if (r != EFI_SUCCESS) {
		printf("ERROR: Failed to register WaitForKey event\n");
		return r;
	}
	r = efi_create_event(EVT_TIMER | EVT_NOTIFY_SIGNAL, TPL_CALLBACK,
			     efi_console_timer_notify, NULL,
			     &console_timer_event);
	if (r != EFI_SUCCESS) {
		printf("ERROR: Failed to register console event\n");
		return r;
	}
	/* 5000 ns cycle is sufficient for 2 MBaud */
	r = efi_set_timer(console_timer_event, EFI_TIMER_PERIODIC, 50);
	if (r != EFI_SUCCESS)
		printf("ERROR: Failed to set console timer\n");
	return r;
out_of_memory:
	printf("ERROR: Out of meemory\n");
	return r;
}


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
Philipp. J. Sci. 1(suppl. 2):147, t. 3. 1906

#### Original name
null

### Remarks
null


text:
import re

from .screen_buffer import ScreenBuffer

class SQLDriver(ScreenBuffer.Driver):
    def __init__(self, level=None, facility=None, host=None, program=None,
            start_date=None):
        self._level = level
        self._facility = facility
        self._host = host
        self._program = program
        self._start_date = start_date

    def has_start_date(self):
        return not (not self._start_date)

    def prepare_datetime_query(self):
        dt_str = self._start_date.strftime('%Y-%m-%d %H:%M:%S')

        return self.select("SELECT id, facility_num, level_num, host, "\
            "datetime, program, pid, message FROM logs WHERE datetime >= "\
            "'{}' ORDER BY datetime ASC LIMIT 1".format(dt_str))

    def prepare_query(self, start, desc, count):
        parts = [
            "SELECT id, facility_num, level_num, host, datetime, program, pid, message",
            "FROM logs",
            self._where(self._id_where(start, desc)),
            self._order(desc),
            self._limit(count)
        ]
        return self.select(' '.join(p for p in parts if p))

    def _build_one_filter(self, value):
        is_wildcard, is_negative = False, False

        match = re.search('(.+)\*$', value)
        if match:
            value = match.group(1)
            is_wildcard = True

        match = re.search('^!(.+)', value)
        if match:
            value = match.group(1)
            is_negative = True

        if not is_wildcard and not is_negative:
            return "= '{}'".format(value)
        elif not is_wildcard:
            return "<> '{}'".format(value)
        elif not is_negative:
            return "LIKE '{}%'".format(value)
        else:
            return "NOT LIKE '{}%'".format(value)

    def _get_separate_conditions(self, column, list):
        return ["{} {}".format(column, self._build_one_filter(x)) for x in list]

    def _get_include_and_exclude_conditions(self, conditions):
        include = []
        exclude = []
        for val in conditions.split(' '):
            if not val:
                continue
            if re.search('^!', val):
                exclude.append(val)
            else:
                include.append(val)
        return (include, exclude)

    def _get_string_condition(self, column, conditions):
        include, exclude = self._get_include_and_exclude_conditions(conditions)
        parts = []
        if include:
            list = " OR ".join(self._get_separate_conditions(column, include))
            parts.append("({})".format(list))
        parts += self._get_separate_conditions(column, exclude)
        return " AND ".join(parts)

    def _id_where(self, start, desc):
        if start is None:
            return
        if desc:
            fmt = 'id < {}'
        else:
            fmt = 'id > {}'
        return fmt.format(start)

    def _where(self, id_where):
        conds = []
        if id_where:
            conds.append(id_where)
        if not self._level is None:
            conds.append('level_num <= {}'.format(self._level))
        if not self._facility is None:
            conds.append('facility_num = {}'.format(self._facility))
        if not self._host is None:
            conds.append(self._get_string_condition('host', self._host))
        if not self._program is None:
            conds.append(self._get_string_condition('program', self._program))
        if not conds:
            return
        return 'WHERE {}'.format(' AND '.join(conds))

    def _order(self, desc):
        if desc:
            return 'ORDER BY id DESC'
        return 'ORDER BY id ASC'

    def _limit(self, count):
        return 'LIMIT {}'.format(count)


text:
Spring-Boot Quickstarts
=======================

Various quickstart projects using [Spring Boot](http://projects.spring.io/spring-boot).

The following quickstarts is provided out of the box:

* [activemq](activemq) - This example demonstrates how you can use Apache ActiveMQ with Spring Boot in a [Java Container](http://fabric8.io/gitbook/javaContainer.html)
* [camel](camel) - This example demonstrates how you can use Apache Camel with Spring Boot in a [Java Container](http://fabric8.io/gitbook/javaContainer.html)
* [keycloak](keycloak) - This example demonstrates how you can use Spring Boot and web mvc with a [Java Container](http://fabric8.io/gitbook/javaContainer.html), using Keycloak for authentication.
* [webmvc](webmvc) - This example demonstrates how you can use Spring Boot and web mvc with a [Java Container](http://fabric8.io/gitbook/javaContainer.html)
* [webmvc-ip](webmvc-ip) - This example demonstrates how you can use Spring Boot and web mvc with a [Java Container](http://fabric8.io/gitbook/javaContainer.html) and returning IP to demonstrate load balancing


text:
<?php abstract class PageTool {
/**
 * PageTool objects operate in a similar way to PageCode objects. PageTools can
 * be seen as groupings of reusable code, that is made accessible to all
 * PageCode.
 *
 * A PageTool is usually created when code within a PageCode becomes required
 * elsewhere in an application. This code is then packaged into a tool, that
 * serves a particular purpose.
 *
 * Common tools are provided with PHP.Gt, but application specific tools can
 * be used to keep the PageCode clean.
 */
protected $_name = null;
/** @var ApiWrapper */
protected $_api = null;
/** @var Dom  */
protected $_dom = null;
/** @var TemplateWrapper */
protected $_template = null;
/** @var PageToolWrapper  */
protected $_tool = null;

public function __construct($api, $dom, $template, $tool) {
	$className = get_called_class();
	$this->_name = substr($className, 0, strrpos($className, "_PageTool"));
	$this->_api = $api;
	$this->_dom = $dom;
	$this->_template = $template;
	$this->_tool = $tool;
}

/**
 * Injects any client side files used by the current tool into the DOM. The
 * injected files can then be compiled/pre-processed/minified in the usual
 * way.
 */
public function clientSide() {
	$dirArrays = array(
		"Script" => array(
			APPROOT . "/PageTool/{$this->_name}/Script/",
			GTROOT  . "/PageTool/{$this->_name}/Script/",
		),
		"Style" => array(
			APPROOT . "/PageTool/{$this->_name}/Style/",
			GTROOT  . "/PageTool/{$this->_name}/Style/",
		),
	);
	$elementInfo = array(
		"Script" => [
			"tagName" => "script",
			"source" => "src",
			"attributes" => [],
		],
		"Style" => [
			"tagName" => "link",
			"source" => "href",
			"attributes" => ["rel" => "stylesheet"],
		],
	);

	$domHead = $this->_dom["html > head"];
	$ptDir = "PageTool/{$this->_name}";
	$wwwDir = APPROOT . "/www/$ptDir";

	foreach ($dirArrays as $currentType => $dirArray) {
		foreach ($dirArray as $dir) {
			if(!is_dir($dir)) {
				continue;
			}

			foreach ($iterator = new RecursiveIteratorIterator(
	  		new RecursiveDirectoryIterator($dir,
	  			RecursiveDirectoryIterator::SKIP_DOTS),
	  		RecursiveIteratorIterator::SELF_FIRST) as $item) {
	  			$subPath = $iterator->getSubPathName();
				if($item->isDir()) {
					if(is_dir("$wwwDir/$subPath")) {
						continue;
					}
					if(!mkdir("$wwwDir/$subPath", 0775, true)) {
						die("error making $wwwDir/$subPath");
					}
				}
				else {
					$destination = APPROOT . "/www/$currentType/$subPath";
					if(!is_dir(dirname($destination))) {
						mkdir(dirname($destination), 0775, true);
					}
					copy($item->getPathname(), $destination);

					$elementAttributes = array();
					$elementAttributes[$elementInfo[$currentType]["source"]]
						= "/$currentType/$subPath";
					$elementAttributes = array_merge(
						$elementAttributes,
						$elementInfo[$currentType]["attributes"]
					);

					$domHead->appendChild(
						$elementInfo[$currentType]["tagName"],
						$elementAttributes);
				}
			}
		}
	}
}

/**
 * Works in the same way that PageCode's go() function does.
 * @param ApiWrapper $api Used exactly like the $api variable from within
 * PageCode, but with access to this tool's TableCollections.
 * @param Dom $dom An extended DomDocument, providing helpful functions and
 * most notably element CSS selection. Any manipulation that is made to the
 * DOM will be sent to the browser.
 * @param array $template An associative array containing all DOM elements
 * that have been scraped out of the DOM with data-template attributes.
 * Each element keeps its designed form from how it appears in the HMTL.
 * @param ToolWrapper $tool The object that acts as a single entry point
 * to all PageTools. Can activate a PageTool by calling it through this
 * Associative array.
 */
abstract protected function go($api, $dom, $template, $tool);

}#


text:
package org.subethamail.smtp.server;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.security.cert.Certificate;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.subethamail.smtp.AuthenticationHandler;
import org.subethamail.smtp.DropConnectionException;
import org.subethamail.smtp.MessageContext;
import org.subethamail.smtp.MessageHandler;
import org.subethamail.smtp.io.CRLFTerminatedReader;

/**
 * The thread that handles a connection. This class
 * passes most of it's responsibilities off to the
 * CommandHandler.
 *
 * @author Jon Stevens
 * @author Jeff Schnitzer
 */
public class Session implements Runnable, MessageContext
{
	private final static Logger log = LoggerFactory.getLogger(Session.class);

	/** A link to our parent server */
	private SMTPServer server;

	/**
	 * A link to our parent server thread, which must be notified when this
	 * connection is finished.
	 */
	private ServerThread serverThread;

	/**
	 * Saved SLF4J mapped diagnostic context of the parent thread. The parent
	 * thread is the one which calls the constructor. MDC is usually inherited
	 * by new threads, but this mechanism does not work with executors.
	 */
	private final Map<?, ?> parentLoggingMdcContext = MDC.getCopyOfContextMap();

	/**
	 * Uniquely identifies this session within an extended time period, useful
	 * for logging.
	 */
	private String sessionId;

	/** Set this true when doing an ordered shutdown */
	private volatile boolean quitting = false;

	/** I/O to the client */
	private Socket socket;
	private InputStream input;
	private CRLFTerminatedReader reader;
	private PrintWriter writer;

	/** Might exist if the client has successfully authenticated */
	private AuthenticationHandler authenticationHandler;

	/** Might exist if the client is giving us a message */
	private MessageHandler messageHandler;

	/** Some state information */
	private String helo;
	private boolean hasMailFrom;
	private int recipientCount;
	/**
	 * The recipient address in the first accepted RCPT command, but only if
	 * there is exactly one such accepted recipient. If there is no accepted
	 * recipient yet, or if there are more than one, then this value is null.
	 * This information is useful in the construction of the FOR clause of the
	 * Received header.
	 */
	private String singleRecipient;

	/**
	 * If the client told us the size of the message, this is the value.
	 * If they didn't, the value will be 0.
	 */
	private int declaredMessageSize = 0;

	/** Some more state information */
	private boolean tlsStarted;
	private Certificate[] tlsPeerCertificates;

	/**
	 * Creates the Runnable Session object.
	 *
	 * @param server a link to our parent
	 * @param socket is the socket to the client
	 * @throws IOException
	 */
	public Session(SMTPServer server, ServerThread serverThread, Socket socket)
		throws IOException
	{
		this.server = server;
		this.serverThread = serverThread;

		this.setSocket(socket);
	}

	/**
	 * @return a reference to the master server object
	 */
	public SMTPServer getServer()
	{
		return this.server;
	}

	/**
	 * The thread for each session runs on this and shuts down when the quitting
	 * member goes true.
	 */
	@Override
	public void run()
	{
		MDC.setContextMap(parentLoggingMdcContext);
		sessionId = server.getSessionIdFactory().create();
		MDC.put("SessionId", sessionId);
		final String originalName = Thread.currentThread().getName();
		Thread.currentThread().setName(
				Session.class.getName() + "-" + socket.getInetAddress() + ":"
						+ socket.getPort());

		if (log.isDebugEnabled())
		{
			InetAddress remoteInetAddress = this.getRemoteAddress().getAddress();
			remoteInetAddress.getHostName();	// Causes future toString() to print the name too

			log.debug("SMTP connection from {}, new connection count: {}", remoteInetAddress,
					this.serverThread.getNumberOfConnections());
		}

		try
		{
			runCommandLoop();
		}
		catch (IOException e1)
		{
			if (!this.quitting)
			{
				try
				{
					// Send a temporary failure back so that the server will try to resend
					// the message later.
					this.sendResponse("421 4.4.0 Problem attempting to execute commands. Please try again later.");
				}
				catch (IOException e) {}

				if (log.isWarnEnabled())
					log.warn("Exception during SMTP transaction", e1);
			}
		}
		catch (Throwable e)
		{
			log.error("Unexpected error in the SMTP handler thread", e);
			try
			{
				this.sendResponse("421 4.3.0 Mail system failure, closing transmission channel");
			}
			catch (IOException e1)
			{
				// just swallow this, the outer exception is the real problem.
			}
			if (e instanceof RuntimeException)
				throw (RuntimeException) e;
			else if (e instanceof Error)
				throw (Error) e;
			else
				throw new RuntimeException("Unexpected exception", e);
		}
		finally
		{
			this.closeConnection();
			this.endMessageHandler();
			serverThread.sessionEnded(this);
			Thread.currentThread().setName(originalName);
			MDC.clear();
		}
	}

	/**
	 * Sends the welcome message and starts receiving and processing client
	 * commands. It quits when {@link #quitting} becomes true or when it can be
	 * noticed or at least assumed that the client no longer sends valid
	 * commands, for example on timeout.
	 *
	 * @throws IOException
	 *             if sending to or receiving from the client fails.
	 */
	private void runCommandLoop() throws IOException
	{
		if (this.serverThread.hasTooManyConnections())
		{
			log.debug("SMTP Too many connections!");

			this.sendResponse("421 Too many connections, try again later");
			return;
		}

		this.sendResponse("220 " + this.server.getHostName() + " ESMTP " + this.server.getSoftwareName());

		// Start with fresh message state
		this.resetMessageState();

		while (!this.quitting)
		{
			try
			{
				String line = null;
				try
				{
					line = this.reader.readLine();
				}
				catch (SocketException ex)
				{
					// Lots of clients just "hang up" rather than issuing QUIT,
					// which would
					// fill our logs with the warning in the outer catch.
					if (log.isDebugEnabled())
						log.debug("Error reading client command: " + ex.getMessage(), ex);

					return;
				}

				if (line == null)
				{
					log.debug("no more lines from client");
					return;
				}

				if (log.isDebugEnabled())
					log.debug("Client: " + line);

				this.server.getCommandHandler().handleCommand(this, line);
			}
			catch (DropConnectionException ex)
			{
				this.sendResponse(ex.getErrorResponse());
				return;
			}
			catch (SocketTimeoutException ex)
			{
				this.sendResponse("421 Timeout waiting for data from client.");
				return;
			}
			catch (CRLFTerminatedReader.TerminationException te)
			{
				String msg = "501 Syntax error at character position " + te.position()
						+ ". CR and LF must be CRLF paired.  See RFC 2821 #2.7.1.";

				log.debug(msg);
				this.sendResponse(msg);

				// if people are screwing with things, close connection
				return;
			}
			catch (CRLFTerminatedReader.MaxLineLengthException mlle)
			{
				String msg = "501 " + mlle.getMessage();

				log.debug(msg);
				this.sendResponse(msg);

				// if people are screwing with things, close connection
				return;
			}
		}
	}

	/**
	 * Close reader, writer, and socket, logging exceptions but otherwise ignoring them
	 */
	private void closeConnection()
	{
		try
		{
			try
			{
				this.writer.close();
				this.input.close();
			}
			finally
			{
				this.closeSocket();
			}
		}
		catch (IOException e)
		{
			log.info(e.toString());
		}
	}

	/**
	 * Initializes our reader, writer, and the i/o filter chains based on
	 * the specified socket.  This is called internally when we startup
	 * and when (if) SSL is started.
	 */
	public void setSocket(Socket socket) throws IOException
	{
		this.socket = socket;
		this.input = this.socket.getInputStream();
		this.reader = new CRLFTerminatedReader(this.input);
		this.writer = new PrintWriter(this.socket.getOutputStream());

		this.socket.setSoTimeout(this.server.getConnectionTimeout());
	}

	/**
	 * This method is only used by the start tls command
	 * @return the current socket to the client
	 */
	public Socket getSocket()
	{
		return this.socket;
	}

	/** Close the client socket if it is open */
	public void closeSocket() throws IOException
	{
		if ((this.socket != null) && this.socket.isBound() && !this.socket.isClosed())
			this.socket.close();
	}

	/**
	 * @return the raw input stream from the client
	 */
	public InputStream getRawInput()
	{
		return this.input;
	}

	/**
	 * @return the cooked CRLF-terminated reader from the client
	 */
	public CRLFTerminatedReader getReader()
	{
		return this.reader;
	}

	/** Sends the response to the client */
	public void sendResponse(String response) throws IOException
	{
		if (log.isDebugEnabled())
			log.debug("Server: " + response);

		this.writer.print(response + "\r\n");
		this.writer.flush();
	}

	/**
	 * Returns an identifier of the session which is reasonably unique within
	 * an extended time period.
	 */
	public String getSessionId() {
		return sessionId;
	}

	/* (non-Javadoc)
	 * @see org.subethamail.smtp.MessageContext#getRemoteAddress()
	 */
	public InetSocketAddress getRemoteAddress()
	{
		return (InetSocketAddress)this.socket.getRemoteSocketAddress();
	}

	/* (non-Javadoc)
	 * @see org.subethamail.smtp.MessageContext#getSMTPServer()
	 */
	public SMTPServer getSMTPServer()
	{
		return this.server;
	}

	/**
	 * @return the current message handler
	 */
	public MessageHandler getMessageHandler()
	{
		return this.messageHandler;
	}

	/** Simple state */
	public String getHelo()
	{
		return this.helo;
	}

	/** */
	public void setHelo(String value)
	{
		this.helo = value;
	}

	/** */
	public boolean getHasMailFrom()
	{
		return this.hasMailFrom;
	}

	/** */
	public void setHasMailFrom(boolean value)
	{
		this.hasMailFrom = value;
	}

	/** */
	public void addRecipient(String recipientAddress)
	{
		this.recipientCount++;
		this.singleRecipient = this.recipientCount == 1 ? recipientAddress : null;
	}

	/** */
	public int getRecipientCount()
	{
		return this.recipientCount;
	}

	/**
	 * Returns the first accepted recipient if there is exactly one accepted
	 * recipient, otherwise it returns null.
	 */
	public String getSingleRecipient()
	{
		return singleRecipient;
	}

	/** */
	public boolean isAuthenticated()
	{
		return this.authenticationHandler != null;
	}

	/** */
	public AuthenticationHandler getAuthenticationHandler()
	{
		return this.authenticationHandler;
	}

	/**
	 * This is called by the AuthCommand when a session is successfully authenticated.  The
	 * handler will be an object created by the AuthenticationHandlerFactory.
	 */
	public void setAuthenticationHandler(AuthenticationHandler handler)
	{
		this.authenticationHandler = handler;
	}

	/**
	 * @return the maxMessageSize
	 */
	public int getDeclaredMessageSize()
	{
		return this.declaredMessageSize;
	}

	/**
	 * @param declaredMessageSize the size that the client says the message will be
	 */
	public void setDeclaredMessageSize(int declaredMessageSize)
	{
		this.declaredMessageSize = declaredMessageSize;
	}

	/**
	 * Reset the SMTP protocol to the initial state, which is the state after
	 * a server issues a 220 service ready greeting.
	 */
	public void resetSmtpProtocol() {
		resetMessageState();
		this.helo = null;
	}

	/**
	 * Some state is associated with each particular message (senders, recipients, the message handler).
	 * Some state is not; seeing hello, TLS, authentication.
	 */
	public void resetMessageState()
	{
		this.endMessageHandler();
		this.messageHandler = null;
		this.hasMailFrom = false;
		this.recipientCount = 0;
		this.singleRecipient = null;
		this.declaredMessageSize = 0;
	}

	public void startMailTransaction() {
		if (this.messageHandler != null)
			throw new IllegalStateException(
					"Mail transaction is already in progress");
		this.messageHandler = this.server.getMessageHandlerFactory().create(
				this);
	}

	/** Safely calls done() on a message hander, if one exists */
	protected void endMessageHandler()
	{
		if (this.messageHandler != null)
		{
			try
			{
				this.messageHandler.done();
			}
			catch (Throwable ex)
			{
				log.error("done() threw exception", ex);
			}
		}
	}

	/**
	 * Triggers the shutdown of the thread and the closing of the connection.
	 */
	public void quit()
	{
		this.quitting = true;
		this.closeConnection();
	}

	/**
	 * @return true when the TLS handshake was completed, false otherwise
	 */
	public boolean isTLSStarted()
	{
		return tlsStarted;
	}

	/**
	 * @param tlsStarted true when the TLS handshake was completed, false otherwise
	 */
	public void setTlsStarted(boolean tlsStarted)
	{
		this.tlsStarted = tlsStarted;
	}

	public void setTlsPeerCertificates(Certificate[] tlsPeerCertificates)
	{
		this.tlsPeerCertificates = tlsPeerCertificates;
	}

	/**
	 * {@inheritDoc}
	 */
	public Certificate[] getTlsPeerCertificates()
	{
		return tlsPeerCertificates;
	}
}


text:
#pragma once
#include <aws/iot1click-devices/IoT1ClickDevicesService_EXPORTS.h>
#include <aws/iot1click-devices/IoT1ClickDevicesServiceRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace IoT1ClickDevicesService
{
namespace Model
{

  /**
   */
  class AWS_IOT1CLICKDEVICESSERVICE_API InitiateDeviceClaimRequest : public IoT1ClickDevicesServiceRequest
  {
  public:
    InitiateDeviceClaimRequest();

    // Service request name is the Operation name which will send this request out,
    // each operation should has unique request name, so that we can get operation's name from this request.
    // Note: this is not true for response, multiple operations may have the same response name,
    // so we can not get operation's name from response.
    inline virtual const char* GetServiceRequestName() const override { return "InitiateDeviceClaim"; }

    Aws::String SerializePayload() const override;

    /**
     *
The unique identifier of the device.

     */
    inline const Aws::String& GetDeviceId() const{ return m_deviceId; }

    /**
     *
The unique identifier of the device.

     */
    inline void SetDeviceId(const Aws::String& value) { m_deviceIdHasBeenSet = true; m_deviceId = value; }

    /**
     *
The unique identifier of the device.

     */
    inline void SetDeviceId(Aws::String&& value) { m_deviceIdHasBeenSet = true; m_deviceId = std::move(value); }

    /**
     *
The unique identifier of the device.

     */
    inline void SetDeviceId(const char* value) { m_deviceIdHasBeenSet = true; m_deviceId.assign(value); }

    /**
     *
The unique identifier of the device.

     */
    inline InitiateDeviceClaimRequest& WithDeviceId(const Aws::String& value) { SetDeviceId(value); return *this;}

    /**
     *
The unique identifier of the device.

     */
    inline InitiateDeviceClaimRequest& WithDeviceId(Aws::String&& value) { SetDeviceId(std::move(value)); return *this;}

    /**
     *
The unique identifier of the device.

     */
    inline InitiateDeviceClaimRequest& WithDeviceId(const char* value) { SetDeviceId(value); return *this;}

  private:

    Aws::String m_deviceId;
    bool m_deviceIdHasBeenSet;
  };

} // namespace Model
} // namespace IoT1ClickDevicesService
} // namespace Aws