text:
from rally.common import logging
from rally.plugins.openstack import scenario
from rally.plugins.openstack.services.identity import identity
from rally.task import validation

class KeystoneBasic(scenario.OpenStackScenario):
    """Base class for Keystone scenarios with initialized service object."""

    def __init__(self, context=None, admin_clients=None, clients=None):
        super(KeystoneBasic, self).__init__(context, admin_clients, clients)
        if hasattr(self, "_admin_clients"):
            self.admin_keystone = identity.Identity(
                self._admin_clients, name_generator=self.generate_random_name,
                atomic_inst=self.atomic_actions())
        if hasattr(self, "_clients"):
            self.keystone = identity.Identity(
                self._clients, name_generator=self.generate_random_name,
                atomic_inst=self.atomic_actions())

@validation.add("required_platform", platform="openstack", admin=True)
@scenario.configure(context={"admin_cleanup": ["keystone"]},
                    name="KeystoneBasic.create_user",
                    platform="openstack")
class CreateUser(KeystoneBasic):

    @logging.log_deprecated_args(
        "The 'name_length' argument to create_user is ignored",
        "0.1.2", ["name_length"], once=True)
    def run(self, name_length=10, **kwargs):
        """Create a keystone user with random name.

        :param kwargs: Other optional parameters to create users like
                         "tenant_id", "enabled".
        """
        self.admin_keystone.create_user(**kwargs)

@validation.add("required_platform", platform="openstack", admin=True)
@scenario.configure(context={"admin_cleanup": ["keystone"]},
                    name="KeystoneBasic.create_delete_user",
                    platform="openstack")
class CreateDeleteUser(KeystoneBasic):

    @logging.log_deprecated_args(
        "The 'name_length' argument to create_delete_user is ignored",
        "0.1.2", ["name_length"], once=True)
    def run(self, name_length=10, **kwargs):
        """Create a keystone user with random name and then delete it.

        :param kwargs: Other optional parameters to create users like
                         "tenant_id", "enabled".
        """
        user = self.admin_keystone.create_user(**kwargs)
        self.admin_keystone.delete_user(user.id)

@validation.add("required_platform", platform="openstack", admin=True)
@scenario.configure(context={"admin_cleanup": ["keystone"]},
                    name="KeystoneBasic.create_user_set_enabled_and_delete",
                    platform="openstack")
class CreateUserSetEnabledAndDelete(KeystoneBasic):

    def run(self, enabled=True, **kwargs):
        """Create a keystone user, enable or disable it, and delete it.

        :param enabled: Initial state of user 'enabled' flag. The user
                        will be created with 'enabled' set to this
                        value, and then it will be toggled.
        :param kwargs: Other optional parameters to create user.
        """
        user = self.admin_keystone.create_user(enabled=enabled, **kwargs)
        self.admin_keystone.update_user(user.id, enabled=(not enabled))
        self.admin_keystone.delete_user(user.id)

@validation.add("required_platform", platform="openstack", admin=True)
@scenario.configure(context={"admin_cleanup": ["keystone"]},
                    name="KeystoneBasic.create_tenant",
                    platform="openstack")
class CreateTenant(KeystoneBasic):

    @logging.log_deprecated_args(
        "The 'name_length' argument to create_tenant is ignored",
        "0.1.2", ["name_length"], once=True)
    def run(self, name_length=10, **kwargs):
        """Create a keystone tenant with random name.

        :param kwargs: Other optional parameters
        """
        self.admin_keystone.create_project(**kwargs)

@validation.add("required_platform", platform="openstack", admin=True)
@scenario.configure(context={"admin_cleanup": ["keystone"]},
                    name="KeystoneBasic.authenticate_user_and_validate_token",
                    platform="openstack")
class AuthenticateUserAndValidateToken(KeystoneBasic):

    def run(self):
        """Authenticate and validate a keystone token."""
        token = self.admin_keystone.fetch_token()
        self.admin_keystone.validate_token(token)

@validation.add("number", param_name="users_per_tenant", minval=1)
@validation.add("required_platform", platform="openstack", admin=True)
@scenario.configure(context={"admin_cleanup": ["keystone"]},
                    name="KeystoneBasic.create_tenant_with_users",
                    platform="openstack")
class CreateTenantWithUsers(KeystoneBasic):

    @logging.log_deprecated_args(
        "The 'name_length' argument to create_tenant_with_users is ignored",
        "0.1.2", ["name_length"], once=True)
    def run(self, users_per_tenant, name_length=10, **kwargs):
        """Create a keystone tenant and several users belonging to it.

        :param users_per_tenant: number of users to create for the tenant
        :param kwargs: Other optional parameters for tenant creation
        :returns: keystone tenant instance
        """
        tenant = self.admin_keystone.create_project(**kwargs)
        self.admin_keystone.create_users(tenant.id,
                                         number_of_users=users_per_tenant)

@validation.add("required_platform", platform="openstack", admin=True)
@scenario.configure(context={"admin_cleanup": ["keystone"]},
                    name="KeystoneBasic.create_and_list_users",
                    platform="openstack")
class CreateAndListUsers(KeystoneBasic):

    @logging.log_deprecated_args(
        "The 'name_length' argument to create_and_list_users is ignored",
        "0.1.2", ["name_length"], once=True)
    def run(self, name_length=10, **kwargs):
        """Create a keystone user with random name and list all users.

        :param kwargs: Other optional parameters to create users like
                         "tenant_id", "enabled".
        """

        kwargs.pop("name", None)
        self.admin_keystone.create_user(**kwargs)
        self.admin_keystone.list_users()

@validation.add("required_platform", platform="openstack", admin=True)
@scenario.configure(context={"admin_cleanup": ["keystone"]},
                    name="KeystoneBasic.create_and_list_tenants",
                    platform="openstack")
class CreateAndListTenants(KeystoneBasic):

    @logging.log_deprecated_args(
        "The 'name_length' argument to create_and_list_tenants is ignored",
        "0.1.2", ["name_length"], once=True)
    def run(self, name_length=10, **kwargs):
        """Create a keystone tenant with random name and list all tenants.

        :param kwargs: Other optional parameters
        """
        self.admin_keystone.create_project(**kwargs)
        self.admin_keystone.list_projects()

@validation.add("required_platform", platform="openstack",
                admin=True, users=True)
@scenario.configure(context={"admin_cleanup": ["keystone"]},
                    name="KeystoneBasic.add_and_remove_user_role",
                    platform="openstack")
class AddAndRemoveUserRole(KeystoneBasic):

    def run(self):
        """Create a user role add to a user and disassociate."""
        tenant_id = self.context["tenant"]["id"]
        user_id = self.context["user"]["id"]
        role = self.admin_keystone.create_role()
        self.admin_keystone.add_role(role_id=role.id, user_id=user_id,
                                     project_id=tenant_id)
        self.admin_keystone.revoke_role(role.id, user_id=user_id,
                                        project_id=tenant_id)

@validation.add("required_platform", platform="openstack", admin=True)
@scenario.configure(context={"admin_cleanup": ["keystone"]},
                    name="KeystoneBasic.create_and_delete_role",
                    platform="openstack")
class CreateAndDeleteRole(KeystoneBasic):

    def run(self):
        """Create a user role and delete it."""
        role = self.admin_keystone.create_role()
        self.admin_keystone.delete_role(role.id)

@validation.add("required_platform", platform="openstack",
                admin=True, users=True)
@scenario.configure(context={"admin_cleanup": ["keystone"]},
                    name="KeystoneBasic.create_add_and_list_user_roles",
                    platform="openstack")
class CreateAddAndListUserRoles(KeystoneBasic):

    def run(self):
        """Create user role, add it and list user roles for given user."""
        tenant_id = self.context["tenant"]["id"]
        user_id = self.context["user"]["id"]
        role = self.admin_keystone.create_role()
        self.admin_keystone.add_role(user_id=user_id, role_id=role.id,
                                     project_id=tenant_id)
        self.admin_keystone.list_roles(user_id=user_id, project_id=tenant_id)

@validation.add("required_platform", platform="openstack", admin=True)
@scenario.configure(context={"admin_cleanup": ["keystone"]},
                    name="KeystoneBasic.get_entities",
                    platform="openstack")
class GetEntities(KeystoneBasic):

    def run(self, service_name="keystone"):
        """Get instance of a tenant, user, role and service by id's.

        An ephemeral tenant, user, and role are each created. By
        default, fetches the 'keystone' service. This can be
        overridden (for instance, to get the 'Identity Service'
        service on older OpenStack), or None can be passed explicitly
        to service_name to create a new service and then query it by
        ID.

        :param service_name: The name of the service to get by ID; or
                             None, to create an ephemeral service and
                             get it by ID.
        """
        project = self.admin_keystone.create_project()
        user = self.admin_keystone.create_user(project_id=project.id)
        role = self.admin_keystone.create_role()
        self.admin_keystone.get_project(project.id)
        self.admin_keystone.get_user(user.id)
        self.admin_keystone.get_role(role.id)
        if service_name is None:
            service = self.admin_keystone.create_service()
        else:
            service = self.admin_keystone.get_service_by_name(service_name)
        self.admin_keystone.get_service(service.id)

@validation.add("required_platform", platform="openstack", admin=True)
@scenario.configure(context={"admin_cleanup": ["keystone"]},
                    name="KeystoneBasic.create_and_delete_service",
                    platform="openstack")
class CreateAndDeleteService(KeystoneBasic):

    @logging.log_deprecated_args(
        "The 'name' argument to create_and_delete_service will be ignored",
        "0.0.5", ["name"])
    def run(self, name=None, service_type=None, description=None):
        """Create and delete service.

        :param service_type: type of the service
        :param description: description of the service
        """
        service = self.admin_keystone.create_service(service_type=service_type,
                                                     description=description)
        self.admin_keystone.delete_service(service.id)

@validation.add("required_platform", platform="openstack", admin=True)
@scenario.configure(context={"admin_cleanup": ["keystone"]},
                    name="KeystoneBasic.create_update_and_delete_tenant",
                    platform="openstack")
class CreateUpdateAndDeleteTenant(KeystoneBasic):

    @logging.log_deprecated_args(
        "The 'name_length' argument to create_update_and_delete_tenant is "
        "ignored", "0.1.2", ["name_length"], once=True)
    def run(self, name_length=None, **kwargs):
        """Create, update and delete tenant.

        :param kwargs: Other optional parameters for tenant creation
        """
        project = self.admin_keystone.create_project(**kwargs)
        new_name = self.generate_random_name()
        new_description = self.generate_random_name()
        self.admin_keystone.update_project(project.id, name=new_name,
                                           description=new_description)
        self.admin_keystone.delete_project(project.id)

@validation.add("required_platform", platform="openstack", admin=True)
@scenario.configure(context={"admin_cleanup": ["keystone"]},
                    name="KeystoneBasic.create_user_update_password",
                    platform="openstack")
class CreateUserUpdatePassword(KeystoneBasic):

    @logging.log_deprecated_args(
        "The 'name_length' and 'password_length' arguments to "
        "create_user_update_password are ignored",
        "0.1.2", ["name_length", "password_length"], once=True)
    def run(self, name_length=None, password_length=None):
        """Create user and update password for that user."""
        user = self.admin_keystone.create_user()
        password = self.generate_random_name()
        self.admin_keystone.update_user(user.id, password=password)

@validation.add("required_platform", platform="openstack", admin=True)
@scenario.configure(context={"admin_cleanup": ["keystone"]},
                    name="KeystoneBasic.create_and_list_services",
                    platform="openstack")
class CreateAndListServices(KeystoneBasic):

    @logging.log_deprecated_args(
        "The 'name' argument to create_and_list_services will be ignored",
        "0.0.5", ["name"])
    def run(self, name=None, service_type=None, description=None):
        """Create and list services.

        :param service_type: type of the service
        :param description: description of the service
        """
        self.admin_keystone.create_service(service_type=service_type,
                                           description=description)
        self.admin_keystone.list_services()

@validation.add("required_platform", platform="openstack", users=True)
@scenario.configure(context={"cleanup": ["keystone"]},
                    name="KeystoneBasic.create_and_list_ec2credentials",
                    platform="openstack")
class CreateAndListEc2Credentials(KeystoneBasic):

    def run(self):
        """Create and List all keystone ec2-credentials."""
        self.keystone.create_ec2credentials(
            self.context["user"]["id"],
            project_id=self.context["tenant"]["id"])
        self.keystone.list_ec2credentials(self.context["user"]["id"])

@validation.add("required_platform", platform="openstack", users=True)
@scenario.configure(context={"cleanup": ["keystone"]},
                    name="KeystoneBasic.create_and_delete_ec2credential",
                    platform="openstack")
class CreateAndDeleteEc2Credential(KeystoneBasic):

    def run(self):
        """Create and delete keystone ec2-credential."""
        creds = self.keystone.create_ec2credentials(
            self.context["user"]["id"],
            project_id=self.context["tenant"]["id"])
        self.keystone.delete_ec2credential(
            self.context["user"]["id"], access=creds.access)

@validation.add("required_platform", platform="openstack", admin=True)
@scenario.configure(context={"admin_cleanup": ["keystone"]},
                    name="KeystoneBasic.create_and_get_role",
                    platform="openstack")
class CreateAndGetRole(KeystoneBasic):

    def run(self, **kwargs):
        """Create a user role and get it detailed information.

        :param kwargs: Optional additional arguments for roles creation
        """
        role = self.admin_keystone.create_role(**kwargs)
        self.admin_keystone.get_role(role.id)

@validation.add("required_platform", platform="openstack", admin=True)
@scenario.configure(context={"admin_cleanup": ["keystone"]},
                    name="KeystoneBasic.create_and_list_roles",
                    platform="openstack")
class CreateAddListRoles(KeystoneBasic):

    def run(self, create_role_kwargs=None, list_role_kwargs=None):
        """Create a role, then list all roles.

        :param create_role_kwargs: Optional additional arguments for
                                   roles create
        :param list_role_kwargs: Optional additional arguments for roles list
        """
        create_role_kwargs = create_role_kwargs or {}
        list_role_kwargs = list_role_kwargs or {}

        role = self.admin_keystone.create_role(**create_role_kwargs)
        msg = "Role isn't created"
        self.assertTrue(role, err_msg=msg)
        all_roles = self.admin_keystone.list_roles(**list_role_kwargs)
        msg = ("Created role is not in the"
               " list of all available roles")
        self.assertIn(role, all_roles, err_msg=msg)

@validation.add("required_platform", platform="openstack", admin=True)
@scenario.configure(context={"admin_cleanup": ["keystone"]},
                    name="KeystoneBasic.create_and_update_user",
                    platform="openstack")
class CreateAndUpdateUser(KeystoneBasic):

    def run(self, create_user_kwargs=None, update_user_kwargs=None):
        """Create user and update the user.

        :param create_user_kwargs: Optional additional arguments for user
                                   creation
        :param update_user_kwargs: Optional additional arguments for user
                                   updation
        """
        create_user_kwargs = create_user_kwargs or {}

        user = self.admin_keystone.create_user(**create_user_kwargs)
        self.admin_keystone.update_user(user.id, **update_user_kwargs)
        user_data = self.admin_clients("keystone").users.get(user.id)

        for args in update_user_kwargs:
            msg = ("%s isn't updated" % args)
            self.assertEqual(getattr(user_data, str(args)),
                             update_user_kwargs[args], err_msg=msg)


text:
package org.apache.bigtop.datagenerators.bigpetstore.cli;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Collection;
import java.util.List;

import org.apache.bigtop.datagenerators.bigpetstore.DataLoader;
import org.apache.bigtop.datagenerators.bigpetstore.datamodels.Customer;
import org.apache.bigtop.datagenerators.bigpetstore.datamodels.Product;
import org.apache.bigtop.datagenerators.bigpetstore.datamodels.Store;
import org.apache.bigtop.datagenerators.bigpetstore.datamodels.Transaction;
import org.apache.bigtop.datagenerators.bigpetstore.datamodels.inputs.InputData;
import org.apache.bigtop.datagenerators.bigpetstore.datamodels.inputs.ProductCategory;
import org.apache.bigtop.datagenerators.bigpetstore.generators.purchase.PurchasingModel;
import org.apache.commons.lang3.tuple.Pair;

public class Driver
{
	int nStores;
	int nCustomers;
	int nPurchasingModels;
	double simulationTime;
	long seed;
	File outputDir;

	static final int NPARAMS = 6;

	private void printUsage()
	{
		String usage = "BigPetStore Data Generator\n" +
				"\n" +
				"Usage: java -jar bps-data-generator-v0.2.java outputDir nStores nCustomers nPurchasingModels simulationLength seed\n" +
				"\n" +
				"outputDir - (string) directory to write files\n" +
				"nStores - (int) number of stores to generate\n" +
				"nCustomers - (int) number of customers to generate\n" +
				"nPurchasingModels - (int) number of purchasing models to generate\n" +
				"simulationLength - (float) number of days to simulate\n" +
				"seed - (long) seed for RNG. If not given, one is reandomly generated.\n";

		System.out.println(usage);
	}

	public void parseArgs(String[] args)
	{
		if(args.length != NPARAMS && args.length != (NPARAMS - 1))
		{
			printUsage();
			System.exit(1);
		}

		int i = -1;

		outputDir = new File(args[++i]);
		if(! outputDir.exists())
		{
			System.err.println("Given path (" + args[i] + ") does not exist.\n");
			printUsage();
			System.exit(1);
		}

		if(! outputDir.isDirectory())
		{
			System.err.println("Given path (" + args[i] + ") is not a directory.\n");
			printUsage();
			System.exit(1);
		}

		try
		{
			nStores = Integer.parseInt(args[++i]);
		}
		catch(Exception e)
		{
			System.err.println("Unable to parse '" + args[i] + "' as an integer for nStores.\n");
			printUsage();
			System.exit(1);
		}

		try
		{
			nCustomers = Integer.parseInt(args[++i]);
		}
		catch(Exception e)
		{
			System.err.println("Unable to parse '" + args[i] + "' as an integer for nCustomers.\n");
			printUsage();
			System.exit(1);
		}

		try
		{
			nPurchasingModels = Integer.parseInt(args[++i]);
		}
		catch(Exception e)
		{
			System.err.println("Unable to parse '" + args[i] + "' as an integer for nPurchasingModels.\n");
			printUsage();
			System.exit(1);
		}

		try
		{
			simulationTime = Double.parseDouble(args[++i]);
		}
		catch(Exception e)
		{
			System.err.println("Unable to parse '" + args[i] + "' as a float for simulationLength.\n");
			printUsage();
			System.exit(1);
		}

		try
		{
			seed = Long.parseLong(args[++i]);
		}
		catch(Exception e)
		{
			System.err.println("Unable to parse '" + args[i] + "' as a long for the seed.\n");
			printUsage();
			System.exit(1);
		}
	}

	private void writeTransactions(Collection<Transaction> transactions) throws Exception
	{
		File outputFile = new File(outputDir.toString() + File.separator + "transactions.txt");
		System.out.println(outputFile.toString());
		OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile));

		for(Transaction transaction : transactions)
		{
			for(Product product : transaction.getProducts())
			{
				String record = transaction.getId() + ",";
				record += transaction.getDateTime() + ",";
				record += transaction.getStore().getId() + ",";
				record += transaction.getStore().getLocation().getZipcode() + ",";
				record += transaction.getStore().getLocation().getCity() + ",";
				record += transaction.getStore().getLocation().getState() + ",";
				record += transaction.getCustomer().getId() + ",";
				Pair<String, String> name = transaction.getCustomer().getName();
				record += name.getLeft() + " " + name.getRight() + ",";
				record += transaction.getCustomer().getLocation().getZipcode() + ",";
				record += transaction.getCustomer().getLocation().getCity() + ",";
				record += transaction.getCustomer().getLocation().getState() + ",";
				record += product.toString() + "\n";

				outputStream.write(record.getBytes());
			}
		}

		outputStream.close();
	}

	private void writeCustomers(Collection<Customer> customers) throws Exception
	{
		File outputFile = new File(outputDir.toString() + File.separator + "customers.txt");
		System.out.println(outputFile.toString());
		OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile));

		for(Customer customer : customers)
		{
			String record = customer.getId() + ",";
			Pair<String, String> name = customer.getName();
			record += name.getLeft() + "," + name.getRight() + ",";
			record += customer.getLocation().getZipcode() + ",";
			record += customer.getLocation().getCity() + ",";
			record += customer.getLocation().getState() + "\n";

			outputStream.write(record.getBytes());
		}

		outputStream.close();
	}

	private void writeStores(Collection<Store> stores) throws Exception
	{
		File outputFile = new File(outputDir.toString() + File.separator + "stores.txt");
		System.out.println(outputFile.toString());
		OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile));

		for(Store store : stores)
		{
			String record = store.getId() + ",";
			record += store.getLocation().getZipcode() + ",";
			record += store.getLocation().getCity() + ",";
			record += store.getLocation().getState() + "\n";

			outputStream.write(record.getBytes());
		}

		outputStream.close();
	}

	private void writeProducts(Collection<ProductCategory> productCategories) throws Exception
	{
		File outputFile = new File(outputDir.toString() + File.separator + "products.txt");
		System.out.println(outputFile.toString());
		OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile));

		for(ProductCategory category : productCategories)
		{

			for(Product product : category.getProducts())
			{
				String record = category.getCategoryLabel() + ",";
				record += product.toString() + "\n";

				outputStream.write(record.getBytes());
			}
		}

		outputStream.close();
	}

	private void writePurchasingProfiles(List<ProductCategory> productCategories, List<PurchasingModel> profiles) throws Exception
	{
		File outputFile = new File(outputDir.toString() + File.separator + "purchasing_profiles.txt");
		System.out.println(outputFile.toString());
		OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile));

		for(ProductCategory category : productCategories)
		{
			int i = 0;
			for(PurchasingModel model : profiles)
			{
				Object productModel = model.getProfile(category.getCategoryLabel());
				String record = productModel.toString();

				outputStream.write(record.getBytes());

				i += 1;
			}
		}

		outputStream.close();
	}

	public Simulation buildSimulation(InputData inputData)
	{
		return new Simulation(inputData, nStores, nCustomers, nPurchasingModels, simulationTime, seed);
	}

	private void run(InputData inputData) throws Exception
	{
		Simulation simulation = buildSimulation(inputData);

		simulation.simulate();

		writeStores(simulation.getStores());
		writeCustomers(simulation.getCustomers());
		writeProducts(simulation.getProductCategories());
		writePurchasingProfiles(simulation.getProductCategories(), simulation.getPurchasingProfiles());
		writeTransactions(simulation.getTransactions());
	}
	public void run(String[] args) throws Exception
	{
		parseArgs(args);

		InputData inputData = (new DataLoader()).loadData();

		run(inputData);
	}

	public static void main(String[] args) throws Exception
	{
		Driver driver = new Driver();
		driver.run(args);
	}

	public Double getSimulationLength()
	{
		return simulationTime;
	}

	public int getNCustomers()
	{
		return nCustomers;
	}

	public long getSeed()
	{
		return seed;
	}

	public int getNStores()
	{
		return nStores;
	}

	public File getOutputDir()
	{
		return outputDir;
	}
}

redpajama_set_name: RedPajamaGithub


text:
package chapter2;

import org.bouncycastle.jce.provider.BouncyCastleProvider;

import java.security.Key;
import java.security.Security;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * Basic example using the KeyGenerator class and
 * showing how to create a SecretKeySpec from an encoded key.
 */
public class KeyGeneratorExample
{
    public static void main(
        String[]    args)
        throws Exception
    {
        Security.addProvider(new BouncyCastleProvider());

        byte[]          input = new byte[] {
                            0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
                            0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
                            0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07 };
        byte[]		    ivBytes = new byte[] {
                            0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, (byte) 0x99};

        Cipher          cipher = Cipher.getInstance("DES", "BC");
        KeyGenerator    generator = KeyGenerator.getInstance("DES", "BC");

        generator.init(64);

        Key encryptionKey = generator.generateKey();

        System.out.println("key   : " + Utils.toHex(encryptionKey.getEncoded()));

        System.out.println("input : " + Utils.toHex(input));

        // encryption pass

        cipher.init(Cipher.ENCRYPT_MODE, encryptionKey, new IvParameterSpec(ivBytes));

        byte[] cipherText = new byte[cipher.getOutputSize(input.length)];

        int ctLength = cipher.update(input, 0, input.length, cipherText, 0);

        ctLength += cipher.doFinal(cipherText, ctLength);

        // decryption pass

        Key	decryptionKey = new SecretKeySpec(encryptionKey.getEncoded(), encryptionKey.getAlgorithm());

        cipher.init(Cipher.DECRYPT_MODE, decryptionKey, new IvParameterSpec(ivBytes));

        byte[] plainText = new byte[cipher.getOutputSize(ctLength)];

        int ptLength = cipher.update(cipherText, 0, ctLength, plainText, 0);

        ptLength += cipher.doFinal(plainText, ptLength);

        System.out.println("plain : " + Utils.toHex(plainText, ptLength) + " bytes: " + ptLength);
    }
}


text:
using System;
using System.Linq;
using NodaTime;
using QuantConnect.Securities;

namespace QuantConnect.Scheduling
{
    /// <summary>
    /// Provides a builder class to allow for fluent syntax when constructing new events
    /// </summary>
    /// <remarks>
    /// This builder follows the following steps for event creation:
    ///
    /// 1. Specify an event name (optional)
    /// 2. Specify an IDateRule
    /// 3. Specify an ITimeRule
    ///     a. repeat 3. to define extra time rules (optional)
    /// 4. Specify additional where clause (optional)
    /// 5. Register event via call to Run
    /// </remarks>
    public class FluentScheduledEventBuilder : IFluentSchedulingDateSpecifier, IFluentSchedulingRunnable
    {
        private IDateRule _dateRule;
        private ITimeRule _timeRule;
        private Func<DateTime, bool> _predicate;

        private readonly string _name;
        private readonly ScheduleManager _schedule;
        private readonly SecurityManager _securities;

        /// <summary>
        /// Initializes a new instance of the <see cref="FluentScheduledEventBuilder"/> class
        /// </summary>
        /// <param name="schedule">The schedule to send created events to</param>
        /// <param name="securities">The algorithm's security manager</param>
        /// <param name="name">A specific name for this event</param>
        public FluentScheduledEventBuilder(ScheduleManager schedule, SecurityManager securities, string name = null)
        {
            _name = name;
            _schedule = schedule;
            _securities = securities;
        }

        private FluentScheduledEventBuilder SetTimeRule(ITimeRule rule)
        {
            // if it's not set, just set it
            if (_timeRule == null)
            {
                _timeRule = rule;
                return this;
            }

            // if it's already a composite, open it up and make a new composite
            // prevent nesting composites
            var compositeTimeRule = _timeRule as CompositeTimeRule;
            if (compositeTimeRule != null)
            {
                var rules = compositeTimeRule.Rules;
                _timeRule = new CompositeTimeRule(rules.Concat(new[] { rule }));
                return this;
            }

            // create a composite from the existing rule and the new rules
            _timeRule = new CompositeTimeRule(_timeRule, rule);
            return this;
        }

        #region DateRules and TimeRules delegation

        /// <summary>
        /// Creates events on each of the specified day of week
        /// </summary>
        IFluentSchedulingTimeSpecifier IFluentSchedulingDateSpecifier.Every(params DayOfWeek[] days)
        {
            _dateRule = _schedule.DateRules.Every(days);
            return this;
        }

        /// <summary>
        /// Creates events on every day of the year
        /// </summary>
        IFluentSchedulingTimeSpecifier IFluentSchedulingDateSpecifier.EveryDay()
        {
            _dateRule = _schedule.DateRules.EveryDay();
            return this;
        }

        /// <summary>
        /// Creates events on every trading day of the year for the symbol
        /// </summary>
        IFluentSchedulingTimeSpecifier IFluentSchedulingDateSpecifier.EveryDay(Symbol symbol)
        {
            _dateRule = _schedule.DateRules.EveryDay(symbol);
            return this;
        }

        /// <summary>
        /// Creates events on the first day of the month
        /// </summary>
        IFluentSchedulingTimeSpecifier IFluentSchedulingDateSpecifier.MonthStart()
        {
            _dateRule = _schedule.DateRules.MonthStart();
            return this;
        }

        /// <summary>
        /// Creates events on the first trading day of the month
        /// </summary>
        IFluentSchedulingTimeSpecifier IFluentSchedulingDateSpecifier.MonthStart(Symbol symbol)
        {
            _dateRule = _schedule.DateRules.MonthStart(symbol);
            return this;
        }

        /// <summary>
        /// Filters the event times using the predicate
        /// </summary>
        IFluentSchedulingTimeSpecifier IFluentSchedulingDateSpecifier.Where(Func<DateTime, bool> predicate)
        {
            _predicate = _predicate == null
                ? predicate
                : (time => _predicate(time) && predicate(time));
            return this;
        }

        /// <summary>
        /// Creates events that fire at the specific time of day in the algorithm's time zone
        /// </summary>
        IFluentSchedulingRunnable IFluentSchedulingTimeSpecifier.At(TimeSpan timeOfDay)
        {
            return SetTimeRule(_schedule.TimeRules.At(timeOfDay));
        }

        /// <summary>
        /// Creates events that fire a specified number of minutes after market open
        /// </summary>
        IFluentSchedulingRunnable IFluentSchedulingTimeSpecifier.AfterMarketOpen(Symbol symbol, double minutesAfterOpen, bool extendedMarketOpen)
        {
            return SetTimeRule(_schedule.TimeRules.AfterMarketOpen(symbol, minutesAfterOpen, extendedMarketOpen));
        }

        /// <summary>
        /// Creates events that fire a specified numer of minutes before market close
        /// </summary>
        IFluentSchedulingRunnable IFluentSchedulingTimeSpecifier.BeforeMarketClose(Symbol symbol, double minuteBeforeClose, bool extendedMarketClose)
        {
            return SetTimeRule(_schedule.TimeRules.BeforeMarketClose(symbol, minuteBeforeClose, extendedMarketClose));
        }

        /// <summary>
        /// Creates events that fire on a period define by the specified interval
        /// </summary>
        IFluentSchedulingRunnable IFluentSchedulingTimeSpecifier.Every(TimeSpan interval)
        {
            return SetTimeRule(_schedule.TimeRules.Every(interval));
        }

        /// <summary>
        /// Filters the event times using the predicate
        /// </summary>
        IFluentSchedulingTimeSpecifier IFluentSchedulingTimeSpecifier.Where(Func<DateTime, bool> predicate)
        {
            _predicate = _predicate == null
                ? predicate
                : (time => _predicate(time) && predicate(time));
            return this;
        }

        /// <summary>
        /// Register the defined event with the callback
        /// </summary>
        ScheduledEvent IFluentSchedulingRunnable.Run(Action callback)
        {
            return ((IFluentSchedulingRunnable)this).Run((name, time) => callback());
        }

        /// <summary>
        /// Register the defined event with the callback
        /// </summary>
        ScheduledEvent IFluentSchedulingRunnable.Run(Action<DateTime> callback)
        {
            return ((IFluentSchedulingRunnable)this).Run((name, time) => callback(time));
        }

        /// <summary>
        /// Register the defined event with the callback
        /// </summary>
        ScheduledEvent IFluentSchedulingRunnable.Run(Action<string, DateTime> callback)
        {
            var name = _name ?? _dateRule.Name + ": " + _timeRule.Name;
            // back the date up to ensure we get all events, the event scheduler will skip past events that whose time has passed
            var dates = _dateRule.GetDates(_securities.UtcTime.Date.AddDays(-1), Time.EndOfTime);
            var eventTimes = _timeRule.CreateUtcEventTimes(dates);
            if (_predicate != null)
            {
                eventTimes = eventTimes.Where(_predicate);
            }
            var scheduledEvent = new ScheduledEvent(name, eventTimes, callback);
            _schedule.Add(scheduledEvent);
            return scheduledEvent;
        }

        /// <summary>
        /// Filters the event times using the predicate
        /// </summary>
        IFluentSchedulingRunnable IFluentSchedulingRunnable.Where(Func<DateTime, bool> predicate)
        {
            _predicate = _predicate == null
                ? predicate
                : (time => _predicate(time) && predicate(time));
            return this;
        }

        /// <summary>
        /// Filters the event times to only include times where the symbol's market is considered open
        /// </summary>
        IFluentSchedulingRunnable IFluentSchedulingRunnable.DuringMarketHours(Symbol symbol, bool extendedMarket)
        {
            var security = GetSecurity(symbol);
            Func<DateTime, bool> predicate = time =>
            {
                var localTime = time.ConvertFromUtc(security.Exchange.TimeZone);
                return security.Exchange.IsOpenDuringBar(localTime, localTime, extendedMarket);
            };
            _predicate = _predicate == null
                ? predicate
                : (time => _predicate(time) && predicate(time));
            return this;
        }

        IFluentSchedulingTimeSpecifier IFluentSchedulingDateSpecifier.On(int year, int month, int day)
        {
            _dateRule = _schedule.DateRules.On(year, month, day);
            return this;
        }

        IFluentSchedulingTimeSpecifier IFluentSchedulingDateSpecifier.On(params DateTime[] dates)
        {
            _dateRule = _schedule.DateRules.On(dates);
            return this;
        }

        IFluentSchedulingRunnable IFluentSchedulingTimeSpecifier.At(int hour, int minute, int second)
        {
            return SetTimeRule(_schedule.TimeRules.At(hour, minute, second));
        }

        IFluentSchedulingRunnable IFluentSchedulingTimeSpecifier.At(int hour, int minute, DateTimeZone timeZone)
        {
            return SetTimeRule(_schedule.TimeRules.At(hour, minute, 0, timeZone));
        }

        IFluentSchedulingRunnable IFluentSchedulingTimeSpecifier.At(int hour, int minute, int second, DateTimeZone timeZone)
        {
            return SetTimeRule(_schedule.TimeRules.At(hour, minute, second, timeZone));
        }

        IFluentSchedulingRunnable IFluentSchedulingTimeSpecifier.At(TimeSpan timeOfDay, DateTimeZone timeZone)
        {
            return SetTimeRule(_schedule.TimeRules.At(timeOfDay, timeZone));
        }

        private Security GetSecurity(Symbol symbol)
        {
            Security security;
            if (!_securities.TryGetValue(symbol, out security))
            {
                throw new Exception(symbol.Permtick + " not found in portfolio. Request this data when initializing the algorithm.");
            }
            return security;
        }

        #endregion
    }

    /// <summary>
    /// Specifies the date rule component of a scheduled event
    /// </summary>
    public interface IFluentSchedulingDateSpecifier
    {
        /// <summary>
        /// Filters the event times using the predicate
        /// </summary>
        IFluentSchedulingTimeSpecifier Where(Func<DateTime, bool> predicate);
        /// <summary>
        /// Creates events only on the specified date
        /// </summary>
        IFluentSchedulingTimeSpecifier On(int year, int month, int day);
        /// <summary>
        /// Creates events only on the specified dates
        /// </summary>
        IFluentSchedulingTimeSpecifier On(params DateTime[] dates);
        /// <summary>
        /// Creates events on each of the specified day of week
        /// </summary>
        IFluentSchedulingTimeSpecifier Every(params DayOfWeek[] days);
        /// <summary>
        /// Creates events on every day of the year
        /// </summary>
        IFluentSchedulingTimeSpecifier EveryDay();
        /// <summary>
        /// Creates events on every trading day of the year for the symbol
        /// </summary>
        IFluentSchedulingTimeSpecifier EveryDay(Symbol symbol);
        /// <summary>
        /// Creates events on the first day of the month
        /// </summary>
        IFluentSchedulingTimeSpecifier MonthStart();
        /// <summary>
        /// Creates events on the first trading day of the month
        /// </summary>
        IFluentSchedulingTimeSpecifier MonthStart(Symbol symbol);
    }

    /// <summary>
    /// Specifies the time rule component of a scheduled event
    /// </summary>
    public interface IFluentSchedulingTimeSpecifier
    {
        /// <summary>
        /// Filters the event times using the predicate
        /// </summary>
        IFluentSchedulingTimeSpecifier Where(Func<DateTime, bool> predicate);
        /// <summary>
        /// Creates events that fire at the specified time of day in the specified time zone
        /// </summary>
        IFluentSchedulingRunnable At(int hour, int minute, int second = 0);
        /// <summary>
        /// Creates events that fire at the specified time of day in the specified time zone
        /// </summary>
        IFluentSchedulingRunnable At(int hour, int minute, DateTimeZone timeZone);
        /// <summary>
        /// Creates events that fire at the specified time of day in the specified time zone
        /// </summary>
        IFluentSchedulingRunnable At(int hour, int minute, int second, DateTimeZone timeZone);
        /// <summary>
        /// Creates events that fire at the specified time of day in the specified time zone
        /// </summary>
        IFluentSchedulingRunnable At(TimeSpan timeOfDay, DateTimeZone timeZone);
        /// <summary>
        /// Creates events that fire at the specific time of day in the algorithm's time zone
        /// </summary>
        IFluentSchedulingRunnable At(TimeSpan timeOfDay);
        /// <summary>
        /// Creates events that fire on a period define by the specified interval
        /// </summary>
        IFluentSchedulingRunnable Every(TimeSpan interval);
        /// <summary>
        /// Creates events that fire a specified number of minutes after market open
        /// </summary>
        IFluentSchedulingRunnable AfterMarketOpen(Symbol symbol, double minutesAfterOpen = 0, bool extendedMarketOpen = false);
        /// <summary>
        /// Creates events that fire a specified numer of minutes before market close
        /// </summary>
        IFluentSchedulingRunnable BeforeMarketClose(Symbol symbol, double minuteBeforeClose = 0, bool extendedMarketClose = false);
    }

    /// <summary>
    /// Specifies the callback component of a scheduled event, as well as final filters
    /// </summary>
    public interface IFluentSchedulingRunnable : IFluentSchedulingTimeSpecifier
    {
        /// <summary>
        /// Filters the event times using the predicate
        /// </summary>
        new IFluentSchedulingRunnable Where(Func<DateTime, bool> predicate);
        /// <summary>
        /// Filters the event times to only include times where the symbol's market is considered open
        /// </summary>
        IFluentSchedulingRunnable DuringMarketHours(Symbol symbol, bool extendedMarket = false);
        /// <summary>
        /// Register the defined event with the callback
        /// </summary>
        ScheduledEvent Run(Action callback);
        /// <summary>
        /// Register the defined event with the callback
        /// </summary>
        ScheduledEvent Run(Action<DateTime> callback);
        /// <summary>
        /// Register the defined event with the callback
        /// </summary>
        ScheduledEvent Run(Action<string, DateTime> callback);
    }
}


text:
<?php

namespace Topxia\WebBundle\Extensions\DataTag;

use Topxia\WebBundle\Extensions\DataTag\DataTag;

class LatestCoursesDataTag extends CourseBaseDataTag implements DataTag
{

    /**
     * 获取最新课程列表
     *
     * 可传入的参数:
     *   categoryId 可选 分类ID
     *   notFree 可选 1:代表不包括免费课程 0:代表包括 默认包括
     *   count    必需 课程数量,取值不能超过100
     *
     * @param  array $arguments 参数
     * @return array 课程列表
     */
    public function getData(array $arguments)
    {
        $this->checkCount($arguments);

        $conditions = array();
        $conditions['status'] = 'published';
        $conditions['parentId'] = 0;

        if (!empty($arguments['categoryId'])) {
            $conditions['categoryId'] = $arguments['categoryId'];
        } elseif (!empty($arguments['categoryCode'])) {
            $category = $this->getCategoryService()->getCategoryByCode($arguments['categoryCode']);
            $conditions['categoryId'] = empty($category) ? -1 : $category['id'];
        }

        // @todo 规则应该调整为 price > 0 && coinPrice > 0 .
        if (!empty($arguments['notFree'])) {
            $conditions['originPrice_GT'] = '0.00';
        }

    	$courses = $this->getCourseService()->searchCourses($conditions,'latest', 0, $arguments['count']);

        return $this->getCourseTeachersAndCategories($courses);
    }
}


text:
using content::BrowserThread;
using content::WebContents;

namespace {

// The dimensions of the certificate selector table view, in pixels.
static const int kTableViewWidth = 400;
static const int kTableViewHeight = 100;

}  // namespace

///////////////////////////////////////////////////////////////////////////////
// CertificateSelectorTableModel:

class CertificateSelectorTableModel : public ui::TableModel {
 public:
  explicit CertificateSelectorTableModel(
      net::SSLCertRequestInfo* cert_request_info);

  // ui::TableModel implementation:
  virtual int RowCount() OVERRIDE;
  virtual string16 GetText(int index, int column_id) OVERRIDE;
  virtual void SetObserver(ui::TableModelObserver* observer) OVERRIDE;

 private:
  std::vector<string16> items_;

  DISALLOW_COPY_AND_ASSIGN(CertificateSelectorTableModel);
};

CertificateSelectorTableModel::CertificateSelectorTableModel(
    net::SSLCertRequestInfo* cert_request_info) {
  for (size_t i = 0; i < cert_request_info->client_certs.size(); ++i) {
    net::X509Certificate* cert = cert_request_info->client_certs[i];
    string16 text = l10n_util::GetStringFUTF16(
        IDS_CERT_SELECTOR_TABLE_CERT_FORMAT,
        UTF8ToUTF16(cert->subject().GetDisplayName()),
        UTF8ToUTF16(cert->issuer().GetDisplayName()));
    items_.push_back(text);
  }
}

int CertificateSelectorTableModel::RowCount() {
  return items_.size();
}

string16 CertificateSelectorTableModel::GetText(int index, int column_id) {
  DCHECK_EQ(column_id, 0);
  DCHECK_GE(index, 0);
  DCHECK_LT(index, static_cast<int>(items_.size()));

  return items_[index];
}

void CertificateSelectorTableModel::SetObserver(
    ui::TableModelObserver* observer) {
}

///////////////////////////////////////////////////////////////////////////////
// SSLClientCertificateSelector:

SSLClientCertificateSelector::SSLClientCertificateSelector(
    WebContents* web_contents,
    const net::HttpNetworkSession* network_session,
    net::SSLCertRequestInfo* cert_request_info,
    const chrome::SelectCertificateCallback& callback)
    : SSLClientAuthObserver(network_session, cert_request_info, callback),
      model_(new CertificateSelectorTableModel(cert_request_info)),
      web_contents_(web_contents),
      window_(NULL),
      table_(NULL),
      view_cert_button_(NULL) {
  DVLOG(1) << __FUNCTION__;
}

SSLClientCertificateSelector::~SSLClientCertificateSelector() {
  table_->SetModel(NULL);
}

void SSLClientCertificateSelector::Init() {
  views::GridLayout* layout = views::GridLayout::CreatePanel(this);
  SetLayoutManager(layout);

  const int column_set_id = 0;
  views::ColumnSet* column_set = layout->AddColumnSet(column_set_id);
  column_set->AddColumn(
      views::GridLayout::FILL, views::GridLayout::FILL,
      1, views::GridLayout::USE_PREF, 0, 0);

  layout->StartRow(0, column_set_id);
  string16 text = l10n_util::GetStringFUTF16(
      IDS_CLIENT_CERT_DIALOG_TEXT,
      ASCIIToUTF16(cert_request_info()->host_and_port));
  views::Label* label = new views::Label(text);
  label->SetMultiLine(true);
  label->SetHorizontalAlignment(gfx::ALIGN_LEFT);
  label->SetAllowCharacterBreak(true);
  layout->AddView(label);

  layout->AddPaddingRow(0, views::kRelatedControlVerticalSpacing);

  CreateCertTable();
  layout->StartRow(1, column_set_id);
  layout->AddView(table_->CreateParentIfNecessary(), 1, 1,
                  views::GridLayout::FILL,
                  views::GridLayout::FILL, kTableViewWidth, kTableViewHeight);

  layout->AddPaddingRow(0, views::kRelatedControlVerticalSpacing);

  StartObserving();

  WebContentsModalDialogManager* web_contents_modal_dialog_manager =
      WebContentsModalDialogManager::FromWebContents(web_contents_);
  window_ = CreateWebContentsModalDialogViews(
      this,
      web_contents_->GetView()->GetNativeView(),
      web_contents_modal_dialog_manager->delegate()->
          GetWebContentsModalDialogHost());
  web_contents_modal_dialog_manager->ShowDialog(window_->GetNativeView());

  // Select the first row automatically.  This must be done after the dialog has
  // been created.
  table_->Select(0);
}

net::X509Certificate* SSLClientCertificateSelector::GetSelectedCert() const {
  int selected = table_->FirstSelectedRow();
  if (selected >= 0 &&
      selected < static_cast<int>(
          cert_request_info()->client_certs.size()))
    return cert_request_info()->client_certs[selected];
  return NULL;
}

///////////////////////////////////////////////////////////////////////////////
// SSLClientAuthObserver implementation:

void SSLClientCertificateSelector::OnCertSelectedByNotification() {
  DVLOG(1) << __FUNCTION__;
  DCHECK(window_);
  window_->Close();
}

///////////////////////////////////////////////////////////////////////////////
// DialogDelegateView implementation:

bool SSLClientCertificateSelector::CanResize() const {
  return true;
}

string16 SSLClientCertificateSelector::GetWindowTitle() const {
  return l10n_util::GetStringUTF16(IDS_CLIENT_CERT_DIALOG_TITLE);
}

void SSLClientCertificateSelector::DeleteDelegate() {
  DVLOG(1) << __FUNCTION__;
  delete this;
}

bool SSLClientCertificateSelector::IsDialogButtonEnabled(
    ui::DialogButton button) const {
  if (button == ui::DIALOG_BUTTON_OK)
    return !!GetSelectedCert();
  return true;
}

bool SSLClientCertificateSelector::Cancel() {
  DVLOG(1) << __FUNCTION__;
  StopObserving();
  CertificateSelected(NULL);

  return true;
}

bool SSLClientCertificateSelector::Accept() {
  DVLOG(1) << __FUNCTION__;
  net::X509Certificate* cert = GetSelectedCert();
  if (cert) {
    StopObserving();
    CertificateSelected(cert);
    return true;
  }

  return false;
}

// TODO(wittman): Remove this override once we move to the new style frame view
// on all dialogs.
views::NonClientFrameView*
    SSLClientCertificateSelector::CreateNonClientFrameView(
        views::Widget* widget) {
  return CreateConstrainedStyleNonClientFrameView(
      widget,
      web_contents_->GetBrowserContext());
}

views::View* SSLClientCertificateSelector::GetInitiallyFocusedView() {
  return table_;
}

views::View* SSLClientCertificateSelector::CreateExtraView() {
  DCHECK(!view_cert_button_);
  view_cert_button_ = new views::LabelButton(this,
      l10n_util::GetStringUTF16(IDS_PAGEINFO_CERT_INFO_BUTTON));
  view_cert_button_->SetStyle(views::Button::STYLE_NATIVE_TEXTBUTTON);
  return view_cert_button_;
}

ui::ModalType SSLClientCertificateSelector::GetModalType() const {
#if defined(USE_ASH)
  return ui::MODAL_TYPE_CHILD;
#else
  return views::WidgetDelegate::GetModalType();
#endif
}

///////////////////////////////////////////////////////////////////////////////
// views::ButtonListener implementation:

void SSLClientCertificateSelector::ButtonPressed(
    views::Button* sender, const ui::Event& event) {
  if (sender == view_cert_button_) {
    net::X509Certificate* cert = GetSelectedCert();
    if (cert)
      ShowCertificateViewer(web_contents_,
                            web_contents_->GetView()->GetTopLevelNativeWindow(),
                            cert);
  }
}

///////////////////////////////////////////////////////////////////////////////
// views::TableViewObserver implementation:
void SSLClientCertificateSelector::OnSelectionChanged() {
  GetDialogClientView()->ok_button()->SetEnabled(!!GetSelectedCert());
}

void SSLClientCertificateSelector::OnDoubleClick() {
  if (Accept())
    window_->Close();
}

///////////////////////////////////////////////////////////////////////////////
// SSLClientCertificateSelector private methods:

void SSLClientCertificateSelector::CreateCertTable() {
  std::vector<ui::TableColumn> columns;
  columns.push_back(ui::TableColumn());
  table_ = new views::TableView(model_.get(),
                                columns,
                                views::TEXT_ONLY,
                                true,  // single_selection
                                true,  // resizable_columns
                                true);  // autosize_columns
  table_->SetObserver(this);
}

namespace chrome {

void ShowSSLClientCertificateSelector(
    content::WebContents* contents,
    const net::HttpNetworkSession* network_session,
    net::SSLCertRequestInfo* cert_request_info,
    const chrome::SelectCertificateCallback& callback) {
  DVLOG(1) << __FUNCTION__ << " " << contents;
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  (new SSLClientCertificateSelector(
       contents, network_session, cert_request_info, callback))->Init();
}

}  // namespace chrome


text:
"""Test that the wallet can send and receive using all combinations of address types.

There are 5 nodes-under-test:
    - node0 uses legacy addresses
    - node1 uses p2sh/segwit addresses
    - node2 uses p2sh/segwit addresses and bech32 addresses for change
    - node3 uses bech32 addresses
    - node4 uses a p2sh/segwit addresses for change

node5 exists to generate new blocks.

## Multisig address test

Test that adding a multisig address with:
    - an uncompressed pubkey always gives a legacy address
    - only compressed pubkeys gives the an `-addresstype` address

## Sending to address types test

A series of tests, iterating over node0-node4. In each iteration of the test, one node sends:
    - 10/101th of its balance to itself (using getrawchangeaddress for single key addresses)
    - 20/101th to the next node
    - 30/101th to the node after that
    - 40/101th to the remaining node
    - 1/101th remains as fee+change

Iterate over each node for single key addresses, and then over each node for
multisig addresses.

Repeat test, but with explicit address_type parameters passed to getnewaddress
and getrawchangeaddress:
    - node0 and node3 send to p2sh.
    - node1 sends to bech32.
    - node2 sends to legacy.

As every node sends coins after receiving, this also
verifies that spending coins sent to all these address types works.

## Change type test

Test that the nodes generate the correct change address type:
    - node0 always uses a legacy change address.
    - node1 uses a bech32 addresses for change if any destination address is bech32.
    - node2 always uses a bech32 address for change
    - node3 always uses a bech32 address for change
    - node4 always uses p2sh/segwit output for change.
"""

from decimal import Decimal
import itertools

from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import (
    assert_equal,
    assert_greater_than,
    assert_raises_rpc_error,
    connect_nodes_bi,
    sync_blocks,
    sync_mempools,
)

class AddressTypeTest(BitcoinTestFramework):
    def set_test_params(self):
        self.num_nodes = 6
        self.extra_args = [
            ["-addresstype=legacy"],
            ["-addresstype=p2sh-segwit"],
            ["-addresstype=p2sh-segwit", "-changetype=bech32"],
            ["-addresstype=bech32"],
            ["-changetype=p2sh-segwit"],
            []
        ]

    def setup_network(self):
        self.setup_nodes()

        # Fully mesh-connect nodes for faster mempool sync
        for i, j in itertools.product(range(self.num_nodes), repeat=2):
            if i > j:
                connect_nodes_bi(self.nodes, i, j)
        self.sync_all()

    def get_balances(self, confirmed=True):
        """Return a list of confirmed or unconfirmed balances."""
        if confirmed:
            return [self.nodes[i].getbalance() for i in range(4)]
        else:
            return [self.nodes[i].getunconfirmedbalance() for i in range(4)]

    def test_address(self, node, address, multisig, typ):
        """Run sanity checks on an address."""
        info = self.nodes[node].getaddressinfo(address)
        assert(self.nodes[node].validateaddress(address)['isvalid'])
        if not multisig and typ == 'legacy':
            # P2PKH
            assert(not info['isscript'])
            assert(not info['iswitness'])
            assert('pubkey' in info)
        elif not multisig and typ == 'p2sh-segwit':
            # P2SH-P2WPKH
            assert(info['isscript'])
            assert(not info['iswitness'])
            assert_equal(info['script'], 'witness_v0_keyhash')
            assert('pubkey' in info)
        elif not multisig and typ == 'bech32':
            # P2WPKH
            assert(not info['isscript'])
            assert(info['iswitness'])
            assert_equal(info['witness_version'], 0)
            assert_equal(len(info['witness_program']), 40)
            assert('pubkey' in info)
        elif typ == 'legacy':
            # P2SH-multisig
            assert(info['isscript'])
            assert_equal(info['script'], 'multisig')
            assert(not info['iswitness'])
            assert('pubkeys' in info)
        elif typ == 'p2sh-segwit':
            # P2SH-P2WSH-multisig
            assert(info['isscript'])
            assert_equal(info['script'], 'witness_v0_scripthash')
            assert(not info['iswitness'])
            assert(info['embedded']['isscript'])
            assert_equal(info['embedded']['script'], 'multisig')
            assert(info['embedded']['iswitness'])
            assert_equal(info['embedded']['witness_version'], 0)
            assert_equal(len(info['embedded']['witness_program']), 64)
            assert('pubkeys' in info['embedded'])
        elif typ == 'bech32':
            # P2WSH-multisig
            assert(info['isscript'])
            assert_equal(info['script'], 'multisig')
            assert(info['iswitness'])
            assert_equal(info['witness_version'], 0)
            assert_equal(len(info['witness_program']), 64)
            assert('pubkeys' in info)
        else:
            # Unknown type
            assert(False)

    def test_change_output_type(self, node_sender, destinations, expected_type):
        txid = self.nodes[node_sender].sendmany(fromaccount="", amounts=dict.fromkeys(destinations, 0.001))
        raw_tx = self.nodes[node_sender].getrawtransaction(txid)
        tx = self.nodes[node_sender].decoderawtransaction(raw_tx)

        # Make sure the transaction has change:
        assert_equal(len(tx["vout"]), len(destinations) + 1)

        # Make sure the destinations are included, and remove them:
        output_addresses = [vout['scriptPubKey']['addresses'][0] for vout in tx["vout"]]
        change_addresses = [d for d in output_addresses if d not in destinations]
        assert_equal(len(change_addresses), 1)

        self.log.debug("Check if change address " + change_addresses[0] + " is " + expected_type)
        self.test_address(node_sender, change_addresses[0], multisig=False, typ=expected_type)

    def run_test(self):
        # Mine 500 blocks on node5 to bring nodes out of IBD and make sure that
        # no coinbases are maturing for the nodes-under-test during the test.
        # Also activates segwit at height 432.
        self.nodes[5].generate(500)
        sync_blocks(self.nodes)

        uncompressed_1 = "0496b538e853519c726a2c91e61ec11600ae1390813a627c66fb8be7947be63c52da7589379515d4e0a604f8141781e62294721166bf621e73a82cbf2342c858ee"
        uncompressed_2 = "047211a824f55b505228e4c3d5194c1fcfaa15a456abdf37f9b9d97a4040afc073dee6c89064984f03385237d92167c13e236446b417ab79a0fcae412ae3316b77"
        compressed_1 = "0296b538e853519c726a2c91e61ec11600ae1390813a627c66fb8be7947be63c52"
        compressed_2 = "037211a824f55b505228e4c3d5194c1fcfaa15a456abdf37f9b9d97a4040afc073"

        # addmultisigaddress with at least 1 uncompressed key should return a legacy address.
        for node in range(4):
            self.test_address(node, self.nodes[node].addmultisigaddress(2, [uncompressed_1, uncompressed_2])['address'], True, 'legacy')
            self.test_address(node, self.nodes[node].addmultisigaddress(2, [compressed_1, uncompressed_2])['address'], True, 'legacy')
            self.test_address(node, self.nodes[node].addmultisigaddress(2, [uncompressed_1, compressed_2])['address'], True, 'legacy')
        # addmultisigaddress with all compressed keys should return the appropriate address type (even when the keys are not ours).
        self.test_address(0, self.nodes[0].addmultisigaddress(2, [compressed_1, compressed_2])['address'], True, 'legacy')
        self.test_address(1, self.nodes[1].addmultisigaddress(2, [compressed_1, compressed_2])['address'], True, 'p2sh-segwit')
        self.test_address(2, self.nodes[2].addmultisigaddress(2, [compressed_1, compressed_2])['address'], True, 'p2sh-segwit')
        self.test_address(3, self.nodes[3].addmultisigaddress(2, [compressed_1, compressed_2])['address'], True, 'bech32')

        for explicit_type, multisig, from_node in itertools.product([False, True], [False, True], range(4)):
            address_type = None
            if explicit_type and not multisig:
                if from_node == 1:
                    address_type = 'bech32'
                elif from_node == 0 or from_node == 3:
                    address_type = 'p2sh-segwit'
                else:
                    address_type = 'legacy'
            self.log.info("Sending from node {} ({}) with{} multisig using {}".format(from_node, self.extra_args[from_node], "" if multisig else "out", "default" if address_type is None else address_type))
            old_balances = self.get_balances()
            self.log.debug("Old balances are {}".format(old_balances))
            to_send = (old_balances[from_node] / 101).quantize(Decimal("0.00000001"))
            sends = {}

            self.log.debug("Prepare sends")
            for n, to_node in enumerate(range(from_node, from_node + 4)):
                to_node %= 4
                change = False
                if not multisig:
                    if from_node == to_node:
                        # When sending non-multisig to self, use getrawchangeaddress
                        address = self.nodes[to_node].getrawchangeaddress(address_type=address_type)
                        change = True
                    else:
                        address = self.nodes[to_node].getnewaddress(address_type=address_type)
                else:
                    addr1 = self.nodes[to_node].getnewaddress()
                    addr2 = self.nodes[to_node].getnewaddress()
                    address = self.nodes[to_node].addmultisigaddress(2, [addr1, addr2])['address']

                # Do some sanity checking on the created address
                if address_type is not None:
                    typ = address_type
                elif to_node == 0:
                    typ = 'legacy'
                elif to_node == 1 or (to_node == 2 and not change):
                    typ = 'p2sh-segwit'
                else:
                    typ = 'bech32'
                self.test_address(to_node, address, multisig, typ)

                # Output entry
                sends[address] = to_send * 10 * (1 + n)

            self.log.debug("Sending: {}".format(sends))
            self.nodes[from_node].sendmany("", sends)
            sync_mempools(self.nodes)

            unconf_balances = self.get_balances(False)
            self.log.debug("Check unconfirmed balances: {}".format(unconf_balances))
            assert_equal(unconf_balances[from_node], 0)
            for n, to_node in enumerate(range(from_node + 1, from_node + 4)):
                to_node %= 4
                assert_equal(unconf_balances[to_node], to_send * 10 * (2 + n))

            # node5 collects fee and block subsidy to keep accounting simple
            self.nodes[5].generate(1)
            sync_blocks(self.nodes)

            new_balances = self.get_balances()
            self.log.debug("Check new balances: {}".format(new_balances))
            # We don't know what fee was set, so we can only check bounds on the balance of the sending node
            assert_greater_than(new_balances[from_node], to_send * 10)
            assert_greater_than(to_send * 11, new_balances[from_node])
            for n, to_node in enumerate(range(from_node + 1, from_node + 4)):
                to_node %= 4
                assert_equal(new_balances[to_node], old_balances[to_node] + to_send * 10 * (2 + n))

        # Get one p2sh/segwit address from node2 and two bech32 addresses from node3:
        to_address_p2sh = self.nodes[2].getnewaddress()
        to_address_bech32_1 = self.nodes[3].getnewaddress()
        to_address_bech32_2 = self.nodes[3].getnewaddress()

        # Fund node 4:
        self.nodes[5].sendtoaddress(self.nodes[4].getnewaddress(), Decimal("1"))
        self.nodes[5].generate(1)
        sync_blocks(self.nodes)
        assert_equal(self.nodes[4].getbalance(), 1)

        self.log.info("Nodes with addresstype=legacy never use a P2WPKH change output")
        self.test_change_output_type(0, [to_address_bech32_1], 'legacy')

        self.log.info("Nodes with addresstype=p2sh-segwit only use a P2WPKH change output if any destination address is bech32:")
        self.test_change_output_type(1, [to_address_p2sh], 'p2sh-segwit')
        self.test_change_output_type(1, [to_address_bech32_1], 'bech32')
        self.test_change_output_type(1, [to_address_p2sh, to_address_bech32_1], 'bech32')
        self.test_change_output_type(1, [to_address_bech32_1, to_address_bech32_2], 'bech32')

        self.log.info("Nodes with change_type=bech32 always use a P2WPKH change output:")
        self.test_change_output_type(2, [to_address_bech32_1], 'bech32')
        self.test_change_output_type(2, [to_address_p2sh], 'bech32')

        self.log.info("Nodes with addresstype=bech32 always use a P2WPKH change output (unless changetype is set otherwise):")
        self.test_change_output_type(3, [to_address_bech32_1], 'bech32')
        self.test_change_output_type(3, [to_address_p2sh], 'bech32')

        self.log.info('getrawchangeaddress defaults to addresstype if -changetype is not set and argument is absent')
        self.test_address(3, self.nodes[3].getrawchangeaddress(), multisig=False, typ='bech32')

        self.log.info('test invalid address type arguments')
        assert_raises_rpc_error(-5, "Unknown address type ''", self.nodes[3].addmultisigaddress, 2, [compressed_1, compressed_2], None, '')
        assert_raises_rpc_error(-5, "Unknown address type ''", self.nodes[3].getnewaddress, None, '')
        assert_raises_rpc_error(-5, "Unknown address type ''", self.nodes[3].getrawchangeaddress, '')
        assert_raises_rpc_error(-5, "Unknown address type 'bech23'", self.nodes[3].getrawchangeaddress, 'bech23')

        self.log.info("Nodes with changetype=p2sh-segwit never use a P2WPKH change output")
        self.test_change_output_type(4, [to_address_bech32_1], 'p2sh-segwit')
        self.test_address(4, self.nodes[4].getrawchangeaddress(), multisig=False, typ='p2sh-segwit')
        self.log.info("Except for getrawchangeaddress if specified:")
        self.test_address(4, self.nodes[4].getrawchangeaddress(), multisig=False, typ='p2sh-segwit')
        self.test_address(4, self.nodes[4].getrawchangeaddress('bech32'), multisig=False, typ='bech32')

if __name__ == '__main__':
    AddressTypeTest().main()


text:
PACKAGE_NAME="opentelemetry-java"
PACKAGE_VERSION=${1:-"v1.16.0"}
PACKAGE_URL="https://github.com/open-telemetry/opentelemetry-java"
OS_NAME=$(grep ^PRETTY_NAME /etc/os-release | cut -d= -f2)
HOME_DIR=$PWD

echo "insstalling dependencies from system repo..."
dnf install -qy git make gcc-c++ java-17-openjdk-devel libtool file diffutils bc

echo "cloning..."
if ! git clone -q $PACKAGE_URL $PACKAGE_NAME; then
	echo "------------------$PACKAGE_NAME:clone_fails---------------------------------------"
	echo "$PACKAGE_URL $PACKAGE_NAME"
	echo "$PACKAGE_NAME  |  $PACKAGE_URL |  $PACKAGE_VERSION | $OS_NAME | GitHub | Fail |  Clone_Fails"
	exit 1
fi

cd $PACKAGE_NAME
git checkout "$PACKAGE_VERSION"
export GRPC_JAVA_VERSION=$(grep -m1 grpc-bom dependencyManagement/build.gradle.kts | cut -f3 -d ":" | sed "s/\",//")
export PROTOBUF_VERSION=$(grep -m1 protobuf-bom dependencyManagement/build.gradle.kts | cut -f3 -d ":" | sed "s/\",//")

sed -i "s/mavenLocal/mavenCentral/" settings.gradle.kts
sed -i "0,/mavenCentral/s/mavenCentral/mavenLocal/" settings.gradle.kts

# building  and installing  protobuf from source
cd "$HOME_DIR"
git clone -q https://github.com/protocolbuffers/protobuf
cd protobuf
git checkout v"$PROTOBUF_VERSION"
git submodule update --init
./autogen.sh
./configure
make -j"$(nproc)" && make install

#building and installing grpc-java
cd "$HOME_DIR"
git clone -q https://github.com/grpc/grpc-java
cd grpc-java
git checkout v"$GRPC_JAVA_VERSION"
sed -i "s/checkArch \"\$FILE\"/#checkArch \"\$FILE\"/" ./compiler/check-artifact.sh
./gradlew publishToMavenLocal -PskipAndroid=true

cd "$HOME_DIR"/$PACKAGE_NAME
if ! ./gradlew build; then
	echo "------------------$PACKAGE_NAME:install_fails-------------------------------------"
	echo "$PACKAGE_URL $PACKAGE_NAME"
	echo "$PACKAGE_NAME  |  $PACKAGE_URL | $PACKAGE_VERSION | $OS_NAME | GitHub | Fail |  Install_Fails"
	exit 1
fi

if ! ./gradlew test; then
	echo "------------------$PACKAGE_NAME:install_success_but_test_fails---------------------"
	echo "$PACKAGE_URL $PACKAGE_NAME"
	echo "$PACKAGE_NAME  |  $PACKAGE_URL | $PACKAGE_VERSION | $OS_NAME | GitHub | Fail |  Install_success_but_test_Fails"
	exit 1
else
	echo "------------------$PACKAGE_NAME:install_&_test_both_success-------------------------"
	echo "$PACKAGE_URL $PACKAGE_NAME"
	echo "$PACKAGE_NAME  |  $PACKAGE_URL | $PACKAGE_VERSION | $OS_NAME | GitHub  | Pass |  Both_Install_and_Test_Success"
	exit 0
fi


text:
const _ = require('lodash');

const fs = require('fs');

/**
 * @memberOf FileUtil
 * @function fdatasyncSync
 *
 * Synchronous {@link http://man7.org/linux/man-pages/man2/fdatasync.2.html|fdatasync(2)}.
 *
 * @param {Object} options
 * @param {Number} options.fd
 *
 * @returns {undefined}
 * @see {@link https://nodejs.org/api/fs.html#fs_fs_fdatasyncsync_fd}
 */
var fdatasyncSync = function (options) {
    var fd = _.get(options, 'fd');

    return fs.fdatasyncSync(fd);
};

module.exports = fdatasyncSync;


text:
import tensorflow as tf
import numpy as np
import os

TRAIN_FILE = 'train.tfrecords'
VALIDATION_FILE = 'valid.tfrecords'
TEST_FILE = 'test.tfrecords'

def accuracy(predictions, labels):
    acc = (100.0 * np.sum(np.argmax(predictions, 1) == np.argmax(labels, 1)) / predictions.shape[0])
    return acc
    # ppv, tpr

def variable_summaries(var, name):
    # Attach a lot of summaries to a Tensor (for TensorBoard visualization).

    with tf.name_scope('summaries_'+ name):
        mean = tf.reduce_mean(var)
        tf.scalar_summary('mean_' + name, mean)
        #with tf.name_scope('stddev'):
        stddev = tf.sqrt(tf.reduce_mean(tf.square(var - mean)))
        tf.scalar_summary('stddev_' + name, stddev)
        tf.scalar_summary('max_' + name, tf.reduce_max(var))
        tf.scalar_summary('min_' + name, tf.reduce_min(var))
        tf.histogram_summary('histogram_' + name, var)

def reformat(dataset, labels, num_labels):
    # input:    dataset     - 3D tensor (batch_size, num_features, num_points)
    # input:    labels      - 1D tensor (batch_size)
    # input:    num_labels  - number of labels
    # output:   dataset     - dataset reshaped in a 2D tensor (batch_size, num_features*num_points)
    # output:   labels      - labels reshaped in a (batch_size, num_labels)

    dataset = tf.reshape(dataset, [-1, dataset.shape[1] * dataset.shape[2]])

    # Map 0 to [1.0, 0.0, 0.0 ...], 1 to [0.0, 1.0, 0.0 ...]
    labels = (np.arange(num_labels) == labels[:, None]).astype(np.float32)
    return dataset, labels

def inference(train_data, num_hidden, num_labels, is_training):
    # input:    train_data      - train tensor [batch_size, num_data]
    # input:    num_hidden      - number of hidden layers
    # input:    num_data        - num_feature*num_points
    # input:    num_labels      - number of labels
    # input:    valid_data      - valid tensor
    # output:   logits          - tensor of computed train_logits
    # output:   valid           - tensor of computed valid_logits
    # output:   saver           - saver of the model

    num_data = int(train_data.get_shape()[1])
    train_data = batch_norm(train_data, is_training)
    with tf.name_scope('Hidden1'):
        w_1 = tf.Variable(
            tf.truncated_normal(shape=(num_data, num_hidden), dtype=tf.float32), name='w_1')
        b_1 = tf.Variable(tf.zeros([num_hidden], dtype=tf.float32), name='b_1', dtype=tf.float32)
        h_final = tf.nn.relu(tf.matmul(train_data, w_1) + b_1)

    # with tf.name_scope('Hidden2'):
    #     w_2 = tf.Variable(
    #         tf.truncated_normal([num_hidden, num_hidden]), name='w_2')
    #     b_2 = tf.Variable(tf.zeros([num_hidden]), name='b_2')
    #     h_final = tf.nn.relu(tf.matmul(h_1, w_2) + b_2)

    with tf.name_scope('Final'):
        w_final = tf.Variable(
            tf.truncated_normal([num_hidden, num_labels], dtype=tf.float32), name='w_final')
        b_final = tf.Variable(tf.zeros([num_labels], dtype=tf.float32), name='b_final')
        logits = tf.matmul(h_final, w_final) + b_final
    # tf.histogram_summary("Logits", logits)

    return logits

def loss(logits, labels):
    # input:    logits      - logits tensor, [batch_size, num_labels]
    # input:    labels      - labels tensor, [batch_size, num_labels]
    # output:   loss        - loss tensor of type float.
    # logits = tf.cast(logits, tf.float32)
    loss = tf.reduce_mean(
        tf.nn.softmax_cross_entropy_with_logits(labels=labels, logits=logits))
        # tf.nn.weighted_cross_entropy_with_logits(targets=labels, logits=logits, pos_weight=0.8, name=None))

    tf.summary.scalar('loss', loss)
    return loss

def training(l, lr):
    # input: l          -loss tensor from loss()
    # input: lr         - learning_rate scalar for gradient descent
    # output: train_op  - the operation for training

    # train_op = tf.train.GradientDescentOptimizer(lr).minimize(l)
    train_op = tf.train.AdamOptimizer(learning_rate=lr).minimize(l)
    return train_op

def batch_norm(inputs, is_training, decay = 0.80):
    scale = tf.Variable(tf.ones([]))
    beta = tf.Variable(tf.zeros([]))
    pop_mean = tf.Variable(tf.zeros([]), trainable=False)
    pop_var = tf.Variable(tf.ones([]), trainable=False)
    epsilon = 0.0001
    if is_training:
        batch_mean, batch_var = tf.nn.moments(inputs, [0, 1])
        print_tensor_shape(batch_mean, "Batch Mean")
        print_tensor_shape(batch_var, "Batch Var")
        print_tensor_shape(pop_mean, "Pop Mean")
        print_tensor_shape(pop_var, "Pop Var")
        train_mean = tf.assign(pop_mean,
                               pop_mean * decay + batch_mean * (1 - decay))
        train_var = tf.assign(pop_var,
                              pop_var * decay + batch_var * (1 - decay))
        with tf.control_dependencies([train_mean, train_var]):
            return tf.nn.batch_normalization(inputs,
                batch_mean, batch_var, beta, scale, epsilon)
    else:
        return tf.nn.batch_normalization(inputs,
            pop_mean, pop_var, beta, scale, epsilon)

def inference_conv(train_data, patch_size, num_features, num_points, num_hidden, num_labels, is_training):
    # Variables.
    # print "data", data.get_shape()
    train_data = tf.cast(train_data, tf.float32)
    depth = 100
    w_1 = tf.Variable(tf.truncated_normal(
        [patch_size, num_features, num_features], stddev=0.1, dtype=tf.float32))
    # b_1 = tf.Variable(tf.zeros([num_points]))
    w_1_2 = tf.Variable(tf.truncated_normal(
        [patch_size, num_features, depth], stddev=0.1, dtype=tf.float32))

    w_2 = tf.Variable(tf.truncated_normal(
        [patch_size, depth, depth], stddev=0.1, dtype=tf.float32))
    b_2 = tf.Variable(tf.constant(1.0, shape=[num_points]))

    w_3 = tf.Variable(tf.truncated_normal(
        [patch_size, patch_size, depth/2, depth], stddev=0.1, dtype=tf.float32))

    w_3_1 = tf.Variable(tf.truncated_normal(
        [patch_size, patch_size, depth, depth], stddev=0.1, dtype=tf.float32))

    # w_4 = tf.Variable(tf.truncated_normal(
    #     [depth * depth, num_hidden], stddev=0.1))
    # w_4 = tf.Variable(tf.truncated_normal(
    #     [num_points * depth, num_hidden], stddev=0.1))
    w_4 = tf.Variable(tf.truncated_normal(
        [num_points * depth, num_hidden], stddev=0.1, dtype=tf.float32))
    b_4 = tf.Variable(tf.constant(1.0, shape=[num_hidden], dtype=tf.float32))
    w_final = tf.Variable(tf.truncated_normal(
        [num_hidden, num_labels], stddev=0.1, dtype=tf.float32))
    b_final = tf.Variable(tf.constant(1.0, shape=[num_labels], dtype=tf.float32))

    # Model.
    def model(data):
        with tf.name_scope('Layer1'):
            data = batch_norm(data, is_training)
            # data = tf.expand_dims(data, 3)
            conv = tf.nn.conv1d(data, w_1, 1, padding='SAME', data_format="NCHW")
            print "conv:", conv.get_shape()
            # hidden = tf.nn.relu(conv + b_1)
            hidden = tf.nn.relu(conv)
            # hidden = batch_norm(hidden, num_points)
            print "hidden:", hidden.get_shape()

        with tf.name_scope('Layer2'):
            # hidden = batch_norm(hidden, is_training)
            conv = tf.nn.conv1d(hidden, w_1_2, 1, padding='SAME', data_format="NCHW")
            print "conv:", conv.get_shape()
            hidden = tf.nn.relu(conv)
            print "hidden:", hidden.get_shape()

        # with tf.name_scope('Layer3'):
        #     # hidden = batch_norm(hidden, is_training)
        #     hidden = tf.expand_dims(hidden, 3)
        #     conv = tf.nn.conv2d(hidden, w_3, [1, 1, 1, 1], padding='SAME', data_format="NCHW")
        #     print "conv:", conv.get_shape()
        #     hidden = tf.nn.relu(conv)
        #     print "hidden:", hidden.get_shape()

        # with tf.name_scope('Layer4'):
            # conv = tf.nn.conv1d(hidden, w_2, 1, padding='SAME', data_format="NCHW")
            # print "conv:", conv.get_shape()
            # hidden = tf.nn.relu(conv)
            # print "hidden:", hidden.get_shape()

        # with tf.name_scope('Layer5'):
            # conv = tf.nn.conv2d(hidden, w_3_1, [1, 1, 1, 1], padding='SAME', data_format="NCHW")
            # print "conv:", conv.get_shape()
            # hidden = tf.nn.relu(conv)
            # print "hidden:", hidden.get_shape()

        # with tf.name_scope('Layer6'):
            # conv = tf.nn.conv1d(hidden, w_3, 1, padding='SAME')
            # print "conv:", conv.get_shape()
            # hidden = tf.nn.relu(conv)
            # print "hidden:", hidden.get_shape()

        # with tf.name_scope('Layer7'):
            # conv = tf.nn.conv1d(hidden, w_2, 1, padding='SAME')
            # print "conv:", conv.get_shape()
            # hidden = tf.nn.relu(conv)
            # print "hidden:", hidden.get_shape()
        with tf.name_scope('LastLayer'):
            # hidden = tf.squeeze(hidden, [3])
            # hidden = batch_norm(hidden, is_training)
            shape = hidden.get_shape().as_list()
            print "shape", shape
            reshape = tf.reshape(hidden, [shape[0], shape[1] * shape[2]])
            hidden = tf.nn.relu(tf.matmul(reshape, w_4) + b_4)
        # hidden = batch_norm(hidden, num_hidden)
        # hidden = batch_norm(hidden, is_training)
        return tf.matmul(hidden, w_final) + b_final

    logits = model(train_data)

    return logits #, valid, saver
#     with tf.name_scope('Hidden1'):
#         w_1 = tf.Variable(
#             tf.truncated_normal([num_data, num_hidden]), name='w_1')
#         b_1 = tf.Variable(tf.zeros([num_hidden]), name='b_1')
#         h_final = tf.nn.relu(tf.matmul(train_data, w_1) + b_1)
#
#     # with tf.name_scope('Hidden2'):
#     #     w_2 = tf.Variable(
#     #         tf.truncated_normal([num_hidden, num_hidden]), name='w_2')
#     #     b_2 = tf.Variable(tf.zeros([num_hidden]), name='b_2')
#     #     h_final = tf.nn.relu(tf.matmul(h_1, w_2) + b_2)
#
#     with tf.name_scope('Final'):
#         w_final = tf.Variable(
#             tf.truncated_normal([num_hidden, num_labels]), name='w_final')
#         b_final = tf.Variable(tf.zeros([num_labels]), name='b_final')
#         logits = tf.matmul(h_final, w_final) + b_final
#     # tf.histogram_summary("Logits", logits)
#
#     saver = tf.train.Saver({"w_1": w_1, "b_1": b_1, "w_final": w_final, "b_final": b_final}, max_to_keep=10000)
#
#     if valid_data is not None:
#         valid = tf.matmul(tf.nn.relu(tf.matmul(valid_data, w_1) + b_1), w_final) + b_final
#     else:
#         valid = None
#     return logits, valid, saver

def read_and_decode(filename_queue, label_type_int64):
    reader = tf.TFRecordReader()
    _, serialized_example = reader.read(filename_queue)
    features = tf.parse_single_example(
      serialized_example,
      # Defaults are not specified since both keys are required.
      features={
          'fiber_raw': tf.FixedLenFeature([], tf.string),
          'label': tf.FixedLenFeature([], tf.string),
      })
    # Convert from a scalar string tensor (whose single string has

    fiber = tf.decode_raw(features['fiber_raw'], tf.float64)
    fiber = tf.cast(fiber, tf.float32)
    if label_type_int64:
        label = tf.decode_raw(features['label'], tf.int64)
        label.set_shape([1])
    else:
        label = features['label']

    return fiber, label

def reformat_train_label(labels, num_labels):
    labels_re = tf.reshape(labels, [-1])
    labels_re = tf.one_hot(labels_re, depth=num_labels)
    return labels_re

def reformat_test_label(labels, num_labels):
    # labels_re = tf.string(labels, out_type=tf.int32)
    labels_re = tf.one_hot(labels, num_labels)
    return labels_re

def inputs(dir, type,  batch_size, num_epochs, conv=False):
    """Reads input data num_epochs times.
    Args:
    train: Selects between the training (True) and validation (False) data.
    batch_size: Number of examples per returned batch.
    num_epochs: Number of times to read the input data, or 0/None to
       train forever.
    Returns:
    A tuple (images, labels), where:
    * images is a float tensor with shape [batch_size, mnist.IMAGE_PIXELS]
      in the range [-0.5, 0.5].
    * labels is an int32 tensor with shape [batch_size] with the true label,
      a number in the range [0, mnist.NUM_CLASSES).
    Note that an tf.train.QueueRunner is added to the graph, which
    must be run using e.g. tf.train.start_queue_runners().
    """

    if not num_epochs:
        num_epochs = None

    if type == 'train':
        label_int = True
        filename = os.path.join(dir, TRAIN_FILE)

    elif type == 'valid':
        label_int = True
        filename = os.path.join(dir, VALIDATION_FILE)

    elif type == 'test':
        label_int = False
        filename = os.path.join(dir, TEST_FILE)

    record_iterator = tf.python_io.tf_record_iterator(path=filename)

    for string_record in record_iterator:
        break
    example = tf.train.Example()
    example.ParseFromString(string_record)

    nb_pts = int(example.features.feature['num_points'].int64_list.value[0])

    nb_ft = int(example.features.feature['num_features'].int64_list.value[0])

    with tf.name_scope('input'):
        filename_queue = tf.train.string_input_producer(
            [filename], num_epochs=num_epochs)

        # Even when reading in multiple threads, share the filename
        # queue.
        fiber, label = read_and_decode(filename_queue, label_int)

        fiber.set_shape([nb_pts*nb_ft])

        if conv:
            fiber = tf.reshape(fiber, [nb_ft, nb_pts])

        # label = tf.reshape(label, [-1])

        # fiber_re = tf.reshape(fiber, [nb_ft, nb_pts])

        print "Shape :", fiber.get_shape()
        print "Shape :", label.get_shape()
        # Shuffle the examples and collect them into batch_size batches.
        # (Internally uses a RandomShuffleQueue.)
        # We run this in two threads to avoid being a bottleneck.
        fibers, sparse_labels = tf.train.shuffle_batch(
            [fiber, label], batch_size=batch_size, num_threads=4,
            capacity=1000 + 3 * batch_size,
            # Ensures a minimum amount of shuffling of examples.
            min_after_dequeue=1000)
    return fibers, sparse_labels

def reformat_conv(dataset, num_features, num_points, labels, num_labels):
    num_channels = 1
    dataset = dataset.reshape(
        (-1, num_features, num_points)).astype(np.float32)
    labels = (np.arange(num_labels) == labels[:, None]).astype(np.float32)
    return dataset, labels

def evaluation (logits, labels, batch_size):
    # input: logits: Logits tensor, float - [batch_size, 256, 256, NUM_CLASSES].
    # input: labels: Labels tensor, int32 - [batch_size, 256, 256]
    # output: scaler int32 tensor with number of examples that were
    #         predicted correctly
    logits = tf.cast(logits, dtype=tf.float32)
    labels = tf.reshape(labels, [-1])
    print ""
    print_tensor_shape(labels, "labels")
    print_tensor_shape(logits, "logits")
    size = 100/batch_size # = 100*(1/batch_size)

    # _, eval = tf.nn.top_k(logits, k=1)
    eval = tf.nn.in_top_k(logits, labels, k=1)
    # eval = tf.cast(eval, dtype=tf.int8)
    eval = tf.reshape(eval, [-1])
    print_tensor_shape(eval, "eval")
    # num_true = tf.where(eval)
    non_zero = tf.count_nonzero(eval)
    # print_tensor_shape(non_zero, "non_zero")
    acc = tf.scalar_mul(size, non_zero)
    # print_tensor_shape(acc, "acc")
    return acc

def print_tensor_shape(tensor, string):
# input: tensor and string to describe it
    if __debug__:
        print('DEBUG ' + string, tensor.get_shape())


text:
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.Set;

import com.google.common.collect.Sets;
import com.google.common.io.CharStreams;
import com.inn.trusthings.integration.TrustFilterByExclusion;
import com.inn.trusthings.integration.TrustFilterByThreshold;
import com.inn.trusthings.integration.TrustScorer;
import com.inn.trusthings.integration.util.RequestBody;

public class InvokeTrustRestFiltering {

	public static void main(String[] args) {
		InputStream is = RequestBody.class.getResourceAsStream("/parameters.json");
		String	criteria = null;
		try {
			Set<URI> set = Sets.newHashSet();
			set.add(new URI("http://abiell.pc.ac.upc.edu:9081/iserve/id/services/d905ea82-ae6d-4eb1-9719-0b801e5c758b/google-maps"));
			set.add(new URI("http://abiell.pc.ac.upc.edu:9081/iserve/id/services/bfef4357-0da5-47d7-9beb-54dd95919179/microsoft-bing-maps"));
			criteria = CharStreams.toString(new InputStreamReader(is));
			is.close();
			if (new TrustFilterByExclusion().apply(set, criteria).isEmpty() == false){
				System.out.println("TrustFilterByExclusion OK");
			}
			if (new TrustFilterByThreshold().apply(set, criteria).isEmpty() == false){
				System.out.println("TrustFilterByThreshold OK");
			}
			if (new TrustScorer().apply(set, criteria).isEmpty() == false){
				System.out.println("TrustScorer OK");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}


text:
define(function(require){
  //
  // L O A D   T H E   A S S E T S   A N D   L I B R A R I E S
  //
  var Backbone   = require('backbone'),
      Collection = require('collections/municipios'),
      Big_cities = require('views/big_cities'),
      Worst_cities = require('views/worst_cities'),
      All_cities = require('views/all_cities'),
      SVG_map    = require('views/svg_map'),
      d3         = require('d3'),
      G          = require('goog!maps,3.17,other_params:sensor=false&region=MX'),
      Municipios = require('data/puebla'),
      Centros    = require('data/centros'),
      Colores    = require('data/colores');

  //
  // I N I T I A L I Z E   T H E   B A C K B O N E   V I E W
  //
  var controller = Backbone.View.extend({

    //
    // D E F I N E   T H E   E V E N T S
    //
    events : {

    },

    //
    // D E F I N E   T H E   T E M P L A T E S
    //

    //
    // S E T   T H E   C O N T A I N E R
    //
    el : "#main.placas",

    //
    // T H E   I N I T I A L I Z E   F U N C T I O N
    //
    initialize : function(){
      // city collection
      this.collection = new Collection(Municipios.puebla);

      // add the color attribute to the collection
      this.collection.each(function(city){
        city.set({
          color : Colores.color[city.get('level')]
        });
      }, this);

      // offices collection
      this.offices = new Backbone.Collection(Centros.centros);
      // the data array
      this.cities = [];

      // the bigger cities
      this.big_cities = [];

      // exectute the calc
      // this.map_data();

      // colorize :D & assign color values
      this.svg_map = new SVG_map({collection : this.collection});
      this.svg_map.render();

      // create the full list
      this.render_full_list();

      // render the big cities
      this.big_cities_view = new Big_cities({collection : this.collection});
      this.big_cities_view.render();

      this.worst_cities = new Worst_cities({collection : this.collection});
      this.worst_cities.render();

      this.all_cities = new All_cities({collection : this.collection});
      this.all_cities.render();

	  this.render_show_hide();

      // render the google map
      // this.render_google_map();
    },

    //
    // R E N D E R   T H E   C O M P L E T E   C I T Y   L I S T
    //
    render_full_list : function(){
      _.each(this.cities, function(city){
        var c = this.collection.findWhere({clave_municipio : city.clave_municipio});
        this.$('#just-all ol').append('
' + c.get('nombre_municipio') + '
');
      }, this);
    },

    //
    // R E N D E R   T H E   S H O W    / H I D E
    //
    render_show_hide: function() {
    	$("#top-ten").hide();
    	$("#worst-ten").hide();
    	$("#just-all").hide();
    	$("#info").hide();

		$("#nav a").on('click', function(){
			$("#nav").find("a").removeClass('current');
	  		event.preventDefault();
			var sectionName = $(this).attr("title");

			$(this).addClass("current");

			$("#top-ten").hide();
			$("#worst-ten").hide();
			$("#just-all").hide();
			$("#base-map").hide();
			$("#info").hide();

			$("#"+sectionName).show();

	  });
    },

    //
    // R E N D E R   T H E   G O O G L E   M A P
    //
    render_google_map : function(){
      // set the map
      var mapOptions = {
        center      : { lat: 19.015416145324707, lng: -98.15610885620117}, // puebla
        zoom        : 8,
        scrollwheel : false
      };
      var map = new google.maps.Map(document.getElementById('centers-and-big-cities'), mapOptions);

      // put the markers on the offices
      var centers = [];
      var cities  = [];
      var center_color = "ffffff";//"3292e6";

      // RENDER THE OFFICE MARKERS
      this.offices.each(function(center){
        // get a marker with the marker color
        var pinImage = new google.maps.MarkerImage("http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|" + center_color,
          new google.maps.Size(21, 34),
          new google.maps.Point(0,0),
          new google.maps.Point(10, 34));

        // create the marker
        centers.push(new google.maps.Marker({
          position: new google.maps.LatLng(center.get('lat'),center.get('lng')),
          map: map,
          icon: pinImage
        }));
      }, this);

      // RENDER THE CITY MARKERS
      _.each(this.big_cities, function(city){
        var c = this.collection.findWhere({clave_municipio : city.clave_municipio});
        var city_color = Colores.colorhex[c.get('level')];
        // get a marker with the marker color
        var pinImage = new google.maps.MarkerImage("http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|" + city_color,
          new google.maps.Size(21, 34),
          new google.maps.Point(0,0),
          new google.maps.Point(10, 34));

        // create the marker
        cities.push(new google.maps.Marker({
          position: new google.maps.LatLng(c.get('lat'),c.get('lng')),
          map: map,
          icon: pinImage
        }));
      }, this);
    }
  });

  return controller;
});


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
Bull. Soc. linn. Normandie, sér. 2 4: 159 (1870)

#### Original name
Ramalina cuspidata var. crassa Delise ex Nyl.

### Remarks
null


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <dimen name="swipe_cell_delete_image_margin">16dp</dimen>
    <dimen name="swipe_cell_delete_text_size">12sp</dimen>
</resources>


text:
/*
 * This Java source file was generated by the Gradle 'init' task.
 */
public class App {
    public String getGreeting() {
        return "Hello world.";
    }

    public static void main(String[] args) {
        System.out.println(new App().getGreeting());
    }
}


text:
package com.oblador.keychain.decryptionHandler;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.oblador.keychain.cipherStorage.CipherStorage.DecryptionContext;
import com.oblador.keychain.cipherStorage.CipherStorage.DecryptionResult;

/** Handler that allows to inject some actions during decrypt operations. */
public interface DecryptionResultHandler {
  /** Ask user for interaction, often its unlock of keystore by biometric data providing. */
  void askAccessPermissions(@NonNull final DecryptionContext context);

  /**
   *
   */
  void onDecrypt(@Nullable final DecryptionResult decryptionResult, @Nullable final Throwable error);

  /** Get reference on results. */
  @Nullable
  DecryptionResult getResult();

  /** Get reference on capture error. */
  @Nullable
  Throwable getError();

  /** Block thread and wait for any result of execution. */
  void waitResult();
}