text:
package org.apache.sling.resource.inventory.impl;

import java.io.PrintWriter;
import java.util.Map;

import org.apache.felix.inventory.Format;
import org.apache.felix.inventory.InventoryPrinter;
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.ConfigurationPolicy;
import org.apache.felix.scr.annotations.Properties;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.Service;
import org.apache.sling.api.resource.LoginException;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ResourceResolverFactory;
import org.apache.sling.commons.json.JSONException;
import org.slf4j.LoggerFactory;

@Component(configurationFactory=true, policy=ConfigurationPolicy.REQUIRE, metatype=true)
@Service(value=InventoryPrinter.class)
@Properties({
    @Property(name=InventoryPrinter.FORMAT, value="JSON", propertyPrivate=true),
    @Property(name=InventoryPrinter.NAME),
    @Property(name=InventoryPrinter.TITLE),
    @Property(name=InventoryPrinter.WEBCONSOLE, boolValue=false, propertyPrivate=true)
})
public class ResourceInventoryPrinterFactory implements InventoryPrinter {

    @Property(value = "")
    private static final String PROP_PATH = "path";

    private String path;

    @Activate
    protected void activate(final Map<String, Object> props) {
        this.path = (String)props.get(PROP_PATH);
    }

    @Reference
    private ResourceResolverFactory factory;

    /**
     * @see org.apache.felix.inventory.InventoryPrinter#print(java.io.PrintWriter, org.apache.felix.inventory.Format, boolean)
     */
    public void print(PrintWriter printWriter, Format format, boolean isZip) {
        if ( this.path == null || !format.equals(Format.JSON) ) {
            return;
        }
        ResourceResolver resolver = null;
        try {
            resolver = factory.getAdministrativeResourceResolver(null);
            final Resource rootResource = resolver.getResource(this.path);
            if ( rootResource != null ) {
                final ResourceTraversor rt = new ResourceTraversor(rootResource);
                rt.collectResources();
                printWriter.write(rt.getJSONObject().toString(2));

            }
        } catch (final LoginException e) {
            // ignore
        } catch (final JSONException ignore) {
            LoggerFactory.getLogger(this.getClass()).warn("Unable to create resource json", ignore);
        } finally {
            if ( resolver != null ) {
                resolver.close();
            }
        }
    }

}


text:
package rx.internal.operators;

import rx.Observable.Operator;
import rx.Producer;
import rx.Subscriber;

/**
 * An {@code Observable} that emits the first {@code num} items emitted by the source {@code Observable}.
 *

 *
 *

 * You can choose to pay attention only to the first {@code num} items emitted by an {@code Observable} by using
 * the {@code take} operator. This operator returns an {@code Observable} that will invoke a subscriber's
 * {@link Subscriber#onNext onNext} function a maximum of {@code num} times before invoking
 * {@link Subscriber#onCompleted onCompleted}.
 */
public final class OperatorTake<T> implements Operator<T, T> {

    final int limit;

    public OperatorTake(int limit) {
        this.limit = limit;
    }

    @Override
    public Subscriber<? super T> call(final Subscriber<? super T> child) {
        final Subscriber<T> parent = new Subscriber<T>() {

            int count = 0;
            boolean completed = false;

            @Override
            public void onCompleted() {
                if (!completed) {
                    child.onCompleted();
                }
            }

            @Override
            public void onError(Throwable e) {
                if (!completed) {
                    child.onError(e);
                }
            }

            @Override
            public void onNext(T i) {
                if (!isUnsubscribed()) {
                    child.onNext(i);
                    if (++count >= limit) {
                        completed = true;
                        child.onCompleted();
                        unsubscribe();
                    }
                }
            }

            /**
             * We want to adjust the requested values based on the `take` count.
             */
            @Override
            protected Producer onSetProducer(final Producer producer) {
                return new Producer() {

                    @Override
                    public void request(int n) {
                        int c = limit - count;
                        if (n < c) {
                            producer.request(n);
                        } else {
                            producer.request(c);
                        }
                    }
                };
            }

        };

        if (limit == 0) {
            child.onCompleted();
            parent.unsubscribe();
        }

        /*
         * We decouple the parent and child subscription so there can be multiple take() in a chain such as for
         * the groupBy Observer use case where you may take(1) on groups and take(20) on the children.
         *
         * Thus, we only unsubscribe UPWARDS to the parent and an onComplete DOWNSTREAM.
         *
         * However, if we receive an unsubscribe from the child we still want to propagate it upwards so we
         * register 'parent' with 'child'
         */
        child.add(parent);

        /**
         * Since we decoupled the subscription chain but want the request to flow through, we reconnect the producer here.
         */
        child.setProducer(new Producer() {

            @Override
            public void request(int n) {
                if (n < 0) {
                    // request up the limit that has been set, no point in asking for more, even if synchronous
                    parent.request(limit);
                } else {
                    parent.request(n);
                }
            }
        });

        return parent;
    }

}

redpajama_set_name: RedPajamaGithub


text:
CONNECTED="$(system_profiler -detailLevel mini SPPowerDataType | grep Connected | grep -oE 'Yes|No')"
STATUS="$(defaults read NSGlobalDomain NSAppSleepDisabled)"

echo "AC adapter Connected: [${CONNECTED}] - AppNap Disabled: [${STATUS}]"
if [ "${CONNECTED}" == "Yes" ] && [ "${STATUS}" != "1" ]; then
	defaults write NSGlobalDomain NSAppSleepDisabled -bool YES && echo "AppNap Enabled"
elif [ "${CONNECTED}" != "Yes" ] && [ "${STATUS}" == "1" ]; then
	defaults write NSGlobalDomain NSAppSleepDisabled -bool NO && echo "AppNap Disabled"
fi


text:
import FileTools
import System.FilePath
import qualified Data.ByteString.Lazy.Char8 as B

main = find "/etc" >>= mapM judgeBashFile >>= mapM handleBashFile

judgeBashFile :: FilePath -> IO (String,Bool)
judgeBashFile file = cat file >>= return . (,) file . isBash
    where isBash bs = B.take 11 bs == B.pack "#!/bin/bash"

handleBashFile :: (String,Bool) -> IO ()
handleBashFile (file,False) = return ()
handleBashFile (file,True) = cat file >>= B.writeFile dest . chg
    where dest = "/home/ueda/hoge/" ++ takeFileName file
          chg cs = B.append (B.pack "#!/usr/local/bin/bash\n")
                            (B.unlines $ drop 1 $ B.lines cs)


text:
class AddAdminColumnToUsers < ActiveRecord::Migration
  def change
    add_column :users, :admin, :boolean, default: false
    add_index :users, :admin
  end
end


text:
class TestSetsController < ApplicationController
    def latest
        test_set = TestSet.find(params[:id])
        run = test_set.test_runs.find(:first, :order => "id desc")

        data = run.test_log.rawtest.gsub(/\<\?xml version="1.0" encoding="utf-8" standalone="no"\?\>/, '')
        data = "<xml>#{data}</xml>"

        respond_to do |format|
            format.xml {render :xml => data}
        end
    end
end


text:
package db

import java.io.{BufferedReader, FileInputStream, InputStreamReader}
import java.text.SimpleDateFormat

import db.utils.MySQLUtils

/**
  * Created by Administrator on 2016/7/20.
  */
object FileToMySQLDemo {
  def main(args: Array[String]) {
    val inPath = "E:/data/chinaNews/gn.txt"
    val seg = "\u00ef"

    val br = new BufferedReader(new InputStreamReader(new FileInputStream(inPath)))

    val mysqlUtils = new MySQLUtils()
      .setURL("jdbc:mysql://192.168.10.121:3306/spider?useUnicode=true&characterEncoding=UTF-8")

    val table = "cn_news_gn_tb"
    val fields = Array("category", "title", "start_date", "content")

    val conn = mysqlUtils.init()

    var count = 0
    var line = br.readLine()
    while (line != null) {
      count += 1

      val tokens = line.split(seg)
      if (tokens.length == 4) {
        val category = tokens(0)
        val title = tokens(1)
        val date = tokens(2)

        val toDate = new SimpleDateFormat("yyyy年MM月dd日 HH:mm")
        val toString = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
        val formattedDate = toString.format(toDate.parse(date))

        val content = tokens(3)

        val values = Array(category, title, formattedDate, content)

        mysqlUtils.insert(conn, table, fields, values)

        if (count % 10000 == 0) {
          println("已插入:" + count / 10000 + " 万条...")
        }

        line = br.readLine()
      }
    }

    mysqlUtils.close()
    br.close()
  }

}


text:
from django.apps import AppConfig

class ContribsConfig(AppConfig):
    name = 'contribs'


text:
#ifndef __CAPTURE_DEV_H__
#define __CAPTURE_DEV_H__

#include "capture_sockettypes.h"

#define CAP_DEV_DUMMY           "/dev/dummy"
#define CAP_DEV_DUMMY_VID       CAP_DEV_DUMMY"video"
#define CAP_DEV_DUMMY_AUD       CAP_DEV_DUMMY"audio"

int capture_devStart(CAP_ASYNC_DESCR_T *pCapCfg);
int capture_devCbOnFrame(void *pCbData, const unsigned char *pData, unsigned int len);

#endif // __CAPTURE_DEV_H__


text:
#pragma once
#include <aws/migrationhubstrategy/MigrationHubStrategyRecommendations_EXPORTS.h>
#include <aws/migrationhubstrategy/model/S3Object.h>
#include <aws/migrationhubstrategy/model/AntipatternReportStatus.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/core/utils/DateTime.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/migrationhubstrategy/model/AntipatternSeveritySummary.h>
#include <aws/migrationhubstrategy/model/StrategySummary.h>
#include <aws/migrationhubstrategy/model/ApplicationComponentSummary.h>
#include <aws/migrationhubstrategy/model/ServerSummary.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
  class JsonView;
} // namespace Json
} // namespace Utils
namespace MigrationHubStrategyRecommendations
{
namespace Model
{

  /**
   *
 Contains the summary of the assessment results.

See Also:

   * AWS
   * API Reference

   */
  class AWS_MIGRATIONHUBSTRATEGYRECOMMENDATIONS_API AssessmentSummary
  {
  public:
    AssessmentSummary();
    AssessmentSummary(Aws::Utils::Json::JsonView jsonValue);
    AssessmentSummary& operator=(Aws::Utils::Json::JsonView jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    /**
     *
 The Amazon S3 object containing the anti-pattern report.

     */
    inline const S3Object& GetAntipatternReportS3Object() const{ return m_antipatternReportS3Object; }

    /**
     *
 The Amazon S3 object containing the anti-pattern report.

     */
    inline bool AntipatternReportS3ObjectHasBeenSet() const { return m_antipatternReportS3ObjectHasBeenSet; }

    /**
     *
 The Amazon S3 object containing the anti-pattern report.

     */
    inline void SetAntipatternReportS3Object(const S3Object& value) { m_antipatternReportS3ObjectHasBeenSet = true; m_antipatternReportS3Object = value; }

    /**
     *
 The Amazon S3 object containing the anti-pattern report.

     */
    inline void SetAntipatternReportS3Object(S3Object&& value) { m_antipatternReportS3ObjectHasBeenSet = true; m_antipatternReportS3Object = std::move(value); }

    /**
     *
 The Amazon S3 object containing the anti-pattern report.

     */
    inline AssessmentSummary& WithAntipatternReportS3Object(const S3Object& value) { SetAntipatternReportS3Object(value); return *this;}

    /**
     *
 The Amazon S3 object containing the anti-pattern report.

     */
    inline AssessmentSummary& WithAntipatternReportS3Object(S3Object&& value) { SetAntipatternReportS3Object(std::move(value)); return *this;}

    /**
     *
 The status of the anti-pattern report.

     */
    inline const AntipatternReportStatus& GetAntipatternReportStatus() const{ return m_antipatternReportStatus; }

    /**
     *
 The status of the anti-pattern report.

     */
    inline bool AntipatternReportStatusHasBeenSet() const { return m_antipatternReportStatusHasBeenSet; }

    /**
     *
 The status of the anti-pattern report.

     */
    inline void SetAntipatternReportStatus(const AntipatternReportStatus& value) { m_antipatternReportStatusHasBeenSet = true; m_antipatternReportStatus = value; }

    /**
     *
 The status of the anti-pattern report.

     */
    inline void SetAntipatternReportStatus(AntipatternReportStatus&& value) { m_antipatternReportStatusHasBeenSet = true; m_antipatternReportStatus = std::move(value); }

    /**
     *
 The status of the anti-pattern report.

     */
    inline AssessmentSummary& WithAntipatternReportStatus(const AntipatternReportStatus& value) { SetAntipatternReportStatus(value); return *this;}

    /**
     *
 The status of the anti-pattern report.

     */
    inline AssessmentSummary& WithAntipatternReportStatus(AntipatternReportStatus&& value) { SetAntipatternReportStatus(std::move(value)); return *this;}

    /**
     *
 The status message of the anti-pattern report.

     */
    inline const Aws::String& GetAntipatternReportStatusMessage() const{ return m_antipatternReportStatusMessage; }

    /**
     *
 The status message of the anti-pattern report.

     */
    inline bool AntipatternReportStatusMessageHasBeenSet() const { return m_antipatternReportStatusMessageHasBeenSet; }

    /**
     *
 The status message of the anti-pattern report.

     */
    inline void SetAntipatternReportStatusMessage(const Aws::String& value) { m_antipatternReportStatusMessageHasBeenSet = true; m_antipatternReportStatusMessage = value; }

    /**
     *
 The status message of the anti-pattern report.

     */
    inline void SetAntipatternReportStatusMessage(Aws::String&& value) { m_antipatternReportStatusMessageHasBeenSet = true; m_antipatternReportStatusMessage = std::move(value); }

    /**
     *
 The status message of the anti-pattern report.

     */
    inline void SetAntipatternReportStatusMessage(const char* value) { m_antipatternReportStatusMessageHasBeenSet = true; m_antipatternReportStatusMessage.assign(value); }

    /**
     *
 The status message of the anti-pattern report.

     */
    inline AssessmentSummary& WithAntipatternReportStatusMessage(const Aws::String& value) { SetAntipatternReportStatusMessage(value); return *this;}

    /**
     *
 The status message of the anti-pattern report.

     */
    inline AssessmentSummary& WithAntipatternReportStatusMessage(Aws::String&& value) { SetAntipatternReportStatusMessage(std::move(value)); return *this;}

    /**
     *
 The status message of the anti-pattern report.

     */
    inline AssessmentSummary& WithAntipatternReportStatusMessage(const char* value) { SetAntipatternReportStatusMessage(value); return *this;}

    /**
     *
 The time the assessment was performed.

     */
    inline const Aws::Utils::DateTime& GetLastAnalyzedTimestamp() const{ return m_lastAnalyzedTimestamp; }

    /**
     *
 The time the assessment was performed.

     */
    inline bool LastAnalyzedTimestampHasBeenSet() const { return m_lastAnalyzedTimestampHasBeenSet; }

    /**
     *
 The time the assessment was performed.

     */
    inline void SetLastAnalyzedTimestamp(const Aws::Utils::DateTime& value) { m_lastAnalyzedTimestampHasBeenSet = true; m_lastAnalyzedTimestamp = value; }

    /**
     *
 The time the assessment was performed.

     */
    inline void SetLastAnalyzedTimestamp(Aws::Utils::DateTime&& value) { m_lastAnalyzedTimestampHasBeenSet = true; m_lastAnalyzedTimestamp = std::move(value); }

    /**
     *
 The time the assessment was performed.

     */
    inline AssessmentSummary& WithLastAnalyzedTimestamp(const Aws::Utils::DateTime& value) { SetLastAnalyzedTimestamp(value); return *this;}

    /**
     *
 The time the assessment was performed.

     */
    inline AssessmentSummary& WithLastAnalyzedTimestamp(Aws::Utils::DateTime&& value) { SetLastAnalyzedTimestamp(std::move(value)); return *this;}

    /**
     *
 List of AntipatternSeveritySummary.

     */
    inline const Aws::Vector<AntipatternSeveritySummary>& GetListAntipatternSeveritySummary() const{ return m_listAntipatternSeveritySummary; }

    /**
     *
 List of AntipatternSeveritySummary.

     */
    inline bool ListAntipatternSeveritySummaryHasBeenSet() const { return m_listAntipatternSeveritySummaryHasBeenSet; }

    /**
     *
 List of AntipatternSeveritySummary.

     */
    inline void SetListAntipatternSeveritySummary(const Aws::Vector<AntipatternSeveritySummary>& value) { m_listAntipatternSeveritySummaryHasBeenSet = true; m_listAntipatternSeveritySummary = value; }

    /**
     *
 List of AntipatternSeveritySummary.

     */
    inline void SetListAntipatternSeveritySummary(Aws::Vector<AntipatternSeveritySummary>&& value) { m_listAntipatternSeveritySummaryHasBeenSet = true; m_listAntipatternSeveritySummary = std::move(value); }

    /**
     *
 List of AntipatternSeveritySummary.

     */
    inline AssessmentSummary& WithListAntipatternSeveritySummary(const Aws::Vector<AntipatternSeveritySummary>& value) { SetListAntipatternSeveritySummary(value); return *this;}

    /**
     *
 List of AntipatternSeveritySummary.

     */
    inline AssessmentSummary& WithListAntipatternSeveritySummary(Aws::Vector<AntipatternSeveritySummary>&& value) { SetListAntipatternSeveritySummary(std::move(value)); return *this;}

    /**
     *
 List of AntipatternSeveritySummary.

     */
    inline AssessmentSummary& AddListAntipatternSeveritySummary(const AntipatternSeveritySummary& value) { m_listAntipatternSeveritySummaryHasBeenSet = true; m_listAntipatternSeveritySummary.push_back(value); return *this; }

    /**
     *
 List of AntipatternSeveritySummary.

     */
    inline AssessmentSummary& AddListAntipatternSeveritySummary(AntipatternSeveritySummary&& value) { m_listAntipatternSeveritySummaryHasBeenSet = true; m_listAntipatternSeveritySummary.push_back(std::move(value)); return *this; }

    /**
     *
 List of ApplicationComponentStrategySummary.

     */
    inline const Aws::Vector<StrategySummary>& GetListApplicationComponentStrategySummary() const{ return m_listApplicationComponentStrategySummary; }

    /**
     *
 List of ApplicationComponentStrategySummary.

     */
    inline bool ListApplicationComponentStrategySummaryHasBeenSet() const { return m_listApplicationComponentStrategySummaryHasBeenSet; }

    /**
     *
 List of ApplicationComponentStrategySummary.

     */
    inline void SetListApplicationComponentStrategySummary(const Aws::Vector<StrategySummary>& value) { m_listApplicationComponentStrategySummaryHasBeenSet = true; m_listApplicationComponentStrategySummary = value; }

    /**
     *
 List of ApplicationComponentStrategySummary.

     */
    inline void SetListApplicationComponentStrategySummary(Aws::Vector<StrategySummary>&& value) { m_listApplicationComponentStrategySummaryHasBeenSet = true; m_listApplicationComponentStrategySummary = std::move(value); }

    /**
     *
 List of ApplicationComponentStrategySummary.

     */
    inline AssessmentSummary& WithListApplicationComponentStrategySummary(const Aws::Vector<StrategySummary>& value) { SetListApplicationComponentStrategySummary(value); return *this;}

    /**
     *
 List of ApplicationComponentStrategySummary.

     */
    inline AssessmentSummary& WithListApplicationComponentStrategySummary(Aws::Vector<StrategySummary>&& value) { SetListApplicationComponentStrategySummary(std::move(value)); return *this;}

    /**
     *
 List of ApplicationComponentStrategySummary.

     */
    inline AssessmentSummary& AddListApplicationComponentStrategySummary(const StrategySummary& value) { m_listApplicationComponentStrategySummaryHasBeenSet = true; m_listApplicationComponentStrategySummary.push_back(value); return *this; }

    /**
     *
 List of ApplicationComponentStrategySummary.

     */
    inline AssessmentSummary& AddListApplicationComponentStrategySummary(StrategySummary&& value) { m_listApplicationComponentStrategySummaryHasBeenSet = true; m_listApplicationComponentStrategySummary.push_back(std::move(value)); return *this; }

    /**
     *
 List of ApplicationComponentSummary.

     */
    inline const Aws::Vector<ApplicationComponentSummary>& GetListApplicationComponentSummary() const{ return m_listApplicationComponentSummary; }

    /**
     *
 List of ApplicationComponentSummary.

     */
    inline bool ListApplicationComponentSummaryHasBeenSet() const { return m_listApplicationComponentSummaryHasBeenSet; }

    /**
     *
 List of ApplicationComponentSummary.

     */
    inline void SetListApplicationComponentSummary(const Aws::Vector<ApplicationComponentSummary>& value) { m_listApplicationComponentSummaryHasBeenSet = true; m_listApplicationComponentSummary = value; }

    /**
     *
 List of ApplicationComponentSummary.

     */
    inline void SetListApplicationComponentSummary(Aws::Vector<ApplicationComponentSummary>&& value) { m_listApplicationComponentSummaryHasBeenSet = true; m_listApplicationComponentSummary = std::move(value); }

    /**
     *
 List of ApplicationComponentSummary.

     */
    inline AssessmentSummary& WithListApplicationComponentSummary(const Aws::Vector<ApplicationComponentSummary>& value) { SetListApplicationComponentSummary(value); return *this;}

    /**
     *
 List of ApplicationComponentSummary.

     */
    inline AssessmentSummary& WithListApplicationComponentSummary(Aws::Vector<ApplicationComponentSummary>&& value) { SetListApplicationComponentSummary(std::move(value)); return *this;}

    /**
     *
 List of ApplicationComponentSummary.

     */
    inline AssessmentSummary& AddListApplicationComponentSummary(const ApplicationComponentSummary& value) { m_listApplicationComponentSummaryHasBeenSet = true; m_listApplicationComponentSummary.push_back(value); return *this; }

    /**
     *
 List of ApplicationComponentSummary.

     */
    inline AssessmentSummary& AddListApplicationComponentSummary(ApplicationComponentSummary&& value) { m_listApplicationComponentSummaryHasBeenSet = true; m_listApplicationComponentSummary.push_back(std::move(value)); return *this; }

    /**
     *
 List of ServerStrategySummary.

     */
    inline const Aws::Vector<StrategySummary>& GetListServerStrategySummary() const{ return m_listServerStrategySummary; }

    /**
     *
 List of ServerStrategySummary.

     */
    inline bool ListServerStrategySummaryHasBeenSet() const { return m_listServerStrategySummaryHasBeenSet; }

    /**
     *
 List of ServerStrategySummary.

     */
    inline void SetListServerStrategySummary(const Aws::Vector<StrategySummary>& value) { m_listServerStrategySummaryHasBeenSet = true; m_listServerStrategySummary = value; }

    /**
     *
 List of ServerStrategySummary.

     */
    inline void SetListServerStrategySummary(Aws::Vector<StrategySummary>&& value) { m_listServerStrategySummaryHasBeenSet = true; m_listServerStrategySummary = std::move(value); }

    /**
     *
 List of ServerStrategySummary.

     */
    inline AssessmentSummary& WithListServerStrategySummary(const Aws::Vector<StrategySummary>& value) { SetListServerStrategySummary(value); return *this;}

    /**
     *
 List of ServerStrategySummary.

     */
    inline AssessmentSummary& WithListServerStrategySummary(Aws::Vector<StrategySummary>&& value) { SetListServerStrategySummary(std::move(value)); return *this;}

    /**
     *
 List of ServerStrategySummary.

     */
    inline AssessmentSummary& AddListServerStrategySummary(const StrategySummary& value) { m_listServerStrategySummaryHasBeenSet = true; m_listServerStrategySummary.push_back(value); return *this; }

    /**
     *
 List of ServerStrategySummary.

     */
    inline AssessmentSummary& AddListServerStrategySummary(StrategySummary&& value) { m_listServerStrategySummaryHasBeenSet = true; m_listServerStrategySummary.push_back(std::move(value)); return *this; }

    /**
     *
 List of ServerSummary.

     */
    inline const Aws::Vector<ServerSummary>& GetListServerSummary() const{ return m_listServerSummary; }

    /**
     *
 List of ServerSummary.

     */
    inline bool ListServerSummaryHasBeenSet() const { return m_listServerSummaryHasBeenSet; }

    /**
     *
 List of ServerSummary.

     */
    inline void SetListServerSummary(const Aws::Vector<ServerSummary>& value) { m_listServerSummaryHasBeenSet = true; m_listServerSummary = value; }

    /**
     *
 List of ServerSummary.

     */
    inline void SetListServerSummary(Aws::Vector<ServerSummary>&& value) { m_listServerSummaryHasBeenSet = true; m_listServerSummary = std::move(value); }

    /**
     *
 List of ServerSummary.

     */
    inline AssessmentSummary& WithListServerSummary(const Aws::Vector<ServerSummary>& value) { SetListServerSummary(value); return *this;}

    /**
     *
 List of ServerSummary.

     */
    inline AssessmentSummary& WithListServerSummary(Aws::Vector<ServerSummary>&& value) { SetListServerSummary(std::move(value)); return *this;}

    /**
     *
 List of ServerSummary.

     */
    inline AssessmentSummary& AddListServerSummary(const ServerSummary& value) { m_listServerSummaryHasBeenSet = true; m_listServerSummary.push_back(value); return *this; }

    /**
     *
 List of ServerSummary.

     */
    inline AssessmentSummary& AddListServerSummary(ServerSummary&& value) { m_listServerSummaryHasBeenSet = true; m_listServerSummary.push_back(std::move(value)); return *this; }

  private:

    S3Object m_antipatternReportS3Object;
    bool m_antipatternReportS3ObjectHasBeenSet;

    AntipatternReportStatus m_antipatternReportStatus;
    bool m_antipatternReportStatusHasBeenSet;

    Aws::String m_antipatternReportStatusMessage;
    bool m_antipatternReportStatusMessageHasBeenSet;

    Aws::Utils::DateTime m_lastAnalyzedTimestamp;
    bool m_lastAnalyzedTimestampHasBeenSet;

    Aws::Vector<AntipatternSeveritySummary> m_listAntipatternSeveritySummary;
    bool m_listAntipatternSeveritySummaryHasBeenSet;

    Aws::Vector<StrategySummary> m_listApplicationComponentStrategySummary;
    bool m_listApplicationComponentStrategySummaryHasBeenSet;

    Aws::Vector<ApplicationComponentSummary> m_listApplicationComponentSummary;
    bool m_listApplicationComponentSummaryHasBeenSet;

    Aws::Vector<StrategySummary> m_listServerStrategySummary;
    bool m_listServerStrategySummaryHasBeenSet;

    Aws::Vector<ServerSummary> m_listServerSummary;
    bool m_listServerSummaryHasBeenSet;
  };

} // namespace Model
} // namespace MigrationHubStrategyRecommendations
} // namespace Aws


text:
__author__ = 'thorsteinn'

def drop_ships_by_key_value(key_to_check, value_to_check, db):
    """
    Steady method for dropping db entries using a key:value requirement
    :param key_to_check:
    :param value_to_check:
    :param db:
    :return: alters the db in place
    """
    ships = db.keys()
    for ship in ships:
        ship_db = db[ship]
        if ship_db[key_to_check] is value_to_check:
            del(db[ship])


text:
"""
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you 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.

"""

from resource_management.libraries.resources.hdfs_resource import HdfsResource
from resource_management.libraries.functions.default import default
from resource_management.libraries.functions.get_not_managed_resources import get_not_managed_resources
from resource_management.libraries.functions import conf_select
from resource_management.libraries.functions import stack_select
from resource_management.libraries.functions import get_kinit_path
from resource_management.libraries.script.script import Script

import functools

#for create_hdfs_directory

# server configurations
config = Script.get_config()

hadoop_bin_dir = stack_select.get_hadoop_dir("bin")
hadoop_conf_dir = conf_select.get_hadoop_conf_dir()

security_enabled = config['configurations']['cluster-env']['security_enabled']
kinit_path_local = get_kinit_path(default('/configurations/kerberos-env/executable_search_paths', None))
hostname = config["hostname"]
hdfs_user_keytab = config['configurations']['hadoop-env']['hdfs_user_keytab']
hdfs_user = config['configurations']['hadoop-env']['hdfs_user']
hdfs_principal_name = config['configurations']['hadoop-env']['hdfs_principal_name']
hdfs_site = config['configurations']['hdfs-site']
default_fs = config['configurations']['core-site']['fs.defaultFS']
dfs_type = default("/commandParams/dfs_type", "")

# create partial functions with common arguments for every HdfsResource call
# to create hdfs directory we need to import this and call HdfsResource in code

HdfsResource = functools.partial(
 HdfsResource,
  hdfs_resource_ignore_file = "/var/lib/ambari-agent/data/.hdfs_resource_ignore",
  security_enabled = security_enabled,
  user = hdfs_user,
  keytab = hdfs_user_keytab,
  kinit_path_local = kinit_path_local,
  hadoop_bin_dir = hadoop_bin_dir,
  hadoop_conf_dir = hadoop_conf_dir,
  principal_name = hdfs_principal_name,
  hdfs_site = hdfs_site,
  default_fs = default_fs,
  immutable_paths = get_not_managed_resources(),
  dfs_type = dfs_type
 )


text:
from __future__ import absolute_import

from datetime import timedelta

from libtaxii.common import generate_message_id
from libtaxii.constants import *
import libtaxii.messages_10 as tm10
import libtaxii.messages_11 as tm11

from taxii_services import handlers, models
from taxii_services.exceptions import StatusMessageException
from taxii_services.util import PollRequestProperties

from .base_handlers import BaseMessageHandler

class PollRequest11Handler(BaseMessageHandler):
    """
    Built-in TAXII 1.1 Poll Request Handler.

    This handler has multiple extension points for developers
    who want to extend and/or customize this class.
    """

    supported_request_messages = [tm11.PollRequest]
    version = "1"

    @classmethod
    def get_content(cls, prp, query_kwargs):
        """
        Given a poll_params_dict get content from the database.

        Arguments:
            prp (util.PollRequestProperties) - Not used in this function, \
                    but can be used by implementers extending this function.
            query_kwargs (dict) - The parameters of the search for content

        Returns:
            An list of models.ContentBlock objects. Classes that override \
            this method only need to return an iterable where each class has \
            a 'to_content_block_11()' function.
        """
        content = prp.collection.content_blocks.filter(**query_kwargs).order_by('timestamp_label')

        return content

    @classmethod
    def create_poll_response(cls, poll_service, prp, content):
        """
        Creates a poll response.

        1. If the request's response type is "Count Only",
        a single poll response w/ more=False used.
        2. If the content size is less than the poll_service's
        max_result_size, a poll response w/ more=False is used.
        3. If the poll_service's max_result_size is blank,
        a poll response w/ more=False used.
        4. If the response type is "Full" and the total
        number of contents are greater than the
        poll_service's max_result_size, a ResultSet
        is created, and a PollResponse w/more=True is used.
        """

        content_count = len(content)

        # RT_COUNT_ONLY - Always use a single result
        # RT_FULL - Use a single response if
        #           poll_service.max_result_size is None or
        #           len(content) <= poll_service.max_result_size
        #           Use a Multi-Part response otherwise

        if (prp.response_type == RT_COUNT_ONLY or
            poll_service.max_result_size is None or
            content_count <= poll_service.max_result_size):

            poll_response = tm11.PollResponse(message_id=generate_message_id(),
                                              in_response_to=prp.message_id,
                                              collection_name=prp.collection.name,
                                              result_part_number=1,
                                              more=False,
                                              exclusive_begin_timestamp_label=prp.exclusive_begin_timestamp_label,
                                              inclusive_end_timestamp_label=prp.inclusive_end_timestamp_label,
                                              record_count=tm11.RecordCount(content_count, False))
            if prp.subscription:
                    poll_response.subscription_id = prp.subscription.subscription_id

            if prp.response_type == RT_FULL:
                for c in content:
                    poll_response.content_blocks.append(c.to_content_block_11())
        else:
            # Split into multiple result sets
            result_set = handlers.create_result_set(poll_service, prp, content)
            rsp_1 = models.ResultSetPart.objects.get(result_set__pk=result_set.pk, part_number=1)
            poll_response = rsp_1.to_poll_response_11(prp.message_id)
            result_set.last_part_returned = rsp_1
            result_set.save()
            response = poll_response

        return poll_response

    @classmethod
    def create_pending_response(cls, poll_service, prp, content):
        """
        Arguments:
            poll_service (models.PollService) - The TAXII Poll Service being invoked
            prp (util.PollRequestProperties) - The Poll Request Properties of the Poll Request
            content - A list of content (nominally, models.ContentBlock objects).

        This method returns a StatusMessage with a Status Type
        of Pending OR raises a StatusMessageException
        based on the following table::

            asynch | Delivery_Params | can_push || Response Type
            ----------------------------------------------------
            True   | -               | -        || Pending - Asynch
            False  | Yes             | Yes      || Pending - Push
            False  | Yes             | No       || StatusMessageException
            False  | No              | -        || StatusMessageException
        """

        # Identify the Exception conditions first (e.g., rows #3 and #4)
        if (prp.allow_asynch is False and
            (prp.delivery_parameters is None or prp.can_push is False)):

            raise StatusMessageException(prp.message_id,
                                         ST_FAILURE,
                                         "The content was not available now and \
                                         the request had allow_asynch=False and no \
                                         Delivery Parameters were specified.")

        # Rows #1 and #2 are both Status Messages with a type of Pending
        result_set = cls.create_result_set(content, prp, poll_service)
        sm = tm11.StatusMessage(message_id=generate_message_id(),
                                in_response_to=prp.message_id,
                                status_type=ST_PENDING)
        if prp.allow_asynch:
            sm.status_details = {SD_ESTIMATED_WAIT: 300, SD_RESULT_ID: result_set.pk, SD_WILL_PUSH: False}
        else:
            # TODO: Check and see if the requested delivery parameters are supported
            sm.status_details = {SD_ESTIMATED_WAIT: 300, SD_RESULT_ID: result_set.pk, SD_WILL_PUSH: True}
            # TODO: Need to try pushing or something.
        return sm

    @classmethod
    def handle_message(cls, poll_service, poll_request, django_request):
        """
        Handles a TAXII 1.1 Poll Request.

        Workflow:
            1. Create a util.PollRequestProperties object from the tm11.PollRequest
            2. If a Query Handler exists, call the `QueryHandler.update_db_kwargs( ... )`
               method of the Query Handler. This allows the QueryHandler a hook to modify the
               database query arguments before the query is sent do the database.
            3. Call `content = cls.get_content(PollRequestProperties, db_kwargs)`, which returns a list of
               objects, each of which must have a `to_content_block_11()` function.
            4. If a Query Handler exists, call the `QueryHandler.filter_content( ... )`
               function. This allows the QueryHandler a hook to modify the results after they have been returned
               from the database, but before they are returned to the requestor.
            5. If the results are available "now", return the result of calling
               `create_poll_response`.
            6. (Experimental) If the results are not available "now", return the result
                of calling `create_pending_response`.
        """
        # Populate a PollRequestProperties object from the poll request
        # A lot of magic happens in this function call
        prp = PollRequestProperties.from_poll_request_11(poll_service, poll_request)
        supported_query = prp.supported_query

        # Get the kwargs to search the DB with
        db_kwargs = prp.get_db_kwargs()

        # If a query handler exists, allow it to
        # inject kwargs
        if supported_query is not None:
            supported_query.query_handler.get_handler_class().update_db_kwargs(prp, db_kwargs)

        # Get content from the database.
        # content MUST be an iterable where each
        # object has a `to_content_block_11()` function
        content_blocks = cls.get_content(prp, db_kwargs)

        # If there is a query handler,
        # allow it do to post-dbquery filtering
        if supported_query:
            content_blocks = supported_query.query_handler.get_handler_class().filter_content(prp, content_blocks)

        # The way this handler is written, this will never be false
        results_available = True  # TODO: Can this flag be usefully implemented?

        if results_available:
            response = cls.create_poll_response(poll_service, prp, content_blocks)
        else:
            response = cls.create_pending_response(poll_service, prp, content_blocks)

        return response

class PollRequest10Handler(BaseMessageHandler):
    """
    Built-in TAXII 1.0 Poll Request Handler
    """
    supported_request_messages = [tm10.PollRequest]
    version = "1"

    @classmethod
    def get_content(cls, prp, query_kwargs):
        """

        :param prp: PollRequestProperties
        :param query_kwargs: The parameters of the search for content
        :return: A list of models.ContentBlock objects. Classes that override this  \
                 method only need to return an iterable where each instance has a \
                 'to_content_block_10()' function.
        """
        content = prp.collection.content_blocks.filter(**query_kwargs).order_by('timestamp_label')

        return content

    @classmethod
    def create_poll_response(cls, poll_service, prp, content_blocks):
        """

        :param poll_service:
        :param prp:
        :param content_blocks:
        :return:
        """

        ietl = prp.exclusive_begin_timestamp_label
        if ietl is not None:
            ietl += timedelta(milliseconds=1)

        pr = tm10.PollResponse(message_id=generate_message_id(),
                               in_response_to=prp.message_id,
                               feed_name=prp.collection.name,
                               inclusive_begin_timestamp_label=ietl,
                               inclusive_end_timestamp_label=prp.inclusive_end_timestamp_label)

        for content_block in content_blocks:
            pr.content_blocks.append(content_block.to_content_block_10())

        return pr

    @classmethod
    def handle_message(cls, poll_service, poll_message, django_request):
        """
        TODO: This isn't tested
        """
        prp = PollRequestProperties.from_poll_request_10(poll_service, poll_message)
        query_kwargs = prp.get_db_kwargs()
        content_blocks = cls.get_content(prp, query_kwargs)
        response = cls.create_poll_response(poll_service, prp, content_blocks)
        return response

class PollRequestHandler(BaseMessageHandler):
    """
    Built-in TAXII 1.1 and TAXII 1.0 Poll Request Handler
    """

    supported_request_messages = [tm10.PollRequest, tm11.PollRequest]
    version = "1"

    @staticmethod
    def handle_message(poll_service, poll_request, django_request):
        """
        Passes the request to either PollRequest10Handler or PollRequest11Handler
        """
        if isinstance(poll_request, tm10.PollRequest):
            return PollRequest10Handler.handle_message(poll_service, poll_request, django_request)
        elif isinstance(poll_request, tm11.PollRequest):
            return PollRequest11Handler.handle_message(poll_service, poll_request, django_request)
        else:
            raise StatusMessageException(poll_request.message_id,
                                         ST_FAILURE,
                                         "TAXII Message not supported by Message Handler.")


text:
.. meta::
   :description: pydoit is a generic tool based on build-tool concepts. Flexible and scalable.
   :keywords: python, doit, CLI, linux, windows, task-runner, build-tool, pipeline, workflow, incremental build, data pipeline

.. title:: pydoit use cases - from CLI task-runner to complex pipelines

=========
Use Cases
=========

Here are some use cases, where `doit` can help you with automation of your tasks.

Simplify cumbersome command line calls
======================================

Do you have to repeatedly call complex command like this?

.. code-block:: console

    $ aws s3 sync _built/html s3://buck/et --exclude "*" --include "*.html"

Wrap it into `dodo.py` file:

.. code-block:: python

    def task_publish():
      """Publish to AWS S3"""
      return {
        "actions": [
            'aws s3 sync _built/html s3://buck/et --exclude "*" --include "*.html"'
        ]
      }

and next time just:

.. code-block:: console

    $ doit publish

It is easy to include multiple actions into one task or use multiple tasks.

Automate typical project related actions
========================================

Do you have to lint your code, run test suite, evaluate coverage,
generate documentation incl. spelling?

Create the `dodo.py`, which defines tasks you have to do and next time:

.. code-block:: console

    $ doit list
    coverage          show coverage for all modules including tests
    coverage_module   show coverage for individual modules
    coverage_src      show coverage for all modules (exclude tests)
    package           create/upload package to pypi
    pyflakes
    pypi              create/upload package to pypi
    spell             spell checker for doc files
    sphinx            build sphinx docs
    tutorial_check    check tutorial sample are at least runnable without error
    ut                run unit-tests
    website           dodo file create website html files
    website_update    update website on SITE_PATH

and then decide which task to run:

.. code-block:: console

    $ doit spell

Share unified way of doing things
=================================

Do you expect your colleagues perform the same steps before committing
changes to repository? What to do with the complains the steps are too complex?

Provide them with the `dodo.py` file doing the things. What goes easy,
is more likely to be used.

`dodo.py` will become easy to use prescription of best practices.

Optimize processing time by skipping tasks already done
=======================================================

You dump your database and convert the data to CSV. It takes minutes,
but often the input is the same as before. Why to do things already
done and wait?

Wrap the conversion into `doit` task and `doit` will automatically
detect, the input and output are already in sync and complete in
fraction of a second, when possible.

Manage complex set of depending tasks
=====================================

The system you code shall do many small actions, which are interdependent.

Split it into small tasks, define (file) dependencies and let `doit`
do the planning of what shall be processed first and what next.

Your solution will be clean and modular.

Speed up by parallel task execution
===================================
You already have bunch of tasks defined, results are correct, it only takes so
much time. But wait, you have multi-core machine!

Just ask for parallel processing:

.. code-block:: console

   $ doit -n 4

and `doit` will take care of planning and make all your CPU cores hot.

No need to rewrite your processing from scratch, properly declared tasks is all
what you have to provide.

Extend your project by doit features
====================================
Your own python project would need features of `doit`, but you cannot ask your users to call `doit` on command line?

Simply integrate `doit` functionality into your own command line tool and nobody will notice where it comes from.

Create cross-platform tool for processing  your stuff
=====================================================
Do you have team members working on MS Windows and others on Linux?

Scripts are great, but all those small shell differences prevent
single reusable solution.

With `dodo.py` and python you are more likely to write the processing
in cross-platform way. Use `pathlib.Path` and `shutils` magic to
create directories, move files around, copy them, etc.


text:
/**
 * Helper utility functions for QueryBuilder.
 */
export declare class QueryBuilderUtils {
    /**
     * Checks if given value is a string representation of alias property,
     * e.g. "post.category" or "post.id".
     */
    static isAliasProperty(str: any): str is string;
}


text:
var Transform = require("stream").Transform;

// == Exports ==================================================================
module.exports = function (iconv) {

    // Additional Public API.
    iconv.encodeStream = function encodeStream(encoding, options) {
        return new IconvLiteEncoderStream(iconv.getCodec(encoding).encoder(options), options);
    }

    iconv.decodeStream = function decodeStream(encoding, options) {
        return new IconvLiteDecoderStream(iconv.getCodec(encoding).decoder(options), options);
    }

    iconv.supportsStreams = true;

    // Not published yet.
    iconv.IconvLiteEncoderStream = IconvLiteEncoderStream;
    iconv.IconvLiteDecoderStream = IconvLiteDecoderStream;
    iconv._collect = IconvLiteDecoderStream.prototype.collect;
};

// == Encoder stream =======================================================
function IconvLiteEncoderStream(conv, options) {
    this.conv = conv;
    options = options || {};
    options.decodeStrings = false; // We accept only strings, so we don't need to decode them.
    Transform.call(this, options);
}

IconvLiteEncoderStream.prototype = Object.create(Transform.prototype, {
    constructor: { value: IconvLiteEncoderStream }
});

IconvLiteEncoderStream.prototype._transform = function (chunk, encoding, done) {
    if (typeof chunk != 'string')
        return done(new Error("Iconv encoding stream needs strings as its input."));
    try {
        var res = this.conv.write(chunk);
        if (res && res.length) this.push(res);
        done();
    }
    catch (e) {
        done(e);
    }
}

IconvLiteEncoderStream.prototype._flush = function (done) {
    try {
        var res = this.conv.end();
        if (res && res.length) this.push(res);
        done();
    }
    catch (e) {
        done(e);
    }
}

IconvLiteEncoderStream.prototype.collect = function (cb) {
    var chunks = [];
    this.on('error', cb);
    this.on('data', function (chunk) {
        chunks.push(chunk);
    });
    this.on('end', function () {
        cb(null, Buffer.concat(chunks));
    });
    return this;
}

// == Decoder stream =======================================================
function IconvLiteDecoderStream(conv, options) {
    this.conv = conv;
    options = options || {};
    options.encoding = this.encoding = 'utf8'; // We output strings.
    Transform.call(this, options);
}

IconvLiteDecoderStream.prototype = Object.create(Transform.prototype, {
    constructor: { value: IconvLiteDecoderStream }
});

IconvLiteDecoderStream.prototype._transform = function (chunk, encoding, done) {
    if (!Buffer.isBuffer(chunk))
        return done(new Error("Iconv decoding stream needs buffers as its input."));
    try {
        var res = this.conv.write(chunk);
        if (res && res.length) this.push(res, this.encoding);
        done();
    }
    catch (e) {
        done(e);
    }
}

IconvLiteDecoderStream.prototype._flush = function (done) {
    try {
        var res = this.conv.end();
        if (res && res.length) this.push(res, this.encoding);
        done();
    }
    catch (e) {
        done(e);
    }
}

IconvLiteDecoderStream.prototype.collect = function (cb) {
    var res = '';
    this.on('error', cb);
    this.on('data', function (chunk) {
        res += chunk;
    });
    this.on('end', function () {
        cb(null, res);
    });
    return this;
}


text:
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "pit.h"

static void action_list()
{
    pit_db_load();
    if (actions->number_of_records > 0) {
        PFormat pf = pit_format_initialize(FORMAT_ACTION, 0, actions->number_of_records);
        for_each_action(pa) {
            pit_format(pf, (char *)pa);
        }
        pit_format_flush(pf);
    }
}

void pit_action(PAction pa)
{
    if (pa) {
        strncpy(pa->username, current_user(), sizeof(pa->username) - 1);
        pit_table_insert(actions, (char *)pa);
        if (pa->project_id || pa->task_id || pa->note_id)
            puts(pa->message);
    }
}

void pit_log(char *argv[])
{
    action_list();
}


text:
////////////////////////////////////////////////////////////////////////////////
//
// CoinNodeData.h
//
// Copyright (c) 2011-2014 Eric Lombrozo
// Copyright (c) 2011-2016 Ciphrex Corp.
//
// Distributed under the MIT software license, see the accompanying
// file LICENSE or http://www.opensource.org/licenses/mit-license.php.
//

#pragma once

#include "hash.h"
#include "IPv6.h"
#include "MerkleTree.h"

#include "BigInt.h"

#include <stdutils/uchar_vector.h>

#include <functional>
#include <list>
#include <queue>

#include <stdio.h>
#include <cstring>
#include <unistd.h>
#include <stdint.h>
#include <sstream>
#include <time.h>

void SetAddressVersion(unsigned char version);
void SetMultiSigAddressVersion(unsigned char version);

#define NODE_NETWORK                  1

#define MSG_ERROR                     0
#define MSG_TX                        1
#define MSG_BLOCK                     2
#define MSG_FILTERED_BLOCK            3
#define MSG_WITNESS_BLOCK             4
#define MSG_WITNESS_TX                5

const uint32_t MSG_WITNESS_FLAG     = 1 << 30;
const uint32_t MSG_TYPE_MASK        = 0xffffffff >> 2;

#define MIN_VAR_INT_SIZE              1
#define MIN_VAR_STR_SIZE              1
#define MIN_NETWORK_ADDRESS_SIZE     26
#define MIN_MESSAGE_HEADER_SIZE      24
#define MIN_VERSION_MESSAGE_SIZE     84
#define MIN_ADDR_MESSAGE_SIZE        31
#define MIN_INVENTORY_ITEM_SIZE      36
#define MIN_GET_BLOCKS_SIZE          69
#define MIN_GET_HEADERS_SIZE         65
#define MIN_OUT_POINT_SIZE           36
#define MIN_TX_IN_SIZE               41
#define MIN_TX_OUT_SIZE               9
//#define MIN_TRANSACTION_SIZE         59
#define MIN_TRANSACTION_SIZE         10 // blank transaction
#define MIN_COIN_BLOCK_HEADER_SIZE   80
#define MIN_COIN_BLOCK_SIZE         140
#define MIN_MERKLE_BLOCK_SIZE        86
#define MIN_FILTER_LOAD_SIZE         10

#define BLOOM_UPDATE_NONE             0
#define BLOOM_UPDATE_ALL              1
#define BLOOM_UPDATE P2PUBKEY_ONLY    2
#define BLOOM_UPDATE_MASK             3

const char* itemTypeToString(uint itemType);

std::string timeToString(time_t time);

std::string blankSpaces(uint n);

std::string satoshisToBtcString(uint64_t satoshis, bool trailing_zeros = true);

extern uchar_vector g_zero32bytes;

namespace Coin
{

enum HashType
{
    SIGHASH_ALL             = 0x01,
    SIGHASH_NONE            = 0x02,
    SIGHASH_SINGLE          = 0x03,
    SIGHASH_ANYONECANPAY    = 0x80
};

typedef std::function<uchar_vector(const uchar_vector&)> hashfunc_t;

class CoinNodeStructure
{
public:
    CoinNodeStructure() : isHashSet_(false) { }

    virtual ~CoinNodeStructure() { }

    virtual const char* getCommand() const = 0;
    virtual uint64_t getSize() const = 0;

    virtual const uchar_vector& getHash() const;
    virtual const uchar_vector& getHashLittleEndian() const;

    virtual const uchar_vector& getHash(hashfunc_t hashfunc) const;
    virtual const uchar_vector& getHashLittleEndian(hashfunc_t hashfunc) const;

    virtual uint32_t getChecksum() const; // 4 least significant bytes, little endian

    virtual uchar_vector getSerialized() const = 0;
    virtual void setSerialized(const uchar_vector& bytes) = 0;

    virtual std::string toString() const = 0;
    virtual std::string toIndentedString(uint spaces = 0) const = 0;

protected:
    mutable uchar_vector hash_;
    mutable uchar_vector hashLittleEndian_;
    mutable bool isHashSet_;
};

class VarInt : public CoinNodeStructure
{
public:
    uint64_t value;

    VarInt() { }
    VarInt(const VarInt& rhs) { this->value = rhs.value; }
    VarInt(uint64_t value) { this->value = value; }
    VarInt(const uchar_vector& bytes) { this->setSerialized(bytes); }

    VarInt& operator=(uint64_t value) { this->value = value; return *this; }

    const char* getCommand() const { return ""; }
    uint64_t getSize() const;
    uchar_vector getSerialized() const;
    void setSerialized(const uchar_vector& bytes);

    std::string toString() const
    {
        std::stringstream ss;
        ss << value;
        return ss.str();
    }
    std::string toIndentedString(uint spaces = 0) const { return blankSpaces(spaces) + this->toString(); }
};

class VarString : public CoinNodeStructure
{
public:
    std::string value;

    VarString() { }
    VarString(const VarString& rhs) { this->value = rhs.value; }
    VarString(const std::string& value) { this->value = value; }
    VarString(const char* value) { this->value = value; }
    VarString(const uchar_vector& bytes) { this->setSerialized(bytes); }

    VarString& operator=(const char* value) { this->value = value; return *this;}
    VarString& operator=(const std::string& value) { this->value = value; return *this; }

    const char* getCommand() const { return ""; }
    uint64_t getSize() const;
    uchar_vector getSerialized() const;
    void setSerialized(const uchar_vector& bytes);

    std::string toString() const { return value; }
    std::string toIndentedString(uint spaces = 0) const { return blankSpaces(spaces) + this->value; }
};

class NetworkAddress : public CoinNodeStructure
{
public:
    uint32_t time;
    uint64_t services;
    IPv6Address ipv6;
    uint16_t port;
    bool hasTime;

    NetworkAddress() { }
    NetworkAddress(uint32_t time, uint64_t services, unsigned char ipv6_bytes[], uint16_t port);
    NetworkAddress(uint64_t services, const unsigned char ipv6_bytes[], uint16_t port);
    NetworkAddress(const NetworkAddress& netaddr);
    NetworkAddress(const uchar_vector& bytes) { this->setSerialized(bytes); }

    void set(uint64_t services, const unsigned char ipv6_bytes[], uint16_t port);

    const char* getCommand() const { return ""; }
    uint64_t getSize() const { return hasTime ? 30 : 26; }
    uchar_vector getSerialized() const;
    void setSerialized(const uchar_vector& bytes);

    std::string getName() const;

    std::string toString() const;
    std::string toIndentedString(uint spaces = 0) const;

    void setTime(uint32_t time) { this->time = time; this->hasTime = true; }
};

class MessageHeader : public CoinNodeStructure
{
public:
    MessageHeader() : hasChecksum(true) { }
    MessageHeader(uint32_t magic, const char* command, uint32_t length); // no checksum
    MessageHeader(uint32_t magic, const char* command, uint32_t length, uint32_t checksum);
    MessageHeader(const MessageHeader&);
    MessageHeader(const uchar_vector& bytes) { this->setSerialized(bytes); }

    const char* getCommand() const { return ""; }
    uint64_t getSize() const { return hasChecksum ? 24 : 20; }
    uchar_vector getSerialized() const;
    void setSerialized(const uchar_vector& bytes);

    std::string toString() const;
    std::string toIndentedString(uint spaces = 0) const;

    void removeChecksum() { hasChecksum = false; }
    uint32_t magic;
    char command[12];
    uint32_t length;
    uint32_t checksum;
    bool hasChecksum;

};

// Full message: header + payload
class CoinNodeMessage : public CoinNodeStructure
{
public:
    MessageHeader header;
    CoinNodeStructure* pPayload;

public:
    CoinNodeMessage(const CoinNodeMessage& message) { this->setMessage(message.header.magic, message.pPayload); }
    CoinNodeMessage(uint32_t magic, CoinNodeStructure* pPayload) { this->setMessage(magic, pPayload); }
    CoinNodeMessage(const uchar_vector& bytes) { this->pPayload = NULL; this->setSerialized(bytes); }
    ~CoinNodeMessage();

    void setMessage(uint32_t magic, CoinNodeStructure* pPayload);

    const char* getCommand() const { return this->pPayload->getCommand(); }
    uint64_t getSize() const;
    uchar_vector getSerialized() const;
    void setSerialized(const uchar_vector& bytes);

    std::string toString() const;
    std::string toIndentedString(uint spaces = 0) const;

    bool isChecksumValid() const;

    MessageHeader getHeader() const { return header; }
    CoinNodeStructure* getPayload() const { return pPayload; }
};

class VersionMessage : public CoinNodeStructure
{
public:
    VersionMessage () { }
    VersionMessage(
        int32_t version,
        uint64_t services,
        int64_t timestamp,
        const NetworkAddress& recipientAddress,
        const NetworkAddress& senderAddress,
        uint64_t nonce,
        const char* subVersion,
        int32_t startHeight,
        bool relay = true
    );
    VersionMessage(const uchar_vector bytes) { this->setSerialized(bytes); }

    int32_t version() const { return version_; }
    uint64_t services() const { return services_; }
    int64_t timestamp() const { return timestamp_; }
    const NetworkAddress& recipientAddress() const { return recipientAddress_; }
    const NetworkAddress& senderAddress() const { return senderAddress_; }
    uint64_t nonce() const { return nonce_; }
    const VarString& subVersion() const { return subVersion_; }
    int32_t startHeight() const { return startHeight_; }
    bool relay() const { return relay_; }

    const char* getCommand() const { return "version"; }
    uint64_t getSize() const;
    uchar_vector getSerialized() const;
    void setSerialized(const uchar_vector& bytes);

    std::string toString() const;
    std::string toIndentedString(uint spaces = 0) const;

private:
    int32_t version_;
    uint64_t services_;
    int64_t timestamp_;
    NetworkAddress recipientAddress_;
    NetworkAddress senderAddress_;
    uint64_t nonce_;
    VarString subVersion_;
    int32_t startHeight_;
    bool relay_;
};

class BlankMessage : public CoinNodeStructure
{
public:
    std::string command;

    BlankMessage(const std::string& _command) : command(_command) { }

    const char* getCommand() const { return this->command.c_str(); }
    uint64_t getSize() const { return 0; }

    uchar_vector getSerialized() const { uchar_vector rval; return rval; }
    void setSerialized(const uchar_vector& /*bytes*/) { }

    std::string toString() const { return ""; }
    std::string toIndentedString(uint spaces = 0) const { return blankSpaces(spaces); }
};

class VerackMessage : public CoinNodeStructure
{
public:
    VerackMessage() { }

    const char* getCommand() const { return "verack"; }
    uint64_t getSize() const { return 0; }

    uchar_vector getSerialized() const { uchar_vector rval; return rval; }
    void setSerialized(const uchar_vector& /*bytes*/) { }

    std::string toString() const { return ""; }
    std::string toIndentedString(uint spaces = 0) const { return blankSpaces(spaces); }
};

class AddrMessage : public CoinNodeStructure
{
public:
    std::vector<NetworkAddress> addrList;

    AddrMessage(const std::vector<NetworkAddress> addrList) { this->addrList = addrList; }
    AddrMessage(const uchar_vector& bytes) { this->setSerialized(bytes); }

    const char* getCommand() const { return "addr"; }
    uint64_t getSize() const { return VarInt(this->addrList.size()).getSize() + 30*this->addrList.size(); }

    uchar_vector getSerialized() const;
    void setSerialized(const uchar_vector& bytes);

    std::string toString() const;
    std::string toIndentedString(uint spaces = 0) const;
};

class InventoryItem : public CoinNodeStructure
{
public:
    uint32_t itemType;
    unsigned char hash[32];

    InventoryItem() { }
    InventoryItem(const uchar_vector& bytes) { this->setSerialized(bytes); }
    InventoryItem(const InventoryItem& item)
    {
        this->itemType = item.itemType;
        memcpy(this->hash, item.hash, 32);
    }
    InventoryItem(uint32_t itemType, const unsigned char* hash)
    {
        this->itemType = itemType;
        memcpy(this->hash, hash, 32);
    }
    InventoryItem(uint32_t itemType, const uchar_vector& hashBytes)
    {
        this->itemType = itemType;
        memcpy(this->hash, (unsigned char*)&hashBytes[0], 32);
    }
    InventoryItem(uint32_t itemType, const std::string& hashHex)
    {
        this->itemType = itemType;
        uchar_vector hashBytes;
        hashBytes.setHex(hashHex);
        hashBytes.padRight(0, 32);
        hashBytes.reverse();
        memcpy(this->hash, &hashBytes[0], 32);
    }

    const char* getCommand() const { return ""; }
    uint64_t getSize() const { return 36; }
    uchar_vector getSerialized() const;
    void setSerialized(const uchar_vector& bytes);

    std::string toString() const;
    std::string toIndentedString(uint spaces = 0) const;

    uint getType() const { return itemType; }
    uchar_vector getItemHash() const { return uchar_vector(hash, 32); }
};

class Inventory : public CoinNodeStructure
{
public:
    std::vector<InventoryItem> items;

    Inventory() { }
    Inventory(const std::vector<InventoryItem> items) { this->items = items; }
    Inventory(const uchar_vector& bytes) { this->setSerialized(bytes); }
    Inventory(const Inventory& inv) { this->items = inv.getItems(); }

    void addItem(const InventoryItem& item) { (this->items).push_back(item); }
    void addItem(uint itemType, const uchar_vector& hashBytes) { this->addItem(InventoryItem(itemType, hashBytes)); }

    std::vector<InventoryItem> getItems() const { return items; }
    uint getCount() const { return (this->items).size(); }

    const char* getCommand() const { return "inv"; }
    uint64_t getSize() const { return VarInt(this->items.size()).getSize() + 36*this->items.size(); }
    uchar_vector getSerialized() const;
    void setSerialized(const uchar_vector& bytes);

    std::string toString() const;
    std::string toIndentedString(uint spaces = 0) const;
};

class GetDataMessage : public Inventory
{
public:
    GetDataMessage() { }
    GetDataMessage(const std::vector<InventoryItem> items) { this->items = items; }
    GetDataMessage(const uchar_vector& bytes) { this->setSerialized(bytes); }
    GetDataMessage(const Inventory& inv) { this->items = inv.getItems(); }

    const char* getCommand() const { return "getdata"; }

    void toFilteredBlocks() { for (auto& item: this->items) { if (item.itemType == MSG_BLOCK) item.itemType = MSG_FILTERED_BLOCK; } }
};

class NotFoundMessage : public Inventory
{
public:
    NotFoundMessage() { }
    NotFoundMessage(const std::vector<InventoryItem> items) { this->items = items; }
    NotFoundMessage(const uchar_vector& bytes) { this->setSerialized(bytes); }
    NotFoundMessage(const Inventory& inv) { this->items = inv.getItems(); }

    const char* getCommand() const { return "getdata"; }
};

/*
class GetDataMessage : public CoinNodeStructure
{
public:
    std::vector<InventoryItem> items;

    GetDataMessage() { }
    GetDataMessage(const std::vector<InventoryItem> items) { this->items = items; }
    GetDataMessage(const uchar_vector& bytes) { this->setSerialized(bytes); }
    GetDataMessage(const Inventory& inv) { this->items = inv.getItems(); }

    void addItem(const InventoryItem& item) { (this->items).push_back(item); }
    void addItem(uint itemType, const uchar_vector& hashBytes) { this->addItem(InventoryItem(itemType, hashBytes)); }

    std::vector<InventoryItem> getItems() const { return items; }
    uint getCount() const { return (this->items).size(); }

    const char* getCommand() const { return "getdata"; }
    uint64_t getSize() const { return VarInt(this->items.size()).getSize() + 36*this->items.size(); }
    uchar_vector getSerialized() const;
    void setSerialized(const uchar_vector& bytes);

    std::string toString() const;
    std::string toIndentedString(uint spaces = 0) const;
};
*/
class GetBlocksMessage : public CoinNodeStructure
{
public:
    uint32_t version;
    std::vector<uchar_vector> blockLocatorHashes;
    uchar_vector hashStop;

    GetBlocksMessage() { this->hashStop = g_zero32bytes; }
    GetBlocksMessage(const GetBlocksMessage& getBlocksMessage)
    {
        this->version = getBlocksMessage.version;
        this->blockLocatorHashes = getBlocksMessage.blockLocatorHashes;
        this->hashStop = getBlocksMessage.hashStop;
    }
    GetBlocksMessage(const uchar_vector& bytes) { this->setSerialized(bytes); }
    GetBlocksMessage(uint32_t version, const std::vector<uchar_vector>& blockLocatorHashes, const uchar_vector& hashStop = g_zero32bytes)
    {
        this->version = version;
        this->blockLocatorHashes = blockLocatorHashes;
        this->hashStop = hashStop;
    }
    GetBlocksMessage(const std::string& hex);

    const char* getCommand() const { return "getblocks"; }
    uint64_t getSize() const { return VarInt(this->blockLocatorHashes.size()).getSize() + 32*this->blockLocatorHashes.size() + 36; }
    uchar_vector getSerialized() const;
    void setSerialized(const uchar_vector& bytes);

    std::string toString() const;
    std::string toIndentedString(uint spaces = 0) const;

    void addHashStart(const uchar_vector& hashStart) { this->blockLocatorHashes.push_back(hashStart); }
    void setHashStop(const uchar_vector& hashStop) { this->hashStop = hashStop; }
};

class GetHeadersMessage : public CoinNodeStructure
{
public:
    uint32_t version;
    std::vector<uchar_vector> blockLocatorHashes;
    uchar_vector hashStop;

    GetHeadersMessage() { this->hashStop = g_zero32bytes; }
    GetHeadersMessage(const GetHeadersMessage& getHeadersMessage)
    {
        this->version = getHeadersMessage.version;
        this->blockLocatorHashes = getHeadersMessage.blockLocatorHashes;
        this->hashStop = getHeadersMessage.hashStop;
    }
    GetHeadersMessage(const uchar_vector& bytes) { this->setSerialized(bytes); }
    GetHeadersMessage(uint32_t version, const std::vector<uchar_vector>& blockLocatorHashes, const uchar_vector& hashStop = g_zero32bytes)
    {
        this->version = version;
        this->blockLocatorHashes = blockLocatorHashes;
        this->hashStop = hashStop;
    }

    const char* getCommand() const { return "getheaders"; }
    uint64_t getSize() const { return VarInt(this->blockLocatorHashes.size()).getSize() + 32*this->blockLocatorHashes.size() + 36; }
    uchar_vector getSerialized() const;
    void setSerialized(const uchar_vector& bytes);

    std::string toString() const;
    std::string toIndentedString(uint spaces = 0) const;

    void addHashStart(const uchar_vector& hashStart) { this->blockLocatorHashes.push_back(hashStart); }
};

class OutPoint : public CoinNodeStructure
{
public:
    unsigned char hash[32];
    uint32_t index;

    OutPoint() { }
    OutPoint(const uchar_vector& hashBytes, uint index) { this->setPoint(hashBytes, index); }
    OutPoint(const std::string& hashHex, uint index) { uchar_vector hashBytes; hashBytes.setHex(hashHex); this->setPoint(hashBytes, index); }
    OutPoint(const uchar_vector& bytes) { this->setSerialized(bytes); }
    OutPoint(const OutPoint& outPoint)
    {
        memcpy(this->hash, outPoint.hash, 32);
        this->index = outPoint.index;
    }

    void setPoint(const uchar_vector& hashBytes, uint index);

    const char* getCommand() const { return ""; }
    uint64_t getSize() const { return 36; }
    uchar_vector getSerialized() const;
    void setSerialized(const uchar_vector& bytes);

    std::string getTxHash() const { return uchar_vector(this->hash, 32).getHex(); }

    std::string toDelimited(const std::string& delimiter) const;
    std::string toString() const;
    std::string toIndentedString(uint spaces = 0) const;
};

class ScriptWitness : public CoinNodeStructure
{
public:
    std::vector<uchar_vector> stack;

    ScriptWitness() { }
    ScriptWitness(const uchar_vector& bytes) { setSerialized(bytes); }

    void clear() { stack.clear(); }
    void push(const uchar_vector& data) { stack.push_back(data); }
    bool isEmpty() const { return stack.empty(); }

    const char* getCommand() const { return ""; }
    uint64_t getSize() const;

    uchar_vector getSerialized() const;
    void setSerialized(const uchar_vector& bytes);

    // TODO: toString methods
    std::string toString() const { return std::string(); }
    std::string toIndentedString(uint spaces = 0) const { return std::string(); }
};

class TxIn : public CoinNodeStructure
{
public:
    OutPoint previousOut;
    uchar_vector scriptSig;
    uint32_t sequence;
    ScriptWitness scriptWitness;

    TxIn() { }
    TxIn(const TxIn& txIn)
        : previousOut(txIn.previousOut), scriptSig(txIn.scriptSig), sequence(txIn.sequence), scriptWitness(txIn.scriptWitness) { }
    TxIn(const OutPoint& _previousOut, const uchar_vector& _scriptSig, uint32_t _sequence)
        : previousOut(_previousOut), scriptSig(_scriptSig), sequence(_sequence) { }
    TxIn(const OutPoint& previousOut, const std::string& scriptSigHex, uint32_t sequence);
    TxIn(const uchar_vector& bytes) { this->setSerialized(bytes); }

    const char* getCommand() const { return ""; }
    uint64_t getSize() const { return VarInt(this->scriptSig.size()).getSize() + scriptSig.size() + 40; } // 40 = previousOut + sequence
    uchar_vector getSerialized() const { return this->getSerialized(true); }
    uchar_vector getSerialized(bool includeScriptSigLength) const;
    void setSerialized(const uchar_vector& bytes);

    uchar_vector getOutpointHash() const { return uchar_vector(this->previousOut.hash, 32); }
    uint32_t getOutpointIndex() const { return this->previousOut.index; }
    std::string getAddress() const;
    std::string toString() const;
    std::string toIndentedString(uint spaces = 0) const;
    std::string toJson() const;

    bool hasWitness() const { return !scriptWitness.isEmpty(); }
};

class TxOut : public CoinNodeStructure
{
public:
    uint64_t value;
    uchar_vector scriptPubKey;

    TxOut() { }
    TxOut(const TxOut& txOut)
        : value(txOut.value), scriptPubKey(txOut.scriptPubKey) { }
    TxOut(uint64_t _value, const uchar_vector& _scriptPubKey)
        : value(_value), scriptPubKey(_scriptPubKey) { }
    TxOut(uint64_t value, const std::string& scriptPubKeyHex);
    TxOut(const uchar_vector& bytes) { this->setSerialized(bytes); }

    const char* getCommand() const { return ""; }
    uint64_t getSize() const { return VarInt(this->scriptPubKey.size()).getSize() + scriptPubKey.size() + 8; } // 8 = sizeof(value)
    uchar_vector getSerialized() const;
    void setSerialized(const uchar_vector& bytes);

    std::string getAddress() const;
    std::string toString() const;
    std::string toIndentedString(uint spaces = 0) const;
    std::string toJson() const;
};

class Transaction : public CoinNodeStructure
{
public:
    uint32_t version;
    std::vector<TxIn> inputs;
    std::vector<TxOut> outputs;
    uint32_t lockTime;

    Transaction() { this->version = 1; lockTime = 0; }
    Transaction(const uchar_vector& bytes) { this->setSerialized(bytes); }
    Transaction(const std::string& hex);
    Transaction(const Transaction& tx)
        : version(tx.version), inputs(tx.inputs), outputs(tx.outputs), lockTime(tx.lockTime) { }

    const uchar_vector& getHash() const { return getHash(false); }
    const uchar_vector& getHash(bool bWithWitness) const;

    const uchar_vector& getHashLittleEndian() const { return getHashLittleEndian(false); }
    const uchar_vector& getHashLittleEndian(bool bWithWitness) const;

    const uchar_vector& getHash(hashfunc_t hashfunc) const { return getHash(hashfunc, false); }
    const uchar_vector& getHash(hashfunc_t hashfunc, bool bWithWitness) const;

    const uchar_vector& getHashLittleEndian(hashfunc_t hashfunc) const { return getHashLittleEndian(hashfunc, false); }
    const uchar_vector& getHashLittleEndian(hashfunc_t hashfunc, bool bWithWitness) const;

    const uchar_vector& hash() const { return getHashLittleEndian(); }

    uint32_t getChecksum() const;

    const char* getCommand() const { return "tx"; }

    bool hasWitness() const { for (auto& input: inputs) { if (input.hasWitness()) return true; } return false; }

    uint64_t getSize() const { return this->getSize(true); }
    uint64_t getSize(bool bWithWitness) const;
    uint64_t getVSize() const;

    uchar_vector getSerialized() const { return this->getSerialized(true); }
    uchar_vector getSerialized(bool bWithWitness) const;

    void setSerialized(const uchar_vector& bytes);

    std::string toString() const;
    std::string toIndentedString(uint spaces = 0) const;
    std::string toJson() const;

    void clearScriptSigs();
    void setScriptSig(uint index, const uchar_vector& scriptSig);
    void setScriptSig(uint index, const std::string& scriptSigHex);

    void clearInputs() { inputs.clear(); }
    void clearOutputs() { outputs.clear(); }

    void addInput(const TxIn& txin) { inputs.push_back(txin); }
    void addOutput(const TxOut& txout) { outputs.push_back(txout); }

    uint64_t getTotalSent() const;

    uchar_vector getHashWithAppendedCode(uint32_t code) const; // in little endian
    uchar_vector getSigHash(uint32_t hashType, uint index, const uchar_vector& script, uint64_t value = 0) const;
    void resetSigHash();

private:
    mutable uchar_vector hashPrevouts;
    mutable uchar_vector hashSequence;
    mutable uchar_vector hashOutputs;
};

class CoinBlock;
class MerkleBlock;

class CoinBlockHeader : public CoinNodeStructure
{
public:
    CoinBlockHeader() : isPOWHashSet_(false) { }
    CoinBlockHeader(uint32_t version, const uchar_vector& prevBlockHash, const uchar_vector& merkleRoot, uint32_t timestamp, uint32_t bits, uint32_t nonce)
        : isPOWHashSet_(false), version_(version), prevBlockHash_(prevBlockHash), merkleRoot_(merkleRoot), timestamp_(timestamp), bits_(bits), nonce_(nonce) { }
    CoinBlockHeader(uint32_t version, uint32_t timestamp, uint32_t bits, uint32_t nonce = 0, const uchar_vector& prevBlockHash = g_zero32bytes, const uchar_vector& merkleRoot = g_zero32bytes)
        : isPOWHashSet_(false), version_(version), prevBlockHash_(prevBlockHash), merkleRoot_(merkleRoot), timestamp_(timestamp), bits_(bits), nonce_(nonce) { }
    CoinBlockHeader(const uchar_vector& bytes) { setSerialized(bytes); }
    CoinBlockHeader(const std::string& hex);

    void set(uint32_t version, uint32_t timestamp, uint32_t bits, uint32_t nonce = 0, const uchar_vector& prevBlockHash = g_zero32bytes, const uchar_vector& merkleRoot = g_zero32bytes)
    {
        isHashSet_ = false;
        isPOWHashSet_ = false;

        version_ = version;
        prevBlockHash_ = prevBlockHash;
        merkleRoot_ = merkleRoot;
        timestamp_ = timestamp;
        bits_ = bits;
        nonce_ = nonce;
    }

    const uchar_vector& hash() const { return getHashLittleEndian(); }
    uint32_t version() const { return version_; }
    const uchar_vector&  prevBlockHash() const { return prevBlockHash_; }
    const uchar_vector& merkleRoot() const { return merkleRoot_; }
    uint32_t timestamp() const { return timestamp_; }
    uint32_t bits() const { return bits_; }
    uint32_t nonce() const { return nonce_; }

    const char* getCommand() const { return ""; }
    uint64_t getSize() const { return 80; }
    uchar_vector getSerialized() const;
    void setSerialized(const uchar_vector& bytes);

    std::string toString() const;
    std::string toIndentedString(uint spaces = 0) const;

    void nonce(uint32_t nonce) { nonce_ = nonce; isHashSet_ = false; isPOWHashSet_ = false; }
    void incrementNonce() { nonce_++; isHashSet_ = false; isPOWHashSet_ = false; }

    const BigInt getTarget() const;
    void setTarget(const BigInt& target);

    const BigInt getWork() const;

    static void setHashFunc(hashfunc_t hashfunc) { hashfunc_ = hashfunc; }
    static void setPOWHashFunc(hashfunc_t hashfunc) { powhashfunc_ = hashfunc; }

    const uchar_vector& getHash() const;
    const uchar_vector& getHashLittleEndian() const;

    const uchar_vector& getPOWHash() const;
    const uchar_vector& getPOWHashLittleEndian() const;

private:
    friend class CoinBlock;
    friend class MerkleBlock;

    static hashfunc_t hashfunc_;
    static hashfunc_t powhashfunc_;

/*
    // Inherited from CoinNodeStructure
    mutable uchar_vector hash_;
    mutable uchar_vector hashLittleEndian_;
    mutable bool isHashSet_;
*/

    mutable uchar_vector POWHash_;
    mutable uchar_vector POWHashLittleEndian_;
    mutable bool isPOWHashSet_;

    void resetHash() const { isHashSet_ = false; isPOWHashSet_ = false; }

    uint32_t version_;
    uchar_vector prevBlockHash_;
    uchar_vector merkleRoot_;
    uint32_t timestamp_;
    uint32_t bits_;
    uint32_t nonce_;
};

class CoinBlock : public CoinNodeStructure
{
public:
    CoinBlockHeader blockHeader;
    std::vector<Transaction> txs;

    CoinBlock() { }
    CoinBlock(const CoinBlockHeader& _blockHeader, const std::vector<Transaction>& _txs)
        : blockHeader(_blockHeader), txs(_txs) { }
    CoinBlock(const CoinBlock& coinBlock)
        : blockHeader(coinBlock.blockHeader), txs(coinBlock.txs) { }
    CoinBlock(uint32_t version, uint32_t timestamp, uint32_t bits, const uchar_vector& prevBlockHash = g_zero32bytes)
    {
        this->blockHeader = CoinBlockHeader(version, timestamp, bits, 0, prevBlockHash);
    }
    CoinBlock(const uchar_vector& bytes) { this->setSerialized(bytes); }
    CoinBlock(const std::string& hex);

    const uchar_vector& hash() const { return blockHeader.getHashLittleEndian(); }
    uint32_t version() const { return blockHeader.version(); }
    const uchar_vector& prevBlockHash() const { return blockHeader.prevBlockHash(); }
    const uchar_vector& merkleRoot() const { return blockHeader.merkleRoot(); }
    uint32_t timestamp() const { return blockHeader.timestamp(); }
    uint32_t bits() const { return blockHeader.bits(); }
    uint32_t nonce() const { return blockHeader.nonce(); }

    const BigInt getTarget() const { return blockHeader.getTarget(); }
    const BigInt getWork() const { return blockHeader.getWork(); }

    const char* getCommand() const { return "block"; }
    uint64_t getSize() const;
    uchar_vector getSerialized() const;
    void setSerialized(const uchar_vector& bytes);

    std::string toString() const;
    std::string toIndentedString(uint spaces = 0) const;
    std::string toRedactedIndentedString(uint spaces = 0) const;

    void addTransaction(const Transaction& tx) { this->txs.push_back(tx); }

    bool isValidMerkleRoot() const;
    void updateMerkleRoot();

    void incrementNonce() { blockHeader.incrementNonce(); }

    uint64_t getTotalSent() const;

    // Only supported for blocks version 2 or higher.
    // Returns -1 for older blocks.
    int64_t getHeight() const;
};

class MerkleBlock : public CoinNodeStructure
{
public:
    CoinBlockHeader blockHeader;
    uint32_t nTxs;
    std::vector<uchar_vector> hashes;
    uchar_vector flags;

    MerkleBlock() { }
    MerkleBlock(const CoinBlockHeader& _blockHeader, uint32_t _nTxs, const std::vector<uchar_vector>& _hashes, const uchar_vector& _flags)
        : blockHeader(_blockHeader), nTxs(_nTxs), hashes(_hashes), flags(_flags) { }
    MerkleBlock(const MerkleBlock& merkleBlock)
        : blockHeader(merkleBlock.blockHeader), nTxs(merkleBlock.nTxs), hashes(merkleBlock.hashes), flags(merkleBlock.flags) { }
    MerkleBlock(const PartialMerkleTree& merkleTree, uint32_t version, const uchar_vector& prevBlockHash, uint32_t timestamp, uint32_t bits, uint32_t nonce);
    explicit MerkleBlock(const uchar_vector& bytes) { setSerialized(bytes); }

    const uchar_vector& hash() const { return blockHeader.getHashLittleEndian(); }
    uint32_t version() const { return blockHeader.version(); }
    const uchar_vector& prevBlockHash() const { return blockHeader.prevBlockHash(); }
    const uchar_vector& merkleRoot() const { return blockHeader.merkleRoot(); }
    uint32_t timestamp() const { return blockHeader.timestamp(); }
    uint32_t bits() const { return blockHeader.bits(); }
    uint32_t nonce() const { return blockHeader.nonce(); }

    PartialMerkleTree merkleTree() const;

    const BigInt getTarget() const { return blockHeader.getTarget(); }
    const BigInt getWork() const { return blockHeader.getWork(); }

    const char* getCommand() const { return "merkleblock"; }
    uint64_t getSize() const;
    uchar_vector getSerialized() const;
    void setSerialized(const uchar_vector& bytes);

    std::string toString() const;
    std::string toIndentedString(uint spaces = 0) const;

    bool isValidMerkleRoot() const;
    void updateMerkleRoot();
};

class HeadersMessage : public CoinNodeStructure
{
public:
    std::vector<CoinBlockHeader> headers;

    HeadersMessage() { }
    HeadersMessage(const std::vector<CoinBlockHeader>& headers) { this->headers = headers; }
    HeadersMessage(const uchar_vector& bytes) { this->setSerialized(bytes); }
    HeadersMessage(const std::string& hex);

    const char* getCommand() const { return "headers"; }
    uint64_t getSize() const;
    uchar_vector getSerialized() const;
    void setSerialized(const uchar_vector& bytes);

    std::string toString() const;
    std::string toIndentedString(uint spaces = 0) const;

    void clear() { this->headers.clear(); }
    void addHeader(const CoinBlockHeader& header) { this->headers.push_back(header); }
};

class GetAddrMessage : public CoinNodeStructure
{
public:
    GetAddrMessage() { }

    const char* getCommand() const { return "getaddr"; }
    uint64_t getSize() const { return 0; }

    uchar_vector getSerialized() const { uchar_vector rval; return rval; }
    void setSerialized(const uchar_vector& /*bytes*/) { }

    std::string toString() const { return ""; }
    std::string toIndentedString(uint spaces = 0) const { return blankSpaces(spaces); }
};

class FilterLoadMessage : public CoinNodeStructure
{
public:
    uchar_vector filter;
    uint32_t nHashFuncs;
    uint32_t nTweak;
    uint8_t nFlags;

    FilterLoadMessage(uint32_t nHashFuncs_ = 0, uint32_t nTweak_ = 0, uint8_t nFlags_ = 0, const uchar_vector& filter_ = uchar_vector())
        : filter(filter_), nHashFuncs(nHashFuncs_), nTweak(nTweak_), nFlags(nFlags_) { }
    FilterLoadMessage(const uchar_vector& bytes) { setSerialized(bytes); }

    const char* getCommand() const { return "filterload"; }
    uint64_t getSize() const;

    uchar_vector getSerialized() const;
    void setSerialized(const uchar_vector& bytes);

    std::string toString() const;
    std::string toIndentedString(uint spaces = 0) const;
};

class FilterAddMessage : public CoinNodeStructure
{
public:
    uchar_vector data;

    FilterAddMessage() { }
    FilterAddMessage(const uchar_vector& bytes) { setSerialized(bytes); }

    const char* getCommand() const { return "filteradd"; }
    uint64_t getSize() const { return VarInt(data.size()).getSize() + data.size(); }

    uchar_vector getSerialized() const { return VarInt(data.size()).getSerialized() + data; }
    void setSerialized(const uchar_vector& bytes);

    std::string toString() const;
    std::string toIndentedString(uint spaces = 0) const;
};

class FilterClearMessage : public BlankMessage
{
public:
    FilterClearMessage() : BlankMessage("filterclear") { }
};

class PingMessage : public CoinNodeStructure
{
public:
    uint64_t nonce;

    PingMessage();
    PingMessage(const uchar_vector& bytes) { setSerialized(bytes); }

    const char* getCommand() const { return "ping"; }
    uint64_t getSize() const { return sizeof(uint64_t); }

    uchar_vector getSerialized() const;
    void setSerialized(const uchar_vector& bytes);

    std::string toString() const;
    std::string toIndentedString(uint spaces = 0) const;
};

class PongMessage : public CoinNodeStructure
{
public:
    uint64_t nonce;

    PongMessage(uint64_t nonce_) : nonce(nonce_) { }
    PongMessage(const uchar_vector& bytes) { setSerialized(bytes); }

    const char* getCommand() const { return "pong"; }
    uint64_t getSize() const { return sizeof(uint64_t); }

    uchar_vector getSerialized() const;
    void setSerialized(const uchar_vector& bytes);

    std::string toString() const;
    std::string toIndentedString(uint spaces = 0) const;
};

} // namespace Coin


text:
function [D,x] = cheb(N)
%   [D,x] = cheb(N) computes the differentiation matrices for Chebyshev
%   spectral method. Script taken from
%   https://people.maths.ox.ac.uk/trefethen/spectral.html

%   This file is part of the LIONSIMBA Toolbox
%
%	Official web-site: 	http://sisdin.unipv.it/labsisdin/lionsimba.php
% 	Official GitHUB: 	https://github.com/lionsimbatoolbox/LIONSIMBA
%
%   LIONSIMBA: A Matlab framework based on a finite volume model suitable for Li-ion battery design, simulation, and control
%   Copyright (C) 2016-2018 :Marcello Torchio, Lalo Magni, Davide Raimondo,
%                            University of Pavia, 27100, Pavia, Italy
%                            Bhushan Gopaluni, Univ. of British Columbia,
%                            Vancouver, BC V6T 1Z3, Canada
%                            Richard D. Braatz,
%                            Massachusetts Institute of Technology,
%                            Cambridge, Massachusetts 02142, USA
%
%   Main code contributors to LIONSIMBA 2.0:
%                           Ian Campbell, Krishnakumar Gopalakrishnan,
%                           Imperial college London, London, UK
%
%   LIONSIMBA is a free Matlab-based software distributed with an MIT
%   license.

% computesthe chebyshev differentiation matrix for N points. Also returns node locations
    if N==0, D=0; x=1; return, end
    x = cos(pi*(0:N)/N)';
    c = [2; ones(N-1,1); 2].*(-1).^(0:N)';
    X = repmat(x,1,N+1);
    dX = X-X';
    D  = (c*(1./c)')./(dX+(eye(N+1)));      % off-diagonal entries
    D  = D - diag(sum(D'));                 % diagonal entries
end


text:
section: Docs
subtitle: API
chapter: Overview
permalink: docs/api/index.html
layout: submenu
---

# Overview

The Aperture Tiles Annotation Service REST API is based on the Aperture Tiles Binning API. Annotations are submitted into tiles and aggregated through a given range of levels based on bin-index. Annotations can be written, modified and removed in real time.

## Web Service Paths

Web service paths are relative to a common base URL.  For example, assuming the hostname *localhost* and port *8080*, the URLs of the various services would be:

- `https://localhost:8080/annotation/{layer}/{uuid}/{level}/{x}/{y}.{ext}`
- `https://localhost:8080/annotation`

## Getting Started

To begin, review the available [Data Types](datatypes/).


text:
package com.aspose.cells.model;

import java.util.*;
public class DataSorter {
  private String CaseSensitive = null;
  private String HasHeaders = null;
  private List<SortKey> KeyList = new ArrayList<SortKey>();
  private String SortLeftToRight = null;
  /**
	 * getCaseSensitive
	 * Gets String
	 * @return CaseSensitive
	 */
  public String getCaseSensitive() {
    return CaseSensitive;
  }

	/**
	 * setCaseSensitive
	 * Sets String
	 * @param CaseSensitive String
	 */
  public void setCaseSensitive(String CaseSensitive) {
    this.CaseSensitive = CaseSensitive;
  }

  /**
	 * getHasHeaders
	 * Gets String
	 * @return HasHeaders
	 */
  public String getHasHeaders() {
    return HasHeaders;
  }

	/**
	 * setHasHeaders
	 * Sets String
	 * @param HasHeaders String
	 */
  public void setHasHeaders(String HasHeaders) {
    this.HasHeaders = HasHeaders;
  }

  /**
	 * getKeyList
	 * Gets List<SortKey>
	 * @return KeyList
	 */
  public List<SortKey> getKeyList() {
    return KeyList;
  }

	/**
	 * setKeyList
	 * Sets List<SortKey>
	 * @param KeyList List<SortKey>
	 */
  public void setKeyList(List<SortKey> KeyList) {
    this.KeyList = KeyList;
  }

  /**
	 * getSortLeftToRight
	 * Gets String
	 * @return SortLeftToRight
	 */
  public String getSortLeftToRight() {
    return SortLeftToRight;
  }

	/**
	 * setSortLeftToRight
	 * Sets String
	 * @param SortLeftToRight String
	 */
  public void setSortLeftToRight(String SortLeftToRight) {
    this.SortLeftToRight = SortLeftToRight;
  }

  @Override
  public String toString()  {
    StringBuilder sb = new StringBuilder();
    sb.append("class DataSorter {\n");
    sb.append("  CaseSensitive: ").append(CaseSensitive).append("\n");
    sb.append("  HasHeaders: ").append(HasHeaders).append("\n");
    sb.append("  KeyList: ").append(KeyList).append("\n");
    sb.append("  SortLeftToRight: ").append(SortLeftToRight).append("\n");
    sb.append("}\n");
    return sb.toString();
  }
}


text:
<?php

namespace Drupal\entity_test\Entity;

use Drupal\Core\Entity\EntityChangedInterface;
use Drupal\Core\Entity\EntityChangedTrait;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Field\BaseFieldDefinition;

/**
 * Defines the test entity class.
 *
 * @ContentEntityType(
 *   id = "entity_test_mul_changed",
 *   label = @Translation("Test entity - data table"),
 *   handlers = {
 *     "view_builder" = "Drupal\entity_test\EntityTestViewBuilder",
 *     "access" = "Drupal\entity_test\EntityTestAccessControlHandler",
 *     "form" = {
 *       "default" = "Drupal\entity_test\EntityTestForm",
 *       "delete" = "Drupal\entity_test\EntityTestDeleteForm"
 *     },
 *     "route_provider" = {
 *       "html" = "Drupal\Core\Entity\Routing\DefaultHtmlRouteProvider",
 *     },
 *     "translation" = "Drupal\content_translation\ContentTranslationHandler",
 *     "views_data" = "Drupal\views\EntityViewsData"
 *   },
 *   base_table = "entity_test_mul_changed",
 *   data_table = "entity_test_mul_changed_property",
 *   translatable = TRUE,
 *   entity_keys = {
 *     "id" = "id",
 *     "uuid" = "uuid",
 *     "bundle" = "type",
 *     "label" = "name",
 *     "langcode" = "langcode"
 *   },
 *   links = {
 *     "add-form" = "/entity_test_mul_changed/add",
 *     "canonical" = "/entity_test_mul_changed/manage/{entity_test_mul_changed}",
 *     "edit-form" = "/entity_test_mul_changed/manage/{entity_test_mul_changed}/edit",
 *     "delete-form" = "/entity_test/delete/entity_test_mul_changed/{entity_test_mul_changed}",
 *   },
 *   field_ui_base_route = "entity.entity_test_mul_changed.admin_form",
 * )
 */
class EntityTestMulChanged extends EntityTestMul implements EntityChangedInterface {

  use EntityChangedTrait;

  /**
   * {@inheritdoc}
   */
  public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
    $fields = parent::baseFieldDefinitions($entity_type);

    $fields['changed'] = BaseFieldDefinition::create('changed_test')
      ->setLabel(t('Changed'))
      ->setDescription(t('The time that the entity was last edited.'))
      ->setTranslatable(TRUE);

    return $fields;
  }

  /**
   * {@inheritdoc}
   */
  public function save() {
    // Ensure a new timestamp.
    sleep(1);
    parent::save();
  }

}


text:
package org.terasology.world.block.loader;

import com.google.common.base.Preconditions;
import com.google.common.collect.Sets;
import org.terasology.assets.Asset;
import org.terasology.assets.AssetType;
import org.terasology.assets.ResourceUrn;
import org.terasology.module.sandbox.API;
import org.terasology.world.block.BlockBuilderHelper;
import org.terasology.world.block.family.BlockFamily;
import org.terasology.world.block.family.BlockFamilyFactory;
import org.terasology.world.block.shapes.BlockShape;
import org.terasology.world.block.tiles.BlockTile;

import java.util.Collections;
import java.util.List;
import java.util.Set;

/**
 * @author Immortius
 */
@API
public class BlockFamilyDefinition extends Asset<BlockFamilyDefinitionData> {

    private BlockFamilyDefinitionData data;

    public BlockFamilyDefinition(ResourceUrn urn, AssetType<?, BlockFamilyDefinitionData> assetType, BlockFamilyDefinitionData data) {
        super(urn, assetType);
        reload(data);
    }

    @Override
    protected void doReload(BlockFamilyDefinitionData blockFamilyDefinitionData) {
        this.data = blockFamilyDefinitionData;
    }

    @Override
    protected void doDispose() {
        data = null;
    }

    public List<String> getCategories() {
        return Collections.unmodifiableList(data.getCategories());
    }

    public boolean isFreeform() {
        return getData().getFamilyFactory().isFreeformSupported();
    }

    public BlockFamily createFamily(BlockBuilderHelper blockBuilderHelper) {
        Preconditions.checkState(!isFreeform());
        return getData().getFamilyFactory().createBlockFamily(this, blockBuilderHelper);
    }

    public BlockFamily createFamily(BlockShape shape, BlockBuilderHelper blockBuilderHelper) {
        Preconditions.checkState(isFreeform());
        return getData().getFamilyFactory().createBlockFamily(this, shape, blockBuilderHelper);
    }

    public BlockFamilyDefinitionData getData() {
        return new BlockFamilyDefinitionData(data);
    }

    public boolean isLoadable() {
        return getData().isValid() && !getData().isTemplate();
    }
}


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <meta name="theme-color" content="#333333">
    <meta name="googlebot" content="index, follow">
    <meta name="robots" content="index, follow, noodp">
    <meta name="category" content="imgur, imgur-tray, open-source, electron, javascript, macOS, yuri brunetto, ybrntt, front-end developer, feliz, rio grande do sul, brasil, brazil, game dev">
    <meta name="coverage" content="Worldwide">
    <meta name="description" content="Upload images to Imgur directly from your tray bar!">

    <meta property="og:locale" content="en_US">
    <meta property="og:site_name" content="Imgur-Tray | Upload images to Imgur directly from your tray bar">
    <meta property="og:type" content="website">
    <meta property="og:url" content="https://yuribrunetto.github.io/imgur-tray-website/">
    <meta property="og:title" content="Imgur-Tray | Upload images to Imgur directly from your tray bar">
    <meta property="og:description" content="Upload images to Imgur directly from your tray bar!">
    <meta property="og:image" content="https://yuribrunetto.github.io/imgur-tray-website/img/favicons/apple-touch-icon.png">

    <meta name="twitter:card" content="summary">
    <meta name="twitter:description" content="Upload images to Imgur directly from your tray bar!">
    <meta name="twitter:title" content="Imgur-Tray | Upload images to Imgur directly from your tray bar">
    <meta name="twitter:site" content="@yuribrunetto">
    <meta name="twitter:image" content="https://yuribrunetto.github.io/imgur-tray-website/img/favicons/apple-touch-icon.png">
    <meta name="twitter:creator" content="@yuribrunetto">
    <meta name="twitter:url" content="https://yuribrunetto.github.io/imgur-tray-website/">

    <meta itemprop="name" content="Imgur-Tray | Upload images to Imgur directly from your tray bar">
    <meta itemprop="description" content="Upload images to Imgur directly from your tray bar!">
    <meta itemprop="image" content="https://yuribrunetto.github.io/imgur-tray-website/img/favicons/apple-touch-icon.png">

    <meta name="mobile-web-app-capable" content="yes">

    <link rel="stylesheet" href="lib/normalize.min.css">
    <link rel="stylesheet" href="css/main.css">

    <link rel="apple-touch-icon" sizes="180x180" href="https://yuribrunetto.github.io/imgur-tray-website/img/favicons/apple-touch-icon.png">
    <link rel="icon" type="image/png" sizes="32x32" href="https://yuribrunetto.github.io/imgur-tray-website/img/favicons/favicon-32x32.png">
    <link rel="icon" type="image/png" sizes="16x16" href="https://yuribrunetto.github.io/imgur-tray-website/img/favicons/favicon-16x16.png">
    <link rel="manifest" href="https://yuribrunetto.github.io/imgur-tray-website/img/favicons/manifest.json">
    <link rel="mask-icon" href="https://yuribrunetto.github.io/imgur-tray-website/img/favicons/safari-pinned-tab.svg" color="#5bbad5">

    <title>Imgur-Tray | Upload images to Imgur directly from your tray bar</title>

Upload images to Imgur directly from your tray bar.

            Get Imgur-Tray

 only for macOS

It's fast, it's simple

The simplest way to upload an image and share it only using 2 clicks!

Don't lose your images

You can check all your images uploaded in the tab My uploads.

Open-source

          View and contribute on GitHub

    © 2017 Yuri Brunetto