text:
package operationlock

import (
	"fmt"
	"sync"
	"time"

	"github.com/lxc/lxd/lxd/project"
	"github.com/lxc/lxd/shared/logger"
)

// TimeoutDefault timeout the operation lock will be kept alive for without needing to call Reset().
const TimeoutDefault time.Duration = time.Second * time.Duration(30)

// TimeoutShutdown timeout that can be used when shutting down an instance.
const TimeoutShutdown time.Duration = time.Minute * time.Duration(5)

// Action indicates the operation action type.
type Action string

// ActionCreate for creating an instance.
const ActionCreate Action = "create"

// ActionStart for starting an instance.
const ActionStart Action = "start"

// ActionStop for stopping an instance.
const ActionStop Action = "stop"

// ActionRestart for restarting an instance.
const ActionRestart Action = "restart"

// ActionRestore for restoring an instance.
const ActionRestore Action = "restore"

// ActionUpdate for updating an instance.
const ActionUpdate Action = "update"

// ActionDelete for deleting an instance.
const ActionDelete Action = "delete"

// ErrNonReusuableSucceeded is returned when no operation is created due to having to wait for a matching
// non-reusuable operation that has now completed successfully.
var ErrNonReusuableSucceeded error = fmt.Errorf("A matching non-reusable operation has now succeeded")

var instanceOperationsLock sync.Mutex
var instanceOperations = make(map[string]*InstanceOperation)

// InstanceOperation operation locking.
type InstanceOperation struct {
	action            Action
	chanDone          chan error
	chanReset         chan time.Duration
	err               error
	projectName       string
	instanceName      string
	reusable          bool
	instanceInitiated bool
}

// Create creates a new operation lock for an Instance if one does not already exist and returns it.
// The lock will be released after TimeoutDefault or when Done() is called, which ever occurs first.
// If createReusuable is set as true then future lock attempts can specify the reuseExisting argument as true
// which will then trigger a reset of the timeout to TimeoutDefault on the existing lock and return it.
func Create(projectName string, instanceName string, action Action, createReusuable bool, reuseExisting bool) (*InstanceOperation, error) {
	if projectName == "" || instanceName == "" {
		return nil, fmt.Errorf("Invalid project or instance name")
	}

	instanceOperationsLock.Lock()
	defer instanceOperationsLock.Unlock()

	opKey := project.Instance(projectName, instanceName)

	op := instanceOperations[opKey]
	if op != nil {
		if op.reusable && reuseExisting {
			// Reset operation timeout without releasing lock or deadlocking using Reset() function.
			op.chanReset <- TimeoutDefault
			logger.Debug("Instance operation lock reused", logger.Ctx{"project": op.projectName, "instance": op.instanceName, "action": op.action, "reusable": op.reusable})

			return op, nil
		}

		return nil, fmt.Errorf("Instance is busy running a %q operation", op.action)
	}

	op = &InstanceOperation{}
	op.projectName = projectName
	op.instanceName = instanceName
	op.action = action
	op.reusable = createReusuable
	op.chanDone = make(chan error)
	op.chanReset = make(chan time.Duration)

	instanceOperations[opKey] = op
	logger.Debug("Instance operation lock created", logger.Ctx{"project": op.projectName, "instance": op.instanceName, "action": op.action, "reusable": op.reusable})

	go func(op *InstanceOperation) {
		timeout := TimeoutDefault
		timer := time.NewTimer(timeout)
		defer timer.Stop()

		for {
			select {
			case <-op.chanDone:
				return
			case timeout = <-op.chanReset:
				if !timer.Stop() {
					<-timer.C
				}

				timer.Reset(timeout)
				continue
			case <-timer.C:
				op.Done(fmt.Errorf("Instance %q operation timed out after %v", op.action, timeout))
				return
			}
		}
	}(op)

	return op, nil
}

// CreateWaitGet is a weird function which does what we happen to want most of the time.
//
// If the instance has an operation of the same type and it's not reusable
// or the caller doesn't want to reuse it, the function will wait and
// indicate that it did so.
//
// If the instance has an existing operation of one of the inheritableActions types, then the operation is returned
// to the user. This allows an operation started in one function/routine to be inherited by another.
//
// If the instance doesn't have an ongoing operation, has an operation of a different type that is not in the
// inheritableActions list or has the right type and is being reused, then this behaves as a Create call.
//
// Returns ErrWaitedForMatching if it waited for a matching operation to finish and it's finished successfully and
// so didn't return create a new operation.
func CreateWaitGet(projectName string, instanceName string, action Action, inheritableActions []Action, createReusuable bool, reuseExisting bool) (*InstanceOperation, error) {
	op := Get(projectName, instanceName)

	// No existing operation, call create.
	if op == nil {
		op, err := Create(projectName, instanceName, action, createReusuable, reuseExisting)
		return op, err
	}

	// Operation action matches but is not reusable or we have been asked not to reuse,
	// so wait and return result.
	if op.action == action && (!reuseExisting || !op.reusable) {
		err := op.Wait()
		if err != nil {
			return nil, err
		}

		// The matching operation ended without error, but this means we've not created a new
		// operation for this request, so return a special error indicating this scenario.
		return nil, ErrNonReusuableSucceeded
	}

	// Operation action matches one the inheritable actions, return the operation.
	if op.ActionMatch(inheritableActions...) {
		logger.Debug("Instance operation lock inherited", logger.Ctx{"project": op.projectName, "instance": op.instanceName, "action": op.action, "reusable": op.reusable, "inheritedByAction": action})

		return op, nil
	}

	// Send the rest to Create to try and create a new operation.
	op, err := Create(projectName, instanceName, action, createReusuable, reuseExisting)

	return op, err
}

// Get retrieves an existing lock or returns nil if no lock exists.
func Get(projectName string, instanceName string) *InstanceOperation {
	instanceOperationsLock.Lock()
	defer instanceOperationsLock.Unlock()

	opKey := project.Instance(projectName, instanceName)

	return instanceOperations[opKey]
}

// Action returns operation's action.
func (op *InstanceOperation) Action() Action {
	// This function can be called on a nil struct.
	if op == nil {
		return ""
	}

	return op.action
}

// ActionMatch returns true if operations' action matches on of the matchActions.
func (op *InstanceOperation) ActionMatch(matchActions ...Action) bool {
	for _, matchAction := range matchActions {
		if op.action == matchAction {
			return true
		}
	}

	return false
}

// Reset resets the operation using TimeoutDefault until it expires.
func (op *InstanceOperation) Reset() error {
	return op.ResetTimeout(TimeoutDefault)
}

// ResetTimeout resets the operation using a custom timeout until it expires.
func (op *InstanceOperation) ResetTimeout(timeout time.Duration) error {
	// This function can be called on a nil struct.
	if op == nil {
		return nil
	}

	instanceOperationsLock.Lock()
	defer instanceOperationsLock.Unlock()

	opKey := project.Instance(op.projectName, op.instanceName)

	// Check if already done
	runningOp, ok := instanceOperations[opKey]
	if !ok || runningOp != op {
		return fmt.Errorf("Operation is already done or expired")
	}

	op.chanReset <- timeout
	return nil
}

// Wait waits for an operation to finish.
func (op *InstanceOperation) Wait() error {
	// This function can be called on a nil struct.
	if op == nil {
		return nil
	}

	<-op.chanDone

	return op.err
}

// Done indicates the operation has finished.
func (op *InstanceOperation) Done(err error) {
	// This function can be called on a nil struct.
	if op == nil {
		return
	}

	instanceOperationsLock.Lock()
	defer instanceOperationsLock.Unlock()

	opKey := project.Instance(op.projectName, op.instanceName)

	// Check if already done.
	runningOp, ok := instanceOperations[opKey]
	if !ok || runningOp != op {
		return
	}

	op.err = err
	delete(instanceOperations, opKey) // Delete before closing chanDone.
	close(op.chanDone)
	logger.Debug("Instance operation lock finished", logger.Ctx{"project": op.projectName, "instance": op.instanceName, "action": op.action, "reusable": op.reusable, "err": err})
}

// SetInstanceInitiated sets the instance initiated marker.
func (op *InstanceOperation) SetInstanceInitiated(instanceInitiated bool) {
	// This function can be called on a nil struct.
	if op == nil {
		return
	}

	op.instanceInitiated = instanceInitiated
}

// GetInstanceInitiated gets the instance initiated marker.
func (op *InstanceOperation) GetInstanceInitiated() bool {
	// This function can be called on a nil struct.
	if op == nil {
		return false
	}

	return op.instanceInitiated
}


text:
"use strict";

exports.__esModule = true;

var _getIterator2 = require("babel-runtime/core-js/get-iterator");

var _getIterator3 = _interopRequireDefault(_getIterator2);

var _isIterable2 = require("babel-runtime/core-js/is-iterable");

var _isIterable3 = _interopRequireDefault(_isIterable2);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

exports.default = function (arr, i) {
  if (Array.isArray(arr)) {
    return arr;
  } else if ((0, _isIterable3.default)(Object(arr))) {
    var _arr = [];

    for (var _iterator = (0, _getIterator3.default)(arr), _step; !(_step = _iterator.next()).done;) {
      _arr.push(_step.value);

      if (i && _arr.length === i) break;
    }

    return _arr;
  } else {
    throw new TypeError("Invalid attempt to destructure non-iterable instance");
  }
};

redpajama_set_name: RedPajamaGithub


text:
package au.edu.federation.caliko.demo2d;

import au.edu.federation.caliko.BoneConnectionPoint;
import au.edu.federation.caliko.FabrikBone2D;
import au.edu.federation.caliko.FabrikChain2D;
import au.edu.federation.caliko.FabrikChain2D.BaseboneConstraintType2D;
import au.edu.federation.caliko.FabrikStructure2D;
import au.edu.federation.utils.Mat4f;
import au.edu.federation.utils.Utils;
import au.edu.federation.utils.Vec2f;

/**
 * @author jsalvo
 */
public class VaryingOffsetFixedChainsWithEmbeddedTargets extends FixedTargetDemo {

	/** Targets and offsets for chains with embedded targets in demo 7. */
	private Vec2f mSmallRotatingTargetLeft  = new Vec2f(-70.0f, 40.0f);
	private Vec2f mSmallRotatingTargetRight = new Vec2f( 50.0f, 20.0f);
	private Vec2f mSmallRotatingOffsetLeft  = new Vec2f( 25.0f, 0.0f);
	private Vec2f mSmallRotatingOffsetRight = new Vec2f(  0.0f, 30.0f);

	@Override
	public void setup() {
		// Instantiate our FabrikStructure2D. We're only drawing a single chain in this instance, but because
		// our demo code is geared to draw a structure, we're going to create a structure and add a chain to it.
		this.structure = new FabrikStructure2D("Demo 7 - Varying-offset 'fixed' chains with embedded targets");

		// Create a new chain
		FabrikChain2D chain = new FabrikChain2D();

		float boneLength = 50.0f;
		float startY     = -100.0f;

		// ----- Central white chain ------
		// Create the first bone, configure it, and add it to the chain
		FabrikBone2D basebone;
		basebone = new FabrikBone2D(new Vec2f(0.0f, startY), new Vec2f(0.0f, startY + boneLength) );
		basebone.setClockwiseConstraintDegs(65.0f);
		basebone.setAnticlockwiseConstraintDegs(65.0f);
		chain.addBone(basebone);

		// Fix the base bone to its current location, and constrain it to the positive Y-axis
		chain.setFixedBaseMode(true);
		chain.setBaseboneConstraintType(BaseboneConstraintType2D.GLOBAL_ABSOLUTE);
		chain.setBaseboneConstraintUV(UP);

		// Add second and third bones
		chain.addConsecutiveBone(UP, boneLength);
		chain.addConsecutiveBone(UP, boneLength);

		// Finally, add the chain to the structure
		this.structure.addChain(chain);

		// ----- Left green chain with embedded target -----
		FabrikChain2D leftChain = new FabrikChain2D();
		leftChain.setEmbeddedTargetMode(true); // Enable embedded targets - we actually set the embedded target location in the demo loop
		basebone = new FabrikBone2D(new Vec2f(), new Vec2f(-boneLength / 6.0f, 0.0f) );

		// Add fifteen bones
		leftChain.addBone(basebone);
		for (int boneLoop = 0; boneLoop < 14; ++boneLoop)
		{
			leftChain.addConsecutiveConstrainedBone(RIGHT, boneLength / 6.0f, 25.0f, 25.0f);
		}

		// Set chain colour and basebone constraint type
		leftChain.setColour(Utils.MID_GREEN);

		// Add the left chain to the structure, connected to the start of bone 1 in chain 0
		this.structure.connectChain(leftChain, 0, 1, BoneConnectionPoint.START);

		// ----- Right grey chain with embedded target -----
		FabrikChain2D rightChain = new FabrikChain2D();
		rightChain.setEmbeddedTargetMode(true); // Enable embedded targets - we actually set the embedded target location in the demo loop
		basebone = new FabrikBone2D(new Vec2f(), new Vec2f(boneLength / 5.0f, 0.0f) );
		basebone.setClockwiseConstraintDegs(60.0f);
		basebone.setAnticlockwiseConstraintDegs(60.0f);

		// Add ten bones
		rightChain.addBone(basebone);
		for (int boneLoop = 0; boneLoop < 9; ++boneLoop)
		{
			rightChain.addConsecutiveBone(RIGHT, boneLength / 5.0f);
		}

		// Set chain colour and basebone constraint type
		rightChain.setColour(Utils.GREY);
		rightChain.setBaseboneConstraintType(BaseboneConstraintType2D.LOCAL_ABSOLUTE);
		rightChain.setBaseboneRelativeConstraintUV(RIGHT);

		// Add the right chain to the structure, connected to the start of bone 2 in chain 0
		this.structure.connectChain(rightChain, 0, 2, BoneConnectionPoint.START);
	}

	@Override
	public void drawTarget(Mat4f mvpMatrix) {
		super.preDrawTarget();

		// Rotate offset and apply to base location of first chain
		this.mRotatingOffset = Vec2f.rotateDegs(this.mRotatingOffset, 1.0f);
		this.structure.getChain(0).setBaseLocation( this.mOrigBaseLocation.plus(this.mRotatingOffset) );

		// Rotate offsets for left and right chains
		this.mSmallRotatingOffsetLeft  = Vec2f.rotateDegs(this.mSmallRotatingOffsetLeft, -1.0f);
		this.mSmallRotatingOffsetRight = Vec2f.rotateDegs(this.mSmallRotatingOffsetRight, 2.0f);

		Vec2f newEmbeddedTargetLoc = new Vec2f();
		newEmbeddedTargetLoc.set(this.structure.getChain(1).getEmbeddedTarget() );
		this.structure.getChain(1).updateEmbeddedTarget( this.mSmallRotatingTargetLeft.plus(this.mSmallRotatingOffsetLeft)   );
		this.structure.getChain(2).updateEmbeddedTarget( this.mSmallRotatingTargetRight.plus(this.mSmallRotatingOffsetRight) );

		super.postDrawTarget();
	}

}


text:
'use strict';

var fs = require('fs'),
  join = require('path').join;

describe('WSSecurityCert', function() {
  var WSSecurityCert = require('../../').WSSecurityCert;
  var cert = fs.readFileSync(join(__dirname, '..', 'certs', 'agent2-cert.pem'));
  var key = fs.readFileSync(join(__dirname, '..', 'certs', 'agent2-key.pem'));

  it('is a function', function() {
    WSSecurityCert.should.be.type('function');
  });

  it('should accept valid constructor variables', function() {
    var instance = new WSSecurityCert(key, cert, '', 'utf8');
    instance.should.have.property('privateKey');
    instance.should.have.property('publicP12PEM');
    instance.should.have.property('signer');
    instance.should.have.property('x509Id');
  });

  it('should not accept invalid constructor variables', function() {
    var passed = true;

    try {
      new WSSecurityCert('*****', cert, '', 'utf8');
    } catch(e) {
      passed = false;
    }

    if (passed) {
      throw new Error('bad private key');
    }

    passed = true;

    try {
      new WSSecurityCert(key, cert, '', 'bob');
    } catch(e) {
      passed = false;
    }

    if (passed) {
      throw new Error('bad encoding');
    }
  });

  it('should insert a WSSecurity signing block when postProcess is called', function() {
    var instance = new WSSecurityCert(key, cert, '', 'utf8');
    var xml = instance.postProcess('<soap:Header></soap:Header><soap:Body></soap:Body>', 'soap');

    xml.should.containEql('<wsse:Security');
    xml.should.containEql('http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd');
    xml.should.containEql('http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd');
    xml.should.containEql('soap:mustUnderstand="1"');
    xml.should.containEql('<wsse:BinarySecurityToken');
    xml.should.containEql('EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary');
    xml.should.containEql('ValueType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3"');
    xml.should.containEql('wsu:Id="' + instance.x509Id);
    xml.should.containEql('</wsse:BinarySecurityToken>');
    xml.should.containEql('<Timestamp xmlns="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" Id="_1">');
    xml.should.containEql('<Created>' + instance.created);
    xml.should.containEql('<Expires>' + instance.expires);
    xml.should.containEql('<Signature xmlns="http://www.w3.org/2000/09/xmldsig#">');
    xml.should.containEql('<wsse:SecurityTokenReference>');
    xml.should.containEql('<wsse:Reference URI="#' + instance.x509Id);
    xml.should.containEql('ValueType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3"/>');
    xml.should.containEql(instance.publicP12PEM);
    xml.should.containEql(instance.signer.getSignatureXml());
  });

  it('should only add two Reference elements, for Soap Body and Timestamp inside wsse:Security element', function() {
    var instance = new WSSecurityCert(key, cert, '', 'utf8');
    var xml = instance.postProcess('<soap:Header></soap:Header><soap:Body><Body></Body><Timestamp></Timestamp></soap:Body>', 'soap');

    xml.match(/<Reference URI="#/g).should.have.length(2);
  });
});


text:
<?php
/**
 * Created by PhpStorm.
 * User: Ricardo Fiorani
 * Date: 02/09/2015
 * Time: 22:41.
 */
namespace Coalmarch\Adapter\Facebook\Factory;

use Coalmarch\Adapter\Facebook\FacebookServiceAdapter;
use Coalmarch\Adapter\CallableServiceAdapterFactoryInterface;
use Coalmarch\Adapter\VideoAdapterInterface;
use Coalmarch\Renderer\EmbedRendererInterface;

class FacebookServiceAdapterFactory implements CallableServiceAdapterFactoryInterface
{
    /**
     * @param string                 $url
     * @param string                 $pattern
     * @param EmbedRendererInterface $renderer
     *
     * @return VideoAdapterInterface
     */
    public function __invoke($url, $pattern, EmbedRendererInterface $renderer)
    {
        return new FacebookServiceAdapter($url, $pattern, $renderer);
    }
}


text:
'use strict';

var mongoose = require('mongoose'),
	 config = require('../../config.json'),
	 env = process.env.NODE_ENV || "development",
	 url = config.MONGODB[env],
	 Promise = require('bluebird'),
	 connection;

Promise.promisifyAll(mongoose);

module.exports = function(){
	if(!connection) {
		connection = mongoose.connect(url);
	}
	return connection;
};


text:
<!doctype html>

    <meta charset="utf-8">
    <meta name="author" content="Dennis Ng, Pooya Griffin, Jamie Nguyen">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Com Tam Thanh - Vietnamese Restaurant </title>

    <link rel="stylesheet" href="css/foundation.min.css">
    <link rel="stylesheet" href="css/app.css">

    <link href="https://fonts.googleapis.com/css?family=Josefin+Sans" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css?family=Varela" rel="stylesheet">

    <link rel="apple-touch-icon" sizes="57x57" href="favicon/apple-icon-57x57.png">
    <link rel="apple-touch-icon" sizes="60x60" href="favicon/apple-icon-60x60.png">
    <link rel="apple-touch-icon" sizes="72x72" href="favicon/apple-icon-72x72.png">
    <link rel="apple-touch-icon" sizes="76x76" href="favicon/apple-icon-76x76.png">
    <link rel="apple-touch-icon" sizes="114x114" href="favicon/apple-icon-114x114.png">
    <link rel="apple-touch-icon" sizes="120x120" href="favicon/apple-icon-120x120.png">
    <link rel="apple-touch-icon" sizes="144x144" href="favicon/apple-icon-144x144.png">
    <link rel="apple-touch-icon" sizes="152x152" href="favicon/apple-icon-152x152.png">
    <link rel="apple-touch-icon" sizes="180x180" href="favicon/apple-icon-180x180.png">
    <link rel="icon" type="image/png" sizes="192x192" href="favicon/android-icon-192x192.png">
    <link rel="icon" type="image/png" sizes="32x32" href="favicon/favicon-32x32.png">
    <link rel="icon" type="image/png" sizes="96x96" href="favicon/favicon-96x96.png">
    <link rel="icon" type="image/png" sizes="16x16" href="favicon/favicon-16x16.png">
    <link rel="manifest" href="favicon/manifest.json">
    <meta name="msapplication-TileColor" content="#ffffff">
    <meta name="msapplication-TileImage" content="favicon/ms-icon-144x144.png">
    <meta name="theme-color" content="#ffffff">

              <button class="menu-icon" type="button" data-toggle></button>

Menu

Hours and Locations

Our Story

VIETNAMESE RESTAURANT

Chef's Recommendations

1. Gỏi Cuốn

Shrimp, Pork, Vermicelli & Lettuce Spring Roll - $5.25

7. Nem NuớngCuốn

BBQ Pork & Lettuce Spring Roll served with Peanut Sauce - $5.25

17.	Cơm Tấm Sườn BòĐại Hàn

Broken Rice w/ Korean Beef BBQ - $8.25

39.	Phở Bò Viên

Rice Noodle w/ Meat Balls - REG. $7.25 LARGE $8.25

72. Bún Tôm Thịt Nướng Chả Giò

Vermicelli w/ BBQ Shrimp, BBQ Pork, Egg Roll & Vegetables  - $8.95

80. Bún bò Huê

Vermicelli w/ BBQ Shrimp, BBQ Pork, Egg Roll & Vegetables - $7.95

Call for Takeout

1150 Story Rd, San Jose, CA 95122

        (408)278-1888

905 S Bascom Ave, San Jose, CA 95128

        (408)279-8588

5733 Stevenson Blvd, Newark, CA 94560

        (510)226-8899

 Copyright CSU East Bay Web Design Team 2017


text:
package com.opengamma.util.test;

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

import org.springframework.context.Lifecycle;

/**
 * Helper class for managing {@link Lifecycle} implementing objects during a test session. Objects may be created by test infrastructure
 * that must be shutdown but are embedded or wrapped in other object instances which don't expose life cycle methods so may not be
 * directly available for the caller to explicitly shut them down.
 *

 * Typically a test method may written along the lines of:
 *
 *

 * public void testFoo() {
 *   TestLifecycle.begin();
 *   try {
 *     // ... test stuff
 *   } finally {
 *     TestLifecycle.end();
 *   }
 * }
 *

 *
 * Any test infrastructure that creates things that must be shutdown at the end of the test can register them, after they've been started,
 * by a call to {@link #register}.
 */
public final class TestLifecycle {

  private static final ThreadLocal<TestLifecycle> INSTANCES = new ThreadLocal<>();

  private final List<Lifecycle> _toStop = new ArrayList<>();

  private TestLifecycle() {
  }

  private static TestLifecycle instance() {
    final TestLifecycle instance = INSTANCES.get();
    if (instance != null) {
      return instance;
    }
    throw new IllegalStateException("Current thread not associated with a test instance");
  }

  /**
   * Call at the start of a test.
   */
  public static void begin() {
    if (INSTANCES.get() != null) {
      throw new IllegalStateException("Current thread already associated with a test instance");
    }
    INSTANCES.set(new TestLifecycle());
  }

  /**
   * Call at the end of a test.
   */
  public static void end() {
    final List<Lifecycle> toStop = instance()._toStop;
    INSTANCES.set(null);
    for (final Lifecycle instance : toStop) {
      if (instance.isRunning()) {
        instance.stop();
      }
    }
  }

  /**
   * Associate a {@link Lifecycle} instance with this test session. When the session ends the {@link Lifecycle#stop} method will be called.
   *

   * The object will only be registered if it is already started.
   *
   * @param instance the instance to register, not null
   * @throws IllegalStateException if {@link #begin} has not been called for this session
   */
  public static void register(final Lifecycle instance) {
    if (instance.isRunning()) {
      instance()._toStop.add(instance);
    }
  }

}


text:
package com.github.pires.example.model;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

import java.util.ArrayList;
import java.util.List;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Version;

@JsonIgnoreProperties(value = {"handler"})
public class User {

    @Id
    private String id;
    @Version
    @JsonIgnore
    private Long version;
    private Long created;
    private String email;
    private String name;
    private Boolean active;
    private String password;
    @OneToMany
    private List<Role> roles;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public Long getVersion() {
        return version;
    }

    public void setVersion(Long version) {
        this.version = version;
    }

    public Long getCreated() {
        return created;
    }

    public void setCreated(Long created) {
        this.created = created;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Boolean getActive() {
        return active;
    }

    public void setActive(Boolean active) {
        this.active = active;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public List<Role> getRoles() {
        if (roles == null) {
            this.roles = new ArrayList<>();
        }
        return roles;
    }

    public void setRoles(List<Role> roles) {
        this.roles = roles;
    }

}


text:
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using DevExpress.XtraEditors;

namespace eidss.gis.Forms
{
    public partial class SaveMapForm : XtraForm
    {
        public SaveMapForm()
        {
            InitializeComponent();
        }

        private List<string> m_MapProjectsList;
        public void SetMapList(List<string> list)
        {
            m_MapProjectsList = list;
            mapsListBox.DataSource = m_MapProjectsList;
        }

        private bool m_Flag;
        private void mapsListBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            if ( m_Flag )
                mapEdit.Text = mapsListBox.SelectedItem.ToString(); //it's ugly!
            else
                m_Flag = true;
        }

        private void mapsListBox_MouseDown(object sender, MouseEventArgs e)
        {
            if (mapsListBox.SelectedItem != null)
            {
                mapEdit.Text = mapsListBox.SelectedItem.ToString();
            }
        }

        public string MapName
        {
            get { return mapEdit.Text; }
        }

        private void mapEdit_TextChanged(object sender, EventArgs e)
        {
            okButton.Enabled = !string.IsNullOrEmpty(mapEdit.Text);
        }
    }
}


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

<title>S-Index</title>
<meta name="date" content="2018-06-28">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Package

Class

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes

A B C D E F G H I J L M O Q R S T U V

S

ScalarResultHandler - Interface in org.mozilla.mentat

Interface defining the structure of a callback from a query returning a single TypedValue.

Store() - Constructor for class org.mozilla.mentat.JNA.Store

store_begin_transaction(JNA.Store, RustError.ByReference) - Method in interface org.mozilla.mentat.JNA

store_cache_attribute_bi_directional(JNA.Store, String, RustError.ByReference) - Method in interface org.mozilla.mentat.JNA

store_cache_attribute_forward(JNA.Store, String, RustError.ByReference) - Method in interface org.mozilla.mentat.JNA

store_cache_attribute_reverse(JNA.Store, String, RustError.ByReference) - Method in interface org.mozilla.mentat.JNA

store_destroy(JNA.Store) - Method in interface org.mozilla.mentat.JNA

store_entid_for_attribute(JNA.Store, String) - Method in interface org.mozilla.mentat.JNA

store_entity_builder_from_entid(JNA.Store, long, RustError.ByReference) - Method in interface org.mozilla.mentat.JNA

store_entity_builder_from_temp_id(JNA.Store, String, RustError.ByReference) - Method in interface org.mozilla.mentat.JNA

store_in_progress_builder(JNA.Store, RustError.ByReference) - Method in interface org.mozilla.mentat.JNA

store_open(String) - Method in interface org.mozilla.mentat.JNA

store_query(JNA.Store, String) - Method in interface org.mozilla.mentat.JNA

store_register_observer(JNA.Store, String, Pointer, int, TxObserverCallback) - Method in interface org.mozilla.mentat.JNA

store_transact(JNA.Store, String, RustError.ByReference) - Method in interface org.mozilla.mentat.JNA

store_unregister_observer(JNA.Store, String) - Method in interface org.mozilla.mentat.JNA

store_value_for_attribute(JNA.Store, long, String, RustError.ByReference) - Method in interface org.mozilla.mentat.JNA

A B C D E F G H I J L M O Q R S T U V

Skip navigation links

Package

Class

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes


text:
<!DOCTYPE html>

		<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">

Angular CKEditor Directive

					<textarea ck-editor ng-model="markUp" plaintext="plainText" options="ckEditorOptions"></textarea>

Markup:

Plain Text:


text:
<input id="testButton" type="input" value="Click Me"/>

 Prevent Default these events:

 Logged events:

  hello!


text:
import EmberTable from 'ember-table/components/ember-table';

export default EmberTable;


text:
extern string get_str(value x);
extern value type_str(value f);
extern value Qstr(string x);
extern value Qstr0(const char *data);
extern const char *str_data(value x);
extern value op_str(value f, string op(string));
extern value op_str2(value f, string op(string,string));
extern value op_str3(value f, string op(string,string,string));
extern value type_concat(value f);
extern value type_length(value f);
extern value type_slice(value f);
extern value type_search(value f);
extern value type_str_num(value f);
extern value type_ord(value f);
extern value type_chr(value f);
extern value type_char_width(value f);
extern value type_dirname(value f);
extern value type_basename(value f);
extern value type_length_common(value f);
extern value type_is_str(value f);

struct collect
	{
	unsigned long len;
	value items;
	unsigned long size;
	const char *const *argv;
	};

extern void beg_collect(value x, struct collect *collect, const char *msg);
extern void end_collect(struct collect *collect);


text:
<?php
/**
 * Created by PhpStorm.
 * User: michi
 * Date: 19.11.17
 * Time: 08:16
 */

namespace Ems\Contracts\Core;

/**
 * Class None
 *
 * This class is for all cases where you want to know if something is really
 * nothing. If you want to now if something is a cache hit even if it is null
 * you can try: Cache::get('key', new None)
 * If you get that None back, you now that the entry does not exist.
 * You can also store None in an array to get rid of that isset($array['key'])
 * and null thing in php.
 *
 * @package Ems\Contracts\Core
 */
class None
{
    //
}


text:
[![Latest Version](http://img.shields.io/badge/latest-0.8.0-brightgreen.svg)](https://github.com/rholder/gradle-wrapper-here/releases/tag/v0.8.0) [![License](http://img.shields.io/badge/license-apache%202-brightgreen.svg)](https://github.com/rholder/gradle-wrapper-here/blob/master/LICENSE)

## What is this?
What if you could just extract the Gradle wrapper files into the project
directory without ever running Gradle or even having it installed? Well now you
can do that with `gradle-wrapper-here`.

I like the [Gradle wrapper](https://docs.gradle.org/5.6.2/userguide/gradle_wrapper.html),
but I think it's silly to have to have an actual installation of Gradle on your
machine to bootstrap from before you can start using it for the first time on a
project. If you've never used Gradle before, I believe this is a much quicker
mechanism to getting a working Gradle installation set up for a project.

## Installation
### macOS & Linux
Drop the latest version of `gradle-wrapper-here` into your $PATH and set it executable:

```bash
sudo curl -o /usr/local/bin/gradle-wrapper-here -L https://github.com/rholder/gradle-wrapper-here/releases/download/v0.8.0/gradle-wrapper-here && \
sudo chmod +x /usr/local/bin/gradle-wrapper-here
```

## Usage
There isn't really much to this project. It extracts a copy of the Gradle
wrapper out into the specified directory, as in:
```bash
mkdir koala
gradle-wrapper-here koala
```
If you prefer to extract the wrapper to the current directory you're in, you
can use:
```bash
gradle-wrapper-here ./
```
Now you should have `gradlew` and some other goodies in your project directory.
Run the following to verify it's working:
```bash
./gradlew -version
```
If you haven't ever used the Gradle wrapper before, it will download and unpack
a version of Gradle into a well-known location for the current user. Running
`./gradlew` again won't redownload it.

## License
The `gradle-wrapper-here` project is released under version 2.0 of the
[Apache License](http://www.apache.org/licenses/LICENSE-2.0).


text:
package org.mini2Dx.core.collision;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * Generates IDs for collision objects (e.g. {@link CollisionBox}, {@link CollisionPoint}, etc.)
 */
public class CollisionIdSequence {
	private static final AtomicInteger ID_SEQUENCE = new AtomicInteger();

	public static int nextId() {
		return ID_SEQUENCE.incrementAndGet();
	}

	public static int offset(int value) {
		ID_SEQUENCE.set(value);
		return value;
	}
}


text:
function [ perf ] = getPerfMLP( w, numOutputs, plotOutput, preProcessData )
%GETPERFMLP Summary of this function goes here
%   Detailed explanation goes here

epochs = 1;
samples = 1000;

% Generate the training data
[testPoints, groupName] = genTrainingDataMLPEKF(epochs, samples);
% Get more information about the training data
[desiredOutput, redPoints, blackPoints] = separateDataMLPEKF(groupName);

curTestData = squeeze(testPoints(1,:,:));
if(preProcessData)
    % Normalize the test data
    curTestData(1,:) = (curTestData(1,:) - mean(curTestData(1,:)))...
        /std(curTestData(1,:));
    curTestData(2,:) = (curTestData(2,:) - mean(curTestData(2,:)))...
        /std(curTestData(2,:));
end

mlpOutput = simMLP(w,curTestData,numOutputs);

redPointsAfter = (mlpOutput >= 0);
blackPointsAfter = (mlpOutput < 0);

correct = logical(redPointsAfter & redPoints) + logical(blackPointsAfter & blackPoints);
% incorrect = logical(blackPointsAfter & blackPoints);

perf = sum(correct)/samples;

if(plotOutput)
    saveFolder = 'C:\Users\Phil\Documents\School\Masters\ECE 739 - Neural Networks\Project\EKF MLP';
    h = figure;
    redPointsCorrect = logical(redPointsAfter & redPoints);
    scatter(...
        testPoints(1,1,redPointsCorrect),...
        testPoints(1,2,redPointsCorrect),...
        20,[1 0 0],...
        'Marker','+');
    hold on;
    blackPointsCorrect = logical(blackPointsAfter & blackPoints);
    scatter(...
        testPoints(1,1,blackPointsCorrect),...
        testPoints(1,2,blackPointsCorrect),...
        20,[0 0 0],...
        'Marker','+');
    hold on;
    redPointsIncorrect = ~redPointsCorrect & redPoints;
    scatter(...
        testPoints(1,1,redPointsIncorrect),...
        testPoints(1,2,redPointsIncorrect),...
        20,[1 0 0],...
        'Marker','x');
    hold on;
    blackPointsIncorrect = ~blackPointsCorrect & blackPoints;
    scatter(...
        testPoints(1,1,blackPointsIncorrect),...
        testPoints(1,2,blackPointsIncorrect),...
        20,[0 0 0],...
        'Marker','x');
    title('Classified data');

    % Construct legend string
    ind1 = 1;
    if(sum(redPointsCorrect) ~= 0)
        legendString{ind1} = 'Correct red points';
        ind1 = ind1 + 1;
    end
    if(sum(blackPointsCorrect) ~= 0)
        legendString{ind1} = 'Correct black points';
        ind1 = ind1 + 1;
    end
    if(sum(redPointsIncorrect) ~= 0)
        legendString{ind1} = 'Incorrect red points';
        ind1 = ind1 + 1;
    end
    if(sum(blackPointsIncorrect) ~= 0)
        legendString{ind1} = 'Incorrect black points';
    end
    legend(legendString);

    axis square;
    hold off;
    saveas(h,[saveFolder filesep 'Classification Performance' '.png']);
    saveas(h,[saveFolder filesep 'Classification Performance' '.fig']);

    % Create a 3D scatter plot
    figure;
    x = squeeze(testPoints(1,1,:));
    y = squeeze(testPoints(1,2,:));
    z = squeeze(mlpOutput)';
    scatter3(x,y,z,10,z);
    axis square;
    view(2);
    title('Output scatter plot of MLP EKF');

    figure;
    x = squeeze(testPoints(1,1,:));
    y = squeeze(testPoints(1,2,:));
    z = squeeze(mlpOutput)';
    tri = delaunay(x,y);
    trisurf(tri,x,y,z);
    hold on
    axis square;
    title('Output surface of MLP EKF');
end

end


text:
CS 10 Review
---

1) Draw a conceptual model of a variable. Label the address, name, and contents of your variable at a minimum.

2) Use your model from part 1 to draw a conceptual model of a vector.

3) Descrive the difference between passing a variable by value and passing a variable by reference.

4) List some types that should almost always be passed by reference. Why is this the case?

5) Write a function that swaps the contents of two variables of type char.

6) Write a function that reverses all the strings in a vector of strings.

7) Write a function that takes as input a vector of strings and does the following:

   Output 'True' to the terminal if more than half the strings in the vector have a length greater than 6.

   Output 'False' to the terminal otherwise.

Brain Teasers
---

Since its right after winter break and your brains are dead and frankly so is your SI Leaders,
heres some fun brain teasers to wake you up and get your brain gears working!

1) What belongs to you, but others use it more?

2) What dissapears the moment you say its name?

3)


text:
{% extends "base.html" %}

{% block doctitle %}
Team settings
{% endblock %}

{% block content %}

{{ organization_user }} @ {{ organization }}

{% if user == organization_user.user %}This is you!{% endif %}

Name: {{ organization_user.full_name }}

Email: {{ organization_user.user.email }}

Edit

 Delete

{% endblock %}


text:
/**
 * Utility classes relating to the {@link org.jsimpledb.kv.KVDatabase} interface.
 */
package org.jsimpledb.kv.util;


text:
require 'csv'
require 'tempfile'
require 'net/http'
require 'rmagick'
require "s3"

RECUT                   = true                # Set to true to re-upload even if the file already exists
DESKEW                  = true                # Set to true to attempt to deskew images before splitting
BUCKET_NAME             = 'scribe.nypl.org'   # S3 Bucket name
BUCKET_FOLDER           = 'emigrant'          # Folder within bucket to place uploaded files
SPLIT_OVERLAP           = 0.03                # When splitting pages cut each side so that it bleeds this
                                              #   far into the other side. (content sometimes bleeds over
                                              #   midline)
S3_API_FAILURE_RETRY    = 3                   # S3 connection failures are common. Retry this many times

START_AT = ARGV[0].nil? ? nil : ARGV[0].to_i
STOP_AT = ARGV[1].nil? ? nil : ARGV[1].to_i

$in_path = "#{File.dirname(File.dirname(__FILE__))}/subjects/subjects_from_api.building.csv"
$out_path = "#{File.dirname(File.dirname(__FILE__))}/subjects/group_only_one_group.building.csv"

$s3 = S3::Service.new(access_key_id: ENV['S3_ID'], secret_access_key: ENV['S3_SECRET'])
$bucket = $s3.buckets.find BUCKET_NAME

# Saves img (IO Stream) to path (String)
# e.g. upload_img(<IO>, "folder/subfolder/filename.jpg")
def upload_image(img, path, retries_remaining = S3_API_FAILURE_RETRY)
  puts "  Uploading #{img.columns}x#{img.rows} image to #{path}"

  # If this image already uploaded, skip (unless we're recutting everything)
  if $existing_paths.include?(path) && ! RECUT
    puts "    Skipping cause already uploaded"

  else
    obj = $bucket.objects.build(path)
    obj.content_type = 'image/jpeg'
    obj.content = img.to_blob
    obj.acl = :public_read
    begin
      obj.save

    rescue S3::Error::RequestTimeout => e
      if retries_remaining > 0
        sleep 10
        upload_image img, path, retries_remaining - 1
      else
        puts "FAILED to write to #{path} after #{S3_API_FAILURE_RETRY} retries. Aborting"
        exit
      end
    end
    sleep 0.25
  end
end

# Updates out_path csv with given subjects rows
def update_csv(rows)
  CSV.open($out_path, "wb") do |csv|

    # `rows` is just an array of hashes; the first will be the headers
    csv << rows.first.keys

    rows.each do |row|
      csv << row.values
    end
  end
end

# Detect best rotation angle by deskewing a sample of the image's middle
def deskew_angle(img)
  temp = Tempfile.new 'split-subjects-vertically'
  sample = img.clone
  # inset crop 10% from borders:
  sample_inset = 0.10
  sample.crop! img.columns * sample_inset, img.rows * sample_inset, img.columns - (img.columns * 2 * sample_inset), img.rows - (img.rows * 2 * sample_inset)
  sample.write temp.path
  sample.write "temp.sample.jpg"
  angle = `convert #{temp.path} -deskew 40 -format '%[deskew:angle]' info:`.to_f
  # If angle is greater than this, it's probably an error
  angle.abs >= 2 ? 0 : angle
end

# Upload default derivs for img, returning urls
def upload_derivs(img, filename)

  ret = {}

  # Full:
  full_path = "#{BUCKET_FOLDER}/full/#{filename}" # data['capture_uuid']}.#{suffix}.jpg"
  upload_image img, full_path
  ret['file_path'] = "https://s3.amazonaws.com/#{BUCKET_NAME}/#{full_path}"

  # Thumb (exactly 150px wide by however tall):
  img.change_geometry("150") { |cols, rows, img| img.resize!(cols, rows) }
  thumb_path = "#{BUCKET_FOLDER}/thumb/#{filename}"
  upload_image img, thumb_path
  ret['thumbnail'] = "https://s3.amazonaws.com/#{BUCKET_NAME}/#{thumb_path}"

  ret
end

$rows = []
$rows = CSV.read($out_path, headers: true).map { |r| r.to_h }
$headers = CSV.read($out_path).first

# Add row to csv
def add_row(row)

  # Delete row if it already exists
  $rows.delete_if { |r| r['file_path'] == row['file_path'] }
  $rows << row

  # rewrite csv:
  update_csv($rows)
end

# Crop given image
def make_crop(img, row, name, coords)
  _row = row.clone

  # Perform crop:
  crop = img.crop coords[:x], coords[:y], coords[:w], coords[:h]

  # Add width, height to csv row:
  _row.merge! width: coords[:w], height: coords[:h]
  # Add source_ coordinates to csv row:
  source_coords = coords.inject({}) {|h, (k,v)| h["source_#{k}"] = v; h }
  _row.merge! source_coords
  # Add URLs to csv row:
  urls =  upload_derivs crop, "#{_row['capture_uuid']}.#{name}.jpg"
  _row.merge! urls

  add_row _row
end

# Perform appropriate crops:
def make_crops(img, row)
  # Cut it in two if it's wider than it is tall:
  if img.columns > img.rows
    puts "Splitting #{row['file_path']}"

    overlap = SPLIT_OVERLAP * img.columns

    coords = { x: 0, y: 0, w: img.columns / 2 + overlap, h: img.rows }
    make_crop img, row, 'left', coords

    coords = { x: img.columns / 2 - overlap, y: 0, w: img.columns / 2 + overlap, h: img.rows }
    make_crop img, row, 'right', coords

  else
    puts "Not splitting #{row['file_path']}"

    coords = { x: 0, y: 0, w: img.columns, h: img.rows }
    make_crop img, row, 'unsplit', coords
  end
end

# Load an rmagick image instance, safely returning nil if images.nypl returns "0"
def load_image(url)
  require 'open-uri'
  temp = Tempfile.new 'split-vertically'
  image = nil

  seems_legit = false
  open(temp.path, 'wb') do |file|
    file << open(url).read
    # Images server returns literally "0" if no image exists
    seems_legit = file.size > 1
  end
  sleep 0.25 # Let's try to be nice to the images server

  Magick::Image.read(temp.path).first if seems_legit
end

# Get list of existing paths in
$existing_paths = $bucket.objects.select { |b| b.key.match /#{BUCKET_FOLDER}\// }.map { |b| b.key }

puts "Processing #{START_AT} - #{STOP_AT} in #{CSV.foreach($in_path, headers: true).size} line input"
CSV.foreach($in_path, headers: true) do |row|
  next if ! START_AT.nil? && $. < START_AT
  break if ! STOP_AT.nil? && $. > STOP_AT

  puts "#{$.}: Processing #{row['file_path']}"
  row = row.to_h

  crops = {}

  # Load image from std url:
  img = load_image row['file_path']
  if img.nil?
    puts "  Problem loading #{row['file_path']}; Skipping"
    next
  end

  # Perform automatic deskew?
  if DESKEW
    img.background_color = 'black'
    # Save source_rotation to csv row and rotate:
    img.rotate! (row['source_rotated'] = deskew_angle(img))
  end

  # Make crops:
  make_crops img, row

end

puts "Done"


text:
var hypster = function(what){
    return {
        do : function(who){
            return who + ' do ' + what + ' like an hypster';
        }
    };
};

module.exports = hypster;


text:
import * as vscode from 'vscode';

import { configuration } from '../configuration/configuration';

export class Decoration {
  static readonly Default = vscode.window.createTextEditorDecorationType({
    backgroundColor: new vscode.ThemeColor('editorCursor.foreground'),
    borderColor: new vscode.ThemeColor('editorCursor.foreground'),
    dark: {
      color: 'rgb(81,80,82)',
    },
    light: {
      // used for light colored themes
      color: 'rgb(255, 255, 255)',
    },
    borderStyle: 'solid',
    borderWidth: '1px',
  });

  static readonly SearchHighlight = vscode.window.createTextEditorDecorationType({
    backgroundColor: configuration.searchHighlightColor,
  });

  static readonly EasyMotion = vscode.window.createTextEditorDecorationType({
    backgroundColor: configuration.searchHighlightColor,
  });
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="VcsDirectoryMappings">
    <mapping directory="$PROJECT_DIR$" vcs="Git" />
    <mapping directory="$PROJECT_DIR$/heroku/server" vcs="Git" />
    <mapping directory="$PROJECT_DIR$/local/HSHacks 2017" vcs="Git" />
    <mapping directory="$PROJECT_DIR$/local/server" vcs="Git" />
    <mapping directory="$PROJECT_DIR$/local/skycam" vcs="Git" />
  </component>
</project>


text:
namespace autofill {
namespace switches {

// All switches in alphabetical order. The switches should be documented
// alongside the definition of their values in the .cc file.
extern const char kDisableCreditCardScan[];
extern const char kDisableFillOnAccountSelect[];
extern const char kDisableFullFormAutofillIOS[];
extern const char kDisableOfferStoreUnmaskedWalletCards[];
extern const char kDisableOfferUploadCreditCards[];
extern const char kDisablePasswordGeneration[];
extern const char kDisableSingleClickAutofill[];
extern const char kEnableCreditCardScan[];
extern const char kEnableFillOnAccountSelect[];
extern const char kEnableFillOnAccountSelectNoHighlighting[];
extern const char kEnableFullFormAutofillIOS[];
extern const char kEnableOfferStoreUnmaskedWalletCards[];
extern const char kEnableOfferUploadCreditCards[];
extern const char kEnablePasswordGeneration[];
extern const char kEnableSingleClickAutofill[];
extern const char kEnableSuggestionsWithSubstringMatch[];
extern const char kEnableWalletMetadataSync[];
extern const char kIgnoreAutocompleteOffForAutofill[];
extern const char kLocalHeuristicsOnlyForPasswordGeneration[];
extern const char kShowAutofillTypePredictions[];
extern const char kWalletSecureServiceUrl[];
extern const char kWalletServiceUrl[];
extern const char kWalletServiceUseSandbox[];

#if defined(OS_ANDROID)
extern const char kDisableAccessorySuggestionView[];
extern const char kEnableAccessorySuggestionView[];
#endif  // defined(OS_ANDROID)

}  // namespace switches
}  // namespace autofill

#endif  // COMPONENTS_AUTOFILL_CORE_COMMON_AUTOFILL_SWITCHES_H_


text:
#ifndef _BalancesManager_H_
#define _BalancesManager_H_

#include <string>
#include <cstring>
#include <list>
#include <glib.h>
#include "Balance.h"
#include "MessageReject.h"
#include "Error.h"

/** \defgroup Operations API Endpoints
 *  Classes containing all the functions for calling API endpoints
 *
 */

namespace Tizen{
namespace ArtikCloud {
/** \addtogroup Balances Balances
 * \ingroup Operations
 *  @{
 */
class BalancesManager {
public:
	BalancesManager();
	virtual ~BalancesManager();

/*! \brief Get balances. *Synchronous*
 *
 * Get current currency balance from all or single exchange.
 * \param exchangeId Filter the balances to the specific exchange.
 * \param handler The callback function to be invoked on completion. *Required*
 * \param accessToken The Authorization token. *Required*
 * \param userData The user data to be passed to the callback function.
 */
bool v1BalancesGetSync(char * accessToken,
	std::string exchangeId,
	void(* handler)(std::list<Balance>, Error, void* )
	, void* userData);

/*! \brief Get balances. *Asynchronous*
 *
 * Get current currency balance from all or single exchange.
 * \param exchangeId Filter the balances to the specific exchange.
 * \param handler The callback function to be invoked on completion. *Required*
 * \param accessToken The Authorization token. *Required*
 * \param userData The user data to be passed to the callback function.
 */
bool v1BalancesGetAsync(char * accessToken,
	std::string exchangeId,
	void(* handler)(std::list<Balance>, Error, void* )
	, void* userData);

	static std::string getBasePath()
	{
		return "https://ems-gateway-aws-eu-central-1-dev.coinapi.io";
	}
};
/** @}*/

}
}
#endif /* BalancesManager_H_ */


text:
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}

module Y.Buffer where

import Control.Lens
import Control.Lens.TH
import Data.Default
import Data.Group
import Data.Monoid
import qualified Data.Vector as V

import qualified Y.String as S

data Buffer = Buffer
    { _text :: S.YiString
    , _cursorPosition :: S.Position
    } deriving (Eq, Show)

makeLenses ''Buffer

instance Default Buffer where
    def = Buffer "" 0

data BufferUpdate
    = Composite (V.Vector BufferUpdate)
    | Insert S.YiString
    | Delete S.YiString
    | CursorFromTo S.Position S.Position
    | Nop
    deriving (Show, Eq)

cursorUp :: Buffer -> BufferUpdate
cursorUp (Buffer string cursor)
    = if y > 0
      then CursorFromTo cursor (S.positionForCoords (pred y, 0) string)
      else Nop
    where
        (y, x) = S.coordsOfPosition cursor string

instance Monoid BufferUpdate where
    mempty = Nop
    mappend x Nop = x
    mappend Nop x = x
    mappend (Insert s) (Insert t) = Insert (mappend s t)
    mappend (Composite xs) (Composite ys) = Composite (mappend xs ys)
    mappend x y = Composite (V.fromList [x, y])

instance Group BufferUpdate where
    invert Nop = Nop
    invert (Insert s) = Delete s
    invert (Delete s) = Insert s
    invert (CursorFromTo x y) = CursorFromTo y x
    invert (Composite xs) = Composite (V.reverse (fmap invert xs))

cursorDown :: Buffer -> BufferUpdate
cursorDown (Buffer string cursor)
    = if y < lineCount
      then CursorFromTo cursor (S.positionForCoords (succ y, 0) string)
      else Nop
    where
        (y, x) = S.coordsOfPosition cursor string
        lineCount = S.countNewLines string

cursorLeft :: Buffer -> BufferUpdate
cursorLeft b | atSof b = Nop
cursorLeft (Buffer _ cursor) = CursorFromTo cursor (pred cursor)

cursorRight :: Buffer -> BufferUpdate
cursorRight b | atEof b = Nop
cursorRight (Buffer _ cursor) = CursorFromTo cursor (succ cursor)

atSof :: Buffer -> Bool
atSof (Buffer _ 0) = True
atSof _ = False

atEof :: Buffer -> Bool
atEof (Buffer string cursor) = cursor == S.fromSize (S.length string)


text:
package ag.ifpb.sct.ws.site.application;

import org.restlet.Context;
import org.restlet.routing.Router;

import ag.ifpb.sct.ws.site.resource.json.ImageResource;
import ag.ifpb.sct.ws.site.resource.json.ImagesResource;

public class WebServiceApplication extends AbstractApplication {

  @Override
  protected Router createRouter(Context ctx) {
    Router routing = new Router(ctx);
    routing.attach("/image", ImageResource.class);
    routing.attach("/images", ImagesResource.class);
    return routing;
  }

}


text:
{% load i18n %}
{% if election.voting_has_started %}
  {% if not election.voting_has_stopped %}

<form id="cast_confirm_form" method="post" action="" onsubmit="show_waiting()">
    <input type="hidden" name="csrf_token" value="{{csrf_token}}" />

{% if status_update_label %}

<input type="checkbox" name="status_update" value="1" checked /> {{status_update_label}}

"{{status_update_message}}"

<input type="hidden" name="status_update_message" value="{{status_update_message}}" />

{% endif %}
{% trans "You are logged in as " %} {{voter|safe}}

    <button class="btn btn-primary" type="submit" >{% trans "CAST this ballot" %}</button>
    <button class="btn btn-danger" type="button" onclick="document.location='/auth/logout';">{% trans "cancel" %}</button>

</form>

{% trans "You can cast as many ballots as you want.
Only the last one counts." %}

    {% blocktrans %}If you cancel now, your ballot will NOT be recorded.

    You can start the voting process over again, of course.{% endblocktrans %}

  {% else %}

  {% trans "voting has stopped, sorry." %}

  {% endif %}
{% else %}

  {% trans "voting has not yet begun, sorry." %}

{% endif %}

{% if not election.voting_has_started or election.voting_has_stopped %}

        {% trans "Visit"  %}   {{election.name}}  {% trans "for more info." %}

{% endif %}


text:
package org.sisioh.aws4s.sqs.model

import com.amazonaws.services.sqs.model.BatchResultErrorEntry
import org.sisioh.aws4s.PimpedType

object BatchResultErrorEntryFactory {

  def create(): BatchResultErrorEntry = new BatchResultErrorEntry()

}

class RichBatchResultErrorEntry(val underlying: BatchResultErrorEntry)
    extends AnyVal with PimpedType[BatchResultErrorEntry] {

  def idOpt: Option[String] = Option(underlying.getId)

  def idOpt_=(value: Option[String]): Unit =
    underlying.setId(value.orNull)

  def withIdOpt(value: Option[String]): BatchResultErrorEntry =
    underlying.withId(value.orNull)

  // --

  def senderFaultOpt: Option[Boolean] = Option(underlying.getSenderFault)

  def senderFaultOpt_=(value: Option[Boolean]): Unit =
    underlying.setSenderFault(value.map(_.asInstanceOf[java.lang.Boolean]).orNull)

  def withSenderFaultOpt(value: Option[Boolean]): BatchResultErrorEntry =
    underlying.withSenderFault(value.map(_.asInstanceOf[java.lang.Boolean]).orNull)

  // ---

  def codeOpt: Option[String] = Option(underlying.getCode)

  def codeOpt_=(value: Option[String]): Unit =
    underlying.setCode(value.orNull)

  def withCodeOpt(value: Option[String]): BatchResultErrorEntry =
    underlying.withCode(value.orNull)

  // ---

  def messageOpt: Option[String] = Option(underlying.getMessage)

  def messageOpt_=(value: Option[String]): Unit =
    underlying.withMessage(value.orNull)

  def withMessageOpt(value: Option[String]): BatchResultErrorEntry =
    underlying.withMessage(value.orNull)
}


text:
using namespace std;

int main(int argc, char* argv[])
{
   ossimTimer::instance()->setStartTick();

   ossimInit::instance()->initialize(argc, argv);

   ossimTimer::Timer_t t1 = ossimTimer::instance()->tick();

   cout << "elapsed time after initialize(ms): "
        << std::setiosflags(ios::fixed)
        << std::setprecision(3)
        << ossimTimer::instance()->time_s() << "\n";

   if (argc < 2)
   {
      cout << argv[0] << "<image_file> <optional_output_file>"
           << "\nOpens up single image chain and dumps the state to keyword"
           << " list." << endl;
      return 0;
   }

   ossimRefPtr<ossimSingleImageChain> sic1 = new ossimSingleImageChain();
   if ( sic1->open( ossimFilename(argv[1]) ) )
   {
      cout << "Opened: " << argv[1] << endl;

      ossimRefPtr<ossimPiecewiseRemapper> pwr = new ossimPiecewiseRemapper();

      // Add to the end of the chain. So it's image_handler->piecewise_remapper.
      sic1->addFirst( pwr.get() );

      ossimKeywordlist kwl;
      std::string key;
      std::string val;

      key = "number_bands";
      val = "1";
      kwl.addPair(key, val);

      key = "remap_type";
      val = "linear_native";
      kwl.addPair(key, val);

      // ((<min_in> <max_in> <min_out> <max_out>),(<min_in> <max_in> <min_out> <max_out>))
      key = "band0.remap0";
      val = "((0, 127, 0, 127), (128, 255, 128, 382))";
      kwl.addPair(key, val);
      key = "band0.remap1";
      val = "((0, 382, 0, 255))";
      kwl.addPair(key, val);

      key = "scalar_type";
      val = "OSSIM_UINT8";
      kwl.addPair(key, val);

      key = "type";
      val = "ossimPiecewiseRemapper";
      kwl.addPair(key, val);

      cout << "kwl:\n" << kwl << "\n";

      pwr->loadState( kwl, 0 );
      // pwr->initialize();

      // sic1->addScalarRemapper();
      sic1->addCache();

      sic1->initialize();

      // Set up chain:
      if ( sic1->getImageHandler()->getNumberOfOutputBands() == 4 )
      {
         // Just guessing...
         // sic1->setThreeBandReverseFlag(true);
      }

      // Always have resampler cache.
      // sic1->setAddResamplerCacheFlag(true);

      // Histogram:
      // sic1->setAddHistogramFlag(true);

      // sic1->createRenderedChain();

      kwl.clear();
      sic1->saveState(kwl, 0);

      cout << "sic1 state: " << kwl << endl;
   }

   if (argc == 3)
   {
      // Write image:
      ossimRefPtr<ossimImageFileWriter> writer = new ossimTiffWriter();
      if ( writer->open( ossimFilename(argv[2]) ) )
      {
         cout << "Outputting file: " << ossimFilename(argv[2]) << endl;

         // Add a listener to get percent complete.
         ossimStdOutProgress prog(0, true);
         writer->addListener(&prog);

         writer->connectMyInputTo(0, sic1.get());
         writer->execute();
         ossimTimer::Timer_t t2 = ossimTimer::instance()->tick();
         cout << "elapsed time after write(ms): "
              << std::setiosflags(ios::fixed)
              << std::setprecision(3)
              << ossimTimer::instance()->time_s() << "\n";

         cout << "write time minus initialize: "
              << std::setiosflags(ios::fixed)
              << std::setprecision(3)
              << ossimTimer::instance()->delta_s(t1, t2) << "\n";
      }
   }

   return 0;
}

#if 0
      // Histogram stretch:
      if ( sic1->openHistogram(ossimHistogramRemapper::LINEAR_AUTO_MIN_MAX) == false )
      {
         cout << "Could not do histogram stretch!" << endl;
      }

      if (argc == 3)
      {
         // Write image:
         ossimRefPtr<ossimImageFileWriter> writer = new ossimTiffWriter();
         if ( writer->open( ossimFilename(argv[2]) ) )
         {
            cout << "Outputting file: " << ossimFilename(argv[2]) << endl;

            // Add a listener to get percent complete.
            ossimStdOutProgress prog(0, true);
            writer->addListener(&prog);

            writer->connectMyInputTo(0, sic1.get());
            writer->execute();
            ossimTimer::Timer_t t2 = ossimTimer::instance()->tick();
            cout << "elapsed time after write(ms): "
                 << std::setiosflags(ios::fixed)
                 << std::setprecision(3)
                 << ossimTimer::instance()->time_s() << "\n";

            cout << "write time minus initialize: "
                 << std::setiosflags(ios::fixed)
                 << std::setprecision(3)
                 << ossimTimer::instance()->delta_s(t1, t2) << "\n";
         }
      }
#endif

#if 0
      ossimRefPtr<ossimImageGeometry> geom = sic1->getImageGeometry();
      if (geom.valid())
      {
         geom->print(cout);
      }

      // Test the load state.
      // ossimKeywordlist kwl;
      kwl.clear();
      sic1->saveState(kwl, 0);

      ossimSingleImageChain* sic2 = new ossimSingleImageChain();
      sic2->loadState(kwl, 0);

      kwl.clear();
      sic2->saveState(kwl, 0);

      cout << "\n\nSingle image chain from load state kwl\n" << kwl;
   }

#endif

#if 0

   // Create a normal chain.
   sic1 = new ossimSingleImageChain(true,  // addHistogramFlag
                                    true,  // addResamplerCacheFlag
                                    true,  // addChainCacheFlag
                                    false, // remapToEightBitFlag
                                    false, // threeBandFlag
                                    false); // threeBandReverseFlag

   if ( sic1->open( ossimFilename(argv[1]) ) )
   {
      sic1->createRenderedChain();
      ossimKeywordlist kwl;
      sic1->saveState(kwl, 0);
      cout << "\n\nNormal single image chain kwl\n" << kwl;
   }

   // Create a stripped down chain.
   sic1 = new ossimSingleImageChain();
   if ( sic1->open( ossimFilename(argv[1]) ) )
   {
      sic1->createRenderedChain();
      ossimKeywordlist kwl;
      sic1->saveState(kwl, 0);
      cout << "\n\nSingle image chain stripped down kwl\n" << kwl;
   }

   // Create a rgb reversed chain.
   sic1 = new ossimSingleImageChain();
   if ( sic1->open( ossimFilename(argv[1]) ) )
   {
      sic1->setThreeBandReverseFlag(true);
      sic1->createRenderedChain();
      ossimKeywordlist kwl;
      sic1->saveState(kwl, 0);
      cout << "\n\nSingle image chain rgb reversed kwl\n" << kwl;
   }

   cout << "constness test:\n";
   ossimRefPtr<const ossimSingleImageChain> consSic = sic1.get();
   ossimRefPtr<const ossimImageHandler> ihConst =  consSic->getImageHandler().get();
   cout << "image handler bands: " << ihConst->getNumberOfOutputBands() << endl;

   return 0;
}
#endif


text:
require 'test_helper'

class ViewIncrementingTest < ActionController::IntegrationTest
  fixtures :all

  test "view incrementing" do
    thread = wasabbi_threads(:norms_thread)

    [
      {},
      {:referer => "http://asdfsdfdsf.googlebot.com"},
      {:referer => "httpasdfsdfdsf.googlebot.com"},
      {:referer => '#$#@#$@**(&*&!**&!#@*(!@()'},
    ].each do |hash|
      assert_difference('WasabbiThread.find(thread.id).views') do
        get wasabbi_thread_path(thread), nil, hash
        assert_response :success
      end
    end
  end

  test "view does not increment" do
    thread = wasabbi_threads(:norms_thread)

    [
      wasabbi_thread_path(thread),
      edit_wasabbi_thread_path(thread),
      new_wasabbi_thread_path(:wasabbi_thread => {:forum_id => thread.forum.id}),
    ].each do |ref|
      assert_no_difference('WasabbiThread.find(thread.id).views') do
        get wasabbi_thread_path(thread), nil, :referer => ref
        assert_response :success
      end
    end
  end
end


text:
package com.leoz.bz.zthumb;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

public class ZSrvCacheFile extends ZSrvCache {

	private static final String TAG = "[z::remote] ZSrvCacheFile"; /// TODO: FIX ME

	private static String mDir;
	private static final String SEP = "/";
	private static Context mContext;

	ZSrvCacheFile() {
		mDir = "";
	}

	public static void setContext(Context c) {
		mContext = c;
		if (mContext != null) {
			mDir = mContext.getCacheDir().getAbsolutePath();
		}
    	Log.v(TAG, "setContext: cache dir is " + mDir); /// TODO: FIX ME
	}

	@Override
	public Bitmap getImage(final String url, final int size) {

    	Log.v(TAG, "getImage for size: " + size + " url " + url); /// TODO: FIX ME

    	String file = generateUrl(url, size);

    	Log.v(TAG, "getImage cache file: " + file); /// TODO: FIX ME

		return readCacheFile(file);
	}

	@Override
	public void putImage(final String url, final int size, Bitmap b) {

    	Log.v(TAG, "putImage for size: " + size + " url " + url); /// TODO: FIX ME

    	String file = generateUrl(url, size);

    	Log.v(TAG, "putImage cache file: " + file); /// TODO: FIX ME

    	generateCacheSubdir(size);

    	writeCacheFile(file, b);
	}

	@Override
	public void clear() {

    	Log.v(TAG, "clear"); /// TODO: FIX ME

    	try {

	        File dir = mContext.getCacheDir();

	        if (dir != null && dir.isDirectory()) {
	            deleteDir(dir);
	        }
	    }
	    catch (Exception e) {

	        Log.e(TAG, "clear: Error", e); /// TODO: FIX ME

	        e.printStackTrace();
	    }
	}

	private static boolean deleteDir(File dir) {

    	Log.v(TAG, "deleteDir"); /// TODO: FIX ME

	    if (dir != null && dir.isDirectory()) {

	    	Log.v(TAG, "deleteDir: deleting " + dir.getName()); /// TODO: FIX ME

	    	String[] children = dir.list();

	        for (int i = 0; i < children.length; i++) {

	            boolean success = deleteDir(new File(dir, children[i]));

	            if (!success) {
	                return false;
	            }
	        }
	    }

	    return dir.delete();
	}

	private void generateCacheSubdir(final int size) {

    	Log.v(TAG, "generateCacheSubdir for size: " + size); /// TODO: FIX ME

    	String dir = mDir + SEP + String.valueOf(size);

		File f = new File (dir);

		if (!f.exists()) {
			f.mkdirs();
	    	Log.v(TAG, "generateCacheSubdir generated: " + dir); /// TODO: FIX ME
		}
		else {
	    	Log.v(TAG, "generateCacheSubdir exists: " + dir); /// TODO: FIX ME
		}
	}

	private void writeCacheFile(final String url, Bitmap bmp) {

    	Log.v(TAG, "writeCacheFile: " + url); /// TODO: FIX ME

        File file = new File(url);

        if (file.exists()) {
	    	Log.v(TAG, "writeCacheFile: file exists"); /// TODO: FIX ME
        }
        else {

	    	Log.v(TAG, "writeCacheFile: file does not exist"); /// TODO: FIX ME

	        try {

		        if (file.createNewFile()) {

		        	Log.v(TAG, "writeCacheFile - file created: " + url); /// TODO: FIX ME

			        // Write to file
			        FileOutputStream os = new FileOutputStream(file);
			        bmp.compress(Bitmap.CompressFormat.PNG, 100, os);
			        os.close();
		        }
		        else {
			        Log.e(TAG, "writeCacheFile: Error creating file - file existed"); /// TODO: FIX ME
		        }
		    }
		    catch (IOException e) {
		        Log.e(TAG, "writeCacheFile: Error writing file", e); /// TODO: FIX ME
				e.printStackTrace();
		    }
		    catch (Exception e) {
		        Log.e(TAG, "writeCacheFile: Error", e); /// TODO: FIX ME
		        e.printStackTrace();
		    }
        }
	}

	private Bitmap readCacheFile(final String url) {

    	Log.v(TAG, "readCacheFile: " + url); /// TODO: FIX ME

		Bitmap bmp = null;

        File file = new File(url);

        if (file.exists()) {

	    	Log.v(TAG, "readCacheFile: file exists"); /// TODO: FIX ME

		    try {
		    	FileInputStream is = new FileInputStream(url);
		    	bmp = BitmapFactory.decodeStream(is, null, null);
		        is.close();
		    }
			catch (MalformedURLException e) {
		        Log.e(TAG, "readCacheFile: wrong URL", e); /// TODO: FIX ME
				e.printStackTrace();
			}
			catch (IOException e) {
		        Log.e(TAG, "readCacheFile: Error", e); /// TODO: FIX ME
				e.printStackTrace();
			}
		}
		else {
	    	Log.v(TAG, "readCacheFile: file does not exist"); /// TODO: FIX ME
		}

	    return bmp;
	}

	private String generateUrl(final String url, final int size) {
    	return mDir + SEP + String.valueOf(size) + SEP + generateFileName(url);
	}

	private static String generateFileName(String url) {
        // replace all special URI characters with a single + symbol
        return url.replaceAll("[.:/,%?&=]", "+").replaceAll("[+]+", "+");
    }
}


text:
/*
	´´½¨ÈÕÆÚ£º	2012/11/05 15:09:48
	×÷Õߣº			daviyang35@gmail.com
	ÃèÊö£º	FlashUI
*/
#ifndef __UIFLASH_H__
#define __UIFLASH_H__
#pragma once

// \Utils\Flash11.tlb ΪFlash11½Ó¿ÚÎļþ£¬²¿·Ö·½·¨ÔڵͰ汾²»´æÔÚ£¬Ê¹ÓÃÐè×¢Òâ
// #import "PROGID:ShockwaveFlash.ShockwaveFlash"  \
//      raw_interfaces_only,       /* Don't add raw_ to method names */ \
//  	named_guids,           /* Named guids and declspecs */    \
//  	rename("IDispatchEx","IMyDispatchEx")	/* fix conflicting with IDispatchEx ant dispex.h */
// using namespace ShockwaveFlashObjects;
#include "Utils/FlashEventHandler.h"
#include "Utils/flash11.tlh"

class CActiveXCtrl;

namespace DuiLib
{
	class UILIB_API CFlashUI
		: public CActiveXUI
	//	, public IOleInPlaceSiteWindowless // ͸Ã÷ģʽ»æͼ£¬ÐèҪʵÏÖÕâ¸ö½Ó¿Ú
		, public _IShockwaveFlashEvents
		, public ITranslateAccelerator
	{
	public:

		CFlashUI(void);
		~CFlashUI(void);

		void SetFlashEventHandler(CFlashEventHandler* pHandler);
		virtual bool DoCreateControl();
		IShockwaveFlash* m_pFlash;

	private:
		virtual LPCTSTR GetClass() const;
		virtual LPVOID GetInterface( LPCTSTR pstrName );

		virtual HRESULT STDMETHODCALLTYPE GetTypeInfoCount( __RPC__out UINT *pctinfo );
		virtual HRESULT STDMETHODCALLTYPE GetTypeInfo( UINT iTInfo, LCID lcid, __RPC__deref_out_opt ITypeInfo **ppTInfo );
		virtual HRESULT STDMETHODCALLTYPE GetIDsOfNames( __RPC__in REFIID riid, __RPC__in_ecount_full(cNames ) LPOLESTR *rgszNames, UINT cNames, LCID lcid, __RPC__out_ecount_full(cNames) DISPID *rgDispId);
		virtual HRESULT STDMETHODCALLTYPE Invoke( DISPID dispIdMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS *pDispParams, VARIANT *pVarResult, EXCEPINFO *pExcepInfo, UINT *puArgErr );

		virtual HRESULT STDMETHODCALLTYPE QueryInterface( REFIID riid, void **ppvObject );
		virtual ULONG STDMETHODCALLTYPE AddRef( void );
		virtual ULONG STDMETHODCALLTYPE Release( void );

		HRESULT OnReadyStateChange (long newState);
		HRESULT OnProgress(long percentDone );
		HRESULT FSCommand (_bstr_t command, _bstr_t args);
		HRESULT FlashCall (_bstr_t request );

		virtual void ReleaseControl();
		HRESULT RegisterEventHandler(BOOL inAdvise);

		// ITranslateAccelerator
		// DuilibÏûÏ¢·Ö·¢¸øWebBrowser
		virtual LRESULT TranslateAccelerator( MSG *pMsg );

	private:
		LONG m_dwRef;
		DWORD m_dwCookie;
		CFlashEventHandler* m_pFlashEventHandler;
	};
}

#endif // __UIFLASH_H__


text:
<?xml version='1.0' encoding='UTF-8'?>
<resources>
    <!--翻译start-->
    <string name="pg_sdk_edit_download">免费下载</string>
    <string name="pg_sdk_edit_photo_edit">编辑</string>
    <string name="pg_sdk_edit_quit">取消</string>
    <string name="pg_sdk_edit_photo_save_my_album">照片已保存到我的相册中</string>
    <string name="pg_sdk_edit_tint_class">偏色</string>
    <string name="pg_sdk_edit_tint_green">青色</string>
    <string name="pg_sdk_edit_tint_red">洋红</string>
    <string name="pg_sdk_edit_tint_yellow">黄色</string>
    <string name="pg_sdk_edit_tint_shadow_color">阴影</string>
    <string name="pg_sdk_edit_tint_middle_color">中间调</string>
    <string name="pg_sdk_edit_tint_high_light_color">高光</string>
    <string name="pg_sdk_edit_face_art_none">无特效</string>
    <string name="pg_sdk_edit_face_art_sweet">甜美可人</string>
    <string name="pg_sdk_edit_face_art_custom_curve">清新丽人</string>
    <string name="pg_sdk_edit_face_art_light_color_sweet">甜蜜</string>
    <string name="pg_sdk_edit_face_art_skin_plus_lab">香艳红唇</string>
    <string name="pg_sdk_edit_face_art_skin_plus_sunshine">暖暖阳光</string>
    <string name="pg_sdk_edit_face_art_light_color_lighting">阳光灿烂</string>
    <string name="pg_sdk_edit_face_art_skin_plus_red_clear">红润</string>
    <string name="pg_sdk_edit_face_art_light_color_sweet_color_balance">唯美</string>
    <string name="pg_sdk_edit_face_art_light_color_low_green">淡雅</string>
    <string name="pg_sdk_edit_face_art_light_color_color_blue">清凉</string>
    <string name="pg_sdk_edit_face_art_skin_plus_bw">黑白</string>
    <string name="pg_sdk_edit_face_portrait_skin">美肤</string>
    <string name="pg_sdk_edit_face_portrait_face_lift">塑颜</string>
    <string name="pg_sdk_edit_face_portrait_art">艺术</string>
    <string name="pg_sdk_edit_face_portrait_skin_strong">磨皮</string>
    <string name="pg_sdk_edit_face_portrait_skin_white_level">美白</string>
    <string name="pg_sdk_edit_face_portrait_skin_skin_color">肤色</string>
    <string name="pg_sdk_edit_face_portrait_face_lift_moulding">塑形</string>
    <string name="pg_sdk_edit_face_portrait_face_lift_eye">大眼</string>
    <string name="pg_sdk_edit_face_portrait_face_lift_edge">瘦脸</string>
    <string name="pg_sdk_edit_lighting_class">光影</string>
    <string name="pg_sdk_edit_frame_class">边框</string>
    <string name="pg_sdk_edit_color_hue">色相</string>
    <string name="pg_sdk_edit_color_light">明亮度</string>
    <string name="pg_sdk_edit_face_class">人像</string>
    <string name="pg_sdk_edit_face_discriminate">面部识别</string>
    <string name="pg_sdk_edit_face_feature">面部特征定位</string>
    <string name="pg_sdk_edit_face_checking">人脸检测中...</string>
    <string name="pg_sdk_edit_face_move_three_feature_point">请拖动照片上的三个特征点分别定位于左眼、右眼和嘴巴</string>
    <string name="pg_sdk_edit_face_plus_plus_support">(由Face++提供技术支持)</string>
    <string name="pg_sdk_edit_lightzone_class">调整</string>
    <string name="pg_sdk_edit_lightzone_hue">色调</string>
    <string name="pg_sdk_edit_lightzone_vibrance">鲜艳度</string>
    <string name="pg_sdk_edit_lightzone_vignette_strong">暗角</string>
    <string name="pg_sdk_edit_lightzone_center_strong">中心亮</string>
    <string name="pg_sdk_edit_lightzone_enhance">层次调节</string>
    <string name="pg_sdk_edit_lightzone_skin">人像</string>
    <string name="pg_sdk_edit_tool_class">工具箱</string>
    <string name="pg_sdk_edit_hsl_class">色彩</string>
    <string name="pg_sdk_edit_hsl_red">红</string>
    <string name="pg_sdk_edit_hsl_orange">橙</string>
    <string name="pg_sdk_edit_hsl_yellow">黄</string>
    <string name="pg_sdk_edit_hsl_green">绿</string>
    <string name="pg_sdk_edit_hsl_cyan">浅绿</string>
    <string name="pg_sdk_edit_hsl_blue">蓝</string>
    <string name="pg_sdk_edit_hsl_purple">紫</string>
    <string name="pg_sdk_edit_hsl_magenta">洋红</string>
    <!--翻译end-->
    <string name="pg_sdk_edit">编辑</string>
    <string name="pg_sdk_edit_first_show_fail">图片加载失败</string>
    <string name="pg_sdk_edit_effect_scale_size">由于特效制作的限制,你编辑后的特效照片将小于你的原片尺寸</string>

    <string name="pg_sdk_edit_left_eye">左眼</string>
    <string name="pg_sdk_edit_right_eye">右眼</string>
    <string name="pg_sdk_edit_mouth">嘴巴</string>

    <string name="pg_sdk_edit_stop_save">停止保存</string>

    <string name="pg_sdk_edit_use">应用</string>
    <string name="pg_sdk_edit_return">返回</string>
    <string name="pg_sdk_edit_save">保存</string>
    <string name="pg_sdk_edit_ok">确定</string>
    <string name="pg_sdk_edit_tool_crop">裁剪</string>
    <string name="pg_sdk_edit_adjust_class">调整</string>
    <string name="pg_sdk_edit_texture_class">纹理</string>
    <string name="pg_sdk_edit_tool_rotate">旋转</string>
    <string name="pg_sdk_edit_tiltshift_class">虚化</string>
    <string name="pg_sdk_edit_effect_class">特效</string>

    <string name="pg_sdk_edit_tiltshift_round">圆形虚化</string>
    <string name="pg_sdk_edit_tiltshift_vertical">纵向虚化</string>
    <string name="pg_sdk_edit_tiltshift_horizontal">横向虚化</string>

    <string name="pg_sdk_edit_crop_crop618_vertical">竖黄金</string>
    <string name="pg_sdk_edit_crop_crop618_horizontal">横黄金</string>
    <string name="pg_sdk_edit_crop_cropFree">自由</string>
    <string name="pg_sdk_edit_crop_cropHorizontal">横</string>
    <string name="pg_sdk_edit_crop_cropVertical">竖</string>
    <string name="pg_sdk_edit_about">关于</string>

    <string name="pg_sdk_edit_lightzone_sharpen">清晰度</string>
    <string name="pg_sdk_edit_lightzone_exposure">曝光</string>
    <string name="pg_sdk_edit_lightzone_contrast">对比度</string>
    <string name="pg_sdk_edit_lightzone_highlight">高光</string>
    <string name="pg_sdk_edit_lightzone_shadow">阴影</string>
    <string name="pg_sdk_edit_lightzone_saturation">饱和度</string>
    <string name="pg_sdk_edit_lightzone_temperature">色温</string>

    <string name="pg_sdk_edit_strength">强度</string>
    <string name="pg_sdk_edit_range">范围</string>

    <string name="pg_sdk_edit_quit_edit">是否放弃当前编辑的图片?</string>
    <string name="pg_sdk_edit_replace_effect">特效选择</string>

    <string name="pg_sdk_edit_no_free_space">抱歉,SD卡空间不足</string>
    <string name="pg_sdk_edit_no_storage">抱歉,未检测到SD卡,请插入SD卡以继续使用</string>
    <string name="pg_sdk_edit_make_photo_fail">保存图片失败</string>

    <string name="pg_sdk_edit_org_photo">点此可回到原始照片</string>
    <string name="pg_sdk_edit_about_desc">Camera360是一款风靡全球的手机拍照应用,超过200款免费顶级特效、十余款创新相机模式及强大的编辑功能,瞬间让你变身摄影达人。</string>

</resources>


text:
package com.yakami.light.bean;

import com.yakami.light.bean.base.Entity;

/**
 * Created by Yakami on 2016/6/6, enjoying it!
 */

public class RawDiscRank extends Entity {

    private int arnk;
    private int curk;
    private long release;
    private boolean amzver;
    private long acot;
    private String title;
    private int type;
    private int prrk;
    private long stot;
    private int rank1;
    private int rank2;
    private int rank3;
    private long atot;
    private int cubk;
    private String sname;
    private int cupt;
    private String asin;
    private int id;
    private int rank4;
    private int sday;
    private int rank5;

    public int getArnk() {
        return arnk;
    }

    public void setArnk(int arnk) {
        this.arnk = arnk;
    }

    public int getCurk() {
        return curk;
    }

    public void setCurk(int curk) {
        this.curk = curk;
    }

    public long getRelease() {
        return release;
    }

    public void setRelease(long release) {
        this.release = release;
    }

    public boolean isAmzver() {
        return amzver;
    }

    public void setAmzver(boolean amzver) {
        this.amzver = amzver;
    }

    public long getAcot() {
        return acot;
    }

    public void setAcot(long acot) {
        this.acot = acot;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public int getType() {
        return type;
    }

    public void setType(int type) {
        this.type = type;
    }

    public int getPrrk() {
        return prrk;
    }

    public void setPrrk(int prrk) {
        this.prrk = prrk;
    }

    public long getStot() {
        return stot;
    }

    public void setStot(long stot) {
        this.stot = stot;
    }

    public int getRank1() {
        return rank1;
    }

    public void setRank1(int rank1) {
        this.rank1 = rank1;
    }

    public int getRank2() {
        return rank2;
    }

    public void setRank2(int rank2) {
        this.rank2 = rank2;
    }

    public int getRank3() {
        return rank3;
    }

    public void setRank3(int rank3) {
        this.rank3 = rank3;
    }

    public long getAtot() {
        return atot;
    }

    public void setAtot(long atot) {
        this.atot = atot;
    }

    public int getCubk() {
        return cubk;
    }

    public void setCubk(int cubk) {
        this.cubk = cubk;
    }

    public String getsName() {
        return sname;
    }

    public void setsName(String sName) {
        this.sname = sName;
    }

    public int getCupt() {
        return cupt;
    }

    public void setCupt(int cupt) {
        this.cupt = cupt;
    }

    public String getAsin() {
        return asin;
    }

    public void setAsin(String asin) {
        this.asin = asin;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getRank4() {
        return rank4;
    }

    public void setRank4(int rank4) {
        this.rank4 = rank4;
    }

    public int getSday() {
        return sday;
    }

    public void setSday(int sday) {
        this.sday = sday;
    }

    public int getRank5() {
        return rank5;
    }

    public void setRank5(int rank5) {
        this.rank5 = rank5;
    }
}


text:
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/compiler_specific.h"
#include "chrome/browser/chromeos/login/screens/user_selection_screen.h"
#include "chrome/browser/chromeos/login/users/fake_user_manager.h"
#include "chrome/browser/chromeos/login/users/multi_profile_user_controller.h"
#include "chrome/browser/chromeos/login/users/multi_profile_user_controller_delegate.h"
#include "chrome/browser/chromeos/login/users/scoped_user_manager_enabler.h"
#include "chrome/browser/signin/screenlock_bridge.h"
#include "chrome/test/base/testing_browser_process.h"
#include "chrome/test/base/testing_profile_manager.h"
#include "components/user_manager/user.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace {

const size_t kMaxUsers = 18; // same as in user_selection_screen.cc
const char* kOwner = "owner@gmail.com";
const char* kUsersPublic[] = {"public0@gmail.com", "public1@gmail.com"};
const char* kUsers[] = {
    "a0@gmail.com", "a1@gmail.com", "a2@gmail.com", "a3@gmail.com",
    "a4@gmail.com", "a5@gmail.com", "a6@gmail.com", "a7@gmail.com",
    "a8@gmail.com", "a9@gmail.com", "a10@gmail.com", "a11@gmail.com",
    "a12@gmail.com", "a13@gmail.com", "a14@gmail.com", "a15@gmail.com",
    "a16@gmail.com", "a17@gmail.com", kOwner, "a18@gmail.com"};

}  // namespace

namespace chromeos {

class SigninPrepareUserListTest
    : public testing::Test,
      public MultiProfileUserControllerDelegate {
 public:
  SigninPrepareUserListTest()
      : fake_user_manager_(new FakeUserManager()),
        user_manager_enabler_(fake_user_manager_) {
  }

  virtual ~SigninPrepareUserListTest() {
  }

  virtual void SetUp() override {
    profile_manager_.reset(
        new TestingProfileManager(TestingBrowserProcess::GetGlobal()));
    ASSERT_TRUE(profile_manager_->SetUp());
    controller_.reset(new MultiProfileUserController(
        this, TestingBrowserProcess::GetGlobal()->local_state()));
    fake_user_manager_->set_multi_profile_user_controller(controller_.get());

    for (size_t i = 0; i < arraysize(kUsersPublic); ++i)
      fake_user_manager_->AddPublicAccountUser(kUsersPublic[i]);

    for (size_t i = 0; i < arraysize(kUsers); ++i)
      fake_user_manager_->AddUser(kUsers[i]);

    fake_user_manager_->set_owner_email(kOwner);
  }

  virtual void TearDown() override {
    controller_.reset();
    profile_manager_.reset();
  }

  // MultiProfileUserControllerDelegate overrides:
  virtual void OnUserNotAllowed(const std::string& user_email) override {
  }

  FakeUserManager* fake_user_manager_;
  ScopedUserManagerEnabler user_manager_enabler_;
  scoped_ptr<TestingProfileManager> profile_manager_;
  std::map<std::string,
           ScreenlockBridge::LockHandler::AuthType> user_auth_type_map;
  scoped_ptr<MultiProfileUserController> controller_;

  DISALLOW_COPY_AND_ASSIGN(SigninPrepareUserListTest);
};

TEST_F(SigninPrepareUserListTest, AlwaysKeepOwnerInList) {
  EXPECT_LT(kMaxUsers, fake_user_manager_->GetUsers().size());
  user_manager::UserList users_to_send =
      UserSelectionScreen::PrepareUserListForSending(
          fake_user_manager_->GetUsers(), kOwner, true /* is signin to add */);

  EXPECT_EQ(kMaxUsers, users_to_send.size());
  EXPECT_EQ(kOwner, users_to_send.back()->email());

  fake_user_manager_->RemoveUserFromList("a16@gmail.com");
  fake_user_manager_->RemoveUserFromList("a17@gmail.com");
  users_to_send = UserSelectionScreen::PrepareUserListForSending(
      fake_user_manager_->GetUsers(),
      kOwner,
      true /* is signin to add */);

  EXPECT_EQ(kMaxUsers, users_to_send.size());
  EXPECT_EQ("a18@gmail.com", users_to_send.back()->email());
  EXPECT_EQ(kOwner, users_to_send[kMaxUsers-2]->email());
}

TEST_F(SigninPrepareUserListTest, PublicAccounts) {
  user_manager::UserList users_to_send =
      UserSelectionScreen::PrepareUserListForSending(
          fake_user_manager_->GetUsers(), kOwner, true /* is signin to add */);

  EXPECT_EQ(kMaxUsers, users_to_send.size());
  EXPECT_EQ("a0@gmail.com", users_to_send.front()->email());

  users_to_send = UserSelectionScreen::PrepareUserListForSending(
      fake_user_manager_->GetUsers(),
      kOwner,
      false /* is signin to add */);

  EXPECT_EQ(kMaxUsers, users_to_send.size());
  EXPECT_EQ("public0@gmail.com", users_to_send.front()->email());
}

}  // namespace chromeos


text:
select load_extension('./libredis_vtbl.so');

create virtual table basic_test using redis (localhost, basic,
    c0 varchar,
    c1 int,
    c2 float
);

insert into basic_test (c0, c1, c2) values ('hello', 1, 3.14159);

select * from basic_test;
select c0 from basic_test where c2 > 3;
select c1 from basic_test where c1 > 0 and c0 = 'hello' and c2 > 3.1;

delete from basic_test;
drop table basic_test;


text:
#ifndef HWMONDRIVER_H
#define HWMONDRIVER_H

#include "Driver.h"

class HwmonDriver : public PolledDriver {
public:
	HwmonDriver();
	~HwmonDriver();

	void readEvents(mxml_node_t *const root);

	void writeEvents(mxml_node_t *root) const;

	void start();

private:
	// Intentionally unimplemented
	HwmonDriver(const HwmonDriver &);
	HwmonDriver &operator=(const HwmonDriver &);
};

#endif // HWMONDRIVER_H


text:
/* patSpace - a homology finding algorithm that occurs mostly in
 * pattern space (as opposed to offset space). */
/* Copyright 1999-2003 Jim Kent.  All rights reserved. */
#include "common.h"
#include "portable.h"
#include "dnaseq.h"
#include "ooc.h"
#include "patSpace.h"

#define blockSize (256)

#define BIGONE	/* define this for 32 bit version. */

#ifdef BIGONE

#define maxBlockCount (2*230*1024 - 1)
#define psBits bits32
/* psBits is the size of an index word.  If 16 bits
 * patSpace will use less memory, but be limited to
 * 16 meg or less genome size. */

#else /* BIGONE */

#define maxBlockCount (64*1024 - 1)
#define psBits bits16
/* psBits is the size of an index word.  If 16 bits
 * patSpace will use less memory, but be limited to
 * 16 meg or less genome size. */

#endif /* BIGONE */

#define maxPatCount (1024*16)    /* Maximum allowed count for one pattern. */

struct blockPos
/* Structure that stores where in a BAC we are -
 * essentially an unpacked block index. */
    {
    bits16 bacIx;          /* Which bac. */
    bits16 seqIx;          /* Which subsequence in bac. */
    struct dnaSeq *seq; /* Pointer to subsequence. */
    int offset;         /* Start position of block within subsequence. */
    int size;           /* Size of block within subsequence. */
    };

struct patSpace
/* A pattern space - something that holds an index of all 10-mers in
 * genome. */
    {
    psBits **lists;                      /* A list for each 10-mer */
    psBits *listSizes;                   /* Size of list for each 10-mer */
    psBits *allocated;                   /* Storage space for all lists. */
    int    blocksUsed;			 /* Number of blocks used, <= maxBlockCount */
    int posBuf[maxBlockCount];           /* Histogram of hits to each block. */
    int hitBlocks[maxBlockCount];        /* Indexes of blocks with hits. */
    struct blockPos blockPos[maxBlockCount]; /* Relates block to sequence. */
    psBits maxPat;                       /* Max # of times pattern can occur
                                          * before it is ignored. */
    int minMatch;                        /* Minimum number of tile hits needed
                                          * to trigger a clump hit. */
    int maxGap;                          /* Max gap between tiles in a clump. */
    int seedSize;			 /* Size of alignment seed. */
    int seedSpaceSize;                    /* Number of possible seed values. */
    };

void freePatSpace(struct patSpace **pPatSpace)
/* Free up a pattern space. */
{
struct patSpace *ps = *pPatSpace;
if (ps != NULL)
    {
    freeMem(ps->allocated);
    freez(pPatSpace);
    }
}

void tooManyBlocks()
/* Complain about too many blocks and abort. */
{
errAbort("Too many blocks, can only handle %d\n", maxBlockCount);
}

static void fixBlockSize(struct blockPos *bp, int blockIx)
/* Update size field from rest of blockPos. */
{
struct dnaSeq *seq = bp->seq;
int size = seq->size - bp->offset;
if (size > blockSize)
	size = blockSize;
bp->size = size;
}

static struct patSpace *newPatSpace(int minMatch, int maxGap, int seedSize)
/* Return an empty pattern space. */
{
struct patSpace *ps;
int seedBitSize = seedSize*2;
int seedSpaceSize;

AllocVar(ps);
ps->seedSize = seedSize;
seedSpaceSize = ps->seedSpaceSize = (1<<seedBitSize);
ps->lists = needLargeZeroedMem(seedSpaceSize * sizeof(ps->lists[0]));
ps->listSizes = needLargeZeroedMem(seedSpaceSize * sizeof(ps->listSizes[0]));
ps->minMatch = minMatch;
ps->maxGap = maxGap;
return ps;
}

static void countPatSpace(struct patSpace *ps, struct dnaSeq *seq)
/* Add up number of times each pattern occurs in sequence into ps->listSizes. */
{
int size = seq->size;
int mask = ps->seedSpaceSize-1;
DNA *dna = seq->dna;
int i;
int bits = 0;
int bVal;
int ls;

for (i=0; i<ps->seedSize-1; ++i)
    {
    bVal = ntValNoN[(int)dna[i]];
    bits <<= 2;
    bits += bVal;
    }
for (i=ps->seedSize-1; i<size; ++i)
    {
    bVal = ntValNoN[(int)dna[i]];
    bits <<= 2;
    bits += bVal;
    bits &= mask;
    ls = ps->listSizes[bits];
    if (ls < maxPatCount)
        ps->listSizes[bits] = ls+1;
    }
}

static int allocPatSpaceLists(struct patSpace *ps)
/* Allocate pat space lists and set up list pointers.
 * Returns size of all lists. */
{
int oneCount;
int count = 0;
int i;
psBits *listSizes = ps->listSizes;
psBits **lists = ps->lists;
psBits *allocated;
psBits maxPat = ps->maxPat;
int size;
int usedCount = 0, overusedCount = 0;
int seedSpaceSize = ps->seedSpaceSize;

for (i=0; i<seedSpaceSize; ++i)
    {
    /* If pattern is too much used it's no good to us, ignore. */
    if ((oneCount = listSizes[i]) < maxPat)
        {
        count += oneCount;
        usedCount += 1;
        }
    else
        {
        overusedCount += 1;
        }
    }
ps->allocated = allocated = needLargeMem(count*sizeof(allocated[0]));
for (i=0; i<seedSpaceSize; ++i)
    {
    if ((size = listSizes[i]) < maxPat)
        {
        lists[i] = allocated;
        allocated += size;
        }
    }
return count;
}

static int addToPatSpace(struct patSpace *ps, int bacIx, int seqIx, struct dnaSeq *seq,int startBlock)
/* Add contents of one sequence to pattern space. Returns end block. */
{
int size = seq->size;
int mask = ps->seedSpaceSize-1;
DNA *dna = seq->dna;
int i;
int bits = 0;
int bVal;
int blockMod = blockSize;
int curCount;
psBits maxPat = ps->maxPat;
psBits *listSizes = ps->listSizes;
psBits **lists = ps->lists;
struct blockPos *bp = &ps->blockPos[startBlock];

bp->bacIx = bacIx;
bp->seqIx = seqIx;
bp->seq = seq;
bp->offset = 0;
fixBlockSize(bp, startBlock);
++bp;
for (i=0; i<ps->seedSize-1; ++i)
    {
    bVal = ntValNoN[(int)dna[i]];
    bits <<= 2;
    bits += bVal;
    }
for (i=ps->seedSize-1; i<size; ++i)
    {
    bVal = ntValNoN[(int)dna[i]];
    bits <<= 2;
    bits += bVal;
    bits &= mask;
    if ((curCount = listSizes[bits]) < maxPat)
        {
        listSizes[bits] = curCount+1;
        lists[bits][curCount] = startBlock;
        }
    if (--blockMod == 0)
        {
        if (++startBlock >= maxBlockCount)
	    tooManyBlocks();
        blockMod = blockSize;
	bp->bacIx = bacIx;
	bp->seqIx = seqIx;
	bp->seq = seq;
	bp->offset = i - (ps->seedSize-1) + 1;
	fixBlockSize(bp, startBlock);
	++bp;
        }
    }
for (i=0; i<ps->seedSize-1; ++i)
    {
    if (--blockMod == 0)
        {
        if (++startBlock >= maxBlockCount)
	    tooManyBlocks();
        blockMod = blockSize;
        }
    }
if (blockMod != blockSize)
    ++startBlock;
return startBlock;
}

struct patSpace *makePatSpace(
    struct dnaSeq **seqArray,       /* Array of sequence lists. */
    int seqArrayCount,              /* Size of above array. */
    int seedSize,	            /* Alignment seed size - 10 or 11. Must match oocFileName */
    char *oocFileName,              /* File with tiles to filter out, may be NULL. */
    int minMatch,                   /* Minimum # of matching tiles.  4 is good. */
    int maxGap                      /* Maximum gap size - 32k is good for
                                       cDNA (introns), 500 is good for DNA assembly. */
    )
/* Allocate a pattern space and fill from sequences.  (Each element of
   seqArray is a list of sequences. */
{
struct patSpace *ps = newPatSpace(minMatch, maxGap,seedSize);
int i;
int startIx = 0;
int total = 0;
struct dnaSeq *seq;
psBits maxPat;
psBits *listSizes;
int seedSpaceSize = ps->seedSpaceSize;

maxPat = ps->maxPat = maxPatCount;
for (i=0; i<seqArrayCount; ++i)
    {
    for (seq = seqArray[i]; seq != NULL; seq = seq->next)
        {
        total += seq->size;
        countPatSpace(ps, seq);
        }
    }

listSizes = ps->listSizes;

/* Scan through over-popular patterns and set their count to value
 * where they won't be added to pat space. */
oocMaskCounts(oocFileName, listSizes, ps->seedSize, maxPat);

/* Get rid of simple repeats as well. */
oocMaskSimpleRepeats(listSizes, ps->seedSize, maxPat);

allocPatSpaceLists(ps);

/* Zero out pattern counts that aren't oversubscribed. */
for (i=0; i<ps->seedSpaceSize; ++i)
    {
    if (listSizes[i] < maxPat)
        listSizes[i] = 0;
    }
for (i=0; i<seqArrayCount; ++i)
    {
	int j;
    for (seq = seqArray[i], j=0; seq != NULL; seq = seq->next, ++j)
        {
        startIx = addToPatSpace(ps, i, j, seq, startIx);
        if (startIx >= maxBlockCount)
	    tooManyBlocks();
        }
    }
ps->blocksUsed = startIx;

/* Zero local over-popular patterns. */
for (i=0; i<seedSpaceSize; ++i)
    {
    if (listSizes[i] >= maxPat)
        listSizes[i] = 0;
    }

return ps;
}

void bfFind(struct patSpace *ps, int block, struct blockPos *ret)
/* Find dna sequence and position within sequence that corresponds to block. */
{
assert(block >= 0 && block < maxBlockCount);
*ret = ps->blockPos[block];
}

static struct patClump *newClump(struct patSpace *ps, struct blockPos *first, struct blockPos *last)
/* Make new clump . */
{
struct dnaSeq *seq = first->seq;
int seqIx = first->seqIx;
int bacIx = first->bacIx;
int start = first->offset;
int end = last->offset+last->size;
int extraAtEnds = blockSize/2;
struct patClump *cl;

start -= extraAtEnds;
if (start < 0)
    start = 0;
end += extraAtEnds;
if (end >seq->size)
    end = seq->size;
AllocVar(cl);
cl->bacIx = bacIx;
cl->seqIx = seqIx;
cl->seq = seq;
cl->start = start;
cl->size = end-start;
return cl;
}

static struct patClump *clumpHits(struct patSpace *ps,
    int hitBlocks[], int hitCount, int posBuf[],
    DNA *dna, int dnaSize)
/* Clumps together hits and returns a list. */
{
/* Clump together hits. */
int block;
int i;
int maxGap = ps->maxGap;
struct blockPos first, cur, pre;
struct patClump *patClump = NULL, *cl;

bfFind(ps, hitBlocks[0], &first);
pre = first;
for (i=1; i<hitCount; ++i)
    {
    block = hitBlocks[i];
    bfFind(ps, block, &cur);
    if (cur.seq != pre.seq || cur.offset - (pre.offset + pre.size) > maxGap)
        {
        /* Write old clump and start new one. */
        cl = newClump(ps, &first, &pre);
        slAddHead(&patClump, cl);
        first = cur;
        }
    else
        {
        /* Extend old clump. */
        }
    pre = cur;
    }
/* Write hitOut last clump. */
cl = newClump(ps, &first, &pre);
slAddHead(&patClump, cl);
slReverse(&patClump);
return patClump;
}

struct patClump *patSpaceFindOne(struct patSpace *ps, DNA *dna, int dnaSize)
/* Find occurrences of DNA in patSpace. */
{
int lastStart = dnaSize - ps->seedSize;
int i,j;
int pat;
int hitBlockCount = 0;
int totalSigHits = 0;
DNA *tile = dna;
int blocksUsed = ps->blocksUsed;
int *posBuf = ps->posBuf;
int *hitBlocks = ps->hitBlocks;
int minMatch = ps->minMatch;

memset(ps->posBuf, 0, sizeof(ps->posBuf[0]) * blocksUsed);
for (i=0; i<=lastStart; i += ps->seedSize)
    {
    psBits *list;
    psBits count;

    pat = 0;
    for (j=0; j<ps->seedSize; ++j)
        {
        int bVal = ntValNoN[(int)tile[j]];
        pat <<= 2;
        pat += bVal;
        }
    list = ps->lists[pat];
    if ((count = ps->listSizes[pat]) > 0)
        {
        for (j=0; j<count; ++j)
            posBuf[list[j]] += 1;
        }
    tile += ps->seedSize;
    }

/* Scan through array that records counts of hits at positions. */
for (i=0; i<blocksUsed-1; ++i)
    {
    /* Save significant hits in a more compact array */
    int a = posBuf[i], b = posBuf[i+1];
    int sum = a + b;
    if (sum >= minMatch)
        {
        if (a > 0)
            {
            if (hitBlockCount == 0 || hitBlocks[hitBlockCount-1] != i)
                {
                hitBlocks[hitBlockCount++] = i;
                totalSigHits += a;
                }
            }
        if (b > 0)
            {
            hitBlocks[hitBlockCount++] = i+1;
            totalSigHits += b;
            }
        }
    }

/* Output data with significant hits. */
if (hitBlockCount > 0 && totalSigHits*ps->seedSize*8 > dnaSize)
    {
    return clumpHits(ps, hitBlocks, hitBlockCount, posBuf, dna,
        dnaSize);
    }
else
    return NULL;
}