text:
import {
  ChangeDetectorRef,
  Component,
  HostListener,
  NgZone,
  ViewChild
} from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import {
  Events,
  Navbar,
  NavController,
  NavParams,
  ViewController
} from 'ionic-angular';
import * as _ from 'lodash';

// Providers
import { ActionSheetProvider, IABCardProvider } from '../../../providers';
import { Config, ConfigProvider } from '../../../providers/config/config';
import { Coin, CurrencyProvider } from '../../../providers/currency/currency';
import { ElectronProvider } from '../../../providers/electron/electron';
import { FilterProvider } from '../../../providers/filter/filter';
import { getActivationFee } from '../../../providers/gift-card/gift-card';
import { CardConfig } from '../../../providers/gift-card/gift-card.types';
import { Logger } from '../../../providers/logger/logger';
import { PlatformProvider } from '../../../providers/platform/platform';
import { ProfileProvider } from '../../../providers/profile/profile';
import { RateProvider } from '../../../providers/rate/rate';
import { SimplexProvider } from '../../../providers/simplex/simplex';
import { TxFormatProvider } from '../../../providers/tx-format/tx-format';

// Pages
import { CryptoOrderSummaryPage } from '../../buy-crypto/crypto-order-summary/crypto-order-summary';
import { BitPayCardTopUpPage } from '../../integrations/bitpay-card/bitpay-card-topup/bitpay-card-topup';
import { ConfirmCardPurchasePage } from '../../integrations/gift-cards/confirm-card-purchase/confirm-card-purchase';
import { CustomAmountPage } from '../../receive/custom-amount/custom-amount';
import { ConfirmPage } from '../confirm/confirm';

import { TranslateService } from '@ngx-translate/core';
import { CoinbaseWithdrawPage } from '../../integrations/coinbase/coinbase-withdraw/coinbase-withdraw';

@Component({
  selector: 'page-amount',
  templateUrl: 'amount.html'
})
export class AmountPage {
  private LENGTH_EXPRESSION_LIMIT: number;
  private availableUnits;
  public unit: string;
  private reNr: RegExp;
  private reOp: RegExp;
  private nextView;
  private fixedUnit: boolean;
  public fiatCode: string;
  private altUnitIndex: number;
  private unitIndex: number;
  private unitToSatoshi: number;
  private satToUnit: number;
  private unitDecimals: number;
  private zone;
  private description: string;

  public disableHardwareKeyboard: boolean;
  public onlyIntegers: boolean;
  public alternativeUnit: string;
  public globalResult: string;
  public alternativeAmount: string;
  public expression;
  public amount;

  public showSendMax: boolean;
  public allowSend: boolean;
  public useSmallFontSize: boolean;
  public recipientType: string;
  public toAddress: string;
  public network: string;
  public name: string;
  public email: string;
  public destinationTag?: string;
  public color: string;
  public useSendMax: boolean;
  public useAsModal: boolean;
  public config: Config;
  public toWalletId: string;
  private _id: string;
  public requestingAmount: boolean;
  public wallet;
  any;

  public cardName: string;
  public cardConfig: CardConfig;

  private fromCoinbase;
  private alternativeCurrency;
  public fromBuyCrypto: boolean;
  public fromExchangeCrypto: boolean;
  public isCardTopUp: boolean;
  public quoteForm: FormGroup;
  public supportedFiatAltCurrencies: string[];
  public altCurrenciesToShow: string[];
  public altCurrenciesToShow2: string[];
  showLoading: boolean;
  cancelText: any;
  okText: any;
  selectOptions: { title: any; cssClass: string };
  altCurrencyInitial: any;
  supportedFiatWarning: boolean;

  @ViewChild(Navbar) navBar: Navbar;

  constructor(
    private actionSheetProvider: ActionSheetProvider,
    private configProvider: ConfigProvider,
    private filterProvider: FilterProvider,
    private currencyProvider: CurrencyProvider,
    private logger: Logger,
    private navParams: NavParams,
    private electronProvider: ElectronProvider,
    private platformProvider: PlatformProvider,
    private rateProvider: RateProvider,
    private txFormatProvider: TxFormatProvider,
    private changeDetectorRef: ChangeDetectorRef,
    private events: Events,
    private viewCtrl: ViewController,
    private profileProvider: ProfileProvider,
    private navCtrl: NavController,
    private iabCardProvider: IABCardProvider,
    private simplexProvider: SimplexProvider,
    private formBuilder: FormBuilder,
    private translate: TranslateService
  ) {
    this.zone = new NgZone({ enableLongStackTrace: false });
    this.wallet = this.profileProvider.getWallet(this.navParams.data.walletId);
    this.config = this.configProvider.get();
    this.useAsModal = this.navParams.data.useAsModal;
    this.recipientType = this.navParams.data.recipientType;
    this.toAddress = this.navParams.data.toAddress;
    this.network = this.navParams.data.network;
    this.name = this.navParams.data.name;
    this.email = this.navParams.data.email;
    this.destinationTag = this.navParams.data.destinationTag;
    this.color = this.navParams.data.color;
    this.fixedUnit = this.navParams.data.fixedUnit;
    this.description = this.navParams.data.description;
    this.onlyIntegers = this.navParams.data.onlyIntegers
      ? this.navParams.data.onlyIntegers
      : false;
    this.fromCoinbase = this.navParams.data.fromCoinbase;
    this.alternativeCurrency = this.navParams.data.alternativeCurrency;
    this.fromBuyCrypto = this.navParams.data.fromBuyCrypto;
    this.fromExchangeCrypto = this.navParams.data.fromExchangeCrypto;
    this.isCardTopUp = !!this.navParams.data.card;
    this.showSendMax = false;
    this.useSendMax = false;
    this.allowSend = false;
    this.useSmallFontSize = false;

    this.availableUnits = [];
    this.expression = '';

    this.LENGTH_EXPRESSION_LIMIT = 19;
    this.amount = 0;
    this.altUnitIndex = 0;
    this.unitIndex = 0;

    this.reNr = /^[1234567890\.]$/;
    this.reOp = /^[\*\+\-\/]$/;

    this.requestingAmount =
      this.navParams.get('nextPage') === 'CustomAmountPage';
    this.nextView = this.getNextView();

    // BitPay Card ID or Wallet ID or Coinbase Account ID
    this._id = this.navParams.data.id;

    // Use only with Coinbase Withdraw
    this.toWalletId = this.navParams.data.toWalletId;

    this.cardName = this.navParams.get('cardName');
    this.cardConfig = this.navParams.get('cardConfig');
  }

  async ionViewDidLoad() {
    this.navBar.backButtonClick = () => {
      if (this.navParams.get('card') === 'v2') {
        this.iabCardProvider.show(true);
      }
      this.navCtrl.pop();
    };
    this.setAvailableUnits();
    if (this.fromBuyCrypto) this.setBuyCryptoParams();
    this.updateUnitUI();
  }

  ionViewWillEnter() {
    this.disableHardwareKeyboard = false;
    this.expression = '';
    this.useSendMax = false;
    this.processAmount();
    this.events.subscribe(
      'Wallet/disableHardwareKeyboard',
      this.walletDisableHardwareKeyboardHandler
    );
  }

  ionViewWillLeave() {
    this._disableHardwareKeyboard();
  }

  private walletDisableHardwareKeyboardHandler: any = () => {
    this._disableHardwareKeyboard();
  };

  private _disableHardwareKeyboard() {
    this.disableHardwareKeyboard = true;
  }

  @HostListener('document:keydown', ['$event'])
  handleKeyboardEvent(event: KeyboardEvent) {
    if (this.disableHardwareKeyboard) return;
    if (!event.key) return;
    if (event.which === 8) {
      event.preventDefault();
      this.removeDigit();
    }

    if (event.key.match(this.reNr)) {
      this.pushDigit(event.key);
    } else if (event.key.match(this.reOp)) {
      this.pushOperator(event.key);
    } else if (event.keyCode === 86) {
      if (event.ctrlKey || event.metaKey) this.processClipboard();
    } else if (event.keyCode === 13) this.finish();
  }

  public isCoin(coin: string): boolean {
    return !!Coin[coin];
  }

  private setAvailableUnits(): void {
    this.availableUnits = [];

    const parentWalletCoin = this.navParams.data.wallet
      ? this.navParams.data.wallet.coin
      : this.wallet && this.wallet.coin;

    for (const coin of this.currencyProvider.getAvailableCoins()) {
      if (parentWalletCoin === coin || !parentWalletCoin) {
        const { unitName, unitCode } = this.currencyProvider.getPrecision(coin);
        this.availableUnits.push({
          name: this.currencyProvider.getCoinName(coin),
          id: unitCode,
          shortName: unitName
        });
      }
    }

    this.unitIndex = 0;

    if (this.navParams.data.coin) {
      let coins = this.navParams.data.coin.split(',');
      let newAvailableUnits = [];

      _.each(coins, (c: string) => {
        let coin = _.find(this.availableUnits, {
          id: c
        });
        if (!coin) {
          this.logger.warn(
            'Could not find desired coin:' + this.navParams.data.coin
          );
        } else {
          newAvailableUnits.push(coin);
        }
      });

      if (newAvailableUnits.length > 0) {
        this.availableUnits = newAvailableUnits;
      }
    }

    //  currency have preference
    let fiatName;
    if (this.navParams.data.currency) {
      this.fiatCode = this.navParams.data.currency;
      this.altUnitIndex = this.unitIndex;
      this.unitIndex = this.availableUnits.length;
    } else {
      this.fiatCode =
        this.alternativeCurrency ||
        this.config.wallet.settings.alternativeIsoCode ||
        'USD';
      fiatName = this.config.wallet.settings.alternativeName || this.fiatCode;
      this.altUnitIndex = this.availableUnits.length;
    }

    this.availableUnits.push({
      name: fiatName || this.fiatCode,
      // TODO
      id: this.fiatCode,
      shortName: this.fiatCode,
      isFiat: true
    });

    if (this.navParams.data.fixedUnit) {
      this.fixedUnit = true;
    }
  }

  private paste(value: string): void {
    this.zone.run(() => {
      this.expression = value;
      this.processAmount();
      this.changeDetectorRef.detectChanges();
    });
  }

  private getNextView() {
    let nextPage;
    switch (this.navParams.data.nextPage) {
      case 'BitPayCardTopUpPage':
        this.showSendMax = false;
        nextPage = BitPayCardTopUpPage;
        break;
      case 'ConfirmCardPurchasePage':
        nextPage = ConfirmCardPurchasePage;
        break;
      case 'CustomAmountPage':
        nextPage = CustomAmountPage;
        break;
      case 'CryptoOrderSummaryPage':
        nextPage = CryptoOrderSummaryPage;
        break;
      case 'CoinbaseWithdrawPage':
        this.showSendMax = false;
        nextPage = CoinbaseWithdrawPage;
        break;
      default:
        this.showSendMax = true;
        nextPage = ConfirmPage;
    }
    return nextPage;
  }

  public processClipboard(): void {
    if (!this.platformProvider.isElectron) return;

    let value = this.electronProvider.readFromClipboard();

    if (value && this.evaluate(value) > 0) this.paste(this.evaluate(value));
  }

  public sendMax(): void {
    this.useSendMax = true;
    this.allowSend = true;
    if (!this.wallet) {
      return this.finish();
    }
    const maxAmount = this.txFormatProvider.satToUnit(
      this.wallet.cachedStatus.availableBalanceSat,
      this.wallet.coin
    );
    this.zone.run(() => {
      this.expression = this.availableUnits[this.unitIndex].isFiat
        ? this.toFiat(maxAmount, this.wallet.coin).toFixed(2)
        : maxAmount;
      this.processAmount();
      this.changeDetectorRef.detectChanges();
      this.finish();
    });
  }

  public isSendMaxButtonShown() {
    return (
      (this.showSendMax && !this.requestingAmount && !this.useAsModal) ||
      this.fromExchangeCrypto
    );
  }

  public resizeFont(): void {
    this.useSmallFontSize = this.expression && this.expression.length >= 10;
  }

  public pushDigit(digit: string): void {
    this.useSendMax = false;
    if (digit === 'delete') {
      return this.removeDigit();
    }
    if (
      this.expression &&
      this.expression.length >= this.LENGTH_EXPRESSION_LIMIT
    )
      return;
    this.zone.run(() => {
      this.expression = (this.expression + digit).replace('..', '.');
      this.processAmount();
      this.changeDetectorRef.detectChanges();
      this.resizeFont();
    });
  }

  public removeDigit(): void {
    this.zone.run(() => {
      this.expression = this.expression.slice(0, -1);
      this.processAmount();
      this.changeDetectorRef.detectChanges();
      this.resizeFont();
    });
  }

  public pushOperator(operator: string): void {
    if (!this.expression || this.expression.length == 0) return;
    this.zone.run(() => {
      this.expression = this._pushOperator(this.expression, operator);
      this.changeDetectorRef.detectChanges();
    });
  }

  private _pushOperator(val: string, operator: string) {
    if (!this.isOperator(_.last(val))) {
      return val + operator;
    } else {
      return val.slice(0, -1) + operator;
    }
  }

  private isOperator(val: string): boolean {
    const regex = /[\/\-\+\x\*]/;
    return regex.test(val);
  }

  private isExpression(val: string): boolean {
    const regex = /^\.?\d+(\.?\d+)?([\/\-\+\*x]\d?\.?\d+)+$/;
    return regex.test(val);
  }

  public isNumber(expression): boolean {
    return _.isNumber(expression) ? true : false;
  }

  private processAmount(): void {
    let formatedValue = this.format(this.expression);
    let result = this.evaluate(formatedValue);
    this.allowSend = this.onlyIntegers
      ? _.isNumber(result) && +result > 0 && Number.isInteger(+result)
      : _.isNumber(result) && +result > 0;

    if (_.isNumber(result)) {
      this.globalResult = this.isExpression(this.expression)
        ? '= ' + this.processResult(result)
        : '';

      if (this.fromBuyCrypto) return;

      if (this.availableUnits[this.unitIndex].isFiat) {
        let a = this.fromFiat(result);
        if (a) {
          this.alternativeAmount = this.txFormatProvider.formatAmount(
            this.availableUnits[this.altUnitIndex].id,
            a * this.unitToSatoshi,
            true
          );
          this.checkAmountForBitpaycard(result);
        } else {
          this.alternativeAmount = result ? 'N/A' : null;
          this.allowSend = false;
        }
      } else {
        this.alternativeAmount = this.filterProvider.formatFiatAmount(
          this.toFiat(result)
        );
        this.checkAmountForBitpaycard(this.toFiat(result));
      }
    }
  }

  private checkAmountForBitpaycard(amount: number): void {
    // Check if the top up amount is at least 1 usd
    const isTopUp =
      this.navParams.data.nextPage === 'BitPayCardTopUpPage' ? true : false;
    if (isTopUp && amount < 1) {
      this.allowSend = false;
    }
  }

  private processResult(val): number {
    if (this.availableUnits[this.unitIndex].isFiat)
      return +this.filterProvider.formatFiatAmount(val);
    else
      return +this.txFormatProvider.formatAmount(
        this.unit.toLowerCase(),
        val.toFixed(this.unitDecimals) * this.unitToSatoshi,
        true
      );
  }

  private fromFiat(val: number, coin?: Coin): number {
    coin = coin || this.availableUnits[this.altUnitIndex].id;
    return parseFloat(
      (
        this.rateProvider.fromFiat(val, this.fiatCode, coin) * this.satToUnit
      ).toFixed(this.unitDecimals)
    );
  }

  private toFiat(val: number, coin?: Coin): number {
    if (
      !this.rateProvider.getRate(
        this.fiatCode,
        coin || this.availableUnits[this.unitIndex].id
      )
    )
      return undefined;

    return parseFloat(
      this.rateProvider
        .toFiat(
          val * this.unitToSatoshi,
          this.fiatCode,
          coin || this.availableUnits[this.unitIndex].id
        )
        .toFixed(2)
    );
  }

  private format(val: string): string {
    if (!val) return undefined;

    let result = val.toString();

    if (this.isOperator(_.last(val))) result = result.slice(0, -1);

    return result.replace('x', '*');
  }

  private evaluate(val: string) {
    let result;
    try {
      result = eval(val);
    } catch (e) {
      return 0;
    }
    if (!_.isFinite(result)) return 0;
    return result;
  }

  public validateGiftCardAmount(amount) {
    return (
      amount <= this.cardConfig.maxAmount && amount >= this.cardConfig.minAmount
    );
  }

  public showCardAmountInfoSheet(amount) {
    const sheetType =
      amount < this.cardConfig.minAmount
        ? 'below-minimum-gift-card-amount'
        : 'above-maximum-gift-card-amount';
    this.actionSheetProvider
      .createInfoSheet(sheetType, this.cardConfig)
      .present();
  }

  public finish(skipActivationFeeAlert: boolean = false): void {
    if (!this.allowSend) return;
    let unit = this.availableUnits[this.unitIndex];
    let _amount = this.evaluate(this.format(this.expression));
    let coin = unit.id;
    let data;

    if (unit.isFiat) {
      coin = this.availableUnits[this.altUnitIndex].id;
    }

    if (this.navParams.data.nextPage) {
      const amount = this.useSendMax ? null : _amount;
      if (this.cardConfig && !this.validateGiftCardAmount(amount)) {
        this.showCardAmountInfoSheet(amount);
        return;
      }

      data = {
        id: this._id,
        amount,
        currency: this.fromBuyCrypto ? this.unit : unit.id.toUpperCase(),
        coin: this.fromBuyCrypto && !this.navParams.data.coin ? null : coin,
        useSendMax: this.useSendMax,
        toWalletId: this.toWalletId,
        cardConfig: this.cardConfig,
        cardName: this.cardName,
        description: this.description
      };
    } else {
      let amount = _amount;
      amount = unit.isFiat
        ? (this.fromFiat(amount) * this.unitToSatoshi).toFixed(0)
        : (amount * this.unitToSatoshi).toFixed(0);
      data = {
        recipientType: this.recipientType,
        amount,
        toAddress: this.toAddress,
        name: this.name,
        email: this.email,
        color: this.color,
        coin,
        useSendMax: this.useSendMax,
        description: this.description,
        fromCoinbase: this.fromCoinbase,
        currency: this.unit
      };

      if (unit.isFiat) {
        data.fiatAmount = _amount;
        data.fiatCode = this.fiatCode;
      }
    }
    this.useSendMax = null;

    if (this.wallet) {
      data.walletId = this.wallet.credentials.walletId;
      data.network = this.wallet.network;
      if (this.wallet.credentials.token) {
        data.tokenAddress = this.wallet.credentials.token.address;
      }
      if (this.wallet.credentials.multisigEthInfo) {
        data.multisigContractAddress = this.wallet.credentials.multisigEthInfo.multisigContractAddress;
      }
    }

    if (this.destinationTag) {
      data.destinationTag = this.destinationTag;
    }

    if (this.navParams.data.fromWalletDetails) {
      data.fromWalletDetails = true;
    }

    if (this.cardName && !skipActivationFeeAlert) {
      const activationFee = getActivationFee(data.amount, this.cardConfig);
      if (activationFee) {
        return this.alertActivationFeeIncluded(activationFee);
      }
    }

    if (this.navParams.get('card') === 'v2') {
      data = {
        ...data,
        v2: true
      };
    }
    this.useAsModal
      ? this.closeModal(data)
      : this.navCtrl.push(this.nextView, data);
  }

  private alertActivationFeeIncluded(fee) {
    if (!fee) return;
    const sheet = this.actionSheetProvider.createInfoSheet(
      'activation-fee-included',
      {
        currency: this.cardConfig.currency,
        displayName: this.cardConfig.displayName,
        fee
      }
    );
    sheet.present();
    sheet.onDidDismiss(ok => ok && this.finish(true));
  }

  private updateUnitUI(): void {
    this.unit = this.fromBuyCrypto
      ? this.altCurrencyInitial
      : this.availableUnits[this.unitIndex].shortName;
    this.alternativeUnit = this.availableUnits[this.altUnitIndex].shortName;
    const { unitToSatoshi, unitDecimals } = this.availableUnits[this.unitIndex]
      .isFiat
      ? this.currencyProvider.getPrecision(
          this.availableUnits[this.altUnitIndex].id
        )
      : this.currencyProvider.getPrecision(this.unit.toLowerCase() as Coin);
    this.unitToSatoshi = unitToSatoshi;
    this.satToUnit = 1 / this.unitToSatoshi;
    this.unitDecimals = unitDecimals;
    this.processAmount();
    this.logger.debug(
      'Update unit coin @amount unit:' +
        this.unit +
        ' alternativeUnit:' +
        this.alternativeUnit
    );
  }

  private resetValues(): void {
    this.expression = '';
    this.globalResult = '';
    this.alternativeAmount = null;
  }

  public changeUnit(): void {
    if (this.fixedUnit) return;

    this.unitIndex++;
    if (this.unitIndex >= this.availableUnits.length) this.unitIndex = 0;

    if (this.availableUnits[this.unitIndex].isFiat) {
      // Always return to BTC... TODO?
      this.altUnitIndex = 0;
    } else {
      this.altUnitIndex = _.findIndex(this.availableUnits, {
        isFiat: true
      });
    }

    this.resetValues();

    this.zone.run(() => {
      this.updateUnitUI();
      this.changeDetectorRef.detectChanges();
    });
  }

  public closeModal(item): void {
    if (this.navParams.data.fromMultiSend) {
      if (item) this.events.publish('addRecipient', item);
      this.navCtrl.remove(this.viewCtrl.index - 1).then(() => {
        this.viewCtrl.dismiss();
      });
    } else {
      this.viewCtrl.dismiss(item);
    }
  }

  private setBuyCryptoParams() {
    const isoCode = this.config.wallet.settings.alternativeIsoCode;
    this.altCurrencyInitial =
      this.fiatCode && this.isSupportedFiat(this.fiatCode)
        ? this.fiatCode
        : this.isSupportedFiat(isoCode)
        ? isoCode
        : 'USD';

    this.quoteForm = this.formBuilder.group({
      amount: [
        200,
        [Validators.required, Validators.min(50), Validators.max(20000)]
      ],
      altCurrency: [this.altCurrencyInitial, [Validators.required]]
    });
    this.altCurrenciesToShow = ['USD', 'EUR'];
    this.altCurrenciesToShow2 = [];

    if (this.altCurrenciesToShow.indexOf(this.altCurrencyInitial) < 0)
      this.altCurrenciesToShow.push(this.altCurrencyInitial);

    this.selectOptions = {
      title: this.translate.instant('Select Currency'),
      cssClass: 'buy-crypto-currency-' + this.altCurrenciesToShow.length
    };

    this.supportedFiatAltCurrencies = this.simplexProvider.getSupportedFiatAltCurrencies();

    this.supportedFiatAltCurrencies.forEach((currency: string) => {
      if (this.altCurrenciesToShow.indexOf(currency) < 0)
        this.altCurrenciesToShow2.push(currency);
    });

    this.okText = this.translate.instant('Select');
    this.cancelText = this.translate.instant('Cancel');
    this.showLoading = false;
  }

  private isSupportedFiat(isoCode: string): boolean {
    return (
      this.simplexProvider.getSupportedFiatAltCurrencies().indexOf(isoCode) > -1
    );
  }

  public altCurrencyChange(): void {
    this.logger.debug(
      'altCurrency changed to: ' + this.quoteForm.value.altCurrency
    );
    this.unit = this.quoteForm.value.altCurrency;
  }
}


text:
package org.wso2.carbon.apimgt.ballerina.caching;

import org.ballerinalang.model.values.BBoolean;
import org.ballerinalang.model.values.BJSON;
import org.ballerinalang.model.values.BString;
import org.ballerinalang.model.values.BValue;
import org.ballerinalang.util.codegen.ProgramFile;
import org.ballerinalang.util.program.BLangFunctions;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import org.wso2.carbon.apimgt.ballerina.caching.util.BTestUtils;

/**
 * Cache Test class which handles caching test for ballerina native cache implementation for API Manager
 *
 *  @since 0.10-SNAPSHOT
 */
public class CacheTest {
    private ProgramFile bLangProgram;
    private static final String s1 = "WSO2 Inc.";

    @BeforeClass
    public void setup() {
        bLangProgram = BTestUtils.parseBalFile("samples/cache/cacheTest.bal");
    }

    @Test
    public void testCacheOperations() {
        //Create arguments to initiate cache
        BValue[] args = {new BString("cacheName"), new BString("15"), new BString("cacheKey"),
                new BString("cacheValue")};
        //Test ballerina cache create, put and get for BString
        BValue[] returns = BLangFunctions.invokeNew(bLangProgram, "testCache", args);
        //Assert if cache entry is BValue
        Assert.assertTrue(returns[0] instanceof BValue);
        final String expected = "cacheValue";
        //Assert if return entry matched with exact entry we put there
        Assert.assertEquals(returns[0].stringValue(), expected);

        //Test ballerina Boolean values.
        BValue[] argsBoolean = {new BString("cacheName"), new BString("15"), new BString("cacheKey"),
                new BBoolean(false)};
        BValue[] returnsBoolean = BLangFunctions.invokeNew(bLangProgram, "testCache", argsBoolean);
        Assert.assertTrue(returnsBoolean[0] instanceof BBoolean);

        //Test ballerina JSON values.
        BValue[] argsJSON = {new BString("cacheName"), new BString("15"), new BString("cacheKey"),
                new BJSON("{}")};
        BValue[] returnsJSON = BLangFunctions.invokeNew(bLangProgram, "testCache", argsJSON);
        Assert.assertTrue(returnsJSON[0] instanceof BJSON);
    }
    @Test
    public void testCacheForNonExistence() {
        ProgramFile bLangProgram1 = BTestUtils.parseBalFile("samples/cache/nonExistenceEntryCacheTest.bal");

        //Create arguments to initiate cache
        BValue[] args = {new BString("cacheName"), new BString("15"), new BString("cacheKey")};
        //Test ballerina cache create, put and get for BString
        BValue[] returns = BLangFunctions.invokeNew(bLangProgram1, "testCacheForNonExistence", args);
        Assert.assertTrue(returns[0] instanceof BBoolean);
        BBoolean value = (BBoolean) returns[0];
        Assert.assertFalse(value.booleanValue());
    }
}

redpajama_set_name: RedPajamaGithub


text:
#include "gtest/gtest.h"
#include "midso/transpose_layer_backward.h"


text:
package org.elasticsearch.action.admin.cluster.storedscripts;

import org.elasticsearch.Version;
import org.elasticsearch.common.bytes.BytesArray;
import org.elasticsearch.common.io.stream.BytesStreamOutput;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.test.ESTestCase;

import java.io.IOException;
import java.util.Base64;

public class PutStoredScriptRequestTests extends ESTestCase {

    public void testSerialization() throws IOException {
        PutStoredScriptRequest storedScriptRequest =
            new PutStoredScriptRequest("foo", "bar", "context", new BytesArray("{}"), XContentType.JSON);

        assertEquals(XContentType.JSON, storedScriptRequest.xContentType());
        try (BytesStreamOutput output = new BytesStreamOutput()) {
            storedScriptRequest.writeTo(output);

            try (StreamInput in = output.bytes().streamInput()) {
                PutStoredScriptRequest serialized = new PutStoredScriptRequest();
                serialized.readFrom(in);
                assertEquals(XContentType.JSON, serialized.xContentType());
                assertEquals(storedScriptRequest.lang(), serialized.lang());
                assertEquals(storedScriptRequest.id(), serialized.id());
                assertEquals(storedScriptRequest.context(), serialized.context());
            }
        }
    }

    public void testSerializationBwc() throws IOException {
        final byte[] rawStreamBytes = Base64.getDecoder().decode("ADwDCG11c3RhY2hlAQZzY3JpcHQCe30A");
        final Version version = randomFrom(Version.V_5_0_0, Version.V_5_0_1, Version.V_5_0_2,
            Version.V_5_1_1, Version.V_5_1_2, Version.V_5_2_0);
        try (StreamInput in = StreamInput.wrap(rawStreamBytes)) {
            in.setVersion(version);
            PutStoredScriptRequest serialized = new PutStoredScriptRequest();
            serialized.readFrom(in);
            assertEquals(XContentType.JSON, serialized.xContentType());
            assertEquals("mustache", serialized.lang());
            assertEquals("script", serialized.id());
            assertEquals(new BytesArray("{}"), serialized.content());

            try (BytesStreamOutput out = new BytesStreamOutput()) {
                out.setVersion(version);
                serialized.writeTo(out);
                out.flush();
                assertArrayEquals(rawStreamBytes, out.bytes().toBytesRef().bytes);
            }
        }
    }
}


text:
// Template Source: Enum.java.tt
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All Rights Reserved.  Licensed under the MIT License.  See License in the project root for license information.
// ------------------------------------------------------------------------------

package com.microsoft.graph.models;

/**
 * The Enum Install Intent.
*/
public enum InstallIntent
{
    /**
    * available
    */
    AVAILABLE,
    /**
    * required
    */
    REQUIRED,
    /**
    * uninstall
    */
    UNINSTALL,
    /**
    * available Without Enrollment
    */
    AVAILABLE_WITHOUT_ENROLLMENT,
    /**
    * For InstallIntent values that were not expected from the service
    */
    UNEXPECTED_VALUE
}


text:
#import "MVSelectorContentView.h"
#import <QuartzCore/QuartzCore.h>

@implementation MVSelectorContentView

- (instancetype)initWithFrame:(CGRect)frame text:(NSString *)text;
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        [self createLabel:text];
    }
    return self;
}

- (void)createLabel:(NSString *)text {

    CGSize size = self.frame.size;
    CGRect labelFrame = CGRectMake(0.0f, 0.0f, size.width, size.height);
    self.label = [[UILabel alloc] initWithFrame:labelFrame];
    self.label.text = text;
    self.label.font = [UIFont boldSystemFontOfSize:12.0f];
    self.label.backgroundColor = [UIColor clearColor];
    self.label.textAlignment = NSTextAlignmentCenter;
    self.label.textColor = [UIColor colorWithWhite:0.5f alpha:1.0f];

    self.label.layer.shadowOffset = CGSizeMake(0.0f, 2.5f);
    self.label.layer.shadowOpacity = 0.15f;
    self.label.layer.shadowRadius = 2.5f;

    [self addSubview:self.label];
}

- (void)setSelected:(BOOL)selected {

    float white = selected ? 0.2f : 0.5f;
    self.label.textColor = [UIColor colorWithWhite:white alpha:1.0f];
}

@end


text:
class PlatformBackend {
public:
    std::tuple<QPoint, QPixmap> getCursor();
    pid_t pid();
    static PlatformBackend &inst() {
        static PlatformBackend inst;
        return inst;
    }
    WId getActiveWID();
};

#endif // X11BACKEND_HPP


text:
#pragma once

enum CharClass
{
	CharClass_Letter,
	CharClass_Digit,
	CharClass_Other
};

bool		IsCppIdSeparator(wchar_t chr);
bool		IsCppIdStart(wchar_t chr);
bool		IsCppKeyword(const wchar_t* str, unsigned int len);
CharClass	GetCharClass(wchar_t chr);


text:
layout: post
date:	2013-06-12 01:49:00
title:  More on scientific names....
tags: [archived-posts]
categories: archives
permalink: /:categories/:year/:month/:day/:title/
---
I do understand the need for scientific names, but I also must add the caveat that they are not required by everyone; some of us ambling-along nature-lovers find some scientific names very off-putting indeed. How interesting it is, to tell a group of children, "See the Spittle-bugs!

Can you see how that froth protects the larvae?" rather than saying:

"The froghoppers, or the superfamily Cercopoidea, are a group of Hemipteran insects, in the suborder Auchenorrhyncha. Traditionally, most of this superfamily was considered a single family, Cercopidae, but this family has been split into three separate families for many years now: the Aphrophoridae, Cercopidae, and Clastopteridae. More recently, the family Epipygidae has been removed from the Aphrophoridae."

If I spout that paragraph at a group of children or adults whom I am taking on a nature trail, they will disappear faster than the dew on the grass...or the froth on it! The only Superfamily many children would be interested in would be from the movie "The Incredibles"!


text:
import re

class RewriteRuleManager:
  def __init__(self):
    self.preRules = []
    self.postRules = []

  def read_from(self, path):
    pre = []
    post = []

    section = None
    for line in open(path):
      line = line.strip()
      if line.startswith('#') or not line:
        continue

      if line.startswith('[') and line.endswith(']'):
        section = line[1:-1].lower()

      else:
        pattern, replacement = line.split('=', 1)
        pattern, replacement = pattern.strip(), replacement.strip()
        rule = RewriteRule(pattern, replacement)

        if section == 'pre':
          pre.append(rule)
        elif section == 'post':
          post.append(rule)

    self.preRules = pre
    self.postRules = post

class RewriteRule:
  def __init__(self, pattern, replacement):
    self.pattern = pattern
    self.replacement = replacement
    self.regex = re.compile(pattern)

  def apply(self, metric):
    return self.regex.sub(self.replacement, metric)

# Ghetto singleton
RewriteRuleManager = RewriteRuleManager()


text:
Capture Web Portal for WiFi solutions. Made for Aerohive.

Current frontpage profiled for 6 municipalities in Norway with logo's, Norwegian text and background picture branded with their co-owned service provider's logo.

Back-end connects to FreeRADIUS' MySQL database and inserts the created users in the correct table there.


text:
package org.unitime.timetable.backup;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;

import org.dom4j.DocumentException;

/**
 * @author Tomas Muller
 */
public interface SessionRestoreInterface {
	public void restore(InputStream input, BackupProgress progress) throws IOException, InstantiationException, IllegalAccessException, DocumentException, InvocationTargetException, NoSuchMethodException;
}


text:
describe package 'mysql-community-server' do
  it { should be_installed }
  its('version') { should match /^5\.5.*/ }
end

describe command 'mysql --version' do
  its('exit_status') { should eq 0 }
  its('stdout') { should match /Distrib 5\.5.*/ }
end


text:
using SqlDotNet.Compiler;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SqlDotNet.Runtime
{
    /// <summary>
    /// Load a constant value onto the stack
    /// </summary>
    public class LoadConstantCCNode : CommandChainNode
    {
        public LoadConstantCCNode(CommandChainNode parent)
            : base(parent)
        {

        }

        /// <summary>
        /// Value of the current constant
        /// </summary>
        public object ConstantValue
        {
            get;
            set;
        }

        /// <summary>
        /// Datatype
        /// </summary>
        public DataType DataType
        {
            get;
            set;
        }
    }
}


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

<configuration debug="false">

    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <!-- encoders are  by default assigned the type
             ch.qos.logback.classic.encoder.PatternLayoutEncoder -->
        <encoder>
            <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
        </encoder>
    </appender>

    <root level="debug">
        <appender-ref ref="STDOUT"/>
    </root>

    <logger name="org.springframework" level="WARN"/>
    <logger name="org.hibernate" level="WARN"/>
    <logger name="org.apache" level="WARN"/>

</configuration>


text:
<?php

/**
* Webzash Plugin Generic Helper
*
* @package Webzash
* @subpackage Webzash.View
*/
class GenericHelper extends AppHelper {

	var $helpers = array('Html', 'Session');

/**
 * Helper method to return the tag
 */
	function showTag($id) {

		if (empty($id)) {
			return '';
		}

		if (empty($this->_View->viewVars['allTags'])) {
			return '';
		}

		$tags = $this->_View->viewVars['allTags'];

		if (empty($tags[$id])) {
			return __d('webzash', 'ERROR');
		}

		$tag = $tags[$id];

		return '' .
			$this->Html->link($tag['title'], array(
					'plugin' => 'webzash',
					'controller' => 'entries',
					'action' => 'index',
					'tag' => $tag['id']
				),
				array('style' => 'color:#' . h($tag['color']) . ';')
			) . '';
	}

/**
 * Show the entry ledger details
 */
	function entryLedgers($id) {
		/* Load the Entry model */
		App::import("Webzash.Model", "Entry");
		$Entry = new Entry();
		return $Entry->entryLedgers($id);
	}

/**
 * Add a row to excel sheet
 */
	function xlsAddRow($row)
	{
		$cells = "";
		foreach ($row as $k => $v) {
			$type = 'String';
			if (is_numeric($v)) {
				$type = 'Number';
			}
			$v = h($v);
			$cells .= "<Cell><Data ss:Type=\"$type\">" . $v . "</Data></Cell>\n";
		}
		return "<Row>\n" . $cells . "</Row>\n";
	}

/**
 * Wzuser return status string
 */
	function wzuser_status($status) {
		switch ($status) {
			case '0': return __d('webzash', 'Disabled');
			case '1': return __d('webzash', 'Enabled');
			default: return __d('webzash', 'ERROR');
		}
	}
/**
 * Wzuser return status options
 */
	function wzuser_status_options() {
		return array(
			'0' => __d('webzash', 'Disabled'),
			'1' => __d('webzash', 'Enabled'),
		);
	}

/**
 * Wzuser return status string
 */
	function wzuser_role($role) {
		switch ($role) {
			case 'admin': return __d('webzash', 'Administrator');
			case 'manager': return __d('webzash', 'Manager');
			case 'accountant': return __d('webzash', 'Accountant');
			case 'dataentry': return __d('webzash', 'Data entry operator');
			case 'guest': return __d('webzash', 'Guest');
			default: return __d('webzash', 'ERROR');
		}
	}
/**
 * Wzuser return status options
 */
	function wzuser_role_options() {
		return array(
			'admin' => __d('webzash', 'Administrator'),
			'manager' => __d('webzash', 'Manager'),
			'accountant' => __d('webzash', 'Accountant'),
			'dataentry' => __d('webzash', 'Data entry operator'),
			'guest' => __d('webzash', 'Guest'),
		);
	}

/**
 * Wzaccount return database type string
 */
	function wzaccount_dbtype($dbtype) {
		switch ($dbtype) {
			case 'Database/Mysql': return __d('webzash', 'MySQL');
			case 'Database/Sqlserver': return __d('webzash', 'MS SQL Server');
			case 'Database/Postgres': return __d('webzash', 'Postgres SQL (BETA)');
			default: return __d('webzash', 'ERROR');
		}
	}

/**
 * Wzaccount return database type options
 */
	function wzaccount_dbtype_options() {
		return array(
			'Database/Mysql' => __d('webzash', 'MySQL'),
			'Database/Sqlserver' => __d('webzash', 'MS SQL Server'),
			'Database/Postgres' => __d('webzash', 'Postgres SQL (BETA)'),
		);
	}

/**
 * Wzsetting return row count options
 */
	function wzsetting_row_count_options() {
		return array(
			'10' => '10',
			'25' => '25',
			'50' => '50',
			'100' => '100',
			'200' => '200',
		);
	}

/**
 * Wzsetting return drcr or toby options
 */
	function wzsetting_drcr_toby_options() {
		return array(
			'drcr' => __d('webzash', 'Dr / Cr'),
			'toby' => __d('webzash', 'To / By'),
		);
	}

/**
 * Group return net or gross options
 */
	function group_netgross_options() {
		return array(
			1 => __d('webzash', 'Gross Profit & Loss'),
			0 => __d('webzash', 'Net Profit & Loss'),
		);
	}

/**
 * Entrytype return numbering options
 */
	function entrytype_numbering_options() {
		return array(
			'1' => __d('webzash', 'Auto'),
			'2' => __d('webzash', 'Manual (required)'),
			'3' => __d('webzash', 'Manual (optional)'),
		);
	}

/**
 * Entrytype return restriction options
 */
	function entrytype_restriction_options() {
		return array(
			'1' => __d('webzash', 'Unrestricted'),
			'2' => __d('webzash', 'Atleast one Bank or Cash account must be present on Debit side'),
			'3' => __d('webzash', 'Atleast one Bank or Cash account must be present on Credit side'),
			'4' => __d('webzash', 'Only Bank or Cash account can be present on both Debit and Credit side'),
			'5' => __d('webzash', 'Only NON Bank or Cash account can be present on both Debit and Credit side'),
		);
	}

/**
 * Search return range options
 */
	function search_range_options() {
		return array(
			'1' => __d('webzash', 'Equal to'),
			'2' => __d('webzash', 'Less than or Equal to'),
			'3' => __d('webzash', 'Greater than or equal to'),
			'4' => __d('webzash', 'In between'),
		);
	}

/**
 * Settings return printer orientation options
 */
	function printer_orientation_options() {
		return array(
			'P' => __d('webzash', 'Potrait'),
			'L' => __d('webzash', 'Landscape'),
		);
	}

/**
 * Settings return printer page format options
 */
	function printer_pageformat_options() {
		return array(
			'H' => __d('webzash', 'HTML'),
			'T' => __d('webzash', 'Text'),
		);
	}

/**
 * return mail protocol options
 */
	function mail_protocol_options() {
		return array(
			'Smtp' => __d('webzash', 'smtp'),
			'Mail' => __d('webzash', 'mail'),
		);
	}

/**
 * return date format options
 *
 * Date format : PHP Format|Javascript Format
 */
	function dateformat_options() {
		return array(
			'd-M-Y|dd-M-yy' => __d('webzash', 'Day-Month-Year'),
			'M-d-Y|M-dd-yy' => __d('webzash', 'Month-Day-Year'),
			'Y-M-d|yy-M-dd' => __d('webzash', 'Year-Month-Day'),
		);
	}

/**
 * return decimal places options
 */
	function decimal_places_options() {
		return array(
			'2' => '2',
			'3' => '3',
		);
	}

/**
 * return currency format options
 */
	function currency_format_options() {
		return array(
			'none' => '(NONE)',
			'##,###.##' => '##,###.##',
			'##,##.##' => '##,##.##',
		);
	}
}


text:
      X

<link rel="stylesheet" href="https://lively-kernel.org/lively4/swd21-pipes-and-filters/demos/swd21/pipes-and-filters/presentation/src/html/pipelineStyles.css" data-href="https://lively-kernel.org/lively4/swd21-pipes-and-filters/demos/swd21/pipes-and-filters/presentation/src/html/pipelineStyles.css">


text:
/*global user_pref*/
user_pref('devtools.responsiveUI.customWidth', 1280);
user_pref('devtools.responsiveUI.customHeight', 800);
user_pref('devtools.responsiveUI.currentPreset', 'custom');


text:
require 'spec_helper'

describe "containers/remove.html.erb" do
  pending "add some examples to (or delete) #{__FILE__}"
end


text:
<?php

namespace Anam\Captcha\Tests;

use Anam\Captcha\Facade\Captcha;
use Anam\Captcha\ServiceProvider\CaptchaServiceProvider;
use Orchestra\Testbench\TestCase as OrchestraTestCase;

class TestCase extends OrchestraTestCase
{
    /**
     * Load package service provider
     *
     * @param  \Illuminate\Foundation\Application  $app
     * @return \Anam\Captcha\ServiceProvider\CaptchaServiceProvider
     */
    protected function getPackageProviders($app)
    {
        return [CaptchaServiceProvider::class];
    }
    /**
     * Load package alias
     *
     * @param  \Illuminate\Foundation\Application $app
     * @return array
     */
    protected function getPackageAliases($app)
    {
        return [
            'Captcha' => Captcha::class,
        ];
    }
}


text:
<!doctype html>

    <link type="text/css" rel="stylesheet" href="stylesheets/default.css"/>
    <title>IronSight Contact</title>


text:
import threading
import subprocess
import os
import signal
from Queue import Queue
from time import sleep
import argparse

import tornado.ioloop
import tornado.web
import alsaaudio

from util.log import *

#
# class RunCmd(threading.Thread):
#     def __init__(self, cmd, timeout):
#         threading.Thread.__init__(self)
#         self.cmd = cmd
#         self.timeout = timeout
#
#     def run(self):
#         self.p = sub.Popen(self.cmd)
#         self.p.wait()
#
#     def Run(self):
#         self.start()
#         self.join(self.timeout)
#
#         if self.is_alive():
#             self.p.terminate()      #use self.p.kill() if process needs a kill -9
#             self.join()

# handlers

class RETURNCODE:
    SUCCESS = '1'
    ERROR   = '2'
    FAIL    = '3'
    EMPTY   = '4'
    NO_RES  = '5'

class StopHandler(tornado.web.RequestHandler):
    def get(self):
        url = self.get_argument("url", None)
        if url is None or url == "":
            INFO("url is empty")
            self.write(str(RETURNCODE.EMPTY))
            return
        if stop_audio(url):
            self.write(RETURNCODE.FAIL)
        else:
            self.write(RETURNCODE.SUCCESS)

class ClearQeueuHandler(tornado.web.RequestHandler):
    def get(self):
        clear_audio_queue()
        self.write(RETURNCODE.SUCCESS)

class VolumeHandler(tornado.web.RequestHandler):

    CARD_NAME = u'R19U'

    def initialize(self):
        cards = alsaaudio.cards()
        INFO(cards)
        card_idx = cards.index(VolumeHandler.CARD_NAME)
        self._m = alsaaudio.Mixer(control='PCM', cardindex=card_idx)
        INFO("use card %d." % card_idx)

    def get(self):
        DEBUG(u"正在获取音量值")
        try:
            volumes = self._m.getvolume()
            INFO("get volumes:%s" % volumes)
            volume = str(int(volumes[0]))
            DEBUG(u"当前音量值为:%s" % volume)
            self.write(volume)
        except Exception, e:
            ERROR(e)
        self.write("")

    def post(self):
        v_str = self.get_argument("v", default=None, strip=False)
        if v_str is None:
            self.write("-1")
            WARN(u"请输入音量值")
            return
        try:
            DEBUG("set volume:%s" % v_str)
            volume = int(v_str)
        except ValueError:
            try:
                volume = float(v_str)
                self.write("-2")
                ERROR(u"音量值必须为整数")
                return
            except ValueError:
                volume = -1
        if volume == -1:
            self.write("-3")
            ERROR(u"音量值无效:%s" % msg)
            return
        self._m.setvolume(volume)
        INFO(u"设置音量值为:%s" % str(volume))
        self.write(RETURNCODE.SUCCESS)

class PlayHandler(tornado.web.RequestHandler):
    def get(self):
        url = self.get_argument("url", None)
        if url is None or url == "":
            INFO("url is empty")
            self.write(str(RETURNCODE.EMPTY))
            return

        is_inqueue = self.get_argument("inqueue", None)
        loop = self.get_argument("loop", None)
        if is_inqueue is None:
            if loop is None:
                play_audio(url)
            else:
                play_audio(url, int(loop))
        else:
            if loop is None:
                play_audio_inqueue(url)
            else:
                play_audio_inqueue(url, int(loop))
        self.write(str(RETURNCODE.SUCCESS))

# class PauseHandler(tornado.web.RequestHandler):
#     def get(self):
#         # url = self.get_argument("url", None)
#         # if url is None or url == "":
#         if pause_audio_queue():
#             self.write(str(RETURNCODE.SUCCESS))
#         else:
#             self.write(str(RETURNCODE.ERROR))
#         # else:
#         #     if pause_audio(url):
#         #         self.write(str(RETURNCODE.SUCCESS))
#         #     else:
#         #         self.write(str(RETURNCODE.ERROR))

# ============== functions ============

# def wait_util_player_finished(mp):
#     sleep(0.1)
#     while mp.time_pos < mp.length \
#                         or mp.paused:
#         # print mp.time_pos
#         sleep(0.1)

def worker(play_url, loop):
    global mp_context

    # mp = Player()
    # mp.loop = loop
    # try:
    #     mp.loadfile(play_url)
    #     INFO("playing %s." % (play_url,))
    #     wait_util_player_finished(mp)
    # except Exception, ex:
    #     print ex
    # mp.loop = -1
    # mp.exit()
    # if play_url in mp_context:
    #     del mp_context[play_url]
    # cmd = ['mplayer', '-ao', 'alsa:device=btheadset', play_url, '-loop', str(loop)]
    # print cmd
    cmd = ['mplayer', play_url, '-loop', str(loop)]
    with open(os.devnull, 'w') as tempf:
        player = subprocess.Popen(cmd, stdout=tempf, stderr=tempf)
        mp_context[play_url] = player
        print "player create: " + str(player.pid)
        player.communicate()
    if play_url in mp_context:
        del mp_context[play_url]
    print "play finished:%s" % (play_url,)

def play_audio(url, loop=1):
    global mp_context

    if url in mp_context:
        mp = mp_context[url]
        if not mp is None:  # for thread-safe
            mp.terminate()
    t = threading.Thread(target=worker, args=(url, loop))
    t.setDaemon(True)
    t.start()

    return True

def play_audio_inqueue(url, loop=1):
    global mp_queue
    mp_queue.put((url, loop))
    INFO("%s was added to queue." % (url,))

def stop_audio(url):
    global mp_context
    if not url in mp_context:
        WARN("%s is not playing" % (url, ))
        return False
    else:
        mp = mp_context[url]
        if not mp is None:  # for thread-safe
            mp.terminate()
            if url in mp_context:
                del mp_context[url]
        return True

# def pause_audio(url):
#     global mp_context
#     if not url in mp_context:
#         WARN("%s is not playing" % (url, ))
#         return False
#     else:
#         INFO("pause: " + url)
#         mp = mp_context[url]
#         mp.pause()
#         return True

# def pause_audio_queue():
#     global mp_context
#     INFO("pause audio queue.")
#     mp = mp_context["queue"]
#     mp.pause()
#     return True

def clear_audio_queue():
    global mp_context
    global mp_queue

    with mp_queue.mutex:
        mp_queue.queue.clear()
    if "queue" in  mp_context:
        mp_context["queue"].terminate()
        del mp_context["queue"]

def queue_worker():
    global mp_context
    global mp_queue

    while True:
        url, loop = mp_queue.get()
        print "get from queue:" + str(url)
        # cmd = ['mplayer', '-ao', 'alsa:device=btheadset', url, '-loop', str(loop)]
        cmd = ['mplayer', url, '-loop', str(loop)]
        # print cmd
        with open(os.devnull, 'w') as tempf:
            player = subprocess.Popen(cmd, stdout=tempf, stderr=tempf)
            mp_context["queue"] = player
            player.communicate()
            print url + u" stopped."
            if "queue" in  mp_context:
                del mp_context["queue"]
        mp_queue.task_done()
    sleep(1)

def init_queue_player():
    t = threading.Thread(target=queue_worker)
    t.setDaemon(True)
    t.start()

mp_context = {}
mp_queue = Queue()
# http://stackoverflow.com/questions/17101502/how-to-stop-the-tornado-web-server-with-ctrlc
is_closing = False
def signal_handler(signum, frame):
    global is_closing
    is_closing = True

def try_exit():
    global is_closing, mp_context
    if is_closing:
        # clean up here
        tornado.ioloop.IOLoop.instance().stop()
        logging.info('exit success')
        for url in mp_context:
            mp = mp_context[url]
            mp.terminate()

application = tornado.web.Application([
    (r"/play", PlayHandler),
    (r"/clear", ClearQeueuHandler),
    (r"/stop", StopHandler),
    (r"/volume", VolumeHandler),
    # (r"/pause", PauseHandler),
])

if __name__ == "__main__":
    parser = argparse.ArgumentParser(
                    description='audio_server.py -p port')
    parser.add_argument('-p',
                        action="store",
                        dest="port",
                        default="8001",
                        )
    port = parser.parse_args().port
    INFO("bind to %s " % (port))

    signal.signal(signal.SIGINT, signal_handler)
    application.listen(port)
    init_queue_player()
    tornado.ioloop.PeriodicCallback(try_exit, 100).start()
    tornado.ioloop.IOLoop.instance().start()


text:
package org.apache.tephra.snapshot;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Throwables;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.inject.Inject;
import org.apache.hadoop.conf.Configuration;
import org.apache.tephra.TxConstants;
import org.apache.tephra.persist.TransactionSnapshot;
import org.apache.tephra.persist.TransactionVisibilityState;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.List;
import java.util.SortedMap;
import javax.annotation.Nonnull;

/**
 * Maintains the codecs for all known versions of the transaction snapshot encoding.
 */
public class SnapshotCodecProvider implements SnapshotCodec {

  private static final Logger LOG = LoggerFactory.getLogger(SnapshotCodecProvider.class);

  private final SortedMap<Integer, SnapshotCodec> codecs = Maps.newTreeMap();

  @Inject
  public SnapshotCodecProvider(Configuration configuration) {
    initialize(configuration);
  }

  /**
   * Register all codec specified in the configuration with this provider.
   * There can only be one codec for a given version.
   */
  private void initialize(Configuration configuration) {
    String[] codecClassNames = configuration.getTrimmedStrings(TxConstants.Persist.CFG_TX_SNAPHOT_CODEC_CLASSES);
    List<Class> codecClasses = Lists.newArrayList();
    if (codecClassNames != null) {
      for (String clsName : codecClassNames) {
        try {
          codecClasses.add(Class.forName(clsName));
        } catch (ClassNotFoundException cnfe) {
          LOG.warn("Unable to load class configured for " + TxConstants.Persist.CFG_TX_SNAPHOT_CODEC_CLASSES
              + ": " + clsName, cnfe);
        }
      }
    }

    if (codecClasses.size() == 0) {
      codecClasses.addAll(Arrays.asList(TxConstants.Persist.DEFAULT_TX_SNAPHOT_CODEC_CLASSES));
    }
    for (Class<?> codecClass : codecClasses) {
      try {
        SnapshotCodec codec = (SnapshotCodec) (codecClass.newInstance());
        codecs.put(codec.getVersion(), codec);
        LOG.debug("Using snapshot codec {} for snapshots of version {}", codecClass.getName(), codec.getVersion());
      } catch (Exception e) {
        LOG.warn("Error instantiating snapshot codec {}. Skipping.", codecClass.getName(), e);
      }
    }
  }

  /**
   * Retrieve the codec for a particular version of the encoding.
   * @param version the version of interest
   * @return the corresponding codec
   * @throws java.lang.IllegalArgumentException if the version is not known
   */
  @Nonnull
  @VisibleForTesting
  SnapshotCodec getCodecForVersion(int version) {
    SnapshotCodec codec = codecs.get(version);
    if (codec == null) {
      throw new IllegalArgumentException(String.format("Version %d of snapshot encoding is not supported", version));
    }
    return codec;
  }

  /**
   * Retrieve the current snapshot codec, that is, the codec with the highest known version.
   * @return the current codec
   * @throws java.lang.IllegalStateException if no codecs are registered
   */
  private SnapshotCodec getCurrentCodec() {
    if (codecs.isEmpty()) {
      throw new IllegalStateException(String.format("No codecs are registered."));
    }
    return codecs.get(codecs.lastKey());
  }

  // Return the appropriate codec for the version in InputStream
  private SnapshotCodec getCodec(InputStream in) {
    BinaryDecoder decoder = new BinaryDecoder(in);
    int persistedVersion;
    try {
      persistedVersion = decoder.readInt();
    } catch (IOException e) {
      LOG.error("Unable to read transaction state version: ", e);
      throw Throwables.propagate(e);
    }
    return getCodecForVersion(persistedVersion);
  }

  @Override
  public int getVersion() {
    return getCurrentCodec().getVersion();
  }

  @Override
  public TransactionSnapshot decode(InputStream in) {
    return getCodec(in).decode(in);
  }

  @Override
  public TransactionVisibilityState decodeTransactionVisibilityState(InputStream in) {
    return getCodec(in).decodeTransactionVisibilityState(in);
  }

  @Override
  public void encode(OutputStream out, TransactionSnapshot snapshot) {
    SnapshotCodec codec = getCurrentCodec();
    try {
      new BinaryEncoder(out).writeInt(codec.getVersion());
    } catch (IOException e) {
      LOG.error("Unable to write transaction state version: ", e);
      throw Throwables.propagate(e);
    }
    codec.encode(out, snapshot);
  }

}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>React Phone Number Input Style Guide</title>


text:
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Collections.Generic;
using System.Security.Cryptography;

namespace BloomFilterTests
{
    [TestClass]
    public class BloomFilterTests
    {
        [TestMethod]
        public void Empty_Bloom_Filter_Contains_Nothing()
        {
            var bf = new BloomFilter<string>(MaxItems: 100, FalsePositiveProbability: .001);
            Assert.IsFalse(bf.Contains("Dummy Value"));
        }

        [TestMethod]
        public void One_Item_Contains_Returns_True()
        {
            var bf = new BloomFilter<string>(MaxItems: 100);
            bf.Add("Test String");
            Assert.IsTrue(bf.Contains("Test String"));

        }

        [TestMethod]
        [ExpectedException(typeof(ArgumentException), "The maximum number of items (1) has already been reached.")]
        public void Cant_Add_More_Than_Max_Items()
        {
            var bf = new BloomFilter<string>(MaxItems: 1, FalsePositiveProbability: .001);
            bf.Add("Test String");
            bf.Add("Test String 2");
        }

        [TestMethod]
        [ExpectedException(typeof(ArgumentException), "Maximum items must be positive.")]
        public void Maximum_Items_Must_Be_Positive()
        {
            var bf = new BloomFilter<string>(MaxItems: -1, FalsePositiveProbability: .001);
        }

        [TestMethod]
        [ExpectedException(typeof(ArgumentException), "False Positive Probability must be between 0 and one.")]
        public void False_Positive_Probability_Must_Be_Greater_Than_Zero()
        {
            var bf = new BloomFilter<string>(MaxItems: 1, FalsePositiveProbability: 0);
        }

        [TestMethod]
        [ExpectedException(typeof(ArgumentException), "False Positive Probability must be between 0 and one.")]
        public void False_Positive_Probability_Must_Be_Less_Than_One()
        {
            var bf = new BloomFilter<string>(MaxItems: 1, FalsePositiveProbability: 1);
        }

        [TestMethod]
        public void Serialize_Object_With_Padding_Returns_Correct_Length_And_Padding_Values()
        {
            var bfbase = new BloomFilter<string>(MaxItems: 100);
            var bf = new PrivateObject(bfbase, new PrivateType(typeof(BloomFilter<string, SHA1Managed>)));
            Int32 i = 1;
            byte[] ba = (byte[])bf.Invoke("serializeObjectWithPadding", new object[] { i });
            Assert.AreEqual(ba.Length, 58);
            Assert.AreEqual(ba[0], 0x00);
            Assert.AreEqual(ba[1], 0x00);
            Assert.AreEqual(ba[2], 0x00);
            Assert.AreEqual(ba[3], 0x00);
        }

        [TestMethod]
        public void Serialize_Object_With_Padding_Returns_Null_When_Given_Null()
        {
            var bfbase = new BloomFilter<string>(MaxItems: 100);
            var bf = new PrivateObject(bfbase, new PrivateType(typeof(BloomFilter<string, SHA1Managed>)));
            object obj = (byte[])bf.Invoke("serializeObjectWithPadding", new object[] { null });
            Assert.IsNull(obj);
        }

        [TestMethod]
        public void Compute_Indices_Returns_Correct_Values_For_SHA1_Integer_One()
        {
            var bfbase = new BloomFilter<int>(MaxItems: 1);
            var bf = new PrivateObject(bfbase, new PrivateType(typeof(BloomFilter<int, SHA1Managed>)));
            int[] ba = (int[])bf.Invoke("computeIndices", new object[] { 1 });
            Assert.AreEqual(ba.Length, 10);
            Assert.AreEqual(ba[0], 12);
            Assert.AreEqual(ba[1], 8);
            Assert.AreEqual(ba[2], 8);
            Assert.AreEqual(ba[3], 7);
            Assert.AreEqual(ba[4], 9);
            Assert.AreEqual(ba[5], 13);
            Assert.AreEqual(ba[6], 0);
            Assert.AreEqual(ba[7], 5);
            Assert.AreEqual(ba[8], 1);
            Assert.AreEqual(ba[9], 11);
        }

        bool FalsePositiveRateIsCorrect(int itemCount, double falsePositiveProbability)
        {
            using (var bf = new BloomFilter<int>(itemCount, falsePositiveProbability))
            {
                for (var i = 0; i < itemCount; i++)
                {
                    bf.Add(i);
                }
                //check the same number of known false values using contains()
                var falsePositives = 0;
                for (var j = itemCount; j < itemCount * 2; j++)
                {
                    if (bf.Contains(j))
                        falsePositives++;
                }
                Console.WriteLine((double)falsePositives / itemCount);
                //we don't have perfect hashing, allow double the false positive probability...
                //I'm more concerned with order of magnitude errors
                return ((double)falsePositives / itemCount <= (falsePositiveProbability * 2));
            }
        }

        [TestMethod]
        public void False_Positive_Probability_For_10000_Items_And_Point_01()
        {
            Assert.IsTrue(FalsePositiveRateIsCorrect(10000, .01));
        }

        [TestMethod]
        public void False_Positive_Probability_For_10000_Items_And_Point_001()
        {
            Assert.IsTrue(FalsePositiveRateIsCorrect(10000, .001));
        }

        [TestMethod]
        public void False_Positive_Probability_For_10000_Items_And_Point_0001()
        {
            Assert.IsTrue(FalsePositiveRateIsCorrect(10000, .0001));
        }

        [TestMethod]
        public void False_Positive_Probability_For_100000_Items_And_Point_1()
        {
            Assert.IsTrue(FalsePositiveRateIsCorrect(100000, .1));
        }

        [TestMethod]
        public void False_Positive_Probability_For_100000_Items_And_Point_01()
        {
            Assert.IsTrue(FalsePositiveRateIsCorrect(100000, .01));
        }

        [TestMethod]
        public void False_Positive_Probability_For_100000_Items_And_Point_001()
        {
            Assert.IsTrue(FalsePositiveRateIsCorrect(100000, .001));
        }

        [TestMethod]
        public void False_Positive_Probability_For_1000000_Items_And_Point_001()
        {
            Assert.IsTrue(FalsePositiveRateIsCorrect(1000000, .001));
        }
    }
}


text:
{% extends "tardis_portal/portal_template.html" %}
{% load basiccomparisonfilters %}
{% load parametertypecheck %}
{% load uploadify_tags %}
{% load dynurl %}

{% block script %}

{% endblock %}

{% block fullpage %}

{{ experiment.title }}

      [Edit]

Description

Datasets ({{ experiment.dataset_set.count }})

	  {% if experiment.ftp_location %}
FTP Download
{% endif %}
	  {% for appurl, appname in apps %}

{{ appname }}

	  {% endfor %}

{% endblock %}


text:
from __future__ import unicode_literals
import argparse
import logging
from .tokenizer import Cutkum

def main():
	p = argparse.ArgumentParser()
	p.add_argument('-v', '--verbose', help='verbose', action='store_true')
	#p.add_argument('-m', '--model_file', required=True, help='model file to load')
	g1 = p.add_mutually_exclusive_group(required=True)
	g1.add_argument('-s', '--sentence', help='sentence to parse')
	g1.add_argument('-i', '--input_file', help='input file')
	g1.add_argument('-id', '--input_dir', help='input directory')

	g2 = p.add_mutually_exclusive_group(required=False)
	g2.add_argument('-o', '--output_file', help='output file if --input_file is given')
	g2.add_argument('-od', '--output_dir', help='output directory if --input_dir is given')

	g3 = p.add_mutually_exclusive_group(required=False)
	g3.add_argument('--viterbi', action='store_const', dest='max_flag', const='vit', help='output word boundary using viterbi (default)')
	g3.add_argument('--max', action='store_const', dest='max_flag', const='max', help='output word boundary using maximum probabilities')
	p.set_defaults(max_flag='max')

	opts = vars(p.parse_known_args()[0])

	verbose = opts['verbose']
	if (verbose):
		log_level = logging.INFO
	else:
		log_level = logging.WARNING
	logging.basicConfig(format='%(levelname)s:%(message)s', level=log_level)

	# OTHERS ARGS
	#model_file		= opts['model_file']
	input_sentence  = opts['sentence']
	input_file      = opts['input_file']
	output_file     = opts['output_file']
	input_dir       = opts['input_dir']
	output_dir      = opts['output_dir']
	max_flag        = opts['max_flag']

	if (input_file is not None) & (output_file is None):
		p.error('--input_file and --output_file must be given together')
	if (input_dir is not None) & (output_dir is None):
		p.error('--input_dir and --output_dir must be given together')
	use_viterbi = True
	if (max_flag == 'max'):
		use_viterbi = False

	ck = Cutkum()
	#ck = Cutkum(model_file)
	if input_file is not None:
		ck.tokenize_file(input_file, output_file, use_viterbi)
	elif (input_dir is not None) & (output_dir is not None):
		ck.tokenize_directory(input_dir, output_dir, use_viterbi)
	elif input_sentence is not None:
		words = ck.tokenize(input_sentence, use_viterbi)
		print("|".join(words))

if __name__ == '__main__':
	main()


text:
<?php
/**
 * Created by PhpStorm.
 * User: user
 * Date: 2/28/2017
 * Time: 11:05 PM
 */

namespace Gossamer\Horus\Traits;

trait SessionTrait
{

    protected function getSession($key) {
        $session = $_SESSION;

        return $this->fixObject($session[$key]);
    }

    protected function setSession($key, $value) {
        $_SESSION[$key] = $value;
    }

    protected function fixObject(&$object) {
        if (!is_object($object) && gettype($object) == 'object') {

            return ($object = unserialize(serialize($object)));
        }

        return $object;
    }
}


text:
package com.xiaozan.common.corba.test1;

import org.omg.CORBA.ORB;

import com.xiaozan.common.corba.test1.getMessage.GetItPOA;

public class GetItImpl extends GetItPOA {

	private ORB orb;

	public void setOrb(ORB orb) {
		this.orb = orb;
	}

	@Override
	public String returnString(String str) {

		return "\nHello " + str;
	}

}


text:
namespace NEventStore.Persistence.AcceptanceTests
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
	using System.Threading.Tasks;

    public static class ExtensionMethods
    {
        public static HashSet<T> ToHashSet<T>(this IEnumerable<T> collection)
        {
            return new HashSet<T>(collection);
        }

        public static LinkedList<T> ToLinkedList<T>(this IEnumerable<T> collection)
        {
            return new LinkedList<T>(collection);
        }

        public static Task<ICommit> CommitSingle(this IPersistStreams persistence, string streamId = null, DateTime? now = null)
        {
            CommitAttempt commitAttempt = (streamId ?? Guid.NewGuid().ToString())
                .BuildAttempt(now:now);

            return persistence.Commit(commitAttempt);
        }

		public static Task<ICommit> CommitNext(this IPersistStreams persistence, ICommit previous)
        {
            var nextAttempt = previous.BuildNextAttempt();
            return persistence.Commit(nextAttempt);
        }

		public static Task<ICommit> CommitNext(this IPersistStreams persistence, CommitAttempt previous)
        {
            var nextAttempt = previous.BuildNextAttempt();
            return persistence.Commit(nextAttempt);
        }

        public static async Task<IEnumerable<CommitAttempt>> CommitMany(this IPersistStreams persistence,
            int numberOfCommits, string streamId = null, string bucketId = null, DateTime? now = null)
        {
            var commits = new List<CommitAttempt>();
            CommitAttempt attempt = null;

            for (int i = 0; i < numberOfCommits; i++)
            {
                attempt = attempt == null ? (streamId ?? Guid.NewGuid().ToString()).BuildAttempt(now, bucketId) : attempt.BuildNextAttempt();
                await persistence.Commit(attempt);
                commits.Add(attempt);
            }

            return commits;
        }

        public static CommitAttempt BuildAttempt(this string streamId, DateTime? now = null, string bucketId = null)
        {
            now = now ?? DateTime.UtcNow;
            bucketId = bucketId ?? Bucket.Default;

            var messages = new List<EventMessage>
            {
                new EventMessage {Body = new SomeDomainEvent {SomeProperty = "Test"}},
                new EventMessage {Body = new SomeDomainEvent {SomeProperty = "Test2"}},
            };

            return new CommitAttempt(bucketId, streamId,
                2,
                Guid.NewGuid(),
                1,
                now.Value,
                new Dictionary<string, object> {{"A header", "A string value"}, {"Another header", 2}},
                messages);
        }

        public static CommitAttempt BuildNextAttempt(this ICommit commit)
        {
            var messages = new List<EventMessage>
            {
                new EventMessage {Body = new SomeDomainEvent {SomeProperty = "Another test"}},
                new EventMessage {Body = new SomeDomainEvent {SomeProperty = "Another test2"}},
            };

            return new CommitAttempt(commit.BucketId,
                commit.StreamId,
                commit.StreamRevision + messages.Count,
                Guid.NewGuid(),
                commit.CommitSequence + 1,
                commit.CommitStamp.AddSeconds(1),
                new Dictionary<string, object>(),
                messages);
        }

        public static CommitAttempt BuildNextAttempt(this CommitAttempt commit)
        {
            var messages = new List<EventMessage>
            {
                new EventMessage {Body = new SomeDomainEvent {SomeProperty = "Another test"}},
                new EventMessage {Body = new SomeDomainEvent {SomeProperty = "Another test2"}},
            };

            return new CommitAttempt(commit.BucketId,
                commit.StreamId,
                commit.StreamRevision + 2,
                Guid.NewGuid(),
                commit.CommitSequence + 1,
                commit.CommitStamp.AddSeconds(1),
                new Dictionary<string, object>(),
                messages);
        }

        public static SimpleMessage Populate(this SimpleMessage message)
        {
            message = message ?? new SimpleMessage();

            return new SimpleMessage
            {
                Id = Guid.NewGuid(),
                Count = 1234,
                Created = new DateTime(2000, 2, 3, 4, 5, 6, 7).ToUniversalTime(),
                Value = message.Value + "Hello, World!",
                Contents = {"a", null, string.Empty, "d"}
            };
        }

        public static CommitAttempt BuildCommit(this string streamId, ISystemTimeProvider systemTimeProvider)
        {
            const int streamRevision = 2;
            const int commitSequence = 2;
            Guid commitId = Guid.NewGuid();
            var headers = new Dictionary<string, object> {{"Key", "Value"}, {"Key2", (long) 1234}, {"Key3", null}};
            var events = new[]
            {
                new EventMessage
                {
                    Headers = {{"MsgKey1", TimeSpan.MinValue}, {"MsgKey2", Guid.NewGuid()}, {"MsgKey3", 1.1M}, {"MsgKey4", (ushort) 1}},
                    Body = "some value"
                },
                new EventMessage
                {
                    Headers = {{"MsgKey1", new Uri("http://www.google.com/")}, {"MsgKey4", "some header"}},
                    Body = new[] {"message body"}
                }
            };

            return new CommitAttempt(streamId, streamRevision, commitId, commitSequence, systemTimeProvider.UtcNow, headers, events.ToList());
        }

        [Serializable]
        public class SomeDomainEvent
        {
            public string SomeProperty { get; set; }

            public override string ToString()
            {
                return SomeProperty;
            }
        }
    }
}


text:
<?php
/**
* @name: Mail
* @description: Kontroler wysyłania maila
*/

class ctrlMail
{
   private $config;
   private $message;
   private $order;
   private $totalPrice;
   private $name;
   private $email;
   private $orderHtml;
   function __construct($config = [])
   {
      $this->config = $config;
   }
   private function createMessage(){
      $this->prepereOrder();
      $this->message = "

               <title>Zamówienie</title>

Zamówienie od: ".$this->name."

                     Zamówienie:

                  ".$this->orderHtml."

Suma do zapłaty: ".$this->totalPrice."zł

         ";
   }
   private function prepereOrder(){
      foreach ($this->order as $key => $value)
      {
         $this->orderHtml .= '
'. $value . '
	';
      }
   }

   public function processData($post){
      $this->order = $post['order'];
      $this->totalPrice = $post['totalPrice'];
      $this->name = $post['name'];
      $this->email = $post['email'];
      $this->createMessage();
   }

   public function sendMail(){
      $headers = "MIME-Version: 1.0" . "\r\n";
      $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
      $headers .= 'From: '.$this->email.'' . "\r\n";
      mail($this->config->to, $this->config->subject, $this->message, $headers);
   }

}


text:
using System;
using System.ComponentModel;
using System.Text;
using System.Windows.Forms;
using MS.WindowsAPICodePack.Internal;
using Microsoft.WindowsAPICodePack.Shell;

namespace Microsoft.WindowsAPICodePack.Controls.WindowsForms
{
    /// <summary>
    /// Implements a CommandLink button that can be used in
    /// WinForms user interfaces.
    /// </summary>
    public class CommandLink : Button
    {
        /// <summary>
        /// Gets a System.Windows.Forms.CreateParams on the base class when
        /// creating a window.
        /// </summary>
        protected override CreateParams CreateParams
        {
            get
            {
                // Add BS_COMMANDLINK style before control creation.
                CreateParams cp = base.CreateParams;

                cp.Style = AddCommandLinkStyle(cp.Style);

                return (cp);
            }
        }

        // Let Windows handle the rendering.
        /// <summary>
        /// Creates a new instance of this class.
        /// </summary>
        public CommandLink()
        {
            // Throw PlatformNotSupportedException if the user is not running Vista or beyond
            CoreHelpers.ThrowIfNotVista();

            FlatStyle = FlatStyle.System;
        }

        // Add Design-Time Support.

        /// <summary>
        /// Increase default width.
        /// </summary>
        protected override System.Drawing.Size DefaultSize
        {
            get { return new System.Drawing.Size(180, 60); }
        }

        /// <summary>
        /// Specifies the supporting note text
        /// </summary>
        [Category("Appearance")]
        [Description("Specifies the supporting note text.")]
        [BrowsableAttribute(true)]
        [DefaultValue("(Note Text)")]
        public string NoteText
        {
            get { return (GetNote(this)); }
            set
            {
                SetNote(this, value);
            }
        }

        /// <summary>
        /// Enable shield icon to be set at design-time.
        /// </summary>
        [Category("Appearance")]
        [Description("Indicates whether the button should be decorated with the security shield icon (Windows Vista only).")]
        [BrowsableAttribute(true)]
        [DefaultValue(false)]
        public bool ShieldIcon
        {
            get { return (shieldIconDisplayed); }
            set
            {
                shieldIconDisplayed = value;
                SetShieldIcon(this, this.shieldIconDisplayed);
            }
        }
        private bool shieldIconDisplayed;

        #region Interop helpers

        private static int AddCommandLinkStyle(int Style)
        {
            int newStyle = Style;

            // Only add BS_COMMANDLINK style on Windows Vista or above.
            // Otherwise, button creation will fail.
            if (Environment.OSVersion.Version.Major >= 6)
            {
                newStyle |= ShellNativeMethods.BS_COMMANDLINK;
            }

            return (newStyle);
        }

        private static string GetNote(System.Windows.Forms.Button Button)
        {
            IntPtr retVal = CoreNativeMethods.SendMessage(
                Button.Handle,
                ShellNativeMethods.BCM_GETNOTELENGTH,
                IntPtr.Zero,
                IntPtr.Zero);

            // Add 1 for null terminator, to get the entire string back.
            int len = ((int)retVal) + 1;
            StringBuilder strBld = new StringBuilder(len);

            retVal = CoreNativeMethods.SendMessage(Button.Handle, ShellNativeMethods.BCM_GETNOTE, ref len, strBld);
            return (strBld.ToString());
        }

        private static void SetNote(System.Windows.Forms.Button button, string text)
        {
            // This call will be ignored on versions earlier than
            // Windows Vista.
            CoreNativeMethods.SendMessage(button.Handle, ShellNativeMethods.BCM_SETNOTE, 0, text);
        }

        static internal void SetShieldIcon(
         System.Windows.Forms.Button Button, bool Show)
        {
            IntPtr fRequired = new IntPtr(Show ? 1 : 0);
            CoreNativeMethods.SendMessage(
               Button.Handle,
                ShellNativeMethods.BCM_SETSHIELD,
                IntPtr.Zero,
                fRequired);
        }

        #endregion

        /// <summary>
        /// Indicates whether this feature is supported on the current platform.
        /// </summary>
        public static bool IsPlatformSupported
        {
            get
            {
                // We need Windows Vista onwards ...
                return CoreHelpers.RunningOnVista;
            }
        }
    }
}


text:
describe('Parser | Image |', function() {
  var rootdir = __dirname + '/../../../';
  var helper =  require(rootdir + 'test/helper.js');
  var rssDir = rootdir + 'test/feeds/rss/';
  var atomDir = rootdir + 'test/feeds/atom/';

  describe('Meta |', function() {
    var results = [];

    before(function(done) {
      var feeds = [
        rssDir + 'rss.1.xml',
        rssDir + 'rss.2.xml',
        rssDir + 'rss.3.xml',
        rssDir + 'rss.4.xml',
        atomDir + 'atom.1.xml',
        atomDir + 'atom.2.xml'
      ];

      helper.getFeedResults('meta', feeds, function (data) {
        results = data;
        done();
      });
    });

    it('should parse image url as top priority', function () {
      expect(results[0].image).to.equal('https://testimageurl/rss.jpg');
    });

    it('should parse image tag contents as next priority', function () {
      expect(results[1].image).to.equal('https://testimage/rss.jpg');
    });

    it('should parse itunes:image href as next priority', function () {
      expect(results[2].image).to.equal('https://testitunesimage/rss.jpg');
    });

    it('should parse media:thumbnail url as next priority', function () {
      expect(results[3].image).to.equal('https://testmediathumbnail/rss.jpg');
    });

    it('should parse logo as next priority', function () {
      expect(results[3].image).to.equal('https://testmediathumbnail/rss.jpg');
    });

    it('should parse logo as next priority', function () {
      expect(results[4].image).to.equal('https://testlogo/rss.jpg');
    });

    it('should parse logo and apply xml base url', function () {
      expect(results[5].image).to.equal('http://testbase.com/logo/rss.jpg');
    });
  });

  describe('Item |', function() {
    var results = [];

    before(function(done) {
      var feeds = [
        rssDir + 'rss.1.xml',
        rssDir + 'rss.2.xml',
        rssDir + 'rss.3.xml',
        rssDir + 'rss.4.xml',
        rssDir + 'rss.5.xml',
        rssDir + 'rss.6.xml',
        rssDir + 'rss.7.xml',
        rssDir + 'rss.8.xml'
      ];

      helper.getFeedResults('item', feeds, function (data) {
        results = data;
        done();
      });
    });

    it('should parse image url as top priority', function () {
      expect(results[0][0].image).to.equal('https://testimageurl/rss.jpg');
    });

    it('should parse image tag contents as next priority', function () {
      expect(results[1][0].image).to.equal('https://testimage/rss.jpg');
    });

    it('should parse media:thumbnail url as next priority', function () {
      expect(results[2][0].image).to.equal('http://mediathumbnail.com/test.jpg');
    });

    it('should parse media:content media:thumbnail url as next priority', function () {
      expect(results[3][0].image).to.equal('http://mediacontentthumbnail.com/test.jpg');
    });

    it('should parse media:group media:thumbnail url as next priority', function () {
      expect(results[4][0].image).to.equal('http://mediagroupthumbnail.com/test.jpg');
    });

    it('should parse itunes:image href as next priority', function () {
      expect(results[5][0].image).to.equal('http://itunesimage.com/test.jpg');
    });

    it('should parse media:content url as next priority', function () {
      expect(results[6][0].image).to.equal('http://testmediacontenturl/test.jpg');
    });

    it('should parse media:group media:content url as next priority', function () {
      expect(results[7][0].image).to.equal('http://testmediagroupcontenturl/test.jpg');
    });
  });

});


text:
package com.twitter.app;

import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import scala.reflect.ClassTag$;

import org.junit.Test;

import com.twitter.util.Duration;
import com.twitter.util.Function;
import com.twitter.util.StorageUnit;
import com.twitter.util.Time;

import static com.twitter.util.Function.func0;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;

public class JavaFlagTest {

  /**
   * A class representing a named thing. Used to illustrate flag-construction for
   * classes defined in application code. See [[com.twitter.app.Flaggable]] for
   * details.
   */
  static class Named {
    String name;

    static Flaggable<Named> ofNamed =
      Flaggable.mandatory(new Function<String, Named>() {
        @Override public Named apply(String n) {
          return new Named(n);
        }
      }, ClassTag$.MODULE$.apply(Named.class));

    Named(String name) {
      this.name = name;
    }
  }

  enum Disney {
    MICKEY,
    MINNIE
  }

  @Test
  public void testJavaFlags() {

    String applicationName = "com.twitter.app.JavaFlagTest";
    Flags flag = new Flags(applicationName);

    Flag<Named> named = flag.create("named", new Named(""), "", Named.ofNamed);
    Flag<String> stringFlag = flag.create("string", "default", "", Flaggable.ofString());
    Flag<Boolean> booleanFlag = flag.create("bool", true, "", Flaggable.ofJavaBoolean());
    Flag<Integer> integerFlag = flag.create("int", 1, "", Flaggable.ofJavaInteger());
    Flag<Long> longFlag = flag.create("long", 1L, "", Flaggable.ofJavaLong());
    Flag<Float> floatFlag = flag.create("float", 1.0f, "", Flaggable.ofJavaFloat());
    Flag<Double> doubleFlag = flag.create("double", 1.0d, "", Flaggable.ofJavaDouble());
    Flag<Duration> durationFlag =
        flag.create("duration", Duration.fromSeconds(1), "", Flaggable.ofDuration());
    Flag<StorageUnit> StorageUnitFlag =
        flag.create("storage unit", StorageUnit.zero(), "", Flaggable.ofStorageUnit());
    Flag<Time> timeFlag = flag.create("time", Time.Bottom(), "", Flaggable.ofTime());
    Flag<InetSocketAddress> addrFlag =
        flag.create("addr", new InetSocketAddress(0), "", Flaggable.ofInetSocketAddress());

    Flag<List<Integer>> listFlag = flag.create(
        "list",
        new ArrayList<>(),
        "",
        Flaggable.ofJavaList(Flaggable.ofJavaInteger())
    );

    Flag<Map<Integer, String>> mapFlag = flag.create(
        "map",
        new HashMap<>(),
        "",
        Flaggable.ofJavaMap(Flaggable.ofJavaInteger(), Flaggable.ofString())
    );

    // non-default flags test
    Flag<Integer> nonDefaultIntFlag = flag.createMandatory("mandatory-int", "you better supply this", "Integer", Flaggable.ofJavaInteger());
    Flag<String> nonDefaultStringFlag = flag.createMandatory("mandatory-str", "you better supply this", "String", Flaggable.ofString());
  }

  @Test
  public void testJavaLongFlags() {
    Flags flags = new Flags("ApplicationName");
    Flag<Long> longFlag = flags.create("long", 1234567890L, "", Flaggable.ofJavaLong());

    longFlag.parse();
    assertEquals(1234567890L, longFlag.apply().longValue());

    longFlag.parse("9876543210");
    assertEquals(9876543210L, longFlag.apply().longValue());

    try {
      longFlag.parse("9876543210L");
      fail();
    } catch (NumberFormatException expected) {
      assertEquals("For input string: \"9876543210L\"", expected.getMessage());
    }
  }

  @Test
  public void testJavaEnumFlags() {
    Flags flags = new Flags("ApplicationName");
    Flag<Disney> enumFlag = flags.create(
            "disney",
            Disney.MICKEY,
            "",
            Flaggable.ofJavaEnum(Disney.class)
    );
    enumFlag.parse();
    assertEquals(Disney.MICKEY, enumFlag.apply());
    // should parse Strings with matching cases without errors
    enumFlag.parse("MICKEY");
    // should parse Strings without matching cases without errors
    enumFlag.parse("minnie");
    // should thrown IllegalArgumentException when property doesn't exist in the Enum
    try{
      enumFlag.parse("MICKY");
    } catch (IllegalArgumentException e) {
      assertEquals(
              "The property MICKY does not belong to Java Enum com.twitter.app.JavaFlagTest$Disney, " +
                      "the constants defined in the class are: MICKEY,MINNIE.",
              e.getMessage()
      );
    }
  }

  @Test
  public void testLet() {
    Flags flags = new Flags("ApplicationName");
    Flag<Long> flag = flags.create("long", 1234567890L, "", Flaggable.ofJavaLong());
    assertEquals("ok", flag.let(5L, func0(() -> "ok")));
  }

}


text:
Partners is a convenient command line tool for switching between different git
users, and combining them when multiple people are working together. It is a
similar alternative to gitswitch.

## Why?

Because switching between different user settings on shared workstations,
especially when pair programming can happen quite frequently, and the existing
tools don't address the problem very nicely.

We've used gitswitch for a long time, but it has a lot of problems:

- Requires cartesian join of all people who are meant to be pair-programming
- Defaults to repository-local switch, which is usually not what you want
- Slow to start, slow to execute
- Dependent on Ruby toolchain, since we primarily work in Ruby and switch Ruby
  version and gemset frequently, this is especially annoying.

All other alternatives we could find seem to be incomplete or unmaintained.

## Installation

First, install Rust and Cargo. You can use [rustup](https://www.rust-lang.org/install.html),
or on OS X you can simply install them via Homebrew like this:

``` sh
$ brew install rust
```

Now install Partners via Cargo:

``` sh
$ cargo install partners
```

It might prompt you to add Cargo's install directory to your path.

Now run partners' interactive setup:

``` sh
$ partners setup
```

This will prompt you to create the configuration file if it doesn't exist.

## Usage

Partners maintains a list of authors it knows about, you can inspect this list by running:

``` sh
$ partners list
```

You can add a new author by running:

``` sh
$ partners add
```

This will prompt you for their nickname, name and email address. You can use
the nickname to quickly change your git author information like this:

``` sh
$ partners set jonas
jonas:
  Name:  Jonas Nicklas
  Email: jonas.nicklas@gmail.com
```

Where `jonas` is the nickname. You can also use multiple nicknames:

``` sh
$ partners set jonas kim
jonas+kim:
  Name:  Jonas Nicklas, Kim Burgestrand
  Email: dev+jonas+kim@elabs.se
```

In the case of multiple authors, partners constructs the email address based
on the authors' nicknames, and the domain, prefix and separator configuration
parameters specified during setup. You can change these any time by running:

``` sh
partners setup
```


text:
package e2e

import (
	"bytes"
	"fmt"
	"os"
	"path/filepath"
	"strings"
	"testing"
	"time"

	"github.com/google/go-cmp/cmp"
	"github.com/minio/minio-go/v6"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"helm.sh/helm/v3/pkg/repo"
)

const (
	defaultChartsContentType = "application/gzip"
)

func TestPush(t *testing.T) {
	t.Log("Test basic push action")

	const (
		repoName        = "test-push"
		repoDir         = "charts"
		chartName       = "foo"
		chartVersion    = "1.2.3"
		chartFilename   = "foo-1.2.3.tgz"
		chartFilepath   = "testdata/" + chartFilename
		chartObjectName = repoDir + "/" + chartFilename
	)

	setupRepo(t, repoName, repoDir)
	defer teardownRepo(t, repoName)

	cmd, stdout, stderr := command(fmt.Sprintf("helm s3 push %s %s", chartFilepath, repoName))
	err := cmd.Run()
	assert.NoError(t, err)
	assertEmptyOutput(t, nil, stderr)
	assert.Contains(t, stdout.String(), "Successfully uploaded the chart to the repository.")

	// Check that chart was actually pushed.

	obj, err := mc.StatObject(repoName, chartObjectName, minio.StatObjectOptions{})
	assert.NoError(t, err)
	assert.Equal(t, chartObjectName, obj.Key)

	// Check that chart has proper content type.

	assert.Equal(t, defaultChartsContentType, obj.ContentType)

	// Check that pushed chart can be searched.

	cmd, stdout, stderr = command(makeSearchCommand(repoName, chartName))
	err = cmd.Run()
	assert.NoError(t, err)
	assertEmptyOutput(t, nil, stderr)

	expected := `test-push/foo	1.2.3        	1.2.3      	A Helm chart for Kubernetes`
	assert.Contains(t, stdout.String(), expected)

	// Check that pushed chart can be fetched.

	tmpdir, err := os.MkdirTemp("", t.Name())
	require.NoError(t, err)
	defer os.RemoveAll(tmpdir)

	cmd, stdout, stderr = command(fmt.Sprintf("helm fetch %s/%s --version %s --destination %s", repoName, chartName, chartVersion, tmpdir))
	err = cmd.Run()
	assert.NoError(t, err)
	assertEmptyOutput(t, stdout, stderr)
	assert.FileExists(t, filepath.Join(tmpdir, chartFilename))

	// Check that pushing the same chart again fails.

	cmd, stdout, stderr = command(fmt.Sprintf("helm s3 push %s %s", chartFilepath, repoName))
	err = cmd.Run()
	assert.Error(t, err)
	assertEmptyOutput(t, stdout, nil)

	expected = "The chart already exists in the repository and cannot be overwritten without an explicit intent."
	assert.Contains(t, stderr.String(), expected)
}

func TestPushContentType(t *testing.T) {
	t.Log("Test push action with --content-type flag")

	const (
		repoName        = "test-push-content-type"
		repoDir         = "charts"
		chartFilename   = "foo-1.2.3.tgz"
		chartFilepath   = "testdata/" + chartFilename
		chartObjectName = repoDir + "/" + chartFilename

		contentType = defaultChartsContentType + "-test"
	)

	setupRepo(t, repoName, repoDir)
	defer teardownRepo(t, repoName)

	cmd, stdout, stderr := command(fmt.Sprintf("helm s3 push --content-type=%s %s %s", contentType, chartFilepath, repoName))
	err := cmd.Run()
	assert.NoError(t, err)
	assertEmptyOutput(t, nil, stderr)
	assert.Contains(t, stdout.String(), "Successfully uploaded the chart to the repository.")

	// Check that chart was actually pushed.

	obj, err := mc.StatObject(repoName, chartObjectName, minio.StatObjectOptions{})
	assert.NoError(t, err)
	assert.Equal(t, chartObjectName, obj.Key)

	// Check that chart has proper content type.

	assert.Equal(t, contentType, obj.ContentType)
}

func TestPushDryRun(t *testing.T) {
	t.Log("Test push action with --dry-run flag")

	const (
		repoName        = "test-push-dry-run"
		repoDir         = "charts"
		chartFilename   = "foo-1.2.3.tgz"
		chartFilepath   = "testdata/" + chartFilename
		chartObjectName = repoDir + "/" + chartFilename
	)

	setupRepo(t, repoName, repoDir)
	defer teardownRepo(t, repoName)

	cmd, stdout, stderr := command(fmt.Sprintf("helm s3 push %s %s --dry-run", chartFilepath, repoName))
	err := cmd.Run()
	assert.NoError(t, err)
	assertEmptyOutput(t, nil, stderr)
	assert.Contains(t, stdout.String(), "Successfully uploaded the chart to the repository.")

	// Check that actually nothing got pushed.

	_, err = mc.StatObject(repoName, chartObjectName, minio.StatObjectOptions{})
	assert.Equal(t, "NoSuchKey", minio.ToErrorResponse(err).Code)
}

func TestPushForce(t *testing.T) {
	t.Log("Test push action with --force flag")

	const (
		repoName        = "test-push-force"
		repoDir         = "charts"
		chartFilename   = "foo-1.2.3.tgz"
		chartFilepath   = "testdata/" + chartFilename
		chartObjectName = repoDir + "/" + chartFilename
	)

	setupRepo(t, repoName, repoDir)
	defer teardownRepo(t, repoName)

	cmd, stdout, stderr := command(fmt.Sprintf("helm s3 push %s %s", chartFilepath, repoName))
	err := cmd.Run()
	assert.NoError(t, err)
	assertEmptyOutput(t, nil, stderr)
	assert.Contains(t, stdout.String(), "Successfully uploaded the chart to the repository.")

	// Check that chart was actually pushed and remember last modification time.

	obj, err := mc.StatObject(repoName, chartObjectName, minio.StatObjectOptions{})
	assert.NoError(t, err)
	assert.Equal(t, chartObjectName, obj.Key)

	lastModified := obj.LastModified

	// Push chart again with --force.

	time.Sleep(time.Second)

	cmd, stdout, stderr = command(fmt.Sprintf("helm s3 push %s %s --force", chartFilepath, repoName))
	err = cmd.Run()
	assert.NoError(t, err)
	assertEmptyOutput(t, nil, stderr)
	assert.Contains(t, stdout.String(), "Successfully uploaded the chart to the repository.")

	// Check that chart was overwritten.

	obj, err = mc.StatObject(repoName, chartObjectName, minio.StatObjectOptions{})
	assert.NoError(t, err)
	assert.True(t, obj.LastModified.After(lastModified), "Expected %s less than %s", lastModified.String(), obj.LastModified.String())
}

func TestPushIgnoreIfExists(t *testing.T) {
	t.Log("Test push action with --ignore-if-exists flag")

	const (
		repoName        = "test-push-ignore-if-exists"
		repoDir         = "charts"
		chartFilename   = "foo-1.2.3.tgz"
		chartFilepath   = "testdata/" + chartFilename
		chartObjectName = repoDir + "/" + chartFilename
	)

	setupRepo(t, repoName, repoDir)
	defer teardownRepo(t, repoName)

	cmd, stdout, stderr := command(fmt.Sprintf("helm s3 push %s %s", chartFilepath, repoName))
	err := cmd.Run()
	assert.NoError(t, err)
	assertEmptyOutput(t, nil, stderr)
	assert.Contains(t, stdout.String(), "Successfully uploaded the chart to the repository.")

	// Check that chart was actually pushed and remember last modification time.

	obj, err := mc.StatObject(repoName, chartObjectName, minio.StatObjectOptions{})
	assert.NoError(t, err)
	assert.Equal(t, chartObjectName, obj.Key)

	lastModified := obj.LastModified

	// Push chart again with --ignore-if-exists.

	cmd, stdout, stderr = command(fmt.Sprintf("helm s3 push %s %s --ignore-if-exists", chartFilepath, repoName))
	err = cmd.Run()
	assert.NoError(t, err)
	assertEmptyOutput(t, nil, stderr)
	assert.Contains(t, stdout.String(), "The chart already exists in the repository, keep existing chart and ignore push.")

	// Check that chart was not overwritten.

	obj, err = mc.StatObject(repoName, chartObjectName, minio.StatObjectOptions{})
	assert.NoError(t, err)
	assert.Equal(t, lastModified, obj.LastModified)
}

func TestPushForceAndIgnoreIfExists(t *testing.T) {
	t.Log("Test push action with both --force and --ignore-if-exists flags")

	const (
		repoName      = "test-push-force-and-ignore-if-exists"
		repoDir       = "charts"
		chartFilename = "foo-1.2.3.tgz"
		chartFilepath = "testdata/" + chartFilename
	)

	setupRepo(t, repoName, repoDir)
	defer teardownRepo(t, repoName)

	cmd, stdout, stderr := command(fmt.Sprintf("helm s3 push %s %s --force --ignore-if-exists", chartFilepath, repoName))
	err := cmd.Run()
	assert.Error(t, err)
	assertEmptyOutput(t, stdout, nil)

	expectedErrorMessage := "The --force and --ignore-if-exists flags are mutually exclusive and cannot be specified together."
	if !strings.HasPrefix(stderr.String(), expectedErrorMessage) {
		t.Errorf("Expected stderr to begin with %q, but got %q", expectedErrorMessage, stderr.String())
	}
}

func TestPushRelative(t *testing.T) {
	t.Log("Test push action with --relative flag")

	const (
		repoName      = "test-push-relative"
		repoDir       = "charts"
		chartName     = "foo"
		chartVersion  = "1.2.3"
		chartFilename = "foo-1.2.3.tgz"
		chartFilepath = "testdata/" + chartFilename
	)

	setupRepo(t, repoName, repoDir)
	defer teardownRepo(t, repoName)

	cmd, stdout, stderr := command(fmt.Sprintf("helm s3 push --relative %s %s", chartFilepath, repoName))
	err := cmd.Run()
	assert.NoError(t, err)
	assertEmptyOutput(t, nil, stderr)
	assert.Contains(t, stdout.String(), "Successfully uploaded the chart to the repository.")

	// Fetch the repo index and check that chart uri is relative.

	tmpdir, err := os.MkdirTemp("", t.Name())
	require.NoError(t, err)
	defer os.RemoveAll(tmpdir)

	indexFile := filepath.Join(tmpdir, "index.yaml")

	err = mc.FGetObject(repoName, repoDir+"/index.yaml", indexFile, minio.GetObjectOptions{})
	require.NoError(t, err)

	idx, err := repo.LoadIndexFile(indexFile)
	require.NoError(t, err)

	cv, err := idx.Get(chartName, chartVersion)
	require.NoError(t, err)

	expected := []string{chartFilename}
	if diff := cmp.Diff(expected, cv.URLs); diff != "" {
		t.Errorf("mismatch (-want +got):\n%s", diff)
	}

	// Check that chart can be successfully fetched.

	cmd, stdout, stderr = command(fmt.Sprintf("helm fetch %s/%s --version %s --destination %s", repoName, chartName, chartVersion, tmpdir))
	err = cmd.Run()
	assert.NoError(t, err)
	assertEmptyOutput(t, stdout, stderr)
	assert.FileExists(t, filepath.Join(tmpdir, chartFilename))
}

func assertEmptyOutput(t *testing.T, stdout, stderr *bytes.Buffer) {
	t.Helper()

	if stdout != nil {
		assert.Empty(t, stdout.String(), "Expected stdout to be empty")
	}
	if stderr != nil {
		assert.Empty(t, stderr.String(), "Expected stderr to be empty")
	}
}


text:
This is a website login example using "headless browser" phantomJS.

Use it like this:

	phantomjs dyndns.js <username> <password>

## Rationale ##
Apart from getting my hands dirty with phantomJS, I'd like to have an automated way of login into my free dyndns account.

Why? Recently DynDNS introduced a new policy of requiring free users to log into web portal at least once a month (or have their
DNS bindings revoked). This should help keeping those pesky naggers away.

## License ##
MIT