text:
package com.example.bounceme;

import java.util.Random;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

class PlaySurfaceView extends SurfaceView implements Runnable,
		SensorEventListener {
	private int VIEW_WIDTH, VIEW_HEIGHT;
	private Thread thread = null;
	private SurfaceHolder surfaceHolder;
	private volatile boolean running = false;
	private int touchX = 0;
	private int levelNum;
	private SensorManager sensorManager;

	private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
	Random random;

	private Level level;
	private boolean acc;

	public PlaySurfaceView(Context context, int num) {
		super(context);
		levelNum = num;
		surfaceHolder = getHolder();

		// reading for prefs whether the user wants to use the accelerometer for
		// movement or not
		SharedPreferences prefs = context.getSharedPreferences("prefs", Context.MODE_PRIVATE);
		acc = prefs.getBoolean("acc", false);

		if (acc) {
			sensorManager = (SensorManager) context.getSystemService("sensor");
		}
	}

	public PlaySurfaceView(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	public PlaySurfaceView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
	}

	public void onResumeMySurfaceView() {
		running = true;
		thread = new Thread(this);
		thread.start();
		if(acc){
			sensorManager.registerListener(this,
				sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
				SensorManager.SENSOR_DELAY_NORMAL);
		}
	}

	public void onPauseMySurfaceView() {
		boolean retry = true;
		running = false;
		while (retry) {
			try {
				thread.join();
				retry = false;
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	public boolean onTouchEvent(MotionEvent event) {
		//if we are not using the accelerometer then we check if the screen is being touched
		if (!acc) {

			//we get the location of the and the status of it and send to ball class for calculating movement
			int action = event.getAction();
			switch (action) {
			case MotionEvent.ACTION_DOWN:
				//if the touch was on the left we give a negative else we give a poitive indicating movement direction
				if (event.getX() < VIEW_WIDTH / 2) {
					touchX = -2;
				} else {
					touchX = 2;
				}
				break;
			case MotionEvent.ACTION_MOVE:
				break;
			case MotionEvent.ACTION_UP:
				touchX = 0;
				break;
			case MotionEvent.ACTION_CANCEL:
				touchX = 0;
				break;
			case MotionEvent.ACTION_OUTSIDE:
				touchX = 0;
				break;

			}
		}
		return true;
	}

	@Override
	public void onSensorChanged(SensorEvent event) {
		float x = event.values[1];
		if (x < -2) {
			if (x > -5) {
				touchX = -1;
			} else {
				touchX = -2;
			}
		} else if (x > 2) {
			if (x < 5) {
				touchX = 1;
			} else {
				touchX = 2;
			}
		} else {
			touchX = 0;
		}
	}

	// the physics thread where the magic happens and all objects are drawn and
	// updated
	@Override
	public void run() {
		paint.setColor(getResources().getColor(R.color.orange));

		// TODO Auto-generated method stub
		while (true) {
			if (surfaceHolder.getSurface().isValid()) {
				Canvas canvas = surfaceHolder.lockCanvas();
				level = new Level(levelNum, canvas.getWidth(),
						canvas.getHeight());
				surfaceHolder.unlockCanvasAndPost(canvas);
				break;
			}
		}

		while (running) {
			if (surfaceHolder.getSurface().isValid()) {
				Canvas canvas = surfaceHolder.lockCanvas();
				// we lock the canvas so that we can draw our new items on it
				int w = canvas.getWidth();
				int h = canvas.getHeight();

				// check if the screen is currently being touched
				level.moveBall(touchX);

				// drawing a rectangle in the background to erase previous
				// drawings
				canvas.drawRect(0, 0, w, h, paint);

				// updating our element's positions and drawing them
				String result = level.animate(canvas, w, h);

				if (result == "reset") {
					((levelGen) getContext()).restart();
				} else if (result == "win") {
					Context context = getContext(); // from
													// MySurfaceView/Activity
					Intent intent = new Intent(context, WinActivity.class);
					intent.putExtra("level", levelNum);
					context.startActivity(intent);
				}

				// we now unlock the canvas and display the newly drawn items
				surfaceHolder.unlockCanvasAndPost(canvas);
			}

		}
	}

	// resets the ball on the level
	public void reset() {
		level.reset();
	}

	// accellerometer accuracy change listener
	@Override
	public void onAccuracyChanged(Sensor arg0, int arg1) {
		// TODO Auto-generated method stub

	}

	// sets the initial width and height for the view (also sets the width and
	// height if there is every a change to them)
	public void onSizeChanged(int w, int h, int ow, int oh) {
		VIEW_WIDTH = w;
		VIEW_HEIGHT = h;
		Log.d("OUTPUT", "(" + VIEW_WIDTH + "," + VIEW_HEIGHT + ")");
	}
}


text:
<?php

namespace Cartalyst\Stripe\Tests\Api;

use Cartalyst\Stripe\Tests\FunctionalTestCase;
use Cartalyst\Stripe\Exception\NotFoundException;

class SkusTest extends FunctionalTestCase
{
    /** @test */
    public function it_can_create_a_new_sku()
    {
        $product = $this->createProduct();

        $sku = $this->createSku($product['id']);

        $this->assertSame(1500, $sku['price']);
    }

    /** @test */
    public function it_can_find_an_existing_sku()
    {
        $product = $this->createProduct();

        $sku = $this->createSku($product['id']);

        $sku = $this->stripe->skus()->find($sku['id']);

        $this->assertSame(1500, $sku['price']);
    }

    /** @test */
    public function it_will_throw_an_exception_when_searching_for_a_non_existing_sku()
    {
        $this->expectException(NotFoundException::class);

        $this->stripe->skus()->find(time());
    }

    /** @test */
    public function it_can_update_an_existing_sku()
    {
        $product = $this->createProduct();

        $sku = $this->createSku($product['id']);

        $sku = $this->stripe->skus()->update($sku['id'], [
            'metadata' => [ 'description' => 'Comfortable gray cotton t-shirt' ]
        ]);

        $this->assertSame(1500, $sku['price']);
        $this->assertSame('Comfortable gray cotton t-shirt', $sku['metadata']['description']);
    }

    /** @test */
    public function it_can_delete_an_existing_sku()
    {
        $product = $this->createProduct();

        $sku = $this->createSku($product['id']);

        $sku = $this->stripe->skus()->delete($sku['id']);

        $this->assertTrue($sku['deleted']);
    }

    /** @test */
    public function it_can_retrieve_all_skus()
    {
        $product = $this->createProduct();

        $this->createSku($product['id']);

        $skus = $this->stripe->skus()->all();

        $this->assertNotEmpty($skus['data']);
        $this->assertIsArray($skus['data']);
    }
}

redpajama_set_name: RedPajamaGithub


text:
// <boost/thread/mutex.hpp>

// <mutex>

// template <class Mutex>
// class unlock_guard
// {
// public:
//     typedef Mutex mutex_type;
//     ...
// };

#include <boost/thread/mutex.hpp>
#include <boost/thread/reverse_lock.hpp>
#include <boost/thread/lock_types.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/static_assert.hpp>
#include <boost/type_traits/is_same.hpp>
#include <boost/detail/lightweight_test.hpp>

int main()
{
  BOOST_STATIC_ASSERT_MSG((boost::is_same<boost::reverse_lock<boost::unique_lock<boost::mutex> >::mutex_type,
      boost::mutex>::value), "");

  return boost::report_errors();
}


text:
module HasLiquidPartials
  extend ActiveSupport::Concern

  included do
    validate :no_unknown_partials
  end

  def no_unknown_partials
    LiquidPartial.missing_partials(partial_names).each do |name|
      errors.add :content, "includes unknown partial '#{name}'"
    end
  end

  # This method is used to find all the plugins referenced in both
  # this partial, and any partials included by this partial. It returns
  # an array of [plugin_name, plugin_ref] pairs.
  #
  # The method operates recursively by instantiating other partials
  # that are referenced in this partial and calling this method on them.
  # To avoid circular references, the recursion is only allowed to a depth
  # of 2 subpartials.
  #
  # For examples, see liquid_partial_spec.rb
  #
  def plugin_refs(ref: nil, depth: 0)
    return [] if depth > 2

    introspector = LiquidTagFinder.new(content)
    plugin_names = introspector.plugin_names
    collector = plugin_names.empty? ? [] : [[plugin_names[0], ref]]
    introspector.partial_refs.each do |partial, child_ref|
      child_partial = LiquidPartial.where(title: partial).first
      next if child_partial.blank?

      collector += child_partial.plugin_refs(ref: child_ref, depth: depth + 1)
    end
    collector.uniq
  end

  def partial_names
    LiquidTagFinder.new(content).partial_names
  end

  def partial_refs
    LiquidTagFinder.new(content).partial_refs
  end
end


text:
paper-slider
============

`paper-slider` allows user to select a value from a range of values by
moving the slider thumb.  The interactive nature of the slider makes it a
great choice for settings that reflect intensity levels, such as volume,
brightness, or color saturation.

Example:

```html
<paper-slider></paper-slider>
```

Use `min` and `max` to specify the slider range. Default is `0` to `100`. For example:
```html
<paper-slider min="10" max="200" value="110"></paper-slider>
```

### Styling slider

The following custom properties and mixins are available for styling:

Custom property | Description | Default
----------------|-------------|----------
`--paper-slider-bar-color` | The background color of the slider | `transparent`
`--paper-slider-active-color` | The progress bar color | `--google-blue-700`
`--paper-slider-secondary-color` | The secondary progress bar color | `--google-blue-300`
`--paper-slider-knob-color` | The knob color | `--google-blue-700`
`--paper-slider-disabled-knob-color` | The disabled knob color | `--google-grey-500`
`--paper-slider-pin-color` | The pin color | `--google-blue-700`
`--paper-slider-font-color` | The pin's text color | `#fff`
`--paper-slider-disabled-active-color` | The disabled progress bar color | `--google-grey-500`
`--paper-slider-disabled-secondary-color` | The disabled secondary progress bar color | `--google-grey-300`

Example:

```
paper-slider {
  --paper-slider-bar-color: #fff;
  --paper-slider-active-color: #0f9d58;
  --paper-slider-knob-color: #0f9d58;
  --paper-slider-pin-color: #0f9d58;
  --paper-slider-font-color: #0f9d58;
  --paper-slider-secondary-color: #0f9d58;
  --paper-slider-disabled-active-color: #ccc;
  --paper-slider-disabled-secondary-color: #ccc;
}
```


text:
<?php

if(!isset($GLOBALS['rw_fmeow'])) die();

Model('NoteGet');
Model('NoteCount');

if(isset($_GET['page']) && is_numeric($_GET['page']) && $_GET['page'] > 0)
    $page = $_GET['page'];
else
    $page = 1;

$pages = ceil(NoteCount('news')/$GLOBALS['per_page_4notes']);
$list = NoteGet('news', ($page-1)*$GLOBALS['per_page_4notes'], $GLOBALS['per_page_4notes']);

ViewHtmlTop("Новости", 'News.css');
ViewHeader();

?>

<?php foreach($list as $key=>$value): ?>

    <?=nl2br($value['data'])?>

<?=$value['at']?>

<?php endforeach; ?>

<?php
Resource("Paginator.php");
Paginator("News", $page, $pages);
?>


text:
package org.apache.activemq.artemis.utils;

/**
 * Utility that detects various properties specific to the current runtime
 * environment, such as JVM bitness and OS type.
 */
public final class Env {

   /** The system will change a few logs and semantics to be suitable to
    *  run a long testsuite.
    *  Like a few log entries that are only valid during a production system.
    *  or a few cases we need to know as warn on the testsuite and as log in production. */
   private static boolean testEnv = false;

   private static final String OS = System.getProperty("os.name").toLowerCase();
   private static final boolean IS_LINUX = OS.startsWith("linux");
   private static final boolean IS_64BIT = checkIs64bit();

   private Env() {

   }

   public static boolean isTestEnv() {
      return testEnv;
   }

   public static void setTestEnv(boolean testEnv) {
      Env.testEnv = testEnv;
   }

   public static boolean isLinuxOs() {
      return IS_LINUX == true;
   }

   public static boolean is64BitJvm() {
      return IS_64BIT;
   }

   private static boolean checkIs64bit() {
      //check the more used JVMs
      String systemProp;
      systemProp = System.getProperty("com.ibm.vm.bitmode");
      if (systemProp != null) {
         return "64".equals(systemProp);
      }
      systemProp = System.getProperty("sun.arch.data.model");
      if (systemProp != null) {
         return "64".equals(systemProp);
      }
      systemProp = System.getProperty("java.vm.version");
      return systemProp != null && systemProp.contains("_64");
   }
}


text:
% JPEG_WRITE  Write a JPEG object struct to a JPEG file
%
%    JPEG_WRITE(JPEGOBJ,FILENAME) Reads JPEGOBJ, a Matlab struct returned
%    by the JPEG_READ function, and writes the contents into a JPEG file
%    named FILENAME.
%
%    This software is based in part on the work of the Independent JPEG Group.
%
%    See also JPEG_READ.

% Phil Sallee, Surya De 6/2003

error("Mex routine jpeg_write.c not compiled\n");


text:
Adds an AWS::IAM::User.Policy resource property to the template.
Contains information about an attached policy.

## SYNTAX

```
Add-VSIAMUserPolicy [-PolicyDocument] <Object> [-PolicyName] <Object> [<CommonParameters>]
```

## DESCRIPTION
Adds an AWS::IAM::User.Policy resource property to the template.
Contains information about an attached policy.

An attached policy is a managed policy that has been attached to a user, group, or role.

For more information about managed policies, refer to Managed Policies and Inline Policies: https://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html in the *Using IAM* guide.

## PARAMETERS

### -PolicyDocument
The policy document.

Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iam-policy.html#cfn-iam-policies-policydocument
PrimitiveType: Json
UpdateType: Mutable

```yaml
Type: Object
Parameter Sets: (All)
Aliases:

Required: True
Position: 1
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -PolicyName
The friendly name not ARN identifying the policy.

Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iam-policy.html#cfn-iam-policies-policyname
PrimitiveType: String
UpdateType: Mutable

```yaml
Type: Object
Parameter Sets: (All)
Aliases:

Required: True
Position: 2
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### CommonParameters
This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216).

## INPUTS

## OUTPUTS

### Vaporshell.Resource.IAM.User.Policy
## NOTES

## RELATED LINKS

[http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iam-policy.html](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iam-policy.html)


text:
FROM golang:1.9.2-alpine as builder

ENV APP_DIR=/go/src/github.com/hermosa-circulo/iga-controller

RUN apk update
RUN apk upgrade
RUN apk --no-cache add git musl-dev make

COPY . $APP_DIR
WORKDIR $APP_DIR
RUN make build-server

FROM alpine:latest
COPY --from=builder /go/src/github.com/hermosa-circulo/iga-controller/iga-controller /hermosa/iga-controller
CMD ["/hermosa/iga-controller"]


text:
require File.expand_path('spec_helper', File.dirname(__FILE__) + '/../..')

java_import 'org.jruby.rack.servlet.RewindableInputStream'

describe RewindableInputStream do

  it "should read data one by one" do
    input = []; 49.times { |i| input << i }
    stream = rewindable_input_stream(input.to_java(:byte), 6, 24)

    49.times do |i|
      stream.read.should == i
    end
    3.times { stream.read.should == -1 }

    stream.rewind

    49.times do |i|
      stream.read.should == i
    end
    2.times { stream.read.should == -1 }
  end

  it "should read data than rewind and read again (in memory)" do
    @stream = it_should_read_127_bytes(32, 256)

    @stream.rewind

    it_should_read_127_bytes
  end

  it "should read data than rewind and read again (temp file)" do
    @stream = it_should_read_127_bytes(16, 64)

    @stream.rewind

    it_should_read_127_bytes
  end

  def it_should_read_127_bytes(init_size = nil, max_size = nil)
    input = []; 127.times { |i| input << i }
    stream = @stream || rewindable_input_stream(input.to_java(:byte), init_size, max_size)

    data = new_byte_array(7)
    stream.read(data, 0, 7).should == 7 # read 7 bytes
    7.times do |i|
      data[i].should == i
    end

    data = new_byte_array(42)
    stream.read(data, 10, 20).should == 20 # read 20 bytes
    10.times { |i| data[i].should == 0 }
    20.times do |i|
      data[i + 10].should == i + 7
    end
    10.times { |i| data[i + 30].should == 0 }

    data = new_byte_array(200)
    stream.read(data, 0, 200).should == 100 # read 100 bytes
    100.times do |i|
      data[i].should == i + 20 + 7
    end
    100.times { |i| data[i + 100].should == 0 }

    stream
  end

  it "should read incomplete data rewind and read until end" do
    input = []; 100.times { |i| input << i }
    stream = rewindable_input_stream(input.to_java(:byte), 10, 50)

    data = new_byte_array(110)
    stream.read(data, 0, 5).should == 5
    5.times do |i|
      data[i].should == i
    end

    stream.rewind
    stream.read(data, 5, 88).should == 88
    88.times do |i|
      data[i + 5].should == i
    end
    stream.read.should == 88
    stream.read.should == 89

    stream.rewind
    stream.read(data, 10, 33).should == 33
    33.times do |i|
      data[i + 10].should == i
    end

    stream.rewind
    stream.read(data, 0, 101).should == 100
    100.times do |i|
      data[i].should == i
    end

    stream.read.should == -1
  end

  it "should rewind unread data" do
    input = []; 100.times { |i| input << i }
    stream = rewindable_input_stream(input.to_java(:byte), 10, 50)
    stream.rewind

    data = new_byte_array(120)
    stream.read(data, 10, 110).should == 100
    100.times do |i|
      data[i + 10].should == i
    end
  end

  it "should mark and reset" do
    input = []; 100.times { |i| input << i }
    stream = rewindable_input_stream(input.to_java(:byte), 5, 20)

    15.times { stream.read }
    stream.markSupported.should == true
    stream.mark(50)

    35.times { |i| stream.read.should == 15 + i }

    stream.reset

    50.times { |i| stream.read.should == 15 + i }
    35.times { |i| stream.read.should == 65 + i }

    stream.read.should == -1
  end

  it "should read an image" do
    image = File.expand_path('../../files/image.jpg', File.dirname(__FILE__))
    file = java.io.RandomAccessFile.new(image, "r")
    file.read bytes = new_byte_array(file.length)

    stream = rewindable_input_stream(bytes)

    index = 0
    while stream.read != -1
      index += 1
    end
    index.should == file.length

    stream.rewind

    file.seek(0); index = 0
    while (byte = stream.read) != -1
      byte.should == file.read
      index += 1
    end
    index.should == file.length
  end

  it "should delete the tmp file on close" do
    class RewindableInputStream
      field_reader :bufferFilePath
    end

    input = '1234567890 42'
    stream = rewindable_input_stream(input, 10, 12)
    13.times { stream.read }

    stream.bufferFilePath.should_not be nil
    File.exist?(stream.bufferFilePath).should be true

    stream.close
    File.exist?(stream.bufferFilePath).should be false
  end

  after :all do
    tmpdir = java.lang.System.getProperty("java.io.tmpdir")
    prefix = RewindableInputStream::TMP_FILE_PREFIX
    FileUtils.rm_r Dir.glob(File.join(tmpdir, "#{prefix}*"))
  end

  private

    def rewindable_input_stream(input, buffer_size = nil, max_buffer_size = nil)
      input = to_input_stream(input) unless input.is_a?(java.io.InputStream)
      buffer_size ||= RewindableInputStream::INI_BUFFER_SIZE
      max_buffer_size ||= RewindableInputStream::MAX_BUFFER_SIZE
      RewindableInputStream.new(input, buffer_size, max_buffer_size)
    end

    def to_input_stream(content = @content)
      bytes = content.respond_to?(:to_java_bytes) ? content.to_java_bytes : content
      java.io.ByteArrayInputStream.new(bytes)
    end

    def new_byte_array(length)
      java.lang.reflect.Array.newInstance(java.lang.Byte::TYPE, length)
    end

end


text:
var AlbumsListPage = {
	init: function() {
		this.$container = $('.albums-container');
		this.render();
		this.bindEvents();
	},

	render: function() {

	},

	bindEvents: function() {
		$('.btn-favorite', this.$container).on('click', function(e) {
			e.preventDefault();

			var self = $(this);
			var url = $(this).attr('href');
			$.getJSON(url, function(result) {
				if (result.success) {
					$('.glyphicon-star', self).toggleClass('active');
				}
			});

			return false;
		});
	}
};

var SongsListPage = {
	init: function() {
		this.$container = $('.songs-container');
		this.render();
		this.bindEvents();
	},

	render: function() {

	},

	bindEvents: function() {
		$('.btn-favorite', this.$container).on('click', function(e) {
			e.preventDefault();

			var self = $(this);
			var url = $(this).attr('href');
			$.getJSON(url, function(result) {
				if (result.success) {
					$('.glyphicon-star', self).toggleClass('active');
				}
			});

			return false;
		});
	}
};

$(document).ready(function() {
	AlbumsListPage.init();
	SongsListPage.init();
});


text:
Subsonic
========

wavepipe features an emulated [Subsonic](http://www.subsonic.org/pages/index.jsp) API, which can be used with
clients which implement the Subsonic API.

There are some fundamental incompatibilities with the data model of Subsonic vs. wavepipe's own data model,
but where possible, efforts are made to emulate Subsonic in the most sane way possible.

To see which Subsonic API endpoints are currently available with wavepipe, check [GoDoc](http://godoc.org/github.com/mdlayher/wavepipe/subsonic).

Clients which are known to work include:
  - [Clementine](https://www.clementine-player.org/)
  - [Subsonic for Android](https://play.google.com/store/apps/details?id=net.sourceforge.subsonic.androidapp&hl=en)

If you find another client which works, feel free to send a pull request!  If you experience any issues using
a client, please [file an issue](https://github.com/mdlayher/wavepipe/issues)!

## Howto

The emulated Subsonic API is exposed via the same HTTP server as wavepipe's own, but is nested under the
`/subsonic` path.  In order to use the Subsonic API, you must first authenticate using wavepipe's own API.

This can be done using `curl` as follows:

```
$ curl -X POST -d "username=test&password=test&client=subsonic" http://localhost:8080/api/v0/login
```

The wavepipe API will return a [Session](http://godoc.org/github.com/mdlayher/wavepipe/data#Session) object:

```json
{
	"error": null,
	"session": {
		"id": 1,
		"userId": 1,
		"client": "subsonic",
		"expire": 1406406363,
		"key": "abcdef0123456789abcdef0123456789"
	}
}
```

Now that a wavepipe session has been generated, we may use the `key` as a "password" to access the Subsonic API.

```
$ curl http://localhost:8080/subsonic/rest/ping.view?u=test&p=abcdef0123456789abcdef0123456789&c=curl&v=1.8.0
<subsonic-response xmlns="http://subsonic.org/restapi" status="ok" version="1.8.0"></subsonic-response>
```

At this point, you have successfully authenticated to wavepipe's emulated Subsonic API.  Often, Subsonic clients
will ask for the following parameters:

| Name | Example | Description |
| :--: | :-----: | :---------: |
| host | `http://localhost:8080/subsonic` | The URL of your wavepipe server, with `/subsonic` path suffix. |
| username | `test` | The username used to authenticate to wavepipe's API. |
| password | `abcdef0123456789abcdef0123456789` | The API session key generated by wavepipe's API. |

Once these parameters have been set, you should be ready to go!

Feel free to [file an issue](https://github.com/mdlayher/wavepipe/issues) if you experience any trouble setting
up wavepipe to work with Subsonic clients.


text:
% FIXPARAMETERVALUE fix any parameter in a model to a specific value
%
%    model = FixParameterValue(model, parameter, value)
%
% The first parameter is the model to modify, the second is either the name
% of the parameter (e.g., 'g') or the number of the parameter (e.g., 1) to
% fix. The third is what value to assign that parameter.
%
% Thus, to take the StandardMixtureModel, which has a guess rate (g) and
% standard deviation (sd) parameter, and make a new model with guess rate
% fixed at 0.5 but a variable standard deviation, use:
%
%   model = FixParameterValue(StandardMixtureModel, 'g', 0.5)
%
function model = FixParameterValue(model, parameter, value)
  % turn parameter into an integer index if it is a string
  if ischar(parameter)
    parameter = find(strcmp(model.paramNames, parameter));
    if isempty(parameter)
      error('Couldn''t find that parameter!');
    end
  end

  % Adjust model functions
  model.originalNumParams = length(model.paramNames);
  model.allButFixed = (1:model.originalNumParams) ~= parameter;
  model.name = sprintf('%s with %s=%g', model.name, ...
    model.paramNames{parameter}, value);
  model.paramNames(parameter) = [];
  model.lowerbound(parameter) = [];
  model.upperbound(parameter) = [];
  model.movestd(parameter) = [];
  model.start(:, parameter) = [];

  % Adjust pdf
  model.oldPdf = model.pdf;
  model.pdf = @NewPDF;
  function p = NewPDF(data, varargin)
    newP(model.allButFixed) = varargin;
    newP{parameter} = value;
    p = model.oldPdf(data, newP{:});
  end

  % Adjust prior
  if isfield(model, 'prior')
    model.oldPrior = model.prior;
    model.prior = @NewPrior;
  end
  function r = NewPrior(p)
    newP(model.allButFixed) = p;
    newP(parameter) = value;
    r = model.oldPrior(newP);
  end

  % Adjust modelPlot
  if isfield(model, 'modelPlot')
    model.oldModelPlot = model.modelPlot;
    model.modelPlot = @NewModelPlot;
  end
  function r = NewModelPlot(data, params, varargin)
    if isstruct(params) && isfield(params, 'vals')
      newP = params;
      cnt = 1;
      for i=1:model.originalNumParams
        if i~=parameter
          newP.vals(:,i) = params.vals(:,cnt);
          cnt=cnt+1;
        else
          newP.vals(:,i) = value;
        end
      end
    else
      newP(model.allButFixed) = params;
      newP(parameter) = value;
    end
    r = model.oldModelPlot(data, newP, varargin);
  end

  % Remove any generator function - model must be sampled the hard way
  if isfield(model, 'generator')
    model = rmfield(model, 'generator');
  end
end


text:
import pytest

from pyproj import CRS, Proj
from pyproj.exceptions import CRSError, ProjError

def test_proj_exception():
    with pytest.raises(ProjError, match="Internal Proj Error"):
        Proj("+proj=bobbyjoe")

def test_crs_exception():
    with pytest.raises(CRSError, match="Internal Proj Error"):
        CRS("+proj=bobbyjoe")


text:
When the model is created, it is hard to say if it is reasonable or not, thus KAP provides a check procedure to inspect the model before building a cube with using it.

The procedure includes four small steps:

1. Check if there are the duplications in primary key of lookup tables.
2. Check if the source data of foreigner key is distributed uniformly.
3. Check if the join condition is reasonable.
4. Calculate single and double columns cardinality.

**Step1.** Start KAP and go to UI,pick a project, such as *learn_kylin*,  then click **Studio** in the left navigator, after that click **Model** tab.

![](images/model_check/24_model_diagnose_1.png)

**Step2.** For the models already exist, such as kylin_sales_model, click the menu on the top right conner and click **Check** button.

![](images/model_check/24_model_diagnose_2.png)

**Step3. Configuration**

Time Range. It asks for selecting a start time and end time if the partition column has been set during creating model. With the time range condition it could reduce the source data, instead of scanning whole data. By default, it will check the whole data.

Sampling percentage. It means it only checks the data in the given ratio, such as 50% will check one line in each two lines.

![](images/model_check/25_model_check.png)

**Step4.** After all configuration is done, click **Submit** button and it starts a check job. The job status can be observed after clicking **Monitor** in the left navigator.

![](images/model_check/24_model_diagnose_4.png)

If creating or editting a model, after clicking **save**, it shows a checkbox to ask user if starting a check model job. By default, it stats the check job.

![](images/model_check/25_model_save.png)

If the model check job is done without any exceptions, it can observe the check result on the model list. In this case, che check result is health,there are other check status and details if the model has some issues.

![](images/model_check/24_model_diagnose_6.png)

As mentioned in the beginning, The Model Check includes 3 different check tasks:

1. **Model status check**: Check if the join condition is reasonable. It will generate a flat table and check the join result. According to the result, it could have basic judgement that if the given join condition is good or bad. If the condition is totally good, there could be some issues in the source data.

2. **Fact table sampling**: Check if the source data on the foreigner key is distributed uniformly. When the data is not distributed uniformly, might cause the whole job can not finish until the latest reducer which possesses the skew data completes its task. It suggests to have some efforts to avoid the this situation before starting the cubing job.

3. **Lookup table sampling**: Check if there are the duplications in primary key of lookup tables. If there are the duplication and it is over the given threshold will terminates the check job immediately. In this case, it's better to remove the duplication.

With the above checks, it defines five model check status:

1. Not Checked Yet. Once a model is created, it will be in this state.
2. On Checking. It means a model check job is running.
3. Good Health. It means there are no any check errors .
4. Warn. It indicates there is one check error.
5. Error. It show there are at least check errors.


text:
using namespace IECoreGL;
using namespace IECore;
using namespace Imath;
using namespace std;
using namespace boost;

IE_CORE_DEFINERUNTIMETYPED( LuminanceTexture );

LuminanceTexture::LuminanceTexture( unsigned int width, unsigned int height, IECore::ConstDataPtr y, IECore::ConstDataPtr a, bool mipMap )
{
	construct( width, height, y, a, mipMap );
}

LuminanceTexture::LuminanceTexture( IECore::ConstImagePrimitivePtr image, bool mipMap )
{
	IECore::ConstDataPtr y = image->channelValid( "Y" ) ? image->variables.find( "Y" )->second.data : 0;
	IECore::ConstDataPtr a = image->channelValid( "A" ) ? image->variables.find( "A" )->second.data : 0;

	if( !y )
	{
		throw Exception( "Image must have at least a \"Y\" channel." );
	}

	int width = image->getDataWindow().size().x + 1;
	int height = image->getDataWindow().size().y + 1;
	construct( width, height, y, a, mipMap );
}

LuminanceTexture::~LuminanceTexture()
{
}

struct LuminanceTexture::Constructor
{
	typedef bool ReturnType;

	template<typename T>
	GLuint operator()( typename T::ConstPtr y )
	{
		typedef typename T::ValueType::value_type ElementType;

		const std::vector<ElementType> &ry = y->readable();
		const std::vector<ElementType> *ra = alpha ? &(staticPointerCast<const T>( alpha )->readable()) : 0;

		unsigned int n = width * height;
		if( ry.size()!=n || (ra && ra->size()!=n) )
		{
			throw IECore::Exception( "Image data has wrong size." );
		}

		std::vector<ElementType> interleaved( n * (ra ? 2 : 1) );

		unsigned int i = 0;
		for( int y=height-1; y>=0; y-- )
		{
			const ElementType *dy = &ry[y*width];
			const ElementType *da = ra ? &(*ra)[y*width] : 0;

			for( unsigned int x=0; x<width; x++ )
			{
				interleaved[i++] = dy[x];
				if( da )
				{
					interleaved[i++] = da[x];
				}
			}
		}

		glPixelStorei( GL_UNPACK_ALIGNMENT, 1 );

		if( mipMap )
		{
			gluBuild2DMipmaps( GL_TEXTURE_2D, ra ? GL_LUMINANCE_ALPHA : GL_LUMINANCE, width, height, ra ? GL_LUMINANCE_ALPHA : GL_LUMINANCE,
				NumericTraits<ElementType>::glType(), &interleaved[0] );
		}
		else
		{
			glTexImage2D( GL_TEXTURE_2D, 0, ra ? GL_LUMINANCE_ALPHA : GL_LUMINANCE, width, height, 0, ra ? GL_LUMINANCE_ALPHA : GL_LUMINANCE,
				NumericTraits<ElementType>::glType(), &interleaved[0] );
		}

		IECoreGL::Exception::throwIfError();

		return true;
	}

	unsigned width;
	unsigned height;
	bool mipMap;
	ConstDataPtr alpha;
};

void LuminanceTexture::construct( unsigned int width, unsigned int height, IECore::ConstDataPtr y, IECore::ConstDataPtr a, bool mipMap )
{
	if( a && (y->typeId() != a->typeId()) )
	{
		throw Exception( "Channel types do not match." );
	}

	glGenTextures( 1, &m_texture );
	ScopedBinding binding( *this );

	Constructor c;
	c.alpha = a;
	c.width = width;
	c.height = height;
	c.mipMap = mipMap;
	IECore::despatchTypedData<Constructor, IECore::TypeTraits::IsNumericVectorTypedData>( constPointerCast<Data>( y ), c );
}

ImagePrimitivePtr LuminanceTexture::imagePrimitive() const
{
	ScopedBinding binding( *this );

	GLint width = 0;
	GLint height = 0;
	glGetTexLevelParameteriv( GL_TEXTURE_2D, 0, GL_TEXTURE_WIDTH, &width );
	glGetTexLevelParameteriv( GL_TEXTURE_2D, 0, GL_TEXTURE_HEIGHT, &height );

	GLint aSize = 0;
	glGetTexLevelParameteriv( GL_TEXTURE_2D, 0, GL_TEXTURE_ALPHA_SIZE, &aSize );

	unsigned int numChannels = aSize ? 2 : 1;

	vector<float> data( width * height * numChannels );

	glGetTexImage( GL_TEXTURE_2D, 0, numChannels==2 ? GL_LUMINANCE_ALPHA : GL_LUMINANCE, GL_FLOAT, &data[0] );

	FloatVectorDataPtr yd = new FloatVectorData();
	vector<float> &y = yd->writable(); y.resize( width * height );

	FloatVectorDataPtr ad = 0;
	vector<float> *a = 0;
	if( aSize )
	{
		ad = new FloatVectorData();
		a = &ad->writable(); a->resize( width * height );
	}

	unsigned int i = 0;
	for( int yy=height-1; yy>=0; yy-- )
	{
		float *ry = &y[yy*width];
		float *ra = a ? &(*a)[yy*width] : 0;
		for( int x=0; x<width; x++ )
		{
			ry[x] = data[i++];
			if( ra )
			{
				ra[x] = data[i++];
			}
		}
	}

	Box2i imageExtents( V2i( 0, 0 ), V2i( width-1, height-1 ) );
	ImagePrimitivePtr image = new ImagePrimitive( imageExtents, imageExtents );
	image->variables["Y"] = PrimitiveVariable( PrimitiveVariable::Vertex, yd );
	if( a )
	{
		image->variables["A"] = PrimitiveVariable( PrimitiveVariable::Vertex, ad );
	}

	IECoreGL::Exception::throwIfError();

	return image;
}


text:
<?php

namespace Database;

use PDO;
use Object\Object;
use Database\DatabaseException;
use Database\QueryBuilder;

/**
 * Description of Database
 *
 * Works for MySQL, PostgreSQL, SQLite
 *
 * @author Zeakis George <zeageorge@gmail.com>
 */
class Database extends Object
{
    /*
     * Drivers constants
     */

    /**
     * CUBRID
     */
    const DRIVER_CUBRID = 'cubrid:';

    /**
     * FreeTDS / Microsoft SQL Server / Sybase
     */
    const DRIVER_DBLIB = 'dblib:';

    /**
     *
     */
    const DRIVER_FIREBIRD = 'firebird:';

    /**
     * IBM DB2
     * http://php.net/manual/en/ref.pdo-ibm.connection.php
     */
    const DRIVER_IBM = 'ibm:';

    /**
     * IBM Informix Dynamic Server
     */
    const DRIVER_INFORMIX = 'informix:';

    /**
     *
     */
    const DRIVER_SQLSRV = 'sqlsrv:';
    //const DRIVER_MSSQL = 'mssql:'; //

    /**
     * MySQL 3.x/4.x/5.x
     */
    const DRIVER_MYSQL = 'mysql:';

    /**
     * Oracle Call Interface
     */
    const DRIVER_OCI = 'oci:';

    /**
     * ODBC v3 (IBM DB2, unixODBC and win32 ODBC)
     */
    const DRIVER_ODBC = 'odbc:';

    /**
     * PostgreSQL
     */
    const DRIVER_PGSQL = 'pgsql:';

    /**
     * SQLite 3 and SQLite 2
     */
    const DRIVER_SQLITE = 'sqlite:';

    /**
     *
     * @param array $config
     */
    public function __construct(array $config = [])
    {
        $this->properties['pdo'] = NULL;
        $this->properties['dsn_prefix'] = NULL;
        $this->properties['host'] = NULL;
        $this->properties['port'] = -1;
        $this->properties['db_name'] = NULL;
        $this->properties['unix_socket'] = NULL;
        /**
         * @var string the charset used for database connection. The property is only used
         * for MySQL, MariaDB and PostgreSQL databases. Defaults to NULL, meaning using default charset
         * as specified by the database.
         *
         * Note that if you're using GBK or BIG5 then it's highly recommended to
         * update to PHP 5.3.6+ and to specify charset via DSN like
         * 'mysql:dbname=mydatabase;host=127.0.0.1;charset=GBK;'.
         */
        $this->properties['charset'] = 'utf8';
        /**
         * @var boolean whether to turn on prepare emulation. Defaults to FALSE, meaning PDO
         * will use the native prepare support if available. For some databases (such as MySQL),
         * this may need to be set TRUE so that PDO can emulate the prepare support to bypass
         * the buggy native prepare support. Note, this property is only effective for PHP 5.1.3 or above.
         * The default value is NULL, which will not change the ATTR_EMULATE_PREPARES value of PDO.
         */
        $this->properties['emulate_prepare'] = FALSE;
        $this->properties['fetch_mode'] = \PDO::FETCH_ASSOC;
        /**
         * For PostgreSQL is user
         */
        $this->properties['username'] = NULL;
        $this->properties['password'] = NULL;
        $this->properties['options'] = NULL;
        $this->properties['table_prefix'] = '';
        $this->properties['last_insert_id'] = -1;
        /**
         * SQLite
         */
        $this->properties['database_absolute_path'] = NULL;

        $this->properties['available_drivers'] = [
//        Database::DRIVER_CUBRID,
//        Database::DRIVER_DBLIB,
//        Database::DRIVER_FIREBIRD,
//        Database::DRIVER_IBM,
//        Database::DRIVER_INFORMIX,
//        Database::DRIVER_SQLSRV,
//        Database::DRIVER_OCI,
//        Database::DRIVER_ODBC,
            Database::DRIVER_MYSQL,
            Database::DRIVER_PGSQL,
            Database::DRIVER_SQLITE,
        ];

        parent::__construct($config);
    }

    /**
     *
     * @return PDO
     */
    protected function public__getPDOInstance()
    {
        return $this->properties['pdo'];
    }

    /**
     *
     * @return string
     */
    protected function public__getDSNPrefix()
    {
        return $this->properties['dsn_prefix'];
    }

    /**
     *
     * @return string
     */
    protected function public__getHost()
    {
        return $this->properties['host'];
    }

    /**
     *
     * @return int
     */
    protected function public__getPort()
    {
        return $this->properties['port'];
    }

    /**
     *
     * @return string
     */
    protected function public__getDbName()
    {
        return $this->properties['db_name'];
    }

    /**
     *
     * @return string
     */
    protected function public__getUnixSocket()
    {
        return $this->properties['unix_socket'];
    }

    /**
     *
     * @return string
     */
    protected function public__getCharset()
    {
        return $this->properties['charset'];
    }

    /**
     *
     * @return bool
     */
    protected function public__getEmulatePrepare()
    {
        return $this->properties['emulate_prepare'];
    }

    /**
     *
     * @return string
     */
    protected function public__getFetchMode()
    {
        return $this->properties['fetch_mode'];
    }

    /**
     *
     * @return string
     */
    protected function public__getUsername()
    {
        return $this->properties['username'];
    }

    /**
     *
     * @return string
     */
    protected function public__getPassword()
    {
        return $this->properties['password'];
    }

    /**
     *
     * @return array
     */
    protected function public__getOptions()
    {
        return $this->properties['options'];
    }

    /**
     *
     * @return string
     */
    protected function public__getTablePrefix()
    {
        return $this->properties['table_prefix'];
    }

    /**
     *
     * @return string|int
     */
    protected function public__getLastInsertId()
    {
        return $this->properties['last_insert_id'];
    }

    /**
     *
     * @return string
     */
    protected function public__getDatabaseAbsolutePath()
    {
        return $this->properties['database_absolute_path'];
    }

    /**
     *
     * @return array
     */
    protected function public__getAvailableDrivers()
    {
        return $this->properties['available_drivers'];
    }

    /**
     *
     * @return QueryBuilder
     */
    protected function public__getQueryBuilder()
    {
        return new QueryBuilder([
            'db' => $this,
        ]);
        // or
        // $qb = new QueryBuilder();
        // $qb->setDb($this);
        // return $qb;
    }

    /**
     *
     * @return string
     */
    protected function public__getDSN()
    {
        switch ($this->properties['dsn_prefix'])
        {
            case self::DRIVER_PGSQL:
                return $this->renderDsnForPgsql();
            case self::DRIVER_SQLITE:
                return $this->renderDsnForSqlite();
            case self::DRIVER_MYSQL:
                return $this->renderDsnForMySQL();
//                case self::DRIVER_CUBRID:
//                    break;
//                case self::DRIVER_DBLIB:
//                    break;
//                case self::DRIVER_IBM:
//                    break;
//                case self::DRIVER_SQLSRV:
//                    break;
//                case self::DRIVER_FIREBIRD:
//                    break;
//                case self::DRIVER_INFORMIX:
//                    break;
//                case self::DRIVER_OCI:
//                    break;
//                case self::DRIVER_ODBC:
//                    break;
            default:
                throw new DatabaseException('Invalid DSN prefix.');
        }
    }

    /**
     *
     * @param PDO $PDO_instance
     * @return \Database\Database
     */
    protected function public__setPDOInstance(PDO $PDO_instance = NULL)
    {
        $this->properties['pdo'] = $PDO_instance;
        return $this;
    }

    /**
     *
     * @param string $dsn_prefix
     * @return \Database\Database
     * @throws DatabaseException
     */
    protected function public__setDSNPrefix($dsn_prefix)
    {
        if (!\in_array($dsn_prefix, $this->getAvailableDrivers()))
        {
            throw new DatabaseException("PDO driver [$dsn_prefix] is not supported.");
        }

        if (!\in_array(\rtrim($dsn_prefix, ':'), \PDO::getAvailableDrivers()))
        {
            throw new DatabaseException("PDO driver [$dsn_prefix] is not loaded.");
        }

        $this->properties['dsn_prefix'] = $dsn_prefix;
        return $this;
    }

    /**
     *
     * @param string $host
     * @return \Database\Database
     */
    protected function public__setHost($host)
    {
        $this->properties['host'] = $host;
        return $this;
    }

    /**
     *
     * @param int $port
     * @return \Database\Database
     */
    protected function public__setPort($port)
    {
        $this->properties['port'] = $port;
        return $this;
    }

    /**
     *
     * @param string $db_name
     * @return \Database\Database
     */
    protected function public__setDbName($db_name)
    {
        $this->properties['db_name'] = $db_name;
        return $this;
    }

    /**
     *
     * @param string $unix_socket
     * @return \Database\Database
     */
    protected function public__setUnixSocket($unix_socket)
    {
        $this->properties['unix_socket'] = $unix_socket;
        return $this;
    }

    /**
     *
     * @param string $charset
     * @return \Database\Database
     */
    protected function public__setCharset($charset)
    {
        $this->properties['charset'] = $charset;
        return $this;
    }

    /**
     *
     * @param boolean $emulate_prepare
     * @return \Database\Database
     */
    protected function public__setEmulatePrepare($emulate_prepare)
    {
        $this->properties['emulate_prepare'] = $emulate_prepare;
        return $this;
    }

    /**
     *
     * @param int $fetch_mode \PDO::FETCH_*
     * @return \Database\Database
     */
    protected function public__setFetchMode($fetch_mode)
    {
        $this->properties['fetch_mode'] = $fetch_mode;
        return $this;
    }

    /**
     *
     * @param string $username
     * @return \Database\Database
     */
    protected function public__setUsername($username)
    {
        $this->properties['username'] = $username;
        return $this;
    }

    /**
     *
     * @param string $password
     * @return \Database\Database
     */
    protected function public__setPassword($password)
    {
        $this->properties['password'] = $password;
        return $this;
    }

    /**
     *
     * @param array $options
     * @return \Database\Database
     */
    protected function public__setOptions(array $options = NULL)
    {
        $this->properties['options'] = $options;
        return $this;
    }

    /**
     *
     * @param string $table_prefix
     * @return \Database\Database
     */
    protected function public__setTablePrefix($table_prefix)
    {
        $this->properties['table_prefix'] = $table_prefix;
        return $this;
    }

    /**
     *
     * @param string|int $last_insert_id
     * @return \Database\Database
     */
    protected function public__setLastInsertId($last_insert_id)
    {
        $this->properties['last_insert_id'] = $last_insert_id;
        return $this;
    }

    /**
     *
     * @param string $database_absolute_path
     * @return \Database\Database
     */
    protected function public__setDatabaseAbsolutePath($database_absolute_path)
    {
        $this->properties['database_absolute_path'] = $database_absolute_path;
        return $this;
    }

    /**
     *
     * @param array $available_drivers
     * @return \Database\Database
     */
    protected function public__setAvailableDrivers(array $available_drivers)
    {
        $this->properties['available_drivers'] = $available_drivers;
        return $this;
    }

    /**
     * Render a DSN for MySQL
     * @return string
     */
    protected function renderDsnForMySQL()
    {
        $h = $this->getHost();
        $p = $this->getPort();
        $s = $this->getUnixSocket();
        $c = $this->getCharset();
        $b = $this->getDbName();
        return self::DRIVER_MYSQL . $this->renderDsnParts([
                    'host' => !empty($h) ? $h : NULL,
                    'port' => !empty($p) ? $p : NULL,
                    'unix_socket' => !empty($s) ? $s : NULL,
                    'dbname' => !empty($b) ? $b : NULL,
                    'username' => $this->getUsername(),
                    'password' => $this->getPassword(),
                    'charset' => !empty($c) ? $c : NULL,
                        ], ';');
    }

    /**
     * Render a DSN for PostGreSQL
     * @return string
     */
    protected function renderDsnForPgsql()
    {
        $h = $this->getHost();
        $p = $this->getPort();
        $b = $this->getDbName();
        return self::DRIVER_PGSQL . $this->renderDsnParts([
                    'host' => !empty($h) ? $h : NULL,
                    'port' => !empty($p) ? $p : NULL,
                    'dbname' => !empty($b) ? $b : NULL,
                    'user' => $this->getUsername(),
                    'password' => $this->getPassword(),
                        ], ' ');
    }

    /**
     * Render a DSN for SQLite
     * @return string
     */
    protected function renderDsnForSqlite()
    {
        return self::DRIVER_SQLITE . $this->getDatabaseAbsolutePath();
    }

    /**
     * Flattens Map of DSN Parts using a Delimiter.
     * @param array $map DSN Parts Map
     * @param string $delimiter Delimiter between DSN Parts
     * @return string
     */
    protected function renderDsnParts(array $map, $delimiter = ';')
    {
        $list = [];
        foreach ($map as $key => $value)
        {
            if (!\is_null($value))
            {
                $list[] = $key . '=' . $value;
            }
        }
        return \implode($delimiter, $list);
    }

    /**
     * execQuery
     *
     * @param string $sql_query An SQL query string
     * @param array $bind_params Paramters to bind
     * @param int $fetch_mode A PDO Fetch mode \PDO::FETCH_*
     * @return array By default an assoc array, but depends on $fetchMode
     */
    protected function public__execQuery($sql_query, array $bind_params = [], $fetch_mode = NULL)
    {
        $sth = $this->getPDOInstance()->prepare($this->getPrefixedTableName($sql_query));
        foreach ($bind_params as $key => $value)
        {
            $sth->bindValue("$key", $value, $this->getPdoType(\gettype($value)));
        }
        $sth->execute();
        return $sth->fetchAll($fetch_mode != NULL ? $fetch_mode : $this->getFetchMode());
    }

    /**
     *
     * @param string $table_name
     * @param string $where
     *     $sqlQuery = "SELECT COUNT(*) as c FROM `$tableName` WHERE $where;";
     *
     * @param array $bind_params
     *    [
     *        ':p1'=>'value',
     *        ':p2'=>'value',
     *        ':pN'=>'value',
     *     ]
     * @return int
     */
    protected function public__count($table_name, $where = NULL, array $bind_params = [])
    {
        $sqlQuery = "SELECT COUNT(*) as c FROM " . $this->quoteTableName($this->getPrefixedTableName($table_name)) . ($where != NULL ? " WHERE $where;" : ";");
        $sth = $this->getPDOInstance()->prepare($sqlQuery);
        foreach ($bind_params as $key => $value)
        {
            $sth->bindValue("$key", $value, $this->getPdoType(\gettype($value)));
        }
        $sth->execute();
        $re = $sth->fetchAll();
        return $re[0]['c'];
    }

    /**
     * insert one record into a table
     *
     * @param string $table_name A name of table to insert into
     * @param array $data_to_insert An associative array:
     * [
     *      'tableColumnName1' => 'value',
     *      'tableColumnName2' => 'value',
     *      'tableColumnNameN' => 'value',
     * ]
     * @return integer Returns the id of the inserted row
     */
    protected function public__insert($table_name, array $data_to_insert)
    {
        $pdo = $this->getPDOInstance();
        \ksort($data_to_insert);
        $fieldNames = \implode('`, `', \array_keys($data_to_insert));
        $fieldValues = ':' . \implode(', :', \array_keys($data_to_insert));
        $sqlQuery = "INSERT INTO " . $this->quoteTableName($this->getPrefixedTableName($table_name)) . " (`$fieldNames`) VALUES ($fieldValues)";
        $sth = $pdo->prepare($sqlQuery);
        foreach ($data_to_insert as $key => $value)
        {
            $sth->bindValue(":$key", $value, $this->getPdoType(\gettype($value)));
        }
        $sth->execute();
        return $this->setLastInsertId($pdo->lastInsertId())->getLastInsertId();
    }

    /**
     * insert multiple records into a table
     *
     * @param string $table_name A name of table to insert into
     * @param array $data_to_insert An associative array:
     * [
     *      'field_names' => ['', '', '', '', '', ],
     *      'values' => [
     *              ['', '', '', '', '', ],
     *              ['', '', '', '', '', ],
     *              ['', '', '', '', '', ],
     *              ['', '', '', '', '', ],
     *      ],
     * ]
     * @return boolean Returns TRUE on success or FALSE on failure
     * @see http://stackoverflow.com/questions/1176352/pdo-prepared-inserts-multiple-rows-in-single-query
     * @see http://stackoverflow.com/questions/19680494/insert-multiple-rows-with-pdo-prepared-statements
     * @see http://stackoverflow.com/questions/10060721/pdo-mysql-insert-multiple-rows-in-one-query
     * @see http://dev.mysql.com/doc/refman/5.7/en/load-data.html
     */
    protected function public__insertMultiple($table_name, array $data_to_insert)
    {
        $pdo = $this->getPDOInstance();
        $fieldNames = \implode('`, `', \array_values($data_to_insert['field_names']));
        $sqlQuery = "INSERT INTO " . $this->quoteTableName($this->getPrefixedTableName($table_name)) . " (`$fieldNames`) VALUES ";

        $i = 0;
        $fieldValues = '';
        foreach ($data_to_insert['values'] as $rec_value)
        {
            $fieldValues .= '(';
            foreach ($rec_value as $value)
            {
                $fieldValues .= ":v$i,";
                $i++;
            }
            $fieldValues .= \rtrim($fieldValues, ',') . '),';
        }
        $sqlQuery .= \rtrim($fieldValues, ',') . ";";
        $sth = $pdo->prepare($sqlQuery);

        $i = 0;
        foreach ($data_to_insert['values'] as $rec_value)
        {
            foreach ($rec_value as $value)
            {
                $sth->bindValue(':v' . $i++, $value, $this->getPdoType(\gettype($value)));
            }
        }

        try
        {
            $pdo->beginTransaction();
            $sth->execute();
            $pdo->commit();
        }
        catch (Exception $exc)
        {
            $pdo->rollback();
            return FALSE;
        }

        return TRUE;
    }

    /**
     * update
     *
     * @param string $table_name A name of table to insert into
     * @param array $data_to_update An associative array
     * [
     *      'tableColumnName1' => 'value',
     *      'tableColumnName2' => 'value',
     *      'tableColumnNameN' => 'value',
     * ]
     * @param string $where the WHERE query part AFTER the WHERE word
     *  eg. $sqlQuery = "UPDATE `" . $tableName . "` SET $dataToUpdate WHERE " . $where . ";";
     *    so the last part is used for the $where
     * @param array $bind_params_for_where_part
     * [
     *  ':id1' => 'someValue1',
     *  ':id2' => 'someValue2',
     *  ':idN' => 'someValueN',
     * ]
     * @return integer Returns the number of affected rows
     */
    protected function public__update($table_name, array $data_to_update, $where = NULL, array $bind_params_for_where_part = [])
    {
        \ksort($data_to_update);
        $fieldDetails = '';
        foreach ($data_to_update as $key => $value)
        {
            $fieldDetails .= $this->quoteColumnName($key) . "=:$key,";
        }
        $fieldDetails = \rtrim($fieldDetails, ',');
        $sqlQuery = "UPDATE " . $this->quoteTableName($this->getPrefixedTableName($table_name)) . " SET $fieldDetails" . ($where != NULL ? " WHERE $where;" : ";");
        $sth = $this->getPDOInstance()->prepare($sqlQuery);
        foreach ($data_to_update as $key => $value)
        {
            $sth->bindValue(":$key", $value, $this->getPdoType(\gettype($value)));
        }
        foreach ($bind_params_for_where_part as $key => $value)
        {
            $sth->bindValue("$key", $value, $this->getPdoType(\gettype($value)));
        }
        return $sth->execute();
    }

    /**
     * delete
     *
     * @param string $table_name
     * @param string $where the WHERE query part AFTER the WHERE word
     * @param array $bind_params
     *    [
     *        ':p1'=>'value',
     *        ':p2'=>'value',
     *        ':pN'=>'value',
     *     ]
     *  eg. $sqlQuery = "DELETE FROM `" . $tableName . "` WHERE " . $where . ";";
     * @return integer the number of affected rows
     */
    protected function public__delete($table_name, $where = NULL, array $bind_params = [])
    {
        $sqlQuery = "DELETE FROM " . $this->quoteTableName($this->getPrefixedTableName($table_name)) . ($where != NULL ? " WHERE $where;" : ";");
        $sth = $this->getPDOInstance()->prepare($sqlQuery);
        foreach ($bind_params as $key => $value)
        {
            $sth->bindValue("$key", $value, $this->getPdoType(\gettype($value)));
        }
        return $sth->execute();
    }

    /**
     * Quotes a string value for use in a query.
     *
     * @param string $str string to be quoted
     * @return string the properly quoted string
     * @see http://www.php.net/manual/en/function.PDO-quote.php
     */
    protected function public__quoteValue($str)
    {
        if (\is_int($str) || \is_float($str))
        {
            return $str;
        }
        $connection_already_opened = FALSE;
        $pdo = $this->getPDOInstance();
        if ($pdo == NULL)
        {
            $this->open();
        }
        else
        {
            $connection_already_opened = TRUE;
        }
        if (($value = $pdo->quote($str)) !== FALSE)
        {
            if ($pdo != NULL && !$connection_already_opened)
            {
                $this->close();
            }
            return $value;
        }
        else
        { // the driver doesn't support quote (e.g. oci)
            if ($pdo != NULL && !$connection_already_opened)
            {
                $this->close();
            }
            return "'" . \addcslashes(\str_replace("'", "''", $str), "\000\n\r\\\032") . "'";
        }
    }

    /**
     * Quotes a table name for use in a query.
     * If the table name contains schema prefix, the prefix will also be properly quoted.
     *
     * @param string $name table name
     * @return string the properly quoted table name
     */
    protected function public__quoteTableName($name)
    {
        return $this->quoteIdentifier($name);
    }

    /**
     * Quotes a column name for use in a query.
     * If the column name contains prefix, the prefix will also be properly quoted.
     *
     * @param string $name column name
     * @return string the properly quoted column name
     */
    protected function public__quoteColumnName($name)
    {
        return $this->quoteIdentifier($name);
    }

    /**
     * Quote a string that is used as an identifier
     * (table names, column names etc). This method can
     * also deal with dot-separated identifiers eg table.column
     *
     * @param string $identifier
     * @return string
     */
    protected function public__quoteIdentifier($identifier)
    {
        $parts = \explode('.', $identifier);
        $parts = \array_map([$this, 'public__quoteIdentifierPart'], $parts);
        return \join('.', $parts);
    }

    /**
     * This method performs the actual quoting of a single
     * part of an identifier, using the identifier quote
     * character specified in the config (or autodetected).
     *
     * @param string $part
     * @return string
     */
    protected function public__quoteIdentifierPart($part, $quote_character = '`')
    {
        if ($part === '*')
        {
            return $part;
        }
        return $quote_character . $part . $quote_character;
    }

    /**
     * Determines the PDO type for the specified PHP type.
     *
     * @param string $type The PHP type (obtained by gettype() call).
     * \gettype($var) returns:
     * Possible values for the returned string are:
     * "boolean"
     * "integer"
     * "double" (for historical reasons "double" is returned in case of
     *          a float, and not simply "float")
     * "string"
     * "array"
     * "object"
     * "resource"
     * "NULL"
     * "unknown type"
     * @return integer the corresponding PDO type
     */
    protected function public__getPdoType($type)
    {
        static $map = [
            'boolean' => \PDO::PARAM_BOOL,
            'bool' => \PDO::PARAM_BOOL,
            'integer' => \PDO::PARAM_INT,
            'int' => \PDO::PARAM_INT,
            'resource' => \PDO::PARAM_LOB,
            'NULL' => \PDO::PARAM_NULL,
            'NULL' => \PDO::PARAM_NULL,
        ];
        return isset($map[$type]) ? $map[$type] : \PDO::PARAM_STR;
    }

    /**
     *
     * @return \Database\Database
     * @throws DatabaseException
     */
    protected function public__open()
    {
        $pdo = $this->getPDOInstance();
        if ($pdo != NULL)
        { // connection already opened
            return $this;
        }

        try
        {
            $this->setPDOInstance(new \PDO($this->getDSN(), $this->getUsername(), $this->getPassword(), $this->getOptions()));

            $pdo = $this->getPDOInstance();
            $pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
            $pdo->setAttribute(\PDO::ATTR_DEFAULT_FETCH_MODE, \PDO::FETCH_ASSOC);
            $pdo->setAttribute(\PDO::ATTR_EMULATE_PREPARES, $this->getEmulatePrepare());

            $cs = $this->getCharset();
            if ($cs != NULL)
            {
                $pdo->exec("SET CHARACTER SET " . $pdo->quote($cs));
            }
        }
        catch (Exception $ex)
        {
            throw new DatabaseException($ex->getMessage());
        }
        return $this;
    }

    /**
     *
     * @return \Database\Database
     */
    protected function public__close()
    {
        $this->setPDOInstance(NULL);
        return $this;
    }

    /**
     *
     * @param string $table_name
     * @return string
     */
    protected function public__getPrefixedTableName($table_name)
    {
        $tp = $this->getTablePrefix();
        return \str_replace("#__", $tp, $table_name);
    }

}


text:
package com.otms.api.service;

import org.apache.http.Consts;
import org.apache.http.HttpClientConnection;
import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.BasicHttpEntity;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.FileEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.pool.BasicConnPool;
import org.apache.http.impl.pool.BasicPoolEntry;
import org.apache.http.message.BasicHttpRequest;
import org.apache.http.message.BasicHttpResponse;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpCoreContext;
import org.apache.http.protocol.HttpProcessor;
import org.apache.http.protocol.HttpProcessorBuilder;
import org.apache.http.protocol.HttpRequestHandler;
import org.apache.http.protocol.HttpService;
import org.apache.http.protocol.ResponseConnControl;
import org.apache.http.protocol.ResponseContent;
import org.apache.http.protocol.ResponseDate;
import org.apache.http.protocol.ResponseServer;
import org.apache.http.protocol.UriHttpRequestHandlerMapper;
import org.apache.http.util.EntityUtils;
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

/**
 * @Author frank
 * @Date 17-11-8
 */
@SpringBootTest
public class TestHttpCore {

    @Test
    public void request() {

        HttpRequest request = new BasicHttpRequest("GET", "www.baidu.com", HttpVersion.HTTP_1_1);

        System.out.println(request.getRequestLine().toString());
    }

    @Test
    public void response() throws IOException {

        HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK");

        System.out.println(response.getStatusLine().toString());

        HttpEntity entity = response.getEntity();
        InputStream content = entity.getContent();
    }

    @Test
    public void entities() throws IOException {

        StringEntity entity = new StringEntity("important message", Consts.UTF_8);

        EntityUtils.toString(entity);
        EntityUtils.toByteArray(entity);

        StringBuilder sb = new StringBuilder();
        Map<String, String> env = System.getenv();
        for (Map.Entry<String, String> envEntry : env.entrySet()) {
            sb.append(envEntry.getKey())
                    .append(": ").append(envEntry.getValue())
                    .append("\r\n");
        }

        // construct without a character encoding (defaults to ISO-8859-1)
        HttpEntity myEntity1 = new StringEntity(sb.toString());

        // alternatively construct with an encoding (mime type defaults to "text/plain")
        HttpEntity myEntity2 = new StringEntity(sb.toString(), Consts.UTF_8);

        // alternatively construct with an encoding and a mime type
        HttpEntity myEntity3 = new StringEntity(sb.toString(),
                ContentType.create("text/plain", Consts.UTF_8));

        BasicHttpEntity myEntity = new BasicHttpEntity();
        myEntity.setContent(new FileInputStream(""));
        myEntity.setContentLength(340); // sets the length to 340

        new ByteArrayEntity(new byte[] {1,2,3},
                ContentType.APPLICATION_OCTET_STREAM);

        new FileEntity(new File(""),
                ContentType.create("application/java-archive"));
    }

    @Test
    public void processor() throws IOException, HttpException {

        HttpProcessor httpProc = HttpProcessorBuilder.create()
                .add(new HttpRequestInterceptor() {
                    public void process(
                            HttpRequest request,
                            HttpContext context) throws HttpException, IOException {
                        String id = (String) context.getAttribute("session-id");
                        if (id != null) {
                            request.addHeader("Session-ID", id);
                        }
                    }
                })
                .build();

        HttpCoreContext context = HttpCoreContext.create();
        HttpRequest request = new BasicHttpRequest("GET", "/");
        httpProc.process(request, context);
    }

    @Test
    public void test() throws ExecutionException, InterruptedException {

        HttpHost target = new HttpHost("localhost");
        BasicConnPool connpool = new BasicConnPool();
        connpool.setMaxTotal(200);
        connpool.setDefaultMaxPerRoute(10);
        connpool.setMaxPerRoute(target, 20);
        Future<BasicPoolEntry> future = connpool.lease(target, null);
        BasicPoolEntry poolEntry = future.get();
        HttpClientConnection conn = poolEntry.getConnection();

        HttpProcessor httpproc = HttpProcessorBuilder.create()
                .add(new ResponseDate())
                .add(new ResponseServer("MyServer-HTTP/1.1"))
                .add(new ResponseContent())
                .add(new ResponseConnControl())
                .build();

        HttpRequestHandler myRequestHandler = new HttpRequestHandler() {

            public void handle(
                    HttpRequest request,
                    HttpResponse response,
                    HttpContext context) throws HttpException, IOException {
                response.setStatusCode(HttpStatus.SC_OK);
                response.setEntity(
                        new StringEntity("some important message",
                                ContentType.TEXT_PLAIN));
            }

        };

        UriHttpRequestHandlerMapper handlerMapper = new UriHttpRequestHandlerMapper();
        handlerMapper.register("/service/*", myRequestHandler);
        HttpService httpService = new HttpService(httpproc, handlerMapper);
    }

    @Test
    public void client() throws URISyntaxException, IOException {

        CloseableHttpClient httpclient = HttpClients.createDefault();

        URI uri = new URIBuilder()
                .setScheme("http")
                .setHost("www.google.com")
                .setPath("/search")
                .setParameter("q", "httpclient")
                .setParameter("btnG", "Google Search")
                .setParameter("aq", "f")
                .setParameter("oq", "")
                .build();
        HttpGet httpget = new HttpGet(uri);
        CloseableHttpResponse response = httpclient.execute(httpget);
    }
}


text:
package rent.model.services.impl;

import rent.model.dao.impl.BillDao;
import rent.model.entities.Bill;
import rent.model.services.AbstractService;

/**
 * Service implementation for {@link Bill}.
 *
 * @author zagart
 */
public class BillService extends AbstractService<Bill, Long, BillDao> {
}


text:
import Vue from 'vue'
import Vuex from 'vuex'
import state from './states'
import actions from './actions'
import getters from './getters'
import modules from './modules'
import mutations from './mutations'

Vue.use(Vuex)

export default new Vuex.Store({
  state,
  getters,
  actions,
  modules,
  mutations
})


text:
angular.module('tossIt.config', [])
	.constant('SERVER_URL', 'http://localhost:3002');


text:
<?xml version="1.0" encoding="UTF-8"?>
<billStatus>
  <bill>
    <calendarNumbers />
    <updateDate>2017-09-11T03:06:32Z</updateDate>
    <cboCostEstimates />
    <policyArea>
      <name>Armed Forces and National Security</name>
    </policyArea>
    <relatedBills>
      <item>
        <type>HR</type>
        <latestAction>
          <text>Referred to the Committee on Veterans' Affairs, and in addition to the Committees on Oversight and Government Reform, and Energy and Commerce, for a period to be subsequently determined by the Speaker, in each case for consideration of such provisions as fall within the jurisdiction of the committee concerned.</text>
          <actionDate>2017-06-29</actionDate>
        </latestAction>
        <number>3158</number>
        <congress>115</congress>
        <latestTitle>Better Workforce for Veterans Act of 2017</latestTitle>
        <relationshipDetails>
          <item>
            <type>Related bill</type>
            <identifiedBy>CRS</identifiedBy>
          </item>
        </relationshipDetails>
      </item>
    </relatedBills>
    <billType>S</billType>
    <congress>115</congress>
    <laws />
    <createDate>2017-06-09T00:26:37Z</createDate>
    <originChamber>Senate</originChamber>
    <cosponsors>
      <item>
        <state>KS</state>
        <middleName />
        <lastName>MORAN</lastName>
        <firstName>JERRY</firstName>
        <sponsorshipWithdrawnDate />
        <fullName>Sen. Moran, Jerry [R-KS]</fullName>
        <isOriginalCosponsor>True</isOriginalCosponsor>
        <bioguideId>M000934</bioguideId>
        <party>R</party>
        <identifiers>
          <gpoId>8307</gpoId>
          <lisID>1507</lisID>
          <bioguideId>M000934</bioguideId>
        </identifiers>
        <sponsorshipDate>2017-06-08</sponsorshipDate>
      </item>
      <item>
        <state>MO</state>
        <middleName />
        <lastName>McCaskill</lastName>
        <firstName>Claire</firstName>
        <sponsorshipWithdrawnDate />
        <fullName>Sen. McCaskill, Claire [D-MO]</fullName>
        <isOriginalCosponsor>True</isOriginalCosponsor>
        <bioguideId>M001170</bioguideId>
        <party>D</party>
        <identifiers>
          <gpoId>8252</gpoId>
          <lisID>1820</lisID>
          <bioguideId>M001170</bioguideId>
        </identifiers>
        <sponsorshipDate>2017-06-08</sponsorshipDate>
      </item>
      <item>
        <state>VA</state>
        <middleName />
        <lastName>Kaine</lastName>
        <firstName>Timothy</firstName>
        <sponsorshipWithdrawnDate />
        <fullName>Sen. Kaine, Tim [D-VA]</fullName>
        <isOriginalCosponsor>True</isOriginalCosponsor>
        <bioguideId>K000384</bioguideId>
        <party>D</party>
        <identifiers>
          <bioguideId>K000384</bioguideId>
          <lisID>2176</lisID>
          <gpoId />
        </identifiers>
        <sponsorshipDate>2017-06-08</sponsorshipDate>
      </item>
      <item>
        <state>NH</state>
        <middleName>Wood</middleName>
        <lastName>Hassan</lastName>
        <firstName>Margaret</firstName>
        <sponsorshipWithdrawnDate />
        <fullName>Sen. Hassan, Margaret Wood [D-NH]</fullName>
        <isOriginalCosponsor>True</isOriginalCosponsor>
        <bioguideId>H001076</bioguideId>
        <party>D</party>
        <identifiers>
          <lisID>2302</lisID>
          <bioguideId>H001076</bioguideId>
          <gpoId />
        </identifiers>
        <sponsorshipDate>2017-06-08</sponsorshipDate>
      </item>
      <item>
        <state>ID</state>
        <middleName>D.</middleName>
        <lastName>CRAPO</lastName>
        <firstName>MICHAEL</firstName>
        <sponsorshipWithdrawnDate />
        <fullName>Sen. Crapo, Mike [R-ID]</fullName>
        <isOriginalCosponsor>True</isOriginalCosponsor>
        <bioguideId>C000880</bioguideId>
        <party>R</party>
        <identifiers>
          <bioguideId>C000880</bioguideId>
          <lisID>250</lisID>
          <gpoId>8289</gpoId>
        </identifiers>
        <sponsorshipDate>2017-06-08</sponsorshipDate>
      </item>
      <item>
        <state>FL</state>
        <middleName>WILLIAM</middleName>
        <lastName>NELSON</lastName>
        <firstName>CLARENCE</firstName>
        <sponsorshipWithdrawnDate />
        <fullName>Sen. Nelson, Bill [D-FL]</fullName>
        <isOriginalCosponsor>False</isOriginalCosponsor>
        <bioguideId>N000032</bioguideId>
        <party>D</party>
        <identifiers>
          <gpoId>8236</gpoId>
          <lisID>859</lisID>
          <bioguideId>N000032</bioguideId>
        </identifiers>
        <sponsorshipDate>2017-07-10</sponsorshipDate>
      </item>
    </cosponsors>
    <committees>
      <billCommittees>
        <item>
          <systemCode>ssva00</systemCode>
          <chamber>Senate</chamber>
          <subcommittees />
          <type>Standing</type>
          <name>Veterans' Affairs Committee</name>
          <activities>
            <item>
              <date>2017-07-11T18:30:44Z</date>
              <name>Hearings by</name>
            </item>
            <item>
              <date>2017-06-08T19:17:37Z</date>
              <name>Referred to</name>
            </item>
          </activities>
        </item>
      </billCommittees>
    </committees>
    <recordedVotes />
    <notes />
    <latestAction>
      <actionDate>2017-07-11</actionDate>
      <text>Committee on Veterans' Affairs. Hearings held.</text>
      <links />
    </latestAction>
    <actions>
      <actionTypeCounts>
        <hearingsHeld>1</hearingsHeld>
        <referredToCommittee>1</referredToCommittee>
        <introducedInSenate>1</introducedInSenate>
      </actionTypeCounts>
      <actionByCounts>
        <senate>3</senate>
      </actionByCounts>
      <item>
        <actionDate>2017-07-11</actionDate>
        <committee>
          <name>Veterans' Affairs Committee</name>
          <systemCode>ssva00</systemCode>
        </committee>
        <links />
        <sourceSystem>
          <name>Senate</name>
          0
        </sourceSystem>
        <text>Committee on Veterans' Affairs. Hearings held.</text>
        <type>Committee</type>
      </item>
      <item>
        <actionDate>2017-06-08</actionDate>
        <committee>
          <name>Veterans' Affairs Committee</name>
          <systemCode>ssva00</systemCode>
        </committee>
        <links />
        <sourceSystem>
          <name>Senate</name>
          0
        </sourceSystem>
        <text>Read twice and referred to the Committee on Veterans' Affairs.</text>
        <type>IntroReferral</type>
      </item>
      <item>
        <actionCode>10000</actionCode>
        <text>Introduced in Senate</text>
        <actionDate>2017-06-08</actionDate>
        <type>IntroReferral</type>
        <sourceSystem>
          <name>Library of Congress</name>
          9
        </sourceSystem>
        <links />
        <committee />
      </item>
    </actions>
    <titles>
      <item>
        <title>Better Workforce for Veterans Act of 2017</title>
        <titleType>(Extracted from GPO) Short Titles as Introduced</titleType>
        <parentTitleType />
        <chamberName />
        <chamberCode />
      </item>
      <item>
        <title>Better Workforce for Veterans Act of 2017</title>
        <titleType>Short Titles as Introduced</titleType>
        <parentTitleType />
        <chamberName />
        <chamberCode />
      </item>
      <item>
        <title>A bill to amend title 38, United States Code, to improve the authorities of the Secretary of Veterans Affairs to hire, recruit, and train employees of the Department of Veterans Affairs, and for other purposes.</title>
        <titleType>Official Title as Introduced</titleType>
        <parentTitleType />
        <chamberName />
        <chamberCode />
      </item>
      <item>
        <title>Better Workforce for Veterans Act of 2017</title>
        <titleType>Display Title</titleType>
        <parentTitleType />
        <chamberName />
        <chamberCode />
      </item>
    </titles>
    <version>1.0.0</version>
    <subjects>
      <billSubjects>
        <legislativeSubjects />
        <policyArea>
          <name>Armed Forces and National Security</name>
        </policyArea>
      </billSubjects>
    </subjects>
    <introducedDate>2017-06-08</introducedDate>
    <sponsors>
      <item>
        <bioguideId>T000464</bioguideId>
        <lastName>Tester</lastName>
        <state>MT</state>
        <identifiers>
          <gpoId>8258</gpoId>
          <bioguideId>T000464</bioguideId>
          <lisID>1829</lisID>
        </identifiers>
        <byRequestType />
        <firstName>Jon</firstName>
        <middleName />
        <party>D</party>
        <fullName>Sen. Tester, Jon [D-MT]</fullName>
      </item>
    </sponsors>
    <summaries>
      <billSummaries />
    </summaries>
    <amendments />
    <committeeReports />
    <billNumber>1325</billNumber>
    <title>Better Workforce for Veterans Act of 2017</title>
  </bill>
  <dublinCore xmlns:dc="http://purl.org/dc/elements/1.1/">
    <dc:format>text/xml</dc:format>
    <dc:language>EN</dc:language>
    <dc:rights>Pursuant to Title 17 Section 105 of the United States Code, this file is not subject to copyright protection and is in the public domain.</dc:rights>
    <dc:contributor>Congressional Research Service, Library of Congress</dc:contributor>
    <dc:description>This file contains bill summaries and statuses for federal legislation. A bill summary describes the most significant provisions of a piece of legislation and details the effects the legislative text may have on current law and federal programs. Bill summaries are authored by the Congressional Research Service (CRS) of the Library of Congress. As stated in Public Law 91-510 (2 USC 166 (d)(6)), one of the duties of CRS is "to prepare summaries and digests of bills and resolutions of a public general nature introduced in the Senate or House of Representatives". For more information, refer to the User Guide that accompanies this file.</dc:description>
  </dublinCore>
</billStatus>


text:
using System;

namespace Xamarin.Forms
{
	public sealed class FileImageSourceConverter : TypeConverter
	{
		public override object ConvertFromInvariantString(string value)
		{
			if (value != null)
				return (FileImageSource)ImageSource.FromFile(value);

			throw new InvalidOperationException(string.Format("Cannot convert \"{0}\" into {1}", value, typeof(FileImageSource)));
		}
	}
}


text:
<?php

namespace PhpBench\Report\Generator;

use PhpBench\Benchmark\SuiteDocument;
use PhpBench\Tabular\Tabular;

/**
 * Report generator which uses custom report definitions.
 */
class ConsoleTabularCustomGenerator extends AbstractConsoleTabularGenerator
{
    private $configPath;

    public function __construct(Tabular $tabular, $configPath)
    {
        parent::__construct($tabular);
        $this->configPath = $configPath;
    }

    /**
     * {@inheritdoc}
     */
    public function getSchema()
    {
        return array(
            'type' => 'object',
            'additionalProperties' => false,
            'properties' => array(
                'title' => array(
                    'oneOf' => array(
                        array('type' => 'string'),
                        array('type' => 'null'),
                    ),
                ),
                'description' => array(
                    'oneOf' => array(
                        array('type' => 'string'),
                        array('type' => 'null'),
                    ),
                ),
                'file' => array(
                    'oneOf' => array(
                        array('type' => 'string'),
                        array('type' => 'null'),
                    ),
                ),
                'params' => array(
                    'oneOf' => array(
                        array('type' => 'object'),
                        array('type' => 'array'),
                    ),
                ),
                'debug' => array(
                    'type' => 'boolean',
                ),
            ),
        );
    }

    /**
     * {@inheritdoc}
     */
    public function generate(SuiteDocument $document, array $config)
    {
        if (!$config['file']) {
            throw new \InvalidArgumentException(
                'You must provide the path to a Tabular JSON report definition with the "file" option.'
            );
        }

        $reportFile = $config['file'];

        // if not an absolute path, make it relative to the config file
        if (substr($reportFile, 0, 1) !== '/') {
            $reportFile = dirname($this->configPath) . '/' . $reportFile;
        }

        $parameters = $config['params'];
        $this->doGenerate($reportFile, $document, $config, $parameters);
    }

    /**
     * {@inheritdoc}
     */
    public function getDefaultReports()
    {
        return array(
        );
    }

    /***
     * {@inheritDoc}
     */

    public function getDefaultConfig()
    {
        return array(
            'debug' => false,
            'title' => null,
            'description' => null,
            'file' => null,
            'params' => array(),
        );
    }
}


text:
/**
 * Powered by Systango
 * http://www.systango.com
 */

import React, { Component } from 'react';
import {
  Platform, Dimensions, Image, View, ListView, Text, TextInput, FlatList
} from 'react-native';
import { Button, SQLiteManager } from 'react-native-crashalert';

import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import * as authActions from '../../actions/user';
import * as fetchRoute from '../../actions/route';
import styles from './styles';

let ds;
let playerArray = [];

class Search extends Component {
  /*
  * Home - Lifecycle
  */
  constructor(props) {
    super(props);

    //* > Setup state
    this.initialStateSetup();

    //* > Get error data
    const obj = new SQLiteManager();
    obj.getDeviceInfo((crashReport) => {
      playerArray = crashReport;
      this.setState({ dataSource: ds.cloneWithRows(playerArray) });
    });

    this.state = ({
      data: ['Aman', 'Abhishek', 'Kapil', 'Shahid', 'Rahul', 'Rituraj', 'Raj', 'Anurag'],
      searchedData: [],
      text: '',
      isSearchPressed: false,
    });
  }

  searchFilterFunction(text) {
    this.setState({ isSearchPressed: true });
    const newData = this.state.data.filter((item) => {
      const itemData = item.toLowerCase();
      return itemData.toString().indexOf(text.toLowerCase()) > -1;
    });

    this.setState({ searchedData: newData, text });
  }

  _renderItem(item) {
    if (typeof item !== 'undefined') {
      return (
        <View style={{
          justifyContent: 'center', alignItems: 'center', backgroundColor: 'grey', marginBottom: 10, marginHorizontal: 10,
        }}
        >
          <Text style={{ color: 'white', fontSize: 20, padding: 12, }}>{item}</Text>
        </View>
      );
    } else {
      return (
        <View style={{
          justifyContent: 'center', alignItems: 'center', marginBottom: 10, marginHorizontal: 10,
        }}
        >
          <Text style={{ color: 'black', fontSize: 20, padding: 12, }}>No Data Found!</Text>
        </View>
      );
    }
  }

  render() {
    return (
      <View style={[styles.container, { width: this.state.width, height: this.state.height }]}>
        <Image
          source={require('../../../assets/home/navigationBG.png')}
          style={{
            position: 'absolute', left: 0, top: 0, width: this.state.width
          }}
        />

        <View style={{
          flexDirection: 'row', height: (Platform.OS === 'android') ? 50 : 64, alignItems: 'center', paddingTop: 5, backgroundColor: 'green'
        }}
        >
          {this.backButtonView()}
          <View style={{
            flex: 1, marginRight: 50, flexDirection: 'row', justifyContent: 'center', paddingTop: 5, alignItems: 'center', height: (Platform.OS === 'android') ? 50 : 64
          }}
          >
            <Text style={{ color: '#fff', backgroundColor: 'transparent' }}>Search</Text>
          </View>
        </View>
        <View style={styles.textInputContainer}>
          <TextInput
            style={styles.TextInputStyleClass}
            onChangeText={text => this.setState({ text, searchedData: '', isSearchPressed: false })}
            value={this.state.text}
            underlineColorAndroid="transparent"
            placeholder="Search Here"
          />
          <Button style={[styles.btn]} onPress={() => this.searchFilterFunction(this.state.text)} searchText={this.state.text}>
                  Search
          </Button>
        </View>
        <FlatList
          data={(!this.state.isSearchPressed) ? this.state.data : this.state.searchedData}
          extraData={this.state}
          renderItem={rowData => this._renderItem(rowData.item)}
        />
      </View>
    );
  }

  /*
   * List - Private Method
   */
  initialStateSetup() {
    ds = new ListView.DataSource({
      rowHasChanged: (r1, r2) => r1 != r2
    });
    this.state = {
      dataSource: ds.cloneWithRows(playerArray),
      width: Dimensions.get('window').width,
      height: Dimensions.get('window').height
    };
  }

  pressRowItem(rowData) {
    const abcData = rowData;
    this.props.actions.crashData(abcData);
    this.props.navigation.push('CrashDetail');
  }

  backButtonView() {
    return (
      <Button
        isBorder={false}
        transparent
        onPress={() => this.handleBackPress()}
        style={{
          marginLeft: 10, width: 50, alignItems: 'center', justifyContent: 'center', height: (Platform.OS === 'android') ? 50 : 64
        }}
      >
        <Image source={require('../../../assets/home/arrow.png')} ref="Back Button" />
      </Button>
    );
  }

  handleBackPress() {
    this.props.navigation.pop();
  }
}

function mapStateToProps(state) {
  return {
    userData: state.user.response,
  };
}

function bindActions(dispatch) {
  return {
    route: bindActionCreators(fetchRoute, dispatch),
    actions: bindActionCreators(authActions, dispatch),
  };
}

export default connect(mapStateToProps, bindActions)(Search);


text:
import { hasError } from '../../src/assertions';

import {
  combinedValidator,
  composedValidator,
  multipleArrayComposedValidator,
  multipleObjectComposedValidator,
  singleRequiredValidator,
  validCombinedData,
} from './_helpers';

it('single validator when invalid returns true', () => {
  expect(hasError(singleRequiredValidator(''))).toBe(true);
});

it('single validator when valid returns false', () => {
  expect(hasError(singleRequiredValidator('a'))).toBe(false);
});

it('composed validator when invalid returns true', () => {
  expect(hasError(composedValidator(''))).toBe(true);
  expect(hasError(composedValidator('1'))).toBe(true);
});

it('composed validator when valid returns false', () => {
  expect(hasError(composedValidator('a'))).toBe(false);
});

it('multiple errors as array when invalid returns true', () => {
  expect(hasError(multipleArrayComposedValidator(''))).toBe(true);
  expect(hasError(multipleArrayComposedValidator('1'))).toBe(true);
});

it('multiple errors as array when valid returns false', () => {
  expect(hasError(multipleArrayComposedValidator('a'))).toBe(false);
});

it('multiple errors as object when invalid returns true', () => {
  expect(hasError(multipleObjectComposedValidator(''))).toBe(true);
  expect(hasError(multipleObjectComposedValidator('1'))).toBe(true);
});

it('multiple errors as object when valid returns false', () => {
  expect(hasError(multipleObjectComposedValidator('a'))).toBe(false);
});

it('combined validator when invalid returns true', () => {
  expect(hasError(combinedValidator({
    ...validCombinedData,
    contact: {
      ...validCombinedData.contact,
      name: '',
    },
  }))).toBe(true);

  expect(hasError(combinedValidator({
    ...validCombinedData,
    contact: {
      ...validCombinedData.contact,
      age: '',
    },
  }))).toBe(true);

  expect(hasError(combinedValidator({
    ...validCombinedData,
    contact: {
      ...validCombinedData.contact,
      age: 'a',
    },
  }))).toBe(true);

  expect(hasError(combinedValidator({
    ...validCombinedData,
    favoriteMeme: '',
  }))).toBe(true);

  expect(hasError(combinedValidator({
    ...validCombinedData,
    phraseArray: 'BBB',
  }))).toBe(true);

  expect(hasError(combinedValidator({
    ...validCombinedData,
    phraseObject: 'BBB',
  }))).toBe(true);
});

it('combined validator when valid returns false', () => {
  expect(hasError(combinedValidator(validCombinedData))).toBe(false);
});


text: node_modules/postcss-cli/bin/postcss -c postcss.json styles/styles.css > css/style.css


text:
var assert = require('should');
var sinon = require('sinon');
var BopURI = require('../js/bopuri.js');

describe('BopURI', function() {
    describe('constructor', function() {
        it('should return an instance', function() {
            var uri1 = BopURI('bop:max@example.org:documents/img/test.png?csum=sha256:aa:bb:cc');
            uri1.should.be.an.instanceof(BopURI);
            var uri2 = new BopURI('bop:max@example.org:documents/img/test.png?csum=sha256:aa:bb:cc');
            uri2.should.be.an.instanceof(BopURI);
        });
        it('should throw with invalid parameter', function() {
            (function() {
                var uri = new BopURI('test');
            }).should.
            throw ();
            (function() {
                var uri = new BopURI();
            }).should.
            throw ();
        });
        it('should fill fields correctly', function() {
            var uri = new BopURI('bop:max@example.org:documents/img/test.png?csum=sha256:aa:bb:cc');
            uri.should.have.property('scheme', 'bop');
            uri.should.have.property('uid', 'max@example.org');
            uri.should.have.property('protocol', 'documents');
            uri.should.have.property('path', '/img/test.png');
            uri.should.have.property('query', 'csum=sha256:aa:bb:cc');
        });
        it('should handle corner cases', function() {
            var uri = new BopURI('bop:max@example.org:proto/p/a/t/h');
            uri.should.have.property('path', '/p/a/t/h');

            uri = new BopURI('bop:max@example.org:proto');
            uri.should.not.have.property('path');

            uri = new BopURI('bop:max@example.org:proto/');
            uri.should.have.property('path', '/');
            uri.should.not.have.property('query');

            uri = new BopURI('bop:max:proto/?q');
            uri.should.have.property('path', '/');
            uri.should.have.property('query', 'q');

            uri = new BopURI('bop:max:proto/?');
            uri.should.have.property('query', '');

            uri = new BopURI('bop:max:proto/?a/b');
            uri.should.have.property('query', 'a/b');
        });
        describe('#create', function() {
            it('should return an instance', function() {
                var uri = BopURI.create('max@example.org', 'documents', '/chat/room1');
                uri.should.be.an.instanceof(BopURI);
                uri.should.have.property('scheme', 'bop');
                uri.should.have.property('uid', 'max@example.org');
                uri.should.have.property('protocol', 'documents');
                uri.should.have.property('path', '/chat/room1');
                uri.should.not.have.property('query');

                uri = BopURI.create('max@example.org', 'documents', 'chat/room1', 'status=away');
                uri.should.be.an.instanceof(BopURI);
                uri.should.have.property('scheme', 'bop');
                uri.should.have.property('uid', 'max@example.org');
                uri.should.have.property('protocol', 'documents');
                uri.should.have.property('path', '/chat/room1');
                uri.should.have.property('query', 'status=away');
            });
        });
        describe('#toString', function() {
            it('should return the correct string', function() {
                new BopURI('bop:max:proto/?q').toString().should.equal('bop:max:proto/?q');
                BopURI.create('max@example.org', 'documents', '/chat/room1').toString().should.equal('bop:max@example.org:documents/chat/room1');
                BopURI.create('max@example.org', 'documents', 'chat/room1', 'status=away').toString().should.equal('bop:max@example.org:documents/chat/room1?status=away');
            });
        });
    });
});


text:
A couple of c# scripts that let you communicate with bluetooth low energy devices (GATT profile).

They require Windows 10 Creators Update and .NET Framework 4.6 or later.

## Getting started

1. Download and install a c# script runner
	* dude.exe (like csi.exe but without installing Visual Studio) or
	* Visual Studio (which includes csi.exe)
2. Clone or download this respository
3. Run the BLE utilities to discover devices, services and characteristics
4. Run the Flower Care sensor or MJ-HT-V1 (Xiaomi Mijia Bluetooth Temperature Humidity Sensor) scripts to read sensor data


text:
package logging

// LoggerInterface is a Logger interface for all implementations in kyma-project/test-infra
type LoggerInterface interface {
	Info(args ...interface{})
	Warn(args ...interface{})
	Error(args ...interface{})
	Debug(args ...interface{})
	Debugf(template string, args ...interface{})
	Infof(template string, args ...interface{})
	Errorf(template string, args ...interface{})
	Debugw(message string, keysAndValues ...interface{})
}

// Logger is an interface to interact with Google logging.
// TODO: this should be replaced by extending LoggerInterface
type Logger interface {
	LogCritical(string)
	LogError(string)
	LogInfo(string)
}