text:
from django.conf.urls import patterns, include, url
#from django.conf import settings

import views
import version.models

web_srv_prefix = version.models.getWebSrvPrefix()

urlpatterns = patterns('',
                       url(r'^' + web_srv_prefix + '/ajax/(?P<module>\w+)/(?P<function>\w+)/', views.ajax, name='ajax'),
                       url(r'^$', views.index, name='index')
)

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/action_save"
        android:title="收藏"
        android:icon="@mipmap/ic_favorite_outline_white"
        app:showAsAction="always"
        />
</menu>


text:
'use strict';

module.exports = function (obj, callback) {
    var item;

    for (item in obj) {
        if (obj.hasOwnProperty(item)) {
            callback(obj[item], item);
        }
    }
};


text:
class Stage4 extends Phaser.Scene {

    obstacles;
    player;
    graphics;
    enemyGroup;
    powders;
    traps;
    itemInfoText;
    previousItems;

    constructor() {
        super({
            key: 'stage4'
        });
    }

    init(data) {
        this.previousItems = data.items;
    }

    createStatics() {
        this.add.image(0, ITEM_BAR_HEIGHT, 'floor').setOrigin(0);
        this.obstacles = this.physics.add.staticGroup();

        // outside borders
        this.obstacles.create(0, ITEM_BAR_HEIGHT, 'obstacle').setOrigin(0, 0).setScale(12, 0.01).refreshBody();
        this.obstacles.create(0, HEIGHT + BORDER_THICKNESS, 'obstacle').setOrigin(0, 0.5).setScale(12, 1).refreshBody();
        this.obstacles.create(0 - BORDER_THICKNESS, ITEM_BAR_HEIGHT, 'obstacle').setOrigin(0.5, 0).setScale(1, 21).refreshBody();
        this.obstacles.create(WIDTH + BORDER_THICKNESS, ITEM_BAR_HEIGHT, 'obstacle').setOrigin(0.5, 0).setScale(1, 21).refreshBody();

        // scatter powder
        this.powders = this.physics.add.staticGroup();
        this.powders.create(WIDTH * 0.15, HEIGHT * 0.95, 'powder');
        this.powders.create(WIDTH * 0.7, HEIGHT * 0.5, 'powder');
        this.powders.getChildren().forEach(powder => powder.name = 'powder');

        // scatter sticky death drap
        this.traps = this.physics.add.staticGroup();
        this.traps.create(WIDTH * 0.7, HEIGHT * 0.15, 'slime');
        this.traps.create(WIDTH * 0.15, HEIGHT * 0.25, 'slime');
        this.traps.create(WIDTH * 0.3, HEIGHT * 0.3, 'slime');

        // goal
        this.goal = this.physics.add.staticImage(320, 610, 'home');
        this.goal.body.setSize(40, 40);
    }

    drawItems() {
        this.itemInfoText.text = `powder: ${this.player.getItems().powder}`;
    }

    create() {
        this.itemInfoText = this.add.text(16, 10, 'key: 0', { fontSize: '32px', fill: '#fff' });

        this.createStatics();

        // player
        this.player = new Player(this, 70, 100, 'player', 0, this.previousItems);
        this.physics.add.collider(this.player, this.obstacles);

        // enemy
        this.graphics = this.add.graphics();
        const enemies = [
            new Enemy(this, WIDTH * 0.4, HEIGHT * 0.35, 'enemy', 0, 'horizontal', 'triangle', 25),
            new Enemy(this, WIDTH * 0.35, HEIGHT * 0.6, 'enemy', 0, 'idle', 'circle', 0, 100)
        ];
        enemies.forEach(enemy => enemy.createCollisionMove());
        this.enemyGroup = this.physics.add.group(enemies);

        // overlap callbacks
        this.physics.add.overlap(this.player, this.powders, this.obtainItem);
        this.physics.add.overlap(this.player, this.traps, this.onTrapped);
        this.physics.add.overlap(this.player, this.enemyGroup, this.arrestPlayer);
        this.physics.add.overlap(this.player, this.goal, clearStage.bind(this, this, 'stage5'));

    }

    update() {
        this.graphics.clear();
        this.drawItems();
        this.player.update();
        this.enemyGroup.getChildren().forEach(enemy => enemy.update(this.player));
    }
}


text:
let LanguageCtrl = (function(){
  return {
    getInstance:function()
    {
      if( !mInstance )
        mInstance = _createInstance();

      return mInstance;
    }
  };
})();

//Sortcut
export const Lang = LanguageCtrl.getInstance();

//------------------------------------------------------------------------------
// Private section
//------------------------------------------------------------------------------
let mInstance = null;
let mCurrentLanguageId = '';
let mTexts = null;

function _createInstance()
{
  return {
    changeLanguage:function( langId, onChangeLanguage )
    {
      mCurrentLanguageId = langId;
      _getLanguageById( onChangeLanguage );
    },
    trans:function( key )
    {
      return _trans( key );
    },
    getCurrentId:function()
    {
      return mCurrentLanguageId;
    }
  };
}

function _getLanguageById( onLanguageOk )
{
  let baseUrl = '';
  let xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function(){
    if( xhttp.readyState == 4 && xhttp.status == 200 )
    {
      let response = xhttp.responseText;
      mTexts = JSON.parse( response );
      if( onLanguageOk )
        onLanguageOk();
    }
  }
  xhttp.open('GET', baseUrl + 'resources/languages/' + mCurrentLanguageId + '.json', true );
  xhttp.send();
}

function _trans( key )
{
  let msg = '';
  if( mTexts[key] == undefined )
    msg = '##'+key+'##';
  else
    msg = mTexts[key];

  return msg;
}

export default LanguageCtrl;


text:
Here you may find thousands pre-made source code pieces for easy implementation in your own programming VBScript and VB6 projects. ByteScout Screen Capturing SDK helps with take manual screenshots during video recording in VBScript and VB6. ByteScout Screen Capturing SDK is the screen video recording SDK helps in quick implementation of screen video recording. WMV, AVI, WebM output options are available with adjustable quality, video size, framerate and video and audio codec. Includes special features like live multiple blacking out of selected areas, recording from web cam as main source and as overlay, optional watermarks for output video.

VBScript and VB6 code snippet like this for ByteScout Screen Capturing SDK works best when you need to quickly implement take manual screenshots during video recording in your VBScript and VB6 application. To do take manual screenshots during video recording in your VBScript and VB6 project or application you may simply copy & paste the code and then run your app! Use of ByteScout Screen Capturing SDK in VBScript and VB6 is also explained in the documentation included along with the product.

Free trial version of ByteScout Screen Capturing SDK is available on our website. Get it to try other samples for VBScript and VB6.

## REQUEST FREE TECH SUPPORT

[Click here to get in touch](https://bytescout.zendesk.com/hc/en-us/requests/new?subject=ByteScout%20Screen%20Capturing%20SDK%20Question)

or just send email to [support@bytescout.com](mailto:support@bytescout.com?subject=ByteScout%20Screen%20Capturing%20SDK%20Question)

## ON-PREMISE OFFLINE SDK

[Get Your 60 Day Free Trial](https://bytescout.com/download/web-installer?utm_source=github-readme)
[Explore SDK Docs](https://bytescout.com/documentation/index.html?utm_source=github-readme)
[Sign Up For Online Training](https://academy.bytescout.com/)

## ON-DEMAND REST WEB API

[Get your API key](https://pdf.co/documentation/api?utm_source=github-readme)
[Explore Web API Documentation](https://pdf.co/documentation/api?utm_source=github-readme)
[Explore Web API Samples](https://github.com/bytescout/ByteScout-SDK-SourceCode/tree/master/PDF.co%20Web%20API)

## VIDEO REVIEW

[https://www.youtube.com/watch?v=fujkvtWUVCw](https://www.youtube.com/watch?v=fujkvtWUVCw)

<!-- code block begin -->

##### ****RecordVideoAndScreenshots.vbs:**

```
' create video capturer activex object
Set capturer = CreateObject("BytescoutScreenCapturing.Capturer")

' set output video file name to .WMV or .AVI file
capturer.OutputFileName = "EntireScreenCaptured.wmv"

' set capturing type to the caScreen =3 to capture the entire screen
capturer.CapturingType = 3

' output video width
capturer.OutputWidth = 640

' output video height
capturer.OutputHeight = 480

' uncomment to set Bytescout Lossless Video format output video compression method
' do not forget to set file to .avi format if you use Video Codec Name
' capturer.CurrentVideoCodecName = "Bytescout Lossless";

' uncomment to enable recording of semitransparent or layered windows (Warning: may cause mouse cursor flickering)
' capturer.CaptureTransparentControls = true

' set the screenshot saving mode type: 0=none (default), 1=onmouseclick, 2=ontimer, 3=manual (using TakeScreenshot() method only)
capturer.ScreenshotSavingType = 3 ' take screenshots on mouse click

' set output folder for the screenshots
set fso = CreateObject("Scripting.FileSystemObject")
' directory in which this script is currently running
CurrentDirectory = fso.GetAbsolutePathName(".")
capturer.ScreenshotOutputFolder = CurrentDirectory ' set output folder to the current one

' set image format for the screenshots (png = 0, bmp = 1)
capturer.ScreenshotImageFormat = 0

MsgBox "This script will record 640x480 video from entire screen for 10 seconds. Output video will go to EntireScreenCaptured.wmv"

' run video capturing
capturer.Run()

' IMPORTANT: if you want to check for some code if need to stop the recording then make sure you are
' using Thread.Sleep(1) inside the checking loop, so you have the loop like
' Do
' Thread.Sleep(1)
' While StopButtonNotClicked

capturer.TakeScreenshot "screenshot1.png"

' sleep 2 seconds
WScript.sleep (2000)

capturer.TakeScreenshot "screenshot2.png"

' sleep 8 seconds
WScript.sleep (8000)

capturer.TakeScreenshot "screenshot3.png"

' stop capturing
capturer.Stop()

' destroy Capturer object so the video will be saved into the disk
Set capturer = Nothing

```

<!-- code block end -->


text:
FROM debian:jessie

RUN apt-get update && apt-get install -y texlive-full biber latexmk make


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace FourSquare.SharpSquare.Entities
{
    public class Price : FourSquareEntity
	{
        public string tier
        {
            get;
            set;
        }

        public string message
        {
            get;
            set;
        }
	}
}


text:
layout: post
title: number-200-and-galleries-are-working
---
It took a bit of time, but I finally hit 200 posts!

It took me almost as long to get the galleries working as it did to hit
200.  To everybody that was waiting on that, I apologize.  I didn't
think that it would take as long as it did.  And if it wasn't for
inspiration striking at lunch today, I'm not sure I would have ever
gotten the galleries functioning properly.

Here are some things to be looking forward to:

1.) I did get a designer to work on something for the site.  I've been
working on getting onto the site.  I have the main page down, but I need
to hit a few more before I can migrate to it.

2.) As soon as we get some more space on the server, I will probably add
the Community Server FTP service, so everybody can go nuts uploading
pictures to the site.

3.) Server…..Needs…….RAM……Will….Get…..Some….Soon…..

4.) Before number 1 gets done, I have a feeling that CS 1.1 will be
loaded onto the site.

5.) Depending on what features are available in CS 1.1, I might add in
some more features to the MetaBlogApi.  (Time will tell)


text:
FiftyTwoFrames
==============

An elegant rendition of the notable Fifty-Two Frames Facebook page.

Seamless asynchronous photo downloading with comment section and full photo browser

![52framesdemo1](https://cloud.githubusercontent.com/assets/5007053/10713827/12381254-7a89-11e5-8c1b-4869d3fa1a7f.gif)

Grid view with paging

![52framesdemo3](https://cloud.githubusercontent.com/assets/5007053/10713831/331c9a62-7a89-11e5-8795-fffbcad979db.gif)

Album selection by category and year

![52framesdemo2](https://cloud.githubusercontent.com/assets/5007053/10713833/4a1b7026-7a89-11e5-9576-d27689ef7a7b.gif)


text:
layout: page
title: Kaufman Family Reunion
date: 2016-05-24
author: Margaret Powers
tags: weekly links, java
status: published
summary: Curabitur a rhoncus elit, eget ornare.
banner: images/banner/meeting-01.jpg
booking:
  startDate: 07/08/2017
  endDate: 07/09/2017
  ctyhocn: CHIHMHX
  groupCode: KFR
published: true
---
In hac habitasse platea dictumst. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Praesent ultricies at eros quis dictum. Suspendisse potenti. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Maecenas sollicitudin nibh diam, sed dapibus dui suscipit eget. Donec at mi a tortor elementum facilisis. Aliquam congue odio sed diam molestie consequat. Sed ut tempor nisl. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Ut vulputate magna orci. Nam et malesuada elit. Proin dolor est, imperdiet sed mauris id, accumsan efficitur odio. Interdum et malesuada fames ac ante ipsum primis in faucibus. Ut congue tortor ipsum, at gravida lectus finibus et. Donec at vulputate massa.

* In eleifend erat ut faucibus condimentum
* Nunc condimentum justo a orci accumsan pellentesque
* Maecenas eu dui sit amet lorem porta accumsan
* Aliquam at sapien interdum, tempus orci eget, ullamcorper nunc
* Mauris quis lacus finibus, accumsan enim id, rhoncus est.

Pellentesque rhoncus orci in cursus pharetra. Mauris dignissim malesuada odio, quis lobortis lacus consectetur at. Integer interdum molestie rutrum. Fusce sodales lacus sit amet odio luctus, id rutrum metus blandit. Etiam laoreet orci sit amet tellus rhoncus fermentum. Nam feugiat lacus ac enim tristique ultrices. Suspendisse quis metus id arcu suscipit ornare sed at purus. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Praesent vel tellus nec justo tincidunt gravida. Mauris id vulputate elit, a feugiat mi. Etiam consequat, velit a gravida consequat, diam risus maximus est, in lobortis elit nibh ut justo. Nullam sollicitudin mattis ligula, ac sagittis enim fringilla non.
Etiam molestie, neque sed tempor interdum, nisl arcu venenatis nibh, at euismod libero nibh nec metus. Curabitur semper tristique ligula sit amet vehicula. Fusce pharetra condimentum orci at viverra. Quisque eget dolor congue, varius turpis et, tincidunt nibh. Vestibulum vitae efficitur massa, id scelerisque felis. Duis non interdum arcu, quis iaculis mi. Duis vitae massa orci.


text:
package net.geforcemods.securitycraft.inventory;

import net.minecraft.core.NonNullList;
import net.minecraft.world.item.ItemStack;
import net.minecraftforge.items.ItemStackHandler;

public class ExtractOnlyItemStackHandler extends ItemStackHandler {
	public ExtractOnlyItemStackHandler(NonNullList<ItemStack> stacks) {
		super(stacks);
	}

	@Override
	public void setStackInSlot(int slot, ItemStack stack) {}

	@Override
	public ItemStack insertItem(int slot, ItemStack stack, boolean simulate) {
		return stack;
	}

	@Override
	public boolean isItemValid(int slot, ItemStack stack) {
		return false;
	}
}


text:
class Symbol

  def pluralize
    self.to_s.pluralize.to_sym
  end

end


text:
@interface NSDateTest : SenTestCase {

}

@end


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Lenzites flaccida f. dichroa Speg.

### Remarks
null


text:
package frames

import (
	"encoding/binary"
	"errors"
	"fmt"

	"github.com/Azure/azure-sdk-for-go/sdk/messaging/azservicebus/internal/go-amqp/internal/buffer"
	"github.com/Azure/azure-sdk-for-go/sdk/messaging/azservicebus/internal/go-amqp/internal/encoding"
)

const HeaderSize = 8

// Frame structure:
//
//     header (8 bytes)
//       0-3: SIZE (total size, at least 8 bytes for header, uint32)
//       4:   DOFF (data offset,at least 2, count of 4 bytes words, uint8)
//       5:   TYPE (frame type)
//                0x0: AMQP
//                0x1: SASL
//       6-7: type dependent (channel for AMQP)
//     extended header (opt)
//     body (opt)

// Header in a structure appropriate for use with binary.Read()
type Header struct {
	// size: an unsigned 32-bit integer that MUST contain the total frame size of the frame header,
	// extended header, and frame body. The frame is malformed if the size is less than the size of
	// the frame header (8 bytes).
	Size uint32
	// doff: gives the position of the body within the frame. The value of the data offset is an
	// unsigned, 8-bit integer specifying a count of 4-byte words. Due to the mandatory 8-byte
	// frame header, the frame is malformed if the value is less than 2.
	DataOffset uint8
	FrameType  uint8
	Channel    uint16
}

// ParseHeader reads the header from r and returns the result.
//
// No validation is done.
func ParseHeader(r *buffer.Buffer) (Header, error) {
	buf, ok := r.Next(8)
	if !ok {
		return Header{}, errors.New("invalid frameHeader")
	}
	_ = buf[7]

	fh := Header{
		Size:       binary.BigEndian.Uint32(buf[0:4]),
		DataOffset: buf[4],
		FrameType:  buf[5],
		Channel:    binary.BigEndian.Uint16(buf[6:8]),
	}

	if fh.Size < HeaderSize {
		return fh, fmt.Errorf("received frame header with invalid size %d", fh.Size)
	}

	if fh.DataOffset < 2 {
		return fh, fmt.Errorf("received frame header with invalid data offset %d", fh.DataOffset)
	}

	return fh, nil
}

// ParseBody reads and unmarshals an AMQP frame.
func ParseBody(r *buffer.Buffer) (FrameBody, error) {
	payload := r.Bytes()

	if r.Len() < 3 || payload[0] != 0 || encoding.AMQPType(payload[1]) != encoding.TypeCodeSmallUlong {
		return nil, errors.New("invalid frame body header")
	}

	switch pType := encoding.AMQPType(payload[2]); pType {
	case encoding.TypeCodeOpen:
		t := new(PerformOpen)
		err := t.Unmarshal(r)
		return t, err
	case encoding.TypeCodeBegin:
		t := new(PerformBegin)
		err := t.Unmarshal(r)
		return t, err
	case encoding.TypeCodeAttach:
		t := new(PerformAttach)
		err := t.Unmarshal(r)
		return t, err
	case encoding.TypeCodeFlow:
		t := new(PerformFlow)
		err := t.Unmarshal(r)
		return t, err
	case encoding.TypeCodeTransfer:
		t := new(PerformTransfer)
		err := t.Unmarshal(r)
		return t, err
	case encoding.TypeCodeDisposition:
		t := new(PerformDisposition)
		err := t.Unmarshal(r)
		return t, err
	case encoding.TypeCodeDetach:
		t := new(PerformDetach)
		err := t.Unmarshal(r)
		return t, err
	case encoding.TypeCodeEnd:
		t := new(PerformEnd)
		err := t.Unmarshal(r)
		return t, err
	case encoding.TypeCodeClose:
		t := new(PerformClose)
		err := t.Unmarshal(r)
		return t, err
	case encoding.TypeCodeSASLMechanism:
		t := new(SASLMechanisms)
		err := t.Unmarshal(r)
		return t, err
	case encoding.TypeCodeSASLChallenge:
		t := new(SASLChallenge)
		err := t.Unmarshal(r)
		return t, err
	case encoding.TypeCodeSASLOutcome:
		t := new(SASLOutcome)
		err := t.Unmarshal(r)
		return t, err
	default:
		return nil, fmt.Errorf("unknown performative type %02x", pType)
	}
}


text:
'use strict';

Object.defineProperty(exports, '__esModule', {
  value: true
});
exports.default = void 0;

function _path() {
  const data = _interopRequireDefault(require('path'));

  _path = function _path() {
    return data;
  };

  return data;
}

function _execa() {
  const data = _interopRequireDefault(require('execa'));

  _execa = function _execa() {
    return data;
  };

  return data;
}

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

function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
  try {
    var info = gen[key](arg);
    var value = info.value;
  } catch (error) {
    reject(error);
    return;
  }
  if (info.done) {
    resolve(value);
  } else {
    Promise.resolve(value).then(_next, _throw);
  }
}

function _asyncToGenerator(fn) {
  return function() {
    var self = this,
      args = arguments;
    return new Promise(function(resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        asyncGeneratorStep(gen, resolve, reject, _next, _throw, 'next', value);
      }
      function _throw(err) {
        asyncGeneratorStep(gen, resolve, reject, _next, _throw, 'throw', err);
      }
      _next(undefined);
    });
  };
}

function _objectSpread(target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i] != null ? arguments[i] : {};
    var ownKeys = Object.keys(source);
    if (typeof Object.getOwnPropertySymbols === 'function') {
      ownKeys = ownKeys.concat(
        Object.getOwnPropertySymbols(source).filter(function(sym) {
          return Object.getOwnPropertyDescriptor(source, sym).enumerable;
        })
      );
    }
    ownKeys.forEach(function(key) {
      _defineProperty(target, key, source[key]);
    });
  }
  return target;
}

function _defineProperty(obj, key, value) {
  if (key in obj) {
    Object.defineProperty(obj, key, {
      value: value,
      enumerable: true,
      configurable: true,
      writable: true
    });
  } else {
    obj[key] = value;
  }
  return obj;
}

const env = _objectSpread({}, process.env, {
  HGPLAIN: '1'
});

const adapter = {
  findChangedFiles: (function() {
    var _findChangedFiles = _asyncToGenerator(function*(cwd, options) {
      const includePaths = (options && options.includePaths) || [];
      const args = ['status', '-amnu'];

      if (options && options.withAncestor) {
        args.push('--rev', `min((!public() & ::.)+.)^`);
      } else if (options && options.changedSince) {
        args.push('--rev', `ancestor(., ${options.changedSince})`);
      } else if (options && options.lastCommit === true) {
        args.push('--change', '.');
      }

      args.push(...includePaths);
      const result = yield (0, _execa().default)('hg', args, {
        cwd,
        env
      });
      return result.stdout
        .split('\n')
        .filter(s => s !== '')
        .map(changedPath => _path().default.resolve(cwd, changedPath));
    });

    function findChangedFiles(_x, _x2) {
      return _findChangedFiles.apply(this, arguments);
    }

    return findChangedFiles;
  })(),
  getRoot: (function() {
    var _getRoot = _asyncToGenerator(function*(cwd) {
      try {
        const result = yield (0, _execa().default)('hg', ['root'], {
          cwd,
          env
        });
        return result.stdout;
      } catch (e) {
        return null;
      }
    });

    function getRoot(_x3) {
      return _getRoot.apply(this, arguments);
    }

    return getRoot;
  })()
};
var _default = adapter;
exports.default = _default;


text:
NS_ASSUME_NONNULL_BEGIN

@interface AppDelegate (StartUp)

- (void)startUp;

@end

NS_ASSUME_NONNULL_END


text: PHP introspection needed a refresh


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

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<title>IM: im_format_raw.h Source File</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="doxygen.css" rel="stylesheet" type="text/css"/>

im_format_raw.h

Go to the documentation of this file.

00001
00007
00008 #ifndef __IM_FORMAT_RAW_H
00009 #define __IM_FORMAT_RAW_H
00010
00011 #if     defined(__cplusplus)
00012 extern "C" {
00013 #endif
00014
00015 /** \defgroup raw RAW - RAW File
00016  *
00017  * \par
00018  * The file must be open/created with the functions \ref imFileOpenRaw and \ref imFileNewRaw.
00019  *
00020  * \section Description
00021  *
00022  * \par
00023  * Internal Implementation.
00024  * \par
00025  * Supports RAW binary images. This is an unstructured and uncompressed binary data.
00026  * It is NOT a Camera RAW file generated in many professional digital cameras. \n
00027  * You must know image parameters a priori and must set the IM_INT attributes "Width", "Height", "ColorMode", "DataType"
00028  * before the imFileReadImageInfo/imFileWriteImageInfo functions.
00029  * \par
00030  * The data must be in binary form, but can start in an arbitrary offset from the begining of the file, use attribute "StartOffset".
00031  * The default is at 0 offset.
00032  * \par
00033  * Integer sign and double precision can be converted using attribute "SwitchType". \n
00034  * The conversions will be BYTE<->CHAR, USHORT<->SHORT, INT<->UINT, FLOAT<->DOUBLE.
00035  * \par
00036  * Byte Order can be Little Endian (Intel=1) or Big Endian (Motorola=0), use the attribute "ByteOrder", the default is the current CPU.
00037  * \par
00038  * The lines can be aligned to a BYTE (1), WORD (2) or DWORD (4) boundaries, ue attribute "Padding" with the respective value.
00039  * \par
00040  * If the compression is ASCII the data is stored in textual format, instead of binary.
00041  * In this case SwitchType and ByteOrder are ignored, and Padding should be 0.
00042  * \par
00043  * See \ref im_raw.h
00044  *
00045  * \section Features
00046  *
00047 \verbatim
00048     Data Types: <all>
00049     Color Spaces: all, except MAP.
00050     Compressions:
00051       NONE - no compression [default]
00052       ASCII (textual data)
00053     Can have more than one image, depends on "StartOffset" attribute.
00054     Can have an alpha channel.
00055     Components can be packed or not.
00056     Lines arranged from top down to bottom or bottom up to top.
00057
00058     Attributes:
00059       Width, Height, ColorMode, DataType IM_INT (1)
00060       ImageCount[1], StartOffset[0], SwitchType[FALSE], ByteOrder[IM_LITTLEENDIAN], Padding[0]  IM_INT (1)
00061
00062     Comments:
00063       In fact ASCII is an expansion, not a compression, because the file will be larger than binary data.
00064 \endverbatim
00065  * \ingroup format */
00066 imFormat* imFormatInitRAW(void);
00067
00068 void imFormatFinishRAW(void);
00069
00070 #if defined(__cplusplus)
00071 }
00072 #endif
00073
00074 #endif

<address class="footer">Generated on Tue May 15 2012 12:06:06 for IM by

 1.7.1 </address>


text:
package adaptors.dailymotion.dmObjects;

import helper.utilities.Utilities;
import org.json.JSONObject;

public class dmUser {
	private String address;
	private String avatar120;
	private String avatar190;
	private String avatar240;
	private String avatar360;
	private String avatar480;
	private String avatar60;
	private String avatar720;
	private String background_url;
	private String banner_url;
	private long birthday;
	private String city;
	private String country;
	private long created_time;
	private String description;
	private String email;
	private String first_name;
	private String fullname;
	private String gender;
	private String id;
	private String language;
	private String last_name;
	private String parent;
	private String post_code;
	private String sceenname;
	private String status;
	private String url;
	private String username;
	private String videos_total;
	private String videostar_url;
	private String views_total;

	public dmUser() {
	}

	public dmUser(JSONObject json) {
		String avatar60 = "";
		String avatar120 = "";
		String avatar190 = "";
		String avatar240 = "";
		String avatar360 = "";
		String avatar480 = "";
		String avatar720 = "";
		String background_url = "";
		String banner_url = "";
		long created_time = -1;
		String description = "";
		String gender = "";
		String id = "";
		String status = "";
		String url = "";
		String username = "";
		String videos_total = "";
		String videostar_url = "";
		String views_total = "";
		String language = "";
		String parent = "";
		String address = "";
		long birthday = -1;
		String city = "";
		String country = "";
		String email = "";
		String first_name = "";
		String fullname = "";
		String last_name = "";
		String post_code = "";
		String screenname = "";
		if (Utilities.isValid(json.optString("id", null))) {
			avatar60 = json.optString("avatar_60_url", null);
			avatar120 = json.optString("avatar_120_url", null);
			avatar190 = json.optString("avatar_190_url", null);
			avatar240 = json.optString("avatar_240_url", null);
			avatar360 = json.optString("avatar_360_url", null);
			avatar480 = json.optString("avatar_480_url", null);
			avatar720 = json.optString("avatar_720_url", null);
			background_url = json.optString("background_url", null);
			banner_url = json.optString("banner_url", null);
			created_time = json.optLong("created_time", -1);
			description = json.optString("description", null);
			gender = json.optString("gender", null);
			id = json.optString("id", null);
			status = json.optString("status", null);
			url = json.optString("url", null);
			username = json.optString("username", null);
			videos_total = json.optString("videos_total", null);
			videostar_url = json.optString("videostar.url", null);
			views_total = json.optString("views_total", null);
			language = json.optString("language", null);
			parent = json.optString("parent", null);
			address = json.optString("address", null);
			birthday = json.optLong("birthday", -1);
			city = json.optString("city", null);
			country = json.optString("country", null);
			email = json.optString("email", null);
			first_name = json.optString("first_name", null);
			fullname = json.optString("fullname", null);
			last_name = json.optString("last_name", null);
			post_code = json.optString("post_code", null);
			screenname = json.optString("screenname", null);
		}
		else if (Utilities.isValid(json.optString("owner.id", null))) {
			avatar60 = json.optString("owner.avatar_60_url", null);
			avatar120 = json.optString("owner.avatar_120_url", null);
			avatar190 = json.optString("owner.avatar_190_url", null);
			avatar240 = json.optString("owner.avatar_240_url", null);
			avatar360 = json.optString("owner.avatar_360_url", null);
			avatar480 = json.optString("owner.avatar_480_url", null);
			avatar720 = json.optString("owner.avatar_720_url", null);
			background_url = json.optString("owner.background_url", null);
			banner_url = json.optString("owner.banner_url", null);
			created_time = json.optLong("owner.created_time", -1);
			description = json.optString("owner.description", null);
			gender = json.optString("owner.gender", null);
			id = json.optString("owner.id", null);
			status = json.optString("owner.status", null);
			url = json.optString("owner.url", null);
			username = json.optString("owner.username", null);
			videos_total = json.optString("owner.videos_total", null);
			videostar_url = json.optString("owner.videostar.url", null);
			views_total = json.optString("owner.views_total", null);
			language = json.optString("owner.language", null);
			parent = json.optString("owner.parent", null);
			address = json.optString("owner.address", null);
			birthday = json.optLong("owner.birthday", -1);
			city = json.optString("owner.city", null);
			country = json.optString("owner.country", null);
			email = json.optString("owner.email", null);
			first_name = json.optString("owner.first_name", null);
			fullname = json.optString("owner.fullname", null);
			last_name = json.optString("owner.last_name", null);
			post_code = json.optString("owner.post_code", null);
			screenname = json.optString("owner.screenname", null);
		}
		this.setPost_code(post_code);
		this.setAvatar60(avatar60);
		this.setAvatar120(avatar120);
		this.setAvatar190(avatar190);
		this.setAvatar240(avatar240);
		this.setAvatar360(avatar360);
		this.setAvatar480(avatar480);
		this.setAvatar720(avatar720);
		this.setBackground_url(background_url);
		this.setBanner_url(banner_url);
		this.setCreated_time(created_time);
		this.setDescription(description);
		this.setGender(gender);
		this.setId(id);
		this.setStatus(status);
		this.setUrl(url);
		this.setUsername(username);
		this.setVideos_total(videos_total);
		this.setVideostar_url(videostar_url);
		this.setViews_total(views_total);
		this.setLanguage(language);
		this.setParent(parent);
		this.setAddress(address);
		this.setBirthday(birthday);
		this.setCity(city);
		this.setCountry(country);
		this.setEmail(email);
		this.setFirst_name(first_name);
		this.setFullname(fullname);
		this.setLast_name(last_name);
		this.setSceenname(screenname);
	}

	public String getViews_total() {
		return views_total;
	}

	public void setViews_total(String views_total) {
		this.views_total = views_total;
	}

	public String getVideostar_url() {
		return videostar_url;
	}

	public void setVideostar_url(String videostar_url) {
		this.videostar_url = videostar_url;
	}

	public String getVideos_total() {
		return videos_total;
	}

	public void setVideos_total(String videos_total) {
		this.videos_total = videos_total;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public String getStatus() {
		return status;
	}

	public void setStatus(String status) {
		this.status = status;
	}

	public String getSceenname() {
		return sceenname;
	}

	public void setSceenname(String sceenname) {
		this.sceenname = sceenname;
	}

	public String getPost_code() {
		return post_code;
	}

	public void setPost_code(String post_code) {
		this.post_code = post_code;
	}

	public String getParent() {
		return parent;
	}

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

	public String getLast_name() {
		return last_name;
	}

	public void setLast_name(String last_name) {
		this.last_name = last_name;
	}

	public String getLanguage() {
		return language;
	}

	public void setLanguage(String language) {
		this.language = language;
	}

	public String getId() {
		return id;
	}

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

	public String getGender() {
		return gender;
	}

	public void setGender(String gender) {
		this.gender = gender;
	}

	public String getFullname() {
		return fullname;
	}

	public void setFullname(String fullname) {
		this.fullname = fullname;
	}

	public String getFirst_name() {
		return first_name;
	}

	public void setFirst_name(String first_name) {
		this.first_name = first_name;
	}

	public String getEmail() {
		return email;
	}

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

	public String getDescription() {
		return description;
	}

	public void setDescription(String description) {
		this.description = description;
	}

	public long getCreated_time() {
		return created_time;
	}

	public void setCreated_time(long created_time) {
		this.created_time = created_time;
	}

	public String getCountry() {
		return country;
	}

	public void setCountry(String country) {
		this.country = country;
	}

	public String getCity() {
		return city;
	}

	public void setCity(String city) {
		this.city = city;
	}

	public long getBirthday() {
		return birthday;
	}

	public void setBirthday(long birthday) {
		this.birthday = birthday;
	}

	public String getBanner_url() {
		return banner_url;
	}

	public void setBanner_url(String banner_url) {
		this.banner_url = banner_url;
	}

	public String getBackground_url() {
		return background_url;
	}

	public void setBackground_url(String background_url) {
		this.background_url = background_url;
	}

	public String getAvatar720() {
		return avatar720;
	}

	public void setAvatar720(String avatar720) {
		this.avatar720 = avatar720;
	}

	public String getAvatar60() {
		return avatar60;
	}

	public void setAvatar60(String avatar60) {
		this.avatar60 = avatar60;
	}

	public String getAvatar480() {
		return avatar480;
	}

	public void setAvatar480(String avatar480) {
		this.avatar480 = avatar480;
	}

	public String getAvatar360() {
		return avatar360;
	}

	public void setAvatar360(String avatar360) {
		this.avatar360 = avatar360;
	}

	public String getAvatar240() {
		return avatar240;
	}

	public void setAvatar240(String avatar240) {
		this.avatar240 = avatar240;
	}

	public String getAvatar190() {
		return avatar190;
	}

	public void setAvatar190(String avatar190) {
		this.avatar190 = avatar190;
	}

	public String getAvatar120() {
		return avatar120;
	}

	public void setAvatar120(String avatar120) {
		this.avatar120 = avatar120;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}
}


text:
export default {
  getPrefixedStyle: style => style
};


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

<title>ParticleEffect (libgdx API)</title>
<meta name="date" content="2016-02-02">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

				libgdx API

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

com.badlogic.gdx.graphics.g3d.particles

Class ParticleEffect

java.lang.Object

com.badlogic.gdx.graphics.g3d.particles.ParticleEffect

All Implemented Interfaces:

ResourceData.Configurable, Disposable

public class ParticleEffect
extends java.lang.Object
implements Disposable, ResourceData.Configurable

It's a set of particles controllers.
 It can be updated, rendered, transformed which means the changes will be applied
 on all the particles controllers.

Author:

inferno

Constructor Summary

Constructors

Constructor and Description

ParticleEffect()

ParticleEffect(ParticleController... emitters)

ParticleEffect(ParticleEffect effect)

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

ParticleEffect
copy()

void
dispose()

Releases all resources of this object.

void
draw()

void
end()

ParticleController
findController(java.lang.String name)

Returns the controller with the specified name, or null.

BoundingBox
getBoundingBox()

Array<ParticleController>
getControllers()

void
init()

void
load(AssetManager assetManager,
    ResourceData data)

Loads all the assets required by all the controllers inside this effect.

void
reset()

void
rotate(Quaternion rotation)

Applies the rotation to the current transformation matrix of each controller.

void
rotate(Vector3 axis,
      float angle)

Applies the rotation by the given angle around the given axis to the current transformation matrix of each controller.

void
save(AssetManager assetManager,
    ResourceData data)

Saves all the assets required by all the controllers inside this effect.

void
scale(float scaleX,
     float scaleY,
     float scaleZ)

Applies the scale to the current transformation matrix of each controller.

void
scale(Vector3 scale)

Applies the scale to the current transformation matrix of each controller.

void
setBatch(Array<ParticleBatch<?>> batches)

Assign one batch, among those passed in, to each controller.

void
setTransform(Matrix4 transform)

Sets the given transform matrix on each controller.

void
start()

void
translate(Vector3 translation)

Applies the translation to the current transformation matrix of each controller.

void
update()

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

ParticleEffect

public ParticleEffect()

ParticleEffect

public ParticleEffect(ParticleEffect effect)

ParticleEffect

public ParticleEffect(ParticleController... emitters)

Method Detail

init

public void init()

start

public void start()

end

public void end()

reset

public void reset()

update

public void update()

draw

public void draw()

setTransform

public void setTransform(Matrix4 transform)

Sets the given transform matrix on each controller.

rotate

public void rotate(Quaternion rotation)

Applies the rotation to the current transformation matrix of each controller.

rotate

public void rotate(Vector3 axis,
                   float angle)

Applies the rotation by the given angle around the given axis to the current transformation matrix of each controller.

Parameters:

axis - the rotation axis

angle - the rotation angle in degrees

translate

public void translate(Vector3 translation)

Applies the translation to the current transformation matrix of each controller.

scale

public void scale(float scaleX,
                  float scaleY,
                  float scaleZ)

Applies the scale to the current transformation matrix of each controller.

scale

public void scale(Vector3 scale)

Applies the scale to the current transformation matrix of each controller.

getControllers

public Array<ParticleController> getControllers()

Returns:

all particle controllers.

findController

public ParticleController findController(java.lang.String name)

Returns the controller with the specified name, or null.

dispose

public void dispose()

Description copied from interface: Disposable

Releases all resources of this object.

Specified by:

dispose in interface Disposable

getBoundingBox

public BoundingBox getBoundingBox()

Returns:

the merged bounding box of all controllers.

setBatch

public void setBatch(Array<ParticleBatch<?>> batches)

Assign one batch, among those passed in, to each controller.
 The batch must be compatible with the controller to be assigned.

copy

public ParticleEffect copy()

Returns:

a copy of this effect, should be used after the particle effect has been loaded.

save

public void save(AssetManager assetManager,
                 ResourceData data)

Saves all the assets required by all the controllers inside this effect.

Specified by:

save in interface ResourceData.Configurable

load

public void load(AssetManager assetManager,
                 ResourceData data)

Loads all the assets required by all the controllers inside this effect.

Specified by:

load in interface ResourceData.Configurable

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

libgdx API

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

				Copyright © 2010-2013 Mario Zechner (contact@badlogicgames.com), Nathan Sweet (admin@esotericsoftware.com)


text:
package android.marshon.likequanmintv.mvp.recommend.ui;

import android.marshon.likequanmintv.R;
import android.marshon.likequanmintv.base.BaseFragment;
import android.marshon.likequanmintv.librarys.http.delagate.IGetDataDelegate;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.zhy.adapter.recyclerview.base.ViewHolder;
import com.zhy.adapter.recyclerview.wrapper.LoadMoreCommonAdapter;

import java.util.List;

/**
 * Created by ITMarshon.Chen on 2016/11/25.
 * emal:itmarshon@163.com
 * desc:
 */

public abstract class BaseListFragment<T> extends BaseFragment implements IGetDataDelegate<List<T>>{

    private RecyclerView mRv;
    protected LoadMoreCommonAdapter<T> adapter;

    @Override
    protected int getLayoutId() {
        return R.layout.layout_listview;
    }

    @Override
    protected void initView(View rootView) {
        mRv=find(R.id.mRv);
        mRv.setLayoutManager(new GridLayoutManager(mActivity,2));
        adapter= new LoadMoreCommonAdapter<T>(mActivity, this.getListItemLayout()) {
            @Override
            protected void convert(ViewHolder holder, T t, int position) {
                convertItem(holder,t,position);
            }
        };
        mRv.setAdapter(adapter);
    }

    @Override
    public void getDataSuccess(List<T> datas) {
        adapter.refreshDatas(datas);
        adapter.notifyDataSetChanged();
    }

    public abstract int getListItemLayout();

    protected abstract void convertItem(ViewHolder holder, T t, int position);
}


text:
package org.apache.pdfbox.util;

import org.apache.pdfbox.cos.COSArray;
import org.apache.pdfbox.cos.COSFloat;
import org.apache.pdfbox.cos.COSNumber;

import java.awt.geom.AffineTransform;
import java.awt.geom.Point2D;
import java.util.Arrays;
import org.apache.pdfbox.cos.COSBase;

/**
 * This class will be used for matrix manipulation.
 *
 * @author Ben Litchfield
 */
public final class Matrix implements Cloneable
{
    public static final int SIZE = 9;
    private float[] single;

    /**
     * Constructor. This produces an identity matrix.
     */
    public Matrix()
    {
        // a b 0
        // c d 0
        // tx ty 1
        // note: hx and hy are reversed vs.the PDF spec as we use AffineTransform's definition x and y shear
        // sx hy 0
        // hx sy 0
        // tx ty 1
        single = new float[] { 1, 0, 0, 0, 1, 0, 0, 0, 1 };
    }

    /**
     * Constructor. This produces a matrix with the given array as data.
     * The source array is not copied or cloned.
     */
    private Matrix(float[] src)
    {
        single = src;
    }

    /**
     * Creates a matrix from a 6-element (a b c d e f) COS array.
     *
     * @param array source array, elements must be or extend COSNumber
     */
    private Matrix(COSArray array)
    {
        single = new float[SIZE];
        single[0] = ((COSNumber)array.getObject(0)).floatValue();
        single[1] = ((COSNumber)array.getObject(1)).floatValue();
        single[3] = ((COSNumber)array.getObject(2)).floatValue();
        single[4] = ((COSNumber)array.getObject(3)).floatValue();
        single[6] = ((COSNumber)array.getObject(4)).floatValue();
        single[7] = ((COSNumber)array.getObject(5)).floatValue();
        single[8] = 1;
    }

    /**
     * Creates a transformation matrix with the given 6 elements. Transformation matrices are
     * discussed in 8.3.3, "Common Transformations" and 8.3.4, "Transformation Matrices" of the PDF
     * specification. For simple purposes (rotate, scale, translate) it is recommended to use the
     * static methods below.
     *
     * Produces the following matrix:
     * a b 0
     * c d 0
     * e f 1
     *
     * @see Matrix#getRotateInstance(double, float, float)
     * @see Matrix#getScaleInstance(float, float)
     * @see Matrix#getTranslateInstance(float, float)
     *
     * @param a the X coordinate scaling element (m00) of the 3x3 matrix
     * @param b the Y coordinate shearing element (m10) of the 3x3 matrix
     * @param c the X coordinate shearing element (m01) of the 3x3 matrix
     * @param d the Y coordinate scaling element (m11) of the 3x3 matrix
     * @param e the X coordinate translation element (m02) of the 3x3 matrix
     * @param f the Y coordinate translation element (m12) of the 3x3 matrix
     */
    public Matrix(float a, float b, float c, float d, float e, float f)
    {
        single = new float[SIZE];
        single[0] = a;
        single[1] = b;
        single[3] = c;
        single[4] = d;
        single[6] = e;
        single[7] = f;
        single[8] = 1;
    }

    /**
     * Creates a matrix with the same elements as the given AffineTransform.
     * @param at matrix elements will be initialize with the values from this affine transformation, as follows:
     *
     *           scaleX shearY 0
     *           shearX scaleY 0
     *           transX transY 1
     *
     */
    public Matrix(AffineTransform at)
    {
        single = new float[SIZE];
        single[0] = (float)at.getScaleX();
        single[1] = (float)at.getShearY();
        single[3] = (float)at.getShearX();
        single[4] = (float)at.getScaleY();
        single[6] = (float)at.getTranslateX();
        single[7] = (float)at.getTranslateY();
        single[8] = 1;
    }

    /**
     * Convenience method to be used when creating a matrix from unverified data. If the parameter
     * is a COSArray with at least six numbers, a Matrix object is created from the first six
     * numbers and returned. If not, then the identity Matrix is returned.
     *
     * @param base a COS object, preferably a COSArray with six numbers.
     *
     * @return a Matrix object.
     */
    public static Matrix createMatrix(COSBase base)
    {
        if (!(base instanceof COSArray))
        {
            return new Matrix();
        }
        COSArray array = (COSArray) base;
        if (array.size() < 6)
        {
            return new Matrix();
        }
        for (int i = 0; i < 6; ++i)
        {
            if (!(array.getObject(i) instanceof COSNumber))
            {
                return new Matrix();
            }
        }
        return new Matrix(array);
    }

    /**
     * Create an affine transform from this matrix's values.
     *
     * @return An affine transform with this matrix's values.
     */
    public AffineTransform createAffineTransform()
    {
        return new AffineTransform(
            single[0], single[1],   // m00 m10 = scaleX shearY
            single[3], single[4],   // m01 m11 = shearX scaleY
            single[6], single[7] ); // m02 m12 = tx ty
    }

    /**
     * This will get a matrix value at some point.
     *
     * @param row The row to get the value from.
     * @param column The column to get the value from.
     *
     * @return The value at the row/column position.
     */
    public float getValue( int row, int column )
    {
        return single[row*3+column];
    }

    /**
     * This will set a value at a position.
     *
     * @param row The row to set the value at.
     * @param column the column to set the value at.
     * @param value The value to set at the position.
     */
    public void setValue( int row, int column, float value )
    {
        single[row*3+column] = value;
    }

    /**
     * Return a single dimension array of all values in the matrix.
     *
     * @return The values of this matrix.
     */
    public float[][] getValues()
    {
        float[][] retval = new float[3][3];
        retval[0][0] = single[0];
        retval[0][1] = single[1];
        retval[0][2] = single[2];
        retval[1][0] = single[3];
        retval[1][1] = single[4];
        retval[1][2] = single[5];
        retval[2][0] = single[6];
        retval[2][1] = single[7];
        retval[2][2] = single[8];
        return retval;
    }

    /**
     * Concatenates (premultiplies) the given matrix to this matrix.
     *
     * @param matrix The matrix to concatenate.
     */
    public void concatenate(Matrix matrix)
    {
        single = checkFloatValues(multiplyArrays(matrix.single, single));
    }

    /**
     * Translates this matrix by the given vector.
     *
     * @param vector 2D vector
     */
    public void translate(Vector vector)
    {
        translate(vector.getX(), vector.getY());
    }

    /**
     * Translates this matrix by the given amount.
     *
     * @param tx x-translation
     * @param ty y-translation
     */
    public void translate(float tx, float ty)
    {
        single[6] += tx * single[0] + ty * single[3];
        single[7] += tx * single[1] + ty * single[4];
        single[8] += tx * single[2] + ty * single[5];
        checkFloatValues(single);
    }

    /**
     * Scales this matrix by the given factors.
     *
     * @param sx x-scale
     * @param sy y-scale
     */
    public void scale(float sx, float sy)
    {
        single[0] *= sx;
        single[1] *= sx;
        single[2] *= sx;
        single[3] *= sy;
        single[4] *= sy;
        single[5] *= sy;
        checkFloatValues(single);
    }

    /**
     * Rotates this matrix by the given factors.
     *
     * @param theta The angle of rotation measured in radians
     */
    public void rotate(double theta)
    {
        concatenate(Matrix.getRotateInstance(theta, 0, 0));
    }

    /**
     * This method multiplies this Matrix with the specified other Matrix, storing the product in a
     * new instance. It is allowed to have (other == this).
     *
     * @param other the second operand Matrix in the multiplication; required
     * @return the product of the two matrices.
     */
    public Matrix multiply(Matrix other)
    {
        return new Matrix(checkFloatValues(multiplyArrays(single, other.single)));
    }

    private float[] checkFloatValues(float[] values)
    {
        if (!Float.isFinite(values[0]) || !Float.isFinite(values[1]) || !Float.isFinite(values[2])
                || !Float.isFinite(values[3]) || !Float.isFinite(values[4]) || !Float.isFinite(values[5])
                || !Float.isFinite(values[6]) || !Float.isFinite(values[7]) || !Float.isFinite(values[8]))
            throw new IllegalArgumentException("Multiplying two matrices produces illegal values");
        return values;
    }

    private float[] multiplyArrays(float[] a, float[] b)
    {
        float[] c = new float[SIZE];
        c[0] = a[0] * b[0] + a[1] * b[3] + a[2] * b[6];
        c[1] = a[0] * b[1] + a[1] * b[4] + a[2] * b[7];
        c[2] = a[0] * b[2] + a[1] * b[5] + a[2] * b[8];
        c[3] = a[3] * b[0] + a[4] * b[3] + a[5] * b[6];
        c[4] = a[3] * b[1] + a[4] * b[4] + a[5] * b[7];
        c[5] = a[3] * b[2] + a[4] * b[5] + a[5] * b[8];
        c[6] = a[6] * b[0] + a[7] * b[3] + a[8] * b[6];
        c[7] = a[6] * b[1] + a[7] * b[4] + a[8] * b[7];
        c[8] = a[6] * b[2] + a[7] * b[5] + a[8] * b[8];
        return c;
    }

    /**
     * Transforms the given point by this matrix.
     *
     * @param point point to transform
     */
    public void transform(Point2D point)
    {
        float x = (float)point.getX();
        float y = (float)point.getY();
        float a = single[0];
        float b = single[1];
        float c = single[3];
        float d = single[4];
        float e = single[6];
        float f = single[7];
        point.setLocation(x * a + y * c + e, x * b + y * d + f);
    }

    /**
     * Transforms the given point by this matrix.
     *
     * @param x x-coordinate
     * @param y y-coordinate
     *
     * @return the transformed point.
     */
    public Point2D.Float transformPoint(float x, float y)
    {
        float a = single[0];
        float b = single[1];
        float c = single[3];
        float d = single[4];
        float e = single[6];
        float f = single[7];
        return new Point2D.Float(x * a + y * c + e, x * b + y * d + f);
    }

    /**
     * Transforms the given vector by this matrix.
     *
     * @param vector 2D vector
     *
     * @return the transformed vector.
     */
    public Vector transform(Vector vector)
    {
        float a = single[0];
        float b = single[1];
        float c = single[3];
        float d = single[4];
        float e = single[6];
        float f = single[7];
        float x = vector.getX();
        float y = vector.getY();
        return new Vector(x * a + y * c + e, x * b + y * d + f);
    }

    /**
     * Convenience method to create a scaled instance.
     *
     * Produces the following matrix:
     * x 0 0
     * 0 y 0
     * 0 0 1
     *
     * @param x The xscale operator.
     * @param y The yscale operator.
     * @return A new matrix with just the x/y scaling
     */
    public static Matrix getScaleInstance(float x, float y)
    {
        return new Matrix(x, 0, 0, y, 0, 0);
    }

    /**
     * Convenience method to create a translating instance.
     *
     * Produces the following matrix:
     * 1 0 0
     * 0 1 0
     * x y 1
     *
     * @param x The x translating operator.
     * @param y The y translating operator.
     * @return A new matrix with just the x/y translating.
     */
    public static Matrix getTranslateInstance(float x, float y)
    {
        return new Matrix(1, 0, 0, 1, x, y);
    }

    /**
     * Convenience method to create a rotated instance.
     *
     * @param theta The angle of rotation measured in radians
     * @param tx The x translation.
     * @param ty The y translation.
     * @return A new matrix with the rotation and the x/y translating.
     */
    public static Matrix getRotateInstance(double theta, float tx, float ty)
    {
        float cosTheta = (float)Math.cos(theta);
        float sinTheta = (float)Math.sin(theta);

        return new Matrix(cosTheta, sinTheta, -sinTheta, cosTheta, tx, ty);
    }

    /**
     * Produces a copy of the first matrix, with the second matrix concatenated.
     *
     * @param a The matrix to copy.
     * @param b The matrix to concatenate.
     *
     * @return a copy of the first matrix with the second matrix concatenated
     */
    public static Matrix concatenate(Matrix a, Matrix b)
    {
        return b.multiply(a);
    }

    /**
     * Clones this object.
     * @return cloned matrix as an object.
     */
    @Override
    public Matrix clone()
    {
        return new Matrix(single.clone());
    }

    /**
     * Returns the x-scaling factor of this matrix. This is calculated from the scale and shear.
     *
     * @return The x-scaling factor.
     */
    public float getScalingFactorX()
    {
        /*
         * BM: if the trm is rotated, the calculation is a little more complicated
         *
         * The rotation matrix multiplied with the scaling matrix is:
         * (   x   0   0)    ( cos  sin  0)    ( x*cos x*sin   0)
         * (   0   y   0) *  (-sin  cos  0)  = (-y*sin y*cos   0)
         * (   0   0   1)    (   0    0  1)    (     0     0   1)
         *
         * So, if you want to deduce x from the matrix you take
         * M(0,0) = x*cos and M(0,1) = x*sin and use the theorem of Pythagoras
         *
         * sqrt(M(0,0)^2+M(0,1)^2) =
         * sqrt(x2*cos2+x2*sin2) =
         * sqrt(x2*(cos2+sin2)) = <- here is the trick cos2+sin2 is one
         * sqrt(x2) =
         * abs(x)
         */
        if (Float.compare(single[1], 0.0f) != 0)
        {
            return (float) Math.sqrt(Math.pow(single[0], 2) +
                                      Math.pow(single[1], 2));
        }
        return single[0];
    }

    /**
     * Returns the y-scaling factor of this matrix. This is calculated from the scale and shear.
     *
     * @return The y-scaling factor.
     */
    public float getScalingFactorY()
    {
        if (Float.compare(single[3], 0.0f) != 0)
        {
            return (float) Math.sqrt(Math.pow(single[3], 2) +
                                      Math.pow(single[4], 2));
        }
        return single[4];
    }

    /**
     * Returns the x-scaling element of this matrix.
     *
     * @see #getScalingFactorX()
     *
     * @return the x-scaling element of the matrix
     */
    public float getScaleX()
    {
        return single[0];
    }

    /**
     * Returns the y-shear element of this matrix.
     *
     * @return the y-shear element of the matrix
     */
    public float getShearY()
    {
        return single[1];
    }

    /**
     * Returns the x-shear element of this matrix.
     *
     * @return the x-sheard element of the matrix
     */
    public float getShearX()
    {
        return single[3];
    }

    /**
     * Returns the y-scaling element of this matrix.
     *
     * @see #getScalingFactorY()
     *
     * @return the y-scaling element of the matrix
     */
    public float getScaleY()
    {
        return single[4];
    }

    /**
     * Returns the x-translation element of this matrix.
     *
     * @return the x-translation element of the matrix
     */
    public float getTranslateX()
    {
        return single[6];
    }

    /**
     * Returns the y-translation element of this matrix.
     *
     * @return the y-translation element of the matrix
     */
    public float getTranslateY()
    {
        return single[7];
    }

    /**
     * Returns a COS array which represent the geometric relevant components of the matrix. The last column of the
     * matrix is ignored, only the first two columns are returned. This is analog to the Matrix(COSArray) constructor.
     *
     * @return a COSArray representing the geometric relevant components of the matrix
     */
    public COSArray toCOSArray()
    {
        COSArray array = new COSArray();
        array.add(new COSFloat(single[0]));
        array.add(new COSFloat(single[1]));
        array.add(new COSFloat(single[3]));
        array.add(new COSFloat(single[4]));
        array.add(new COSFloat(single[6]));
        array.add(new COSFloat(single[7]));
        return array;
    }

    @Override
    public String toString()
    {
        return "[" +
            single[0] + "," +
            single[1] + "," +
            single[3] + "," +
            single[4] + "," +
            single[6] + "," +
            single[7] + "]";
    }

    @Override
    public int hashCode()
    {
        return Arrays.hashCode(single);
    }

    @Override
    public boolean equals(Object obj)
    {
        if (this == obj)
        {
            return true;
        }
        if (obj == null)
        {
            return false;
        }
        if (getClass() != obj.getClass())
        {
            return false;
        }
        return Arrays.equals(this.single, ((Matrix) obj).single);
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Web;
using SSW.Data.Interfaces;
using SSW.DataOnion.UserGroupDemo.DataInterfaces.Repositories;
using SSW.DataOnion.UserGroupDemo.Domain;

namespace SSW.DataOnion.UserGroupDemo.WebUI.ViewModels
{
    public class StudentVm
    {

        public int Id { get; set; }

        public string FirstName { get; set; }

        public string LastName { get; set; }

        public int CountCourses { get; set; }

        public int CountActivities { get; set; }

        public byte[] RowVersion { get; set; }

        public string RowVersionBase64
        {
            get { return this.RowVersion == null ? null : Convert.ToBase64String(this.RowVersion); }
            set { this.RowVersion = Convert.FromBase64String(value); }
        }

    }

    public interface IStudentVmMapper
    {
        StudentVm GetViewModel(int id);

        StudentVm ToViewModel(Student entity);

        Student SaveViewModel(StudentVm model);

        IQueryable<StudentVm> GetList();

    }

    public class StudentVmMapper : IStudentVmMapper
    {

        private readonly IStudentRepository _studentRepository;
        private readonly IUnitOfWork _unitOfWork;

        public StudentVmMapper(IStudentRepository studentRepository,
            IUnitOfWork unitOfWork)
        {
            _studentRepository = studentRepository;
            _unitOfWork = unitOfWork;
        }

        public StudentVm GetViewModel(int id)
        {
            var entity = _studentRepository.Find(id);
            return this.ToViewModel(entity);
        }

        public StudentVm ToViewModel(Student entity)
        {
            return ViewModelProjection.Compile().Invoke(entity);
        }

        public Student SaveViewModel(StudentVm model)
        {
            var entity = model.Id > 0
                ? _studentRepository.Find(model.Id)
                : new Student();

            entity.FirstName = model.FirstName;
            entity.LastName = model.LastName;
            entity.RowVersion = model.RowVersion;

            return entity;
        }

        public IQueryable<StudentVm> GetList()
        {
            return _studentRepository.Get()
                .Select(ViewModelProjection);
        }

        protected   Expression<Func<Student, StudentVm>> ViewModelProjection {
            get
            {
                return s => new StudentVm()
                {
                    Id = s.Id,
                    FirstName = s.FirstName,
                    LastName = s.LastName,
                    CountActivities = s.Activities.Count(),
                    CountCourses = s.Courses.Count(),
                    RowVersion = s.RowVersion
                };
            }
        }

    }

}


text:
using FireSharp.Interfaces;
using Newtonsoft.Json;

namespace FireSharp.Serialization.JsonNet
{
    internal class JsonSerializerWrapper : ISerializer
    {
        public T Deserialize<T>(string json)
        {
            return JsonConvert.DeserializeObject<T>(json);
        }

        public string Serialize<T>(T value)
        {
            return JsonConvert.SerializeObject(value);
        }
    }
}


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

<TITLE>
P-Index
</TITLE>

<META NAME="date" CONTENT="2009-06-19">

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

      Package
      Class
      Use
      Tree
      Deprecated
    Index
      Help

 PREV LETTER
 NEXT LETTER

  FRAMES
 NO FRAMES

  All Classes

A B C D E F G H I J K L M N O P Q R S T Y

P

parse() -
Method in class android.CSLite.OptData

Put the data from params into maps that we can use

parseAccept(StringTokenizer) -
Static method in class android.CSLite.MessageReceiver

Parse accept message

parseAddPl(StringTokenizer) -
Static method in class android.CSLite.MessageReceiver

Parse add_pl message

parseDrop(StringTokenizer) -
Static method in class android.CSLite.MessageReceiver

Parse drop message

parseDropPU(StringTokenizer) -
Static method in class android.CSLite.MessageReceiver

Parse drop_pu message

parseEnd(StringTokenizer, Context) -
Static method in class android.CSLite.MessageReceiver

Parse end message

parseFire(StringTokenizer) -
Static method in class android.CSLite.MessageReceiver

Parse fire message

parseHit(StringTokenizer) -
Static method in class android.CSLite.MessageReceiver

Parse hit message

parseJoin(StringTokenizer) -
Static method in class android.CSLite.MessageReceiver

Parse JOIN message

parseLeave(StringTokenizer) -
Static method in class android.CSLite.MessageReceiver

Parse leave message

parseLeft(StringTokenizer) -
Static method in class android.CSLite.MessageReceiver

Parse left message

parseMine(StringTokenizer) -
Static method in class android.CSLite.MessageReceiver

parse mine message

parseMineDes(StringTokenizer) -
Static method in class android.CSLite.MessageReceiver

Parse mine_des message

parseMyPos(StringTokenizer) -
Static method in class android.CSLite.MessageReceiver

Parse my_pos message (currently unimplemented)

parseMyStat(StringTokenizer, Context) -
Static method in class android.CSLite.MessageReceiver

Parse mystat message

parseNewName(StringTokenizer) -
Static method in class android.CSLite.MessageReceiver

Parse newname message

parseRejoin(StringTokenizer) -
Static method in class android.CSLite.MessageReceiver

Parse rejoin message

parseWhoAmI(StringTokenizer) -
Static method in class android.CSLite.MessageReceiver

Parse the whoami message

parseYouAre(StringTokenizer) -
Static method in class android.CSLite.MessageReceiver

Parse YOuare message

phoneNumber -
Variable in class android.CSLite.Player

pitch -
Static variable in class android.CSLite.Game

PIXELS_PER_METER -
Static variable in class android.CSLite.RadarThread

play(Context, int) -
Static method in class android.CSLite.Radio

Plays a sound file on the players phone

player -
Static variable in class android.CSLite.Game

Player - Class in android.CSLite
THis class stores info on a player in the game
Player(String) -
Constructor for class android.CSLite.Player

Make a player

player_location -
Static variable in class android.CSLite.RadarThread

players -
Static variable in class android.CSLite.Game

point(Location, double, double, double) -
Static method in class android.CSLite.LocationStuff

Compute a point which is along a vector a certain distance away

PORT -
Static variable in class android.CSLite.Game

pupulateDropRate() -
Method in class android.CSLite.Options

Populate the drop box rates (times between drops) in the UI

      Package
      Class
      Use
      Tree
      Deprecated
    Index
      Help

 PREV LETTER
 NEXT LETTER

  FRAMES
 NO FRAMES

  All Classes

A B C D E F G H I J K L M N O P Q R S T Y


text:
version();
"transform-version-call";


text:
package org.jboss.arquillian.junit5.container;

import org.jboss.arquillian.container.test.spi.client.deployment.AuxiliaryArchiveAppender;
import org.jboss.arquillian.core.spi.LoadableExtension;

public class JUnitJupiterContainerExtension implements LoadableExtension {

    @Override
    public void register(ExtensionBuilder builder) {
        builder
                .service(AuxiliaryArchiveAppender.class, JUnitJupiterDeploymentAppender.class)
                .observer(RunModeEventHandler.class)
        ;
    }
}


text:
import sys
import timeit
import time
from cassandra.cluster import Cluster
from cassandra.concurrent import execute_concurrent_with_args

def main(argv):

    cluster = Cluster(['10.2.3.31', "10.2.3.30", "10.2.3.5"])
    # cluster = Cluster(['10.2.2.187', "10.2.2.180", "10.2.0.157"])
    session = cluster.connect("group4")

    query_1 = "SELECT SERVICE_NODE_ID FROM CDR WHERE MOBILE_ID_TYPE IN (1,2,3,4) AND CITY_ID > 1 AND CITY_ID < 5 LIMIT 100;"
    query_2 = "SELECT COUNT(SEQ_NUM) FROM CDR WHERE MOBILE_ID_TYPE = 1 AND CITY_ID =5 AND MONTH_DAY = 14 AND MSC_CODE > 1 AND MSC_CODE < 1500 LIMIT 100"
    query_3 = "SELECT SEQ_NUM FROM CDR WHERE MOBILE_ID_TYPE IN (1,3,4,5) AND (CITY_ID, MONTH_DAY, MSC_CODE, SERVICE_NODE_ID, SEQ_NUM) > (1,2,10,5,100) AND (CITY_ID, MONTH_DAY, MSC_CODE, SERVICE_NODE_ID, SEQ_NUM) < (7,20,50,9,400) LIMIT 100"
    query_4 = "SELECT GROUP_AND_COUNT(CITY_ID) FROM CDR WHERE MOBILE_ID_TYPE = 1 AND CITY_ID IN (0,1,2) AND (MONTH_DAY, MSC_CODE) >= (1,10) AND (MONTH_DAY, MSC_CODE) <= (10,20)"
    query_5 = "SELECT GROUP_AND_COUNT(MONTH_DAY) FROM CDR WHERE MOBILE_ID_TYPE = 2 AND (CITY_ID, MONTH_DAY, MSC_CODE, SERVICE_NODE_ID, SEQ_NUM) >= (1,1,30,7,100) AND (CITY_ID, MONTH_DAY, MSC_CODE, SERVICE_NODE_ID, SEQ_NUM) <= (1,10,50,9,200)"

    start_time = timeit.default_timer()
    rows = session.execute(query_1)
    seconds_1 = timeit.default_timer() - start_time
    print "Query 1 finished in " + str( seconds_1 ) + " seconds."

    start_time = timeit.default_timer()
    rows = session.execute(query_2)
    seconds_2 = timeit.default_timer() - start_time
    print "Query 2 finished in " + str( seconds_2 ) + " seconds."

    start_time = timeit.default_timer()
    rows = session.execute(query_3)
    seconds_3 = timeit.default_timer() - start_time
    print "Query 3 finished in " + str( seconds_3 ) + " seconds."

    start_time = timeit.default_timer()
    rows = session.execute(query_4)
    seconds_4 = timeit.default_timer() - start_time
    print "Query 4 finished in " + str( seconds_4 ) + " seconds."

    start_time = timeit.default_timer()
    rows = session.execute(query_5)
    seconds_5 = timeit.default_timer() - start_time
    print "Query 5 finished in " + str( seconds_5 ) + " seconds."

if __name__ == "__main__":
    main(sys.argv)


text:
---
layout: post
category: JUnit
title: JUnit4 使用进阶五
tags: ['Junit4']
author: 唐 治
email: tangzhi@asiainfo-linkage.com
description: 在进阶二中,我们介绍了`@Rule`的两个用法,对异常进行检查和对超时时间的设定。其实,Rule还有很多用途,本文将做进一步介绍

---

在[进阶二]中,我们介绍了`@Rule`的两个用法,对异常进行检查和对超时时间的设定。其实,Rule还有很多用途,本文将做进一步介绍。

###Rule的应用

Rule将在框架的很多方面提供解决方案。下面一一举例:

1. **TemporaryFolder**

	`TemporaryFolder`作为Rule,可以运行在测试过程中创建临时文件或者临时目录,当测试结束后,框架会自动删除。

	见实例:

		  public static class HasTempFolder {
          @Rule
          public TemporaryFolder folder = new TemporaryFolder();

          @Test
          public void testUsingTempFolder() throws IOException {
            File createdFile = folder.newFile("myfile.txt");
            File createdFolder = folder.newFolder("subfolder");
            // ...
          }
        }

	* `TemporaryFolder#newFolder(String... folderNames)`可以根据输入的参数创建目录。如果是多级目录,可以递归创建。
	* `TemporaryFolder#newFile()`可以创建一个随机名字的临时文件;
	* `TemporaryFolder##newFolder()` 可以创建一个随机名字的临时目录。

1. **ExternalResource**

	`ExternalResource`可以设置测试前后需要做的事情(比如:文件、socket、服务、数据库的连接与关闭)。这个我们在之前的[进阶二]中稍有提及。

	见实例:

	    public static class UsesExternalResource {
          Server myServer = new Server();

          @Rule
          public ExternalResource resource = new ExternalResource() {
            @Override
            protected void before() throws Throwable {
              myServer.connect();
            };

            @Override
            protected void after() {
              myServer.disconnect();
            };
          };

          @Test
          public void testFoo() {
            new Client().run(myServer);
          }
        }

    * `ExternalResource#before`会在每个测试之前处理;`#after`会在每个测试之后处理;
	* 关于`ExternalResource`与`@Before`已经`@After`等标记步骤的执行顺序,我们会在本文后面部分介绍。

1. **ErrorCollector**

	`ErrorCollector`这个Rule,在出现一个错误后,还可以让测试继续进行下去。

	他提供三个方法:

		checkThat(final T value, Matcher<T> matcher)
		checkSucceeds(Callable<Object> callable)
		addError(Throwable error)

	前面两个是用来处理断言的,最后一个是添加错误至错误列表中。

	看下面例子:

        package mytest;

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

        import java.util.concurrent.Callable;

        import org.junit.Rule;
        import org.junit.Test;
        import org.junit.rules.ErrorCollector;

        public class JUnitCoreErrorControllerRuleTest {

          private final int multiplesOf2[] = { 0, 2, 4, 7, 8, 11, 12 };

          @Rule
          public ErrorCollector errorCollector = new ErrorCollector();

          /*
           * 下面这个测试,会报告两个failures。这一点和下面的checkSucceeds测试不同
           */
          @Test
          public void testMultiplesOf2() {
            int multiple = 0;
            for (int multipleOf2 : multiplesOf2) {
              // Will count the number of issues in this list
              // - 3*2 = 6 not 7, 5*2 = 10 not 11 : 2 Failures
              errorCollector.checkThat(2 * multiple, is(multipleOf2));
              multiple++;
            }
          }

          /*
           * 下面代码中有两个断言会失败,但每次运行JUnit框架只会报告一个。这一点和上面的checkThat测试不同,可以对比一下。
           */
          @Test
          public void testCallableMultiples() {
            errorCollector.checkSucceeds(new Callable<Object>() {
              public Object call() throws Exception {
                assertThat(2 * 2, is(5));
                assertThat(2 * 3, is(6));
                assertThat(2 * 4, is(8));
                assertThat(2 * 5, is(9));
                return null;
              }
            });
          }

          /*
           * 下面运行时,会报告2个错误
           */
          @Test
          public void testAddingAnError() {
            assertThat(2 * 2, is(4));
            errorCollector.addError(new Throwable("Error Collector added an error"));
            assertThat(2 * 3, is(6));
            errorCollector.addError(new Throwable(
                "Error Collector added a second error"));
          }

        }

    运行结果,类似下面:

    	Failed tests:

    	testCallableMultiples(mytest.JUnitCoreErrorControllerRuleTest):
		Expected: is <5>
     		but: was <4>

  		testMultiplesOf2(mytest.JUnitCoreErrorControllerRuleTest):
		Expected: is <7>
     		but: was <6>

  		testMultiplesOf2(mytest.JUnitCoreErrorControllerRuleTest):
		Expected: is <11>
     		but: was <10>

     	Tests in error:
  		testAddingAnError(tangzhi.mytest.JUnitCoreErrorControllerRuleTest): Error Collector added an error

  		testAddingAnError(tangzhi.mytest.JUnitCoreErrorControllerRuleTest): Error Collector added a second error

	从这个例子,可以看出:

	* `ErrorCollector#checkThat` 会报告测试中的每一个failures
	* `ErrorCollector#checkSucceeds` 只会检查是否成功,如果不成功,只报告第一个导致不成功的failure
	* `ErrorCollector#addError` 是添加一个错误(error)。

1. **Verifier**

	如果,你想在每个测试之后,甚至是在`@After`之后,想检查些什么,就可以使用`Verifier`这个Rule.

	看例子:

        private static String sequence;

        public static class UsesVerifier {
          @Rule
          public Verifier collector = new Verifier() {
              @Override
              protected void verify() {
                  sequence += " verify ";
              }
          };

          @Test
          public void example() {
              sequence += "test";
          }

          @Test
          public void example2() {
              sequence += "test2";
          }

          @After
          public void after() {
        	  sequence += " after";
          }
        }

        @Test
        public void verifierRunsAfterTest() {
          sequence = "";
          assertThat(testResult(UsesVerifier.class), isSuccessful());
          assertEquals("test after verify test2 after verify ", sequence);
        }

    从上面例子可以看出:`Verifier#verify`针对每个测试都会运行一次,并且运行在`@After`步骤之后。

    需要说明:如果某测试出现失败(fail),那么这个测试之后就不会做`verify`,这一点,可以结合下面的例子看出。

1. **TestWatcher**

	对测试的每个步骤进行监控。

	看例子:

        package tangzhi.mytest;

        import static org.junit.Assert.*;
        import static org.hamcrest.CoreMatchers.*;

        import org.junit.After;
        import org.junit.Rule;
        import org.junit.Test;
        import org.junit.rules.TestRule;
        import org.junit.rules.TestWatcher;
        import org.junit.rules.Verifier;
        import org.junit.runner.Description;
        import org.junit.runners.model.Statement;

        public class WatchmanTest {
        	private static String watchedLog;

        	  @Rule
        	  public TestRule watchman = new TestWatcher() {
        	    @Override
        	    public Statement apply(Statement base, Description description) {
        	    	Statement s = super.apply(base, description);
        	    	watchedLog="";
        	    	System.out.println("watch apply.");
        	    	return s;
        	    }

        	    @Override
        	    protected void succeeded(Description description) {
        	    	watchedLog += description.getDisplayName() + " " + "success!";
        	    	System.out.println("watch succeed:"+watchedLog);

        	    }

        	    @Override
        	    protected void failed(Throwable e, Description description) {
        	    	watchedLog += description.getDisplayName() + " " + e.getClass().getSimpleName();
        	    	System.out.println("watch failed:"+watchedLog);

        	    }

        	    @Override
        	    protected void starting(Description description) {
        	      super.starting(description);
        	      System.out.println("watch starting.");
        	    }

        	    @Override
        	    protected void finished(Description description) {
        	      super.finished(description);
        	      System.out.println("watch finished.");
        	    }
        	  };

        	  @Rule
              public Verifier collector = new Verifier() {
                  @Override
                  protected void verify() {
                	  System.out.println("@Verify:"+watchedLog);
                  }
        	  };

        	  @Test
        	  public void fails() {
        		  System.out.println("in fails");
        		  assertThat("ssss", is("sss"));
        	  }

        	  @Test
        	  public void succeeds() {
        		  System.out.println("in succeeds");
        	  }

        	  @After
        	  public void after() {
        		  System.out.println("@After");
        	  }
        }

	运行后,日志如下:

        watch apply.
        watch starting.
        in succeeds
        @After
        watch succeed:succeeds(tangzhi.mytest.WatchmanTest) success!
        watch finished.
        @Verify:succeeds(tangzhi.mytest.WatchmanTest) success!
        watch apply.
        watch starting.
        in fails
        @After
        watch failed:fails(tangzhi.mytest.WatchmanTest) AssertionError
        watch finished.

1. **TestName**

	`TestName`可以获取当前测试方法的名字。

	看例子:

        public class NameRuleTest {
          @Rule
          public TestName name = new TestName();

          @Test
          public void testA() {
            assertEquals("testA", name.getMethodName());
          }

          @Test
          public void testB() {
            assertEquals("testB", name.getMethodName());
          }
        }

    如果,是在参数化测试(Parameterized)中,使用了`@Parameters`,那么其`name`属性定义的方法名也将会被`TestName#getMethodName`获取。

1. **Timeout**

	这个我们在前面介绍过,可以设置某个测试类,所有测试方法的超时时间。详见[进阶二]。

1. **ExpectedException**

	这个也在[进阶二]中有介绍。

1. **ClassRule**

	注释`@ClassRule`是类级别的,而不是方法级别的。

	见下面例子:

		@RunWith(Suite.class)
        @SuiteClasses({A.class, B.class, C.class})
        public class UsesExternalResource {
          public static Server myServer= new Server();

          @ClassRule
          public static ExternalResource resource= new ExternalResource() {
            @Override
            protected void before() throws Throwable {
              myServer.connect();
            };

            @Override
            protected void after() {
              myServer.disconnect();
            };
          };
        }

	在Suite所打包的几个类测试前后,会执行一遍`ClassRule`。

 1. **RuleChain**

 	见例子:

		public static class UseRuleChain {
            @Rule
            public TestRule chain= RuleChain
                                   .outerRule(new LoggingRule("outer rule")
                                   .around(new LoggingRule("middle rule")
                                   .around(new LoggingRule("inner rule");

            @Test
            public void example() {
                assertTrue(true);
            }
        }

 	执行后,日志如下:

 	    starting outer rule
        starting middle rule
        starting inner rule
        finished inner rule
        finished middle rule
        finished outer rule

[进阶二]: junit-usage-2.html


text:
// ***********************************************************************
// Copyright (c) 2017 Charlie Poole
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************

using System;

namespace NUnit.Framework.Internal.Commands
{
    /// <summary>
    /// EmptyTestCommand is a TestCommand that does nothing. It simply
    /// returns the current result from the context when executed. We
    /// use it to avoid testing for null when executing a chain of
    /// DelegatingTestCommands.
    /// </summary>
    public class EmptyTestCommand : TestCommand
    {
        /// <summary>
        /// Construct a NullCommand for a test
        /// </summary>
        public EmptyTestCommand(Test test) : base(test) { }

        /// <summary>
        /// Execute the command
        /// </summary>
        public override TestResult Execute(TestExecutionContext context)
        {
            return context.CurrentResult;
        }
    }
}


text:
/**
 * @fileoverview Enforce html element has lang prop.
 * @author Ethan Cohen
 */

// ----------------------------------------------------------------------------
// Rule Definition
// ----------------------------------------------------------------------------

import { elementType, getProp, getPropValue } from 'jsx-ast-utils';

const errorMessage = '<html> elements must have the lang prop.';

module.exports = context => ({
  JSXOpeningElement: node => {
    const type = elementType(node);

    if (type && type !== 'html') {
      return;
    }

    const lang = getPropValue(getProp(node.attributes, 'lang'));

    if (lang) {
      return;
    }

    context.report({
      node,
      message: errorMessage,
    });
  },
});

module.exports.schema = [
  { type: 'object' },
];


text:
\hypertarget{_sensor_fusion_module_8cpp}{}\section{app/\+Sensor\+Fusion\+Module.cpp File Reference}
\label{_sensor_fusion_module_8cpp}\index{app/\+Sensor\+Fusion\+Module.\+cpp@{app/\+Sensor\+Fusion\+Module.\+cpp}}

E\+N\+P\+M808X, Midsemester project.

{\ttfamily \#include $<$vector$>$}\\*
{\ttfamily \#include \char`\"{}Sensor\+Fusion\+Module.\+hpp\char`\"{}}\\*
Include dependency graph for Sensor\+Fusion\+Module.\+cpp\+:
\nopagebreak
\begin{figure}[H]
\begin{center}
\leavevmode
\includegraphics[width=263pt]{_sensor_fusion_module_8cpp__incl}
\end{center}
\end{figure}

\subsection{Detailed Description}
E\+N\+P\+M808X, Midsemester project.

\begin{DoxyAuthor}{Author}
Karan Vivek Bhargava
\end{DoxyAuthor}
\begin{DoxyCopyright}{Copyright}
M\+IT License
\end{DoxyCopyright}
\hypertarget{_robot_test_8cpp_DESCRIPTION}{}\subsection{D\+E\+S\+C\+R\+I\+P\+T\+I\+ON}\label{_robot_test_8cpp_DESCRIPTION}
This program is controlling a robot\textquotesingle{}s heading direction using sensor fusion.