text:
import { connect } from 'react-redux';
import _ from 'lodash'
import ChangesText from '../components/ChangesText';
import * as actions from '../actions/formActionCreators';

const idsToNames = (items, idsArray) => (
  items.filter((item => idsArray.includes(item.id))
  ).map(item => item.name).sort().join(", ")
)

const mapStateToProps = (state) => {
  const { categories, form, showChangesText } = state
  const { existingIds, checkedIds } = form
  const items = _.flatten(categories.map(category => category.items))
  const intersection = _.intersection(existingIds, checkedIds)

  return({
    added:    idsToNames(items, _.difference(checkedIds, intersection)),
    removed:  idsToNames(items, _.difference(existingIds, intersection)),
    showChangesText
  })
};

const mapDispatchToProps = (dispatch, ownProps) => {
  return {
    onToggleChangesTextClick: () => {
      dispatch(actions.toggleChangesText())
    }
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(ChangesText);

redpajama_set_name: RedPajamaGithub


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.wpi.first.wpilibj.TigerRobotics.AirCannon.Controls;

/**
 * Common Interface for various controls system layouts
 * @author Gus Michel
 */
public interface ControlMap {
    public double getThrottle();
    public double getTurn();
    public double getLeftThrottle();
    public double getRightThrottle();
    public boolean getFire();
    public void setStopSwitch();
    public void setTankSwitch();
}


text:
  * making AJAX requests using jQuery
  * having a server respond with different data-types (strings, JSON, partials)
  * writing AJAX requests in a modular, testable way.

## Summary

In this challenge, you'll be AJAX-ifying a working Sinatra app. By the end of today, your Hacker News clone will allow users to vote on posts, delete posts, create new posts, and sort all posts without ever refreshing the page.

To get started, download the skeleton, install your dependencies, and create and seed your database.

## Releases

### Release 0 : Voting

Press the vote button next to a post. You'll notice the page refreshes, and the points count of the post has increased. You'll also notice in your shotgun window that your server had to make 21 SQL queries when the page refreshed! Your job is to speed up the load time by using AJAX. If done correctly, the act of clicking a vote button will not cause the entire page to refresh, but instead only update the color of the button — while still updating the database.

Here's the basic flow of this particular AJAX request:

1. You should bind an event listener to any anchor tag of the vote-button class
2. To stop a client refresh from occuring, the provided callback function should prevent the default behavior of clicking a link.
3. It should then make an AJAX request to the server, hitting the get '/posts/:id/vote' route with the right id value.
4. The server should update the vote total of the given post in the database.
5. The server response should include everything the client (your JS callback function) needs to update the DOM..
6. The client, after being notified of a successful response by the server, should update the vote count and change the color of the given vote button to red.

You'll need to alter the get '/posts/:id/vote' route  and write some custom JavaScript and jQuery to get this working. Here's the basic syntax for an AJAX request using jQuery.

```javascript
  // $.ajax takes a hashmap of options as an argument.
  var ajaxRequest = $.ajax({
    // these two attributes determine which route in your controller will be called.
    url: "/foo",
    type: 'GET',
    // the 'data' attribute determines what data is sent to the server.
    // The server will be able to access these values using the params hash.
    // If the server only needs to know information passed in the URL, this attribute is not necessary.
    data: { bar: 'baz' }
  })

  // the .done function takes a callback, which will only be fired if the server responds
  // with a success status code. the callback will receive arguments corresponding to the
  // request object, status, and data sent from the server.
  ajaxRequest.done(someCallbackFunction)

  // like the .done function, the .fail function will fire off a callback if the server responds
  // with an error status code.
  ajaxRequest.fail(someOtherCallbackFunction)
```

What does the server need to know to update a given vote total? What does the client need to know to update the DOM? How does the client get access to data sent from the server, and vice versa? You'll need to figure this all out to make this functional.

### Release 1 : Points

Sure, a successful vote causes the upvote arrow to change color — but the point score of the post hasn't been updated! Your task in this release is to asynchronously update a post's points value on the page whenever someone clicks the vote button

In release 0, you were asked to send data from the server to the client that identified which vote button to update. You sent this data as an unformatted string. That is a viable solution when you have a single piece of information to transmit, but becomes untenable when you need to send more than one piece of information -- like a post ID and a vote total. For this release, you should send back a string formatted in JSON. Your code will look something like this:

```ruby
  get '/posts/:id/vote' do
    ##logic for adding a vote to a post.

    content_type :json
    { foo: 'bar', baz: 'qux' }.to_json
  end
```

The .done() callback will now have access to the data passed from the server, which can be accessed as a JavaScript hashmap.

### Release 2 : Deleting

Now that you've got voting up and running, you should make the "delete this post" link functional. Clicking the link should delete the associated post from the database and consequently remote the post from the DOM.

We've already created a skeleton route for you to use. You'll need to write the body of that route, an event listener, and callback functions to make this work.

### Release 3 : Creating

With deletion done, you're on to your hardest challenge yet — getting the creation form at the bottom of the page to work. Your first challenge will be to send the the right data to the server. Look into using jQuery's .serialize() function -- its a useful way to get data out of forms.

You've already had routes respond with an unformatted string and with a string formatted as JSON. For this release, you should have your server return a string formmated in HTML, a.k.a. a partial. You can then append the partial directly to the page.

### Release 4 : Are you sure everything works?

Great, you've created a new post! Does its vote button work? its delete link? Probably not. Get them working.

There are many ways to solve this problem. [jQuery's implementation of event delegation](https://learn.jquery.com/events/event-delegation/) may prove to be useful.

### Release 5 : Validations

Users can currently create posts with blank titles. You should prevent that from happening using ActiveRecord validations. If a post fails to create, use the server must let the client know, and the client should let the user know by updating the DOM.

Servers provide an easy way for surfacing errors -- HTTP status codes. Codes in the 200's correspond to successful requests, while  codes in the 400's and 500's correspond to errors. The $.ajax() function will decide which callback to fire based on the error code returned by the server. You can set error codes like this in Sinatra:

```ruby
  post '/posts' do
    #logic for attempting to save a post.
    if @post.save
      status 200
      erb :_post, :layout => false
    else
      status 422
    end
  end
```

### Release 6 : Sorting

Now its time to make the links at the top of the page work.

  * When a user clicks 'new', the page should display a list of posts sorted by creation date.
  * When a user clicks 'comments', the page should display a list of posts sorted by comment count.
  * When a user clicks 'popular', the page should display a list of posts sorted by point count.

All of this should be handled by AJAX requests. It's up to you how to architect this system -- should there be different routes in the controller for each sorting strategy? one route that responds to different parameters? What should the return value of the routes be?

This data that needs to be sent back is likely too complex and large to be sent as HTML. Instead, the server should respond with a nested JSON object, and the client should parse that data out, turn it into HTML, and update the DOM.

### Release 7 : OOJS

Now that you've got your functionality working, you should attempt to organize your code in a modular and extendable way. A series of 40-line functions won't work! Separate your code out into the MVC structure:

  * There should be a single object responsible for talking to your DOM (e.g. the View)
  * There should be a single object responsible for making AJAX requests (e.g. the Server)
  * There should be a controller object responsible for managing the Server and View objects, as well as binding event listeners.

Handling $.ajax .done() and .fail() callbacks can be difficult in MVC, as they are tightly coupled to the request itself. To get around that, have your model return the request object to be modified in your controller. like this:

```javascript
  Server.prototype = {
    makeDeleteRequest: function(opts) {
      var requestObect = $.ajax({
        //the details of the request go here.
        })

      return requestObject
    }
  }

  Controller.prototype = {
    deletePost: function() {
     // the controller would be passed a server object on instantiation.
     var request = this.server.makeDeleteRequest( options );
     request.done( this.removePost );
     request.fail( this.displayError );
    }
  }
```

### Release 8 : Testing

Jasmine is a unit testing framework for JavaScript, meaning that it is meant to test your functions independent of the DOM, server, or any other part of your app. Unit testing DOM-interactive is consequently difficult. You will have to mock all elements on the DOM to

What should you test? All the functions that interact with the server -- e.g. your AJAX calls -- should not be tested. Instead, you should test all your functions that do simple transforms in JavaScript or alter the DOM. If you haven't already, you should name and separate out your callbacks from your AJAX functions, so you can test your callbacks independently of AJAX.

Refer to your Orange Trees challenge for an example of DOM testing in Jasmine.


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

<title>org.acra.attachment Class Hierarchy</title>
<meta name="date" content="2020-03-18">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Hierarchy For Package org.acra.attachment

Package Hierarchies:

All Packages

Class Hierarchy

java.lang.Object

android.content.ContentProvider (implements android.content.ComponentCallbacks2)

org.acra.attachment.AcraContentProvider

org.acra.attachment.DefaultAttachmentProvider (implements org.acra.attachment.AttachmentUriProvider)

Interface Hierarchy

org.acra.attachment.AttachmentUriProvider

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
function generateTest(internalFormat, pixelFormat, pixelType, prologue, resourcePath, defaultContextVersion) {
    var wtu = WebGLTestUtils;
    var tiu = TexImageUtils;
    var gl = null;
    var successfullyParsed = false;
    var whiteColor = [255, 255, 255, 255];
    var redColor = [255, 0, 0, 255];
    var greenColor = [0, 255, 0, 255];
    var semiTransparentRedColor = [127, 0, 0, 127];
    var semiTransparentGreenColor = [0, 127, 0, 127];
    var repeatCount;

    function replicateRedChannel(color)
    {
        color[1] = color[0];
        color[2] = color[0];
    }

    function zapColorChannels(color)
    {
        color[0] = 0;
        color[1] = 0;
        color[2] = 0;
    }

    function setAlphaChannelTo1(color)
    {
        color[3] = 255;
    }

    function replicateAllRedChannels()
    {
        replicateRedChannel(redColor);
        replicateRedChannel(semiTransparentRedColor);
        replicateRedChannel(greenColor);
        replicateRedChannel(semiTransparentGreenColor);
    }

    function setAllAlphaChannelsTo1()
    {
        setAlphaChannelTo1(redColor);
        setAlphaChannelTo1(semiTransparentRedColor);
        setAlphaChannelTo1(greenColor);
        setAlphaChannelTo1(semiTransparentGreenColor);
    }

    function repeatCountForTextureFormat(internalFormat, pixelFormat, pixelType)
    {
        // There were bugs in early WebGL 1.0 implementations when repeatedly uploading canvas
        // elements into textures. In response, this test was changed into a regression test by
        // repeating all of the cases multiple times. Unfortunately, this means that adding a new
        // case above significantly increases the run time of the test suite. The problem is made
        // even worse by the addition of many more texture formats in WebGL 2.0.
        //
        // Doing repeated runs with just a couple of WebGL 1.0's supported texture formats acts as a
        // sufficient regression test for the old bugs. For this reason the test has been changed to
        // only repeat for those texture formats.
        if ((internalFormat == 'RGBA' && pixelFormat == 'RGBA' && pixelType == 'UNSIGNED_BYTE') ||
            (internalFormat == 'RGB' && pixelFormat == 'RGB' && pixelType == 'UNSIGNED_BYTE')) {
            return 4;
        }

        return 1;
    }

    function init()
    {
        description('Verify texImage2D and texSubImage2D code paths taking canvas elements (' + internalFormat + '/' + pixelFormat + '/' + pixelType + ')');

        // Set the default context version while still allowing the webglVersion URL query string to override it.
        wtu.setDefault3DContextVersion(defaultContextVersion);
        gl = wtu.create3DContext("example");

        if (!prologue(gl)) {
            finishTest();
            return;
        }

        repeatCount = repeatCountForTextureFormat(internalFormat, pixelFormat, pixelType);

        switch (gl[pixelFormat]) {
          case gl.RED:
          case gl.RED_INTEGER:
            // Zap green and blue channels.
            whiteColor[1] = 0;
            whiteColor[2] = 0;
            greenColor[1] = 0;
            semiTransparentGreenColor[1] = 0;
            // Alpha channel is 1.0.
            setAllAlphaChannelsTo1();
            break;
          case gl.RG:
          case gl.RG_INTEGER:
            // Zap blue channel.
            whiteColor[2] = 0;
            // Alpha channel is 1.0.
            setAllAlphaChannelsTo1();
            break;
          case gl.LUMINANCE:
            // Replicate red channels.
            replicateAllRedChannels();
            // Alpha channel is 1.0.
            setAllAlphaChannelsTo1();
            break;
          case gl.ALPHA:
            // Red, green and blue channels are all 0.0.
            zapColorChannels(redColor);
            zapColorChannels(semiTransparentRedColor);
            zapColorChannels(greenColor);
            zapColorChannels(semiTransparentGreenColor);
            zapColorChannels(whiteColor);
            break;
          case gl.LUMINANCE_ALPHA:
            // Replicate red channels.
            replicateAllRedChannels();
            break;
          case gl.RGB:
          case gl.RGB_INTEGER:
            // Alpha channel is 1.0.
            setAllAlphaChannelsTo1();
            break;
          default:
            break;
        }

        switch (gl[internalFormat]) {
          case gl.SRGB8:
          case gl.SRGB8_ALPHA8:
            semiTransparentRedColor = wtu.sRGBToLinear(semiTransparentRedColor);
            semiTransparentGreenColor = wtu.sRGBToLinear(semiTransparentGreenColor);
            break;
          case gl.RGBA8UI:
            // For int and uint textures, TexImageUtils outputs the maximum value (in this case,
            // 255) for the alpha channel all the time because of differences in behavior when
            // sampling integer textures with and without alpha channels. Since changing this
            // behavior may have large impact across the test suite, leave it as is for now.
            setAllAlphaChannelsTo1();
            break;
        }

        gl.clearColor(0,0,0,1);
        gl.clearDepth(1);

        runTest();
    }

    function setCanvasToRedGreen(ctx) {
      var width = ctx.canvas.width;
      var height = ctx.canvas.height;
      var halfHeight = Math.floor(height / 2);
      ctx.clearRect(0, 0, width, height);
      ctx.fillStyle = "#ff0000";
      ctx.fillRect(0, 0, width, halfHeight);
      ctx.fillStyle = "#00ff00";
      ctx.fillRect(0, halfHeight, width, height - halfHeight);
    }

    function setCanvasToSemiTransparentRedGreen(ctx) {
      var width = ctx.canvas.width;
      var height = ctx.canvas.height;
      var halfHeight = Math.floor(height / 2);
      ctx.clearRect(0, 0, width, height);
      ctx.fillStyle = "rgba(127, 0, 0, 0.5)";
      ctx.fillRect(0, 0, width, halfHeight);
      ctx.fillStyle = "rgba(0, 127, 0, 0.5)";
      ctx.fillRect(0, halfHeight, width, height - halfHeight);
    }

    function drawTextInCanvas(ctx, bindingTarget) {
      var width = ctx.canvas.width;
      var height = ctx.canvas.height;
      ctx.fillStyle = "#ffffff";
      ctx.fillRect(0, 0, width, height);
      ctx.font = '20pt Arial';
      ctx.fillStyle = 'black';
      ctx.textAlign = "center";
      ctx.textBaseline = "middle";
      ctx.fillText("1234567890", width / 2, height / 4);
    }

    function setCanvasTo257x257(ctx, bindingTarget) {
      ctx.canvas.width = 257;
      ctx.canvas.height = 257;
      setCanvasToRedGreen(ctx);
    }

    function setCanvasTo257x257SemiTransparent(ctx, bindingTarget) {
      ctx.canvas.width = 257;
      ctx.canvas.height = 257;
      setCanvasToSemiTransparentRedGreen(ctx);
    }

    function setCanvasToMin(ctx, bindingTarget) {
      if (bindingTarget == gl.TEXTURE_CUBE_MAP) {
        // cube map texture must be square.
        ctx.canvas.width = 2;
      } else {
        ctx.canvas.width = 1;
      }
      ctx.canvas.height = 2;
      setCanvasToRedGreen(ctx);
    }

    function setCanvasToMinSemiTransparent(ctx, bindingTarget) {
      if (bindingTarget == gl.TEXTURE_CUBE_MAP) {
        // cube map texture must be square.
        ctx.canvas.width = 2;
      } else {
        ctx.canvas.width = 1;
      }
      ctx.canvas.height = 2;
      setCanvasToSemiTransparentRedGreen(ctx);
    }

    function runOneIteration(canvas, useTexSubImage2D, flipY, semiTransparent, program, bindingTarget, opt_texture, opt_fontTest)
    {
        var objType = 'canvas';
        if (canvas.transferToImageBitmap)
          objType = 'OffscreenCanvas';
        debug('Testing ' + (useTexSubImage2D ? 'texSubImage2D' : 'texImage2D') +
              ' with flipY=' + flipY + ' bindingTarget=' + (bindingTarget == gl.TEXTURE_2D ? 'TEXTURE_2D' : 'TEXTURE_CUBE_MAP') +
              ' canvas size: ' + canvas.width + 'x' + canvas.height +
              ' source object type: ' + objType +
              (opt_fontTest ? " with fonts" : " with" + (semiTransparent ? " semi-transparent" : "") + " red-green"));
        gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
        if (!opt_texture) {
            var texture = gl.createTexture();
            // Bind the texture to texture unit 0
            gl.bindTexture(bindingTarget, texture);
            // Set up texture parameters
            gl.texParameteri(bindingTarget, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
            gl.texParameteri(bindingTarget, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
            gl.texParameteri(bindingTarget, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
            gl.texParameteri(bindingTarget, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
        } else {
            var texture = opt_texture;
        }
        // Set up pixel store parameters
        gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, flipY);
        gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);
        wtu.failIfGLError(gl, 'gl.pixelStorei(gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, gl.NONE);');
        var targets = [gl.TEXTURE_2D];
        if (bindingTarget == gl.TEXTURE_CUBE_MAP) {
            targets = [gl.TEXTURE_CUBE_MAP_POSITIVE_X,
                       gl.TEXTURE_CUBE_MAP_NEGATIVE_X,
                       gl.TEXTURE_CUBE_MAP_POSITIVE_Y,
                       gl.TEXTURE_CUBE_MAP_NEGATIVE_Y,
                       gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
                       gl.TEXTURE_CUBE_MAP_NEGATIVE_Z];
        }
        // Upload the image into the texture
        for (var tt = 0; tt < targets.length; ++tt) {
            // Initialize the texture to black first
            if (useTexSubImage2D) {
                gl.texImage2D(targets[tt], 0, gl[internalFormat], canvas.width, canvas.height, 0,
                              gl[pixelFormat], gl[pixelType], null);
                gl.texSubImage2D(targets[tt], 0, 0, 0, gl[pixelFormat], gl[pixelType], canvas);
            } else {
                gl.texImage2D(targets[tt], 0, gl[internalFormat], gl[pixelFormat], gl[pixelType], canvas);
            }
        }

        var width = gl.canvas.width;
        var height = gl.canvas.height;
        var halfWidth = Math.floor(width / 2);
        var halfHeight = Math.floor(height / 2);
        var top = flipY ? 0 : (height - halfHeight);
        var bottom = flipY ? (height - halfHeight) : 0;

        var loc;
        if (bindingTarget == gl.TEXTURE_CUBE_MAP) {
            loc = gl.getUniformLocation(program, "face");
        }

        for (var tt = 0; tt < targets.length; ++tt) {
            if (bindingTarget == gl.TEXTURE_CUBE_MAP) {
                gl.uniform1i(loc, targets[tt]);
            }
            // Draw the triangles
            wtu.clearAndDrawUnitQuad(gl, [0, 255, 0, 255]);

            if (opt_fontTest) {
                // check half is a solid color.
                wtu.checkCanvasRect(
                      gl, 0, top, width, halfHeight,
                      whiteColor,
                      "should be white");
                // check other half is not a solid color.
                wtu.checkCanvasRectColor(
                      gl, 0, bottom, width, halfHeight,
                      whiteColor, 0,
                      function() {
                        testFailed("font missing");
                      },
                      function() {
                        testPassed("font rendered");
                      },
                      debug);
            } else {
                var localRed   = semiTransparent ? semiTransparentRedColor : redColor;
                var localGreen = semiTransparent ? semiTransparentGreenColor : greenColor;

                // Allow a tolerance for premultiplication/unmultiplication, especially for texture
                // formats with lower bit depths.
                var tolerance = 0;
                if (semiTransparent) {
                    tolerance = 3;
                    if (pixelType == 'UNSIGNED_SHORT_5_6_5' || internalFormat == 'RGB565') {
                        tolerance = 6;
                    } else if (pixelType == 'UNSIGNED_SHORT_4_4_4_4' || internalFormat == 'RGBA4') {
                        tolerance = 9;
                    } else if (pixelType == 'UNSIGNED_SHORT_5_5_5_1' || internalFormat == 'RGB5_A1') {
                        // Semi-transparent values are allowed to convert to either 1 or 0 for this
                        // single-bit alpha format per OpenGL ES 3.0.5 section 2.1.6.2, "Conversion
                        // from Floating-Point to Normalized Fixed-Point". Ignore alpha for these
                        // tests.
                        tolerance = 6;
                        localRed = localRed.slice(0, 3);
                        localGreen = localGreen.slice(0, 3);
                    } else if (internalFormat == 'RGB10_A2') {
                        // The alpha channel is too low-resolution for any meaningful comparisons.
                        localRed = localRed.slice(0, 3);
                        localGreen = localGreen.slice(0, 3);
                    }
                }

                // Check the top and bottom halves and make sure they have the right color.
                debug("Checking " + (flipY ? "top" : "bottom"));
                wtu.checkCanvasRect(gl, 0, bottom, width, halfHeight, localRed,
                                    "shouldBe " + localRed, tolerance);
                debug("Checking " + (flipY ? "bottom" : "top"));
                wtu.checkCanvasRect(gl, 0, top, width, halfHeight, localGreen,
                                    "shouldBe " + localGreen, tolerance);
            }

            if (!useTexSubImage2D && pixelFormat == "RGBA") {
                if (pixelType == "FLOAT") {
                    // Attempt to set a pixel in the texture to ensure the texture was
                    // actually created with floats. Regression test for http://crbug.com/484968
                    var pixels = new Float32Array([1000.0, 1000.0, 1000.0, 1000.0]);
                    gl.texSubImage2D(targets[tt], 0, 0, 0, 1, 1, gl[pixelFormat], gl[pixelType], pixels);
                    wtu.glErrorShouldBe(gl, gl.NO_ERROR, "Texture should be backed by floats");
                } else if (pixelType == "HALF_FLOAT_OES" || pixelType == "HALF_FLOAT") {
                    // Attempt to set a pixel in the texture to ensure the texture was
                    // actually created with half-floats. Regression test for http://crbug.com/484968
                    var halfFloatTenK = 0x70E2; // Half float 10000
                    var pixels = new Uint16Array([halfFloatTenK, halfFloatTenK, halfFloatTenK, halfFloatTenK]);
                    gl.texSubImage2D(targets[tt], 0, 0, 0, 1, 1, gl[pixelFormat], gl[pixelType], pixels);
                    wtu.glErrorShouldBe(gl, gl.NO_ERROR, "Texture should be backed by half-floats");
                }
            }
        }

        if (false) {
          var m = wtu.makeImageFromCanvas(gl.canvas);
          document.getElementById("console").appendChild(m);
          document.getElementById("console").appendChild(document.createElement("hr"));
        }

        return texture;
    }

    function runTest()
    {
        var canvas = document.createElement('canvas');

        var cases = [
            { canvas: canvas, sub: false, flipY: true,  semiTransparent: false, font: false, init: setCanvasToMin },
            { canvas: canvas, sub: false, flipY: false, semiTransparent: false, font: false },
            { canvas: canvas, sub: true,  flipY: true,  semiTransparent: false, font: false },
            { canvas: canvas, sub: true,  flipY: false, semiTransparent: false, font: false },
            { canvas: canvas, sub: false, flipY: true,  semiTransparent: true,  font: false, init: setCanvasToMinSemiTransparent },
            { canvas: canvas, sub: false, flipY: false, semiTransparent: true,  font: false },
            { canvas: canvas, sub: true,  flipY: true,  semiTransparent: true,  font: false },
            { canvas: canvas, sub: true,  flipY: false, semiTransparent: true,  font: false },
            { canvas: canvas, sub: false, flipY: true,  semiTransparent: false, font: false, init: setCanvasTo257x257 },
            { canvas: canvas, sub: false, flipY: false, semiTransparent: false, font: false },
            { canvas: canvas, sub: true,  flipY: true,  semiTransparent: false, font: false },
            { canvas: canvas, sub: true,  flipY: false, semiTransparent: false, font: false },
            { canvas: canvas, sub: false, flipY: true,  semiTransparent: true,  font: false, init: setCanvasTo257x257SemiTransparent },
            { canvas: canvas, sub: false, flipY: false, semiTransparent: true,  font: false },
            { canvas: canvas, sub: true,  flipY: true,  semiTransparent: true,  font: false },
            { canvas: canvas, sub: true,  flipY: false, semiTransparent: true,  font: false },
        ];

        // The font tests don't work with ALPHA-only textures since they draw to the color channels.
        if (internalFormat != 'ALPHA') {
            cases = cases.concat([
                { canvas: canvas, sub: false, flipY: true,  semiTransparent: false, font: true, init: drawTextInCanvas },
                { canvas: canvas, sub: false, flipY: false, semiTransparent: false, font: true },
                { canvas: canvas, sub: true,  flipY: true,  semiTransparent: false, font: true },
                { canvas: canvas, sub: true,  flipY: false, semiTransparent: false, font: true },
            ]);
        }

        if (window.OffscreenCanvas) {
            var offscreenCanvas = new OffscreenCanvas(1, 1);
            cases = cases.concat([
                { canvas: offscreenCanvas, sub: false, flipY: true,  semiTransparent: false, font: false, init: setCanvasToMin },
                { canvas: offscreenCanvas, sub: false, flipY: false, semiTransparent: false, font: false },
                { canvas: offscreenCanvas, sub: true,  flipY: true,  semiTransparent: false, font: false },
                { canvas: offscreenCanvas, sub: true,  flipY: false, semiTransparent: false, font: false },
                { canvas: offscreenCanvas, sub: false, flipY: true,  semiTransparent: true,  font: false, init: setCanvasToMinSemiTransparent },
                { canvas: offscreenCanvas, sub: false, flipY: false, semiTransparent: true,  font: false },
                { canvas: offscreenCanvas, sub: true,  flipY: true,  semiTransparent: true,  font: false },
                { canvas: offscreenCanvas, sub: true,  flipY: false, semiTransparent: true,  font: false },
            ]);
        }

        function runTexImageTest(bindingTarget) {
            var program;
            if (bindingTarget == gl.TEXTURE_2D) {
                program = tiu.setupTexturedQuad(gl, internalFormat);
            } else {
                program = tiu.setupTexturedQuadWithCubeMap(gl, internalFormat);
            }

            return new Promise(function(resolve, reject) {
                var count = repeatCount;
                var caseNdx = 0;
                var texture = undefined;
                function runNextTest() {
                    var c = cases[caseNdx];
                    var imageDataBefore = null;
                    if (c.init) {
                      c.init(c.canvas.getContext('2d'), bindingTarget);
                    }
                    texture = runOneIteration(c.canvas, c.sub, c.flipY, c.semiTransparent, program, bindingTarget, texture, c.font);
                    // for the first 2 iterations always make a new texture.
                    if (count < 2) {
                      gl.deleteTexture(texture);
                      texture = undefined;
                    }
                    ++caseNdx;
                    if (caseNdx == cases.length) {
                        caseNdx = 0;
                        --count;
                        if (!count) {
                            resolve("SUCCESS");
                            return;
                        }
                    }
                    // While we are working with Canvases, it's really unlikely that
                    // waiting for composition will change anything here, and it's much
                    // slower, so just dispatchPromise. If we want to test with composites,
                    // we should test a more narrow subset of tests.
                    wtu.dispatchPromise(runNextTest);
                }
                runNextTest();
            });
        }

        runTexImageTest(gl.TEXTURE_2D).then(function(val) {
            runTexImageTest(gl.TEXTURE_CUBE_MAP).then(function(val) {
                wtu.glErrorShouldBe(gl, gl.NO_ERROR, "should be no errors");
                finishTest();
            });
        });
    }

    return init;
}


text:
package opensesim.world;

import java.util.Map;
import opensesim.sesim.Assets.CurrencyAsset;
import opensesim.sesim.Assets.DummyAsset;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;

/**
 *
 * @author 7u83 <7u83@mail.ru>
 */
public class AccountTest {

    public AccountTest() {
    }

    @BeforeClass
    public static void setUpClass() {
    }

    @AfterClass
    public static void tearDownClass() {
    }

    @Before
    public void setUp() {
    }

    @After
    public void tearDown() {
    }

    /**
     * Test of getAssets method, of class Account.
     */
    /*   @Test
    public void testGetAssets() {
        System.out.println("getAssets");
        Account instance = new Account();
        Map<AbstractAsset, Double> expResult = null;
        Map<AbstractAsset, Double> result = instance.getAssets();
        assertEquals(expResult, result);
        // TODO review the generated test code and remove the default call to fail.
     //   fail("The test case is a prototype.");
    }
     */
    /**
     * Test of getOwner method, of class Account.
     */
    @Test
    public void testGetOwner() {
        System.out.println("getOwner");
        Account instance = new Account();
        Trader expResult = null;
        Trader result = instance.getOwner();
        assertEquals(expResult, result);
        // TODO review the generated test code and remove the default call to fail.
        //   fail("The test case is a prototype.");
    }

    /**
     * Test of add method, of class Account.
     */
    @Test
    public void testAdd() {

        System.out.println("add");

        AbstractAsset c = new DummyAsset("EUR", "Euro", 2);

        Double expResult = 123.0;
        AssetPack pack = new AssetPack(c, expResult);
        Account account = new Account();

        account.add(pack);
        Double result;

        result = account.get(c);
        assertEquals(expResult, result);

        account.add(pack);
        result = account.get(c);
        expResult *= 2;
        assertEquals(expResult, result);
    }

}


text:
require 'rails_helper'

RSpec.describe 'admins/users/index' do
  before(:each) do
    without_partial_double_verification do
      allow(view).to receive(:sort_column).and_return('')
      allow(view).to receive(:sort_direction).and_return('')
    end
  end

  it 'should list the user email' do
    user = create :user

    render template: 'admins/users/index', locals: { users: User.page(1) }

    expect(rendered).to have_content user.email
  end

  it 'should list the user\'s total points' do
    user = create :user, total_points: 6

    render template: 'admins/users/index', locals: { users: User.page(1) }

    expect(rendered).to have_selector "#user_#{user.id} .total_points", text: 6
  end

  it 'should list the user\'s total redeemed points' do
    user = create :user, total_points: 6
    create :redemption, user: user, value: 5

    render template: 'admins/users/index', locals: { users: User.page(1) }

    expect(rendered).to have_selector \
      "#user_#{user.id} .redeemed_points", text: 5
  end

  it 'should list how many points the user has redeemed this month' do
    user = create :user, total_points: 12
    create :redemption, user: user, value: 5
    create :redemption, user: user, value: 7, created_at: 2.months.ago

    render template: 'admins/users/index', locals: { users: User.page(1) }

    expect(rendered).to have_selector \
      "#user_#{user.id} .points_redeemed_this_month", text: 5
  end
end


text:
require 'fileutils'
require 'chef/mixin/shell_out'

include Chef::Mixin::ShellOut
include Windows::Helper

def whyrun_supported?
  true
end

action :extract do
  converge_by("Extract #{@new_resource.source} => #{@new_resource.path} (overwrite=#{@new_resource.overwrite})") do
    FileUtils.mkdir_p(@new_resource.path) unless Dir.exists?(@new_resource.path)
    local_source = cached_file(@new_resource.source, @new_resource.checksum)
    cmd = "#{seven_zip_exe} x"
    cmd << " -y" if @new_resource.overwrite
    cmd << " -o#{win_friendly_path(@new_resource.path)}"
    cmd << " #{local_source}"
    Chef::Log.debug(cmd)
    shell_out!(cmd)
  end
end

def seven_zip_exe()
  Chef::Log.debug("seven zip home: #{node['seven_zip']['home']}")
  win_friendly_path(::File.join(node['seven_zip']['home'], '7z.exe'))
end


text:
require("ember-views/views/view");
require("ember-views/views/states");
require("ember-views/views/container_view");
require("ember-views/views/collection_view");


text:
DEFINE_int32(size, 0, "Size of the magic square.");
DEFINE_bool(impact, false, "Use impact search.");
DEFINE_int32(restart, -1, "Parameter for constant restart monitor.");
DEFINE_bool(luby, false,
            "Use luby restart monitor instead of constant restart monitor.");
DEFINE_bool(run_all_heuristics, false, "Run all heuristics.");
DEFINE_int32(heuristics_period, 200, "Frequency to run all heuristics.");
DEFINE_int32(choose_var_strategy, 0,
             "Selection strategy for variable: 0 = max sum impact, "
             "1 = max average impact, "
             "2 = max individual impact.");
DEFINE_bool(select_max_impact_value, false,
            "Select the value with max impact instead of min impact.");
DEFINE_double(restart_log_size, -1.0,
              "Threshold for automatic restarting the search in default"
              " phase.");
DEFINE_bool(verbose_impact, false, "Verbose output of impact search.");
DEFINE_bool(use_nogoods, false, "Use no goods in automatic restart.");

namespace operations_research {

void MagicSquare(int grid_size) {
  Solver solver("magicsquare");
  const int total_size = grid_size * grid_size;
  const int sum = grid_size * (total_size + 1) / 2;
  // create the variables
  std::vector<IntVar*> vars;
  solver.MakeIntVarArray(total_size, 1, total_size, "", &vars);
  solver.AddConstraint(solver.MakeAllDifferent(vars));

  // create the constraints
  std::vector<IntVar*> diag1(grid_size);
  std::vector<IntVar*> diag2(grid_size);
  for (int n = 0; n < grid_size; ++n) {
    std::vector<IntVar*> sub_set(grid_size);

    for (int m = 0; m < grid_size; ++m) {  // extract row indices
      sub_set[m] = vars[m + n * grid_size];
    }
    solver.AddConstraint(solver.MakeSumEquality(sub_set, sum));

    for (int m = 0; m < grid_size; ++m) {
      sub_set[m] = vars[m * grid_size + n];  // extract column indices
    }
    solver.AddConstraint(solver.MakeSumEquality(sub_set, sum));
    diag1[n] = vars[n + n * grid_size];  // extract first diagonal indices
    diag2[n] = vars[(grid_size - 1 - n) + n * grid_size];  // second diagonal
  }
  solver.AddConstraint(solver.MakeSumEquality(diag1, sum));
  solver.AddConstraint(solver.MakeSumEquality(diag2, sum));

  // To break a simple symmetry: the upper right corner
  // must be less than the lower left corner
  solver.AddConstraint(
      solver.MakeLess(vars[grid_size - 1], vars[(grid_size - 1) * grid_size]));
  // TODO(user) use local search

  DefaultPhaseParameters parameters;
  parameters.run_all_heuristics = FLAGS_run_all_heuristics;
  parameters.heuristic_period = FLAGS_heuristics_period;
  parameters.restart_log_size = FLAGS_restart_log_size;
  parameters.display_level = FLAGS_verbose_impact
                                 ? DefaultPhaseParameters::VERBOSE
                                 : DefaultPhaseParameters::NORMAL;
  parameters.use_no_goods = FLAGS_use_nogoods;
  switch (FLAGS_choose_var_strategy) {
    case 0: {
      parameters.var_selection_schema =
          DefaultPhaseParameters::CHOOSE_MAX_SUM_IMPACT;
      break;
    }
    case 1: {
      parameters.var_selection_schema =
          DefaultPhaseParameters::CHOOSE_MAX_AVERAGE_IMPACT;
      break;
    }
    case 2: {
      parameters.var_selection_schema =
          DefaultPhaseParameters::CHOOSE_MAX_VALUE_IMPACT;
      break;
    }
    default: { LOG(FATAL) << "Should not be here"; }
  }
  parameters.value_selection_schema =
      FLAGS_select_max_impact_value ? DefaultPhaseParameters::SELECT_MAX_IMPACT
                                    : DefaultPhaseParameters::SELECT_MIN_IMPACT;

  DecisionBuilder* const db =
      FLAGS_impact ? solver.MakeDefaultPhase(vars, parameters)
                   : solver.MakePhase(vars, Solver::CHOOSE_FIRST_UNBOUND,
                                      Solver::ASSIGN_MIN_VALUE);

  std::vector<SearchMonitor*> monitors;
  SearchMonitor* const log = solver.MakeSearchLog(100000);
  monitors.push_back(log);
  SearchMonitor* const restart =
      FLAGS_restart != -1
          ? (FLAGS_luby ? solver.MakeLubyRestart(FLAGS_restart)
                        : solver.MakeConstantRestart(FLAGS_restart))
          : NULL;
  if (restart) {
    monitors.push_back(restart);
  }
  solver.NewSearch(db, monitors);
  if (solver.NextSolution()) {
    for (int n = 0; n < grid_size; ++n) {
      std::string output;
      for (int m = 0; m < grid_size; ++m) {  // extract row indices
        int64 v = vars[n * grid_size + m]->Value();
        StringAppendF(&output, "%3lld ", v);
      }
      LOG(INFO) << output;
    }
    LOG(INFO) << "";
  } else {
    LOG(INFO) << "No solution found!";
  }
  solver.EndSearch();
}

}  // namespace operations_research

int main(int argc, char** argv) {
  gflags::ParseCommandLineFlags( &argc, &argv, true);
  if (FLAGS_size != 0) {
    operations_research::MagicSquare(FLAGS_size);
  } else {
    for (int n = 3; n < 6; ++n) {
      operations_research::MagicSquare(n);
    }
  }
  return 0;
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">

<title>奢华</title>
<link href="css/me1.css" rel="stylesheet" type="text/css" />
<link href="css/kh-index.css" rel="stylesheet" type="text/css" />

            {include file="nav.html"}

您好!欢迎进入在线库存中心

			{include file="me_nav.html"}

				<form action="{write_url url=$thisurl go='append'}" method="post" enctype="multipart/form-data">

修改倍率

*倍率	<input name="mag" type="text" value="{$show.mag}" style="width:70%"  />

<input value="修改资料" type="submit" style="height:auto; line-height:normal;" />

				</form>

    {include file="foot.html"}


text:
<?xml version="1.0"?>
<project name="org.pathvisio.biopax3" default="install" basedir="." xmlns:ivy="antlib:org.apache.ivy.ant">

  <property name="pathvisio.dir" value="../../common-bundles/trunk/"/>
  <property name="common.bundles" value="../../common-bundles/trunk"/>

  	<path id="project.class.path">
		<fileset dir="${pathvisio.dir}/modules">
			<include name="org.pathvisio.core.jar"/>
			<include name="org.pathvisio.gui.jar"/>
			<include name="org.pathvisio.desktop.jar"/>
		</fileset>
		<fileset dir="lib">
			<include name="paxtools*.jar"/>
		</fileset>
		<fileset dir="${pathvisio.dir}/lib">
			<include name="*jdom*.jar"/>
			<include name="felix*.jar"/>
			<include name="org.bridgedb.jar"/>
			<include name="org.bridgedb.bio.jar"/>
		</fileset>
		<fileset dir="${common.bundles}">
			<include name="*google.collect*.jar"/>
		</fileset>
	</path>

	<path id="test.class.path">
		<fileset dir="${pathvisio.dir}/modules">
			<include name="org.wikipathways.client.jar"/>
		</fileset>
		<fileset dir="${pathvisio.dir}/lib">
			<include name="org.junit*.jar"/>
		</fileset>
		<fileset dir="${common.bundles}">
			<include name="nl.helixsoft.util.xml*.jar"/>
			<!--use com.springsource.javax.xml.rpc.jar which contains class files-->
			<include name="com.springsource.javax.xml.rpc*.jar"/>
		</fileset>
	</path>

	<import file="${common.bundles}/plugin-common.xml" />

	<target name="prepare">
		<unjar dest="build/classes">
        <fileset dir="lib">
            <include name="paxtools*.jar" />
        </fileset>
    	</unjar>
	</target>

	<target name="install" depends="jar">
		<copy todir="${bundle.dest}">
			<fileset dir="${common.bundles}">
				<include name="*google.collect*.jar"/>
			</fileset>
  		</copy>
	</target>

	<target name="test" depends="compile">
		<javac srcdir="test" debug="true"
					destdir="build/classes"
					source="1.5">
			<classpath>
				<path refid="test.class.path"/>
				<path refid="project.class.path"/>
			</classpath>
		</javac>
		<junit printsummary="on" haltonfailure="true" fork="true" dir=".">
			<formatter type="brief" usefile="false"/>
			<classpath>
				<pathelement path="build/classes"/>
				<path refid="project.class.path"/>
				<path refid="test.class.path"/>
			</classpath>
			<batchtest>
				<fileset dir="test">
					<include name="**/*Test*.java"/>
				</fileset>
			</batchtest>
		</junit>
	</target>

  <target name="webstart" depends="jar">
	<fail message="You must specify a keystore password for opening visioKeyStore: ant -Dkeystore.password=***** [ant target]">
		<condition>
			<not> <isset property="keystore.password"/> </not>
		</condition>
	</fail>
  	<mkdir dir="${webstart.dir}"/>
  	<copy file="${jar.name}" todir="${webstart.dir}"/>
  	<copy todir="${webstart.dir}">
		<fileset dir="${pathvisio.dir}">
  			<include name="pathvisio.jar"/>
			<include name="lib/**/*.jar"/>
		</fileset>
  	</copy>
  	<copy todir="${webstart.dir}/lib">
		<fileset dir="lib">
			<include name="**/*.jar"/>
		</fileset>
  	</copy>
	<copy todir="${webstart.dir}" file="Biopax3GPML.jnlp"/>
    <signjar alias="PV" lazy = "true"
		storepass="${keystore.password}" keystore="${pathvisio.dir}/lib/visioKeyStore">
		<fileset dir="${webstart.dir}" includes="**/*.jar"/>
	</signjar>
  </target>

</project>


text:
import zlib
import base64
import uuid
import urllib

from datetime import datetime
from lxml import etree
from lxml.builder import ElementMaker

def create(
    _clock=None,
    _uuid=None,
    _zlib=None,
    _base64=None,
    _urllib=None,
    **kwargs
    ):
    """Create a URL string which can be used to redirect a samlp:AuthnRequest to the identity provider.
    Return a URL string containing the idp_sso_target_url and a deflated, base64-encoded, url-encoded (in that order) samlp:AuthnRequest XML element as the value of the SAMLRequest parameter.

    Keyword arguments:
    assertion_consumer_service_url -- The URL at which the SAML assertion should be received.
    issuer -- The name of your application. Some identity providers might need this to establish the identity of the service provider requesting the login.
    name_identifier_format -- The format of the username required by this application. If you need the email address, use "urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress". See http://docs.oasis-open.org/security/saml/v2.0/saml-core-2.0-os.pdf section 8.3 for other options. Note that the identity provider might not support all options.
    idp_sso_target_url -- The URL to which the authentication request should be sent. This would be on the identity
"""
    if _clock is None:
        _clock = datetime.utcnow
    if _uuid is None:
        _uuid = uuid.uuid4
    if _zlib is None:
        _zlib = zlib
    if _base64 is None:
        _base64 = base64
    if _urllib is None:
        _urllib = urllib

    assertion_consumer_service_url = kwargs.pop(
        'assertion_consumer_service_url',
        )
    issuer = kwargs.pop('issuer')
    name_identifier_format = kwargs.pop('name_identifier_format')
    idp_sso_target_url = kwargs.pop('idp_sso_target_url')

    now = _clock()
    # Resolution finer than milliseconds not allowed
    # http://docs.oasis-open.org/security/saml/v2.0/saml-core-2.0-os.pdf Section
    # 1.3.3
    now = now.replace(microsecond=0)
    now_iso = now.isoformat()

    unique_id = _uuid()
    unique_id = unique_id.hex

    samlp_maker = ElementMaker(
        namespace='urn:oasis:names:tc:SAML:2.0:protocol',
        nsmap=dict(samlp='urn:oasis:names:tc:SAML:2.0:protocol'),
        )
    saml_maker = ElementMaker(
        namespace='urn:oasis:names:tc:SAML:2.0:assertion',
        nsmap=dict(saml='urn:oasis:names:tc:SAML:2.0:assertion'),
        )

    authn_request = samlp_maker.AuthRequest(
        ProtocolBinding='urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST',
        Version='2.0',
        IssueInstant=now_iso,
        ID=unique_id,
        AssertionConsumerServiceURL=assertion_consumer_service_url,
        )

    saml_issuer = saml_maker.Issuer()
    saml_issuer.text = issuer
    authn_request.append(saml_issuer)

    name_id_policy = samlp_maker.NameIDPolicy(
        Format=name_identifier_format,
        AllowCreate='true',
        )
    authn_request.append(name_id_policy)

    request_authn_context = samlp_maker.RequestedAuthnContext(
        Comparison='exact',
        )
    authn_request.append(request_authn_context)

    authn_context_class_ref = saml_maker.AuthnContextClassRef()
    authn_context_class_ref.text = ('urn:oasis:names:tc:SAML:2.0:ac:classes:'
                                    + 'PasswordProtectedTransport'
                                    )
    request_authn_context.append(authn_context_class_ref)

    compressed_request = _zlib.compress(etree.tostring(authn_request))
    # Strip the first 2 bytes (header) and the last 4 bytes (checksum) to get the raw deflate
    deflated_request = compressed_request[2:-4]
    encoded_request = _base64.b64encode(deflated_request)
    urlencoded_request = _urllib.urlencode(
        [('SAMLRequest', encoded_request)],
        )

    return '{url}?{query}'.format(
        url=idp_sso_target_url,
        query=urlencoded_request,
        )


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>Release 4.0: memp_XXX</title>
    <link rel="stylesheet" href="gettingStarted.css" type="text/css" />
    <meta name="generator" content="DocBook XSL Stylesheets V1.73.2" />
    <link rel="start" href="index.html" title="Berkeley DB Programmer's Reference Guide" />
    <link rel="up" href="upgrade_4_0_toc.html" title="Chapter 37. Upgrading Berkeley DB 3.3 applications to Berkeley DB 4.0" />
    <link rel="prev" href="upgrade_4_0_log.html" title="Release 4.0: log_XXX" />
    <link rel="next" href="upgrade_4_0_txn.html" title="Release 4.0: txn_XXX" />

          Release 4.0: memp_XXX

          Prev
          Chapter 37. Upgrading Berkeley DB 3.3 applications to Berkeley DB 4.0
           Next

Release 4.0: memp_XXX

The C API for the Berkeley DB Memory Pool subsystem was reworked in the 4.0
release as follows:

          <colgroup>
            <col />
            <col />
          </colgroup>

              Historic functional interface
              Berkeley DB 4.X method

              memp_register

                DB_ENV->memp_register()

              memp_stat

                DB_ENV->memp_stat()

              memp_sync

                DB_ENV->memp_sync()

              memp_trickle

                DB_ENV->memp_trickle()

              memp_fopen

                DB_ENV->memp_fcreate()

              DB_MPOOL_FINFO: ftype

                DB_MPOOLFILE->set_ftype()

              DB_MPOOL_FINFO: pgcookie

                DB_MPOOLFILE->set_pgcookie()

              DB_MPOOL_FINFO: fileid

                DB_MPOOLFILE->set_fileid()

              DB_MPOOL_FINFO: lsn_offset

                DB_MPOOLFILE->set_lsn_offset()

              DB_MPOOL_FINFO: clear_len

                DB_MPOOLFILE->set_clear_len()

              memp_fopen

                DB_MPOOLFILE->open()

              memp_fclose

                DB_MPOOLFILE->close()

              memp_fput

                DB_MPOOLFILE->put()

              memp_fset
              DB_MPOOLFILE->set

              memp_fsync

                DB_MPOOLFILE->sync()

Applications calling any of the memp_register, memp_stat, memp_sync or
memp_trickle functions should update those calls to use the enclosing
DB_ENV class handle's method (easily done as the first argument to the
existing call is the correct DB_ENV class handle).

In addition, the DB_ENV->memp_stat() call has been changed in the 4.0
release to take a flags argument.  To leave their historic behavior
unchanged, applications should add a final argument of 0 to any calls
made to DB_ENV->memp_stat().

Applications calling the memp_fopen function should update those calls
as follows: First, acquire a Cache chapter handle using the
DB_ENV->memp_fcreate() method.  Second, if the DB_MPOOL_FINFO structure
reference passed to the memp_fopen function was non-NULL, call the
Cache chapter method corresponding to each initialized field in
the DB_MPOOL_FINFO structure.  Third, call the DB_MPOOLFILE->open() method
method to open the underlying file.  If the DB_MPOOLFILE->open() method call
fails, then DB_MPOOLFILE->close() method must be called to destroy the allocated
handle.

Applications calling the memp_fopen, memp_fclose, memp_fput, memp_fset,
or memp_fsync functions should update those calls to use the enclosing
Cache chapter handle's method.  Again, this is easily done as the
first argument to the existing call is the correct Cache chapter
handle.  With one exception, the calling conventions of the old and new
interfaces are identical; the one exception is the DB_MPOOLFILE->close() method,
which requires an additional flag parameter that should be set to 0.

          Prev

            Up

           Next

          Release 4.0: log_XXX

            Home

           Release 4.0: txn_XXX


text:
MenuMain::MenuMain(CEGUI::String name) : MenuAbstract(name)
{
	this->buttonCloseShow = false;
}

CEGUI::Window ** MenuMain::generateContent()
{
    CEGUI::WindowManager &wmgr = CEGUI::WindowManager::getSingleton();

    //the add MainMenu button
    CEGUI::Window * continueWdw = wmgr.createWindow("SleekSpace/Button", "MainMenu/continue"+this->name);
    continueWdw->setText("Reprendre");
    continueWdw->setSize(CEGUI::UVector2(CEGUI::UDim( 0.8f, 0.0f ), CEGUI::UDim( 0.10f, 0.0f )));
    continueWdw->setPosition(CEGUI::UVector2( CEGUI::UDim( 0.1f, 0.0f ), CEGUI::UDim( 0.33f, 0.0f )));
    continueWdw->subscribeEvent(CEGUI::PushButton::EventClicked, CEGUI::Event::Subscriber(&MenuMain::actionButtonContinue, this));

    CEGUI::Window * quitWdw = wmgr.createWindow("SleekSpace/Button", "MainMenu/quit"+this->name);
    quitWdw->setText("Quitter");
    quitWdw->setSize(CEGUI::UVector2(CEGUI::UDim( 0.8f, 0.0f ), CEGUI::UDim( 0.10f, 0.0f )));
    quitWdw->setPosition(CEGUI::UVector2( CEGUI::UDim( 0.1f, 0.0f ), CEGUI::UDim( 0.66f, 0.0f )));
    quitWdw->subscribeEvent(CEGUI::PushButton::EventClicked, CEGUI::Event::Subscriber(&MenuMain::actionButtonQuit, this));

    CEGUI::Window ** tblWin = new CEGUI::Window *[3];
    tblWin[0] = continueWdw;
    tblWin[1] = quitWdw;
    tblWin[2] = 0;

    return tblWin;
}

void MenuMain::actionFromUser(Controls::Controls key)
{
    switch(key)
    {
      case Controls::OPEN_MENU :
        if(GestInteraction::getSingletonPtr()->getAppLauched())
        {
          this->windowSwitch();
          GestInteraction::getSingletonPtr()->switchPauseState();
        }
        break;

      default:
          break;
    }
}

bool MenuMain::actionButtonContinue(const CEGUI::EventArgs & evt)
{
	this->windowHide();

	GestInteraction::getSingletonPtr()->initScene();

	return true;
}

bool MenuMain::actionButtonQuit(const CEGUI::EventArgs & evt)
{
	this->windowHide();

	GestInteraction::getSingletonPtr()->quitApplication();

	return true;
}

bool MenuMain::destroyWindow(const CEGUI::EventArgs & evt)
{
	CEGUI::WindowManager &wmgr = CEGUI::WindowManager::getSingleton();
	wmgr.destroyWindow((static_cast<const CEGUI::WindowEventArgs&>(evt)).window->getParent()->getParent()->getParent());

  return true;
}


text:
(function() {
  "use strict";

  var WORD = /[\w$]+/, RANGE = 500;

  CodeMirror.registerHelper("hint", "anyword", function(editor, options) {
	var word = options && options.word || WORD;
	var range = options && options.range || RANGE;
	var cur = editor.getCursor(), curLine = editor.getLine(cur.line);
	var start = cur.ch, end = start;
	while (end < curLine.length && word.test(curLine.charAt(end))) ++end;
	while (start && word.test(curLine.charAt(start - 1))) --start;
	var curWord = start != end && curLine.slice(start, end);

	var list = [], seen = {};

	if (editor.getMode().name === "solidity")
	{
		list = addSolToken(curWord, list, seen, solCurrency(), solCurrency);
		list = addSolToken(curWord, list, seen, solKeywords(), solKeywords);
		list = addSolToken(curWord, list, seen, solStdContract(), solStdContract);
		list = addSolToken(curWord, list, seen, solTime(), solTime);
		list = addSolToken(curWord, list, seen, solTypes(), solTypes);
		list = addSolToken(curWord, list, seen, solMisc(), solMisc);
	}

	//TODO: tokenize properly
	if (curLine.slice(start - 6, start) === "block.")
		list = addSolToken(curWord, list, seen, solBlock(), solBlock);
	else if (curLine.slice(start - 4, start) === "msg.")
		list = addSolToken(curWord, list, seen, solMsg(), solMsg);
	else if (curLine.slice(start - 3, start) === "tx.")
		list = addSolToken(curWord, list, seen, solTx(), solTx);

	var previousWord = "";
	var re = new RegExp(word.source, "g");
	for (var dir = -1; dir <= 1; dir += 2) {
	  var line = cur.line, endLine = Math.min(Math.max(line + dir * range, editor.firstLine()), editor.lastLine()) + dir;
	  for (; line != endLine; line += dir) {
		var text = editor.getLine(line), m;
		while (m = re.exec(text)) {
		  if (line == cur.line && m[0] === curWord) continue;
		  if ((!curWord || m[0].lastIndexOf(curWord, 0) === 0) && !Object.prototype.hasOwnProperty.call(seen, m[0])) {
			seen[m[0]] = true;
			var w = { text: m[0] };
			checkDeclaration(previousWord, "Contract", w);
			checkDeclaration(previousWord, "Function", w);
			list.push(w);
		  }
		  previousWord = m[0];
		}
	  }
	}
	return {list: list, from: CodeMirror.Pos(cur.line, start), to: CodeMirror.Pos(cur.line, end)};
  });
})();

function addSolToken(curWord, list, seen, tokens, type)
{
	var keywordsTypeName = keywordsName();
	for (var key in tokens)
	{
		seen[key] = true;
		if (curWord === false || key.indexOf(curWord, 0) === 0)
		{
			var token = { text: key };
			token.render = function(elt, data, cur)
			{
				render(elt, data, cur, type.name.toLowerCase(), keywordsTypeName[type.name.toLowerCase()]);
			}
			list.push(token);
		}
	}
	return list;
}

function render(elt, data, cur, csstype, type)
{
	var container = document.createElement("div");
	var word = document.createElement("div");
	word.className = csstype + " solToken";
	word.appendChild(document.createTextNode(cur.displayText || cur.text));
	var typeDiv = document.createElement("type");
	typeDiv.appendChild(document.createTextNode(type));
	typeDiv.className = "solTokenType";
	container.appendChild(word);
	container.appendChild(typeDiv);
	elt.appendChild(container);
}

function checkDeclaration(previousToken, target, current)
{
	if (previousToken.toLowerCase() === target.toLowerCase())
	{
		current.render = function(elt, data, cur)
		{
			render(elt, data, cur, "sol" + target, target);
		}
	}
}


text:
package org.uberfire.ext.preferences.backend;

import org.uberfire.ext.preferences.shared.annotations.Property;
import org.uberfire.ext.preferences.shared.annotations.WorkbenchPreference;
import org.uberfire.ext.preferences.shared.bean.BasePreference;

@WorkbenchPreference(identifier = "InvalidDefaultPreference")
public class InvalidDefaultPreference implements BasePreference<InvalidDefaultPreference> {

    @Property
    String text;

    @Override
    public InvalidDefaultPreference defaultValue( final InvalidDefaultPreference defaultValue ) {
        return new InvalidDefaultPreference();
    }
}


text:
gump
====

Generally Useful Modules in Python


text:
'use strict';

const express = require('express');
const topicCtrl = require('../controllers').topicCtrl;
const topicRouter = express.Router();
const auth = require('../middlewares');

//获取topic列表
topicRouter.get('/', topicCtrl.getTopicList);

//获取topic详情
topicRouter.get('/:topicId', topicCtrl.getTopicDetail);

//创建topic
topicRouter.post('/', auth.signinRequired, topicCtrl.createTopic);

//更新topic
topicRouter.put('/:topicId', auth.signinRequired, topicCtrl.updateTopic);

//删除topic
topicRouter.delete('/:topicId', auth.signinRequired, topicCtrl.removeTopic);

//置顶
//PUT /topics/:id/top
topicRouter.put(
  '/:topicId/top',
  auth.signinRequired,
  auth.adminRequired,
  topicCtrl.toggleIsTop
);

//设为精华文章
////PUT /topics/:id/good
topicRouter.put(
  '/:topicId/good',
  auth.signinRequired,
  auth.adminRequired,
  topicCtrl.toggleIsGood
);

//点赞
//PUT /topics/:id/vote
topicRouter.put(
  '/:topicId/vote',
  auth.signinRequired,
  topicCtrl.toggleVote
);

//收藏
topicRouter.put(
  '/:topicId/fav',
  auth.signinRequired,
  topicCtrl.toggleFavorite
);

//获取收藏的topic
topicRouter.get(
  '/favs/:id',
  auth.signinRequired,
  topicCtrl.getFavoriteTopics
);

//获取点赞的topic
topicRouter.get(
  '/votes/:id',
  auth.signinRequired,
  topicCtrl.getVoteTopics
);

module.exports = topicRouter;


text:
module Syntax where

import Data.List
import qualified Environment as E

type VEnv a = E.Env (Value a)
type Program a = [Bind a]
type Id = String

data Bind a = Bind Id (Maybe QType) [Id] (Expr a)
  deriving (Read, Show, Eq, Ord)

-- Exceptions
data Exception a =
  LexingError String
  | ParsingError String
  -- Evaluator errors
  | EvaluatorError String
  | InvalidUnits BaseUnit BaseUnit
  | DivideByZero
  | ScopeError Id (VEnv a)
  | TypeError Type Type
  deriving (Read, Show, Eq, Ord)

-- Tokens which the input can be transformed into
data Token a =
  Num a
  | Booly Bool
  | BType BaseType
  | Keyword Keywords
  | Operator Operator
  | Units String
  | Identifier Id
  | Bracket Brackets
  | Semicolon
  | UnitApply
  deriving (Read, Show, Eq, Ord)

data List a = Empty | Cons a (List a) deriving (Read, Show, Eq, Ord)

-- This is the values which the program should be able to return
data Value a = Number a Unit
           | Boolean Bool
           | Listy (List (Value a))
           | Fun Id (VEnv a) [Id] (Expr a)
           | P Operator [Value a]
           | C Id [Value a]
           deriving (Read, Show, Eq, Ord)

-- And this is what the parser should output
-- (eventually turned into a valid program)
data Expr a =
  End
  | Const (Value a)
  | Var Id
  | Prim Operator
  | App (Expr a) (Expr a)
  | LetIn [Bind a] (Expr a)
  | IfThenElse (Expr a) (Expr a) (Expr a)
  deriving (Read, Show, Eq, Ord)

data Keywords =
  If | Then | Else
  | Case | Of
  | Let | In
  | Where
  deriving (Read, Show, Eq, Ord)

data Operator =
  Add | Sub | Mul | Div | Mod | Pow
  | Gt | Ge | Lt | Le | Eq | Ne
  | And | Or | Not
  | Head | Tail | ListCons | IsEmpty
  | Comma
  | Assignment | TypeAssignment | TypeArrow
  deriving (Read, Show, Eq, Ord)

data Brackets =
  LeftParen | RightParen
  | LeftBracket | RightBracket
  | LeftSquareBracket | RightSquareBracket
  deriving (Read, Show, Eq, Ord)

-- For the type checker
data QType = Forall Id QType
            | Ty Type
            deriving (Read, Show, Eq, Ord)

data Type = Arrow Type Type
          | Prod Type Type
          | Sum Type Type
          | Base BaseType
          | TypeVar Id
          deriving (Read, Show, Eq, Ord)

data BaseType = UnitType
              | Int
              | Float
              | Bool
              deriving (Read, Show, Eq, Ord)

-- Units for number
data Unit = Unit [SingleUnit]
  deriving (Read, Show, Eq, Ord)

type SingleUnit = (BaseUnit, UnitPrefix, Exponent)
type Exponent = Int

data BaseUnit =
  Metre       -- m
  | Second    -- s
  | Gram      -- g
  | Ampere    -- A
  | Kelvin    -- K
  | Mole      -- mol
  | Candela   -- cd
  | CustomUnit String
  deriving (Read, Show, Eq, Ord)

-- Stardard metric prefixes
data UnitPrefix =
    Yocto   -- 10^-24 y
  | Zepto   -- 10^-21 z
  | Atto    -- 10^-18 a
  | Femto   -- 10^-15 f
  | Pico    -- 10^-12 p
  | Nano    -- 10^-9  n
  | Micro   -- 10^-6  mu
  | Milli   -- 10^-3  m
  | Centi   -- 10^-2  c
  | Deci    -- 10^-1  d
  | None
  | Deca    -- 10^1   da
  | Hecto   -- 10^2   h
  | Kilo    -- 10^3   k
  | Mega    -- 10^6   M
  | Giga    -- 10^9   G
  | Tera    -- 10^12  T
  | Peta    -- 10^15  P
  | Exa     -- 10^18  E
  | Zetta   -- 10^21  Z
  | Yotta   -- 10^24  Y
  deriving (Enum, Read, Show, Eq, Ord)

  -- Printing values in a nice
printValue :: (Show a) => Value a -> IO ()
printValue v = putStrLn $ formatValue v

formatValue :: (Show a) => Value a -> String
formatValue (Number n u)  = (show n) ++ (formatUnit u)
formatValue (Boolean b)   = (show b)
formatValue (Listy l)     = prettyList l
formatValue _             = error "Value is not supposed to be outputted"

prettyList :: (Show a) => List (Value a) -> String
prettyList l = "[" ++ (intercalate ", " $ prettyList' l) ++ "]"
  where
    prettyList' Empty       = []
    prettyList' (Cons v l)  = (formatValue v) : (prettyList' l)

formatUnit :: Unit -> String
formatUnit (Unit [])  = ""
formatUnit u          = " <<" ++ (intercalate " * " $ formatUnit' u) ++ ">>"
  where
    formatUnit' (Unit [])     = []
    formatUnit' (Unit (u:us)) = (prettyUnit u) : formatUnit' (Unit us)

prettyUnit :: SingleUnit -> String
prettyUnit (u, p, e) = (prefixToString p) ++ (baseUnitToString u) ++ (expoString e)
  where expoString e = if e == 1 then "" else ("^" ++ (show e))

prefixToString :: UnitPrefix -> String
prefixToString None = ""
prefixToString Yocto  = "y"
prefixToString Zepto  = "z"
prefixToString Atto   = "a"
prefixToString Femto  = "f"
prefixToString Pico   = "p"
prefixToString Nano   = "n"
prefixToString Micro  = "mu"
prefixToString Milli  = "m"
prefixToString Centi  = "c"
prefixToString Deci   = "d"
prefixToString Deca   = "da"
prefixToString Hecto  = "h"
prefixToString Kilo   = "k"
prefixToString Mega   = "M"
prefixToString Giga   = "G"
prefixToString Tera   = "T"
prefixToString Peta   = "P"
prefixToString Exa    = "E"
prefixToString Zetta  = "Z"
prefixToString Yotta  = "Y"

baseUnitToString :: BaseUnit -> String
baseUnitToString Metre    = "m"
baseUnitToString Second   = "s"
baseUnitToString Gram     = "g"
baseUnitToString Ampere   = "A"
baseUnitToString Kelvin   = "K"
baseUnitToString Mole     = "mol"
baseUnitToString Candela  = "cd"
baseUnitToString (CustomUnit s) = s


text:
//
//  HeaderParser.h
//  snowcrash
//
//  Created by Zdenek Nemec on 5/22/13.
//  Copyright (c) 2013 Apiary Inc. All rights reserved.
//

#ifndef SNOWCRASH_HEADERPARSER_H
#define SNOWCRASH_HEADERPARSER_H

#include "SectionParser.h"
#include "RegexMatch.h"
#include "CodeBlockUtility.h"
#include "StringUtility.h"
#include "BlueprintUtility.h"
#include "RegexMatch.h"

#include <string.h>

namespace snowcrash
{

    /** Headers matching regex */
    const char* const HeadersRegex = "^[[:blank:]]*[Hh]eaders?[[:blank:]]*$";

    /** Header Iterator in its containment group */
    typedef Collection<Header>::const_iterator HeaderIterator;

    /** Base class for functor to check validity of parsed header */
    struct ValidateFunctorBase {

        /** intended to generate warning message */
        virtual std::string getMessage() const = 0;

        /**
         * intended to invoke validation
         * \return true if validation is ok
         *
         * data for validation you can inject into functor via c-tor
         */
        virtual bool operator()() const = 0;
    };

    /** Functor implementation for check header name is valid token according to specification \see
     * http://tools.ietf.org/html/rfc7230#section-3.2.6 */
    struct HeaderNameTokenChecker : public ValidateFunctorBase {

        const std::string& headerName;

        explicit HeaderNameTokenChecker(const std::string& headerName) : headerName(headerName) {}

        virtual bool operator()() const;
        virtual std::string getMessage() const;
    };

    /** Functor implementation for check header contains colon character between name and value */
    struct ColonPresentedChecker : public ValidateFunctorBase {

        const CaptureGroups& captures;

        explicit ColonPresentedChecker(const CaptureGroups& captures) : captures(captures) {}

        virtual bool operator()() const;
        virtual std::string getMessage() const;
    };

    /** Functor implementation to check Headers duplicity */
    struct HeadersDuplicateChecker : public ValidateFunctorBase {

        const Header& header;
        const Headers& headers;

        explicit HeadersDuplicateChecker(const Header& header, const Headers& headers)
            : header(header), headers(headers)
        {
        }

        virtual bool operator()() const;
        virtual std::string getMessage() const;
    };

    /** Functor implementation to check Headers duplicity */
    struct HeaderValuePresentedChecker : public ValidateFunctorBase {

        const Header& header;

        explicit HeaderValuePresentedChecker(const Header& header) : header(header) {}

        virtual bool operator()() const;
        virtual std::string getMessage() const;
    };

    /** Functor receive and invoke individual Validators and conditionally push reports  */
    struct HeaderParserValidator {

        const ParseResultRef<Headers>& out;
        mdp::CharactersRangeSet sourceMap;

        HeaderParserValidator(const ParseResultRef<Headers>& out, mdp::CharactersRangeSet sourceMap)
            : out(out), sourceMap(sourceMap)
        {
        }

        bool operator()(const ValidateFunctorBase& rule);
    };

    /**
     *  Headers Section Processor
     */
    template <>
    struct SectionProcessor<Headers> : public SectionProcessorBase<Headers> {

        static MarkdownNodeIterator processSignature(const MarkdownNodeIterator& node,
            const MarkdownNodes& siblings,
            SectionParserData& pd,
            SectionLayout& layout,
            const ParseResultRef<Headers>& out)
        {

            mdp::ByteBuffer content;
            CodeBlockUtility::signatureContentAsCodeBlock(node, pd, out.report, content);

            // drop first line (it contain " + Headers")
            // we need just "content"
            mdp::BytesRangeSet::const_iterator begin = node->sourceMap.begin();
            begin++;

            headersFromContent(node, begin, node->sourceMap.end(), pd, out);

            return ++MarkdownNodeIterator(node);
        }

        NO_SECTION_DESCRIPTION(Headers)

        static MarkdownNodeIterator processContent(const MarkdownNodeIterator& node,
            const MarkdownNodes& siblings,
            SectionParserData& pd,
            const ParseResultRef<Headers>& out)
        {

            mdp::ByteBuffer content;
            CodeBlockUtility::contentAsCodeBlock(node, pd, out.report, content);

            headersFromContent(node, node->sourceMap.begin(), node->sourceMap.end(), pd, out);

            return ++MarkdownNodeIterator(node);
        }

        static bool isContentNode(const MarkdownNodeIterator& node, SectionType sectionType)
        {

            return (SectionKeywordSignature(node) == UndefinedSectionType);
        }

        static SectionType sectionType(const MarkdownNodeIterator& node)
        {

            if (node->type == mdp::ListItemMarkdownNodeType && !node->children().empty()) {

                mdp::ByteBuffer subject = node->children().front().text;
                mdp::ByteBuffer signature;
                mdp::ByteBuffer remainingContent;

                signature = GetFirstLine(subject, remainingContent);
                TrimString(signature);

                if (RegexMatch(signature, HeadersRegex))
                    return HeadersSectionType;
            }

            return UndefinedSectionType;
        }

        static void finalize(
            const MarkdownNodeIterator& node, SectionParserData& pd, const ParseResultRef<Headers>& out)
        {

            if (out.node.empty()) {

                // WARN: No valid headers defined
                mdp::CharactersRangeSet sourceMap
                    = mdp::BytesRangeSetToCharactersRangeSet(node->sourceMap, pd.sourceCharacterIndex);
                out.report.warnings.push_back(Warning("no valid headers specified", FormattingWarning, sourceMap));
            }
        }

        /**
         * Parse individual line of header
         * \return true if valid header definition
         *
         * Header name is checked against token definition
         *
         * \param line - contains individual line with header definition
         * \param header - is filled by name and value if definition is valid
         * \param out - "report" member can receive warning while checking validity
         * \param sourceMap - just contain source mapping for warning report
         */
        static bool parseHeaderLine(const mdp::ByteBuffer& line,
            Header& header,
            const ParseResultRef<Headers>& out,
            const mdp::CharactersRangeSet sourceMap)
        {

            std::string re = "^ *([^:[:blank:]]+)(( *:? *)(.*)?)$";

            CaptureGroups parts;
            bool matched = RegexCapture(line, re, parts, 5);

            if (!matched) {
                // WARN: unable to parse header
                out.report.warnings.push_back(Warning(
                    "unable to parse HTTP header, expected '<header name> : <header value>', one header per line",
                    FormattingWarning,
                    sourceMap));
                return false;
            }

            header = std::make_pair(parts[1], parts[4]);
            TrimString(header.second);

            HeaderParserValidator validate(out, sourceMap);

            if (!validate(HeaderNameTokenChecker(header.first))) {
                return false;
            }

            validate(ColonPresentedChecker(parts));
            validate(HeadersDuplicateChecker(header, out.node));
            validate(HeaderValuePresentedChecker(header));

            return !header.first.empty();
        }

        static bool fetchLine(const std::string& input, mdp::BytesRange& map, std::string& line)
        {

            if (input.length() < (map.location + map.length)) {
                return false;
            }

            TrimRange trim = GetTrimInfo(input.begin() + map.location, input.begin() + map.location + map.length);

            map.length = std::get<1>(trim);

            if (map.length <= 0) {
                return false;
            }

            map.location += std::get<0>(trim);

            line = input.substr(map.location, map.length);

            return true;
        }

        static bool isCodeFence(const std::string& line)
        {
            return (!memcmp(line.c_str(), "```", 3) || !memcmp(line.c_str(), "~~~", 3));
        }

        /** Retrieve headers from content */
        static void headersFromContent(const MarkdownNodeIterator& node,
            mdp::BytesRangeSet::const_iterator from,
            mdp::BytesRangeSet::const_iterator to,
            const SectionParserData& pd,
            const ParseResultRef<Headers>& out)
        {

            bool inCodeFence = false;

            for (mdp::BytesRangeSet::const_iterator it = from; it != to; it++) {

                mdp::BytesRange map(*it);
                std::string line;

                if (!fetchLine(pd.sourceData, map, line)) {
                    continue;
                }

                if (it == from) {
                    inCodeFence = isCodeFence(line);
                };

                if (inCodeFence && isCodeFence(line)) {
                    continue;
                }

                Header header;

                mdp::BytesRangeSet byteMap;
                byteMap.push_back(map);
                mdp::CharactersRangeSet sourceMap
                    = mdp::BytesRangeSetToCharactersRangeSet(byteMap, pd.sourceCharacterIndex);

                if (parseHeaderLine(line, header, out, sourceMap)) {
                    out.node.push_back(header);

                    if (pd.exportSourceMap()) {
                        SourceMap<Header> headerSM;
                        headerSM.sourceMap = sourceMap;
                        out.sourceMap.collection.push_back(headerSM);
                    }
                }
            }
        }

        /** Inject headers into transaction examples requests and responses */
        static void injectDeprecatedHeaders(SectionParserData& pd,
            const Headers& headers,
            const SourceMap<Headers>& headersSM,
            TransactionExamples& examples,
            SourceMap<TransactionExamples>& examplesSM)
        {

            Collection<TransactionExample>::iterator exampleIt = examples.begin();
            Collection<SourceMap<TransactionExample> >::iterator exampleSourceMapIt;

            if (pd.exportSourceMap()) {
                exampleSourceMapIt = examplesSM.collection.begin();
            }

            while (exampleIt != examples.end()) {

                Collection<Request>::iterator requestIt = exampleIt->requests.begin();
                Collection<SourceMap<Request> >::iterator requestSourceMapIt;

                if (pd.exportSourceMap()) {
                    requestSourceMapIt = exampleSourceMapIt->requests.collection.begin();
                }

                // Requests
                while (requestIt != exampleIt->requests.end()) {

                    requestIt->headers.insert(requestIt->headers.begin(), headers.begin(), headers.end());
                    ++requestIt;

                    if (pd.exportSourceMap()) {
                        requestSourceMapIt->headers.collection.insert(requestSourceMapIt->headers.collection.begin(),
                            headersSM.collection.begin(),
                            headersSM.collection.end());
                        ++requestSourceMapIt;
                    }
                }

                Collection<Response>::iterator responseIt = exampleIt->responses.begin();
                Collection<SourceMap<Response> >::iterator responseSourceMapIt;

                if (pd.exportSourceMap()) {
                    responseSourceMapIt = exampleSourceMapIt->responses.collection.begin();
                }

                // Responses
                while (responseIt != exampleIt->responses.end()) {

                    responseIt->headers.insert(responseIt->headers.begin(), headers.begin(), headers.end());
                    ++responseIt;

                    if (pd.exportSourceMap()) {
                        responseSourceMapIt->headers.collection.insert(responseSourceMapIt->headers.collection.begin(),
                            headersSM.collection.begin(),
                            headersSM.collection.end());
                        ++responseSourceMapIt;
                    }
                }

                ++exampleIt;

                if (pd.exportSourceMap()) {
                    ++exampleSourceMapIt;
                }
            }
        }
    };

    /** Headers Section Parser */
    typedef SectionParser<Headers, ListSectionAdapter> HeadersParser;
}

#endif


text:
import numpy as np
import pandas as pd
import statsmodels.api as sm
import time
import random
from multiprocessing import Pool, TimeoutError
import os
from math import isclose

def import_data(path, response, key):
    # path, response, key: string

    # numpy import is real slow, even compared to pandas import with conversion
    data = pd.read_csv(path).as_matrix()

    # Manual indexing in numpy is super fast compared to pandas selection
    r = data[:, 0].copy()
    k = data[:, 6].copy()
    data = data[:, 1:6]

    # add constant
    data = np.column_stack((data, np.ones((data.shape[0], 1))))

    return data, r, k

def score_stat(residuals, variance, key_var):
    # residuals, variance, key_var : 1d np arrays
    key_var_sq = key_var**2

    score_numerator = (residuals.transpose().dot(key_var))**2
    score_denominator = key_var_sq.transpose().dot(variance)
    score = score_numerator/score_denominator

    return score

def null_score_stat(X, y, key_var):
    # X : 2d np array
    # y : 1d np array 0-1-2
    # key_var : 1d np array

    # key_var = X[key].copy()

    logreg = sm.Logit(y, X)
    fit = logreg.fit()

    fitted = fit.predict(X)

    residuals = y - fitted

    variance = fitted * (1 - fitted)

    score = score_stat(residuals, variance, key_var)

    return score, residuals, variance

def g(_):

    # sample random set of indices.
    # Faster than numpy or random

    # Generate and sort random ints.
    ints = state.randint(0, NROW, int(1.02 * NUM_NONZERO))
    ints.sort()

    # Take uniques by grabbing locations array[N] != array[N - 1].
    # We prepend 'True' so as to not throw away the first value and skew the
    # sampling distribution
    uniques = ints[
        np.concatenate(
            (np.array([True]), ints[1:] != ints[:-1])
        )
    ]

    # If the first pass does not return a list of length >= NUM_NONZERO
    while len(uniques) < NUM_NONZERO:

        ints = state.randint(0, NROW, NUM_NONZERO-len(uniques))
        ints.sort()

        more_uniques = ints[
            np.concatenate(
                (np.array([True]), ints[1:] != ints[:-1])
            )
        ]

        uniques = np.concatenate(
            (uniques, more_uniques)
        )

    np.random.shuffle(uniques)

    # In case we generated more than we need.
    uniques = uniques[:NUM_NONZERO]

    # Score Stat calculation
    key_var = perm_key_var
    key_var_sq = key_var**2
    residuals = null_residuals[uniques]
    variance  = null_variance[uniques]

    score_numerator = (residuals.dot(key_var))**2
    score_denominator = key_var_sq.dot(variance)
    score = score_numerator/score_denominator

    return score

if __name__ =='__main__':
    state = np.random.RandomState()

    KEY = 'X_1'
    RESPONSE = 'Y'
    NUM_PERMUTATIONS = 10**7

    data, response, key_var = import_data('data/data.csv', RESPONSE, KEY)
    NROW = len(response)

    NUM_ONES = sum(key_var == 1)
    NUM_TWOS = sum(key_var == 2)
    NUM_NONZERO = NUM_ONES + NUM_TWOS

    # Logistic Regression Score Test
    time1 = time.time()

    null_score, null_residuals, null_variance = null_score_stat(data, response, key_var)

    if not isclose(null_score, 2.2678647166344645):
        raise AssertionError('Observed Value of Score is Wrong!')

    # Instead of permuting the entire column, which is mostly 0s,
    # we permute the indices for 1s and 2s, and fill in the column
    perm_key_var = np.concatenate((np.ones(NUM_ONES), np.ones(NUM_TWOS) + 1))

    with Pool(processes=os.cpu_count()) as pool:
        perm_scores = pool.imap_unordered(g, range(NUM_PERMUTATIONS))
        # perm_scores = map(g, range(NUM_PERMUTATIONS))
        p_value = sum([(s > null_score) for s in perm_scores])/(NUM_PERMUTATIONS + 1)

    print(p_value)
    time2 = time.time()
    print(time2 - time1)


text:
import normalize from './normalize'

const read = (path, data) => {
  const location = normalize(path)
  let value = data
  let i

  for (let i = 0; i < location.length; i++) {
    if (value === null || typeof value !== 'object') {
      return undefined
    }

    value = value[location[i]]

    if (value === undefined) {
      return undefined
    }
  }

  return value
}

export default read


text:
@class HTTPServer;

@interface HTTPResponseHandler : NSObject
{
	CFHTTPMessageRef request;
	NSString *requestMethod;
	NSDictionary *headerFields;
	NSFileHandle *fileHandle;
	HTTPServer *server;
	NSURL *url;
}

+ (NSUInteger)priority;
+ (void)registerHandler:(Class)handlerClass;

+ (HTTPResponseHandler *)handlerForRequest:(CFHTTPMessageRef)aRequest
	fileHandle:(NSFileHandle *)requestFileHandle
	server:(HTTPServer *)aServer;

- (id)initWithRequest:(CFHTTPMessageRef)aRequest
	method:(NSString *)method
	url:(NSURL *)requestURL
	headerFields:(NSDictionary *)requestHeaderFields
	fileHandle:(NSFileHandle *)requestFileHandle
	server:(HTTPServer *)aServer;
- (void)startResponse;
- (NSString *)serverIPForRequest;
- (void)endResponse;

@end


text:
package eu.socialsensor.framework.common.domain;

/**
 * This class stores the sentiment information of the specific DySCO object.
 * @author etzoannos
 */
public class Sentiment {

}


text:
import os
from django.core.management.base import NoArgsCommand
from optparse import make_option

class Command(NoArgsCommand):
    option_list = NoArgsCommand.option_list + (
        make_option('--plain', action='store_true', dest='plain',
            help='Tells Django to use plain Python, not IPython.'),
    )
    help = "Runs a Python interactive interpreter. Tries to use IPython, if it's available."
    shells = ['ipython', 'bpython']
    requires_model_validation = False

    def ipython(self):
        try:
            from IPython import embed
            embed()
        except ImportError:
            # IPython < 0.11
            # Explicitly pass an empty list as arguments, because otherwise
            # IPython would use sys.argv from this script.
            try:
                from IPython.Shell import IPShell
                shell = IPShell(argv=[])
                shell.mainloop()
            except ImportError:
                # IPython not found at all, raise ImportError
                raise

    def bpython(self):
        import bpython
        bpython.embed()

    def run_shell(self):
        for shell in self.shells:
            try:
                return getattr(self, shell)()
            except ImportError:
                pass
        raise ImportError

    def handle_noargs(self, **options):
        # XXX: (Temporary) workaround for ticket #1796: force early loading of all
        # models from installed apps.
        from django.db.models.loading import get_models
        get_models()

        use_plain = options.get('plain', False)

        try:
            if use_plain:
                # Don't bother loading IPython, because the user wants plain Python.
                raise ImportError
            self.run_shell()
        except ImportError:
            import code
            # Set up a dictionary to serve as the environment for the shell, so
            # that tab completion works on objects that are imported at runtime.
            # See ticket 5082.
            imported_objects = {}
            try: # Try activating rlcompleter, because it's handy.
                import readline
            except ImportError:
                pass
            else:
                # We don't have to wrap the following import in a 'try', because
                # we already know 'readline' was imported successfully.
                import rlcompleter
                readline.set_completer(rlcompleter.Completer(imported_objects).complete)
                readline.parse_and_bind("tab:complete")

            # We want to honor both $PYTHONSTARTUP and .pythonrc.py, so follow system
            # conventions and get $PYTHONSTARTUP first then import user.
            if not use_plain:
                pythonrc = os.environ.get("PYTHONSTARTUP")
                if pythonrc and os.path.isfile(pythonrc):
                    try:
                        execfile(pythonrc)
                    except NameError:
                        pass
                # This will import .pythonrc.py as a side-effect
                import user
            code.interact(local=imported_objects)


text:
package main

import (

	//_ "net/http/pprof" // Activate pprof for profiling
	"fmt"
	"os"
	"os/signal"
	"syscall"
	"time"

	"github.com/themotion/ladder/autoscaler"
	"github.com/themotion/ladder/autoscaler/arrange"
	"github.com/themotion/ladder/autoscaler/filter"
	"github.com/themotion/ladder/autoscaler/gather"
	"github.com/themotion/ladder/autoscaler/scale"
	"github.com/themotion/ladder/autoscaler/solve"
	"github.com/themotion/ladder/config"
	"github.com/themotion/ladder/log"
	"github.com/themotion/ladder/plugin"
	"github.com/themotion/ladder/version"
	"github.com/themotion/ladder/web"
	"github.com/themotion/ladder/web/api/v1"

	// Register app healthcheck
	"github.com/themotion/ladder/health"

	// Register metrics
	_ "github.com/themotion/ladder/metrics"

	// Register blocks
	_ "github.com/themotion/ladder/autoscaler/arrange/common"
	_ "github.com/themotion/ladder/autoscaler/filter/aws"
	_ "github.com/themotion/ladder/autoscaler/filter/common"
	_ "github.com/themotion/ladder/autoscaler/gather/aws"
	_ "github.com/themotion/ladder/autoscaler/gather/common"
	_ "github.com/themotion/ladder/autoscaler/gather/metrics"
	_ "github.com/themotion/ladder/autoscaler/scale/aws"
	_ "github.com/themotion/ladder/autoscaler/scale/common"
	_ "github.com/themotion/ladder/autoscaler/solve/common"
)

func clean() error {
	log.Logger.Infof("Cleaning before exiting")
	time.Sleep(1 * time.Second)
	return nil
}

func main() {
	// Run main program
	exCode := Main()

	// Clean
	err := clean()

	if err != nil {
		log.Logger.Errorf("Cleanig error: %v", err)
		exCode = 1
	}

	if exCode == 0 {
		log.Logger.Infof("Good bye!")
	} else {
		log.Logger.Infof("Good bye! (with errors)")
	}

	os.Exit(exCode)
}

// Main is the main process of Ladder
func Main() int {
	// Parse command line flags
	if err := parse(os.Args[1:]); err != nil {
		log.Logger.Error(err)
		return 1
	}

	verStr := version.Get().String()
	// Show version
	if cfg.showVersion {
		fmt.Println(verStr)
		return 0
	}

	// Set up logger
	lFields := log.Fields{
		"dryrun":  cfg.dryRun,
		"version": verStr,
	}
	log.Setup(os.Stderr, lFields, cfg.jsonLog, cfg.debug)

	// Load debug if required
	if cfg.debug {
		// Register dummy blocks
		gather.Register("dummy", &gather.DummyCreator{})
		arrange.Register("dummy", &arrange.DummyCreator{})
		scale.Register("dummy", &scale.DummyCreator{})
		solve.Register("dummy", &solve.DummyCreator{})
		filter.Register("dummy", &filter.DummyCreator{})
	}

	// Load config file configuration
	c, err := config.LoadConfig(cfg.configFile)
	if err != nil {
		log.Logger.Errorf("Error starting ladder: %s", err)
		return 1
	}

	// Load config plugins
	log.Logger.Infof("Loading plugins")
	pl, err := plugin.NewBaseLoader()
	if err != nil {
		log.Logger.Errorf("Error Creating plugin loader: %s", err)
	}

	if err := pl.LoadFromConfig(c); err != nil {
		log.Logger.Errorf("Error loading plugins: %s", err)
		return 1
	}

	// Set the flags config on the global config so it passes around the program
	c.Debug = cfg.debug
	c.DryRun = cfg.dryRun

	log.Logger.Infof("Ladder ready to rock!")
	log.Logger.Infof("Starting...")
	if c.DryRun {
		log.Logger.Warningf("Ladder will run in dry run mode!!")
	}

	// check if there are no autoscalers
	if len(c.Autoscalers) == 0 {
		log.Logger.Warningf("No autoscalers present")
		return 0
	}

	// Create an error channel
	errChan := make(chan error)

	// Create all the scalers
	autoscalers := map[string]autoscaler.Autoscaler{}
	for _, ac := range c.Autoscalers {
		if ac.Disabled {
			log.Logger.Warningf("%s autoscaler is disabled, not loading it", ac.Name)
			continue
		}
		// We need to pass the config pointer to copy, if we pass directly
		// then all the autoscalers will point to the same object
		act := ac
		as, err2 := autoscaler.NewIntervalAutoscaler(&act, c.DryRun)
		if err2 != nil {
			log.Logger.Errorf("Error creating autoscaler %s: %v", ac.Name, err2)
			return 1
		}
		autoscalers[as.Name] = as
	}
	log.Logger.Debugf("%d autoscalers created", len(autoscalers))

	// If all autoscalers ok then run them
	for k := range autoscalers {
		// Don't iterate over autoscalers getting them so we don't have to copy it to
		// pass to the goroutine. Note that this is made because loops reuse the same variable
		// in all iterations.
		// Istead we take the key and get from the map directly
		go func(asName string) {
			errChan <- autoscalers[asName].Run()
		}(k)
	}
	log.Logger.Debugf("%d autoscalers running", len(autoscalers))

	// Create our HTTP handler
	api, err := v1.NewAPIV1(c.Global.APIV1Path, autoscalers)
	if err != nil {
		log.Logger.Errorf("Error creating API handler: %v", err)
		return 1
	}
	h, err := web.NewHandler(c, health.MainCheck, api)
	if err != nil {
		log.Logger.Errorf("Error creating http handler: %v", err)
		return 1
	}
	// Serve
	go func() {
		errChan <- h.Serve(cfg.listenAddress)
	}()

	// Wait until signal (ctr+c, SIGTERM...)
	sigC := make(chan os.Signal, 1)
	signal.Notify(sigC, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT)

	// Wait for goroutines
	for {
		select {
		// Wait for errors
		case err := <-errChan:
			if err != nil {
				log.Logger.Error(err)
				return 1
			}
			// Wait for signal
		case <-sigC:
			return 0
		}
	}
}


text:
from setuptools import setup

with open('README.rst') as file:
    long_description = file.read()

setup(name='py_easy_async',
      version='0.1.2',
      description='Provides simple interface for threading to easy perform async actions',
      long_description=long_description,
      author='Petrovskyi Anatolii',
      author_email='inbox@toxa.io',
      url='https://github.com/aka-toxa/py_easy_async',
      packages=['py_easy_async'],
      license='MIT',
      package_data={
        # Include readme and license
        '': ['LICENSE', 'README.rst'],
      },
      classifiers=[
                  'License :: OSI Approved :: MIT License',
                  'Intended Audience :: Developers',
                  'Programming Language :: Python :: 3.4',
                  'Programming Language :: Python :: 3.5',
                  'Topic :: Software Development :: Libraries',
                  'Development Status :: 4 - Beta'
      ])


text:
package io.fabric8.kubernetes.client.mock;

import io.fabric8.kubernetes.api.model.PodListBuilder;
import io.fabric8.kubernetes.client.Config;
import io.fabric8.kubernetes.client.ConfigBuilder;
import io.fabric8.kubernetes.client.DefaultKubernetesClient;
import io.fabric8.kubernetes.client.KubernetesClient;
import io.fabric8.kubernetes.client.server.mock.KubernetesServer;
import org.junit.Rule;
import org.junit.Test;

public class HttpServerTest {
  @Rule
  public KubernetesServer server = new KubernetesServer(false);

  @Test
  public void testListWithTrustCerts() {
   server.expect().withPath("/api/v1/namespaces/test/pods").andReturn(200, new PodListBuilder().build()).once();
    //We override the config to create a client that doesn't trust all certs.
    Config override = new ConfigBuilder(server.getClient().getConfiguration()).build();

    KubernetesClient client = new DefaultKubernetesClient(override);
    client.pods().list();
  }

}


text:
'use strict';

angular.module('eMarketApp').factory('AdminInfo', function() {
  return {
    'adminInfo': {}
  };
});


text:
package seedu.geekeep.storage;

import java.io.IOException;
import java.util.Optional;

import seedu.geekeep.commons.exceptions.DataConversionException;
import seedu.geekeep.model.ReadOnlyGeeKeep;

/**
 * Represents a storage for {@link seedu.geekeep.model.GeeKeep}.
 */
public interface GeeKeepStorage {

    /**
     * Returns the file path of the data file.
     */
    String getGeeKeepFilePath();

    //@@author A0147622H
    /**
     * Set the file path of the data file.
     */
    void setGeeKeepFilePath(String filePath);

    //@@author
    /**
     * Returns GeeKeep data as a {@link ReadOnlyGeeKeep}.
     *   Returns {@code Optional.empty()} if storage file is not found.
     * @throws DataConversionException if the data in storage is not in the expected format.
     * @throws IOException if there was any problem when reading from the storage.
     */
    Optional<ReadOnlyGeeKeep> readGeeKeep() throws DataConversionException, IOException;

    /**
     * @see #getGeeKeepFilePath()
     */
    Optional<ReadOnlyGeeKeep> readGeeKeep(String filePath) throws DataConversionException, IOException;

    /**
     * Saves the given {@link ReadOnlyGeeKeep} to the storage.
     * @param geeKeep cannot be null.
     * @throws IOException if there was any problem writing to the file.
     */
    void saveGeeKeep(ReadOnlyGeeKeep geeKeep) throws IOException;

    /**
     * @see #saveGeeKeep(ReadOnlyGeeKeep)
     */
    void saveGeeKeep(ReadOnlyGeeKeep geeKeep, String filePath) throws IOException;

}