text:
using ProjectManager.Commands;
using ProjectManager.Common.Exceptions;
using ProjectManager.Contracts;
using ProjectManager.Data;
using ProjectManager.Factories;
using ProjectManager.Factories.Contracts;
using ProjectManager.Models;
using ProjectManager.Models.Contracts;
using System;

namespace ProjectManager.Factories
{
    public class CommandsFactory : ICommandsFactory
    {
        private Database db;

        private ModelsFactory engine;

        public CommandsFactory(Database db, ModelsFactory engine)
        {
            this.db = db;
            this.engine = engine;
        }

        public ICommand CreateCommandFromString(string commandName)
        {
            var command = this.BuildCommand(commandName);

            switch (command)
            {
                case "createproject": return new CreateProjectCommand(this.db, this.engine);
                case "createtask": return new CreateTaskCommand();
                case "listprojects": return new ListProjectsCommand(this.db);
                case "createuser": return new CreateUserCommand();
                case "listprojectdetails": return new ListProjectDetails(this.db);
                default: throw new UserValidationException("The passed command is not valid!");
            }
        }

        private string BuildCommand(string parameters)
        {
            var command = parameters.ToLower();
            return command;
        }
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>{{ site.name }}</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="">
    <meta name="author" content="">
    {% bundle %}
    - /_assets/fonts.css
    - /_assets/bootstrap-arimo.min.css
    - /_assets/site.css
    - /_assets/bootstrap-responsive.min.css
    {% endbundle %}
    <link href="/favicon.png" rel="shortcut icon" type="image/png">

{{ site.description }}

            {{ site.name }}

redpajama_set_name: RedPajamaGithub


text:
package server

import (
	"context"

	"github.com/GoogleCloudPlatform/declarative-resource-client-library/dcl"
	computepb "github.com/GoogleCloudPlatform/declarative-resource-client-library/python/proto/compute/compute_go_proto"
	emptypb "github.com/GoogleCloudPlatform/declarative-resource-client-library/python/proto/empty_go_proto"
	"github.com/GoogleCloudPlatform/declarative-resource-client-library/services/google/compute"
)

// Server implements the gRPC interface for TargetVpnGateway.
type TargetVpnGatewayServer struct{}

// ProtoToTargetVpnGatewayStatusEnum converts a TargetVpnGatewayStatusEnum enum from its proto representation.
func ProtoToComputeTargetVpnGatewayStatusEnum(e computepb.ComputeTargetVpnGatewayStatusEnum) *compute.TargetVpnGatewayStatusEnum {
	if e == 0 {
		return nil
	}
	if n, ok := computepb.ComputeTargetVpnGatewayStatusEnum_name[int32(e)]; ok {
		e := compute.TargetVpnGatewayStatusEnum(n[len("ComputeTargetVpnGatewayStatusEnum"):])
		return &e
	}
	return nil
}

// ProtoToTargetVpnGateway converts a TargetVpnGateway resource from its proto representation.
func ProtoToTargetVpnGateway(p *computepb.ComputeTargetVpnGateway) *compute.TargetVpnGateway {
	obj := &compute.TargetVpnGateway{
		Id:          dcl.Int64OrNil(p.Id),
		Name:        dcl.StringOrNil(p.Name),
		Description: dcl.StringOrNil(p.Description),
		Region:      dcl.StringOrNil(p.Region),
		Network:     dcl.StringOrNil(p.Network),
		Status:      ProtoToComputeTargetVpnGatewayStatusEnum(p.GetStatus()),
		SelfLink:    dcl.StringOrNil(p.SelfLink),
		Project:     dcl.StringOrNil(p.Project),
	}
	for _, r := range p.GetTunnel() {
		obj.Tunnel = append(obj.Tunnel, r)
	}
	for _, r := range p.GetForwardingRule() {
		obj.ForwardingRule = append(obj.ForwardingRule, r)
	}
	return obj
}

// TargetVpnGatewayStatusEnumToProto converts a TargetVpnGatewayStatusEnum enum to its proto representation.
func ComputeTargetVpnGatewayStatusEnumToProto(e *compute.TargetVpnGatewayStatusEnum) computepb.ComputeTargetVpnGatewayStatusEnum {
	if e == nil {
		return computepb.ComputeTargetVpnGatewayStatusEnum(0)
	}
	if v, ok := computepb.ComputeTargetVpnGatewayStatusEnum_value["TargetVpnGatewayStatusEnum"+string(*e)]; ok {
		return computepb.ComputeTargetVpnGatewayStatusEnum(v)
	}
	return computepb.ComputeTargetVpnGatewayStatusEnum(0)
}

// TargetVpnGatewayToProto converts a TargetVpnGateway resource to its proto representation.
func TargetVpnGatewayToProto(resource *compute.TargetVpnGateway) *computepb.ComputeTargetVpnGateway {
	p := &computepb.ComputeTargetVpnGateway{
		Id:          dcl.ValueOrEmptyInt64(resource.Id),
		Name:        dcl.ValueOrEmptyString(resource.Name),
		Description: dcl.ValueOrEmptyString(resource.Description),
		Region:      dcl.ValueOrEmptyString(resource.Region),
		Network:     dcl.ValueOrEmptyString(resource.Network),
		Status:      ComputeTargetVpnGatewayStatusEnumToProto(resource.Status),
		SelfLink:    dcl.ValueOrEmptyString(resource.SelfLink),
		Project:     dcl.ValueOrEmptyString(resource.Project),
	}
	for _, r := range resource.Tunnel {
		p.Tunnel = append(p.Tunnel, r)
	}
	for _, r := range resource.ForwardingRule {
		p.ForwardingRule = append(p.ForwardingRule, r)
	}

	return p
}

// ApplyTargetVpnGateway handles the gRPC request by passing it to the underlying TargetVpnGateway Apply() method.
func (s *TargetVpnGatewayServer) applyTargetVpnGateway(ctx context.Context, c *compute.Client, request *computepb.ApplyComputeTargetVpnGatewayRequest) (*computepb.ComputeTargetVpnGateway, error) {
	p := ProtoToTargetVpnGateway(request.GetResource())
	res, err := c.ApplyTargetVpnGateway(ctx, p)
	if err != nil {
		return nil, err
	}
	r := TargetVpnGatewayToProto(res)
	return r, nil
}

// ApplyTargetVpnGateway handles the gRPC request by passing it to the underlying TargetVpnGateway Apply() method.
func (s *TargetVpnGatewayServer) ApplyComputeTargetVpnGateway(ctx context.Context, request *computepb.ApplyComputeTargetVpnGatewayRequest) (*computepb.ComputeTargetVpnGateway, error) {
	cl, err := createConfigTargetVpnGateway(ctx, request.ServiceAccountFile)
	if err != nil {
		return nil, err
	}
	return s.applyTargetVpnGateway(ctx, cl, request)
}

// DeleteTargetVpnGateway handles the gRPC request by passing it to the underlying TargetVpnGateway Delete() method.
func (s *TargetVpnGatewayServer) DeleteComputeTargetVpnGateway(ctx context.Context, request *computepb.DeleteComputeTargetVpnGatewayRequest) (*emptypb.Empty, error) {

	cl, err := createConfigTargetVpnGateway(ctx, request.ServiceAccountFile)
	if err != nil {
		return nil, err
	}
	return &emptypb.Empty{}, cl.DeleteTargetVpnGateway(ctx, ProtoToTargetVpnGateway(request.GetResource()))

}

// ListComputeTargetVpnGateway handles the gRPC request by passing it to the underlying TargetVpnGatewayList() method.
func (s *TargetVpnGatewayServer) ListComputeTargetVpnGateway(ctx context.Context, request *computepb.ListComputeTargetVpnGatewayRequest) (*computepb.ListComputeTargetVpnGatewayResponse, error) {
	cl, err := createConfigTargetVpnGateway(ctx, request.ServiceAccountFile)
	if err != nil {
		return nil, err
	}

	resources, err := cl.ListTargetVpnGateway(ctx, request.Project, request.Region)
	if err != nil {
		return nil, err
	}
	var protos []*computepb.ComputeTargetVpnGateway
	for _, r := range resources.Items {
		rp := TargetVpnGatewayToProto(r)
		protos = append(protos, rp)
	}
	return &computepb.ListComputeTargetVpnGatewayResponse{Items: protos}, nil
}

func createConfigTargetVpnGateway(ctx context.Context, service_account_file string) (*compute.Client, error) {

	conf := dcl.NewConfig(dcl.WithUserAgent("dcl-test"), dcl.WithCredentialsFile(service_account_file))
	return compute.NewClient(conf), nil
}


text: The main web size


text:
module Main where

import Language.TECS.Jack.ToDeck.Layout
import Language.TECS.Jack.ToDeck.Compile
import Language.TECS.Jack.Parser

import System.Environment (getArgs)
import System.FilePath (replaceExtension)
import System.IO (hPutStrLn, stderr, withFile, IOMode(..))

import qualified Data.ByteString.Lazy as BS (readFile)
import Text.PrettyPrint.HughesPJClass (pPrint)
import Text.PrettyPrint.HughesPJ (render)

main =
  do
    filenames <- getArgs
    mapM_ compileFile filenames

compileFile filename =
  do
    putStr $ unwords ["Compiling", filename, "... "]
    bs <- BS.readFile filename
    case parseJack bs filename of
      Left err ->
        do
          putStrLn ""
          hPutStrLn stderr err
      Right jack ->
        do
          -- Use withFile/hPutStrLn to ensure terminating newline
          withFile outfile WriteMode $ \h -> do
            hPutStrLn h $ render . pPrint $ compile . layout $ jack
          putStrLn $ unwords ["created", outfile]
  where
    outfile = replaceExtension filename "deck"


text:
package org.jkiss.dbeaver.registry.driver;

import org.jkiss.dbeaver.DBException;
import org.jkiss.dbeaver.model.connection.DBPNativeClientLocation;
import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor;

import java.io.File;

/**
 * LocalNativeClientLocation
 */
public class LocalNativeClientLocation implements DBPNativeClientLocation {
    private final String id;
    private final File path;

    public LocalNativeClientLocation(String id, String path) {
        this.id = id;
        this.path = new File(path != null ? path : id);
    }

    @Override
    public String getName() {
        return id;
    }

    @Override
    public File getPath() {
        return path;
    }

    @Override
    public String getDisplayName() {
        return path.getAbsolutePath();
    }

    @Override
    public boolean validateFilesPresence(DBRProgressMonitor progressMonitor) throws DBException {
        return true;
    }

    @Override
    public String toString() {
        File path = getPath();
        return "Local: " + (path == null ? id : path.getAbsolutePath());
    }

    @Override
    public boolean equals(Object obj) {
        return obj instanceof DBPNativeClientLocation && ((DBPNativeClientLocation) obj).getName().equals(getName());
    }
}


text:
<?php

namespace CodeIgniter;

use BadMethodCallException;
use Closure;
use CodeIgniter\Database\BaseBuilder;
use CodeIgniter\Database\BaseConnection;
use CodeIgniter\Database\BaseResult;
use CodeIgniter\Database\ConnectionInterface;
use CodeIgniter\Database\Exceptions\DatabaseException;
use CodeIgniter\Database\Exceptions\DataException;
use CodeIgniter\Database\Query;
use CodeIgniter\Exceptions\ModelException;
use CodeIgniter\I18n\Time;
use CodeIgniter\Validation\ValidationInterface;
use Config\Database;
use ReflectionClass;
use ReflectionException;
use ReflectionProperty;

/**
 * Class Model
 *
 * The Model class extends BaseModel and provides additional
 * convenient features that makes working with a SQL database
 * table less painful.
 *
 * It will:
 *      - automatically connect to database
 *      - allow intermingling calls to the builder
 *      - removes the need to use Result object directly in most cases
 *
 * @mixin    BaseBuilder
 * @property BaseConnection $db
 */
class Model extends BaseModel
{
	/**
	 * Name of database table
	 *
	 * @var string
	 */
	protected $table;

	/**
	 * The table's primary key.
	 *
	 * @var string
	 */
	protected $primaryKey = 'id';

	/**
	 * Whether primary key uses auto increment.
	 *
	 * @var boolean
	 */
	protected $useAutoIncrement = true;

	/**
	 * Query Builder object
	 *
	 * @var BaseBuilder|null
	 */
	protected $builder;

	/**
	 * Holds information passed in via 'set'
	 * so that we can capture it (not the builder)
	 * and ensure it gets validated first.
	 *
	 * @var array
	 */
	protected $tempData = [];

	/**
	 * Escape array that maps usage of escape
	 * flag for every parameter.
	 *
	 * @var array
	 */
	protected $escape = [];

	/**
	 * Model constructor.
	 *
	 * @param ConnectionInterface|null $db         DB Connection
	 * @param ValidationInterface|null $validation Validation
	 */
	public function __construct(ConnectionInterface &$db = null, ValidationInterface $validation = null)
	{
		/**
		 * @var BaseConnection $db
		 */
		$db = $db ?? Database::connect($this->DBGroup);

		$this->db = &$db;

		parent::__construct($validation);
	}

	/**
	 * Specify the table associated with a model
	 *
	 * @param string $table Table
	 *
	 * @return $this
	 */
	public function setTable(string $table)
	{
		$this->table = $table;

		return $this;
	}

	/**
	 * Fetches the row of database from $this->table with a primary key
	 * matching $id. This methods works only with dbCalls
	 * This methods works only with dbCalls
	 *
	 * @param boolean                   $singleton Single or multiple results
	 * @param array|integer|string|null $id        One primary key or an array of primary keys
	 *
	 * @return array|object|null    The resulting row of data, or null.
	 */
	protected function doFind(bool $singleton, $id = null)
	{
		$builder = $this->builder();

		if ($this->tempUseSoftDeletes)
		{
			$builder->where($this->table . '.' . $this->deletedField, null);
		}

		if (is_array($id))
		{
			$row = $builder->whereIn($this->table . '.' . $this->primaryKey, $id)
				->get()
				->getResult($this->tempReturnType);
		}
		elseif ($singleton)
		{
			$row = $builder->where($this->table . '.' . $this->primaryKey, $id)
				->get()
				->getFirstRow($this->tempReturnType);
		}
		else
		{
			$row = $builder->get()->getResult($this->tempReturnType);
		}

		return $row;
	}

	/**
	 * Fetches the column of database from $this->table
	 * This methods works only with dbCalls
	 *
	 * @param string $columnName Column Name
	 *
	 * @return array|null The resulting row of data, or null if no data found.
	 */
	protected function doFindColumn(string $columnName)
	{
		return $this->select($columnName)->asArray()->find(); // @phpstan-ignore-line
	}

	/**
	 * Works with the current Query Builder instance to return
	 * all results, while optionally limiting them.
	 * This methods works only with dbCalls
	 *
	 * @param integer $limit  Limit
	 * @param integer $offset Offset
	 *
	 * @return array
	 */
	protected function doFindAll(int $limit = 0, int $offset = 0)
	{
		$builder = $this->builder();

		if ($this->tempUseSoftDeletes)
		{
			$builder->where($this->table . '.' . $this->deletedField, null);
		}

		return $builder->limit($limit, $offset)
			->get()
			->getResult($this->tempReturnType);
	}

	/**
	 * Returns the first row of the result set. Will take any previous
	 * Query Builder calls into account when determining the result set.
	 * This methods works only with dbCalls
	 *
	 * @return array|object|null
	 */
	protected function doFirst()
	{
		$builder = $this->builder();

		if ($this->tempUseSoftDeletes)
		{
			$builder->where($this->table . '.' . $this->deletedField, null);
		}
		elseif ($this->useSoftDeletes && empty($builder->QBGroupBy) && $this->primaryKey)
		{
			$builder->groupBy($this->table . '.' . $this->primaryKey);
		}

		// Some databases, like PostgreSQL, need order
		// information to consistently return correct results.
		if ($builder->QBGroupBy && empty($builder->QBOrderBy) && $this->primaryKey)
		{
			$builder->orderBy($this->table . '.' . $this->primaryKey, 'asc');
		}

		return $builder->limit(1, 0)->get()->getFirstRow($this->tempReturnType);
	}

	/**
	 * Inserts data into the current table.
	 * This methods works only with dbCalls
	 *
	 * @param array $data Data
	 *
	 * @return Query|boolean
	 */
	protected function doInsert(array $data)
	{
		$escape       = $this->escape;
		$this->escape = [];

		// Require non empty primaryKey when
		// not using auto-increment feature
		if (! $this->useAutoIncrement && empty($data[$this->primaryKey]))
		{
			throw DataException::forEmptyPrimaryKey('insert');
		}

		$builder = $this->builder();

		// Must use the set() method to ensure to set the correct escape flag
		foreach ($data as $key => $val)
		{
			$builder->set($key, $val, $escape[$key] ?? null);
		}

		$result = $builder->insert();

		// If insertion succeeded then save the insert ID
		if ($result)
		{
			$this->insertID = ! $this->useAutoIncrement ? $data[$this->primaryKey] : $this->db->insertID();
		}

		return $result;
	}

	/**
	 * Compiles batch insert strings and runs the queries, validating each row prior.
	 * This methods works only with dbCalls
	 *
	 * @param array|null   $set       An associative array of insert values
	 * @param boolean|null $escape    Whether to escape values and identifiers
	 * @param integer      $batchSize The size of the batch to run
	 * @param boolean      $testing   True means only number of records is returned, false will execute the query
	 *
	 * @return integer|boolean Number of rows inserted or FALSE on failure
	 */
	protected function doInsertBatch(?array $set = null, ?bool $escape = null, int $batchSize = 100, bool $testing = false)
	{
		if (is_array($set))
		{
			foreach ($set as $row)
			{
				// Require non empty primaryKey when
				// not using auto-increment feature
				if (! $this->useAutoIncrement && empty($row[$this->primaryKey]))
				{
					throw DataException::forEmptyPrimaryKey('insertBatch');
				}
			}
		}

		return $this->builder()->testMode($testing)->insertBatch($set, $escape, $batchSize);
	}

	/**
	 * Updates a single record in $this->table.
	 * This methods works only with dbCalls
	 *
	 * @param integer|array|string|null $id   ID
	 * @param array|null                $data Data
	 *
	 * @return boolean
	 */
	protected function doUpdate($id = null, $data = null): bool
	{
		$escape       = $this->escape;
		$this->escape = [];

		$builder = $this->builder();

		if ($id)
		{
			$builder = $builder->whereIn($this->table . '.' . $this->primaryKey, $id);
		}

		// Must use the set() method to ensure to set the correct escape flag
		foreach ($data as $key => $val)
		{
			$builder->set($key, $val, $escape[$key] ?? null);
		}

		return $builder->update();
	}

	/**
	 * Compiles an update string and runs the query
	 * This methods works only with dbCalls
	 *
	 * @param array|null  $set       An associative array of update values
	 * @param string|null $index     The where key
	 * @param integer     $batchSize The size of the batch to run
	 * @param boolean     $returnSQL True means SQL is returned, false will execute the query
	 *
	 * @return mixed    Number of rows affected or FALSE on failure
	 *
	 * @throws DatabaseException
	 */
	protected function doUpdateBatch(array $set = null, string $index = null, int $batchSize = 100, bool $returnSQL = false)
	{
		return $this->builder()->testMode($returnSQL)->updateBatch($set, $index, $batchSize);
	}

	/**
	 * Deletes a single record from $this->table where $id matches
	 * the table's primaryKey
	 * This methods works only with dbCalls
	 *
	 * @param integer|string|array|null $id    The rows primary key(s)
	 * @param boolean                   $purge Allows overriding the soft deletes setting.
	 *
	 * @return string|boolean
	 *
	 * @throws DatabaseException
	 */
	protected function doDelete($id = null, bool $purge = false)
	{
		$builder = $this->builder();

		if ($id)
		{
			$builder = $builder->whereIn($this->primaryKey, $id);
		}

		if ($this->useSoftDeletes && ! $purge)
		{
			if (empty($builder->getCompiledQBWhere()))
			{
				if (CI_DEBUG)
				{
					throw new DatabaseException(
						'Deletes are not allowed unless they contain a "where" or "like" clause.'
					);
				}

				return false; // @codeCoverageIgnore
			}

			$set[$this->deletedField] = $this->setDate();

			if ($this->useTimestamps && $this->updatedField)
			{
				$set[$this->updatedField] = $this->setDate();
			}

			return $builder->update($set);
		}

		return $builder->delete();
	}

	/**
	 * Permanently deletes all rows that have been marked as deleted
	 * through soft deletes (deleted = 1)
	 * This methods works only with dbCalls
	 *
	 * @return boolean|mixed
	 */
	protected function doPurgeDeleted()
	{
		return $this->builder()
			->where($this->table . '.' . $this->deletedField . ' IS NOT NULL')
			->delete();
	}

	/**
	 * Works with the find* methods to return only the rows that
	 * have been deleted.
	 * This methods works only with dbCalls
	 *
	 * @return void
	 */
	protected function doOnlyDeleted()
	{
		$this->builder()->where($this->table . '.' . $this->deletedField . ' IS NOT NULL');
	}

	/**
	 * Compiles a replace into string and runs the query
	 * This methods works only with dbCalls
	 *
	 * @param array|null $data      Data
	 * @param boolean    $returnSQL Set to true to return Query String
	 *
	 * @return mixed
	 */
	protected function doReplace(array $data = null, bool $returnSQL = false)
	{
		return $this->builder()->testMode($returnSQL)->replace($data);
	}

	/**
	 * Grabs the last error(s) that occurred from the Database connection.
	 * The return array should be in the following format:
	 *  ['source' => 'message']
	 * This methods works only with dbCalls
	 *
	 * @return array<string,string>
	 */
	protected function doErrors()
	{
		// $error is always ['code' => string|int, 'message' => string]
		$error = $this->db->error();

		if ((int) $error['code'] === 0)
		{
			return [];
		}

		return [get_class($this->db) => $error['message']];
	}

	/**
	 * Returns the id value for the data array or object
	 *
	 * @param array|object $data Data
	 *
	 * @return integer|array|string|null
	 *
	 * @deprecated Use getIdValue() instead. Will be removed in version 5.0.
	 */
	protected function idValue($data)
	{
		return $this->getIdValue($data);
	}

	/**
	 * Returns the id value for the data array or object
	 *
	 * @param array|object $data Data
	 *
	 * @return integer|array|string|null
	 */
	public function getIdValue($data)
	{
		if (is_object($data) && isset($data->{$this->primaryKey}))
		{
			return $data->{$this->primaryKey};
		}

		if (is_array($data) && ! empty($data[$this->primaryKey]))
		{
			return $data[$this->primaryKey];
		}

		return null;
	}

	/**
	 * Loops over records in batches, allowing you to operate on them.
	 * Works with $this->builder to get the Compiled select to
	 * determine the rows to operate on.
	 * This methods works only with dbCalls
	 *
	 * @param integer $size     Size
	 * @param Closure $userFunc Callback Function
	 *
	 * @return void
	 *
	 * @throws DataException
	 */
	public function chunk(int $size, Closure $userFunc)
	{
		$total  = $this->builder()->countAllResults(false);
		$offset = 0;

		while ($offset <= $total)
		{
			$builder = clone $this->builder();
			$rows    = $builder->get($size, $offset);

			if (! $rows)
			{
				throw DataException::forEmptyDataset('chunk');
			}

			$rows = $rows->getResult($this->tempReturnType);

			$offset += $size;

			if (empty($rows))
			{
				continue;
			}

			foreach ($rows as $row)
			{
				if ($userFunc($row) === false)
				{
					return;
				}
			}
		}
	}

	/**
	 * Override countAllResults to account for soft deleted accounts.
	 *
	 * @param boolean $reset Reset
	 * @param boolean $test  Test
	 *
	 * @return mixed
	 */
	public function countAllResults(bool $reset = true, bool $test = false)
	{
		if ($this->tempUseSoftDeletes)
		{
			$this->builder()->where($this->table . '.' . $this->deletedField, null);
		}

		// When $reset === false, the $tempUseSoftDeletes will be
		// dependant on $useSoftDeletes value because we don't
		// want to add the same "where" condition for the second time
		$this->tempUseSoftDeletes = $reset
			? $this->useSoftDeletes
			: ($this->useSoftDeletes ? false : $this->useSoftDeletes);

		return $this->builder()->testMode($test)->countAllResults($reset);
	}

	/**
	 * Provides a shared instance of the Query Builder.
	 *
	 * @param string|null $table Table name
	 *
	 * @return BaseBuilder
	 * @throws ModelException
	 */
	public function builder(?string $table = null)
	{
		// Check for an existing Builder
		if ($this->builder instanceof BaseBuilder)
		{
			// Make sure the requested table matches the builder
			if ($table && $this->builder->getTable() !== $table)
			{
				return $this->db->table($table);
			}

			return $this->builder;
		}

		// We're going to force a primary key to exist
		// so we don't have overly convoluted code,
		// and future features are likely to require them.
		if (empty($this->primaryKey))
		{
			throw ModelException::forNoPrimaryKey(static::class);
		}

		$table = empty($table) ? $this->table : $table;

		// Ensure we have a good db connection
		if (! $this->db instanceof BaseConnection)
		{
			$this->db = Database::connect($this->DBGroup);
		}

		$builder = $this->db->table($table);

		// Only consider it "shared" if the table is correct
		if ($table === $this->table)
		{
			$this->builder = $builder;
		}

		return $builder;
	}

	/**
	 * Captures the builder's set() method so that we can validate the
	 * data here. This allows it to be used with any of the other
	 * builder methods and still get validated data, like replace.
	 *
	 * @param mixed        $key    Field name, or an array of field/value pairs
	 * @param string|null  $value  Field value, if $key is a single field
	 * @param boolean|null $escape Whether to escape values and identifiers
	 *
	 * @return $this
	 */
	public function set($key, ?string $value = '', ?bool $escape = null)
	{
		$data = is_array($key) ? $key : [$key => $value];

		foreach (array_keys($data) as $k)
		{
			$this->tempData['escape'][$k] = $escape;
		}

		$this->tempData['data'] = array_merge($this->tempData['data'] ?? [], $data);

		return $this;
	}

	/**
	 * This method is called on save to determine if entry have to be updated
	 * If this method return false insert operation will be executed
	 *
	 * @param array|object $data Data
	 *
	 * @return boolean
	 */
	protected function shouldUpdate($data) : bool
	{
		// When useAutoIncrement feature is disabled check
		// in the database if given record already exists
		return parent::shouldUpdate($data) &&
			($this->useAutoIncrement
				? true
				: $this->where($this->primaryKey, $this->getIdValue($data))->countAllResults() === 1
			);
	}

	/**
	 * Inserts data into the database. If an object is provided,
	 * it will attempt to convert it to an array.
	 *
	 * @param array|object|null $data     Data
	 * @param boolean           $returnID Whether insert ID should be returned or not.
	 *
	 * @return BaseResult|object|integer|string|false
	 *
	 * @throws ReflectionException
	 */
	public function insert($data = null, bool $returnID = true)
	{
		if (! empty($this->tempData['data']))
		{
			if (empty($data))
			{
				$data = $this->tempData['data'] ?? null;
			}
			else
			{
				$data = $this->transformDataToArray($data, 'insert');
				$data = array_merge($this->tempData['data'], $data);
			}
		}

		$this->escape   = $this->tempData['escape'] ?? [];
		$this->tempData = [];

		return parent::insert($data, $returnID);
	}

	/**
	 * Updates a single record in the database. If an object is provided,
	 * it will attempt to convert it into an array.
	 *
	 * @param integer|array|string|null $id   ID
	 * @param array|object|null         $data Data
	 *
	 * @return boolean
	 *
	 * @throws ReflectionException
	 */
	public function update($id = null, $data = null): bool
	{
		if (! empty($this->tempData['data']))
		{
			if (empty($data))
			{
				$data = $this->tempData['data'] ?? null;
			}
			else
			{
				$data = $this->transformDataToArray($data, 'update');
				$data = array_merge($this->tempData['data'], $data);
			}
		}

		$this->escape   = $this->tempData['escape'] ?? [];
		$this->tempData = [];

		return parent::update($id, $data);
	}

	/**
	 * Takes a class an returns an array of it's public and protected
	 * properties as an array with raw values.
	 *
	 * @param string|object $data        Data
	 * @param boolean       $onlyChanged Only Changed Property
	 * @param boolean       $recursive   If true, inner entities will be casted as array as well
	 *
	 * @return array|null Array
	 *
	 * @throws ReflectionException
	 */
	protected function objectToRawArray($data, bool $onlyChanged = true, bool $recursive = false): ?array
	{
		$properties = parent::objectToRawArray($data, $onlyChanged);

		// Always grab the primary key otherwise updates will fail.
		if (method_exists($data, 'toRawArray') && (! empty($properties) && ! empty($this->primaryKey) && ! in_array($this->primaryKey, $properties, true)
				&& ! empty($data->{$this->primaryKey})))
		{
			$properties[$this->primaryKey] = $data->{$this->primaryKey};
		}

		return $properties;
	}

	/**
	 * Provides/instantiates the builder/db connection and model's table/primary key names and return type.
	 *
	 * @param string $name Name
	 *
	 * @return mixed
	 */
	public function __get(string $name)
	{
		if (parent::__isset($name))
		{
			return parent::__get($name);
		}

		if (isset($this->builder()->$name))
		{
			return $this->builder()->$name;
		}

		return null;
	}

	/**
	 * Checks for the existence of properties across this model, builder, and db connection.
	 *
	 * @param string $name Name
	 *
	 * @return boolean
	 */
	public function __isset(string $name): bool
	{
		if (parent::__isset($name))
		{
			return true;
		}
		return isset($this->builder()->$name);
	}

	/**
	 * Provides direct access to method in the builder (if available)
	 * and the database connection.
	 *
	 * @param string $name   Name
	 * @param array  $params Params
	 *
	 * @return $this|null
	 */
	public function __call(string $name, array $params)
	{
		$result = parent::__call($name, $params);

		if ($result === null && method_exists($builder = $this->builder(), $name))
		{
			$result = $builder->{$name}(...$params);
		}

		if (empty($result))
		{
			if (! method_exists($this->builder(), $name))
			{
				$className = static::class;

				throw new BadMethodCallException('Call to undefined method ' . $className . '::' . $name);
			}

			return $result;
		}

		if ($result instanceof BaseBuilder)
		{
			return $this;
		}

		return $result;
	}

	/**
	 * Takes a class an returns an array of it's public and protected
	 * properties as an array suitable for use in creates and updates.
	 *
	 * @param string|object $data        Data
	 * @param string|null   $primaryKey  Primary Key
	 * @param string        $dateFormat  Date Format
	 * @param boolean       $onlyChanged Only Changed
	 *
	 * @return array
	 *
	 * @throws ReflectionException
	 *
	 * @codeCoverageIgnore
	 *
	 * @deprecated since 4.1
	 */
	public static function classToArray($data, $primaryKey = null, string $dateFormat = 'datetime', bool $onlyChanged = true): array
	{
		if (method_exists($data, 'toRawArray'))
		{
			$properties = $data->toRawArray($onlyChanged);

			// Always grab the primary key otherwise updates will fail.
			if (! empty($properties) && ! empty($primaryKey) && ! in_array($primaryKey, $properties, true) && ! empty($data->{$primaryKey}))
			{
				$properties[$primaryKey] = $data->{$primaryKey};
			}
		}
		else
		{
			$mirror = new ReflectionClass($data);
			$props  = $mirror->getProperties(ReflectionProperty::IS_PUBLIC | ReflectionProperty::IS_PROTECTED);

			$properties = [];

			// Loop over each property,
			// saving the name/value in a new array we can return.
			foreach ($props as $prop)
			{
				// Must make protected values accessible.
				$prop->setAccessible(true);
				$properties[$prop->getName()] = $prop->getValue($data);
			}
		}

		// Convert any Time instances to appropriate $dateFormat
		if ($properties)
		{
			foreach ($properties as $key => $value)
			{
				if ($value instanceof Time)
				{
					switch ($dateFormat)
					{
						case 'datetime':
							$converted = $value->format('Y-m-d H:i:s');
							break;
						case 'date':
							$converted = $value->format('Y-m-d');
							break;
						case 'int':
							$converted = $value->getTimestamp();
							break;
						default:
							$converted = (string) $value;
					}

					$properties[$key] = $converted;
				}
			}
		}

		return $properties;
	}
}


text:
"use strict";

/*
	Push content or elements of an array to the
	output linear program.
*/
function push(content, env)
{
	if (Array.isArray(content) === false)
	{
		env.outputProgram.push(content);
	}
	else
	{
		env.outputProgram.push(...content);
	}
}

module.exports = push;


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <modelVersion>4.0.0</modelVersion>

  <parent>
    <groupId>org.pentaho.di.plugins</groupId>
    <artifactId>file-open-save</artifactId>
    <version>8.0-SNAPSHOT</version>
  </parent>

  <artifactId>file-open-save-core</artifactId>
  <version>8.0-SNAPSHOT</version>
  <packaging>bundle</packaging>

  <name>PDI File Open and Save Plugin Core</name>

  <properties>
    <maven-replacer-plugin.version>1.5.2</maven-replacer-plugin.version>
    <src.dir>target/processed-sources</src.dir>
  </properties>

  <dependencies>
    <dependency>
      <groupId>pentaho-kettle</groupId>
      <artifactId>kettle-core</artifactId>
    </dependency>
    <dependency>
      <groupId>pentaho-kettle</groupId>
      <artifactId>kettle-ui-swt</artifactId>
    </dependency>
    <dependency>
      <groupId>pentaho-kettle</groupId>
      <artifactId>kettle-engine</artifactId>
    </dependency>
    <dependency>
      <groupId>pentaho</groupId>
      <artifactId>pentaho-platform-extensions</artifactId>
    </dependency>
    <dependency>
      <groupId>pentaho</groupId>
      <artifactId>pentaho-i18n-bundle</artifactId>
    </dependency>
    <dependency>
      <groupId>pentaho</groupId>
      <artifactId>pentaho-i18n-webservice-bundle</artifactId>
    </dependency>
    <dependency>
      <groupId>org.eclipse.swt</groupId>
      <artifactId>org.eclipse.swt.win32.win32.x86_64</artifactId>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-annotations</artifactId>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.jaxrs</groupId>
      <artifactId>jackson-jaxrs-json-provider</artifactId>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.jaxrs</groupId>
      <artifactId>jackson-jaxrs-base</artifactId>
    </dependency>
    <dependency>
      <groupId>javax.ws.rs</groupId>
      <artifactId>javax.ws.rs-api</artifactId>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
    </dependency>
    <dependency>
      <groupId>org.webjars</groupId>
      <artifactId>requirejs</artifactId>
    </dependency>
    <dependency>
      <groupId>org.webjars.bower</groupId>
      <artifactId>angular</artifactId>
    </dependency>
    <dependency>
      <groupId>org.webjars.bower</groupId>
      <artifactId>angular-i18n</artifactId>
    </dependency>
    <dependency>
      <groupId>org.webjars.bower</groupId>
      <artifactId>requirejs-text</artifactId>
    </dependency>
    <dependency>
      <groupId>org.webjars.bower</groupId>
      <artifactId>require-css</artifactId>
    </dependency>
    <dependency>
      <groupId>com.googlecode.json-simple</groupId>
      <artifactId>json-simple</artifactId>
    </dependency>
  </dependencies>
  <build>
    <sourceDirectory>${src.dir}</sourceDirectory>
    <resources>
      <resource>
        <filtering>false</filtering>
        <directory>src/main/resources</directory>
        <includes>
          <include>**/*</include>
        </includes>
        <excludes>
          <exclude>META-INF/**/*</exclude>
          <exclude>OSGI-INF/**/*</exclude>
          <exclude>app/index.html</exclude>
        </excludes>
      </resource>
      <resource>
        <filtering>true</filtering>
        <directory>src/main/resources</directory>
        <includes>
          <include>META-INF/**/*</include>
          <include>OSGI-INF/**/*</include>
          <include>app/index.html</include>
        </includes>
      </resource>
      <resource>
        <directory>src/main/javascript</directory>
        <includes>
          <include>**/*</include>
        </includes>
      </resource>
    </resources>
    <plugins>
      <plugin>
        <groupId>com.google.code.maven-replacer-plugin</groupId>
        <artifactId>replacer</artifactId>
        <version>${maven-replacer-plugin.version}</version>
        <executions>
          <execution>
            <phase>generate-sources</phase>
            <goals>
              <goal>replace</goal>
            </goals>
          </execution>
        </executions>
        <configuration>
          <basedir>${basedir}/src/main/java</basedir>
          <outputDir>../../../target/processed-sources</outputDir>
          <includes>
            <include>**/*.java</include>
          </includes>
          <replacements>
            <replacement>
              <token>@PROJECT_ARTIFACT_ID@</token>
              <value>${project.artifactId}</value>
            </replacement>
            <replacement>
              <token>@PROJECT_VERSION@</token>
              <value>${project.version}</value>
            </replacement>
          </replacements>
        </configuration>
      </plugin>
      <plugin>
        <artifactId>maven-remote-resources-plugin</artifactId>
        <version>1.5</version>
        <executions>
          <execution>
            <goals>
              <goal>bundle</goal>
            </goals>
          </execution>
        </executions>
        <configuration>
          <includes>
            <include>**/*</include>
          </includes>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.felix</groupId>
        <artifactId>maven-bundle-plugin</artifactId>
        <version>2.4.0</version>
        <extensions>true</extensions>
        <configuration>
          <instructions>
            <Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
            <Bundle-Version>${project.version}</Bundle-Version>
            <Import-Package>org.pentaho.di.osgi, *</Import-Package>
          </instructions>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>


text:
<?php $av = Loader::helper('concrete/avatar'); ?>

		<a href="<?php echo View::url('/profile',$profile->getUserID())?>"><?php echo $av->outputUserAvatar($profile)?>

		<a href="<?php echo View::url('/profile',$profile->getUserID())?>"><?php echo $profile->getUsername()?>

<?php echo t('Member Since')?>

	<?php echo Loader::helper('date')->formatDate($profile->getUserDateAdded(), true)?>

	<?php
	$u = new User();
	if ($u->isRegistered() && $u->getUserID() != $profile->getUserID()) { ?>

		<?php if( !UsersFriends::isFriend( $profile->getUserID(), $u->uID ) ){ ?>
			<a href="<?php echo View::url('/profile/friends','add_friend', $profile->getUserID())?>">
				<?php echo t('Add to My Friends') ?>

		<?php }else{ ?>
			<a href="<?php echo View::url('/profile/friends','remove_friend', $profile->getUserID() )?>">
				<?php echo t('Remove from My Friends') ?>

		<?php } ?>

		<?php if ($profile->getUserProfilePrivateMessagesEnabled() == 1) { ?>
			<a href="<?php echo $this->url('/profile/messages', 'write', $profile->getUserID())?>"><?php echo t('Send Private Message')?>
		<?php } ?>

	<?php } ?>

	<?php
	if($u->getUserID() == $profile->getUserID()) {
		$nc = Page::getByPath('/profile');
		$pl = new PageList();
		$pl->filterByParentID($nc->getCollectionID());
		$pages = $pl->get(0);
		if (is_array($pages) && !empty($pages)) {
			$nh = Loader::helper('navigation');
			?>

			<?php foreach ($pages as $page) { ?>

<a href="<?php echo $nh->getLinkToCollection($page) ?>"><?php echo t($page->getCollectionName())?>

			<?php } ?>

		<?php
		}
	}
	?>

		<form method="get" action="<?php echo $this->url('/members')?>">

<?php echo t('Search Members')?>

		<?php
		$form = Loader::helper('form');
		print $form->text('keywords', array('style' => 'width: 80px'));
		print '  ';
		print $form->submit('submit', t('Search'));
		?>

		</form>


text:
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletingTrait;
use Illuminate\Database\Eloquent\SoftDeletes;

class Product extends Model
{
     use SoftDeletes;

     protected $table = 'products';
     protected $primaryKey = 'idProduct';
     /*for soft deletes*/
     protected $dates = ['deleted_at'];

     protected $guarded = ['idProduct'];

     public function bought(){
       return $this->belongsToMany(Transaction::class, 'idProduct', 'idProduct');
     }

     public function reviews(){
        return $this->hasMany(Review::class, 'idProduct', 'idProduct');
     }

     public function stocks(){
        return $this->hasMany(Product_Stock::class, 'idProduct', 'idProduct');
     }

     public function addNewProduct(Product_Stock $stock){
        return $this->stocks()->save($stock);
     }
     /*
     public function reviewData(){
       $reviewData = DB::table('reviews')
                       ->select(DB::raw('count(*) as reviewCount, average(rating) as ratingAve'))
                       ->where('idProduct', $this->idProduct)
                       ->groupBy('idProduct')
                       ->get();
        //return $reviewData;
     }*/
}


text:
<?php

namespace Longman\Platfourm\Database\Eloquent\Traits;

use Exception;

/**
 * Sorter model trait.
 *
 * Usage:
 *
 * Model table must have sort_order table column.
 *
 * In the model class definition:
 *
 *   use Longman\Platfourm\Database\Eloquent\Traits\Sorter;
 *
 * To set orders:
 *
 *   $model->setSorterOrder($recordIds, $recordOrders);
 *
 * You can change the sort field used by declaring:
 *
 *   const SORT_ORDER = 'my_sort_order';
 */
trait Sorter
{
    /**
     * Boot the Sorter trait for this model.
     *
     * @return void
     */
    public static function bootSorter()
    {
        static::created(function ($model) {
            $model->setSorterOrder($model->id);
        });
    }

    /**
     * Sets the sort order of records to the specified orders. If the orders is
     * undefined, the record identifier is used.
     */
    public function setSorterOrder($itemIds, $itemOrders = null)
    {
        if (!is_array($itemIds)) {
            $itemIds = [$itemIds];
        }

        if ($itemOrders === null) {
            $itemOrders = $itemIds;
        }

        if (count($itemIds) != count($itemOrders)) {
            throw new Exception('Invalid setSorterOrder call - count of itemIds do not match count of itemOrders');
        }

        foreach ($itemIds as $index => $id) {
            $order = $itemOrders[$index];
            $this->newQuery()->where('id', $id)->update([$this->getSortOrderColumn() => $order]);
        }
    }

    /**
     * Get the name of the "sort order" column.
     *
     * @return string
     */
    public function getSortOrderColumn()
    {
        return defined('static::SORT_ORDER') ? static::SORT_ORDER : 'sort_order';
    }
}


text:
```bash
sh docker-machine.sh
```

### Build the docker container
```bash
sh docker-build.sh
```

### Build the docker image
```bash
docker build --name steven/citeshare:latest .
```

### Run the image
```bash
docker run -P -d steven/citeshare:latest
```

### Get the IP and Port
```bash
IP=$(docker-machine ip default) PORT=$(docker port citeshare 8888 | sed -e 's/.*://') && echo $IP:$PORT
```


text:
package com.wan.yalandan.app.model;

import java.util.List;

/**
 * Created by emre.can on 7/28/2015.
 */
public class Word {
    // TODO - use properties which is more usable
    private String headWord;
    private String functionalLabel;
    private String meaningCore;
    private String illustrativeSentence;
    private List<String> synonymList;
    private List<String> relatedWords;
    private List<String> antonyms;

    public String getHeadWord() {
        return headWord;
    }

    public String getFunctionalLabel() {
        return functionalLabel;
    }

    public String getMeaningCore() {
        return meaningCore;
    }

    public List<String> getSynonymList() {
        return synonymList;
    }

    public String getIllustrativeSentence() {
        return illustrativeSentence;
    }

    public List<String> getRelatedWords() {
        return relatedWords;
    }

    public List<String> getAntonyms() {
        return antonyms;
    }

    public Word(String headWord, String functionalLabel, String meaningCore, String illustrativeSentence, List<String> synonymList, List<String> relatedWords, List<String> antonyms) {
        this.headWord = headWord;
        this.functionalLabel = functionalLabel;
        this.meaningCore = meaningCore;
        this.illustrativeSentence = illustrativeSentence;
        this.synonymList = synonymList;
        this.relatedWords = relatedWords;
        this.antonyms = antonyms;
    }
}


text:
Requirements
1. Provide working source code that will :

a. For a given stock

i. Given a market price as input, calculate the dividend yield

ii. Given a market price as input, calculate the P/E Ratio

iii. Record a trade, with timestamp, quantity of shares, buy or sell indicator and
trade price

iv. Calculate Volume Weighted Stock Price based on trades in past 15 minutes

b. Calculate the GBCE All Share Index using the geometric mean of prices for all stocks

# formulas is uploaded as formulas.png
you can find and useformulas in formulas.png file to do.

# small set of data as dictionary

data = {'TEA': {'Type': 'Common', 'Last_Dividend': 0, 'Fixed_Dividend': None, 'Par_Value': 100},
        'POP': {'Type': 'Common', 'Last_Dividend': 8, 'Fixed_Dividend': None, 'Par_Value': 100},
        'ALE': {'Type': 'Common', 'Last_Dividend': 23, 'Fixed_Dividend': None, 'Par_Value': 60},
        'GIN': {'Type': 'Preferred', 'Last_Dividend': 8, 'Fixed_Dividend': 0.02, 'Par_Value': 100},
        'JOE': {'Type': 'Common', 'Last_Dividend': 13, 'Fixed_Dividend': None, 'Par_Value': 250}}


text:
import unittest
import os
import os.path

import test.env

from pypcpe2 import comsubseq
from pypcpe2 import env

class TestComSubseq(unittest.TestCase):
    def setUp(self):
        self.test_data_folder = os.path.join(test.env.test_data_folder,
                                             "comsubseq")
        self.test_output_folder = os.path.join(test.env.test_output_folder,
                                               "comsubseq")
        if not os.path.isdir(self.test_output_folder):
            os.makedirs(self.test_output_folder)

        self.saved_temp_path = env.setting().temp_path
        env.setting().temp_path = self.test_output_folder
        self.temp_path = env.setting().temp_path

    def tearDown(self):
        env.setting().temp_path = self.saved_temp_path

    def test_read_comsubseq(self):
        path = os.path.join(self.test_data_folder, "comsubseq.bin")

        seqs = comsubseq.read_comsubseq_file(path)
        ans = [comsubseq.ComSubseq(2, 1, 3, 1, 6),
               comsubseq.ComSubseq(1, 1, 2, 0, 6),
               comsubseq.ComSubseq(2, 1, 2, 0, 6),
               comsubseq.ComSubseq(0, 0, 1, 0, 6),
               comsubseq.ComSubseq(1, 0, 1, 0, 6),
               comsubseq.ComSubseq(2, 0, 1, 0, 6)]

        self.assertEqual(seqs, ans)

    def test_read_empty_comsubseq(self):
        path = os.path.join(self.test_data_folder, "empty_comsubseq.bin")

        seqs = comsubseq.read_comsubseq_file(path)
        self.assertEqual(seqs, [])


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

<title>StandardSocketOptions (Java Platform SE 7 )</title>
<meta name="date" content="2014-12-18">
<meta name="keywords" content="java.net.StandardSocketOptions class">
<meta name="keywords" content="SO_BROADCAST">
<meta name="keywords" content="SO_KEEPALIVE">
<meta name="keywords" content="SO_SNDBUF">
<meta name="keywords" content="SO_RCVBUF">
<meta name="keywords" content="SO_REUSEADDR">
<meta name="keywords" content="SO_LINGER">
<meta name="keywords" content="IP_TOS">
<meta name="keywords" content="IP_MULTICAST_IF">
<meta name="keywords" content="IP_MULTICAST_TTL">
<meta name="keywords" content="IP_MULTICAST_LOOP">
<meta name="keywords" content="TCP_NODELAY">
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Java™ Platform
Standard Ed. 7

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

java.net

Class StandardSocketOptions

java.lang.Object

java.net.StandardSocketOptions

public final class StandardSocketOptions
extends Object

Defines the standard socket options.

 The name of each socket option defined by this
 class is its field name.

 In this release, the socket options defined here are used by network channels in the channels package.

Since:

1.7

Field Summary

Fields

Modifier and Type
Field and Description

static SocketOption<NetworkInterface>
IP_MULTICAST_IF

The network interface for Internet Protocol (IP) multicast datagrams.

static SocketOption<Boolean>
IP_MULTICAST_LOOP

Loopback for Internet Protocol (IP) multicast datagrams.

static SocketOption<Integer>
IP_MULTICAST_TTL

The time-to-live for Internet Protocol (IP) multicast datagrams.

static SocketOption<Integer>
IP_TOS

The Type of Service (ToS) octet in the Internet Protocol (IP) header.

static SocketOption<Boolean>
SO_BROADCAST

Allow transmission of broadcast datagrams.

static SocketOption<Boolean>
SO_KEEPALIVE

Keep connection alive.

static SocketOption<Integer>
SO_LINGER

Linger on close if data is present.

static SocketOption<Integer>
SO_RCVBUF

The size of the socket receive buffer.

static SocketOption<Boolean>
SO_REUSEADDR

Re-use address.

static SocketOption<Integer>
SO_SNDBUF

The size of the socket send buffer.

static SocketOption<Boolean>
TCP_NODELAY

Disable the Nagle algorithm.

Method Summary

Methods inherited from class java.lang.Object

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

Field Detail

SO_BROADCAST

public static final SocketOption<Boolean> SO_BROADCAST

Allow transmission of broadcast datagrams.

 The value of this socket option is a Boolean that represents
 whether the option is enabled or disabled. The option is specific to
 datagram-oriented sockets sending to IPv4
 broadcast addresses. When the socket option is enabled then the socket
 can be used to send broadcast datagrams.

 The initial value of this socket option is FALSE. The socket
 option may be enabled or disabled at any time. Some operating systems may
 require that the Java virtual machine be started with implementation
 specific privileges to enable this option or send broadcast datagrams.

See Also:

RFC 929:
 Broadcasting Internet Datagrams,
DatagramSocket.setBroadcast(boolean)

SO_KEEPALIVE

public static final SocketOption<Boolean> SO_KEEPALIVE

Keep connection alive.

 The value of this socket option is a Boolean that represents
 whether the option is enabled or disabled. When the SO_KEEPALIVE
 option is enabled the operating system may use a keep-alive
 mechanism to periodically probe the other end of a connection when the
 connection is otherwise idle. The exact semantics of the keep alive
 mechanism is system dependent and therefore unspecified.

 The initial value of this socket option is FALSE. The socket
 option may be enabled or disabled at any time.

See Also:

RFC 1122
 Requirements for Internet Hosts -- Communication Layers,
Socket.setKeepAlive(boolean)

SO_SNDBUF

public static final SocketOption<Integer> SO_SNDBUF

The size of the socket send buffer.

 The value of this socket option is an Integer that is the
 size of the socket send buffer in bytes. The socket send buffer is an
 output buffer used by the networking implementation. It may need to be
 increased for high-volume connections. The value of the socket option is
 a hint to the implementation to size the buffer and the actual
 size may differ. The socket option can be queried to retrieve the actual
 size.

 For datagram-oriented sockets, the size of the send buffer may limit
 the size of the datagrams that may be sent by the socket. Whether
 datagrams larger than the buffer size are sent or discarded is system
 dependent.

 The initial/default size of the socket send buffer and the range of
 allowable values is system dependent although a negative size is not
 allowed. An attempt to set the socket send buffer to larger than its
 maximum size causes it to be set to its maximum size.

 An implementation allows this socket option to be set before the
 socket is bound or connected. Whether an implementation allows the
 socket send buffer to be changed after the socket is bound is system
 dependent.

See Also:

Socket.setSendBufferSize(int)

SO_RCVBUF

public static final SocketOption<Integer> SO_RCVBUF

The size of the socket receive buffer.

 The value of this socket option is an Integer that is the
 size of the socket receive buffer in bytes. The socket receive buffer is
 an input buffer used by the networking implementation. It may need to be
 increased for high-volume connections or decreased to limit the possible
 backlog of incoming data. The value of the socket option is a
 hint to the implementation to size the buffer and the actual
 size may differ.

 For datagram-oriented sockets, the size of the receive buffer may
 limit the size of the datagrams that can be received. Whether datagrams
 larger than the buffer size can be received is system dependent.
 Increasing the socket receive buffer may be important for cases where
 datagrams arrive in bursts faster than they can be processed.

 In the case of stream-oriented sockets and the TCP/IP protocol, the
 size of the socket receive buffer may be used when advertising the size
 of the TCP receive window to the remote peer.

 The initial/default size of the socket receive buffer and the range
 of allowable values is system dependent although a negative size is not
 allowed. An attempt to set the socket receive buffer to larger than its
 maximum size causes it to be set to its maximum size.

 An implementation allows this socket option to be set before the
 socket is bound or connected. Whether an implementation allows the
 socket receive buffer to be changed after the socket is bound is system
 dependent.

See Also:

RFC 1323: TCP
 Extensions for High Performance,
Socket.setReceiveBufferSize(int),
ServerSocket.setReceiveBufferSize(int)

SO_REUSEADDR

public static final SocketOption<Boolean> SO_REUSEADDR

Re-use address.

 The value of this socket option is a Boolean that represents
 whether the option is enabled or disabled. The exact semantics of this
 socket option are socket type and system dependent.

 In the case of stream-oriented sockets, this socket option will
 usually determine whether the socket can be bound to a socket address
 when a previous connection involving that socket address is in the
 TIME_WAIT state. On implementations where the semantics differ,
 and the socket option is not required to be enabled in order to bind the
 socket when a previous connection is in this state, then the
 implementation may choose to ignore this option.

 For datagram-oriented sockets the socket option is used to allow
 multiple programs bind to the same address. This option should be enabled
 when the socket is to be used for Internet Protocol (IP) multicasting.

 An implementation allows this socket option to be set before the
 socket is bound or connected. Changing the value of this socket option
 after the socket is bound has no effect. The default value of this
 socket option is system dependent.

See Also:

RFC 793: Transmission
 Control Protocol,
ServerSocket.setReuseAddress(boolean)

SO_LINGER

public static final SocketOption<Integer> SO_LINGER

Linger on close if data is present.

 The value of this socket option is an Integer that controls
 the action taken when unsent data is queued on the socket and a method
 to close the socket is invoked. If the value of the socket option is zero
 or greater, then it represents a timeout value, in seconds, known as the
 linger interval. The linger interval is the timeout for the
 close method to block while the operating system attempts to
 transmit the unsent data or it decides that it is unable to transmit the
 data. If the value of the socket option is less than zero then the option
 is disabled. In that case the close method does not wait until
 unsent data is transmitted; if possible the operating system will transmit
 any unsent data before the connection is closed.

 This socket option is intended for use with sockets that are configured
 in blocking mode
 only. The behavior of the close method when this option is
 enabled on a non-blocking socket is not defined.

 The initial value of this socket option is a negative value, meaning
 that the option is disabled. The option may be enabled, or the linger
 interval changed, at any time. The maximum value of the linger interval
 is system dependent. Setting the linger interval to a value that is
 greater than its maximum value causes the linger interval to be set to
 its maximum value.

See Also:

Socket.setSoLinger(boolean, int)

IP_TOS

public static final SocketOption<Integer> IP_TOS

The Type of Service (ToS) octet in the Internet Protocol (IP) header.

 The value of this socket option is an Integer representing
 the value of the ToS octet in IP packets sent by sockets to an IPv4 socket. The interpretation of the ToS
 octet is network specific and is not defined by this class. Further
 information on the ToS octet can be found in RFC 1349 and RFC 2474. The value
 of the socket option is a hint. An implementation may ignore the
 value, or ignore specific values.

 The initial/default value of the TOS field in the ToS octet is
 implementation specific but will typically be 0. For
 datagram-oriented sockets the option may be configured at any time after
 the socket has been bound. The new value of the octet is used when sending
 subsequent datagrams. It is system dependent whether this option can be
 queried or changed prior to binding the socket.

 The behavior of this socket option on a stream-oriented socket, or an
 IPv6 socket, is not defined in this
 release.

See Also:

DatagramSocket.setTrafficClass(int)

IP_MULTICAST_IF

public static final SocketOption<NetworkInterface> IP_MULTICAST_IF

The network interface for Internet Protocol (IP) multicast datagrams.

 The value of this socket option is a NetworkInterface that
 represents the outgoing interface for multicast datagrams sent by the
 datagram-oriented socket. For IPv6
 sockets then it is system dependent whether setting this option also
 sets the outgoing interface for multlicast datagrams sent to IPv4
 addresses.

 The initial/default value of this socket option may be null
 to indicate that outgoing interface will be selected by the operating
 system, typically based on the network routing tables. An implementation
 allows this socket option to be set after the socket is bound. Whether
 the socket option can be queried or changed prior to binding the socket
 is system dependent.

See Also:

MulticastChannel,
MulticastSocket.setInterface(java.net.InetAddress)

IP_MULTICAST_TTL

public static final SocketOption<Integer> IP_MULTICAST_TTL

The time-to-live for Internet Protocol (IP) multicast datagrams.

 The value of this socket option is an Integer in the range
 <tt>0 <= value <= 255</tt>. It is used to control
 the scope of multicast datagrams sent by the datagram-oriented socket.
 In the case of an IPv4 socket
 the option is the time-to-live (TTL) on multicast datagrams sent by the
 socket. Datagrams with a TTL of zero are not transmitted on the network
 but may be delivered locally. In the case of an IPv6 socket the option is the
 hop limit which is number of hops that the datagram can
 pass through before expiring on the network. For IPv6 sockets it is
 system dependent whether the option also sets the time-to-live
 on multicast datagrams sent to IPv4 addresses.

 The initial/default value of the time-to-live setting is typically
 1. An implementation allows this socket option to be set after
 the socket is bound. Whether the socket option can be queried or changed
 prior to binding the socket is system dependent.

See Also:

MulticastChannel,
MulticastSocket.setTimeToLive(int)

IP_MULTICAST_LOOP

public static final SocketOption<Boolean> IP_MULTICAST_LOOP

Loopback for Internet Protocol (IP) multicast datagrams.

 The value of this socket option is a Boolean that controls
 the loopback of multicast datagrams. The value of the socket
 option represents if the option is enabled or disabled.

 The exact semantics of this socket options are system dependent.
 In particular, it is system dependent whether the loopback applies to
 multicast datagrams sent from the socket or received by the socket.
 For IPv6 sockets then it is
 system dependent whether the option also applies to multicast datagrams
 sent to IPv4 addresses.

 The initial/default value of this socket option is TRUE. An
 implementation allows this socket option to be set after the socket is
 bound. Whether the socket option can be queried or changed prior to
 binding the socket is system dependent.

See Also:

MulticastChannel,
MulticastSocket.setLoopbackMode(boolean)

TCP_NODELAY

public static final SocketOption<Boolean> TCP_NODELAY

Disable the Nagle algorithm.

 The value of this socket option is a Boolean that represents
 whether the option is enabled or disabled. The socket option is specific to
 stream-oriented sockets using the TCP/IP protocol. TCP/IP uses an algorithm
 known as The Nagle Algorithm to coalesce short segments and
 improve network efficiency.

 The default value of this socket option is FALSE. The
 socket option should only be enabled in cases where it is known that the
 coalescing impacts performance. The socket option may be enabled at any
 time. In other words, the Nagle Algorithm can be disabled. Once the option
 is enabled, it is system dependent whether it can be subsequently
 disabled. If it cannot, then invoking the setOption method to
 disable the option has no effect.

See Also:

RFC 1122:
 Requirements for Internet Hosts -- Communication Layers,
Socket.setTcpNoDelay(boolean)

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Java™ Platform
Standard Ed. 7

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

 Submit a bug or feature
For further API reference and developer documentation, see Java SE Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.
 Copyright © 1993, 2015, Oracle and/or its affiliates.  All rights reserved.


text:
<form action="/pip24/reset" method="post" class="form">

Delete saved answers

  <input type="submit" value="delete answers" />
</form>


text:
'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
	Schema = mongoose.Schema;

/**
 * Product Schema
 */
var ProductSchema = new Schema({

  name: String,

  brand: String,

  category: {type: Schema.Types.ObjectId, ref: 'Category'},

	created: {type: Date, default: Date.now},
	user: {type: Schema.ObjectId, ref: 'User'}
});
mongoose.model('Product', ProductSchema);


text:
#include "pk11.h"

#include "config.h"
#include "sessions.h"
#include "utils.h"
#include "tpm.h"
#include "object.h"
#include "log.h"

#include <sys/mman.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <endian.h>

#define SLOT_ID 0x1234

#define get_session(x) ((struct session*) x)

static const CK_MECHANISM_TYPE supported_mechanisms[] = {
  CKM_RSA_PKCS,
};

static struct config pk11_config = {0};
static struct session main_session;

CK_RV C_GetInfo(CK_INFO_PTR info) {
  print_log(VERBOSE, "C_GetInfo");
  info->cryptokiVersion.major = CRYPTOKI_VERSION_MAJOR;
  info->cryptokiVersion.minor = CRYPTOKI_VERSION_MINOR;
  strncpy_pad(info->manufacturerID, sizeof(info->manufacturerID), TPM2_PK11_MANUFACTURER, sizeof(info->manufacturerID));
  strncpy_pad(info->libraryDescription, sizeof(info->libraryDescription), TPM2_PK11_LIBRARY_DESCRIPTION, sizeof(info->libraryDescription));
  info->flags = 0;

  return CKR_OK;
}

CK_RV C_GetSlotList(CK_BBOOL present, CK_SLOT_ID_PTR list, CK_ULONG_PTR count) {
  print_log(VERBOSE, "C_GetSlotList: present = %s", present ? "true" : "false");
  if (*count && list)
    *list = SLOT_ID;

  *count = 1;

  return CKR_OK;
}

CK_RV C_OpenSession(CK_SLOT_ID id, CK_FLAGS flags, CK_VOID_PTR application, CK_NOTIFY notify, CK_SESSION_HANDLE_PTR session) {
  print_log(VERBOSE, "C_OpenSession: id = %d, flags = %x", id, flags);
  *session = (unsigned long) malloc(sizeof(struct session));
  if ((void*) *session == NULL)
    return CKR_GENERAL_ERROR;

  int ret = session_init((struct session*) *session, &pk11_config);

  return ret != 0 ? CKR_GENERAL_ERROR : CKR_OK;
}

CK_RV C_CloseSession(CK_SESSION_HANDLE session_handle) {
  print_log(VERBOSE, "C_CloseSession: session = %x", session_handle);
  session_close(get_session(session_handle));
  free(get_session(session_handle));
  return CKR_OK;
}

CK_RV C_GetSessionInfo(CK_SESSION_HANDLE session_handle, CK_SESSION_INFO_PTR info) {
  print_log(VERBOSE, "C_GetSessionInfo: session = %x", session_handle);
  info->slotID = 0;
  info->state = CKS_RO_USER_FUNCTIONS;
  info->flags = CKF_SERIAL_SESSION;
  info->ulDeviceError = 0;
  return CKR_OK;
}

CK_RV C_GetSlotInfo(CK_SLOT_ID id, CK_SLOT_INFO_PTR info) {
  print_log(VERBOSE, "C_GetSlotInfo: id = %d", id);
  TPMS_CAPABILITY_DATA fixed;
  if (tpm_info(main_session.context, TPM2_PT_FIXED, &fixed) != TPM2_RC_SUCCESS)
    return CKR_DEVICE_ERROR;

  TPML_TAGGED_TPM_PROPERTY props = fixed.data.tpmProperties;
  TPMS_TAGGED_PROPERTY* manufacturer = tpm_info_get(props.tpmProperty, props.count, TPM2_PT_MANUFACTURER);
  UINT32 manufacturer_val = manufacturer ? htobe32(manufacturer->value) : 0;
  strncpy_pad(info->manufacturerID, sizeof(info->manufacturerID), manufacturer ? (char*) &manufacturer_val : TPM2_PK11_MANUFACTURER, manufacturer ? 4 : sizeof(info->manufacturerID));
  strncpy_pad(info->slotDescription, sizeof(info->slotDescription), TPM2_PK11_SLOT_DESCRIPTION, sizeof(info->slotDescription));

  info->flags = CKF_TOKEN_PRESENT | CKF_HW_SLOT;
  TPMS_TAGGED_PROPERTY* revision = tpm_info_get(props.tpmProperty, props.count, TPM2_PT_REVISION);
  info->hardwareVersion.major = revision ? revision->value / 100 : 0;
  info->hardwareVersion.minor = revision ? revision->value % 100 : 0;
  TPMS_TAGGED_PROPERTY* major = tpm_info_get(props.tpmProperty, props.count, TPM2_PT_FIRMWARE_VERSION_1);
  info->firmwareVersion.major = major ? major->value : 0;
  TPMS_TAGGED_PROPERTY* minor = tpm_info_get(props.tpmProperty, props.count, TPM2_PT_FIRMWARE_VERSION_2);
  info->firmwareVersion.minor = major ? major->value : 0;
  return CKR_OK;
}

CK_RV C_GetTokenInfo(CK_SLOT_ID id, CK_TOKEN_INFO_PTR info) {
  print_log(VERBOSE, "C_GetTokenInfo: id = %d", id);
  TPMS_CAPABILITY_DATA fixed;
  if (tpm_info(main_session.context, TPM2_PT_FIXED, &fixed) != TPM2_RC_SUCCESS)
    return CKR_DEVICE_ERROR;

  TPML_TAGGED_TPM_PROPERTY props = fixed.data.tpmProperties;
  strncpy_pad(info->label, sizeof(info->label), TPM2_PK11_EMPTY, sizeof(info->label));
  TPMS_TAGGED_PROPERTY* manufacturer = tpm_info_get(props.tpmProperty, props.count, TPM2_PT_MANUFACTURER);
  UINT32 manufacturer_val = manufacturer ? htobe32(manufacturer->value) : 0;
  strncpy_pad(info->manufacturerID, sizeof(info->manufacturerID), manufacturer ? (char*) &manufacturer_val : TPM2_PK11_MANUFACTURER, manufacturer ? 4 : sizeof(info->manufacturerID));
  strncpy_pad(info->model, sizeof(info->label), TPM2_PK11_MODEL, sizeof(info->label));
  strncpy_pad(info->serialNumber, sizeof(info->serialNumber), TPM2_PK11_SERIAL, sizeof(info->serialNumber));
  strncpy_pad(info->utcTime, sizeof(info->utcTime), "", sizeof(info->utcTime));

  info->flags = CKF_TOKEN_INITIALIZED | CKF_WRITE_PROTECTED;
  if (pk11_config.login_required)
    info->flags |= CKF_LOGIN_REQUIRED;

  TPMS_TAGGED_PROPERTY* max_sessions = tpm_info_get(props.tpmProperty, props.count, TPM2_PT_ACTIVE_SESSIONS_MAX);
  info->ulMaxSessionCount = max_sessions ? max_sessions->value : CK_EFFECTIVELY_INFINITE;
  info->ulSessionCount = open_sessions;
  info->ulMaxRwSessionCount = max_sessions ? max_sessions->value : CK_EFFECTIVELY_INFINITE;
  info->ulRwSessionCount = 0;
  info->ulMaxPinLen = 64;
  info->ulMinPinLen = 0;
  info->ulTotalPublicMemory = CK_UNAVAILABLE_INFORMATION;
  info->ulFreePublicMemory = CK_UNAVAILABLE_INFORMATION;
  info->ulTotalPrivateMemory = CK_UNAVAILABLE_INFORMATION;
  info->ulFreePrivateMemory = CK_UNAVAILABLE_INFORMATION;
  TPMS_TAGGED_PROPERTY* revision = tpm_info_get(props.tpmProperty, props.count, TPM2_PT_REVISION);
  info->hardwareVersion.major = revision ? revision->value / 100 : 0;
  info->hardwareVersion.minor = revision ? revision->value % 100 : 0;
  TPMS_TAGGED_PROPERTY* major = tpm_info_get(props.tpmProperty, props.count, TPM2_PT_FIRMWARE_VERSION_1);
  info->firmwareVersion.major = major ? major->value : 0;
  TPMS_TAGGED_PROPERTY* minor = tpm_info_get(props.tpmProperty, props.count, TPM2_PT_FIRMWARE_VERSION_2);
  info->firmwareVersion.minor = major ? major->value : 0;

  return CKR_OK;
}

CK_RV C_Finalize(CK_VOID_PTR reserved) {
  print_log(VERBOSE, "C_Finalize");
  session_close(&main_session);
  return CKR_OK;
}

CK_RV C_FindObjectsInit(CK_SESSION_HANDLE session_handle, CK_ATTRIBUTE_PTR filters, CK_ULONG count) {
  print_log(VERBOSE, "C_FindObjectsInit: session = %x, count = %d", session_handle, count);
  struct session *session = get_session(session_handle);
  session->find_cursor = session->objects;
  session->filters = filters;
  session->num_filters = count;
  return CKR_OK;
}

CK_RV C_FindObjects(CK_SESSION_HANDLE session_handle, CK_OBJECT_HANDLE_PTR object_handle, CK_ULONG max_objects, CK_ULONG_PTR found) {
  print_log(VERBOSE, "C_FindObjects: session = %x, max = %d", session_handle, max_objects);
  TPMS_CAPABILITY_DATA persistent;
  tpm_info(get_session(session_handle)->context, TPM2_HT_PERSISTENT, &persistent);
  struct session* session = get_session(session_handle);
  *found = 0;

  while (session->find_cursor != NULL && *found < max_objects) {
    pObject object = session->find_cursor->object;
    bool filtered = false;
    for (int j = 0; j < session->num_filters; j++) {
      size_t size = 0;
      void* value = attr_get(object, session->filters[j].type, &size);
      if (session->filters[j].ulValueLen != size || memcmp(session->filters[j].pValue, value, size) != 0) {
        filtered = true;
        break;
      }
    }
    if (!filtered) {
      object_handle[*found] = (CK_OBJECT_HANDLE) session->find_cursor->object;
      (*found)++;
    }
    session->find_cursor = session->find_cursor->next;
  }

  return CKR_OK;
}

CK_RV C_FindObjectsFinal(CK_SESSION_HANDLE session_handle) {
  print_log(VERBOSE, "C_FindObjectsFinal: session = %x", session_handle);
  return CKR_OK;
}

CK_RV C_GetAttributeValue(CK_SESSION_HANDLE session_handle, CK_OBJECT_HANDLE object_handle, CK_ATTRIBUTE_PTR template, CK_ULONG count) {
  print_log(VERBOSE, "C_GetAttributeValue: session = %x, object = %x, count = %d", session_handle, object_handle, count);
  pObject object = (pObject) object_handle;

  for (int i = 0; i < count; i++) {
    void* entry_obj = NULL;
    pAttrIndex entry = NULL;
    for (int j = 0; j < object->num_entries; j++) {
      void *obj = object->entries[j].object;
      pAttrIndex index = object->entries[j].indexes;
      for (int k = 0; k < object->entries[j].num_attrs; k++) {
        if (template[i].type == index[k].type) {
          entry = &index[k];
          entry_obj = obj;
          continue;
        }
      }
      if (entry)
        continue;
    }
    if (!entry) {
      print_log(DEBUG, " attribute not found: type = %x", template[i].type);
      template[i].ulValueLen = 0;
    } else if (entry->size_offset == 0) {
      print_log(DEBUG, " return attribute: type = %x, size = %d, buffer_size = %d", template[i].type, entry->size, template[i].ulValueLen);
      retmem(template[i].pValue, &template[i].ulValueLen, entry_obj + entry->offset, entry->size);
    } else {
      print_log(DEBUG, " return attribute: type = %x, size = %d, buffer_size = %d", template[i].type, *((size_t*) (entry_obj + entry->size_offset)), template[i].ulValueLen);
      retmem(template[i].pValue, &template[i].ulValueLen, *((void**) (entry_obj + entry->offset)), *((size_t*) (entry_obj + entry->size_offset)));
    }
  }

  return CKR_OK;
}

CK_RV C_SignInit(CK_SESSION_HANDLE session_handle, CK_MECHANISM_PTR mechanism, CK_OBJECT_HANDLE key) {
  print_log(VERBOSE, "C_SignInit: session = %x, key = %x", session_handle, key);
  pObject object = (pObject) key;
  struct session* session = get_session(session_handle);
  session->key_handle = object->tpm_handle;
  session->current_object = object;
  return CKR_OK;
}

CK_RV C_Sign(CK_SESSION_HANDLE session_handle, CK_BYTE_PTR data, CK_ULONG data_len, CK_BYTE_PTR signature, CK_ULONG_PTR signature_len) {
  print_log(VERBOSE, "C_Sign: session = %x, len = %d", session_handle, data_len);
  struct session* session = get_session(session_handle);
  TPM2_RC ret;

  if (pk11_config.sign_using_encrypt) {
    TPM2B_PUBLIC_KEY_RSA message = { .TSS_COMPAT_TMPB(size) = TPM2_MAX_RSA_KEY_BYTES };
    pObject object = session->current_object->opposite;
    CK_ULONG_PTR key_size = (CK_ULONG_PTR) attr_get(object, CKA_MODULUS_BITS, NULL);
    ret = tpm_sign_encrypt(session->context, session->key_handle, *key_size / 8, data, data_len, &message, session->password);
    retmem(signature, signature_len, message.TSS_COMPAT_TMPB(buffer), message.TSS_COMPAT_TMPB(size));
  } else {
    TPMT_SIGNATURE sign = {0};
    ret = tpm_sign(session->context, session->key_handle, data, data_len, &sign, session->password);
    retmem(signature, signature_len, sign.signature.rsassa.sig.TSS_COMPAT_TMPB(buffer), sign.signature.rsassa.sig.TSS_COMPAT_TMPB(size));
  }

  return ret == TPM2_RC_SUCCESS ? CKR_OK : CKR_GENERAL_ERROR;
}

CK_RV C_DecryptInit(CK_SESSION_HANDLE session_handle, CK_MECHANISM_PTR mechanism, CK_OBJECT_HANDLE key) {
  print_log(VERBOSE, "C_DecryptInit: session = %x, key = %x", session_handle, key);
  pObject object = (pObject) key;
  get_session(session_handle)->key_handle = object->tpm_handle;
  return CKR_OK;
}

CK_RV C_Decrypt(CK_SESSION_HANDLE session_handle, CK_BYTE_PTR enc_data, CK_ULONG enc_data_len, CK_BYTE_PTR data, CK_ULONG_PTR data_len) {
  print_log(VERBOSE, "C_Decrypt: session = %x, len = %d", session_handle, enc_data_len);
  TPM2B_PUBLIC_KEY_RSA message = { .TSS_COMPAT_TMPB(size) = TPM2_MAX_RSA_KEY_BYTES };
  struct session* session = get_session(session_handle);
  TPM2_RC ret = tpm_decrypt(session->context, session->key_handle, enc_data, enc_data_len, &message, session->password);
  retmem(data, data_len, message.TSS_COMPAT_TMPB(buffer), message.TSS_COMPAT_TMPB(size));

  return ret == TPM2_RC_SUCCESS ? CKR_OK : CKR_GENERAL_ERROR;
}

CK_RV C_Initialize(CK_VOID_PTR pInitArgs) {
  print_log(VERBOSE, "C_Initialize");
  char configfile_path[256];
  snprintf(configfile_path, sizeof(configfile_path), "%s/" TPM2_PK11_CONFIG_DIR "/" TPM2_PK11_CONFIG_FILE, getenv("HOME"));
  if (config_load(configfile_path, &pk11_config) < 0)
    return CKR_GENERAL_ERROR;

  session_init(&main_session, &pk11_config);
  log_init(pk11_config.log_file, pk11_config.log_level);
  return CKR_OK;
}

/* Stubs for not yet supported functions*/
CK_RV C_GetMechanismList(CK_SLOT_ID id, CK_MECHANISM_TYPE_PTR list, CK_ULONG_PTR count) {
  print_log(VERBOSE, "C_GetMechanismList: slot = %d", id);

  if (count == NULL_PTR)
    return CKR_ARGUMENTS_BAD;

  int countSupported = sizeof(supported_mechanisms) / sizeof(CK_MECHANISM_TYPE);

  if (list != NULL_PTR && *count < countSupported) {
    *count = countSupported;
    return CKR_BUFFER_TOO_SMALL;
  }

  *count = countSupported;
  if (list != NULL_PTR) {
    for (CK_ULONG i = 0; i < countSupported; i++) {
      list[i] = supported_mechanisms[i];
    }
  }

  return CKR_OK;
}

CK_RV C_GetMechanismInfo (CK_SLOT_ID id, CK_MECHANISM_TYPE type, CK_MECHANISM_INFO_PTR info) {
  print_log(VERBOSE, "C_GetMechanismInfo: slot = %d", id);
  return CKR_FUNCTION_NOT_SUPPORTED;
}

CK_RV C_InitToken (CK_SLOT_ID id, CK_CHAR_PTR pin, CK_ULONG pin_len, CK_CHAR_PTR label) {
  print_log(VERBOSE, "C_InitToken: slot = %d", id);
  return CKR_FUNCTION_NOT_SUPPORTED;
}

CK_RV C_InitPIN (CK_SESSION_HANDLE session_handle, CK_CHAR_PTR pin, CK_ULONG pin_len) {
  print_log(VERBOSE, "C_InitPIN: session = %x", session_handle);
  return CKR_FUNCTION_NOT_SUPPORTED;
}

CK_RV C_SetPIN (CK_SESSION_HANDLE session_handle, CK_CHAR_PTR old_pin, CK_ULONG old_pin_len, CK_CHAR_PTR new_pin, CK_ULONG new_pin_len) {
  print_log(VERBOSE, "C_SetPIN: session = %x", session_handle);
  return CKR_FUNCTION_NOT_SUPPORTED;
}

CK_RV C_CloseAllSessions (CK_SLOT_ID id) {
  print_log(VERBOSE, "C_CloseAllSessions: slot = %d", id);
  return CKR_FUNCTION_NOT_SUPPORTED;
}

CK_RV C_GetOperationState(CK_SESSION_HANDLE session_handle, CK_BYTE_PTR state, CK_ULONG_PTR state_len) {
  print_log(VERBOSE, "C_GetOperationState: session = %x, len = %d", session_handle, state_len);
  return CKR_FUNCTION_NOT_SUPPORTED;
}

CK_RV C_SetOperationState(CK_SESSION_HANDLE session_handle, CK_BYTE_PTR state, CK_ULONG state_len, CK_OBJECT_HANDLE enc_key, CK_OBJECT_HANDLE auth_key) {
  print_log(VERBOSE, "C_SetOperationState: session = %x, len = %d, enc_key = %x, auth_key = %x", session_handle, state_len, enc_key, auth_key);
  return CKR_FUNCTION_NOT_SUPPORTED;
}

CK_RV C_Login(CK_SESSION_HANDLE session_handle, CK_USER_TYPE userType, CK_UTF8CHAR_PTR pin, CK_ULONG pin_len) {
  print_log(VERBOSE, "C_Login: session = %x", session_handle);

  if (userType != CKU_USER)
    return CKR_USER_TYPE_INVALID;

  struct session* session = get_session(session_handle);
  session->password = strndup(pin, pin_len);

  return CKR_OK;
}

CK_RV C_Logout(CK_SESSION_HANDLE session_handle) {
  print_log(VERBOSE, "C_Logout: session = %x", session_handle);

  struct session* session = get_session(session_handle);
  if (session->password) {
    free(session->password);
    session->password = NULL;
  }

  return CKR_OK;
}

CK_RV C_CreateObject(CK_SESSION_HANDLE session_handle, CK_ATTRIBUTE_PTR template, CK_ULONG count, CK_OBJECT_HANDLE_PTR object) {
  print_log(VERBOSE, "C_CreateObject: session = %x, count = %d", session_handle, count);
  return CKR_FUNCTION_NOT_SUPPORTED;
}

CK_RV C_CopyObject(CK_SESSION_HANDLE session_handle, CK_OBJECT_HANDLE object, CK_ATTRIBUTE_PTR template, CK_ULONG count, CK_OBJECT_HANDLE_PTR new_object) {
  print_log(VERBOSE, "C_CopyObject: session = %x, object = %x, count = %d", session_handle, object, count);
  return CKR_FUNCTION_NOT_SUPPORTED;
}

CK_RV C_DestroyObject(CK_SESSION_HANDLE session_handle, CK_OBJECT_HANDLE object) {
  print_log(VERBOSE, "C_DestroyObject: session = %x, object = %x", session_handle, object);
  return CKR_FUNCTION_NOT_SUPPORTED;
}

CK_RV C_GetObjectSize(CK_SESSION_HANDLE session_handle, CK_OBJECT_HANDLE object, CK_ULONG_PTR size) {
  print_log(VERBOSE, "C_GetObjectSize: session = %x, object = %x", session_handle, object);
  return CKR_FUNCTION_NOT_SUPPORTED;
}

CK_RV C_SetAttributeValue(CK_SESSION_HANDLE session_handle, CK_OBJECT_HANDLE object, CK_ATTRIBUTE_PTR template, CK_ULONG count) {
  print_log(VERBOSE, "C_SetAttributeValue: session = %x, object = %x, count = %d", session_handle, object, count);
  return CKR_FUNCTION_NOT_SUPPORTED;
}

CK_RV C_EncryptInit(CK_SESSION_HANDLE session_handle, CK_MECHANISM_PTR mechanism, CK_OBJECT_HANDLE object) {
  print_log(VERBOSE, "C_EncryptInit: session = %x, object = %x", session_handle, object);
  return CKR_FUNCTION_NOT_SUPPORTED;
}

CK_RV C_Encrypt(CK_SESSION_HANDLE session_handle, CK_BYTE_PTR data, CK_ULONG data_len, CK_BYTE_PTR enc_data, CK_ULONG_PTR enc_data_len) {
  print_log(VERBOSE, "C_Encrypt: session = %x, len = %x", session_handle, data_len);
  return CKR_FUNCTION_NOT_SUPPORTED;
}

CK_RV C_EncryptUpdate(CK_SESSION_HANDLE session_handle, CK_BYTE_PTR data, CK_ULONG data_len, CK_BYTE_PTR enc_data, CK_ULONG_PTR enc_data_len) {
  print_log(VERBOSE, "C_EncryptUpdate: session = %x, len = %x", session_handle, data_len);
  return CKR_FUNCTION_NOT_SUPPORTED;
}

CK_RV C_EncryptFinal(CK_SESSION_HANDLE session_handle, CK_BYTE_PTR enc_data, CK_ULONG_PTR enc_data_len) {
  print_log(VERBOSE, "C_EncryptFinal: session = %x", session_handle);
  return CKR_FUNCTION_NOT_SUPPORTED;
}

CK_RV C_DecryptUpdate(CK_SESSION_HANDLE session_handle, CK_BYTE_PTR enc_data, CK_ULONG enc_data_len, CK_BYTE_PTR data, CK_ULONG_PTR data_len) {
  print_log(VERBOSE, "C_DecryptUpdate: session = %x, len = %x", session_handle, enc_data_len);
  return CKR_FUNCTION_NOT_SUPPORTED;
}

CK_RV C_DecryptFinal(CK_SESSION_HANDLE session_handle, CK_BYTE_PTR data, CK_ULONG_PTR data_len) {
  print_log(VERBOSE, "C_DecryptFinal: session = %x", session_handle);
  return CKR_FUNCTION_NOT_SUPPORTED;
}

CK_RV C_DigestInit(CK_SESSION_HANDLE session_handle, CK_MECHANISM_PTR mechanism) {
  print_log(VERBOSE, "C_DigestInit: session = %x", session_handle);
  return CKR_FUNCTION_NOT_SUPPORTED;
}

CK_RV C_Digest(CK_SESSION_HANDLE session_handle, CK_BYTE_PTR data, CK_ULONG data_len, CK_BYTE_PTR digest, CK_ULONG_PTR digest_len) {
  print_log(VERBOSE, "C_Digest: session = %x, len = %x", session_handle, data_len);
  return CKR_FUNCTION_NOT_SUPPORTED;
}

CK_RV C_DigestUpdate(CK_SESSION_HANDLE session_handle, CK_BYTE_PTR part, CK_ULONG part_len) {
  print_log(VERBOSE, "C_DigestUpdate: session = %x, len = %x", session_handle, part_len);
  return CKR_FUNCTION_NOT_SUPPORTED;
}

CK_RV C_DigestKey(CK_SESSION_HANDLE session_handle, CK_OBJECT_HANDLE object) {
  print_log(VERBOSE, "C_DigestKey: session = %x, object = %x", session_handle, object);
  return CKR_FUNCTION_NOT_SUPPORTED;
}

CK_RV C_DigestFinal(CK_SESSION_HANDLE session_handle, CK_BYTE_PTR digest, CK_ULONG_PTR digest_len) {
  print_log(VERBOSE, "C_DigestFinal: session = %x", session_handle);
  return CKR_FUNCTION_NOT_SUPPORTED;
}

CK_RV C_SignUpdate(CK_SESSION_HANDLE session_handle, CK_BYTE_PTR part, CK_ULONG part_len) {
  print_log(VERBOSE, "C_SignUpdate: session = %x, len = %x", session_handle, part_len);
  return CKR_FUNCTION_NOT_SUPPORTED;
}

CK_RV C_SignFinal(CK_SESSION_HANDLE session_handle, CK_BYTE_PTR signature, CK_ULONG_PTR signature_len) {
  print_log(VERBOSE, "C_SignFinal: session = %x", session_handle);
  return CKR_FUNCTION_NOT_SUPPORTED;
}

CK_RV C_SignRecoverInit(CK_SESSION_HANDLE session_handle, CK_MECHANISM_PTR mechanism, CK_OBJECT_HANDLE key) {
  print_log(VERBOSE, "C_SignRecoverInit: session = %x, key = %x", session_handle, key);
  return CKR_FUNCTION_NOT_SUPPORTED;
}

CK_RV C_SignRecover(CK_SESSION_HANDLE session_handle, CK_BYTE_PTR data, CK_ULONG data_len, CK_BYTE_PTR signature, CK_ULONG_PTR signature_len) {
  print_log(VERBOSE, "C_SignRecover: session = %x, len = %d", session_handle, data_len);
  return CKR_FUNCTION_NOT_SUPPORTED;
}

CK_RV C_VerifyInit(CK_SESSION_HANDLE session_handle, CK_MECHANISM_PTR mechanism, CK_OBJECT_HANDLE key) {
  print_log(VERBOSE, "C_VerifyInit: session = %x, key = %x", session_handle, key);
  return CKR_FUNCTION_NOT_SUPPORTED;
}

CK_RV C_Verify(CK_SESSION_HANDLE session_handle, CK_BYTE_PTR data, CK_ULONG data_len, CK_BYTE_PTR signature, CK_ULONG signature_len) {
  print_log(VERBOSE, "C_Verify: session = %x, len = %d", session_handle, data_len);
  return CKR_FUNCTION_NOT_SUPPORTED;
}

CK_RV C_VerifyUpdate(CK_SESSION_HANDLE session_handle, CK_BYTE_PTR part, CK_ULONG part_len) {
  print_log(VERBOSE, "C_VerifyUpdate: session = %x, len = %d", session_handle, part_len);
  return CKR_FUNCTION_NOT_SUPPORTED;
}

CK_RV C_VerifyFinal(CK_SESSION_HANDLE session_handle, CK_BYTE_PTR signature, CK_ULONG signature_len) {
  print_log(VERBOSE, "C_VerifyFinal: session = %x", session_handle);
  return CKR_FUNCTION_NOT_SUPPORTED;
}

CK_RV C_VerifyRecoverInit(CK_SESSION_HANDLE session_handle, CK_MECHANISM_PTR mechanism, CK_OBJECT_HANDLE key) {
  print_log(VERBOSE, "C_VerifyRecoverInit: session = %x, key = %x", session_handle, key);
  return CKR_FUNCTION_NOT_SUPPORTED;
}

CK_RV C_VerifyRecover(CK_SESSION_HANDLE session_handle, CK_BYTE_PTR signature, CK_ULONG signature_len, CK_BYTE_PTR data, CK_ULONG_PTR data_len) {
  print_log(VERBOSE, "C_VerifyRecover: session = %x, len = %d", session_handle, signature_len);
  return CKR_FUNCTION_NOT_SUPPORTED;
}

CK_RV C_DigestEncryptUpdate(CK_SESSION_HANDLE session_handle, CK_BYTE_PTR part, CK_ULONG part_len, CK_BYTE_PTR enc_part, CK_ULONG_PTR enc_part_len) {
  print_log(VERBOSE, "C_DigestEncryptUpdate: session = %x, len = %d", session_handle, part_len);
  return CKR_FUNCTION_NOT_SUPPORTED;
}

CK_RV C_DecryptDigestUpdate(CK_SESSION_HANDLE session_handle, CK_BYTE_PTR part, CK_ULONG part_len, CK_BYTE_PTR dec_part, CK_ULONG_PTR dec_part_len) {
  print_log(VERBOSE, "C_DigestEncryptUpdate: session = %x, len = %d", session_handle, part_len);
  return CKR_FUNCTION_NOT_SUPPORTED;
}

CK_RV C_SignEncryptUpdate(CK_SESSION_HANDLE session_handle, CK_BYTE_PTR part, CK_ULONG part_len, CK_BYTE_PTR enc_part, CK_ULONG_PTR enc_part_len) {
  print_log(VERBOSE, "C_DigestEncryptUpdate: session = %x, len = %d", session_handle, part_len);
  return CKR_FUNCTION_NOT_SUPPORTED;
}

CK_RV C_DecryptVerifyUpdate(CK_SESSION_HANDLE session_handle, CK_BYTE_PTR enc_part, CK_ULONG enc_part_len, CK_BYTE_PTR part, CK_ULONG_PTR part_len) {
  print_log(VERBOSE, "C_DigestEncryptUpdate: session = %x, len = %d", session_handle, enc_part_len);
  return CKR_FUNCTION_NOT_SUPPORTED;
}

CK_RV C_GenerateKey(CK_SESSION_HANDLE session_handle, CK_MECHANISM_PTR mechanism, CK_ATTRIBUTE_PTR template, CK_ULONG count, CK_OBJECT_HANDLE_PTR key) {
  print_log(VERBOSE, "C_GenerateKey: session = %x, count = %d", session_handle, count);
  return CKR_FUNCTION_NOT_SUPPORTED;
}

CK_RV C_GenerateKeyPair(CK_SESSION_HANDLE session_handle, CK_MECHANISM_PTR mechanism, CK_ATTRIBUTE_PTR public_key_template, CK_ULONG public_key_attr_count, CK_ATTRIBUTE_PTR private_key_template, CK_ULONG private_key_attr_count, CK_OBJECT_HANDLE_PTR public_key, CK_OBJECT_HANDLE_PTR private_key) {
  print_log(VERBOSE, "C_GenerateKeyPair: session = %x, public_count = %d, private_count = %d", session_handle, public_key_attr_count, private_key_attr_count);
  return CKR_FUNCTION_NOT_SUPPORTED;
}

CK_RV C_WrapKey(CK_SESSION_HANDLE session_handle, CK_MECHANISM_PTR mechanism, CK_OBJECT_HANDLE wrapping_key, CK_OBJECT_HANDLE key, CK_BYTE_PTR wrapped_key, CK_ULONG_PTR wrapped_key_len) {
  print_log(VERBOSE, "C_WrapKey: session = %x, wrapping_key = %x, key = %x", session_handle, wrapping_key, key);
  return CKR_FUNCTION_NOT_SUPPORTED;
}

CK_RV C_UnwrapKey(CK_SESSION_HANDLE session_handle, CK_MECHANISM_PTR mechanism, CK_OBJECT_HANDLE unwrapping_key, CK_BYTE_PTR wrapped_key, CK_ULONG wrapped_key_len, CK_ATTRIBUTE_PTR template, CK_ULONG count, CK_OBJECT_HANDLE_PTR key) {
  print_log(VERBOSE, "C_UnwrapKey: session = %x, unwrapping_key = %x, key = %x, count = %d", session_handle, unwrapping_key, key, count);
  return CKR_FUNCTION_NOT_SUPPORTED;
}

CK_RV C_DeriveKey(CK_SESSION_HANDLE session_handle, CK_MECHANISM_PTR mechanism, CK_OBJECT_HANDLE base_key, CK_ATTRIBUTE_PTR template, CK_ULONG count, CK_OBJECT_HANDLE_PTR key) {
  print_log(VERBOSE, "C_WrapKey: session = %x, base_key = %x, count = %d", session_handle, base_key, count);
  return CKR_FUNCTION_NOT_SUPPORTED;
}

CK_RV C_SeedRandom(CK_SESSION_HANDLE session_handle, CK_BYTE_PTR seed, CK_ULONG seed_len) {
  print_log(VERBOSE, "C_SeedRandom: session = %x, len = %d", session_handle, seed_len);
  return CKR_FUNCTION_NOT_SUPPORTED;
}

CK_RV C_GenerateRandom(CK_SESSION_HANDLE session_handle, CK_BYTE_PTR random_data, CK_ULONG random_data_len) {
  print_log(VERBOSE, "C_GenerateRandom: session = %x, len = %d", session_handle, random_data_len);
  return CKR_FUNCTION_NOT_SUPPORTED;
}

CK_RV C_GetFunctionStatus(CK_SESSION_HANDLE session_handle) {
  print_log(VERBOSE, "C_GetFunctionStatus: session = %x", session_handle);
  return CKR_FUNCTION_NOT_SUPPORTED;
}

CK_RV C_CancelFunction(CK_SESSION_HANDLE session_handle) {
  print_log(VERBOSE, "C_CancelFunction: session = %x", session_handle);
  return CKR_FUNCTION_NOT_SUPPORTED;
}

CK_RV C_WaitForSlotEvent(CK_FLAGS flags, CK_SLOT_ID_PTR slot, CK_VOID_PTR reserved) {
  print_log(VERBOSE, "C_WaitForSlotEvent: flags = %x", flags);
  return CKR_FUNCTION_NOT_SUPPORTED;
}

static CK_FUNCTION_LIST function_list = {
  { CRYPTOKI_VERSION_MAJOR, CRYPTOKI_VERSION_MINOR },
  .C_Initialize = C_Initialize,
  .C_Finalize = C_Finalize,
  .C_GetInfo = C_GetInfo,
  .C_GetSlotList = C_GetSlotList,
  .C_GetSlotInfo = C_GetSlotInfo,
  .C_GetTokenInfo = C_GetTokenInfo,
  .C_GetMechanismList = C_GetMechanismList,
  .C_GetMechanismInfo = C_GetMechanismInfo,
  .C_InitToken = C_InitToken,
  .C_InitPIN = C_InitPIN,
  .C_SetPIN = C_SetPIN,
  .C_OpenSession = C_OpenSession,
  .C_CloseSession = C_CloseSession,
  .C_CloseAllSessions = C_CloseAllSessions,
  .C_GetSessionInfo = C_GetSessionInfo,
  .C_CloseAllSessions = C_CloseAllSessions,
  .C_GetOperationState = C_GetOperationState,
  .C_SetOperationState = C_SetOperationState,
  .C_Login = C_Login,
  .C_Logout = C_Logout,
  .C_CreateObject = C_CreateObject,
  .C_CopyObject = C_CopyObject,
  .C_DestroyObject = C_DestroyObject,
  .C_GetObjectSize = C_GetObjectSize,
  .C_GetAttributeValue = C_GetAttributeValue,
  .C_SetAttributeValue = C_SetAttributeValue,
  .C_FindObjectsInit = C_FindObjectsInit,
  .C_FindObjects = C_FindObjects,
  .C_FindObjectsFinal = C_FindObjectsFinal,
  .C_EncryptInit = C_EncryptInit,
  .C_Encrypt = C_Encrypt,
  .C_EncryptUpdate = C_EncryptUpdate,
  .C_EncryptFinal = C_EncryptFinal,
  .C_DecryptInit = C_DecryptInit,
  .C_Decrypt = C_Decrypt,
  .C_DecryptUpdate = C_DecryptUpdate,
  .C_DecryptFinal = C_DecryptFinal,
  .C_DigestInit = C_DigestInit,
  .C_Digest = C_Digest,
  .C_DigestUpdate = C_DigestUpdate,
  .C_DigestKey = C_DigestKey,
  .C_DigestFinal = C_DigestFinal,
  .C_SignInit = C_SignInit,
  .C_Sign = C_Sign,
  .C_SignUpdate = C_SignUpdate,
  .C_SignFinal = C_SignFinal,
  .C_SignRecoverInit = C_SignRecoverInit,
  .C_SignRecover = C_SignRecover,
  .C_VerifyInit = C_VerifyInit,
  .C_Verify = C_Verify,
  .C_VerifyUpdate = C_VerifyUpdate,
  .C_VerifyFinal = C_VerifyFinal,
  .C_VerifyRecoverInit = C_VerifyRecoverInit,
  .C_VerifyRecover = C_VerifyRecover,
  .C_DigestEncryptUpdate = C_DigestEncryptUpdate,
  .C_DecryptDigestUpdate = C_DecryptDigestUpdate,
  .C_SignEncryptUpdate = C_SignEncryptUpdate,
  .C_DecryptVerifyUpdate = C_DecryptVerifyUpdate,
  .C_GenerateKey = C_GenerateKey,
  .C_GenerateKeyPair = C_GenerateKeyPair,
  .C_WrapKey = C_WrapKey,
  .C_UnwrapKey = C_UnwrapKey,
  .C_DeriveKey = C_DeriveKey,
  .C_SeedRandom = C_SeedRandom,
  .C_GenerateRandom = C_GenerateRandom,
  .C_GetFunctionStatus = C_GetFunctionStatus,
  .C_CancelFunction = C_CancelFunction,
  .C_WaitForSlotEvent = C_WaitForSlotEvent,
};

CK_RV C_GetFunctionList(CK_FUNCTION_LIST_PTR_PTR list) {
  if (list == NULL_PTR)
    return CKR_ARGUMENTS_BAD;

  *list = &function_list;
  return CKR_OK;
}


text:
CONTIKI_PROJECT=webserver6
all: $(CONTIKI_PROJECT) $(WITH_WEBSERVER)

ifeq ($(WITH_WEBSERVER),)
#
#Set default webserver for different platforms
#Although Makefile.include sets the default target, we need to know it now.
#
ifeq ($(TARGET),)
  -include Makefile.target
endif
ifeq ($(TARGET),sky)
SMALL=1
WITH_WEBSERVER=webserver-nano
else ifeq ($(TARGET),avr-raven)
WITH_WEBSERVER=raven-webserver
endif
#
endif

ifneq ($(WITH_WEBSERVER),)
APPS = $(WITH_WEBSERVER)
ifeq ($(WITH_WEBSERVER),raven-webserver)
APPS+=raven-lcd-interface
endif
#copy output to e.g. webserver-nano.sky, raven-webserver.avr-raven
$(WITH_WEBSERVER) : $(CONTIKI_PROJECT)
	cp $(CONTIKI_PROJECT).$(TARGET) $(WITH_WEBSERVER).$(TARGET)
	@if (test -n "$(ELF_SIZE)");then $(ELF_SIZE) $(WITH_WEBSERVER).$(TARGET);fi
else
APPS=webserver

all : $(CONTIKI_PROJECT)
	@if (test -n "$(ELF_SIZE)");then $(ELF_SIZE) $(CONTIKI_PROJECT).$(TARGET);fi
endif

DEFINES=UIP_CONF_TCP=1

# Make no RPL the default for minimal-net builds
ifeq ($(TARGET),minimal-net)
ifndef CONTIKI_WITH_RPL
CONTIKI_WITH_RPL = 0
endif
endif

CONTIKI = ../..
CONTIKI_WITH_IPV6 = 1
include $(CONTIKI)/Makefile.include


text:
var MollieComponents = Class.create();
MollieComponents.prototype = {
    components: {},

    initialize: function (profile_id, testmode, locale) {
        if (!window.Nodelist && !window.NodeList.prototype.each && window.NodeList.prototype.forEach) {
            NodeList.prototype.each = NodeList.prototype.forEach;
        }

        try {
            this.mollie = Mollie(profile_id, {
                testMode: testmode,
                locale: locale
            });

            this.components.cardHolder = this.mollie.createComponent('cardHolder');
            this.components.cardNumber = this.mollie.createComponent('cardNumber');
            this.components.expiryDate = this.mollie.createComponent('expiryDate');
            this.components.verificationCode = this.mollie.createComponent('verificationCode');
        } catch (error) {
            console.error(error);
        }
    },

    getMollieToken: function() {
        if ($$('input:checked[name=payment[method]]')[0].value !== 'mollie_creditcard') {
            return this.parentSave();
        }

        this.mollie.createToken().then( function (result) {
            if (result.error) {
                alert(result.error.message);
                return false;
            }

            var tokenFields = $$('[name=cardToken]');
            if (result.token && tokenFields && tokenFields.length) {
                var tokenField = tokenFields.shift();
                tokenField.removeAttribute('disabled');
                tokenField.value = result.token;
            }

            this.parentSave();
        }.bind(this));
    },

    mount: function () {
        payment.addAfterInitFunction('mollie_components', function () {
            this.parentSave = payment.save.bind(payment);
            payment.save = this.getMollieToken.bind(this);
        }.bind(this));

        this.mountElement(this.components.cardHolder, '#card-holder');
        this.mountElement(this.components.cardNumber, '#card-number');
        this.mountElement(this.components.expiryDate, '#expiry-date');
        this.mountElement(this.components.verificationCode, '#verification-code');
    },

    mountElement: function (element, id) {
        element.mount(id);

        var errorElement = document.querySelector(id + '-error');
        element.addEventListener('change', function (event) {
            if (event.error && event.touched) {
                errorElement.textContent = event.error;
                errorElement.style.display = 'block';
            } else {
                errorElement.textContent = '';
                errorElement.style.display = 'none';
            }
        });
    }
};


text:
from __future__ import unicode_literals

from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion

class Migration(migrations.Migration):

    dependencies = [
        ('websqlrunner', '0002_remove_run_parallel'),
    ]

    operations = [
        migrations.AlterField(
            model_name='sqlscript',
            name='createdby',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL),
        ),
    ]