text:
package com.qingbo.ginkgo.ygb.account.payment.qdd;

import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.qingbo.ginkgo.ygb.account.payment.PaymentResponse;

public class QDDPaymentResponse implements PaymentResponse {
	private String rawText;
	private Map<String, String> map;
	private String message;
	private boolean success;

	@SuppressWarnings("unchecked")
	public QDDPaymentResponse(String rawText) {
		this.rawText = rawText;
		if(rawText == null || (rawText=rawText.trim()).length() == 0) {
			this.map = new HashMap<>();
		}else if(rawText.startsWith("[")) {//转账可能会返回两个结果:转账成功+审核通过,这里只取转账成功
			Map<String, String>[] maps = JSON.parseObject(rawText, HashMap[].class);
			this.map = maps[0];
		}else if(rawText.startsWith("{")){
			this.map = JSON.parseObject(rawText, HashMap.class);
		}else {
			this.map = new HashMap<>();
		}
		this.message = this.map.get("Message");
		this.success = "88".equals(this.map.get("ResultCode"));
	}

	@Override
	public boolean success() {
		return success;
	}

	@Override
	public String message() {
		return message;
	}

	@Override
	public String rawText() {
		return rawText;
	}

	@Override
	public Map<String, String> map() {
		return map;
	}
}

redpajama_set_name: RedPajamaGithub


text:
.class public Lcom/thoughtworks/xstream/core/util/ThreadSafeSimpleDateFormat;
.super Ljava/lang/Object;
.source ""

# instance fields
.field private final formatString:Ljava/lang/String;

.field private final pool:Lcom/thoughtworks/xstream/core/util/Pool;

.field private final timeZone:Ljava/util/TimeZone;

# direct methods
.method public constructor <init>(Ljava/lang/String;Ljava/util/TimeZone;IIZ)V
    .locals 7

    .line 45
    move-object v0, p0

    move-object v1, p1

    move-object v2, p2

    sget-object v3, Ljava/util/Locale;->ENGLISH:Ljava/util/Locale;

    move v4, p3

    move v5, p4

    move v6, p5

    invoke-direct/range {v0 .. v6}, Lcom/thoughtworks/xstream/core/util/ThreadSafeSimpleDateFormat;-><init>(Ljava/lang/String;Ljava/util/TimeZone;Ljava/util/Locale;IIZ)V

    .line 46
    return-void
.end method

.method public constructor <init>(Ljava/lang/String;Ljava/util/TimeZone;Ljava/util/Locale;IIZ)V
    .locals 2

    .line 50
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    .line 51
    iput-object p1, p0, Lcom/thoughtworks/xstream/core/util/ThreadSafeSimpleDateFormat;->formatString:Ljava/lang/String;

    .line 52
    iput-object p2, p0, Lcom/thoughtworks/xstream/core/util/ThreadSafeSimpleDateFormat;->timeZone:Ljava/util/TimeZone;

    .line 53
    new-instance v0, Lcom/thoughtworks/xstream/core/util/Pool;

    new-instance v1, Lcom/thoughtworks/xstream/core/util/ThreadSafeSimpleDateFormat$1;

    invoke-direct {v1, p0, p3, p6}, Lcom/thoughtworks/xstream/core/util/ThreadSafeSimpleDateFormat$1;-><init>(Lcom/thoughtworks/xstream/core/util/ThreadSafeSimpleDateFormat;Ljava/util/Locale;Z)V

    invoke-direct {v0, p4, p5, v1}, Lcom/thoughtworks/xstream/core/util/Pool;-><init>(IILcom/thoughtworks/xstream/core/util/Pool$Factory;)V

    iput-object v0, p0, Lcom/thoughtworks/xstream/core/util/ThreadSafeSimpleDateFormat;->pool:Lcom/thoughtworks/xstream/core/util/Pool;

    .line 61
    return-void
.end method

.method static synthetic access$000(Lcom/thoughtworks/xstream/core/util/ThreadSafeSimpleDateFormat;)Ljava/lang/String;
    .locals 1

    .line 36
    iget-object v0, p0, Lcom/thoughtworks/xstream/core/util/ThreadSafeSimpleDateFormat;->formatString:Ljava/lang/String;

    return-object v0
.end method

.method private fetchFromPool()Ljava/text/DateFormat;
    .locals 4

    .line 82
    iget-object v0, p0, Lcom/thoughtworks/xstream/core/util/ThreadSafeSimpleDateFormat;->pool:Lcom/thoughtworks/xstream/core/util/Pool;

    invoke-virtual {v0}, Lcom/thoughtworks/xstream/core/util/Pool;->fetchFromPool()Ljava/lang/Object;

    move-result-object v0

    check-cast v0, Ljava/text/DateFormat;

    move-object v2, v0

    .line 83
    iget-object v0, p0, Lcom/thoughtworks/xstream/core/util/ThreadSafeSimpleDateFormat;->timeZone:Ljava/util/TimeZone;

    if-eqz v0, :cond_0

    iget-object v0, p0, Lcom/thoughtworks/xstream/core/util/ThreadSafeSimpleDateFormat;->timeZone:Ljava/util/TimeZone;

    goto :goto_0

    :cond_0
    invoke-static {}, Ljava/util/TimeZone;->getDefault()Ljava/util/TimeZone;

    move-result-object v0

    .line 84
    :goto_0
    move-object v3, v0

    invoke-virtual {v2}, Ljava/text/DateFormat;->getTimeZone()Ljava/util/TimeZone;

    move-result-object v1

    invoke-virtual {v0, v1}, Ljava/lang/Object;->equals(Ljava/lang/Object;)Z

    move-result v0

    if-nez v0, :cond_1

    .line 85
    invoke-virtual {v2, v3}, Ljava/text/DateFormat;->setTimeZone(Ljava/util/TimeZone;)V

    .line 87
    :cond_1
    return-object v2
.end method

# virtual methods
.method public format(Ljava/util/Date;)Ljava/lang/String;
    .locals 2

    .line 64
    invoke-direct {p0}, Lcom/thoughtworks/xstream/core/util/ThreadSafeSimpleDateFormat;->fetchFromPool()Ljava/text/DateFormat;

    move-result-object v1

    .line 66
    :try_start_0
    invoke-virtual {v1, p1}, Ljava/text/DateFormat;->format(Ljava/util/Date;)Ljava/lang/String;

    move-result-object p1
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    .line 68
    iget-object v0, p0, Lcom/thoughtworks/xstream/core/util/ThreadSafeSimpleDateFormat;->pool:Lcom/thoughtworks/xstream/core/util/Pool;

    invoke-virtual {v0, v1}, Lcom/thoughtworks/xstream/core/util/Pool;->putInPool(Ljava/lang/Object;)V

    return-object p1

    :catchall_0
    move-exception p1

    iget-object v0, p0, Lcom/thoughtworks/xstream/core/util/ThreadSafeSimpleDateFormat;->pool:Lcom/thoughtworks/xstream/core/util/Pool;

    invoke-virtual {v0, v1}, Lcom/thoughtworks/xstream/core/util/Pool;->putInPool(Ljava/lang/Object;)V

    throw p1
.end method

.method public parse(Ljava/lang/String;)Ljava/util/Date;
    .locals 2

    .line 73
    invoke-direct {p0}, Lcom/thoughtworks/xstream/core/util/ThreadSafeSimpleDateFormat;->fetchFromPool()Ljava/text/DateFormat;

    move-result-object v1

    .line 75
    :try_start_0
    invoke-virtual {v1, p1}, Ljava/text/DateFormat;->parse(Ljava/lang/String;)Ljava/util/Date;

    move-result-object p1
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    .line 77
    iget-object v0, p0, Lcom/thoughtworks/xstream/core/util/ThreadSafeSimpleDateFormat;->pool:Lcom/thoughtworks/xstream/core/util/Pool;

    invoke-virtual {v0, v1}, Lcom/thoughtworks/xstream/core/util/Pool;->putInPool(Ljava/lang/Object;)V

    return-object p1

    :catchall_0
    move-exception p1

    iget-object v0, p0, Lcom/thoughtworks/xstream/core/util/ThreadSafeSimpleDateFormat;->pool:Lcom/thoughtworks/xstream/core/util/Pool;

    invoke-virtual {v0, v1}, Lcom/thoughtworks/xstream/core/util/Pool;->putInPool(Ljava/lang/Object;)V

    throw p1
.end method

.method public toString()Ljava/lang/String;
    .locals 1

    .line 91
    iget-object v0, p0, Lcom/thoughtworks/xstream/core/util/ThreadSafeSimpleDateFormat;->formatString:Ljava/lang/String;

    return-object v0
.end method


text:
var validations = {
  page: function(req) {
    var required = [],
        validation = {'status': true},
        errors = {};
        invalid_fields = [];

    // Validate Fraud Type
    if ( req.path == '/fraud-type' ) {
      if ( Object.keys(req.body).length === 0 ) {
        validation.status = false;
        errors = get_errors('', 'You must select at least one option');
      }
      validation.errors = get_errors('', '', required);
      return validation;
    }

    // Validate Employment Details Page
    if ( req.path == '/employment-details' ) {
      validation.errors = get_errors('', '', required);
      return validation;
    }

    // Partner Details
    if ( req.path == '/partner-details' ) {
      if ( req.body.other_name_select === 'Yes' ) {
        if ( req.body.other_name === '' ) {
          validation.status = false;
          validation.other_name = 'error';
          required.push('Other name');
        }
      }

      if ( req.body.address_details === 'yes_and_know') {
        if ( req.body.street === '' ) {
          validation.status = false;
          validation.street = 'error';
          required.push('Street');
        }

        if ( req.body.town === '' ) {
          validation.status = false;
          validation.town = 'error';
          required.push('Town');
        }
      }

      if ( req.body.dob_select === 'Yes' ) {
        if ( req.body.dob_day === '' || req.body.dob_month === '' || req.body.dob_year === '' ) {
          validation.status = false;
          validation.dob = 'error';
          required.push('Date of birth');
        }
      } else {
        if ( req.body.age === '' ) {
          validation.status = false;
          validation.age = 'error';
          required.push('Approximate age');
        }
      }

      if ( req.body.nino_select === 'Yes' ) {
        if ( req.body.nino === '' ) {
          validation.status = false;
          validation.nino = 'error';
          required.push('National Insurance number');
        }
      }

      if ( req.body.phone_select === 'Yes' ) {
        if ( req.body.phone === '' ) {
          validation.status = false;
          validation.phone = 'error';
          required.push('Phone');
        }
      }

      if ( req.body.email_select === 'Yes' ) {
        if ( req.body.email === '' ) {
          validation.status = false;
          validation.email = 'error';
          required.push('Email');
        }
      }
      validation.errors = get_errors('', '', required);
      return validation;
    }

    // Partner Employment
    if ( req.path == '/partner-employment' ) {

      return validation;
    }

    // Disability
    if ( req.path == '/disability') {
      if ( req.body.what_makes_you_doubt === '' ) {
        validation.status = false;
        validation.what_makes_you_doubt = 'error';
        required.push('What activity are they doing?');
      }
      validation.errors = get_errors('', '', '');
      return validation;
    }

    // Carers
    if ( req.path == '/carers') {
      if ( req.body.carers === '' ) {
        validation.status = false;
        validation.why_do_you_think_that = 'error';
        required.push('Why do you think that?');
      }
      validation.errors = get_errors('', '', '');
      return validation;
    }

    // Abroad
    if ( req.path == '/abroad') {
      validation.errors = get_errors('', '', '');
      return validation;
    }

    // Identity
    if ( req.path == '/identity') {
      if ( req.body.identity === '' ) {
        validation.status = false;
        validation.identity = 'error';
        required.push("Why do you think they're committing identity fraud?");
      }
      validation.errors = get_errors('', '', '');
      return validation;
    }

    // Income
    if ( req.path == '/income') {
      if ( req.body.what_makes_you_think === '' ) {
        validation.status = false;
        validation.what_makes_you_think = 'error';
        required.push('What makes you think this person has undeclared savings or income?');
      }
      validation.errors = get_errors('', '', '');
      return validation;
    }

    // Income More
    if ( req.path == '/income-more') {
      var counter = 0;

      for ( var element in req.body ) {
        if ( req.body[element] === '' ) {
          counter++;
        }
      }

      if ( Object.keys(req.body).length === counter ) {
        validation.status = false;
        validation.errors = get_errors('', 'You must select at least one option');
      } else {
        validation.errors = get_errors('', '', '');
      }

      return validation;
    }

    // Other
    if ( req.path == '/other') {
      if ( req.body.other === '' ) {
        validation.status = false;
        validation.other = 'error';
        required.push('other');
      }
      validation.errors = get_errors('', '', '');
      return validation;
    }
  }
};

module.exports = validations;

function get_errors(message, desc, linkref) {
  var errors = {};

  if ( message === undefined || message === '' ) {
    errors.message = "There was a problem";
  } else {
    errors.message = message;
  }

  if ( desc === undefined || desc === '' ) {
    errors.desc = 'Please check you have filled out all the relevant fields';
  } else {
    if ( desc.constructor === Array ) {
      errors.array = true;
    }
    errors.desc = desc;
  }

  if ( linkref === undefined ) {
    errors.linkref = "";
  } else {
    errors.linkref = linkref;
  }

  return errors;
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.13"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>SAC Effects: AudioInfo Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="navtree.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

SAC Effects
    v1.0

Public Member Functions |
List of all members

AudioInfo Class Reference

Audio object info dialog class.
 More...

#include <AudioInfo.h>

Inheritance diagram for AudioInfo:

<map name="_audio_info_inherit__map" id="_audio_info_inherit__map">
</map>
[legend]

Collaboration diagram for AudioInfo:

<map name="_audio_info_coll__map" id="_audio_info_coll__map">
</map>
[legend]

Public Member Functions

 	AudioInfo (QWidget *parent=0)

 	AudioInfo constructor.  More...

 	~AudioInfo ()

 	AudioInfo destructor.

void 	setFile (WAVFile *file)

 	It sets a audio file.  More...

Detailed Description

Author

Andrés González Fornell

Definition at line 23 of file AudioInfo.h.

Constructor & Destructor Documentation

◆ AudioInfo()

          AudioInfo::AudioInfo
          (
          QWidget *
          parent = 0	)

Parameters

parent	user interface parent object

Definition at line 8 of file AudioInfo.cpp.

Here is the call graph for this function:

<map name="class_audio_info_ad24c69ecc331c48790cdf2886c721132_cgraph" id="class_audio_info_ad24c69ecc331c48790cdf2886c721132_cgraph">
<area shape="rect" id="node2" href="_logger_8cpp.html#ad3268f5fc285cfb356a498e2d24b27f4" title="Log a message on console. " alt="" coords="196,5,281,32"/>
<area shape="rect" id="node3" href="_logger_8cpp.html#a551ee9103bbb16b6eea45a3f536617bd" title="It returns the string tab code to align log messages. " alt="" coords="329,5,369,32"/>
</map>

Member Function Documentation

◆ setFile()

          void AudioInfo::setFile
          (
          WAVFile *
          file	)

Parameters

file	audio file object

Definition at line 26 of file AudioInfo.cpp.

Here is the caller graph for this function:

<map name="class_audio_info_a2d05a12b4191202227e17afc5e57f349_icgraph" id="class_audio_info_a2d05a12b4191202227e17afc5e57f349_icgraph">
<area shape="rect" id="node2" href="class_s_a_c_effects.html#a9af83c6a63fcdf10e4bd849fa3c5973c" title="It sets SAC parameter HRTF model. " alt="" coords="179,31,365,57"/>
<area shape="rect" id="node3" href="class_s_a_c_effects.html#a4500b30a621d5eff4a108f1f8d0d59a3" title="It resets all decoding parameters, including input file. " alt="" coords="413,5,540,32"/>
<area shape="rect" id="node4" href="class_s_a_c_effects.html#aad64fe6a36a53d1ffeae59bccbd8af33" title="SACEffects constructor. " alt="" coords="793,31,959,57"/>
<area shape="rect" id="node5" href="class_s_a_c_effects.html#aaa9092eb132a8fe2b0560b3a600747b5" title="It sets the source audio file. " alt="" coords="588,56,745,83"/>
</map>

The documentation for this class was generated from the following files:

src/interface/AudioInfo.h

src/interface/AudioInfo.cpp

AudioInfo

Generated by

     1.8.13


text:
from apiwrapper.endpoints.endpoint import Endpoint
from apiwrapper.endpoints.user import User

class AnnualOverview(Endpoint):

    __endpoint_annual_overview = "export-annual-overview"
    __endpoint_annual_overview_content = "content"

    @classmethod
    def _get_base_endpoint(cls, user_id, overview_id=None):
        endpoint = User._get_base_endpoint(user_id)
        endpoint += "/%s" % cls.__endpoint_annual_overview
        if overview_id is not None:
            endpoint += "/%d" % overview_id
        return endpoint

    def get_all_annual_overviews_for_user(self, user_id):
        endpoint = self._get_base_endpoint(user_id)

        return self._make_get_request(endpoint)

    def get_annual_overview_by_id(self, user_id, overview_id):
        endpoint = self._get_base_endpoint(user_id, overview_id)

        return self._make_get_request(endpoint)

    def get_content_of_annual_overview(self, user_id, overview_id):
        endpoint = self._get_base_endpoint(user_id, overview_id)
        endpoint += "/%s" % self.__endpoint_annual_overview_content

        return self._make_get_request(endpoint)


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

using Microsoft.Azure.Insights.Models;

namespace Microsoft.Azure.Commands.Insights.OutputClasses
{
    /// <summary>
    /// Wraps around MetricDefinition to provide detailed data about it
    /// </summary>
    public class PSMetricDefinition : MetricDefinition
    {
        /// <summary>
        /// Gets or sets the Dimensions of the metric
        /// </summary>
        public new PSDimensionCollection Dimensions { get; set; }

        /// <summary>
        /// Gets or sets the MetricAvailabilties of the metric
        /// </summary>
        public new PSAvailabilityCollection MetricAvailabilities { get; set; }

        /// <summary>
        /// Gets or sets the Name of the metric
        /// </summary>
        public new string Name { get; set; }

        /// <summary>
        /// Gets or sets the Proterties of the metric
        /// </summary>
        public new PSDictionaryElement Properties { get; set; }

        /// <summary>
        /// Initializes an new instance of the PSMetricDefinition class
        /// </summary>
        /// <param name="metricDefinition">The MetricDefinition</param>
        public PSMetricDefinition(MetricDefinition metricDefinition)
        {
            // Keep the original value (localized string, Dictionary, List) in the base
            base.Dimensions = metricDefinition.Dimensions;
            base.MetricAvailabilities = metricDefinition.MetricAvailabilities;
            base.Name = metricDefinition.Name;
            base.Properties = metricDefinition.Properties;

            this.Dimensions = new PSDimensionCollection(metricDefinition.Dimensions);
            this.MetricAvailabilities = new PSAvailabilityCollection(metricDefinition.MetricAvailabilities);
            this.Name = metricDefinition.Name.ToString(localizedValue: false);
            this.PrimaryAggregationType = metricDefinition.PrimaryAggregationType;
            this.Properties = new PSDictionaryElement(metricDefinition.Properties);
            this.ResourceId = metricDefinition.ResourceId;
            this.Unit = metricDefinition.Unit;
        }
    }
}


text:
var through = require('through2');
var streamEqual = require('stream-equal');
var fs = require('fs');
var clangFormat = require('clang-format');

module.exports = {
  /**
   * Verifies that files are already in the format produced by clang-format.
   * Prints a warning to the console for any file which isn't formatted.
   * @param {string|Object} options the string "file" to search for a
   * '.clang-format' file, or an object literal containing clang-format options
   * http://clang.llvm.org/docs/ClangFormatStyleOptions.html#configurable-format-style-options
   */
  checkFormat: function(options) {
    options = (typeof options === "undefined") ?
                  {
                    BasedOnStyle: "Google"
                  } :
                  options;
    var optsStr =
        (typeof options === "string") ? options : JSON.stringify(options);
    return through.obj(function(file, enc, done) {
      var actual = file.isStream() ?
                       file.content :
                       fs.createReadStream(file.path, {encoding: enc});

      streamEqual(actual,
                  clangFormat(file, enc, optsStr, done), function(err, equal) {
                    if (err) {
                      return done(err);
                    }
                    if (!equal) {
                      console.log("WARNING: " + file.path +
                                  " is not properly formatted.");
                      console.log("Please run clang-format -i -style='" +
                                  optsStr + "' " + file.path);
                    }
                    done();
                  });
    });
  }
};


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

import com.facebook.presto.common.Page;
import com.facebook.presto.common.Subfield;
import com.facebook.presto.common.function.SqlFunctionProperties;
import com.facebook.presto.common.predicate.TupleDomain;
import com.facebook.presto.common.relation.Predicate;
import com.facebook.presto.common.type.Type;
import com.facebook.presto.common.type.TypeManager;
import com.facebook.presto.expressions.DefaultRowExpressionTraversalVisitor;
import com.facebook.presto.hive.BucketAdaptation;
import com.facebook.presto.hive.EncryptionInformation;
import com.facebook.presto.hive.FileFormatDataSourceStats;
import com.facebook.presto.hive.HdfsEnvironment;
import com.facebook.presto.hive.HiveClientConfig;
import com.facebook.presto.hive.HiveCoercer;
import com.facebook.presto.hive.HiveColumnHandle;
import com.facebook.presto.hive.HiveFileContext;
import com.facebook.presto.hive.HiveOrcAggregatedMemoryContext;
import com.facebook.presto.hive.HiveSelectivePageSourceFactory;
import com.facebook.presto.hive.HiveType;
import com.facebook.presto.hive.SubfieldExtractor;
import com.facebook.presto.hive.metastore.Storage;
import com.facebook.presto.orc.DwrfEncryptionProvider;
import com.facebook.presto.orc.FilterFunction;
import com.facebook.presto.orc.OrcAggregatedMemoryContext;
import com.facebook.presto.orc.OrcDataSource;
import com.facebook.presto.orc.OrcDataSourceId;
import com.facebook.presto.orc.OrcEncoding;
import com.facebook.presto.orc.OrcPredicate;
import com.facebook.presto.orc.OrcReader;
import com.facebook.presto.orc.OrcReaderOptions;
import com.facebook.presto.orc.OrcSelectiveRecordReader;
import com.facebook.presto.orc.StripeMetadataSource;
import com.facebook.presto.orc.TupleDomainFilter;
import com.facebook.presto.orc.TupleDomainOrcPredicate;
import com.facebook.presto.orc.cache.OrcFileTailSource;
import com.facebook.presto.spi.ConnectorPageSource;
import com.facebook.presto.spi.ConnectorSession;
import com.facebook.presto.spi.FixedPageSource;
import com.facebook.presto.spi.PrestoException;
import com.facebook.presto.spi.function.StandardFunctionResolution;
import com.facebook.presto.spi.relation.CallExpression;
import com.facebook.presto.spi.relation.DeterminismEvaluator;
import com.facebook.presto.spi.relation.InputReferenceExpression;
import com.facebook.presto.spi.relation.PredicateCompiler;
import com.facebook.presto.spi.relation.RowExpression;
import com.facebook.presto.spi.relation.RowExpressionService;
import com.facebook.presto.spi.relation.SpecialFormExpression;
import com.facebook.presto.spi.relation.VariableReferenceExpression;
import com.google.common.collect.BiMap;
import com.google.common.collect.ImmutableBiMap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Maps;
import com.google.common.util.concurrent.UncheckedExecutionException;
import io.airlift.slice.Slice;
import io.airlift.units.DataSize;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hive.ql.io.orc.OrcSerde;
import org.apache.hadoop.hive.serde2.typeinfo.TypeInfo;
import org.joda.time.DateTimeZone;

import javax.inject.Inject;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.IntStream;

import static com.facebook.presto.expressions.LogicalRowExpressions.TRUE_CONSTANT;
import static com.facebook.presto.expressions.LogicalRowExpressions.binaryExpression;
import static com.facebook.presto.expressions.LogicalRowExpressions.extractConjuncts;
import static com.facebook.presto.expressions.RowExpressionNodeInliner.replaceExpression;
import static com.facebook.presto.hive.HiveBucketing.getHiveBucket;
import static com.facebook.presto.hive.HiveColumnHandle.ColumnType.REGULAR;
import static com.facebook.presto.hive.HiveErrorCode.HIVE_CANNOT_OPEN_SPLIT;
import static com.facebook.presto.hive.HiveErrorCode.HIVE_INVALID_BUCKET_FILES;
import static com.facebook.presto.hive.HiveErrorCode.HIVE_MISSING_DATA;
import static com.facebook.presto.hive.HiveSessionProperties.getOrcLazyReadSmallRanges;
import static com.facebook.presto.hive.HiveSessionProperties.getOrcMaxBufferSize;
import static com.facebook.presto.hive.HiveSessionProperties.getOrcMaxMergeDistance;
import static com.facebook.presto.hive.HiveSessionProperties.getOrcMaxReadBlockSize;
import static com.facebook.presto.hive.HiveSessionProperties.getOrcStreamBufferSize;
import static com.facebook.presto.hive.HiveSessionProperties.getOrcTinyStripeThreshold;
import static com.facebook.presto.hive.HiveSessionProperties.isAdaptiveFilterReorderingEnabled;
import static com.facebook.presto.hive.HiveSessionProperties.isOrcBloomFiltersEnabled;
import static com.facebook.presto.hive.HiveSessionProperties.isOrcZstdJniDecompressionEnabled;
import static com.facebook.presto.hive.HiveUtil.getPhysicalHiveColumnHandles;
import static com.facebook.presto.hive.HiveUtil.typedPartitionKey;
import static com.facebook.presto.orc.DwrfEncryptionProvider.NO_ENCRYPTION;
import static com.facebook.presto.orc.OrcEncoding.ORC;
import static com.facebook.presto.orc.OrcReader.INITIAL_BATCH_SIZE;
import static com.facebook.presto.spi.relation.SpecialFormExpression.Form.AND;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Strings.nullToEmpty;
import static com.google.common.base.Verify.verify;
import static com.google.common.collect.ImmutableBiMap.toImmutableBiMap;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.collect.ImmutableMap.toImmutableMap;
import static com.google.common.collect.Maps.uniqueIndex;
import static java.lang.String.format;
import static java.util.Objects.requireNonNull;

public class OrcSelectivePageSourceFactory
        implements HiveSelectivePageSourceFactory
{
    private final TypeManager typeManager;
    private final StandardFunctionResolution functionResolution;
    private final RowExpressionService rowExpressionService;
    private final boolean useOrcColumnNames;
    private final HdfsEnvironment hdfsEnvironment;
    private final FileFormatDataSourceStats stats;
    private final int domainCompactionThreshold;
    private final OrcFileTailSource orcFileTailSource;
    private final StripeMetadataSource stripeMetadataSource;
    private final TupleDomainFilterCache tupleDomainFilterCache;

    @Inject
    public OrcSelectivePageSourceFactory(
            TypeManager typeManager,
            StandardFunctionResolution functionResolution,
            RowExpressionService rowExpressionService,
            HiveClientConfig config,
            HdfsEnvironment hdfsEnvironment,
            FileFormatDataSourceStats stats,
            OrcFileTailSource orcFileTailSource,
            StripeMetadataSource stripeMetadataSource,
            TupleDomainFilterCache tupleDomainFilterCache)
    {
        this(
                typeManager,
                functionResolution,
                rowExpressionService,
                requireNonNull(config, "hiveClientConfig is null").isUseOrcColumnNames(),
                hdfsEnvironment,
                stats,
                config.getDomainCompactionThreshold(),
                orcFileTailSource,
                stripeMetadataSource,
                tupleDomainFilterCache);
    }

    public OrcSelectivePageSourceFactory(
            TypeManager typeManager,
            StandardFunctionResolution functionResolution,
            RowExpressionService rowExpressionService,
            boolean useOrcColumnNames,
            HdfsEnvironment hdfsEnvironment,
            FileFormatDataSourceStats stats,
            int domainCompactionThreshold,
            OrcFileTailSource orcFileTailSource,
            StripeMetadataSource stripeMetadataSource,
            TupleDomainFilterCache tupleDomainFilterCache)
    {
        this.typeManager = requireNonNull(typeManager, "typeManager is null");
        this.functionResolution = requireNonNull(functionResolution, "functionResolution is null");
        this.rowExpressionService = requireNonNull(rowExpressionService, "rowExpressionService is null");
        this.useOrcColumnNames = useOrcColumnNames;
        this.hdfsEnvironment = requireNonNull(hdfsEnvironment, "hdfsEnvironment is null");
        this.stats = requireNonNull(stats, "stats is null");
        this.domainCompactionThreshold = domainCompactionThreshold;
        this.orcFileTailSource = requireNonNull(orcFileTailSource, "orcFileTailCache is null");
        this.stripeMetadataSource = requireNonNull(stripeMetadataSource, "stripeMetadataSource is null");
        this.tupleDomainFilterCache = requireNonNull(tupleDomainFilterCache, "tupleDomainFilterCache is null");
    }

    @Override
    public Optional<? extends ConnectorPageSource> createPageSource(
            Configuration configuration,
            ConnectorSession session,
            Path path,
            long start,
            long length,
            long fileSize,
            Storage storage,
            List<HiveColumnHandle> columns,
            Map<Integer, String> prefilledValues,
            Map<Integer, HiveCoercer> coercers,
            Optional<BucketAdaptation> bucketAdaptation,
            List<Integer> outputColumns,
            TupleDomain<Subfield> domainPredicate,
            RowExpression remainingPredicate,
            DateTimeZone hiveStorageTimeZone,
            HiveFileContext hiveFileContext,
            Optional<EncryptionInformation> encryptionInformation)
    {
        if (!OrcSerde.class.getName().equals(storage.getStorageFormat().getSerDe())) {
            return Optional.empty();
        }

        // per HIVE-13040 and ORC-162, empty files are allowed
        if (fileSize == 0) {
            return Optional.of(new FixedPageSource(ImmutableList.of()));
        }

        return Optional.of(createOrcPageSource(
                session,
                ORC,
                hdfsEnvironment,
                configuration,
                path,
                start,
                length,
                fileSize,
                columns,
                prefilledValues,
                coercers,
                bucketAdaptation,
                outputColumns,
                domainPredicate,
                remainingPredicate,
                useOrcColumnNames,
                hiveStorageTimeZone,
                typeManager,
                functionResolution,
                rowExpressionService,
                isOrcBloomFiltersEnabled(session),
                stats,
                domainCompactionThreshold,
                orcFileTailSource,
                stripeMetadataSource,
                hiveFileContext,
                tupleDomainFilterCache,
                encryptionInformation,
                NO_ENCRYPTION));
    }

    public static OrcSelectivePageSource createOrcPageSource(
            ConnectorSession session,
            OrcEncoding orcEncoding,
            HdfsEnvironment hdfsEnvironment,
            Configuration configuration,
            Path path,
            long start,
            long length,
            long fileSize,
            List<HiveColumnHandle> columns,
            Map<Integer, String> prefilledValues,
            Map<Integer, HiveCoercer> coercers,
            Optional<BucketAdaptation> bucketAdaptation,
            List<Integer> outputColumns,
            TupleDomain<Subfield> domainPredicate,
            RowExpression remainingPredicate,
            boolean useOrcColumnNames,
            DateTimeZone hiveStorageTimeZone,
            TypeManager typeManager,
            StandardFunctionResolution functionResolution,
            RowExpressionService rowExpressionService,
            boolean orcBloomFiltersEnabled,
            FileFormatDataSourceStats stats,
            int domainCompactionThreshold,
            OrcFileTailSource orcFileTailSource,
            StripeMetadataSource stripeMetadataSource,
            HiveFileContext hiveFileContext,
            TupleDomainFilterCache tupleDomainFilterCache,
            Optional<EncryptionInformation> encryptionInformation,
            DwrfEncryptionProvider dwrfEncryptionProvider)
    {
        checkArgument(domainCompactionThreshold >= 1, "domainCompactionThreshold must be at least 1");

        DataSize maxMergeDistance = getOrcMaxMergeDistance(session);
        DataSize maxBufferSize = getOrcMaxBufferSize(session);
        DataSize streamBufferSize = getOrcStreamBufferSize(session);
        DataSize tinyStripeThreshold = getOrcTinyStripeThreshold(session);
        DataSize maxReadBlockSize = getOrcMaxReadBlockSize(session);
        OrcReaderOptions orcReaderOptions = new OrcReaderOptions(maxMergeDistance, tinyStripeThreshold, maxReadBlockSize, isOrcZstdJniDecompressionEnabled(session));
        boolean lazyReadSmallRanges = getOrcLazyReadSmallRanges(session);

        OrcDataSource orcDataSource;
        try {
            FSDataInputStream inputStream = hdfsEnvironment.getFileSystem(session.getUser(), path, configuration).openFile(path, hiveFileContext);
            orcDataSource = new HdfsOrcDataSource(
                    new OrcDataSourceId(path.toString()),
                    fileSize,
                    maxMergeDistance,
                    maxBufferSize,
                    streamBufferSize,
                    lazyReadSmallRanges,
                    inputStream,
                    stats);
        }
        catch (Exception e) {
            if (nullToEmpty(e.getMessage()).trim().equals("Filesystem closed") ||
                    e instanceof FileNotFoundException) {
                throw new PrestoException(HIVE_CANNOT_OPEN_SPLIT, e);
            }
            throw new PrestoException(HIVE_CANNOT_OPEN_SPLIT, splitError(e, path, start, length), e);
        }

        OrcAggregatedMemoryContext systemMemoryUsage = new HiveOrcAggregatedMemoryContext();
        try {
            OrcReader reader = new OrcReader(
                    orcDataSource,
                    orcEncoding,
                    orcFileTailSource,
                    stripeMetadataSource,
                    systemMemoryUsage,
                    orcReaderOptions,
                    hiveFileContext.isCacheable(),
                    dwrfEncryptionProvider);

            checkArgument(!domainPredicate.isNone(), "Unexpected NONE domain");

            List<HiveColumnHandle> physicalColumns = getPhysicalHiveColumnHandles(columns, useOrcColumnNames, reader, path);
            Map<Integer, Integer> indexMapping = IntStream.range(0, columns.size())
                    .boxed()
                    .collect(toImmutableMap(i -> columns.get(i).getHiveColumnIndex(), i -> physicalColumns.get(i).getHiveColumnIndex()));

            Map<Integer, String> columnNames = physicalColumns.stream()
                    .collect(toImmutableMap(HiveColumnHandle::getHiveColumnIndex, HiveColumnHandle::getName));

            Map<Integer, HiveCoercer> mappedCoercers = coercers.entrySet().stream().collect(toImmutableMap(entry -> indexMapping.get(entry.getKey()), Map.Entry::getValue));

            OrcPredicate orcPredicate = toOrcPredicate(domainPredicate, physicalColumns, mappedCoercers, typeManager, domainCompactionThreshold, orcBloomFiltersEnabled);

            Map<String, Integer> columnIndices = ImmutableBiMap.copyOf(columnNames).inverse();
            Map<Integer, Map<Subfield, TupleDomainFilter>> tupleDomainFilters = toTupleDomainFilters(domainPredicate, columnIndices, mappedCoercers, tupleDomainFilterCache);

            List<Integer> outputIndices = outputColumns.stream().map(indexMapping::get).collect(toImmutableList());
            Map<Integer, List<Subfield>> requiredSubfields = collectRequiredSubfields(physicalColumns, outputIndices, tupleDomainFilters, remainingPredicate, columnIndices, functionResolution, rowExpressionService, session);

            Map<Integer, Type> columnTypes = physicalColumns.stream()
                    .collect(toImmutableMap(HiveColumnHandle::getHiveColumnIndex, column -> typeManager.getType(column.getTypeSignature())));

            Map<Integer, Object> typedPrefilledValues = Maps.transformEntries(
                    prefilledValues.entrySet().stream()
                            .collect(toImmutableMap(entry -> indexMapping.get(entry.getKey()), Map.Entry::getValue)),
                    (hiveColumnIndex, value) -> typedPartitionKey(value, columnTypes.get(hiveColumnIndex), columnNames.get(hiveColumnIndex), hiveStorageTimeZone));

            BiMap<Integer, Integer> inputs = IntStream.range(0, physicalColumns.size())
                    .boxed()
                    .collect(toImmutableBiMap(i -> physicalColumns.get(i).getHiveColumnIndex(), Function.identity()));

            // use column types from the current table schema; these types might be different from this partition's schema
            Map<VariableReferenceExpression, InputReferenceExpression> variableToInput = columnNames.keySet().stream()
                    .collect(toImmutableMap(
                            hiveColumnIndex -> new VariableReferenceExpression(columnNames.get(hiveColumnIndex), getColumnTypeFromTableSchema(coercers, columnTypes, hiveColumnIndex)),
                            hiveColumnIndex -> new InputReferenceExpression(inputs.get(hiveColumnIndex), getColumnTypeFromTableSchema(coercers, columnTypes, hiveColumnIndex))));

            Optional<BucketAdapter> bucketAdapter = bucketAdaptation.map(adaptation -> new BucketAdapter(
                    Arrays.stream(adaptation.getBucketColumnIndices())
                            .map(indexMapping::get)
                            .map(inputs::get)
                            .toArray(),
                    adaptation.getBucketColumnHiveTypes(),
                    adaptation.getTableBucketCount(),
                    adaptation.getPartitionBucketCount(),
                    adaptation.getBucketToKeep()));

            List<FilterFunction> filterFunctions = toFilterFunctions(replaceExpression(remainingPredicate, variableToInput), bucketAdapter, session, rowExpressionService.getDeterminismEvaluator(), rowExpressionService.getPredicateCompiler());

            Map<Integer, Slice> keyMap = ImmutableMap.of();
            if (encryptionInformation.isPresent() && encryptionInformation.get().getDwrfEncryptionMetadata().isPresent()) {
                keyMap = encryptionInformation.get().getDwrfEncryptionMetadata().get().toKeyMap(reader.getTypes(), physicalColumns);
            }

            OrcSelectiveRecordReader recordReader = reader.createSelectiveRecordReader(
                    columnTypes,
                    outputIndices,
                    tupleDomainFilters,
                    filterFunctions,
                    inputs.inverse(),
                    requiredSubfields,
                    typedPrefilledValues,
                    Maps.transformValues(mappedCoercers, Function.class::cast),
                    orcPredicate,
                    start,
                    length,
                    hiveStorageTimeZone,
                    session.getSqlFunctionProperties().isLegacyMapSubscript(),
                    systemMemoryUsage,
                    Optional.empty(),
                    INITIAL_BATCH_SIZE,
                    keyMap);

            return new OrcSelectivePageSource(
                    recordReader,
                    orcDataSource,
                    systemMemoryUsage.newOrcAggregatedMemoryContext(),
                    stats);
        }
        catch (Exception e) {
            try {
                orcDataSource.close();
            }
            catch (IOException ignored) {
            }
            // instanceof and class comparison do not work here since they are loaded by different class loaders.
            if (e.getClass().getName().equals(UncheckedExecutionException.class.getName()) && e.getCause() instanceof PrestoException) {
                throw (PrestoException) e.getCause();
            }
            if (e instanceof PrestoException) {
                throw (PrestoException) e;
            }
            String message = splitError(e, path, start, length);
            if (e.getClass().getSimpleName().equals("BlockMissingException")) {
                throw new PrestoException(HIVE_MISSING_DATA, message, e);
            }
            throw new PrestoException(HIVE_CANNOT_OPEN_SPLIT, message, e);
        }
    }

    private static Type getColumnTypeFromTableSchema(Map<Integer, HiveCoercer> coercers, Map<Integer, Type> columnTypes, int hiveColumnIndex)
    {
        return coercers.containsKey(hiveColumnIndex) ? coercers.get(hiveColumnIndex).getToType() : columnTypes.get(hiveColumnIndex);
    }

    private static Map<Integer, List<Subfield>> collectRequiredSubfields(List<HiveColumnHandle> physicalColumns, List<Integer> outputColumns, Map<Integer, Map<Subfield, TupleDomainFilter>> tupleDomainFilters, RowExpression remainingPredicate, Map<String, Integer> columnIndices, StandardFunctionResolution functionResolution, RowExpressionService rowExpressionService, ConnectorSession session)
    {
        /**
         * The logic is:
         *
         * - columns projected fully are not modified;
         * - columns projected partially are updated to include subfields used in the filters or
         *      to be read in full if entire column is used in a filter
         * - columns used for filtering only are updated to prune subfields if filters don't use full column
         */

        Map<Integer, Set<Subfield>> outputSubfields = new HashMap<>();
        physicalColumns.stream()
                .filter(column -> outputColumns.contains(column.getHiveColumnIndex()))
                .forEach(column -> outputSubfields.put(column.getHiveColumnIndex(), new HashSet<>(column.getRequiredSubfields())));

        Map<Integer, Set<Subfield>> predicateSubfields = new HashMap<>();
        SubfieldExtractor subfieldExtractor = new SubfieldExtractor(functionResolution, rowExpressionService.getExpressionOptimizer(), session);
        remainingPredicate.accept(
                new RequiredSubfieldsExtractor(subfieldExtractor),
                subfield -> predicateSubfields.computeIfAbsent(columnIndices.get(subfield.getRootName()), v -> new HashSet<>()).add(subfield));

        for (Map.Entry<Integer, Map<Subfield, TupleDomainFilter>> entry : tupleDomainFilters.entrySet()) {
            predicateSubfields.computeIfAbsent(entry.getKey(), v -> new HashSet<>()).addAll(entry.getValue().keySet());
        }

        Map<Integer, List<Subfield>> allSubfields = new HashMap<>();
        for (Map.Entry<Integer, Set<Subfield>> entry : outputSubfields.entrySet()) {
            int columnIndex = entry.getKey();
            if (entry.getValue().isEmpty()) {
                // entire column is projected out
                continue;
            }

            if (!predicateSubfields.containsKey(columnIndex)) {
                // column is not used in filters
                allSubfields.put(columnIndex, ImmutableList.copyOf(entry.getValue()));
                continue;
            }

            List<Subfield> prunedSubfields = pruneSubfields(ImmutableSet.<Subfield>builder()
                    .addAll(entry.getValue())
                    .addAll(predicateSubfields.get(columnIndex)).build());

            if (prunedSubfields.size() == 1 && isEntireColumn(prunedSubfields.get(0))) {
                // entire column is used in a filter
                continue;
            }

            allSubfields.put(columnIndex, prunedSubfields);
        }

        for (Map.Entry<Integer, Set<Subfield>> entry : predicateSubfields.entrySet()) {
            int columnIndex = entry.getKey();
            if (outputSubfields.containsKey(columnIndex)) {
                // this column has been already processed (in the previous loop)
                continue;
            }

            List<Subfield> prunedSubfields = pruneSubfields(entry.getValue());
            if (prunedSubfields.size() == 1 && isEntireColumn(prunedSubfields.get(0))) {
                // entire column is used in a filter
                continue;
            }

            allSubfields.put(columnIndex, prunedSubfields);
        }

        return allSubfields;
    }

    // Prunes subfields: if one subfield is a prefix of another subfield, keeps the shortest one.
    // Example: {a.b.c, a.b} -> {a.b}
    private static List<Subfield> pruneSubfields(Set<Subfield> subfields)
    {
        verify(!subfields.isEmpty());

        return subfields.stream()
                .filter(subfield -> !prefixExists(subfield, subfields))
                .collect(toImmutableList());
    }

    private static boolean prefixExists(Subfield subfield, Collection<Subfield> subfields)
    {
        return subfields.stream().anyMatch(path -> path.isPrefix(subfield));
    }

    private static final class RequiredSubfieldsExtractor
            extends DefaultRowExpressionTraversalVisitor<Consumer<Subfield>>
    {
        private final SubfieldExtractor subfieldExtractor;

        public RequiredSubfieldsExtractor(SubfieldExtractor subfieldExtractor)
        {
            this.subfieldExtractor = requireNonNull(subfieldExtractor, "subfieldExtractor is null");
        }

        @Override
        public Void visitCall(CallExpression call, Consumer<Subfield> context)
        {
            Optional<Subfield> subfield = subfieldExtractor.extract(call);
            if (subfield.isPresent()) {
                context.accept(subfield.get());
                return null;
            }

            call.getArguments().forEach(argument -> argument.accept(this, context));
            return null;
        }

        @Override
        public Void visitSpecialForm(SpecialFormExpression specialForm, Consumer<Subfield> context)
        {
            Optional<Subfield> subfield = subfieldExtractor.extract(specialForm);
            if (subfield.isPresent()) {
                context.accept(subfield.get());
                return null;
            }

            specialForm.getArguments().forEach(argument -> argument.accept(this, context));
            return null;
        }

        @Override
        public Void visitVariableReference(VariableReferenceExpression reference, Consumer<Subfield> context)
        {
            Optional<Subfield> subfield = subfieldExtractor.extract(reference);
            if (subfield.isPresent()) {
                context.accept(subfield.get());
                return null;
            }

            return null;
        }
    }

    private static Map<Integer, Map<Subfield, TupleDomainFilter>> toTupleDomainFilters(TupleDomain<Subfield> domainPredicate, Map<String, Integer> columnIndices, Map<Integer, HiveCoercer> coercers, TupleDomainFilterCache tupleDomainFilterCache)
    {
        Map<Subfield, TupleDomainFilter> filtersBySubfield = Maps.transformValues(domainPredicate.getDomains().get(), tupleDomainFilterCache::getFilter);

        Map<Integer, Map<Subfield, TupleDomainFilter>> filtersByColumn = new HashMap<>();
        for (Map.Entry<Subfield, TupleDomainFilter> entry : filtersBySubfield.entrySet()) {
            Subfield subfield = entry.getKey();
            int columnIndex = columnIndices.get(subfield.getRootName());
            TupleDomainFilter filter = entry.getValue();
            if (coercers.containsKey(columnIndex)) {
                filter = coercers.get(columnIndex).toCoercingFilter(filter, subfield);
            }
            filtersByColumn.computeIfAbsent(columnIndex, k -> new HashMap<>()).put(subfield, filter);
        }

        return ImmutableMap.copyOf(filtersByColumn);
    }

    private static boolean isEntireColumn(Subfield subfield)
    {
        return subfield.getPath().isEmpty();
    }

    private static OrcPredicate toOrcPredicate(TupleDomain<Subfield> domainPredicate, List<HiveColumnHandle> physicalColumns, Map<Integer, HiveCoercer> coercers, TypeManager typeManager, int domainCompactionThreshold, boolean orcBloomFiltersEnabled)
    {
        ImmutableList.Builder<TupleDomainOrcPredicate.ColumnReference<HiveColumnHandle>> columnReferences = ImmutableList.builder();
        for (HiveColumnHandle column : physicalColumns) {
            if (column.getColumnType() == REGULAR) {
                Type type = typeManager.getType(column.getTypeSignature());
                columnReferences.add(new TupleDomainOrcPredicate.ColumnReference<>(column, column.getHiveColumnIndex(), type));
            }
        }

        Map<String, HiveColumnHandle> columnsByName = uniqueIndex(physicalColumns, HiveColumnHandle::getName);
        TupleDomain<HiveColumnHandle> entireColumnDomains = domainPredicate
                .transform(subfield -> isEntireColumn(subfield) ? columnsByName.get(subfield.getRootName()) : null)
                // filter out columns with coercions to avoid type mismatch errors between column stats in the file and values domain
                .transform(column -> coercers.containsKey(column.getHiveColumnIndex()) ? null : column);
        return new TupleDomainOrcPredicate<>(entireColumnDomains, columnReferences.build(), orcBloomFiltersEnabled, Optional.of(domainCompactionThreshold));
    }

    /**
     * Split filter expression into groups of conjuncts that depend on the same set of inputs,
     * then compile each group into FilterFunction.
     */
    private static List<FilterFunction> toFilterFunctions(RowExpression filter, Optional<BucketAdapter> bucketAdapter, ConnectorSession session, DeterminismEvaluator determinismEvaluator, PredicateCompiler predicateCompiler)
    {
        ImmutableList.Builder<FilterFunction> filterFunctions = ImmutableList.builder();

        bucketAdapter.map(predicate -> new FilterFunction(session.getSqlFunctionProperties(), true, predicate))
                .ifPresent(filterFunctions::add);

        if (TRUE_CONSTANT.equals(filter)) {
            return filterFunctions.build();
        }

        if (!isAdaptiveFilterReorderingEnabled(session)) {
            filterFunctions.add(new FilterFunction(session.getSqlFunctionProperties(), determinismEvaluator.isDeterministic(filter), predicateCompiler.compilePredicate(session.getSqlFunctionProperties(), filter).get()));
            return filterFunctions.build();
        }

        List<RowExpression> conjuncts = extractConjuncts(filter);
        if (conjuncts.size() == 1) {
            filterFunctions.add(new FilterFunction(session.getSqlFunctionProperties(), determinismEvaluator.isDeterministic(filter), predicateCompiler.compilePredicate(session.getSqlFunctionProperties(), filter).get()));
            return filterFunctions.build();
        }

        // Use LinkedHashMap to preserve user-specified order of conjuncts. This will be the initial order in which filters are applied.
        Map<Set<Integer>, List<RowExpression>> inputsToConjuncts = new LinkedHashMap<>();
        for (RowExpression conjunct : conjuncts) {
            inputsToConjuncts.computeIfAbsent(extractInputs(conjunct), k -> new ArrayList<>()).add(conjunct);
        }

        inputsToConjuncts.values().stream()
                .map(expressions -> binaryExpression(AND, expressions))
                .map(predicate -> new FilterFunction(session.getSqlFunctionProperties(), determinismEvaluator.isDeterministic(predicate), predicateCompiler.compilePredicate(session.getSqlFunctionProperties(), predicate).get()))
                .forEach(filterFunctions::add);

        return filterFunctions.build();
    }

    private static Set<Integer> extractInputs(RowExpression expression)
    {
        ImmutableSet.Builder<Integer> inputs = ImmutableSet.builder();
        expression.accept(new InputReferenceBuilderVisitor(), inputs);
        return inputs.build();
    }

    private static class InputReferenceBuilderVisitor
            extends DefaultRowExpressionTraversalVisitor<ImmutableSet.Builder<Integer>>
    {
        @Override
        public Void visitInputReference(InputReferenceExpression input, ImmutableSet.Builder<Integer> builder)
        {
            builder.add(input.getField());
            return null;
        }
    }

    private static String splitError(Throwable t, Path path, long start, long length)
    {
        return format("Error opening Hive split %s (offset=%s, length=%s): %s", path, start, length, t.getMessage());
    }

    private static class BucketAdapter
            implements Predicate
    {
        public final int[] bucketColumns;
        public final int bucketToKeep;
        public final int tableBucketCount;
        public final int partitionBucketCount; // for sanity check only
        private final List<TypeInfo> typeInfoList;

        public BucketAdapter(int[] bucketColumnIndices, List<HiveType> bucketColumnHiveTypes, int tableBucketCount, int partitionBucketCount, int bucketToKeep)
        {
            this.bucketColumns = requireNonNull(bucketColumnIndices, "bucketColumnIndices is null");
            this.bucketToKeep = bucketToKeep;
            this.typeInfoList = requireNonNull(bucketColumnHiveTypes, "bucketColumnHiveTypes is null").stream()
                    .map(HiveType::getTypeInfo)
                    .collect(toImmutableList());
            this.tableBucketCount = tableBucketCount;
            this.partitionBucketCount = partitionBucketCount;
        }

        @Override
        public int[] getInputChannels()
        {
            return bucketColumns;
        }

        @Override
        public boolean evaluate(SqlFunctionProperties properties, Page page, int position)
        {
            int bucket = getHiveBucket(tableBucketCount, typeInfoList, page, position);
            if ((bucket - bucketToKeep) % partitionBucketCount != 0) {
                throw new PrestoException(HIVE_INVALID_BUCKET_FILES, format(
                        "A row that is supposed to be in bucket %s is encountered. Only rows in bucket %s (modulo %s) are expected",
                        bucket, bucketToKeep % partitionBucketCount, partitionBucketCount));
            }

            return bucket == bucketToKeep;
        }
    }
}


text:
MenuTestBase::MenuTestBase()
    : ViewEventTestBase(),
      button_(NULL),
      menu_(NULL),
      last_command_(0) {
}

MenuTestBase::~MenuTestBase() {
}

void MenuTestBase::Click(views::View* view, const base::Closure& next) {
  ui_test_utils::MoveMouseToCenterAndPress(
      view,
      ui_controls::LEFT,
      ui_controls::DOWN | ui_controls::UP,
      next);
}

void MenuTestBase::KeyPress(ui::KeyboardCode keycode,
                            const base::Closure& next) {
  ui_controls::SendKeyPressNotifyWhenDone(
      GetWidget()->GetNativeWindow(), keycode, false, false,
      false, false, next);
}

int MenuTestBase::GetMenuRunnerFlags() {
  return views::MenuRunner::HAS_MNEMONICS;
}

void MenuTestBase::SetUp() {
  button_ = new views::MenuButton(
      NULL, base::ASCIIToUTF16("Menu Test"), this, true);
  menu_ = new views::MenuItemView(this);
  BuildMenu(menu_);
  menu_runner_.reset(new views::MenuRunner(menu_, GetMenuRunnerFlags()));

  ViewEventTestBase::SetUp();
}

void MenuTestBase::TearDown() {
  // We cancel the menu first because certain operations (like a menu opened
  // with views::MenuRunner::FOR_DROP) don't take kindly to simply pulling the
  // runner out from under them.
  menu_runner_->Cancel();

  menu_runner_.reset();
  menu_ = NULL;
  ViewEventTestBase::TearDown();
}

views::View* MenuTestBase::CreateContentsView() {
  return button_;
}

void MenuTestBase::DoTestOnMessageLoop() {
  Click(button_, CreateEventTask(this, &MenuTestBase::DoTestWithMenuOpen));
}

gfx::Size MenuTestBase::GetPreferredSize() const {
  return button_->GetPreferredSize();
}

void MenuTestBase::OnMenuButtonClicked(views::View* source,
                                       const gfx::Point& point) {
  gfx::Point screen_location;
  views::View::ConvertPointToScreen(source, &screen_location);
  gfx::Rect bounds(screen_location, source->size());
  ignore_result(menu_runner_->RunMenuAt(source->GetWidget(),
                                        button_,
                                        bounds,
                                        views::MENU_ANCHOR_TOPLEFT,
                                        ui::MENU_SOURCE_NONE));
}

void MenuTestBase::ExecuteCommand(int id) {
  last_command_ = id;
}


text:
#include <common.h>
#include <asm/omap_common.h>
#include <asm/io.h>

/*
 * Setup LDOVBB for OMAP5.
 * On OMAP5+ some ABB settings are fused. They are handled
 * in the following way:
 *
 * 1. corresponding EFUSE register contains ABB enable bit
 *    and VSET value
 * 2. If ABB enable bit is set to 1, than ABB should be
 *    enabled, otherwise ABB should be disabled
 * 3. If ABB is enabled, than VSET value should be copied
 *    to corresponding MUX control register
 */
s8 abb_setup_ldovbb(u32 fuse, u32 ldovbb)
{
	u32 vset;
	u32 fuse_enable_mask = OMAP5_PROD_ABB_FUSE_ENABLE_MASK;
	u32 fuse_vset_mask = OMAP5_PROD_ABB_FUSE_VSET_MASK;

	if (!is_omap54xx()) {
		/* DRA7 */
		fuse_enable_mask = DRA7_ABB_FUSE_ENABLE_MASK;
		fuse_vset_mask = DRA7_ABB_FUSE_VSET_MASK;
	}
	/*
	 * ABB parameters must be properly fused
	 * otherwise ABB should be disabled
	 */
	vset = readl(fuse);
	if (!(vset & fuse_enable_mask))
		return -1;

	/* prepare VSET value for LDOVBB mux register */
	vset &= fuse_vset_mask;
	vset >>= ffs(fuse_vset_mask) - 1;
	vset <<= ffs(OMAP5_ABB_LDOVBBMPU_VSET_OUT_MASK) - 1;
	vset |= OMAP5_ABB_LDOVBBMPU_MUX_CTRL_MASK;

	/* setup LDOVBB using fused value */
	clrsetbits_le32(ldovbb,  OMAP5_ABB_LDOVBBMPU_VSET_OUT_MASK, vset);

	return 0;
}


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Orchis sesquipedalis Willd.

### Remarks
null


text:
import React from 'react';

import {decorate, getTabsProps} from '../utils/plugins';

import Tabs_ from './tabs';
import {HeaderProps} from '../hyper';

const Tabs = decorate(Tabs_, 'Tabs');

export default class Header extends React.PureComponent<HeaderProps> {
  headerMouseDownWindowX!: number;
  headerMouseDownWindowY!: number;

  onChangeIntent = (active: string) => {
    // we ignore clicks if they're a byproduct of a drag
    // motion to move the window
    if (window.screenX !== this.headerMouseDownWindowX || window.screenY !== this.headerMouseDownWindowY) {
      return;
    }

    this.props.onChangeTab(active);
  };

  handleHeaderMouseDown = () => {
    // the hack of all hacks, this prevents the term
    // iframe from losing focus, for example, when
    // the user drags the nav around
    // Fixed by calling window.focusActiveTerm(), thus we can support drag tab
    // ev.preventDefault();

    // persist start positions of a potential drag motion
    // to differentiate dragging from clicking
    this.headerMouseDownWindowX = window.screenX;
    this.headerMouseDownWindowY = window.screenY;
  };

  handleHamburgerMenuClick = (event: React.MouseEvent) => {
    let {right: x, bottom: y} = event.currentTarget.getBoundingClientRect();
    x -= 15; // to compensate padding
    y -= 12; // ^ same
    this.props.openHamburgerMenu({x, y});
  };

  handleMaximizeClick = () => {
    if (this.props.maximized) {
      this.props.unmaximize();
    } else {
      this.props.maximize();
    }
  };

  handleMinimizeClick = () => {
    this.props.minimize();
  };

  handleCloseClick = () => {
    this.props.close();
  };

  getWindowHeaderConfig() {
    const {showHamburgerMenu, showWindowControls} = this.props;

    const defaults = {
      hambMenu: !this.props.isMac, // show by default on windows and linux
      winCtrls: !this.props.isMac // show by default on Windows and Linux
    };

    // don't allow the user to change defaults on macOS
    if (this.props.isMac) {
      return defaults;
    }

    return {
      hambMenu: showHamburgerMenu === '' ? defaults.hambMenu : showHamburgerMenu,
      winCtrls: showWindowControls === '' ? defaults.winCtrls : showWindowControls
    };
  }

  render() {
    const {isMac} = this.props;
    const props = getTabsProps(this.props, {
      tabs: this.props.tabs,
      borderColor: this.props.borderColor,
      onClose: this.props.onCloseTab,
      onChange: this.onChangeIntent,
      fullScreen: this.props.fullScreen
    });
    const {borderColor} = props;
    let title = 'Hyper';
    if (props.tabs.length === 1 && props.tabs[0].title) {
      // if there's only one tab we use its title as the window title
      title = props.tabs[0].title;
    }
    const {hambMenu, winCtrls} = this.getWindowHeaderConfig();
    const left = winCtrls === 'left';
    const maxButtonHref = this.props.maximized
      ? './renderer/assets/icons.svg#restore-window'
      : './renderer/assets/icons.svg#maximize-window';

    return (
      <header
        className={`header_header ${isMac && 'header_headerRounded'}`}
        onMouseDown={this.handleHeaderMouseDown}
        onMouseUp={() => window.focusActiveTerm()}
        onDoubleClick={this.handleMaximizeClick}
      >
        {!isMac && (
          <div
            className={`header_windowHeader ${props.tabs.length > 1 ? 'header_windowHeaderWithBorder' : ''}`}
            style={{borderColor}}
          >
            {hambMenu && (
              <svg
                className={`header_shape ${left ? 'header_hamburgerMenuRight' : 'header_hamburgerMenuLeft'}`}
                onClick={this.handleHamburgerMenuClick}
              >
                <use xlinkHref="./renderer/assets/icons.svg#hamburger-menu" />
              </svg>
            )}
            {title}
            {winCtrls && (
              <div className={`header_windowControls ${left ? 'header_windowControlsLeft' : ''}`}>
                <div className={`${left ? 'header_minimizeWindowLeft' : ''}`} onClick={this.handleMinimizeClick}>
                  <svg className="header_shape">
                    <use xlinkHref="./renderer/assets/icons.svg#minimize-window" />
                  </svg>

                <div className={`${left ? 'header_maximizeWindowLeft' : ''}`} onClick={this.handleMaximizeClick}>
                  <svg className="header_shape">
                    <use xlinkHref={maxButtonHref} />
                  </svg>

                <div
                  className={`header_closeWindow ${left ? 'header_closeWindowLeft' : ''}`}
                  onClick={this.handleCloseClick}
                >
                  <svg className="header_shape">
                    <use xlinkHref="./renderer/assets/icons.svg#close-window" />
                  </svg>

            )}

        )}
        {this.props.customChildrenBefore}
        <Tabs {...props} />
        {this.props.customChildren}

    );
  }
}


text:
var fs = require('fs');
var parse = require('csv-parse');
var minimist = require('minimist');
var argv = minimist(process.argv.slice(2));

if (argv._.length < 2) {
    console.log('node transformCSV.js <inputFile.csv> <outputFile.csv>');
    process.exit(9);
}

var input = fs.createReadStream(argv._[0]);
var output = fs.createWriteStream(argv._[1]);

function isNumber(n) {
    return !isNaN(parseFloat(n)) && isFinite(n);
}

var parser = parse({trim:true}, function(err, data) {

    var headers = 0;
    var rows = 0;

    var transformed = data.reduce(function(prev, current) {

        var header = prev[0];
        var avg = prev[1];

        var firstCell = current[0];

        if (!isNumber(firstCell)) {
            if (header) {
                prev[0] = header.map(function(headerValue, idx) {
                    return headerValue + ":" + current[idx];
                });
            } else {
                prev[0] = current.concat();
            }

            headers = headers + 1;

        } else {

            if (avg) {
                prev[1] = avg.map(function(value, idx) {
                    // Running Average
                    return ((value * rows) + parseFloat(current[idx]))/(rows + 1);
                });
            } else {
                prev[1] = current.map(function(v) { return parseFloat(v); });
            }

            rows = rows + 1;
        }

        return prev;

    }, []);

    output.write(transformed.reduce(function(prev, current) {
        return prev + '\n' + current.join(',');
    }, ''));
});

input.pipe(parser);


text:
_An immense centipede-like beast erupts from the snow, rows of chitinous plates on its back glowing red-hot._

**Remorhaz CR 7**

**XP 3,200**

N Huge [magical beast](creatureTypes#_magical-beast)

**Init** +1; **Senses** darkvision 60 ft., low-light vision, [tremorsense](universalMonsterRules#_tremorsense) 60 ft.; [Perception](../skills/perception#_perception) +16

**Defense**

**AC** 20, touch 9, flat-footed 19 (+1 Dex, +11 natural, –2 size)

**hp** 94 (9d10+45)

**Fort** +11, **Ref** +7, **Will** +4

**Immune** fire, cold

**Offense**

**Speed** 30 ft., burrow 20 ft.

**Melee** bite +13 (3d6+9 plus [grab](universalMonsterRules#_grab))

**Space** 15 ft.; **Reach** 15 ft.

**Special Attacks** heat, [swallow whole](universalMonsterRules#_swallow-whole) (2d6+9 plus 8d6 fire, AC 15, hp 9)

**Statistics**

**Str** 22, **Dex** 13, **Con** 21, **Int** 5, **Wis** 12, **Cha** 10

**Base Atk** +9; **CMB** +17 (+21 grapple); **CMD** 28 (can't be tripped)

**Feats** [Awesome Blow](monsterFeats#_awesome-blow), [Cleave](../feats#_cleave), [Improved Bull Rush](../feats#_improved-bull-rush), [Power Attack](../feats#_power-attack), [Skill Focus](../feats#_skill-focus) ( [Perception](../skills/perception#_perception))

**Skills** [Perception](../skills/perception#_perception) +16

**Languages** Giant (cannot speak)

**Ecology**

**Environment** cold deserts and glaciers

**Organization** solitary

**Treasure** none

**Special Abilities**

**Heat (Su)** An enraged remorhaz generates heat so intense that anything touching its body takes 8d6 points of fire damage. Creatures striking a remorhaz with natural attacks or unarmed strikes are subject to this damage, but creatures striking with melee weapons are not. The heat can melt or burn weapons; any weapon that strikes a remorhaz is allowed a DC 19 Fortitude save to avoid taking damage. The save DC is Constitution-based.

In a world of ice and snow, the remorhaz is particularly feared for the terrible fires that burn within its body. These internal fires cause the armor plates along its back to glow red-hot when the creature is particularly angry, excited, or in pain. Creatures adapted to arctic regions are often particularly vulnerable to fire, making the remorhaz's primary defense an incredibly potent one and securing its role as a dangerous predator in such frozen reaches.

Remorhazes dwell in extensive warrens carved into the hearts of glaciers. The beasts use their heat to melt tunnels through ice, tunnels whose smooth glassy sides swiftly refreeze in their wake to create uncommonly stable and numerous mazes.

Although the remorhaz has much in common superficially with lesser vermin, the beast is surprisingly intelligent. While not capable of speech, the typical remorhaz has a good grasp of the Giant tongue, and tribes of giants often use this to their advantage to secure allegiances with the great beasts. Frost giants are particularly obsessed with them, for those giants who brave the cruel and deadly burns a remorhaz can inflict to become "worm friends" gain a potent weapon to use against their enemies—an assassin capable of burrowing up through the floor of a glacial keep to strike directly against a frost giant's greatest weakness: fire. Other giants use the beasts as living forges, for their backs are hot enough to melt metal.

A remorhaz is 25 feet long and weighs 10,000 pounds.


text:
<?php
/**
 * Содержит класс BlogEditor
 *
 * @package energine
 * @subpackage blog
 * @author sign
 */

 /**
  * Редактор постов блога
  *
  * @package energine
  * @subpackage blog
  * @author sign
  */
 class BlogEditor extends Grid {
    /**
     * Конструктор класса
     *
     * @param string $name
     * @param string $module

     * @param array $params
     * @access public
     */
    public function __construct($name,    array $params = null) {
        parent::__construct($name, $params);
        $this->setTableName('blog_title');
//        $this->setOrderColumn('blog_name');
    }
     /**
     * Устанавливаем дефолтные значения
     *
     * @access protected
     * @return void
     */
//    protected function add() {
//        parent::add();
//        $this->getData()->getFieldByName('vacancy_is_active')->setData(true, true);
//        $this->getData()->getFieldByName('vacancy_date')->setData(date('Y-m-d'), true);
//        $this->getDataDescription()->getFieldDescriptionByName('vacancy_url_segment')->setProperty('nullable','nullable');
//        $this->getDataDescription()->getFieldDescriptionByName('vacancy_url_segment')->removeProperty('pattern');
//    }

    /**
     * Устанавливаем необязательность vacancy_url_segment
     *
     * @access protected
     * @return void
     */
//    protected function edit() {
//        parent::edit();
//        $this->getDataDescription()->getFieldDescriptionByName('vacancy_url_segment')->setProperty('nullable','nullable');
//        $this->getDataDescription()->getFieldDescriptionByName('vacancy_url_segment')->removeProperty('pattern');
//    }

    /**
     * ПРи сохранении данных устанавливаем сегмент УРЛа
     *
     * @access protected
     * @return mixed
     */
//    protected function saveData() {
//        if (!isset($_POST[$this->getTableName()]['vacancy_url_segment']) || empty($_POST[$this->getTableName()]['vacancy_url_segment'])) {
//            $_POST[$this->getTableName()]['vacancy_url_segment'] = Translit::transliterate(
//                $_POST[$this->getTranslationTableName()][E()->getLanguage()->getDefault()]['vacancy_name']
//            , '-', true);
//        }
//        return parent::saveData();
//    }
}


text:
class CreateAudios < ActiveRecord::Migration
  def change
    create_table :audios do |t|
      t.references :audioable, polymorphic: true, index: true
      t.attachment :audio
      t.boolean :online, default: true

      t.timestamps null: false
    end
  end
end


text:
[![Travis Build Status](https://img.shields.io/travis/exonum/exonum/master.svg?label=Linux%20Build)](https://travis-ci.com/exonum/exonum)
[![License: Apache-2.0](https://img.shields.io/github/license/exonum/exonum.svg)](https://github.com/exonum/exonum/blob/master/LICENSE)
![rust 1.42.0+ required](https://img.shields.io/badge/rust-1.42.0+-blue.svg?label=Required%20Rust)

`exonum-supervisor` is a main service of the [Exonum blockchain framework](https://exonum.com/).
It is capable of deploying and starting new services,
changing the state of existing services (such as stopping, freezing,
or initiating a data migration), and changing configuration
of the started services.

## Description

Supervisor is an Exonum service capable of the following activities:

- Deploying service artifacts and unloading unused artifacts
- Instantiating services
- Changing configuration of instantiated services
- Changing a state of instantiated services: stopping, freezing, resuming,
  and initiating data migrations
- Changing consensus configuration

More information on the artifact / service lifecycle can be found in the
documentation of [service lifecycle][docs:lifecycle] and the [supervisor][docs:supervisor].

Supervisor service has two different operating modes: a "simple" mode and a
"decentralized" mode. The difference between modes is in the decision making approach:

- In the decentralized mode, to instantiate a service or apply a new
  configuration, more than 2/3rds of validators should reach a consensus.
- In the simple mode, any decision is executed after a single validator
  approval.

The simple mode can be useful if one network administrator manages all the
validator nodes or for testing purposes (e.g., to test service configuration
with `TestKit`).

For a network with a low node confidence, consider using the decentralized
mode.

## Interaction

The intended way to interact with supervisor is the REST API. To be precise,
requests should be sent to the one of the following endpoints:
`deploy-artifact`, `propose-config` or `confirm-config`.

Once received, supervisor will convert the request into appropriate
transaction, sign it with the validator keys and broadcast for the
rest of the network.

Key point here is that user **should not** send transactions to the supervisor
by himself. An expected format of requests for those endpoints is a serialized
Protobuf message.

To deploy an artifact, one (within the "simple" mode) or majority (within the
"decentralized" mode) of the nodes should submit a `DeployRequest` message
through API.

To request a config change, one node should submit a `ConfigPropose` message
through API.
For the "simple" mode, no more actions are required. For the "decentralized"
mode, the majority of the nodes should also submit `ConfigVote` messages
with a hash of the proposed configuration.
The proposal initiator that sends the original `ConfigPropose` message
should not vote for the configuration; the supervisor considers that the initiator
has voted by submitting a proposal.

Starting, resuming or freezing a service, or unloading an artifact
are treated similarly to a configuration change and follow the same rules.

## HTTP API

REST API of the service is documented in [the crate docs](https://docs.rs/exonum-supervisor).

## Usage

Include `exonum-supervisor` as a dependency in your `Cargo.toml`:

```toml
[dependencies]
exonum = "1.0.0"
exonum-supervisor = "1.0.0"
```

Note that the supervisor service is added to the blockchain automatically
by the [`exonum-cli`] crate, so no actions are required if you use this crate.

## License

`exonum-supervisor` is licensed under the Apache License (Version 2.0).
See [LICENSE](LICENSE) for details.

[docs:supervisor]: https://exonum.com/doc/version/latest/advanced/supervisor/
[docs:lifecycle]: https://exonum.com/doc/version/latest/architecture/service-lifecycle/
[`exonum-cli`]: https://crates.io/crates/exonum-cli


text:
module Makura
  module Plugin
    module Pager
      module SingletonMethods
        def pager(page, limit)
          Makura::Plugin::Pager::Pagination.new(self, :pager, page, limit)
        end
      end

      class Pagination
        def initialize(model, view, page, limit)
          @model, @view, @page, @limit = model, view, page, limit
        end

        # /pager/_all_docs?count=10&group=true
        # /pager/_all_docs?startkey=%224f9dca1c66121f9320a69553546db07a%22&startkey_docid=4f9dca1c66121f9320a69553546db07a&skip=1&descending=false&count=10&group=true
        # /pager/_all_docs?startkey=%22_design%2FUser%22&startkey_docid=_design%2FUser&skip=1&descending=false&count=10&group=true
        # /pager/_all_docs?startkey=%22d850f0801686b85035680bb6f38d5c5c%22&startkey_docid=d850f0801686b85035680bb6f38d5c5c&skip=1&descending=false&count=10&group=true

        # NOTE:
        #   * descending should be true if you page backwards

        include Enumerable

        def each(start_id = nil, descending = false, &block)
          opts = {
            :count => @limit,
            :group => true,
            :descending => descending,
            # :include_docs => true,
          }

          if start_id
            opts[:skip] = 1
            opts[:startkey_docid] = start_id
            opts[:startkey] = start_id
          end

          @model.view(@view, opts).each(&block)
        end

        def count
        end

        def first_page?
        end

        def last_page?
        end

        def empty?
        end
      end
    end
  end
end


text:
<?php
namespace Aspose\Words\Models;
/**
 * $model.description$
 *
 * NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually.
 *
 */
class DocumentStatData {
	static $swaggerTypes = array(
		'WordCount' => 'int',
		'ParagraphCount' => 'int',
		'PageCount' => 'int',
		'PageStatData' => 'array[PageStatData]'

	);

	public $WordCount; // int
	public $ParagraphCount; // int
	public $PageCount; // int
	public $PageStatData; // array[PageStatData]
	}


text:
using namespace std;

class Text {
private:
	int id;
	string text;
public:
	Text();
	Text(string _text);
	Text(int _id, string _text);
	~Text();
	int getId();
	string getText();
};


text:
<?php
namespace tests\Extractor\Fields;

class getFieldFromStringTest extends \PHPUnit_Framework_TestCase
{
    /**
     * when field is ENUM then catch ENUM type
     */
    public function testWhenFieldIsEnumThenCatchEnumType()
    {
        $fieldExtractor = \Mockery::mock('\\MySQLExtractor\\Extractor\\Fields')->makePartial();

        $fieldStringLine = "`ShiftType` enum('full-time','part-time') NOT NULL DEFAULT 'part-time' COMMENT 'Specifies the working hours type (full-time, part-time).',";

        $field = $fieldExtractor::getFieldFromString($fieldStringLine);
        $this->assertEquals('ShiftType', $field->Id);
        $this->assertEquals('ENUM', $field->Type);
    }

    /**
     * When field default in string zero then Default will be int or string zero.
     */
    public function testWhenFieldDefaultInStringZeroThenDefaultWillBeIntOrStringZero()
    {
        $fieldExtractor = \Mockery::mock('\\MySQLExtractor\\Extractor\\Fields')->makePartial();

        $fieldStringLine = "`comment_id` bigint(20) unsigned NOT NULL DEFAULT '0',";
        $field = $fieldExtractor::getFieldFromString($fieldStringLine);

        $this->assertEquals('0', $field->Default);
    }

    /**
     * when field is ENUM then catch ENUM values as field values
     */
    public function testWhenFieldIsEnumThenCatchEnumValuesAsFieldValues()
    {
        $fieldExtractor = \Mockery::mock('\\MySQLExtractor\\Extractor\\Fields')->makePartial();

        $expected = array(
            'full-time',
            'part-time'
        );

        $fieldStringLine = "`ShiftType` enum('full-time', 'part-time') NOT NULL DEFAULT 'part-time' COMMENT 'Specifies the working hours type (full-time, part-time).',";

        $field = $fieldExtractor::getFieldFromString($fieldStringLine);
        $this->assertEquals($expected, $field->Values);
    }

    /**
     * when field is not found then return false
     */
    public function testWhenFieldIsNotFoundThenReturnFalse()
    {
        $fieldExtractor = \Mockery::mock('\\MySQLExtractor\\Extractor\\Fields')->makePartial();

        $fieldStringLine = "PRIMARY KEY (`AuthorID`)";

        $response = $fieldExtractor::getFieldFromString($fieldStringLine);
        $this->assertFalse($response);
    }
}


text:
<resources>
    <!-- Base application theme. -->
    <style name="AppTheme.Light" parent="MaterialDrawerTheme.Light.DarkToolbar">
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>

        <item name="colorDefaultBackground">@color/colorPrimary</item>
        <item name="colorCardBackground">#ffffff</item>
        <item name="colorBehindCardBackground">#e4e4e4</item>
        <item name="colorLightSeparatorBackground">#d8d8d8</item>
        <item name="colorLighterSeparatorBackground">#cccccc</item>
        <item name="colorAccountHeader">@color/colorPrimary</item>
        <item name="colorHighlightBackground">@color/md_blue_100</item>
        <item name="lightTextColor">#9a9a9a</item>
        <item name="colorTradeScorePositive">@color/md_green_600</item>
        <item name="colorTradeScoreNegative">@color/md_red_600</item>
    </style>

    <style name="AppTheme.Dark" parent="MaterialDrawerTheme">
        <item name="colorPrimary">@color/dark.colorPrimary</item>
        <item name="colorPrimaryDark">#000000</item>
        <item name="colorAccent">@color/colorAccent</item>

        <item name="colorDefaultBackground">@color/dark.colorPrimary</item>
        <item name="colorCardBackground">@color/dark.colorPrimary</item>
        <item name="colorBehindCardBackground">@color/colorTransparent</item>
        <item name="colorLightSeparatorBackground">#666666</item>
        <item name="colorLighterSeparatorBackground">#333333</item>
        <item name="colorAccountHeader">#000000</item>
        <item name="colorHighlightBackground">@color/md_blue_grey_700</item>
        <item name="lightTextColor">#777777</item>
        <item name="colorTradeScorePositive">@color/md_green_600</item>
        <item name="colorTradeScoreNegative">@color/md_red_600</item>
    </style>

    <style name="TransparentText" parent="@android:style/TextAppearance">
        <item name="android:textColor">#00000000</item>
    </style>

    <style name="NormalText" parent="@android:style/TextAppearance.Small">
        <item name="android:textSize">14sp</item>
    </style>

    <style name="SmallText" parent="@android:style/TextAppearance.Small">
        <item name="android:textSize">10sp</item>
    </style>

    <style name="MediumText" parent="@android:style/TextAppearance.Small">
        <item name="android:textSize">12sp</item>
    </style>

    <style name="BigText" parent="@android:style/TextAppearance.Small">
        <item name="android:textSize">16sp</item>
    </style>

    <style name="MediumButton" parent="@style/Widget.AppCompat.Button.Borderless">
        <item name="android:textSize">12sp</item>
        <item name="android:minWidth">0dp</item>
        <item name="android:minHeight">8dp</item>
    </style>

    <style name="MediumButton.Colored" parent="@style/Widget.AppCompat.Button.Borderless.Colored">
        <item name="android:textSize">12sp</item>
        <item name="android:minWidth">0dp</item>
        <item name="android:minHeight">8dp</item>
    </style>

    <!-- Comment Styles -->

    <style name="SmallText.Light" parent="SmallText">
        <item name="android:textColor">?attr/lightTextColor</item>
    </style>

    <style name="SmallText.NormalUser" parent="SmallText.Light">
        <item name="android:textStyle">bold</item>
    </style>

    <style name="SmallText.HighlightOp" parent="SmallText">
        <item name="android:textColor">@color/md_white_1000</item>
        <item name="android:background">?attr/colorAccountHeader</item>
        <item name="android:textStyle">bold</item>
    </style>

    <!-- Use rather rectangular image in the account header. -->
    <style name="BezelImageView">
        <item name="biv_maskDrawable">@drawable/material_drawer_square_mask</item>
        <item name="biv_drawCircularShadow">false</item>
        <item name="biv_selectorOnPress">@color/material_drawer_primary</item>
    </style>

    <style name="GiveawayIndicatorIcon">
        <item name="android:layout_width">@dimen/giveaway_list_indicator_size</item>
        <item name="android:layout_height">@dimen/giveaway_list_indicator_size</item>
        <item name="android:layout_marginRight">@dimen/giveaway_list_indicator_padding</item>
        <item name="android:layout_gravity">center_vertical</item>
    </style>
</resources>


text:
module('JSHint - routes');
test('routes/contact.js should pass jshint', function() {
  ok(true, 'routes/contact.js should pass jshint.');
});


text:
module Naam

  # Public: Base class for a rule of grammar. The goal of a rule is
  # to transform lexical units into an AST.
  class BaseRule

    # Public: Returns Boolean true if the next units form an if clause.
    def self.if_clause?(units)
      unit = units[1]
      unit.type == :keyword && unit.value == 'if'
    end

    # Public: Initialize a new rule. The units and ast_node objects
    # given in arguments will be modified by #apply!.
    #
    # units    - Array of LexicalUnits.
    # ast_node - An AST object, for adding children, etc.
    def initialize(units, ast_node)
      @units = units
      @ast_node = ast_node
      @series = []
    end

    # Public: Apply the rule to the list of lexical units, creating
    # and/or modifying the ast node. #apply! modify the units and
    # ast_node objects given to #initialize.
    def apply!
      raise NotImplementedError
    end

    private

    # Accepts the next lexical unit, given type match the unit type.
    # If value is given, it has to match the unit value.
    #
    # type  - Expected Symbol type of the next unit.
    # value - Expected String value of the next unit. Default is the
    #         empty string, meaning the value doesn't matter.
    #
    # Returns nothing.
    # Raises BadLexemeError if type or value doesn't match.
    def accept(type, value = '')
      unit = @units.slice!(0)
      @series << unit
      unless unit.type == type
        raise(BadLexemeError,
          "Expected: (#{type}, #{value}), got: (#{unit.type}, #{unit.value})")
      end
      if value != ''
        raise BadLexemeError unless unit.value == value
      end
    end

    # A shortcut method to #accept. Usefull when we have several calls
    # to #accept. Calls #accept for each of the symbol in args.
    #
    # args - A series of Symbol.
    #
    # Returns nothing.
    def accept_series(*args)
      args.each {|arg| accept(arg) }
    end

  end
end


text:
package org.onosproject.incubator.net.routing;

import org.onlab.packet.IpAddress;
import org.onlab.packet.IpPrefix;
import org.onlab.packet.MacAddress;
import org.onosproject.net.ConnectPoint;

import java.util.Objects;

import static com.google.common.base.MoreObjects.toStringHelper;

/**
 * Represents a route with the next hop MAC address resolved.
 */
public class ResolvedRoute {

    private final IpPrefix prefix;
    private final IpAddress nextHop;
    private final MacAddress nextHopMac;
    private final ConnectPoint location;

    /**
     * Creates a new resolved route.
     *
     * @param route input route
     * @param nextHopMac next hop MAC address
     * @param location connect point where the next hop connects to
     */
    public ResolvedRoute(Route route, MacAddress nextHopMac, ConnectPoint location) {
        this.prefix = route.prefix();
        this.nextHop = route.nextHop();
        this.nextHopMac = nextHopMac;
        this.location = location;
    }

    /**
     * Creates a new resolved route.
     *
     * @param prefix route prefix
     * @param nextHop route next hop IP address
     * @param nextHopMac next hop MAC address
     * @param location connect point where the next hop connects to
     */
    public ResolvedRoute(IpPrefix prefix, IpAddress nextHop, MacAddress nextHopMac,
                         ConnectPoint location) {
        this.prefix = prefix;
        this.nextHop = nextHop;
        this.nextHopMac = nextHopMac;
        this.location = location;
    }

    /**
     * Returns the IP prefix.
     *
     * @return IP prefix
     */
    public IpPrefix prefix() {
        return prefix;
    }

    /**
     * Returns the next hop IP address.
     *
     * @return IP address
     */
    public IpAddress nextHop() {
        return nextHop;
    }

    /**
     * Returns the next hop MAC address.
     *
     * @return MAC address
     */
    public MacAddress nextHopMac() {
        return nextHopMac;
    }

    /**
     * Returns the next hop location.
     *
     * @return connect point where the next hop attaches to
     */
    public ConnectPoint location() {
        return location;
    }

    @Override
    public int hashCode() {
        return Objects.hash(prefix, nextHop, nextHopMac, location);
    }

    @Override
    public boolean equals(Object other) {
        if (this == other) {
            return true;
        }

        if (!(other instanceof ResolvedRoute)) {
            return false;
        }

        ResolvedRoute that = (ResolvedRoute) other;

        return Objects.equals(this.prefix, that.prefix) &&
                Objects.equals(this.nextHop, that.nextHop) &&
                Objects.equals(this.nextHopMac, that.nextHopMac) &&
                Objects.equals(this.location, that.location);
    }

    @Override
    public String toString() {
        return toStringHelper(this)
                .add("prefix", prefix)
                .add("nextHop", nextHop)
                .add("nextHopMac", nextHopMac)
                .add("location", location)
                .toString();
    }
}


text:
:host {
  /* technical */
  display: block;
  box-sizing: border-box;
  -moz-box-sizing: border-box;
  /* border/shadow */
	border-bottom: 1px solid rgba(0, 0, 0, 0.15);
	/* size */
  height: 60px;
  font-size: 21px;
	position: relative;
}

:host(.narrow-layout[responsive]:host) {
  position: fixed;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 1;
  border: 0;
  border-top: 1px solid rgba(0, 0, 0, 0.28);
}

/* TODO(sorvell): use of !important due to inability to
  naturally win over an :host style */
/*@polyfill :host > polymer-ui-icon-button */
::content > polymer-ui-icon-button {
  margin: 0px 8px 0 8px !important;
}

/*@polyfill :host > polymer-ui-menu-button */
::content > polymer-ui-menu-button {
  margin: 0px 8px 0 8px !important;
}

/*@polyfill :host > polymer-ui-toolbar */
::content > polymer-ui-toolbar {
  margin: 0;
}

/*@polyfill :host > polymer-ui-toolbar:not(.narrow-layout) */
::content > polymer-ui-toolbar:not(.narrow-layout) {
  border: 0;
  background: transparent none;
}


text:
'use strict';

// MODULES //

var lastIndexOf = require( 'last-index-of' );

// MAIN //

/**
* Returns the basename of a package.
*
* @private
* @param {string} pkg - package name (e.g., `@stdlib/math/base/special/sin` or `math/base/special/sin`)
* @returns {string} basename
*/
function basename( pkg ) {
	var idx = lastIndexOf( pkg, '/' );
	return pkg.substring( idx+1 ); // e.g., `sin`
}

// EXPORTS //

module.exports = basename;


text:
<?php
/* @var $this TasksController */
/* @var $model Tasks */

$this->breadcrumbs=array(
	'Tasks'=>array('index'),
	'Manage',
);

$this->menu=array(
	array('label'=>'List Tasks', 'url'=>array('index')),
	array('label'=>'Create Tasks', 'url'=>array('create')),
);

Yii::app()->clientScript->registerScript('search', "
$('.search-button').click(function(){
	$('.search-form').toggle();
	return false;
});
$('.search-form form').submit(function(){
	$('#tasks-grid').yiiGridView('update', {
		data: $(this).serialize()
	});
	return false;
});
");
?>

Manage Tasks

You may optionally enter a comparison operator (<, <=, >, >=, <>
or =) at the beginning of each of your search values to specify how the comparison should be done.

<?php echo CHtml::link('Advanced Search','#',array('class'=>'search-button')); ?>

<?php $this->renderPartial('_search',array(
	'model'=>$model,
)); ?>

<?php $this->widget('zii.widgets.grid.CGridView', array(
	'id'=>'tasks-grid',
	'dataProvider'=>$model->search(),
	'filter'=>$model,
	'columns'=>array(
		'taksId',
		'userId',
		'workingGroupId',
		'taskHeadline',
		'taskDescription',
		'insertDate',
		/*
		'updateDate',
		'taskDuration',
		'taskDurationEntity',
		*/
		array(
			'class'=>'CButtonColumn',
		),
	),
)); ?>