text:
@interface SGQRCodeGenerateManager : NSObject

/// 生成一张普通的二维码
+ (UIImage *)SG_generateWithDefaultQRCodeData:(NSString *)data imageViewWidth:(CGFloat)imageViewWidth;
/// 生成一张带有logo的二维码(logoScaleToSuperView:相对于父视图的缩放比取值范围0-1;0,不显示,1,代表与父视图大小相同)
+ (UIImage *)SG_generateWithLogoQRCodeData:(NSString *)data logoImageName:(NSString *)logoImageName logoScaleToSuperView:(CGFloat)logoScaleToSuperView;
/// 生成一张彩色的二维码
+ (UIImage *)SG_generateWithColorQRCodeData:(NSString *)data backgroundColor:(CIColor *)backgroundColor mainColor:(CIColor *)mainColor;

@end


text:
package dcraft.ctp.stream;

import io.netty.buffer.ByteBuf;

import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarConstants;
import org.apache.commons.compress.archivers.zip.ZipEncoding;
import org.apache.commons.compress.archivers.zip.ZipEncodingHelper;
import org.apache.commons.compress.utils.ArchiveUtils;

import dcraft.ctp.f.FileDescriptor;
import dcraft.lang.op.OperationContext;
import dcraft.script.StackEntry;
import dcraft.xml.XElement;

public class UntarStream extends TransformStream {
	protected enum UntarState {
        RECORD,
        XTRAS,
        PREP,
        CONTENT,
        SKIP
    }

    protected byte[] header_buffer = new byte[TarConstants.DEFAULT_RCDSIZE];
    protected int partialLength = 0;

    protected TarArchiveEntry currEntry = null;
    protected ZipEncoding encoding = null;
    protected long remainContent = 0;
    protected long remainSkip = 0;

    protected UntarState tstate = UntarState.RECORD;

    public UntarStream() {
        this.encoding  = ZipEncodingHelper.getZipEncoding("UTF-8");
    }

	@Override
	public void init(StackEntry stack, XElement el) {
	}

	// make sure we don't return without first releasing the file reference content
	@Override
	public ReturnOption handle(FileSlice slice) {
    	if (slice == FileSlice.FINAL)
    		return this.downstream.handle(slice);

    	ByteBuf in = slice.getData();

    	if (in != null) {
    		while (in.isReadable()) {
    			switch (this.tstate) {
    			case RECORD:
		    		// starting a new record
		    		if (in.readableBytes() < TarConstants.DEFAULT_RCDSIZE - this.partialLength) {
		    			int offset = this.partialLength;

		    			this.partialLength += in.readableBytes();

		    			in.readBytes(this.header_buffer, offset, in.readableBytes());

		    			continue;
		    		}

	    			in.readBytes(this.header_buffer, this.partialLength, TarConstants.DEFAULT_RCDSIZE - this.partialLength);

		    		this.partialLength = 0;

		    		//in.readBytes(this.header_buffer, 0, this.header_buffer.length);

		            boolean hasHitEOF = this.isEOFRecord(this.header_buffer);

		            // if we hit this twice in a row we are at the end - however, source will send FINAL anyway so we don't really care
		            if (hasHitEOF) {
		                this.setEntry(null);
		                continue;
		            }

		            try {
		            	this.setEntry(new TarArchiveEntry(this.header_buffer, this.encoding));
		            }
		            catch (Exception x) {
		            	OperationContext.get().getTaskRun().kill("Error detected parsing the header: " + x);
		                in.release();
		                return ReturnOption.DONE;
		            }

		            this.tstate = UntarState.XTRAS;
    			case XTRAS:
		            if (!in.isReadable())
		            	continue;

		            // TODO support long names and such - see org.apache.commons.compress.archivers.tar.TarArchiveInputStream
			        if (this.currEntry.isGNULongLinkEntry()) {
			    		/*
			            byte[] longLinkData = getLongNameData();
			            if (longLinkData == null) {
			                // Bugzilla: 40334
			                // Malformed tar file - long link entry name not followed by
			                // entry
			                return null;
			            }
			            currEntry.setLinkName(encoding.decode(longLinkData));
			            */

			        	OperationContext.get().getTaskRun().kill("long link currently not supported");
		                in.release();
			        	return ReturnOption.DONE;
			        }

			        if (this.currEntry.isGNULongNameEntry()) {
			    		/*
			            byte[] longNameData = getLongNameData();
			            if (longNameData == null) {
			                // Bugzilla: 40334
			                // Malformed tar file - long entry name not followed by
			                // entry
			                return null;
			            }
			            currEntry.setName(encoding.decode(longNameData));
			            */

			        	OperationContext.get().getTaskRun().kill("long name currently not supported");
		                in.release();
			        	return ReturnOption.DONE;
			        }

			        if (this.currEntry.isPaxHeader()) {
			        	// Process Pax headers
			    		/*
			            paxHeaders();
			            */

			        	OperationContext.get().getTaskRun().kill("pax currently not supported");
		                in.release();
			        	return ReturnOption.DONE;
			        }

			        if (this.currEntry.isGNUSparse()) {
			        	// Process sparse files
			    		/*
			            readGNUSparse();
			            */

			        	OperationContext.get().getTaskRun().kill("sparse currently not supported");
		                in.release();
			        	return ReturnOption.DONE;
			        }

		            this.tstate = UntarState.PREP;
    			case PREP:
		            if (!in.isReadable())
		            	continue;

			        // TODO remove
		            System.out.println("name: " + this.currEntry.getName());
		            System.out.println("size: " + this.currEntry.getSize());
		            System.out.println("modified: " + this.currEntry.getModTime());

		            // If the size of the next element in the archive has changed
		            // due to a new size being reported in the posix header
		            // information, we update entrySize here so that it contains
		            // the correct value.
		            long entrySize = this.currEntry.getSize();
		            this.remainContent = entrySize;

		            long numRecords = (entrySize / this.header_buffer.length) + 1;
		            this.remainSkip = (numRecords * this.header_buffer.length) - entrySize;

		            // grab as much as we can from the current buffer
		            int readSize = (int) Math.min(this.remainContent, in.readableBytes());
		            this.remainContent -= readSize;

		            // handle empty files too
		            if ((readSize > 0) || (this.remainContent == 0)) {
			            System.out.println("reading content: " + readSize);

			            ByteBuf out = in.copy(in.readerIndex(), readSize);

			            int skipSize = (int) Math.min(this.remainSkip, in.readableBytes() - readSize);
			            this.remainSkip -= skipSize;

			            in.skipBytes(readSize + skipSize);

			            this.addSlice(out, 0, this.remainContent == 0);
		            }

		            this.tstate = UntarState.CONTENT;
    			case CONTENT:
		            if (!in.isReadable())
		            	continue;

	    			// check if there is still content left in the entry we were last reading from
	    			if (this.remainContent > 0) {
	    	            readSize = (int) Math.min(this.remainContent, in.readableBytes());
	    	            this.remainContent -= readSize;

	    	            //System.out.println("reading content: " + readSize);

	    	            //ByteBuf out = Hub.instance.getBufferAllocator().heapBuffer((int) readSize);

	    	            ByteBuf out = in.copy(in.readerIndex(), readSize);

	    	            int skipSize = (int) Math.min(this.remainSkip, in.readableBytes() - readSize);
	    	            this.remainSkip -= skipSize;

		                //System.out.println("skipping content: " + skipSize);

	    	            in.skipBytes(readSize + skipSize);

			            this.addSlice(out, 0, this.remainContent == 0);
	    			}

	    			if (this.remainContent > 0)
	    				continue;

		            this.setEntry(null);

		            this.tstate = UntarState.SKIP;
    			case SKIP:
    	            if (!in.isReadable())
    	            	continue;

	    			// check if there is still padding left in the entry we were last reading from
		    		if (this.remainSkip > 0) {
		                int skipSize = (int) Math.min(this.remainSkip, in.readableBytes());
		                this.remainSkip -= skipSize;

		                //System.out.println("skipping content: " + skipSize);

		                in.skipBytes((int) skipSize);
		    		}

	    			if (this.remainSkip > 0)
	    				continue;

		            this.tstate = UntarState.RECORD;
    			}
    		}

    		in.release();
    	}

		// write all messages in the queue
    	return this.handlerFlush();
    }

	public void setEntry(TarArchiveEntry v) {
		if (v == null) {
			this.currEntry = null;
			this.currfile = null;
		}
		else {
			// create the output message
			FileDescriptor blk = new FileDescriptor();

	        blk.setPath("/" + v.getName());
	        blk.setSize(v.getRealSize());
	        blk.setModTime(v.getModTime().getTime());

	        this.currfile = blk;
			this.currEntry = v;
		}
	}

    protected boolean isEOFRecord(byte[] record) {
        return record == null || ArchiveUtils.isArrayZero(record, TarConstants.DEFAULT_RCDSIZE);
    }
}

redpajama_set_name: RedPajamaGithub


text:
var searchData=
[
  ['cameramodule',['CameraModule',['../class_camera_module.html',1,'']]],
  ['cameratest',['CameraTest',['../class_camera_test.html',1,'']]]
];


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<title></title>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<link rel="stylesheet" type="text/css" href="search.css"/>

Loading...

  line.cpp

  line.h

  loadobjectfilethread.cpp

  loadobjectfilethread.h

  loadobjectspanel.cpp

  loadobjectspanel.h

  loadtoolscriptsthread.cpp

  loadtoolscriptsthread.h

  loopinxyplane.cpp

  loopinxyplane.h

Searching...

No Matches


text:
import { deprecate } from '@ember/debug';

/**
 @module @ember/polyfills
*/

export default function merge<T, U>(original: T, updates: U): T & U;

/**
  Merge the contents of two objects together into the first object.

  ```javascript
  import { merge } from '@ember/polyfills';

  merge({ first: 'Tom' }, { last: 'Dale' }); // { first: 'Tom', last: 'Dale' }
  var a = { first: 'Yehuda' };
  var b = { last: 'Katz' };
  merge(a, b); // a == { first: 'Yehuda', last: 'Katz' }, b == { last: 'Katz' }
  ```

  @method merge
  @static
  @for @ember/polyfills
  @param {Object} original The object to merge into
  @param {Object} updates The object to copy properties from
  @return {Object}
  @deprecated
  @public
*/
export default function merge(original: object, updates: object) {
  deprecate('Use of `merge` has been deprecated. Please use `assign` instead.', false, {
    id: 'ember-polyfills.deprecate-merge',
    until: '4.0.0',
    url: 'https://emberjs.com/deprecations/v3.x/#toc_ember-polyfills-deprecate-merge',
  });

  if (updates === null || typeof updates !== 'object') {
    return original;
  }

  let props = Object.keys(updates);
  let prop;

  for (let i = 0; i < props.length; i++) {
    prop = props[i];
    original[prop] = updates[prop];
  }

  return original;
}


text:
var stringify     = require("querystring").stringify,
	hmac          = require("crypto").createHmac,
	EventEmitter  = require('events').EventEmitter,
	io 			  = require('socket.io-client')('wss://nodejs1.bleutrade.com:8080'),
	request       = require("request"),
	util 	      = require("util"),
	publicMethods = ['getmarkets', 'getcurrencies', 'getticker', 'getmarketsummary', 'getmarketsummaries', 'getorderbook', 'getmarkethistory'];

function BleuTradeClient(key, secret, requeue) {
	var self    = this;

	self.key     = key;
	self.secret  = secret;
	self.jar     = request.jar();
	self.requeue = requeue || 0;

	function api_query(method, callback, args) {
		var args_tmp = {};

		for(var i in args) {
			if(args[i]) {
				args_tmp[i] = args[i];
			}
		}

		args = args_tmp;

		var options = {
			uri     : 'https://bleutrade.com/api/v2/' + method,
			agent   : false,
			method  : 'GET',
			jar     : self.jar,
			headers : {
				"User-Agent": "Mozilla/4.0 (compatible; Bleutrade API node client)",
				"Content-type": "application/x-www-form-urlencoded"
			}
		};

		if(publicMethods.indexOf(method) > -1) {
			options.method = 'GET';
			options.uri    = 'https://bleutrade.com/api/v2/public/' + method + '?' + stringify(args);;
		}	else	{
			if (!self.key || !self.secret) {
				throw new Error("Must provide key and secret to make this API request.");
			}	else{
				args.apikey = self.key;
				args.nonce = new Date().getTime();
			 	options.uri += ('?' + stringify(args));
				options.headers.apisign = new hmac("sha512", self.secret).update(options.uri).digest('hex');
			}
		}

		request(options, function(err, res, body) {
			if(!body || !res || res.statusCode != 200) {
				var requeue = +self.requeue;

				if(requeue) {
					setTimeout(function() {
						api_query(method, callback, args);
					}, requeue);
				}
				else if(typeof callback === 'function') {
					console.error(err);
					console.error(body);
					callback.call(this, "Error in server response", null);
				}
			} else {
				var error  = null;
				var result = null;

				try {
					var response = JSON.parse(body);

					if(response.error) {
						error = response.error;
					} else {
						result = response.return || response;
					}
				} catch(e) {
					error = "Error parsing server response: " + e.message;
				}

				if(typeof callback === 'function') {
					callback.call(this, error, result);
				}
			}
		});
	}

	// public
	self.getcurrencies = function(callback) {
		api_query('getcurrencies', callback);
	};

	self.getmarkets = function(callback) {
		api_query('getmarkets', callback);
	};

	self.getticker = function(market, callback) {
		api_query('getticker', callback, {market: market});
	};

	self.getmarketsummaries = function(callback) {
		api_query('getmarketsummaries', callback);
	};

	self.getmarketsummary = function(market, callback) {
		api_query('getmarketsummaries', callback, {market: market});
	};

	self.getorderbook = function(market, type, depth, callback) {
		api_query('getorderbook', callback, {market: market, type: type, depth: depth});
	};

	self.getmarkethistory = function(market, count, callback) {
		api_query('getmarkethistory', callback, {market: market, count: count});
	};

	self.getcandles = function(market, period, count, lasthours, callback) {
		api_query('getorderbook', callback, {market: market, period: period, count: count, lasthours: lasthours});
	};

	////////////////////////////////////////////////////////////////////////
	// Private
	////////////////////////////////////////////////////////////////////////

	// Market
	self.market_buylimit = function(market, rate, quantity, comments, callback) {
		api_query('market/buylimit', callback, {market: market, rate: rate, quantity: quantity, comments: comments});
	};

	self.market_selllimit = function(market, rate, quantity, comments, callback) {
		api_query('market/selllimit', callback, {market: market, rate: rate, quantity: quantity, comments: comments});
	};

	self.market_cancel = function(orderid, callback) {
		api_query('market/cancel', callback, {orderid: orderid});
	};

	self.market_getopenorders = function(callback) {
		api_query('market/getopenorders', callback);
	};

	// Account
	self.getbalances = function(currencies, callback) {
		api_query('account/getbalances', callback, { currencies: currencies });
	};

	self.getbalance = function(currency, callback) {
		api_query('account/getbalance', callback, { currency: currency });
	};

	self.getdepositaddress = function(currency, callback) {
		api_query('account/getdepositaddress', callback, { currency: currency });
	};

	self.withdraw = function(currency, quantity, address, callback) {
		api_query('account/withdraw', callback, { currency: currency, quantity: quantity, address: address });
	};

	self.transfer = function(currency, quantity, touser, callback) {
		api_query('account/transfer', callback, { currency: currency, quantity: quantity, touser: touser });
	};

	self.getorder = function(orderid, callback) {
		api_query('account/getorder', callback, { orderid: orderid });
	};

	self.getorders = function(market, orderstatus, callback) {
		api_query('account/getorders', callback, { market: market, orderstatus: orderstatus });
	};

	self.getorderhistory = function(orderid, callback) {
		api_query('account/getorderhistory', callback, { orderid: orderid });
	};

	self.getdeposithistory = function(callback) {
		api_query('account/getdeposithistory', callback);
	};

	self.getwithdrawhistory = function(callback) {
		api_query('account/getwithdrawhistory', callback);
	};

	self.chatsend = function(channel, text, callback) {
		api_query('account/chatsend', callback, {channel: channel, text: text});
	};

	////////////////////////////////////////////////////////////////////////
	// Push API
	////////////////////////////////////////////////////////////////////////
	self.subscribe = function() {
		io.on('message', self.handlePushEvents.bind(this));
	};

	self.handlePushEvents = function(data) {
	  var channel = data[0];
		if(channel === 'Bleutrade_CH1') {
			var msgType = data[1][0];
			self.emit('msgType', data);
		}
	};

}

util.inherits(BleuTradeClient, EventEmitter);

module.exports = BleuTradeClient;


text:
using System;

// Problem 2. Bonus Score
// • Write a program that applies bonus score to given score in the range  [1…9]  by the following rules:
// ◦ If the score is between  1  and  3 , the program multiplies it by  10 .
// ◦ If the score is between  4  and  6 , the program multiplies it by  100 .
// ◦ If the score is between  7  and  9 , the program multiplies it by  1000 .
// ◦ If the score is  0  or more than  9 , the program prints  "invalid score" .

public class BonusScore
{
    public static void Main()
    {
        Console.Write("Please enter your current score: ");
        int currentScore = int.Parse(Console.ReadLine());
        int newScore = 0;

        if ((currentScore >= 1) && (currentScore <= 3))
        {
            newScore = currentScore * 10;
            Console.WriteLine("Your new score is: {0}", newScore);
        }
        else if ((currentScore > 3) && (currentScore <= 6))
        {
            newScore = currentScore * 100;
            Console.WriteLine("Your new score is: {0}", newScore);
        }
        else if ((currentScore >= 7) && (currentScore <= 9))
        {
            newScore = currentScore * 1000;
            Console.WriteLine("Your new score is: {0}", newScore);
        }
        else if ((currentScore > 9) || (currentScore == 0))
        {
            Console.WriteLine("Invalid score");
        }
    }
}


text:
var Tile;

Tile = (function() {
  function Tile(tileBasics) {
    this.tileBasics = tileBasics;
    this.contentFontScaling = 1;
  }

  Tile.prototype.addToDoc = function() {
    this.tileId = "sqTile_" + this.tileBasics.tierIdx + "_" + this.tileBasics.groupIdx + "_" + this.tileIdx;
    $(this.tileBasics.parentTag).append("\n
\n
\n");
    if (this.tileBasics.clickFn != null) {
      $("#" + this.tileId).click((function(_this) {
        return function() {
          _this.playClickSound();
          return _this.tileBasics.clickFn(_this.tileBasics.clickParam);
        };
      })(this));
    }
    return this.contents = $("#" + this.tileId + ">.sqInner");
  };

  Tile.prototype.playClickSound = function() {
    return this.tileBasics.mediaPlayHelper.play("click");
  };

  Tile.prototype.distMoved = function(x1, y1, x2, y2) {
    var dist, xSep, ySep;
    xSep = x1 - x2;
    ySep = y1 - y2;
    dist = Math.sqrt((xSep * xSep) + (ySep * ySep));
    return dist;
  };

  Tile.prototype.removeFromDoc = function() {
    if (this.refreshId != null) {
      clearInterval(this.refreshId);
    }
    return $('#' + this.tileId).remove();
  };

  Tile.prototype.setTileIndex = function(tileIdx) {
    this.tileIdx = tileIdx;
  };

  Tile.prototype.reposition = function(posX, posY, sizeX, sizeY, fontScaling) {
    this.posX = posX;
    this.posY = posY;
    this.sizeX = sizeX;
    this.sizeY = sizeY;
    this.fontScaling = fontScaling;
    return this.setPositionCss(this.posX, this.posY, this.sizeX, this.sizeY, this.fontScaling);
  };

  Tile.prototype.setPositionCss = function(posX, posY, sizeX, sizeY, fontScaling) {
    return $('#' + this.tileId).css({
      "margin-left": posX + "px",
      "margin-top": posY + "px",
      "width": sizeX + "px",
      "height": sizeY + "px",
      "font-size": (fontScaling * this.contentFontScaling) + "%",
      "display": "block"
    });
  };

  Tile.prototype.setContentFontScaling = function(contentFontScaling) {
    this.contentFontScaling = contentFontScaling;
    return this.setPositionCss(this.posX, this.posY, this.sizeX, this.sizeY, this.fontScaling);
  };

  Tile.prototype.getElement = function(element) {
    return $('#' + this.tileId + " " + element);
  };

  Tile.prototype.isVisible = function(isPortrait) {
    if (this.tileBasics.visibility === "all") {
      return true;
    }
    if (this.tileBasics.visibility === "portrait" && isPortrait) {
      return true;
    }
    if (this.tileBasics.visibility === "landscape" && (!isPortrait)) {
      return true;
    }
    return false;
  };

  Tile.prototype.setInvisible = function() {
    return $('#' + this.tileId).css({
      "display": "none"
    });
  };

  Tile.prototype.setRefreshInterval = function(intervalInSecs, callbackFn, firstCallNow) {
    this.callbackFn = callbackFn;
    if (firstCallNow) {
      this.callbackFn();
    }
    return this.refreshId = setInterval((function(_this) {
      return function() {
        return _this.callbackFn();
      };
    })(this), intervalInSecs * 1000);
  };

  Tile.prototype.setIcon = function(iconName) {
    var iconUrl;
    iconUrl = 'img/' + iconName + '.png';
    if (iconUrl !== "") {
      return $('#' + this.tileId + " .sqSceneButtonIcon img").attr("src", iconUrl);
    }
  };

  Tile.prototype.setText = function(textStr) {
    this.textStr = textStr;
    return $('#' + this.tileId + " .sqSceneButtonText").html(textStr);
  };

  return Tile;

})();


text:
package uk.co.staticvoid.iou.conveyor.response;

import uk.co.staticvoid.iou.domain.Person;

public class GetPersonResponse {
    private String nickname;
    private String uuid;

    public GetPersonResponse() {
    }

    public GetPersonResponse(Person person) {
        this.nickname = person.getNickname();
        this.uuid = person.getUuid();
    }

    public String getNickname() {
        return nickname;
    }

    public void setNickname(String nickname) {
        this.nickname = nickname;
    }

    public String getUuid() {
        return uuid;
    }

    public void setUuid(String uuid) {
        this.uuid = uuid;
    }
}


text:
<!DOCTYPE html>

<meta charset="utf-8">

<link rel="stylesheet" type="text/css" href="../unit.css" />

  <canvas id="glweb20" width="16" height="16"></canvas>

Optional: Enter a comma-separated list of functions to fuzz (leave blank for full API)

  <input type="text" size="40" id="funcnames" value="">


text:
<?php

$adminRoutes = $this->import('routes/admin');
$siteRoutes = $this->import('routes/site');
$routes = array_merge($adminRoutes, $siteRoutes);

return array(
    'namespace' => 'My\\Namespace',
    'routers' => $routes
);


text:
package network;

import com.firebase.client.*;

import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;

/**
 * Created by brian on 1/24/16.
 */
public class FirebaseAuth {

    private String email;
    private String password;
    private AtomicReference<String> uid;

    private Firebase firebaseRef;

    public FirebaseAuth() {
        email = getRandomEmail();
        password = getRandomString();

        firebaseRef = new Firebase(FirebaseDataConnection.FIREBASE_URL);

        assureAuthenticated();
    }

    public String getUid() {
        return uid.get();
    }

    private void assureAuthenticated() {
        if (firebaseRef.getAuth() == null) {
            createAccount();
            logIn();
        }
    }

    private void logIn() {
        CountDownLatch latch = new CountDownLatch(1);

        firebaseRef.authWithPassword(email, password, new Firebase.AuthResultHandler() {
            @Override
            public void onAuthenticated(AuthData authData) {
                latch.countDown();
            }

            @Override
            public void onAuthenticationError(FirebaseError firebaseError) {
                System.out.println("could not log in");
                throw firebaseError.toException();
            }
        });

        awaitLatchResolution(latch);
    }

    private void createAccount() {
        final CountDownLatch latch = new CountDownLatch(1);
        uid = new AtomicReference<>();

        firebaseRef.createUser(email, password, new Firebase.ValueResultHandler<Map<String, Object>>() {
            @Override
            public void onSuccess(Map<String, Object> authMap) {
                uid.set((String) authMap.get("uid"));
                latch.countDown();
            }

            @Override
            public void onError(FirebaseError firebaseError) {
                System.out.println("could not create account");
                throw firebaseError.toException();
            }
        });

        awaitLatchResolution(latch);
    }

    private String getRandomEmail() {
        return getRandomString() + "@fake.turingchat.com";
    }

    private String getRandomString() {
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < 10; i++) {
            builder.append(getRandomChar());
        }

        return builder.toString();
    }

    private char getRandomChar() {
        return (char) (((int)(Math.random() * 26)) + 97);
    }

    private void awaitLatchResolution(CountDownLatch latch) {
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}


text:
<?php

namespace MwbExporter\Formatter\Doctrine2\Annotation\Model;

class ForeignKey extends \MwbExporter\Core\Model\ForeignKey
{
    public function __construct($data, $parent)
    {
        parent::__construct($data, $parent);

        $referencedColumn = $this->data->xpath("value[@key='referencedColumns']");
        $local = \MwbExporter\Core\Registry::get((string) $referencedColumn[0]->link);

        $ownerColumn = $this->data->xpath("value[@key='columns']");
        $foreign = \MwbExporter\Core\Registry::get((string) $ownerColumn[0]->link);

        $this->local   = $local;   // local column object
        $this->foreign = $foreign; // foreign column object

        // for doctrine2 annotations switch the local and the foreign
        // reference for a proper output
        $local->markAsForeignReference($this);
        $foreign->markAsLocalReference($this);

        // many to many
        if($fk = $this->getOwningTable()->getForeignKeys()){
            // only two or more foreign keys implicate an m2m relation
            // of the current table
            if(count($fk) > 1){
                foreach($fk as $foreignKey1){
                    foreach($fk as $foreignKey2){
                        if($foreignKey1->getReferencedTable()->getId() != $foreignKey2->getReferencedTable()->getId()){
                            $foreignKey1->getReferencedTable()->setManyToManyRelation(
                                array(
                                    'reference'  => $this,
                                    'refTable'   => $foreignKey2->getReferencedTable()
                                )
                            );
                        }
                    }
                }
            }
        }
    }

    public function display()
    {
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <group android:checkableBehavior="single">
        <item
            android:id="@+id/nav_friends"
            android:icon="@mipmap/ic_contacts"
            android:title="@string/nav_item_friends"></item>
        <item
            android:icon="@mipmap/ic_bell"
            android:title="@string/nav_item_message"></item>
        <item
            android:icon="@mipmap/gear"
            android:title="@string/nav_item_setting"></item>
    </group>

    <item
        android:title="@string/nav_item_communicate">
        <menu>
            <item
                android:icon="@mipmap/ic_share"
                android:title="@string/nav_item_share"></item>
        </menu>
    </item>
</menu>


text:
import alvisnlp
import sys
import stanza
from concurrent.futures import process

class PretokenizedStub:
    @staticmethod
    def get_doc(sec):
        return list(list(w.form for w in sec.words(s)) for s in sec.sentences())

    @staticmethod
    def get_sentences(stanza_doc, sec):
        return zip(stanza_doc.sentences, sec.sentences())

    @staticmethod
    def get_token_map(sec, stanza_sent, anlp_sent):
        return dict((stanza_tok.id, anlp_tok) for stanza_tok, anlp_tok in zip(stanza_sent.tokens, sec.words(anlp_sent)))

class RawStub:
    @staticmethod
    def get_doc(sec):
        return sec.contents

    @staticmethod
    def convert_sentence(sec, stanza_sent):
        return sec.create_annotation('sentences', stanza_sent.tokens[0].start_char, stanza_sent.tokens[-1].end_char)

    @staticmethod
    def get_sentences(stanza_doc, sec):
        for stanza_sent in stanza_doc.sentences:
            yield stanza_sent, RawStub.convert_sentence(sec, stanza_sent)

    @staticmethod
    def get_token_map(sec, stanza_sent, anlp_sent):
        token_map = {}
        for tok in stanza_sent.tokens:
            a = sec.create_annotation('words', tok.start_char, tok.end_char)
            token_map[tok.id] = a
        return token_map

class StanzaApp:
    def __init__(self):
        self.corpus = alvisnlp.Corpus.parse_json(sys.stdin)
        self.pretokenized = self.b('pretokenized')
        self.lang = self.corpus.params['lang']
        self.parse = self.b('parse')
        self.ner = self.b('ner')
        self.constituency = self.b('constituency')

    def b(self, param):
        s = self.corpus.params[param]
        return s == 'yes' or s == 'y' or s == 'true'

    def get_processors(self):
        processors = ['tokenize', 'mwt', 'pos', 'lemma']
        if self.parse:
            processors.append('depparse')
        if self.constituency:
            processors.append('constituency')
        if self.ner:
            processors.append('ner')
        return processors

    def get_stanza_pipeline(self):
        processors = self.get_processors()
        return stanza.Pipeline(lang=self.lang, processors=','.join(processors), tokenize_pretokenized=self.pretokenized)

    def get_stub(self):
        if self.pretokenized:
            return PretokenizedStub
        return RawStub

    @staticmethod
    def convert_token_info(stanza_sent, token_map):
        for tok in stanza_sent.tokens:
            a = token_map[tok.id]
            if len(tok.words) > 1:
                sys.stderr.write('token has multiple words: %s\n' % ', '.join(w.text for w in tok.words))
            w = tok.words[0]
            a.features['lemma'] = w.lemma
            a.features['pos'] = w.xpos
            a.features['upos'] = w.upos
            a.features['morph'] = w.feats
            a.features['stanza-id'] = str(tok.id)

    @staticmethod
    def convert_dependencies(sec, anlp_sent, stanza_sent, token_map):
        for head, label, tail in stanza_sent.dependencies:
            ta = token_map[tail.parent.id]
            if head.parent is None:
                sec.create_tuple('dependencies', args=dict(dependent=ta, sentence=anlp_sent), features=dict(label=label))
            else:
                ha = token_map[head.parent.id]
                sec.create_tuple('dependencies', args=dict(head=ha, dependent=ta, sentence=anlp_sent), features=dict(label=label))

    @staticmethod
    def _convert_tree_recursive(sec, const):
        if not const.is_preterminal():
            prets = list(const.yield_preterminals())
            start = min(pret.anlp_token.start for pret in prets)
            end = max(pret.anlp_token.end for pret in prets)
            sec.create_annotation('constituents', start, end, features=dict(label=const.label))
            for child in const.children:
                StanzaApp._convert_tree_recursive(sec, child)

    @staticmethod
    def convert_constituencies(sec, anlp_sent, stanza_sent, token_map):
        for pret, stanza_word in zip(stanza_sent.constituency.yield_preterminals(), stanza_sent.words):
            anlp_token = token_map[stanza_word.parent.id]
            pret.anlp_token = anlp_token
        StanzaApp._convert_tree_recursive(sec, stanza_sent.constituency)

    @staticmethod
    def convert_entities(sec, stanza_sent, token_map):
        for ent in stanza_sent.ents:
            start = token_map[ent.tokens[0].id].start
            end = token_map[ent.tokens[-1].id].end
            sec.create_annotation('entities', start, end, features=dict(type=ent.type))

    def run(self):
        nlp = self.get_stanza_pipeline()
        stub = self.get_stub()
        for doc in self.corpus.documents:
            for sec in doc.sections:
                stanza_doc = nlp(stub.get_doc(sec))
                for stanza_sent, anlp_sent in stub.get_sentences(stanza_doc, sec):
                    token_map = stub.get_token_map(sec, stanza_sent, anlp_sent)
                    StanzaApp.convert_token_info(stanza_sent, token_map)
                    if self.parse:
                        StanzaApp.convert_dependencies(sec, anlp_sent, stanza_sent, token_map)
                    if self.constituency:
                        StanzaApp.convert_constituencies(sec, anlp_sent, stanza_sent, token_map)
                    if self.ner:
                        StanzaApp.convert_entities(sec, stanza_sent, token_map)
        self.corpus.write_events_json(sys.stdout)

StanzaApp().run()


text:
Python script that will read in a natural language requirements demand for software and attempt to build a collection entities that would be modeled in the corresponding software project. Basically takes in text, pops out classes
# Usage
To use the tool simply call the script with the expected arguments

```
python3 driver.py inputfile.txt output.json
```
Where:
- inputfile.txt is the natural laguage file.
- output.json is the outputting json.


text:
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Microsoft.VisualStudio.Project")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Microsoft.VisualStudio.Project")]
[assembly: AssemblyCopyright("Copyright ©  2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components.  If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("A83A3A20-D1E0-4ED9-A2CB-13C4574FB483")]

// Version information for an assembly consists of the following four values:
//
//      Major Version
//      Minor Version
//      Build Number
//      Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.1.0.0")]
[assembly: AssemblyFileVersion("0.1.0.0")]

[assembly: InternalsVisibleTo("VisualRust, PublicKey=00240000048000009400000006020000002400005253413100040000010001007755e184d6da3fe8b941736d1567d465beee5164177fa4517975dc035826e7cb94d733944a9df378cc038429af191f7ca06ddd4a146e6cd5882595030cfcf82b194cec14fe9745368245993236e5059f21a5721c0cad36c71bfa9101f41ac58c39318fdf91b7abf4ae799aa7e3ed5cb79efac57b651eb04c105219cbf1b2b69f")]
[assembly: InternalsVisibleTo("VisualRust.Project, PublicKey=00240000048000009400000006020000002400005253413100040000010001007755e184d6da3fe8b941736d1567d465beee5164177fa4517975dc035826e7cb94d733944a9df378cc038429af191f7ca06ddd4a146e6cd5882595030cfcf82b194cec14fe9745368245993236e5059f21a5721c0cad36c71bfa9101f41ac58c39318fdf91b7abf4ae799aa7e3ed5cb79efac57b651eb04c105219cbf1b2b69f")]
#if TEST
[assembly: InternalsVisibleTo("VisualRust.Test.Integration, PublicKey=00240000048000009400000006020000002400005253413100040000010001007755e184d6da3fe8b941736d1567d465beee5164177fa4517975dc035826e7cb94d733944a9df378cc038429af191f7ca06ddd4a146e6cd5882595030cfcf82b194cec14fe9745368245993236e5059f21a5721c0cad36c71bfa9101f41ac58c39318fdf91b7abf4ae799aa7e3ed5cb79efac57b651eb04c105219cbf1b2b69f")]
#endif


text:
@interface LFH264VideoEncoder : NSObject <LFVideoEncoding> {

}

- (void)shutdown;

@end


text:
title: "Подготовка рабочей среды"
permalink: /docs/course-vm/
---

Для выполнения заданий курса можно использовать несколько вариантов:

* взять подготовленную виртуалку vmware или virtualbox
* подготовить виртуалку самостоятельно
* работать без создания виртуальной машины

Любой вариант подходит и с каждым возможны нюансы.
Использовать подготовленные vm совершенно не обязательно, в них нет никаких
особых настроек.

## Выбор ОС

Для курса подходит любая ОС: Linux, Mac OS, Windows.  На каждой ОС возможны
свои нюансы с установкой Python и модулей, но как правило, ничего критичного.

Задания и утилиты протестированы на Linux (Debian) и Windows 10 + Cmder. На
Mac OS проблем быть не должно, можно в целом делать плюс-минус как на Linux.

На Windows рекомендуется использовать [Cmder](https://cmder.app/) с git (кнопка
Download Full).  Если вы используете другой терминал, надо будет устанавливать
git cli и может не работать утилита pyneng. Я физически не могу учесть все
возможные варианты тут и перепробовать их, поэтому, к сожалению, в этом случае
вам надо будет разбираться самостоятельно.

## Версия Python

Если вы хотите самостоятельно подготовить виртуальную машину или работать без
виртуалки, вам нужно будет установить Python версии 3.7-3.10.  По умолчанию,
лучше установить Python 3.10, так как в 3.10 улучшилось отображение ошибок и
это последняя стабильная версия Python на данный момент.  Если что-то пойдет не
так при установке Python 3.10, можно попробовать версию меньше (3.9, 3.8, 3.7).

## Подготовка виртуальной машины/хоста самостоятельно

* [Инструкция для подготовки Linux](/docs/pynenglinux/)
* [Инструкция для подготовки Windows](/docs/pynengwindows/)

Список модулей, которые нужно установить (эта же команда обновит модули, если они уже установлены):

```
pip install -U pytest pytest-clarity pyyaml tabulate jinja2 textfsm pexpect netmiko graphviz
```

> [Установка Python на разных ОС](https://realpython.com/installing-python/)

## Подготовленные виртуальные машины

Для курса подготовлены виртуальные машины, в которых установлены:

* Debian 11 ([статьи по основам Linux](/docs/linux/))
* Python 3.10 в виртуальном окружении
* IPython и другие модули, которые потребуются для выполнения заданий
* текстовые редакторы vim, Thonny и VS Code (установлен, но не настроен)
* GNS3 для работы с сетевым оборудованием

Есть два варианта подготовленных виртуальных машин:

* VirtualBox
* VMware

### VirtualBox

[Скачать подготовленный образ](https://drive.google.com/file/d/1Vn03kAsjM-vMjRJV8NMHtJ76XD-SCggr/view?usp=sharing).
Виртуалка создавалась на VirtualBox 6.1.36.

1. Открыть VirtualBox
2. Выбрать File > Import Appliance
3. Выбрать файл образа .ova
4. Нажать Next
5. Нажать Import

В vm есть предустановленный пользователь:

* Username: vagrant
* Password: vagrant

> В vm root без пароля, задать пароль можно самостоятельно ``sudo passwd``, но
> скорее всего root не понадобится.

### VMware

[Скачать подготовленный образ](https://drive.google.com/file/d/1XxVaWovQnvcK9XkVYY613zLOTUFfW1os/view?usp=sharing).
Виртуалка создавалась в VMware Workstation Pro 15.5.2.

В vm есть предустановленный пользователь:

* Username: python
* Password: python

> Пароль пользователя root: pythonroot, но скорее всего root не понадобится.


text:
Resizable Container Element

Current width: {{ width }}

Current media breakpoint inside this element: {{ breakpoint }}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.macula.cart</groupId>
		<artifactId>macula-cart-parent</artifactId>
		<version>1.12-SNAPSHOT</version>
		<relativePath>../macula-cart-parent/pom.xml</relativePath>
	</parent>
	<artifactId>macula-cart-api-impl</artifactId>

	<properties>
		<maven.build.timestamp.format>yyMMdd-HHmm</maven.build.timestamp.format>
		<buildNumber>${maven.build.timestamp}</buildNumber>
		<m.version>${project.version}-${buildNumber}</m.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.macula.cart</groupId>
			<artifactId>macula-cart-api</artifactId>
			<version>${project.version}</version>
		</dependency>

		<dependency>
			<groupId>org.macula.cart</groupId>
			<artifactId>macula-cart-repository</artifactId>
			<version>${project.version}</version>
		</dependency>

		<dependency>
			<groupId>org.macula.plugins</groupId>
			<artifactId>macula-plugins-dubbo</artifactId>
		</dependency>

		<dependency>
			<groupId>org.macula.plugins</groupId>
			<artifactId>macula-plugins-cat</artifactId>
		</dependency>
	</dependencies>

	<build>
		<finalName>macula-cart-api-${environment}[${project.version}.${buildNumber}]</finalName>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-resources-plugin</artifactId>
				<version>2.7</version>
				<executions>
					<execution>
						<id>copy-resources</id>
						<phase>validate</phase>
						<goals>
							<goal>copy-resources</goal>
						</goals>
						<configuration>
							<outputDirectory>target/classes</outputDirectory>
							<resources>
								<resource>
									<directory>src/main/deploy/${environment}</directory>
									<filtering>true</filtering>
								</resource>
							</resources>
						</configuration>
					</execution>
				</executions>
			</plugin>
		</plugins>
	</build>

	<profiles>
		<profile>
			<id>main</id>
			<build>
				<pluginManagement>
					<plugins>
						<plugin>
							<groupId>org.eclipse.m2e</groupId>
							<artifactId>lifecycle-mapping</artifactId>
							<version>1.0.0</version>
							<configuration>
								<lifecycleMappingMetadata>
									<pluginExecutions>
										<pluginExecution>
											<pluginExecutionFilter>
												<groupId>org.apache.maven.plugins</groupId>
												<artifactId>maven-dependency-plugin</artifactId>
												<versionRange>[2.0,)</versionRange>
												<goals>
													<goal>copy-dependencies</goal>
												</goals>
											</pluginExecutionFilter>
											<action>
												<ignore />
											</action>
										</pluginExecution>
									</pluginExecutions>
								</lifecycleMappingMetadata>
							</configuration>
						</plugin>
					</plugins>
				</pluginManagement>
				<plugins>
					<plugin>
						<groupId>org.apache.maven.plugins</groupId>
						<artifactId>maven-jar-plugin</artifactId>
						<version>2.6</version>
						<configuration>
							<classesDirectory>target/classes/</classesDirectory>
							<archive>
								<manifest>
									<mainClass>com.alibaba.dubbo.container.Main</mainClass>
									<useUniqueVersions>false</useUniqueVersions>
									<addClasspath>true</addClasspath>
									<classpathPrefix>lib/</classpathPrefix>
								</manifest>
								<manifestEntries>
									<Manifest-Version>${m.version}</Manifest-Version>
									<Class-Path>.</Class-Path>
								</manifestEntries>
							</archive>
						</configuration>
					</plugin>
					<plugin>
						<groupId>org.apache.maven.plugins</groupId>
						<artifactId>maven-dependency-plugin</artifactId>
						<version>2.10</version>
						<executions>
							<execution>
								<id>copy-dependencies</id>
								<phase>package</phase>
								<goals>
									<goal>copy-dependencies</goal>
								</goals>
								<configuration>
									<type>jar</type>
									<includeTypes>jar</includeTypes>
									<useUniqueVersions>false</useUniqueVersions>
									<outputDirectory>
										${project.build.directory}/lib
									</outputDirectory>
								</configuration>
							</execution>
						</executions>
					</plugin>
				</plugins>
			</build>
		</profile>

		<profile>
			<id>dev</id>
			<properties>
				<environment>dev</environment>
			</properties>
		</profile>

		<profile>
			<id>test</id>
			<properties>
				<environment>test</environment>
			</properties>
		</profile>

		<profile>
			<id>staging</id>
			<properties>
				<environment>staging</environment>
			</properties>
		</profile>

		<profile>
			<id>prd</id>
			<properties>
				<environment>prd</environment>
			</properties>
		</profile>
	</profiles>

</project>


text:
const rx = require('rx');
const uuid = require('uuid');

module.exports =
class AggroBot {
  constructor(name) {
    this.id = uuid.v4();
    this.name = name;

    this.isBot = true;
    this.holeCards = [];
  }

  // TOO STRONK
  getAction(availableActions, previousActions) {
    let desiredAction = { name: 'call' };

    if (availableActions.indexOf('raise') > -1) {
      desiredAction = { name: 'raise' };
    } else if (availableActions.indexOf('bet') > -1) {
      desiredAction = { name: 'bet' };
    }

    let delay = 2000 + (Math.random() * 2000);
    return rx.Observable.timer(delay)
      .flatMap(() => rx.Observable.return(desiredAction));
  }
};


text:
echo "Enabling Kinect..."
echo '1-1.3' > /sys/bus/usb/drivers/usb/bind
echo "Done"
roslaunch frobo_bringup kinect.launch


text:
package org.h2.samples;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

import org.h2.store.fs.FileUtils;
import org.h2.tools.Script;
import org.h2.tools.DeleteDbFiles;
import org.h2.tools.RunScript;

/**
 * This sample application shows how to compact the database files.
 * This is done by creating a SQL script, and then re-creating the database
 * using this script.
 */
public class Compact {

    /**
     * This method is called when executing this sample application from the
     * command line.
     *
     * @param args the command line parameters
     */
    public static void main(String... args) throws Exception {
        DeleteDbFiles.execute("./data", "test", true);
        Class.forName("org.h2.Driver");
        Connection conn = DriverManager.getConnection("jdbc:h2:./data/test", "sa", "");
        Statement stat = conn.createStatement();
        stat.execute("CREATE TABLE TEST(ID INT PRIMARY KEY, NAME VARCHAR)");
        stat.execute("INSERT INTO TEST VALUES(1, 'Hello'), (2, 'World');");
        stat.close();
        conn.close();
        System.out.println("Compacting...");
        compact("./data", "test", "sa", "");
        System.out.println("Done.");
    }

    /**
     * Utility method to compact a database.
     *
     * @param dir the directory
     * @param dbName the database name
     * @param user the user name
     * @param password the password
     */
    public static void compact(String dir, String dbName,
            String user, String password) throws SQLException {
        String url = "jdbc:h2:" + dir + "/" + dbName;
        String file = "data/test.sql";
        Script.process(url, user, password, file, "", "");
        DeleteDbFiles.execute(dir, dbName, true);
        RunScript.execute(url, user, password, file, null, false);
        FileUtils.delete(file);
    }

}


text:
/**
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.aurora.scheduler.http.api.security;

import javax.security.auth.kerberos.KerberosPrincipal;

import org.apache.aurora.common.args.ArgParser;
import org.apache.aurora.common.args.parsers.NonParameterizedTypeParser;

@ArgParser
class KerberosPrincipalParser extends NonParameterizedTypeParser<KerberosPrincipal> {
  @Override
  public KerberosPrincipal doParse(String raw) throws IllegalArgumentException {
    return new KerberosPrincipal(raw);
  }
}


text:
/*
 * Copyright (C) 1990,91   Silicon Graphics, Inc.
 *
 _______________________________________________________________________
 ______________  S I L I C O N   G R A P H I C S   I N C .  ____________
 |
 |   $Revision: 1.1.1.1 $
 |
 |   Classes:
 |	SoCallbackAction
 |
 |   Author(s)		: Paul S. Strauss
 |
 ______________  S I L I C O N   G R A P H I C S   I N C .  ____________
 _______________________________________________________________________
 */

#include <Inventor/actions/SoCallbackAction.h>
#include <Inventor/elements/SoComplexityElement.h>
#include <Inventor/elements/SoCoordinateElement.h>
#include <Inventor/elements/SoCreaseAngleElement.h>
#include <Inventor/elements/SoFocalDistanceElement.h>
#include <Inventor/elements/SoFontNameElement.h>
#include <Inventor/elements/SoFontSizeElement.h>
#include <Inventor/elements/SoLightAttenuationElement.h>
#include <Inventor/elements/SoLinePatternElement.h>
#include <Inventor/elements/SoLineWidthElement.h>
#include <Inventor/elements/SoModelMatrixElement.h>
#include <Inventor/elements/SoNormalElement.h>
#include <Inventor/elements/SoPointSizeElement.h>
#include <Inventor/elements/SoProfileCoordinateElement.h>
#include <Inventor/elements/SoProfileElement.h>
#include <Inventor/elements/SoProjectionMatrixElement.h>
#include <Inventor/elements/SoShapeHintsElement.h>
#include <Inventor/elements/SoSwitchElement.h>
#include <Inventor/elements/SoTextureCoordinateBindingElement.h>
#include <Inventor/elements/SoTextureCoordinateElement.h>
#include <Inventor/elements/SoTextureImageElement.h>
#include <Inventor/elements/SoTextureMatrixElement.h>
#include <Inventor/elements/SoUnitsElement.h>
#include <Inventor/elements/SoViewVolumeElement.h>
#include <Inventor/elements/SoViewingMatrixElement.h>
#include <Inventor/nodes/SoShape.h>

struct nodeTypeCallback {
    SoType					type;
    SoCallbackAction::SoCallbackActionCB	*cb;
    void					*data;
};

struct tailCallback {
    SoCallbackAction::SoCallbackActionCB	*cb;
    void					*data;
};

struct triangleCallback {
    SoType					type;
    SoTriangleCB				*cb;
    void					*data;
};

struct lineSegmentCallback {
    SoType					type;
    SoLineSegmentCB				*cb;
    void					*data;
};

struct pointCallback {
    SoType					type;
    SoPointCB					*cb;
    void					*data;
};

SO_ACTION_SOURCE(SoCallbackAction);

////////////////////////////////////////////////////////////////////////
//
// Description:
//    Default constructor.
//
// Use: public

SoCallbackAction::SoCallbackAction()
//
////////////////////////////////////////////////////////////////////////
{
    SO_ACTION_CONSTRUCTOR(SoCallbackAction);
}

////////////////////////////////////////////////////////////////////////
//
// Description:
//    Destructor.
//
// Use: public

SoCallbackAction::~SoCallbackAction()
//
////////////////////////////////////////////////////////////////////////
{
    int i;

    // Free up the structures in the callback lists:

    for (i = 0; i < preCallbackList.getLength(); i++)
	delete (nodeTypeCallback *) preCallbackList[i];

    for (i = 0; i < postCallbackList.getLength(); i++)
	delete (nodeTypeCallback *) postCallbackList[i];

    for (i = 0; i < preTailCallbackList.getLength(); i++)
	delete (nodeTypeCallback *) preTailCallbackList[i];

    for (i = 0; i < postTailCallbackList.getLength(); i++)
	delete (nodeTypeCallback *) postTailCallbackList[i];

    for (i = 0; i < triangleCallbackList.getLength(); i++)
	delete (triangleCallback *) triangleCallbackList[i];

    for (i = 0; i < lineSegmentCallbackList.getLength(); i++)
	delete (lineSegmentCallback *) lineSegmentCallbackList[i];

    for (i = 0; i < pointCallbackList.getLength(); i++)
	delete (pointCallback *) pointCallbackList[i];
}

////////////////////////////////////////////////////////////////////////
//
// Description:
//    These all add callbacks to a callback list.
//
// Use: public (all of them)
//
////////////////////////////////////////////////////////////////////////

void
SoCallbackAction::addPreCallback(SoType type,
				 SoCallbackAction::SoCallbackActionCB cb,
				 void *data)
{
    nodeTypeCallback *cbStruct = new nodeTypeCallback;
    cbStruct->type = type;
    cbStruct->cb = cb;
    cbStruct->data = data;

    preCallbackList.append((void *)cbStruct);
}

void
SoCallbackAction::addPostCallback(SoType type,
				  SoCallbackAction::SoCallbackActionCB cb,
				  void *data)
{
    nodeTypeCallback *cbStruct = new nodeTypeCallback;
    cbStruct->type = type;
    cbStruct->cb = cb;
    cbStruct->data = data;

    postCallbackList.append((void *)cbStruct);
}

void
SoCallbackAction::addPreTailCallback(SoCallbackAction::SoCallbackActionCB cb,
				     void *data)
{
    tailCallback *cbStruct = new tailCallback;
    cbStruct->cb = cb;
    cbStruct->data = data;

    preTailCallbackList.append((void *)cbStruct);
}

void
SoCallbackAction::addPostTailCallback(SoCallbackAction::SoCallbackActionCB cb,
				      void *data)
{
    tailCallback *cbStruct = new tailCallback;
    cbStruct->cb = cb;
    cbStruct->data = data;

    postTailCallbackList.append((void *)cbStruct);
}

void
SoCallbackAction::addTriangleCallback(SoType type,
				      SoTriangleCB cb, void *data)
{
    triangleCallback *cbStruct = new triangleCallback;
    cbStruct->type = type;
    cbStruct->cb = cb;
    cbStruct->data = data;

    triangleCallbackList.append((void *)cbStruct);
}

void SoCallbackAction::addLineSegmentCallback(SoType type,
					      SoLineSegmentCB cb, void *data)
{
    lineSegmentCallback *cbStruct = new lineSegmentCallback;
    cbStruct->type = type;
    cbStruct->cb = cb;
    cbStruct->data = data;

    lineSegmentCallbackList.append((void *)cbStruct);
}

void
SoCallbackAction::addPointCallback(SoType type, SoPointCB cb, void *data)
{
    pointCallback *cbStruct = new pointCallback;
    cbStruct->type = type;
    cbStruct->cb = cb;
    cbStruct->data = data;

    pointCallbackList.append((void *)cbStruct);
}

////////////////////////////////////////////////////////////////////////
//
// Description:
//    These all return various items accessed from elements in the
//    state. They can be called from callback functions.
//
// Use: public (all of them)

float
SoCallbackAction::getComplexity() const
{
    return SoComplexityElement::get(state);
}

SoComplexity::Type
SoCallbackAction::getComplexityType() const
{
    return (SoComplexity::Type) SoComplexityTypeElement::get(state);
}

int32_t
SoCallbackAction::getNumCoordinates() const
{
    return SoCoordinateElement::getInstance(state)->getNum();
}

const SbVec3f &
SoCallbackAction::getCoordinate3(int index) const
{
    return SoCoordinateElement::getInstance(state)->get3(index);
}

const SbVec4f &
SoCallbackAction::getCoordinate4(int index) const
{
    return SoCoordinateElement::getInstance(state)->get4(index);
}

SoDrawStyle::Style
SoCallbackAction::getDrawStyle() const
{
    return (SoDrawStyle::Style) SoDrawStyleElement::get(state);
}

u_short
SoCallbackAction::getLinePattern() const
{
    return SoLinePatternElement::get(state);
}

float
SoCallbackAction::getLineWidth() const
{
    return SoLineWidthElement::get(state);
}

float
SoCallbackAction::getPointSize() const
//
////////////////////////////////////////////////////////////////////////
{
    return SoPointSizeElement::get(state);
}

const SbName &
SoCallbackAction::getFontName() const
{
    return SoFontNameElement::get(state);
}

float
SoCallbackAction::getFontSize() const
{
    return SoFontSizeElement::get(state);
}

SoLightModel::Model
SoCallbackAction::getLightModel() const
{
    return (SoLightModel::Model) SoLazyElement::getLightModel(state);
}

const SbVec3f &
SoCallbackAction::getLightAttenuation() const
{
    return SoLightAttenuationElement::get(state);
}

void
SoCallbackAction::getMaterial(SbColor &ambient,
			      SbColor &diffuse,
			      SbColor &specular,
			      SbColor &emission,
			      float   &shininess,
			      float   &transparency,
			      int     mtlIndex) const
{
    const SoLazyElement* le = SoLazyElement::getInstance(state);
    int32_t ind = le->getNumTransparencies() - 1;

#ifdef DEBUG
    if ( mtlIndex > le->getNumDiffuse()){
	SoDebugError::post("SoCallbackAction::getMaterial",
	    "not enough diffuse colors");
    }
    if (( mtlIndex > ind )&& (ind > 0)){
	SoDebugError::post("SoCallbackAction::getMaterial",
	    "not enough transparencies");
    }
#endif /*DEBUG*/
    ambient = SoLazyElement::getAmbient(state);
    diffuse = SoLazyElement::getDiffuse(state, mtlIndex);
    specular = SoLazyElement::getSpecular(state);
    emission = SoLazyElement::getEmissive(state);
    shininess = SoLazyElement::getShininess(state);

    if (ind > 0) ind = mtlIndex;
	else ind = 0;
    transparency = SoLazyElement::getTransparency(state, ind);
}

SoMaterialBinding::Binding
SoCallbackAction::getMaterialBinding() const
{
    return (SoMaterialBinding::Binding) SoMaterialBindingElement::get(state);
}

int32_t
SoCallbackAction::getNumNormals() const
{
    return SoNormalElement::getInstance(state)->getNum();
}

const SbVec3f &
SoCallbackAction::getNormal(int index) const
{
    return SoNormalElement::getInstance(state)->get(index);
}

SoNormalBinding::Binding
SoCallbackAction::getNormalBinding() const
{
    return (SoNormalBinding::Binding) SoNormalBindingElement::get(state);
}

int32_t
SoCallbackAction::getNumProfileCoordinates() const
{
    return SoProfileCoordinateElement::getInstance(state)->getNum();
}

const SbVec2f &
SoCallbackAction::getProfileCoordinate2(int index) const
{
    return SoProfileCoordinateElement::getInstance(state)->get2(index);
}

const SbVec3f &
SoCallbackAction::getProfileCoordinate3(int index) const
{
    return SoProfileCoordinateElement::getInstance(state)->get3(index);
}

const SoNodeList &
SoCallbackAction::getProfile() const
{
    return SoProfileElement::get(state);
}

SoShapeHints::VertexOrdering
SoCallbackAction::getVertexOrdering() const
{
    SoShapeHintsElement::VertexOrdering	v;
    SoShapeHintsElement::ShapeType	s;
    SoShapeHintsElement::FaceType	f;

    SoShapeHintsElement::get(state, v, s, f);
    return (SoShapeHints::VertexOrdering) v;
}

SoShapeHints::ShapeType
SoCallbackAction::getShapeType() const
{
    SoShapeHintsElement::VertexOrdering	v;
    SoShapeHintsElement::ShapeType	s;
    SoShapeHintsElement::FaceType	f;

    SoShapeHintsElement::get(state, v, s, f);
    return (SoShapeHints::ShapeType) s;
}

SoShapeHints::FaceType
SoCallbackAction::getFaceType() const
{
    SoShapeHintsElement::VertexOrdering	v;
    SoShapeHintsElement::ShapeType	s;
    SoShapeHintsElement::FaceType	f;

    SoShapeHintsElement::get(state, v, s, f);
    return (SoShapeHints::FaceType) f;
}

float
SoCallbackAction::getCreaseAngle() const
{
    return SoCreaseAngleElement::get(state);
}

int32_t
SoCallbackAction::getNumTextureCoordinates() const
{
    return SoTextureCoordinateElement::getInstance(state)->getNum();
}

const SbVec2f &
SoCallbackAction::getTextureCoordinate2(int index) const
{
    return SoTextureCoordinateElement::getInstance(state)->get2(index);
}

const SbVec4f &
SoCallbackAction::getTextureCoordinate4(int index) const
{
    return SoTextureCoordinateElement::getInstance(state)->get4(index);
}

SoTextureCoordinateBinding::Binding
SoCallbackAction::getTextureCoordinateBinding() const
{
    return (SoTextureCoordinateBinding::Binding)
	SoTextureCoordinateBindingElement::get(state);
}

const SbColor &
SoCallbackAction::getTextureBlendColor() const
{
    SbVec2s size;
    int numComponents, wrapS, wrapT, model;
    static SbColor blendColor;
    const unsigned char *bytes;
    bytes = SoTextureImageElement::get(
	state, size, numComponents, wrapS, wrapT, model,
	blendColor);

    return blendColor;
}

const unsigned char *
SoCallbackAction::getTextureImage(SbVec2s &size, int &numComponents) const
{
    int wrapS, wrapT, model;
    static SbColor blendColor;
    const unsigned char *bytes;
    bytes = SoTextureImageElement::get(
	state, size, numComponents, wrapS, wrapT, model,
	blendColor);

    return bytes;
}

const SbMatrix &
SoCallbackAction::getTextureMatrix() const
{
    return SoTextureMatrixElement::get(state);
}

SoTexture2::Model
SoCallbackAction::getTextureModel() const
{
    SbVec2s size;
    int numComponents, wrapS, wrapT, model;
    static SbColor blendColor;
    const unsigned char *bytes;
    bytes = SoTextureImageElement::get(
	state, size, numComponents, wrapS, wrapT, model,
	blendColor);
    return (SoTexture2::Model)model;
}

SoTexture2::Wrap
SoCallbackAction::getTextureWrapS() const
{
    SbVec2s size;
    int numComponents, wrapS, wrapT, model;
    static SbColor blendColor;
    const unsigned char *bytes;
    bytes = SoTextureImageElement::get(
	state, size, numComponents, wrapS, wrapT, model,
	blendColor);
    return (SoTexture2::Wrap)wrapS;
}

SoTexture2::Wrap
SoCallbackAction::getTextureWrapT() const
{
    SbVec2s size;
    int numComponents, wrapS, wrapT, model;
    static SbColor blendColor;
    const unsigned char *bytes;
    bytes = SoTextureImageElement::get(
	state, size, numComponents, wrapS, wrapT, model,
	blendColor);
    return (SoTexture2::Wrap)wrapT;
}

const SbMatrix &
SoCallbackAction::getModelMatrix() const
{
    return SoModelMatrixElement::get(state);
}

SoUnits::Units
SoCallbackAction::getUnits() const
{
    return (SoUnits::Units) SoUnitsElement::get(state);
}

float
SoCallbackAction::getFocalDistance() const
{
    return SoFocalDistanceElement::get(state);
}

const SbMatrix &
SoCallbackAction::getProjectionMatrix() const
{
    return SoProjectionMatrixElement::get(state);
}

const SbMatrix &
SoCallbackAction::getViewingMatrix() const
{
    return SoViewingMatrixElement::get(state);
}

const SbViewVolume &
SoCallbackAction::getViewVolume() const
{
    return SoViewVolumeElement::get(state);
}

SoPickStyle::Style
SoCallbackAction::getPickStyle() const
{
    return (SoPickStyle::Style) SoPickStyleElement::get(state);
}

int32_t
SoCallbackAction::getSwitch() const
{
    return SoSwitchElement::get(state);
}

////////////////////////////////////////////////////////////////////////
//
// Description:
//    Invoke pre callbacks before a node is traversed.
//
// Use: internal

void
SoCallbackAction::invokePreCallbacks(const SoNode *node)
//
////////////////////////////////////////////////////////////////////////
{
    Response		newResponse;
    nodeTypeCallback	*typeCb;
    tailCallback	*tailCb;
    int			i;

    // If we had been pruning, stop. (We know that if this node is
    // traversed, it wasn't pruned.)
    if (response == PRUNE)
	response = CONTINUE;

    for (i = 0; i < preCallbackList.getLength(); i++) {
	typeCb = (nodeTypeCallback *)preCallbackList[i];
	if (node->isOfType(typeCb->type)) {
	    newResponse = (typeCb->cb)(typeCb->data, this, node);
	    if (newResponse != CONTINUE) {
		response = newResponse;
		if (newResponse == ABORT) {
		    setTerminated(TRUE);
		    return;
		}
	    }
	}
    }

    const SoPath *pathAppliedTo = getPathAppliedTo();

    if (preTailCallbackList.getLength() > 0 &&
	pathAppliedTo != NULL &&
	(*getCurPath()) == (*pathAppliedTo)) {

	for (i = 0; i < preTailCallbackList.getLength(); i++) {
	    tailCb = (tailCallback *)preTailCallbackList[i];
	    newResponse = (tailCb->cb)(tailCb->data, this, node);
	    if (newResponse != CONTINUE) {
		response = newResponse;
		if (newResponse == ABORT) {
		    setTerminated(TRUE);
		    return;
		}
	    }
	}
    }
}

////////////////////////////////////////////////////////////////////////
//
// Description:
//    Invoke post callbacks.
//
// Use: internal

void
SoCallbackAction::invokePostCallbacks(const SoNode *node)
//
////////////////////////////////////////////////////////////////////////
{
    Response		newResponse;
    nodeTypeCallback	*typeCb;
    tailCallback	*tailCb;
    int			i;

    if (response == PRUNE)
	response = CONTINUE;

    for (i = 0; i < postCallbackList.getLength(); i++) {
	typeCb = (nodeTypeCallback *)postCallbackList[i];
	if (node->isOfType(typeCb->type)) {
	    newResponse = (typeCb->cb)(typeCb->data, this, node);
	    if (newResponse != CONTINUE)
		response = newResponse;
	    if (newResponse == ABORT) {
		setTerminated(TRUE);
		return;
	    }
	}
    }

    const SoPath *pathAppliedTo = getPathAppliedTo();

    if (postTailCallbackList.getLength() > 0 &&
	pathAppliedTo != NULL &&
	(*getCurPath()) == (*pathAppliedTo)) {

	for (i = 0; i < postTailCallbackList.getLength(); i++) {
	    tailCb = (tailCallback *)postTailCallbackList[i];
	    newResponse = (tailCb->cb)(tailCb->data, this, node);
	    if (newResponse != CONTINUE)
		response = newResponse;
	    if (newResponse == ABORT) {
		setTerminated(TRUE);
		return;
	    }
	}
    }
}

////////////////////////////////////////////////////////////////////////
//
// Description:
//    Invoke triangle callbacks.
//
// Use: internal

void
SoCallbackAction::invokeTriangleCallbacks(const SoShape *shape,
					  const SoPrimitiveVertex *v1,
					  const SoPrimitiveVertex *v2,
					  const SoPrimitiveVertex *v3)
//
////////////////////////////////////////////////////////////////////////
{
    triangleCallback	*triCb;
    int			i;

    for (i = 0; i < triangleCallbackList.getLength(); i++) {
	triCb = (triangleCallback *)triangleCallbackList[i];
	if (shape->isOfType(triCb->type))
	    (triCb->cb)(triCb->data, this, v1, v2, v3);
    }
}

////////////////////////////////////////////////////////////////////////
//
// Description:
//    Invoke line segment callbacks.
//
// Use: internal

void
SoCallbackAction::invokeLineSegmentCallbacks(const SoShape *shape,
					     const SoPrimitiveVertex *v1,
					     const SoPrimitiveVertex *v2)
//
////////////////////////////////////////////////////////////////////////
{
    lineSegmentCallback	*lsCb;
    int			i;

    for (i = 0; i < lineSegmentCallbackList.getLength(); i++) {
	lsCb = (lineSegmentCallback *)lineSegmentCallbackList[i];
	if (shape->isOfType(lsCb->type))
	    (lsCb->cb)(lsCb->data, this, v1, v2);
    }
}

////////////////////////////////////////////////////////////////////////
//
// Description:
//    Invoke point callbacks.
//
// Use: internal

void
SoCallbackAction::invokePointCallbacks(const SoShape *shape,
				       const SoPrimitiveVertex *v)
//
////////////////////////////////////////////////////////////////////////
{
    pointCallback	*pntCb;
    int			i;

    for (i = 0; i < pointCallbackList.getLength(); i++) {
	pntCb = (pointCallback *)pointCallbackList[i];
	if (shape->isOfType(pntCb->type))
	    (pntCb->cb)(pntCb->data, this, v);
    }
}

////////////////////////////////////////////////////////////////////////
//
// Description:
//    Returns TRUE if the given node should have primitives generated
//    for it.  SoShape takes care of checking this flag and calling
//    (or not calling) the appropriate callbacks.
//
// Use: internal

SbBool
SoCallbackAction::shouldGeneratePrimitives(const SoShape *shape) const
//
////////////////////////////////////////////////////////////////////////
{
    triangleCallback	*triCb;
    lineSegmentCallback	*lsCb;
    pointCallback	*pntCb;
    int			i;

    // Look at each callback list to see if there is an occurrence of
    // this shape type.  Return TRUE if the type is found.
    for (i = 0; i < triangleCallbackList.getLength(); i++) {
	triCb = (triangleCallback *)triangleCallbackList[i];
	if (shape->isOfType(triCb->type))
            return TRUE;
    }
    for (i = 0; i < lineSegmentCallbackList.getLength(); i++) {
	lsCb = (lineSegmentCallback *)lineSegmentCallbackList[i];
	if (shape->isOfType(lsCb->type))
            return TRUE;
    }
    for (i = 0; i < pointCallbackList.getLength(); i++) {
	pntCb = (pointCallback *)pointCallbackList[i];
	if (shape->isOfType(pntCb->type))
            return TRUE;
    }

    return FALSE;
}

////////////////////////////////////////////////////////////////////////
//
// Description:
//    Initiates action on a graph.
//
// Use: protected

void
SoCallbackAction::beginTraversal(SoNode *node)
//
////////////////////////////////////////////////////////////////////////
{
    response = CONTINUE;

    traverse(node);
}

/////////////////////////////////////////////////////////////////////////
//
// Description:
//     Provides current node being traversed
//     Relies on SoNode::callbackS setting the node, rather than
//     the path being accumulated during traversal.
//
// Use: public, virtual

SoNode *
SoCallbackAction::getCurPathTail()
{
#ifdef DEBUG
    if ( currentNode != ((SoFullPath*)getCurPath())->getTail()){
	SoDebugError::post("SoCallbackAction::getCurPathTail\n",
	"Path tail inconsistent.  Did you change the scene graph\n"
	"during a callback action?\n");
    }
#endif /*DEBUG*/
    return(currentNode);
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>net.apexes.wsonrpc</groupId>
		<artifactId>wsonrpc</artifactId>
		<version>1.1.0</version>
		<relativePath>../pom.xml</relativePath>
	</parent>
	<artifactId>wsonrpc-server</artifactId>

	<dependencies>
		<!-- wsonrpc -->
		<dependency>
			<groupId>net.apexes.wsonrpc</groupId>
			<artifactId>wsonrpc-core</artifactId>
		</dependency>

		<!-- javax.servlet -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>2.5</version>
			<scope>provided</scope>
		</dependency>
	</dependencies>
</project>


text:
<?php

namespace Kunstmaan\FormBundle\Tests\AdminList;

use Doctrine\Common\Collections\ArrayCollection;
use Kunstmaan\FormBundle\AdminList\FormSubmissionExportListConfigurator;
use Kunstmaan\FormBundle\Entity\FormSubmission;
use Kunstmaan\FormBundle\Entity\FormSubmissionFieldTypes\BooleanFormSubmissionField;
use Kunstmaan\NodeBundle\Entity\Node;
use Kunstmaan\NodeBundle\Entity\NodeTranslation;
use Symfony\Component\Translation\Translator;
use Kunstmaan\NodeBundle\Tests\Stubs\TestRepository;
use Kunstmaan\FormBundle\Tests\Stubs\TestConfiguration;

class FakeFormSubmission extends FormSubmission
{
    public function setFields(ArrayCollection $fields)
    {
        $this->fields = $fields;
    }
}

/**
 * This test tests the FormPageAdminListConfigurator
 */
class FormSubmissionExportListConfiguratorTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var FormSubmissionExportListConfigurator
     */
    protected $object;

    /**
     * Sets up the fixture, for example, opens a network connection.
     * This method is called before a test is executed.
     */
    protected function setUp()
    {
        $em = $this->getMockedEntityManager();
        $node = new Node();
        $node->setId(666);
        $nt = new NodeTranslation();
        $nt->setNode($node);
        $translator = new Translator('nl');
        $this->object = new FormSubmissionExportListConfigurator($em, $nt, $translator);
    }

    /**
     * https://gist.github.com/1331789
     *
     * @return \Doctrine\ORM\EntityManager
     */
    protected function getMockedEntityManager()
    {

        $queryBuilder = $this->getMockBuilder('Doctrine\ORM\QueryBuilder')
            ->disableOriginalConstructor()
            ->getMock();

        $field = new BooleanFormSubmissionField();
        $field->setFieldName('check');
        $field->setValue(true);

        $sub = new FakeFormSubmission();
        $sub->setFields(new ArrayCollection([
            $field,
        ]));

        $submissions = [
            [$sub],
            [new FormSubmission()],
            [new FormSubmission()],
        ];
        $query = $this->getMockBuilder('Doctrine\ORM\AbstractQuery')
            ->disableOriginalConstructor()
            ->getMock();

        $query->expects($this->any())
            ->method('iterate')
            ->willReturn($submissions);

        $methods = [
            'select', 'from', 'innerJoin', 'andWhere', 'setParameter', 'addOrderBy'
        ];
        foreach ($methods as $method) {
            $queryBuilder->expects($this->any())
                ->method($method)
                ->willReturn($queryBuilder);
        }

        $queryBuilder->expects($this->any())
            ->method('getQuery')
            ->willReturn($query);

        $emMock  = $this->createMock('\Doctrine\ORM\EntityManager', [], [], '', false);
        $emMock->expects($this->any())
            ->method('getRepository')
            ->will($this->returnValue(new TestRepository()));
        $emMock->expects($this->any())
            ->method('getConfiguration')
            ->will($this->returnValue(new TestConfiguration()));
        $emMock->expects($this->any())
            ->method('getClassMetadata')
            ->will($this->returnValue((object) array('name' => 'aClass')));
        $emMock->expects($this->any())
            ->method('persist')
            ->will($this->returnValue(null));
        $emMock->expects($this->any())
            ->method('flush')
            ->will($this->returnValue(null));
        $emMock->expects($this->any())
            ->method('createQueryBuilder')
            ->will($this->returnValue($queryBuilder));

        /** @var  \Doctrine\ORM\EntityManager $emMock */
        return $emMock;
    }

    public function testGetStringValue()
    {
        $this->assertNull($this->object->buildFilters());
        $this->assertEquals('', $this->object->getStringValue([], 'fail'));
        $this->assertEquals('pass', $this->object->getStringValue(['test' => 'pass'], 'test'));
    }

    public function testBuildExportFields()
    {
        $this->object->buildExportFields();
        $this->assertCount(3, $this->object->getExportFields());
        $this->object->addExportField('abc', 'def');
        $this->assertCount(4, $this->object->getExportFields());
    }

    public function testBuildIterator()
    {
        $this->object->buildIterator();
        $filters = $this->object->getIterator();
        $this->assertInstanceOf(\ArrayIterator::class, $filters);
        $first = $filters->current();
        $this->assertCount(1, $first);
        $first = $first[0];
        $this->assertArrayHasKey('check', $first);
        $this->assertEquals('true', $first['check']);

    }
}


text:
local Observable = require 'observable'
local util = require 'util'

--- Returns a new Observable that skips elements until the predicate returns falsy for one of them.
-- @arg {function} predicate - The predicate used to continue skipping values.
-- @returns {Observable}
function Observable:skipWhile(predicate)
  predicate = predicate or util.identity

  return Observable.create(function(observer)
    local skipping = true

    local function onNext(...)
      if skipping then
        util.tryWithObserver(observer, function(...)
          skipping = predicate(...)
        end, ...)
      end

      if not skipping then
        return observer:onNext(...)
      end
    end

    local function onError(message)
      return observer:onError(message)
    end

    local function onCompleted()
      return observer:onCompleted()
    end

    return self:subscribe(onNext, onError, onCompleted)
  end)
end


text:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.thinkgem.jeesite.modules.pro.dao.ProTapeEmptyDao">

	<sql id="proTapeEmptyColumns">
		a.id AS "id",
		a.pro_tape_type_id AS "proTapeType.id",
		a.bar_code AS "barCode",
		a.set_date AS "setDate",
		a.start_date AS "startDate",
		a.cur_state AS "curState",
		a.version AS "version",
		a.create_by AS "createBy.id",
		a.create_date AS "createDate",
		a.update_by AS "updateBy.id",
		a.update_date AS "updateDate",
		a.remarks AS "remarks",
		a.del_flag AS "delFlag",

		a2.name AS "proTapeType.name"
	</sql>

	<sql id="proTapeEmptyJoins">
		LEFT JOIN pro_tape_type a2 ON a2.id = a.pro_tape_type_id
	</sql>

	<select id="get" resultType="ProTapeEmpty">
		SELECT
			<include refid="proTapeEmptyColumns"/>
		FROM pro_tape_empty a
		<include refid="proTapeEmptyJoins"/>
		WHERE a.id = #{id}
	</select>

	<select id="findList" resultType="ProTapeEmpty">
		SELECT
			<include refid="proTapeEmptyColumns"/>
		FROM pro_tape_empty a
		<include refid="proTapeEmptyJoins"/>
		<where>
			a.del_flag = #{DEL_FLAG_NORMAL}
			<if test="proTapeType != null and proTapeType.id != null and proTapeType.id != ''">
				AND a.pro_tape_type_id = #{proTapeType.id}
			</if>
			<if test="barCode != null and barCode != ''">
				AND a.bar_code = #{barCode}
			</if>
		</where>
		<choose>
			<when test="page !=null and page.orderBy != null and page.orderBy != ''">
				ORDER BY ${page.orderBy}
			</when>
			<otherwise>
				ORDER BY a.update_date DESC
			</otherwise>
		</choose>
	</select>

	<select id="findAllList" resultType="ProTapeEmpty">
		SELECT
			<include refid="proTapeEmptyColumns"/>
		FROM pro_tape_empty a
		<include refid="proTapeEmptyJoins"/>
		<where>
			a.del_flag = #{DEL_FLAG_NORMAL}
		</where>
		<choose>
			<when test="page !=null and page.orderBy != null and page.orderBy != ''">
				ORDER BY ${page.orderBy}
			</when>
			<otherwise>
				ORDER BY a.update_date DESC
			</otherwise>
		</choose>
	</select>

	<insert id="insert">
		INSERT INTO pro_tape_empty(
			id,
			pro_tape_type_id,
			bar_code,
			set_date,
			start_date,
			cur_state,
			version,
			create_by,
			create_date,
			update_by,
			update_date,
			remarks,
			del_flag
		) VALUES (
			#{id},
			#{proTapeType.id},
			#{barCode},
			#{setDate},
			#{startDate},
			#{curState},
			#{version},
			#{createBy.id},
			#{createDate},
			#{updateBy.id},
			#{updateDate},
			#{remarks},
			#{delFlag}
		)
	</insert>

	<update id="update">
		UPDATE pro_tape_empty SET
			pro_tape_type_id = #{proTapeType.id},
			bar_code = #{barCode},
			set_date = #{setDate},
			start_date = #{startDate},
			cur_state = #{curState},
			version = #{version},
			update_by = #{updateBy.id},
			update_date = #{updateDate},
			remarks = #{remarks}
		WHERE id = #{id}
	</update>

	<update id="delete">
		UPDATE pro_tape_empty SET
			del_flag = #{DEL_FLAG_DELETE}
		WHERE id = #{id}
	</update>

</mapper>


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

describe YARD::CodeObjects::Proxy do
  before { Registry.clear }

  it "should return the object if it's in the Registry" do
    pathobj = ModuleObject.new(:root, :YARD)
    proxyobj = P(:root, :YARD)
    proxyobj.type.should == :module
    Proxy.should_not === proxyobj
  end

  it "should handle complex string namespaces" do
    ModuleObject.new(:root, :A)
    pathobj = ModuleObject.new(P(nil, :A), :B)
    P(:root, "A::B").should be_instance_of(ModuleObject)
  end

  it "should not return true to Proxy === obj if obj is a Proxy class holding a resolved object" do
    Proxy.should === P(:root, 'a')
    Proxy.should_not === P(:root)
    MethodObject.new(:root, 'a')
    Proxy.should_not === P(:root, 'a')
    x = Proxy.new(:root, 'a')
    Proxy.should_not === x
  end

  it "should return the object if it's an included Module" do
    yardobj = ModuleObject.new(:root, :YARD)
    pathobj = ClassObject.new(:root, :TestClass)
    pathobj.instance_mixins << yardobj
    P(P(nil, :TestClass), :YARD).should be_instance_of(ModuleObject)
  end

  it "should respond_to respond_to?" do
    obj = ClassObject.new(:root, :Object)
    yardobj = ModuleObject.new(:root, :YARD)
    P(:YARD).respond_to?(:children).should == true
    P(:NOTYARD).respond_to?(:children).should == false

    P(:YARD).respond_to?(:initialize).should == false
    P(:YARD).respond_to?(:initialize, true).should == true
    P(:NOTYARD).respond_to?(:initialize).should == false
    P(:NOTYARD).respond_to?(:initialize, true).should == true
  end

  it "should make itself obvious that it's a proxy" do
    pathobj = P(:root, :YARD)
    pathobj.class.should == Proxy
    (Proxy === pathobj).should == true
  end

  it "should pretend it's the object's type if it can resolve" do
    pathobj = ModuleObject.new(:root, :YARD)
    proxyobj = P(:root, :YARD)
    proxyobj.should be_instance_of(ModuleObject)
  end

  it "should handle instance method names" do
    obj = P(nil, '#test')
    obj.name.should == :test
    obj.path.should == "#test"
    obj.namespace.should == Registry.root
  end

  it "should handle instance method names under a namespace" do
    pathobj = ModuleObject.new(:root, :YARD)
    obj = P(pathobj, "A::B#test")
    obj.name.should == :test
    obj.path.should == "A::B#test"
  end

  it "should allow type to be changed" do
    obj = P("InvalidClass")
    obj.type.should == :proxy
    Proxy.should === obj
    obj.type = :class
    obj.type.should == :class
  end

  it "should NOT retain a type change between Proxy objects" do
    P("InvalidClass").type = :class
    P("InvalidClass").type.should == :proxy
  end

  it "should use type to ensure resolved object is of intended type" do
    YARD.parse_string <<-eof
      module Foo
        class Bar; end
        def self.Bar; end
      end
    eof
    proxy = Proxy.new(P('Foo'), 'Bar')
    proxy.type = :method
    proxy.path.should == 'Foo.Bar'
  end

  it "should allow type in initializer" do
    Proxy.new(Registry.root, 'Foo', :method).type.should == :method
    P(Registry.root, 'Foo', :method).type.should == :method
  end

  it "should never equal Registry.root" do
    P("MYPROXY").should_not == Registry.root
    P("X::A").should_not == Registry.root
  end

  it "should reset namespace and name when object is resolved" do
    obj1 = ModuleObject.new(:root, :YARD)
    obj2 = ModuleObject.new(:root, :NOTYARD)
    resolved = Proxy.new(obj2, :YARD)
    resolved.should == obj1
    resolved.namespace.should == Registry.root
    resolved.name.should == :YARD
  end

  it "should ensure that the correct object was resolved" do
    foo = ModuleObject.new(:root, :Foo)
    foobar = ModuleObject.new(foo, :Bar)
    foobaz = ClassObject.new(foo, :Baz)

    # Remember, we're looking for Qux::Bar, not just 'Bar'
    proxy = Proxy.new(foobar, 'Foo::Qux::Bar')
    proxy.type.should == :proxy

    qux = ModuleObject.new(foo, :Qux)
    quxbar = ModuleObject.new(qux, :Bar)

    # Now it should resolve
    proxy.type.should == :module
  end

  it "should handle constant names in namespaces" do
    YARD.parse_string <<-eof
      module A; end; B = A
      module B::C; def foo; end end
    eof
    Proxy.new(:root, 'B::C').should == Registry.at('A::C')
  end
end


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>batchrun-dialog.h Source File</title>
<link href="doxygen.css" rel="stylesheet" type="text/css">
<link href="tabs.css" rel="stylesheet" type="text/css">

Main Page

Related Pages

Classes

Files

batchrun-dialog.h

00001 #ifndef BATCHRUN_DIALOG_H
00002 #define BATCHRUN_DIALOG_H
00003
00004 #include <QDialog>
00005 #include <QVector>
00006
00007 #include "ui_batchrun.h"
00008
00011 class BatchRunDialog : public QDialog, public Ui_BatchRunDialog {
00012         Q_OBJECT
00013
00014 public:
00018         BatchRunDialog(QStringList& trsets, QWidget *parent = 0);
00019
00020 signals:
00023         void tracerouteBatch(const QString& batchFilename);
00024
00025 private slots:
00027         void on_buttonBox_accepted();
00028
00030         void on_buttonBox_rejected();
00031 };
00032
00033 #endif // BATCHRUN_DIALOG_H

<address style="text-align: right;">Generated on Mon Dec 21 16:45:07 2009 by

 1.5.6 </address>