text:
/**
 *     This code was auto-generated by a Codezu.
 *
 *     Changes to this file may cause incorrect behavior and will be lost if
 *     the code is regenerated.
 */
package com.mozu.api.clients.commerce.carts;

import java.util.List;
import java.util.ArrayList;
import com.mozu.api.MozuClient;
import com.mozu.api.MozuClientFactory;
import com.mozu.api.MozuUrl;
import com.mozu.api.Headers;
import org.joda.time.DateTime;
import com.mozu.api.AsyncCallback;
import java.util.concurrent.CountDownLatch;
import com.mozu.api.security.AuthTicket;
import org.apache.commons.lang.StringUtils;

/**
 * Use the Cart Coupons subresource to apply a coupon to a defined cart or remove a coupon from a cart. When the shopper proceeds to checkout, the coupons applied to the cart apply to the order.
 *
 */
public class AppliedDiscountClient {

	/**
	 *
	 *

	 * MozuClient<com.mozu.api.contracts.commerceruntime.carts.Cart> mozuClient=ApplyCouponClient( cartId,  couponCode);
	 * client.setBaseAddress(url);
	 * client.executeRequest();
	 * Cart cart = client.Result();
	 *

	 * @param cartId Identifier of the cart to delete.
	 * @param couponCode Code associated with the coupon to remove from the cart.
	 * @return Mozu.Api.MozuClient <com.mozu.api.contracts.commerceruntime.carts.Cart>
	 * @see com.mozu.api.contracts.commerceruntime.carts.Cart
	 */
	public static MozuClient<com.mozu.api.contracts.commerceruntime.carts.Cart> applyCouponClient(String cartId, String couponCode) throws Exception
	{
		return applyCouponClient( cartId,  couponCode,  null);
	}

	/**
	 *
	 *

	 * MozuClient<com.mozu.api.contracts.commerceruntime.carts.Cart> mozuClient=ApplyCouponClient( cartId,  couponCode,  responseFields);
	 * client.setBaseAddress(url);
	 * client.executeRequest();
	 * Cart cart = client.Result();
	 *

	 * @param cartId Identifier of the cart to delete.
	 * @param couponCode Code associated with the coupon to remove from the cart.
	 * @param responseFields Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object. This parameter should only be used to retrieve data. Attempting to update data using this parameter may cause data loss.
	 * @return Mozu.Api.MozuClient <com.mozu.api.contracts.commerceruntime.carts.Cart>
	 * @see com.mozu.api.contracts.commerceruntime.carts.Cart
	 */
	public static MozuClient<com.mozu.api.contracts.commerceruntime.carts.Cart> applyCouponClient(String cartId, String couponCode, String responseFields) throws Exception
	{
		MozuUrl url = com.mozu.api.urls.commerce.carts.AppliedDiscountUrl.applyCouponUrl(cartId, couponCode, responseFields);
		String verb = "PUT";
		Class<?> clz = com.mozu.api.contracts.commerceruntime.carts.Cart.class;
		MozuClient<com.mozu.api.contracts.commerceruntime.carts.Cart> mozuClient = (MozuClient<com.mozu.api.contracts.commerceruntime.carts.Cart>) MozuClientFactory.getInstance(clz);
		mozuClient.setVerb(verb);
		mozuClient.setResourceUrl(url);
		return mozuClient;

	}

	/**
	 *
	 *

	 * MozuClient<com.mozu.api.contracts.commerceruntime.carts.Cart> mozuClient=RemoveCouponsClient( cartId);
	 * client.setBaseAddress(url);
	 * client.executeRequest();
	 * Cart cart = client.Result();
	 *

	 * @param cartId Identifier of the cart to delete.
	 * @return Mozu.Api.MozuClient <com.mozu.api.contracts.commerceruntime.carts.Cart>
	 * @see com.mozu.api.contracts.commerceruntime.carts.Cart
	 */
	public static MozuClient<com.mozu.api.contracts.commerceruntime.carts.Cart> removeCouponsClient(String cartId) throws Exception
	{
		MozuUrl url = com.mozu.api.urls.commerce.carts.AppliedDiscountUrl.removeCouponsUrl(cartId);
		String verb = "DELETE";
		Class<?> clz = com.mozu.api.contracts.commerceruntime.carts.Cart.class;
		MozuClient<com.mozu.api.contracts.commerceruntime.carts.Cart> mozuClient = (MozuClient<com.mozu.api.contracts.commerceruntime.carts.Cart>) MozuClientFactory.getInstance(clz);
		mozuClient.setVerb(verb);
		mozuClient.setResourceUrl(url);
		return mozuClient;

	}

	/**
	 *
	 *

	 * MozuClient<com.mozu.api.contracts.commerceruntime.carts.Cart> mozuClient=RemoveCouponClient( cartId,  couponCode);
	 * client.setBaseAddress(url);
	 * client.executeRequest();
	 * Cart cart = client.Result();
	 *

	 * @param cartId Identifier of the cart to delete.
	 * @param couponCode Code associated with the coupon to remove from the cart.
	 * @return Mozu.Api.MozuClient <com.mozu.api.contracts.commerceruntime.carts.Cart>
	 * @see com.mozu.api.contracts.commerceruntime.carts.Cart
	 */
	public static MozuClient<com.mozu.api.contracts.commerceruntime.carts.Cart> removeCouponClient(String cartId, String couponCode) throws Exception
	{
		MozuUrl url = com.mozu.api.urls.commerce.carts.AppliedDiscountUrl.removeCouponUrl(cartId, couponCode);
		String verb = "DELETE";
		Class<?> clz = com.mozu.api.contracts.commerceruntime.carts.Cart.class;
		MozuClient<com.mozu.api.contracts.commerceruntime.carts.Cart> mozuClient = (MozuClient<com.mozu.api.contracts.commerceruntime.carts.Cart>) MozuClientFactory.getInstance(clz);
		mozuClient.setVerb(verb);
		mozuClient.setResourceUrl(url);
		return mozuClient;

	}

}


text:
"""The setup script."""

from setuptools import setup, find_packages

with open('README.rst') as readme_file:
    readme = readme_file.read()

with open('HISTORY.rst') as history_file:
    history = history_file.read()

requirements = [
    'menu==3.1.0',
    # TODO: put package requirements here
]

setup_requirements = [
    'pytest-runner',
    # TODO(romainmartinez): put setup requirements (distutils extensions, etc.) here
]

test_requirements = [
    'pytest',
    # TODO: put package test requirements here
]

setup(
    name='bmch',
    version='0.1.0',
    description="bmch contains usefull tools to conduct a biomechanical analysis",
    long_description=readme + '\n\n' + history,
    author="Romain Martinez",
    author_email='martinez.staps@gmail.com',
    url='https://github.com/romainmartinez/bmch',
    packages=find_packages(include=['bmch']),
    entry_points={
        'console_scripts': [
            'bmch=bmch.cli:main'
        ]
    },
    include_package_data=True,
    install_requires=requirements,
    license="MIT license",
    zip_safe=False,
    keywords='bmch',
    classifiers=[
        'Development Status :: 2 - Pre-Alpha',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Natural Language :: English',
        'Programming Language :: Python :: 3.6',
    ],
    test_suite='tests',
    tests_require=test_requirements,
    setup_requires=setup_requirements,
)

redpajama_set_name: RedPajamaGithub


text:
package java.security.spec;

import java.math.BigInteger;

/**
 * This class specifies an RSA multi-prime private key, as defined in the
 * PKCS#1 v2.1, using the Chinese Remainder Theorem (CRT) information
 * values for efficiency.
 *
 * @author Valerie Peng
 *
 *
 * @see java.security.Key
 * @see java.security.KeyFactory
 * @see KeySpec
 * @see PKCS8EncodedKeySpec
 * @see RSAPrivateKeySpec
 * @see RSAPublicKeySpec
 * @see RSAOtherPrimeInfo
 *
 * @since 1.4
 */

public class RSAMultiPrimePrivateCrtKeySpec extends RSAPrivateKeySpec {

    private final BigInteger publicExponent;
    private final BigInteger primeP;
    private final BigInteger primeQ;
    private final BigInteger primeExponentP;
    private final BigInteger primeExponentQ;
    private final BigInteger crtCoefficient;
    private final RSAOtherPrimeInfo otherPrimeInfo[];

   /**
    * Creates a new RSAMultiPrimePrivateCrtKeySpec
    * given the modulus, publicExponent, privateExponent,
    * primeP, primeQ, primeExponentP, primeExponentQ,
    * crtCoefficient, and otherPrimeInfo as defined in PKCS#1 v2.1.
    *
    *
Note that the contents of otherPrimeInfo
    * are copied to protect against subsequent modification when
    * constructing this object.
    *
    * @param modulus the modulus n.
    * @param publicExponent the public exponent e.
    * @param privateExponent the private exponent d.
    * @param primeP the prime factor p of n.
    * @param primeQ the prime factor q of n.
    * @param primeExponentP this is d mod (p-1).
    * @param primeExponentQ this is d mod (q-1).
    * @param crtCoefficient the Chinese Remainder Theorem
    * coefficient q-1 mod p.
    * @param otherPrimeInfo triplets of the rest of primes, null can be
    * specified if there are only two prime factors (p and q).
    * @exception NullPointerException if any of the parameters, i.e.
    * modulus,
    * publicExponent, privateExponent,
    * primeP, primeQ,
    * primeExponentP, primeExponentQ,
    * crtCoefficient, is null.
    * @exception IllegalArgumentException if an empty, i.e. 0-length,
    * otherPrimeInfo is specified.
    */
    public RSAMultiPrimePrivateCrtKeySpec(BigInteger modulus,
                                BigInteger publicExponent,
                                BigInteger privateExponent,
                                BigInteger primeP,
                                BigInteger primeQ,
                                BigInteger primeExponentP,
                                BigInteger primeExponentQ,
                                BigInteger crtCoefficient,
                                RSAOtherPrimeInfo[] otherPrimeInfo) {
        super(modulus, privateExponent);
        if (modulus == null) {
            throw new NullPointerException("the modulus parameter must be " +
                                            "non-null");
        }
        if (publicExponent == null) {
            throw new NullPointerException("the publicExponent parameter " +
                                            "must be non-null");
        }
        if (privateExponent == null) {
            throw new NullPointerException("the privateExponent parameter " +
                                            "must be non-null");
        }
        if (primeP == null) {
            throw new NullPointerException("the primeP parameter " +
                                            "must be non-null");
        }
        if (primeQ == null) {
            throw new NullPointerException("the primeQ parameter " +
                                            "must be non-null");
        }
        if (primeExponentP == null) {
            throw new NullPointerException("the primeExponentP parameter " +
                                            "must be non-null");
        }
        if (primeExponentQ == null) {
            throw new NullPointerException("the primeExponentQ parameter " +
                                            "must be non-null");
        }
        if (crtCoefficient == null) {
            throw new NullPointerException("the crtCoefficient parameter " +
                                            "must be non-null");
        }
        this.publicExponent = publicExponent;
        this.primeP = primeP;
        this.primeQ = primeQ;
        this.primeExponentP = primeExponentP;
        this.primeExponentQ = primeExponentQ;
        this.crtCoefficient = crtCoefficient;
        if (otherPrimeInfo == null)  {
            this.otherPrimeInfo = null;
        } else if (otherPrimeInfo.length == 0) {
            throw new IllegalArgumentException("the otherPrimeInfo " +
                                                "parameter must not be empty");
        } else {
            this.otherPrimeInfo = otherPrimeInfo.clone();
        }
    }

    /**
     * Returns the public exponent.
     *
     * @return the public exponent.
     */
    public BigInteger getPublicExponent() {
        return this.publicExponent;
    }

    /**
     * Returns the primeP.
     *
     * @return the primeP.
     */
    public BigInteger getPrimeP() {
        return this.primeP;
    }

    /**
     * Returns the primeQ.
     *
     * @return the primeQ.
     */
    public BigInteger getPrimeQ() {
        return this.primeQ;
    }

    /**
     * Returns the primeExponentP.
     *
     * @return the primeExponentP.
     */
    public BigInteger getPrimeExponentP() {
        return this.primeExponentP;
    }

    /**
     * Returns the primeExponentQ.
     *
     * @return the primeExponentQ.
     */
    public BigInteger getPrimeExponentQ() {
        return this.primeExponentQ;
    }

    /**
     * Returns the crtCoefficient.
     *
     * @return the crtCoefficient.
     */
    public BigInteger getCrtCoefficient() {
        return this.crtCoefficient;
    }

    /**
     * Returns a copy of the otherPrimeInfo or null if there are
     * only two prime factors (p and q).
     *
     * @return the otherPrimeInfo. Returns a new array each
     * time this method is called.
     */
    public RSAOtherPrimeInfo[] getOtherPrimeInfo() {
        if (otherPrimeInfo == null) return null;
        return otherPrimeInfo.clone();
    }
}


text:
@interface QYResultTableViewController : UITableViewController<UISearchResultsUpdating>
//设置搜索的数据源
@property (nonatomic, strong)NSArray *array;
@end


text:
from __future__ import division, unicode_literals

"""
This module defines some useful design patterns.
"""

__author__ = "Shyue Ping Ong"
__copyright__ = "Copyright 2011, The Materials Project"
__version__ = "1.0"
__maintainer__ = "Shyue Ping Ong"
__email__ = "shyuep@gmail.com"
__status__ = "Production"
__date__ = "Sep 23, 2011"

class Enum(set):
    """
    Creates an enum out of a set.
    """
    def __getattr__(self, name):
        if name in self:
            return name
        raise AttributeError


text:
<?php

namespace TZK\Taiga\Contracts;

interface RequestWrapper
{
    /**
     * Send a request to a specific endpoint.
     *
     * @param string $url
     * @param string $method
     * @param array  $data
     *
     * @throws TZK\Taiga\Exceptions\RequestException if an error occured (bad status code or error during transmission)
     *
     * @return mixed the json response decoded as an array or object
     */
    public function send($url, $method, $data = []);

    /**
     * @param string $name
     * @param mixed  $value
     *
     * @return TZK\Taiga\Contracts\RequestWrapper
     */
    public function setHeader($name, $value);

    /**
     * @param bool $bool
     *
     * @return TZK\Taiga\Contracts\RequestWrapper
     */
    public function enableSSL($bool = true);

    /**
     * @param string $agent
     *
     * @return TZK\Taiga\Contracts\RequestWrapper
     */
    public function setUserAgent($agent);

    /**
     * @return string
     */
    public function getErrorMessage();
}


text:
package org.wso2.carbon.device.mgt.mobile.dao.impl;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.mobile.dao.MobileDeviceManagementDAOException;
import org.wso2.carbon.device.mgt.mobile.dao.MobileFeatureDAO;
import org.wso2.carbon.device.mgt.mobile.dao.util.MobileDeviceManagementDAOUtil;
import org.wso2.carbon.device.mgt.mobile.dto.MobileFeature;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * Implementation of MobileFeatureDAO.
 */
public class MobileFeatureDAOImpl implements MobileFeatureDAO {

	private DataSource dataSource;
	private static final Log log = LogFactory.getLog(MobileFeatureDAOImpl.class);

	public MobileFeatureDAOImpl(DataSource dataSource) {
		this.dataSource = dataSource;
	}

	@Override
	public boolean addFeature(MobileFeature mobileFeature)
			throws MobileDeviceManagementDAOException {
		boolean status = false;
		Connection conn = null;
		PreparedStatement stmt = null;
		try {
			conn = this.getConnection();
			String createDBQuery =
					"INSERT INTO AD_FEATURE(CODE, NAME, DESCRIPTION, DEVICE_TYPE) VALUES (?, ?, ?, ?)";

			stmt = conn.prepareStatement(createDBQuery);
			stmt.setString(1, mobileFeature.getCode());
			stmt.setString(2, mobileFeature.getName());
			stmt.setString(3, mobileFeature.getDescription());
			stmt.setString(4, mobileFeature.getDeviceType());
			int rows = stmt.executeUpdate();
			if (rows > 0) {
                if (log.isDebugEnabled()) {
					log.debug("Added a new MobileFeature " + mobileFeature.getCode() + " to the" +
					          " MDM database.");
				}
                status = true;
			}

		} catch (SQLException e) {
			String msg = "Error occurred while adding feature code - '" +
			             mobileFeature.getCode() + "' to feature table";
			log.error(msg, e);
			throw new MobileDeviceManagementDAOException(msg, e);
		} finally {
			MobileDeviceManagementDAOUtil.cleanupResources(conn, stmt, null);
		}
		return status;
	}

	@Override
	public boolean updateFeature(MobileFeature mobileFeature)
			throws MobileDeviceManagementDAOException {
		boolean status = false;
		Connection conn = null;
		PreparedStatement stmt = null;
		try {
			conn = this.getConnection();
			String updateDBQuery =
					"UPDATE AD_FEATURE SET CODE = ?, NAME = ?, DESCRIPTION = ?, DEVICE_TYPE = ?" +
					" WHERE FEATURE_ID = ?";
			stmt = conn.prepareStatement(updateDBQuery);
			stmt.setString(1, mobileFeature.getCode());
			stmt.setString(2, mobileFeature.getName());
			stmt.setString(3, mobileFeature.getDescription());
			stmt.setString(4, mobileFeature.getDeviceType());
			stmt.setInt(5, mobileFeature.getId());
			int rows = stmt.executeUpdate();
			if (rows > 0) {
				status = true;
				if (log.isDebugEnabled()) {
					log.debug("Updated MobileFeature " + mobileFeature.getCode());
				}
			}
		} catch (SQLException e) {
			String msg = "Error occurred while updating the feature with feature code - '" +
			             mobileFeature.getId() + "'";
			log.error(msg, e);
			throw new MobileDeviceManagementDAOException(msg, e);
		} finally {
			MobileDeviceManagementDAOUtil.cleanupResources(conn, stmt, null);
		}
		return status;
	}

	@Override
	public boolean deleteFeatureByCode(String mblFeatureCode)
			throws MobileDeviceManagementDAOException {
		boolean status = false;
		Connection conn = null;
		PreparedStatement stmt = null;
		try {
			conn = this.getConnection();
			String deleteDBQuery =
					"DELETE FROM AD_FEATURE WHERE CODE = ?";
			stmt = conn.prepareStatement(deleteDBQuery);
			stmt.setString(1, mblFeatureCode);
			int rows = stmt.executeUpdate();
			if (rows > 0) {
				status = true;
				if (log.isDebugEnabled()) {
					log.debug("Deleted MobileFeature code " + mblFeatureCode + " from the" +
					          " MDM database.");
				}
			}
		} catch (SQLException e) {
			String msg = "Error occurred while deleting feature with code - " + mblFeatureCode;
			log.error(msg, e);
			throw new MobileDeviceManagementDAOException(msg, e);
		} finally {
			MobileDeviceManagementDAOUtil.cleanupResources(conn, stmt, null);
		}
		return status;
	}

	@Override
	public boolean deleteFeatureById(int mblFeatureId)
			throws MobileDeviceManagementDAOException {
		boolean status = false;
		Connection conn = null;
		PreparedStatement stmt = null;
		try {
			conn = this.getConnection();
			String deleteDBQuery =
					"DELETE FROM AD_FEATURE WHERE FEATURE_ID = ?";
			stmt = conn.prepareStatement(deleteDBQuery);
			stmt.setInt(1, mblFeatureId);
			int rows = stmt.executeUpdate();
			if (rows > 0) {
				status = true;
				if (log.isDebugEnabled()) {
					log.debug("Deleted MobileFeature id " + mblFeatureId + " from the" +
					          " MDM database.");
				}
			}
		} catch (SQLException e) {
			String msg = "Error occurred while deleting feature with id - " + mblFeatureId;
			log.error(msg, e);
			throw new MobileDeviceManagementDAOException(msg, e);
		} finally {
			MobileDeviceManagementDAOUtil.cleanupResources(conn, stmt, null);
		}
		return status;
	}

	@Override
	public MobileFeature getFeatureByCode(String mblFeatureCode)
			throws MobileDeviceManagementDAOException {
		Connection conn = null;
		PreparedStatement stmt = null;
		MobileFeature mobileFeature = null;
		try {
			conn = this.getConnection();
			String selectDBQuery =
					"SELECT FEATURE_ID, CODE, NAME, DESCRIPTION, DEVICE_TYPE FROM AD_FEATURE " +
					"WHERE CODE = ?";
			stmt = conn.prepareStatement(selectDBQuery);
			stmt.setString(1, mblFeatureCode);
			ResultSet resultSet = stmt.executeQuery();
			if (resultSet.next()) {
				mobileFeature = new MobileFeature();
				mobileFeature.setId(resultSet.getInt(1));
				mobileFeature.setCode(resultSet.getString(2));
				mobileFeature.setName(resultSet.getString(3));
				mobileFeature.setDescription(resultSet.getString(4));
				mobileFeature.setDeviceType(resultSet.getString(5));
				if (log.isDebugEnabled()) {
					log.debug("Fetched MobileFeature " + mblFeatureCode + " from the" +
					          " MDM database.");
				}
			}
		} catch (SQLException e) {
			String msg = "Error occurred while fetching feature code - '" +
			             mblFeatureCode + "'";
			log.error(msg, e);
			throw new MobileDeviceManagementDAOException(msg, e);
		} finally {
			MobileDeviceManagementDAOUtil.cleanupResources(conn, stmt, null);
		}
		return mobileFeature;
	}

	@Override
	public MobileFeature getFeatureById(int mblFeatureId)
			throws MobileDeviceManagementDAOException {
		Connection conn = null;
		PreparedStatement stmt = null;
		MobileFeature mobileFeature = null;
		try {
			conn = this.getConnection();
			String selectDBQuery =
					"SELECT FEATURE_ID, CODE, NAME, DESCRIPTION, DEVICE_TYPE FROM AD_FEATURE" +
					" WHERE FEATURE_ID = ?";
			stmt = conn.prepareStatement(selectDBQuery);
			stmt.setInt(1, mblFeatureId);
			ResultSet resultSet = stmt.executeQuery();
			if (resultSet.next()) {
				mobileFeature = new MobileFeature();
				mobileFeature.setId(resultSet.getInt(1));
				mobileFeature.setCode(resultSet.getString(2));
				mobileFeature.setName(resultSet.getString(3));
				mobileFeature.setDescription(resultSet.getString(4));
				mobileFeature.setDeviceType(resultSet.getString(5));
				if (log.isDebugEnabled()) {
					log.debug("Fetched MobileFeatureId" + mblFeatureId + " from the" +
					          " MDM database.");
				}
			}
		} catch (SQLException e) {
			String msg = "Error occurred while fetching feature id - '" +
			             mblFeatureId + "'";
			log.error(msg, e);
			throw new MobileDeviceManagementDAOException(msg, e);
		} finally {
			MobileDeviceManagementDAOUtil.cleanupResources(conn, stmt, null);
		}
		return mobileFeature;
	}

	@Override
	public List<MobileFeature> getAllFeatures() throws MobileDeviceManagementDAOException {
		Connection conn = null;
		PreparedStatement stmt = null;
		MobileFeature mobileFeature;
		List<MobileFeature> mobileFeatures = new ArrayList<MobileFeature>();
		try {
			conn = this.getConnection();
			String selectDBQuery =
					"SELECT FEATURE_ID, CODE, NAME, DESCRIPTION, DEVICE_TYPE FROM AD_FEATURE";
			stmt = conn.prepareStatement(selectDBQuery);
			ResultSet resultSet = stmt.executeQuery();
			while (resultSet.next()) {
				mobileFeature = new MobileFeature();
				mobileFeature.setId(resultSet.getInt(1));
				mobileFeature.setCode(resultSet.getString(2));
				mobileFeature.setName(resultSet.getString(3));
				mobileFeature.setDescription(resultSet.getString(4));
				mobileFeature.setDeviceType(resultSet.getString(5));
				mobileFeatures.add(mobileFeature);
			}
			if (log.isDebugEnabled()) {
				log.debug("Fetched all MobileFeatures from the MDM database.");
			}
			return mobileFeatures;
		} catch (SQLException e) {
			String msg = "Error occurred while fetching all features.'";
			log.error(msg, e);
			throw new MobileDeviceManagementDAOException(msg, e);
		} finally {
			MobileDeviceManagementDAOUtil.cleanupResources(conn, stmt, null);
		}
	}

	@Override
	public List<MobileFeature> getFeatureByDeviceType(String deviceType) throws
	                                                                           MobileDeviceManagementDAOException {
		Connection conn = null;
		PreparedStatement stmt = null;
		MobileFeature mobileFeature;
		List<MobileFeature> mobileFeatures = new ArrayList<MobileFeature>();
		try {
			conn = this.getConnection();
			String selectDBQuery =
					"SELECT FEATURE_ID, CODE, NAME, DESCRIPTION, DEVICE_TYPE FROM AD_FEATURE" +
					" WHERE DEVICE_TYPE = ?";
			stmt = conn.prepareStatement(selectDBQuery);
			stmt.setString(1, deviceType);
			ResultSet resultSet = stmt.executeQuery();
			while (resultSet.next()) {
				mobileFeature = new MobileFeature();
				mobileFeature.setId(resultSet.getInt(1));
				mobileFeature.setCode(resultSet.getString(2));
				mobileFeature.setName(resultSet.getString(3));
				mobileFeature.setDescription(resultSet.getString(4));
				mobileFeature.setDeviceType(resultSet.getString(5));
				mobileFeatures.add(mobileFeature);
			}
			if (log.isDebugEnabled()) {
				log.debug("Fetched all MobileFeatures of type " + deviceType + " from the MDM" +
				          " database.");
			}
			return mobileFeatures;
		} catch (SQLException e) {
			String msg = "Error occurred while fetching all features.'";
			log.error(msg, e);
			throw new MobileDeviceManagementDAOException(msg, e);
		} finally {
			MobileDeviceManagementDAOUtil.cleanupResources(conn, stmt, null);
		}
	}

	private Connection getConnection() throws MobileDeviceManagementDAOException {
		try {
			return dataSource.getConnection();
		} catch (SQLException e) {
			String msg = "Error occurred while obtaining a connection from the mobile specific " +
			             "datasource.";
			log.error(msg, e);
			throw new MobileDeviceManagementDAOException(msg, e);
		}
	}
}


text:
local path  = require('path')
local fs    = require('fs')
local json  = require('json')

-- 当 DHCP 客户端获取到新的 IP 地址时调用这个方法
-- - 这个方法由 /usr/share/udhcpc/default.script 中调用
-- - 这个方法将获取到新地址等保存到 network.conf 配置文件中
-- TODO: 改为保存到临时目录

local function start()
    local function saveConfig(data)
        local filename = path.join(os.tmpdir, 'run/dhcp.json')
        local filedata = json.stringify(data)
        fs.writeFile(filename, filedata)
    end

    local config = {}
    config.ip = os.getenv("ip")
    config.router = os.getenv("router")
    config.netmask = os.getenv("subnet")
    config.broadcast = os.getenv("broadcast")

    config.ifname  = os.getenv("interface")
    config.dns = os.getenv("dns")
    config.domain = os.getenv("domain")
    config.ntpsrv = os.getenv("ntpsrv")
    config.updated = Date.now()

    if (config.ip) then
        saveConfig(config)
    else
        print('dhcp: invalid ip params')
    end
end

local function stop()

end

start()


text:
function t = filetype(A)
% xff::filetype  - return filetype associated with object

% Version:  v0.9d
% Build:    14061918
% Date:     Jun-19 2014, 6:15 PM EST
% Author:   Jochen Weber, SCAN Unit, Columbia University, NYC, NY, USA
% URL/Info: http://neuroelf.net/

% Copyright (c) 2014, Jochen Weber
% All rights reserved.
%
% Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions are met:
%     * Redistributions of source code must retain the above copyright
%       notice, this list of conditions and the following disclaimer.
%     * Redistributions in binary form must reproduce the above copyright
%       notice, this list of conditions and the following disclaimer in the
%       documentation and/or other materials provided with the distribution.
%     * Neither the name of Columbia University nor the
%       names of its contributors may be used to endorse or promote products
%       derived from this software without specific prior written permission.
%
% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
% ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
% WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
% DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY
% DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
% (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
% LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
% ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
% (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
% SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

try
    if numel(A) == 1
        Asc = xffgetscont(A.L);
        t = Asc.S.Extensions{1};
    else
        A = struct(A);
        t = cell(size(A));
        for fc = 1:numel(t)
            Asc = xffgetscont(A(fc).L);
            t{fc} = Asc.S.Extensions{1};
        end
    end
catch ne_eo;
    rethrow(ne_eo);
end


text:
State *make_state(char *input) {
	State *state = calloc(sizeof(State), 1);
	state->out = make_tree(NULL);
	state->in = input;
	return state;
};

void free_state(State *state) {
	free_tree(state->out);
	free_link(state->opstk);
	free(state);
}


text:
import zstackwoodpecker.test_state as ts_header
import os
TestAction = ts_header.TestAction
def path():

    return dict(initial_formation="template5", checking_point=1, faild_point=100000, path_list=[
		[TestAction.create_mini_vm, 'vm1', 'data_volume=true', 'cluster=cluster2'],
		[TestAction.create_volume, 'volume2', 'cluster=cluster2', 'flag=scsi'],
		[TestAction.attach_volume, 'vm1', 'volume2'],
		[TestAction.create_volume_backup, 'volume2', 'volume2-backup1'],
		[TestAction.create_mini_vm, 'vm2', 'network=random', 'cluster=cluster1'],
		[TestAction.create_volume, 'volume3', 'cluster=cluster1', 'flag=scsi'],
		[TestAction.resize_data_volume, 'volume3', 5*1024*1024],
		[TestAction.poweroff_only, 'cluster=cluster1'],
		[TestAction.create_volume, 'volume4', 'size=random', 'cluster=cluster1', 'flag=scsi'],
		[TestAction.create_volume, 'volume5', 'cluster=cluster1', 'flag=thick,scsi'],
		[TestAction.add_image, 'image1', 'root', 'http://172.20.1.28/mirror/diskimages/centos_vdbench.qcow2'],
		[TestAction.create_vm_backup, 'vm1', 'vm1-backup2'],
		[TestAction.delete_vm_backup, 'vm1-backup2'],
		[TestAction.delete_image, 'image1'],
		[TestAction.expunge_image, 'image1'],
		[TestAction.create_vm_backup, 'vm1', 'vm1-backup5'],
		[TestAction.destroy_vm, 'vm1'],
		[TestAction.recover_vm, 'vm1'],
		[TestAction.poweroff_only, 'cluster=cluster2'],
		[TestAction.resize_volume, 'vm2', 5*1024*1024],
		[TestAction.attach_volume, 'vm1', 'volume2'],
		[TestAction.create_volume, 'volume6', 'cluster=cluster2', 'flag=thin,scsi'],
		[TestAction.use_volume_backup, 'volume2-backup5'],
		[TestAction.start_vm, 'vm2'],
		[TestAction.stop_vm, 'vm2'],
		[TestAction.delete_volume, 'volume6'],
		[TestAction.expunge_volume, 'volume6'],
		[TestAction.add_image, 'image2', 'root', os.environ.get('isoForVmUrl')],
		[TestAction.create_vm_by_image, 'image2', 'iso', 'vm3', 'cluster=cluster2'],
		[TestAction.create_vm_backup, 'vm3', 'vm3-backup8'],
		[TestAction.migrate_vm, 'vm3'],
		[TestAction.poweroff_only, 'cluster=cluster1'],
		[TestAction.use_vm_backup, 'vm1-backup5'],
])

'''
The final status:
Running:['vm3']
Stopped:['vm1', 'vm2']
Enadbled:['volume2-backup1', 'vm1-backup5', 'auto-volume1-backup5', 'volume2-backup5', 'vm3-backup8', 'image2']
attached:['volume2']
Detached:['volume3', 'volume4', 'volume5', 'auto-volume1']
Deleted:['vm1-backup2', 'auto-volume1-backup2', 'volume2-backup2']
Expunged:['volume6', 'image1']
Ha:[]
Group:
	vm_backup2:['vm3-backup8']---vm3@
	vm_backup1:['vm1-backup5', 'auto-volume1-backup5', 'volume2-backup5']---vm1@auto-volume1_volume2
'''


text:
package io.github.charly1811.materialcolors;

import android.content.Context;

import java.util.Random;

import io.github.charly1811.materialcolors.R;

public class MaterialColorRandom {

    private Random random = new Random();

    private int[] allColors;

    private int[] primaryColors;
    private int[] darkColors;

    public MaterialColorRandom(Context context) {
        primaryColors = context.getResources().getIntArray(R.array.primary_colors);
        darkColors = context.getResources().getIntArray(R.array.dark_colors);
    }

    public MaterialColor nextMaterialColor() {
        int index = random.nextInt(primaryColors.length);
        return new MaterialColor(primaryColors[index],darkColors[index]);
    }
}


text:
"""
Installation of Cygwin packages.

A state module to manage cygwin packages. Packages can be installed
or removed.

.. code-block:: yaml

    dos2unix:
      cyg.installed
"""

import logging

log = logging.getLogger(__name__)

def __virtual__():
    """
    Only load if cyg module is available in __salt__.
    """
    if "cyg.list" in __salt__:
        return True
    return (False, "cyg module could not be loaded")

def installed(name, cyg_arch="x86_64", mirrors=None):
    """
    Make sure that a package is installed.

    name
        The name of the package to install

    cyg_arch : x86_64
        The cygwin architecture to install the package into.
        Current options are x86 and x86_64

    mirrors : None
        List of mirrors to check.
        None will use a default mirror (kernel.org)

    CLI Example:

    .. code-block:: yaml

        rsync:
          cyg.installed:
            - mirrors:
              - http://mirror/without/public/key: ""
              - http://mirror/with/public/key: http://url/of/public/key
    """
    ret = {"name": name, "result": None, "comment": "", "changes": {}}

    if cyg_arch not in ["x86", "x86_64"]:
        ret["result"] = False
        ret["comment"] = "The 'cyg_arch' argument must be one of 'x86' or 'x86_64'"
        return ret

    log.debug("Installed State: Initial Mirror list: %s", mirrors)

    if not __salt__["cyg.check_valid_package"](
        name, cyg_arch=cyg_arch, mirrors=mirrors
    ):
        ret["result"] = False
        ret["comment"] = "Invalid package name."
        return ret

    pkgs = __salt__["cyg.list"](name, cyg_arch)
    if name in pkgs:
        ret["result"] = True
        ret["comment"] = "Package is already installed."
        return ret

    if __opts__["test"]:
        ret["comment"] = "The package {} would have been installed".format(name)
        return ret

    if __salt__["cyg.install"](name, cyg_arch=cyg_arch, mirrors=mirrors):
        ret["result"] = True
        ret["changes"][name] = "Installed"
        ret["comment"] = "Package was successfully installed"
    else:
        ret["result"] = False
        ret["comment"] = "Could not install package."

    return ret

def removed(name, cyg_arch="x86_64", mirrors=None):
    """
    Make sure that a package is not installed.

    name
        The name of the package to uninstall

    cyg_arch : x86_64
        The cygwin architecture to remove the package from.
        Current options are x86 and x86_64

    mirrors : None
        List of mirrors to check.
        None will use a default mirror (kernel.org)

    CLI Example:

    .. code-block:: yaml

        rsync:
          cyg.removed:
            - mirrors:
              - http://mirror/without/public/key: ""
              - http://mirror/with/public/key: http://url/of/public/key
    """
    ret = {"name": name, "result": None, "comment": "", "changes": {}}

    if cyg_arch not in ["x86", "x86_64"]:
        ret["result"] = False
        ret["comment"] = "The 'cyg_arch' argument must be one of 'x86' or 'x86_64'"
        return ret

    if not __salt__["cyg.check_valid_package"](
        name, cyg_arch=cyg_arch, mirrors=mirrors
    ):
        ret["result"] = False
        ret["comment"] = "Invalid package name."
        return ret

    if name not in __salt__["cyg.list"](name, cyg_arch):
        ret["result"] = True
        ret["comment"] = "Package is not installed."
        return ret

    if __opts__["test"]:
        ret["comment"] = "The package {} would have been removed".format(name)
        return ret
    if __salt__["cyg.uninstall"](name, cyg_arch):
        ret["result"] = True
        ret["changes"][name] = "Removed"
        ret["comment"] = "Package was successfully removed."
    else:
        ret["result"] = False
        ret["comment"] = "Could not remove package."
    return ret

def updated(name=None, cyg_arch="x86_64", mirrors=None):
    """
    Make sure all packages are up to date.

    name : None
        No affect, salt fails poorly without the arg available

    cyg_arch : x86_64
        The cygwin architecture to update.
        Current options are x86 and x86_64

    mirrors : None
        List of mirrors to check.
        None will use a default mirror (kernel.org)

    CLI Example:

    .. code-block:: yaml

        rsync:
          cyg.updated:
            - mirrors:
              - http://mirror/without/public/key: ""
              - http://mirror/with/public/key: http://url/of/public/key
    """
    ret = {"name": "cyg.updated", "result": None, "comment": "", "changes": {}}

    if cyg_arch not in ["x86", "x86_64"]:
        ret["result"] = False
        ret["comment"] = "The 'cyg_arch' argument must be one of 'x86' or 'x86_64'"
        return ret

    if __opts__["test"]:
        ret["comment"] = "All packages would have been updated"
        return ret

    if not mirrors:
        log.warning("No mirror given, using the default.")

    before = __salt__["cyg.list"](cyg_arch=cyg_arch)
    if __salt__["cyg.update"](cyg_arch, mirrors=mirrors):
        after = __salt__["cyg.list"](cyg_arch=cyg_arch)
        differ = DictDiffer(after, before)
        ret["result"] = True
        if differ.same():
            ret["comment"] = "Nothing to update."
        else:
            ret["changes"]["added"] = list(differ.added())
            ret["changes"]["removed"] = list(differ.removed())
            ret["changes"]["changed"] = list(differ.changed())
            ret["comment"] = "All packages successfully updated."
    else:
        ret["result"] = False
        ret["comment"] = "Could not update packages."
    return ret

# https://github.com/hughdbrown/dictdiffer
# DictDiffer is licensed as MIT code
# A dictionary difference calculator
# Originally posted as:
# http://stackoverflow.com/a/1165552

class DictDiffer:
    """
    Calculate the difference between two dictionaries.

    (1) items added
    (2) items removed
    (3) keys same in both but changed values
    (4) keys same in both and unchanged values
    """

    def __init__(self, current_dict, past_dict):
        """
        Iitialize the differ.
        """
        self.current_dict, self.past_dict = current_dict, past_dict
        self.current_keys, self.past_keys = (
            set(d.keys()) for d in (current_dict, past_dict)
        )
        self.intersect = self.current_keys.intersection(self.past_keys)

    def same(self):
        """
        True if the two dicts are the same.
        """
        return self.current_dict == self.past_dict

    def added(self):
        """
        Return a set of additions to past_dict.
        """
        return self.current_keys - self.intersect

    def removed(self):
        """
        Return a set of things removed from past_dict.
        """
        return self.past_keys - self.intersect

    def changed(self):
        """
        Return a set of the keys with changed values.
        """
        return {o for o in self.intersect if self.past_dict[o] != self.current_dict[o]}

    def unchanged(self):
        """
        Return a set of the keys with unchanged values.
        """
        return {o for o in self.intersect if self.past_dict[o] == self.current_dict[o]}


text:
require_relative 'test_helper'
require 'remote_files/resque_job'

describe RemoteFiles::ResqueJob do
  describe 'loading the implementation file' do
    before do
      @file = RemoteFiles::File.new('identifier',
        :content_type => 'text/plain',
        :content      => 'content',
        :stored_in    => [:s3],
        :foo          => :bar
      )

      load 'remote_files/resque_job.rb'
    end

    it 'should setup the right synchronize_stores hook' do
      Resque.expects(:enqueue).with(RemoteFiles::ResqueJob,
        :identifier    => 'identifier',
        :content_type  => 'text/plain',
        :stored_in     => [:s3],
        :foo           => :bar,
        :configuration => :default,
        :_action       => :synchronize
      )

      RemoteFiles.synchronize_stores(@file)
    end

    it 'should setup the right delete_file hook' do
      Resque.expects(:enqueue).with(RemoteFiles::ResqueJob,
        :identifier    => 'identifier',
        :content_type  => 'text/plain',
        :stored_in     => [:s3],
        :foo           => :bar,
        :configuration => :default,
        :_action       => :delete
      )

      RemoteFiles.delete_file(@file)
    end
  end

  describe "running the job" do
    before do
      @options = {
        :identifier   => 'identifier',
        :content_type => 'text/plain',
        :stored_in    => [:s3],
        :foo          => :bar
      }

      @file = stub

      RemoteFiles::File.expects(:new).with('identifier',
        :content_type => 'text/plain',
        :stored_in    => [:s3],
        :foo          => :bar
      ).returns(@file)
    end

    it 'should call #synchronize! on the reconstructed file when asked to' do
      @file.expects(:synchronize!)

      RemoteFiles::ResqueJob.perform(@options.merge(:_action => :synchronize))
    end

    it 'should call #delete_now! on the reconstructed file when asked to' do
      @file.expects(:delete_now!)

      RemoteFiles::ResqueJob.perform(@options.merge(:_action => :delete))
    end
  end

end


text:
require 'dm-core'

module DataMapper
  module Model
    include Padrino::OrmAdapter::ToAdapter
  end

  module Resource
    class OrmAdapter < Padrino::OrmAdapter::Base
      # get a list of column names for a given class
      def column_names
        klass.properties.map(&:name)
      end

      # @see OrmAdapter::Base#get!
      def get!(id)
        klass.get!(id)
      end

      # @see OrmAdapter::Base#get
      def get(id)
        klass.get(id)
      end

      # @see OrmAdapter::Base#find_first
      def find_first(options = {})
        conditions, order = extract_conditions!(options)
        klass.first :conditions => conditions, :order => order_clause(order)
      end

      # @see OrmAdapter::Base#find_all
      def find_all(options = {})
        conditions, order, limit, offset = extract_conditions!(options)
        opts = { :conditions => conditions, :order => order_clause(order) }
        opts = opts.merge({ :limit => limit }) unless limit.nil?
        opts = opts.merge({ :offset => offset }) unless offset.nil?
        klass.all opts
      end

      # @see OrmAdapter::Base#create!
      def create!(attributes = {})
        klass.create(attributes)
      end

      # @see OrmAdapter::Base#destroy
      def destroy(object)
        object.destroy if valid_object?(object)
      end

    protected

      def order_clause(order)
        order.map {|pair| pair.first.send(pair.last)}
      end
    end
  end
end


text:
package org.openforis.collect.io.data.csv;

public class Column {

	public enum DataType {
		STRING, INTEGER, DECIMAL, DATE, TIME, IMAGE_BYTE_ARRAY
	}

	String header;
	DataType dataType;

	public Column(String header) {
		this(header, DataType.STRING);
	}

	public Column(String header, DataType dataType) {
		super();
		this.header = header;
		this.dataType = dataType;
	}

	public String getHeader() {
		return header;
	}

	public void setHeader(String header) {
		this.header = header;
	}

	public DataType getDataType() {
		return dataType;
	}

	public void setDataType(DataType dataType) {
		this.dataType = dataType;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((header == null) ? 0 : header.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Column other = (Column) obj;
		if (header == null) {
			if (other.header != null)
				return false;
		} else if (!header.equals(other.header))
			return false;
		return true;
	}

	@Override
	public String toString() {
		return "Column [header=" + header + "]";
	}
}


text:
@interface BWPusherHandler()
- (void)setupPusherWithKey:(NSString *)apiKey;
@end

@implementation BWPusherHandler
@synthesize client, subscribedChannels;

+ (id)pusherHandlerWithKey:(NSString *)apiKey
{
    BWPusherHandler *pusherHandler = [[BWPusherHandler alloc] initWithKey:apiKey];
    return pusherHandler;
}

- (id)initWithKey:(NSString *)apiKey
{
    self = [super init];
    if (self != nil) {
        self.subscribedChannels = [NSMutableDictionary dictionary];
        [self setupPusherWithKey:apiKey];
    }
    return self;
}

- (void)setupPusherWithKey:(NSString *)apiKey
{
    self.client = [PTPusher pusherWithKey:apiKey delegate:(id <PTPusherDelegate>)[UIApplication sharedApplication].delegate encrypted:YES];
    self.client.reconnectAutomatically = YES;

    PTPusherChannel *channel = [self.client subscribeToChannelNamed:@"common"];

    [channel bindToEventNamed:@"build:started" target:[[BWCommandBuildStarted alloc] init] action:@selector(buildWasStarted:)];
    [channel bindToEventNamed:@"build:finished" target:[[BWCommandBuildFinished alloc] init] action:@selector(buildWasFinished:)];
    [channel bindToEventNamed:@"job:finished" target:[[BWCommandJobFinished alloc] init] action:@selector(jobWasFinished:)];

#if PUSHER_EVENT_LOGGING
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReceiveEvent:) name:PTPusherEventReceivedNotification object:channel];
#endif

}

- (void)subscribeToChannel:(NSString *)channelName
{
    if ([self.subscribedChannels valueForKey:channelName]) {
        return;
    }

    PTPusherChannel *channel = [self.client subscribeToChannelNamed:channelName];
    [self.subscribedChannels setValue:channel forKey:channelName];

    [channel bindToEventNamed:@"job:log" target:[[BWCommandJobLog alloc] init] action:@selector(jobLogAppended:)];
}

- (void)unsubscribeFromChannel:(NSString *)channelName
{
    PTPusherChannel *channel = [self.subscribedChannels valueForKey:channelName];
    [self.subscribedChannels removeObjectForKey:channelName];

    [self.client unsubscribeFromChannel:channel];
}

// will only get called if PUSHER_EVENT_LOGGING is true
- (void)didReceiveEvent:(NSNotification *)note
{
    PTPusherEvent *event = (PTPusherEvent *)[[note userInfo] valueForKey:PTPusherEventUserInfoKey];
    NSLog(@"pusher - notification: %@", [event data]);
}

@end


text:
.. spelling::

    cub

.. index:: unsorted ; cub

.. _pkg.cub:

cub
===

-  `Official <https://github.com/NVlabs/cub>`__
-  `Hunterized <https://github.com/hunter-packages/cub>`__
-  `Example <https://github.com/ruslo/hunter/blob/master/examples/cub/CMakeLists.txt>`__
-  Added by `David Hirvonen <https://github.com/headupinclouds>`__ (`pr-1162 <https://github.com/ruslo/hunter/pull/1162>`__)

.. code-block:: cmake

    hunter_add_package(cub)
    find_package(cub CONFIG REQUIRED)
    target_link_libraries(foo cub::cub)


text:
const AWS = require('aws-sdk');
const regions = require('../../etc/regions');
const urls = require('../../etc/urls');
const pipelineNames = require('../../etc/pipeline-names');
const { emoji } = require('../../etc/execution-emoji');

const sns = new AWS.SNS({
  apiVersion: '2010-03-31',
  region: process.env.SLACK_MESSAGE_RELAY_TOPIC_ARN.split(':')[3],
});

module.exports = async (event) => {
  const region = event.region;
  const pipeline = event.detail.pipeline;
  const execId = event.detail['execution-id'];

  const regionNickname = regions(region);
  const pipelineNickname = pipelineNames(pipeline);
  const url = urls.executionConsoleUrl(region, pipeline, execId);
  const icon = emoji(execId);
  const header = [
    `*<${url}|${regionNickname} » ${pipelineNickname}>*`,
    `*Execution ID:* \`${execId}\` ${icon}`,
  ].join('\n');

  await sns
    .publish({
      TopicArn: process.env.SLACK_MESSAGE_RELAY_TOPIC_ARN,
      Message: JSON.stringify({
        channel: `#ops-deploys-${event.region}`,
        username: 'AWS CodePipeline',
        icon_emoji: ':ops-codepipeline:',
        attachments: [
          {
            color: '#f4f323',
            fallback: `${regionNickname} ${pipelineNickname} has started.`,
            blocks: [
              {
                type: 'section',
                text: {
                  type: 'mrkdwn',
                  text: header,
                },
              },
              {
                type: 'section',
                text: {
                  type: 'mrkdwn',
                  text: 'Pipeline execution has started.',
                },
              },
            ],
          },
        ],
      }),
    })
    .promise();
};


text:
NSString * const key_DCHImageTurbo_UIImage_ResizeWidth = @"key_DCHImageTurbo_UIImage_ResizeWidth";  // NSNumber
NSString * const key_DCHImageTurbo_UIImage_ResizeHeight = @"key_DCHImageTurbo_UIImage_ResizeHeight";  // NSNumber
NSString * const key_DCHImageTurbo_UIImage_ResizeScale = @"key_DCHImageTurbo_UIImage_ResizeScale";  // NSNumber
NSString * const key_DCHImageTurbo_UIImage_CornerRadius = @"key_DCHImageTurbo_UIImage_CornerRadius";  // NSNumber
NSString * const key_DCHImageTurbo_UIImage_BorderColor = @"key_DCHImageTurbo_UIImage_BorderColor";  // UIColor
NSString * const key_DCHImageTurbo_UIImage_BorderWidth = @"key_DCHImageTurbo_UIImage_BorderWidth";  // NSNumber
NSString * const key_DCHImageTurbo_UIImage_BlurEdgeInsets = @"key_DCHImageTurbo_UIImage_BlurEdgeInsets";  // NSValue(UIEdgeInsets)
NSString * const key_DCHImageTurbo_UIImage_BlurRadius = @"key_DCHImageTurbo_UIImage_BlurRadius";  // NSNumber
NSString * const key_DCHImageTurbo_UIImage_BlurTintColor = @"key_DCHImageTurbo_UIImage_BlurTintColor";  // UIColor
NSString * const key_DCHImageTurbo_UIImage_BlurSaturationDeltaFactor = @"key_DCHImageTurbo_UIImage_BlurSaturationDeltaFactor";  // NSNumber
NSString * const key_DCHImageTurbo_UIImage_BlurMaskImage = @"key_DCHImageTurbo_UIImage_BlurMaskImage";  // UIImage

@implementation UIImage (DCHImageTurbo)

+ (instancetype)dch_customizeImage:(UIImage *)image withParams:(NSDictionary *)paramsDic contentMode:(UIViewContentMode)contentMode {
    UIImage *result = image;
    do {
        if (DCH_IsEmpty(image) || DCH_IsEmpty(paramsDic)) {
            break;
        }
        NSNumber *resizeWidth = [paramsDic dch_safe_objectForKey:key_DCHImageTurbo_UIImage_ResizeWidth];
        NSNumber *resizeHeight = [paramsDic dch_safe_objectForKey:key_DCHImageTurbo_UIImage_ResizeHeight];
        NSNumber *resizeScale = [paramsDic dch_safe_objectForKey:key_DCHImageTurbo_UIImage_ResizeScale];

        NSNumber *cornerRadius = [paramsDic dch_safe_objectForKey:key_DCHImageTurbo_UIImage_CornerRadius];

        NSNumber *borderWidth = [paramsDic dch_safe_objectForKey:key_DCHImageTurbo_UIImage_BorderWidth];
        UIColor *borderColor = [paramsDic dch_safe_objectForKey:key_DCHImageTurbo_UIImage_BorderColor];

        NSValue *blurEdgeInsetsValue = [paramsDic dch_safe_objectForKey:key_DCHImageTurbo_UIImage_BlurEdgeInsets];
        NSNumber *blurRadius = [paramsDic dch_safe_objectForKey:key_DCHImageTurbo_UIImage_BlurRadius];
        UIColor *blurTintColor = [paramsDic dch_safe_objectForKey:key_DCHImageTurbo_UIImage_BlurTintColor];
        NSNumber *blurSaturationDeltaFactor = [paramsDic dch_safe_objectForKey:key_DCHImageTurbo_UIImage_BlurSaturationDeltaFactor];
        UIImage *blurMaskImage = [paramsDic dch_safe_objectForKey:key_DCHImageTurbo_UIImage_BlurMaskImage];

        CGSize targetSize = image.size;
        CGFloat scale = image.scale;

        // Resize
        if (!DCH_IsEmpty(resizeWidth) && !DCH_IsEmpty(resizeHeight) && !DCH_IsEmpty(resizeScale)) {
            CGSize size = CGSizeMake(resizeWidth.floatValue, resizeHeight.floatValue);
            if (!CGSizeEqualToSize(size, CGSizeZero)) {
                targetSize = CGSizeMake(resizeWidth.floatValue, resizeHeight.floatValue);
                scale = resizeScale.floatValue;
            }
        }

        UIGraphicsBeginImageContextWithOptions(targetSize, NO, scale);
        CGContextRef context1 = UIGraphicsGetCurrentContext();
        CALayer *layer1 = [CALayer layer];
        layer1.frame = (CGRect){CGPointZero, targetSize};
        layer1.contentsGravity = [UIImage dch_layerContentsGravityFromViewContentMode:contentMode];
        layer1.contents = (__bridge id)(image.CGImage);
        [layer1 renderInContext:context1];
        result = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();

        // Blur
        if (!DCH_IsEmpty(blurRadius) && !DCH_IsEmpty(blurTintColor) && !DCH_IsEmpty(blurSaturationDeltaFactor)) {
            if (DCH_IsEmpty(blurEdgeInsetsValue)) {
                result = [UIImage dch_applyBlur:result withRadius:blurRadius.floatValue tintColor:blurTintColor saturationDeltaFactor:blurSaturationDeltaFactor.floatValue maskImage:blurMaskImage];
            } else {
                UIEdgeInsets edgeInsets = [blurEdgeInsetsValue UIEdgeInsetsValue];
                result = [UIImage dch_applyBlur:result forEdgeInsets:edgeInsets withRadius:blurRadius.floatValue tintColor:blurTintColor saturationDeltaFactor:blurSaturationDeltaFactor.floatValue maskImage:blurMaskImage didCancel:nil];
            }

        }

        // Corner and Border
        UIGraphicsBeginImageContextWithOptions(targetSize, NO, scale);
        CGContextRef context2 = UIGraphicsGetCurrentContext();
        CALayer *layer2 = [CALayer layer];
        layer2.frame = (CGRect){CGPointZero, targetSize};
        layer2.contentsGravity = [UIImage dch_layerContentsGravityFromViewContentMode:contentMode];
        layer2.contents = (__bridge id)(result.CGImage);
        if (!DCH_IsEmpty(cornerRadius)) {
            layer2.cornerRadius = cornerRadius.floatValue;
        }
        if (!DCH_IsEmpty(borderWidth) && !DCH_IsEmpty(borderColor)) {
            layer2.borderWidth = borderWidth.floatValue;
            layer2.borderColor = borderColor.CGColor;
        }
        layer2.masksToBounds = YES;
        [layer2 renderInContext:context2];
        result = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    } while (NO);
    return result;
}

+ (NSString *)dch_layerContentsGravityFromViewContentMode:(UIViewContentMode)viewContentMode {
    NSString *result = kCAGravityResize;
    switch (viewContentMode) {
        case UIViewContentModeCenter: {
            result = kCAGravityCenter;
        }
            break;
        case UIViewContentModeTop: {
            result = kCAGravityTop;
        }
            break;
        case UIViewContentModeBottom: {
            result = kCAGravityBottom;
        }
            break;
        case UIViewContentModeLeft: {
            result = kCAGravityLeft;
        }
            break;
        case UIViewContentModeRight: {
            result = kCAGravityRight;
        }
            break;
        case UIViewContentModeTopLeft: {
            result = kCAGravityTopLeft;
        }
            break;
        case UIViewContentModeTopRight: {
            result = kCAGravityRight;
        }
            break;
        case UIViewContentModeBottomLeft:
            result = kCAGravityBottomLeft;
            break;
        case UIViewContentModeBottomRight: {
            result = kCAGravityBottomRight;
        }
            break;
        case UIViewContentModeScaleAspectFit: {
            result = kCAGravityResizeAspect;
        }
            break;
        case UIViewContentModeScaleAspectFill: {
            result = kCAGravityResizeAspectFill;
        }
            break;
        case UIViewContentModeScaleToFill:
        default: {
            result = kCAGravityResize;
        }
            break;
    }
    return result;
}

+ (NSString *)dch_imageSignature:(NSDictionary *)dic {
    NSString *result = nil;
    do {
        if (DCH_IsEmpty(dic)) {
            break;
        }

        NSMutableString *tmp = [NSMutableString string];
        NSNumber *resizeWidth = [dic objectForKey:key_DCHImageTurbo_UIImage_ResizeWidth];
        NSNumber *resizeHeight = [dic objectForKey:key_DCHImageTurbo_UIImage_ResizeHeight];
        NSNumber *resizeScale = [dic objectForKey:key_DCHImageTurbo_UIImage_ResizeScale];
        if (resizeWidth && resizeHeight && resizeScale) {
            [tmp appendFormat:@"ResizeW%fH%fS%f", [resizeWidth floatValue], [resizeHeight floatValue], [resizeScale floatValue]];
        }

        NSNumber *cornerRadius = [dic objectForKey:key_DCHImageTurbo_UIImage_CornerRadius];
        if (cornerRadius) {
            [tmp appendFormat:@"CornerRadius%f", [cornerRadius floatValue]];
        }

        UIColor *borderColor = [dic objectForKey:key_DCHImageTurbo_UIImage_BorderColor];
        NSNumber *borderWidth = [dic objectForKey:key_DCHImageTurbo_UIImage_BorderWidth];
        if (borderColor && borderWidth) {
            CGFloat components[4] = {0.0, 0.0, 0.0, 0.0};
            [borderColor getRed:&components[0] green:&components[1] blue:&components[2] alpha:&components[3]];
            [tmp appendFormat:@"BorderColorR%fG:%fB:%fA:%fWidth%f", components[0], components[1], components[2], components[3], [borderWidth floatValue]];
        }

        NSValue *blurEdgeInsetsValue = [dic objectForKey:key_DCHImageTurbo_UIImage_BlurEdgeInsets];
        UIColor *blurTintColor = [dic objectForKey:key_DCHImageTurbo_UIImage_BlurTintColor];
        NSNumber *blurRadius = [dic objectForKey:key_DCHImageTurbo_UIImage_BlurRadius];
        NSNumber *blurSaturationDeltaFactor = [dic objectForKey:key_DCHImageTurbo_UIImage_BlurSaturationDeltaFactor];
        NSUInteger blurMaskImageHash = [[dic objectForKey:key_DCHImageTurbo_UIImage_BlurMaskImage] hash];
        if (blurTintColor && blurRadius && blurSaturationDeltaFactor) {
            CGFloat components[4] = {0.0, 0.0, 0.0, 0.0};
            [blurTintColor getRed:&components[0] green:&components[1] blue:&components[2] alpha:&components[3]];
            [tmp appendFormat:@"BlurColorR%fG:%fB:%fA:%fRadius%fSaturationDeltaFactor%fMaskImageHash%lu", components[0], components[1], components[2], components[3], [blurRadius floatValue], [blurSaturationDeltaFactor floatValue], (unsigned long)blurMaskImageHash];
            if (blurEdgeInsetsValue) {
                UIEdgeInsets edgeInsets = [blurEdgeInsetsValue UIEdgeInsetsValue];
                [tmp appendFormat:@"RatioRectT%fB%fL%fR%f", edgeInsets.top, edgeInsets.bottom, edgeInsets.left, edgeInsets.right];
            }
        }

        result = [tmp dch_md5String];
    } while (NO);
    return result;
}

@end


text:
<!doctype html>

<title>Sai Karthik Karra</title>
<meta name="description" content="Sai Karthik">
<meta name="keywords" content="sai karthik, kskarthik, karra">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" type="text/css" href="bootstrap.min.css"/>
<link rel="stylesheet" type="text/css" href="main.css"/>

Sai Karthik

Web Developer

I'm an avid supporter of free software & actively involved in
various open source projects which include, But not only limited to Firefox, Sailfish OS, AppImage, OpenSUSE.
My skills include Linux system administration, Front end web designing, Javascript, Wordpress, Git, Bash, Python, SEO.
I evangelize on online privacy, Encryption, Blockchain technology.

Projects

 Proton+: A firefox add-on which unlocks a few premium features for free protonmail account

 Hardware adaptation of SailfishOS for Mozilla flame

 Hardware adaptation of postmarketOS for Sony Xperia Z3C

Status


text:
layout: post
date: 2011-05-06
time: "09:00:00"
author: "Greg Wilson"
title: The Architecture of Open Source Applications
category: ["Noticed"]
---

My apologies for how quiet this site has been recently—finding a new job takes time [1], and we had to make one final push on the other project I've been working on.  But I'm pleased to announce that The Architecture of Open Source Applications is now at the printer's—we're going to give the first copy a final going-over, then make it available for purchase (hopefully within two weeks). I'm very pleased with how it looks, and very grateful to my co-editor Amy Brown, the contributors, and the reviewers for all their hard work.

One note, though: if and when you buy it, please buy it directly from Lulu.com, rather than through Amazon or another outlet—it makes an enormous difference to how much money we raise for charity:

You buy from:

Lulu

Amazon

You pay:

$35.00

$35.00

Lulu gets:

$3.74

$0.94

Amazon gets:

$0.00

$17.50

Amnesty gets:

$14.98

$3.78


text:
#pragma once
#include <aws/elasticmapreduce/EMR_EXPORTS.h>
#include <aws/elasticmapreduce/model/ComputeLimitsUnitType.h>
#include <utility>

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

  /**
   *
 The EC2 unit limits for a managed scaling policy. The managed scaling
   * activity of a cluster can not be above or below these limits. The limit only
   * applies to the core and task nodes. The master node cannot be scaled after
   * initial configuration.

See Also:
   AWS
   * API Reference

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

    /**
     *
 The unit type used for specifying a managed scaling policy.

     */
    inline const ComputeLimitsUnitType& GetUnitType() const{ return m_unitType; }

    /**
     *
 The unit type used for specifying a managed scaling policy.

     */
    inline bool UnitTypeHasBeenSet() const { return m_unitTypeHasBeenSet; }

    /**
     *
 The unit type used for specifying a managed scaling policy.

     */
    inline void SetUnitType(const ComputeLimitsUnitType& value) { m_unitTypeHasBeenSet = true; m_unitType = value; }

    /**
     *
 The unit type used for specifying a managed scaling policy.

     */
    inline void SetUnitType(ComputeLimitsUnitType&& value) { m_unitTypeHasBeenSet = true; m_unitType = std::move(value); }

    /**
     *
 The unit type used for specifying a managed scaling policy.

     */
    inline ComputeLimits& WithUnitType(const ComputeLimitsUnitType& value) { SetUnitType(value); return *this;}

    /**
     *
 The unit type used for specifying a managed scaling policy.

     */
    inline ComputeLimits& WithUnitType(ComputeLimitsUnitType&& value) { SetUnitType(std::move(value)); return *this;}

    /**
     *
 The lower boundary of EC2 units. It is measured through vCPU cores or
     * instances for instance groups and measured through units for instance fleets.
     * Managed scaling activities are not allowed beyond this boundary. The limit only
     * applies to the core and task nodes. The master node cannot be scaled after
     * initial configuration.

     */
    inline int GetMinimumCapacityUnits() const{ return m_minimumCapacityUnits; }

    /**
     *
 The lower boundary of EC2 units. It is measured through vCPU cores or
     * instances for instance groups and measured through units for instance fleets.
     * Managed scaling activities are not allowed beyond this boundary. The limit only
     * applies to the core and task nodes. The master node cannot be scaled after
     * initial configuration.

     */
    inline bool MinimumCapacityUnitsHasBeenSet() const { return m_minimumCapacityUnitsHasBeenSet; }

    /**
     *
 The lower boundary of EC2 units. It is measured through vCPU cores or
     * instances for instance groups and measured through units for instance fleets.
     * Managed scaling activities are not allowed beyond this boundary. The limit only
     * applies to the core and task nodes. The master node cannot be scaled after
     * initial configuration.

     */
    inline void SetMinimumCapacityUnits(int value) { m_minimumCapacityUnitsHasBeenSet = true; m_minimumCapacityUnits = value; }

    /**
     *
 The lower boundary of EC2 units. It is measured through vCPU cores or
     * instances for instance groups and measured through units for instance fleets.
     * Managed scaling activities are not allowed beyond this boundary. The limit only
     * applies to the core and task nodes. The master node cannot be scaled after
     * initial configuration.

     */
    inline ComputeLimits& WithMinimumCapacityUnits(int value) { SetMinimumCapacityUnits(value); return *this;}

    /**
     *
 The upper boundary of EC2 units. It is measured through vCPU cores or
     * instances for instance groups and measured through units for instance fleets.
     * Managed scaling activities are not allowed beyond this boundary. The limit only
     * applies to the core and task nodes. The master node cannot be scaled after
     * initial configuration.

     */
    inline int GetMaximumCapacityUnits() const{ return m_maximumCapacityUnits; }

    /**
     *
 The upper boundary of EC2 units. It is measured through vCPU cores or
     * instances for instance groups and measured through units for instance fleets.
     * Managed scaling activities are not allowed beyond this boundary. The limit only
     * applies to the core and task nodes. The master node cannot be scaled after
     * initial configuration.

     */
    inline bool MaximumCapacityUnitsHasBeenSet() const { return m_maximumCapacityUnitsHasBeenSet; }

    /**
     *
 The upper boundary of EC2 units. It is measured through vCPU cores or
     * instances for instance groups and measured through units for instance fleets.
     * Managed scaling activities are not allowed beyond this boundary. The limit only
     * applies to the core and task nodes. The master node cannot be scaled after
     * initial configuration.

     */
    inline void SetMaximumCapacityUnits(int value) { m_maximumCapacityUnitsHasBeenSet = true; m_maximumCapacityUnits = value; }

    /**
     *
 The upper boundary of EC2 units. It is measured through vCPU cores or
     * instances for instance groups and measured through units for instance fleets.
     * Managed scaling activities are not allowed beyond this boundary. The limit only
     * applies to the core and task nodes. The master node cannot be scaled after
     * initial configuration.

     */
    inline ComputeLimits& WithMaximumCapacityUnits(int value) { SetMaximumCapacityUnits(value); return *this;}

    /**
     *
 The upper boundary of On-Demand EC2 units. It is measured through vCPU cores
     * or instances for instance groups and measured through units for instance fleets.
     * The On-Demand units are not allowed to scale beyond this boundary. The parameter
     * is used to split capacity allocation between On-Demand and Spot Instances.

     */
    inline int GetMaximumOnDemandCapacityUnits() const{ return m_maximumOnDemandCapacityUnits; }

    /**
     *
 The upper boundary of On-Demand EC2 units. It is measured through vCPU cores
     * or instances for instance groups and measured through units for instance fleets.
     * The On-Demand units are not allowed to scale beyond this boundary. The parameter
     * is used to split capacity allocation between On-Demand and Spot Instances.

     */
    inline bool MaximumOnDemandCapacityUnitsHasBeenSet() const { return m_maximumOnDemandCapacityUnitsHasBeenSet; }

    /**
     *
 The upper boundary of On-Demand EC2 units. It is measured through vCPU cores
     * or instances for instance groups and measured through units for instance fleets.
     * The On-Demand units are not allowed to scale beyond this boundary. The parameter
     * is used to split capacity allocation between On-Demand and Spot Instances.

     */
    inline void SetMaximumOnDemandCapacityUnits(int value) { m_maximumOnDemandCapacityUnitsHasBeenSet = true; m_maximumOnDemandCapacityUnits = value; }

    /**
     *
 The upper boundary of On-Demand EC2 units. It is measured through vCPU cores
     * or instances for instance groups and measured through units for instance fleets.
     * The On-Demand units are not allowed to scale beyond this boundary. The parameter
     * is used to split capacity allocation between On-Demand and Spot Instances.

     */
    inline ComputeLimits& WithMaximumOnDemandCapacityUnits(int value) { SetMaximumOnDemandCapacityUnits(value); return *this;}

    /**
     *
 The upper boundary of EC2 units for core node type in a cluster. It is
     * measured through vCPU cores or instances for instance groups and measured
     * through units for instance fleets. The core units are not allowed to scale
     * beyond this boundary. The parameter is used to split capacity allocation between
     * core and task nodes.

     */
    inline int GetMaximumCoreCapacityUnits() const{ return m_maximumCoreCapacityUnits; }

    /**
     *
 The upper boundary of EC2 units for core node type in a cluster. It is
     * measured through vCPU cores or instances for instance groups and measured
     * through units for instance fleets. The core units are not allowed to scale
     * beyond this boundary. The parameter is used to split capacity allocation between
     * core and task nodes.

     */
    inline bool MaximumCoreCapacityUnitsHasBeenSet() const { return m_maximumCoreCapacityUnitsHasBeenSet; }

    /**
     *
 The upper boundary of EC2 units for core node type in a cluster. It is
     * measured through vCPU cores or instances for instance groups and measured
     * through units for instance fleets. The core units are not allowed to scale
     * beyond this boundary. The parameter is used to split capacity allocation between
     * core and task nodes.

     */
    inline void SetMaximumCoreCapacityUnits(int value) { m_maximumCoreCapacityUnitsHasBeenSet = true; m_maximumCoreCapacityUnits = value; }

    /**
     *
 The upper boundary of EC2 units for core node type in a cluster. It is
     * measured through vCPU cores or instances for instance groups and measured
     * through units for instance fleets. The core units are not allowed to scale
     * beyond this boundary. The parameter is used to split capacity allocation between
     * core and task nodes.

     */
    inline ComputeLimits& WithMaximumCoreCapacityUnits(int value) { SetMaximumCoreCapacityUnits(value); return *this;}

  private:

    ComputeLimitsUnitType m_unitType;
    bool m_unitTypeHasBeenSet;

    int m_minimumCapacityUnits;
    bool m_minimumCapacityUnitsHasBeenSet;

    int m_maximumCapacityUnits;
    bool m_maximumCapacityUnitsHasBeenSet;

    int m_maximumOnDemandCapacityUnits;
    bool m_maximumOnDemandCapacityUnitsHasBeenSet;

    int m_maximumCoreCapacityUnits;
    bool m_maximumCoreCapacityUnitsHasBeenSet;
  };

} // namespace Model
} // namespace EMR
} // namespace Aws


text:
<?php
namespace Owja\ImageProxyBundle\Service;

use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;

use League\Flysystem\FileNotFoundException;
use League\Flysystem\FilesystemInterface;

use Owja\ImageProxyBundle\Exception\ConfigurationException;
use Owja\ImageProxyBundle\Exception\NotFoundException;
use Owja\ImageProxyBundle\Exception\ProcessingException;

use Symfony\Component\HttpFoundation\Response as SymfonyResponse;
use Symfony\Component\HttpFoundation\Request as SymfonyRequest;

class Proxy
{
    /**
     * @var int
     */
    private $timeout;

    /**
     * @var string
     */
    private $namespace = 'default';

    /**
     * @var string
     */
    private $token;

    /**
     * @var FilesystemInterface
     */
    private $filesystem;

    /**
     * @var Process
     */
    private $processor;

    /**
     * @var string
     */
    protected $processType = Process::RESIZE;

    /**
     * @var int
     */
    protected $height;

    /**
     * @var int
     */
    protected $width;

    /**
     * @var string
     */
    protected $url;

    /**
     * @var string
     */
    protected $original;

    /**
     * @var string
     */
    protected $processed;

    /**
     * @var string
     */
    protected $originalFile;

    /**
     * @var string
     */
    protected $processedFile;

    /**
     * @var array
     */
    protected $allowedMimeTypes = [
        'image/png',
        'image/jpeg',
        'image/gif',
    ];

    /**
     * Constructor
     *
     * @param FilesystemInterface   $filesystem
     * @param Process               $processor
     * @param int                   $timeout
     */
    public function __construct(FilesystemInterface $filesystem, Process $processor, int $timeout = 10)
    {
        $this->filesystem   = $filesystem;
        $this->processor    = $processor;
        $this->timeout      = $timeout ?: 10;
    }

    /**
     * Set namespace
     *
     * @param   string  $namespace
     * @return  Proxy
     * @throws  ConfigurationException
     */
    public function setNamespace(string $namespace) : Proxy
    {
        if (empty($namespace)) {
            throw new ConfigurationException('Namespace not defined.');
        }

        $this->namespace = $namespace;

        $this->reset(true);
        $this->reset(false);

        return $this;
    }

    /**
     * Set token header
     *
     * @param   string|null $token
     * @return  Proxy
     */
    public function setToken(string $token = null) : Proxy
    {
        $this->token = empty($token) ? null : $token;
        return $this;
    }

    /**
     * Set remote url
     *
     * @param   string $url
     * @return  Proxy
     */
    public function setUrl(string $url) : Proxy
    {
        $this->url = $url;

        $this->reset(true);
        $this->reset(false);

        return $this;
    }

    /**
     * Set image width
     *
     * @param   int|null $width
     * @return  Proxy
     */
    public function setWidth(int $width = null) : Proxy
    {
        $this->width = $width ?: 0;
        $this->processor->setWidth($this->width);

        $this->reset(false);

        return $this;
    }

    /**
     * Set image height
     *
     * @param   int|null $height
     * @return  Proxy
     */
    public function setHeight(int $height = null) : Proxy
    {
        $this->height = $height ?: 0;
        $this->processor->setHeight($this->height);

        $this->reset(false);

        return $this;
    }

    /**
     * Set image process type
     *
     * @param   string|null $type
     * @return  Proxy
     */
    public function setProcessType(string $type = null) : Proxy
    {
        switch ($type) {
            case Process::CROP:
                $this->processType = Process::CROP;
                break;
            default:
                $this->processType = Process::RESIZE;
                break;
        }

        $this->processor->setType($this->processType);

        $this->reset(false);

        return $this;
    }

    /**
     * Get mime type of image
     *
     * @return string
     */
    public function getMimeType() : string
    {
        $this->loadImage();
        return $this->filesystem->getMimetype($this->getPath(false));
    }

    /**
     * Get modified of image
     *
     * @return string
     */
    public function getTimestamp() : string
    {
        $this->loadImage();
        return $this->filesystem->getTimestamp($this->getPath(false));
    }

    /**
     * Get cache tag
     *
     * @return string
     */
    public function getCacheTag() : string
    {
        $this->loadImage();
        return md5($this->processed);
    }

    /**
     * Get image blob
     *
     * @return string
     */
    public function getContent() : string
    {
        $this->loadImage();
        return $this->processed;
    }

    /**
     * Create Response
     *
     * @param SymfonyRequest $request
     * @return SymfonyResponse
     */
    public function createResponse(SymfonyRequest $request = null)
    {
        $response = new SymfonyResponse($this->getContent(), 200, [
            'Content-Type' => $this->getMimeType()
        ]);

        $response->setPublic();
        $response->setExpires(new \DateTime('now +7 days'));
        $response->setEtag($this->getCacheTag());

        if ($request !== null) {
            $response->isNotModified($request);
        }

        return $response;
    }

    /**
     * Clean Image Cache
     */
    public function cleanImageCache()
    {
        foreach ($this->filesystem->listContents() as $item)
        {
            if ($item['type'] === 'dir') {
                $this->filesystem->deleteDir($item['path']);
            }
        }
    }

    /**
     * Load image
     */
    protected function loadImage()
    {
        $this->loadProcessed()
        || ( $this->loadOriginal() && $this->process() );
    }

    /**
     * Load processed image from filesystem
     *
     * @return bool
     */
    protected function loadProcessed() : bool
    {
        if ($this->processed) {
            return true;
        }

        try {
            $this->processed = $this->filesystem->read($this->getPath(false));
            return true;
        } catch (FileNotFoundException $e) {
            $this->processed = null;
            return false;
        }
    }

    /**
     * Load original image
     * @return bool
     * @throws NotFoundException
     * @throws ProcessingException
     */
    protected function loadOriginal() : bool
    {
        $path = $this->getPath(true);

        try {
            $this->original = $this->filesystem->read($path);
            return true;
        } catch (FileNotFoundException $e) {
            $this->original = null;
        }

        $headers =  [
            'Accept' => implode(', ', $this->allowedMimeTypes),
            'User-Agent' => "OWJA!bot ImageProxy"
        ];

        if ($this->token) {
            $headers['owja-image-proxy'] = $this->token;
        }

        try {
            $client = new Client([ 'headers' => $headers ]);
            $request = new Request('GET', $this->url);

            $response = $client->send($request, [
                'timeout' => $this->timeout
            ] );

            $content = (string) $response->getBody();

        } catch (\Exception $e) {
            throw new NotFoundException('Could not load image from URL.', 404, $e);
        }

        if (empty($response->getHeader('Content-Type'))
            || !in_array($response->getHeader('Content-Type')[0], $this->allowedMimeTypes)) {
            throw new ProcessingException('File ist not a Image of type png, jpeg or gif.', 500, $e);
        }

        $this->original = $content;
        $this->filesystem->write($path, $content);

        return true;
    }

    /**
     * Process image
     *
     * @return bool
     */
    protected function process() : bool
    {
        $this->processed = $this->processor->processContent($this->original);
        $this->filesystem->write($this->getPath(false), $this->processed);

        return true;
    }

    /**
     * Get image path
     *
     * @param bool $original
     * @return string
     */
    protected function getPath(bool $original = false) : string
    {
        if ($original && $this->originalFile) {
            return $this->originalFile;
        } else if (!$original && $this->processedFile) {
            return $this->processedFile;
        }

        $path  = $this->namespace . DIRECTORY_SEPARATOR;

        if ($original) {
            $path .= 'original' . DIRECTORY_SEPARATOR;
            $path .= md5($this->url);
            $this->originalFile = $path;
        } else {
            $path .= $this->processType . DIRECTORY_SEPARATOR;
            $path .= $this->width . 'x' . $this->height . DIRECTORY_SEPARATOR;
            $path .= md5($this->url);
            $this->processedFile = $path;
        }

        return $path;
    }

    /**
     * Reset
     *
     * @param bool $original
     */
    protected function reset(bool $original)
    {
        if ($original) {
            $this->originalFile  = null;
            $this->original      = null;
        } else {
            $this->processedFile = null;
            $this->processed     = null;
        }
    }
}


text:
"""Constrained Optimization By Linear Approximation optimizer."""

from typing import Optional

from .scipy_optimizer import SciPyOptimizer

class COBYLA(SciPyOptimizer):
    """
    Constrained Optimization By Linear Approximation optimizer.

    COBYLA is a numerical optimization method for constrained problems
    where the derivative of the objective function is not known.

    Uses scipy.optimize.minimize COBYLA.
    For further detail, please refer to
    https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize.html
    """

    _OPTIONS = ["maxiter", "disp", "rhobeg"]

    # pylint: disable=unused-argument
    def __init__(
        self,
        maxiter: int = 1000,
        disp: bool = False,
        rhobeg: float = 1.0,
        tol: Optional[float] = None,
        options: Optional[dict] = None,
        **kwargs,
    ) -> None:
        """
        Args:
            maxiter: Maximum number of function evaluations.
            disp: Set to True to print convergence messages.
            rhobeg: Reasonable initial changes to the variables.
            tol: Final accuracy in the optimization (not precisely guaranteed).
                 This is a lower bound on the size of the trust region.
            options: A dictionary of solver options.
            kwargs: additional kwargs for scipy.optimize.minimize.
        """
        if options is None:
            options = {}
        for k, v in list(locals().items()):
            if k in self._OPTIONS:
                options[k] = v
        super().__init__(method="COBYLA", options=options, tol=tol, **kwargs)


text:
<form action="<?php echo base_url("pdi-save"); ?>" class="form-horizontal row-border" id="frmkwitansidp" method="post" enctype="multipart/form-data" parsley-validate novalidate>

Pre Delivery Inspection

                            No Sales Order

                                <input style="text-transform: uppercase;" class="typeahead form-control" parsley-trigger="change" required name="noso" id="noso" type="text" placeholder="Type No Sales Order">

                            Nama

                                <input type="text" readonly="true" name="nama" id="nama" parsley-trigger="change" required placeholder="Nama Customer" class="form-control">

                            Tanggal SO

                                <input type="text" readonly="true" name="tanggal" id="tanggal" parsley-trigger="change"     placeholder="Tanggal" class="form-control">

                            Tanggal PDI

                                <input type="text" name="tgl_pdi" required="true" id="tgl_pdi" parsley-trigger="change" value="<?php echo date('Y-m-d'); ?>"   placeholder="Tanggal PDI" class="form-control datepicker">

                            PIC

                                <input type="text" name="pic" id="pic" parsley-trigger="change" required="true" placeholder="Input PIC" class="form-control">

                            Tipe

                                <input type="text" name="tipe" readonly="true" id="type" parsley-trigger="change" required placeholder="Tipe" class="form-control">

                            No. Mesin

                                <input type="text" readonly="true" name="no_mesin" id="no_mesin" parsley-trigger="change"     placeholder="No. Mesin" class="form-control">

                            No. Rangka

                                <input type="text" readonly="true" name="no_rangka" id="no_rangka" parsley-trigger="change"     placeholder="No. Rangka" class="form-control">

                            Warna

                                <input type="text" readonly="true" name="warna" id="warna" parsley-trigger="change" required   placeholder="Warna" class="form-control">

                            No. PDI

                                <input type="hidden" readonly="true" name="nosj" id="nosj" parsley-trigger="change" required   value="<?php echo $codesj; ?>" class="form-control">
                                <input type="text" readonly="true" name="kdpdi" id="no_pdi" parsley-trigger="change" required   value="<?php echo $codepdi; ?>" class="form-control">

                            Gudang

                                <select name="gudang_id" id="gudang_id"  onchange="getAccessories(this.value);" parsley-trigger="change" required class="form-control">
                                    <option value="" selected="true" disabled="true">-- Pilih Gudang--</option>
                                    <?php foreach ($gudang as $kGudang => $vGudang) { ?>
                                        <option value="<?php echo $vGudang['id']; ?>"><?php echo $vGudang['gudang']; ?></option>
                                    <?php } ?>
                                </select>

Cek List Accessories

                             Aksesories
                             Kode

                             Aki

                                <select name="aksesoris[]" id="aki" class="form-control">
                                    <option value=""> </option>
                                </select>

                             Spion

                                <select name="aksesoris[]" id="spion" class="form-control">
                                    <option value=""> </option>
                                </select>

                             Toolkit

                                <select name="aksesoris[]" id="toolkit" class="form-control">
                                    <option value=""> </option>
                                </select>

                             Helm

                                <select name="aksesoris[]" id="helm" class="form-control">
                                    <option value=""> </option>
                                </select>

                             Buku Pedoman Pemilik

                                Available

                             Kertas Gesekan Polda

                                Available

                            Rumah Plat

                                <select name="aksesoris[]" id="rumah_plat" class="form-control">
                                    <option value=""> </option>
                                </select>

                            Jacket

                                <select name="aksesoris[]" id="jacket" class="form-control">
                                    <option value=""> </option>
                                </select>

                            Jas Hujan

                                <select name="aksesoris[]" id="jas_hujan" class="form-control">
                                    <option value=""> </option>
                                </select>

                            <button type="submit" name="save" id="save" class="btn btn-primary">Save</button>
                            <a href="<?php echo base_url('pdi');?>" class="btn btn-warning">Cancel

</form>


text:
package main

import (
	"bufio"
	"encoding/json"
	"log"
	"os"
)

// requestDetails stores information about request, it's used for creating unique hash and also as a payload structure
type requestDetails struct {
	Path        string `json:"path"`
	Method      string `json:"method"`
	Destination string `json:"destination"`
	Query       string `json:"query"`
}

// res structure hold response body from external service, body is not decoded and is supposed
// to be bytes, however headers should provide all required information for later decoding
// by the client.
type responseDetails struct {
	Status  int                 `json:"status"`
	Body    string              `json:"body"`
	Headers map[string][]string `json:"headers"`
}

// Payload structure holds request and response structure
type Payload struct {
	Response responseDetails `json:"response"`
	Request  requestDetails  `json:"request"`
	ID       string          `json:"id"`
}

func main() {
	// logging to stderr
	l := log.New(os.Stderr, "", 0)

	s := bufio.NewScanner(os.Stdin)
	for s.Scan() {

		var payload Payload

		err := json.Unmarshal(s.Bytes(), &payload)
		if err != nil {
			l.Println("Failed to unmarshal payload from hoverfly")
		}

		newHeaders := make(map[string][]string)

		vals := []string{"changed response"}

		newHeaders["middleware"] = vals

		payload.Response.Status = 404
		payload.Response.Body = "Custom body here"
		payload.Response.Headers = newHeaders

		bts, err := json.Marshal(payload)
		if err != nil {
			l.Println("Failed to marshal new payload")
		}
		os.Stdout.Write(bts)

	}
}


text:
<?php

namespace Eloqua\Api\Soap\ExternalActionService;

class ExternalActionStatus {

    const __default = 'AwaitingAction';
    const AwaitingAction = 'AwaitingAction';
    const InProgress = 'InProgress';
    const Complete = 'Complete';

}


text:
import json
import os
f = open('city.list.json', 'r')
saveFileName = 'sorted_CN_city.txt'
dic = {}
for line in f:
	if '"CN"' in line:
		j = json.loads(line)
		key = j["name"]
		dic[key] = line

dict = sorted(dic.iteritems(), key=lambda d:d[0])

for fileName in os.listdir(os.getcwd()):
	if fileName == saveFileName:
		os.remove(fileName)

g = open(saveFileName, 'w')
for item in dict:
	g.write(item[1])
g.close()
f.close()


text:
from google.appengine.ext import ndb
from flask import Blueprint, request
from utilities import response, get_form, Date
from entities.user import User
from entities.audit import Purchase, Exchange, Earn, Consume
from api import *
from datetime import datetime

audit_api = Blueprint('audit', __name__, url_prefix='/api/audit')

@audit_api.route('/sync/', methods=['POST'])
def sync():
    from main import app

    data = request.json
    app.logger.debug('Received sync data: %s' % data)

    user = User.get(data['uuid'])
    sync_history(user.key, data['version'], data['history'])
    last_purchase, last_exchange, last_earn, last_consume = get_last_sync_timestamp(user.key)

    return response(purchase=last_purchase, exchange=last_exchange, earn=last_earn, consume=last_consume)

@audit_api.route('/purchase/', methods=['POST'])
def save_purchase():
    from main import app

    form = get_form(PurchaseForm(request.form))
    uuid, goods_id = form.uuid.data, form.goods_id.data
    user = User.get(uuid)
    app.logger.info('[%s] Purchased goods_id: %d' % (uuid, goods_id))
    Purchase(parent=user.key, goods_id=goods_id, version=form.version.data, date=datetime.fromtimestamp(int(form.date.data))).put()

    return response()

@audit_api.route('/exchange/', methods=['POST'])
def save_exchange():
    form = get_form(ExchangeForm(request.form))
    user = User.get(form.uuid.data)
    Exchange(parent=user.key, goods_id=form.goods_id.data, version=form.version.data, date=datetime.fromtimestamp(int(form.date.data))).put()

    return response()

@audit_api.route('/earn/', methods=['POST'])
def save_earn():
    form = get_form(EarnForm(request.form))
    user = User.get(form.uuid.data)
    Earn(parent=user.key, type_id=form.type_id.data, version=form.version.data, date=datetime.fromtimestamp(int(form.date.data))).put()

    return response()

@audit_api.route('/consume/', methods=['POST'])
def save_consume():
    form = get_form(ConsumeForm(request.form))
    user = User.get(form.uuid.data)
    Consume(parent=user.key, type_id=form.type_id.data, album=form.album.data, level=form.level.data, picture=form.picture.data,
            version=form.version.data, date=datetime.fromtimestamp(int(form.date.data))).put()

    return response()

@ndb.transactional()
def sync_history(user_key, version, history):
    from main import app

    last_purchase, last_exchange, last_earn, last_consume = get_last_sync_timestamp(user_key)
    purchases, exchanges, earns, consumes = history['purchase'], history['exchange'], history['earn'], history['consume']

    for purchase in purchases:
        if int(purchase['date'] / 1000) > last_purchase:
            app.logger.debug('Save new purchase: %s' % purchase)
            Purchase(parent=user_key, goods_id=purchase['goods'], version=version, date=Date.get_date_from_js_timestamp(purchase['date'])).put()

    for exchange in exchanges:
        if int(exchange['date'] / 1000) > last_exchange:
            app.logger.debug('Save new exchange: %s' % exchange)
            Exchange(parent=user_key, goods_id=exchange['goods'], version=version, date=Date.get_date_from_js_timestamp(exchange['date'])).put()

    for earn in earns:
        if int(earn['date'] / 1000) > last_earn:
            app.logger.debug('Save new earn: %s' % earn)
            Earn(parent=user_key, type_id=earn['type'], version=version, date=Date.get_date_from_js_timestamp(earn['date'])).put()

    for consume in consumes:
        if int(consume['date'] / 1000) > last_consume:
            app.logger.debug('Save new consume: %s' % consume)
            album = consume['album'] if 'album' in consume else None
            level = consume['level'] if 'level' in consume else None
            picture = consume['picture'] if 'picture' in consume else None
            Consume(parent=user_key, type_id=consume['type'], album=album, level=level, picture=picture, version=version,
                    date=Date.get_date_from_js_timestamp(consume['date'])).put()

def get_last_sync_timestamp(user_key):
    purchase = Purchase.get_last(user_key).fetch(1)
    exchange = Exchange.get_last(user_key).fetch(1)
    earn = Earn.get_last(user_key).fetch(1)
    consume = Consume.get_last(user_key).fetch(1)

    return (Date.get_timestamp(purchase[0].date) if purchase else None,
            Date.get_timestamp(exchange[0].date) if exchange else None,
            Date.get_timestamp(earn[0].date) if earn else None,
            Date.get_timestamp(consume[0].date) if consume else None)

class PurchaseForm(BaseForm):
    goods_id = IntegerField('goods_id', [validators.input_required()])
    version = StringField('version', [validators.length(min=3, max=5)])
    date = IntegerField('date', [validators.input_required()])

class ExchangeForm(BaseForm):
    goods_id = IntegerField('goods_id', [validators.input_required()])
    version = StringField('version', [validators.length(min=3, max=5)])
    date = IntegerField('date', [validators.input_required()])

class EarnForm(BaseForm):
    type_id = IntegerField('type_id', [validators.input_required()])
    version = StringField('version', [validators.length(min=3, max=5)])
    date = IntegerField('date', [validators.input_required()])

class ConsumeForm(BaseForm):
    type_id = IntegerField('type_id', [validators.input_required()])
    album = IntegerField('album', [validators.optional()])
    level = IntegerField('level', [validators.optional()])
    picture = IntegerField('picture', [validators.optional()])
    version = StringField('version', [validators.length(min=3, max=5)])
    date = IntegerField('date', [validators.input_required()])


text:
title:  "Честность в отношениях с Богом"
date:   10/02/2018
---

### Библейские тексты для исследования:
Лк. 16:10; Лев. 27:30; Быт. 22:1–12; Евр. 12:2; Лк. 11:42; Евр. 7:2–10; Неем. 13.

>
Памятный стих:

> «А упавшее на добрую землю, это те, которые, услышав слово, хранят его в добром и чистом сердце и приносят плод в терпении» (Лк. 8:15).

Что означает иметь «чистое сердце» (в других переводах — «честное сердце»)? В чем это проявляется? Современная культура рассматривает честность как некую неопределенную, относительную этическую категорию. Большинство людей проявляют нечестность время от времени, полагая, что в незначительном объеме она допустима. Также считается, что особые обстоятельства могут служить оправданием нечестности.

Истина и честность всегда идут рука об руку. Тем не менее мы не рождаемся со склонностью поступать честно. Это приобретаемая добродетель, и она лежит в основе морального облика управителя.

Проявление честности дает нам преимущества. Например, нет необходимости беспокоиться о том, что мы будем уличены во лжи, или же скрывать ее. Честность является ценным личностным качеством, особенно в трудных ситуациях, когда появляется искушение проявить нечестность.

На этой неделе мы будем изучать духовный принцип честности на примере практики приношения десятин и посмотрим, почему возвращение десятин столь важно для управителя и управления ресурсами.