text:
package output

import (
	"context"
	"crypto/tls"
	"encoding/json"
	"fmt"
	"math"
	"math/rand"
	"strconv"
	"sync"
	"time"

	"github.com/Jeffail/benthos/v3/internal/batch/policy"
	"github.com/Jeffail/benthos/v3/internal/bloblang/field"
	"github.com/Jeffail/benthos/v3/internal/bloblang/mapping"
	"github.com/Jeffail/benthos/v3/internal/bloblang/query"
	"github.com/Jeffail/benthos/v3/internal/component"
	"github.com/Jeffail/benthos/v3/internal/component/metrics"
	"github.com/Jeffail/benthos/v3/internal/component/output"
	"github.com/Jeffail/benthos/v3/internal/docs"
	"github.com/Jeffail/benthos/v3/internal/interop"
	"github.com/Jeffail/benthos/v3/internal/log"
	"github.com/Jeffail/benthos/v3/internal/message"
	"github.com/Jeffail/benthos/v3/internal/old/util/retries"
	btls "github.com/Jeffail/benthos/v3/internal/tls"
	"github.com/gocql/gocql"
)

//------------------------------------------------------------------------------

func init() {
	Constructors[TypeCassandra] = TypeSpec{
		constructor: fromSimpleConstructor(func(conf Config, mgr interop.Manager, log log.Modular, stats metrics.Type) (output.Streamed, error) {
			c, err := newCassandraWriter(conf.Cassandra, mgr, log, stats)
			if err != nil {
				return nil, err
			}
			w, err := NewAsyncWriter(
				TypeCassandra, conf.Cassandra.MaxInFlight, c, log, stats,
			)
			if err != nil {
				return nil, err
			}
			return NewBatcherFromConfig(conf.Cassandra.Batching, w, mgr, log, stats)
		}),
		Status:  docs.StatusBeta,
		Batches: true,
		Async:   true,
		Summary: `
Runs a query against a Cassandra database for each message in order to insert data.`,
		Description: `
Query arguments can be set using [interpolation functions](/docs/configuration/interpolation#bloblang-queries) in the ` + "`args`" + ` field or by creating a bloblang array for the fields using the ` + "`args_mapping`" + ` field.

When populating timestamp columns the value must either be a string in ISO 8601 format (2006-01-02T15:04:05Z07:00), or an integer representing unix time in seconds.`,
		Examples: []docs.AnnotatedExample{
			{
				Title:   "Basic Inserts",
				Summary: "If we were to create a table with some basic columns with `CREATE TABLE foo.bar (id int primary key, content text, created_at timestamp);`, and were processing JSON documents of the form `{\"id\":\"342354354\",\"content\":\"hello world\",\"timestamp\":1605219406}`, we could populate our table with the following config:",
				Config: `
output:
  cassandra:
    addresses:
      - localhost:9042
    query: 'INSERT INTO foo.bar (id, content, created_at) VALUES (?, ?, ?)'
    args_mapping: |
      root = [
        this.id,
        this.content,
        this.timestamp
      ]
    batching:
      count: 500
`,
			},
			{
				Title:   "Insert JSON Documents",
				Summary: "The following example inserts JSON documents into the table `footable` of the keyspace `foospace` using INSERT JSON (https://cassandra.apache.org/doc/latest/cql/json.html#insert-json).",
				Config: `
output:
  cassandra:
    addresses:
      - localhost:9042
    query: 'INSERT INTO foospace.footable JSON ?'
    args_mapping: 'root = [ this ]'
    batching:
      count: 500
`,
			},
		},
		FieldSpecs: docs.FieldSpecs{
			docs.FieldString(
				"addresses",
				"A list of Cassandra nodes to connect to. Multiple comma separated addresses can be specified on a single line.",
				[]string{"localhost:9042"},
				[]string{"foo:9042", "bar:9042"},
				[]string{"foo:9042,bar:9042"},
			).Array(),
			btls.FieldSpec(),
			docs.FieldAdvanced(
				"password_authenticator",
				"An object containing the username and password.",
			).WithChildren(
				docs.FieldCommon("enabled", "Whether to use password authentication."),
				docs.FieldCommon("username", "A username."),
				docs.FieldCommon("password", "A password."),
			),
			docs.FieldAdvanced(
				"disable_initial_host_lookup",
				"If enabled the driver will not attempt to get host info from the system.peers table. This can speed up queries but will mean that data_centre, rack and token information will not be available.",
			),
			docs.FieldCommon("query", "A query to execute for each message."),
			docs.FieldBloblang(
				"args_mapping",
				"A [Bloblang mapping](/docs/guides/bloblang/about) that can be used to provide arguments to Cassandra queries. The result of the query must be an array containing a matching number of elements to the query arguments.").AtVersion("3.55.0"),
			docs.FieldAdvanced(
				"consistency",
				"The consistency level to use.",
			).HasOptions(
				"ANY", "ONE", "TWO", "THREE", "QUORUM", "ALL", "LOCAL_QUORUM", "EACH_QUORUM", "LOCAL_ONE",
			),
			docs.FieldAdvanced("max_retries", "The maximum number of retries before giving up on a request."),
			docs.FieldAdvanced("backoff", "Control time intervals between retry attempts.").WithChildren(
				docs.FieldAdvanced("initial_interval", "The initial period to wait between retry attempts."),
				docs.FieldAdvanced("max_interval", "The maximum period to wait between retry attempts."),
				docs.FieldDeprecated("max_elapsed_time"),
			),
			docs.FieldString("timeout", "The client connection timeout.").AtVersion("3.63.0"),
		}.Merge(docs.FieldSpecs{
			docs.FieldCommon("max_in_flight", "The maximum number of messages to have in flight at a given time. Increase this to improve throughput."),
			policy.FieldSpec(),
		}),
	}
}

//------------------------------------------------------------------------------

// PasswordAuthenticator contains the fields that will be used to authenticate with
// the Cassandra cluster.
type PasswordAuthenticator struct {
	Enabled  bool   `json:"enabled" yaml:"enabled"`
	Username string `json:"username" yaml:"username"`
	Password string `json:"password" yaml:"password"`
}

// CassandraConfig contains configuration fields for the Cassandra output type.
type CassandraConfig struct {
	Addresses                []string              `json:"addresses" yaml:"addresses"`
	TLS                      btls.Config           `json:"tls" yaml:"tls"`
	PasswordAuthenticator    PasswordAuthenticator `json:"password_authenticator" yaml:"password_authenticator"`
	DisableInitialHostLookup bool                  `json:"disable_initial_host_lookup" yaml:"disable_initial_host_lookup"`
	Query                    string                `json:"query" yaml:"query"`
	ArgsMapping              string                `json:"args_mapping" yaml:"args_mapping"`
	Consistency              string                `json:"consistency" yaml:"consistency"`
	Timeout                  string                `json:"timeout" yaml:"timeout"`
	// TODO: V4 Remove this and replace with explicit values.
	retries.Config `json:",inline" yaml:",inline"`
	MaxInFlight    int           `json:"max_in_flight" yaml:"max_in_flight"`
	Batching       policy.Config `json:"batching" yaml:"batching"`
}

// NewCassandraConfig creates a new CassandraConfig with default values.
func NewCassandraConfig() CassandraConfig {
	rConf := retries.NewConfig()
	rConf.MaxRetries = 3
	rConf.Backoff.InitialInterval = "1s"
	rConf.Backoff.MaxInterval = "5s"
	rConf.Backoff.MaxElapsedTime = ""

	return CassandraConfig{
		Addresses: []string{},
		TLS:       btls.NewConfig(),
		PasswordAuthenticator: PasswordAuthenticator{
			Enabled:  false,
			Username: "",
			Password: "",
		},
		DisableInitialHostLookup: false,
		Query:                    "",
		ArgsMapping:              "",
		Consistency:              gocql.Quorum.String(),
		Timeout:                  "600ms",
		Config:                   rConf,
		MaxInFlight:              1,
		Batching:                 policy.NewConfig(),
	}
}

type cassandraWriter struct {
	conf    CassandraConfig
	log     log.Modular
	stats   metrics.Type
	tlsConf *tls.Config

	backoffMin time.Duration
	backoffMax time.Duration

	session  *gocql.Session
	connLock sync.RWMutex

	args        []*field.Expression
	argsMapping *mapping.Executor
}

func newCassandraWriter(conf CassandraConfig, mgr interop.Manager, log log.Modular, stats metrics.Type) (*cassandraWriter, error) {
	c := cassandraWriter{
		log:   log,
		stats: stats,
		conf:  conf,
	}

	var err error
	if conf.TLS.Enabled {
		if c.tlsConf, err = conf.TLS.Get(); err != nil {
			return nil, err
		}
	}
	if c.backoffMin, err = time.ParseDuration(c.conf.Config.Backoff.InitialInterval); err != nil {
		return nil, fmt.Errorf("parsing backoff initial interval: %w", err)
	}
	if c.backoffMax, err = time.ParseDuration(c.conf.Config.Backoff.MaxInterval); err != nil {
		return nil, fmt.Errorf("parsing backoff max interval: %w", err)
	}
	if err = c.parseArgs(mgr); err != nil {
		return nil, fmt.Errorf("parsing args: %w", err)
	}

	return &c, nil
}

func (c *cassandraWriter) parseArgs(mgr interop.Manager) error {
	if c.conf.ArgsMapping != "" {
		var err error
		if c.argsMapping, err = mgr.BloblEnvironment().NewMapping(c.conf.ArgsMapping); err != nil {
			return fmt.Errorf("parsing args_mapping: %w", err)
		}
	}
	return nil
}

// ConnectWithContext establishes a connection to Cassandra.
func (c *cassandraWriter) ConnectWithContext(ctx context.Context) error {
	c.connLock.Lock()
	defer c.connLock.Unlock()
	if c.session != nil {
		return nil
	}

	var err error
	conn := gocql.NewCluster(c.conf.Addresses...)
	if c.tlsConf != nil {
		conn.SslOpts = &gocql.SslOptions{
			Config: c.tlsConf,
			CaPath: c.conf.TLS.RootCAsFile,
		}
		conn.DisableInitialHostLookup = c.conf.TLS.InsecureSkipVerify
	}
	if c.conf.PasswordAuthenticator.Enabled {
		conn.Authenticator = gocql.PasswordAuthenticator{
			Username: c.conf.PasswordAuthenticator.Username,
			Password: c.conf.PasswordAuthenticator.Password,
		}
	}
	conn.DisableInitialHostLookup = c.conf.DisableInitialHostLookup
	if conn.Consistency, err = gocql.ParseConsistencyWrapper(c.conf.Consistency); err != nil {
		return fmt.Errorf("parsing consistency: %w", err)
	}

	conn.RetryPolicy = &decorator{
		NumRetries: int(c.conf.Config.MaxRetries),
		Min:        c.backoffMin,
		Max:        c.backoffMax,
	}
	if tout := c.conf.Timeout; len(tout) > 0 {
		var err error
		if conn.Timeout, err = time.ParseDuration(tout); err != nil {
			return fmt.Errorf("failed to parse timeout string: %v", err)
		}
	}
	session, err := conn.CreateSession()
	if err != nil {
		return fmt.Errorf("creating Cassandra session: %w", err)
	}

	c.session = session
	c.log.Infof("Sending messages to Cassandra: %v\n", c.conf.Addresses)
	return nil
}

// WriteWithContext writes a message to Cassandra.
func (c *cassandraWriter) WriteWithContext(ctx context.Context, msg *message.Batch) error {
	c.connLock.RLock()
	session := c.session
	c.connLock.RUnlock()

	if c.session == nil {
		return component.ErrNotConnected
	}

	if msg.Len() == 1 {
		return c.writeRow(session, msg)
	}
	return c.writeBatch(session, msg)
}

func (c *cassandraWriter) writeRow(session *gocql.Session, msg *message.Batch) error {
	values, err := c.mapArgs(msg, 0)
	if err != nil {
		return fmt.Errorf("parsing args: %w", err)
	}

	if err := session.Query(c.conf.Query, values...).Exec(); err != nil {
		return err
	}
	return nil
}

func (c *cassandraWriter) writeBatch(session *gocql.Session, msg *message.Batch) error {
	batch := session.NewBatch(gocql.UnloggedBatch)

	if err := msg.Iter(func(i int, p *message.Part) error {
		values, err := c.mapArgs(msg, i)
		if err != nil {
			return fmt.Errorf("parsing args for part: %d: %w", i, err)
		}
		batch.Query(c.conf.Query, values...)
		return nil
	}); err != nil {
		return err
	}

	err := session.ExecuteBatch(batch)
	if err != nil {
		return err
	}
	return nil
}

func (c *cassandraWriter) mapArgs(msg *message.Batch, index int) ([]interface{}, error) {
	if c.argsMapping != nil {
		// We've got an "args_mapping" field, extract values from there.
		part, err := c.argsMapping.MapPart(index, msg)
		if err != nil {
			return nil, fmt.Errorf("executing bloblang mapping: %w", err)
		}

		jraw, err := part.JSON()
		if err != nil {
			return nil, fmt.Errorf("parsing bloblang mapping result as json: %w", err)
		}

		j, ok := jraw.([]interface{})
		if !ok {
			return nil, fmt.Errorf("expected bloblang mapping result to be []interface{} but was %T", jraw)
		}

		for i, v := range j {
			j[i] = genericValue{v: v}
		}
		return j, nil
	}

	// If we've been given the "args" field, extract values from there.
	if len(c.args) > 0 {
		values := make([]interface{}, 0, len(c.args))
		for _, arg := range c.args {
			values = append(values, stringValue(arg.String(index, msg)))
		}
		return values, nil
	}

	return nil, nil
}

// CloseAsync shuts down the Cassandra output and stops processing messages.
func (c *cassandraWriter) CloseAsync() {
	go func() {
		c.connLock.Lock()
		if c.session != nil {
			c.session.Close()
			c.session = nil
		}
		c.connLock.Unlock()
	}()
}

// WaitForClose blocks until the Cassandra output has closed down.
func (c *cassandraWriter) WaitForClose(timeout time.Duration) error {
	return nil
}

type decorator struct {
	NumRetries int
	Min, Max   time.Duration
}

func (d *decorator) Attempt(q gocql.RetryableQuery) bool {
	if q.Attempts() > d.NumRetries {
		return false
	}
	time.Sleep(getExponentialTime(d.Min, d.Max, q.Attempts()))
	return true
}

func getExponentialTime(min, max time.Duration, attempts int) time.Duration {
	minFloat := float64(min)
	napDuration := minFloat * math.Pow(2, float64(attempts-1))

	// Add some jitter
	napDuration += rand.Float64()*minFloat - (minFloat / 2)
	if napDuration > float64(max) {
		return max
	}
	return time.Duration(napDuration)
}

func (d *decorator) GetRetryType(err error) gocql.RetryType {
	switch t := err.(type) {
	// not enough replica alive to perform query with required consistency
	case *gocql.RequestErrUnavailable:
		if t.Alive > 0 {
			return gocql.RetryNextHost
		}
		return gocql.Retry
	// write timeout - uncertain whetever write was succesful or not
	case *gocql.RequestErrWriteTimeout:
		if t.Received > 0 {
			return gocql.Ignore
		}
		return gocql.Retry
	default:
		return gocql.Rethrow
	}
}

func formatCassandraInt64(x int64) []byte {
	return []byte{byte(x >> 56), byte(x >> 48), byte(x >> 40), byte(x >> 32),
		byte(x >> 24), byte(x >> 16), byte(x >> 8), byte(x)}
}

func formatCassandraInt32(x int32) []byte {
	return []byte{byte(x >> 24), byte(x >> 16), byte(x >> 8), byte(x)}
}

type stringValue string

// All of our argument values are string types due to interpolation. However,
// gocql performs type checking and unfortunately does not like timestamp and
// some other values as strings:
// https://github.com/gocql/gocql/blob/5913df4d474e0b2492a129d17bbb3c04537a15cd/marshal.go#L1160
//
// In order to work around this we manually marshal some types.
func (s stringValue) MarshalCQL(info gocql.TypeInfo) ([]byte, error) {
	switch info.Type() {
	case gocql.TypeTimestamp:
		t, err := time.Parse(time.RFC3339Nano, string(s))
		if err == nil {
			if t.IsZero() {
				return []byte{}, nil
			}
			x := t.UTC().Unix()*1e3 + int64(t.UTC().Nanosecond()/1e6)
			return formatCassandraInt64(x), nil
		}
		x, err := strconv.ParseInt(string(s), 10, 64)
		if err != nil {
			return nil, fmt.Errorf("failed to parse time value '%v': expected either an ISO 8601 string or unix epoch in seconds", s)
		}
		return formatCassandraInt64(x * 1e3), nil
	case gocql.TypeTime:
		x, err := strconv.ParseInt(string(s), 10, 64)
		if err != nil {
			return nil, fmt.Errorf("failed to parse time value '%v': expected milliseconds", s)
		}
		return formatCassandraInt64(x), nil
	case gocql.TypeBoolean:
		if s == "true" {
			return []byte{1}, nil
		} else if s == "false" {
			return []byte{0}, nil
		}
	case gocql.TypeFloat:
		f, err := strconv.ParseFloat(string(s), 32)
		if err != nil {
			return nil, err
		}
		return formatCassandraInt32(int32(math.Float32bits(float32(f)))), nil
	case gocql.TypeDouble:
		f, err := strconv.ParseFloat(string(s), 64)
		if err != nil {
			return nil, err
		}
		return formatCassandraInt64(int64(math.Float64bits(f))), nil
	}
	return gocql.Marshal(info, string(s))
}

type genericValue struct {
	v interface{}
}

// We get typed values out of mappings. However, gocql performs type checking
// and unfortunately does not like timestamp and some other values as strings:
// https://github.com/gocql/gocql/blob/5913df4d474e0b2492a129d17bbb3c04537a15cd/marshal.go#L1160
// it's also very strict on numerical types, so we need to do some magic here.
func (g genericValue) MarshalCQL(info gocql.TypeInfo) ([]byte, error) {
	switch info.Type() {
	case gocql.TypeTimestamp:
		t, err := query.IGetTimestamp(g.v)
		if err != nil {
			return nil, err
		}
		return gocql.Marshal(info, t)
	case gocql.TypeDouble:
		f, err := query.IGetNumber(g.v)
		if err != nil {
			return nil, err
		}
		return gocql.Marshal(info, f)
	case gocql.TypeFloat:
		f, err := query.IGetFloat32(g.v)
		if err != nil {
			return nil, err
		}
		return gocql.Marshal(info, f)
	case gocql.TypeVarchar:
		return gocql.Marshal(info, query.IToString(g.v))
	}
	if _, isJSONNum := g.v.(json.Number); isJSONNum {
		i, err := query.IGetInt(g.v)
		if err != nil {
			return nil, err
		}
		return gocql.Marshal(info, i)
	}
	return gocql.Marshal(info, g.v)
}


text:
require 'beaker-rspec'

# Install Puppet
unless ENV['RS_PROVISION'] == 'no'
  # This will install the latest available package on el and deb based
  # systems fail on windows and osx, and install via gem on other *nixes
  foss_opts = { :default_action => 'gem_install' }

  if default.is_pe?; then install_pe; else install_puppet( foss_opts ); end

  hosts.each do |host|
    on host, "mkdir -p #{host['distmoduledir']}"
  end
end

UNSUPPORTED_PLATFORMS = ['AIX','Solaris']

RSpec.configure do |c|
  # Project root
  proj_root = File.expand_path(File.join(File.dirname(__FILE__), '..'))

  # Readable test descriptions
  c.formatter = :documentation

  # Configure all nodes in nodeset
  c.before :suite do
    # Install module and dependencies
    hosts.each do |host|
      copy_module_to(host, :source => proj_root, :module_name => 'nodejs')
      shell("/bin/touch #{default['puppetpath']}/hiera.yaml")
      on host, puppet('module install puppetlabs-apt --version 1.8.0'), { :acceptable_exit_codes => [0,1] }
      on host, puppet('module install gentoo-portage --version 2.0.1'), { :acceptable_exit_codes => [0,1] }
      on host, puppet('module install chocolatey-chocolatey --version 0.5.2'), { :acceptable_exit_codes => [0,1] }
      on host, puppet('module install stahnma-epel --version 1.0.0'), { :acceptable_exit_codes => [0,1] }
      on host, puppet('module install treydock-gpg_key --version 0.0.3'), { :acceptable_exit_codes => [0,1] }
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
#include <aws/core/client/AWSError.h>
#include <aws/comprehend/ComprehendErrorMarshaller.h>
#include <aws/comprehend/ComprehendErrors.h>

using namespace Aws::Client;
using namespace Aws::Comprehend;

AWSError<CoreErrors> ComprehendErrorMarshaller::FindErrorByName(const char* errorName) const
{
  AWSError<CoreErrors> error = ComprehendErrorMapper::GetErrorForName(errorName);
  if(error.GetErrorType() != CoreErrors::UNKNOWN)
  {
    return error;
  }

  return AWSErrorMarshaller::FindErrorByName(errorName);
}


text:
namespace Microsoft.Azure.Management.Kusto
{
    using Microsoft.Rest;
    using Microsoft.Rest.Azure;
    using Models;
    using System.Collections;
    using System.Collections.Generic;
    using System.Threading;
    using System.Threading.Tasks;

    /// <summary>
    /// PrivateEndpointConnectionsOperations operations.
    /// </summary>
    public partial interface IPrivateEndpointConnectionsOperations
    {
        /// <summary>
        /// Returns the list of private endpoint connections.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// The name of the resource group containing the Kusto cluster.
        /// </param>
        /// <param name='clusterName'>
        /// The name of the Kusto cluster.
        /// </param>
        /// <param name='customHeaders'>
        /// The headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="Microsoft.Rest.Azure.CloudException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="Microsoft.Rest.SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="Microsoft.Rest.ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        Task<AzureOperationResponse<IEnumerable<PrivateEndpointConnection>>> ListWithHttpMessagesAsync(string resourceGroupName, string clusterName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
        /// <summary>
        /// Gets a private endpoint connection.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// The name of the resource group containing the Kusto cluster.
        /// </param>
        /// <param name='clusterName'>
        /// The name of the Kusto cluster.
        /// </param>
        /// <param name='privateEndpointConnectionName'>
        /// The name of the private endpoint connection.
        /// </param>
        /// <param name='customHeaders'>
        /// The headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="Microsoft.Rest.Azure.CloudException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="Microsoft.Rest.SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="Microsoft.Rest.ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        Task<AzureOperationResponse<PrivateEndpointConnection>> GetWithHttpMessagesAsync(string resourceGroupName, string clusterName, string privateEndpointConnectionName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
        /// <summary>
        /// Approve or reject a private endpoint connection with a given name.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// The name of the resource group containing the Kusto cluster.
        /// </param>
        /// <param name='clusterName'>
        /// The name of the Kusto cluster.
        /// </param>
        /// <param name='privateEndpointConnectionName'>
        /// The name of the private endpoint connection.
        /// </param>
        /// <param name='parameters'>
        /// </param>
        /// <param name='customHeaders'>
        /// The headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="Microsoft.Rest.Azure.CloudException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="Microsoft.Rest.SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="Microsoft.Rest.ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        Task<AzureOperationResponse<PrivateEndpointConnection>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string clusterName, string privateEndpointConnectionName, PrivateEndpointConnection parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
        /// <summary>
        /// Deletes a private endpoint connection with a given name.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// The name of the resource group containing the Kusto cluster.
        /// </param>
        /// <param name='clusterName'>
        /// The name of the Kusto cluster.
        /// </param>
        /// <param name='privateEndpointConnectionName'>
        /// The name of the private endpoint connection.
        /// </param>
        /// <param name='customHeaders'>
        /// The headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="Microsoft.Rest.Azure.CloudException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="Microsoft.Rest.ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string clusterName, string privateEndpointConnectionName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
        /// <summary>
        /// Approve or reject a private endpoint connection with a given name.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// The name of the resource group containing the Kusto cluster.
        /// </param>
        /// <param name='clusterName'>
        /// The name of the Kusto cluster.
        /// </param>
        /// <param name='privateEndpointConnectionName'>
        /// The name of the private endpoint connection.
        /// </param>
        /// <param name='parameters'>
        /// </param>
        /// <param name='customHeaders'>
        /// The headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="Microsoft.Rest.Azure.CloudException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="Microsoft.Rest.SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="Microsoft.Rest.ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        Task<AzureOperationResponse<PrivateEndpointConnection>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string clusterName, string privateEndpointConnectionName, PrivateEndpointConnection parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
        /// <summary>
        /// Deletes a private endpoint connection with a given name.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// The name of the resource group containing the Kusto cluster.
        /// </param>
        /// <param name='clusterName'>
        /// The name of the Kusto cluster.
        /// </param>
        /// <param name='privateEndpointConnectionName'>
        /// The name of the private endpoint connection.
        /// </param>
        /// <param name='customHeaders'>
        /// The headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="Microsoft.Rest.Azure.CloudException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="Microsoft.Rest.ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string clusterName, string privateEndpointConnectionName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
    }
}


text:
describe Facter::Resolvers::Freebsd::DmiBios do
  describe '#resolve' do
    subject(:resolver) { Facter::Resolvers::Freebsd::DmiBios }

    let(:bios_date) { '12/12/2018' }
    let(:bios_vendor) { 'Phoenix Technologies LTD' }
    let(:bios_version) { '6.00' }
    let(:product_name) { 'VMware Virtual Platform' }
    let(:product_serial) { 'VMware-42 1a 02 ea e6 27 76 b8-a1 23 a7 8a d3 12 ee cf' }
    let(:product_uuid) { 'ea021a42-27e6-b876-a123-a78ad312eecf' }
    let(:sys_vendor) { 'VMware, Inc.' }

    before do
      allow(Facter::Freebsd::FfiHelper).to receive(:kenv)
        .with(:get, 'smbios.bios.reldate')
        .and_return(bios_date)
      allow(Facter::Freebsd::FfiHelper).to receive(:kenv)
        .with(:get, 'smbios.bios.vendor')
        .and_return(bios_vendor)
      allow(Facter::Freebsd::FfiHelper).to receive(:kenv)
        .with(:get, 'smbios.bios.version')
        .and_return(bios_version)
      allow(Facter::Freebsd::FfiHelper).to receive(:kenv)
        .with(:get, 'smbios.system.product')
        .and_return(product_name)
      allow(Facter::Freebsd::FfiHelper).to receive(:kenv)
        .with(:get, 'smbios.system.serial')
        .and_return(product_serial)
      allow(Facter::Freebsd::FfiHelper).to receive(:kenv)
        .with(:get, 'smbios.system.uuid')
        .and_return(product_uuid)
      allow(Facter::Freebsd::FfiHelper).to receive(:kenv)
        .with(:get, 'smbios.system.maker')
        .and_return(sys_vendor)
    end

    after do
      Facter::Resolvers::Freebsd::DmiBios.invalidate_cache
    end

    context 'when bios_date is available' do
      it 'returns bios_release_date' do
        expect(resolver.resolve(:bios_date)).to eq(bios_date)
      end
    end

    context 'when bios_vendor is available' do
      it 'returns bios_release_date' do
        expect(resolver.resolve(:bios_vendor)).to eq(bios_vendor)
      end
    end

    context 'when bios_version is available' do
      it 'returns bios_version' do
        expect(resolver.resolve(:bios_version)).to eq(bios_version)
      end
    end

    context 'when sys_vendor is available' do
      it ' returns sys_vendor' do
        expect(resolver.resolve(:sys_vendor)).to eq(sys_vendor)
      end
    end

    context 'when product_name is available' do
      it 'returns product_name' do
        expect(resolver.resolve(:product_name)).to eq(product_name)
      end
    end

    context 'when product_serial is available' do
      it 'returns product_serial_number' do
        expect(resolver.resolve(:product_serial)).to eq(product_serial)
      end
    end

    context 'when product_uuid is available' do
      it 'returns product_uuid' do
        expect(resolver.resolve(:product_uuid)).to eq(product_uuid)
      end
    end
  end
end


text:
<?php

namespace PHPExiftool\Driver\Tag\PSP;

use JMS\Serializer\Annotation\ExclusionPolicy;
use PHPExiftool\Driver\AbstractTag;

/**
 * @ExclusionPolicy("all")
 */
class ResolutionUnit extends AbstractTag
{

    protected $Id = 16;

    protected $Name = 'ResolutionUnit';

    protected $FullName = 'PSP::Image';

    protected $GroupName = 'PSP';

    protected $g0 = 'PSP';

    protected $g1 = 'PSP';

    protected $g2 = 'Image';

    protected $Type = 'int8u';

    protected $Writable = false;

    protected $Description = 'Resolution Unit';

    protected $Values = array(
        0 => array(
            'Id' => 0,
            'Label' => 'None',
        ),
        1 => array(
            'Id' => 1,
            'Label' => 'inches',
        ),
        2 => array(
            'Id' => 2,
            'Label' => 'cm',
        ),
    );

}


text:
Tree of Life Media Manager

Instructions

Images

Please upload only JPEG, GIF, or PNG files. Ideally your
                        master image should be around 800 pixels wide or high
                        (example).
                        See Illustrations for
                        Tree of Life Pages for more information.

Documents

Select this media type for uploading text files, PDF, Word, Excel, PowerPoint documents, etc.

Size limit

 You may upload media files up to 5 megabytes.
                        Most sound and movie files under one minute will fit this
                        requirement. If you would like to contribute a larger file, contact  for instructions.

Upload a new media file

Edit data for one of my media files
                in the ToL database

Delete one of my media files from
                the ToL database

Update my registration information

Upload a new media file

                <form jwcid="@UploadNewMediaForm" noInstructions="ognl:true" inContainingForm="ognl:true" editedObjectId="ognl:node.nodeId" nodeId="ognl:node.nodeId"/>

Edit data for one of my media files in the ToL database

				<form jwcid="@ImageSearch" searchPageName="ognl:pageName" callbackType="ognl:@org.tolweb.tapestry.ImageSearchResults@EDIT_IMAGE_CALLBACK"  groupName="ognl:nodeName"
                instructions="ognl:instructions"
                	linkString="edit"
					buttonText="Find Media" editedObjectId="ognl:node.nodeId"
                	wrapperType="ognl:@org.tolweb.tapestry.AbstractWrappablePage@NEW_FORM_WRAPPER"/>

Note: You will only be able to edit data for media files that you have contributed yourself
				or for which you own the copyright.

Delete one of my media files from the ToL database

				<form jwcid="@ImageSearch" searchPageName="ognl:pageName" callbackType="ognl:@org.tolweb.tapestry.ImageSearchResults@DELETE_IMAGE_CALLBACK" groupName="ognl:nodeName"
	            instructions="Click the 'delete' link to delete that image" linkString="delete"
	            buttonText="Find Media" editedObjectId="ognl:node.nodeId"
                wrapperType="ognl:@org.tolweb.tapestry.AbstractWrappablePage@NEW_FORM_WRAPPER"/>


text:
<product name="IntelliJ IDEA">
    IU
    IC

    <channel id="maiaEAP" name="IntelliJ IDEA 9 updates" status="release" majorVersion="9"
             url="http://www.jetbrains.com/idea/whatsnew"
             feedback="http://youtrack.jetbrains.net">
        <build number="95.627" version="9.0.4">
            <message>IntelliJ IDEA 9.0.4 is available.
                Please visit http://www.jetbrains.com/idea to learn more and download it.
            </message>
            <patch from="95.429" size="2"/>
        </build>
    </channel>

    <channel id="idea90" name="IntelliJ IDEA 9 updates" status="release" majorVersion="9"
             url="http://www.jetbrains.com/idea/whatsnew">
        <build number="95.627" version="9.0.4">
            <message>IntelliJ IDEA 9.0.4 is available.
                Please visit http://www.jetbrains.com/idea to learn more and download it.
            </message>
            <patch from="95.429" size="2"/>
        </build>
    </channel>

    <channel id="IDEA10EAP" name="IntelliJ IDEA X EAP" status="release" majorVersion="10"
             url="http://confluence.jetbrains.net/display/IDEADEV/IDEA+X+EAP">
        <build number="98.520" version="10">
            <message>IntelliJ IDEA X RC is available.
                Please visit http://confluence.jetbrains.net/display/IDEADEV/IDEA+X+EAP to learn more and download it.
            </message>

        </build>
    </channel>
</product>


text:
<?php

namespace spec\Sylius\Bundle\ResourceBundle\DependencyInjection\Driver\Exception;

use PhpSpec\ObjectBehavior;

/**
 * @author Arnaud Langlade <aRn0D.dev@gmail.com>
 */
class UnknownDriverExceptionSpec extends ObjectBehavior
{
    function let()
    {
        $this->beConstructedWith('driver');
    }

    function it_is_initializable()
    {
        $this->shouldHaveType('Sylius\Bundle\ResourceBundle\DependencyInjection\Driver\Exception\UnknownDriverException');
    }

    function it_extends_exception()
    {
        $this->shouldHaveType(\Exception::class);
    }

    function it_has_a_message()
    {
        $this->getMessage()->shouldReturn('Unknown driver "driver".');
    }
}


text:
import sys,os
import struct
import argparse
from xml.dom import minidom

def cascade_info(path):
    #parse xml file
    xmldoc = minidom.parse(path)

    trees = xmldoc.getElementsByTagName('trees')
    n_stages = len(trees)

    # read stages
    stages = [len(t.childNodes)/2 for t in trees][0:n_stages]
    stage_threshold = xmldoc.getElementsByTagName('stage_threshold')[0:n_stages]

    # total number of features
    n_features = sum(stages)
    # read features threshold
    threshold = xmldoc.getElementsByTagName('threshold')[0:n_features]
    #theres one of each per feature
    alpha1 = xmldoc.getElementsByTagName('left_val')[0:n_features]
    alpha2 = xmldoc.getElementsByTagName('right_val')[0:n_features]

    #read rectangles
    feature = xmldoc.getElementsByTagName('rects')[0:n_features]

    #read cascade size
    size = (map(int, xmldoc.getElementsByTagName('size')[0].childNodes[0].nodeValue.split()))
    fout = open(os.path.basename(path).split('.')[0]+".cascade", "w")

    n_rectangles = 0
    for f in feature:
        rects = f.getElementsByTagName('_')
        n_rectangles = n_rectangles + len(rects)

    #print some cascade info
    print("size:%dx%d"%(size[0], size[1]))
    print("stages:%d"%len(stages))
    print("features:%d"%n_features)
    print("rectangles:%d"%n_rectangles)

def cascade_binary(path, n_stages, name):
    #parse xml file
    xmldoc = minidom.parse(path)

    trees = xmldoc.getElementsByTagName('trees')
    max_stages = len(trees)
    if n_stages > max_stages:
        raise Exception("The max number of stages is: %d"%(max_stages))

    if n_stages == 0:
        n_stages = max_stages

    # read stages
    stages = [len(t.childNodes)/2 for t in trees][0:n_stages]
    stage_threshold = xmldoc.getElementsByTagName('stage_threshold')[0:n_stages]

    # total number of features
    n_features = sum(stages)

    # read features threshold
    threshold = xmldoc.getElementsByTagName('threshold')[0:n_features]

    # theres one of each per feature
    alpha1 = xmldoc.getElementsByTagName('left_val')[0:n_features]
    alpha2 = xmldoc.getElementsByTagName('right_val')[0:n_features]

    # read rectangles
    feature = xmldoc.getElementsByTagName('rects')[0:n_features]

    # read cascade size
    size = (map(int, xmldoc.getElementsByTagName('size')[0].childNodes[0].nodeValue.split()))

    # open output file with the specified name or xml file name
    if not name:
        name = os.path.basename(path).split('.')[0]
    fout = open(name+".cascade", "w")

    n_rectangles = 0
    for f in feature:
        rects = f.getElementsByTagName('_')
        n_rectangles = n_rectangles + len(rects)

    # write detection window size
    fout.write(struct.pack('i', size[0]))
    fout.write(struct.pack('i', size[1]))

    # write num stages
    fout.write(struct.pack('i', len(stages)))

    # write num feat in stages
    for s in stages:
        fout.write(struct.pack('B', s)) # uint8_t

    # write stages thresholds
    for t in stage_threshold:
        fout.write(struct.pack('h', int(float(t.childNodes[0].nodeValue)*256))) #int16_t

    # write features threshold 1 per feature
    for t in threshold:
        fout.write(struct.pack('h', int(float(t.childNodes[0].nodeValue)*4096))) #int16_t

    # write alpha1 1 per feature
    for a in alpha1:
        fout.write(struct.pack('h', int(float(a.childNodes[0].nodeValue)*256))) #int16_t

    # write alpha2 1 per feature
    for a in alpha2:
        fout.write(struct.pack('h', int(float(a.childNodes[0].nodeValue)*256))) #int16_t

    # write num_rects per feature
    for f in feature:
        rects = f.getElementsByTagName('_')
        fout.write(struct.pack('B', len(rects))) # uint8_t

    # write rects weights 1 per rectangle
    for f in feature:
        rects = f.getElementsByTagName('_')
        for r in rects:
            l = map(int, r.childNodes[0].nodeValue[:-1].split())
            fout.write(struct.pack('b', l[4])) #int8_t NOTE: multiply by 4096

    # write rects
    for f in feature:
        rects = f.getElementsByTagName('_')
        for r in rects:
            l = map(int, r.childNodes[0].nodeValue[:-1].split())
            fout.write(struct.pack('BBBB',l[0], l[1], l[2], l[3])) #uint8_t

    # print cascade info
    print("size:%dx%d"%(size[0], size[1]))
    print("stages:%d"%len(stages))
    print("features:%d"%n_features)
    print("rectangles:%d"%n_rectangles)
    print("binary cascade generated")

def cascade_header(path, n_stages, name):
    #parse xml file
    xmldoc = minidom.parse(path)

    trees = xmldoc.getElementsByTagName('trees')
    max_stages = len(trees)
    if n_stages > max_stages:
        raise Exception("The max number of stages is: %d"%(max_stages))

    if n_stages == 0:
        n_stages = max_stages

    # read stages
    stages = [len(t.childNodes)/2 for t in trees][0:n_stages]
    stage_threshold = xmldoc.getElementsByTagName('stage_threshold')[0:n_stages]

    # total number of features
    n_features = sum(stages)

    # read features threshold
    threshold = xmldoc.getElementsByTagName('threshold')[0:n_features]

    # theres one of each per feature
    alpha1 = xmldoc.getElementsByTagName('left_val')[0:n_features]
    alpha2 = xmldoc.getElementsByTagName('right_val')[0:n_features]

    # read rectangles
    feature = xmldoc.getElementsByTagName('rects')[0:n_features]

    # read cascade size
    size = (map(int, xmldoc.getElementsByTagName('size')[0].childNodes[0].nodeValue.split()))

    # open output file with the specified name or xml file name
    if not name:
        name = os.path.basename(path).split('.')[0]
    fout = open(name+".h", "w")

    n_rectangles = 0
    for f in feature:
        rects = f.getElementsByTagName('_')
        n_rectangles = n_rectangles + len(rects)

    # write detection window size
    fout.write("const int %s_window_w=%d;\n" %( name, size[0]))
    fout.write("const int %s_window_h=%d;\n" %(name, size[1]))

    # write num stages
    fout.write("const int %s_n_stages=%d;\n" %(name, len(stages)))

    # write num feat in stages
    fout.write("const uint8_t %s_stages_array[]={%s};\n"
            %(name, ", ".join(str(x) for x in stages)))

    # write stages thresholds
    fout.write("const int16_t %s_stages_thresh_array[]={%s};\n"
            %(name, ", ".join(str(int(float(t.childNodes[0].nodeValue)*256)) for t in stage_threshold)))

    # write features threshold 1 per feature
    fout.write("const int16_t %s_tree_thresh_array[]={%s};\n"
            %(name, ", ".join(str(int(float(t.childNodes[0].nodeValue)*4096)) for t in threshold)))

    # write alpha1 1 per feature
    fout.write("const int16_t %s_alpha1_array[]={%s};\n"
            %(name, ", ".join(str(int(float(t.childNodes[0].nodeValue)*256)) for t in alpha1)))

    # write alpha2 1 per feature
    fout.write("const int16_t %s_alpha2_array[]={%s};\n"
            %(name, ", ".join(str(int(float(t.childNodes[0].nodeValue)*256)) for t in alpha2)))

    # write num_rects per feature
    fout.write("const int8_t %s_num_rectangles_array[]={%s};\n"
            %(name, ", ".join(str(len(f.getElementsByTagName('_'))) for f in feature)))

    # write rects weights 1 per rectangle
    rect_weights = lambda rects:", ".join(r.childNodes[0].nodeValue[:-1].split()[4] for r in rects)
    fout.write("const int8_t %s_weights_array[]={%s};\n"
            %(name, ", ".join(rect_weights(f.getElementsByTagName('_')) for f in feature)))

    # write rects
    rect = lambda rects:", ".join(", ".join(r.childNodes[0].nodeValue.split()[:-1]) for r in rects)
    fout.write("const int8_t %s_rectangles_array[]={%s};\n"
            %(name, ", ".join(rect(f.getElementsByTagName('_')) for f in feature)))

    # print cascade info
    print("size:%dx%d"%(size[0], size[1]))
    print("stages:%d"%len(stages))
    print("features:%d"%n_features)
    print("rectangles:%d"%n_rectangles)
    print("C header cascade generated")

def main():
    # CMD args parser
    parser = argparse.ArgumentParser(description='haar cascade generator')
    parser.add_argument("-i", "--info",     action = "store_true",  help = "print cascade info and exit")
    parser.add_argument("-n", "--name",     action = "store",       help = "set cascade name", default = "")
    parser.add_argument("-s", "--stages",   action = "store",       help = "set the maximum number of stages", type = int, default=0)
    parser.add_argument("-c", "--header",   action = "store_true",  help = "generate a C header")
    parser.add_argument("file", action = "store", help = "OpenCV xml cascade file path")

    # Parse CMD args
    args = parser.parse_args()

    if args.info:
        # print cascade info and exit
        cascade_info(args.file)
        return

    if args.header:
        # generate a C header from the xml cascade
        cascade_header(args.file, args.stages, args.name)
        return

    # generate a binary cascade from the xml cascade
    cascade_binary(args.file, args.stages, args.name)

if __name__ == '__main__':
    main()


text:
#include "drv_mic.h"
#include "fsl_common.h"
#include "fsl_iocon.h"
#include "fsl_dmic.h"
#include "fsl_dma.h"
#include "fsl_dmic_dma.h"

struct mic_device
{
    dma_handle_t dma_handle;
    dmic_dma_handle_t dmic_dma_handle;
    struct rt_audio_device audio;
    struct rt_audio_configure config;
    rt_uint8_t *rx_fifo;
};

#define DMAREQ_DMIC0 16U
#define DMAREQ_DMIC1 17U
#define DMAREQ_CHANNEL DMAREQ_DMIC0
#define DMIC_CHANNEL kDMIC_Channel0
#define DMIC_CHANNEL_ENABLE DMIC_CHANEN_EN_CH0(1)
#define FIFO_DEPTH 15U

#define RX_DMA_FIFO_SIZE (2048)

struct mic_device mic_dev;

void dmic_dma_transfer_callback(DMIC_Type *base,
                                dmic_dma_handle_t *handle,
                                status_t status,
                                void *userData)
{
    struct mic_device *mic_dev = (struct mic_device *)userData;
    rt_audio_rx_done(&mic_dev->audio, &mic_dev->rx_fifo[0], RX_DMA_FIFO_SIZE);
    dmic_transfer_t dmic_transfer;
    dmic_transfer.data = (uint16_t *)&mic_dev->rx_fifo[0];
    dmic_transfer.dataSize = RX_DMA_FIFO_SIZE / 2;
    DMIC_TransferReceiveDMA(DMIC0, &mic_dev->dmic_dma_handle, &dmic_transfer, kDMIC_Channel0);
}

rt_err_t mic_device_init(struct rt_audio_device *audio)
{
    dmic_channel_config_t dmic_channel_cfg;

    CLOCK_EnableClock(kCLOCK_Iocon);
    CLOCK_EnableClock(kCLOCK_InputMux);
    CLOCK_EnableClock(kCLOCK_Gpio0);

    IOCON_PinMuxSet(IOCON, 1, 16, IOCON_FUNC1 | IOCON_DIGITAL_EN);
    IOCON_PinMuxSet(IOCON, 1, 15, IOCON_FUNC1 | IOCON_DIGITAL_EN);

    CLOCK_AttachClk(kFRO12M_to_DMIC);
    CLOCK_SetClkDiv(kCLOCK_DivDmicClk, 14, false);

    dmic_channel_cfg.divhfclk = kDMIC_PdmDiv1;
    dmic_channel_cfg.osr = 25U;
    dmic_channel_cfg.gainshft = 2U;
    dmic_channel_cfg.preac2coef = kDMIC_CompValueZero;
    dmic_channel_cfg.preac4coef = kDMIC_CompValueZero;
    dmic_channel_cfg.dc_cut_level = kDMIC_DcCut155;
    dmic_channel_cfg.post_dc_gain_reduce = 1;
    dmic_channel_cfg.saturate16bit = 1U;
    dmic_channel_cfg.sample_rate = kDMIC_PhyFullSpeed;
    DMIC_Init(DMIC0);

    DMIC_ConfigIO(DMIC0, kDMIC_PdmDual);
    DMIC_Use2fs(DMIC0, true);
    DMIC_SetOperationMode(DMIC0, kDMIC_OperationModeDma);
    DMIC_ConfigChannel(DMIC0, DMIC_CHANNEL, kDMIC_Left, &dmic_channel_cfg);

    DMIC_FifoChannel(DMIC0, DMIC_CHANNEL, FIFO_DEPTH, true, true);

    DMIC_EnableChannnel(DMIC0, DMIC_CHANNEL_ENABLE);

    DMA_EnableChannel(DMA0, DMAREQ_CHANNEL);

    /* Request dma channels from DMA manager. */
    DMA_CreateHandle(&mic_dev.dma_handle, DMA0, DMAREQ_CHANNEL);

    /* Create DMIC DMA handle. */
    DMIC_TransferCreateHandleDMA(DMIC0,
                                 &mic_dev.dmic_dma_handle,
                                 dmic_dma_transfer_callback,
                                 (void *)&mic_dev,
                                 &mic_dev.dma_handle);
    return RT_EOK;
}

rt_err_t mic_device_start(struct rt_audio_device *audio, int stream)
{
    struct mic_device *mic_dev = (struct mic_device *)audio->parent.user_data;
    if (stream == AUDIO_STREAM_RECORD)
    {
        dmic_transfer_t dmic_transfer;
        dmic_transfer.data = (uint16_t *)&mic_dev->rx_fifo[0];
        dmic_transfer.dataSize = RX_DMA_FIFO_SIZE / 2;
        DMIC_TransferReceiveDMA(DMIC0, &mic_dev->dmic_dma_handle, &dmic_transfer, kDMIC_Channel0);
    }
    return RT_EOK;
}

rt_err_t mic_device_stop(struct rt_audio_device *audio, int stream)
{
    struct mic_device *mic_dev = (struct mic_device *)audio->parent.user_data;
    if (stream == AUDIO_STREAM_RECORD)
    {
        DMIC_TransferAbortReceiveDMA(DMIC0, &mic_dev->dmic_dma_handle);
    }
    return RT_EOK;
}

rt_err_t mic_device_getcaps(struct rt_audio_device *audio, struct rt_audio_caps *caps)
{
    return RT_EOK;
}

rt_err_t mic_device_configure(struct rt_audio_device *audio, struct rt_audio_caps *caps)
{
    return RT_EOK;
}

static struct rt_audio_ops _mic_audio_ops =
{
    .getcaps     = mic_device_getcaps,
    .configure   = mic_device_configure,
    .init        = mic_device_init,
    .start       = mic_device_start,
    .stop        = mic_device_stop,
    .transmit    = RT_NULL,
    .buffer_info = RT_NULL,
};

int rt_hw_mic_init(void)
{
    struct rt_audio_device *audio = &mic_dev.audio;
    /* mic default */
    mic_dev.rx_fifo = rt_calloc(1, RX_DMA_FIFO_SIZE);
    if (mic_dev.rx_fifo == RT_NULL)
    {
        return -RT_ENOMEM;
    }

    mic_dev.config.channels = 1;
    mic_dev.config.samplerate = 16000;
    mic_dev.config.samplebits = 16;

    /* register mic device */
    audio->ops = &_mic_audio_ops;
    rt_audio_register(audio, "mic0", RT_DEVICE_FLAG_RDONLY, (void *)&mic_dev);

    return RT_EOK;
}
INIT_DEVICE_EXPORT(rt_hw_mic_init);


text:
using System.Collections.Generic;
using Cards.Extensions.Tfs.Core.Interfaces;
using Cards.Extensions.Tfs.Core.Models;
using FluentAssertions;
using Moq;
using Xunit;

namespace Cards.Extensions.Tfs.Tests
{
    public class WorkItemTests
    {
        public class Structure
        {
            [Fact]
            [Trait("Category", "WorkItem")]
            public void WhenInitialize_ShouldNotBeNull()
            {
                WorkItem workItem = new WorkItem();
                workItem.Should().NotBeNull();
            }

            [Fact]
            [Trait("Category", "WorkItem")]
            public void WhenInitialize_ShouldIDBeZero()
            {
                WorkItem workItem = new WorkItem();
                workItem.ID.Should().Be(0);
            }

            [Fact]
            [Trait("Category", "WorkItem")]
            public void WhenInitialize_ShouldTitleBeNull()
            {
                WorkItem workItem = new WorkItem();
                workItem.Title.Should().BeNull();
            }

            [Fact]
            [Trait("Category", "WorkItem")]
            public void WhenInitialize_ShouldDescriptionBeNull()
            {
                WorkItem workItem = new WorkItem();
                workItem.Description.Should().BeNull();
            }

            [Fact]
            [Trait("Category", "WorkItem")]
            public void WhenInitialize_ShouldAssignedToBeNull()
            {
                WorkItem workItem = new WorkItem();
                workItem.AssignedTo.Should().BeNull();
            }
        }

        public class GetByIdMethod
        {
            [Fact]
            [Trait("Category", "WorkItem")]
            public void WhenGet_ShouldBeNull()
            {
                var tfsProvider = new Mock<ITFSProvider>();

                tfsProvider.Setup(d => d.GetTFSItem(It.Is<int>(i => i == 1))).Returns(new WorkItem() { ID = 1, Title = "TFS Work Item", Description = "TFS Work Item Description", AssignedTo = "Somebody" });

                WorkItem workItem = new WorkItem(tfsProvider.Object);

                var subject = workItem.Get(0);

                subject.Should().BeNull();
            }

            [Fact]
            [Trait("Category", "WorkItem")]
            public void WhenGet_ShouldNotBeNull()
            {
                var tfsProvider = new Mock<ITFSProvider>();

                tfsProvider.Setup(d => d.GetTFSItem(It.Is<int>(i => i == 1))).Returns(new WorkItem() { ID = 1, Title = "TFS Work Item", Description = "TFS Work Item Description", AssignedTo = "Somebody" });

                WorkItem workItem = new WorkItem(tfsProvider.Object);

                var subject = workItem.Get(1);

                subject.Should().NotBeNull();
            }

            [Fact]
            [Trait("Category", "WorkItem")]
            public void WhenGet_ShoudIDBeOne()
            {
                var tfsProvider = new Mock<ITFSProvider>();

                tfsProvider.Setup(d => d.GetTFSItem(It.Is<int>(i => i == 1))).Returns(new WorkItem() { ID = 1, Title = "TFS Work Item", Description = "TFS Work Item Description", AssignedTo = "Somebody" });

                WorkItem workItem = new WorkItem(tfsProvider.Object);

                var subject = workItem.Get(1);

                subject.ID.Should().Be(1);
            }

            [Fact]
            [Trait("Category", "WorkItem")]
            public void WhenGet_ShoudHaveTitle()
            {
                var tfsProvider = new Mock<ITFSProvider>();

                tfsProvider.Setup(d => d.GetTFSItem(It.Is<int>(i => i == 1))).Returns(new WorkItem() { ID = 1, Title = "TFS Work Item", Description = "TFS Work Item Description", AssignedTo = "Somebody" });

                WorkItem workItem = new WorkItem(tfsProvider.Object);

                var subject = workItem.Get(1);

                subject.Title.Should().NotBeNullOrEmpty();
            }
        }

        public class GetBySavedQueryMethod
        {
            [Fact]
            [Trait("Category", "WorkItem")]
            public void WhenGet_ShouldNotBeNull()
            {
                var tfsProvider = new Mock<ITFSProvider>();

                tfsProvider.
                    Setup(d => d.GetTFSItems(It.IsAny<string>()))
                    .Returns(() => { return new List<WorkItem>() { new WorkItem() { ID = 1, Title = "TFS Work Item", Description = "TFS Work Item Description", AssignedTo = "Somebody" } }; });

                WorkItem workItem = new WorkItem(tfsProvider.Object);

                var subject = workItem.Get("query");

                subject.Should().NotBeNull();
            }

            [Fact]
            [Trait("Category", "WorkItem")]
            public void WhenGet_ShouldCountBeOne()
            {
                var tfsProvider = new Mock<ITFSProvider>();

                tfsProvider.
                    Setup(d => d.GetTFSItems(It.IsAny<string>()))
                    .Returns(() => { return new List<WorkItem>() { new WorkItem() { ID = 1, Title = "TFS Work Item", Description = "TFS Work Item Description", AssignedTo = "Somebody" } }; });

                WorkItem workItem = new WorkItem(tfsProvider.Object);

                var subject = workItem.Get("query");

                subject.Count.Should().Be(1);
            }
        }
    }
}


text:
package com.facebook.buck.util;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

import java.util.Arrays;
import java.util.Collections;
import java.util.Map;
import java.util.TreeMap;
import org.junit.Test;

public class PatternsMatcherTest {

  @Test
  public void testMatchesPattern() {
    PatternsMatcher patternsMatcher =
        new PatternsMatcher(Arrays.asList("pattern.*", "test_pattern"));

    assertTrue(patternsMatcher.matches("pattern"));
    assertTrue(patternsMatcher.matches("test_pattern"));
    assertTrue(patternsMatcher.substringMatches("pattern"));
    assertTrue(patternsMatcher.substringMatches("test_pattern"));
  }

  @Test
  public void testMatchesAnyWithExactMatch() {
    PatternsMatcher patternsMatcher =
        new PatternsMatcher(Arrays.asList("pattern.*", "test_pattern"));

    assertTrue(patternsMatcher.matches("test_pattern"));
  }

  @Test
  public void testMatchesAnyWithWildcard() {
    PatternsMatcher patternsMatcher =
        new PatternsMatcher(Arrays.asList("pattern.*", "test_pattern"));

    assertTrue(patternsMatcher.matches("pattern"));
  }

  @Test
  public void testDoesNotMatchPrefix() {
    PatternsMatcher patternsMatcher = new PatternsMatcher(Collections.singletonList("test"));

    assertFalse(patternsMatcher.matches("test_pattern"));
  }

  @Test
  public void testMatchAnyWithNonMatchingPrefixReturnsFalse() {
    PatternsMatcher patternsMatcher = new PatternsMatcher(Collections.singletonList("test"));

    assertFalse(patternsMatcher.matches("test_pattern"));
  }

  @Test
  public void testSubstringMatchesPrefix() {
    PatternsMatcher patternsMatcher = new PatternsMatcher(Collections.singletonList("test"));

    assertTrue(patternsMatcher.substringMatches("test_pattern"));
  }

  @Test
  public void testDoesNotMatchSuffix() {
    PatternsMatcher patternsMatcher = new PatternsMatcher(Collections.singletonList("pattern"));

    assertFalse(patternsMatcher.matches("test_pattern"));
  }

  @Test
  public void testSubstringMatchesSuffix() {
    PatternsMatcher patternsMatcher = new PatternsMatcher(Collections.singletonList("pattern"));

    assertTrue(patternsMatcher.substringMatches("test_pattern"));
  }

  @Test
  public void testDoesNotMatchInfix() {
    PatternsMatcher patternsMatcher = new PatternsMatcher(Collections.singletonList("_"));

    assertFalse(patternsMatcher.matches("test_pattern"));
  }

  @Test
  public void testSubstringMatchesInfix() {
    PatternsMatcher patternsMatcher = new PatternsMatcher(Collections.singletonList("_"));

    assertTrue(patternsMatcher.substringMatches("test_pattern"));
  }

  @Test
  public void testDoesNotMatchPattern() {
    PatternsMatcher patternsMatcher =
        new PatternsMatcher(Arrays.asList("pattern.*", "test_pattern"));

    assertFalse(patternsMatcher.matches("wrong_pattern"));
    assertFalse(patternsMatcher.substringMatches("wrong_pat"));
  }

  @Test
  public void testMatchesAnyDoesNotMatchPattern() {
    PatternsMatcher patternsMatcher =
        new PatternsMatcher(Arrays.asList("pattern.*", "test_pattern"));

    assertFalse(patternsMatcher.matches("wrong_pattern"));
  }

  @Test
  public void testMatchesAnyDoesNotMatchEmptyPatterns() {
    assertFalse(PatternsMatcher.NONE.matches("wrong_pattern"));
  }

  @Test
  public void testMatchesMatchesEmptyPatterns() {
    assertTrue(PatternsMatcher.ANY.matches("wrong_pattern"));
  }

  @Test
  public void testHasPatterns() {
    PatternsMatcher patternsMatcher =
        new PatternsMatcher(Arrays.asList("pattern.*", "test_pattern"));

    assertFalse(patternsMatcher.isMatchesAny());
    assertFalse(patternsMatcher.isMatchesNone());
  }

  @Test
  public void testHasNoPatterns() {
    PatternsMatcher patternsMatcher = new PatternsMatcher(Collections.emptyList());

    assertTrue(patternsMatcher.isMatchesNone());
    assertFalse(patternsMatcher.isMatchesAny());
  }

  @Test
  public void testFilterMatchingMapEntriesWithEmptyPatterns() {
    PatternsMatcher patternsMatcher = PatternsMatcher.ANY;

    Map<String, String> entries =
        new TreeMap<String, String>() {
          {
            put("e1", "v1");
            put("e2", "v2");
            put("e3", "v3");
          }
        };

    assertEquals(entries, patternsMatcher.filterMatchingMapKeys(entries));
  }

  @Test
  public void testFilterMatchingMapEntries() {
    PatternsMatcher patternsMatcher = new PatternsMatcher(Arrays.asList("e1", "e2"));

    Map<String, String> entries =
        new TreeMap<String, String>() {
          {
            put("e1", "v1");
            put("e2", "v2");
            put("e3", "v3");
          }
        };

    Map<String, String> expectedEntries =
        new TreeMap<String, String>() {
          {
            put("e1", "v1");
            put("e2", "v2");
          }
        };

    assertEquals(expectedEntries, patternsMatcher.filterMatchingMapKeys(entries));
  }
}


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

#include "pal_config.h"
#include "pal_runtimeinformation.h"
#include "pal_types.h"
#include <stdio.h>
#include <sys/utsname.h>

extern "C" const char* SystemNative_GetUnixName()
{
    return PAL_UNIX_NAME;
}

extern "C" int32_t SystemNative_GetUnixVersion(char* version, int* capacity)
{
    struct utsname _utsname;
    if (uname(&_utsname) != -1)
    {
        int r = snprintf(version, static_cast<size_t>(*capacity), "%s %s %s", _utsname.sysname, _utsname.release, _utsname.version);
        if (r > *capacity)
        {
            *capacity = r + 1;
            return -1;
        }
    }

    return 0;
}

/* Returns an int representing the OS Architecture:
 0 - x86
 1 - x64
 2 - ARM
 3 - ARM64 */
extern "C" int32_t SystemNative_GetOSArchitecture()
{
#if defined(_ARM_)
    return ARCH_ARM;
#elif defined(_ARM64_)
    return ARCH_ARM64;
#elif defined(_AMD64_)
    return ARCH_X64;
#elif defined(_X86_)
    return ARCH_X86;
#else
#error Unidentified Architecture
#endif
}

/* Returns an int representing the OS Architecture:
0 - x86
1 - x64
2 - ARM
3 - ARM64 */
extern "C" int32_t SystemNative_GetProcessArchitecture()
{
#if defined(_ARM_)
    return ARCH_ARM;
#elif defined(_ARM64_)
    return ARCH_ARM64;
#elif defined(_AMD64_)
    return ARCH_X64;
#elif defined(_X86_)
    return ARCH_X86;
#else
#error Unidentified Architecture
#endif
}


text:
require 'spec_helper'

describe YmlGtranslate do

  before { @gt = YmlGtranslate::Translator.new("en", "de", "") }

  it "asserts comment token properly suffixed" do

    @gt.comment("stuff").should eq("stuff" + YmlGtranslate::Translator::COMMENT_TOKEN)
  end

  it "checks german translation" do
    @gt.translate("Good morning").should eq("guten Morgen")
  end

  it "checks comparing empty hashes" do
    @gt.compare({},{}).should eq({})
  end

end


text:
$pkg_name = "hab-pkg-export-tar"
$pkg_origin = "core"
$pkg_maintainer = "The Habitat Maintainers <humans@habitat.sh>"
$pkg_license = @("Apache-2.0")
$pkg_bin_dirs = @("bin")
$pkg_deps=@(
    "core/docker",
    "core/visual-cpp-redist-2015"
)
$pkg_build_deps = @(
    "core/visual-cpp-build-tools-2015",
    "core/rust/$(Get-Content "$PLAN_CONTEXT/../../../rust-toolchain")",
    "core/cacerts"
)

function pkg_version {
    Get-Content "$SRC_PATH/../../VERSION"
}

function Invoke-Before {
    Invoke-DefaultBefore
    Set-PkgVersion
}

function Invoke-Prepare {
    if($env:HAB_CARGO_TARGET_DIR) {
        $env:CARGO_TARGET_DIR           = "$env:HAB_CARGO_TARGET_DIR"
    } else {
        $env:CARGO_TARGET_DIR           = Join-Path -Path "$HAB_CACHE_SRC_PATH" -ChildPath "$pkg_dirname"
    }

    $env:SSL_CERT_FILE              = "$(Get-HabPackagePath "cacerts")/ssl/certs/cacert.pem"
    $env:LIB                        += ";$HAB_CACHE_SRC_PATH/$pkg_dirname/lib"
    $env:INCLUDE                    += ";$HAB_CACHE_SRC_PATH/$pkg_dirname/include"

    # Used by the `build.rs` program to set the version of the binaries
    $env:PLAN_VERSION = "$pkg_version/$pkg_release"
    Write-BuildLine "Setting env:PLAN_VERSION=$env:PLAN_VERSION"

    # Used to set the active package target for the binaries at build time
    $env:PLAN_PACKAGE_TARGET = "$pkg_target"
    Write-BuildLine "Setting env:PLAN_PACKAGE_TARGET=$env:PLAN_PACKAGE_TARGET"
}

function Invoke-Build {
    Push-Location "$PLAN_CONTEXT"
    try {
        cargo build --release
        if($LASTEXITCODE -ne 0) {
            Write-Error "Cargo build failed!"
        }
    } finally { Pop-Location }
}

function Invoke-Install {
    Copy-Item "$env:CARGO_TARGET_DIR/release/hab-pkg-export-tar.exe" "$pkg_prefix/bin/hab-pkg-export-tar.exe"
    Copy-Item "$(Get-HabPackagePath "visual-cpp-redist-2015")/bin/*.dll" "$pkg_prefix/bin"
}


text:
	<md-sidenav class="md-sidenav-right md-whiteframe-z2" md-component-id="right">
		<md-toolbar class="md-theme-light">

Add Song

		</md-toolbar>
		<md-content layout-padding>

			<form novalidate ng-submit="create()">
				<md-input-container>
					Name
					<input required="" type="text" id="testInput"
						   ng-model="name" md-sidenav-focus>
				</md-input-container>
				<md-input-container>
					URL
					<input required="" type="text" id="link"
						   ng-model="link">
				</md-input-container>
				<md-button type="submit" class="md-primary md-raised">
					Save
				</md-button>
			</form>

		</md-content>
	</md-sidenav>

			<videogular vg-player-ready="controller.onPlayerReady($API)" vg-complete="controller.onCompleteVideo()" vg-theme="controller.config.theme.url" class="videogular-container audio">
				<vg-media vg-src="controller.config.sources"
						  vg-tracks="controller.config.tracks"  vg-type="audio">
				</vg-media>

				<vg-controls>
					<vg-play-pause-button></vg-play-pause-button>

				</vg-controls>

			</videogular>

		<md-content class="md-default-theme">
			<md-list>
				<md-list-item class="md-3-line" ng-repeat="song in songs | orderBy :'-score' track by $index">

{{song.name}}

{{song.link}}

Rating

								<md-slider ng-change="ratingChanged(song)" flex class="md-warn" md-discrete
										   ng-model="song.score" step="1" min="1" max="100" aria-label="rating">
								</md-slider>

					<md-divider></md-divider>
				</md-list-item>
			</md-list>

		</md-content>


text:
""" Methods for Regex Operations """
import re

def get_ncl(link):
""" Method to extract ncl value of a story"""
	ncl_string = re.findall("ncl=.*?&",link)
	if ncl_string:
		return ncl_string[0][4:-1]
	else:
		return ''


text:
var baseIsNative = require('./_baseIsNative'),
    getValue = require('./_getValue');

/**
 * Gets the native function at `key` of `object`.
 *
 * @private
 * @param {Object} object The object to query.
 * @param {string} key The key of the method to get.
 * @returns {*} Returns the function if it's native, else `undefined`.
 */
function getNative(object, key) {
    var value = getValue(object, key);
    return baseIsNative(value) ? value : undefined;
}

module.exports = getNative;


text:
require 'spec_helper.rb'

describe Flattery::ValueCache::Settings do
  let(:settings_class) { Flattery::ValueCache::Settings }
  let(:settings) { cache_class.value_cache_options }
  subject { settings }

  context "with a standard belongs_to association" do
    let(:cache_class) do
      class ::ValueCacheHarness < Note
        include Flattery::ValueCache
        flatten_value category: :name
      end
      ValueCacheHarness
    end
    context "before resolution" do
      it { should be_a(settings_class) }
      its(:raw_settings) { should eql([
        {from_entity: :category, to_entity: :name, as: nil}
      ]) }
      its(:resolved) { should be_false }
    end
    context "after resolution" do
      before { settings.settings }
      its(:resolved) { should be_true }
      its(:settings) { should eql({
        "category_name"=>{from_entity: :category, to_entity: :name, changed_on: ["category_id"]}
      }) }
    end
  end

  context "with inherited model definitions and ValueCache defined in the parent" do
    let!(:parent_cache_class) do
      class ::ValueCacheHarness < Note
        include Flattery::ValueCache
        flatten_value category: :name
      end
      ValueCacheHarness
    end
    let!(:child_cache_class) do
      class ::ChildValueCacheHarness < ::ValueCacheHarness
        flatten_value country: :name
      end
      ChildValueCacheHarness
    end
    context "before resolution" do
      describe "parent" do
        let(:settings) { parent_cache_class.value_cache_options }
        its(:raw_settings) { should eql([
          {from_entity: :category, to_entity: :name, as: nil}
        ]) }
      end
      describe "child" do
        let(:settings) { child_cache_class.value_cache_options }
        its(:raw_settings) { should eql([
          {from_entity: :category, to_entity: :name, as: nil},
          {from_entity: :country, to_entity: :name, as: nil}
        ]) }
      end
    end
    context "after resolution" do
      before { parent_cache_class.value_cache_options.settings && child_cache_class.value_cache_options.settings}
      describe "parent" do
        let(:settings) { parent_cache_class.value_cache_options }
        its(:resolved) { should be_true }
        its(:settings) { should eql({
          "category_name"=>{from_entity: :category, to_entity: :name, changed_on: ["category_id"]}
        }) }
      end
      describe "child" do
        let(:settings) { child_cache_class.value_cache_options }
        its(:resolved) { should be_true }
        its(:settings) { should eql({
          "category_name"=>{from_entity: :category, to_entity: :name, changed_on: ["category_id"]},
          "country_name"=>{from_entity: :country, to_entity: :name, changed_on: ["country_id"]}
        }) }
      end
    end
  end

end


text:
package com.xeiam.xchange.btcchina.dto.trade;

import org.apache.commons.lang3.builder.ToStringBuilder;

import com.fasterxml.jackson.annotation.JsonProperty;

public class BTCChinaMarketDepthObject {

  private BTCChinaMarketDepth marketDepth;

  public BTCChinaMarketDepthObject(@JsonProperty("market_depth") BTCChinaMarketDepth marketDepth) {

    this.marketDepth = marketDepth;
  }

  public BTCChinaMarketDepth getMarketDepth() {

    return marketDepth;
  }

  public void setMarketDepth(BTCChinaMarketDepth marketDepth) {

    this.marketDepth = marketDepth;
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public String toString() {

    return ToStringBuilder.reflectionToString(this);
  }

}


text:
import { GithubAuthProvider } from "firebase/auth";

const credential = GithubAuthProvider.credential(token);
// [END auth_github_provider_credential_modular]


text:
package net.bytebuddy.implementation.bind.annotation;

import net.bytebuddy.description.annotation.AnnotationDescription;
import net.bytebuddy.description.field.FieldDescription;
import net.bytebuddy.description.field.FieldList;
import net.bytebuddy.description.method.MethodDescription;
import net.bytebuddy.description.method.MethodList;
import net.bytebuddy.description.method.ParameterDescription;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.description.type.generic.GenericTypeDescription;
import net.bytebuddy.implementation.Implementation;
import net.bytebuddy.implementation.bind.MethodDelegationBinder;
import net.bytebuddy.implementation.bytecode.StackManipulation;
import net.bytebuddy.implementation.bytecode.assign.Assigner;
import net.bytebuddy.implementation.bytecode.member.FieldAccess;
import net.bytebuddy.implementation.bytecode.member.MethodVariableAccess;

import java.lang.annotation.*;

import static net.bytebuddy.matcher.ElementMatchers.named;

/**
 * Assigns the value of a field of the instrumented type to the annotated parameter. For a binding to be valid,
 * the instrumented type must be able to access a field of the given name. Also, the parameter's type must be
 * assignable to the given field. For attempting a type casting, the {@link RuntimeType} annotation can be
 * applied to the parameter.
 *
 * @see net.bytebuddy.implementation.MethodDelegation
 * @see net.bytebuddy.implementation.bind.annotation.TargetMethodAnnotationDrivenBinder
 * @see net.bytebuddy.implementation.bind.annotation.RuntimeType
 */
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
public @interface FieldValue {

    /**
     * The name of the field to be accessed.
     *
     * @return The name of the field.
     */
    String value();

    /**
     * Defines the type on which the field is declared. If this value is not set, the most specific type's field is read,
     * if two fields with the same name exist in the same type hierarchy.
     *
     * @return The type that declares the accessed field.
     */
    Class<?> definingType() default void.class;

    /**
     * Binds a {@link FieldValue} annotation.
     */
    enum Binder implements TargetMethodAnnotationDrivenBinder.ParameterBinder<FieldValue> {

        /**
         * The singleton instance.
         */
        INSTANCE;

        /**
         * The annotation method that for the defining type.
         */
        private static final MethodDescription.InDefinedShape DEFINING_TYPE;

        /**
         * The annotation method for the field's name.
         */
        private static final MethodDescription.InDefinedShape FIELD_NAME;

        /*
         * Initializes the methods of the annotation that is read by this binder.
         */
        static {
            MethodList<MethodDescription.InDefinedShape> methodList = new TypeDescription.ForLoadedType(FieldValue.class).getDeclaredMethods();
            DEFINING_TYPE = methodList.filter(named("definingType")).getOnly();
            FIELD_NAME = methodList.filter(named("value")).getOnly();
        }

        @Override
        public Class<FieldValue> getHandledType() {
            return FieldValue.class;
        }

        @Override
        public MethodDelegationBinder.ParameterBinding<?> bind(AnnotationDescription.Loadable<FieldValue> annotation,
                                                               MethodDescription source,
                                                               ParameterDescription target,
                                                               Implementation.Target implementationTarget,
                                                               Assigner assigner) {
            FieldLocator.Resolution resolution = FieldLocator
                    .of(annotation.getValue(DEFINING_TYPE, TypeDescription.class), implementationTarget.getTypeDescription())
                    .resolve(annotation.getValue(FIELD_NAME, String.class), source.isStatic());
            if (resolution.isResolved()) {
                StackManipulation stackManipulation = new StackManipulation.Compound(
                        resolution.getFieldDescription().isStatic()
                                ? StackManipulation.Trivial.INSTANCE
                                : MethodVariableAccess.REFERENCE.loadOffset(0),
                        FieldAccess.forField(resolution.getFieldDescription()).getter(),
                        assigner.assign(resolution.getFieldDescription().getType().asErasure(),
                                target.getType().asErasure(),
                                RuntimeType.Verifier.check(target))
                );
                return stackManipulation.isValid()
                        ? new MethodDelegationBinder.ParameterBinding.Anonymous(stackManipulation)
                        : MethodDelegationBinder.ParameterBinding.Illegal.INSTANCE;
            } else {
                return MethodDelegationBinder.ParameterBinding.Illegal.INSTANCE;
            }
        }

        @Override
        public String toString() {
            return "FieldValue.Binder." + name();
        }

        /**
         * Responsible for locating a field of the instrumented type.
         */
        protected abstract static class FieldLocator {

            /**
             * Creates a field locator for the given type and instrumented type.
             *
             * @param typeDescription  The type which is supposed to define the field or {@code void} if a type should be located
             *                         in the hierarchy.
             * @param instrumentedType The instrumented type from which the field is accessed.
             * @return The field locator for the given field.
             */
            protected static FieldLocator of(TypeDescription typeDescription, TypeDescription instrumentedType) {
                return typeDescription.represents(void.class)
                        ? new ForFieldInHierarchy(instrumentedType)
                        : ForSpecificType.of(typeDescription, instrumentedType);
            }

            /**
             * Attempts to locate a type for a given field.
             *
             * @param fieldName    The name of the field.
             * @param staticMethod {@code} true if the field is accessed from a static method.
             * @return The resolution for the requested lookup.
             */
            protected abstract Resolution resolve(String fieldName, boolean staticMethod);

            /**
             * A resolution of a field locator.
             */
            protected interface Resolution {

                /**
                 * Returns the located field description if available or throws an exception if this method is called for an
                 * unresolved resolution.
                 *
                 * @return The located field.
                 */
                FieldDescription getFieldDescription();

                /**
                 * Returns {@code true} if a field was successfully located.
                 *
                 * @return {@code true} if a field was successfully located.
                 */
                boolean isResolved();

                /**
                 * A canonical implementation of an unresolved field resolution.
                 */
                enum Unresolved implements Resolution {

                    /**
                     * The singleton instance.
                     */
                    INSTANCE;

                    @Override
                    public FieldDescription getFieldDescription() {
                        throw new IllegalStateException("Cannot resolve field for unresolved lookup");
                    }

                    @Override
                    public boolean isResolved() {
                        return false;
                    }

                    @Override
                    public String toString() {
                        return "FieldValue.Binder.FieldLocator.Resolution.Unresolved." + name();
                    }
                }

                /**
                 * A successfully resolved field resolution.
                 */
                class Resolved implements Resolution {

                    /**
                     * The resolved field.
                     */
                    private final FieldDescription fieldDescription;

                    /**
                     * Creates a successful field resolution.
                     *
                     * @param fieldDescription The resolved field.
                     */
                    public Resolved(FieldDescription fieldDescription) {
                        this.fieldDescription = fieldDescription;
                    }

                    @Override
                    public FieldDescription getFieldDescription() {
                        return fieldDescription;
                    }

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

                    @Override
                    public boolean equals(Object other) {
                        if (this == other) return true;
                        if (!(other instanceof Resolved)) return false;
                        Resolved resolved = (Resolved) other;
                        return fieldDescription.equals(resolved.fieldDescription);
                    }

                    @Override
                    public int hashCode() {
                        return fieldDescription.hashCode();
                    }

                    @Override
                    public String toString() {
                        return "FieldValue.Binder.FieldLocator.Resolution.Resolved{" +
                                "fieldDescription=" + fieldDescription +
                                '}';
                    }
                }
            }

            /**
             * Attempts to locate a field within a type's hierarchy.
             */
            protected static class ForFieldInHierarchy extends FieldLocator {

                /**
                 * The instrumented type which defines the field.
                 */
                private final TypeDescription instrumentedType;

                /**
                 * Creates a new field locator for locating a field in the instrumented type's class hierarchy.
                 *
                 * @param instrumentedType The instrumented type
                 */
                protected ForFieldInHierarchy(TypeDescription instrumentedType) {
                    this.instrumentedType = instrumentedType;
                }

                @Override
                protected Resolution resolve(String fieldName, boolean staticMethod) {
                    for (GenericTypeDescription currentType : instrumentedType) {
                        FieldList<?> fieldList = currentType.getDeclaredFields().filter(named(fieldName));
                        if (!fieldList.isEmpty() && fieldList.getOnly().isVisibleTo(instrumentedType) && (!staticMethod || fieldList.getOnly().isStatic())) {
                            return new Resolution.Resolved(fieldList.getOnly());
                        }
                    }
                    return Resolution.Unresolved.INSTANCE;
                }

                @Override
                public boolean equals(Object other) {
                    if (this == other) return true;
                    if (!(other instanceof ForFieldInHierarchy)) return false;
                    ForFieldInHierarchy that = (ForFieldInHierarchy) other;
                    return instrumentedType.equals(that.instrumentedType);
                }

                @Override
                public int hashCode() {
                    return instrumentedType.hashCode();
                }

                @Override
                public String toString() {
                    return "FieldValue.Binder.FieldLocator.ForFieldInHierarchy{" +
                            "instrumentedType=" + instrumentedType +
                            '}';
                }
            }

            /**
             * Locates a field only within a given type.
             */
            protected static class ForSpecificType extends FieldLocator {

                /**
                 * The type which is supposed to define the field.
                 */
                private final TypeDescription typeDescription;

                /**
                 * The instrumented type which is accessing the field.
                 */
                private final TypeDescription instrumentedType;

                /**
                 * Creates a new field locator for looking up a field within a specific type.
                 *
                 * @param typeDescription  The type which is supposed to define the field.
                 * @param instrumentedType The instrumented type which is accessing the field.
                 */
                protected ForSpecificType(TypeDescription typeDescription, TypeDescription instrumentedType) {
                    this.typeDescription = typeDescription;
                    this.instrumentedType = instrumentedType;
                }

                /**
                 * Creates a field locator that locates a field within the given type only if that type is within the
                 * instrumented type's type hierarchy.
                 *
                 * @param typeDescription  The given type to locate a field within.
                 * @param instrumentedType The instrumented type.
                 * @return An appropriate field locator.
                 */
                protected static FieldLocator of(TypeDescription typeDescription, TypeDescription instrumentedType) {
                    if (typeDescription.isInterface() || typeDescription.isPrimitive() || typeDescription.isArray()) {
                        throw new IllegalStateException(typeDescription + " is not capable of declaring a field");
                    }
                    return instrumentedType.isAssignableTo(typeDescription)
                            ? new ForSpecificType(typeDescription, instrumentedType)
                            : new Impossible();
                }

                @Override
                protected Resolution resolve(String fieldName, boolean staticMethod) {
                    FieldList<?> fieldList = typeDescription.getDeclaredFields().filter(named(fieldName));
                    return fieldList.isEmpty() || !fieldList.getOnly().isVisibleTo(instrumentedType) || (staticMethod && !fieldList.getOnly().isStatic())
                            ? Resolution.Unresolved.INSTANCE
                            : new Resolution.Resolved(fieldList.getOnly());
                }

                @Override
                public boolean equals(Object other) {
                    if (this == other) return true;
                    if (!(other instanceof ForSpecificType)) return false;
                    ForSpecificType that = (ForSpecificType) other;
                    return typeDescription.equals(that.typeDescription)
                            && instrumentedType.equals(that.instrumentedType);
                }

                @Override
                public int hashCode() {
                    int result = typeDescription.hashCode();
                    result = 31 * result + instrumentedType.hashCode();
                    return result;
                }

                @Override
                public String toString() {
                    return "FieldValue.Binder.FieldLocator.ForSpecificType{" +
                            "typeDescription=" + typeDescription +
                            ", instrumentedType=" + instrumentedType +
                            '}';
                }
            }

            /**
             * A field locator that never locates a field.
             */
            protected static class Impossible extends FieldLocator {

                @Override
                protected Resolution resolve(String fieldName, boolean staticMethod) {
                    return Resolution.Unresolved.INSTANCE;
                }

                @Override
                public int hashCode() {
                    return 31;
                }

                @Override
                public boolean equals(Object other) {
                    return other != null && other.getClass() == getClass();
                }

                @Override
                public String toString() {
                    return "FieldValue.Binder.FieldLocator.Impossible{}";
                }
            }
        }
    }
}


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

<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>pinpoint</artifactId>
        <groupId>com.navercorp.pinpoint</groupId>
        <version>1.8.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>pinpoint-flink</artifactId>
    <name>pinpoint-flink</name>

    <properties>
        <jdk.version>1.8</jdk.version>
        <jdk.home>${env.JAVA_8_HOME}</jdk.home>
        <sniffer.artifactid>java18</sniffer.artifactid>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.apache.flink</groupId>
            <artifactId>flink-java</artifactId>
            <version>1.3.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.flink</groupId>
            <artifactId>flink-streaming-java_2.10</artifactId>
            <version>1.3.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.flink</groupId>
            <artifactId>flink-clients_2.10</artifactId>
            <version>1.3.1</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>com.navercorp.pinpoint</groupId>
            <artifactId>pinpoint-commons-hbase</artifactId>
        </dependency>
        <dependency>
            <groupId>com.navercorp.pinpoint</groupId>
            <artifactId>pinpoint-commons-server</artifactId>
        </dependency>
        <dependency>
            <groupId>com.navercorp.pinpoint</groupId>
            <artifactId>pinpoint-thrift</artifactId>
        </dependency>
        <dependency>
            <groupId>com.navercorp.pinpoint</groupId>
            <artifactId>pinpoint-rpc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.thrift</groupId>
            <artifactId>libthrift</artifactId>
        </dependency>
        <dependency>
            <groupId>com.navercorp.pinpoint</groupId>
            <artifactId>pinpoint-web</artifactId>
            <classifier>classes</classifier>
            <exclusions>
                <exclusion>
                    <groupId>*</groupId>
                    <artifactId>*</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>com.navercorp.pinpoint</groupId>
            <artifactId>pinpoint-collector</artifactId>
            <classifier>classes</classifier>
            <exclusions>
                <exclusion>
                    <groupId>*</groupId>
                    <artifactId>*</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>commons-logging</groupId>
                    <artifactId>commons-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
        </dependency>
        <dependency>
            <groupId>net.sf.ehcache</groupId>
            <artifactId>ehcache-core</artifactId>
        </dependency>

        <!-- Logging depedencies -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
        </dependency>
        <!-- commons-logging-adapter -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jcl-over-slf4j</artifactId>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>io.dropwizard.metrics</groupId>
            <artifactId>metrics-core</artifactId>
        </dependency>
        <dependency>
            <groupId>io.dropwizard.metrics</groupId>
            <artifactId>metrics-jvm</artifactId>
        </dependency>
        <dependency>
            <groupId>io.dropwizard.metrics</groupId>
            <artifactId>metrics-servlets</artifactId>
        </dependency>
    </dependencies>

    <build>
        <resources>
            <resource>
                <directory>${basedir}/src/main/java</directory>
                <excludes>
                    <exclude>**/*.java</exclude>
                </excludes>
            </resource>
            <resource>
                <filtering>true</filtering>
                <directory>${basedir}/src/main/resources</directory>
            </resource>
            <resource>
                <directory>${basedir}/src/main/resources-${env}</directory>
            </resource>
        </resources>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.5.1</version>
                <configuration>
                    <source>${jdk.version}</source>
                    <target>${jdk.version}</target>
                    <fork>true</fork>
                    <debug>true</debug>
                    <optimize>true</optimize>
                    <encoding>${encoding}</encoding>
                    <showDeprecation>true</showDeprecation>
                    <compilerVersion>${jdk.version}</compilerVersion>
                    <executable>${jdk.home}/bin/javac</executable>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>2.4.3</version>
                <executions>
                    <execution>
                        <id>build-first</id>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                            <transformers>
                                <transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
                                    <resource>META-INF/spring.handlers</resource>
                                </transformer>
                                <transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
                                    <resource>META-INF/spring.schemas</resource>
                                </transformer>
                                <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                    <mainClass>com.navercorp.pinpoint.flink.StatStreamingVer2Job</mainClass>
                                </transformer>
                            </transformers>
                            <finalName>pinpoint-flink-job-${project.version}</finalName>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>


text:
<?php

//$responseBody = $appRPC->getDefualtLang();
/**
 * Default Language
 */
/**
 * Language Constants
 */
define('EN_LANG', 1);

define('DEFAULT_LANG',  EN_LANG);
/**
 * main Languages
 */
$GLOBALS ['sysLang'] = array(EN_LANG => 'en');
$GLOBALS ['sysLangLabels'] = array(EN_LANG => 'English');
$GLOBALS ['sysLangProp'] = array(
    $GLOBALS ['sysLang'][EN_LANG] => array('label' => 'English','againstID' => AR_LANG, 'dir' => 'ltr','designProps'=> array(
        'dropdownClass' =>'flag-gb' ,
        'dropdownMainID'=>'enLang',
        'data-bootstro-placement'=>'right',
        'direction'=>'left')),

);

/////////////////////////////////////// Languages

/*
 * define Request Language
 */
App::languageDefine();
//for index set language variable
$sizeOfArgs = sizeof($GLOBALS ['registry']->args) - 1;
if (in_array($GLOBALS ['registry']->args[$sizeOfArgs], $GLOBALS ['sysLang'])) {
    $GLOBALS ['registry']->request->setGet('viewLang', $GLOBALS ['registry']->args[$sizeOfArgs]);
}
unset($sizeOfArgs);

foreach($GLOBALS ['sysLang'] as $key => $lang){
   $current= DEFAULT_LANG;
    if($GLOBALS ['registry']->currentViewLang==$lang){
        $current=$key;
    }
}
define('CURRENT_LANG',$current);

/**
 * @var object translate
 * @GLOBAL
 * @see Zend_Translate
 * define translate in registry
 */
$viewLang = $GLOBALS ['sysLang'][DEFAULT_LANG];

$GLOBALS ['registry']->tr = new Zend_Translate(array('adapter' => 'gettext', 'content' => LANG_PATH . $viewLang . '.mo', 'locale' => $viewLang));


text:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import NoAlertPresentException
import unittest, time, re

class Test42(unittest.TestCase):
    def setUp(self):
        self.driver = webdriver.Firefox()
        self.driver.implicitly_wait(30)
        self.base_url = "http://powertex.staging.code-on.be/"
        self.verificationErrors = []
        self.accept_next_alert = True

    def test_untitled(self):
        driver = self.driver
        driver.find_element_by_link_text("PowertexShop").click()
        driver.find_element_by_xpath("//article[@id='content']/ul/li[2]/a/span/img").click()
        driver.find_element_by_css_selector("div.row > button[type=\"submit\"]").click()
        driver.find_element_by_css_selector("button.btn-black.align-right").click()
        self.assertEqual("Billing address", driver.find_element_by_xpath("//article[@id='content']/div/div/form/fieldset/div/div/h2").text)
        driver.get(self.base_url + "/en/")
        driver.find_element_by_link_text("PowertexShop").click()
        driver.find_element_by_xpath("//article[@id='content']/ul/li[2]/a/span/img").click()
        driver.find_element_by_css_selector("div.row > button[type=\"submit\"]").click()
        driver.find_element_by_css_selector("button.btn-black.align-right").click()
        try: self.assertEqual("Proceed Order", driver.find_element_by_css_selector("h1").text)
        except AssertionError as e: self.verificationErrors.append(str(e))

    def is_element_present(self, how, what):
        try: self.driver.find_element(by=how, value=what)
        except NoSuchElementException, e: return False
        return True

    def is_alert_present(self):
        try: self.driver.switch_to_alert()
        except NoAlertPresentException, e: return False
        return True

    def close_alert_and_get_its_text(self):
        try:
            alert = self.driver.switch_to_alert()
            alert_text = alert.text
            if self.accept_next_alert:
                alert.accept()
            else:
                alert.dismiss()
            return alert_text
        finally: self.accept_next_alert = True

    def tearDown(self):
        self.driver.quit()
        self.assertEqual([], self.verificationErrors)

if __name__ == "__main__":
    unittest.main()


text:
var helmet = require('../');

var koa = require('koa');
var request = require('supertest');

describe('contentTypeOptions', function() {
  var app;

  beforeEach(function() {
    app = koa();
    app.use(helmet.contentTypeOptions());
    app.use(function *() {
      this.body = 'Hello world!';
    });
  });

  it('sets header properly', function(done) {
    request(app.listen())
      .get('/')
      .expect('X-Content-Type-Options', 'nosniff', done);
  });
});