Adapting Bayesian logistic regression script to my data - logistic-regression

I'm looking to run a hierarchical logistic regression in a Bayesian framework, but am having trouble adapting codes for my data. I have the great book "Doing Bayesian Data Analysis", but I'm not sure how to modify the script the author provided (will paste below) to rerun the analysis on my thesis data. Specifically, I have the following questions:
How do I add more terms to this model? I had 5 predictors in my thesis, and this model only has 2
How do I make it hierarchical/include multiple steps or blocks?
How do I add interaction terms among my predictors?
I believe this script is set up for metric predictors (the book's example used height and weight data); If I am running a mixture of metric and nominal independent variables, how do I need to adapt it?
any help on any of these questions would be wonderful.
# Jags-Ydich-XmetMulti-Mlogistic.R
# Accompanies the book:
# Kruschke, J. K. (2015). Doing Bayesian Data Analysis, Second Edition:
# A Tutorial with R, JAGS, and Stan. Academic Press / Elsevier.
source("DBDA2E-utilities.R")
#===============================================================================
genMCMC = function( data , xName="x" , yName="y" ,
numSavedSteps=10000 , thinSteps=1 , saveName=NULL ,
runjagsMethod=runjagsMethodDefault ,
nChains=nChainsDefault ) {
require(runjags)
#-----------------------------------------------------------------------------
# THE DATA.
y = data[,yName]
x = as.matrix(data[,xName],ncol=length(xName))
# Do some checking that data make sense:
if ( any( !is.finite(y) ) ) { stop("All y values must be finite.") }
if ( any( !is.finite(x) ) ) { stop("All x values must be finite.") }
cat("\nCORRELATION MATRIX OF PREDICTORS:\n ")
show( round(cor(x),3) )
cat("\n")
flush.console()
# Specify the data in a list, for later shipment to JAGS:
dataList = list(
x = x ,
y = y ,
Nx = dim(x)[2] ,
Ntotal = dim(x)[1]
)
#-----------------------------------------------------------------------------
# THE MODEL.
modelString = "
# Standardize the data:
data {
for ( j in 1:Nx ) {
xm[j] <- mean(x[,j])
xsd[j] <- sd(x[,j])
for ( i in 1:Ntotal ) {
zx[i,j] <- ( x[i,j] - xm[j] ) / xsd[j]
}
}
}
# Specify the model for standardized data:
model {
for ( i in 1:Ntotal ) {
# In JAGS, ilogit is logistic:
y[i] ~ dbern( ilogit( zbeta0 + sum( zbeta[1:Nx] * zx[i,1:Nx] ) ) )
}
# Priors vague on standardized scale:
zbeta0 ~ dnorm( 0 , 1/2^2 )
for ( j in 1:Nx ) {
zbeta[j] ~ dnorm( 0 , 1/2^2 )
}
# Transform to original scale:
beta[1:Nx] <- zbeta[1:Nx] / xsd[1:Nx]
beta0 <- zbeta0 - sum( zbeta[1:Nx] * xm[1:Nx] / xsd[1:Nx] )
}
" # close quote for modelString
# Write out modelString to a text file
writeLines( modelString , con="TEMPmodel.txt" )
#-----------------------------------------------------------------------------
# INTIALIZE THE CHAINS.
# Let JAGS do it...
#-----------------------------------------------------------------------------
# RUN THE CHAINS
parameters = c( "beta0" , "beta" ,
"zbeta0" , "zbeta" )
adaptSteps = 500 # Number of steps to "tune" the samplers
burnInSteps = 1000
runJagsOut <- run.jags( method=runjagsMethod ,
model="TEMPmodel.txt" ,
monitor=parameters ,
data=dataList ,
#inits=initsList ,
n.chains=nChains ,
adapt=adaptSteps ,
burnin=burnInSteps ,
sample=ceiling(numSavedSteps/nChains) ,
thin=thinSteps ,
summarise=FALSE ,
plots=FALSE )
codaSamples = as.mcmc.list( runJagsOut )
# resulting codaSamples object has these indices:
# codaSamples[[ chainIdx ]][ stepIdx , paramIdx ]
if ( !is.null(saveName) ) {
save( codaSamples , file=paste(saveName,"Mcmc.Rdata",sep="") )
}
return( codaSamples )
} # end function
#===============================================================================
smryMCMC = function( codaSamples ,
saveName=NULL ) {
summaryInfo = NULL
mcmcMat = as.matrix(codaSamples)
paramName = colnames(mcmcMat)
for ( pName in paramName ) {
summaryInfo = rbind( summaryInfo , summarizePost( mcmcMat[,pName] ) )
}
rownames(summaryInfo) = paramName
if ( !is.null(saveName) ) {
write.csv( summaryInfo , file=paste(saveName,"SummaryInfo.csv",sep="") )
}
return( summaryInfo )
}
#===============================================================================
plotMCMC = function( codaSamples , data , xName="x" , yName="y" ,
showCurve=FALSE , pairsPlot=FALSE ,
saveName=NULL , saveType="jpg" ) {
# showCurve is TRUE or FALSE and indicates whether the posterior should
# be displayed as a histogram (by default) or by an approximate curve.
# pairsPlot is TRUE or FALSE and indicates whether scatterplots of pairs
# of parameters should be displayed.
#-----------------------------------------------------------------------------
y = data[,yName]
x = as.matrix(data[,xName])
mcmcMat = as.matrix(codaSamples,chains=TRUE)
chainLength = NROW( mcmcMat )
zbeta0 = mcmcMat[,"zbeta0"]
zbeta = mcmcMat[,grep("^zbeta$|^zbeta\\[",colnames(mcmcMat))]
if ( ncol(x)==1 ) { zbeta = matrix( zbeta , ncol=1 ) }
beta0 = mcmcMat[,"beta0"]
beta = mcmcMat[,grep("^beta$|^beta\\[",colnames(mcmcMat))]
if ( ncol(x)==1 ) { beta = matrix( beta , ncol=1 ) }
#-----------------------------------------------------------------------------
if ( pairsPlot ) {
# Plot the parameters pairwise, to see correlations:
openGraph()
nPtToPlot = 1000
plotIdx = floor(seq(1,chainLength,by=chainLength/nPtToPlot))
panel.cor = function(x, y, digits=2, prefix="", cex.cor, ...) {
usr = par("usr"); on.exit(par(usr))
par(usr = c(0, 1, 0, 1))
r = (cor(x, y))
txt = format(c(r, 0.123456789), digits=digits)[1]
txt = paste(prefix, txt, sep="")
if(missing(cex.cor)) cex.cor <- 0.8/strwidth(txt)
text(0.5, 0.5, txt, cex=1.5 ) # was cex=cex.cor*r
}
pairs( cbind( beta0 , beta )[plotIdx,] ,
labels=c( "beta[0]" ,
paste0("beta[",1:ncol(beta),"]\n",xName) ) ,
lower.panel=panel.cor , col="skyblue" )
if ( !is.null(saveName) ) {
saveGraph( file=paste(saveName,"PostPairs",sep=""), type=saveType)
}
}
#-----------------------------------------------------------------------------
# Data with posterior predictive:
# If only 1 predictor:
if ( ncol(x)==1 ) {
openGraph(width=7,height=6)
par( mar=c(3.5,3.5,2,1) , mgp=c(2.0,0.7,0) )
plot( x[,1] , y , xlab=xName[1] , ylab=yName ,
cex=2.0 , cex.lab=1.5 , col="black" , main="Data with Post. Pred." )
abline(h=0.5,lty="dotted")
cVec = floor(seq(1,chainLength,length=30))
xWid=max(x)-min(x)
xComb = seq(min(x)-0.1*xWid,max(x)+0.1*xWid,length=201)
for ( cIdx in cVec ) {
lines( xComb , 1/(1+exp(-(beta0[cIdx]+beta[cIdx,1]*xComb ))) , lwd=1.5 ,
col="skyblue" )
xInt = -beta0[cIdx]/beta[cIdx,1]
arrows( xInt,0.5, xInt,-0.04, length=0.1 , col="skyblue" , lty="dashed" )
}
if ( !is.null(saveName) ) {
saveGraph( file=paste(saveName,"DataThresh",sep=""), type=saveType)
}
}
# If only 2 predictors:
if ( ncol(x)==2 ) {
openGraph(width=7,height=7)
par( mar=c(3.5,3.5,2,1) , mgp=c(2.0,0.7,0) )
plot( x[,1] , x[,2] , pch=as.character(y) , xlab=xName[1] , ylab=xName[2] ,
col="black" , main="Data with Post. Pred.")
cVec = floor(seq(1,chainLength,length=30))
for ( cIdx in cVec ) {
abline( -beta0[cIdx]/beta[cIdx,2] , -beta[cIdx,1]/beta[cIdx,2] , col="skyblue" )
}
if ( !is.null(saveName) ) {
saveGraph( file=paste(saveName,"DataThresh",sep=""), type=saveType)
}
}
#-----------------------------------------------------------------------------
# Marginal histograms:
decideOpenGraph = function( panelCount , saveName , finished=FALSE ,
nRow=1 , nCol=3 ) {
# If finishing a set:
if ( finished==TRUE ) {
if ( !is.null(saveName) ) {
saveGraph( file=paste0(saveName,ceiling((panelCount-1)/(nRow*nCol))),
type=saveType)
}
panelCount = 1 # re-set panelCount
return(panelCount)
} else {
# If this is first panel of a graph:
if ( ( panelCount %% (nRow*nCol) ) == 1 ) {
# If previous graph was open, save previous one:
if ( panelCount>1 & !is.null(saveName) ) {
saveGraph( file=paste0(saveName,(panelCount%/%(nRow*nCol))),
type=saveType)
}
# Open new graph
openGraph(width=nCol*7.0/3,height=nRow*2.0)
layout( matrix( 1:(nRow*nCol) , nrow=nRow, byrow=TRUE ) )
par( mar=c(4,4,2.5,0.5) , mgp=c(2.5,0.7,0) )
}
# Increment and return panel count:
panelCount = panelCount+1
return(panelCount)
}
}
# Original scale:
panelCount = 1
panelCount = decideOpenGraph( panelCount , saveName=paste0(saveName,"PostMarg") )
histInfo = plotPost( beta0 , cex.lab = 1.75 , showCurve=showCurve ,
xlab=bquote(beta[0]) , main="Intercept" )
for ( bIdx in 1:ncol(beta) ) {
panelCount = decideOpenGraph( panelCount , saveName=paste0(saveName,"PostMarg") )
histInfo = plotPost( beta[,bIdx] , cex.lab = 1.75 , showCurve=showCurve ,
xlab=bquote(beta[.(bIdx)]) , main=xName[bIdx] )
}
panelCount = decideOpenGraph( panelCount , finished=TRUE , saveName=paste0(saveName,"PostMarg") )
# Standardized scale:
panelCount = 1
panelCount = decideOpenGraph( panelCount , saveName=paste0(saveName,"PostMargZ") )
histInfo = plotPost( zbeta0 , cex.lab = 1.75 , showCurve=showCurve ,
xlab=bquote(z*beta[0]) , main="Intercept" )
for ( bIdx in 1:ncol(beta) ) {
panelCount = decideOpenGraph( panelCount , saveName=paste0(saveName,"PostMargZ") )
histInfo = plotPost( zbeta[,bIdx] , cex.lab = 1.75 , showCurve=showCurve ,
xlab=bquote(z*beta[.(bIdx)]) , main=xName[bIdx] )
}
panelCount = decideOpenGraph( panelCount , finished=TRUE , saveName=paste0(saveName,"PostMargZ") )
#-----------------------------------------------------------------------------
}
#===============================================================================

Related

Getting Syntax error in this python code, how to eleminate?

////// section begins /* use this afl when buy is different from cover and sell is different from short / RequestTimedRefresh( 1, onlyvisible = False ) ; _SECTION_BEGIN( "Algoji.com intraday.afl" ); intra = ParamToggle( "Activate Intraday Mode", "NO|YES" ); per10 = Param( "Trade Entry From(HHMM)", 920, 900, 2300, 1 ); per11 = Param( "Trade Entry Upto(HHMM)", 1445, 900, 2300, 1 ); per12 = Param( "Trade Exit(HHMM)", 1515, 900, 2300, 100 ); pop= ParamToggle( "Percentage or Points", "Points|Percentage"); slp = Param( "StopLoss", 0, 0, 1000, 0.1 ); tsl= Param("Trail Stop", 0, 0, 1000, 0.1); tgtp = Param( "Target", 0, 0, 1000, 0.1 ); Col = ParamColor( "Color of Modified Signals", colorYellow ); delay= ParamToggle("Trade Intrabar?", "YES|Candle Completion"); dlong= ParamToggle("Disable Long?", "NO|YES"); dshort= ParamToggle("Disable Short?", "NO|YES"); if(dlong){Buy=Sell=0;} if(dshort){Short=Cover=0;} dd= DaysSince1900(); d=prof= 0; if(delay) {Buy=Ref(Buy,-1); Sell=Ref(Sell,-1); Short= Ref(Short,-1); Cover= Ref(Cover,-1);} qt= Param("Trade Quantity", 0, 0, 1000000) ; exposure= Param("Exposure", 0, 0, 1000000) ; if(exposure>0) qt= round(exposure/ValueWhen(Day()!=Ref(Day(),-1), C)); maxl= Param("Qty using SL (MaxLoss)",0,0,100000 ); if(maxl>0 AND !pop) qt= round(maxl/slp); if(maxl>0 AND pop) { basicprice= LastValue(ValueWhen(Day()!=Ref(Day(),-1), C)); sl= slpbasicprice/100; qt= round(maxl/sl); } intraex = intra AND (TimeNum() > per12 * 100); intraen = !intra OR ( TimeNum() <= per11 * 100 AND TimeNum() >= per10 * 100 ); Buy1 = Buy; Sell1 = Sell; Short1 = Short; Cover1 = Cover; Buy=Sell=Short=Cover=0; bflag = sflag = sp=bp = 0; slarr = tgtarr = qtarr= Null; for ( i = 10; i < BarCount; i++ ) { if ( ( Cover1[i] OR intraex[i]OR( H[i] > slarr[i-1] AND (sl>0 OR tsl>0) ) OR ( L[i] < tgtarr[i-1] AND tgt > 0 ) ) AND sflag ) { Cover[i] = 1; CoverPrice[i]= C[i]; sflag = 0; d= dd[i]; prof= sp-C[i]; } if ( ( Sell1[i] OR intraex[i] OR( L[i] < slarr[i-1] AND (sl>0 OR tsl>0) ) OR ( H[i] > tgtarr[i-1] AND tgt > 0 ) ) AND bflag ) { Sell[i] = 1; SellPrice[i]= C[i]; bflag = 0; d= dd[i]; prof= C[i]- bp; } if ( Buy1[i] AND intraen[i] AND bflag == 0 ) { Buy[i] = 1; bflag = 1; bp= C[i]; sl=slp; tgt= tgtp; if(pop) {sl= slpbp/100; tgt= tgtpbp/100;} if ( slp ) slarr[i] = bp-sl; if ( tgtp ) tgtarr[i] = bp+tgt; } if ( bflag AND Buy[i]==0 ) { slarr[i] = slarr[i-1]; tgtarr[i] = tgtarr[i-1]; if(tsl>0 AND pop) slarr[i] = Max(slarr[i-1], H[i](1-tsl/100)); if(tsl>0 AND !pop) slarr[i] = Max(slarr[i-1], H[i]-tsl); } if ( Short1[i] AND intraen[i] AND sflag == 0 ) { Short[i] = 1; sflag = 1; Sp= C[i]; sl= slp; tgt= tgtp; if(pop) {sl= slpSp/100; tgt= tgtpSp/100;} if ( slp ) slarr[i] = sp + sl; if ( tgtp ) tgtarr[i] = sp - tgt; } if ( sflag AND Short[i] == 0 ) { slarr[i] = slarr[i-1]; tgtarr[i] = tgtarr[i-1]; if(tsl>0 AND pop) slarr[i] = Min(slarr[i-1], L[i](1+tsl/100)); if(tsl>0 AND !pop) slarr[i] = Min(slarr[i-1], L[i]+tsl); } } Plot( slarr, "SL", Col, styleThick ); Plot( tgtarr, "TGT", Col, styleThick ); PlotShapes( IIf( Buy, shapeUpArrow, shapeNone ), Col, 0, H, Offset = 15 ); PlotShapes( IIf( Short, shapeDownArrow, shapeNone ), Col, 0, L, Offset = 15 ); PlotShapes( IIf( Cover, shapeStar, shapeNone ), Col, 0, H, Offset = -25 ); PlotShapes( IIf( Sell, shapeStar, shapeNone ), Col, 0, L, Offset = -25 ); sig = IIf( BarsSince( Buy ) < BarsSince( Short ), 1, 0 ); messageboard = ParamToggle( "Message Board", "Show|Hide", 1 ); if ( messageboard == 1 ) { GfxSelectFont( "Tahoma", 13, 100 ); GfxSetBkMode( 1 ); GfxSetTextColor( colorWhite ); GfxSelectSolidBrush( colorDarkTeal ); // this is the box background color pxHeight = Status( "pxchartheight" ) ; xx = Status( "pxchartwidth" ); Left = 1100; width = 310; x = 5; x2 = 310; y = pxHeight; GfxSelectPen( colorGreen, 1 ); // broader color GfxRoundRect( x, y - 160, x2, y , 7, 7 ) ; GfxTextOut( ""+WriteIf(intra, "Intraday Mode Activated", "Intraday Mode Not Activated" ), 13, y-160 ); GfxTextOut( ( "Current Qty "+qt ), 13, y-140 ); GfxTextOut( ( "Last" + " Signal came " + ( BarsSince( Buy OR Short ) ) * Interval() / 60 + " mins ago" ), 13, y - 120 ) ; // The text format location GfxTextOut( ( "" + WriteIf( sig == 1, "BUY # " + ValueWhen(Buy,C) , "SHORT # " + ValueWhen(Short,C) ) ), 13, y - 100 ); GfxTextOut( "Stop Loss : " + WriteIf(slp==0, "Not Activated", ""+slarr), 13, y - 80 ); GfxTextOut( "Target : " + WriteIf(tgtp==0, "Not Activated", ""+tgtarr), 13, y - 60 ); GfxTextOut( ( "Current P/L : " + WriteVal( IIf( sig == 1, (C-ValueWhen(Buy,C))*qt, (ValueWhen(Short,C)-C)*qt ), 2.2 ) ), 13, y-40 ); // GfxTextOut( ( "jhjh " ), 13, y-20 ); } //section begins for auto trade instr= ParamList("Instrument Name","EQ|FUTIDX|FUTSTK|OPTIDX|OPTSTK|FUTCOM"); stag= ParamStr("Strategy Tag", "STG1"); qty= NumToStr(qt[BarCount-1], 1.0, False) ; bp= sp= NumToStr(Close[BarCount-1],1.2, False); if(dlong){Buy=Sell=0;} if(dshort){Short=Cover=0;} if(delay) {Buy=Ref(Buy,-1); Sell=Ref(Sell,-1); Short= Ref(Short,-1); Cover= Ref(Cover,-1);} global algoji; algoji = Name() + NumToStr( Interval() / 60, 1.0, False ) ; procedure aStaticVarSet( SName, Svalue ) { global algoji; StaticVarSet( Sname + algoji, Svalue ); } function aStaticVarGet( SName ) { global algoji; Var = StaticVarGet( Sname + algoji ); if ( IsNull( Var = StaticVarGet( Sname + algoji ) ) ) Var = 0; return Var; } sym = Name(); //_TRACE("t"+t); Checkdt=Nz(aStaticVarGet("lastdt")); dt = LastValue( DateTime() ); Checkdtss=Nz(aStaticVarGet("lastdtss")); dtss = LastValue( DateTime() ); Checkdtc=Nz(aStaticVarGet("lastdtc")); dtc = LastValue( DateTime() ); Checkdts=Nz(aStaticVarGet("lastdts")); dts = LastValue( DateTime() ); RTBuy = LastValue( Buy) AND Checkdt != dt; RTShort = LastValue( Short) AND Checkdtss != dtss; RTCover = LastValue( Cover) AND Checkdtc != dtc; RTSell = LastValue( Sell) AND Checkdts != dts; if ( RTCover ) { aStaticVarSet("lastdtc",dtc ); StaticVarSet("counter", Nz(StaticVarGet("counter"))+1 ); _TRACE( "#"+Nz(StaticVarGet("counter"))+",SX,"+sym+",,," +bp +","+qty+","+instr+",,"); Algoji_Signal(NumToStr(Nz(StaticVarGet("counter")),0,False), "SX",sym,"M","",bp,qty,instr,stag); } if ( RTSell ) { aStaticVarSet("lastdts",dts ); StaticVarSet("counter", Nz(StaticVarGet("counter"))+1 ); _TRACE( "#"+Nz(StaticVarGet("counter"))+",LX,"+sym+",,," +sp +","+qty+",,,"); Algoji_Signal(NumToStr(Nz(StaticVarGet("counter")),0,False), "LX",sym,"M","",sp,qty,instr,stag); } if ( RTBuy ) { aStaticVarSet("lastdt",dt ); StaticVarSet("counter", Nz(StaticVarGet("counter"))+1 ); _TRACE( "#"+Nz(StaticVarGet("counter"))+",LE,"+sym+",,," +bp +","+qty+","+instr+",,"); Algoji_Signal(NumToStr(Nz(StaticVarGet("counter")),0,False), "LE",sym,"M","",bp,qty,instr,stag); } if ( RTShort ) { aStaticVarSet("lastdtss",dtss ); StaticVarSet("counter", Nz(StaticVarGet("counter"))+1 ); sp= NumToStr(Close[BarCount-1],1.2, False); _TRACE( "#"+Nz(StaticVarGet("counter"))+",SE,"+sym+",,," +sp +","+qty+","+instr+",,"); Algoji_Signal(NumToStr(Nz(StaticVarGet("counter")),0,False), "SE",sym,"M","",bp,qty,instr,stag); } Button = ParamToggle( "Enable Button Trading", "YES|NO" ); expiry= ParamStr("Expiry",""); strike= ParamStr("Strike",""); type= ParamStr("Option Type", ""); sym = Name()+ "|"+expiry+ "|" +strike+ "|" +type; function GetSecondNum() { Time = Now( 4 ); Seconds = int( Time % 100 ); Minutes = int( Time / 100 % 100 ); Hours = int( Time / 10000 % 100 ); SecondNum = int( Hours * 60 * 60 + Minutes * 60 + Seconds ); return SecondNum; } function PopupWindowEx( popupID, bodytext, captiontext, timeout, left, top ) { displayText = bodytext + captiontext; if ( ( StaticVarGetText( "prevPopup" + popupID ) != displayText) OR ( StaticVarGet( "prevPopupTime" + popupID ) < GetSecondNum() ) ) { StaticVarSetText( "prevPopup" + popupID, displayText); StaticVarSet( "prevPopupTime" + popupID, GetSecondNum() + timeout ); PopupWindow( bodytext, Captiontext + popupID, timeout, Left, top ); } } x1= Status( "pxchartleft" )+10; y1= Status( "pxcharttop" )+20; if ( Button == 0 ) { click = GetCursorMouseButtons() == 9; Px = GetCursorXPosition( 1 ); Py = GetCursorYPosition( 1 ); x2 = x1 + 60; y2 = y1 + 60; GfxSelectSolidBrush( ColorRGB( 0, 102, 0 ) ); //buy GfxSelectFont( "Tahoma", 13, 100 ); GfxSetBkMode( 1 ); GfxSetTextColor( colorWhite ); GfxRoundRect( x1, y1, x2, y2 , 7, 7 ) ; GfxTextOut( "LE", x1 + 20, y1 + 20 ); sx1 = x2; sy1 = y1; sx2 = sx1 + 60; sy2 = sy1 + 60; GfxSelectSolidBrush( ColorRGB( 255, 204, 204 ) );//sell GfxRoundRect( sx1, sy1, sx2, sy2 , 7, 7 ) ; GfxSetTextColor( ColorRGB( 153, 0, 0 ) ); GfxTextOut( "SE", sx1 + 20, sy1 + 20 ); ex1 = x1; ey1 = y1+60; ex2 = ex1 + 60; ey2 = ey1 + 60; GfxSelectSolidBrush( ColorRGB( 255, 204, 204 ) );//sell GfxRoundRect( ex1, ey1, ex2, ey2 , 7, 7 ) ; GfxSetTextColor( ColorRGB( 153, 0, 0 ) ); GfxTextOut( "LX", ex1 + 20, ey1 + 20 ); GfxSelectSolidBrush( ColorRGB( 0, 102, 0 ) );//sell GfxRoundRect( ex2, ey1, ex2+60, ey2 , 7, 7 ) ; GfxSetTextColor( colorWhite ); GfxTextOut( "SX", ex2 + 20, ey1 + 20 ); if ( px > x1 AND pxy1 AND py < y2 AND Click ) { _TRACE( "# ," + NumToStr(Nz(StaticVarGet("counter")),0,False) + ", BUY triggered from button, " ); AlertIf( 1, "SOUND C:\Windows\Media\tada.wav", "Audio alert", 1, 2, 1 ); StaticVarSet("counter", Nz(StaticVarGet("counter"))+1 ); PopupWindowEx( "ID:1", "BUY", "Buy Triggered from Button "+Name(), 1, -1, -1 ); AlgoJi_Signal(NumToStr(Nz(StaticVarGet("counter")),0,False), "LE",sym,"M","",sp,qty,instr,stag); } //https://algoji.com/ if ( px > sx1 AND pxsy1 AND py < sy2 AND Click ) { _TRACE( "# ," + NumToStr( DateTime(), formatDateTime ) + ", SHORT triggered from button, " ); AlertIf( 2, "SOUND C:\Windows\Media\tada.wav", "Audio alert", 2, 2, 1 ); StaticVarSet("counter", Nz(StaticVarGet("counter"))+1 ); PopupWindowEx( "ID:3", "SHORT", "Short Triggered from Button "+Name(), 1, -1, -1 ); AlgoJi_Signal(NumToStr(Nz(StaticVarGet("counter")),0,False), "SE",sym,"M","",sp,qty,instr,stag); } //https://algoji.com/ if ( px > ex1 AND pxey1 AND py<ey2 AND Click ) { _TRACE( "# ," + NumToStr( DateTime(), formatDateTime ) + ", SELL triggered from button, " ); AlertIf( 3, "SOUND C:\Windows\Media\tada.wav", "Audio alert", 2, 2, 1 ); StaticVarSet("counter", Nz(StaticVarGet("counter"))+1 ); PopupWindowEx( "ID:3", "SELL", "Sell Triggered from Button "+Name(), 1, -1, -1 ); AlgoJi_Signal(NumToStr(Nz(StaticVarGet("counter")),0,False), "LX",sym,"M","",sp,qty,instr,stag); } //https://algoji.com/ if ( px > ex2 AND px<(ex2+60) AND py>ey1 AND py < ey2 AND Click ) { _TRACE( "# ," + NumToStr( DateTime(), formatDateTime ) + ", Cover triggered from button, " ); AlertIf( 4, "SOUND C:\Windows\Media\tada.wav", "Audio alert", 2, 2, 1 ); StaticVarSet("counter", Nz(StaticVarGet("counter"))+1 ); PopupWindowEx( "ID:3", "Cover", "Cover Triggered from Button "+Name(), 1, -1, -1 ); AlgoJi_Signal(NumToStr(Nz(StaticVarGet("counter")),0,False), "SX",sym,"M","",sp,qty,instr,stag); } }
It is not a Python, it is AFL. It will be much easier if you post it as a code.
If you run it in AFL Formula Editor it will help you to debug it - simply click "Apply" and you will have all errors highlined.
I've found that you missed some "*" in your formula.

mediawiki query NOT IN syntax

I have a database query and I would like to add the condition:
$not_these_ids = array(22, 34, 55, 66)
'page_id' != $not_these_ids;
How do I write it in the mediawiki syntax?
`
$dbr = wfGetDB( DB_SLAVE ); ...
$conds = array( 'rev_id = page_latest',
'page_id' != $not_these_ids
); `
but it doesn't work.
You can just pass an array of strings, one for each conditions, to the third parameter of select().
Example from maintenance/Maintenance.php:
$dbw = wfGetDB( DB_MASTER );
$dbw->begin( __METHOD__ );
[...]
if ( count( $latestRevs ) > 0 ) {
$revConds[] = 'rev_id NOT IN (' . $dbw->makeList( $latestRevs ) . ')';
}
$res = $dbw->select( 'revision', 'rev_id', $revConds, __METHOD__ );
$oldRevs = array();
foreach ( $res as $row ) {
$oldRevs[] = $row->rev_id;
}
$this->output( "done.\n" );

Get the Count based on Conditions

I am using SQL Server 2008 R2. I have one table say BrokerTable
-----------------------------------
BrokerCode | Rank | BrokerId
-----------------------------------
1527339 | 1 | 3880
1527488 | 1 | 7550
1527366 | 1 | 3854
1527400 | 1 | 1519
1527358 | 1 | 3862
1527357 | 1 | 3863
Below is my part of query which calculate Business of Broker which are in above table. For example BrokerId 3880
SELECT CONVERT(DECIMAL(18, 2), SUM(T.Amount11))
FROM ( SELECT ISNULL(( CASE WHEN mb.PlanType = 'MULTIPLE'
THEN CASE WHEN mb.Mode = 'MLY' THEN ( ( ( SUM(SelfAmount) + SUM(UnitAmount) )
* ( SELECT bcm.PromoteeQuota FROM dbo.BusinessCalcMaster AS bcm
WHERE bcm.PlanType = mb.PlanType AND bcm.PlanName = mb.PlanName
AND bcm.Year = mb.Year AND mb.Mode = 'MLY'
AND bcm.MLY_From <= mb.InstallmentNo AND bcm.MLY_To >= mb.InstallmentNo
) ) / 100 ) WHEN mb.Mode = 'QLY' THEN ( ( ( SUM(SelfAmount)
+ SUM(UnitAmount) ) * ( SELECT bcm.PromoteeQuota FROM
dbo.BusinessCalcMaster AS bcm WHERE bcm.PlanType = mb.PlanType
AND bcm.PlanName = mb.PlanName AND bcm.Year = mb.Year
AND mb.Mode = 'QLY' AND bcm.MLY_From <= mb.InstallmentNo
AND bcm.MLY_To >= mb.InstallmentNo ) ) / 100 )
WHEN mb.Mode = 'HLY' THEN ( ( ( SUM(SelfAmount) + SUM(UnitAmount) )
* ( SELECT bcm.PromoteeQuota FROM dbo.BusinessCalcMaster AS bcm WHERE
bcm.PlanType = mb.PlanType AND bcm.PlanName = mb.PlanName
AND bcm.Year = mb.Year AND mb.Mode = 'HLY' AND bcm.MLY_From <= mb.InstallmentNo
AND bcm.MLY_To >= mb.InstallmentNo ) ) / 100 )
WHEN mb.Mode = 'YLY' THEN ( ( ( SUM(SelfAmount) + SUM(UnitAmount) )
* ( SELECT bcm.PromoteeQuota FROM dbo.BusinessCalcMaster AS bcm
WHERE bcm.PlanType = mb.PlanType AND bcm.PlanName = mb.PlanName
AND bcm.Year = mb.Year AND mb.Mode = 'YLY' AND bcm.MLY_From <= mb.InstallmentNo
AND bcm.MLY_To >= mb.InstallmentNo ) ) / 100 ) END
WHEN mb.PlanType = 'SINGLE' THEN ( ( SUM(SelfAmount) + SUM(UnitAmount)
* ( SELECT bcm.PromoteeQuota FROM dbo.BusinessCalcMaster
AS bcm WHERE bcm.PlanType = mb.PlanType
AND bcm.PlanName = mb.PlanName AND bcm.Year = mb.Year ) ) / 100 )
END ), 0) AS Amount11 , mb.InstallmentNo
FROM dbo.MemberBusiness AS mb WHERE mb.BrokerId = 3880
AND ( ( mb.PlanType = 'MULTIPLE' AND ( ( mb.Mode = 'HLY'
AND mb.InstallmentNo = 2 ) OR ( mb.Mode = 'QLY' AND mb.InstallmentNo >= 2
AND mb.InstallmentNo <= 4 ) OR ( mb.Mode = 'MLY' AND mb.InstallmentNo >= 2
AND mb.InstallmentNo <= 12 ) OR ( mb.InstallmentNo = 1 ) ))
OR ( mb.PlanType = 'SINGLE' ) )AND mb.Date >= '2013-02-01 00:00:00.000'
AND mb.Date <= '2013-02-28 00:00:00.000' GROUP BY mb.Mode , mb.Year ,
mb.PlanName , mb.PlanType , mb.InstallmentNo ) AS T
In BrokerTable there may be any number of Brokers. I want to calculate Business of each broker from BrokerTable and get number of Brokers whose Business is greater than 15000.
I can use a cursor but as I told there may be any number of Brokers in table, query takes more time to execute. How can I get result in less time or easiest way?. Thanks
Try:
SELECT B.BrokerId,
MAX(B.BrokerCode) BrokerCode,
CONVERT(DECIMAL(18, 2), SUM(T.Amount11)) BrokerAMount
FROM BrokerTable B
JOIN (SELECT CASE WHEN mb.PlanType = 'MULTIPLE' AND mb.Mode in ('MLY', 'QLY', 'HLY', 'YLY')
THEN ( SUM(SelfAmount) + SUM(UnitAmount) ) *
( SELECT bcm.PromoteeQuota
FROM dbo.BusinessCalcMaster AS bcm
WHERE bcm.PlanType = mb.PlanType AND bcm.PlanName = mb.PlanName AND bcm.Year = mb.Year
AND bcm.MLY_From <= mb.InstallmentNo AND bcm.MLY_To >= mb.InstallmentNo)
/ 100
WHEN mb.PlanType = 'SINGLE'
THEN ( SUM(SelfAmount) + SUM(UnitAmount) *
( SELECT bcm.PromoteeQuota
FROM dbo.BusinessCalcMaster AS bcm
WHERE bcm.PlanType = mb.PlanType AND bcm.PlanName = mb.PlanName AND bcm.Year = mb.Year )
) / 100
END AS Amount11,
mb.BrokerId,
mb.InstallmentNo
FROM dbo.MemberBusiness AS mb
WHERE ( ( mb.PlanType = 'MULTIPLE' AND
( ( mb.Mode = 'HLY' AND mb.InstallmentNo = 2 ) OR
( mb.Mode = 'QLY' AND mb.InstallmentNo >= 2 AND mb.InstallmentNo <= 4 ) OR
( mb.Mode = 'MLY' AND mb.InstallmentNo >= 2 AND mb.InstallmentNo <= 12 ) OR
mb.InstallmentNo = 1
)
) OR
mb.PlanType = 'SINGLE'
) AND
mb.Date >= '2013-02-01 00:00:00.000' AND mb.Date <= '2013-02-28 00:00:00.000'
GROUP BY mb.BrokerId , mb.Mode , mb.Year , mb.PlanName , mb.PlanType , mb.InstallmentNo
) AS T
ON B.BrokerId = T.BrokerId
GROUP BY B.BrokerId
HAVING SUM(T.Amount11) > 15000

DBI: How to find the right data-types for unknown data?

With of these two approaches would you prefer: trying to find the right data-types or simply using always varchar?
# ...
use HTML::TableExtract;
my $te = HTML::TableExtract->new( headers => [ 'some headers', 'one', 'two' ], keep_headers => 1 );
$te->parse( $html_string );
die $te->tables if $te->tables != 1;
( my $grid ) = $te->tables;
use DBI;
my $dbh = DBI->connect( ... ) or die $DBI::errstr;
my $table = 'my_test_table';
my #rows = $grid->rows;
my $header_row = shift #rows;
##### version 1 ####
use Data::Types qw(:all);
my #create_row;
for my $col ( 0 .. $#$header_row ) {
my ( $count, $int, $float ) = ( 0, 0, 0 );
my $longest = 0;
for my $row ( #rows ) {
$longest = length $row->[$col] if length $row->[$col] > $longest;
$int++ if is_int( $row->[$col] );
$float++ if is_float( $row->[$col] );
$count++;
}
if ( $int == $count ) {
$create_row[$col] = $dbh->quote( $header_row->[$col] ) . ' int';
}
elsif ( $float == $count ) {
$create_row[$col] = $dbh->quote( $header_row->[$col] ) . ' float';
}
else {
$create_row[$col] = $dbh->quote( $header_row->[$col] ) . " char($longest)";
}
}
$sql = sprintf "CREATE TABLE $table ( %s )",
join( ', ', #create_row );
$dbh->do( $sql );
$sql = sprintf "INSERT INTO $table ( %s ) VALUES( %s )",
join( ',', map { $dbh->quote( $_ ) } #$header_row ), join( ',', ('?') x #$header_row );
my $sth = $dbh->prepare( $sql );
#### version 2 ####
# always varchar
$sql = sprintf "CREATE TABLE $table ( %s )",
join( ', ', map { "'$_' varchar(60)" } #$header_row );
$dbh->do( $sql );
$sql = sprintf "INSERT INTO $table ( %s ) VALUES( %s )",
join( ',', map { $dbh->quote( $_ ) } #$header_row ), join( ',', ('?') x #$header_row );
my $sth = $dbh->prepare( $sql );
If the table you're processing will not change, and if the column will only be used for that single table's data, then it is safe to guess a data type that seems to fit (version 1).
However, if you plan to add any more data to that column then you'd need to keep everything as varchars in case there's some data of a different type in future (version 2).

How do i correct jqgrid footer information?

I am using jqgrid in one of my application.
Right now i am facing a strange problem and do not know how to rectify it?
Actually in one of the reports (having multiple link) jqgrid is showing wrong footer information that is its showing Page 0 of 0 even if there are records in the table.
This is the code which runs:
if( isset($this->params['named']['ajax']) && $this->params['named']['ajax'] == '1' )
{
$this->autoRender = false;
// get how many rows we want to have into the grid - rowNum parameter in the grid
$limit = $this->params['url']['rows'];
// get index row - i.e. user click to sort. At first time sortname parameter -
// after that the index from colModel
$sidx = $this->params['url']['sidx'];
// sorting order - at first time sortorder
$sord = $this->params['url']['sord'];
$page = $this->params['url']['page'];
// if we not pass at first time index use the first column for the index or what you want
if( !$sidx ) $sidx = 1;
// calculate the number of rows for the query. We need this for paging the result
$findconditions = array();
if(!empty($this->params['named']['batch']))
array_push(&$findconditions, array('Batch.id' => $this->params['named']['batch'] ));
$row = $this->Placement->find('count',array(
'link' => array(
'Student' => array(
'Batch'
)
),
'conditions'=> $findconditions
));
$count = $row;
// calculate the total pages for the query
if( $count > 0 )
{
$total_pages = ceil($count / $limit);
}
else
{
$total_pages = 0;
}
// if for some reasons the requested page is greater than the total
// set the requested page to total page
if( $page > $total_pages ) $page = $total_pages;
// calculate the starting position of the rows
$start = $limit * $page - $limit;
// if for some reasons start position is negative set it to 0
// typical case is that the user type 0 for the requested page
if( $start < 0 ) $start = 0;
// the actual query for the grid data
$limit_range = $start . "," . $limit;
$sort_range = $this->modelClass . '.' . $sidx . " " . $sord;
$this->Placement->recursive = -1;
$where='';
if( $this->params['url']['_search'] == 'true' )
{
//pr($this->params);
$searchconditions = array();
if( isset($this->params['named']['batch']) && !empty($this->params['named']['batch']) )
{
$where.= " Batch.id =".$this->params['named']['batch'];
}
if( isset($this->params['url']['isstillworking']) && !empty($this->params['url']['isstillworking']) )
{
$where.= " AND Placement.isstillworking ='".$this->params['url']['isstillworking']."'";
}
if( isset($this->params['url']['studentname']) && !empty($this->params['url']['studentname']) )
{
$where.=" AND Student.fullname LIKE '" .$this->params['url']['studentname'] . "%'";
}
if( isset($this->params['url']['companyname']) && !empty($this->params['url']['companyname']) )
{
$where.=" AND Company.name LIKE '" .$this->params['url']['companyname'] . "%'";
}
if( isset($this->params['url']['salary']) && !empty($this->params['url']['salary']) )
{
$where.= " AND Placement.salary =".$this->params['url']['salary'];
}
if( isset($this->params['url']['contactnumber1']) && !empty($this->params['url']['contactnumber1']) )
{
$where.= " AND Student.contactnumber1 =".$this->params['url']['contactnumber1'];
}
if( isset($this->params['url']['batchname']) && !empty($this->params['url']['batchname']) )
{
$where.=" AND Batch.name LIKE '" .$this->params['url']['batchname'] . "%'";
}
$sql="SELECT Student.fullname,
Placement.isstillworking,
Company.id,
Company.name,
Placement.id,
Placement.salary,
Placement.created,
Student.id,
Student.contactnumber1,
Batch.id,
Batch.name
FROM placements Placement
INNER JOIN (
SELECT student_id, isstillworking, max( created ) AS other_col
FROM placements
GROUP BY student_id
) AS b ON Placement.student_id = b.student_id
AND Placement.created = b.other_col
INNER JOIN students Student ON ( Student.id = Placement.student_id )
INNER JOIN batches Batch ON ( Student.batch_id = Batch.id )
INNER JOIN companies Company ON ( Company.id = Placement.company_id )
WHERE ".$where.
" AND Student.type='student'
AND Student.trainingcompleted=1
ORDER BY ".$sort_range."
LIMIT ".$limit_range
;
$result=$this->Placement->query($sql);
}
else
{
$sql="SELECT Student.fullname,
Placement.isstillworking,
Company.id,
Company.name,
Placement.id,
Placement.salary,
Placement.created,
Student.id,
Student.contactnumber1,
Batch.id,
Batch.name
FROM placements Placement
INNER JOIN (
SELECT student_id, isstillworking, max( created ) AS other_col
FROM placements
GROUP BY student_id
) AS b ON Placement.student_id = b.student_id
AND Placement.created = b.other_col
INNER JOIN students Student ON ( Student.id = Placement.student_id )
INNER JOIN batches Batch ON ( Student.batch_id = Batch.id )
INNER JOIN companies Company ON ( Company.id = Placement.company_id )
WHERE Batch.id =
".$this->params['named']['batch'].
" AND Student.type='student'
AND Student.trainingcompleted=1
ORDER BY ".$sort_range."
LIMIT ".$limit_range
;
$result=$this->Placement->query($sql);
}
$i = 0;
$response->page = $page;
$response->total = $total_pages;
$response->records = $count;
//pr($result);
foreach($result as $result)
{
$response->rows[$i]['id'] = $result['Placement']['id'];
$student = "<a href='" . APP_URL . "placements/report18/studentid:" . $result['Student']['id']."'>" . $result['Student']['fullname'] . "</a>";
$company = "<a href='" . APP_URL . "companies/view/" . $result['Company']['id'] . "'>" . $result['Company']['name'] . "</a>";
$batch = "<a href='" . APP_URL . "batches/view/" . $result['Batch']['id'] . "'>" . $result['Batch']['name'] . "</a>";
$contactnumber1 =$result['Student']['contactnumber1'];
$response->rows[$i]['cell'] = array($student, $result['Placement']['isstillworking'], $result['Company']['name'], $result['Placement']['salary'], $contactnumber1, $batch);
$i++;
}
echo json_encode($response);
}
I am also attaching the screen shot for reference.
Please help me on this.
Regards,
Pankaj
Why on earth would you not use Cake's ORM layer and Pagination class? If you use Model->query() you have to escape input yourself!

Resources