text:
<?php
/**
 * Implements hook_form_FORM_ID_alter().
 *
 * @param $form
 *   The form.
 * @param $form_state
 *   The form state.
 */
function corporateclean_form_system_theme_settings_alter(&$form, &$form_state) {

  $form['mtt_settings'] = array(
    '#type' => 'fieldset',
    '#title' => t('Corporate Clean Theme Settings'),
    '#collapsible' => FALSE,
	'#collapsed' => FALSE,
  );

  $form['mtt_settings']['breadcrumb'] = array(
    '#type' => 'fieldset',
    '#title' => t('Breadcrumb'),
    '#collapsible' => TRUE,
	'#collapsed' => FALSE,
  );

  $form['mtt_settings']['breadcrumb']['breadcrumb_display'] = array(
    '#type' => 'checkbox',
    '#title' => t('Show breadcrumb'),
  	'#description'   => t('Use the checkbox to enable or disable breadcrumb.'),
	'#default_value' => theme_get_setting('breadcrumb_display','corporateclean'),
  );

  $form['mtt_settings']['breadcrumb']['breadcrumb_separator'] = array(
    '#type' => 'textfield',
    '#title' => t('Breadcrumb separator'),
	'#default_value' => theme_get_setting('breadcrumb_separator','corporateclean'),
    '#size'          => 5,
    '#maxlength'     => 10,
  );

  $form['mtt_settings']['breadcrumb']['breadcrumb_home'] = array(
    '#type'          => 'checkbox',
    '#title'         => t('Show home page link in breadcrumb'),
  	'#description'   => t('Use the checkbox to enable or disable the home page link in breadcrumb.'),
    '#default_value' => theme_get_setting('breadcrumb_home'),
  );

  $form['mtt_settings']['slideshow'] = array(
    '#type' => 'fieldset',
    '#title' => t('Front Page Slideshow'),
    '#collapsible' => TRUE,
	'#collapsed' => FALSE,
  );

  $form['mtt_settings']['slideshow']['slideshow_display'] = array(
    '#type' => 'checkbox',
    '#title' => t('Show slideshow'),
	'#default_value' => theme_get_setting('slideshow_display','corporateclean'),
  );

  $form['mtt_settings']['slideshow']['slideshow_js'] = array(
    '#type' => 'checkbox',
    '#title' => t('Include slideshow javascript code'),
	'#default_value' => theme_get_setting('slideshow_js','corporateclean'),
  );

  $form['mtt_settings']['slideshow']['slideshow_effect'] = array(
    '#type' => 'select',
    '#title' => t('Effects'),
  	'#description'   => t('From the drop-down menu, select the slideshow effect you prefer.'),
	'#default_value' => theme_get_setting('slideshow_effect','corporateclean'),
    '#options' => array(
		'blindX' => t('blindX'),
		'blindY' => t('blindY'),
		'blindZ' => t('blindZ'),
		'cover' => t('cover'),
		'curtainX' => t('curtainX'),
		'curtainY' => t('curtainY'),
		'fade' => t('fade'),
		'fadeZoom' => t('fadeZoom'),
		'growX' => t('growX'),
		'growY' => t('growY'),
		'scrollUp' => t('scrollUp'),
		'scrollDown' => t('scrollDown'),
		'scrollLeft' => t('scrollLeft'),
		'scrollRight' => t('scrollRight'),
		'scrollHorz' => t('scrollHorz'),
		'scrollVert' => t('scrollVert'),
		'shuffle' => t('shuffle'),
		'slideX' => t('slideX'),
		'slideY' => t('slideY'),
		'toss' => t('toss'),
		'turnUp' => t('turnUp'),
		'turnDown' => t('turnDown'),
		'turnLeft' => t('turnLeft'),
		'turnRight' => t('turnRight'),
		'uncover' => t('uncover'),
		'wipe' => t('wipe'),
		'zoom' => t('zoom'),
    ),
  );

  $form['mtt_settings']['slideshow']['slideshow_effect_time'] = array(
    '#type' => 'textfield',
    '#title' => t('Effect duration (sec)'),
	'#default_value' => theme_get_setting('slideshow_effect_time','corporateclean'),
  );

  $form['mtt_settings']['slideshow']['slideshow_randomize'] = array(
    '#type' => 'checkbox',
    '#title' => t('Randomize slideshow order'),
	'#default_value' => theme_get_setting('slideshow_randomize','corporateclean'),
  );

  $form['mtt_settings']['slideshow']['slideshow_wrap'] = array(
    '#type' => 'checkbox',
    '#title' => t('Prevent slideshow from wrapping'),
	'#default_value' => theme_get_setting('slideshow_wrap','corporateclean'),
  );

  $form['mtt_settings']['slideshow']['slideshow_pause'] = array(
    '#type' => 'checkbox',
    '#title' => t('Pause slideshow on hover'),
	'#default_value' => theme_get_setting('slideshow_pause','corporateclean'),
  );

  $form['mtt_settings']['support'] = array(
    '#type' => 'fieldset',
    '#title' => t('Accessibility and support settings'),
    '#collapsible' => TRUE,
	'#collapsed' => FALSE,
  );

  $form['mtt_settings']['support']['responsive'] = array(
    '#type' => 'fieldset',
    '#title' => t('Responsive'),
    '#collapsible' => TRUE,
	'#collapsed' => FALSE,
  );

  $form['mtt_settings']['support']['responsive']['responsive_meta'] = array(
    '#type' => 'checkbox',
    '#title' => t('Add meta tags to support responsive design on mobile devices.'),
	'#default_value' => theme_get_setting('responsive_meta','corporateclean'),
  );

  $form['mtt_settings']['support']['responsive']['responsive_respond'] = array(
    '#type' => 'checkbox',
    '#title' => t('Add Respond.js JavaScript to add basic CSS3 media query support to IE 6-8.'),
	'#default_value' => theme_get_setting('responsive_respond','corporateclean'),
    '#description'   => t('IE 6-8 require a JavaScript polyfill solution to add basic support of CSS3 media queries. Note that you should enable Aggregate and compress CSS files through /admin/config/development/performance.'),
  );

  $form['mtt_settings']['credits'] = array(
    '#type' => 'fieldset',
    '#title' => t('Credits'),
    '#collapsible' => TRUE,
	'#collapsed' => FALSE,
  );

  $form['mtt_settings']['credits']['credits_display'] = array(
    '#type' => 'checkbox',
    '#title' => t('Show credits'),
  	'#description'   => t('Use the checkbox to enable or disable credits.'),
	'#default_value' => theme_get_setting('credits_display','corporateclean'),
  );

}

redpajama_set_name: RedPajamaGithub


text:
module FantasyLanguage where
    import Data.List
    import Control.Monad
    import System.Random
    import Probability()

    data LanguageType = CommonSpeech | ElvishSpeech | DwarvenSpeech | HalflingSpeech | OrcishSpeech | InfernalLanguage | CelestialLanguage | ReptilianSpeech | InsectSpeech | SacredLanguage | DeadLanguage | FaeSpeech | SilentLanguage | BlackSpeech | AvianSpeech | AstralSpeech | SecretLanguage | AncientSpeech | AlienSpeech | OutsiderSpeech | TrueSpeech
      deriving (Eq, Show, Read, Enum, Bounded)

    data Language = LanguageType [(String,String)]
      deriving (Eq, Show, Read)

    -- compose a mock language translating our adjectives and nouns (so we can translate/"encrypt" placenames etc)
    -- genLanguage

    humanizedLanguages :: [LanguageType] -> String
    humanizedLanguages langs = intercalate ", " (map show langs)

    genLangs n = replicateM n (randomIO :: IO LanguageType)


text:
package org.datatransferproject.datatransfer.backblaze.common;

import java.net.URI;
import software.amazon.awssdk.auth.credentials.AwsSessionCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;

public class BaseBackblazeS3ClientFactory implements BackblazeS3ClientFactory {
    private static final String S3_ENDPOINT_FORMAT_STRING = "https://s3.%s.backblazeb2.com";

    public S3Client createS3Client(String accessKey, String secretKey, String region) {
        AwsSessionCredentials awsCreds = AwsSessionCredentials.create(accessKey, secretKey, "");

        ClientOverrideConfiguration clientOverrideConfiguration =
                ClientOverrideConfiguration.builder().putHeader("User-Agent", "Facebook-DTP").build();

        // Use any AWS region for the client, the Backblaze API does not care about it
        Region awsRegion = Region.US_EAST_1;

        return S3Client.builder()
                .credentialsProvider(StaticCredentialsProvider.create(awsCreds))
                .overrideConfiguration(clientOverrideConfiguration)
                .endpointOverride(URI.create(String.format(S3_ENDPOINT_FORMAT_STRING, region)))
                .region(awsRegion)
                .build();
    }
}


text:
package nxt.http;

import nxt.Account;
import nxt.Alias;
import nxt.Appendix;
import nxt.Asset;
import nxt.AssetTransfer;
import nxt.Attachment;
import nxt.Block;
import nxt.Constants;
import nxt.Currency;
import nxt.CurrencyExchangeOffer;
import nxt.CurrencyFounder;
import nxt.CurrencyTransfer;
import nxt.CurrencyType;
import nxt.DigitalGoodsStore;
import nxt.Exchange;
import nxt.Nxt;
import nxt.Order;
import nxt.Poll;
import nxt.Token;
import nxt.Trade;
import nxt.Transaction;
import nxt.crypto.Crypto;
import nxt.crypto.EncryptedData;
import nxt.peer.Hallmark;
import nxt.peer.Peer;
import nxt.util.Convert;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

import java.util.Collections;
import java.util.Map;

final class JSONData {

    static JSONObject alias(Alias alias) {
        JSONObject json = new JSONObject();
        putAccount(json, "account", alias.getAccountId());
        json.put("aliasName", alias.getAliasName());
        json.put("aliasURI", alias.getAliasURI());
        json.put("timestamp", alias.getTimestamp());
        json.put("alias", Convert.toUnsignedLong(alias.getId()));
        Alias.Offer offer = Alias.getOffer(alias);
        if (offer != null) {
            json.put("priceNQT", String.valueOf(offer.getPriceNQT()));
            if (offer.getBuyerId() != 0) {
                json.put("buyer", Convert.toUnsignedLong(offer.getBuyerId()));
            }
        }
        return json;
    }

    static JSONObject accountBalance(Account account) {
        JSONObject json = new JSONObject();
        if (account == null) {
            json.put("balanceNQT", "0");
            json.put("unconfirmedBalanceNQT", "0");
            json.put("effectiveBalanceNXT", "0");
            json.put("forgedBalanceNQT", "0");
            json.put("guaranteedBalanceNQT", "0");
        } else {
            json.put("balanceNQT", String.valueOf(account.getBalanceNQT()));
            json.put("unconfirmedBalanceNQT", String.valueOf(account.getUnconfirmedBalanceNQT()));
            json.put("effectiveBalanceNXT", account.getEffectiveBalanceNXT());
            json.put("forgedBalanceNQT", String.valueOf(account.getForgedBalanceNQT()));
            json.put("guaranteedBalanceNQT", String.valueOf(account.getGuaranteedBalanceNQT(1440)));
        }
        return json;
    }

    static JSONObject lessor(Account account) {
        JSONObject json = new JSONObject();
        json.put("currentLesseeRS", Convert.rsAccount(account.getCurrentLesseeId()));
        json.put("currentHeightFrom", String.valueOf(account.getCurrentLeasingHeightFrom()));
        json.put("currentHeightTo", String.valueOf(account.getCurrentLeasingHeightTo()));
        json.put("nextLesseeRS", Convert.rsAccount(account.getNextLesseeId()));
        json.put("nextHeightFrom", String.valueOf(account.getNextLeasingHeightFrom()));
        json.put("nextHeightTo", String.valueOf(account.getNextLeasingHeightTo()));
        json.put("effectiveBalanceNXT", String.valueOf(account.getGuaranteedBalanceNQT(1440) / Constants.ONE_NXT));
        return json;
    }

    static JSONObject asset(Asset asset, boolean includeCounts) {
        JSONObject json = new JSONObject();
        putAccount(json, "account", asset.getAccountId());
        json.put("name", asset.getName());
        json.put("description", asset.getDescription());
        json.put("decimals", asset.getDecimals());
        json.put("quantityQNT", String.valueOf(asset.getQuantityQNT()));
        json.put("asset", Convert.toUnsignedLong(asset.getId()));
        if (includeCounts) {
            json.put("numberOfTrades", Trade.getTradeCount(asset.getId()));
            json.put("numberOfTransfers", AssetTransfer.getTransferCount(asset.getId()));
            json.put("numberOfAccounts", Account.getAssetAccountCount(asset.getId()));
        }
        return json;
    }

    static JSONObject currency(Currency currency, boolean includeCounts) {
        JSONObject json = new JSONObject();
        json.put("currency", Convert.toUnsignedLong(currency.getId()));
        putAccount(json, "account", currency.getAccountId());
        json.put("name", currency.getName());
        json.put("code", currency.getCode());
        json.put("description", currency.getDescription());
        json.put("type", currency.getType());
        json.put("initialSupply", String.valueOf(currency.getInitialSupply()));
        json.put("currentSupply", String.valueOf(currency.getCurrentSupply()));
        json.put("reserveSupply", String.valueOf(currency.getReserveSupply()));
        json.put("maxSupply", String.valueOf(currency.getMaxSupply()));
        json.put("creationHeight", currency.getCreationHeight());
        json.put("issuanceHeight", currency.getIssuanceHeight());
        json.put("minReservePerUnitNQT", String.valueOf(currency.getMinReservePerUnitNQT()));
        json.put("currentReservePerUnitNQT", String.valueOf(currency.getCurrentReservePerUnitNQT()));
        json.put("minDifficulty", currency.getMinDifficulty());
        json.put("maxDifficulty", currency.getMaxDifficulty());
        json.put("algorithm", currency.getAlgorithm());
        json.put("decimals", currency.getDecimals());
        if (includeCounts) {
            json.put("numberOfExchanges", Exchange.getExchangeCount(currency.getId()));
            json.put("numberOfTransfers", CurrencyTransfer.getTransferCount(currency.getId()));
        }
        JSONArray types = new JSONArray();
        for (CurrencyType type : CurrencyType.values()) {
            if (currency.is(type)) {
                types.add(type.toString());
            }
        }
        json.put("types", types);
        return json;
    }

    static JSONObject currencyFounder(CurrencyFounder founder) {
        JSONObject json = new JSONObject();
        json.put("currency", Convert.toUnsignedLong(founder.getCurrencyId()));
        putAccount(json, "account", founder.getAccountId());
        json.put("amountPerUnitNQT", String.valueOf(founder.getAmountPerUnitNQT()));
        return json;
    }

    static JSONObject accountAsset(Account.AccountAsset accountAsset, boolean includeAccount, boolean includeAssetInfo) {
        JSONObject json = new JSONObject();
        if (includeAccount) {
            putAccount(json, "account", accountAsset.getAccountId());
        }
        json.put("asset", Convert.toUnsignedLong(accountAsset.getAssetId()));
        json.put("quantityQNT", String.valueOf(accountAsset.getQuantityQNT()));
        json.put("unconfirmedQuantityQNT", String.valueOf(accountAsset.getUnconfirmedQuantityQNT()));
        if (includeAssetInfo) {
            putAssetInfo(json, accountAsset.getAssetId());
        }
        return json;
    }

    static JSONObject accountCurrency(Account.AccountCurrency accountCurrency, boolean includeAccount, boolean includeCurrencyInfo) {
        JSONObject json = new JSONObject();
        if (includeAccount) {
            putAccount(json, "account", accountCurrency.getAccountId());
        }
        json.put("currency", Convert.toUnsignedLong(accountCurrency.getCurrencyId()));
        json.put("units", String.valueOf(accountCurrency.getUnits()));
        json.put("unconfirmedUnits", String.valueOf(accountCurrency.getUnconfirmedUnits()));
        if (includeCurrencyInfo) {
            putCurrencyInfo(json, accountCurrency.getCurrencyId());
        }
        return json;
    }

    static JSONObject askOrder(Order.Ask order) {
        JSONObject json = order(order);
        json.put("type", "ask");
        return json;
    }

    static JSONObject bidOrder(Order.Bid order) {
        JSONObject json = order(order);
        json.put("type", "bid");
        return json;
    }

    static JSONObject order(Order order) {
        JSONObject json = new JSONObject();
        json.put("order", Convert.toUnsignedLong(order.getId()));
        json.put("asset", Convert.toUnsignedLong(order.getAssetId()));
        putAccount(json, "account", order.getAccountId());
        json.put("quantityQNT", String.valueOf(order.getQuantityQNT()));
        json.put("priceNQT", String.valueOf(order.getPriceNQT()));
        json.put("height", order.getHeight());
        return json;
    }

    static JSONObject offer(CurrencyExchangeOffer offer) {
        JSONObject json = new JSONObject();
        json.put("offer", Convert.toUnsignedLong(offer.getId()));
        putAccount(json, "account", offer.getAccountId());
        json.put("height", offer.getHeight());
        json.put("expirationHeight", offer.getExpirationHeight());
        json.put("currency", Convert.toUnsignedLong(offer.getCurrencyId()));
        json.put("rateNQT", String.valueOf(offer.getRateNQT()));
        json.put("limit", String.valueOf(offer.getLimit()));
        json.put("supply", String.valueOf(offer.getSupply()));
        return json;
    }

    static JSONObject block(Block block, boolean includeTransactions) {
        JSONObject json = new JSONObject();
        json.put("block", block.getStringId());
        json.put("height", block.getHeight());
        putAccount(json, "generator", block.getGeneratorId());
        json.put("generatorPublicKey", Convert.toHexString(block.getGeneratorPublicKey()));
        json.put("timestamp", block.getTimestamp());
        json.put("numberOfTransactions", block.getTransactions().size());
        json.put("totalAmountNQT", String.valueOf(block.getTotalAmountNQT()));
        json.put("totalFeeNQT", String.valueOf(block.getTotalFeeNQT()));
        json.put("payloadLength", block.getPayloadLength());
        json.put("version", block.getVersion());
        json.put("baseTarget", Convert.toUnsignedLong(block.getBaseTarget()));
        json.put("cumulativeDifficulty", block.getCumulativeDifficulty().toString());
        if (block.getPreviousBlockId() != 0) {
            json.put("previousBlock", Convert.toUnsignedLong(block.getPreviousBlockId()));
        }
        if (block.getNextBlockId() != 0) {
            json.put("nextBlock", Convert.toUnsignedLong(block.getNextBlockId()));
        }
        json.put("payloadHash", Convert.toHexString(block.getPayloadHash()));
        json.put("generationSignature", Convert.toHexString(block.getGenerationSignature()));
        if (block.getVersion() > 1) {
            json.put("previousBlockHash", Convert.toHexString(block.getPreviousBlockHash()));
        }
        json.put("blockSignature", Convert.toHexString(block.getBlockSignature()));
        JSONArray transactions = new JSONArray();
        for (Transaction transaction : block.getTransactions()) {
            transactions.add(includeTransactions ? transaction(transaction) : Convert.toUnsignedLong(transaction.getId()));
        }
        json.put("transactions", transactions);
        return json;
    }

    static JSONObject encryptedData(EncryptedData encryptedData) {
        JSONObject json = new JSONObject();
        json.put("data", Convert.toHexString(encryptedData.getData()));
        json.put("nonce", Convert.toHexString(encryptedData.getNonce()));
        return json;
    }

    static JSONObject goods(DigitalGoodsStore.Goods goods, boolean includeCounts) {
        JSONObject json = new JSONObject();
        json.put("goods", Convert.toUnsignedLong(goods.getId()));
        json.put("name", goods.getName());
        json.put("description", goods.getDescription());
        json.put("quantity", goods.getQuantity());
        json.put("priceNQT", String.valueOf(goods.getPriceNQT()));
        putAccount(json, "seller", goods.getSellerId());
        json.put("tags", goods.getTags());
        JSONArray tagsJSON = new JSONArray();
        Collections.addAll(tagsJSON, goods.getParsedTags());
        json.put("parsedTags", tagsJSON);
        json.put("delisted", goods.isDelisted());
        json.put("timestamp", goods.getTimestamp());
        if (includeCounts) {
            json.put("numberOfPurchases", DigitalGoodsStore.Purchase.getGoodsPurchaseCount(goods.getId(), false, true));
            json.put("numberOfPublicFeedbacks", DigitalGoodsStore.Purchase.getGoodsPurchaseCount(goods.getId(), true, true));
        }
        return json;
    }

    static JSONObject tag(DigitalGoodsStore.Tag tag) {
        JSONObject json = new JSONObject();
        json.put("tag", tag.getTag());
        json.put("inStockCount", tag.getInStockCount());
        json.put("totalCount", tag.getTotalCount());
        return json;
    }

    static JSONObject hallmark(Hallmark hallmark) {
        JSONObject json = new JSONObject();
        putAccount(json, "account", Account.getId(hallmark.getPublicKey()));
        json.put("host", hallmark.getHost());
        json.put("weight", hallmark.getWeight());
        String dateString = Hallmark.formatDate(hallmark.getDate());
        json.put("date", dateString);
        json.put("valid", hallmark.isValid());
        return json;
    }

    static JSONObject token(Token token) {
        JSONObject json = new JSONObject();
        putAccount(json, "account", Account.getId(token.getPublicKey()));
        json.put("timestamp", token.getTimestamp());
        json.put("valid", token.isValid());
        return json;
    }

    static JSONObject peer(Peer peer) {
        JSONObject json = new JSONObject();
        json.put("address", peer.getPeerAddress());
        json.put("state", peer.getState().ordinal());
        json.put("announcedAddress", peer.getAnnouncedAddress());
        json.put("shareAddress", peer.shareAddress());
        if (peer.getHallmark() != null) {
            json.put("hallmark", peer.getHallmark().getHallmarkString());
        }
        json.put("weight", peer.getWeight());
        json.put("downloadedVolume", peer.getDownloadedVolume());
        json.put("uploadedVolume", peer.getUploadedVolume());
        json.put("application", peer.getApplication());
        json.put("version", peer.getVersion());
        json.put("platform", peer.getPlatform());
        json.put("blacklisted", peer.isBlacklisted());
        json.put("lastUpdated", peer.getLastUpdated());
        return json;
    }

    static JSONObject poll(Poll poll) {
        JSONObject json = new JSONObject();
        json.put("name", poll.getName());
        json.put("description", poll.getDescription());
        JSONArray options = new JSONArray();
        Collections.addAll(options, poll.getOptions());
        json.put("options", options);
        json.put("minNumberOfOptions", poll.getMinNumberOfOptions());
        json.put("maxNumberOfOptions", poll.getMaxNumberOfOptions());
        json.put("optionsAreBinary", poll.isOptionsAreBinary());
        JSONArray voters = new JSONArray();
        for (Long voterId : poll.getVoters().keySet()) {
            voters.add(Convert.toUnsignedLong(voterId));
        }
        json.put("voters", voters);
        return json;
    }

    static JSONObject purchase(DigitalGoodsStore.Purchase purchase) {
        JSONObject json = new JSONObject();
        json.put("purchase", Convert.toUnsignedLong(purchase.getId()));
        json.put("goods", Convert.toUnsignedLong(purchase.getGoodsId()));
        json.put("name", purchase.getName());
        putAccount(json, "seller", purchase.getSellerId());
        json.put("priceNQT", String.valueOf(purchase.getPriceNQT()));
        json.put("quantity", purchase.getQuantity());
        putAccount(json, "buyer", purchase.getBuyerId());
        json.put("timestamp", purchase.getTimestamp());
        json.put("deliveryDeadlineTimestamp", purchase.getDeliveryDeadlineTimestamp());
        if (purchase.getNote() != null) {
            json.put("note", encryptedData(purchase.getNote()));
        }
        json.put("pending", purchase.isPending());
        if (purchase.getEncryptedGoods() != null) {
            json.put("goodsData", encryptedData(purchase.getEncryptedGoods()));
            json.put("goodsIsText", purchase.goodsIsText());
        }
        if (purchase.getFeedbackNotes() != null) {
            JSONArray feedbacks = new JSONArray();
            for (EncryptedData encryptedData : purchase.getFeedbackNotes()) {
                feedbacks.add(encryptedData(encryptedData));
            }
            json.put("feedbackNotes", feedbacks);
        }
        if (purchase.getPublicFeedbacks() != null) {
            JSONArray publicFeedbacks = new JSONArray();
            for (String publicFeedback : purchase.getPublicFeedbacks()) {
                publicFeedbacks.add(publicFeedback);
            }
            json.put("publicFeedbacks", publicFeedbacks);
        }
        if (purchase.getRefundNote() != null) {
            json.put("refundNote", encryptedData(purchase.getRefundNote()));
        }
        if (purchase.getDiscountNQT() > 0) {
            json.put("discountNQT", String.valueOf(purchase.getDiscountNQT()));
        }
        if (purchase.getRefundNQT() > 0) {
            json.put("refundNQT", String.valueOf(purchase.getRefundNQT()));
        }
        return json;
    }

    static JSONObject trade(Trade trade, boolean includeAssetInfo) {
        JSONObject json = new JSONObject();
        json.put("timestamp", trade.getTimestamp());
        json.put("quantityQNT", String.valueOf(trade.getQuantityQNT()));
        json.put("priceNQT", String.valueOf(trade.getPriceNQT()));
        json.put("asset", Convert.toUnsignedLong(trade.getAssetId()));
        json.put("askOrder", Convert.toUnsignedLong(trade.getAskOrderId()));
        json.put("bidOrder", Convert.toUnsignedLong(trade.getBidOrderId()));
        json.put("askOrderHeight", trade.getAskOrderHeight());
        json.put("bidOrderHeight", trade.getBidOrderHeight());
        putAccount(json, "seller", trade.getSellerId());
        putAccount(json, "buyer", trade.getBuyerId());
        json.put("block", Convert.toUnsignedLong(trade.getBlockId()));
        json.put("height", trade.getHeight());
        json.put("tradeType", trade.isBuy() ? "buy" : "sell");
        if (includeAssetInfo) {
            putAssetInfo(json, trade.getAssetId());
        }
        return json;
    }

    static JSONObject assetTransfer(AssetTransfer assetTransfer, boolean includeAssetInfo) {
        JSONObject json = new JSONObject();
        json.put("assetTransfer", Convert.toUnsignedLong(assetTransfer.getId()));
        json.put("asset", Convert.toUnsignedLong(assetTransfer.getAssetId()));
        putAccount(json, "sender", assetTransfer.getSenderId());
        putAccount(json, "recipient", assetTransfer.getRecipientId());
        json.put("quantityQNT", String.valueOf(assetTransfer.getQuantityQNT()));
        json.put("height", assetTransfer.getHeight());
        json.put("timestamp", assetTransfer.getTimestamp());
        if (includeAssetInfo) {
            putAssetInfo(json, assetTransfer.getAssetId());
        }
        return json;
    }

    static JSONObject currencyTransfer(CurrencyTransfer transfer, boolean includeCurrencyInfo) {
        JSONObject json = new JSONObject();
        json.put("transfer", Convert.toUnsignedLong(transfer.getId()));
        json.put("currency", Convert.toUnsignedLong(transfer.getCurrencyId()));
        putAccount(json, "sender", transfer.getSenderId());
        putAccount(json, "recipient", transfer.getRecipientId());
        json.put("units", String.valueOf(transfer.getUnits()));
        json.put("height", transfer.getHeight());
        json.put("timestamp", transfer.getTimestamp());
        if (includeCurrencyInfo) {
            putCurrencyInfo(json, transfer.getCurrencyId());
        }
        return json;
    }

    static JSONObject exchange(Exchange exchange, boolean includeCurrencyInfo) {
        JSONObject json = new JSONObject();
        json.put("transaction", Convert.toUnsignedLong(exchange.getTransactionId()));
        json.put("timestamp", exchange.getTimestamp());
        json.put("units", String.valueOf(exchange.getUnits()));
        json.put("rateNQT", String.valueOf(exchange.getRate()));
        json.put("currency", Convert.toUnsignedLong(exchange.getCurrencyId()));
        json.put("offer", Convert.toUnsignedLong(exchange.getOfferId()));
        putAccount(json, "seller", exchange.getSellerId());
        putAccount(json, "buyer", exchange.getBuyerId());
        json.put("block", Convert.toUnsignedLong(exchange.getBlockId()));
        json.put("height", exchange.getHeight());
        if (includeCurrencyInfo) {
            putCurrencyInfo(json, exchange.getCurrencyId());
        }
        return json;
    }

    static JSONObject exchangeRequest(Transaction transaction, boolean includeCurrencyInfo) {
        JSONObject json = new JSONObject();
        json.put("transaction", Convert.toUnsignedLong(transaction.getId()));
        json.put("subtype", transaction.getType().getSubtype());
        Attachment.MonetarySystemExchange attachment = (Attachment.MonetarySystemExchange) transaction.getAttachment();
        json.put("timestamp", transaction.getTimestamp());
        json.put("units", String.valueOf(attachment.getUnits()));
        json.put("rateNQT", String.valueOf(attachment.getRateNQT()));
        if (includeCurrencyInfo) {
            putCurrencyInfo(json, attachment.getCurrencyId());
        }
        return json;
    }

    static JSONObject unconfirmedTransaction(Transaction transaction) {
        JSONObject json = new JSONObject();
        json.put("type", transaction.getType().getType());
        json.put("subtype", transaction.getType().getSubtype());
        json.put("timestamp", transaction.getTimestamp());
        json.put("deadline", transaction.getDeadline());
        json.put("senderPublicKey", Convert.toHexString(transaction.getSenderPublicKey()));
        if (transaction.getRecipientId() != 0) {
            putAccount(json, "recipient", transaction.getRecipientId());
        }
        json.put("amountNQT", String.valueOf(transaction.getAmountNQT()));
        json.put("feeNQT", String.valueOf(transaction.getFeeNQT()));
        if (transaction.getReferencedTransactionFullHash() != null) {
            json.put("referencedTransactionFullHash", transaction.getReferencedTransactionFullHash());
        }
        byte[] signature = Convert.emptyToNull(transaction.getSignature());
        if (signature != null) {
            json.put("signature", Convert.toHexString(signature));
            json.put("signatureHash", Convert.toHexString(Crypto.sha256().digest(signature)));
            json.put("fullHash", transaction.getFullHash());
            json.put("transaction", transaction.getStringId());
        }
        JSONObject attachmentJSON = new JSONObject();
        for (Appendix appendage : transaction.getAppendages()) {
            attachmentJSON.putAll(appendage.getJSONObject());
        }
        if (! attachmentJSON.isEmpty()) {
            for (Map.Entry entry : (Iterable<Map.Entry>) attachmentJSON.entrySet()) {
                if (entry.getValue() instanceof Long) {
                    entry.setValue(String.valueOf(entry.getValue()));
                }
            }
            json.put("attachment", attachmentJSON);
        }
        putAccount(json, "sender", transaction.getSenderId());
        json.put("height", transaction.getHeight());
        json.put("version", transaction.getVersion());
        if (transaction.getVersion() > 0) {
            json.put("ecBlockId", Convert.toUnsignedLong(transaction.getECBlockId()));
            json.put("ecBlockHeight", transaction.getECBlockHeight());
        }

        return json;
    }

    static JSONObject transaction(Transaction transaction) {
        JSONObject json = unconfirmedTransaction(transaction);
        json.put("block", Convert.toUnsignedLong(transaction.getBlockId()));
        json.put("confirmations", Nxt.getBlockchain().getHeight() - transaction.getHeight());
        json.put("blockTimestamp", transaction.getBlockTimestamp());
        json.put("transactionIndex", transaction.getIndex());
        return json;
    }

    static void putAccount(JSONObject json, String name, long accountId) {
        json.put(name, Convert.toUnsignedLong(accountId));
        json.put(name + "RS", Convert.rsAccount(accountId));
    }

    static void putCurrencyInfo(JSONObject json, long currencyId) {
        Currency currency = Currency.getCurrency(currencyId);
        if (currency == null) {
            return;
        }
        json.put("name", currency.getName());
        json.put("code", currency.getCode());
        json.put("type", currency.getType());
        json.put("decimals", currency.getDecimals());
        json.put("issuanceHeight", currency.getIssuanceHeight());
        putAccount(json, "issuerAccount", currency.getAccountId());
    }

    static void putAssetInfo(JSONObject json, long assetId) {
        Asset asset = Asset.getAsset(assetId);
        json.put("name", asset.getName());
        json.put("decimals", asset.getDecimals());
    }

    private JSONData() {} // never

}


text:
/* @flow */

const url = require(`url`)
const glob = require(`glob`)
const fs = require(`fs`)
const openurl = require(`better-opn`)
const chokidar = require(`chokidar`)
const express = require(`express`)
const graphqlHTTP = require(`express-graphql`)
const graphqlPlayground = require(`graphql-playground-middleware-express`)
  .default
const graphiqlExplorer = require(`gatsby-graphiql-explorer`)
const { formatError } = require(`graphql`)
const got = require(`got`)
const rl = require(`readline`)
const webpack = require(`webpack`)
const webpackConfig = require(`../utils/webpack.config`)
const bootstrap = require(`../bootstrap`)
const { store, emitter } = require(`../redux`)
const { syncStaticDir } = require(`../utils/get-static-dir`)
const buildHTML = require(`./build-html`)
const { withBasePath } = require(`../utils/path`)
const report = require(`gatsby-cli/lib/reporter`)
const launchEditor = require(`react-dev-utils/launchEditor`)
const formatWebpackMessages = require(`react-dev-utils/formatWebpackMessages`)
const chalk = require(`chalk`)
const address = require(`address`)
const cors = require(`cors`)
const telemetry = require(`gatsby-telemetry`)
const WorkerPool = require(`../utils/worker/pool`)

const withResolverContext = require(`../schema/context`)
const sourceNodes = require(`../utils/source-nodes`)
const websocketManager = require(`../utils/websocket-manager`)
const getSslCert = require(`../utils/get-ssl-cert`)
const slash = require(`slash`)
const { initTracer } = require(`../utils/tracer`)
const apiRunnerNode = require(`../utils/api-runner-node`)
const db = require(`../db`)
const detectPortInUseAndPrompt = require(`../utils/detect-port-in-use-and-prompt`)
const onExit = require(`signal-exit`)
const queryUtil = require(`../query`)
const queryQueue = require(`../query/queue`)
const queryWatcher = require(`../query/query-watcher`)
const requiresWriter = require(`../bootstrap/requires-writer`)

// const isInteractive = process.stdout.isTTY

// Watch the static directory and copy files to public as they're added or
// changed. Wait 10 seconds so copying doesn't interfere with the regular
// bootstrap.
setTimeout(() => {
  syncStaticDir()
}, 10000)

const rlInterface = rl.createInterface({
  input: process.stdin,
  output: process.stdout,
})

// Quit immediately on hearing ctrl-c
rlInterface.on(`SIGINT`, () => {
  process.exit()
})

onExit(() => {
  telemetry.trackCli(`DEVELOP_STOP`)
})

const waitJobsFinished = () =>
  new Promise((resolve, reject) => {
    const onEndJob = () => {
      if (store.getState().jobs.active.length === 0) {
        resolve()
        emitter.off(`END_JOB`, onEndJob)
      }
    }
    emitter.on(`END_JOB`, onEndJob)
    onEndJob()
  })

async function startServer(program) {
  const directory = program.directory
  const directoryPath = withBasePath(directory)
  const workerPool = WorkerPool.create()
  const createIndexHtml = async () => {
    try {
      await buildHTML.buildPages({
        program,
        stage: `develop-html`,
        pagePaths: [`/`],
        workerPool,
      })
    } catch (err) {
      if (err.name !== `WebpackError`) {
        report.panic(err)
        return
      }
      report.panic(
        report.stripIndent`
          There was an error compiling the html.js component for the development server.

          See our docs page on debugging HTML builds for help https://gatsby.dev/debug-html
        `,
        err
      )
    }
  }

  await createIndexHtml()

  const devConfig = await webpackConfig(
    program,
    directory,
    `develop`,
    program.port
  )

  const compiler = webpack(devConfig)

  /**
   * Set up the express app.
   **/
  const app = express()
  app.use(telemetry.expressMiddleware(`DEVELOP`))
  app.use(
    require(`webpack-hot-middleware`)(compiler, {
      log: false,
      path: `/__webpack_hmr`,
      heartbeat: 10 * 1000,
    })
  )

  app.use(cors())

  /**
   * Pattern matching all endpoints with graphql or graphiql with 1 or more leading underscores
   */
  const graphqlEndpoint = `/_+graphi?ql`

  if (process.env.GATSBY_GRAPHQL_IDE === `playground`) {
    app.get(
      graphqlEndpoint,
      graphqlPlayground({
        endpoint: `/___graphql`,
      }),
      () => {}
    )
  } else {
    graphiqlExplorer(app, {
      graphqlEndpoint,
    })
  }

  app.use(
    graphqlEndpoint,
    graphqlHTTP(() => {
      const schema = store.getState().schema
      return {
        schema,
        graphiql: false,
        context: withResolverContext({}, schema),
        formatError(err) {
          return {
            ...formatError(err),
            stack: err.stack ? err.stack.split(`\n`) : [],
          }
        },
      }
    })
  )

  /**
   * Refresh external data sources.
   * This behavior is disabled by default, but the ENABLE_REFRESH_ENDPOINT env var enables it
   * If no GATSBY_REFRESH_TOKEN env var is available, then no Authorization header is required
   **/
  app.post(`/__refresh`, (req, res) => {
    const enableRefresh = process.env.ENABLE_GATSBY_REFRESH_ENDPOINT
    const refreshToken = process.env.GATSBY_REFRESH_TOKEN
    const authorizedRefresh =
      !refreshToken || req.headers.authorization === refreshToken

    if (enableRefresh && authorizedRefresh) {
      console.log(`Refreshing source data`)
      sourceNodes()
    }
    res.end()
  })

  app.get(`/__open-stack-frame-in-editor`, (req, res) => {
    launchEditor(req.query.fileName, req.query.lineNumber)
    res.end()
  })

  // Disable directory indexing i.e. serving index.html from a directory.
  // This can lead to serving stale html files during development.
  //
  // We serve by default an empty index.html that sets up the dev environment.
  app.use(require(`./develop-static`)(`public`, { index: false }))

  app.use(
    require(`webpack-dev-middleware`)(compiler, {
      logLevel: `trace`,
      publicPath: devConfig.output.publicPath,
      stats: `errors-only`,
    })
  )

  // Expose access to app for advanced use cases
  const { developMiddleware } = store.getState().config

  if (developMiddleware) {
    developMiddleware(app)
  }

  // Set up API proxy.
  const { proxy } = store.getState().config
  if (proxy) {
    const { prefix, url } = proxy
    app.use(`${prefix}/*`, (req, res) => {
      const proxiedUrl = url + req.originalUrl
      const {
        // remove `host` from copied headers
        // eslint-disable-next-line no-unused-vars
        headers: { host, ...headers },
        method,
      } = req
      req
        .pipe(
          got
            .stream(proxiedUrl, { headers, method, decompress: false })
            .on(`response`, response =>
              res.writeHead(response.statusCode, response.headers)
            )
            .on(`error`, (err, _, response) => {
              if (response) {
                res.writeHead(response.statusCode, response.headers)
              } else {
                const message = `Error when trying to proxy request "${
                  req.originalUrl
                }" to "${proxiedUrl}"`

                report.error(message, err)
                res.sendStatus(500)
              }
            })
        )
        .pipe(res)
    })
  }

  await apiRunnerNode(`onCreateDevServer`, { app })

  // In case nothing before handled hot-update - send 404.
  // This fixes "Unexpected token < in JSON at position 0" runtime
  // errors after restarting development server and
  // cause automatic hard refresh in the browser.
  app.use(/.*\.hot-update\.json$/i, (req, res) => {
    res.status(404).end()
  })

  // Render an HTML page and serve it.
  app.use((req, res, next) => {
    res.sendFile(directoryPath(`public/index.html`), err => {
      if (err) {
        res.status(500).end()
      }
    })
  })

  /**
   * Set up the HTTP server and socket.io.
   **/
  let server = require(`http`).Server(app)

  // If a SSL cert exists in program, use it with `createServer`.
  if (program.ssl) {
    server = require(`https`).createServer(program.ssl, app)
  }
  websocketManager.init({ server, directory: program.directory })
  const socket = websocketManager.getSocket()

  const listener = server.listen(program.port, program.host, err => {
    if (err) {
      if (err.code === `EADDRINUSE`) {
        // eslint-disable-next-line max-len
        report.panic(
          `Unable to start Gatsby on port ${
            program.port
          } as there's already a process listening on that port.`
        )
        return
      }

      report.panic(`There was a problem starting the development server`, err)
    }
  })

  // Register watcher that rebuilds index.html every time html.js changes.
  const watchGlobs = [`src/html.js`, `plugins/**/gatsby-ssr.js`].map(path =>
    slash(directoryPath(path))
  )

  chokidar.watch(watchGlobs).on(`change`, async () => {
    await createIndexHtml()
    socket.to(`clients`).emit(`reload`)
  })

  return [compiler, listener]
}

module.exports = async (program: any) => {
  initTracer(program.openTracingConfigFile)
  telemetry.trackCli(`DEVELOP_START`)
  telemetry.startBackgroundUpdate()

  const port =
    typeof program.port === `string` ? parseInt(program.port, 10) : program.port

  // In order to enable custom ssl, --cert-file --key-file and -https flags must all be
  // used together
  if ((program[`cert-file`] || program[`key-file`]) && !program.https) {
    report.panic(
      `for custom ssl --https, --cert-file, and --key-file must be used together`
    )
  }

  // Check if https is enabled, then create or get SSL cert.
  // Certs are named after `name` inside the project's package.json.
  // Scoped names are converted from @npm/package-name to npm--package-name
  if (program.https) {
    program.ssl = await getSslCert({
      name: program.sitePackageJson.name.replace(`@`, ``).replace(`/`, `--`),
      certFile: program[`cert-file`],
      keyFile: program[`key-file`],
      directory: program.directory,
    })
  }

  program.port = await detectPortInUseAndPrompt(port, rlInterface)
  // Start bootstrap process.
  const { graphqlRunner } = await bootstrap(program)

  // Start the createPages hot reloader.
  require(`../bootstrap/page-hot-reloader`)(graphqlRunner)

  const queryIds = queryUtil.calcInitialDirtyQueryIds(store.getState())
  const { staticQueryIds, pageQueryIds } = queryUtil.groupQueryIds(queryIds)

  let activity = report.activityTimer(`run static queries`)
  activity.start()
  await queryUtil.processStaticQueries(staticQueryIds, {
    activity,
    state: store.getState(),
  })
  activity.end()

  activity = report.activityTimer(`run page queries`)
  activity.start()
  await queryUtil.processPageQueries(pageQueryIds, { activity })
  activity.end()

  require(`../redux/actions`).boundActionCreators.setProgramStatus(
    `BOOTSTRAP_QUERY_RUNNING_FINISHED`
  )

  await waitJobsFinished()
  requiresWriter.startListener()
  db.startAutosave()
  queryUtil.startListening(queryQueue.createDevelopQueue())
  queryWatcher.startWatchDeletePage()

  const [compiler] = await startServer(program)

  function prepareUrls(protocol, host, port) {
    const formatUrl = hostname =>
      url.format({
        protocol,
        hostname,
        port,
        pathname: `/`,
      })
    const prettyPrintUrl = hostname =>
      url.format({
        protocol,
        hostname,
        port: chalk.bold(port),
        pathname: `/`,
      })

    const isUnspecifiedHost = host === `0.0.0.0` || host === `::`
    let lanUrlForConfig, lanUrlForTerminal
    if (isUnspecifiedHost) {
      try {
        // This can only return an IPv4 address
        lanUrlForConfig = address.ip()
        if (lanUrlForConfig) {
          // Check if the address is a private ip
          // https://en.wikipedia.org/wiki/Private_network#Private_IPv4_address_spaces
          if (
            /^10[.]|^172[.](1[6-9]|2[0-9]|3[0-1])[.]|^192[.]168[.]/.test(
              lanUrlForConfig
            )
          ) {
            // Address is private, format it for later use
            lanUrlForTerminal = prettyPrintUrl(lanUrlForConfig)
          } else {
            // Address is not private, so we will discard it
            lanUrlForConfig = undefined
          }
        }
      } catch (_e) {
        // ignored
      }
    }
    // TODO collect errors (GraphQL + Webpack) in Redux so we
    // can clear terminal and print them out on every compile.
    // Borrow pretty printing code from webpack plugin.
    const localUrlForTerminal = prettyPrintUrl(host)
    const localUrlForBrowser = formatUrl(host)
    return {
      lanUrlForConfig,
      lanUrlForTerminal,
      localUrlForTerminal,
      localUrlForBrowser,
    }
  }

  function printInstructions(appName, urls, useYarn) {
    report._setStage({
      stage: `DevelopBootstrapFinished`,
      context: {
        url: urls.localUrlForBrowser,
        appName,
      },
    })
    console.log(`You can now view ${chalk.bold(appName)} in the browser.`)
    console.log()

    if (urls.lanUrlForTerminal) {
      console.log(
        `  ${chalk.bold(`Local:`)}            ${urls.localUrlForTerminal}`
      )
      console.log(
        `  ${chalk.bold(`On Your Network:`)}  ${urls.lanUrlForTerminal}`
      )
    } else {
      console.log(`  ${urls.localUrlForTerminal}`)
    }

    console.log()
    console.log(
      `View ${
        process.env.GATSBY_GRAPHQL_IDE === `playground`
          ? `the GraphQL Playground`
          : `GraphiQL`
      }, an in-browser IDE, to explore your site's data and schema`
    )
    console.log()
    console.log(`  ${urls.localUrlForTerminal}___graphql`)

    console.log()
    console.log(`Note that the development build is not optimized.`)
    console.log(
      `To create a production build, use ` + `${chalk.cyan(`npm run build`)}`
    )
    console.log()
  }

  function printDeprecationWarnings() {
    const deprecatedApis = [`boundActionCreators`, `pathContext`]
    const fixMap = {
      boundActionCreators: {
        newName: `actions`,
        docsLink: `https://gatsby.dev/boundActionCreators`,
      },
      pathContext: {
        newName: `pageContext`,
        docsLink: `https://gatsby.dev/pathContext`,
      },
    }
    const deprecatedLocations = {}
    deprecatedApis.forEach(api => (deprecatedLocations[api] = []))

    glob
      .sync(`{,!(node_modules|public)/**/}*.js`, { nodir: true })
      .forEach(file => {
        const fileText = fs.readFileSync(file)
        const matchingApis = deprecatedApis.filter(
          api => fileText.indexOf(api) !== -1
        )
        matchingApis.forEach(api => deprecatedLocations[api].push(file))
      })

    deprecatedApis.forEach(api => {
      if (deprecatedLocations[api].length) {
        console.log(
          `%s %s %s %s`,
          chalk.cyan(api),
          chalk.yellow(`is deprecated. Please use`),
          chalk.cyan(fixMap[api].newName),
          chalk.yellow(
            `instead. For migration instructions, see ${
              fixMap[api].docsLink
            }\nCheck the following files:`
          )
        )
        console.log()
        deprecatedLocations[api].forEach(file => console.log(file))
        console.log()
      }
    })
  }

  let isFirstCompile = true
  // "done" event fires when Webpack has finished recompiling the bundle.
  // Whether or not you have warnings or errors, you will get this event.
  compiler.hooks.done.tapAsync(`print getsby instructions`, (stats, done) => {
    // We have switched off the default Webpack output in WebpackDevServer
    // options so we are going to "massage" the warnings and errors and present
    // them in a readable focused way.
    const messages = formatWebpackMessages(stats.toJson({}, true))
    const urls = prepareUrls(
      program.ssl ? `https` : `http`,
      program.host,
      program.port
    )
    const isSuccessful = !messages.errors.length
    // if (isSuccessful) {
    // console.log(chalk.green(`Compiled successfully!`))
    // }
    // if (isSuccessful && (isInteractive || isFirstCompile)) {
    if (isSuccessful && isFirstCompile) {
      printInstructions(program.sitePackageJson.name, urls, program.useYarn)
      printDeprecationWarnings()
      if (program.open) {
        Promise.resolve(openurl(urls.localUrlForBrowser)).catch(err =>
          console.log(
            `${chalk.yellow(
              `warn`
            )} Browser not opened because no browser was found`
          )
        )
      }
    }

    isFirstCompile = false

    // If errors exist, only show errors.
    // if (messages.errors.length) {
    // // Only keep the first error. Others are often indicative
    // // of the same problem, but confuse the reader with noise.
    // if (messages.errors.length > 1) {
    // messages.errors.length = 1
    // }
    // console.log(chalk.red("Failed to compile.\n"))
    // console.log(messages.errors.join("\n\n"))
    // return
    // }

    // Show warnings if no errors were found.
    // if (messages.warnings.length) {
    // console.log(chalk.yellow("Compiled with warnings.\n"))
    // console.log(messages.warnings.join("\n\n"))

    // // Teach some ESLint tricks.
    // console.log(
    // "\nSearch for the " +
    // chalk.underline(chalk.yellow("keywords")) +
    // " to learn more about each warning."
    // )
    // console.log(
    // "To ignore, add " +
    // chalk.cyan("// eslint-disable-next-line") +
    // " to the line before.\n"
    // )
    // }

    done()
  })
}


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

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.5"/>
<title>CTPy: ctpy.data.pergeneration_stats_traits.PerGenerationStatsTraits.__mongometa__ Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

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

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

CTPy
    1.0.3

Cultural Transmission using simuPOP

Main Page

Related Pages

Classes

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Class List

Class Index

Class Hierarchy

Class Members

 All Classes Functions Variables Pages

ctpy

data

pergeneration_stats_traits

PerGenerationStatsTraits

__mongometa__

Static Public Attributes |
List of all members

ctpy.data.pergeneration_stats_traits.PerGenerationStatsTraits.__mongometa__ Class Reference

Static Public Attributes

tuple 	session = Session.by_name(_get_dataobj_id())

string 	name = 'pergeneration_stats_traits'

tuple 	simulation_run_id = Field(str)

tuple 	simulation_time = Field(int)

tuple 	replication = Field(int)

tuple 	sample_size = Field(int)

tuple 	population_size = Field(int)

tuple 	mutation_rate = Field(float)

tuple 	dimensionality = Field(int)

tuple 	mean_trait_richness = Field(float)

tuple 	mean_evenness_shannon_entropy = Field(float)

tuple 	mean_evenness_iqv = Field(float)

tuple 	loci_trait_richness = Field([int])

tuple 	loci_evenness_shannon_entropy = Field([float])

tuple 	loci_evenness_iqv = Field([float])

tuple 	loci_neutrality_slatkin = Field([float])

tuple 	mean_neutrality_slatkin = Field(float)

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

ctpy/data/pergeneration_stats_traits.py

<address class="footer">
Generated on Sun Oct 13 2013 16:46:26 for CTPy by

 1.8.5
</address>


text:
const React = require('react');
const PubComponent = require('./pub-component');
import {Link} from 'react-router-dom';

function pubList(pubs) {

    return pubs.map(pub =>
        <PubComponent key={pub.Index} pub={pub}/>
    );
}

function getPubImg(name) {
    const val = (name.charCodeAt(0) % 3) + 1;

    return `/assets/img/PubIcon${val}.png`;
}

class PubCrawlComponent extends React.Component {
    render(){
        return (

                        <Link key={this.props.pubCrawl.UserID + this.props.pubCrawl.PubCrawlName} to={`/pubCrawl?id=${this.props.pubCrawl.PubCrawlName}`}>
                            {this.props.pubCrawl.PubCrawlName}
                        </Link>

By {this.props.pubCrawl.UserID}

                        {pubList(this.props.pubCrawl.PubCrawlItem)}

        );
    }
}

module.exports = PubCrawlComponent;


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN""http://www.w3.org/TR/REC-html40/loose.dtd">

<TITLE>
VerticalTabbedPane.VerticalTextIcon
</TITLE>
<LINK REL ="stylesheet" TYPE="text/css" HREF="stylesheet.css" TITLE="Style">

            Package

    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

Class  VerticalTabbedPane.VerticalTextIcon

java.lang.Object
  |
  +--VerticalTabbedPane.VerticalTextIcon

All Implemented Interfaces:
javax.swing.Icon

Enclosing class:
VerticalTabbedPane

private class VerticalTabbedPane.VerticalTextIcon
extends java.lang.Object
implements javax.swing.Icon

Field Summary

private  boolean
m_bClockwise

private  java.lang.String
m_sText

Constructor Summary

VerticalTabbedPane.VerticalTextIcon(java.lang.String sText,
                                    boolean bClockwise)

Method Summary

 int
getIconHeight()

 int
getIconWidth()

 void
paintIcon(java.awt.Component c,
          java.awt.Graphics g,
          int x,
          int y)

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

m_sText

private java.lang.String m_sText

m_bClockwise

private boolean m_bClockwise

Constructor Detail

VerticalTabbedPane.VerticalTextIcon

public VerticalTabbedPane.VerticalTextIcon(java.lang.String sText,
                                           boolean bClockwise)

Method Detail

paintIcon

public void paintIcon(java.awt.Component c,
                      java.awt.Graphics g,
                      int x,
                      int y)

Specified by:
paintIcon in interface javax.swing.Icon

getIconWidth

public int getIconWidth()

Specified by:
getIconWidth in interface javax.swing.Icon

getIconHeight

public int getIconHeight()

Specified by:
getIconHeight in interface javax.swing.Icon

            Package

    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text:
require 'perobs/Log'

module PEROBS

  # The FlatFile blob header has the following structure:
  #
  # 1 Byte:  Flags byte.
  #          Bit 0: 0 deleted entry, 1 valid entry
  #          Bit 1: 0 reserved, must be 0
  #          Bit 2: 0 uncompressed data, 1 compressed data
  #          Bit 3: 0 current entry, 1 outdated entry
  #          Bit 4 - 7: reserved, must be 0
  # 8 bytes: Length of the data blob in bytes
  # 8 bytes: ID of the value in the data blob
  # 4 bytes: CRC32 checksum of the data blob
  #
  # If the bit 0 of the flags byte is 0, only the length is valid. The blob is
  # empty. Only of bit 0 is set then entry is valid.
  class FlatFileBlobHeader

    # The 'pack()' format of the header.
    FORMAT = 'CQQL'
    # The length of the header in bytes.
    LENGTH = 25
    VALID_FLAG_BIT = 0
    COMPRESSED_FLAG_BIT = 2
    OUTDATED_FLAG_BIT = 3

    attr_reader :addr, :flags, :length, :id, :crc
    attr_accessor :corruption_start

    # Create a new FlatFileBlobHeader with the given flags, length, id and crc.
    # @param file [File] the FlatFile that contains the header
    # @param addr [Integer] the offset address of the header in the file
    # @param flags [Integer] 8 bit number, see above
    # @param length [Integer] length of the header in bytes
    # @param id [Integer] ID of the blob entry
    # @param crc [Integer] CRC32 checksum of the blob entry
    def initialize(file, addr, flags, length, id, crc)
      @file = file
      @addr = addr
      @flags = flags
      @length = length
      @id = id
      @crc = crc
      # This is only set if the header is preceded by a corrupted blob.
      @corruption_start = nil
    end

    # Read the header from the given File.
    # @param file [File]
    # @param addr [Integer] address in the file to start reading. If no
    #        address is specified use the current position in the file.
    # @param id [Integer] Optional ID that the header should have. If no id is
    #        specified there is no check against the actual ID done.
    # @return FlatFileBlobHeader or nil if there are no more blobs to read in
    #         the file.
    def FlatFileBlobHeader::read(file, addr = nil, id = nil)
      # If an address was specified we expect the read to always succeed. If
      # no address is specified and we can't read the header we generate an
      # error message but it is not fatal.
      errors_are_fatal = !addr.nil?

      mode = :searching_next_header
      addr = file.pos unless addr
      buf = nil
      corruption_start = nil

      loop do
        buf_with_crc = nil
        begin
          file.seek(addr)
          buf_with_crc = file.read(LENGTH)
        rescue IOError => e
          if errors_are_fatal
            PEROBS.log.fatal "Cannot read blob header in flat file DB at " +
              "address #{addr}: #{e.message}"
          else
            PEROBS.log.error "Cannot read blob header in flat file DB: " +
              e.message
            return nil
          end
        end

        # Did we read anything?
        if buf_with_crc.nil?
          if errors_are_fatal
            PEROBS.log.fatal "Cannot read blob header " +
              "#{id ? "for ID #{id} " : ''}at address #{addr}"
          else
            if corruption_start
              PEROBS.log.error "Corruption found at end of blob file at " +
                "address #{addr}"
            end
            # We have reached the end of the file.
            return nil
          end
        end

        # Did we get the full header?
        if buf_with_crc.length != LENGTH
          msg = "Incomplete FlatFileBlobHeader: Only " +
            "#{buf_with_crc.length} " +
            "bytes of #{LENGTH} could be read "
          "#{id ? "for ID #{id} " : ''}at address #{addr}"
          if errors_are_fatal
            PEROBS.log.fatal msg
          else
            PEROBS.log.error msg
          end
          return nil
        end

        # Check the CRC of the header
        buf = buf_with_crc[0..-5]
        crc = buf_with_crc[-4..-1].unpack('L')[0]

        if (read_crc = Zlib.crc32(buf, 0)) == crc
          # We have found a valid header.
          if corruption_start
            PEROBS.log.error "FlatFile corruption ends at #{addr}. " +
              "#{addr - corruption_start} bytes skipped. Some data may " +
              "not be recoverable."
          end
          break
        else
          if errors_are_fatal
            PEROBS.log.fatal "FlatFile Header CRC mismatch at address " +
              "#{addr}. Header CRC is #{'%08x' % read_crc} but should be " +
              "#{'%08x' % crc}."
          else
            if corruption_start.nil?
              if errors_are_fatal
                PEROBS.log.fatal "FlatFile corruption found. The FlatFile " +
                  "Header CRC mismatch at address #{addr}. Header CRC is " +
                  "#{'%08x' % read_crc} but should be #{'%08x' % crc}."
              else
                PEROBS.log.error "FlatFile corruption found. The FlatFile " +
                  "Header CRC mismatch at address #{addr}. Header CRC is " +
                  "#{'%08x' % read_crc} but should be #{'%08x' % crc}. " +
                  "Trying to find the next header."
              end
              corruption_start = addr
            end
            # The blob file is corrupted. There is no valid header at the
            # current position in the file. We now try to find the next valid
            # header by iterating over the remainder of the file advanding one
            # byte with each step until we hit the end of the file or find the
            # next valid header.
            addr += 1
          end
        end
      end

      header = FlatFileBlobHeader.new(file, addr, *buf.unpack(FORMAT))
      if corruption_start
        header.corruption_start = corruption_start
      end

      if id && header.id != id
        PEROBS.log.fatal "Mismatch between FlatFile index and blob file " +
          "found. FlatFile has entry with ID #{header.id} at address " +
          "#{addr}. Index has ID #{id} for this address."
      end

      return header
    end

    # Write the header to a given File.
    def write
      begin
        buf = [ @flags, @length, @id, @crc].pack(FORMAT)
        crc = Zlib.crc32(buf, 0)
        @file.seek(@addr)
        @file.write(buf + [ crc ].pack('L'))
      rescue IOError => e
        PEROBS.log.fatal "Cannot write blob header into flat file DB: " +
          e.message
      end
    end

    # Reset all the flags bit to 0. This marks the blob as invalid.
    def clear_flags
      @flags = 0
      write
    end

    # Return true if the header is for a non-empty blob.
    def is_valid?
      bit_set?(VALID_FLAG_BIT)
    end

    # Return true if the blob contains compressed data.
    def is_compressed?
      bit_set?(COMPRESSED_FLAG_BIT)
    end

    # Set the outdated bit. The entry will be invalid as soon as the current
    # transaction has been completed.
    def set_outdated_flag
      set_flag(OUTDATED_FLAG_BIT)
      write
    end

    # Return true if the blob contains outdated data.
    def is_outdated?
      bit_set?(OUTDATED_FLAG_BIT)
    end

    private

    def bit_set?(n)
      mask = 1 << n
      @flags & mask == mask
    end

    def set_flag(n)
      @flags |= (1 << n)
    end

    def clear_flag(n)
      @flags &= ~(1 << n) & 0xFF
    end

  end

end


text:
import React, { PropTypes as T } from 'react';

import Card from 'components/Card';

export default class Item extends React.Component {
  static propTypes = {
    place: T.object.isRequired,
  }

  render() {
    const { place } = this.props;

    if (!place) { return null; }

    // Link should be /place/type/zone/key
    let link = '';

    switch (place.type) {
      case 'exhibit':
        link = `/${place.type}/${place.colorZone}/${place.exhibitCode}/${place.key}`;
        break;
      case 'facilities':
        link = `/${place.type}/${place.colorZone}/${place.subType}/${place.key}`;
        break;
      default:
        link = null;
        break;
    }

    // Check if the second letter or place.location is not a number
    // If it is, use location
    // Otherwise use exhibit code
    const room = (isNaN(place.location) && isNaN(place.location.charAt(1)))
      ? place.location
      : place.exhibitCode;
    const location = `${place.building}, ${room}`;

    const cardInfo = {
      link,
      place,
      location,
      name: place.name,
      zone: place.imagineRitArea,
      zoneClass: place.colorZone,
    };

    return (
      <Card
        place={cardInfo}
      />
    );
  }
}


text:
Inspired loosely by the Lisp seen [here](www.buildyourownlisp.com/). Mostly it
takes the parsing technology and the nomenclature. Notably Q-expressions are
the thing I bring over, denoted by {} Q-expressions are loosly equivalent to
LISP macros in that they stop evaluation of whatever is contained within them.

To build tests I suggest 'make -s tests'

# Goals

The goal isn't necessarily to create a REPL (I might implement one though),
but rather to make an easily embeddable Lisp interpreter for use in larger
programs to do things C normally wouldn't pull of comfortably (Read: AI and
metaprogramming and Greenspun's 10th)

## Status, By Module

### Memory
Currently working, though untested for arbitrarily large loads
Needs to be decoupled from lval modules in a big way. Currently the overlap
in function between lval manipulation and memory manipulation is causing
blockers in progress to the evaluator and environment.

### Parser
Reading from strings is currently implemented, I doubt it will change much.
That said it's not been tested on anything other than very simple valid and
invalid expressions.

Printing the structure resulting from the read step is implemented both to
strings and file pointers

### Lval
A work in progress, all manipulations of the lval type which aren't directly
related to managing memory are going through this module.

### Environment
Simple Environment management has been started on; C functions can be bound to
any valid symbol name.

Environments can now have parent/child relationships.

In language function binding and variable binding need to be implemented


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

    <title>Answers and Praises</title>
    <link rel="stylesheet" type="text/css" href="chrome://kneemail/skin/css/help.css">

Answers and Praises

Choose this menu item

        to show a list of all the answered prayer and praises in your journal. Just
        as you can with the Prayer Plan dialog, double-clicking an item on the list
        will bring up the Compose dialog if you want to edit the entry. This tool
        will help praising God for answered prayer. Below is a screenshot of the
        Answers and Praises dialog:


text:
import { Component } from '@angular/core';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html'
})

export class AppComponent {
    source: any =
    {
        localdata: this.generateData(),
        datatype: 'array',
        datafields:
        [
            { name: 'firstname', type: 'string' },
            { name: 'lastname', type: 'string' },
            { name: 'productname', type: 'string' },
            { name: 'quantity', type: 'number' },
            { name: 'price', type: 'number' },
            { name: 'total', type: 'number' }
        ]
    }

    dataAdapter: any = new jqx.dataAdapter(this.source);

    columns: any[] =
    [
        {
            text: '#', sortable: false, filterable: false, editable: false,
            groupable: false, draggable: false, resizable: false,
            datafield: '', columntype: 'number', width: 50,
            cellsrenderer: (row: number, column: any, value: number): string => {
                return '
' + (value + 1) + '
';
            }
        },
        { text: 'Name', datafield: 'firstname', width: 120 },
        { text: 'Last Name', datafield: 'lastname', width: 120 },
        { text: 'Product', datafield: 'productname', width: 180 },
        { text: 'Quantity', datafield: 'quantity', width: 80, cellsalign: 'right' },
        { text: 'Unit Price', datafield: 'price', width: 90, cellsalign: 'right', cellsformat: 'c2' },
        { text: 'Total', datafield: 'total', cellsalign: 'right', cellsformat: 'c2' }
    ];

    generateData(): any[] {
        let data = new Array();

        let firstNames =
            [
                'Andrew', 'Nancy', 'Shelley', 'Regina', 'Yoshi', 'Antoni', 'Mayumi', 'Ian', 'Peter', 'Lars', 'Petra', 'Martin', 'Sven', 'Elio', 'Beate', 'Cheryl', 'Michael', 'Guylene'
            ];

        let lastNames =
            [
                'Fuller', 'Davolio', 'Burke', 'Murphy', 'Nagase', 'Saavedra', 'Ohno', 'Devling', 'Wilson', 'Peterson', 'Winkler', 'Bein', 'Petersen', 'Rossi', 'Vileid', 'Saylor', 'Bjorn', 'Nodier'
            ];

        let productNames =
            [
                'Black Tea', 'Green Tea', 'Caffe Espresso', 'Doubleshot Espresso', 'Caffe Latte', 'White Chocolate Mocha', 'Cramel Latte', 'Caffe Americano', 'Cappuccino', 'Espresso Truffle', 'Espresso con Panna', 'Peppermint Mocha Twist'
            ];

        let priceValues =
            [
                '2.25', '1.5', '3.0', '3.3', '4.5', '3.6', '3.8', '2.5', '5.0', '1.75', '3.25', '4.0'
            ];

        for (let i = 0; i < 200; i++) {
            let row = {};
            let productindex = Math.floor(Math.random() * productNames.length);
            let price = parseFloat(priceValues[productindex]);
            let quantity = 1 + Math.round(Math.random() * 10);
            row['firstname'] = firstNames[Math.floor(Math.random() * firstNames.length)];
            row['lastname'] = lastNames[Math.floor(Math.random() * lastNames.length)];
            row['productname'] = productNames[productindex];
            row['price'] = price;
            row['quantity'] = quantity;
            row['total'] = price * quantity;
            data[i] = row;
        }

        return data;
    }
}


text:
order: 14
title:
  zh-CN: 弹出层中的新建表单
  en-US: Form in Modal to Create
---

## zh-CN

当用户访问一个展示了某个列表的页面,想新建一项但又不想跳转页面时,可以用 Modal 弹出一个表单,用户填写必要信息后创建新的项。

> 🛎 想要 3 分钟实现?试试 ProForm 的 [Modal 表单](https://procomponents.ant.design/components/form#modal-%E8%A1%A8%E5%8D%95)!

## en-US

When user visit a page with a list of items, and want to create a new item. The page can popup a form in Modal, then let user fill in the form to create an item.

```tsx
import { Button, Form, Input, Modal, Radio } from 'antd';
import React, { useState } from 'react';

interface Values {
  title: string;
  description: string;
  modifier: string;
}

interface CollectionCreateFormProps {
  open: boolean;
  onCreate: (values: Values) => void;
  onCancel: () => void;
}

const CollectionCreateForm: React.FC<CollectionCreateFormProps> = ({
  open,
  onCreate,
  onCancel,
}) => {
  const [form] = Form.useForm();
  return (
    <Modal
      open={open}
      title="Create a new collection"
      okText="Create"
      cancelText="Cancel"
      onCancel={onCancel}
      onOk={() => {
        form
          .validateFields()
          .then(values => {
            form.resetFields();
            onCreate(values);
          })
          .catch(info => {
            console.log('Validate Failed:', info);
          });
      }}
    >
      <Form
        form={form}
        layout="vertical"
        name="form_in_modal"
        initialValues={{ modifier: 'public' }}
      >
        <Form.Item
          name="title"
          label="Title"
          rules={[{ required: true, message: 'Please input the title of collection!' }]}
        >
          <Input />
        </Form.Item>
        <Form.Item name="description" label="Description">
          <Input type="textarea" />
        </Form.Item>
        <Form.Item name="modifier" className="collection-create-form_last-form-item">
          <Radio.Group>
            <Radio value="public">Public</Radio>
            <Radio value="private">Private</Radio>
          </Radio.Group>
        </Form.Item>
      </Form>
    </Modal>
  );
};

const App: React.FC = () => {
  const [open, setOpen] = useState(false);

  const onCreate = (values: any) => {
    console.log('Received values of form: ', values);
    setOpen(false);
  };

  return (
    <div>
      <Button
        type="primary"
        onClick={() => {
          setOpen(true);
        }}
      >
        New Collection
      </Button>
      <CollectionCreateForm
        open={open}
        onCreate={onCreate}
        onCancel={() => {
          setOpen(false);
        }}
      />
    </div>
  );
};

export default App;
```

```css
.collection-create-form_last-form-item {
  margin-bottom: 0;
}
```


text:
package com.yitong.weixin.modules.wechat.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.yitong.weixin.common.config.Global;
import com.yitong.weixin.common.persistence.Page;
import com.yitong.weixin.common.utils.DateUtils;
import com.yitong.weixin.common.utils.StringUtils;
import com.yitong.weixin.common.utils.excel.ExportExcel;
import com.yitong.weixin.common.web.BaseController;
import com.yitong.weixin.modules.sys.entity.User;
import com.yitong.weixin.modules.wechat.entity.WeixinMessage;
import com.yitong.weixin.modules.wechat.service.WeixinMessageService;

/**
 * 微信消息存储表Controller
 * @author Fwy
 * @version 2016-01-07
 */
@Controller
@RequestMapping(value = "${adminPath}/wechat/weixinMessage")
public class WeixinMessageController extends BaseController {

	@Autowired
	private WeixinMessageService weixinMessageService;

	@ModelAttribute
	public WeixinMessage get(@RequestParam(required=false) String id) {
		WeixinMessage entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = weixinMessageService.get(id);
		}
		if (entity == null){
			entity = new WeixinMessage();
		}
		return entity;
	}

	@RequestMapping(value = {"list", ""})
	public String list(WeixinMessage message, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<WeixinMessage> page = weixinMessageService.findPageGroupBy(new Page<WeixinMessage>(request, response), message);
		model.addAttribute("page", page);
		model.addAttribute("messageModel", message);
		return "modules/wechat/wx_message_list";
	}

	@RequestMapping("/findPageByMsgId")
	@ResponseBody
	public Page<WeixinMessage> findPageByMsgId(String msgId, HttpServletRequest request,
			HttpServletResponse response) {
		Page<WeixinMessage> page = new Page<WeixinMessage>(request, response);
		if(null == msgId) {
			return page;
		}
		return weixinMessageService.findPageByMsgId(page, msgId);
	}

	@RequiresPermissions("wechat:weixinMessage:view")
	@RequestMapping(value = "form")
	public String form(WeixinMessage weixinMessage, Model model) {
		model.addAttribute("weixinMessage", weixinMessage);
		return "modules/wechat/weixinMessageForm";
	}

	@RequiresPermissions("wechat:weixinMessage:edit")
	@RequestMapping(value = "save")
	public String save(WeixinMessage weixinMessage, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, weixinMessage)){
			return form(weixinMessage, model);
		}
		weixinMessageService.save(weixinMessage);
		addMessage(redirectAttributes, "保存消息成功");
		return "redirect:"+Global.getAdminPath()+"/wechat/weixinMessage/?repage";
	}

	@RequiresPermissions("wechat:weixinMessage:edit")
	@RequestMapping(value = "delete")
	public String delete(WeixinMessage weixinMessage, RedirectAttributes redirectAttributes) {
		weixinMessageService.delete(weixinMessage);
		addMessage(redirectAttributes, "删除消息成功");
		return "redirect:"+Global.getAdminPath()+"/wechat/weixinMessage/?repage";
	}

	/**
	 * 导出消息数据
	 * @param user
	 * @param request
	 * @param response
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("wechat:weixinMessage:edit")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(WeixinMessage message, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "消息数据"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<WeixinMessage> page = weixinMessageService.findPageGroupBy(new Page<WeixinMessage>(request, response, -1), message);
    		new ExportExcel("消息数据", WeixinMessage.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出消息失败!失败信息:"+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/wechat/weixinMessage/?repage";
    }

}


text:
FOUNDATION_EXPORT double CupidVersionNumber;

//! Project version string for Cupid.
FOUNDATION_EXPORT const unsigned char CupidVersionString[];

// In this header, you should import all the public headers of your framework using statements like #import <Cupid/PublicHeader.h>


text:
/*****************************************************
Author:				Johnny-Martin
Email:				970803555@qq.com
Date:				2017.9.17
Description:		äÖȾ²ßÂÔ¹ÜÀíÆ÷
*****************************************************/
#pragma once
#include "../stdafx.h"

class RenderManager
{
public:
	static HRESULT					Init();
	static HRESULT					UnInit();
#ifdef USE_D2D_RENDER_MODE
public:
	static ID2D1Factory*			m_pD2DFactory;
	static IDWriteFactory*			m_pD2DWriteFactory;
	static D2D1_PIXEL_FORMAT		m_gPixelFormat;
	static D2D1_BITMAP_PROPERTIES   m_gBitmapProperties;

#else
private:
	static ULONG_PTR				m_gdiplusToken;
	static GdiplusStartupInput		m_gdiStartupInput;
#endif
};

class UIObject;
class UIPos;
class RenderTarget
{
#ifdef USE_D2D_RENDER_MODE
public:
	virtual HRESULT					Draw(ID2D1RenderTarget* pRenderTarget, const RECT& rcInvalid, UIObject* pTargetObject = nullptr);
	virtual HRESULT					OnDrawImpl(ID2D1RenderTarget* pRenderTarget, const D2D1_RECT_F& rcWndPos) = 0;

protected:
	virtual HRESULT					CreateDeviceDependentResources(ID2D1RenderTarget* pRenderTarget) = 0;
	virtual HRESULT					DiscardDeviceDependentResources() = 0;
#else
public:
	virtual HRESULT					Draw(Graphics& graphics, const RECT& rcInvalid, UIObject* pTargetObject = nullptr);
	virtual HRESULT					OnDrawImpl(Graphics& graphics, const UIPos& rcWndPos) = 0;
#endif // USE_D2D_RENDER_MODE

};


text:
. $PSScriptRoot\Shared.ps1

Describe 'TabExpansion Tests' {
    It 'Exports a TabExpansion function' {
        $module.ExportedFunctions.Keys -contains 'TabExpansion' | Should Be $true
    }
    Context 'Subcommand TabExpansion Tests' {
        It 'Tab completes without subcommands' {
            $result = & $module GitTabExpansionInternal 'git whatever '

            $result | Should Be @()
        }
        It 'Tab completes bisect subcommands' {
            $result = & $module GitTabExpansionInternal 'git bisect '

            $result -contains '' | Should Be $false
            $result -contains 'start' | Should Be $true
            $result -contains 'run' | Should Be $true

            $result2 = & $module GitTabExpansionInternal 'git bisect s'

            $result2 -contains 'start' | Should Be $true
            $result2 -contains 'skip' | Should Be $true
        }
        It 'Tab completes remote subcommands' {
            $result = & $module GitTabExpansionInternal 'git remote '

            $result -contains '' | Should Be $false
            $result -contains 'add' | Should Be $true
            $result -contains 'set-branches' | Should Be $true
            $result -contains 'get-url' | Should Be $true
            $result -contains 'update' | Should Be $true

            $result2 = & $module GitTabExpansionInternal 'git remote s'

            $result2 -contains 'set-branches' | Should Be $true
            $result2 -contains 'set-head' | Should Be $true
            $result2 -contains 'set-url' | Should Be $true
        }
        It 'Tab completes update-git-for-windows only on Windows' {
            $result = & $module GitTabExpansionInternal 'git update-'

            if ((($PSVersionTable.PSVersion.Major -eq 5) -or $IsWindows)) {
                $result -contains '' | Should Be $false
                $result -contains 'update-git-for-windows' | Should Be $true
            }
            else {
                $result | Should BeNullOrEmpty
            }
        }
    }
    Context 'Fetch/Push/Pull TabExpansion Tests' {
        BeforeEach {
            # Ensure master branch exists
            &$gitbin branch -q master 2>$null
            # Ensure an origin remote exists
            &$gitbin remote add origin . 2>$null
            # Ensure origin/master exists
            &$gitbin update-ref refs/remotes/origin/master $(git rev-parse master) 2>$null
            # Ensure origin/HEAD exists
            &$gitbin symbolic-ref refs/remotes/origin/HEAD refs/remotes/origin/master 2>$null
        }
        It 'Tab completes all remotes' {
            (&$gitbin remote) -contains 'origin' | Should Be $true

            $result = & $module GitTabExpansionInternal 'git push '
            $result -contains 'origin' | Should Be $true
        }
        It 'Tab completes all branches' {
            $result = & $module GitTabExpansionInternal 'git push origin '
            $result -contains 'master' | Should Be $true
            $result -contains 'origin/master' | Should Be $true
            $result -contains 'origin/HEAD' | Should Be $true
        }
        It 'Tab completes all :branches' {
            $result = & $module GitTabExpansionInternal 'git push origin :'
            $result -contains ':master' | Should Be $true
        }
        It 'Tab completes matching remotes' {
            $result = & $module GitTabExpansionInternal 'git push or'
            $result | Should BeExactly 'origin'
        }
        It 'Tab completes matching branches' {
            $result = & $module GitTabExpansionInternal 'git push origin ma'
            $result | Should BeExactly 'master'
        }
        It 'Tab completes matching remote/branches' {
            $result = & $module GitTabExpansionInternal 'git push origin origin/ma'
            $result | Should BeExactly 'origin/master'
        }
        It 'Tab completes matching :branches' {
            $result = & $module GitTabExpansionInternal 'git push origin :ma'
            $result | Should BeExactly ':master'
        }
        It 'Tab completes matching ref:branches' {
            $result = & $module GitTabExpansionInternal 'git push origin HEAD:ma'
            $result | Should BeExactly 'HEAD:master'
        }
        It 'Tab completes matching +ref:branches' {
            $result = & $module GitTabExpansionInternal 'git push origin +HEAD:ma'
            $result | Should BeExactly '+HEAD:master'
        }
        It 'Tab completes matching remote with preceding parameters' {
            $result = & $module GitTabExpansionInternal 'git push --follow-tags  -u   or'
            $result | Should BeExactly 'origin'
        }
        It 'Tab completes all branches with preceding parameters' {
            $result = & $module GitTabExpansionInternal 'git push  --follow-tags  -u   origin '
            $result -contains 'master' | Should Be $true
            $result -contains 'origin/master' | Should Be $true
            $result -contains 'origin/HEAD' | Should Be $true
        }
        It 'Tab completes matching branch with preceding parameters' {
            $result = & $module GitTabExpansionInternal 'git push  --follow-tags  -u   origin ma'
            $result | Should BeExactly 'master'
        }
        It 'Tab completes matching branch with intermixed parameters' {
            $result = & $module GitTabExpansionInternal 'git push -u origin --follow-tags ma'
            $result | Should BeExactly 'master'
            $result = & $module GitTabExpansionInternal 'git push  -u  origin  --follow-tags   ma'
            $result | Should BeExactly 'master'
        }
        It 'Tab completes matching ref:branch with intermixed parameters' {
            $result = & $module GitTabExpansionInternal 'git push -u origin --follow-tags HEAD:ma'
            $result | Should BeExactly 'HEAD:master'
            $result = & $module GitTabExpansionInternal 'git push  -u  origin  --follow-tags   +HEAD:ma'
            $result | Should BeExactly '+HEAD:master'
        }
        It 'Tab completes matching multiple push ref specs with intermixed parameters' {
            $result = & $module GitTabExpansionInternal 'git push -u origin --follow-tags one :two three:four  ma'
            $result | Should BeExactly 'master'
            $result = & $module GitTabExpansionInternal 'git push -u origin --follow-tags one :two three:four  --crazy-param ma'
            $result | Should BeExactly 'master'
            $result = & $module GitTabExpansionInternal 'git push -u origin --follow-tags one :two three:four  HEAD:ma'
            $result | Should BeExactly 'HEAD:master'
            $result = & $module GitTabExpansionInternal 'git push -u origin --follow-tags one :two three:four  --crazy-param HEAD:ma'
            $result | Should BeExactly 'HEAD:master'

            $result = & $module GitTabExpansionInternal 'git push -u origin --follow-tags one :two three:four  +ma'
            $result | Should BeExactly '+master'
            $result = & $module GitTabExpansionInternal 'git push -u origin --follow-tags one :two three:four  --crazy-param +ma'
            $result | Should BeExactly '+master'
            $result = & $module GitTabExpansionInternal 'git push  -u  origin  --follow-tags one :two three:four  +HEAD:ma'
            $result | Should BeExactly '+HEAD:master'
            $result = & $module GitTabExpansionInternal 'git push  -u  origin  --follow-tags  one :two three:four  --crazy-param  +HEAD:ma'
            $result | Should BeExactly '+HEAD:master'
        }
        It 'Tab complete returns empty result for missing remote' {
            $result = & $module GitTabExpansionInternal 'git push zy'
            $result | Should BeNullOrEmpty
        }
        It 'Tab complete returns empty result for missing branch' {
            $result = & $module GitTabExpansionInternal 'git push origin zy'
            $result | Should BeNullOrEmpty
        }
        It 'Tab complete returns empty result for missing remotebranch' {
            $result = & $module GitTabExpansionInternal 'git fetch origin/zy'
            $result | Should BeNullOrEmpty
        }

        It 'Tab completes branch names with - and -- in them' {
            $branchName = 'branch--for-Pester-tests'
            if (&$gitbin branch --list -q $branchName) {
                &$gitbin branch -D $branchName
            }

            &$gitbin branch $branchName
            try {
                $result = & $module GitTabExpansionInternal 'git push origin branch-'
                $result | Should BeExactly $branchName

                $result = & $module GitTabExpansionInternal 'git push  --follow-tags  -u   origin '
                $result -contains $branchName | Should Be $true
            }
            finally {
                &$gitbin branch -D $branchName
            }
        }
    }

    Context 'Vsts' {
        BeforeEach {
            [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssigments', '')]
            $repoPath = NewGitTempRepo

            # Test with non-standard vsts pr alias name
            &$gitbin config alias.test-vsts-pr "!f() { exec vsts code pr \`"`$`@\`"; }; f"
        }
        AfterEach {
            RemoveGitTempRepo $repoPath
        }
        It 'Tab completes pr options' {
            $result = & $module GitTabExpansionInternal 'git test-vsts-pr '
            $result -contains 'abandon' | Should Be $true
        }
    }

    Context 'Add/Reset/Checkout TabExpansion Tests' {
        BeforeEach {
            [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssigments', '')]
            $repoPath = NewGitTempRepo
        }
        AfterEach {
            RemoveGitTempRepo $repoPath
        }
        It 'Tab completes non-ASCII file name' {
            &$gitbin config core.quotepath true # Problematic (default) config

            $fileName = "posh$([char]8226)git.txt"
            New-Item $fileName -ItemType File

            $gitStatus = & $module Get-GitStatus

            $result = & $module GitTabExpansionInternal 'git add ' $gitStatus
            $result | Should BeExactly $fileName
        }
    }

    Context 'Alias TabExpansion Tests' {
        $addedAliases = @()
        function Add-GlobalTestAlias($Name, $Value) {
            if (!(&$gitbin config --global "alias.$Name")) {
                &$gitbin config --global "alias.$Name" $Value
                $addedAliases += $Name
            }
        }
        BeforeAll {
            [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssigments', '')]
            $repoPath = NewGitTempRepo -MakeInitialCommit
        }
        AfterAll {
            $addedAliases | Where-Object { $_ } | ForEach-Object {
                &$gitbin config --global --unset "alias.$_" 2>$null
            }

            RemoveGitTempRepo $repoPath
        }
        It 'Command completion includes unique list of aliases' {
            $alias = "test-$(New-Guid)"

            Add-GlobalTestAlias $alias config
            &$gitbin config alias.$alias help
            (&$gitbin config --get-all alias.$alias).Count | Should Be 2

            $result = @(& $module GitTabExpansionInternal "git $alias")
            $result.Count | Should Be 1
            $result[0] | Should BeExactly $alias
        }
        It 'Tab completes when there is one alias of a given name' {
            $alias = "test-$(New-Guid)"

            &$gitbin config alias.$alias checkout
            (&$gitbin config --get-all alias.$alias).Count | Should Be 1

            $result = & $module GitTabExpansionInternal "git $alias ma"
            $result | Should BeExactly 'master'
        }
        It 'Tab completes when there are multiple aliases of the same name' {
            Add-GlobalTestAlias co checkout

            &$gitbin config alias.co checkout
            (&$gitbin config --get-all alias.co).Count | Should BeGreaterThan 1

            $result = & $module GitTabExpansionInternal 'git co ma'
            $result | Should BeExactly 'master'
        }
    }

    Context 'PowerShell Special Chars Tests' {
        BeforeAll {
            [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssigments', '')]
            $repoPath = NewGitTempRepo -MakeInitialCommit
        }
        AfterAll {
            RemoveGitTempRepo $repoPath
        }
        AfterEach {
            ResetGitTempRepoWorkingDir $repoPath
        }
        It 'Tab completes remote name with special char as quoted' {
            &$gitbin remote add '#test' https://github.com/dahlbyk/posh-git.git 2> $null

            $result = & $module GitTabExpansionInternal 'git push #'
            $result | Should BeExactly "'#test'"
        }
        It 'Tab completes branch name with special char as quoted' {
            &$gitbin branch '#develop' 2>$null

            $result = & $module GitTabExpansionInternal 'git checkout #'
            $result | Should BeExactly "'#develop'"
        }
        It 'Tab completes git feature branch name with special char as quoted' {
            &$gitbin branch '#develop' 2>$null

            $result = & $module GitTabExpansionInternal 'git flow feature list #'
            $result | Should BeExactly "'#develop'"
        }
        It 'Tab completes a tag name with special char as quoted' {
            $tag = "v1.0.0;abcdef"
            &$gitbin tag $tag

            $result = & $module GitTabExpansionInternal 'git show v1'
            $result | Should BeExactly "'$tag'"
        }
        It 'Tab completes a tag name with single quote correctly' {
            &$gitbin tag "v2.0.0'"

            $result = & $module GitTabExpansionInternal 'git show v2'
            $result | Should BeExactly "'v2.0.0'''"
        }
        It 'Tab completes add file in working dir with special char as quoted' {
            $filename = 'foo{bar} (x86).txt';
            New-Item $filename -ItemType File

            $gitStatus = & $module Get-GitStatus

            $result = & $module GitTabExpansionInternal 'git add ' $gitStatus
            $result | Should BeExactly "'$filename'"
        }
    }
}


text:
package org.apache.hadoop.mapreduce.jobhistory;

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

import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.classification.InterfaceStability;
import org.apache.hadoop.mapreduce.JobACL;
import org.apache.hadoop.mapreduce.JobID;
import org.apache.hadoop.security.authorize.AccessControlList;

import org.apache.avro.util.Utf8;

/**
 * Event to record the submission of a job
 *
 */
@InterfaceAudience.Private
@InterfaceStability.Unstable
public class JobSubmittedEvent implements HistoryEvent {
  private JobSubmitted datum = new JobSubmitted();

  /**
   * Create an event to record job submission
   * @param id The job Id of the job
   * @param jobName Name of the job
   * @param userName Name of the user who submitted the job
   * @param submitTime Time of submission
   * @param jobConfPath Path of the Job Configuration file
   * @param jobACLs The configured acls for the job.
   * @param jobQueueName The job-queue to which this job was submitted to
   */
  public JobSubmittedEvent(JobID id, String jobName, String userName,
      long submitTime, String jobConfPath,
      Map<JobACL, AccessControlList> jobACLs, String jobQueueName) {
    this(id, jobName, userName, submitTime, jobConfPath, jobACLs,
        jobQueueName, "", "", "", "");
  }

  /**
   * Create an event to record job submission
   * @param id The job Id of the job
   * @param jobName Name of the job
   * @param userName Name of the user who submitted the job
   * @param submitTime Time of submission
   * @param jobConfPath Path of the Job Configuration file
   * @param jobACLs The configured acls for the job.
   * @param jobQueueName The job-queue to which this job was submitted to
   * @param workflowId The Id of the workflow
   * @param workflowName The name of the workflow
   * @param workflowNodeName The node name of the workflow
   * @param workflowAdjacencies The adjacencies of the workflow
   */
  public JobSubmittedEvent(JobID id, String jobName, String userName,
      long submitTime, String jobConfPath,
      Map<JobACL, AccessControlList> jobACLs, String jobQueueName,
      String workflowId, String workflowName, String workflowNodeName,
      String workflowAdjacencies) {
    this(id, jobName, userName, submitTime, jobConfPath, jobACLs,
        jobQueueName, workflowId, workflowName, workflowNodeName,
        workflowAdjacencies, "");
  }

    /**
     * Create an event to record job submission
     * @param id The job Id of the job
     * @param jobName Name of the job
     * @param userName Name of the user who submitted the job
     * @param submitTime Time of submission
     * @param jobConfPath Path of the Job Configuration file
     * @param jobACLs The configured acls for the job.
     * @param jobQueueName The job-queue to which this job was submitted to
     * @param workflowId The Id of the workflow
     * @param workflowName The name of the workflow
     * @param workflowNodeName The node name of the workflow
     * @param workflowAdjacencies The adjacencies of the workflow
     * @param workflowTags Comma-separated tags for the workflow
     */
    public JobSubmittedEvent(JobID id, String jobName, String userName,
        long submitTime, String jobConfPath,
        Map<JobACL, AccessControlList> jobACLs, String jobQueueName,
        String workflowId, String workflowName, String workflowNodeName,
        String workflowAdjacencies, String workflowTags) {
    datum.jobid = new Utf8(id.toString());
    datum.jobName = new Utf8(jobName);
    datum.userName = new Utf8(userName);
    datum.submitTime = submitTime;
    datum.jobConfPath = new Utf8(jobConfPath);
    Map<CharSequence, CharSequence> jobAcls = new HashMap<CharSequence, CharSequence>();
    for (Entry<JobACL, AccessControlList> entry : jobACLs.entrySet()) {
      jobAcls.put(new Utf8(entry.getKey().getAclName()), new Utf8(
          entry.getValue().getAclString()));
    }
    datum.acls = jobAcls;
    if (jobQueueName != null) {
      datum.jobQueueName = new Utf8(jobQueueName);
    }
    if (workflowId != null) {
      datum.workflowId = new Utf8(workflowId);
    }
    if (workflowName != null) {
      datum.workflowName = new Utf8(workflowName);
    }
    if (workflowNodeName != null) {
      datum.workflowNodeName = new Utf8(workflowNodeName);
    }
    if (workflowAdjacencies != null) {
      datum.workflowAdjacencies = new Utf8(workflowAdjacencies);
    }
    if (workflowTags != null) {
      datum.workflowTags = new Utf8(workflowTags);
    }
  }

  JobSubmittedEvent() {}

  public Object getDatum() { return datum; }
  public void setDatum(Object datum) {
    this.datum = (JobSubmitted)datum;
  }

  /** Get the Job Id */
  public JobID getJobId() { return JobID.forName(datum.jobid.toString()); }
  /** Get the Job name */
  public String getJobName() { return datum.jobName.toString(); }
  /** Get the Job queue name */
  public String getJobQueueName() {
    if (datum.jobQueueName != null) {
      return datum.jobQueueName.toString();
    }
    return null;
  }
  /** Get the user name */
  public String getUserName() { return datum.userName.toString(); }
  /** Get the submit time */
  public long getSubmitTime() { return datum.submitTime; }
  /** Get the Path for the Job Configuration file */
  public String getJobConfPath() { return datum.jobConfPath.toString(); }
  /** Get the acls configured for the job **/
  public Map<JobACL, AccessControlList> getJobAcls() {
    Map<JobACL, AccessControlList> jobAcls =
        new HashMap<JobACL, AccessControlList>();
    for (JobACL jobACL : JobACL.values()) {
      Utf8 jobACLsUtf8 = new Utf8(jobACL.getAclName());
      if (datum.acls.containsKey(jobACLsUtf8)) {
        jobAcls.put(jobACL, new AccessControlList(datum.acls.get(
            jobACLsUtf8).toString()));
      }
    }
    return jobAcls;
  }
  /** Get the id of the workflow */
  public String getWorkflowId() {
    if (datum.workflowId != null) {
      return datum.workflowId.toString();
    }
    return null;
  }
  /** Get the name of the workflow */
  public String getWorkflowName() {
    if (datum.workflowName != null) {
      return datum.workflowName.toString();
    }
    return null;
  }
  /** Get the node name of the workflow */
  public String getWorkflowNodeName() {
    if (datum.workflowNodeName != null) {
      return datum.workflowNodeName.toString();
    }
    return null;
  }
  /** Get the adjacencies of the workflow */
  public String getWorkflowAdjacencies() {
    if (datum.workflowAdjacencies != null) {
      return datum.workflowAdjacencies.toString();
    }
    return null;
  }
  /** Get the workflow tags */
  public String getWorkflowTags() {
    if (datum.workflowTags != null) {
      return datum.workflowTags.toString();
    }
    return null;
  }
  /** Get the event type */
  public EventType getEventType() { return EventType.JOB_SUBMITTED; }

}