I've found a script that works within Greasemonkey on Firefox but doesn't work on Tampermonkey in Chrome. The only thing i've found online to try is changing "unsafewindow" to "window" as it doesnt work in chrome, which didnt work. Beyond that i have no idea and i'd really appreciate some help.
And i've gotta try and fill the wordcount because it wont let me post.
// ==UserScript==
// #name Haggler
// #version 1.1.0
// #namespace Shinzan
// #Description Neopets autohaggler
// #Match http://www.neopets.com/haggle.phtml*
// #Match http://www.neopets.com/haggle.phtml
// #include http://www.neopets.com/objects.phtml?obj_type=*&type=shop
// #include http://www.neopets.com/objects.phtml?type=shop&obj_type=*
// #require https://raw.githubusercontent.com/hectorvazc/jsfun/master/jsfun.min.js
// ==/UserScript==
var url = document.URL;
var OCR = true;
var return_ab = true;
var haggle_type = 1;
function solve_captcha(url, callback) {
var captcha = new Image();
captcha.src = url;
captcha.onload = function(){
var width = captcha.width;
var height = captcha.height;
var canvas = unsafeWindow.document.createElement('canvas');
canvas.width = width;
canvas.height = width;
canvas.getContext("2d").drawImage(captcha, 0, 0);
var imgData = canvas.getContext("2d").getImageData(0, 0, width, height);
var lowy = 999;
var lowx = 999;
var low = 999;
for (var x = 0; x < imgData.width; x++){
for (var y = 0; y < imgData.height; y++){
var i = x*4+y*4*imgData.width;
var avg = Math.floor((imgData.data[i]+imgData.data[i+1]+imgData.data[i+2])/3);
if (avg < low){
low = avg;
lowx = x;
lowy = y;
}
}
}
callback(lowx, lowy);
};
}
function smart_haggle(haggle_price){
var val = new Array(2);
val[0] = haggle_price.substr(0,1);
val[1] = haggle_price.substr(1,1);
var x = 0;
var end_price = "";
for(x=0; x<haggle_price.length; x++){
end_price += val[(x%2)];
}
return end_price;
}
function pctr_haggle(haggle_price){
var randomPer = (Math.floor(((Math.random()*10) + 90))/ 100);
return Math.floor(parseInt(haggle_price) * randomPer);
}
if(url === 'http://www.neopets.com/haggle.phtml'){
if(return_ab) js().getNode('input[type="submit"]')[1].click();
}else if(url.includes('objects.phtml')){
var content = js().getNode('table[align="center"][cellpadding="4"][border="0"]');
js().here(content).find('tr').each(function(tr){
js().here(tr).find('td').each(function(td){
var a = js().here(td).find('a').detach()[0];
js(a).removeAttribute('onclick');
js(td).insertFirst(a);
});
});
}else if(url.includes('haggle.phtml')){
var src = js().here('div[align=center]').getNode('img[width="450"][height="150"]');
var haggle_price = js().getNode('font')[2];
haggle_price = js().here(haggle_price).getNode('b')[3].innerHTML;
haggle_price = (haggle_price.match("([0-9-,]+)")[0]).replace(",", "");
var value = (haggle_type) == 1 ? smart_haggle(haggle_price) : pctr_haggle(haggle_price);
js().find('input[name=current_offer]').val(value);
if(OCR){
solve_captcha(document.querySelector('input[type="image"]').src, function(x, y) {
setTimeout(function(){
var haggleform = document.querySelector('form[name="haggleform"]');
var newInput = document.createElement("input");
var newInput2 = document.createElement("input");
newInput.type="hidden";
newInput.name="x";
newInput.value=x;
haggleform.appendChild(newInput);
newInput2.type="hidden";
newInput2.name="y";
newInput2.value=y;
haggleform.appendChild(newInput2);
haggleform.submit();
}, 500);
});
}
}
Related
I am on a frame in Animate by Adobe. When I add a "change" listener to my tween I lose scope when I hit the change function called animateParticle. Also related, the tween attached to the particle doesn't recognize .setPaused(true) function.
this.stop();
that = this;
var particleCount = 0;
var aParticle;
var mySpeed = 12;
var myRotation = 4;
var totalParticles = 5;
var stopParticles = false;
var particleHolder = new createjs.Container();
var mc_coll1 = this.parent.mc_coll0;
mc_coll1.setBounds(0,0,156,34);
var collission_ar = [this.parent.mc_coll0, this.parent.mc_coll1, this.parent.mc_coll2, this.parent.mc_coll3, this.parent.mc_coll4, this.parent.mc_coll5, this.parent.mc_coll6, this.parent.mc_coll7, this.parent.mc_coll8, this.parent.mc_coll9, this.parent.mc_coll10, this.parent.mc_coll11, this.parent.mc_coll12, this.parent.mc_coll13, this.parent.mc_coll14];
var totalCollisions = collission_ar.length;
this.addChild(particleHolder);
var xRange = width;
var yRange = height;
var scaleNum = 1;
//var collisionMethod = ndgmr.checkPixelCollision;
this.scaleX = 1;
this.scaleY = 1;
createParticles()
setTimeout(function(){
removeTimer();
//clearTimeout(that.pauseVar);
}, 2000)
function createParticles(){
var particle_ar = [];
var randNum = Math.ceil(Math.random() * totalParticles);
aParticle = new lib['MC_leaf'+randNum]();
aParticle.name = 'aParticle'+particleCount;
aParticle.x = Math.random() * xRange;
aParticle.y = -Math.random() * 15;
theNum = Math.random() * scaleNum;
aParticle.scaleX = theNum
aParticle.scaleY = theNum
aParticle.alpha = 1;
aParticle.collision = Math.floor(Math.random() * 2);
particleHolder.addChild(aParticle);
particleCount++;
var tween2 = createjs.Tween.get(aParticle).wait(0).to({y:yRange}, 2000, createjs.Ease.easeOut).call(removeObj,[aParticle], that).addEventListener('change', animateParticle.bind(that));
aParticle.tween = tween2;
if(!stopParticles){
timer = setTimeout(function() { createParticles() }, 100);
}
}
function animateParticle (event){
var part = event.currentTarget;
var mc_newColl;
console.log('part '+part.name);
for(var i=0; i < totalCollisions; i++){
// collision checking
mc_newColl = collission_ar[i];
var intersection = checkIntersection(part,mc_newColl);
if (intersection){
part.tween.setPaused(true);
//part.removeEventListener("tick", animateParticle.bind(that));
}
}
}
function checkIntersection(part, coll) {
if ( part.x >= coll.x + coll.width || part.x + part.width <= coll.x || part.y >= coll.y + coll.height || part.y + part.height <= coll.y ) return false;
return true;
}
function removeObj(part){
particleHolder.removeChild(part);
}
function removeTimer() {
stopParticles = true;
timer = clearInterval();
//var tween2 = createjs.Tween.get(particleHolder).wait(0).to({alpha:0}, 2000, createjs.Ease.easeOut);
}
//var timer = setInterval(function() { createParticles() }, 200, that);
var timer = setTimeout(function() { createParticles() }, 100, this);
In animateParticle, part is undefined.
The target of the change event will not be the particle, but the tween itself, since it is the dispatching object.
createjs.Tween.get(particle).to({x:1000}, 2000)
.on("change", function(event) {
console.log(event.target); // Tween
console.log(event.target.name); // undefined
console.log(event.target.target); // particle
console.log(event.target.target.name); // particle's name
}, that);
The undefined you are seeing is not the particle, but the name that you are logging.
Note that using on instead of addEventListener lets you pass a scope as a parameter instead of using bind.
Hope that helps.
I have create a group in phaserjs
this.fruitsOutline = this.game.add.group();
After that I have added few sprites in it. Everything is working correctly. Now if want to access this.fruitsOutline, from inside of a onDragStart event handler, it is giving undefined
var GameState = {
init:function(){
this.physics.startSystem(Phaser.Physics.ARCADE);
},
create: function () {
var innerImgPos = {x:150,y:200};
var outlineImgPos = {x:460,y:200};
var FIXED_DISTANCE_Y = 150;
var gameData = [
//...some data
];
this.background = this.game.add.sprite(0, 0, 'background');
this.overlapHappen = false;
this.startPos = {x:150,y:197};
this.fruitsOutline = this.game.add.group();
this.fruitsInner = this.game.add.group();
for(var i=0; i<gameData.length; i++){
fruitOuter = this.fruitsOutline.create(outlineImgPos.x,((outlineImgPos.y+25)*i)+FIXED_DISTANCE_Y,gameData[i].fruit_outline.img);
fruitOuter.name = gameData[i].fruitName;
fruitOuter.anchor.setTo(.5);
fruitOuter.customParams = {myName:gameData[i].fruit_outline.name};
this.game.physics.arcade.enable(fruitOuter);
fruitOuter.body.setSize(100,100,50,50);
fruitInner = this.fruitsInner.create(innerImgPos.x,((innerImgPos.y+25)*i)+FIXED_DISTANCE_Y,gameData[i].fruit_inner.img);
fruitInner.name = gameData[i].fruitName;
fruitInner.anchor.setTo(0.5);
fruitInner.inputEnabled = true;
fruitInner.input.enableDrag();
fruitInner.input.pixelPerfectOver = true;
fruitInner.originalPos = {x:fruitInner.position.x,y:fruitInner.position.y};
this.game.physics.arcade.enable(fruitInner);
fruitInner.body.setSize(100,100,50,50);
fruitInner.customParams = {myName:gameData[i].fruit_inner.name,targetKey:fruitOuter,targetImg:gameData[i].fruit_outline.name};
fruitInner.events.onDragStart.add(this.onDragStart);
fruitInner.events.onDragStop.add(this.onDragStop,this);
}
},
update: function () {
},
onDragStart:function(sprite,pointer){
console.log(this.fruitsInner) //this gives undefined I expect an array
},
onDragStop:function(sprite,pointer){
var endSprite = sprite.customParams.targetKey;
console.log(endSprite);
this.stopDrag(sprite,endSprite)
},
stopDrag:function(currentSprite,endSprite){
var currentSpriteRight = currentSprite.position.x + (currentSprite.width / 2);
if (!this.game.physics.arcade.overlap(currentSprite, endSprite, function() {
var currentSpriteTarget = currentSprite.customParams.targetImg;
var endSpriteName = endSprite.customParams.myName;
console.log(currentSpriteTarget,endSpriteName);
if(currentSpriteTarget === endSpriteName){
currentSprite.input.draggable = false;
currentSprite.position.copyFrom(endSprite.position);
currentSprite.anchor.setTo(endSprite.anchor.x, endSprite.anchor.y);
}
console.log(currentSprite.width);
})) {
//currentSprite.position.copyFrom(currentSprite.originalPosition);
currentSprite.position.x = currentSprite.originalPos.x;
currentSprite.position.y = currentSprite.originalPos.y;
}
},
render:function(){
game.debug.body(this.fruitsInner);
//game.debug.body(this.orange_outline);
}
}
You're missing the context when adding the drag callback.
Try that (adding this as the second argument):
fruitInner.events.onDragStart.add(this.onDragStart, this);
Oh, and inside the callback (or anywhere in the state) this.fruitsInner will be an instance of Phaser.Group, not an array like that comment says. The array you're looking for is probably this.fruitsInner.children.
So I am using this npm package: node-stl
And its working great. However the regexp syntax, mathematics and geometrical calculations are somewhat confusing to me. Especially all at the same time.
Basically what I want to achieve is to extend the script to calculate the bounding box of the STL.
Here is the main file that calculates the volume and weight of the STL being parsed/read.
var fs = require('fs');
// Vertex
function Vertex (v1,v2,v3) {
this.v1 = Number(v1);
this.v2 = Number(v2);
this.v3 = Number(v3);
}
// Vertex Holder
function VertexHolder (vertex1,vertex2,vertex3) {
this.vert1 = vertex1;
this.vert2 = vertex2;
this.vert3 = vertex3;
}
// transforming a Node.js Buffer into a V8 array buffer
function _toArrayBuffer (buffer) {
var
ab = new ArrayBuffer(buffer.length),
view = new Uint8Array(ab);
for (var i = 0; i < buffer.length; ++i) {
view[i] = buffer[i];
}
return ab;
}
// calculation of the triangle volume
// source: http://stackoverflow.com/questions/6518404/how-do-i-calculate-the-volume-of-an-object-stored-in-stl-files
function _triangleVolume (vertexHolder) {
var
v321 = Number(vertexHolder.vert3.v1 * vertexHolder.vert2.v2 * vertexHolder.vert1.v3),
v231 = Number(vertexHolder.vert2.v1 * vertexHolder.vert3.v2 * vertexHolder.vert1.v3),
v312 = Number(vertexHolder.vert3.v1 * vertexHolder.vert1.v2 * vertexHolder.vert2.v3),
v132 = Number(vertexHolder.vert1.v1 * vertexHolder.vert3.v2 * vertexHolder.vert2.v3),
v213 = Number(vertexHolder.vert2.v1 * vertexHolder.vert1.v2 * vertexHolder.vert3.v3),
v123 = Number(vertexHolder.vert1.v1 * vertexHolder.vert2.v2 * vertexHolder.vert3.v3);
return Number(1.0/6.0)*(-v321 + v231 + v312 - v132 - v213 + v123);
}
// parsing an STL ASCII string
function _parseSTLString (stl) {
var totalVol = 0;
// yes, this is the regular expression, matching the vertexes
// it was kind of tricky but it is fast and does the job
var vertexes = stl.match(/facet\s+normal\s+([-+]?\b(?:[0-9]*\.)?[0-9]+(?:[eE][-+]?[0-9]+)?\b)\s+([-+]?\b(?:[0-9]*\.)?[0-9]+(?:[eE][-+]?[0-9]+)?\b)\s+([-+]?\b(?:[0-9]*\.)?[0-9]+(?:[eE][-+]?[0-9]+)?\b)\s+outer\s+loop\s+vertex\s+([-+]?\b(?:[0-9]*\.)?[0-9]+(?:[eE][-+]?[0-9]+)?\b)\s+([-+]?\b(?:[0-9]*\.)?[0-9]+(?:[eE][-+]?[0-9]+)?\b)\s+([-+]?\b(?:[0-9]*\.)?[0-9]+(?:[eE][-+]?[0-9]+)?\b)\s+vertex\s+([-+]?\b(?:[0-9]*\.)?[0-9]+(?:[eE][-+]?[0-9]+)?\b)\s+([-+]?\b(?:[0-9]*\.)?[0-9]+(?:[eE][-+]?[0-9]+)?\b)\s+([-+]?\b(?:[0-9]*\.)?[0-9]+(?:[eE][-+]?[0-9]+)?\b)\s+vertex\s+([-+]?\b(?:[0-9]*\.)?[0-9]+(?:[eE][-+]?[0-9]+)?\b)\s+([-+]?\b(?:[0-9]*\.)?[0-9]+(?:[eE][-+]?[0-9]+)?\b)\s+([-+]?\b(?:[0-9]*\.)?[0-9]+(?:[eE][-+]?[0-9]+)?\b)\s+endloop\s+endfacet/g);
vertexes.forEach(function (vert) {
var preVertexHolder = new VertexHolder();
vert.match(/vertex\s+([-+]?\b(?:[0-9]*\.)?[0-9]+(?:[eE][-+]?[0-9]+)?\b)\s+([-+]?\b(?:[0-9]*\.)?[0-9]+(?:[eE][-+]?[0-9]+)?\b)\s+([-+]?\b(?:[0-9]*\.)?[0-9]+(?:[eE][-+]?[0-9]+)?\b)\s/g).forEach(function (vertex, i) {
var tempVertex = vertex.replace('vertex', '').match(/[-+]?[0-9]*\.?[0-9]+/g);
var preVertex = new Vertex(tempVertex[0],tempVertex[1],tempVertex[2]);
preVertexHolder['vert'+(i+1)] = preVertex;
});
var partVolume = _triangleVolume(preVertexHolder);
totalVol += Number(partVolume);
})
var volumeTotal = Math.abs(totalVol)/1000;
return {
volume: volumeTotal, // cubic cm
weight: volumeTotal * 1.04 // gm
}
}
// parsing an STL Binary File
// (borrowed some code from here: https://github.com/mrdoob/three.js/blob/master/examples/js/loaders/STLLoader.js)
function _parseSTLBinary (buf) {
buf = _toArrayBuffer(buf);
var
headerLength = 80,
dataOffset = 84,
faceLength = 12*4 + 2,
le = true; // is little-endian
var
dvTriangleCount = new DataView(buf, headerLength, 4),
numTriangles = dvTriangleCount.getUint32(0, le),
totalVol = 0;
for (var i = 0; i < numTriangles; i++) {
var
dv = new DataView(buf, dataOffset + i*faceLength, faceLength),
normal = new Vertex(dv.getFloat32(0, le), dv.getFloat32(4, le), dv.getFloat32(8, le)),
vertHolder = new VertexHolder();
for(var v = 3; v < 12; v+=3) {
var vert = new Vertex(dv.getFloat32(v*4, le), dv.getFloat32((v+1)*4, le), dv.getFloat32( (v+2)*4, le ) );
vertHolder['vert'+(v/3)] = vert;
}
totalVol += _triangleVolume(vertHolder);
}
var volumeTotal = Math.abs(totalVol)/1000;
return {
volume: volumeTotal, // cubic cm
weight: volumeTotal * 1.04 // gm
}
}
// NodeStl
// =======
// > var stl = NodeStl(__dirname + '/myCool.stl');
// > console.log(stl.volume + 'cm^3');
// > console.log(stl.weight + 'gm');
function NodeStl (stlPath) {
var
buf = fs.readFileSync(stlPath),
isAscii = true;
for (var i=0, len=buf.length; i<len; i++) {
if (buf[i] > 127) { isAscii=false; break; }
}
if (isAscii)
return _parseSTLString(buf.toString());
else
return _parseSTLBinary(buf);
}
module.exports = NodeStl;
If anyone could help me with this it would be great. I know and it feels like it simple. That I just need to know max/min of the different directions(x,y,z) and could then calculate the bounding box.
But I do not understand what the max/min for x,y and z is here. Please answer if you have an idea.
I've made a new branch https://github.com/johannesboyne/node-stl/tree/boundingbox could you please verify whether the applied algorithm works?
Best,
Johannes
Edit: If the branch is stable -> works I'll push it into v.0.1.0 (don't know why it is still 0.0.1)
I am getting the values of the properties of an object(top,width...) as an object is being scaled/moved by using this function :
canvas.on('object:scaling', onObjectModification);
canvas.on('object:moving', onObjectModification);
canvas.on('object:rotating', onObjectModification);
function onObjectModification(e) {
var activeObject = e.target;
var reachedLimit = false;
objectLeft = activeObject.left,
objectTop = activeObject.top,
objectWidth = activeObject.width,
objectHeight = activeObject.height,
canvasWidth = canvas.width,
canvasHeight = canvas.height;
}
How can I get the same for each object that are being moved as a group? I need the values to be constantly changing as the object:scaling event provide.
I know of the event selection:created but I am lost how to use that to attain what I want. Any help from you guys would be highly appreciated.
Thanks
during object scaling width and height will not change. They will be the same all the time, just scaleX and scaleY will change.
You have to write a function that will iterate on possibile group sub objects.
canvas.on('object:scaling', onObjectModification);
canvas.on('object:moving', onObjectModification);
canvas.on('object:rotating', onObjectModification);
function onObjectModification(e) {
var activeObject = e.target;
if (!activeObject) {
return;
}
var canvasWidth = canvas.width;
var canvasHeight = canvas.height;
var reachedLimit = false;
var objectLeft = activeObject.left;
var objectTop = activeObject.top;
// this provide scaled height and width
var objectWidth = activeObject.getWidth();
var objectHeight = activeObject.getHeight();
if (activeObject._objects) {
objs = activeObject._objects;
for (var i= 0; i < objs.length; i++) {
var obj = objs[i];
var objWidth = activeObject.getWidth() * activeObject.scaleX;
var objHeight = activeObject.getHeight() * activeObject.scaleY;
}
}
}
my project using flex mobile 4.5 using socket .. receive huge data stream..
and ui application like hang... in minute before all process data complete
and how to do with multi thread in socket in as3 ? any axamples ?
any trick? to make background process
bellow my code
private var workQueue:Array = new Array();
/**************** VARIABLES ************************/
[Bindable]public var defauldSocketIP:String ="119.99.67.168";
[Bindable]public var defauldPort:Number = 9090;
[Bindable]public var heartbeatTime:Number = 1000 * 60;
[Bindable]public var limitLivetrade:Number = 30;
[Bindable]public var sessionid:String;
[Bindable]public var userid:String;
[Bindable]public var password:String;
[Bindable]public var msgdata:String;
[Bindable]public var busyIndicator:Boolean = false;
[Bindable]public var livetradeData:ArrayCollection = new ArrayCollection();
[Bindable]public var IndicesSectoralData:ArrayCollection = new ArrayCollection();
[Bindable]public var topGainerBrokerData:ArrayCollection = new ArrayCollection();
[Bindable]public var brokerData:ArrayCollection = new ArrayCollection();
[Bindable]public var stockData:ArrayCollection = new ArrayCollection();
[Bindable]public var marketChartData:ArrayCollection = new ArrayCollection();
/* best Quote */
[Bindable]public var bestQuoteDataA:ArrayCollection = new ArrayCollection();
[Bindable]public var bestQuoteDataB:ArrayCollection = new ArrayCollection();
[Bindable]public var bestQuoteBID:ArrayCollection = new ArrayCollection();
[Bindable]public var bestQuoteOFFER:ArrayCollection = new ArrayCollection();
[Bindable]public var bestQuoteTFREQ:ArrayCollection = new ArrayCollection();
[Bindable]public var stockSummarayData:ArrayCollection = new ArrayCollection();
/* end of best Quote */
[Bindable]public var tempDataSocket:ByteArray = new ByteArray();
[Bindable]public var sTemp:int = new int();
[Bindable]public var db:ArrayCollection = new ArrayCollection();
[Bindable]public var curentCode:String;//current code for unscribe
/**************** Socket ********************/
private var buffer:ByteArray = new ByteArray();
public var _data:ByteArray;
[Bindable]public var websocketData:String;
[Bindable]public var isLogin:Boolean = false;
public var flipTrans:FlipViewTransition = new FlipViewTransition();
\
/* socket connection */
public var socket : Socket;
public function init() : void {
//navigator.defaultPushTransition = new FlipViewTransition();
socket = new Socket();
socket.addEventListener(Event.CONNECT, onConnect);
socket.addEventListener(Event.CLOSE, onSocketClose);
socket.addEventListener(ProgressEvent.SOCKET_DATA, onSocketData);
socket.addEventListener( IOErrorEvent.IO_ERROR, onIOError );
socket.addEventListener( SecurityErrorEvent.SECURITY_ERROR, onSEC_ERRORError );
/****************** INTERVAL FOR PING SERVER *************/
var myInterval:uint = setInterval (heartbeat, heartbeatTime);
//clearInterval(myInterval);
if(isLogin){
flipTrans.duration = 1000;
flipTrans.mode = FlipViewTransitionMode.CARD;
flipTrans.direction = ViewTransitionDirection.RIGHT;
mainview.pushView(MainView,null,null,flipTrans);
}
/****************** Database setup *************/
initDB();
if(db.length == 0){ createDefauldConfig(); }
}
/**************** menus ********************/
/**************** alert information box *********************/
protected function alertSoketError():void
{
Alert.show(this, Alert.IC_INFO, "Information", "Sorry cannot connect to server please contact administrator.");
}
/**************** inquotes database ********************/
public var sqlConnection:SQLConnection;
public function onSEC_ERRORError( errorEvent:SecurityErrorEvent ):void
{
busyIndicator = false;
isLogin = false;
mainview.pushView(login);
trace( "onSEC_ERRORError: " + errorEvent );
alertSoketError();
}
public function onSocketClose(e:Event,reconect:Boolean = true):void{ resetData();
socket.close();
mainview.pushView(login);
trace("socket Closed");
if(reconect){
reconnect();
}
}
public function onIOError( errorEvent:IOErrorEvent ):void
{
busyIndicator = false;
isLogin = false;
mainview.pushView(login);
trace( "IOError: " + errorEvent.text );
alertSoketError();
}
public function onConnect(event : Event) : void {
trace("login|"+userid+"|"+(MD5.hash(password)));
sendData("login|"+userid+"|"+(MD5.hash(password)));
}
public function getFormattedTime(t:int):String
{
var s:String = new String();
var hour:String = t.toString().substr(0,2);
var minute:String = t.toString().substr(2,2);
var scn:String = t.toString().substr(4,5);
return s =hour+":"+minute+":"+scn;
}
public function checkTipe(data:String):void{
var split:Array = spliter.doSplit(data,"|");
/*Login */
if(split[0]=="login" && split[1]=="ok" && isLogin == false){
trace("split[0]"+split[0]+"-split[1]"+split[1]+"isLogin =="+isLogin);
sessionid = new String();
sessionid = split[2];
isLogin = true;
flipTrans.duration = 1000;
flipTrans.mode = FlipViewTransitionMode.CARD;
flipTrans.direction = ViewTransitionDirection.RIGHT;
mainview.pushView(MainView,null,null,flipTrans);
sendData("subscribe|"+sessionid+"|4|0");
sendData("subscribe|"+sessionid+"|3|0");
sendData("subscribe|"+sessionid+"|5|0");
}
/*Login fail*/
if(split[0]=="login" && split[1]!="ok"){
sessionid = new String();
Alert.show(this, Alert.IC_INFO, "Login", "Sorry Fail.. check your user name or password");
}
/*live trade */
if(split[1]=="2"){
curentCode = "2";
var change:Number = split[17] == 0 ? 0 : split[6] - split[17];
var obj:Object = new Object();
obj.header = split[0];
obj.type = split[1];
obj.seqno = split[2];
obj.time = FormatTime.getFormattedTime(split[3]);
obj.stock = split[4];
obj.board = split[5];
obj.last = split[6];
obj.lot = split[7];
obj.buyer = split[8];
obj.buy = split[9];
obj.seller = split[10];
obj.sell = split[11];
obj.bestbid = split[12];
obj.bestbidlot = split[13];
obj.bestoffer = split[14];
obj.bestofferlot = split[15];
obj.tradeno = split[16];
obj.previous = split[17];
obj.change = change;
obj.percent = Number((change * 100 ) / split[17]).toFixed(1);
if(livetradeData.length < limitLivetrade){
livetradeData.addItem(obj);
}else{
livetradeData.removeItemAt(livetradeData.length-1);
livetradeData.addItemAt(obj,0);
}
livetradeData.refresh();
}
if(split[1]=="6"){
curentCode = "6" ;
IndicesSectoralData = IndicesSectoral.setIndicesSectoral(split,IndicesSectoralData);
IndicesSectoralData.refresh();
}
if(split[1]=="TSBB"){
curentCode = "TSBB";
var obj:Object = new Object();
obj.header = split[0];
obj.type = split[1];
obj.seqno = split[2];
obj.min1 = split[3];
obj.min2 = split[4];
obj.BrokerID = split[5];
obj.min3 = split[6];
obj.BuyAvg = split[7];
obj.SellAvg = split[8];
obj.BuyVol = split[9];
obj.BuyVal = formater.formatMoneyUnit(Number(split[10]));
obj.BuyFreq = split[11];
obj.SellVol = split[12];
obj.SellVal = formater.formatMoneyUnit(split[13]);
obj.SellFreq = formater.formatMoneyUnit(split[14]);
obj.ValNet = formater.formatMoneyUnit((Number(split[10]) -
Number(split[13])));
obj.TotalVal = formater.formatMoneyUnit((Number(split[10]) +
Number(split[13])));
obj.TotalVol = formater.formatMoneyUnit((Number(split[9]) +
Number(split[12])));
obj.FreqTotal = formater.formatMoneyUnit((Number(split[11]) +
Number(split[14])));
/*header|type|seqno|-|-|BrokerID|-|BuyAvg|SellAvg|BuyVol|BuyVal|BuyFreq|SellVol|SellVal|SellFreq
ValNet = BuyVal - SellVal
TotalVal = BuyVal + SellVal
TotalVol = BuyVol + SellVol
FreqTotal = BuyFreq + SellFreq
Diurut Berdasarkan TotalVal*/
var brokerIndex:int = find.findIndex(brokerData,"BrokerID", split[5]);
if(brokerIndex != -1){
obj.BrokerName = brokerData.getItemAt(brokerIndex).BrokerName;
}
var idx:int = find.findIndex(topGainerBrokerData,"BrokerID", split[5]);
//trace("BrokerID:"+idx+"arr[5]"+arr[5]);
if(idx == -1){
topGainerBrokerData.addItem(obj);
}else{
topGainerBrokerData.removeItemAt(idx);
topGainerBrokerData.addItemAt(obj,idx);
}
ArrayCollection. */
//topGainerBrokerData.sort = numericDataSort;
topGainerBrokerData.refresh();
}
/*broker */
if(split[1]=="4"){
curentCode = "4";
brokerData = Broker.setBroker(split,brokerData);
brokerData.refresh();
}
/*Stock */
if(split[1]=="3"){
curentCode = "3";
var objStock:Object = new Object();
objStock.header = split[0];
objStock.type = split[1];
objStock.seqno = split[2];
objStock.stockcode = split[3];
objStock.stockname = split[4];
objStock.status = split[5];
objStock.stocktype = split[6];
objStock.sector = split[7];
objStock.ipoprice = split[8];
objStock.baseprice = split[9];
objStock.listedshares = split[10];
objStock.tradelistedshares = split[11];
objStock.shareperlot = split[12];
var idStock:int = find.findIndex(stockData,"stockcode", split[3]);
//trace("BrokerID:"+idx+"arr[5]"+arr[5]);
if(idStock == -1){
stockData.addItem(objStock);
}else{
stockData.removeItemAt(idStock);
stockData.addItemAt(objStock,idStock);
}
}
if(split[1]=="1"){
curentCode = "1" ;
trace("best Quote A:"+data+"\n");
/* best quote bid */
var XB:Array = spliter.doSplit(data,"<");
var bLotBid:String = XB[1].toString().substring(1,XB[1].toString().indexOf("]")-1);
trace("bLotBid:"+bLotBid);
if(bLotBid != ""){
bLotBid = bLotBid.substring(1,bLotBid.length);
var bLotBidArr:Array = spliter.doSplit(bLotBid,">");
var bInt:int;
for(bInt = 0; bInt < 10;bInt++){
if(bLotBidArr[bInt] != undefined){
trace("dipotong :"+bLotBidArr[bInt]);
var bBidDAT:Array = spliter.doSplit(bLotBidArr[bInt],"|");
var obLotBid:Object = new Object();
obLotBid.freq = formater.formatNumber(bBidDAT[0]);
obLotBid.lot = formater.formatNumber(bBidDAT[1]);
obLotBid.bid = formater.formatNumber(bBidDAT[2]);
bestQuoteBID.addItem(obLotBid);
}
}
}
/* best quote bid */
/* offer */
var bOFF:String =
XB[1].toString().substring(XB[1].toString().indexOf("O[")+2,XB[1].toString().indexOf("]L"));
trace("bOFF:"+bOFF);
var boffArr:Array = spliter.doSplit(bOFF,">");
var bIof:int;
for(bIof = 0; bIof < 10;bIof++){
if(boffArr[bIof] != undefined && boffArr[bIof] != ""){
trace("dipotong offer :"+boffArr[bIof]);
var boofDAT:Array = spliter.doSplit(boffArr[bIof],"|");
var obLotBidOFF:Object = new Object();
obLotBidOFF.offer = formater.formatNumber(boofDAT[0]);
obLotBidOFF.lot = formater.formatNumber(boofDAT[1]);
obLotBidOFF.o = formater.formatNumber(boofDAT[2]);
bestQuoteOFFER.addItem(obLotBidOFF);
}
}
}
// best Quote B //
if(split[1]=="TP"){
curentCode = "TP";
trace("best Quote TP:"+data+"\n");
//header|type|seqno|stock|board|price|T.Lot|T.Freq
var objTp:Object = new Object();
objTp.header = split[0];
objTp.type = split[1];
objTp.seqno = split[2];
objTp.stock = split[3];
objTp.board = split[4];
objTp.price = formater.formatNumber(split[5]);
objTp.Tlot = formater.formatNumber(split[6]);
objTp.Tfreq = formater.formatNumber(split[7]);
bestQuoteTFREQ.addItem(objTp);
}
/* stock summary */
if(split[1]=="5"){
//curentCode = "5" ;
var objStcSum:Object = new Object();
objStcSum.header = split[0];
objStcSum.type = split[1];
objStcSum.seqno = split[2];
objStcSum.code = split[3];
objStcSum.board = split[4];
objStcSum.remarks = split[5];
objStcSum.previous = split[6];
objStcSum.highest = split[7];
objStcSum.lowest = split[8];
objStcSum.closing = split[9];
objStcSum.change = split[10];
objStcSum.tradedvolume = split[11];
objStcSum.tradedvalue = split[12];
objStcSum.tradedfrequency = split[13];
objStcSum.individualindices = split[14];
objStcSum.foreigner = split[15];
objStcSum.opening = split[16];
objStcSum.bestbid = split[17];
objStcSum.bestbidvolume = split[18];
objStcSum.bestoffer = split[19];
objStcSum.bestoffervolume = split[20];
stockSummarayData.addItem(objStcSum);
var idStockSum:int = find.findIndex(stockSummarayData,"code", split[3]);
if(idStockSum == -1){
stockSummarayData.addItem(objStcSum);
}else{
stockSummarayData.removeItemAt(idStockSum);
stockSummarayData.addItemAt(objStcSum,idStock);
}
}
/* market chart */
//trace("COMPOSITE-->"+split[1]);
if(split[0]=="CHI" && split[1]=="COMPOSITE"){
curentCode = "COMPOSITE";
//trace("split[1]:"+split[1]+"split[2]:"+split[2]+"split[3]:"+split[3]+"split[4]:"+split[4]);
var mrc:Array = spliter.doSplit(split.toString(),"\n");
if(split[2]!= null){
var o:int;
for(o = 0;o < (mrc.length -1);o++){
var dtmrc:Array = spliter.doSplit(mrc[o],",");
var objMcht:Object = new Object();
if(o == 0){
objMcht.time = FormatTime.getFormattedTime(dtmrc[2]);
objMcht.timeUnformat = dtmrc[2];
objMcht.type = dtmrc[3];
objMcht.value = dtmrc[4];
trace("mrc[o]"+mrc[o]+"== dtmrc:"+dtmrc[0]);
trace("dtmrc[2]"+dtmrc[2]);
trace("MARKET CHART time 0-->"+FormatTime.getFormattedTime(dtmrc[2]));
}else{
objMcht.time = FormatTime.getFormattedTime(dtmrc[0]);
objMcht.timeUnformat = dtmrc[0];
objMcht.type = dtmrc[1];
objMcht.value = dtmrc[2];
//trace("dtmrc[0]"+dtmrc[0]);
//trace("MARKET CHART time1-->"+FormatTime.getFormattedTime(dtmrc[0]))+"-->value-->"+dtmrc[2];
}
marketChartData.addItem(objMcht);
}
//time|type|value
}
marketChartData.refresh();
}
}
public function onSocketData(event : ProgressEvent) : void {
busyIndicator = true;
var msgdataTemp:String = new String();
var n:int = socket.bytesAvailable;
var bArray:ByteArray = new ByteArray();
try{
//trace("n "+n.toString());
while(n > 0){
var p:int = socket.bytesAvailable;
var s:int = new int();
if(sTemp == 0){
if(p > 0)
p = socket.bytesAvailable;
try{
s = socket.readInt();//total
}catch(e:EOFError){
trace("err :"+e);
break;
}
p = socket.bytesAvailable;
//trace("bArray"+bArray.toString()+" s:"+s.toString()+" "+p);
if(s > p){
var bytex:ByteArray = new ByteArray();
socket.readBytes(bytex,0,p);
tempDataSocket.writeBytes(bytex,0,bytex.length);
sTemp = s;
break;
}
socket.readBytes(bArray,0,s);
bArray.uncompress(CompressionAlgorithm.ZLIB);
checkTipe(bArray.toString());
n = n-( 4+ s);
}else{
if(sTemp > p){
//bArray.writeBytes(tempDataSocket,0,bArray.length);
socket.readBytes(bArray,0,p);
tempDataSocket.writeBytes(bArray,0,bArray.length);
// trace("sTemp > p sTemp :"+sTemp+" S :"+s+" p:"+p+" n:"+n+" "+tempDataSocket.length);
sTemp = sTemp +s;
if(sTemp == tempDataSocket.length){
tempDataSocket.uncompress(CompressionAlgorithm.ZLIB);
checkTipe(tempDataSocket.toString());
}
break;
}
//trace("sTemp :"+sTemp+" S :"+s+" p:"+p+" n:"+n+" tempDataSocket :"+tempDataSocket.length+" bArray.length:"+bArray.length);
var bnew:ByteArray = new ByteArray();
if(socket.bytesAvailable > 0){
socket.readBytes(bArray,0,(sTemp - tempDataSocket.length));
}
//tempDataSocket.writeBytes(bArray,tempDataSocket.length,bArray.length);
//bnew.writeBytes(bArray,sTemp
bnew.writeBytes(tempDataSocket,0,tempDataSocket.length);
bnew.writeBytes(bArray,0,bArray.length);
bnew.uncompress(CompressionAlgorithm.ZLIB);
//trace("bnew:"+bnew.toString());
checkTipe(bnew.toString());
tempDataSocket = new ByteArray();
n = socket.bytesAvailable;
sTemp = 0;
}
p = socket.bytesAvailable;
if(p>0){
}
}
}catch(ev:Error){
trace("socket_error:"+ev.getStackTrace());
}finally{
}
}
public function resetData():void{
sessionid = "";
msgdata = "";
busyIndicator = false;
livetradeData = new ArrayCollection();
IndicesSectoralData = new ArrayCollection();
topGainerBrokerData = new ArrayCollection();
brokerData = new ArrayCollection();
stockData = new ArrayCollection();
marketChartData = new ArrayCollection();
bestQuoteDataA = new ArrayCollection();
bestQuoteDataB = new ArrayCollection();
bestQuoteBID = new ArrayCollection();
bestQuoteOFFER = new ArrayCollection();
bestQuoteTFREQ = new ArrayCollection();
stockSummarayData = new ArrayCollection();
tempDataSocket = new ByteArray();
sTemp = new int();
curentCode = "";//current code for unscribe
buffer = new ByteArray();
_data = new ByteArray();
websocketData = "";
isLogin = false;
}
public function trim( s:String ):String
{
return s.replace( /^([\s|\t|\n]+)?(.*)([\s|\t|\n]+)?$/gm, "$2" );
}
private function removeBufferBefore(pos:int):void {
if (pos == 0) return;
var nextBuffer:ByteArray = new ByteArray();
buffer.position = pos;
buffer.readBytes(nextBuffer);
buffer = nextBuffer;
}
public function unSubscribe():void{
if(curentCode != null && sessionid != null && curentCode != ""){
try{
socket.writeMultiByte("unsubscribe|"+sessionid+"|"+curentCode,"iso-8859-1");
socket.writeByte(0xff);
socket.flush();
}catch(e:flash.events.ErrorEvent){
Alert.show(this, Alert.IC_INFO, "Sorry..", e.text);
}
}
}
public function sendData(data:String):void{
busyIndicator = true;
unSubscribe();
socket.writeMultiByte(data,"iso-8859-1");
socket.writeByte(0xff);
socket.flush();
trace("sendData:"+data);
}
public function connect(useridx:String,passwordx:String) : void {
busyIndicator = true;
userid = useridx;
password = passwordx;
trace("userid:"+userid);
trace("password:"+password);
socket.connect(db.getItemAt(0).defauldIpAdress, db.getItemAt(0).defauldPort);
//threadedSocket();
}
]]>
</fx:Script>
<s:ViewNavigator label="Main" backgroundColor="0x000" id="mainview" width="100%" height="100%"
firstView="views.login" icon="#Embed('assets/home.png')"/>
<s:ViewNavigator label="Menu" backgroundColor="0x000" width="100%" height="100%" firstView="views.MenuView"
icon="#Embed('assets/menu.png')"/>
<s:ViewNavigator label="about" backgroundColor="0x000" width="100%" height="100%" firstView="views.aboutView"
icon="#Embed('assets/info.png')"/>
<fx:Declarations>
<!-- Place non-visual elements (e.g., services, value objects) here -->
<!--<mx:NumberFormatter
decimalSeparatorFrom="."
decimalSeparatorTo="."
precision="-1"
rounding="none|up|down|nearest"
thousandsSeparatorFrom=","
thousandsSeparatorTo=","
useNegativeSign="true|false"
useThousandsSeparator="true|false"/>-->
<mx:NumberFormatter id="fortmar1" precision="6"
rounding="none"
decimalSeparatorFrom="."
decimalSeparatorTo="."
thousandsSeparatorTo=","
thousandsSeparatorFrom=","
useThousandsSeparator="true"
useNegativeSign="true"
/>
</fx:Declarations>
</s:TabbedViewNavigatorApplication>
If you are stuck with an old version of the flash player, you need to search google for "Green Threads in AS3".
If you are using a newer version of the player, or Adobe AIR for desktop and devices, multithreading, via "actionscript workers", is available.