text:
import json
from tests.fixtures import (    # noqa: F401
    client, initial_data, basic_auth_admin_headers,
    test_admin_user, test_user, account_data, user1_data,
)
from . import IntegrationApiManagement

class TestIntegrationApiManagementAdminUser(IntegrationApiManagement):

    def test_accounts_empty_get(
            self, client, initial_data,                         # noqa: F811
            basic_auth_admin_headers):                          # noqa: F811
        res = client.get("/api/v1/pdnsadmin/accounts",
                         headers=basic_auth_admin_headers)
        data = res.get_json(force=True)
        assert res.status_code == 200
        assert data == []

    def test_users_empty_get(
            self, client, initial_data,                         # noqa: F811
            test_admin_user, test_user,                         # noqa: F811
            basic_auth_admin_headers):                          # noqa: F811
        res = client.get("/api/v1/pdnsadmin/users",
                         headers=basic_auth_admin_headers)
        data = res.get_json(force=True)
        assert res.status_code == 200
        # Initally contains 2 records
        assert len(data) == 2
        for user in data:
            assert user["username"] in (test_admin_user, test_user)

    def test_accounts(
            self, client, initial_data,                         # noqa: F811
            account_data,                                       # noqa: F811
            basic_auth_admin_headers):                          # noqa: F811
        account_name = account_data["name"]
        self.client = client
        self.basic_auth_admin_headers = basic_auth_admin_headers

        # Create account
        res = client.post(
            "/api/v1/pdnsadmin/accounts",
            headers=basic_auth_admin_headers,
            data=json.dumps(account_data),
            content_type="application/json",
        )
        data = res.get_json(force=True)
        assert res.status_code == 201

        # Check account
        data = self.check_account(account_data)
        account_id = data["id"]

        updated = account_data.copy()
        # Update and check values
        for upd_key in ["description", "contact", "mail"]:
            upd_value = "upd-{}".format(account_data[upd_key])

            # Update
            data = {"name": account_name, upd_key: upd_value}
            res = client.put(
                "/api/v1/pdnsadmin/accounts/{}".format(account_id),
                data=json.dumps(data),
                headers=basic_auth_admin_headers,
                content_type="application/json",
            )
            assert res.status_code == 204
            updated[upd_key] = upd_value

            # Check
            data = self.check_account(updated)

        # Update to defaults
        res = client.put(
            "/api/v1/pdnsadmin/accounts/{}".format(account_id),
            data=json.dumps(account_data),
            headers=basic_auth_admin_headers,
            content_type="application/json",
        )
        assert res.status_code == 204

        # Check account
        res = client.get(
            "/api/v1/pdnsadmin/accounts/{}".format(account_name),
            headers=basic_auth_admin_headers,
            content_type="application/json",
        )
        data = res.get_json(force=True)
        assert res.status_code == 200
        assert len(data) == 1
        data = data[0]
        account_id = data["id"]
        for key, value in account_data.items():
            assert data[key] == value

        # Cleanup (delete account)
        res = client.delete(
            "/api/v1/pdnsadmin/accounts/{}".format(account_id),
            data=json.dumps(account_data),
            headers=basic_auth_admin_headers,
            content_type="application/json",
        )
        assert res.status_code == 204

        # Get non-existing account (should fail)
        data = self.get_account(account_name, status_code=404)

        # Update non-existing account (should fail)
        res = client.put(
            "/api/v1/pdnsadmin/accounts/{}".format(account_id),
            data=json.dumps(account_data),
            headers=basic_auth_admin_headers,
            content_type="application/json",
        )
        assert res.status_code == 404

        # Delete non-existing account (should fail)
        res = client.delete(
            "/api/v1/pdnsadmin/accounts/{}".format(account_id),
            data=json.dumps(account_data),
            headers=basic_auth_admin_headers,
            content_type="application/json",
        )
        assert res.status_code == 404

    def test_users(
            self, client, initial_data,                         # noqa: F811
            user1_data,                                         # noqa: F811
            basic_auth_admin_headers):                          # noqa: F811
        user1name = user1_data["username"]
        self.client = client
        self.basic_auth_admin_headers = basic_auth_admin_headers

        # Create user (user1)
        res = client.post(
            "/api/v1/pdnsadmin/users",
            headers=basic_auth_admin_headers,
            data=json.dumps(user1_data),
            content_type="application/json",
        )
        data = res.get_json(force=True)
        assert res.status_code == 201
        assert len(data) == 1

        # Check user
        user1 = self.check_user(user1_data, data[0])
        user1_id = user1["id"]

        updated = user1_data.copy()
        # Update and check values
        for upd_key in ["firstname", "lastname", "email"]:
            upd_value = "upd-{}".format(user1_data[upd_key])

            # Update
            data = {"username": user1name, upd_key: upd_value}
            res = client.put(
                "/api/v1/pdnsadmin/users/{}".format(user1_id),
                data=json.dumps(data),
                headers=basic_auth_admin_headers,
                content_type="application/json",
            )
            assert res.status_code == 204
            updated[upd_key] = upd_value

            # Check
            data = self.check_user(updated)

        # Update to defaults
        res = client.put(
            "/api/v1/pdnsadmin/users/{}".format(user1_id),
            data=json.dumps(user1_data),
            headers=basic_auth_admin_headers,
            content_type="application/json",
        )
        assert res.status_code == 204

        # Check user
        self.check_user(user1_data)

        # Cleanup (delete user)
        res = client.delete(
            "/api/v1/pdnsadmin/users/{}".format(user1_id),
            data=json.dumps(user1_data),
            headers=basic_auth_admin_headers,
            content_type="application/json",
        )
        assert res.status_code == 204

        # Get non-existing user (should fail)
        data = self.get_user(user1name, status_code=404)

        # Update non-existing user (should fail)
        res = client.put(
            "/api/v1/pdnsadmin/users/{}".format(user1_id),
            data=json.dumps(user1_data),
            headers=basic_auth_admin_headers,
            content_type="application/json",
        )
        assert res.status_code == 404

        # Delete non-existing user (should fail)
        res = client.delete(
            "/api/v1/pdnsadmin/users/{}".format(user1_id),
            data=json.dumps(user1_data),
            headers=basic_auth_admin_headers,
            content_type="application/json",
        )
        assert res.status_code == 404

    def test_account_users(
            self, client, initial_data,                         # noqa: F811
            test_user, account_data, user1_data,                # noqa: F811
            basic_auth_admin_headers):                          # noqa: F811
        self.client = client
        self.basic_auth_admin_headers = basic_auth_admin_headers
        test_user_id = self.get_user(test_user)["id"]

        # Create account
        res = client.post(
            "/api/v1/pdnsadmin/accounts",
            headers=basic_auth_admin_headers,
            data=json.dumps(account_data),
            content_type="application/json",
        )
        data = res.get_json(force=True)
        assert res.status_code == 201

        # Check account
        data = self.check_account(account_data)
        account_id = data["id"]

        # Create user1
        res = client.post(
            "/api/v1/pdnsadmin/users",
            headers=basic_auth_admin_headers,
            data=json.dumps(user1_data),
            content_type="application/json",
        )
        data = res.get_json(force=True)
        assert res.status_code == 201
        assert len(data) == 1

        # Check user
        user1 = self.check_user(user1_data, data[0])
        user1_id = user1["id"]

        # Assert test account has no users
        res = client.get(
            "/api/v1/pdnsadmin/accounts/users/{}".format(account_id),
            headers=basic_auth_admin_headers,
            content_type="application/json",
        )
        data = res.get_json(force=True)
        assert res.status_code == 200
        assert data == []

        # Assert unlinking an unlinked account fails
        res = client.delete(
            "/api/v1/pdnsadmin/accounts/users/{}/{}".format(
                account_id, user1_id),
            headers=basic_auth_admin_headers,
            content_type="application/json",
        )
        assert res.status_code == 404

        # Link user to account
        res = client.put(
            "/api/v1/pdnsadmin/accounts/users/{}/{}".format(
                account_id, user1_id),
            headers=basic_auth_admin_headers,
            content_type="application/json",
        )
        assert res.status_code == 204

        # Check user is linked to account
        res = client.get(
            "/api/v1/pdnsadmin/accounts/users/{}".format(account_id),
            headers=basic_auth_admin_headers,
            content_type="application/json",
        )
        data = res.get_json(force=True)
        assert res.status_code == 200
        assert len(data) == 1
        self.check_user(user1_data, data[0])

        # Unlink user from account
        res = client.delete(
            "/api/v1/pdnsadmin/accounts/users/{}/{}".format(
                account_id, user1_id),
            headers=basic_auth_admin_headers,
            content_type="application/json",
        )
        assert res.status_code == 204

        # Check user is unlinked from account
        res = client.get(
            "/api/v1/pdnsadmin/accounts/users/{}".format(account_id),
            headers=basic_auth_admin_headers,
            content_type="application/json",
        )
        data = res.get_json(force=True)
        assert res.status_code == 200
        assert data == []

        # Unlink unlinked user from account (should fail)
        res = client.delete(
            "/api/v1/pdnsadmin/accounts/users/{}/{}".format(
                account_id, user1_id),
            headers=basic_auth_admin_headers,
            content_type="application/json",
        )
        assert res.status_code == 404

        # Cleanup (delete user)
        res = client.delete(
            "/api/v1/pdnsadmin/users/{}".format(user1_id),
            data=json.dumps(user1_data),
            headers=basic_auth_admin_headers,
            content_type="application/json",
        )
        assert res.status_code == 204

        # Link non-existing user to account (should fail)
        res = client.put(
            "/api/v1/pdnsadmin/accounts/users/{}/{}".format(
                account_id, user1_id),
            headers=basic_auth_admin_headers,
            content_type="application/json",
        )
        assert res.status_code == 404

        # Unlink non-exiting user from account (should fail)
        res = client.delete(
            "/api/v1/pdnsadmin/accounts/users/{}/{}".format(
                account_id, user1_id),
            headers=basic_auth_admin_headers,
            content_type="application/json",
        )
        assert res.status_code == 404

        # Cleanup (delete account)
        res = client.delete(
            "/api/v1/pdnsadmin/accounts/{}".format(account_id),
            data=json.dumps(account_data),
            headers=basic_auth_admin_headers,
            content_type="application/json",
        )
        assert res.status_code == 204

        # List users in non-existing account (should fail)
        res = client.get(
            "/api/v1/pdnsadmin/accounts/users/{}".format(account_id),
            headers=basic_auth_admin_headers,
            content_type="application/json",
        )
        assert res.status_code == 404

        # Link existing user to non-existing account (should fail)
        res = client.put(
            "/api/v1/pdnsadmin/accounts/users/{}/{}".format(
                account_id, test_user_id),
            headers=basic_auth_admin_headers,
            content_type="application/json",
        )
        assert res.status_code == 404


text:
package dotty.tools
package dotc
package core
package tasty

import Contexts._, SymDenotations._
import dotty.tools.dotc.ast.tpd
import TastyUnpickler._, TastyBuffer._
import util.Positions._
import util.{SourceFile, NoSource}
import PositionUnpickler._
import classfile.ClassfileParser

object DottyUnpickler {

  /** Exception thrown if classfile is corrupted */
  class BadSignature(msg: String) extends RuntimeException(msg)
}

/** A class for unpickling Tasty trees and symbols.
 *  @param bytes         the bytearray containing the Tasty file from which we unpickle
 */
class DottyUnpickler(bytes: Array[Byte]) extends ClassfileParser.Embedded {
  import tpd._

  private val unpickler = new TastyUnpickler(bytes)
  private val treeUnpickler = unpickler.unpickle(new TreeSectionUnpickler).get

  /** Enter all toplevel classes and objects into their scopes
   *  @param roots          a set of SymDenotations that should be overwritten by unpickling
   */
  def enter(roots: Set[SymDenotation])(implicit ctx: Context): Unit =
    treeUnpickler.enterTopLevel(roots)

  /** The unpickled trees, and the source file they come from
   *  @param readPositions if true, trees get decorated with position information.
   */
  def body(readPositions: Boolean = false)(implicit ctx: Context): (List[Tree], SourceFile) = {
    val source = unpickler.unpickle(new SourceFileUnpickler).getOrElse(NoSource)
    if (readPositions)
      for ((totalRange, positions) <- unpickler.unpickle(new PositionsSectionUnpickler))
        treeUnpickler.usePositions(totalRange, positions)
    (treeUnpickler.unpickle(), source)
  }

  private class SourceFileUnpickler extends SectionUnpickler[SourceFile]("Sourcefile") {
    def unpickle(reader: TastyReader, tastyName: TastyName.Table) =
      new SourceFile(tastyName(reader.readNameRef()).toString, Seq())
  }

  private class TreeSectionUnpickler extends SectionUnpickler[TreeUnpickler]("ASTs") {
    def unpickle(reader: TastyReader, tastyName: TastyName.Table) =
      new TreeUnpickler(reader, tastyName)
  }

  private class PositionsSectionUnpickler extends SectionUnpickler[(Position, AddrToPosition)]("Positions") {
    def unpickle(reader: TastyReader, tastyName: TastyName.Table) =
      new PositionUnpickler(reader).unpickle()
  }
}

redpajama_set_name: RedPajamaGithub


text:
package com.datasift.connector.writer;

/**
 * Defines globally available message constants for logging.
 */
public final class Messages {

    /**
     * Prevent construction.
     */
    private Messages() { }

    // Configuration loading
    /**
     * Configuration message stating file is not valid JSON.
     */
    public static final String CONFIG_NOT_JSON =
            "Error parsing config provided. "
            + "Configuration file must be valid JSON & adhere to "
            + "format set in configuration documentation";

    /**
     * Configuration message stating required items are missing.
     */
    public static final String CONFIG_MISSING_ITEMS =
            "Empty or missing configuration options provided. "
            + "Configuration file must adhere to format set in "
            + "configuration documentation";

    /**
     * Configuration message stating file is not readable.
     */
    public static final String CONFIG_NOT_READABLE =
            "Error reading configuration file provided";

    // Service shut-down
    /**
     * Service message stating command line usage is incorrect.
     */
    public static final String EXIT_ARGUMENTS_EMPTY =
            "No arguments provided. "
            + "Usage: java -cp './*' "
            + "com.datasift.connector.DataSiftWriter "
            + "/etc/datasift/writer.json";

    /**
     * Service message stating that configuration parsing failed.
     */
    public static final String EXIT_CONFIG =
            "Service shutting down due to configuration error";
}


text:
<?php namespace App\Models;

use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;

use Sentry;

class User extends \Cartalyst\Sentry\Users\Eloquent\User implements UserInterface, RemindableInterface {

	use UserTrait, RemindableTrait;

	/**
	 * The database table used by the model.
	 *
	 * @var string
	 */
	protected $table = 'users';

  /**
   * The attributes that are mass assignable.
   *
   * @var array
   */
  protected $fillable = array(
    'email',
    'password',
    'first_name',
    'last_name',
    'profile_picture',
    'fb_id'
  );

	/**
	 * The attributes excluded from the model's JSON form.
	 *
	 * @var array
	 */
	protected $hidden = array(
		'password',
    'old_password',
		'reset_password_code',
		'activation_code',
		'remember_token'
	);

  /**
   * function isAdmin
   *
   * @return string
   */
  public function isAdmin()
  {
    return Sentry::check() && Sentry::getUser()->hasAccess('admin');
  }

}


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="chrome=1">
        <title>rTree Map Demo</title>
        <meta name="description" content="Demo of rTree.js with leaflet">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">

        <link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.6.4/leaflet.css" />

   <link rel="stylesheet" href="libs/gh-fork-ribbon.css" />

    <link rel="stylesheet" href="libs/bootstrap/css/bootstrap.css" />

            Fork me on GitHub

          <button type="button" class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">

          </button>
          rTree

Worker Example

    About

Move the map to watch it recompute based on the bounds,
also if you hold down shift you can put in your own bbox
and right click (or scroll) to remove it


text:
package profile

import (
	"io/ioutil"
	"log"
	"os"
	"os/signal"
	"path/filepath"
	"runtime"
	"runtime/pprof"
	"sync/atomic"
)

const (
	cpuMode = iota
	memMode
	blockMode
	traceMode
)

// Profile represents an active profiling session.
type Profile struct {
	// quiet suppresses informational messages during profiling.
	quiet bool

	// noShutdownHook controls whether the profiling package should
	// hook SIGINT to write profiles cleanly.
	noShutdownHook bool

	// mode holds the type of profiling that will be made
	mode int

	// path holds the base path where various profiling files are  written.
	// If blank, the base path will be generated by ioutil.TempDir.
	path string

	// memProfileRate holds the rate for the memory profile.
	memProfileRate int

	// closer holds a cleanup function that run after each profile
	closer func()

	// stopped records if a call to profile.Stop has been made
	stopped uint32
}

// NoShutdownHook controls whether the profiling package should
// hook SIGINT to write profiles cleanly.
// Programs with more sophisticated signal handling should set
// this to true and ensure the Stop() function returned from Start()
// is called during shutdown.
func NoShutdownHook(p *Profile) { p.noShutdownHook = true }

// Quiet suppresses informational messages during profiling.
func Quiet(p *Profile) { p.quiet = true }

// CPUProfile enables cpu profiling.
// It disables any previous profiling settings.
func CPUProfile(p *Profile) { p.mode = cpuMode }

// DefaultMemProfileRate is the default memory profiling rate.
// See also http://golang.org/pkg/runtime/#pkg-variables
const DefaultMemProfileRate = 4096

// MemProfile enables memory profiling.
// It disables any previous profiling settings.
func MemProfile(p *Profile) {
	p.memProfileRate = DefaultMemProfileRate
	p.mode = memMode
}

// MemProfileRate enables memory profiling at the preferred rate.
// It disables any previous profiling settings.
func MemProfileRate(rate int) func(*Profile) {
	return func(p *Profile) {
		p.memProfileRate = rate
		p.mode = memMode
	}
}

// BlockProfile enables block (contention) profiling.
// It disables any previous profiling settings.
func BlockProfile(p *Profile) { p.mode = blockMode }

// Trace profile controls if execution tracing will be enabled. It disables any previous profiling settings.
func TraceProfile(p *Profile) { p.mode = traceMode }

// ProfilePath controls the base path where various profiling
// files are written. If blank, the base path will be generated
// by ioutil.TempDir.
func ProfilePath(path string) func(*Profile) {
	return func(p *Profile) {
		p.path = path
	}
}

// Stop stops the profile and flushes any unwritten data.
func (p *Profile) Stop() {
	if !atomic.CompareAndSwapUint32(&p.stopped, 0, 1) {
		// someone has already called close
		return
	}
	p.closer()
	atomic.StoreUint32(&started, 0)
}

// started is non zero if a profile is running.
var started uint32

// Start starts a new profiling session.
// The caller should call the Stop method on the value returned
// to cleanly stop profiling.
func Start(options ...func(*Profile)) interface {
	Stop()
} {
	if !atomic.CompareAndSwapUint32(&started, 0, 1) {
		log.Fatal("profile: Start() already called")
	}

	var prof Profile
	for _, option := range options {
		option(&prof)
	}

	path, err := func() (string, error) {
		if p := prof.path; p != "" {
			return p, os.MkdirAll(p, 0777)
		}
		return ioutil.TempDir("", "profile")
	}()

	if err != nil {
		log.Fatalf("profile: could not create initial output directory: %v", err)
	}

	logf := func(format string, args ...interface{}) {
		if !prof.quiet {
			log.Printf(format, args...)
		}
	}

	switch prof.mode {
	case cpuMode:
		fn := filepath.Join(path, "cpu.pprof")
		f, err := os.Create(fn)
		if err != nil {
			log.Fatalf("profile: could not create cpu profile %q: %v", fn, err)
		}
		logf("profile: cpu profiling enabled, %s", fn)
		pprof.StartCPUProfile(f)
		prof.closer = func() {
			pprof.StopCPUProfile()
			f.Close()
			logf("profile: cpu profiling disabled, %s", fn)
		}

	case memMode:
		fn := filepath.Join(path, "mem.pprof")
		f, err := os.Create(fn)
		if err != nil {
			log.Fatalf("profile: could not create memory profile %q: %v", fn, err)
		}
		old := runtime.MemProfileRate
		runtime.MemProfileRate = prof.memProfileRate
		logf("profile: memory profiling enabled (rate %d), %s", runtime.MemProfileRate, fn)
		prof.closer = func() {
			pprof.Lookup("heap").WriteTo(f, 0)
			f.Close()
			runtime.MemProfileRate = old
			logf("profile: memory profiling disabled, %s", fn)
		}

	case blockMode:
		fn := filepath.Join(path, "block.pprof")
		f, err := os.Create(fn)
		if err != nil {
			log.Fatalf("profile: could not create block profile %q: %v", fn, err)
		}
		runtime.SetBlockProfileRate(1)
		logf("profile: block profiling enabled, %s", fn)
		prof.closer = func() {
			pprof.Lookup("block").WriteTo(f, 0)
			f.Close()
			runtime.SetBlockProfileRate(0)
			logf("profile: block profiling disabled, %s", fn)
		}

	case traceMode:
		fn := filepath.Join(path, "trace.out")
		f, err := os.Create(fn)
		if err != nil {
			log.Fatalf("profile: could not create trace output file %q: %v", fn, err)
		}
		if err := startTrace(f); err != nil {
			log.Fatalf("profile: could not start trace: %v", err)
		}
		logf("profile: trace enabled, %s", fn)
		prof.closer = func() {
			stopTrace()
			logf("profile: trace disabled, %s", fn)
		}
	}

	if !prof.noShutdownHook {
		go func() {
			c := make(chan os.Signal, 1)
			signal.Notify(c, os.Interrupt)
			<-c

			log.Println("profile: caught interrupt, stopping profiles")
			prof.Stop()

			os.Exit(0)
		}()
	}

	return &prof
}


text:
using System;
using System.Threading.Tasks;
using Windows.Devices.Enumeration;
using Windows.Devices.I2c;
using Windows.Foundation.Metadata;

namespace ABElectronics_Win10IOT_Libraries
{
    /// <summary>
    ///     Class for controlling the RTC Pi and RTC Pi Plus expansion boards from AB Electronics UK
    ///     Based on the DS1307 real-time clock from Maxim.
    /// </summary>
    public class RTCPi : IDisposable
    {
        // Register addresses for the DS1307 IC
        private const byte SECONDS = 0x00;
        private const byte MINUTES = 0x01;
        private const byte HOURS = 0x02;
        private const byte DAYOFWEEK = 0x03;
        private const byte DAY = 0x04;
        private const byte MONTH = 0x05;
        private const byte YEAR = 0x06;
        private const byte CONTROL = 0x07;

        // the DS1307 does not store the current century so that has to be added on manually.
        private readonly int century = 2000;

        // initial configuration - square wave and output disabled, frequency set to 32.768KHz.
        private byte config = 0x03;
        private readonly ABE_Helpers helper = new ABE_Helpers();

        private I2cDevice i2cbus; // create an instance of the i2c bus.

        // variables
        private readonly byte rtcAddress = 0x68; // I2C address

        // Flag: Has Dispose already been called?
        bool disposed = false;
        // Instantiate a SafeHandle instance.
        System.Runtime.InteropServices.SafeHandle handle = new Microsoft.Win32.SafeHandles.SafeFileHandle(IntPtr.Zero, true);

        /// <summary>
        ///     Create an instance of a RTC Pi bus.
        /// </summary>
        public RTCPi()
        {
            IsConnected = false;
        }

        /// <summary>
        ///     Shows if there is a connection with the RTC Pi.
        /// </summary>
        public bool IsConnected { get; private set; }

        /// <summary>
        ///     Open a connection with the RTC Pi.
        /// </summary>
        /// <returns></returns>
        public async Task Connect()
        {
            if (IsConnected)
            {
                return; // Already connected
            }

            if (!ApiInformation.IsTypePresent("Windows.Devices.I2c.I2cDevice"))
            {
                return; // This system does not support this feature: can't connect
            }

            /* Initialize the I2C bus */
            try
            {
                var aqs = I2cDevice.GetDeviceSelector(ABE_Helpers.I2C_CONTROLLER_NAME); // Find the selector string for the I2C bus controller
                var dis = await DeviceInformation.FindAllAsync(aqs); // Find the I2C bus controller device with our selector string

                if (dis.Count == 0)
                {
                    return; // Controller not found
                }

                var settings = new I2cConnectionSettings(rtcAddress) {BusSpeed = I2cBusSpeed.FastMode};

                i2cbus = await I2cDevice.FromIdAsync(dis[0].Id, settings); // Create an I2cDevice with our selected bus controller and I2C settings
                if (i2cbus != null)
                {
                    // i2c bus is connected so set IsConnected to true and fire the Connected event handler
                    IsConnected = true;

                    // Fire the Connected event handler
                    Connected?.Invoke(this, EventArgs.Empty);
                }
            }
            catch (Exception ex)
            {
                IsConnected = false;
                throw new Exception("I2C Initialization Failed", ex);
            }
        }

        /// <summary>
        ///     Event occurs when connection is made.
        /// </summary>
        public event EventHandler Connected;

        /// <summary>
        ///     Converts BCD format to integer.
        /// </summary>
        /// <param name="x">BCD formatted byte</param>
        /// <returns></returns>
        private int BCDtoInt(byte x)
        {
            return x - 6 * (x >> 4);
        }

        /// <summary>
        ///     Converts byte to BCD format.
        /// </summary>
        /// <param name="val">value to convert</param>
        /// <returns>Converted byte</returns>
        private byte BytetoBCD(int val)
        {
            return (byte) (val / 10 * 16 + val % 10);
        }

        /// <summary>
        ///     Set the date and time on the RTC.
        /// </summary>
        /// <param name="date">DateTime</param>
        public void SetDate(DateTime date)
        {
            CheckConnected();

            helper.WriteI2CByte(i2cbus, SECONDS, BytetoBCD(date.Second));
            helper.WriteI2CByte(i2cbus, MINUTES, BytetoBCD(date.Minute));
            helper.WriteI2CByte(i2cbus, HOURS, BytetoBCD(date.Hour));
            helper.WriteI2CByte(i2cbus, DAYOFWEEK, BytetoBCD((int) date.DayOfWeek));
            helper.WriteI2CByte(i2cbus, DAY, BytetoBCD(date.Day));
            helper.WriteI2CByte(i2cbus, MONTH, BytetoBCD(date.Month));
            helper.WriteI2CByte(i2cbus, YEAR, BytetoBCD(date.Year - century));
        }

        /// <summary>
        ///     Read the date and time from the RTC.
        /// </summary>
        /// <returns>DateTime</returns>
        public DateTime ReadDate()
        {
            CheckConnected();

            var DateArray = helper.ReadI2CBlockData(i2cbus, 0, 7);
            var year = BCDtoInt(DateArray[6]) + century;
            var month = BCDtoInt(DateArray[5]);
            var day = BCDtoInt(DateArray[4]);
            // var dayofweek = BCDtoInt(DateArray[3]);
            var hours = BCDtoInt(DateArray[2]);
            var minutes = BCDtoInt(DateArray[1]);
            var seconds = BCDtoInt(DateArray[0]);

            try
            {
                var date = new DateTime(year, month, day, hours, minutes, seconds);
                return date;
            }
            catch
            {
                var date = new DateTime(1990, 01, 01, 01, 01, 01);
                return date;
            }
        }

        /// <summary>
        ///     Enable the clock output pin.
        /// </summary>
        public void EnableOutput()
        {
            CheckConnected();

            config = helper.UpdateByte(config, 7, true);
            config = helper.UpdateByte(config, 4, true);
            helper.WriteI2CByte(i2cbus, CONTROL, config);
        }

        /// <summary>
        ///     Disable the clock output pin.
        /// </summary>
        public void DisableOutput()
        {
            CheckConnected();

            config = helper.UpdateByte(config, 7, false);
            config = helper.UpdateByte(config, 4, false);
            helper.WriteI2CByte(i2cbus, CONTROL, config);
        }

        /// <summary>
        ///     Set the frequency of the output pin square-wave.
        /// </summary>
        /// <param name="frequency">options are: 1 = 1Hz, 2 = 4.096KHz, 3 = 8.192KHz, 4 = 32.768KHz</param>
        public void SetFrequency(byte frequency)
        {
            CheckConnected();

            switch (frequency)
            {
                case 1:
                    config = helper.UpdateByte(config, 0, false);
                    config = helper.UpdateByte(config, 1, false);
                    break;
                case 2:
                    config = helper.UpdateByte(config, 0, true);
                    config = helper.UpdateByte(config, 1, false);
                    break;
                case 3:
                    config = helper.UpdateByte(config, 0, false);
                    config = helper.UpdateByte(config, 1, true);
                    break;
                case 4:
                    config = helper.UpdateByte(config, 0, true);
                    config = helper.UpdateByte(config, 1, true);
                    break;
                default:
                    throw new ArgumentOutOfRangeException(nameof(frequency));
            }
            helper.WriteI2CByte(i2cbus, CONTROL, config);
        }

        private void CheckConnected()
        {
            if (!IsConnected)
            {
                throw new InvalidOperationException("Not connected. You must call .Connect() first.");
            }
        }

        /// <summary>
        ///     Dispose of the resources
        /// </summary>
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        /// <summary>
        /// Protected implementation of Dispose pattern
        /// </summary>
        /// <param name="disposing"></param>
        protected virtual void Dispose(bool disposing)
        {
            if (disposed)
                return;

            if (disposing)
            {
                handle.Dispose();
                // Free any other managed objects here.
                i2cbus?.Dispose();
                i2cbus = null;

                IsConnected = false;
            }

            // Free any unmanaged objects here.
            //
            disposed = true;
        }
    }
}


text:
enum TaskStatus {
    UNACCEPTABLE,
    ACCEPTABLE,
    DURING,
    CAN_SUMBIT,
    SUBMITTED
}
enum ErrorCode{
    SUCCESS,
    FAILED
}


text:
using ::testing::TestWithParam;
using ::testing::Values;

// As a general rule, to prevent a test from affecting the tests that come
// after it, you should create and destroy the tested objects for each test
// instead of reusing them.  In this sample we will define a simple factory
// function for PrimeTable objects.  We will instantiate objects in test's
// SetUp() method and delete them in TearDown() method.
// 按照通常的惯例,已经被测试过的实体不应该在多个测试之间重复利用,所以你应该为每个测试创建并销毁他们
// 在这个例子中我们将为PrimeTable实体定义一个简单的工厂方法,他们将在测试的SetUp()方法中实例化实体并且在TearDown()中删除他们
typedef PrimeTable* CreatePrimeTableFunc();

PrimeTable* CreateOnTheFlyPrimeTable() {
  return new OnTheFlyPrimeTable();
}

template <size_t max_precalculated>
PrimeTable* CreatePreCalculatedPrimeTable() {
  return new PreCalculatedPrimeTable(max_precalculated);
}

// Inside the test body, fixture constructor, SetUp(), and TearDown() you
// can refer to the test parameter by GetParam().  In this case, the test
// parameter is a factory function which we call in fixture's SetUp() to
// create and store an instance of PrimeTable.
// 在测试体、fixture的构造函数、 SetUp(), 和 TearDown()里,你可以通过GetParam()函数来指向测试参数。
// 在这个案例中,这个测试参数是一个PrimeTableFactory接口的指针。
// 我们用这个指针在fixture的SetUp()函数中去创建和存储PrimeTable的一个实例
class PrimeTableTest : public TestWithParam<CreatePrimeTableFunc*> {
 public:
  virtual ~PrimeTableTest() { delete table_; }
  virtual void SetUp() { table_ = (*GetParam())(); }
  virtual void TearDown() {
    delete table_;
    table_ = NULL;
  }

 protected:
  PrimeTable* table_;
};

TEST_P(PrimeTableTest, ReturnsFalseForNonPrimes) {
  EXPECT_FALSE(table_->IsPrime(-5));
  EXPECT_FALSE(table_->IsPrime(0));
  EXPECT_FALSE(table_->IsPrime(1));
  EXPECT_FALSE(table_->IsPrime(4));
  EXPECT_FALSE(table_->IsPrime(6));
  EXPECT_FALSE(table_->IsPrime(100));
}

TEST_P(PrimeTableTest, ReturnsTrueForPrimes) {
  EXPECT_TRUE(table_->IsPrime(2));
  EXPECT_TRUE(table_->IsPrime(3));
  EXPECT_TRUE(table_->IsPrime(5));
  EXPECT_TRUE(table_->IsPrime(7));
  EXPECT_TRUE(table_->IsPrime(11));
  EXPECT_TRUE(table_->IsPrime(131));
}

TEST_P(PrimeTableTest, CanGetNextPrime) {
  EXPECT_EQ(2, table_->GetNextPrime(0));
  EXPECT_EQ(3, table_->GetNextPrime(2));
  EXPECT_EQ(5, table_->GetNextPrime(3));
  EXPECT_EQ(7, table_->GetNextPrime(5));
  EXPECT_EQ(11, table_->GetNextPrime(7));
  EXPECT_EQ(131, table_->GetNextPrime(128));
}

// In order to run value-parameterized tests, you need to instantiate them,
// or bind them to a list of values which will be used as test parameters.
// You can instantiate them in a different translation module, or even
// instantiate them several times.
// 为了运行这个值参数化测试,你需要实例化他们并且把他们绑定到可能被用作测试参数的一系列值上,
// 你可以在一个不同的调用模块实例化他们,甚至可以实例化他们多次
// Here, we instantiate our tests with a list of two PrimeTable object
// factory functions:
// 在这里,我们利用两个PrimeTable实体工程方法的列表来实例化我们的测试
INSTANTIATE_TEST_CASE_P(
    OnTheFlyAndPreCalculated,
    PrimeTableTest,
    Values(&CreateOnTheFlyPrimeTable, &CreatePreCalculatedPrimeTable<1000>));

#else

// Google Test may not support value-parameterized tests with some
// compilers. If we use conditional compilation to compile out all
// code referring to the gtest_main library, MSVC linker will not link
// that library at all and consequently complain about missing entry
// point defined in that library (fatal error LNK1561: entry point
// must be defined). This dummy test keeps gtest_main linked in.
TEST(DummyTest, ValueParameterizedTestsAreNotSupportedOnThisPlatform) {}

#endif  // GTEST_HAS_PARAM_TEST


text:
namespace AcademyRPG.Models
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    public class House : StaticObject
    {
        private const int houseHitPoints = 500;

        public House(Point position, int owner) : base(position, owner)
        {
            this.HitPoints = houseHitPoints;
        }
    }
}


text:
#ifndef PROJECT_NOTES_H
#define PROJECT_NOTES_H

#include <QMainWindow>
#include <QCloseEvent>

#include "SerializingObject.h"

class QAction;
class QComboBox;
class QTextCharFormat;
class QTextEdit;

class EXPORT ProjectNotes : public QMainWindow, public SerializingObject
{
	Q_OBJECT
public:
	ProjectNotes();
	virtual ~ProjectNotes();

	void clear();
	void setText( const QString & _text );

	virtual void saveSettings( QDomDocument & _doc, QDomElement & _parent );
	virtual void loadSettings( const QDomElement & _this );

	inline virtual QString nodeName() const
	{
		return "projectnotes";
	}

protected:
	virtual void closeEvent( QCloseEvent * _ce );
	void setupActions();

private slots:
	void textBold();
	void textUnderline();
	void textItalic();
	void textFamily( const QString & _f );
	void textSize( const QString & _p );
	void textColor();
	void textAlign( QAction * _a );

	void formatChanged( const QTextCharFormat & _f );
	void alignmentChanged( int _a );

private:
	QTextEdit * m_edit;
	QAction * m_actionTextBold,
		* m_actionTextUnderline,
		* m_actionTextItalic,
		* m_actionTextColor,
		* m_actionAlignLeft,
		* m_actionAlignCenter,
		* m_actionAlignRight,
		* m_actionAlignJustify;
	QComboBox * m_comboFont;
	QComboBox * m_comboSize;

} ;

#endif


text:
package ru.job4j.generic;

import org.junit.Test;
import org.junit.Before;

import java.util.Iterator;

import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;

/**
 * Test.
 *
 * @author Natasha Panchina (panchinanata25@gmail.com)
 * @version 1
 * @since 14.02.2019
 */
public class SimpleArrayTest {
    SimpleArray<Integer> simpleArray;

    @Before
    public void create() {
        simpleArray = new SimpleArray<>(3);
        simpleArray.add(1);
        simpleArray.add(2);
        simpleArray.add(3);
    }

    @Test(expected = IndexOutOfBoundsException.class)
    public void whenAddUnnecessaryElementThenThrowException() {
        simpleArray.add(4);
    }

    @Test
    public void whenSetElementThenArrayShouldHaveNewValue() {
        simpleArray.set(0, 10);
        assertThat(simpleArray.get(0), is(10));
    }

    @Test
    public void whenRemoveElementFromArrayThanElementsShouldMove() {
        simpleArray.remove(1);
        assertThat(simpleArray.get(1), is(3));
    }

    @Test
    public void whenCreateArrayIterator() {
        Iterator<Integer> it = simpleArray.iterator();
        assertThat(it.hasNext(), is(true));
        assertThat(it.next(), is(1));
        assertThat(it.next(), is(2));
        assertThat(it.hasNext(), is(true));
        assertThat(it.next(), is(3));
        assertThat(it.hasNext(), is(false));
    }
}


text:
.asset-container .asset-path {
    display: none;
    white-space: nowrap;
    margin-top: .3em;
    position: absolute;
}

.asset-container .list-group-item-text {
    align-self: flex-start;
    transition: all .5s;
}

.asset-container:hover .asset-path {
    display: block;
}


text:
import QueryProxyInternal from './-query-proxy';

export default class ArrayProxyInternal extends QueryProxyInternal {

  _createModel() {
    return this.store._createArrayProxy(this);
  }

  get _loaderType() {
    return 'find';
  }

  get values() {
    return this.filter(true).values;
  }

}


text:
package com.cloud.network.dao;

import java.util.List;

import org.springframework.stereotype.Component;

import com.cloud.network.element.OvsProviderVO;
import com.cloud.utils.db.DB;
import com.cloud.utils.db.GenericDaoBase;
import com.cloud.utils.db.SearchBuilder;
import com.cloud.utils.db.SearchCriteria;

@Component
@DB()
public class OvsProviderDaoImpl extends GenericDaoBase<OvsProviderVO, Long>
        implements OvsProviderDao {
    final SearchBuilder<OvsProviderVO> AllFieldsSearch;

    public OvsProviderDaoImpl() {
        super();
        AllFieldsSearch = createSearchBuilder();
        AllFieldsSearch.and("id", AllFieldsSearch.entity().getId(),
            SearchCriteria.Op.EQ);
        AllFieldsSearch.and("nsp_id", AllFieldsSearch.entity().getNspId(),
            SearchCriteria.Op.EQ);
        AllFieldsSearch.and("uuid", AllFieldsSearch.entity().getUuid(),
            SearchCriteria.Op.EQ);
        AllFieldsSearch.and("enabled", AllFieldsSearch.entity().isEnabled(),
            SearchCriteria.Op.EQ);
        AllFieldsSearch.done();
    }

    @Override
    public OvsProviderVO findByNspId(long nspId) {
        SearchCriteria<OvsProviderVO> sc = AllFieldsSearch.create();
        sc.setParameters("nsp_id", nspId);
        return findOneBy(sc);
    }

    @Override
    public List<OvsProviderVO> listByEnabled(boolean enabled) {
        SearchCriteria<OvsProviderVO> sc = AllFieldsSearch.create();
        sc.setParameters("enabled", enabled);
        return listBy(sc);
    }

    @Override
    public OvsProviderVO findByIdAndEnabled(long id, boolean enabled) {
        SearchCriteria<OvsProviderVO> sc = AllFieldsSearch.create();
        sc.setParameters("id", id);
        sc.setParameters("enabled", enabled);
        return findOneBy(sc);
    }
}


text:
/**
 * Fisher–Yates shuffle implementation - https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#The_modern_algorithm
 */
export default function shuffle<T>(array: T[]): T[] {
    const arrayCopy = [...array];
    for (let i = arrayCopy.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [arrayCopy[i], arrayCopy[j]] = [arrayCopy[j], arrayCopy[i]];
    }

    return arrayCopy;
}


text:
<?php
namespace AsyncHTTP;

class Response
{
    /*** var @int HTTP status code */
    protected $status_code;

    /*** @var array */
    protected $headers = [];

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

    /*** @var \Exception */
    protected $exception;

    /**
     * @param string Response message
     */
    public function parseMessage($message)
    {
        $lines = explode("\n", $message);

        $lines_num = count($lines);
        if ($lines_num == 0) {
            return false;
        }

        preg_match("/^HTTP\/\d\.\d\s(\d{3})/", $lines[0], $matches);
        if (!isset($matches[1])) {
            return false;
        }

        $this->status_code = (int)$matches[1];

        $this->headers = [];
        $this->body = null;

        for ($i = 1; $i < $lines_num; $i += 1) {
            $line = trim($lines[$i]);

            if (empty($line)) {
                $this->body = implode("\n", array_slice($lines, $i + 1));
                break;
            }

            if (strpos($line, ":") !== false) {
                list($name, $value) = explode(':', $line, 2);
                $this->headers[trim($name)] = trim($value);
            }
        }
    }

    public function getStatusCode()
    {
        return $this->status_code;
    }

    public function getHeaders()
    {
        return $this->headers;
    }

    public function getBody()
    {
        return $this->body;
    }

    public function setException(\Exception $exception)
    {
        $this->exception = $exception;
    }

    public function getException()
    {
        return $this->exception;
    }

    public function hasException()
    {
        return ($this->exception !== null);
    }
}


text:
<?php
class ControllerExtensionPaymentSecureTradingPp extends Controller {
	private $error = array();

	public function index() {
		$this->load->model('setting/setting');
		$this->load->model('localisation/geo_zone');
		$this->load->model('localisation/order_status');
		$this->load->language('extension/payment/securetrading_pp');

		if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validate()) {
			$this->request->post['securetrading_pp_site_reference'] = trim($this->request->post['securetrading_pp_site_reference']);

			$this->model_setting_setting->editSetting('securetrading_pp', $this->request->post);

			$this->session->data['success'] = $this->language->get('text_success');

			$this->response->redirect($this->url->link('extension/extension', 'token=' . $this->session->data['token'] . '&type=payment', true));
		}

		if (isset($this->request->post['securetrading_pp_site_reference'])) {
			$data['securetrading_pp_site_reference'] = $this->request->post['securetrading_pp_site_reference'];
		} else {
			$data['securetrading_pp_site_reference'] = $this->config->get('securetrading_pp_site_reference');
		}

		if (isset($this->request->post['securetrading_pp_username'])) {
			$data['securetrading_pp_username'] = $this->request->post['securetrading_pp_username'];
		} else {
			$data['securetrading_pp_username'] = $this->config->get('securetrading_pp_username');
		}

		if (isset($this->request->post['securetrading_pp_password'])) {
			$data['securetrading_pp_password'] = $this->request->post['securetrading_pp_password'];
		} else {
			$data['securetrading_pp_password'] = $this->config->get('securetrading_pp_password');
		}

		if (isset($this->request->post['securetrading_pp_notification_password'])) {
			$data['securetrading_pp_notification_password'] = $this->request->post['securetrading_pp_notification_password'];
		} else {
			$data['securetrading_pp_notification_password'] = $this->config->get('securetrading_pp_notification_password');
		}

		if (isset($this->request->post['securetrading_pp_site_security_password'])) {
			$data['securetrading_pp_site_security_password'] = $this->request->post['securetrading_pp_site_security_password'];
		} else {
			$data['securetrading_pp_site_security_password'] = $this->config->get('securetrading_pp_site_security_password');
		}

		if (isset($this->request->post['securetrading_pp_site_security_status'])) {
			$data['securetrading_pp_site_security_status'] = $this->request->post['securetrading_pp_site_security_status'];
		} else {
			$data['securetrading_pp_site_security_status'] = $this->config->get('securetrading_pp_site_security_status');
		}

		if (isset($this->request->post['securetrading_pp_site_security_password'])) {
			$data['securetrading_pp_site_security_password'] = $this->request->post['securetrading_pp_site_security_password'];
		} else {
			$data['securetrading_pp_site_security_password'] = $this->config->get('securetrading_pp_site_security_password');
		}

		if (isset($this->request->post['securetrading_pp_site_security_status'])) {
			$data['securetrading_pp_site_security_status'] = $this->request->post['securetrading_pp_site_security_status'];
		} else {
			$data['securetrading_pp_site_security_status'] = $this->config->get('securetrading_pp_site_security_status');
		}

		if (isset($this->request->post['securetrading_pp_webservice_username'])) {
			$data['securetrading_pp_webservice_username'] = $this->request->post['securetrading_pp_webservice_username'];
		} else {
			$data['securetrading_pp_webservice_username'] = $this->config->get('securetrading_pp_webservice_username');
		}

		if (isset($this->request->post['securetrading_pp_webservice_password'])) {
			$data['securetrading_pp_webservice_password'] = $this->request->post['securetrading_pp_webservice_password'];
		} else {
			$data['securetrading_pp_webservice_password'] = $this->config->get('securetrading_pp_webservice_password');
		}

		if (isset($this->request->post['securetrading_pp_order_status_id'])) {
			$data['securetrading_pp_order_status_id'] = $this->request->post['securetrading_pp_order_status_id'];
		} elseif($this->config->get('securetrading_pp_order_status_id') != '') {
			$data['securetrading_pp_order_status_id'] = $this->config->get('securetrading_pp_order_status_id');
		} else {
			$data['securetrading_pp_order_status_id'] = 1;
		}

		if (isset($this->request->post['securetrading_pp_declined_order_status_id'])) {
			$data['securetrading_pp_declined_order_status_id'] = $this->request->post['securetrading_pp_declined_order_status_id'];
		} elseif($this->config->get('securetrading_pp_declined_order_status_id') != '') {
			$data['securetrading_pp_declined_order_status_id'] = $this->config->get('securetrading_pp_declined_order_status_id');
		} else {
			$data['securetrading_pp_declined_order_status_id'] = 8;
		}

		if (isset($this->request->post['securetrading_pp_refunded_order_status_id'])) {
			$data['securetrading_pp_refunded_order_status_id'] = $this->request->post['securetrading_pp_refunded_order_status_id'];
		} elseif($this->config->get('securetrading_pp_refunded_order_status_id') != '') {
			$data['securetrading_pp_refunded_order_status_id'] = $this->config->get('securetrading_pp_refunded_order_status_id');
		} else {
			$data['securetrading_pp_refunded_order_status_id'] = 11;
		}

		if (isset($this->request->post['securetrading_pp_authorisation_reversed_order_status_id'])) {
			$data['securetrading_pp_authorisation_reversed_order_status_id'] = $this->request->post['securetrading_pp_authorisation_reversed_order_status_id'];
		} elseif($this->config->get('securetrading_pp_authorisation_reversed_order_status_id') != '') {
			$data['securetrading_pp_authorisation_reversed_order_status_id'] = $this->config->get('securetrading_pp_authorisation_reversed_order_status_id');
		} else {
			$data['securetrading_pp_authorisation_reversed_order_status_id'] = 12;
		}

		if (isset($this->request->post['securetrading_pp_settle_status'])) {
			$data['securetrading_pp_settle_status'] = $this->request->post['securetrading_pp_settle_status'];
		} else {
			$data['securetrading_pp_settle_status'] = $this->config->get('securetrading_pp_settle_status');
		}

		if (isset($this->request->post['securetrading_pp_settle_due_date'])) {
			$data['securetrading_pp_settle_due_date'] = $this->request->post['securetrading_pp_settle_due_date'];
		} else {
			$data['securetrading_pp_settle_due_date'] = $this->config->get('securetrading_pp_settle_due_date');
		}

		if (isset($this->request->post['securetrading_pp_geo_zone_id'])) {
			$data['securetrading_pp_geo_zone_id'] = $this->request->post['securetrading_pp_geo_zone_id'];
		} else {
			$data['securetrading_pp_geo_zone_id'] = $this->config->get('securetrading_pp_geo_zone_id');
		}

		if (isset($this->request->post['securetrading_pp_status'])) {
			$data['securetrading_pp_status'] = $this->request->post['securetrading_pp_status'];
		} else {
			$data['securetrading_pp_status'] = $this->config->get('securetrading_pp_status');
		}

		if (isset($this->request->post['securetrading_pp_sort_order'])) {
			$data['securetrading_pp_sort_order'] = $this->request->post['securetrading_pp_sort_order'];
		} else {
			$data['securetrading_pp_sort_order'] = $this->config->get('securetrading_pp_sort_order');
		}

		if (isset($this->request->post['securetrading_pp_total'])) {
			$data['securetrading_pp_total'] = $this->request->post['securetrading_pp_total'];
		} else {
			$data['securetrading_pp_total'] = $this->config->get('securetrading_pp_total');
		}

		if (isset($this->request->post['securetrading_pp_parent_css'])) {
			$data['securetrading_pp_parent_css'] = $this->request->post['securetrading_pp_parent_css'];
		} else {
			$data['securetrading_pp_parent_css'] = $this->config->get('securetrading_pp_parent_css');
		}

		if (isset($this->request->post['securetrading_pp_child_css'])) {
			$data['securetrading_pp_child_css'] = $this->request->post['securetrading_pp_child_css'];
		} else {
			$data['securetrading_pp_child_css'] = $this->config->get('securetrading_pp_child_css');
		}

		if (isset($this->request->post['securetrading_pp_cards_accepted'])) {
			$data['securetrading_pp_cards_accepted'] = $this->request->post['securetrading_pp_cards_accepted'];
		} else {
			$data['securetrading_pp_cards_accepted'] = $this->config->get('securetrading_pp_cards_accepted');

			if ($data['securetrading_pp_cards_accepted'] == null) {
				$data['securetrading_pp_cards_accepted'] = array();
			}
		}

		$this->document->setTitle($this->language->get('heading_title'));

		$data['heading_title'] = $this->language->get('heading_title');

		$data['entry_site_reference'] = $this->language->get('entry_site_reference');
		$data['entry_username'] = $this->language->get('entry_username');
		$data['entry_password'] = $this->language->get('entry_password');
		$data['entry_security_status'] = $this->language->get('entry_security_status');
		$data['entry_site_security_password'] = $this->language->get('entry_site_security_password');
		$data['entry_site_security_status'] = $this->language->get('entry_site_security_status');
		$data['entry_notification_password'] = $this->language->get('entry_notification_password');
		$data['entry_order_status'] = $this->language->get('entry_order_status');
		$data['entry_failed_order_status'] = $this->language->get('entry_failed_order_status');
		$data['entry_declined_order_status'] = $this->language->get('entry_declined_order_status');
		$data['entry_refunded_order_status'] = $this->language->get('entry_refunded_order_status');
		$data['entry_authorisation_reversed_order_status'] = $this->language->get('entry_authorisation_reversed_order_status');
		$data['entry_settle_status'] = $this->language->get('entry_settle_status');
		$data['entry_settle_due_date'] = $this->language->get('entry_settle_due_date');
		$data['entry_geo_zone'] = $this->language->get('entry_geo_zone');
		$data['entry_sort_order'] = $this->language->get('entry_sort_order');
		$data['entry_status'] = $this->language->get('entry_status');
		$data['entry_total'] = $this->language->get('entry_total');
		$data['entry_parent_css'] = $this->language->get('entry_parent_css');
		$data['entry_child_css'] = $this->language->get('entry_child_css');
		$data['entry_cards_accepted'] = $this->language->get('entry_cards_accepted');

		$data['text_enabled'] = $this->language->get('text_enabled');
		$data['text_disabled'] = $this->language->get('text_disabled');
		$data['text_yes'] = $this->language->get('text_yes');
		$data['text_no'] = $this->language->get('text_no');
		$data['text_all_geo_zones'] = $this->language->get('text_all_geo_zones');
		$data['text_process_immediately'] = $this->language->get('text_process_immediately');
		$data['text_wait_x_days'] = $this->language->get('text_wait_x_days');

		$data['help_username'] = $this->language->get('help_username');
		$data['help_password'] = $this->language->get('help_password');
		$data['help_total'] = $this->language->get('help_total');

		$data['button_save'] = $this->language->get('button_save');
		$data['button_cancel'] = $this->language->get('button_cancel');

		if (isset($this->error['warning'])) {
			$data['error_warning'] = $this->error['warning'];
		} else {
			$data['error_warning'] = '';
		}

		if (isset($this->error['site_reference'])) {
			$data['error_site_reference'] = $this->error['site_reference'];
		} else {
			$data['error_site_reference'] = '';
		}

		if (isset($this->error['cards_accepted'])) {
			$data['error_cards_accepted'] = $this->error['cards_accepted'];
		} else {
			$data['error_cards_accepted'] = '';
		}

		if (isset($this->error['notification_password'])) {
			$data['error_notification_password'] = $this->error['notification_password'];
		} else {
			$data['error_notification_password'] = '';
		}

		$data['breadcrumbs'] = array();

		$data['breadcrumbs'][] = array(
			'text' => $this->language->get('text_home'),
			'href' => $this->url->link('common/dashboard', 'token=' . $this->session->data['token'], true)
		);

		$data['breadcrumbs'][] = array(
			'text' => $this->language->get('text_extension'),
			'href' => $this->url->link('extension/extension', 'token=' . $this->session->data['token'] . '&type=payment', true)
		);

		$data['breadcrumbs'][] = array(
			'text' => $this->language->get('heading_title'),
			'href' => $this->url->link('extension/payment/securetrading_pp', 'token=' . $this->session->data['token'], true)
		);

		$data['geo_zones'] = $this->model_localisation_geo_zone->getGeoZones();
		$data['order_statuses'] = $this->model_localisation_order_status->getOrderStatuses();
		$data['cards'] = array(
			'AMEX' => 'American Express',
			'VISA' => 'Visa',
			'DELTA' => 'Visa Debit',
			'ELECTRON' => 'Visa Electron',
			'PURCHASING' => 'Visa Purchasing',
			'VPAY' => 'V Pay',
			'MASTERCARD' => 'MasterCard',
			'MASTERCARDDEBIT' => 'MasterCard Debit',
			'MAESTRO' => 'Maestro',
			'PAYPAL' => 'PayPal',
		);

		$data['settlement_statuses'] = array(
			'0' => $this->language->get('text_pending_settlement'),
			'1' => $this->language->get('text_pending_settlement_manually_overriden'),
			'2' => $this->language->get('text_pending_suspended'),
			'100' => $this->language->get('text_pending_settled'),
		);

		$data['action'] = $this->url->link('extension/payment/securetrading_pp', 'token=' . $this->session->data['token'], true);

		$data['cancel'] = $this->url->link('extension/extension', 'token=' . $this->session->data['token'] . '&type=payment', true);

		$data['header'] = $this->load->controller('common/header');
		$data['column_left'] = $this->load->controller('common/column_left');
		$data['footer'] = $this->load->controller('common/footer');

		$this->response->setOutput($this->load->view('extension/payment/securetrading_pp', $data));
	}

	public function install() {
		$this->load->model('extension/payment/securetrading_pp');
		$this->model_extension_payment_securetrading_pp->install();
	}

	public function uninstall() {
		$this->load->model('extension/payment/securetrading_pp');
		$this->model_extension_payment_securetrading_pp->uninstall();
	}

	public function order() {

		if ($this->config->get('securetrading_pp_status')) {
			$this->load->model('extension/payment/securetrading_pp');

			$securetrading_pp_order = $this->model_extension_payment_securetrading_pp->getOrder($this->request->get['order_id']);

			if (!empty($securetrading_pp_order)) {
				$this->load->language('extension/payment/securetrading_pp');

				$securetrading_pp_order['total_released'] = $this->model_extension_payment_securetrading_pp->getTotalReleased($securetrading_pp_order['securetrading_pp_order_id']);

				$securetrading_pp_order['total_formatted'] = $this->currency->format($securetrading_pp_order['total'], $securetrading_pp_order['currency_code'], false, false);
				$securetrading_pp_order['total_released_formatted'] = $this->currency->format($securetrading_pp_order['total_released'], $securetrading_pp_order['currency_code'], false, false);

				$data['securetrading_pp_order'] = $securetrading_pp_order;

				$data['auto_settle'] = $securetrading_pp_order['settle_type'];

				$data['text_payment_info'] = $this->language->get('text_payment_info');
				$data['text_order_ref'] = $this->language->get('text_order_ref');
				$data['text_order_total'] = $this->language->get('text_order_total');
				$data['text_total_released'] = $this->language->get('text_total_released');
				$data['text_release_status'] = $this->language->get('text_release_status');
				$data['text_void_status'] = $this->language->get('text_void_status');
				$data['text_rebate_status'] = $this->language->get('text_rebate_status');
				$data['text_transactions'] = $this->language->get('text_transactions');
				$data['text_yes'] = $this->language->get('text_yes');
				$data['text_no'] = $this->language->get('text_no');
				$data['text_column_amount'] = $this->language->get('text_column_amount');
				$data['text_column_type'] = $this->language->get('text_column_type');
				$data['text_column_created'] = $this->language->get('text_column_created');
				$data['button_release'] = $this->language->get('button_release');
				$data['button_rebate'] = $this->language->get('button_rebate');
				$data['button_void'] = $this->language->get('button_void');
				$data['text_confirm_void'] = $this->language->get('text_confirm_void');
				$data['text_confirm_release'] = $this->language->get('text_confirm_release');
				$data['text_confirm_rebate'] = $this->language->get('text_confirm_rebate');

				$data['order_id'] = $this->request->get['order_id'];
				$data['token'] = $this->request->get['token'];

				return $this->load->view('extension/payment/securetrading_pp_order', $data);
			}
		}
	}

	public function void() {
		$this->load->language('extension/payment/securetrading_pp');
		$json = array();

		if (isset($this->request->post['order_id']) && $this->request->post['order_id'] != '') {
			$this->load->model('extension/payment/securetrading_pp');

			$securetrading_pp_order = $this->model_extension_payment_securetrading_pp->getOrder($this->request->post['order_id']);

			$void_response = $this->model_extension_payment_securetrading_pp->void($this->request->post['order_id']);

			$this->model_extension_payment_securetrading_pp->logger('Void result:\r\n' . print_r($void_response, 1));

			if ($void_response !== false) {
				$response_xml = simplexml_load_string($void_response);

				if ($response_xml->response['type'] == 'ERROR' || (string)$response_xml->response->error->code != '0') {
					$json['msg'] = (string)$response_xml->response->error->message;
					$json['error'] = true;
				} else {

					$this->model_extension_payment_securetrading_pp->addTransaction($securetrading_pp_order['securetrading_pp_order_id'], 'reversed', 0.00);
					$this->model_extension_payment_securetrading_pp->updateVoidStatus($securetrading_pp_order['securetrading_pp_order_id'], 1);

					$this->data = array(
						'order_status_id' => $this->config->get('securetrading_pp_authorisation_reversed_order_status_id'),
						'notify' => false,
						'comment' => '',
					);

					$this->load->model('sale/order');

					$this->model_sale_order->addOrderHistory($this->request->post['order_id'], $this->data);

					$json['msg'] = $this->language->get('text_authorisation_reversed');
					$json['data']['created'] = date("Y-m-d H:i:s");
					$json['error'] = false;
				}
			} else {
				$json['msg'] = $this->language->get('error_connection');
				$json['error'] = true;
			}
		} else {
			$json['error'] = true;
			$json['msg'] = 'Missing data';
		}

		$this->response->setOutput(json_encode($json));
	}

	public function release() {
		$this->load->language('extension/payment/securetrading_pp');
		$json = array();

		$amount = number_format($this->request->post['amount'], 2);

		if (isset($this->request->post['order_id']) && $this->request->post['order_id'] != '' && isset($amount) && $amount > 0) {
			$this->load->model('extension/payment/securetrading_pp');

			$securetrading_pp_order = $this->model_extension_payment_securetrading_pp->getOrder($this->request->post['order_id']);

			$release_response = $this->model_extension_payment_securetrading_pp->release($this->request->post['order_id'], $amount);

			$this->model_extension_payment_securetrading_pp->logger('Release result:\r\n' . print_r($release_response, 1));

			if ($release_response !== false) {
				$response_xml = simplexml_load_string($release_response);

				if ($response_xml->response['type'] == 'ERROR' || (string)$response_xml->response->error->code != '0') {
					$json['error'] = true;
					$json['msg'] = (string)$response_xml->response->error->message;
				} else {
					$this->model_extension_payment_securetrading_pp->addTransaction($securetrading_pp_order['securetrading_pp_order_id'], 'payment', $amount);

					$total_released = $this->model_extension_payment_securetrading_pp->getTotalReleased($securetrading_pp_order['securetrading_pp_order_id']);

					if ($total_released >= $securetrading_pp_order['total'] || $securetrading_pp_order['settle_type'] == 100) {
						$this->model_extension_payment_securetrading_pp->updateReleaseStatus($securetrading_pp_order['securetrading_pp_order_id'], 1);
						$release_status = 1;
						$json['msg'] = $this->language->get('text_release_ok_order');

						$this->load->model('sale/order');

						$history = array();
						$history['order_status_id'] = $this->config->get('securetrading_pp_order_status_success_settled_id');
						$history['comment'] = '';
						$history['notify'] = '';

						$this->model_sale_order->addOrderHistory($this->request->post['order_id'], $history);
					} else {
						$release_status = 0;
						$json['msg'] = $this->language->get('text_release_ok');
					}

					$json['data'] = array();
					$json['data']['created'] = date("Y-m-d H:i:s");
					$json['data']['amount'] = $amount;
					$json['data']['release_status'] = $release_status;
					$json['data']['total'] = (double)$total_released;
					$json['error'] = false;
				}
			} else {
				$json['error'] = true;
				$json['msg'] = $this->language->get('error_connection');
			}
		} else {
			$json['error'] = true;
			$json['msg'] = $this->language->get('error_data_missing');
		}

		$this->response->setOutput(json_encode($json));
	}

	public function rebate() {
		$this->load->language('extension/payment/securetrading_pp');
		$json = array();

		if (isset($this->request->post['order_id']) && !empty($this->request->post['order_id'])) {
			$this->load->model('extension/payment/securetrading_pp');

			$securetrading_pp_order = $this->model_extension_payment_securetrading_pp->getOrder($this->request->post['order_id']);

			$amount = number_format($this->request->post['amount'], 2);

			$rebate_response = $this->model_extension_payment_securetrading_pp->rebate($this->request->post['order_id'], $amount);

			$this->model_extension_payment_securetrading_pp->logger('Rebate result:\r\n' . print_r($rebate_response, 1));

			if ($rebate_response !== false) {
				$response_xml = simplexml_load_string($rebate_response);

				$error_code = (string)$response_xml->response->error->code;

				if ($error_code == '0') {

					$this->model_extension_payment_securetrading_pp->addTransaction($securetrading_pp_order['securetrading_pp_order_id'], 'rebate', $amount * -1);

					$total_rebated = $this->model_extension_payment_securetrading_pp->getTotalRebated($securetrading_pp_order['securetrading_pp_order_id']);
					$total_released = $this->model_extension_payment_securetrading_pp->getTotalReleased($securetrading_pp_order['securetrading_pp_order_id']);

					if ($total_released <= 0 && $securetrading_pp_order['release_status'] == 1) {
						$json['status'] = 1;
						$json['message'] = $this->language->get('text_refund_issued');

						$this->model_extension_payment_securetrading_pp->updateRebateStatus($securetrading_pp_order['securetrading_pp_order_id'], 1);
						$rebate_status = 1;
						$json['msg'] = $this->language->get('text_rebate_ok_order');

						$this->load->model('sale/order');

						$history = array();
						$history['order_status_id'] = $this->config->get('securetrading_pp_refunded_order_status_id');
						$history['comment'] = '';
						$history['notify'] = '';

						$this->model_sale_order->addOrderHistory($this->request->post['order_id'], $history);
					} else {
						$rebate_status = 0;
						$json['msg'] = $this->language->get('text_rebate_ok');
					}

					$json['data'] = array();
					$json['data']['created'] = date("Y-m-d H:i:s");
					$json['data']['amount'] = $amount * -1;
					$json['data']['total_released'] = (double)$total_released;
					$json['data']['total_rebated'] = (double)$total_rebated;
					$json['data']['rebate_status'] = $rebate_status;
					$json['error'] = false;
				} else {
					$json['error'] = true;
					$json['msg'] = (string)$response_xml->response->error->message;
				}
			} else {
				$json['status'] = 0;
				$json['message'] = $this->language->get('error_connection');
			}
		} else {
			$json['error'] = true;
			$json['msg'] = 'Missing data';
		}

		$this->response->setOutput(json_encode($json));
	}

	protected function validate() {
		if (!$this->user->hasPermission('modify', 'extension/payment/securetrading_pp')) {
			$this->error['warning'] = $this->language->get('error_permission');
		}

		if (!$this->request->post['securetrading_pp_site_reference']) {
			$this->error['site_reference'] = $this->language->get('error_site_reference');
		}

		if (empty($this->request->post['securetrading_pp_cards_accepted'])) {
			$this->error['cards_accepted'] = $this->language->get('error_cards_accepted');
		}

		if (!$this->request->post['securetrading_pp_notification_password']) {
			$this->error['notification_password'] = $this->language->get('error_notification_password');
		}

		return !$this->error;
	}
}


text:
package org.apache.camel.cloud;

import org.apache.camel.CamelContext;

/**
 * A factory to create ServiceChooser
 *
 * @see ServiceChooser
 */
public interface ServiceChooserFactory {
    /**
     * Creates an instance of a ServiceChooser.
     */
    ServiceChooser newInstance(CamelContext camelContext) throws Exception;
}


text:
package example;
//-*- mode:java; encoding:utf-8 -*-
// vim:set fileencoding=utf-8:
//@homepage@
import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;

public final class MainPanel extends JPanel {
    private final JTextPane textpane = new JTextPane();
    private final JTextArea ta = new JTextArea();

    public MainPanel() {
        super(new BorderLayout());
        textpane.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 12));
        FontMetrics fm = textpane.getFontMetrics(textpane.getFont());
        int charWidth = fm.charWidth('m');
        int tabWidth = charWidth * 4;
        TabStop[] tabs = new TabStop[10];
        for (int j = 0; j < tabs.length; j++) {
            tabs[j] = new TabStop((j + 1) * tabWidth);
        }
        TabSet tabSet = new TabSet(tabs);
        SimpleAttributeSet attributes = new SimpleAttributeSet();
        StyleConstants.setTabSet(attributes, tabSet);
        int length = textpane.getDocument().getLength();
        textpane.getStyledDocument().setParagraphAttributes(0, length, attributes, false);
        textpane.setText("JTextPane\naaaa\n\taaaa\n\t\taaaa\n");

        ta.setTabSize(4);
        ta.setText("JTextArea\naaaa\n\taaaa\n\t\taaaa\n");

        add(new JScrollPane(ta), BorderLayout.NORTH);
        add(new JScrollPane(textpane));
        setPreferredSize(new Dimension(320, 240));
    }

    public static void main(String... args) {
        EventQueue.invokeLater(new Runnable() {
            @Override public void run() {
                createAndShowGUI();
            }
        });
    }
    public static void createAndShowGUI() {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (ClassNotFoundException | InstantiationException
               | IllegalAccessException | UnsupportedLookAndFeelException ex) {
            ex.printStackTrace();
        }
        JFrame frame = new JFrame("@title@");
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.getContentPane().add(new MainPanel());
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jee="http://www.springframework.org/schema/jee"
	xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jpa="http://www.springframework.org/schema/data/jpa"
	xsi:schemaLocation="
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
		http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd
		http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.1.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
		http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd"
	default-lazy-init="true">

	<description>Spring公共配置 </description>
	<!-- 使用annotation 自动注册bean, 并保证@Required、@Autowired的属性被注入 -->
	<context:component-scan base-package="com.sap.data.app">
		<context:exclude-filter type="annotation"
			expression="org.springframework.stereotype.Controller" />
	</context:component-scan>

	<!-- <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
		<property name="configLocation"> <value>classpath:dm/cfg.xml</value> </property>
		</bean> -->

	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<property name="configLocation">
			<value>classpath:db/db-hibernate.cfg.xml</value>
		</property>
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
				<prop key="hibernate.show_sql">true</prop>
			</props>
		</property>
	</bean>

	<!-- Jpa Entity Manager 配置 -->
	<bean id="entityManagerFactory"
		class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<property name="persistenceUnitName" value="defaultPU" />
		<property name="jpaVendorAdapter" ref="hibernateJpaVendorAdapter" />
		<property name="jpaProperties">
			<props>
				<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
				<prop key="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory
				</prop>
				<prop key="net.sf.ehcache.configurationResourceName">ehcache/ehcache-hibernate-local.xml</prop>
				<prop key="hibernate.ejb.naming_strategy">org.hibernate.cfg.ImprovedNamingStrategy</prop>
			</props>
		</property>
	</bean>

	<bean id="hibernateJpaVendorAdapter"
		class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />

	<!-- Spring Data Jpa配置 -->
	<jpa:repositories base-package="com.sap.data.app"
		transaction-manager-ref="transactionManager"
		entity-manager-factory-ref="entityManagerFactory" />

	<!-- Jpa 事务配置 -->
	<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
		<property name="entityManagerFactory" ref="entityManagerFactory" />
	</bean>

	<!-- 使用annotation定义事务 -->
	<tx:annotation-driven transaction-manager="transactionManager"
		proxy-target-class="true" />

	<bean id="dataSource" class="com.sap.data.app.datasource.CompanyRountingDataSource">
		<property name="targetDataSources">
			<map key-type="java.lang.String">
				<entry key="40288b8147cd16ce0147cd236df20000" value-ref="40288b8147cd16ce0147cd236df20000" />
				<entry key="40288b8147cd16ce0147cd24e2850001" value-ref="40288b8147cd16ce0147cd24e2850001" />
				<entry key="40288b8147cd16ce0147cd25921d0002" value-ref="40288b8147cd16ce0147cd25921d0002" />
			</map>
		</property>
		<property name="defaultTargetDataSource" ref="provisioning" />
	</bean>

	<bean id="parentDataSource"
		class="org.springframework.jdbc.datasource.DriverManagerDataSource"
		abstract="true">
		<property name="driverClassName" value="com.mysql.jdbc.Driver" />
	</bean>

	<bean id="40288b8147cd16ce0147cd236df20000" parent="parentDataSource">
		<property name="url"
			value="jdbc:mysql://datamigration3.mysql.rds.aliyuncs.com/schema_dell?useUnicode=true&characterEncoding=utf-8" />
		<property name="username" value="dell_user" />
		<property name="password" value="agfacgD0od" />
	</bean>

	<bean id="40288b8147cd16ce0147cd24e2850001" parent="parentDataSource">
		<property name="url"
			value="jdbc:mysql://datamigration3.mysql.rds.aliyuncs.com/schema_lenovo?useUnicode=true&characterEncoding=utf-8" />
		<property name="username" value="lenovo_user" />
		<property name="password" value="agfacgD0ole" />
	</bean>

	<bean id="40288b8147cd16ce0147cd25921d0002" parent="parentDataSource">
		<property name="url"
			value="jdbc:mysql://datamigration3.mysql.rds.aliyuncs.com/schema_apple?useUnicode=true&characterEncoding=utf-8" />
		<property name="username" value="apple_user" />
		<property name="password" value="agfacgD0odellapp" />
	</bean>

	<bean id="provisioning" parent="parentDataSource">
		<property name="url"
			value="jdbc:mysql://datamigration3.mysql.rds.aliyuncs.com/dm_platform?useUnicode=true&characterEncoding=utf-8" />
		<property name="username" value="dmplatform_user" />
		<property name="password" value="agfacgD0odmp" />
	</bean>

</beans>


text:
<!DOCTYPE html>
<meta charset="utf-8">
<title>Append child writable stream demo</title>

<link rel=stylesheet href="resources/common.css">
<link rel=stylesheet href="resources/commits.css">

Append child writable stream demo

Back to demo index
<view-source></view-source>

  <button id="load">Load JSON stream</button>
  <button id="reset">Reset</button>


text:
from O365 import Account
import json

class MockConnection:

    ret_value = None

    def get(self, url, params=None, **kwargs):
        self.url = url
        self.kwargs = kwargs

class TestMailBox:

    def setup_class(self):
        credentials = ("client id","client secret")
        self.account = Account(credentials)
        self.mailbox = self.account.mailbox()
        self.mailbox.con = MockConnection()

    def teardown_class(self):
        pass

    def test_mailbox(self):
        assert self.mailbox.root

#    def test_get_mailbox_folders(self):
#        self.mailbox.con.ret_value = ['Inbox','Drafts']
#
#        folders = self.mailbox.get_folders(limit=5)
#
#        assert len(folders) > 0


text:
import os
TEST_DATABASE_CHARSET = 'utf8'

def update_settings_for_tests(settings):
    """Modify some of the values set in settings.py.
    """

    if getattr(settings, '_settings_updated', None):
        return
    settings['_settings_updated'] = True
    settings['BROKER_BACKEND'] = 'memory'
    settings['COMPRESS_PRECOMPILERS'] = []

    settings['PASSWORD_HASHERS'] = (
        'django.contrib.auth.hashers.MD5PasswordHasher',
        'django.contrib.auth.hashers.SHA1PasswordHasher',
    )

    print "Warning: disabling cache middleware for the duration of unit tests"
    settings['MIDDLEWARE_CLASSES'] = [mc
                                      for mc in settings['MIDDLEWARE_CLASSES']
                                      if 'CacheMiddleware' not in mc]

    if os.getenv('FASTER'):
        settings['DATABASES'] = {
            'default': {
                'NAME': ':memory:',
                'ENGINE': 'django.db.backends.sqlite3',
            },
        }


text:
package de.robv.android.xposed.mods.appsettings;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.TextView;

/**
 * Composite component that displays a header and a triplet of radio buttons for
 * selection of All / Overridden / Unchanged settings for each parameter
 */
public class FilterItemComponent extends LinearLayout {

	private OnFilterChangeListener listener;

	/** Constructor for designer instantiation */
	public FilterItemComponent(Context context, AttributeSet attrs) {
		super(context, attrs);

		LayoutInflater.from(context).inflate(R.layout.filter_item, this);

		TypedArray atts = context.obtainStyledAttributes(attrs, R.styleable.FilterItem);

		// Load label values, if any
		setLabel(R.id.txtFilterName, atts.getString(R.styleable.FilterItem_label));
		setLabel(R.id.radAll, atts.getString(R.styleable.FilterItem_all_label));
		setLabel(R.id.radOverridden, atts.getString(R.styleable.FilterItem_overridden_label));
		setLabel(R.id.radUnchanged, atts.getString(R.styleable.FilterItem_unchanged_label));
		atts.recycle();

		setupListener();
	}

	/** Constructor for programmatic instantiation */
	public FilterItemComponent(Context context, String filterName, String labelAll, String labelOverriden, String labelUnchanged) {
		super(context);

		LayoutInflater.from(context).inflate(R.layout.filter_item, this);

		// Load label values, if any
		setLabel(R.id.txtFilterName, filterName);
		setLabel(R.id.radAll, labelAll);
		setLabel(R.id.radOverridden, labelOverriden);
		setLabel(R.id.radUnchanged, labelUnchanged);

		setupListener();
	}

	private void setupListener() {
		// Notify any listener of changes in the selected option
		((RadioGroup) findViewById(R.id.radOptions)).setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				if (listener != null) {
					switch (checkedId) {
					case R.id.radOverridden:
						listener.onFilterChanged(FilterItemComponent.this, FilterState.OVERRIDDEN);
						break;
					case R.id.radUnchanged:
						listener.onFilterChanged(FilterItemComponent.this, FilterState.UNCHANGED);
						break;
					default:
						listener.onFilterChanged(FilterItemComponent.this, FilterState.ALL);
						break;
					}
				}
			}
		});
	}

	/*
	 * Update the label of a view id, if non-null
	 */
	private void setLabel(int id, CharSequence value) {
		TextView label = (TextView) findViewById(id);
		if (label != null && value != null) {
			label.setText(value);
		}
	}

	/**
	 * Enable or disable all the items within this compound component
	 */
	@Override
	public void setEnabled(boolean enabled) {
		findViewById(R.id.radOptions).setEnabled(enabled);
		findViewById(R.id.radAll).setEnabled(enabled);
		findViewById(R.id.radOverridden).setEnabled(enabled);
		findViewById(R.id.radUnchanged).setEnabled(enabled);
	}

	/**
	 * Check if this compound component is enabled
	 */
	@Override
	public boolean isEnabled() {
		return findViewById(R.id.radOptions).isEnabled();
	}

	/**
	 * Get currently selected filter option
	 */
	public FilterState getFilterState() {
		switch (((RadioGroup) findViewById(R.id.radOptions)).getCheckedRadioButtonId()) {
		case R.id.radOverridden:
			return FilterState.OVERRIDDEN;
		case R.id.radUnchanged:
			return FilterState.UNCHANGED;
		default:
			return FilterState.ALL;
		}
	}

	/**
	 * Activate one of the 3 options as the selected one
	 */
	public void setFilterState(FilterState state) {
		// Handle null values and use the default "All"
		if (state == null)
			state = FilterState.ALL;

		switch (state) {
		case OVERRIDDEN:
			((RadioGroup) findViewById(R.id.radOptions)).check(R.id.radOverridden);
			break;
		case UNCHANGED:
			((RadioGroup) findViewById(R.id.radOptions)).check(R.id.radUnchanged);
			break;
		default:
			((RadioGroup) findViewById(R.id.radOptions)).check(R.id.radAll);
			break;
		}
	}

	/**
	 * Register a listener to be notified when the selection changes
	 */
	public void setOnFilterChangeListener(OnFilterChangeListener listener) {
		this.listener = listener;
	}

	/**
	 * Interface for listeners that will be notified of selection changes
	 */
	public static interface OnFilterChangeListener {
		/**
		 * Notification that this filter item has changed to a new selected state
		 */
		public void onFilterChanged(FilterItemComponent item, FilterState state);
	}

	/**
	 * Possible values for the filter state: All / Overridden / Unchanged
	 */
	public static enum FilterState {
		ALL, OVERRIDDEN, UNCHANGED;
	}
}


text:
package me.callmeavarice.jbox2d;

import me.callmeavarice.jbox2d.tests.PuttingBounceInTheMoshPit;
import me.callmeavarice.jbox2d.tests.SimpleJBox2DWorld;
import org.jbox2d.testbed.framework.TestbedController;
import org.jbox2d.testbed.framework.TestbedErrorHandler;
import org.jbox2d.testbed.framework.TestbedModel;
import org.jbox2d.testbed.framework.j2d.DebugDrawJ2D;
import org.jbox2d.testbed.framework.j2d.TestPanelJ2D;
import org.jbox2d.testbed.framework.j2d.TestbedSidePanel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.swing.*;
import java.awt.*;

public class TestbedMain {
    private static final Logger log = LoggerFactory.getLogger(TestbedMain.class);

    public static void main(String[] args) {
        try {
            UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
        } catch (Exception e) {
            log.warn("Could not set the look and feel to nimbus.  "
                    + "Hopefully you're on a mac so the window isn't ugly as crap.");
        }
        TestbedModel model = new TestbedModel();
        final TestbedController controller =
                new TestbedController(model, TestbedController.UpdateBehavior.UPDATE_CALLED, TestbedController.MouseBehavior.NORMAL,
                        new TestbedErrorHandler() {
                            @Override
                            public void serializationError(Exception e, String message) {
                                JOptionPane.showMessageDialog(null, message, "Serialization Error",
                                        JOptionPane.ERROR_MESSAGE);
                            }
                        });
        TestPanelJ2D panel = new TestPanelJ2D(model, controller);
        model.setPanel(panel);
        model.setDebugDraw(new DebugDrawJ2D(panel, true));

        model.addCategory("Featured");
        model.addTest(new SimpleJBox2DWorld());
        model.addTest(new PuttingBounceInTheMoshPit());

        JFrame testbed = new JFrame();
        testbed.setTitle("JBox2D Testbed");
        testbed.setLayout(new BorderLayout());
        TestbedSidePanel side = new TestbedSidePanel(model, controller);
        testbed.add(panel, "Center");
        testbed.add(new JScrollPane(side), "East");
        testbed.pack();
        testbed.setVisible(true);
        testbed.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                controller.playTest(0);
                controller.start();
            }
        });

    }
}


text:
package com.nebhale.devoxx2013.web;

import com.nebhale.devoxx2013.domain.Door;
import org.springframework.hateoas.Resource;
import org.springframework.hateoas.ResourceAssembler;
import org.springframework.stereotype.Component;

import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo;

@Component
final class DoorResourceAssembler implements ResourceAssembler<Door, Resource<Door>> {

    @Override
    public Resource<Door> toResource(Door door) {
        Resource<Door> resource = new Resource<>(door);
        resource.add(linkTo(DoorController.class, door.getGame().getId()).slash(door).withSelfRel());

        return resource;
    }
}


text:
/***************************************************************************/
/*                                                                         */
/*  ftinit.c                                                               */
/*                                                                         */
/*    FreeType initialization layer (body).                                */
/*                                                                         */
/*  Copyright 1996-2001, 2002, 2005, 2007, 2009 by                         */
/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */
/*                                                                         */
/*  This file is part of the FreeType project, and may only be used,       */
/*  modified, and distributed under the terms of the FreeType project      */
/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */
/*  this file you indicate that you have read the license and              */
/*  understand and accept it fully.                                        */
/*                                                                         */
/***************************************************************************/

  /*************************************************************************/
  /*                                                                       */
  /*  The purpose of this file is to implement the following two           */
  /*  functions:                                                           */
  /*                                                                       */
  /*  FT_Add_Default_Modules():                                            */
  /*     This function is used to add the set of default modules to a      */
  /*     fresh new library object.  The set is taken from the header file  */
  /*     `freetype/config/ftmodule.h'.  See the document `FreeType 2.0     */
  /*     Build System' for more information.                               */
  /*                                                                       */
  /*  FT_Init_FreeType():                                                  */
  /*     This function creates a system object for the current platform,   */
  /*     builds a library out of it, then calls FT_Default_Drivers().      */
  /*                                                                       */
  /*  Note that even if FT_Init_FreeType() uses the implementation of the  */
  /*  system object defined at build time, client applications are still   */
  /*  able to provide their own `ftsystem.c'.                              */
  /*                                                                       */
  /*************************************************************************/

#include <ft2build.h>
#include FT_CONFIG_CONFIG_H
#include FT_INTERNAL_OBJECTS_H
#include FT_INTERNAL_DEBUG_H
#include FT_MODULE_H
#include "basepic.h"

  /*************************************************************************/
  /*                                                                       */
  /* The macro FT_COMPONENT is used in trace mode.  It is an implicit      */
  /* parameter of the FT_TRACE() and FT_ERROR() macros, used to print/log  */
  /* messages during execution.                                            */
  /*                                                                       */
#undef  FT_COMPONENT
#define FT_COMPONENT  trace_init

#ifndef FT_CONFIG_OPTION_PIC

#undef  FT_USE_MODULE
#ifdef __cplusplus
#define FT_USE_MODULE( type, x )  extern "C" const type  x;
#else
#define FT_USE_MODULE( type, x )  extern const type  x;
#endif

#include FT_CONFIG_MODULES_H

#undef  FT_USE_MODULE
#define FT_USE_MODULE( type, x )  (const FT_Module_Class*)&(x),

  static
  const FT_Module_Class*  const ft_default_modules[] =
  {
#include FT_CONFIG_MODULES_H
    0
  };

#else /* FT_CONFIG_OPTION_PIC */

#ifdef __cplusplus
#define FT_EXTERNC  extern "C"
#else
#define FT_EXTERNC  extern
#endif

  /* declare the module's class creation/destruction functions */
#undef  FT_USE_MODULE
#define FT_USE_MODULE( type, x )  \
  FT_EXTERNC FT_Error FT_Create_Class_##x( FT_Library library, FT_Module_Class** output_class ); \
  FT_EXTERNC void     FT_Destroy_Class_##x( FT_Library library, FT_Module_Class*  clazz );

#include FT_CONFIG_MODULES_H

  /* count all module classes */
#undef  FT_USE_MODULE
#define FT_USE_MODULE( type, x )  MODULE_CLASS_##x,

  enum {
#include FT_CONFIG_MODULES_H
    FT_NUM_MODULE_CLASSES
  };

  /* destroy all module classes */
#undef  FT_USE_MODULE
#define FT_USE_MODULE( type, x )  \
  if ( classes[i] ) { FT_Destroy_Class_##x(library, classes[i]); } \
  i++;                                                             \

  FT_BASE_DEF( void )
  ft_destroy_default_module_classes( FT_Library  library )
  {
    FT_Module_Class** classes;
    FT_Memory         memory;
    FT_UInt           i;
    BasePIC*          pic_container = library->pic_container.base;

    if ( !pic_container->default_module_classes )
      return;

    memory = library->memory;
    classes = pic_container->default_module_classes;
    i = 0;

#include FT_CONFIG_MODULES_H

    FT_FREE( classes );
    pic_container->default_module_classes = 0;
  }

  /* initialize all module classes and the pointer table */
#undef  FT_USE_MODULE
#define FT_USE_MODULE( type, x )                \
  error = FT_Create_Class_##x(library, &clazz); \
  if (error) goto Exit;                         \
  classes[i++] = clazz;

  FT_BASE_DEF( FT_Error )
  ft_create_default_module_classes( FT_Library  library )
  {
    FT_Error          error;
    FT_Memory         memory;
    FT_Module_Class** classes;
    FT_Module_Class*  clazz;
    FT_UInt           i;
    BasePIC*          pic_container = library->pic_container.base;

    memory = library->memory;
    pic_container->default_module_classes = 0;

    if ( FT_ALLOC(classes, sizeof(FT_Module_Class*) * (FT_NUM_MODULE_CLASSES + 1) ) )
      return error;
    /* initialize all pointers to 0, especially the last one */
    for (i = 0; i < FT_NUM_MODULE_CLASSES; i++)
      classes[i] = 0;
    classes[FT_NUM_MODULE_CLASSES] = 0;

    i = 0;

#include FT_CONFIG_MODULES_H

Exit:
    if (error) ft_destroy_default_module_classes( library );
    else pic_container->default_module_classes = classes;

    return error;
  }

#endif /* FT_CONFIG_OPTION_PIC */

  /* documentation is in ftmodapi.h */

  FT_EXPORT_DEF( void )
  FT_Add_Default_Modules( FT_Library  library )
  {
    FT_Error                       error;
    const FT_Module_Class* const*  cur;

    /* test for valid `library' delayed to FT_Add_Module() */

    cur = FT_DEFAULT_MODULES_GET;
    while ( *cur )
    {
      error = FT_Add_Module( library, *cur );
      /* notify errors, but don't stop */
      if ( error )
        FT_TRACE0(( "FT_Add_Default_Module:"
                    " Cannot install `%s', error = 0x%x\n",
                    (*cur)->module_name, error ));
      cur++;
    }
  }

  /* documentation is in freetype.h */

  FT_EXPORT_DEF( FT_Error )
  FT_Init_FreeType( FT_Library  *alibrary )
  {
    FT_Error   error;
    FT_Memory  memory;

    /* First of all, allocate a new system object -- this function is part */
    /* of the system-specific component, i.e. `ftsystem.c'.                */

    memory = FT_New_Memory();
    if ( !memory )
    {
      FT_ERROR(( "FT_Init_FreeType: cannot find memory manager\n" ));
      return FT_Err_Unimplemented_Feature;
    }

    /* build a library out of it, then fill it with the set of */
    /* default drivers.                                        */

    error = FT_New_Library( memory, alibrary );
    if ( error )
      FT_Done_Memory( memory );
    else
      FT_Add_Default_Modules( *alibrary );

    return error;
  }

  /* documentation is in freetype.h */

  FT_EXPORT_DEF( FT_Error )
  FT_Done_FreeType( FT_Library  library )
  {
    if ( library )
    {
      FT_Memory  memory = library->memory;

      /* Discard the library object */
      FT_Done_Library( library );

      /* discard memory manager */
      FT_Done_Memory( memory );
    }

    return FT_Err_Ok;
  }

/* END */