text:
Ibex simulation for RISC-V Compliance Testing
=============================================

This directory contains a compiled simulation of Ibex to be used as target
in the [RISC-V Compliance Test](https://github.com/riscv/riscv-compliance).
In addition to Ibex itself, it contains a 64 kB RAM and a memory-mapped helper
module to interact with the software, e.g. to dump out the test signature and to
end the simulation.

The simulation is designed for Verilator, but can be adapted to other simulators
if needed.

How to run RISC-V Compliance on Ibex
------------------------------------

0. Check your prerequisites
   To compile the simulation and run the compliance test suite you need to
   have the following tools installed:
   - Verilator
   - fusesoc
   - srecord (for `srec_cat`)
   - A RV32 compiler

   On Ubuntu/Debian, install the required tools like this:

   ```sh
   sudo apt-get install srecord python3-pip
   pip3 install --user -U fusesoc
   ```

   We recommend installing Verilator from source as versions from Linux
   distributions are often outdated. See
   https://www.veripool.org/projects/verilator/wiki/Installing for installation
   instructions.

1. Build a simulation of Ibex

   ```sh
   cd $IBEX_REPO_BASE
   fusesoc --cores-root=. run --target=sim --setup --build lowrisc:ibex:ibex_riscv_compliance --RV32E=0 --RV32M=ibex_pkg::RV32MNone
   ```

   You can use the two compile-time options `--RV32M` and `--RV32E` to
   enable/disable the M and E ISA extensions, respectively.

   You can now find the compiled simulation at `build/lowrisc_ibex_ibex_riscv_compliance_0.1/sim-verilator/Vibex_riscv_compliance`.

2. Get the RISC-V Compliance test suite

   The upstream RISC-V compliance test suite supports Ibex out of the box.

   ```
   git clone https://github.com/riscv/riscv-compliance.git
   cd riscv-compliance
   ```

3. Run the test suite
   ```sh
   cd $RISCV_COMPLIANCE_REPO_BASE
   # adjust to match your compiler name
   export RISCV_PREFIX=riscv32-unknown-elf-
   # give the absolute path to the simulation binary compiled in step 1
   export TARGET_SIM=/path/to/your/Vibex_riscv_compliance

   export RISCV_DEVICE=rv32imc
   export RISCV_TARGET=ibex

   # Note: rv32imc does not include the I and M extension tests
   make RISCV_ISA=rv32i && make RISCV_ISA=rv32im && make RISCV_ISA=rv32imc && \
      make RISCV_ISA=rv32Zicsr && make RISCV_ISA=rv32Zifencei
   ```

Compliance test suite system
----------------------------

This directory contains a system designed especially to run the compliance test
suite. The system consists of

- an Ibex core,
- a bus,
- a single-port memory for data and instructions,
- a bus-attached test utility.

The CPU core boots from SRAM at address 0x0.

The test utility is used by the software to end the simulation, and to inform
the simulator of the memory region where the test signature is stored.
The bus host reads the test signature from memory.

The memory map of the whole system is as follows:

| Start   | End     | Size  | Device                         |
|---------|---------|-------|--------------------------------|
| 0x0     | 0xFFFF  | 64 kB | shared instruction/data memory |
| 0x20000 | 0x203FF | 1 kB  | test utility                   |

The test utility provides the following registers relative to the base address.

| Address | R/W | Description                                                         |
|---------|-----|---------------------------------------------------------------------|
| 0x0     | W   | Write any value to dump the test signature and terminate simulation |
| 0x4     | W   | Start address of the test signature                                 |
| 0x8     | W   | End address of the test signature                                   |


text:
# encoding: UTF-8

module Spontaneous
  class Facet

    def initialize(root)
      @root = File.expand_path(root)
      paths.add :lib, ["lib", "**/*.rb"]
      paths.add :schema, ["schema", "**/*.rb"]
      paths.add :templates, "templates"
      paths.add :config, "config"
      paths.add :public, "public"
      paths.add :assets, "assets"
      paths.add :tasks, ["lib/tasks", "**/*.rake"]
      paths.add :migrations, ["db/migrations", "**/*.rake"]
      paths.add :plugins, ["plugins", "*"]
      paths.add :features, "features"
    end

    def root(*path)
      return @root if path.empty?
      File.join(@root, path)
    end

    def path(*args)
      Pathname.new(@root).join(*args)
    end

    def path!(*args)
      self.path(*args).tap do |path|
        path.mkpath
      end
    end

    def name
      File.basename(root)
    end

    # used by publishing mechanism to place files into the appropriate subdirectories
    # in the public folder.
    def file_namespace
      name
    end

    def paths
      _paths
    end

    def _paths
      @paths ||= Spontaneous::Paths.new(@root)
    end

    def config
      Spontaneous::Site.instance.config
    end

    def load_config!
      paths.expanded(:config).each do |config_path|
        Spontaneous::Site.config.load(config_path)
      end
    end

    # use Rails' alphabetical load order for initializers
    def run_initializers
      paths.expanded(:config).each do |config_path|
        Dir["#{config_path / "initializers"}/*.rb"].sort.each do |initializer|
          require initializer
        end
      end
    end

    def init!
    end

    def load!
      load_order.each { |category| load_files(category) }
    end

    def load_files(category)
      loaders[category].load!
    end

    def reload_all!
      load_order.each { |category| loaders[category].reload! }
    end
    alias_method :reload!, :reload_all!

    def load_order
      [:lib, :schema]
    end

    def loaders
      @loaders ||= \
      begin
        use_reloader = config.reload_classes
        {:schema => Spontaneous::SchemaLoader.new(schema_load_paths, use_reloader),
         :lib => Spontaneous::Loader.new(load_paths, use_reloader) }
      end
    end

    def load_paths
      load_paths_for_category(:lib)
    end

    def schema_load_paths
      load_paths_for_category(:schema)
    end

    def load_paths_for_category(category)
      self.paths.expanded(category)
    end

  end # Facet
end # Spontaneous

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" android:versionName="1.0" package="com.xamarin.signaturepad" android:installLocation="auto">
	<uses-sdk android:minSdkVersion="10" />
	<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
	<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
	<application android:label="@string/app_name" android:icon="@drawable/ic_launcher" android:theme="@style/Theme.AppCompat.Light.DarkActionBar"></application>
</manifest>


text:
package servers

import (
	"fmt"
	"net/http"
	"testing"
	"time"

	th "github.com/rackspace/gophercloud/testhelper"
	"github.com/rackspace/gophercloud/testhelper/client"
)

func TestWaitForStatus(t *testing.T) {
	th.SetupHTTP()
	defer th.TeardownHTTP()

	th.Mux.HandleFunc("/servers/4321", func(w http.ResponseWriter, r *http.Request) {
		time.Sleep(2 * time.Second)
		w.Header().Add("Content-Type", "application/json")
		w.WriteHeader(http.StatusOK)
		fmt.Fprintf(w, `
		{
			"server": {
				"name": "the-server",
				"id": "4321",
				"status": "ACTIVE"
			}
		}`)
	})

	err := WaitForStatus(client.ServiceClient(), "4321", "ACTIVE", 0)
	if err == nil {
		t.Errorf("Expected error: 'Time Out in WaitFor'")
	}

	err = WaitForStatus(client.ServiceClient(), "4321", "ACTIVE", 3)
	th.CheckNoErr(t, err)
}


text:
/* global angular */

/**
 * Http method interceptor. Broadcast events for show or hide the loader.
 */
angular
  .module('ng.httpLoader.httpMethodInterceptor', [])

  .provider('httpMethodInterceptor', function () {
    var domains = [],
      whitelistLocalRequests = false;

    /**
     * Add domains to the white list
     *
     * @param {string} domain
     * Added Domain to the white list domains collection
     */
    this.whitelistDomain = function (domain) {
      domains.push(domain);
    };

    /**
     * White list requests to the local domain
     */
    this.whitelistLocalRequests = function () {
      whitelistLocalRequests = true;
    };

    this.$get = [
      '$q',
      '$rootScope',
      function ($q, $rootScope) {
        var numLoadings = 0;

        /**
         * Check if the url domain is on the whitelist
         *
         * @param {string} url
         *
         * @returns {boolean}
         */
        var isUrlOnWhitelist = function (url) {
          if (url.substring(0, 2) !== '//' &&
            url.indexOf('://') === -1 &&
            whitelistLocalRequests) {
            return true;
          }

          for (var i = domains.length; i--;) {
            if (url.indexOf(domains[i]) !== -1) {
              return true;
            }
          }

          return false;
        };

        /**
         * Emit hide loader logic
         *
         * @param {object} config
         * The response configuration
         */
        var checkAndHide = function (config) {
          if (isUrlOnWhitelist(config.url) &&
            (--numLoadings) === 0) {
            $rootScope.$emit('loaderHide', config.method);
          }
        };

        return {
          /**
           * Broadcast the loader show event
           *
           * @param {object} config
           *
           * @returns {object|Promise}
           */
          request: function (config) {
            if (isUrlOnWhitelist(config.url)) {
              numLoadings++;
              $rootScope.$emit('loaderShow', config.method);
            }

            return config || $q.when(config);
          },

          /**
           * Broadcast the loader hide event
           *
           * @param {object} response
           *
           * @returns {object|Promise}
           */
          response: function (response) {
            checkAndHide(response.config);

            return response || $q.when(response);
          },

          /**
           * Handle errors
           *
           * @param {object} response
           *
           * @returns {Promise}
           */
          responseError: function (response) {
            checkAndHide(response.config);

            return $q.reject(response);
          }
        };
      }
    ];
  })

  .config(['$httpProvider', function ($httpProvider) {
    $httpProvider.interceptors.unshift('httpMethodInterceptor');
  }]);


text:
<?php

namespace Sylius\Bundle\AddressingBundle\Validator\Constraints;

use Symfony\Component\Validator\Constraint;

/**
 * Constraint to require a province to be valid.
 *
 * @author Julien Janvier <j.janvier@gmail.com>
 */
class ProvinceAddressConstraint extends Constraint
{
    public $message = 'sylius.address.province.valid';

    public function getTargets()
    {
        return self::CLASS_CONSTRAINT;
    }

    public function validatedBy()
    {
        return 'sylius_province_address_validator';
    }
}


text:
#if defined(_MSC_VER)
#pragma once
#endif

#ifndef PBRT_CAMERAS_ORTHOGRAPHIC_H
#define PBRT_CAMERAS_ORTHOGRAPHIC_H

// cameras/orthographic.h*
#include "pbrt.h"
#include "camera.h"
#include "film.h"

// OrthographicCamera Declarations
class OrthoCamera : public ProjectiveCamera {
public:
    // OrthoCamera Public Methods
    OrthoCamera(const AnimatedTransform &cam2world, const float screenWindow[4],
        float sopen, float sclose, float lensr, float focald, Film *film);
    float GenerateRay(const CameraSample &sample, Ray *) const;
    float GenerateRayDifferential(const CameraSample &sample, RayDifferential *) const;
private:
    // OrthoCamera Private Data
    Vector dxCamera, dyCamera;
};

OrthoCamera *CreateOrthographicCamera(const ParamSet &params,
        const AnimatedTransform &cam2world, Film *film);

#endif // PBRT_CAMERAS_ORTHOGRAPHIC_H


text:
require 'helper'

class TestWorksheetDataBar01 < Minitest::Test
  def setup
    @workbook = WriteXLSX.new(StringIO.new)
    @worksheet = @workbook.add_worksheet('')
  end

  ###############################################################################
  #
  # Tests for WriteXLSX::Worksheet methods.
  #
  #
  def test_data_bar_01
    @worksheet.select

    @worksheet.conditional_formatting(
      'A1',
      :type => 'data_bar'
    )

    @worksheet.assemble_xml_file
    result = got_to_array(@worksheet.instance_variable_get(:@writer).string)

    expected = expected_to_array(expected_xml)
    assert_equal(expected, result)
  end

  def expected_xml
    <<EOS
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
  <dimension ref="A1"/>
  <sheetViews>
    <sheetView tabSelected="1" workbookViewId="0"/>
  </sheetViews>
  <sheetFormatPr defaultRowHeight="15"/>
  <sheetData/>
  <conditionalFormatting sqref="A1">
    <cfRule type="dataBar" priority="1">
      <dataBar>
        <cfvo type="min" val="0"/>
        <cfvo type="max" val="0"/>
        <color rgb="FF638EC6"/>
      </dataBar>
    </cfRule>
  </conditionalFormatting>
  <pageMargins left="0.7" right="0.7" top="0.75" bottom="0.75" header="0.3" footer="0.3"/>
</worksheet>
EOS
  end
end


text:
using NQuery.Symbols;

namespace NQuery.Hosting
{
    public static class NullProviders
    {
        private sealed class NullPropertyProvider : IPropertyProvider
        {
            public IEnumerable<PropertySymbol> GetProperties(Type type)
            {
                ArgumentNullException.ThrowIfNull(type);

                return Enumerable.Empty<PropertySymbol>();
            }
        }

        private sealed class NullMethodProvider : IMethodProvider
        {
            public IEnumerable<MethodSymbol> GetMethods(Type type)
            {
                ArgumentNullException.ThrowIfNull(type);

                return Enumerable.Empty<MethodSymbol>();
            }
        }

        public static readonly IPropertyProvider PropertyProvider = new NullPropertyProvider();
        public static readonly IMethodProvider MethodProvider = new NullMethodProvider();
    }
}


text:
package com.xsolla.android.sdk.data.model.sellable;

public class XSubscriptionActive {

    private String id;//"id":"187fc9f4",
    private String date_next_charge;//"date_next_charge":"2016-10-07 12:19:56",
    private String date_plan_change;//"date_plan_change":"2016-10-07 12:19:56",
    private boolean is_possible_renew;//"is_possible_renew":true

    @Override
    public String toString() {
        return "XSubscriptionActive{" +
                "id='" + id + '\'' +
                ", date_next_charge='" + date_next_charge + '\'' +
                ", date_plan_change='" + date_plan_change + '\'' +
                ", is_possible_renew=" + is_possible_renew +
                '}';
    }
}


text:
import six

import pfp.bitwrap as bitwrap
import pfp.errors as errors
import pfp.utils as utils
import pfp.fields

class BaseFunction(object):
	pass

class Function(BaseFunction):
	"""A class to maintain function state and arguments"""
	def __init__(self, return_type, params, scope):
		"""
		Initialized the function. The Function body is intended to be set
		after the Function object has been created.
		"""
		super(Function, self).__init__()

		self.name = None
		self.body = None

		# note that the _scope is determined by where the function is
		# declared, not where it is called from
	 	# TODO see the comment in Scope.clone for potential future work/bugs
		self._scope = scope.clone()
		self._params = params

	def call(self, args, ctxt, scope, stream, interp, coord, no_cast=False):
		# the no_cast arg does nothing for interpreted functions

		if self.body is None:
			raise errors.InvalidState(coord)

		# scopes will be pushed and popped by the Compound node handler!
		# If a return statement is interpreted in the function,
		# the Compound statement will pop the scope before the exception
		# bubbles up to here

		self._scope.push()

		params = self._params.instantiate(self._scope, args, interp)

		ret_val = None
		try:
			interp._handle_node(self.body, self._scope, ctxt, stream)
		except errors.InterpReturn as e:
			# TODO do some type checking on the return value??
			# perhaps this should be done when initially traversing
			# the AST of the function... a dry run traversing it to find
			# return values??
			ret_val = e.value
		finally:
			self._scope.pop()

		return ret_val

class NativeFunction(BaseFunction):
	"""A class for native functions"""
	def __init__(self, name, func, ret, send_interp=False):
		"""
		"""
		super(NativeFunction, self).__init__()
		self._pfp__name = name
		self.name = name
		self.func = func
		self.ret = ret
		self.send_interp = send_interp

	def call(self, args, ctxt, scope, stream, interp, coord, no_cast=False):
		if self.send_interp:
			res = self.func(args, ctxt, scope, stream, coord, interp)
		else:
			res = self.func(args, ctxt, scope, stream, coord)

		if no_cast:
			res_field = res
		elif utils.is_str(res) and self.ret == pfp.fields.Array:
			tmp_stream = bitwrap.BitwrappedStream(six.BytesIO(res))
			res_field = pfp.fields.Array(len(res), pfp.fields.Char, tmp_stream)
		elif utils.is_str(self.ret) and scope.get_type(self.ret) is not None:
			# TODO should we do any type-checking here to make sure that the
			# return value matches what is declared as the return type?
			res_field = res
		else:
			res_field = self.ret()
			res_field._pfp__set_value(res)

		return res_field

class ParamListDef(object):
	"""docstring for ParamList"""
	def __init__(self, params, coords):
		super(ParamListDef, self).__init__()

		self._params = params
		self._coords = coords

	def instantiate(self, scope, args, interp):
		"""Create a ParamList instance for actual interpretation

		:args: TODO
		:returns: A ParamList object

		"""
		param_instances = []

		BYREF = "byref"

		# TODO are default values for function parameters allowed in 010?
		for param_name, param_cls in self._params:
			# we don't instantiate a copy of byref params
			if getattr(param_cls, "byref", False):
				param_instances.append(BYREF)
			else:
				field = param_cls()
				field._pfp__name = param_name
				param_instances.append(field)

		if len(args) != len(param_instances):
			raise errors.InvalidArguments(
				self._coords,
				[x.__class__.__name__ for x in args],
				[x.__class__.__name__ for x in param_instances]
			)

		# TODO type checking on provided types

		for x in six.moves.range(len(args)):
			param = param_instances[x]
			if param is BYREF:
				param = args[x]
				param_instances[x] = param
				scope.add_local(self._params[x][0], param)
			else:
				param._pfp__set_value(args[x])
				scope.add_local(param._pfp__name, param)
			param._pfp__interp = interp

		return ParamList(param_instances)

class ParamList(object):
	"""Used for when a function is actually called. See ParamListDef
	for how function definitions store function parameter definitions
	"""

	def __init__(self, params):
		super(ParamList, self).__init__()
		self.params = params

		# for use by __getitem__
		self._params_map = {}
		for param in self.params:
			self._params_map[param._pfp__name] = param

	def __iter__(self):
		"""Return an iterator that will iterate through each of the
		parameters in order

		"""
		for param in self.params:
			yield param

	def __getitem__(self, name):
		if name in self._params_map:
			return self._params_map[name]
		raise KeyError(name)

	# def __setitem__???


text:
    <textarea cols="75" rows="10" class="richtext-fix"></textarea>

            Line width
            <input type="number" min="1" name="borderWidth" />

            Line color

                <input type="text" name="strokeColor" id="strokeColor" />
                <input type="color" name="strokeColorPicker" id="strokeColorPicker" />

                <input type="button" class="btn-popup-save" value="Save" />
                <input type="button" class="btn-popup-cancel" value="Cancel" />
                <input type="button" class="btn-popup-delete" value="Delete" />

    <input type="hidden" name="changed" value="false" />


text:
package org.hibernate.test.typeoverride;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertSame;

import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
import org.hibernate.dialect.Dialect;
import org.hibernate.dialect.PostgreSQL81Dialect;
import org.hibernate.dialect.PostgreSQLDialect;
import org.hibernate.dialect.SybaseASE15Dialect;
import org.hibernate.dialect.SybaseDialect;
import org.hibernate.testing.SkipForDialect;
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase;
import org.hibernate.type.descriptor.sql.BlobTypeDescriptor;
import org.hibernate.type.descriptor.sql.IntegerTypeDescriptor;
import org.hibernate.type.descriptor.sql.SqlTypeDescriptor;
import org.hibernate.type.descriptor.sql.VarcharTypeDescriptor;
import org.junit.Test;

/**
 * @author Gail Badner
 */
public class TypeOverrideTest extends BaseCoreFunctionalTestCase {
	@Override
	public String[] getMappings() {
		return new String[] { "typeoverride/Entity.hbm.xml" };
	}

	@Override
	public void configure(Configuration cfg) {
		cfg.registerTypeOverride( StoredPrefixedStringType.INSTANCE );
	}

	@Test
	public void testStandardBasicSqlTypeDescriptor() {
		// no override
		assertSame( IntegerTypeDescriptor.INSTANCE, remapSqlTypeDescriptor( IntegerTypeDescriptor.INSTANCE ) );

		// A few dialects explicitly override BlobTypeDescriptor.DEFAULT
		if ( PostgreSQL81Dialect.class.isInstance( getDialect() ) || PostgreSQLDialect.class.isInstance( getDialect() ) )  {
			assertSame(
					BlobTypeDescriptor.BLOB_BINDING,
					getDialect().remapSqlTypeDescriptor( BlobTypeDescriptor.DEFAULT )
			);
		}
		else if (SybaseDialect.class.isInstance( getDialect() )) {
			assertSame(
					BlobTypeDescriptor.PRIMITIVE_ARRAY_BINDING,
					getDialect().remapSqlTypeDescriptor( BlobTypeDescriptor.DEFAULT )
			);
		}
		else {
			assertSame(
					BlobTypeDescriptor.DEFAULT,
					getDialect().remapSqlTypeDescriptor( BlobTypeDescriptor.DEFAULT )
			);
		}
	}

	@Test
	public void testNonStandardSqlTypeDescriptor() {
		// no override
		SqlTypeDescriptor sqlTypeDescriptor = new IntegerTypeDescriptor() {
			@Override
			public boolean canBeRemapped() {
				return false;
			}
		};
		assertSame( sqlTypeDescriptor, remapSqlTypeDescriptor( sqlTypeDescriptor ) );
	}

	@Test
	public void testDialectWithNonStandardSqlTypeDescriptor() {
		assertNotSame( VarcharTypeDescriptor.INSTANCE, StoredPrefixedStringType.INSTANCE.getSqlTypeDescriptor() );
		final Dialect dialect = new H2DialectOverridePrefixedVarcharSqlTypeDesc();
		final SqlTypeDescriptor remapped = remapSqlTypeDescriptor( dialect, StoredPrefixedStringType.PREFIXED_VARCHAR_TYPE_DESCRIPTOR );
		assertSame( VarcharTypeDescriptor.INSTANCE, remapped );
	}

	private SqlTypeDescriptor remapSqlTypeDescriptor(SqlTypeDescriptor sqlTypeDescriptor) {
		return remapSqlTypeDescriptor( sessionFactory().getDialect(), sqlTypeDescriptor );
	}

	private SqlTypeDescriptor remapSqlTypeDescriptor(Dialect dialect, SqlTypeDescriptor sqlTypeDescriptor) {
		return dialect.remapSqlTypeDescriptor( sqlTypeDescriptor );
	}

	@Test
	public void testInsert() {
		Session s = openSession();
		s.getTransaction().begin();
		Entity e = new Entity( "name" );
		s.save( e );
		s.getTransaction().commit();
		s.close();

		s = openSession();
		s.getTransaction().begin();
		e = ( Entity ) s.get( Entity.class, e.getId() );
		assertFalse( e.getName().startsWith( StoredPrefixedStringType.PREFIX ) );
		assertEquals( "name", e.getName() );
		s.delete( e );
		s.getTransaction().commit();
		s.close();
	}

	@Test
    @SkipForDialect( value = SybaseASE15Dialect.class, jiraKey = "HHH-6426")
	public void testRegisteredFunction() {
		Session s = openSession();
		s.getTransaction().begin();
		Entity e = new Entity( "name " );
		s.save( e );
		s.getTransaction().commit();
		s.close();

		s = openSession();
		s.getTransaction().begin();
		e = ( Entity ) s.get( Entity.class, e.getId() );
		assertFalse( e.getName().startsWith( StoredPrefixedStringType.PREFIX ) );
		assertEquals( "name ", e.getName() );
		s.getTransaction().commit();
		s.close();

		s = openSession();
		s.getTransaction().begin();
		s.delete( e );
		s.getTransaction().commit();
		s.close();
	}
}


text:
package org.apache.dubbo.metadata.definition;

import org.apache.dubbo.metadata.definition.builder.TypeBuilder;
import org.apache.dubbo.metadata.definition.model.TypeDefinition;

import java.lang.reflect.Type;
import java.util.Map;

/**
 * test for sort
 */
public class TestTypeBuilder implements TypeBuilder {
    // it is smaller than the implements of TypeBuilder
    public int getPriority(){
        return -3;
    }

    @Override
    public boolean accept(Type type, Class<?> clazz) {
        return false;
    }

    @Override
    public TypeDefinition build(Type type, Class<?> clazz, Map<Class<?>, TypeDefinition> typeCache) {
        return null;
    }
}


text:
package com.leon.channel.reader;

import com.leon.channel.common.ChannelConstants;
import com.leon.channel.common.V2SchemeUtil;
import com.leon.channel.common.verify.ApkSignatureSchemeV2Verifier;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.Map;

/**
 * Created by leontli on 17/1/19.
 */

public class IdValueReader {

    /**
     * get string value by id
     *
     * @param channelFile
     * @param id
     * @return
     */
    public static String getStringValueById(File channelFile, int id) {
        if (channelFile == null || !channelFile.exists() || !channelFile.isFile()) {
            return null;
        }

        byte[] buffer = getByteValueById(channelFile, id);
        try {
            if (buffer != null && buffer.length > 0) {
                return new String(buffer, ChannelConstants.CONTENT_CHARSET);
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * get byte[] value from apk by id
     *
     * @param channelFile
     * @param id
     * @return
     */
    public static byte[] getByteValueById(File channelFile, int id) {
        if (channelFile == null || !channelFile.exists() || !channelFile.isFile()) {
            return null;
        }

        ByteBuffer value = getByteBufferValueById(channelFile, id);
        System.out.println("getByteValueById , id = " + id + " , value = " + value);
        if (value != null) {
            return Arrays.copyOfRange(value.array(), value.arrayOffset() + value.position(), value.arrayOffset() + value.limit());
        }
        return null;
    }

    /**
     * get ByteBuffer value from apk by id
     *
     * @param channelFile
     * @param id
     * @return
     */
    public static ByteBuffer getByteBufferValueById(File channelFile, int id) {
        if (channelFile == null || !channelFile.exists() || !channelFile.isFile()) {
            return null;
        }

        Map<Integer, ByteBuffer> idValueMap = getAllIdValueMap(channelFile);
        System.out.println("getByteBufferValueById , destApk " + channelFile.getAbsolutePath() + " IdValueMap = " + idValueMap);

        if (idValueMap != null) {
            return idValueMap.get(id);
        }

        return null;
    }

    /**
     * find all Id-Value Pair from Apk
     *
     * @param channelFile
     * @return
     */
    public static Map<Integer, ByteBuffer> getAllIdValueMap(File channelFile) {
        if (channelFile == null || !channelFile.exists() || !channelFile.isFile()) {
            return null;
        }

        try {
            ByteBuffer apkSigningBlock = V2SchemeUtil.getApkSigningBlock(channelFile);
            return V2SchemeUtil.getAllIdValue(apkSigningBlock);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ApkSignatureSchemeV2Verifier.SignatureNotFoundException e) {
            e.printStackTrace();
        }

        return null;
    }
}


text:
const ip = require('ip');
const winston = require('winston-debug');
const winstonWrapper = require('winston-meta-wrapper');

const log = winstonWrapper(winston);
log.addMeta({
  module: 'stun:attributes',
});

const IPv4 = 0x01;
const IPv6 = 0x02;

const xor = (a, b) => {
  const data = [];
  let aCopy = a.slice(0);
  let bCopy = b.slice(0);

  if (bCopy.length > aCopy.length) {
    const tmp = aCopy;
    aCopy = bCopy;
    bCopy = tmp;
  }

  for (let i = 0, len = aCopy.length; i < len; i += 1) {
    data.push(aCopy[i] ^ bCopy[i]); // eslint-disable-line no-bitwise
  }

  return new Buffer(data);
};

const encode = (address, port) => {
  // checks
  if (address === undefined || port === undefined) {
    const attrError = 'invalid address attribute';
    log.error(attrError);
    throw new Error(attrError);
  }
  if (!ip.isV4Format(address) && !ip.isV6Format(address)) {
    const hostError = 'invalid address host';
    log.error(hostError);
    throw new Error(hostError);
  }
  if (port < 0 || port > 65536) {
    const portError = 'invalid address port';
    log.error(portError);
    throw new Error(portError);
  }
  // create family type
  const familyByte = new Buffer(1);
  if (ip.isV4Format(address)) {
    familyByte.writeUInt8(IPv4);
  } else {
    familyByte.writeUInt8(IPv6);
  }
  // create address bytes
  const addressBytes = ip.toBuffer(address);
  // create null byte
  const nullByte = new Buffer(1);
  nullByte.writeUInt8(0, 0);
  // create port bytes
  const portBytes = new Buffer(2);
  portBytes.writeUInt16BE(port, 0);
  // concat
  return Buffer.concat([nullByte, familyByte, portBytes, addressBytes]);
};

const encodeXor = (address, port, magic, tid) => {
  // checks
  if (address === undefined || port === undefined) {
    const attrError = 'invalid address attribute';
    log.error(attrError);
    throw new Error(attrError);
  }
  if (!ip.isV4Format(address) && !ip.isV6Format(address)) {
    const hostError = 'invalid address host';
    log.error(hostError);
    throw new Error(hostError);
  }
  if (port < 0 || port > 65536) {
    const portError = 'invalid address port';
    log.error(portError);
    throw new Error(portError);
  }
  if (magic === undefined || tid === undefined) {
    const keyError = 'invalid xor keys';
    log.error(keyError);
    throw new Error(keyError);
  }
  // magic and tid bytes -- needed for xor mapping
  const magicBytes = new Buffer(4);
  magicBytes.writeUInt32BE(magic);
  const tidBytes = new Buffer(12);
  tidBytes.writeUInt32BE(0);
  tidBytes.writeUInt32BE(0, 4);
  tidBytes.writeUInt32BE(tid, 8);
  // create family type
  const familyByte = new Buffer(1);
  if (ip.isV4Format(address)) {
    familyByte.writeUInt8(IPv4);
  } else {
    familyByte.writeUInt8(IPv6);
  }
  // create xaddress bytes
  const addressBytes = ip.toBuffer(address);
  const xaddressBytes = xor(addressBytes, ip.isV4Format(address) ?
    magicBytes : Buffer.concat([magicBytes, tidBytes]));
  // create null byte
  const nullByte = new Buffer(1);
  nullByte.writeUInt8(0, 0);
  // create xport bytes
  const portBytes = new Buffer(2);
  portBytes.writeUInt16BE(port, 0);
  const xportBytes = xor(portBytes, magicBytes.slice(0, 2));
  // concat
  return Buffer.concat([nullByte, familyByte, xportBytes, xaddressBytes]);
};

const decode = (bytes) => {
  const family = (bytes.readUInt8(1) === IPv4) ? 4 : 6;
  const portBytes = bytes.slice(2, 4); // LE
  const addressBytes = bytes.slice(4, family === 4 ? 8 : 20); // LE
  const result = {
    family,
    port: portBytes.readUInt16BE(0),
    address: ip.toString(addressBytes, 0, family),
  };
  return result;
};

const decodeXor = (bytes, magicBytes, tidBytes) => {
  const family = (bytes.readUInt8(1) === IPv4) ? 4 : 6;
  const xportBytes = bytes.slice(2, 4); // LE
  const portBytes = xor(xportBytes, magicBytes.slice(0, 2));
  const xaddressBytes = bytes.slice(4, family === 4 ? 8 : 20); // LE
  const addressBytes = xor(xaddressBytes, family === 4 ?
    magicBytes : Buffer.concat([magicBytes, tidBytes]));
  const result = {
    family,
    port: portBytes.readUInt16BE(0),
    address: ip.toString(addressBytes, 0, family),
  };
  return result;
};

exports.encode = encode;
exports.encodeXor = encodeXor;
exports.decode = decode;
exports.decodeXor = decodeXor;


text:
<?php
/*! index.php | Crashdump Browser | Adam Perry | opensource.org/licenses/MIT */
// Renders initial page
// This is the only page directly accessed by the user; the rest of the rendering and heavy lifting is performed in the JS.
include_once("includes/db.inc.php");
include_once("includes/install.inc.php"); // attempt to install in case this is the first run

$projectSelect = "";
$metaColumns = "";
$messages = "";
$exceptions = array();
$files = array();
$functions = array();
$errorTypes = db::getErrorTypes();
foreach($errorTypes as $e) {
   if (empty($files[$e[DB_COL_PROJECTNAME]])) {
      $exceptions[$e[DB_COL_PROJECTNAME]] = array();
      $files[$e[DB_COL_PROJECTNAME]] = array();
      $functions[$e[DB_COL_PROJECTNAME]] = array();
   }
   $error = explode(ERROR_DELIMITER, $e[DB_COL_ERRORNAME]);
   $file = substr($error[1], 0, strrpos($error[1], ":"));
   if (!empty($error[0]) && !in_array($error[0], $exceptions[$e[DB_COL_PROJECTNAME]])) {
      $exceptions[$e[DB_COL_PROJECTNAME]][$e[DB_COL_ERRORID]] = $error[0];
   } else if (!empty($error[0])) {
      $key = array_search($error[0], $exceptions[$e[DB_COL_PROJECTNAME]]);
      $exceptions[$e[DB_COL_PROJECTNAME]][$key .",". $e[DB_COL_ERRORID]] = $error[0];
      unset($exceptions[$e[DB_COL_PROJECTNAME]][$key]);
   }
   if (!empty($file) && !in_array($file, $files[$e[DB_COL_PROJECTNAME]])) {
      $files[$e[DB_COL_PROJECTNAME]][$e[DB_COL_ERRORID]] = $file;
   } else if (!empty($file)) {
      $key = array_search($file, $files[$e[DB_COL_PROJECTNAME]]);
      $files[$e[DB_COL_PROJECTNAME]][$key .",". $e[DB_COL_ERRORID]] = $file;
      unset($files[$e[DB_COL_PROJECTNAME]][$key]);
   }
   if (!empty($error[2]) && !in_array($error[2], $functions[$e[DB_COL_PROJECTNAME]])) {
      $functions[$e[DB_COL_PROJECTNAME]][$e[DB_COL_ERRORID]] = $error[2];
   } else if (!empty($error[2])) {
      $key = array_search($error[2], $functions[$e[DB_COL_PROJECTNAME]]);
      $functions[$e[DB_COL_PROJECTNAME]][$key .",". $e[DB_COL_ERRORID]] = $error[2];
      unset($functions[$e[DB_COL_PROJECTNAME]][$key]);
   }
}
$exceptionSelect = createSelect($exceptions);
$fileSelect = createSelect($files);
$functionSelect = createSelect($functions);
if (defined("MULTIPROJECT") && MULTIPROJECT) {
   $projectSelect = '<option value="">All projects</option>';
   $projects = db::getProjects();
   foreach($projects as $project) {
      $projectSelect .= '<option value="'. htmlspecialchars($project[DB_COL_PROJECTID]) .'">'. htmlspecialchars($project[DB_COL_PROJECTNAME]) .'</option>';
   }
   $projectSelect = '
Current Project: <select id="projSelect">'. $projectSelect .'</select>
';
} else {
   $projectSelect = '<input type="hidden" id="projSelect" value=""/>';
}
if (defined("METADATA") && METADATA) {
   $metadata = explode(",", METADATA);
   foreach($metadata as $m) {
      $metaColumns .= ''. $m .'	';
   }
}
if (!file_exists(REPORT_DIR)) {
   $messages = 'Your reports directory is configured incorrectly! This will prevent you from receiving crash reports. Please see step 7 of the README for instructions on correcting this.';
}

function createSelect($selectData) {
   $select = "";
   ksort($selectData);
   foreach($selectData as $project => $projectData) {
      if (defined("MULTIPROJECT") && MULTIPROJECT && count($selectData) > 1) {
         $select .= '<optgroup label="'. htmlspecialchars($project) .'">';
      }
      ksort($projectData);
      foreach($projectData as $key => $data) {
         $select .= '<option value="'. $key .'">'. htmlspecialchars($data) .'</option>';
      }
      if (defined("MULTIPROJECT") && MULTIPROJECT && count($selectData) > 1) {
         $select .= '</optgroup>';
      }
   }
   return $select;
}

?><!DOCTYPE HTML>

   <title>Crashdump Browser</title>
   <link rel="stylesheet" type="text/css" href="media/<?php echo THEME; ?>"/>

   <?php echo $projectSelect; ?>

Crashdump Browser

<?php echo $messages; ?>

                  Min version: <input type="text" id="overviewMinVersion" data-sync="minversion"/>

                  Max version: <input type="text" id="overviewMaxVersion" data-sync="maxversion"/>

                  Min count: <input type="text" id="minCount"/>

                  Max count: <input type="text" id="maxCount"/>

                  Status:

                  <select name="status" multiple="multiple">
                     <option value="<?php echo STATUS_NEW; ?>" selected="selected">New</option>
                     <option value="<?php echo STATUS_REOPENED; ?>" selected="selected">Reopened</option>
                     <option value="<?php echo STATUS_INPROGRESS; ?>" selected="selected">In Progress</option>
                     <option value="<?php echo STATUS_FIXED; ?>">Fixed</option>
                     <option value="<?php echo STATUS_WONTFIX; ?>">Won't Fix</option>
                     <option value="<?php echo STATUS_DUPLICATE; ?>">Duplicate</option>
                  </select>

                  Error Type:

                  <select name="exception" multiple="multiple">
                     <?php echo $exceptionSelect; ?>
                  </select>

                  File:

                  <select name="file" multiple="multiple">
                     <?php echo $fileSelect; ?>
                  </select>

                  Function:

                  <select name="function" multiple="multiple">
                     <?php echo $functionSelect; ?>
                  </select>

               <input type="submit" id="filterGrid" value="Apply filters"/>

               Bulk actions:
               <select id="overviewBulk">
                  <option value="">Select...</option>
                  <option value="<?php echo ACTION_STATUS_INPROGRESS; ?>">Move to In Progress</option>
                  <option value="<?php echo ACTION_STATUS_FIXED; ?>">Move to Fixed</option>
                  <option value="<?php echo ACTION_STATUS_WONTFIX; ?>">Move to Won't Fix</option>
                  <option value="<?php echo ACTION_STATUS_REOPENED; ?>">Move to Reopened</option>
                  <option value="<?php echo ACTION_STATUS_DUPLICATE; ?>">Mark as Duplicate...</option>

               </select>

               Click on a row for more details on that error.

                  <input type="checkbox" class="topCheck"/>
                  Actions
                  <th title="Internal error ID number" class="sortable" data-sort="<?php echo DB_COL_ERRORID; ?>">Error ID
                  Error Count
                  <th title="Current working status of this error" class="sortable" data-sort="<?php echo DB_COL_STATUS; ?>">Status
                  <?php if (MULTIPROJECT) { ?><th title="Project ID" class="sortable" data-sort="<?php echo DB_COL_PROJECTID; ?>">Project	<?php } ?>
                  Error Type
                  Line
                  Function
                  First encountered
                  Last encountered
                  Earliest version
                  Latest version

<input type="submit" value="Generate test report"/>

         <form action="report.php" method="POST" enctype="multipart/form-data"><input type="file" name="report"/><input type="submit" value="Manually submit report"/></form>

            Back to Overview >

                  Min version: <input type="text" id="errorMinVersion" data-sync="minversion"/>

                  Max version: <input type="text" id="errorMaxVersion" data-sync="maxversion"/>

            <input type="submit" id="filterError" value="Apply filters"/>

               Click on a row for more details on that report.

                  <th title="Internal report ID number, for reference only" class="sortable sortDown" data-sort="<?php echo DB_COL_REPORTID; ?>">Report ID
                  <th title="Date at which the error was encountered" class="sortable" data-sort="<?php echo DB_COL_TIMESTAMP; ?>">Date
                  <th title="Version in which the error was encountered" class="sortable" data-sort="<?php echo DB_COL_INTVERSION; ?>">Version
                  <?php echo $metaColumns; ?>

            Back to Error View >

               Warning: The files listed below are user-submitted. Be aware that files may be submitted by malicious users!

                  View
                  Download
                  Filename
                  Filesize
                  Compressed Filesize

Mark as Duplicate:

            Select the duplicated error from the suggested list below, or type the error ID into the box and click on the submit button.

            Error ID: <input type="text" id="similarId"/> <input type="submit" id="similarSubmit" value="Use this error ID"/>

         <input type="submit" id="similarCancel" value="Cancel"/>


text:
using System;
using System.IO;

namespace Correspondence.Data
{
    public abstract class StreamBasedDataStructure : IDisposable
    {
        private byte[] _readBuffer = new byte[8];
        protected Stream _stream;

        protected StreamBasedDataStructure(Stream stream)
        {
            _stream = stream;
        }

        public void Dispose()
        {
            _stream.Dispose();
        }

        protected void SeekTo(long position)
        {
            _stream.Seek(position, SeekOrigin.Begin);
        }

        protected byte ReadByte()
        {
            return (byte)_stream.ReadByte();
        }

        protected void WriteByte(byte value)
        {
            _stream.WriteByte(value);
        }

        protected int ReadInt()
        {
            _stream.Read(_readBuffer, 0, 4);
            return BitConverter.ToInt32(_readBuffer, 0);
        }

        protected void WriteInt(int value)
        {
            byte[] writeBuffer = BitConverter.GetBytes(value);
            _stream.Write(writeBuffer, 0, 4);
        }

        protected long ReadLong()
        {
            _stream.Read(_readBuffer, 0, 8);
            return BitConverter.ToInt64(_readBuffer, 0);
        }

        protected void WriteLong(long value)
        {
            byte[] writeBuffer = BitConverter.GetBytes(value);
            _stream.Write(writeBuffer, 0, 8);
        }

        protected void ReadBytes(byte[] data)
        {
            _stream.Read(data, 0, data.Length);
        }

        protected void WriteBytes(byte[] data)
        {
            _stream.Write(data, 0, data.Length);
        }

        public long GetSize()
        {
            return _stream.Length;
        }
    }
}


text:
import scrapy

class PoliticlsWatchSpider(scrapy.Spider):
    name = "politicl_watch"

    def __init__(self, name=None, **kwargs):
        from cwpoliticl.database_factory import DatabaseFactory, CollectionTypes
        database_factory = DatabaseFactory(kwargs['host'], kwargs['port'],
                                           kwargs['user'], kwargs['passwd'],
                                           kwargs['db'], kwargs['collection_name'])

        self._cache_db = database_factory.get_database(CollectionTypes.cache)
        self._history_db = database_factory.get_database(CollectionTypes.history)

        from cwpoliticl.spiders.dispatch.spider_watch_dispatch import SpiderWatchDispatch
        self.watch_dispatch = SpiderWatchDispatch()

        # Dynamic the domains and start url.
        self.allowed_domains = self.watch_dispatch.get_allowed_domains()
        self.start_urls = self.watch_dispatch.get_pagination_websites()

        super(PoliticlsWatchSpider, self).__init__(name, **kwargs)

    @classmethod
    def from_crawler(cls, crawler, *args, **kwargs):
        return super(PoliticlsWatchSpider, cls).from_crawler(crawler,
                                                             args,
                                                             host=crawler.settings.get('SQL_HOST'),
                                                             port=crawler.settings.get('SQL_PORT'),
                                                             user=crawler.settings.get('SQL_USER'),
                                                             passwd=crawler.settings.get('SQL_PASSWD'),
                                                             db=crawler.settings.get('SQL_DB'),
                                                             collection_name=crawler.settings.get(
                                                                 'SQL_COLLECTION_NAME')
                                                             )

    # This methond is entry point
    def parse(self, response):
        self.watch_dispatch.parse_from_pagination(response.url, response, self._cache_db, self._history_db)


text:
namespace Boilerplate.Common.Exceptions
{
    using System;

    public class NotFoundException : Exception
    {
        public NotFoundException(string format, params object[] arguments)
        : base(string.Format(format, arguments))
        {
        }
    }
}


text:
package common

import (
	"bytes"
)

// Fingerprint returns the first 6 bytes of a byte slice.
// If the slice is less than 6 bytes, the fingerprint
// contains trailing zeroes.
func Fingerprint(slice []byte) []byte {
	fingerprint := make([]byte, 6)
	copy(fingerprint, slice)
	return fingerprint
}

func IsZeros(slice []byte) bool {
	for _, byt := range slice {
		if byt != byte(0) {
			return false
		}
	}
	return true
}

func RightPadBytes(slice []byte, l int) []byte {
	if l < len(slice) {
		return slice
	}
	padded := make([]byte, l)
	copy(padded[0:len(slice)], slice)
	return padded
}

func LeftPadBytes(slice []byte, l int) []byte {
	if l < len(slice) {
		return slice
	}
	padded := make([]byte, l)
	copy(padded[l-len(slice):], slice)
	return padded
}

func TrimmedString(b []byte) string {
	trimSet := string([]byte{0})
	return string(bytes.TrimLeft(b, trimSet))

}


text:
body{
	background: #081E2D;
	color: #fff;
}
.panel.panel-custom{
/*	cursor: pointer;*/
	background-clip: content-box;
/*	border:2px dashed #0071BF;*/
	margin-top: 20%;
}
.panel.panel-custom:hover{
	border-style: solid;
}
.panel.panel-custom .panel-heading img{
	margin: 0 auto;
	width: 250px;
}
.panel.panel-custom .panel-body{
	background: #0071BF;
	color: #fff;
}


text:
  A fairly simple rails engine that takes your Rails locale and makes it available
  in your Javascript.
  All you have to do is add this to your Gemfile, mount the engine and include the javascript locale in
  your page.

## Examples

  add the gem to your Gemfile

  ```
  gem 'locale_js'
  ```

  mount the engine in our routes.rb

  ```
  mount LocaleJs::Engine => '/i18n'
  ```

  then add this to your application layout

  ```
  <script src="/i18n/locale/<%= I18n.locale %>.js"></script>
  ```

  Populate your locale file as normal..

  ```
  en:
    hello: "Hello World"
    foo: "%{foo} test"
    bar:
      baz: "The craic is %{craic}"
  ```

  You can then translate strings in your JS just like I18n...

  ```
  I18n.t('hello')
  => 'Hello World'

  I18n.t('foo', {foo: 'bar'})
  => 'bar test'

  I18n.t('bar.baz', {craic: 'mighty!'})
  => 'The craic is mighty!'
  ```

## Requirements

  Rails 3.0 or greater

## Copyright

Copyright (c) 2012 John Butler

See LICENSE.txt for details.


text:
#pragma once
#include <aws/email/SES_EXPORTS.h>
#include <aws/email/SESRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace SES
{
namespace Model
{

  /**
   *
Represents a request to begin email address verification with Amazon SES. For
   * information about email address verification, see the Amazon
   * SES Developer Guide.

See Also:
   AWS
   * API Reference

   */
  class AWS_SES_API VerifyEmailAddressRequest : public SESRequest
  {
  public:
    VerifyEmailAddressRequest();

    // Service request name is the Operation name which will send this request out,
    // each operation should has unique request name, so that we can get operation's name from this request.
    // Note: this is not true for response, multiple operations may have the same response name,
    // so we can not get operation's name from response.
    inline virtual const char* GetServiceRequestName() const override { return "VerifyEmailAddress"; }

    Aws::String SerializePayload() const override;

  protected:
    void DumpBodyToUrl(Aws::Http::URI& uri ) const override;

  public:

    /**
     *
The email address to be verified.

     */
    inline const Aws::String& GetEmailAddress() const{ return m_emailAddress; }

    /**
     *
The email address to be verified.

     */
    inline void SetEmailAddress(const Aws::String& value) { m_emailAddressHasBeenSet = true; m_emailAddress = value; }

    /**
     *
The email address to be verified.

     */
    inline void SetEmailAddress(Aws::String&& value) { m_emailAddressHasBeenSet = true; m_emailAddress = std::move(value); }

    /**
     *
The email address to be verified.

     */
    inline void SetEmailAddress(const char* value) { m_emailAddressHasBeenSet = true; m_emailAddress.assign(value); }

    /**
     *
The email address to be verified.

     */
    inline VerifyEmailAddressRequest& WithEmailAddress(const Aws::String& value) { SetEmailAddress(value); return *this;}

    /**
     *
The email address to be verified.

     */
    inline VerifyEmailAddressRequest& WithEmailAddress(Aws::String&& value) { SetEmailAddress(std::move(value)); return *this;}

    /**
     *
The email address to be verified.

     */
    inline VerifyEmailAddressRequest& WithEmailAddress(const char* value) { SetEmailAddress(value); return *this;}

  private:

    Aws::String m_emailAddress;
    bool m_emailAddressHasBeenSet;
  };

} // namespace Model
} // namespace SES
} // namespace Aws


text:
<?php

/**
 * Returns information about a file path
 *
 * @phpstub
 *
 * @param string $path
 * @param int $options
 *
 * @return mixed If the  parameter is not passed, an
 *               associative ``array`` containing the following elements is
 *               returned:
 *               , ,
 *               (if any), and .
 */
function pathinfo($path, $options = false)
{
}


text:
<?php

    namespace app\assets;

    use yii\web\AssetBundle;

    class WowjsAsset extends AssetBundle
    {
        public $sourcePath = '@bower/wowjs';

        public $css = [
            'css/libs/animate.css',
        ];
        public $js = [
            'dist/wow.min.js',
        ];
        public $jsOptions = [

        ];
    }


text:
package com.allanbank.mongodb.builder;

import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;

import java.awt.Point;
import java.awt.geom.Point2D;

import org.junit.Test;

import com.allanbank.mongodb.bson.builder.BuilderFactory;
import com.allanbank.mongodb.bson.builder.DocumentBuilder;

/**
 * AggregationGeoNearTest provides tests for the {@link AggregationGeoNear}
 * class.
 *
 * @copyright 2013, Allanbank Consulting, Inc., All Rights Reserved
 */
@SuppressWarnings("boxing")
public class AggregationGeoNearTest {

    /**
     * Test method for {@link AggregationGeoNear}.
     */
    @Test
    public void testAggregationGeoNearFull() {
        final Point2D location = new Point(1, 2);

        final AggregationGeoNear geoNear = AggregationGeoNear.builder()
                .location(location).distanceField("dist")
                .distanceMultiplier(1.2).limit(123).locationField("loc")
                .maxDistance(12345.6).query(BuilderFactory.start().add("a", 2))
                .spherical().uniqueDocs(false).build();

        assertThat(geoNear.getLocation(), is(location));
        assertThat(geoNear.getDistanceField(), is("dist"));
        assertThat(geoNear.getDistanceMultiplier(), is(1.2));
        assertThat(geoNear.getLimit(), is(123L));
        assertThat(geoNear.getLocationField(), is("loc"));
        assertThat(geoNear.getMaxDistance(), is(12345.6));
        assertThat(geoNear.getQuery(), is(BuilderFactory.start().add("a", 2)
                .build()));
        assertThat(geoNear.isSpherical(), is(true));
        assertThat(geoNear.isUniqueDocs(), is(false));

        final DocumentBuilder expected = BuilderFactory.start();
        expected.pushArray("near").add(1).add(2);
        expected.add("distanceField", "dist");
        expected.add("spherical", true);
        expected.add("uniqueDocs", false);

        expected.add("limit", 123L);
        expected.add("maxDistance", 12345.6);
        expected.add("query", BuilderFactory.start().add("a", 2));
        expected.add("distanceMultiplier", 1.2);
        expected.add("includeLocs", "loc");

        assertThat(geoNear.asDocument(), is(expected.build()));
    }

    /**
     * Test method for {@link AggregationGeoNear}.
     */
    @Test
    public void testAggregationGeoNearMinimal() {
        final Point2D location = new Point(1, 2);

        final AggregationGeoNear geoNear = AggregationGeoNear.builder()
                .location(location).distanceField("dist").build();

        assertThat(geoNear.getLocation(), is(location));
        assertThat(geoNear.getDistanceField(), is("dist"));
        assertThat(geoNear.getDistanceMultiplier(), nullValue());
        assertThat(geoNear.getLimit(), nullValue());
        assertThat(geoNear.getLocationField(), nullValue());
        assertThat(geoNear.getMaxDistance(), nullValue());
        assertThat(geoNear.getQuery(), nullValue());
        assertThat(geoNear.isSpherical(), is(false));
        assertThat(geoNear.isUniqueDocs(), is(true));

        final DocumentBuilder expected = BuilderFactory.start();
        expected.pushArray("near").add(1).add(2);
        expected.add("distanceField", "dist");
        expected.add("spherical", false);
        expected.add("uniqueDocs", true);

        assertThat(geoNear.asDocument(), is(expected.build()));
    }

    /**
     * Test method for {@link AggregationGeoNear} .
     */
    @Test()
    public void testAggregationGeoNearMissingDistanceField() {
        final Point2D location = new Point(1, 2);

        final AggregationGeoNear.Builder builder = AggregationGeoNear.builder()
                .location(location).distanceField(null);

        boolean built = false;
        try {
            builder.build();
            built = true;
        }
        catch (final IllegalArgumentException expected) {
            // Good.
        }
        assertFalse(
                "Should have failed to create a AggregationGeoNear command without a distance field.",
                built);
    }

    /**
     * Test method for {@link AggregationGeoNear} .
     */
    @Test()
    public void testAggregationGeoNearMissingLocation() {

        final AggregationGeoNear.Builder builder = AggregationGeoNear.builder()
                .location(null).distanceField("dist");

        boolean built = false;
        try {
            builder.build();
            built = true;
        }
        catch (final IllegalArgumentException expected) {
            // Good.
        }
        assertFalse(
                "Should have failed to create a AggregationGeoNear command without a location.",
                built);
    }

    /**
     * Test method for {@link AggregationGeoNear}.
     */
    @Test
    public void testAggregationGeoNearReset() {
        final Point2D location = new Point(1, 2);

        final AggregationGeoNear.Builder builder = AggregationGeoNear.builder()
                .location(location).distanceField("dist")
                .distanceMultiplier(1.2).limit(123).locationField("loc")
                .maxDistance(12345.6).query(BuilderFactory.start().add("a", 2))
                .spherical(true).uniqueDocs(false);
        AggregationGeoNear geoNear = builder.build();

        assertThat(geoNear.getLocation(), is(location));
        assertThat(geoNear.getDistanceField(), is("dist"));
        assertThat(geoNear.getDistanceMultiplier(), is(1.2));
        assertThat(geoNear.getLimit(), is(123L));
        assertThat(geoNear.getLocationField(), is("loc"));
        assertThat(geoNear.getMaxDistance(), is(12345.6));
        assertThat(geoNear.getQuery(), is(BuilderFactory.start().add("a", 2)
                .build()));
        assertThat(geoNear.isSpherical(), is(true));
        assertThat(geoNear.isUniqueDocs(), is(false));

        builder.reset();

        boolean built = false;
        try {
            builder.build();
            built = true;
        }
        catch (final IllegalArgumentException expected) {
            // Good.
        }
        assertFalse(
                "Should have failed to create a geoNear command without a location.",
                built);

        geoNear = builder.location(location).distanceField("dist").build();

        assertThat(geoNear.getLocation(), is(location));
        assertThat(geoNear.getDistanceField(), is("dist"));
        assertThat(geoNear.getDistanceMultiplier(), nullValue());
        assertThat(geoNear.getLimit(), nullValue());
        assertThat(geoNear.getLocationField(), nullValue());
        assertThat(geoNear.getMaxDistance(), nullValue());
        assertThat(geoNear.getQuery(), nullValue());
        assertThat(geoNear.isSpherical(), is(false));
        assertThat(geoNear.isUniqueDocs(), is(true));
    }

    /**
     * Test method for {@link AggregationGeoNear}.
     */
    @Test
    public void testAggregationGeoNearWithExplicitSpherical() {
        final Point2D location = new Point(1, 2);

        final AggregationGeoNear geoNear = AggregationGeoNear.builder()
                .location(location).distanceField("dist")
                .distanceMultiplier(1.2).limit(123).locationField("loc")
                .maxDistance(12345.6).query(BuilderFactory.start().add("a", 2))
                .spherical(true).uniqueDocs(false).build();

        assertThat(geoNear.getLocation(), is(location));
        assertThat(geoNear.getDistanceField(), is("dist"));
        assertThat(geoNear.getDistanceMultiplier(), is(1.2));
        assertThat(geoNear.getLimit(), is(123L));
        assertThat(geoNear.getLocationField(), is("loc"));
        assertThat(geoNear.getMaxDistance(), is(12345.6));
        assertThat(geoNear.getQuery(), is(BuilderFactory.start().add("a", 2)
                .build()));
        assertThat(geoNear.isSpherical(), is(true));
        assertThat(geoNear.isUniqueDocs(), is(false));

        final DocumentBuilder expected = BuilderFactory.start();
        expected.pushArray("near").add(1).add(2);
        expected.add("distanceField", "dist");
        expected.add("spherical", true);
        expected.add("uniqueDocs", false);

        expected.add("limit", 123L);
        expected.add("maxDistance", 12345.6);
        expected.add("query", BuilderFactory.start().add("a", 2));
        expected.add("distanceMultiplier", 1.2);
        expected.add("includeLocs", "loc");

        assertThat(geoNear.asDocument(), is(expected.build()));
    }
}


text:
describe('CONTROLLER - CtrlAdminProcess', function (){
    var LocationManagerMock;
    var AdminUserRequestManagerMock;
    var AdminUserMock;
    var localStorageServiceMock;
    beforeEach(function (){
        LocationManagerMock = jasmine.createSpyObj('LocationManager',['handleAdminProcessLocation','handleAdminProcessLocation','isLogged','isAdmin']);
        AdminUserMock = jasmine.createSpyObj('AdminUser',['getName','getProcessList']);
        AdminUserRequestManagerMock = jasmine.createSpyObj('AdminUserRequestManager',['getAllAdminCreatedActiveProcessList','getAdminInfo']);
        localStorageServiceMock = jasmine.createSpyObj('localStorageService',['add']);

        module('CtrlAdminProcess');

        inject (function($rootScope, $controller){
            // Creo uno scope fittizio
            $scope = $rootScope.$new();

            AdminUserMock.getName.andReturn('Test Admin Name');
            LocationManagerMock.isLogged.andReturn('true');
            LocationManagerMock.isAdmin.andReturn('true');

            // Creo un controller fittizio
            ctrl = $controller('CtrlAdminProcess', {
                $scope : $scope,
                LocationManager : LocationManagerMock,
                AdminUser : AdminUserMock,
                AdminUserRequestManager : AdminUserRequestManagerMock,
                localStorageService : localStorageServiceMock
            });
        });
    });

    it('should set be able to get the admin info', function(){
        $scope.openWebSocket = function(variable){};
        expect(LocationManagerMock.handleAdminProcessLocation).toHaveBeenCalled();
        $scope.$broadcast('REQUEST_INFO_IS_END','');
        expect(AdminUserRequestManagerMock.getAdminInfo).toHaveBeenCalled();
        expect(AdminUserRequestManagerMock.getAllAdminCreatedActiveProcessList).toHaveBeenCalled();
        expect($scope.user).toEqual('Test Admin Name');
    });

    it('should set be able get an empty list during find process that have been created', function(){
        var result="Non ci sono processi attivi";
        $scope.$broadcast('GET_ALL_ADMIN_CREATED_ACTIVE_PROCESS_IS_END', result);
        expect($scope.processList).toEqual([]);
        expect($scope.messageResult).toEqual(result);
    });

    it('should set be able get process have been created by the admin', function(){
        var processList={};
        inject(function(){
            AdminUserMock.getProcessList.andReturn(processList);
        });
        var result="Hai processo attivi";
        $scope.$broadcast('GET_ALL_ADMIN_CREATED_ACTIVE_PROCESS_IS_END','', result);
        expect($scope.processList).toEqual(processList);
        expect($scope.user).toEqual('Test Admin Name');
        expect($scope.currentPage).toEqual(0);
        expect($scope.pageSize).toEqual(5);
        // expect($scope.numberOfPages).toEqual(Math.ceil($scope.processList.length/$scope.pageSize));
    });

    it('should set be able do goToModifyProcess', function(){
       $scope.goToModifyProcess();
        expect(localStorageServiceMock.add).toHaveBeenCalled();
    });

    it('should set be able do goToViewAllListUserProcess', function(){
        $scope.goToViewAllListUserProcess();
        expect(localStorageServiceMock.add).toHaveBeenCalled();
    });

    it('should be able to do CONNECTION_PROBLEM broadcast', function(){
        $scope.closeWebSocket = function(){};
        $scope.$broadcast('CONNECTION_PROBLEM','Connection problem');
    });
});


text:
using System;
using System.Globalization;
using Windows.UI.Xaml.Data;

namespace WhatSizeWithBindingConverter
{
    public class FormattedStringConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, string language)
        {
            if (value is IFormattable &&
                parameter is string &&
                !String.IsNullOrEmpty(parameter as string) &&
                targetType == typeof(string))
            {
                if (String.IsNullOrEmpty(language))
                    return (value as IFormattable).ToString(parameter as string, null);

                return (value as IFormattable).ToString(parameter as string,
                                                        new CultureInfo(language));
            }

            return value;
        }
        public object ConvertBack(object value, Type targetType, object parameter, string language)
        {
            return value;
        }
    }
}


text:
package org.drools.workbench.screens.dsltext.backend.server.indexing;

import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;

import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;

import org.drools.compiler.lang.dsl.DSLMapping;
import org.drools.compiler.lang.dsl.DSLMappingEntry;
import org.drools.compiler.lang.dsl.DSLTokenizedMappingFile;
import org.drools.workbench.screens.dsltext.type.DSLResourceTypeDefinition;
import org.guvnor.common.services.project.model.Module;
import org.guvnor.common.services.project.model.Package;
import org.kie.soup.project.datamodel.oracle.ModuleDataModelOracle;
import org.kie.workbench.common.services.datamodel.backend.server.service.DataModelService;
import org.kie.workbench.common.services.refactoring.IndexElementsGenerator;
import org.kie.workbench.common.services.refactoring.Resource;
import org.kie.workbench.common.services.refactoring.backend.server.indexing.DefaultIndexBuilder;
import org.kie.workbench.common.services.refactoring.backend.server.indexing.IndexBuilder;
import org.kie.workbench.common.services.refactoring.backend.server.indexing.drools.AbstractDrlFileIndexer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.uberfire.backend.server.util.Paths;
import org.uberfire.java.nio.file.Path;

// TODO: yeah, so there's no "rule => <rule name>" key-value pair added to the lucene index doc here
// (because we don't want to add the name of a dummy rule -- a name which is repeatedly used in order to
// be able to convert the DSl to a DRL and parse it..

// so..  what to do? :D (Maybe add DSL("dsl") to ResourceType and add a key-value pair of dsl => <dsl name>
// but what's the "dsl name" then?!?
@ApplicationScoped
public class DslFileIndexer extends AbstractDrlFileIndexer {

    public static final String MOCK_RULE_NAME = DslFileIndexer.class.getSimpleName() + "_parsing_dummy_rule";
    private static final Logger logger = LoggerFactory.getLogger(AbstractDrlFileIndexer.class);
    @Inject
    protected DSLResourceTypeDefinition dslType;
    @Inject
    private DataModelService dataModelService;

    @Override
    public boolean supportsPath(final Path path) {
        return dslType.accept(Paths.convert(path));
    }

    @Override
    public IndexBuilder fillIndexBuilder(final Path path) throws Exception {

        final List<String> lhs = new ArrayList<String>();
        final List<String> rhs = new ArrayList<String>();
        final String dsl = ioService.readAllString(path);

        //Construct a dummy DRL file to parse index elements
        final DSLTokenizedMappingFile dslLoader = new DSLTokenizedMappingFile();
        if (dslLoader.parseAndLoad(new StringReader(dsl))) {
            DSLMapping dslMapping = dslLoader.getMapping();
            for (DSLMappingEntry e : dslMapping.getEntries()) {
                switch (e.getSection()) {
                    case CONDITION:
                        lhs.add(e.getValuePattern());
                        break;
                    case CONSEQUENCE:
                        rhs.add(e.getValuePattern());
                        break;
                    default:
                        // no-op
                }
            }

            final String drl = makeDrl(path,
                                       lhs,
                                       rhs);

            return fillDrlIndexBuilder(path,
                                       drl);
        }

        return null;
    }

    @Override
    protected DefaultIndexBuilder getIndexBuilder(Path path) {
        final Module module = moduleService.resolveModule(Paths.convert(path));
        if (module == null) {
            logger.error("Unable to index " + path.toUri().toString() + ": module could not be resolved.");
            return null;
        }

        final Package pkg = moduleService.resolvePackage(Paths.convert(path));
        if (pkg == null) {
            logger.error("Unable to index " + path.toUri().toString() + ": package could not be resolved.");
            return null;
        }

        // responsible for basic index info: module name, branch, etc
        return new DefaultIndexBuilder(Paths.convert(path).getFileName(),
                                       module,
                                       pkg) {
            @Override
            public DefaultIndexBuilder addGenerator(final IndexElementsGenerator generator) {
                // Don't include the rule created to parse DSL
                if (generator instanceof Resource && ((Resource) generator).getResourceFQN().endsWith(MOCK_RULE_NAME)) {
                    return this;
                }
                return super.addGenerator(generator);
            }
        };
    }

    /*
     * (non-Javadoc)
     * @see org.kie.workbench.common.services.refactoring.backend.server.indexing.drools.AbstractDrlFileIndexer#getModuleDataModelOracle(org.uberfire.java.nio.file.Path)
     */
    @Override
    protected ModuleDataModelOracle getModuleDataModelOracle(final Path path) {
        return dataModelService.getModuleDataModel(Paths.convert(path));
    }

    private String makeDrl(final Path path,
                           final List<String> lhs,
                           final List<String> rhs) {
        final StringBuilder sb = new StringBuilder();
        final String packageName = getPackageName(path);
        if (!(packageName == null || packageName.isEmpty())) {
            sb.append("package ").append(packageName).append("\n");
        }
        sb.append("rule \"" + MOCK_RULE_NAME + "\"\n");
        sb.append("when\n");
        for (String e : lhs) {
            sb.append(e).append("\n");
        }
        sb.append("then\n");
        for (String e : rhs) {
            sb.append(e).append("\n");
        }
        sb.append("end\n");

        final String drl = sb.toString();
        return drl.replaceAll("\\{.*\\}",
                              "0");
    }
}


text:
//
// Copyright 2022 Google LLC
//
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you 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.
//

using Google.Solutions.WWAuth.Data;
using Google.Solutions.WWAuth.Util;
using System.Windows.Forms;

namespace Google.Solutions.WWAuth.View
{
    [SkipCodeCoverageAttribute]
    internal partial class ViewTokenSheet : UserControl, IPropertiesSheet
    {
        public ViewTokenSheet(ISubjectToken token)
        {
            InitializeComponent();

            var vm = new ViewTokenViewModel(token);
            this.ViewModel = vm;

            this.attributesList.Items.AddRange(vm.Attributes);

            this.issuerTextBox.BindReadonlyProperty(
                c => c.Text,
                vm,
                m => m.Issuer,
                this.Container);
            this.audienceTextBox.BindReadonlyProperty(
                c => c.Text,
                vm,
                m => m.Audience,
                this.Container);
            this.expiryTextBox.BindReadonlyProperty(
                c => c.Text,
                vm,
                m => m.Expiry,
                this.Container);
        }

        public IPropertiesSheetViewModel ViewModel { get; }

        public void OnActivated()
        {
        }
    }
}


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

<TITLE>
EventBroadcaster (Apache FOP 1.1 API)
</TITLE>

<META NAME="date" CONTENT="2012-10-16">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

fop 1.1

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

org.apache.fop.events

Interface EventBroadcaster

All Known Implementing Classes:
DefaultEventBroadcaster

public interface EventBroadcaster

The EventBroadcaster is the central relay point for events. It receives events from various
 parts of the application and forwards them to any registered EventListener.

Method Summary

 void
addEventListener(EventListener listener)

          Adds an event listener to the broadcaster.

 void
broadcastEvent(Event event)

          Broadcasts an event.

 EventProducer
getEventProducerFor(java.lang.Class clazz)

          Returns an event producer instance for the given interface class.

 boolean
hasEventListeners()

          Indicates whether any listeners have been registered with the broadcaster.

 void
removeEventListener(EventListener listener)

          Removes an event listener from the broadcaster.

Method Detail

addEventListener

void addEventListener(EventListener listener)

Adds an event listener to the broadcaster. It is appended to the list of previously
 registered listeners (the order of registration defines the calling order).

Parameters:
listener - the listener to be added

removeEventListener

void removeEventListener(EventListener listener)

Removes an event listener from the broadcaster. If the event listener is not registered,
 nothing happens.

Parameters:
listener - the listener to be removed

hasEventListeners

boolean hasEventListeners()

Indicates whether any listeners have been registered with the broadcaster.

Returns:
true if listeners are present, false otherwise

broadcastEvent

void broadcastEvent(Event event)

Broadcasts an event. This method is usually called from within the observed component.

Parameters:
event - the event to be broadcast

getEventProducerFor

EventProducer getEventProducerFor(java.lang.Class clazz)

Returns an event producer instance for the given interface class.

Parameters:
clazz - the Class object identifying an EventProducer interface

Returns:
the event producer instance

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

fop 1.1

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

Copyright 1999-2012 The Apache Software Foundation. All Rights Reserved.


text:
Implement run-length encoding and decoding.

Run-length encoding (RLE) is a simple form of data compression, where runs
(consecutive data elements) are replaced by just one data value and count.

For example we can represent the original 53 characters with only 13.

```
"WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWB"  ->  "12WB12W3B24WB"
```

RLE allows the original data to be perfectly reconstructed from
the compressed data, which makes it a lossless data compression.

```
"AABCCCDEEEE"  ->  "2AB3CD4E"  ->  "AABCCCDEEEE"
```

For simplicity, you can assume that the unencoded string will only contain
the letters A through Z (either lower or upper case) and whitespace. This way
data to be encoded will never contain any numbers and numbers inside data to
be decoded always represent the count for the following character.


text:
from django.test import TestCase
from user.views import ResetPasswordView
from user.models import ResetPasswordProfile, User

class TestViewRecoverProfile(TestCase):

    def setUp(self):
        self.view = ResetPasswordView
        self.model = ResetPasswordProfile

        # Creating user in database.
        self.user = User()
        self.user.email = "teste@teste.com"
        self.user.password = "teste404"
        self.user.is_active = False
        self.user.name = "usuario"
        self.user.save()

    # Test if ResetPasswordProfile are save databe.
    def test_user_create_recover_profile(self):

        recover = self.view._create_recover_profile(self.view, self.user)
        recover.save()
        query = ResetPasswordProfile.objects.filter(pk=recover.pk)

        self.assertTrue(query.exists())


text:
package dns

import (
	"io/ioutil"
	"os"
	"path/filepath"
	"strings"
	"testing"
)

const normal string = `
# Comment
domain somedomain.com
nameserver 10.28.10.2
nameserver 11.28.10.1
`

const missingNewline string = `
domain somedomain.com
nameserver 10.28.10.2
nameserver 11.28.10.1` // <- NOTE: NO newline.

func testConfig(t *testing.T, data string) {
	cc, err := ClientConfigFromReader(strings.NewReader(data))
	if err != nil {
		t.Errorf("error parsing resolv.conf: %v", err)
	}
	if l := len(cc.Servers); l != 2 {
		t.Errorf("incorrect number of nameservers detected: %d", l)
	}
	if l := len(cc.Search); l != 1 {
		t.Errorf("domain directive not parsed correctly: %v", cc.Search)
	} else {
		if cc.Search[0] != "somedomain.com" {
			t.Errorf("domain is unexpected: %v", cc.Search[0])
		}
	}
}

func TestNameserver(t *testing.T)          { testConfig(t, normal) }
func TestMissingFinalNewLine(t *testing.T) { testConfig(t, missingNewline) }

func TestNdots(t *testing.T) {
	ndotsVariants := map[string]int{
		"options ndots:0":  0,
		"options ndots:1":  1,
		"options ndots:15": 15,
		"options ndots:16": 15,
		"options ndots:-1": 0,
		"":                 1,
	}

	for data := range ndotsVariants {
		cc, err := ClientConfigFromReader(strings.NewReader(data))
		if err != nil {
			t.Errorf("error parsing resolv.conf: %v", err)
		}
		if cc.Ndots != ndotsVariants[data] {
			t.Errorf("Ndots not properly parsed: (Expected: %d / Was: %d)", ndotsVariants[data], cc.Ndots)
		}
	}
}

func TestClientConfigFromReaderAttempts(t *testing.T) {
	testCases := []struct {
		data     string
		expected int
	}{
		{data: "options attempts:0", expected: 1},
		{data: "options attempts:1", expected: 1},
		{data: "options attempts:15", expected: 15},
		{data: "options attempts:16", expected: 16},
		{data: "options attempts:-1", expected: 1},
		{data: "options attempt:", expected: 2},
	}

	for _, test := range testCases {
		test := test
		t.Run(strings.Replace(test.data, ":", " ", -1), func(t *testing.T) {
			t.Parallel()

			cc, err := ClientConfigFromReader(strings.NewReader(test.data))
			if err != nil {
				t.Errorf("error parsing resolv.conf: %v", err)
			}
			if cc.Attempts != test.expected {
				t.Errorf("A attempts not properly parsed: (Expected: %d / Was: %d)", test.expected, cc.Attempts)
			}
		})
	}
}

func TestReadFromFile(t *testing.T) {
	tempDir, err := ioutil.TempDir("", "")
	if err != nil {
		t.Fatalf("tempDir: %v", err)
	}
	defer os.RemoveAll(tempDir)

	path := filepath.Join(tempDir, "resolv.conf")
	if err := ioutil.WriteFile(path, []byte(normal), 0644); err != nil {
		t.Fatalf("writeFile: %v", err)
	}
	cc, err := ClientConfigFromFile(path)
	if err != nil {
		t.Errorf("error parsing resolv.conf: %v", err)
	}
	if l := len(cc.Servers); l != 2 {
		t.Errorf("incorrect number of nameservers detected: %d", l)
	}
	if l := len(cc.Search); l != 1 {
		t.Errorf("domain directive not parsed correctly: %v", cc.Search)
	} else {
		if cc.Search[0] != "somedomain.com" {
			t.Errorf("domain is unexpected: %v", cc.Search[0])
		}
	}
}

func TestNameListNdots1(t *testing.T) {
	cfg := ClientConfig{
		Ndots: 1,
	}
	// fqdn should be only result returned
	names := cfg.NameList("miek.nl.")
	if len(names) != 1 {
		t.Errorf("NameList returned != 1 names: %v", names)
	} else if names[0] != "miek.nl." {
		t.Errorf("NameList didn't return sent fqdn domain: %v", names[0])
	}

	cfg.Search = []string{
		"test",
	}
	// Sent domain has NDots and search
	names = cfg.NameList("miek.nl")
	if len(names) != 2 {
		t.Errorf("NameList returned != 2 names: %v", names)
	} else if names[0] != "miek.nl." {
		t.Errorf("NameList didn't return sent domain first: %v", names[0])
	} else if names[1] != "miek.nl.test." {
		t.Errorf("NameList didn't return search last: %v", names[1])
	}
}
func TestNameListNdots2(t *testing.T) {
	cfg := ClientConfig{
		Ndots: 2,
	}

	// Sent domain has less than NDots and search
	cfg.Search = []string{
		"test",
	}
	names := cfg.NameList("miek.nl")

	if len(names) != 2 {
		t.Errorf("NameList returned != 2 names: %v", names)
	} else if names[0] != "miek.nl.test." {
		t.Errorf("NameList didn't return search first: %v", names[0])
	} else if names[1] != "miek.nl." {
		t.Errorf("NameList didn't return sent domain last: %v", names[1])
	}
}

func TestNameListNdots0(t *testing.T) {
	cfg := ClientConfig{
		Ndots: 0,
	}
	cfg.Search = []string{
		"test",
	}
	// Sent domain has less than NDots and search
	names := cfg.NameList("miek")
	if len(names) != 2 {
		t.Errorf("NameList returned != 2 names: %v", names)
	} else if names[0] != "miek." {
		t.Errorf("NameList didn't return search first: %v", names[0])
	} else if names[1] != "miek.test." {
		t.Errorf("NameList didn't return sent domain last: %v", names[1])
	}
}


text:
package org.nusco.narjillos.creature.body;

import java.util.ArrayList;
import java.util.List;

import org.nusco.narjillos.core.geometry.Vector;
import org.nusco.narjillos.creature.body.pns.Nerve;

/**
 * An organ that is connected to other organs in a tree to form a body.
 */
public abstract class ConnectedOrgan extends Organ {

	private transient ConnectedOrgan parent;

	private final List<ConnectedOrgan> children = new ArrayList<>();

	private final Nerve nerve;

	public ConnectedOrgan(int adultLength, int adultThickness, Fiber fiber, ConnectedOrgan parent, Nerve nerve) {
		super(adultLength, adultThickness, fiber);
		setParent(parent);
		this.nerve = nerve;
	}

	public final void setParent(ConnectedOrgan parent) {
		this.parent = parent;
	}

	@Override
	protected Vector calculateStartPoint() {
		return getParent().getEndPoint();
	}

	public final ConnectedOrgan getParent() {
		return parent;
	}

	public List<ConnectedOrgan> getChildren() {
		return children;
	}

	public ConnectedOrgan addChild(ConnectedOrgan child) {
		children.add(child);
		return child;
	}

	public boolean isLeaf() {
		return getChildren().isEmpty();
	}

	public void growToAdultFormWithChildren() {
		growBy(Integer.MAX_VALUE);
		update();

		for (ConnectedOrgan child : getChildren())
			child.growToAdultFormWithChildren();
	}

	protected abstract double getMetabolicRate();

	Nerve getNerve() {
		return nerve;
	}
}


text:
<?php

namespace DataTable\Controller;

use DataTable\Model\DataTableModel;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;

class IndexController extends AbstractActionController
{
    public function indexAction()
    {
        $this->layout('layout/bootstrap');
        $result  = [];
        return new ViewModel(['date' => $result]);
    }

    public function ajaxAction()
    {
        /** @var DataTableModel $dataTable */
        $dataTable = $this->getServiceLocator()->get('dataTableModel');
        $result    = $dataTable->init($this->params()->fromQuery(), 'card', "`effect` IS NULL")->getJson();

        echo $result;
        exit;
    }
}


text:
#include <stdio.h>
#include <time.h>
#include "internal/cryptlib.h"
#include <openssl/opensslconf.h>
#include "crypto/rand.h"
#include <openssl/engine.h>
#include "internal/thread_once.h"
#include "crypto/rand_pool.h"

/*
 * Allocate memory and initialize a new random pool
 */
RAND_POOL *ossl_rand_pool_new(int entropy_requested, int secure,
                              size_t min_len, size_t max_len)
{
    RAND_POOL *pool = OPENSSL_zalloc(sizeof(*pool));
    size_t min_alloc_size = RAND_POOL_MIN_ALLOCATION(secure);

    if (pool == NULL)
        return NULL;

    pool->min_len = min_len;
    pool->max_len = (max_len > RAND_POOL_MAX_LENGTH) ?
        RAND_POOL_MAX_LENGTH : max_len;
    pool->alloc_len = min_len < min_alloc_size ? min_alloc_size : min_len;
    if (pool->alloc_len > pool->max_len)
        pool->alloc_len = pool->max_len;

    if (secure)
        pool->buffer = OPENSSL_secure_zalloc(pool->alloc_len);
    else
        pool->buffer = OPENSSL_zalloc(pool->alloc_len);

    if (pool->buffer == NULL)
        goto err;

    pool->entropy_requested = entropy_requested;
    pool->secure = secure;
    return pool;

err:
    OPENSSL_free(pool);
    return NULL;
}

/*
 * Attach new random pool to the given buffer
 *
 * This function is intended to be used only for feeding random data
 * provided by RAND_add() and RAND_seed() into the <master> DRBG.
 */
RAND_POOL *ossl_rand_pool_attach(const unsigned char *buffer, size_t len,
                                 size_t entropy)
{
    RAND_POOL *pool = OPENSSL_zalloc(sizeof(*pool));

    if (pool == NULL)
        return NULL;

    /*
     * The const needs to be cast away, but attached buffers will not be
     * modified (in contrary to allocated buffers which are zeroed and
     * freed in the end).
     */
    pool->buffer = (unsigned char *) buffer;
    pool->len = len;

    pool->attached = 1;

    pool->min_len = pool->max_len = pool->alloc_len = pool->len;
    pool->entropy = entropy;

    return pool;
}

/*
 * Free |pool|, securely erasing its buffer.
 */
void ossl_rand_pool_free(RAND_POOL *pool)
{
    if (pool == NULL)
        return;

    /*
     * Although it would be advisable from a cryptographical viewpoint,
     * we are not allowed to clear attached buffers, since they are passed
     * to ossl_rand_pool_attach() as `const unsigned char*`.
     * (see corresponding comment in ossl_rand_pool_attach()).
     */
    if (!pool->attached) {
        if (pool->secure)
            OPENSSL_secure_clear_free(pool->buffer, pool->alloc_len);
        else
            OPENSSL_clear_free(pool->buffer, pool->alloc_len);
    }

    OPENSSL_free(pool);
}

/*
 * Return the |pool|'s buffer to the caller (readonly).
 */
const unsigned char *ossl_rand_pool_buffer(RAND_POOL *pool)
{
    return pool->buffer;
}

/*
 * Return the |pool|'s entropy to the caller.
 */
size_t ossl_rand_pool_entropy(RAND_POOL *pool)
{
    return pool->entropy;
}

/*
 * Return the |pool|'s buffer length to the caller.
 */
size_t ossl_rand_pool_length(RAND_POOL *pool)
{
    return pool->len;
}

/*
 * Detach the |pool| buffer and return it to the caller.
 * It's the responsibility of the caller to free the buffer
 * using OPENSSL_secure_clear_free() or to re-attach it
 * again to the pool using ossl_rand_pool_reattach().
 */
unsigned char *ossl_rand_pool_detach(RAND_POOL *pool)
{
    unsigned char *ret = pool->buffer;
    pool->buffer = NULL;
    pool->entropy = 0;
    return ret;
}

/*
 * Re-attach the |pool| buffer. It is only allowed to pass
 * the |buffer| which was previously detached from the same pool.
 */
void ossl_rand_pool_reattach(RAND_POOL *pool, unsigned char *buffer)
{
    pool->buffer = buffer;
    OPENSSL_cleanse(pool->buffer, pool->len);
    pool->len = 0;
}

/*
 * If |entropy_factor| bits contain 1 bit of entropy, how many bytes does one
 * need to obtain at least |bits| bits of entropy?
 */
#define ENTROPY_TO_BYTES(bits, entropy_factor) \
    (((bits) * (entropy_factor) + 7) / 8)

/*
 * Checks whether the |pool|'s entropy is available to the caller.
 * This is the case when entropy count and buffer length are high enough.
 * Returns
 *
 *  |entropy|  if the entropy count and buffer size is large enough
 *      0      otherwise
 */
size_t ossl_rand_pool_entropy_available(RAND_POOL *pool)
{
    if (pool->entropy < pool->entropy_requested)
        return 0;

    if (pool->len < pool->min_len)
        return 0;

    return pool->entropy;
}

/*
 * Returns the (remaining) amount of entropy needed to fill
 * the random pool.
 */

size_t ossl_rand_pool_entropy_needed(RAND_POOL *pool)
{
    if (pool->entropy < pool->entropy_requested)
        return pool->entropy_requested - pool->entropy;

    return 0;
}

/* Increase the allocation size -- not usable for an attached pool */
static int rand_pool_grow(RAND_POOL *pool, size_t len)
{
    if (len > pool->alloc_len - pool->len) {
        unsigned char *p;
        const size_t limit = pool->max_len / 2;
        size_t newlen = pool->alloc_len;

        if (pool->attached || len > pool->max_len - pool->len) {
            ERR_raise(ERR_LIB_RAND, ERR_R_INTERNAL_ERROR);
            return 0;
        }

        do
            newlen = newlen < limit ? newlen * 2 : pool->max_len;
        while (len > newlen - pool->len);

        if (pool->secure)
            p = OPENSSL_secure_zalloc(newlen);
        else
            p = OPENSSL_zalloc(newlen);
        if (p == NULL)
            return 0;
        memcpy(p, pool->buffer, pool->len);
        if (pool->secure)
            OPENSSL_secure_clear_free(pool->buffer, pool->alloc_len);
        else
            OPENSSL_clear_free(pool->buffer, pool->alloc_len);
        pool->buffer = p;
        pool->alloc_len = newlen;
    }
    return 1;
}

/*
 * Returns the number of bytes needed to fill the pool, assuming
 * the input has 1 / |entropy_factor| entropy bits per data bit.
 * In case of an error, 0 is returned.
 */

size_t ossl_rand_pool_bytes_needed(RAND_POOL *pool, unsigned int entropy_factor)
{
    size_t bytes_needed;
    size_t entropy_needed = ossl_rand_pool_entropy_needed(pool);

    if (entropy_factor < 1) {
        ERR_raise(ERR_LIB_RAND, RAND_R_ARGUMENT_OUT_OF_RANGE);
        return 0;
    }

    bytes_needed = ENTROPY_TO_BYTES(entropy_needed, entropy_factor);

    if (bytes_needed > pool->max_len - pool->len) {
        /* not enough space left */
        ERR_raise(ERR_LIB_RAND, RAND_R_RANDOM_POOL_OVERFLOW);
        return 0;
    }

    if (pool->len < pool->min_len &&
        bytes_needed < pool->min_len - pool->len)
        /* to meet the min_len requirement */
        bytes_needed = pool->min_len - pool->len;

    /*
     * Make sure the buffer is large enough for the requested amount
     * of data. This guarantees that existing code patterns where
     * ossl_rand_pool_add_begin, ossl_rand_pool_add_end or ossl_rand_pool_add
     * are used to collect entropy data without any error handling
     * whatsoever, continue to be valid.
     * Furthermore if the allocation here fails once, make sure that
     * we don't fall back to a less secure or even blocking random source,
     * as that could happen by the existing code patterns.
     * This is not a concern for additional data, therefore that
     * is not needed if rand_pool_grow fails in other places.
     */
    if (!rand_pool_grow(pool, bytes_needed)) {
        /* persistent error for this pool */
        pool->max_len = pool->len = 0;
        return 0;
    }

    return bytes_needed;
}

/* Returns the remaining number of bytes available */
size_t ossl_rand_pool_bytes_remaining(RAND_POOL *pool)
{
    return pool->max_len - pool->len;
}

/*
 * Add random bytes to the random pool.
 *
 * It is expected that the |buffer| contains |len| bytes of
 * random input which contains at least |entropy| bits of
 * randomness.
 *
 * Returns 1 if the added amount is adequate, otherwise 0
 */
int ossl_rand_pool_add(RAND_POOL *pool,
                  const unsigned char *buffer, size_t len, size_t entropy)
{
    if (len > pool->max_len - pool->len) {
        ERR_raise(ERR_LIB_RAND, RAND_R_ENTROPY_INPUT_TOO_LONG);
        return 0;
    }

    if (pool->buffer == NULL) {
        ERR_raise(ERR_LIB_RAND, ERR_R_INTERNAL_ERROR);
        return 0;
    }

    if (len > 0) {
        /*
         * This is to protect us from accidentally passing the buffer
         * returned from ossl_rand_pool_add_begin.
         * The check for alloc_len makes sure we do not compare the
         * address of the end of the allocated memory to something
         * different, since that comparison would have an
         * indeterminate result.
         */
        if (pool->alloc_len > pool->len && pool->buffer + pool->len == buffer) {
            ERR_raise(ERR_LIB_RAND, ERR_R_INTERNAL_ERROR);
            return 0;
        }
        /*
         * We have that only for cases when a pool is used to collect
         * additional data.
         * For entropy data, as long as the allocation request stays within
         * the limits given by ossl_rand_pool_bytes_needed this rand_pool_grow
         * below is guaranteed to succeed, thus no allocation happens.
         */
        if (!rand_pool_grow(pool, len))
            return 0;
        memcpy(pool->buffer + pool->len, buffer, len);
        pool->len += len;
        pool->entropy += entropy;
    }

    return 1;
}

/*
 * Start to add random bytes to the random pool in-place.
 *
 * Reserves the next |len| bytes for adding random bytes in-place
 * and returns a pointer to the buffer.
 * The caller is allowed to copy up to |len| bytes into the buffer.
 * If |len| == 0 this is considered a no-op and a NULL pointer
 * is returned without producing an error message.
 *
 * After updating the buffer, ossl_rand_pool_add_end() needs to be called
 * to finish the update operation (see next comment).
 */
unsigned char *ossl_rand_pool_add_begin(RAND_POOL *pool, size_t len)
{
    if (len == 0)
        return NULL;

    if (len > pool->max_len - pool->len) {
        ERR_raise(ERR_LIB_RAND, RAND_R_RANDOM_POOL_OVERFLOW);
        return NULL;
    }

    if (pool->buffer == NULL) {
        ERR_raise(ERR_LIB_RAND, ERR_R_INTERNAL_ERROR);
        return NULL;
    }

    /*
     * As long as the allocation request stays within the limits given
     * by ossl_rand_pool_bytes_needed this rand_pool_grow below is guaranteed
     * to succeed, thus no allocation happens.
     * We have that only for cases when a pool is used to collect
     * additional data. Then the buffer might need to grow here,
     * and of course the caller is responsible to check the return
     * value of this function.
     */
    if (!rand_pool_grow(pool, len))
        return NULL;

    return pool->buffer + pool->len;
}

/*
 * Finish to add random bytes to the random pool in-place.
 *
 * Finishes an in-place update of the random pool started by
 * ossl_rand_pool_add_begin() (see previous comment).
 * It is expected that |len| bytes of random input have been added
 * to the buffer which contain at least |entropy| bits of randomness.
 * It is allowed to add less bytes than originally reserved.
 */
int ossl_rand_pool_add_end(RAND_POOL *pool, size_t len, size_t entropy)
{
    if (len > pool->alloc_len - pool->len) {
        ERR_raise(ERR_LIB_RAND, RAND_R_RANDOM_POOL_OVERFLOW);
        return 0;
    }

    if (len > 0) {
        pool->len += len;
        pool->entropy += entropy;
    }

    return 1;
}