text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package JavaLineArray;
import ArmyC2.C2SD.Utilities.ErrorLogger;
import ArmyC2.C2SD.Utilities.RendererException;
import ArmyC2.C2SD.Utilities.RendererSettings;
import java.awt.geom.Rectangle2D;
/**
 * A class to calculate the number of pixels based points required for a line
 * @author Michael Deutch
 */
public final class countsupport
{
    private static final double maxLength = 100;	//max arrow size
    private static final double minLength = 2.5;		//min arrow size
    private static final String _className = "countsupport";

//    protected static void setMinLength(double mLength)
//    {
//        minLength=mLength;
//    }
    /**
     * The main function to return the number of points needed for a symbol
     * @param vbiDrawThis the line type
     * @param vblCounter the number of client points
     * @param pLinePoints the client point array
     * @return the number of points required to draw the symbol
     */
    protected static int GetCountersDouble(int vbiDrawThis,
                                int vblCounter,
                                POINT2[] pLinePoints,
                                Rectangle2D clipBounds,
                                int rev)
    {
        int count=0;
        try
        {
            //declaration section
            int j = 0;
            int vblSaveCounter = vblCounter;
            POINT2[] pSquarePoints = new POINT2[4];
            POINT2[] pUpperLinePoints = null,
                pLowerLinePoints = null;
            int[] segments = null;
            POINT2[] pNewLinePoints = null;
            double dRadius = 0;
            POINT2[] pointsCorner = new POINT2[2];
            //double saveMaxPixels = 2000;//CELineArrayGlobals.MaxPixels2;

            pUpperLinePoints=new POINT2[vblCounter];
            pLowerLinePoints=new POINT2[vblCounter];

            for(j=0;j<vblCounter;j++)
            {
                pUpperLinePoints[j]=new POINT2(pLinePoints[j]);
                pLowerLinePoints[j]=new POINT2(pLinePoints[j]);
            }
            lineutility.InitializePOINT2Array(pointsCorner);
            lineutility.InitializePOINT2Array(pSquarePoints);
            //end delcarations
            switch (vbiDrawThis)
            {
                case TacticalLines.BS_ELLIPSE:
                case TacticalLines.PBS_ELLIPSE:
                case TacticalLines.PBS_CIRCLE:
                    count=37;
                    break;
                case TacticalLines.BS_CROSS:
                    count=4;
                    break;
//                case TacticalLines.BS_RECTANGLE:
//                case TacticalLines.BBS_RECTANGLE:
//                    count=5;
//                    break;
                case TacticalLines.OVERHEAD_WIRE:
                    count=vblCounter*15;    //15 points per segment
                    break;
                case TacticalLines.OVERHEAD_WIRE_LS:
                    count=vblCounter*2;    //15 points per segment
                    break;
                case TacticalLines.ICE_DRIFT:
                    vblCounter += 3;	//3 extra points for the arrow
                    count=vblCounter;
                    break;
                case TacticalLines.REEF:
                    vblCounter = GetReefCount(pLinePoints, vblSaveCounter);
                    count=vblCounter;
                    break;
                case TacticalLines.RESTRICTED_AREA:
                    vblCounter = GetRestrictedAreaCount(pLinePoints, vblSaveCounter);
                    count=vblCounter;
                    break;
                case TacticalLines.TRAINING_AREA:
                    vblCounter += 30;
                    count=vblCounter;
                    break;
                case TacticalLines.PIPE:
                    count = GetPipeCount(pLinePoints, vblSaveCounter);
                    break;
                case TacticalLines.ANCHORAGE_AREA:
                case TacticalLines.ANCHORAGE_LINE:
                    //vblSaveCounter = vblCounter;
                    count = flot.GetAnchorageCountDouble(pLinePoints, vblCounter);
                    break;
                case TacticalLines.LRO:
                    int xCount=GetXPointsCount(vbiDrawThis, pLinePoints,vblCounter);
                    int lvoCount=GetLVOCount(vbiDrawThis, pLinePoints,vblCounter);
                    count=xCount+lvoCount;
                    break;
                case TacticalLines.LVO:
                    count=GetLVOCount(vbiDrawThis, pLinePoints,vblCounter);
                    break;
                case TacticalLines.ICING:
                    vblCounter = GetIcingCount(pLinePoints, vblCounter);
                    count=vblCounter;
                    break;
                case TacticalLines.FLOT:
                case TacticalLines.MVFR:
                case TacticalLines.UNDERCAST:
                    vblSaveCounter = vblCounter;
                    vblCounter = flot.GetFlotCountDouble(pLinePoints, vblCounter);
                    count=vblCounter;
                    break;
                case TacticalLines.ITD:
                    vblCounter = GetITDQty(pLinePoints, vblCounter) + vblCounter;
                    count=vblCounter;
                    break;
                case TacticalLines.CONVERGANCE:
                    vblCounter = GetConverganceQty(pLinePoints, vblCounter) + vblCounter;
                    count=vblCounter;
                    break;
                case TacticalLines.RIDGE:
                    vblCounter = GetFORTLCountDouble(pLinePoints, vbiDrawThis, vblSaveCounter);
                    count=vblCounter;
                    break;
                case TacticalLines.TROUGH:
                case TacticalLines.INSTABILITY:
                case TacticalLines.SHEAR:
                    //CELineArrayGlobals.MaxPixels2=saveMaxPixels+100;
                    vblCounter = GetSquallQty(pLinePoints, 6, 30, (int)vblSaveCounter);
                    count=vblCounter;
                    break;
                case TacticalLines.SQUALL:
                    vblCounter = GetSquallQty(pLinePoints, 5, 30, (int)vblSaveCounter)+ 2 * vblSaveCounter;
                    count=vblCounter;
                    break;
                case TacticalLines.USF:
                case TacticalLines.SFG:
                case TacticalLines.SFY:
                case TacticalLines.SF:
                    vblCounter = flot.GetSFCountDouble(pLinePoints, vblCounter);
                    count=vblCounter;
                    break;
                case TacticalLines.OFY:
                    vblSaveCounter = vblCounter;
                    vblCounter = flot.GetOFYCountDouble(pLinePoints, vblCounter, vbiDrawThis);
                    count=vblCounter;
                    break;
                case TacticalLines.UCF:
                case TacticalLines.CF:
                case TacticalLines.CFG:
                case TacticalLines.CFY:
                    count = GetFORTLCountDouble(pLinePoints, vbiDrawThis, vblSaveCounter);
                    count += vblSaveCounter;
                    break;
                case TacticalLines.FOLLA:
                case TacticalLines.FOLSP:
                    //count = vblCounter + 14;
                    count=16;
                    break;
                case TacticalLines.ROADBLK:
                case TacticalLines.FERRY:
                    //vblCounter = vblCounter + 6;
                    count=8;
                    break;
                case TacticalLines.NAVIGATION:
                case TacticalLines.IL:
                case TacticalLines.PLANNED:
                case TacticalLines.ESR1:
                case TacticalLines.ESR2:
                case TacticalLines.FORDSITE:
                case TacticalLines.FOXHOLE:
                case TacticalLines.DECEIVE:
                    count = 4;
                    break;
                //case TacticalLines.FLOT:
                //case TacticalLines.MVFR:
                //case TacticalLines.UNDERCAST:
                    //count = flot.GetFlotCountDouble(pLinePoints, vblCounter);
                    //break;
                case TacticalLines.TRIP:
                    count = 35;
                    break;
                case TacticalLines.AMBUSH:	//extra 3 for open arrow, extra 26 for the tail arc,
                    //and an extra 22 for the tail line segments
                    count = 53;//vblCounter+51;
                    break;
                case TacticalLines.CLUSTER:
                    count = 28;
                    break;
                case TacticalLines.DUMMY:
                    //count = 33; //was 58
                    count=vblCounter+3;   //commented 5-3-10
                    break;
                case TacticalLines.CONTAIN:
                    count = 40;
                    break;
                case TacticalLines.BYIMP:
                    count = 18;
                    break;
                case TacticalLines.SPTBYFIRE:
                    count = 16;
                    break;
                case TacticalLines.BLOCK:
                case TacticalLines.MNFLDBLK:
                    count = 4;
                    break;
                case TacticalLines.PAA_RECTANGULAR:
                    count = 5;
                    break;
                case TacticalLines.PENETRATE:
                    count = 7;
                    break;
                case TacticalLines.ASLTXING:	//double for the channel type plus 4 for the hash marks
                case TacticalLines.BRIDGE:
                case TacticalLines.GAP:
                case TacticalLines.BYPASS:
                case TacticalLines.EASY:
                case TacticalLines.BREACH:
                case TacticalLines.CANALIZE:
                    count = 12;
                    break;
                case TacticalLines.MNFLDDIS:
                    count = 22;
                    break;
                case TacticalLines.WITHDRAW:
                case TacticalLines.WDRAWUP:
                case TacticalLines.DELAY:		//extra four points for hash marks on last segment
                case TacticalLines.RETIRE:
                    count = 23;
                    break;
                case TacticalLines.SEIZE:
                case TacticalLines.SEIZE_REVC:
                    count = 37;
                    break;
                case TacticalLines.RIP:
                    count = 29;
                    break;
                case TacticalLines.DIRATKSPT:
                    count = vblCounter + 3;
                    break;
                case TacticalLines.ABATIS:
                    count = vblCounter + 3;
                    break;
                case TacticalLines.FPF:	//extra two points for blocks at each end
                case TacticalLines.LINTGT:	//extra two points for blocks at each end
                case TacticalLines.LINTGTS:
                    count = vblCounter + 4;
                    break;
                case TacticalLines.CHANNEL:
                case TacticalLines.CHANNEL_FLARED:
                case TacticalLines.CHANNEL_DASHED:
                    //pvblCounters[0]=2*lElements;
                    //pvblCounters[1]=lElements;
                    count=2*vblCounter;
                    break;
                case TacticalLines.SARA:
                    count = 16;	//same for DISM
                    break;
                case TacticalLines.COVER:		//vblSaveCounter = vblCounter;
                case TacticalLines.SCREEN:
                case TacticalLines.GUARD:
                case TacticalLines.COVER_REVC:		//vblSaveCounter = vblCounter;
                case TacticalLines.SCREEN_REVC:
                case TacticalLines.GUARD_REVC:
                case TacticalLines.PDF:
                case TacticalLines.ATKBYFIRE:
                    count = 14;	//same for DISM
                    break;
                case TacticalLines.RAFT:
                case TacticalLines.MFLANE:	//extra eight points for hash marks at either end
                    //count = vblCounter + 6;
                    count = 8;
                    break;
                case TacticalLines.DIRATKGND:
                    count = vblCounter + 10;
                    break;
                case TacticalLines.DIRATKAIR:
                    count = vblCounter + 9;
                    //count = vblCounter + 11;//12-17-10
                    break;
                case TacticalLines.DISRUPT:
                case TacticalLines.CLEAR:
                    count = 20;
                    break;
                case TacticalLines.UAV_USAS:
                case TacticalLines.MRR_USAS:
                    vblCounter = 6 * (vblSaveCounter - 1);	//6 per segment
                    count = vblCounter + 26 * vblSaveCounter*2;	//26 for each circle and potentially two circles at each endpoint
                    break;
                case TacticalLines.UAV:
                case TacticalLines.MRR:
                    //count = 6;
                    if(rev==RendererSettings.Symbology_2525C)
                    {
                        vblCounter = 6 * (vblSaveCounter - 1);	//6 per segment
                        count = vblCounter + 26 * vblSaveCounter*2;	//26 for each circle and potentially two circles at each endpoint
                    }
                    else
                        count=6;
                    break;
                case TacticalLines.DIRATKFNT:	//extra three for arrow plus extra three for the feint
                    count = vblCounter + 6;
                    break;
                case TacticalLines.MSDZ:
                    count = 300;
                    break;
                case TacticalLines.CONVOY:
                case TacticalLines.HCONVOY:
                    count = 10;
                    break;
                case TacticalLines.ISOLATE:
                case TacticalLines.CORDONKNOCK:
                case TacticalLines.CORDONSEARCH:
                    count = 50;
                    break;
                case TacticalLines.OCCUPY:
                    count = 32;
                    break;
                case TacticalLines.SECURE:
                    count = 29;
                    break;
                case TacticalLines.RETAIN:
                    count = 75;
                    break;
                case TacticalLines.TURN:
                    count = 29;
                    break;
                case TacticalLines.AIRFIELD:
                    count = vblCounter + 5;
                    break;
                case TacticalLines.DMA:
                    count=vblCounter + 4;
                    break;
                case TacticalLines.DMAF:
                    count=vblCounter + 3;
                    break;
                case TacticalLines.ALT:
                    count = vblCounter * 9;
                    break;
                case TacticalLines.TWOWAY:
                    count = vblCounter * 11;
                    break;
                case TacticalLines.ONEWAY:
                    count = vblCounter * 6;
                    break;
                case TacticalLines.WF:
                case TacticalLines.UWF:
                    vblCounter = flot.GetFlotCount2Double(pLinePoints, vblCounter, vbiDrawThis);
                    vblCounter += vblSaveCounter;
                    count=vblCounter;
                    break;
                case TacticalLines.WFG:
                case TacticalLines.WFY:
                    vblCounter = flot.GetFlotCount2Double(pLinePoints, vblCounter, vbiDrawThis);
                    count=vblCounter;
                    break;
                case TacticalLines.FORDIF:
                    dRadius = lineutility.CalcDistanceToLineDouble(pLinePoints[0], pLinePoints[1], pLinePoints[2]);
                    count=(int)( (dRadius/5)*3)+6;
                    if(clipBounds != null)
                    {
                        double width=clipBounds.getWidth();
                        double height=clipBounds.getHeight();
                        dRadius=Math.sqrt(width*width+height*height);
                        count = (int)(dRadius / 5) + 6;
                    }

                    break;
                case TacticalLines.ATDITCH:	//call function to determine the array size
                case TacticalLines.ATDITCHC:	//call function to determine the array size
                case TacticalLines.ATDITCHM:
                    count = GetDitchCountDouble(pLinePoints, vblSaveCounter, vbiDrawThis);
                    break;
                case TacticalLines.CATK:
                case TacticalLines.AXAD:
                case TacticalLines.MAIN:
                case TacticalLines.MAIN_STRAIGHT:
                case TacticalLines.AAFNT:
                case TacticalLines.AAFNT_STRAIGHT:
                case TacticalLines.AIRAOA:
                case TacticalLines.SPT:
                case TacticalLines.SPT_STRAIGHT:
                    //points for these need not be bounded
                    //they have an extra 8 points for the arrowhead
                    //pvblCounters[0]=2*lElements+8;
                    //pvblCounters[1]=lElements;
                    count=2*vblCounter+8;
                    break;
                case TacticalLines.CATKBYFIRE:
                    //pvblCounters[0] = 2 * lElements + 17;
                    //pvblCounters[1] = lElements;
                    count=2*vblCounter+17;
                    break;
                case TacticalLines.AAAAA:
                    //pvblCounters[0] = 2 * lElements + 19;
                    //pvblCounters[1] = lElements;
                    count=2*vblCounter+19;
                    break;
                case TacticalLines.FEBA:		//double for the shortened user line plus quadruple for
                    // X's, plus 26 times for the circles
                    count = 32 * vblCounter;
                    break;
                case TacticalLines.LLTR:  //added 5-4-07
                case TacticalLines.SAAFR:
                case TacticalLines.AC:
                    vblCounter = 6 * (vblSaveCounter - 1);	//6 per segment
                    count = vblCounter + 26 * vblSaveCounter*2;	//26 for each circle and potentially two circles at each endpoint
                    break;
                case TacticalLines.ATWALL:
                //case TacticalLines.ATWALL3D:
                case TacticalLines.LINE:
                case TacticalLines.OBSAREA:
                case TacticalLines.OBSFAREA:
                case TacticalLines.STRONG:
                case TacticalLines.ZONE:
                case TacticalLines.BELT:	//add per change 2
                case TacticalLines.ENCIRCLE:
                case TacticalLines.FORT:
                case TacticalLines.FORTL:
                    count = GetFORTLCountDouble(pLinePoints, vbiDrawThis, vblSaveCounter);
                    break;
                case TacticalLines.BELT1:
                    pUpperLinePoints = new POINT2[vblCounter];
                    pLowerLinePoints = new POINT2[vblCounter];
                    POINT2[]pUpperLowerLinePoints = new POINT2[2 * vblCounter];
                    for (j = 0; j < vblCounter; j++)
                        pLowerLinePoints[j] = pLinePoints[j];
                    for (j = 0; j < vblCounter; j++)
                        pUpperLinePoints[j] = pLinePoints[j];
                    pUpperLinePoints = Channels.CoordIL2Double(1, pUpperLinePoints, 1, vblCounter, vbiDrawThis,30);
                    pLowerLinePoints = Channels.CoordIL2Double(1, pLowerLinePoints, 0, vblCounter, vbiDrawThis,30);
                    for (j = 0; j < vblCounter; j++)
                        pUpperLowerLinePoints[j] = pUpperLinePoints[j];
                    for (j = 0; j < vblCounter; j++)
                        pUpperLowerLinePoints[j + vblCounter] = pLowerLinePoints[vblCounter - j - 1];
                    vblSaveCounter = 2 * vblCounter;
                    count = GetFORTLCountDouble(pUpperLowerLinePoints, vbiDrawThis, 2 * vblCounter);
                    break;
                case TacticalLines.TRIPLE:
                case TacticalLines.DOUBLEC:
                case TacticalLines.SINGLEC:
                case TacticalLines.HWFENCE:
                case TacticalLines.LWFENCE:
                case TacticalLines.UNSP:
                case TacticalLines.DOUBLEA:
                case TacticalLines.SFENCE:
                case TacticalLines.DFENCE:
                    count = Channels.GetTripleCountDouble(pLinePoints, vblCounter, vbiDrawThis);
                    break;
                case TacticalLines.BBS_LINE:
                    count=2*vblCounter;
                    break;
                case TacticalLines.LC:
                    pUpperLinePoints = Channels.GetChannelArray2Double(1,pUpperLinePoints,1,vblCounter,vbiDrawThis,20);
                    pLowerLinePoints = Channels.GetChannelArray2Double(1,pLowerLinePoints,0,vblCounter,vbiDrawThis,20);
                    int lUpperFlotCount= flot.GetFlotCountDouble(pUpperLinePoints,vblCounter);
                    int lLowerFlotCount= flot.GetFlotCountDouble(pLowerLinePoints,vblCounter);
                    count=lUpperFlotCount+lLowerFlotCount;
                    break;
                case TacticalLines.OCCLUDED:
                case TacticalLines.UOF:
                    vblSaveCounter = vblCounter;
                    vblCounter = flot.GetOccludedCountDouble(pLinePoints, vblCounter);
                    vblCounter += vblSaveCounter;
                    count=vblCounter;
                    break;
                case TacticalLines.FIX:
                case TacticalLines.MNFLDFIX:
                    if(pLinePoints.length>1)
                        count = GetDISMFixCountDouble(pLinePoints[0], pLinePoints[1],clipBounds);
                    else count=0;
                    break;
                case TacticalLines.BYDIF:
                    //commented section 10-27-10
//                    GetByDifSegment(pLinePoints, pointsCorner);
//                    vblCounter = lineutility.BoundPointsCount(pointsCorner, 2);
//                    segments = new int[vblCounter];
//                    pNewLinePoints = new POINT2[vblCounter];
//                    for (j = 0; j < 2; j++)
//                        pNewLinePoints[j] = new POINT2(pointsCorner[j]);
//
//                    vblCounter = lineutility.BoundPoints(pNewLinePoints, 2, segments);
//                    //there is only one possible viable segment since we bounded 2 points
//                    for (j = 0; j < vblCounter - 1; j++)
//                    {
//                        if (segments[j] != 0)
//                        {
//                            count = GetDISMFixCountDouble(pNewLinePoints[j], pNewLinePoints[j + 1]);
//                            break;
//                        }
//                    }
//                    count += 12;
                    //end section
                    if(clipBounds != null)
                    {
                        GetByDifSegment(pLinePoints, pointsCorner);
                        POINT2 ul=new POINT2(clipBounds.getMinX(),clipBounds.getMinY());    //-100,1000
                        POINT2 lr=new POINT2(clipBounds.getMaxX(),clipBounds.getMaxY());  //-100,1000
                        POINT2[] ptsCorner=lineutility.BoundOneSegment(pointsCorner[0],pointsCorner[1], ul, lr);

                        if(ptsCorner != null)
                            count = GetDISMFixCountDouble(ptsCorner[0], ptsCorner[1],clipBounds);
                        else
                            count=20;
                    }
                    else
                        count = GetDISMFixCountDouble(pLinePoints[0], pLinePoints[1],clipBounds);

                    break;
                default:
                    count=vblCounter;
                    break;
            }
        }
        catch(Exception exc)
        {
            ErrorLogger.LogException(_className ,"GetCountersDouble",
                    new RendererException("Failed inside GetCountersDouble " + Integer.toString(vbiDrawThis), exc));
        }
        return count;
    }
    //for DMAF, not currently used
//    protected static int GetXPointsCount(POINT2[] pLinePoints)
//    {
//        int total=0;
//        try
//        {
//            int j=0,iterations=0;
//            double dist=0;
//            for(j=0;j<pLinePoints.length-1;j++)
//            {
//                dist=lineutility.CalcDistanceDouble(pLinePoints[j],pLinePoints[j+1]);
//                iterations=(int)(dist-5)/10;
//                total += iterations *4;
//            }
//        }
//        catch(Exception e)
//        {
//            System.out.println(e.getMessage());
//        }
//        return total;
//    }

    private static int GetReefCount(POINT2[] pLinePoints,
            int vblCounter) {
        int count = 0;
        try {
            double d = 0;
            for (int j = 0; j < vblCounter - 1; j++) {
                d = lineutility.CalcDistanceDouble(pLinePoints[j], pLinePoints[j + 1]);
                count += 5 * (int) d / 40;
            }
            count += 2 * (int) vblCounter;
        } catch (Exception exc) {
            ErrorLogger.LogException(_className ,"GetReefCount",
                    new RendererException("Failed inside GetReefCount", exc));
        }
        return count;
    }
    private static int GetRestrictedAreaCount(POINT2[] pLinePoints,
            int vblCounter) {
        int count = 0;
        try {
            double d = 0;
            for (int j = 0; j < vblCounter - 1; j++) {
                d = lineutility.CalcDistanceDouble(pLinePoints[j], pLinePoints[j + 1]);
                count += 4 * (int) d / 15;
            }
            count += 2 * (int) vblCounter;
        } catch (Exception exc) {
            ErrorLogger.LogException(_className ,"GetRestrictedAreaCount",
                    new RendererException("Failed inside GetRestrictedAreaCount", exc));
        }
        return count;
    }

    private static int GetPipeCount(POINT2[] pLinePoints,
            int vblCounter) {
        int count = 0;
        try {
            double d = 0;
            for (int j = 0; j < vblCounter - 1; j++) {
                d = lineutility.CalcDistanceDouble(pLinePoints[j], pLinePoints[j + 1]);
                count += 3 * (int) d / 20;
            }
            count += 2 * (int) vblCounter;
        } catch (Exception exc) {
            ErrorLogger.LogException(_className ,"GetPipeCount",
                    new RendererException("Failed inside GetPipeCount", exc));
            }
        return count;
    }

    protected static int GetXPointsCount(int linetype, POINT2[] pOriginalLinePoints, int vblCounter)
    {
        int xCounter=0;
        try
        {
            int j=0;
            double d=0;
            //POINT2 pt0,pt1,pt2,pt3=new POINT2(),pt4=new POINT2(),pt5=new POINT2(),pt6=new POINT2();
            int numThisSegment=0;
            for(j=0;j<vblCounter-1;j++)
            {
                d=lineutility.CalcDistanceDouble(pOriginalLinePoints[j],pOriginalLinePoints[j+1]);
                numThisSegment=(int)((d-10)/20);
                if(linetype==TacticalLines.LRO)
                    numThisSegment=(int)((d-15)/30);
                xCounter += 4*numThisSegment;
            }
        }
        catch(Exception exc)
        {
            ErrorLogger.LogException(_className ,"GetXPointsCount",
                    new RendererException("Failed inside GetXPointsCount", exc));
        }
        return xCounter;
    }

    protected static int GetLVOCount(int linetype, POINT2[] pOriginalLinePoints, int vblCounter)
    {
        int lEllipseCounter = 0;
        try {
            double d = 0;
            int lHowManyThisSegment = 0, j = 0;
            //end declarations
            for (j = 0; j < vblCounter - 1; j++)
            {
                d = lineutility.CalcDistanceDouble(pOriginalLinePoints[j], pOriginalLinePoints[j + 1]);
                //lHowManyThisSegment = (int) ((d - 20) / 20);
                lHowManyThisSegment = (int) ((d - 20) / 20)+1;
                if(linetype==TacticalLines.LRO)
                    lHowManyThisSegment = (int) ((d - 30) / 30)+1;
                lEllipseCounter += lHowManyThisSegment*37;
            }
        } catch (Exception exc) {
            ErrorLogger.LogException(_className ,"GetLVOCount",
                    new RendererException("Failed inside GetLVOCount", exc));
        }
        return lEllipseCounter;
    }

    private static int GetIcingCount(POINT2[] points, int vblCounter) {
        int total = 2 * vblCounter;
        try {
            double length = 0;
            for (int j = 0; j < vblCounter - 1; j++) {
                length = lineutility.CalcDistanceDouble(points[j], points[j + 1]);
                length = (length / 15) * 4;
                total += length;
            }
        } catch (Exception exc) {
            ErrorLogger.LogException(_className ,"GetIcingCount",
                    new RendererException("Failed inside GetIcingCount", exc));
            }
        return total;
    }

    protected static int GetITDQty(POINT2[] pLinePoints, int vblCounter) {
        int total = 0;
        try {
            int j = 0;
            double d = 0;
            int n=0;
            for (j = 0; j < vblCounter - 1; j++) {
                d = lineutility.CalcDistanceDouble(pLinePoints[j], pLinePoints[j + 1]);
                n= 2 * (int) (d / 15);
                if(n<2)
                    n=2;
                //total += 2 * (int) (d / 15);
                total += n;
            }
        } catch (Exception exc) {
            ErrorLogger.LogException(_className ,"GetITDQty",
                    new RendererException("Failed inside GetITDQty", exc));
            }
        return total;
        }

    protected static int GetConverganceQty(POINT2[] pLinePoints, int vblCounter) {
        int total = vblCounter;
        try
        {
            int j = 0;
            double d = 0;
            for (j = 0; j < vblCounter - 1; j++)
            {
                d = lineutility.CalcDistanceDouble(pLinePoints[j], pLinePoints[j + 1]);
                total += 4 * (int) (d / 10);
            }
        } catch (Exception exc) {
            ErrorLogger.LogException(_className ,"GetConverganceQty",
                    new RendererException("Failed inside GetConverganceQty", exc));
        }
        return total;
    }

    /**
     * Calculates the points for ATDITCH, ATDITCHC, ATDITCHM
     * @param pLinePoints the client point array
     * @param vblCounter the number of client points
     * @param vbiDrawThis the line type
     * @return
     */
    private static int GetDitchCountDouble(POINT2[] pLinePoints,
            int vblCounter,
            int vbiDrawThis) {
        int vblXCounter = 0;
        try {
            //declarations
            int j = 0;
            int nHowManyThisSegment = 0;
            double dHowFar = 0;
                    //dPrinter = (double) nPrinter;

            vblXCounter = vblCounter;

            for (j = 0; j < vblCounter - 1; j++) {
                dHowFar = lineutility.CalcDistanceDouble(pLinePoints[j], pLinePoints[j + 1]);
                //nHowManyThisSegment = (int) ((dHowFar - 3) / 12);
                nHowManyThisSegment = (int) ( (dHowFar-1) / 12);
                if (dHowFar > 24) {
                    switch (vbiDrawThis) {
                        //case TacticalLines.FORT:
                        //    break;
                        case TacticalLines.ATDITCHM:
                            vblXCounter += 5 * nHowManyThisSegment+1;//was 4 * nHowManyThisSegment
                            break;
                        default:
                            vblXCounter += 4 * nHowManyThisSegment;//was 3 * nHowManyThisSegment
                            break;
                    }	//end switch
                    } //end if
                else {
                    vblXCounter += 2;
                }
            }	//end for
            } catch (Exception exc) {
            ErrorLogger.LogException(_className ,"GetDitchcountDouble",
                    new RendererException("Failed inside GetDitchCountDouble " + Integer.toString(vbiDrawThis), exc));
        }
        return vblXCounter;
    }
    protected static int GetSquallQty(POINT2[] pLinePoints,
            int quantity,
            int length,
            int numPoints) {
        int counter = 0;
        try {
            int j = 0;
            double dist = 0;
            int numCurves = 0;
            //end declarations

            for (j = 0; j < numPoints-1; j++) {
                dist = lineutility.CalcDistanceDouble(pLinePoints[j], pLinePoints[j + 1]);
                numCurves = (int) (dist / (double) length);
                counter += numCurves * quantity;
                if (numCurves == 0) {
                    counter += 2;
                }
            }

            if (counter < numPoints) {
                counter = numPoints;
            }

            //clean up
            } catch (Exception exc) {
            ErrorLogger.LogException(_className ,"GetSquallQty",
                    new RendererException("Failed inside GetSquallQty", exc));
        }
        return counter;
    }

    protected static int GetSquallSegQty(POINT2 StartPt,
            POINT2 EndPt,
            int quantity,
            int length) {
        int qty = 0;
        try {
            double dist = lineutility.CalcDistanceDouble(StartPt, EndPt);
            int numCurves = (int) (dist / (double) length);
            qty = numCurves * quantity;
        } catch (Exception exc) {
            ErrorLogger.LogException(_className ,"GetSquallSegQty",
                    new RendererException("Failed inside GetSquallSegQty", exc));
        }
        return qty;
    }

    /**
     * returns number of points required for ATWALL, FORT and other symbols
     * @param pLinePoints the client points
     * @param linetype the line type
     * @param vblCounter the number of client points
     * @return
     */
    protected static int GetFORTLCountDouble(POINT2[] pLinePoints,
            int linetype,
            int vblCounter) {
        int lCounter = 0;
        try {
            //declarations
            int j = 0;
            double dCounter = 0, dIncrement = 0;
            //end declarations

            switch (linetype) {
                    case TacticalLines.UCF:
                    case TacticalLines.CF:
                    case TacticalLines.CFG:
                    case TacticalLines.CFY:
                        dIncrement = 60;
                        break;
                    case TacticalLines.RIDGE:
                        dIncrement = 20;
                        break;
                default:
                    dIncrement = 20;
                    break;
            }

            for (j = 0; j < vblCounter - 1; j++) {
                dCounter = lineutility.CalcDistanceDouble(pLinePoints[j], pLinePoints[j + 1]);

                switch (linetype) {
                        case TacticalLines.CFG:
                            dCounter = (dCounter / dIncrement) * 13;
                            break;
                        case TacticalLines.CFY:
                            dCounter = (dCounter / dIncrement) * 17;
                            break;
                    default:
                        dCounter = (dCounter / dIncrement) * 10;
                        break;
                }

                if (dCounter < 4) {
                    dCounter = 4;
                }
                lCounter += (long) dCounter;
            }
            lCounter += 10 + vblCounter;

        } catch (Exception exc) {
            ErrorLogger.LogException(_className ,"GetFORTLCountDouble",
                    new RendererException("Failed inside GetFORTLCountDouble", exc));
            }
        return lCounter;
    }

    private static void GetByDifSegment(POINT2[] points, POINT2[] pointsCorner) {
        try {
            // draw open-ended rectangle
            POINT2 point_mid = new POINT2();
            //int j=0;
            //	POINT1 pts[4];
            if (pointsCorner == null) {
                pointsCorner = new POINT2[2];
                lineutility.InitializePOINT2Array(pointsCorner);
            }
            point_mid.x = (points[0].x + points[1].x) / 2;
            point_mid.y = (points[0].y + points[1].y) / 2;
            pointsCorner[0].x = points[0].x - point_mid.x + points[2].x;
            pointsCorner[0].y = points[0].y - point_mid.y + points[2].y;
            pointsCorner[1].x = points[1].x - point_mid.x + points[2].x;
            pointsCorner[1].y = points[1].y - point_mid.y + points[2].y;
            return;
        } catch (Exception exc) {
            ErrorLogger.LogException(_className ,"GetByDifSegment",
                    new RendererException("Failed inside GetByDifSegment", exc));
        }
    }
    /**
     * clipBounds is used because of the glyphs on one segment
     * @param FirstLinePoint
     * @param LastLinePoint
     * @param clipBounds
     * @return
     */
    protected static int GetDISMFixCountDouble(POINT2 FirstLinePoint,
            POINT2 LastLinePoint,
            Rectangle2D clipBounds) {
        int counter = 0;
        try {
            POINT2[] savepoints = new POINT2[2];
            //double dAngle1 = 0;
            double dLength = 0;
            double dJaggyHalfAmp = 0;
            double dJaggyHalfPeriod = 0;
            int iNumJaggies = 0;

            savepoints[0] = new POINT2(FirstLinePoint);
            savepoints[1] = new POINT2(LastLinePoint);

            //Boolean drawJaggies=true;
            if(clipBounds != null)
            {
                POINT2 ul=new POINT2(clipBounds.getMinX(),clipBounds.getMinY());
                POINT2 lr=new POINT2(clipBounds.getMaxX(),clipBounds.getMaxY());
                savepoints=lineutility.BoundOneSegment(FirstLinePoint, LastLinePoint, ul, lr);
            }

//            if(savepoints==null)
//            {
//                //savepoints[0] = new POINT2(FirstLinePoint);
//                //savepoints[1] = new POINT2(LastLinePoint);
//                //drawJaggies=false;
//                return 20;
//            }
            if(savepoints==null)
                return 0;

            dLength = Math.sqrt((savepoints[1].x - savepoints[0].x) * (savepoints[1].x - savepoints[0].x) +
                    (savepoints[1].y - savepoints[0].y) * (savepoints[1].y - savepoints[0].y));
            dJaggyHalfAmp = dLength / 15; // half the amplitude of the "jaggy function"

            if (dJaggyHalfAmp > maxLength) {
                dJaggyHalfAmp = maxLength;
            }
            if (dJaggyHalfAmp < minLength) {
                dJaggyHalfAmp = minLength;
            }

            dJaggyHalfPeriod = dJaggyHalfAmp / 1.5; // half the period of the "jaggy function"
            iNumJaggies = (int) (dLength / dJaggyHalfPeriod) - 3;
            if (iNumJaggies < 0) {
                iNumJaggies = 0;
            }

            savepoints = null;
            counter = 20 + iNumJaggies * 3;
        } catch (Exception exc) {
            ErrorLogger.LogException(_className ,"GetDISMFixCount",
                    new RendererException("Failed inside GetDISMFixCount", exc));
        }
        return counter;
    }

}


text:
module ZooniverseData
  module Projects
    require 'zooniverse_data/projects/default'
    require 'zooniverse_data/projects/asteroid'
    require 'zooniverse_data/projects/condor'
    require 'zooniverse_data/projects/higgs_hunter'
    require 'zooniverse_data/projects/illustratedlife'
    require 'zooniverse_data/projects/milky_way'
    require 'zooniverse_data/projects/orchid'
    require 'zooniverse_data/projects/penguin'
    require 'zooniverse_data/projects/serengeti'
    require 'zooniverse_data/projects/sunspot'
  end
end

redpajama_set_name: RedPajamaGithub


text:
import argparse
import itertools
import sys

def main():

	args = setArgs()

	sc = args.shellcode.split(',')
	enc = encrypt(sc, args.key)

	print("\nHex Shellcode")
	dumpHexCode(enc)
	print("\nC Style Array")
	dumpCodeArray(enc)

def encrypt(clear, keystr):
	key = itertools.cycle(keystr)
	cipher = bytearray()
	for b in clear:
		offset = ord(next(key))
		cipher.append((int(b, 16)+offset)%256)

	return cipher

def dumpHexCode(code):
	nChars = 0
	for c in code:
		sys.stdout.write("0x{0:02x},".format(c))
		nChars+=1
		if nChars == 10:
			sys.stdout.write("\n")
			nChars = 0

def dumpCodeArray(code):
	nChars = 0
	sys.stdout.write("\"")
	for c in code:
		sys.stdout.write("\\x{0:02x}".format(c))
		nChars+=1
		if nChars == 10:
			sys.stdout.write("\"\n\"")
			nChars = 0
	sys.stdout.write("\";\n")

def setArgs():
	parser = argparse.ArgumentParser(description='Vigenere encrypt shellcode')
	parser.add_argument('shellcode', help='A shellcode string in 0xXX,0xXX,0xXX format.')
	parser.add_argument('key', help='The encryption key string')

	return parser.parse_args()

if __name__ == '__main__':
	main()


text:
package com.planet_ink.coffee_mud.Abilities.Properties;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.DatabaseEngine.PlayerData;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;

import java.util.*;

@SuppressWarnings({"unchecked","rawtypes"})
public class Prop_RoomForSale extends Property implements LandTitle
{
	@Override public String ID() { return "Prop_RoomForSale"; }
	@Override public String name(){ return "Putting a room up for sale";}
	@Override protected int canAffectCode(){return Ability.CAN_ROOMS;}

	public final static String SALESTR=" This lot is for sale (look id).";
	public final static String RENTSTR=" This lot (look id) is for rent on a monthly basis.";
	public final static String INDOORSTR=" An empty room";
	public final static String OUTDOORSTR=" An empty plot";
	protected int lastItemNums=-1;
	protected int lastDayDone=-1;
	protected boolean scheduleReset=false;

	@Override
	public String accountForYourself()
	{ return "For Sale";	}

	@Override public boolean allowsExpansionConstruction(){ return false;}

	@Override
	public void setMiscText(String newMiscText)
	{
		super.setMiscText(newMiscText);
	}

	@Override
	public int getPrice()
	{
		if(text().length()==0)
			return 100000;
		final String s=text();
		int index=s.length();
		while((--index)>=0)
		{
			if((!Character.isDigit(s.charAt(index)))
			&&(!Character.isWhitespace(s.charAt(index))))
				break;
		}
		int price=CMath.s_int(s.substring(index+1).trim());

		if(price<=0) price=100000;
		return price;
	}

	@Override public List<Room> getConnectedPropertyRooms() { return getAllTitledRooms();}

	@Override
	public void setPrice(int price)
	{
		setMiscText(getOwnerName()+"/"
			+(rentalProperty()?"RENTAL ":"")
			+((backTaxes()!=0)?"TAX"+backTaxes()+"X ":"")
			+price);
	}

	@Override
	public String getOwnerName()
	{
		final int dex=text().indexOf('/');
		if(dex<0) return "";
		return text().substring(0,dex);
	}

	@Override
	public CMObject getOwnerObject()
	{
		final String owner=getOwnerName();
		if(owner.length()==0) return null;
		final Clan C=CMLib.clans().getClan(owner);
		if(C!=null) return C;
		return CMLib.players().getLoadPlayer(owner);
	}

	@Override
	public void setOwnerName(String owner)
	{
		if((owner.length()==0)&&(getOwnerName().length()>0))
			scheduleReset=true;
		setMiscText(owner+"/"
				+(rentalProperty()?"RENTAL ":"")
				+((backTaxes()!=0)?"TAX"+backTaxes()+"X ":"")
				+getPrice());
	}

	@Override
	public int backTaxes()
	{
		final int dex=text().indexOf('/');
		if(dex<0) return 0;
		final int x=text().indexOf("TAX",dex);
		if(x<0) return 0;
		final String s=CMParms.parse(text().substring(x+3)).firstElement();
		return CMath.s_int(s.substring(0,s.length()-1));
	}
	@Override
	public void setBackTaxes(int tax)
	{
		setMiscText(getOwnerName()+"/"
				+(rentalProperty()?"RENTAL ":"")
				+((tax!=0)?"TAX"+tax+"X ":"")
				+getPrice());
	}

	@Override
	public boolean rentalProperty()
	{
		final String upperText=text().toUpperCase();
		final int dex=upperText.indexOf('/');
		if(dex<0) return upperText.indexOf("RENTAL")>=0;
		return upperText.indexOf("RENTAL",dex)>0;
	}

	@Override
	public void setRentalProperty(boolean truefalse)
	{
		setMiscText(getOwnerName()+"/"
				+(truefalse?"RENTAL ":"")
				+((backTaxes()!=0)?"TAX"+backTaxes()+"X ":"")
				+getPrice());
	}

	// update title, since it may affect clusters, worries about ALL involved
	@Override
	public void updateTitle()
	{
		if(affected instanceof Room)
			CMLib.database().DBUpdateRoom((Room)affected);
		else
		{
			final Room R=CMLib.map().getRoom(landPropertyID());
			if(R!=null) CMLib.database().DBUpdateRoom(R);
		}
	}

	@Override
	public String getTitleID()
	{
		if(affected instanceof Room)
			return "LAND_TITLE_FOR#"+CMLib.map().getExtendedRoomID((Room)affected);
		else
		{
			final Room R=CMLib.map().getRoom(landPropertyID());
			if(R!=null)
				return "LAND_TITLE_FOR#"+CMLib.map().getExtendedRoomID(R);
		}
		return "";
	}

	@Override public String getUniqueLotID(){ return "ROOM_PROPERTY_"+landPropertyID();}

	@Override
	public String landPropertyID()
	{
		if((affected!=null)&&(affected instanceof Room))
			return CMLib.map().getExtendedRoomID(((Room)affected));
		return "";
	}

	@Override public void setLandPropertyID(String landID){}

	public static boolean shopkeeperMobPresent(Room R)
	{
		if(R==null) return false;
		MOB M=null;
		for(int i=0;i<R.numInhabitants();i++)
		{
			M=R.fetchInhabitant(i);
			if((M.getStartRoom()==R)
			&&(M.isMonster())
			&&(CMLib.coffeeShops().getShopKeeper(M)!=null))
				return true;
		}
		return false;
	}

	public static boolean robberyCheck(LandTitle A, CMMsg msg)
	{
		if((msg.targetMinor()==CMMsg.TYP_GET)||(msg.targetMinor()==CMMsg.TYP_PUSH)||(msg.targetMinor()==CMMsg.TYP_PULL))
		{
			if((msg.target() instanceof Item)
			&&(((Item)msg.target()).owner() ==msg.source().location())
			&&((!(msg.tool() instanceof Item))||(msg.source().isMine(msg.tool())))
			&&(!msg.sourceMajor(CMMsg.MASK_ALWAYS))
			&&(A.getOwnerName().length()>0)
			&&(msg.source().location()!=null)
			&&(msg.othersMessage()!=null)
			&&(msg.othersMessage().length()>0)
			&&(!shopkeeperMobPresent(msg.source().location()))
			&&(!CMLib.law().doesHavePriviledgesHere(msg.source(),msg.source().location())))
			{
				final Room R=msg.source().location();
				final LegalBehavior B=CMLib.law().getLegalBehavior(R);
				if(B!=null)
				{
					for(int m=0;m<R.numInhabitants();m++)
					{
						final MOB M=R.fetchInhabitant(m);
						if(CMLib.law().doesHavePriviledgesHere(M,R))
							return true;
					}
					MOB D=null;
					final Clan C=CMLib.clans().getClan(A.getOwnerName());
					if(C!=null)
						D=C.getResponsibleMember();
					else
						D=CMLib.players().getLoadPlayer(A.getOwnerName());
					if(D==null) return true;
					B.accuse(CMLib.law().getLegalObject(R),msg.source(),D,new String[]{"PROPERTYROB","THIEF_ROBBERY"});
				}
			}
			return true;
		}
		return false;
	}

	@Override
	public void executeMsg(final Environmental myHost, final CMMsg msg)
	{
		super.executeMsg(myHost,msg);
		if(((msg.sourceMinor()==CMMsg.TYP_SHUTDOWN)
				||((msg.targetMinor()==CMMsg.TYP_EXPIRE)&&(msg.target()==affected))
				||(msg.sourceMinor()==CMMsg.TYP_ROOMRESET))
		&&(affected instanceof Room))
		{
			updateLot(null);
			final Vector mobs=new Vector();
			Room R=(Room)affected;
			if(R!=null)
			{
				synchronized(("SYNC"+R.roomID()).intern())
				{
					R=CMLib.map().getRoom(R);
					for(int m=0;m<R.numInhabitants();m++)
					{
						final MOB M=R.fetchInhabitant(m);
						if((M!=null)
						&&(M.isSavable())
						&&(M.getStartRoom()==R)
						&&((M.basePhyStats().rejuv()==0)||(M.basePhyStats().rejuv()==PhyStats.NO_REJUV)))
						{
							CMLib.catalog().updateCatalogIntegrity(M);
							mobs.addElement(M);
						}
					}
					if(!CMSecurity.isSaveFlag("NOPROPERTYMOBS"))
						CMLib.database().DBUpdateTheseMOBs(R,mobs);
				}
			}
		}
	}

	@Override
	public boolean okMessage(final Environmental myHost, final CMMsg msg)
	{
		if(!super.okMessage(myHost,msg)) return false;
		Prop_RoomForSale.robberyCheck(this,msg);
		return true;
	}

	public static void colorForSale(Room R, boolean rental, boolean reset)
	{
		synchronized(("SYNC"+R.roomID()).intern())
		{
			R=CMLib.map().getRoom(R);
			final String theStr=rental?RENTSTR:SALESTR;
			final String otherStr=rental?SALESTR:RENTSTR;
			int x=R.description().indexOf(otherStr);
			while(x>=0)
			{
				R.setDescription(R.description().substring(0,x));
				CMLib.database().DBUpdateRoom(R);
				x=R.description().indexOf(otherStr);
			}
			final String oldDescription=R.description();
			x=R.description().indexOf(theStr.trim());
			if((x<0)||(reset&&(!R.displayText().equals(CMath.bset(R.domainType(), Room.INDOORS)?INDOORSTR:OUTDOORSTR))))
			{
				if(reset)
				{
					R.setDescription("");
					R.setDisplayText(CMath.bset(R.domainType(), Room.INDOORS)?INDOORSTR:OUTDOORSTR);
					x=-1;
				}
				if(x<0)
					R.setDescription(R.description()+theStr);
				else
				if(!reset)
					R.setDescription(R.description().substring(0,x+theStr.trim().length()));
				if(!R.description().equals(oldDescription))
					CMLib.database().DBUpdateRoom(R);
			}
			else
			{
				R.setDescription(R.description().substring(0,x+theStr.trim().length()));
				if(!R.description().equals(oldDescription))
					CMLib.database().DBUpdateRoom(R);
			}
			Item I=R.findItem(null,"$id$");
			if((I==null)||(!I.ID().equals("GenWallpaper")))
			{
				I=CMClass.getItem("GenWallpaper");
				CMLib.flags().setReadable(I,true);
				I.setName(("id"));
				I.setReadableText(CMLib.lang()._("This room is "+CMLib.map().getExtendedRoomID(R)));
				I.setDescription(CMLib.lang()._("This room is @x1",CMLib.map().getExtendedRoomID(R)));
				R.addItem(I);
				CMLib.database().DBUpdateItems(R);
			}
		}
	}

	@Override
	public List<Room> getAllTitledRooms()
	{
		final List<Room> V=new Vector();
		if(affected instanceof Room)
			V.add((Room)affected);
		else
		{
			final Room R=CMLib.map().getRoom(landPropertyID());
			if(R!=null) V.add(R);
		}
		return V;
	}

	public static int updateLotWithThisData(Room R,
											LandTitle T,
											boolean resetRoomName,
											boolean clearAllItems,
											List optPlayerList,
											int lastNumItems)
	{
		boolean updateItems=false;
		boolean updateExits=false;
		boolean updateRoom=false;
		synchronized(("SYNC"+R.roomID()).intern())
		{
			R=CMLib.map().getRoom(R);
			if(T.getOwnerName().length()==0)
			{
				Item I=null;
				for(int i=R.numItems()-1;i>=0;i--)
				{
					I=R.getItem(i);
					if((I==null)||(I.Name().equalsIgnoreCase("id"))) continue;
					CMLib.catalog().updateCatalogIntegrity(I);
					if(clearAllItems)
					{
						I.destroy();
						updateItems=true;
					}
					else
					{
						if(I.expirationDate()==0)
						{
							long now=System.currentTimeMillis();
							now+=(TimeManager.MILI_MINUTE*CMProps.getIntVar(CMProps.Int.EXPIRE_PLAYER_DROP));
							I.setExpirationDate(now);
						}
						if((I.phyStats().rejuv()!=PhyStats.NO_REJUV)
						&&(I.phyStats().rejuv()!=0))
						{
							I.basePhyStats().setRejuv(PhyStats.NO_REJUV);
							I.recoverPhyStats();
						}
					}
				}
				Ability A=null;
				if(clearAllItems)
					for(final Enumeration<Ability> a=R.effects();a.hasMoreElements();)
					{
						A=a.nextElement();
						if(((A!=null)&&((A.classificationCode()&Ability.ALL_ACODES)!=Ability.ACODE_PROPERTY)))
						{
							A.unInvoke();
							R.delEffect(A);
							updateRoom=true;
						}
				}
				for(int d=Directions.NUM_DIRECTIONS()-1;d>=0;d--)
				{
					final Room R2=R.rawDoors()[d];
					Exit E=R.getRawExit(d);
					if((E!=null)&&(E.hasALock())&&(E.isGeneric()))
					{
						E.setKeyName("");
						E.setDoorsNLocks(E.hasADoor(),E.isOpen(),E.defaultsClosed(),false,false,false);
						updateExits=true;
						if(R2!=null)
						{
							E=R2.getRawExit(Directions.getOpDirectionCode(d));
							if((E!=null)&&(E.hasALock())&&(E.isGeneric()))
							{
								E.setKeyName("");
								E.setDoorsNLocks(E.hasADoor(),E.isOpen(),E.defaultsClosed(),false,false,false);
								CMLib.database().DBUpdateExits(R2);
								R2.getArea().fillInAreaRoom(R2);
							}
						}
					}
				}
				if(updateExits)
				{
					CMLib.database().DBUpdateExits(R);
					R.getArea().fillInAreaRoom(R);
				}
				if(updateItems)
					CMLib.database().DBUpdateItems(R);
				if(updateRoom)
					CMLib.database().DBUpdateRoom(R);
				colorForSale(R,T.rentalProperty(),resetRoomName);
				return -1;
			}

			if((lastNumItems<0)
			&&(!CMSecurity.isDisabled(CMSecurity.DisFlag.PROPERTYOWNERCHECKS))
			&&(optPlayerList!=null))
			{
				boolean playerExists=(CMLib.players().getPlayer(T.getOwnerName())!=null);
				if(!playerExists) playerExists=(CMLib.clans().getClan(T.getOwnerName())!=null);
				if(!playerExists) playerExists=optPlayerList.contains(T.getOwnerName());
				if(!playerExists)
				for(int i=0;i<optPlayerList.size();i++)
					if(((String)optPlayerList.get(i)).equalsIgnoreCase(T.getOwnerName()))
					{ playerExists=true; break;}
				if(!playerExists)
				{
					T.setOwnerName("");
					T.updateLot(null);
					return -1;
				}
			}

			int x=R.description().indexOf(SALESTR);
			if(x>=0)
			{
				R.setDescription(R.description().substring(0,x));
				CMLib.database().DBUpdateRoom(R);
			}
			x=R.description().indexOf(RENTSTR);
			if(x>=0)
			{
				R.setDescription(R.description().substring(0,x));
				CMLib.database().DBUpdateRoom(R);
			}

			// this works on the priciple that
			// 1. if an item has ONLY been removed, the lastNumItems will be != current # items
			// 2. if an item has ONLY been added, the dispossessiontime will be != null
			// 3. if an item has been added AND removed, the dispossession time will be != null on the added
			if((lastNumItems>=0)&&(R.numItems()!=lastNumItems))
				updateItems=true;

			for(int i=0;i<R.numItems();i++)
			{
				final Item I=R.getItem(i);
				if((I.expirationDate()!=0)
				&&((I.isSavable())||(I.Name().equalsIgnoreCase("id")))
				&&((!(I instanceof DeadBody))||(((DeadBody)I).playerCorpse())))
				{
					I.setExpirationDate(0);
					updateItems=true;
				}

				if((I.phyStats().rejuv()!=Integer.MAX_VALUE)
				&&(I.phyStats().rejuv()!=0))
				{
					I.basePhyStats().setRejuv(PhyStats.NO_REJUV);
					I.recoverPhyStats();
					updateItems=true;
				}
			}
			lastNumItems=R.numItems();
			if((!CMSecurity.isSaveFlag("NOPROPERTYITEMS"))
			&&(updateItems))
				CMLib.database().DBUpdateItems(R);
		}
		return lastNumItems;
	}

	public static boolean doRentalProperty(Area A, String ID, String owner, int rent)
	{
		if(!CMProps.getBoolVar(CMProps.Bool.MUDSTARTED))
			return false;
		final int month=A.getTimeObj().getMonth();
		final int day=A.getTimeObj().getDayOfMonth();
		final int year=A.getTimeObj().getYear();
		final Object O=Resources.getResource("RENTAL INFO/"+owner);
		List<PlayerData> pDataV=null;
		if(O instanceof List)
			pDataV=(List<PlayerData>)O;
		else
			pDataV=CMLib.database().DBReadData(owner,"RENTAL INFO");
		if(pDataV==null)
			pDataV=new Vector();
		DatabaseEngine.PlayerData pData = null;
		if(pDataV.size()==0)
		{
			pData = new DatabaseEngine.PlayerData();
			pData.who=owner;
			pData.section="RENTAL INFO";
			pData.key="RENTAL INFO/"+owner;
			pData.xml=ID+"|~>|"+day+" "+month+" "+year+"|~;|";
			CMLib.database().DBCreateData(owner,"RENTAL INFO","RENTAL INFO/"+owner,pData.xml);
			pDataV.add(pData);
			Resources.submitResource("RENTAL INFO/"+owner,pDataV);
			return false;
		}
		else
		if(pDataV.get(0) != null)
		{
			pData=pDataV.get(0);
			String parse=pData.xml;
			int x=parse.indexOf("|~;|");
			final StringBuffer reparse=new StringBuffer("");
			boolean changesMade=false;
			boolean needsToPay=false;
			while(x>=0)
			{
				String thisOne=parse.substring(0,x);
				if(thisOne.startsWith(ID+"|~>|"))
				{
					thisOne=thisOne.substring((ID+"|~>|").length());
					final Vector dateV=CMParms.parse(thisOne);
					if(dateV.size()==3)
					{
						int lastYear=CMath.s_int((String)dateV.lastElement());
						int lastMonth=CMath.s_int((String)dateV.elementAt(1));
						final int lastDay=CMath.s_int((String)dateV.firstElement());
						while(!needsToPay)
						{
							if(lastYear<year)
								needsToPay=true;
							else
							if((lastYear==year)&&(lastMonth<month)&&(day>=lastDay))
								needsToPay=true;
							if(needsToPay)
							{
								if(CMLib.beanCounter().modifyLocalBankGold(A,
										owner,
										CMLib.utensils().getFormattedDate(A)+":Withdrawal of "+rent+": Rent for "+ID,
										CMLib.beanCounter().getCurrency(A),
										(-rent)))
								{
									lastMonth++;
									if(lastMonth>A.getTimeObj().getMonthsInYear())
									{
										lastMonth=1;
										lastYear++;
									}
									changesMade=true;
									needsToPay=false;
								}
							}
							else
								break;
						}
						if(changesMade)
							reparse.append(ID+"|~>|"+lastDay+" "+lastMonth+" "+lastYear+"|~;|");
						if(needsToPay&&(!changesMade))
							return true;
					}
				}
				else
					reparse.append(thisOne+"|~;|");
				parse=parse.substring(x+4);
				x=parse.indexOf("|~;|");
			}
			if(changesMade)
			{
				CMLib.database().DBReCreateData(owner,"RENTAL INFO","RENTAL INFO/"+owner,reparse.toString());
				pData = new DatabaseEngine.PlayerData();
				pData.who=owner;
				pData.section="RENTAL INFO";
				pData.key="RENTAL INFO/"+owner;
				pData.xml=reparse.toString();
				pDataV.set(0,pData);
				Resources.removeResource("RENTAL INFO/"+owner);
				Resources.submitResource("RENTAL INFO/"+owner,pDataV);
			}
			return needsToPay;
		}
		return false;
	}

	// update lot, since its called by the savethread, ONLY worries about itself
	@Override
	public void updateLot(List optPlayerList)
	{
		if(affected instanceof Room)
		{
			Room R=(Room)affected;
			synchronized(("SYNC"+R.roomID()).intern())
			{
				R=CMLib.map().getRoom(R);
				lastItemNums=updateLotWithThisData(R,this,false,scheduleReset,optPlayerList,lastItemNums);
				if((lastDayDone!=R.getArea().getTimeObj().getDayOfMonth())
				&&(CMProps.getBoolVar(CMProps.Bool.MUDSTARTED)))
				{
					lastDayDone=R.getArea().getTimeObj().getDayOfMonth();
					if((getOwnerName().length()>0)&&rentalProperty()&&(R.roomID().length()>0))
						if(doRentalProperty(R.getArea(),R.roomID(),getOwnerName(),getPrice()))
						{
							setOwnerName("");
							CMLib.database().DBUpdateRoom(R);
							lastItemNums=updateLotWithThisData(R,this,false,scheduleReset,optPlayerList,lastItemNums);
						}
				}
				scheduleReset=false;
			}
		}
	}
}


text:
/* -*- Mode: C; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
 *     Copyright 2014-2019 Couchbase, Inc.
 *
 *   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.
 */

#include "docreq/docreq.h"
#include "internal.h"
#include "sllist-inl.h"

using namespace lcb::docreq;

static void docreq_handler(void *arg);
static void invoke_pending(Queue *);

#define MAX_PENDING_DOCREQ 10
#define MIN_SCHED_SIZE 5
#define DOCQ_DELAY_US 200000

Queue::Queue(lcb_INSTANCE *instance_)
    : instance(instance_), parent(NULL), timer(lcbio_timer_new(instance->iotable, this, docreq_handler)),
      cb_ready(NULL), cb_throttle(NULL), n_awaiting_schedule(0), n_awaiting_response(0),
      max_pending_response(MAX_PENDING_DOCREQ), min_batch_size(MIN_SCHED_SIZE), cancelled(false), refcount(1)
{

    memset(&pending_gets, 0, sizeof pending_gets);
    memset(&cb_queue, 0, sizeof cb_queue);
}

Queue::~Queue()
{
    cancel();
    lcbio_timer_destroy(timer);
}

void Queue::unref()
{
    if (!--refcount) {
        delete this;
    }
}

void Queue::cancel()
{
    cancelled = true;
}

/* Calling this function ensures that the request will be scheduled in due
 * time. This may be done at the next event loop iteration, or after a delay
 * depending on how many items are actually found within the queue. */
static void docq_poke(Queue *q)
{
    if (q->n_awaiting_response < q->max_pending_response) {
        if (q->n_awaiting_schedule > q->min_batch_size) {
            lcbio_async_signal(q->timer);
            q->cb_throttle(q, 0);
        }
    }

    if (!lcbio_timer_armed(q->timer)) {
        lcbio_timer_rearm(q->timer, DOCQ_DELAY_US);
    }
}

void Queue::add(DocRequest *req)
{
    sllist_append(&pending_gets, &req->slnode);
    n_awaiting_schedule++;
    req->parent = this;
    req->ready = 0;
    ref();
    docq_poke(this);
}

static void docreq_handler(void *arg)
{
    Queue *q = reinterpret_cast< Queue * >(arg);
    sllist_iterator iter;
    lcb_INSTANCE *instance = q->instance;

    lcb_sched_enter(instance);
    SLLIST_ITERFOR(&q->pending_gets, &iter)
    {
        DocRequest *cont = SLLIST_ITEM(iter.cur, DocRequest, slnode);

        if (q->n_awaiting_response > q->max_pending_response) {
            lcbio_timer_rearm(q->timer, DOCQ_DELAY_US);
            q->cb_throttle(q, 1);
            break;
        }

        q->n_awaiting_schedule--;

        if (q->cancelled) {
            cont->docresp.rc = LCB_EINTERNAL;
            cont->ready = 1;

        } else {
            lcb_STATUS rc;
            rc = q->cb_schedule(q, cont);
            if (rc != LCB_SUCCESS) {
                cont->docresp.rc = rc;
                cont->ready = 1;
            } else {
                q->n_awaiting_response++;
            }
        }
        sllist_iter_remove(&q->pending_gets, &iter);
        sllist_append(&q->cb_queue, &cont->slnode);
    }

    lcb_sched_leave(instance);
    lcb_sched_flush(instance);

    if (q->n_awaiting_schedule < q->min_batch_size) {
        q->cb_throttle(q, 0);
    }

    /* Ensure we're called again */
    docq_poke(q);

    /* Flush out any bad responses */
    invoke_pending(q);
}

/* Invokes the callback on all requests which are ready, until a request which
 * is not yet ready is reached. */
static void invoke_pending(Queue *q)
{
    sllist_iterator iter = {NULL};
    q->ref();
    SLLIST_ITERFOR(&q->cb_queue, &iter)
    {
        DocRequest *dreq = SLLIST_ITEM(iter.cur, DocRequest, slnode);
        void *bufh = NULL;

        if (dreq->ready == 0) {
            break;
        }

        if (dreq->docresp.rc == LCB_SUCCESS && dreq->docresp.bufh) {
            bufh = dreq->docresp.bufh;
        }

        sllist_iter_remove(&q->cb_queue, &iter);

        q->cb_ready(q, dreq);
        if (bufh) {
            lcb_backbuf_unref(reinterpret_cast< lcb_BACKBUF >(bufh));
        }
        q->unref();
    }
    q->unref();
}

void Queue::check()
{
    /* Ensure the invoke_pending doesn't destroy us */
    invoke_pending(this);
    docq_poke(this);
}


text:
pg_port = ask("What port are you going to use for this postgresql instance?")
pg_port = "5432" if pg_port.blank?

create_file '.env' do <<-EOF
PG_PORT: #{pg_port}
EOF
end

inject_into_file 'config/secrets.yml', "  db_port: <%= ENV['PG_PORT'] %>\n", after: "development:\n"

inject_into_file 'config/secrets.yml', "  db_port: <%= ENV['PG_PORT'] %>\n", after: "test:\n"

inject_into_file 'config/database.yml',
  :before => "default:" do <<-YAML
local: &local
  pg_port: Rails.application.secrets.db_port

YAML
end

inject_into_file 'config/database.yml',
  :after => "development:" do <<-YAML

  <<: *local
YAML
end

inject_into_file 'config/database.yml',
  :after => "test:" do <<-YAML

  <<: *local
YAML
end

# see http://mauricio.github.io/2014/02/09/foreman-and-environment-variables.html
create_file 'Procfile.dev' do <<-EOF
postgresql: postgres -p #{pg_port} -D vendor/postgresql
rails: bundle exec rails s -b 0.0.0.0 -p $PORT
guard: bundle exec guard --no-interactions
EOF
end

app_port = ask("On which port do you want to run this application?")
app_port = "5000" if app_port.blank?

create_file '.foreman' do <<-EOF
port: #{app_port}
EOF
end

run "echo #{app_port.to_i+100} > ~/.pow/#{app_name}"

gem 'activerecord-colored_log_subscriber' # colorized SQL logging, will be the default on Rails 5
gem 'devise'
gem 'rack-mini-profiler'

# Use Puma as the app server
gem 'puma'

gem_group :development, :test do
  gem 'rspec-rails', '~> 3.0'
  gem 'factory_girl_rails'
end

gem_group :test do
  gem 'database_cleaner'
  gem 'capybara'
  gem 'shoulda-matchers'
  gem 'simplecov', :require => false
end

gem_group :development do
  # Preview mail in the browser instead of sending it.
  gem 'letter_opener_web', '~> 1.2.0'

  gem 'annotate', '~> 2.6.6'
  gem 'bullet'
  gem 'guard-rspec', require: false
  gem 'quiet_assets'
end

run 'bundle install --path .bundle'

run "pg_ctl init -D vendor/postgresql"

initializer 'mini_profiler.rb', <<-CODE
Rack::MiniProfiler.config.position = 'right'
Rack::MiniProfiler.config.start_hidden = true
CODE

#rake 'db:create'

inject_into_file 'config/application.rb',
  after: "config.active_record.raise_in_transactional_callbacks = true\n" do <<-RUBY
    config.generators do |g|
      g.stylesheets     false
      g.javascripts     false
    end
RUBY
end

generate 'rspec:install'
run 'bundle binstubs rspec-core'

create_file '.simplecov' do <<-EOF
SimpleCov.start 'rails' do
  add_filter '/.bundle/'
  add_group "Uploaders", "app/uploaders"
end
EOF
end

inject_into_file 'spec/rails_helper.rb', "require 'simplecov'\n", after: "ENV['RAILS_ENV'] ||= 'test'\n"
inject_into_file 'spec/rails_helper.rb', "require 'capybara/rspec'\n", after: "# Add additional requires below this line. Rails is not loaded until this point!\n"
inject_into_file 'spec/rails_helper.rb', "require 'capybara/rails'\n", after: "# Add additional requires below this line. Rails is not loaded until this point!\n"
inject_into_file 'spec/rails_helper.rb',
  :before => /^end/ do <<-RUBY

  config.include Devise::TestHelpers, type: :controller
  config.include Rails.application.routes.url_helpers

  # Include Factory Girl syntax to simplify calls to factories
  config.include FactoryGirl::Syntax::Methods

  config.expect_with :rspec do |c|
    c.syntax = :expect
  end
RUBY
end

route <<-EOF
if Rails.env.development?
    mount LetterOpenerWeb::Engine, at: '/letter_opener'
  end
EOF

generate 'annotate:install'
generate 'devise:install'

initializer 'bullet.rb', <<-CODE
if defined? Bullet
  Bullet.enable = true # this is to actually enable the gem
  Bullet.bullet_logger = true
  Bullet.console = true
  Bullet.add_footer = true
end
CODE

run 'bundle exec guard init rspec'

git :init
git add: "."
git commit: "-m 'Project initialization'"

if yes?('Do you want to create a devise model now? (yes/no)')
  devise_model = ask("What would you want to name it? (empty for the default 'User')")
  devise_model = "User" if devise_model.blank?
  generate "devise #{devise_model}"
end

if yes?('Do you want to add omniauth authentication? (yes/no)')

  generate 'model identity user:references provider:string uid:string'

  inject_into_file 'app/models/identity.rb',
    before: /^end/ do <<-RUBY
  belongs_to #{devise_model.downcase.to_sym}

  validates_presence_of :uid, :provider
  validates_uniqueness_of :uid, :scope => :provider

  def self.find_for_oauth(auth)
    find_or_create_by(uid: auth.uid, provider: auth.provider)
  end
RUBY
end

  gsub_file 'config/routes.rb', /devise_for :users/, "devise_for :users, :controllers => { omniauth_callbacks: 'omniauth_callbacks' }"

  create_file 'app/controllers/omniauth_callbacks_controller' do <<-'RUBY'
class OmniauthCallbacksController < Devise::OmniauthCallbacksController
  skip_before_action :authenticate_user!

  def self.provides_callback_for(provider)
    class_eval %Q{
      def #{provider}
        @user = User.find_for_oauth(env["omniauth.auth"], current_user)

        if @user.persisted?
          sign_in_and_redirect @user, event: :authentication
          set_flash_message(:notice, :success, kind: "#{provider}".capitalize) if is_navigational_format?
        else
          session["devise.#{provider}_data"] = env["omniauth.auth"]
          redirect_to new_user_registration_url
        end
      end
    }
  end

  [:facebook].each do |provider|
    provides_callback_for provider
  end

  def after_sign_in_path_for(resource)
    if resource.email_verified?
      super resource
    else
      finish_signup_path(resource)
    end
  end
end
RUBY
  end

  inject_into_file 'app/models/user.rb',
    before: /^end/ do <<-'RUBY'
  TEMP_EMAIL_PREFIX = 'change@me'
  TEMP_EMAIL_REGEX = /\Achange@me/

  validates_format_of :email, :without => TEMP_EMAIL_REGEX, on: :update

  def self.find_for_oauth(auth, signed_in_resource = nil)
    # Get the identity and user if they exist
    identity = Identity.find_for_oauth(auth)

    # If a signed_in_resource is provided it always overrides the existing user
    # to prevent the identity being locked with accidentally created accounts.
    # Note that this may leave zombie accounts (with no associated identity) which
    # can be cleaned up at a later date.
    user = signed_in_resource ? signed_in_resource : identity.user

    # Create the user if needed
    if user.nil?

      # Get the existing user by email if the provider gives us a verified email.
      # If no verified email was provided we assign a temporary email and ask the
      # user to verify it on the next step via UsersController.finish_signup
      email_is_verified = auth.info.email && (auth.info.verified || auth.info.verified_email)
      email = auth.info.email if email_is_verified
      user = User.where(:email => email).first if email

      # Create the user if it's a new registration
      if user.nil?
        user = User.new(
          first_name: auth.extra.raw_info.first_name,
          last_name: auth.extra.raw_info.last_name,
          #username: auth.info.nickname || auth.uid,
          email: email ? email : "#{TEMP_EMAIL_PREFIX}-#{auth.uid}-#{auth.provider}.com",
          password: Devise.friendly_token[0,20]
        )
        user.skip_confirmation!
        user.save!
      end
    end

    # Associate the identity with the user if needed
    if identity.user != user
      identity.user = user
      identity.save!
    end
    user
  end

  def email_verified?
    self.email && self.email !~ TEMP_EMAIL_REGEX
  end
RUBY
  end

  route "match '/users/:id/finish_signup' => 'users#finish_signup', via: [:get, :patch], :as => :finish_signup"

  inject_into_file 'config/secrets.yml', "  omniauth:\n", after: "development:\n"

  gsub_file 'app/models/user.rb', /:validatable/, ':validatable, :omniauthable'

  if yes?('Do you want to allow signing in via Facebook?')
    gem 'omniauth-facebook'
    run 'bundle install'

    inject_into_file 'config/secrets.yml',
        after: "omniauth:\n" do <<-YAML
    facebook:
      app_id: <%= ENV["FACEBOOK_APP_ID"] %>
      app_secret: <%= ENV["FACEBOOK_APP_SECRET"] %>
YAML
    end

    inject_into_file 'config/initializers/devise.rb',
      after: "# config.omniauth :github, 'APP_ID', 'APP_SECRET', scope: 'user,public_repo'\n" do <<-RUBY
  config.omniauth :facebook,
                  Rails.application.secrets.omniauth['facebook']['app_id'],
                  Rails.application.secrets.omniauth['facebook']['app_secret'],
                  info_fields: 'name,email,first_name,last_name,middle_name,verified'
RUBY
    end

    git add: "."
    git commit: "-m 'Setup omniauth'"

  end
end


text:
package it.pkg;

import com.google.web.bindery.requestfactory.shared.RequestFactory;

public interface BasicFactory extends RequestFactory {
	GreetingContext greeting();
}


text:
import R from 'ramda'
import { select, call } from 'redux-saga/effects'
import {encryptJson, signPublicKey} from 'lib/crypto'
import {keyableIsTrusted} from 'lib/trust'
import {orgRoleIsAdmin} from 'lib/roles'
import {
  getUser,
  getApp,
  getServer,
  getUsersForApp,
  getServersWithPubkeyForApp,
  getLocalKey,
  getLocalKeysWithPubkeyForApp,
  getCurrentUser,
  getCurrentUserEnvironmentsAssignableToAppUser,
  getCurrentUserEnvironmentAssignableToServer,
  getEnvsWithMetaWithPending,
  getRawEnvWithPendingForApp,
  getAppUserBy,
  getApps,
  getPrivkey,
  getTrustedPubkeys
} from 'selectors'
import {productionInheritanceOverrides} from 'lib/env/inheritance'
import {
  ADD_ASSOC_REQUEST,
  CREATE_ASSOC_SUCCESS,
  REMOVE_ASSOC_REQUEST,
  REMOVE_OBJECT_REQUEST
} from "actions"

export function* envParamsWithAppUser({
  appId,
  userId,
  role,
  withTrustedPubkey,
  isAcceptingInvite=false
}, envParams={}){

  const privkey = yield select(getPrivkey),
        user = yield select(getUser(userId)),
        pubkey = withTrustedPubkey || user.pubkey || user.invitePubkey,
        environments = yield select(getCurrentUserEnvironmentsAssignableToAppUser({appId, userId, role})),
        targetAppUser = yield select(getAppUserBy({appId, userId})),
        trustedPubkeys = yield select(getTrustedPubkeys),
        envs = {}

  // Make productionMetaOnly assignable for a dev user when accepting an invitation
  if(isAcceptingInvite && !environments.includes("productionMetaOnly")){
    environments.push("productionMetaOnly")
  }

  if(pubkey && (withTrustedPubkey || keyableIsTrusted(user, trustedPubkeys))){
    const app = yield select(getApp(appId)),
          envsWithMeta = yield select(getEnvsWithMetaWithPending("app", appId)),
          encryptedEnvs = yield environments.map(environment => encryptJson({data: envsWithMeta[environment], pubkey, privkey}))

    envs.envsWithMeta = R.zipObj(environments, encryptedEnvs)
  }

  if(R.isEmpty(envs))return envParams
  return R.assocPath(["users", userId, "apps", appId], envs, envParams)
}

export function* envParamsWithServer({appId, serverId}, envParams={}){
  const privkey = yield select(getPrivkey),
        server = yield select(getServer(serverId)),
        trustedPubkeys = yield select(getTrustedPubkeys),
        {pubkey, subEnvId, role: serverRole} = server,
        environment = yield select(getCurrentUserEnvironmentAssignableToServer({appId, serverId}))

  if(!keyableIsTrusted(server, trustedPubkeys)) return envParams

  if (environment){
    const rawEnv = yield select(getRawEnvWithPendingForApp({appId, environment, subEnvId}))
    return R.assocPath(["servers", serverId], {
      env: yield encryptJson({data: rawEnv, pubkey, privkey })
    }, envParams)
  } else {
    const {role: appRole} =  yield select(getApp(appId))
    if (appRole == "development" && serverRole == "production"){
      const envsWithMeta = yield select(getEnvsWithMetaWithPending("app", appId)),
            inheritanceOverrides = productionInheritanceOverrides(envsWithMeta, subEnvId)

      if (R.isEmpty(inheritanceOverrides)){
        return envParams
      } else {
        return R.assocPath(["servers", serverId], {
          inheritanceOverrides: yield encryptJson({ data: inheritanceOverrides, pubkey, privkey})
        }, envParams)
      }
    } else {
      return envParams
    }
  }
}

export function* envParamsWithLocalKey({appId, localKeyId}, envParams={}){
  const privkey = yield select(getPrivkey),
        localKey = yield select(getLocalKey(localKeyId)),
        trustedPubkeys = yield select(getTrustedPubkeys),
        {pubkey, role: localKeyRole} = localKey,
        environment = "development"

  if(!keyableIsTrusted(localKey, trustedPubkeys)) return envParams

  const rawEnv = yield select(getRawEnvWithPendingForApp({appId, environment}))
  return R.assocPath(["localKeys", localKeyId], {
    env: yield encryptJson({data: rawEnv, pubkey, privkey })
  }, envParams)
}

export function* envParamsForApp({appId}){
  const
    users = yield select(getUsersForApp(appId)),
    servers = yield select(getServersWithPubkeyForApp(appId)),
    localKeys = yield select(getLocalKeysWithPubkeyForApp(appId)),

    userGenerators = users.map(({id: userId})=> call(envParamsWithAppUser, {appId, userId})),

    serverGenerators = servers.map(({id: serverId})=> call(envParamsWithServer, {appId, serverId})),

    localKeyGenerators = localKeys.map(({id: localKeyId})=> call(envParamsWithLocalKey, {appId, localKeyId})),

    allGenerators = userGenerators.concat(serverGenerators, localKeyGenerators),

    allParams = yield allGenerators,

    merged = allParams.reduce(R.mergeDeepRight)

  return merged
}

export function *envParamsForInvitee({userId, permittedAppIds}){
  const generators = permittedAppIds.map(appId => call(envParamsWithAppUser, {userId, appId})),
        allParams = yield generators,
        merged = allParams.reduce(R.mergeDeepRight)

  return { envs: merged }
}

export function *envParamsForAcceptedInvite(withTrustedPubkey){
  const {id: userId} = yield select(getCurrentUser),
        apps = yield select(getApps),
        generators = apps.map(({id: appId})=> call(envParamsWithAppUser, {userId, appId, withTrustedPubkey, isAcceptingInvite: true})),
        allParams = yield generators,
        merged = allParams.reduce(R.mergeDeepRight)

  return merged
}

export function *envParamsForUpdateOrgRole({userId, role: newRole}){
  const {orgRole: currentRole} = yield select(getUser(userId)),

        isCurrentAdmin = orgRoleIsAdmin(currentRole),

        isUpdatingToAdmin = orgRoleIsAdmin(newRole),

        isUpdatingNonAdminToAdmin = !isCurrentAdmin && isUpdatingToAdmin

  if (!isUpdatingNonAdminToAdmin) return {}

  const apps = yield select(getApps),
        generators = apps.map(({id: appId})=> call(envParamsWithAppUser, {userId, appId, role: newRole})),
        allParams = yield generators,
        merged = allParams.reduce(R.mergeDeepRight)

  return merged
}

export function* attachAssocEnvs(action){
  let envParams

  const {
    meta: { parentType, assocType, parentId, assocId, targetId },
    payload,
    type
  } = action

  const appId = parentId,
        app = yield(select(getApp(parentId)))

  if(type != ADD_ASSOC_REQUEST)return action
  envParams = yield call(envParamsWithAppUser, {
    appId: app.id,
    userId: assocId,
    role: R.values(payload)[0].role
  })

  if(R.isEmpty(envParams)){
    return action
  } else {
    return R.assocPath(["payload", "envs"], envParams)(action)
  }
}