text:
<?php

/**
 * @category   Payment Gateway
 * @package    Adyen_Payment
 * @author     Adyen
 * @property   Adyen B.V
 * @copyright  Copyright (c) 2014 Adyen BV (http://www.adyen.com)
 */
class Adyen_Payment_Block_Form_Sepa extends Mage_Payment_Block_Form {

    protected function _construct() {
        $paymentMethodIcon = $this->getSkinUrl('images'.DS.'adyen'.DS."img_trans.gif");
        $label = Mage::helper('adyen')->_getConfigData("title", "adyen_sepa");

        $mark = Mage::getConfig()->getBlockClassName('core/template');
        $mark = new $mark;
        $mark->setTemplate('adyen/payment/payment_method_label.phtml')
            ->setPaymentMethodIcon($paymentMethodIcon)
            ->setPaymentMethodLabel($label)
            ->setPaymentMethodClass("adyen_sepa");

        $this->setTemplate('adyen/form/sepa.phtml')
            ->setMethodTitle('')
            ->setMethodLabelAfterHtml($mark->toHtml());

        parent::_construct();
    }

    public function getCountries() {

        $sepaCountriesAllowed = array("AT", "BE", "BG", "CH", "CY","CZ","DE","DK","EE","ES","FI","FR",
                                      "GB","GF","GI","GP","GR","HR","HU","IE","IS","IT","LI","LT","LU",
                                      "LV","MC","MQ","MT","NL","NO","PL","PT","RE","RO","SE","SI","SK");

       $countryList = Mage::getResourceModel('directory/country_collection')
            ->loadData()
            ->toOptionArray(false);

        $sepaCountries = array();

        foreach($countryList as $key => $country) {

            $value = $country['value'];
            if(!in_array($value, $sepaCountriesAllowed)) {
                unset($countryList[$key]);
            }
        }
        return $countryList;
    }

    public function getShopperCountryId() {
        $country = "";
        if(Mage::app()->getStore()->isAdmin())
        {
            $quote = Mage::getSingleton('adminhtml/session_quote')->getQuote();
        } else {
            $quote = Mage::helper('checkout/cart')->getQuote();
        }

        if($quote) {
            $billingAddress = $quote->getBillingAddress();
            if($billingAddress) {
                $country = $billingAddress->getCountryId();
            }
        }
        return $country;
    }

}


text:
package org.openntf.xpt.core.utils;

import java.io.IOException;
import java.util.Date;

import org.openntf.xpt.core.json.JSONEmptyValueStrategy;

import com.ibm.commons.util.io.json.JsonException;
import com.ibm.domino.services.util.JsonWriter;

/**
 * JSON Support is a library of convenience function to write values as
 * property: value pair. The class is heavily used by the JSONBinder Framework
 *
 * @author Christian Guedemann
 *
 */
public class JSONSupport {
	/**
	 * Writes a String value for a given property
	 *
	 * @param writer
	 * @param jsonProperty
	 * @param value
	 * @param writeEmpty
	 * @throws IOException
	 * @throws JsonException
	 */
	public static void writeString(JsonWriter writer, String jsonProperty, String value, boolean writeEmpty) throws IOException, JsonException {
		writeString(writer, jsonProperty, value, writeEmpty ? JSONEmptyValueStrategy.NULL : JSONEmptyValueStrategy.NOPROPERTY);
	}

	/**
	 * Writes a Integer value for a given property
	 *
	 * @param writer
	 * @param jsonProperty
	 * @param nValue
	 * @param writeEmpty
	 * @throws IOException
	 * @throws JsonException
	 */
	public static void writeInt(JsonWriter writer, String jsonProperty, Integer nValue, boolean writeEmpty) throws IOException, JsonException {
		writeInt(writer, jsonProperty, nValue, writeEmpty ? JSONEmptyValueStrategy.NULL : JSONEmptyValueStrategy.NOPROPERTY);
	}

	/**
	 * Writes a Date value for a given property
	 *
	 * @param writer
	 * @param jsonProperty
	 * @param datCurrent
	 * @param writeEmpty
	 * @throws IOException
	 * @throws JsonException
	 */
	public static void writeDate(JsonWriter writer, String jsonProperty, Date datCurrent, boolean writeEmpty) throws IOException, JsonException {
		writeDate(writer, jsonProperty, datCurrent, writeEmpty ? JSONEmptyValueStrategy.NULL : JSONEmptyValueStrategy.NOPROPERTY);
	}

	/**
	 * Writes a Double value for a given property
	 *
	 * @param writer
	 * @param jsonProperty
	 * @param dblValue
	 * @param writeEmpty
	 * @throws IOException
	 * @throws JsonException
	 */
	public static void writeDouble(JsonWriter writer, String jsonProperty, Double dblValue, boolean writeEmpty) throws IOException, JsonException {
		writeDouble(writer, jsonProperty, dblValue, writeEmpty ? JSONEmptyValueStrategy.NULL : JSONEmptyValueStrategy.NOPROPERTY);
	}

	/**
	 * Writes a Boolean value for a given property
	 *
	 * @param writer
	 * @param jsonProperty
	 * @param blValue
	 * @param writeEmpty
	 * @throws IOException
	 * @throws JsonException
	 */
	public static void writeBoolean(JsonWriter writer, String jsonProperty, Boolean blValue, boolean writeEmpty) throws IOException, JsonException {
		writeBoolean(writer, jsonProperty, blValue, writeEmpty ? JSONEmptyValueStrategy.NULL : JSONEmptyValueStrategy.NOPROPERTY);
	}

	/**
	 * Writes a Boolean value for a given property
	 *
	 * @param writer
	 * @param strJSONProperty
	 * @param blValue
	 * @param strategy
	 * @throws IOException
	 * @throws JsonException
	 */
	public static void writeBoolean(JsonWriter writer, String strJSONProperty, Boolean blValue, JSONEmptyValueStrategy strategy) throws IOException, JsonException {
		if (blValue != null) {
			writer.startProperty(strJSONProperty);
			writer.outBooleanLiteral(blValue);
			writer.endProperty();

		} else {
			writeEmpty(writer, strJSONProperty, strategy);
		}

	}

	/**
	 * Writes a Date value for a given property
	 *
	 * @param writer
	 * @param strJSONProperty
	 * @param datValue
	 * @param strategy
	 * @throws IOException
	 * @throws JsonException
	 */
	public static void writeDate(JsonWriter writer, String strJSONProperty, Date datValue, JSONEmptyValueStrategy strategy) throws IOException, JsonException {
		if (datValue != null) {
			writer.startProperty(strJSONProperty);
			writer.outDateLiteral(datValue);
			writer.endProperty();

		} else {
			writeEmpty(writer, strJSONProperty, strategy);
		}

	}

	/**
	 * Writes a Double value for a given property
	 *
	 * @param writer
	 * @param strJSONProperty
	 * @param nValue
	 * @param strategy
	 * @throws IOException
	 * @throws JsonException
	 */
	public static void writeDouble(JsonWriter writer, String strJSONProperty, Double nValue, JSONEmptyValueStrategy strategy) throws IOException, JsonException {
		if (nValue != null) {
			writer.startProperty(strJSONProperty);
			writer.outNumberLiteral(nValue);
			writer.endProperty();

		} else {
			writeEmpty(writer, strJSONProperty, strategy);
		}

	}

	/**
	 * Writes a Integer value for a given property
	 *
	 * @param writer
	 * @param strJSONProperty
	 * @param nValue
	 * @param strategy
	 * @throws IOException
	 * @throws JsonException
	 */
	public static void writeInt(JsonWriter writer, String strJSONProperty, Integer nValue, JSONEmptyValueStrategy strategy) throws IOException, JsonException {
		if (nValue != null) {
			writer.startProperty(strJSONProperty);
			writer.outIntLiteral(nValue);
			writer.endProperty();

		} else {
			writeEmpty(writer, strJSONProperty, strategy);
		}

	}

	/**
	 * Writes a String value for a given property
	 *
	 * @param writer
	 * @param strJSONProperty
	 * @param strValue
	 * @param strategy
	 * @throws IOException
	 * @throws JsonException
	 */
	public static void writeString(JsonWriter writer, String strJSONProperty, String strValue, JSONEmptyValueStrategy strategy) throws IOException, JsonException {
		if (strValue != null) {
			writer.startProperty(strJSONProperty);
			writer.outStringLiteral(strValue);
			writer.endProperty();

		} else {
			writeEmpty(writer, strJSONProperty, strategy);
		}
	}

	/**
	 * Writes a Empty value for a given property
	 *
	 * @param writer
	 * @param jsonProperty
	 * @param strategy
	 * @throws IOException
	 * @throws JsonException
	 */
	private static void writeEmpty(JsonWriter writer, String jsonProperty, JSONEmptyValueStrategy strategy) throws IOException, JsonException {
		if (strategy != JSONEmptyValueStrategy.NOPROPERTY) {
			writer.startProperty(jsonProperty);
			strategy.writeJSONValue(writer);
			writer.endProperty();

		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
require 'forwardable'

module SSHKit

  module Formatter

    class Abstract

      extend Forwardable
      attr_reader :original_output
      def_delegators :@original_output, :read, :rewind

      def initialize(oio)
        @original_output = oio
      end

      def write(obj)
        raise "Abstract formatter should not be used directly, maybe you want SSHKit::Formatter::BlackHole"
      end
      alias :<< :write

    end

  end

end


text:
package com.liferay.knowledgebase.util.comparator;

import com.liferay.knowledgebase.model.KBArticle;
import com.liferay.portal.kernel.util.OrderByComparator;

/**
 * @author Peter Shin
 * @author Brian Wing Shun Chan
 */
public class KBArticleViewCountComparator extends OrderByComparator {

	public static final String ORDER_BY_ASC = "KBArticle.viewCount ASC";

	public static final String ORDER_BY_DESC = "KBArticle.viewCount DESC";

	public static final String[] ORDER_BY_FIELDS = {"viewCount"};

	public KBArticleViewCountComparator() {
		this(false);
	}

	public KBArticleViewCountComparator(boolean ascending) {
		_ascending = ascending;
	}

	@Override
	public int compare(Object obj1, Object obj2) {
		KBArticle kbArticle1 = (KBArticle)obj1;
		KBArticle kbArticle2 = (KBArticle)obj2;

		int value = 0;

		if (kbArticle1.getViewCount() < kbArticle2.getViewCount()) {
			value = -1;
		}
		else if (kbArticle1.getViewCount() > kbArticle2.getViewCount()) {
			value = 1;
		}

		if (_ascending) {
			return value;
		}
		else {
			return -value;
		}
	}

	@Override
	public String getOrderBy() {
		if (_ascending) {
			return ORDER_BY_ASC;
		}
		else {
			return ORDER_BY_DESC;
		}
	}

	@Override
	public String[] getOrderByFields() {
		return ORDER_BY_FIELDS;
	}

	@Override
	public boolean isAscending() {
		return _ascending;
	}

	private boolean _ascending;

}


text:
package ai.subut.kurjun.repo;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Objects;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.inject.Inject;
import com.google.inject.assistedinject.Assisted;

import ai.subut.kurjun.ar.CompressionType;
import ai.subut.kurjun.common.service.KurjunContext;
import ai.subut.kurjun.metadata.common.DefaultMetadata;
import ai.subut.kurjun.metadata.common.raw.RawMetadata;
import ai.subut.kurjun.metadata.factory.PackageMetadataStoreFactory;
import ai.subut.kurjun.model.index.ReleaseFile;
import ai.subut.kurjun.model.metadata.Metadata;
import ai.subut.kurjun.model.metadata.PackageMetadataStore;
import ai.subut.kurjun.model.metadata.SerializableMetadata;
import ai.subut.kurjun.model.storage.FileStore;
import ai.subut.kurjun.storage.factory.FileStoreFactory;

public class LocalRawRepository extends LocalRepositoryBase
{

    private static final Logger LOGGER = LoggerFactory.getLogger( LocalRawRepository.class );

    private final PackageMetadataStoreFactory metadataStoreFactory;

    private final FileStoreFactory fileStoreFactory;

    private final KurjunContext context;

    @Inject
    public LocalRawRepository( PackageMetadataStoreFactory metadataStoreFactory, FileStoreFactory fileStoreFactory,
                               @Assisted KurjunContext context )
    {
        this.metadataStoreFactory = metadataStoreFactory;
        this.fileStoreFactory = fileStoreFactory;
        this.context = context;
    }

    @Override
    public Metadata put( InputStream is, CompressionType compressionType ) throws IOException
    {
        throw new UnsupportedOperationException( "Use other put method" );
    }

    @Override
    public Metadata put( final InputStream is, final CompressionType compressionType, final String owner )
            throws IOException
    {
        Objects.requireNonNull( is, "InputStream cannot be null" );

        return null;
    }

    @Override
    public Metadata put( final File file, final CompressionType compressionType, final String owner ) throws IOException
    {
        DefaultMetadata metadata = new DefaultMetadata();
        metadata.setName( file.getName() );

        SerializableMetadata oldmeta = getPackageInfo( metadata );

        if ( oldmeta != null )
        {
            // delete old record having the same file name
            delete( oldmeta.getMd5Sum() );
        }

        String md5 = getFileStore().put( file );

        RawMetadata meta = new RawMetadata( md5, file.getName(), file.length(), owner );
        getMetadataStore().put( meta );

        return meta;
    }

    public Metadata put( final File file, String name, final String owner )
            throws IOException
    {
        DefaultMetadata metadata = new DefaultMetadata();

        metadata.setName( name );

        SerializableMetadata oldmeta = getPackageInfo( metadata );

        if ( oldmeta != null )
        {
            // delete old record having the same file name
            delete( oldmeta.getMd5Sum() );
        }

        String md5 = getFileStore().put( file );

        RawMetadata meta = new RawMetadata( md5, name, file.length(), owner );

        getMetadataStore().put( meta );

        return meta;
    }

    @Override
    protected Logger getLogger()
    {
        return LOGGER;
    }

    @Override
    protected PackageMetadataStore getMetadataStore()
    {
        return metadataStoreFactory.create( context );
    }

    @Override
    protected FileStore getFileStore()
    {
        return fileStoreFactory.create( context );
    }

    @Override
    public URL getUrl()
    {
        throw new UnsupportedOperationException( "TODO: Not supported yet." );
    }

    @Override
    public boolean isKurjun()
    {
        return true;
    }

    @Override
    public Set<ReleaseFile> getDistributions()
    {
        throw new UnsupportedOperationException( "Not supported for raw repositories" );
    }

    @Override
    public KurjunContext getContext()
    {
        return null;
    }
}


text:
/**
 * Pipeline step to generate babel configuration.
 */
import { ArrayHelper } from "unitejs-framework/dist/helpers/arrayHelper";
import { ObjectHelper } from "unitejs-framework/dist/helpers/objectHelper";
import { IFileSystem } from "unitejs-framework/dist/interfaces/IFileSystem";
import { ILogger } from "unitejs-framework/dist/interfaces/ILogger";
import { BabelConfiguration } from "../../configuration/models/babel/babelConfiguration";
import { UniteConfiguration } from "../../configuration/models/unite/uniteConfiguration";
import { EngineVariables } from "../../engine/engineVariables";
import { PipelineStepBase } from "../../engine/pipelineStepBase";

export class JavaScript extends PipelineStepBase {
    private static readonly FILENAME: string = ".babelrc";

    private _configuration: BabelConfiguration;

    public mainCondition(uniteConfiguration: UniteConfiguration, engineVariables: EngineVariables): boolean | undefined {
        return super.condition(uniteConfiguration.sourceLanguage, "JavaScript");
    }

    public async initialise(logger: ILogger,
                            fileSystem: IFileSystem,
                            uniteConfiguration: UniteConfiguration,
                            engineVariables: EngineVariables,
                            mainCondition: boolean): Promise<number> {
        if (mainCondition) {
            return super.fileReadJson<BabelConfiguration>(logger,
                                                          fileSystem,
                                                          engineVariables.wwwRootFolder,
                                                          JavaScript.FILENAME,
                                                          engineVariables.force,
                                                          async (obj) => {
                    this._configuration = obj;

                    ArrayHelper.addRemove(uniteConfiguration.sourceExtensions, "js", true);
                    this.configDefaults(engineVariables);

                    return 0;
                });
        } else {
            return 0;
        }
    }

    public async configure(logger: ILogger, fileSystem: IFileSystem, uniteConfiguration: UniteConfiguration, engineVariables: EngineVariables, mainCondition: boolean): Promise<number> {
        // Removing and old dependency always false
        engineVariables.toggleDevDependency(
            [
                "babel-preset-es2015",
                "babel-core",
                "babel-plugin-transform-class-properties",
                "babel-plugin-transform-decorators",
                "babel-plugin-transform-decorators-legacy",
                "babel-plugin-transform-react-jsx",
                "babel-preset-env",
                "babel-preset-react"
            ],
            false);

        // Remove old config for plugins
        const babelConfiguration = engineVariables.getConfiguration<BabelConfiguration>("Babel");
        if (babelConfiguration) {
            ArrayHelper.addRemove(babelConfiguration.presets, "env", false, (obj, item) => Array.isArray(item) && item.length > 0 && item[0] === obj[0]);
            ArrayHelper.addRemove(babelConfiguration.presets, "react", false, (obj, item) => Array.isArray(item) && item.length > 0 && item[0] === obj[0]);
            ArrayHelper.addRemove(babelConfiguration.plugins, "transform-react-jsx", false);
            ArrayHelper.addRemove(babelConfiguration.plugins, "transform-decorators-legacy", false);
            ArrayHelper.addRemove(babelConfiguration.plugins, "transform-class-properties", false);
        }

        // We always include babel as we might need to transpile client packages
        engineVariables.toggleDevDependency(["@babel/core", "@babel/preset-env"], true);

        return 0;
    }

    public async finalise(logger: ILogger, fileSystem: IFileSystem, uniteConfiguration: UniteConfiguration, engineVariables: EngineVariables, mainCondition: boolean): Promise<number> {
        return super.fileToggleJson(logger,
                                    fileSystem,
                                    engineVariables.wwwRootFolder,
                                    JavaScript.FILENAME,
                                    engineVariables.force,
                                    mainCondition,
                                    async () => this._configuration);

    }

    private configDefaults(engineVariables: EngineVariables): void {
        const defaultConfiguration = new BabelConfiguration();

        defaultConfiguration.presets = [];
        defaultConfiguration.plugins = [];
        defaultConfiguration.env = {};

        this._configuration = ObjectHelper.merge(defaultConfiguration, this._configuration);

        engineVariables.setConfiguration("Babel", this._configuration);
    }
}


text:
exports.Event = function() {
    var handlers = [];
    var evt = function() {
        var args = arguments;
        handlers.forEach(function(handler) { handler.func.apply(null, args); });
    };

    /**
     * Adds a new handler via
     *  a) evt.add(handlerFunc)
     *  b) evt.add(reference, handlerFunc)
     */
    evt.add = function() {
        if (arguments.length == 1) {
            handlers.push({
                ref: arguments[0],
                func: arguments[0]
            });
        } else {
            handlers.push({
                ref: arguments[0],
                func: arguments[1]
            });
        }
    };

    evt.remove = function(ref) {
        var notEqual = function(other) { return ref !== other.ref; };
        handlers = handlers.filter(notEqual);
    };

    evt.removeAll = function() {
        handlers = [];
    };

    return evt;
};


text:
package org.apache.hadoop.crypto.key.kms;

import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.crypto.key.KeyProvider;
import org.apache.hadoop.crypto.key.KeyProviderCryptoExtension.CryptoExtension;
import org.apache.hadoop.crypto.key.KeyProviderCryptoExtension.EncryptedKeyVersion;
import org.apache.hadoop.crypto.key.KeyProviderDelegationTokenExtension;
import org.apache.hadoop.security.Credentials;
import org.apache.hadoop.security.token.Token;
import org.apache.hadoop.util.Time;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.annotations.VisibleForTesting;

/**
 * A simple LoadBalancing KMSClientProvider that round-robins requests
 * across a provided array of KMSClientProviders. It also retries failed
 * requests on the next available provider in the load balancer group. It
 * only retries failed requests that result in an IOException, sending back
 * all other Exceptions to the caller without retry.
 */
public class LoadBalancingKMSClientProvider extends KeyProvider implements
    CryptoExtension,
    KeyProviderDelegationTokenExtension.DelegationTokenExtension {

  public static Logger LOG =
      LoggerFactory.getLogger(LoadBalancingKMSClientProvider.class);

  static interface ProviderCallable<T> {
    public T call(KMSClientProvider provider) throws IOException, Exception;
  }

  @SuppressWarnings("serial")
  static class WrapperException extends RuntimeException {
    public WrapperException(Throwable cause) {
      super(cause);
    }
  }

  private final KMSClientProvider[] providers;
  private final AtomicInteger currentIdx;

  public LoadBalancingKMSClientProvider(KMSClientProvider[] providers,
      Configuration conf) {
    this(shuffle(providers), Time.monotonicNow(), conf);
  }

  @VisibleForTesting
  LoadBalancingKMSClientProvider(KMSClientProvider[] providers, long seed,
      Configuration conf) {
    super(conf);
    this.providers = providers;
    this.currentIdx = new AtomicInteger((int)(seed % providers.length));
  }

  @VisibleForTesting
  KMSClientProvider[] getProviders() {
    return providers;
  }

  private <T> T doOp(ProviderCallable<T> op, int currPos)
      throws IOException {
    IOException ex = null;
    for (int i = 0; i < providers.length; i++) {
      KMSClientProvider provider = providers[(currPos + i) % providers.length];
      try {
        return op.call(provider);
      } catch (IOException ioe) {
        LOG.warn("KMS provider at [{}] threw an IOException [{}]!!",
            provider.getKMSUrl(), ioe.getMessage());
        ex = ioe;
      } catch (Exception e) {
        if (e instanceof RuntimeException) {
          throw (RuntimeException)e;
        } else {
          throw new WrapperException(e);
        }
      }
    }
    if (ex != null) {
      LOG.warn("Aborting since the Request has failed with all KMS"
          + " providers in the group. !!");
      throw ex;
    }
    throw new IOException("No providers configured !!");
  }

  private int nextIdx() {
    while (true) {
      int current = currentIdx.get();
      int next = (current + 1) % providers.length;
      if (currentIdx.compareAndSet(current, next)) {
        return current;
      }
    }
  }

  @Override
  public Token<?>[]
      addDelegationTokens(final String renewer, final Credentials credentials)
          throws IOException {
    return doOp(new ProviderCallable<Token<?>[]>() {
      @Override
      public Token<?>[] call(KMSClientProvider provider) throws IOException {
        return provider.addDelegationTokens(renewer, credentials);
      }
    }, nextIdx());
  }

  @Override
  public long renewDelegationToken(final Token<?> token) throws IOException {
    return doOp(new ProviderCallable<Long>() {
      @Override
      public Long call(KMSClientProvider provider) throws IOException {
        return provider.renewDelegationToken(token);
      }
    }, nextIdx());
  }

  @Override
  public Void cancelDelegationToken(final Token<?> token) throws IOException {
    return doOp(new ProviderCallable<Void>() {
      @Override
      public Void call(KMSClientProvider provider) throws IOException {
        provider.cancelDelegationToken(token);
        return null;
      }
    }, nextIdx());
  }

  // This request is sent to all providers in the load-balancing group
  @Override
  public void warmUpEncryptedKeys(String... keyNames) throws IOException {
    for (KMSClientProvider provider : providers) {
      try {
        provider.warmUpEncryptedKeys(keyNames);
      } catch (IOException ioe) {
        LOG.error(
            "Error warming up keys for provider with url"
            + "[" + provider.getKMSUrl() + "]");
      }
    }
  }

  // This request is sent to all providers in the load-balancing group
  @Override
  public void drain(String keyName) {
    for (KMSClientProvider provider : providers) {
      provider.drain(keyName);
    }
  }

  @Override
  public EncryptedKeyVersion
      generateEncryptedKey(final String encryptionKeyName)
          throws IOException, GeneralSecurityException {
    try {
      return doOp(new ProviderCallable<EncryptedKeyVersion>() {
        @Override
        public EncryptedKeyVersion call(KMSClientProvider provider)
            throws IOException, GeneralSecurityException {
          return provider.generateEncryptedKey(encryptionKeyName);
        }
      }, nextIdx());
    } catch (WrapperException we) {
      if (we.getCause() instanceof GeneralSecurityException) {
        throw (GeneralSecurityException) we.getCause();
      }
      throw new IOException(we.getCause());
    }
  }

  @Override
  public KeyVersion
      decryptEncryptedKey(final EncryptedKeyVersion encryptedKeyVersion)
          throws IOException, GeneralSecurityException {
    try {
      return doOp(new ProviderCallable<KeyVersion>() {
        @Override
        public KeyVersion call(KMSClientProvider provider)
            throws IOException, GeneralSecurityException {
          return provider.decryptEncryptedKey(encryptedKeyVersion);
        }
      }, nextIdx());
    } catch (WrapperException we) {
      if (we.getCause() instanceof GeneralSecurityException) {
        throw (GeneralSecurityException) we.getCause();
      }
      throw new IOException(we.getCause());
    }
  }

  @Override
  public KeyVersion getKeyVersion(final String versionName) throws IOException {
    return doOp(new ProviderCallable<KeyVersion>() {
      @Override
      public KeyVersion call(KMSClientProvider provider) throws IOException {
        return provider.getKeyVersion(versionName);
      }
    }, nextIdx());
  }

  @Override
  public List<String> getKeys() throws IOException {
    return doOp(new ProviderCallable<List<String>>() {
      @Override
      public List<String> call(KMSClientProvider provider) throws IOException {
        return provider.getKeys();
      }
    }, nextIdx());
  }

  @Override
  public Metadata[] getKeysMetadata(final String... names) throws IOException {
    return doOp(new ProviderCallable<Metadata[]>() {
      @Override
      public Metadata[] call(KMSClientProvider provider) throws IOException {
        return provider.getKeysMetadata(names);
      }
    }, nextIdx());
  }

  @Override
  public List<KeyVersion> getKeyVersions(final String name) throws IOException {
    return doOp(new ProviderCallable<List<KeyVersion>>() {
      @Override
      public List<KeyVersion> call(KMSClientProvider provider)
          throws IOException {
        return provider.getKeyVersions(name);
      }
    }, nextIdx());
  }

  @Override
  public KeyVersion getCurrentKey(final String name) throws IOException {
    return doOp(new ProviderCallable<KeyVersion>() {
      @Override
      public KeyVersion call(KMSClientProvider provider) throws IOException {
        return provider.getCurrentKey(name);
      }
    }, nextIdx());
  }
  @Override
  public Metadata getMetadata(final String name) throws IOException {
    return doOp(new ProviderCallable<Metadata>() {
      @Override
      public Metadata call(KMSClientProvider provider) throws IOException {
        return provider.getMetadata(name);
      }
    }, nextIdx());
  }

  @Override
  public KeyVersion createKey(final String name, final byte[] material,
      final Options options) throws IOException {
    return doOp(new ProviderCallable<KeyVersion>() {
      @Override
      public KeyVersion call(KMSClientProvider provider) throws IOException {
        return provider.createKey(name, material, options);
      }
    }, nextIdx());
  }

  @Override
  public KeyVersion createKey(final String name, final Options options)
      throws NoSuchAlgorithmException, IOException {
    try {
      return doOp(new ProviderCallable<KeyVersion>() {
        @Override
        public KeyVersion call(KMSClientProvider provider) throws IOException,
            NoSuchAlgorithmException {
          return provider.createKey(name, options);
        }
      }, nextIdx());
    } catch (WrapperException e) {
      if (e.getCause() instanceof GeneralSecurityException) {
        throw (NoSuchAlgorithmException) e.getCause();
      }
      throw new IOException(e.getCause());
    }
  }
  @Override
  public void deleteKey(final String name) throws IOException {
    doOp(new ProviderCallable<Void>() {
      @Override
      public Void call(KMSClientProvider provider) throws IOException {
        provider.deleteKey(name);
        return null;
      }
    }, nextIdx());
  }
  @Override
  public KeyVersion rollNewVersion(final String name, final byte[] material)
      throws IOException {
    return doOp(new ProviderCallable<KeyVersion>() {
      @Override
      public KeyVersion call(KMSClientProvider provider) throws IOException {
        return provider.rollNewVersion(name, material);
      }
    }, nextIdx());
  }

  @Override
  public KeyVersion rollNewVersion(final String name)
      throws NoSuchAlgorithmException, IOException {
    try {
      return doOp(new ProviderCallable<KeyVersion>() {
        @Override
        public KeyVersion call(KMSClientProvider provider) throws IOException,
        NoSuchAlgorithmException {
          return provider.rollNewVersion(name);
        }
      }, nextIdx());
    } catch (WrapperException e) {
      if (e.getCause() instanceof GeneralSecurityException) {
        throw (NoSuchAlgorithmException) e.getCause();
      }
      throw new IOException(e.getCause());
    }
  }

  // Close all providers in the LB group
  @Override
  public void close() throws IOException {
    for (KMSClientProvider provider : providers) {
      try {
        provider.close();
      } catch (IOException ioe) {
        LOG.error("Error closing provider with url"
            + "[" + provider.getKMSUrl() + "]");
      }
    }
  }

  @Override
  public void flush() throws IOException {
    for (KMSClientProvider provider : providers) {
      try {
        provider.flush();
      } catch (IOException ioe) {
        LOG.error("Error flushing provider with url"
            + "[" + provider.getKMSUrl() + "]");
      }
    }
  }

  private static KMSClientProvider[] shuffle(KMSClientProvider[] providers) {
    List<KMSClientProvider> list = Arrays.asList(providers);
    Collections.shuffle(list);
    return list.toArray(providers);
  }
}


text:
/** Ordres de tri possibles */
export enum SortOrder {
    /** Ascendant */
    ascending,
    /** Descendant */
    descending,
}


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">

    <meta content="MySQL主备模式配置" name="description">

    <meta name="keywords" content="linux,mysql,master,slave,主备">

  <meta name="author" content="Jack">

  <title>

        Jalpc|MySQL主备模式配置

  </title>

  <link rel="shortcut icon" href="/static/img/favicon.ico">

  <link href="/bower_components/normalize-css/normalize.min.css" rel="stylesheet">
  <link href="/bower_components/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">
  <link href="/bower_components/animate.css/animate.min.css" rel="stylesheet">
  <link href="/bower_components/components-font-awesome/css/font-awesome.min.css" rel="stylesheet">
  <link href="/static/font-mfizz/font-mfizz.css" rel="stylesheet">

  <link href="/bower_components/jquery.gritter/css/jquery.gritter.css" rel="stylesheet">
  <link rel="stylesheet" href="/search/css/cb-search.css">

  <link href="/static/css/style.min.css" rel="stylesheet">
  <link href="/static/css/pygments.css" rel="stylesheet">

    <input type="text" class="form-control search-content" id="search-content" style="position: fixed; top: 60px" placeholder="Search Blog">

                    <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
                        Toggle navigation

                    </button>
                    Jalpc

                            Blog

                            Python

                            Linux

                            HTML

                            Database

                            Mac

                            Life

        Previous

        Next

                        	<button class="btn btn-white btn-xs" type="button">Database</button>

                     3 Apr 2015

                            MySQL主备模式配置

背景:

主数据库IP:192.168.100.2

从数据库IP:192.168.100.3

一、修改主数据库的的配置文件:

[mysqld]

server-id=1
log-bin=mysqlmaster-bin.log
sync_binlog=1
#注意:下面这个参数需要修改为服务器内存的70%左右
innodb_buffer_pool_size = 512M
innodb_flush_log_at_trx_commit=1
sql_mode=STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION,NO_AUTO_VALUE_ON_ZERO
lower_case_table_names=1
log_bin_trust_function_creators=1

修改之后要重启mysql

二、修改从数据库的的配置文件(server-id配置为大于1的数字即可):

[mysqld]

server-id=2
log-bin=mysqlslave-bin.log
sync_binlog=1
#注意:下面这个参数需要修改为服务器内存的70%左右
innodb_buffer_pool_size = 512M
innodb_flush_log_at_trx_commit=1
sql_mode=STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION,NO_AUTO_VALUE_ON_ZERO
lower_case_table_names=1
log_bin_trust_function_creators=1

修改之后要重启mysql

三、SSH登录到主数据库:

(1)在主数据库上创建用于主从复制的账户(192.168.100.3换成你的从数据库IP):

GRANT REPLICATION SLAVE ON *.* TO 'repl'@'192.168.100.3' IDENTIFIED BY 'repl';

(2)主数据库锁表(禁止再插入数据以获取主数据库的的二进制日志坐标):

FLUSH TABLES WITH READ LOCK;

(3)然后克隆一个SSH会话窗口,在这个窗口打开MySQL命令行:

SHOW MASTER STATUS;
+——————---------------——+—------——-+——------——–+——————+——————-+
| File                  | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set |
+—————---------------———+——------—-+——------——–+——————+——————-+
| mysqlmaster-bin.000001 |   332   |           |      |       |
+—————---------------———+—------——-+—------———–+——————+——————-+

1 row in set (0.00 sec)
exit;

在这个例子中,二进制日志文件是mysqlmaster-bin.000001,位置是332,记录下这两个值,稍后要用到。

(4)在主数据库上使用mysqldump命令创建一个数据快照:

#mysqldump
-uroot -p -h127.0.0.1 -P3306 –all-databases –triggers –routines –events >all.sql

接下来会提示你输入mysql数据库的root密码,输入完成后,如果当前数据库不大,很快就能导出完成。

(5)解锁第(2)步主数据的锁表操作:

UNLOCK TABLES;

四、SSH登录到从数据库:

(1)通过FTP、SFTP或其他方式,将上一步备份的主数据库快照all.sql上传到从数据库某个路径,例如我放在了/home/yimiju/目录下;

(2)从导入主的快照:

#cd /home/yimiju
#mysql -uroot -p -h127.0.0.1 -P3306 < all.sql

接下来会提示你输入mysql数据库的root密码,输入完成后,如果当前数据库不大,很快就能导入完成。

(3)给从数据库设置复制的主数据库信息(注意修改MASTER_LOG_FILE和MASTER_LOG_POS的值):

#mysql -uroot -p

mysql>``` sql
CHANGE MASTER TO MASTER_HOST='192.168.100.2',MASTER_USER='repl',MASTER_PASSWORD='repl',MASTER_LOG_FILE='mysqlmaster-bin.000001',MASTER_LOG_POS=332;</p>
<div class="highlighter-rouge"><pre class="highlight"><code>
然后启动从数据库的复制线程:

mysql>``` sql
START slave;

接着查询数据库的slave状态:

mysql>``` sql
SHOW slave STATUS \G</p>
<div class="highlighter-rouge"><pre class="highlight"><code>
如果下面两个参数都是Yes,则说明主从配置成功!

</code></pre>
</div>
<p>Slave_IO_Running: Yes
Slave_SQL_Running: Yes
```

(4)接下来你可以在主数据库上创建数据库、表、插入数据,然后看从数据库是否同步了这些操作。

大功告成。

Tags:

                                    <button class="btn btn-white btn-xs" type="button">MySQL</button>

                                    <button class="btn btn-white btn-xs" type="button">主从</button>

Stats:

                                  0 comments

                                <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal2">
    Donate
</button>

                <button type="button" class="close" data-dismiss="modal">×Close</button>

Donate Me

                Thanks for your support!

                            Alipay

                            Wechat

                <button type="button" class="btn btn-white" data-dismiss="modal">Close</button>

Share:

Please enable JavaScript to view the comments powered by Disqus.


text:
'use strict';

class FreeList {
  constructor(name, max, ctor) {
    this.name = name;
    this.ctor = ctor;
    this.max = max;
    this.list = [];
  }

  alloc() {
    return this.list.length ? this.list.pop() :
                              this.ctor.apply(this, arguments);
  }

  free(obj) {
    if (this.list.length < this.max) {
      this.list.push(obj);
      return true;
    }
    return false;
  }
}

module.exports = FreeList;


text:
#pragma once

#include <QFrame>
#include "Code/Interface/QRDInterface.h"

namespace Ui
{
class GLPipelineStateViewer;
}

class QXmlStreamWriter;

class RDLabel;
class RDTreeWidget;
class RDTreeWidgetItem;
class PipelineStateViewer;

class GLPipelineStateViewer : public QFrame, public ICaptureViewer
{
  Q_OBJECT

public:
  explicit GLPipelineStateViewer(ICaptureContext &ctx, PipelineStateViewer &common,
                                 QWidget *parent = 0);
  ~GLPipelineStateViewer();

  // ICaptureViewer
  void OnCaptureLoaded() override;
  void OnCaptureClosed() override;
  void OnSelectedEventChanged(uint32_t eventId) override {}
  void OnEventChanged(uint32_t eventId) override;

private slots:
  // automatic slots
  void on_showDisabled_toggled(bool checked);
  void on_showEmpty_toggled(bool checked);
  void on_exportHTML_clicked();
  void on_meshView_clicked();
  void on_viAttrs_itemActivated(RDTreeWidgetItem *item, int column);
  void on_viBuffers_itemActivated(RDTreeWidgetItem *item, int column);
  void on_viAttrs_mouseMove(QMouseEvent *event);
  void on_viBuffers_mouseMove(QMouseEvent *event);
  void on_pipeFlow_stageSelected(int index);

  // manual slots
  void shaderView_clicked();
  void shaderEdit_clicked();
  void shaderSave_clicked();
  void resource_itemActivated(RDTreeWidgetItem *item, int column);
  void ubo_itemActivated(RDTreeWidgetItem *item, int column);
  void vertex_leave(QEvent *e);

private:
  Ui::GLPipelineStateViewer *ui;
  ICaptureContext &m_Ctx;
  PipelineStateViewer &m_Common;

  enum class GLReadWriteType
  {
    Atomic,
    SSBO,
    Image,
  };

  QString MakeGenericValueString(uint32_t compCount, CompType compType,
                                 const GLPipe::VertexAttribute &val);
  GLReadWriteType GetGLReadWriteType(ShaderResource res);

  void setShaderState(const GLPipe::Shader &stage, RDLabel *shader, RDTreeWidget *tex,
                      RDTreeWidget *samp, RDTreeWidget *ubo, RDTreeWidget *sub, RDTreeWidget *rw);
  void clearShaderState(RDLabel *shader, RDTreeWidget *tex, RDTreeWidget *samp, RDTreeWidget *ubo,
                        RDTreeWidget *sub, RDTreeWidget *rw);
  void setState();
  void clearState();

  void setInactiveRow(RDTreeWidgetItem *node);
  void setEmptyRow(RDTreeWidgetItem *node);
  void highlightIABind(int slot);

  QString formatMembers(int indent, const QString &nameprefix, const rdcarray<ShaderConstant> &vars);
  const GLPipe::Shader *stageForSender(QWidget *widget);

  bool showNode(bool usedSlot, bool filledSlot);

  void exportHTML(QXmlStreamWriter &xml, const GLPipe::VertexInput &vtx);
  void exportHTML(QXmlStreamWriter &xml, const GLPipe::Shader &sh);
  void exportHTML(QXmlStreamWriter &xml, const GLPipe::Feedback &xfb);
  void exportHTML(QXmlStreamWriter &xml, const GLPipe::Rasterizer &rs);
  void exportHTML(QXmlStreamWriter &xml, const GLPipe::FrameBuffer &fb);

  // keep track of the VB nodes (we want to be able to highlight them easily on hover)
  QList<RDTreeWidgetItem *> m_VBNodes;
};


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
J. Linn. Soc. , Bot. 11(no. 56): 501 (1871)

#### Original name
Agaricus phlyctaenodes Berk. & Broome, 1871

### Remarks
null


text:
A python script for automating downloads from data.kartverket.no

##Installation
1. clone repo
2. create a virtualenv
3. install requirements ```pip install -r requirements.txt```

##Usage
<pre>
Usage: skdata.py [OPTIONS] COMMAND [ARGS]...

Options:
  --help  Show this message and exit.

Commands:
  categories  List categories
  datasets    Show datasets in category
  download    Download all files in specified dataset
</pre>


text:
This package is required to get backwards compatibility with RxJS previous to version 6. It contains the imports to add operators to `Observable.prototype` and creation methods to `Observable`. This is what allows, for instance, dot-chaining:

```
Observable.interval(1)
  .map(i => i * i)
```

vs

```
Observable.interval(1)
  .pipe(map(i => i * i))
```


text:
/* eslint-disable no-unused-vars*/
import React from 'react';
/* eslint-enable no-unused-vars*/
import { Router, Route, IndexRoute } from 'react-router';
import createBrowserHistory from 'history/lib/createBrowserHistory';

import App from './App/';
import Home from './Home/';

const Routes = () => (
  <Router history={createBrowserHistory()}>
    <Route path="/" component={App}>
      <IndexRoute component={Home} />
    </Route>
  </Router>
);

export default Routes;


text:
namespace mongocxx {
MONGOCXX_INLINE_NAMESPACE_BEGIN
namespace result {
namespace gridfs {

upload::upload(bsoncxx::types::value id)
    : _id_owned(bsoncxx::builder::basic::make_array(id)), _id(_id_owned.view()[0].get_value()) {}

const bsoncxx::types::value& upload::id() const {
    return _id;
}

bool MONGOCXX_CALL operator==(const upload& lhs, const upload& rhs) {
    return lhs.id() == rhs.id();
}
bool MONGOCXX_CALL operator!=(const upload& lhs, const upload& rhs) {
    return !(lhs == rhs);
}

}  // namespace gridfs
}  // namespace result
MONGOCXX_INLINE_NAMESPACE_END
}  // namespace mongocxx


text:
package net.dirtyfilthy.bouncycastle.crypto.io;

import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;

import net.dirtyfilthy.bouncycastle.crypto.Mac;

public class MacInputStream
    extends FilterInputStream
{
    protected Mac mac;

    public MacInputStream(
        InputStream stream,
        Mac         mac)
    {
        super(stream);
        this.mac = mac;
    }

    public int read()
        throws IOException
    {
        int b = in.read();

        if (b >= 0)
        {
            mac.update((byte)b);
        }
        return b;
    }

    public int read(
        byte[] b,
        int off,
        int len)
        throws IOException
    {
        int n = in.read(b, off, len);
        if (n >= 0)
        {
            mac.update(b, off, n);
        }
        return n;
    }

    public Mac getMac()
    {
        return mac;
    }
}


text:
        <svg class="icon icon-heart">
          <use xlink:href="#icon-heart"></use>
        </svg>

Health Record

          <svg class="icon icon-plus" ng-hide="vm.misc.isSideMenuOpen">
            <use xlink:href="#icon-plus"></use>
          </svg>
          <svg class="icon icon-minus" ng-show="vm.misc.isSideMenuOpen">
            <use xlink:href="#icon-minus"></use>
          </svg>

{{ 'LOGOUT' | translate}}

          <svg class="icon icon-{{ item.iconName }}">
            <use xlink:href="{{ '#icon-' + item.iconName }}"></use>
          </svg>

{{ item.lbl | translate }}


text:
using namespace std;
using namespace charls;

extern template class JlsCodecFactory<EncoderStrategy>;
extern template class JlsCodecFactory<DecoderStrategy>;

// Default bin sizes for JPEG-LS statistical modeling. Can be overriden at compression time, however this is rarely done.
const int BASIC_T1 = 3;
const int BASIC_T2 = 7;
const int BASIC_T3 = 21;

namespace
{

// JFIF\0
uint8_t jfifID[] = { 'J', 'F', 'I', 'F', '\0' };

int32_t CLAMP(int32_t i, int32_t j, int32_t MAXVAL)
{
    if (i > MAXVAL || i < j)
        return j;

    return i;
}

ApiResult CheckParameterCoherent(const JlsParameters& params)
{
    if (params.bitsPerSample < 2 || params.bitsPerSample > 16)
        return ApiResult::ParameterValueNotSupported;

    if (params.interleaveMode < InterleaveMode::None || params.interleaveMode > InterleaveMode::Sample)
        return ApiResult::InvalidCompressedData;

    switch (params.components)
    {
        case 4: return params.interleaveMode == InterleaveMode::Sample ? ApiResult::ParameterValueNotSupported : ApiResult::OK;
        case 3: return ApiResult::OK;
        case 0: return ApiResult::InvalidJlsParameters;

        default: return params.interleaveMode != InterleaveMode::None ? ApiResult::ParameterValueNotSupported : ApiResult::OK;
    }
}

} // namespace

JpegLSPresetCodingParameters ComputeDefault(int32_t MAXVAL, int32_t NEAR)
{
    JpegLSPresetCodingParameters preset;

    const int32_t FACTOR = (std::min(MAXVAL, 4095) + 128) / 256;

    preset.Threshold1 = CLAMP(FACTOR * (BASIC_T1 - 2) + 2 + 3 * NEAR, NEAR + 1, MAXVAL);
    preset.Threshold2 = CLAMP(FACTOR * (BASIC_T2 - 3) + 3 + 5 * NEAR, preset.Threshold1, MAXVAL);
    preset.Threshold3 = CLAMP(FACTOR * (BASIC_T3 - 4) + 4 + 7 * NEAR, preset.Threshold2, MAXVAL);
    preset.MaximumSampleValue = MAXVAL;
    preset.ResetValue = BASIC_RESET;
    return preset;
}

void JpegImageDataSegment::Serialize(JpegStreamWriter& streamWriter)
{
    JlsParameters info = _params;
    info.components = _componentCount;
    auto codec = JlsCodecFactory<EncoderStrategy>().GetCodec(info, _params.custom);
    unique_ptr<ProcessLine> processLine(codec->CreateProcess(_rawStreamInfo));
    ByteStreamInfo compressedData = streamWriter.OutputStream();
    const size_t cbyteWritten = codec->EncodeScan(move(processLine), compressedData);
    streamWriter.Seek(cbyteWritten);
}

JpegStreamReader::JpegStreamReader(ByteStreamInfo byteStreamInfo) :
    _byteStream(byteStreamInfo),
    _params(),
    _rect()
{
}

void JpegStreamReader::Read(ByteStreamInfo rawPixels)
{
    ReadHeader();

    const auto result = CheckParameterCoherent(_params);
    if (result != ApiResult::OK)
        throw charls_error(result);

    if (_rect.Width <= 0)
    {
        _rect.Width = _params.width;
        _rect.Height = _params.height;
    }

    const int64_t bytesPerPlane = static_cast<int64_t>(_rect.Width) * _rect.Height * ((_params.bitsPerSample + 7)/8);

    if (rawPixels.rawData && static_cast<int64_t>(rawPixels.count) < bytesPerPlane * _params.components)
        throw charls_error(ApiResult::UncompressedBufferTooSmall);

    int componentIndex = 0;

    while (componentIndex < _params.components)
    {
        ReadStartOfScan(componentIndex == 0);

        unique_ptr<DecoderStrategy> qcodec = JlsCodecFactory<DecoderStrategy>().GetCodec(_params, _params.custom);
        unique_ptr<ProcessLine> processLine(qcodec->CreateProcess(rawPixels));
        qcodec->DecodeScan(move(processLine), _rect, _byteStream);
        SkipBytes(rawPixels, static_cast<size_t>(bytesPerPlane));

        if (_params.interleaveMode != InterleaveMode::None)
            return;

        componentIndex += 1;
    }
}

void JpegStreamReader::ReadNBytes(vector<char>& dst, int byteCount)
{
    for (int i = 0; i < byteCount; ++i)
    {
        dst.push_back(static_cast<char>(ReadByte()));
    }
}

void JpegStreamReader::ReadHeader()
{
    if (ReadNextMarker() != JpegMarkerCode::StartOfImage)
        throw charls_error(ApiResult::InvalidCompressedData);

    for (;;)
    {
        const JpegMarkerCode marker = ReadNextMarker();
        if (marker == JpegMarkerCode::StartOfScan)
            return;

        const int32_t cbyteMarker = ReadWord();
        const int bytesRead = ReadMarker(marker) + 2;

        const int paddingToRead = cbyteMarker - bytesRead;
        if (paddingToRead < 0)
            throw charls_error(ApiResult::InvalidCompressedData);

        for (int i = 0; i < paddingToRead; ++i)
        {
            ReadByte();
        }
    }
}

JpegMarkerCode JpegStreamReader::ReadNextMarker()
{
    auto byte = ReadByte();
    if (byte != 0xFF)
    {
        ostringstream message;
        message << setfill('0');
        message << "Expected JPEG Marker start byte 0xFF but the byte value was 0x" << hex << uppercase << setw(2) << static_cast<unsigned int>(byte);
        throw charls_error(ApiResult::MissingJpegMarkerStart, message.str());
    }

    // Read all preceding 0xFF fill values until a non 0xFF value has been found. (see T.81, B.1.1.2)
    do
    {
        byte = ReadByte();
    } while (byte == 0xFF);

    return static_cast<JpegMarkerCode>(byte);
}

int JpegStreamReader::ReadMarker(JpegMarkerCode marker)
{
    // ISO/IEC 14495-1, ITU-T Recommendation T.87, C.1.1. defines the following markers valid for a JPEG-LS byte stream:
    // SOF55, LSE, SOI, EOI, SOS, DNL, DRI, RSTm, APPn, COM.
    // All other markers shall not be present.
    switch (marker)
    {
        case JpegMarkerCode::StartOfFrameJpegLS:
            return ReadStartOfFrame();

        case JpegMarkerCode::Comment:
            return ReadComment();

        case JpegMarkerCode::JpegLSPresetParameters:
            return ReadPresetParameters();

        case JpegMarkerCode::ApplicationData0:
            return 0;

        case JpegMarkerCode::ApplicationData7:
            return ReadColorSpace();

        case JpegMarkerCode::ApplicationData8:
            return ReadColorXForm();

        case JpegMarkerCode::StartOfFrameBaselineJpeg:
        case JpegMarkerCode::StartOfFrameExtendedSequential:
        case JpegMarkerCode::StartOfFrameProgressive:
        case JpegMarkerCode::StartOfFrameLossless:
        case JpegMarkerCode::StartOfFrameDifferentialSequential:
        case JpegMarkerCode::StartOfFrameDifferentialProgressive:
        case JpegMarkerCode::StartOfFrameDifferentialLossless:
        case JpegMarkerCode::StartOfFrameExtendedArithemtic:
        case JpegMarkerCode::StartOfFrameProgressiveArithemtic:
        case JpegMarkerCode::StartOfFrameLosslessArithemtic:
            {
                ostringstream message;
                message << "JPEG encoding with marker " << static_cast<unsigned int>(marker) << " is not supported.";
                throw charls_error(ApiResult::UnsupportedEncoding, message.str());
            }

        // Other tags not supported (among which DNL DRI)
        default:
            {
                ostringstream message;
                message << "Unknown JPEG marker " << static_cast<unsigned int>(marker) << " encountered.";
                throw charls_error(ApiResult::UnknownJpegMarker, message.str());
            }
    }
}

int JpegStreamReader::ReadPresetParameters()
{
    const int type = ReadByte();

    switch (type)
    {
    case 1:
        {
            _params.custom.MaximumSampleValue = ReadWord();
            _params.custom.Threshold1 = ReadWord();
            _params.custom.Threshold2 = ReadWord();
            _params.custom.Threshold3 = ReadWord();
            _params.custom.ResetValue = ReadWord();
            return 11;
        }
    }

    return 1;
}

void JpegStreamReader::ReadStartOfScan(bool firstComponent)
{
    if (!firstComponent)
    {
        if (ReadByte() != 0xFF)
            throw charls_error(ApiResult::MissingJpegMarkerStart);
        if (static_cast<JpegMarkerCode>(ReadByte()) != JpegMarkerCode::StartOfScan)
            throw charls_error(ApiResult::InvalidCompressedData);// TODO: throw more specific error code.
    }
    int length = ReadByte();
    length = length * 256 + ReadByte(); // TODO: do something with 'length' or remove it.

    const int componentCount = ReadByte();
    if (componentCount != 1 && componentCount != _params.components)
        throw charls_error(ApiResult::ParameterValueNotSupported);

    for (int i = 0; i < componentCount; ++i)
    {
        ReadByte();
        ReadByte();
    }
    _params.allowedLossyError = ReadByte();
    _params.interleaveMode = static_cast<InterleaveMode>(ReadByte());
    if (!(_params.interleaveMode == InterleaveMode::None || _params.interleaveMode == InterleaveMode::Line || _params.interleaveMode == InterleaveMode::Sample))
        throw charls_error(ApiResult::InvalidCompressedData);// TODO: throw more specific error code.
    if (ReadByte() != 0)
        throw charls_error(ApiResult::InvalidCompressedData);// TODO: throw more specific error code.

    if(_params.stride == 0)
    {
        const int width = _rect.Width != 0 ? _rect.Width : _params.width;
        const int components = _params.interleaveMode == InterleaveMode::None ? 1 : _params.components;
        _params.stride = components * width * ((_params.bitsPerSample + 7) / 8);
    }
}

int JpegStreamReader::ReadComment() const
{
    return 0;
}

void JpegStreamReader::ReadJfif()
{
    for(int i = 0; i < static_cast<int>(sizeof(jfifID)); i++)
    {
        if(jfifID[i] != ReadByte())
            return;
    }
    _params.jfif.version   = ReadWord();

    // DPI or DPcm
    _params.jfif.units = ReadByte();
    _params.jfif.Xdensity = ReadWord();
    _params.jfif.Ydensity = ReadWord();

    // thumbnail
    _params.jfif.Xthumbnail = ReadByte();
    _params.jfif.Ythumbnail = ReadByte();
    if(_params.jfif.Xthumbnail > 0 && _params.jfif.thumbnail)
    {
        vector<char> tempbuff(static_cast<char*>(_params.jfif.thumbnail),
            static_cast<char*>(_params.jfif.thumbnail)+3*_params.jfif.Xthumbnail*_params.jfif.Ythumbnail);
        ReadNBytes(tempbuff, 3*_params.jfif.Xthumbnail*_params.jfif.Ythumbnail);
    }
}

int JpegStreamReader::ReadStartOfFrame()
{
    _params.bitsPerSample = ReadByte();
    _params.height = ReadWord();
    _params.width = ReadWord();
    _params.components= ReadByte();
    return 6;
}

uint8_t JpegStreamReader::ReadByte()
{
    if (_byteStream.rawStream)
        return static_cast<uint8_t>(_byteStream.rawStream->sbumpc());

    if (_byteStream.count == 0)
        throw charls_error(ApiResult::CompressedBufferTooSmall);

    const uint8_t value = _byteStream.rawData[0];
    SkipBytes(_byteStream, 1);
    return value;
}

int JpegStreamReader::ReadWord()
{
    const int i = ReadByte() * 256;
    return i + ReadByte();
}

int JpegStreamReader::ReadColorSpace() const
{
    return 0;
}

int JpegStreamReader::ReadColorXForm()
{
    vector<char> sourceTag;
    ReadNBytes(sourceTag, 4);

    if (strncmp(sourceTag.data(), "mrfx", 4) != 0)
        return 4;

    const auto xform = ReadByte();
    switch (xform)
    {
        case static_cast<uint8_t>(ColorTransformation::None):
        case static_cast<uint8_t>(ColorTransformation::HP1):
        case static_cast<uint8_t>(ColorTransformation::HP2):
        case static_cast<uint8_t>(ColorTransformation::HP3):
            _params.colorTransformation = static_cast<ColorTransformation>(xform);
            return 5;

        case 4: // RgbAsYuvLossy (The standard lossy RGB to YCbCr transform used in JPEG.)
        case 5: // Matrix (transformation is controlled using a matrix that is also stored in the segment.
            throw charls_error(ApiResult::ImageTypeNotSupported);
        default:
            throw charls_error(ApiResult::InvalidCompressedData);
    }
}


text:
namespace Serviceable.Objects.Composition.Graph.Commands.NodeInstance.ExecutionData
{
    using System;
    using System.Collections.Generic;

    public class ExecutionCommandResult
    {
        public SingleContextExecutionResultWithInfo SingleContextExecutionResultWithInfo { get; set; }
        public List<IEvent> PublishedEvents { get; set; } = new List<IEvent>();
        public bool IsFaulted { get; set; }
        public bool IsIdle { get; set; }
        public bool IsPaused { get; set; }
        public Exception Exception { get; set; }
    }
}


text:
using System;
using System.Text;

public class SMSTyping
{
    public static void Main()
    {
        int charactersNumber = int.Parse(Console.ReadLine());
        StringBuilder sms = new StringBuilder();

        for (int i = 0; i < charactersNumber; i++)
        {
            string input = Console.ReadLine();

            if (input.Equals("0"))
            {
                sms.Append(" ");
                continue;
            }

            int digitsNumber = input.Length;
            int mainDigit = int.Parse(input[0].ToString());
            int offset = !(mainDigit == 8 || mainDigit == 9) ? (mainDigit - 2) * 3 : ((mainDigit - 2) * 3) + 1;
            int letterIndex = offset + digitsNumber - 1;
            char currentLetter = (char)(letterIndex + 97);
            sms.Append(currentLetter);
        }

        Console.WriteLine(sms.ToString());
    }
}


text:
import ConfigParser
import logging
import numpy
import threading
import time

import Adafruit_PCA9685
import atexit
from flask import Flask
from sqlalchemy import create_engine, case
from sqlalchemy.orm import sessionmaker
from sqlalchemy.sql import func

from models import Base, Map, MapCell, Scan, ScanResult
from scanner import Scanner
from trackcontroller import TrackController
from util import bresenham, pol2cart

# Configuration
MY_NAME = 0x0061

GPIO_PIN_WHEEL_ENCODER_INT = 4

I2C_ADDR_FORWARD_DISTANCE = 0x29
I2C_ADDR_PWM_CONTROLLER = 0x4F
I2C_ADDR_WHEEL_CONTROLLER = 0x6F
I2C_ADDR_WHEEL_ENCODERS = 0x27

PWM_FORWARD_SCANNER = 3

# Calibration
FORWARD_SCANNER_DEGREES_MIN = 6
FORWARD_SCANNER_DEGREES_MAX = 174
FORWARD_SCANNER_PULSE_MIN = 150
FORWARD_SCANNER_PULSE_MAX = 599

# Initialization
# logging.basicConfig(level=logging.INFO, format='%(levelname)8s (%(threadName)-10s) %(message)s')
logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)8s (%(threadName)-10s) %(name)s: %(message)s')
log = logging.getLogger(__name__)

class RoverA:
    def __init__(self):
        log.info("Hello! Starting a-Rex")

        # Parse Config
        Config = ConfigParser.ConfigParser()
        Config.read("config.ini")

        # Init DB
        connection_string = Config.get('database', 'engine')
        engine = create_engine(connection_string, echo=False)

        Base.metadata.create_all(engine)
        self.DBSession = sessionmaker(bind=engine)

        self.pwm = Adafruit_PCA9685.PCA9685(I2C_ADDR_PWM_CONTROLLER)
        self.pwm.set_pwm_freq(60)

        # self.wheels = TrackController(GPIO_PIN_WHEEL_ENCODER_INT, mot_addr=I2C_ADDR_WHEEL_CONTROLLER,
        #                              enc_addr=I2C_ADDR_WHEEL_ENCODERS)

        self.scanner = Scanner(self.pwm, sensor_addr=I2C_ADDR_FORWARD_DISTANCE, pwm_servo_index=PWM_FORWARD_SCANNER,
                               servo_pulse_min=FORWARD_SCANNER_PULSE_MIN, servo_pulse_max=FORWARD_SCANNER_PULSE_MAX,
                               servo_degrees_min=FORWARD_SCANNER_DEGREES_MIN,
                               servo_degrees_max=FORWARD_SCANNER_DEGREES_MAX)

        # Globals
        self.position = (0, 0)
        self.rotation = 90  # polar degree 0 points towards 'east' cartesian (∞,0) rex starts pointed 'north' on map

        # Get Map
        try:
            default_map_name = Config.get('map', 'name')
        except ConfigParser.NoSectionError:
            default_map_name = 'default'

        session = self.DBSession()

        default_map = session.query(Map).filter(Map.name == default_map_name).one_or_none()
        if default_map is not None:
            self.map = default_map
        else:
            log.info('Creating new map [{0}]'.format(default_map_name))

            new_map = Map(name=default_map_name, scale=50)
            session.add(new_map)
            session.commit()
            self.map = new_map

        log.info('Using map {0}'.format(self.map))

        # Start API
        self.api_thread = threading.Thread(target=self.run_api)
        self.api_thread.start()

    def run(self):
        session = self.DBSession()
        val = self.do_scan()

        session.add(val)
        session.commit()

        hits, misses = self.make_map_cells(val)

        log.info("Updating Hits")
        session.bulk_save_objects(hits)
        session.commit()
        log.info(hits[0])

        log.info("Updating Misses")
        session.bulk_save_objects(misses)
        session.commit()
        log.info(misses[0])
        log.info("Done")

        exit()

    def do_scan(self, scan_count=1, rescan_tries=5):
        log.info("Starting Scan Quality[{0}]".format(scan_count))

        new_scan = Scan(x=self.position[0], y=self.position[1], rotation=self.rotation, quality=scan_count)
        raw_scan = self.scanner.do_scan(scan_count=scan_count, rescan_tries=rescan_tries)
        results = []

        for deg, measurement in enumerate(raw_scan):
            if measurement is not None:
                results.append(ScanResult(angle=deg, distance=measurement))

        new_scan.scan_results = results

        return new_scan

    def make_map_cells(self, scan):
        hits = []
        misses = []

        for result in scan.scan_results:
            if result.distance is not -1:
                point1 = self.position

                cart = pol2cart(result.distance / self.map.scale, numpy.radians(result.angle + (self.rotation - 90)))
                point2 = (cart[0] + self.position[0], cart[1] + self.position[1])

                line_points = bresenham(point1, point2)
                hit = line_points.path.pop()

                hits.append(hit)
                for line_point in line_points.path:
                    misses.append(line_point)

        misses_dup_len = len(misses)
        misses = set(misses)

        log.info("Found Misses: {0} ({1}) Hits: {2}".format(len(misses), misses_dup_len, len(hits)))

        hit_cells = []
        for hit in hits:
            hit_cell = MapCell(map=self.map, x=hit[0], y=hit[1], hit=True, scan=scan)
            hit_cells.append(hit_cell)

        miss_cells = []
        for miss in misses:
            miss_cell = MapCell(map=self.map, x=miss[0], y=miss[1], hit=False, scan=scan)
            miss_cells.append(miss_cell)

        return hit_cells, miss_cells

    def get_map_dimensions(self):
        session = self.DBSession()

        max_x = session.query(MapCell.x.label('x')).order_by(MapCell.x.desc()).first().x
        min_x = session.query(MapCell.x.label('x')).order_by(MapCell.x.asc()).first().x
        max_y = session.query(MapCell.y.label('y')).order_by(MapCell.y.desc()).first().y
        min_y = session.query(MapCell.y.label('y')).order_by(MapCell.y.asc()).first().y

        return (min_x, min_y), (max_x, max_y)

    def get_map(self):
        map_min, map_max = self.get_map_dimensions()

        session = self.DBSession()
        map_query = session.query(MapCell.x.label('x'),
                                  MapCell.y.label('y'),
                                  (func.sum(case({'TRUE': 1.0},
                                                 value=MapCell.hit,
                                                 else_=0.0)) / func.count(MapCell.hit)).label('p')). \
            group_by(MapCell.x, MapCell.y)

        w = map_max[0] - map_min[0]
        h = map_max[1] - map_min[1]

        map_grid = [[None for _ in range(h + 1)] for _ in range(w + 1)]

        for cell in map_query.all():
            map_grid[cell.x - map_min[0]][cell.y - map_min[1]] = cell.p

        return map_grid

    def make_text_map(self, map_grid):

        w = len(map_grid)
        h = len(map_grid[0])

        line = ''
        for y in range(h):
            for x in range(w):
                cell = map_grid[x][h - y - 1]
                if cell is None:
                    line += ' '
                elif cell == 1:
                    line += '*'
                else:
                    line += str(int(cell * 10))
            line += '\n'

        return line

    def run_api(self):
        app = Flask(__name__)

        @app.route("/map")
        def hello():
            map_grid = self.get_map()
            return self.make_text_map(map_grid)

        app.run(host='0.0.0.0')


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

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;

namespace Microsoft.WindowsAzure.Storage.Table.DataServices.Entities
{
    [Obsolete("Support for accessing Windows Azure Tables via WCF Data Services is now obsolete. It's recommended that you use the Microsoft.WindowsAzure.Storage.Table namespace for working with tables.")]
    public class ComplexEntity : TableServiceEntity
    {
        public ComplexEntity()
            : base()
        {
        }

        public ComplexEntity(string pk, string rk)
            : base(pk, rk)
        {
        }

        private DateTime dateTime = DateTime.Now;
        public DateTime DateTime
        {
            get { return dateTime; }
            set { dateTime = value; }
        }

        private Boolean boolObj = false;
        public Boolean Bool
        {
            get { return boolObj; }
            set { boolObj = value; }
        }

        private bool boolPrimitive = false;
        public bool BoolPrimitive
        {
            get { return boolPrimitive; }
            set { boolPrimitive = value; }
        }

        private Byte[] binary = new Byte[] { 1, 2, 3, 4 };
        public Byte[] Binary
        {
            get { return binary; }
            set { binary = value; }
        }

        private byte[] binaryPrimitive = new byte[] { 1, 2, 3, 4 };
        public byte[] BinaryPrimitive
        {
            get { return binaryPrimitive; }
            set { binaryPrimitive = value; }
        }

        private double doublePrimitive = (double)1234.1234;
        public double DoublePrimitive
        {
            get { return doublePrimitive; }
            set { doublePrimitive = value; }
        }

        private Double doubleOBj = (Double)1234.1234;
        public Double Double
        {
            get { return doubleOBj; }
            set { doubleOBj = value; }
        }

        private Guid guid = Guid.NewGuid();
        public Guid Guid
        {
            get { return guid; }
            set { guid = value; }
        }

        private int integerPrimitive = 1234;
        public int IntegerPrimitive
        {
            get { return integerPrimitive; }
            set { integerPrimitive = value; }
        }

        private Int32 int32 = 1234;
        public Int32 Int32
        {
            get { return int32; }
            set { int32 = value; }
        }

        private long longPrimitive = 123456789012;
        public long LongPrimitive
        {
            get { return longPrimitive; }
            set { longPrimitive = value; }
        }

        private Int64 int64 = 123456789012;
        public Int64 Int64
        {
            get { return int64; }
            set { int64 = value; }
        }

        private string stringObj = "test";
        public string String
        {
            get { return stringObj; }
            set { stringObj = value; }
        }

        public static void AssertEquality(ComplexEntity a, ComplexEntity b)
        {
            Assert.AreEqual(a.String, b.String);
            Assert.AreEqual(a.Int64, b.Int64);
            Assert.AreEqual(a.LongPrimitive, b.LongPrimitive);
            Assert.AreEqual(a.Int32, b.Int32);
            Assert.AreEqual(a.IntegerPrimitive, b.IntegerPrimitive);
            Assert.AreEqual(a.Guid, b.Guid);
            Assert.AreEqual(a.Double, b.Double);
            Assert.AreEqual(a.DoublePrimitive, b.DoublePrimitive);
            Assert.AreEqual(a.BinaryPrimitive, b.BinaryPrimitive);
            Assert.AreEqual(a.Binary, b.Binary);
            Assert.AreEqual(a.BoolPrimitive, b.BoolPrimitive);
            Assert.AreEqual(a.Bool, b.Bool);
            Assert.AreEqual(a.DateTime, b.DateTime);

            Assert.AreEqual(a.PartitionKey, b.PartitionKey);
            Assert.AreEqual(a.RowKey, b.RowKey);
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <dimen name="smallest_object_size">16dp</dimen>
</resources>


text:
/* You can add global styles to this file, and also import other style files */
@import "~@angular/material/prebuilt-themes/deeppurple-amber.css";

* {
  box-sizing: border-box;
}

html {
  -webkit-font-smoothing: antialiased;
  -ms-overflow-style: none;
  overflow: auto;
}


text:
<?php

namespace Elastica\Test\Filter;

use Elastica\Filter\Query;
use Elastica\Query\QueryString;
use Elastica\Test\Base as BaseTest;

class QueryTest extends BaseTest
{
    public function testSimple()
    {
        $query = new QueryString('foo bar');
        $filter = new Query($query);

        $expected = array(
            'query' => array(
                'query_string' => array(
                    'query' => 'foo bar',
                ),
            ),
        );

        $this->assertEquals($expected, $filter->toArray());
    }

    public function testExtended()
    {
        $query = new QueryString('foo bar');
        $filter = new Query($query);
        $filter->setCached(true);

        $expected = array(
            'fquery' => array(
                'query' => array(
                    'query_string' => array(
                        'query' => 'foo bar',
                    ),
                ),
                '_cache' => true,
            ),
        );

        $this->assertEquals($expected, $filter->toArray());
    }
}