text:
Q: graph axis scaling incorrect when putting two Y axis on graph Can someone explain why my plot apparently overwrites the first line with the second? The values are in no way the same.
per.acc<-c(0.508407842930696, 0.508407842930696, 0.508776550216615, 0.508895063272804,
           0.509619309727288, 0.51039622865119, 0.510712263467692, 0.511871057794867,
           0.512252933198141, 0.513280046351773, 0.514122805862446, 0.514478345031011,
           0.514768043612805, 0.515676643710249, 0.516084855348231, 0.51682226992007,
           0.517757206252222, 0.519008177400877, 0.519890441263613, 0.520680528304868,
           0.521286261703164, 0.522181693683254, 0.523024453193927, 0.524222751873165,
           0.524420273633479, 0.524986502679712, 0.525631740430071, 0.52609262453747,
           0.526777366639891, 0.52733042756877, 0.52788348849765, 0.528278532018277,
           0.528673575538905, 0.529661184340475, 0.530569784437919, 0.531109677249444,
           0.530833146785004, 0.531425712065946, 0.531280862775049, 0.53063562502469,
           0.531465216418009, 0.531215022188278, 0.531188685953569, 0.53153105700478,
           0.53180758746922, 0.532110454168368, 0.532005109229533, 0.532070949816305,
           0.53233431216339, 0.532189462872493, 0.532307975928682, 0.532321144046036,
           0.531741746882448, 0.531504720770071, 0.530214245269354, 0.529661184340475,
           0.529002778472762, 0.529845537983434, 0.53054344820321, 0.529108123411596,
           0.528186355196797, 0.527896656615004, 0.526830039109309, 0.526263810063075,
           0.525091847618546, 0.524354433046707, 0.523538009770743, 0.522655745908008,
           0.522036844392357, 0.520812209478411, 0.519640247033882, 0.518520957058769,
           0.517335826496886, 0.515531794419352, 0.514715371143388, 0.51314836517823,
           0.511831553442804, 0.510975625814777, 0.510040689482625, 0.508118144348902,
           0.507104199312624, 0.505813723811907, 0.505168486061548, 0.504312558433521,
           0.503311781514597, 0.502284668360964, 0.501297059559395, 0.500546476870202,
           0.500072424645448, 0.499018975257107, 0.497886517164641, 0.496964748949843,
           0.495516256040874, 0.494120435601322, 0.493383021029483, 0.492803623865896,
           0.492421748462622, 0.492118881763474, 0.492026704941994, 0.491684333890784
)

num.pred<-c(38609L, 38609L, 38637L, 38646L, 38701L, 38760L, 38784L, 38872L,
            38901L, 38979L, 39043L, 39070L, 39092L, 39161L, 39192L, 39248L,
            39319L, 39414L, 39481L, 39541L, 39587L, 39655L, 39719L, 39810L,
            39825L, 39868L, 39917L, 39952L, 40004L, 40046L, 40088L, 40118L,
            40148L, 40223L, 40292L, 40333L, 40312L, 40357L, 40346L, 40297L,
            40360L, 40341L, 40339L, 40365L, 40386L, 40409L, 40401L, 40406L,
            40426L, 40415L, 40424L, 40425L, 40381L, 40363L, 40265L, 40223L,
            40173L, 40237L, 40290L, 40181L, 40111L, 40089L, 40008L, 39965L,
            39876L, 39820L, 39758L, 39691L, 39644L, 39551L, 39462L, 39377L,
            39287L, 39150L, 39088L, 38969L, 38869L, 38804L, 38733L, 38587L,
            38510L, 38412L, 38363L, 38298L, 38222L, 38144L, 38069L, 38012L,
            37976L, 37896L, 37810L, 37740L, 37630L, 37524L, 37468L, 37424L,
            37395L, 37372L, 37365L, 37339L)

plot(x=1:100,y=per.acc, main="RSI predicting trend",ylab=NA,xlab="RSI cutoff value",col="blue",type="p")
par(new=T)
plot(x=1:100,y=num.pred,axes=F,xlab=NA,main=NA,ylab=NA,col="red",type="p")
axis(side=4)

A: Because your per.acc and num.pred has perfect co-linearity:
plot(per.acc, num.pred)

Therefore, your second plot and first plot just differ by a vertical shift. When you do par(new = TRUE), they coincide.
On the other hand, if you do some random shuffling:
set.seed(0); num.pred <- sample(num.pred)

the issue goes away:


text:
Q: Applying variable transparency to an image in java I'm wondering how to apply a variable mask to an image's transparency in Java (presumably using buffered image). So, for instance, I want to apply a mask such as the following:

To the an image such as the following:

In order to get:

It's important that the transparency is changed by the gradient, not just the color, because I want to be able to to this kind of thing:

I've found an incredibly slow way of achieving this by going through and setting the transparency value of every single pixel manually, but as I said, it's super slow. What should I be looking at to try to accomplish this? Or should I even be doing it in Java? I've been getting to know python recently, so if anyone thinks it's better to try this sort of thing with a particular python module, that would be useful information as well.
Thank in advance!

A: Here is one way to get a transparent mask.
GradientMask.java:
import Utilities.*;
import javax.swing.*;
import javax.imageio.*;
import java.awt.*;
import java.awt.image.*;
import java.io.*;
public class GradientMask {
    public static void main(String[] args) throws Exception{
        JFrame Main = new JFrame("Gradient Mask");
        JLabel imageLayer = new JLabel();
        JLabel maskLayer = new JLabel();
        BufferedImage image = ImageIO.read(new File("C:\\Users\\"+System.getenv("username")+"\\Desktop\\Cat Image.jpg"));
        BufferedImage gradientMask = new GradientImage(image.getWidth(), image.getHeight(), new Color[]{new Color(255, 255, 255, 125), Color.BLACK}, GradientImage.RADIAL_FROM_CENTER).getImage();
        Main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Main.setBounds(100, 50, image.getWidth(), image.getHeight());
        imageLayer.setBounds(0, 0, Main.getWidth(), Main.getHeight());
        maskLayer.setBounds(0, 0, Main.getWidth(), Main.getHeight());
        imageLayer.setIcon(new ImageIcon((Image) image));
        maskLayer.setIcon(new ImageIcon((Image) gradientMask));
        Main.getContentPane().add(imageLayer);
        imageLayer.add(maskLayer);
        Main.setVisible(true);
    }
}

GradientImage.java:
package Utilities;
import java.awt.*;
import java.awt.image.*;
public class GradientImage {
    public final static int LINEAR_LEFT_TO_RIGHT = 1;
    public final static int LINEAR_RIGHT_TO_LEFT = 2;
    public final static int LINEAR_TOP_TO_BOTTOM = 3;
    public final static int LINEAR_BOTTOM_TO_TOP = 4;
    public final static int LINEAR_DIAGONAL_UP = 5;
    public final static int LINEAR_DIAGONAL_DOWN = 6;
    public final static int RADIAL_FROM_TOP_LEFT_CORNER = 7;
    public final static int RADIAL_FROM_BOTTOM_LEFT_CORNER = 8;
    public final static int RADIAL_FROM_TOP_RIGHT_CORNER = 9;
    public final static int RADIAL_FROM_BOTTOM_RIGHT_CORNER = 10;
    public final static int RADIAL_FROM_CENTER = 11;
    public final static int RADIAL_FROM_CORNERS = 12;
    public final static int PATH_FROM_CENTER = 13;
    public final static int PATH_FROM_TOP_LEFT_CORNER = 14;
    public final static int PATH_FROM_TOP_RIGHT_CORNER = 15;
    public final static int PATH_FROM_BOTTOM_LEFT_CORNER = 16;
    public final static int PATH_FROM_BOTTOM_RIGHT_CORNER = 17;
    public final static int LINEAR_FROM_TOP_RIGHT_CORNER = 18;
    public final static int LINEAR_FROM_TOP_LEFT_CORNER = 19;
    public final static int LINEAR_FROM_BOTTOM_RIGHT_CORNER = 20;
    public final static int LINEAR_FROM_BOTTOM_LEFT_CORNER = 21;
    public final static int LINEAR_FROM_CENTER = 22;
    public final static int LINEAR_FROM_CORNERS = 23;
    public final static int PATH_FROM_CORNERS = 24;
    private BufferedImage image = null;
    private BufferedImage circleImage = null;
    private int[] pixels;
    private int[] circlePixels;
    private int[] positions;
    private Color[] colors;
    private int[] rgbs;
    private int alignment;
    private int width;
    private int height;
    public GradientImage(int width, int height, Color[] colors, int alignment){
        image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        pixels = ((DataBufferInt) image.getRaster().getDataBuffer()).getData();
        this.alignment = alignment;
        this.width = width;
        this.height = height;
        this.colors = colors;
        rgbs = new int[colors.length];
        for (int i=0;i<rgbs.length;i++){
            rgbs[i] = colors[i].getRGB();
        }
        try{
            renderImage();
        }catch(Exception error){error.printStackTrace();}
    }
    public GradientImage(int width, int height, Color[] colors, int[] positions, int alignment){
        image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        pixels = ((DataBufferInt) image.getRaster().getDataBuffer()).getData();
        this.alignment = alignment;
        this.width = width;
        this.height = height;
        this.colors = colors;
        this.positions = positions;
        rgbs = new int[colors.length];
        for (int i=0;i<rgbs.length;i++){
            rgbs[i] = colors[i].getRGB();
        }
        try{
            renderImage();
        }catch(Exception error){error.printStackTrace();}
    }
    public BufferedImage getImage(){
        return image;
    }
    public BufferedImage getImageAsCircle(){
        if (circleImage==null){
            circleImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
            circlePixels = ((DataBufferInt) circleImage.getRaster().getDataBuffer()).getData();
            int radius = Math.min(width, height)>>1;
            for (int x=0;x<width;x++){
                for (int y=0;y<height;y++){
                    if (Math.sqrt((Math.max(width>>1, x)-Math.min(width>>1, x))*(Math.max(width>>1, x)-Math.min(width>>1, x))+(Math.max(height>>1, y)-Math.min(height>>1, y))*(Math.max(height>>1, y)-Math.min(height>>1, y)))<=radius){
                        circlePixels[x+y*width] = pixels[x+y*width];
                    }
                }
            }
        }
        return circleImage;
    }
    private void renderImage() throws Exception{
        if (alignment==LINEAR_LEFT_TO_RIGHT){
            int[] rgbRange = loadRGBRange(width, rgbs, positions);
            for (int x=0;x<width;x++){
                for (int y=0;y<height;y++){
                    pixels[x+y*width] = rgbRange[x];
                }
            }
        }else if (alignment==LINEAR_RIGHT_TO_LEFT){
            int[] rgbRange = loadRGBRange(width, rgbs, positions);
            for (int x=0;x<width;x++){
                for (int y=0;y<height;y++){
                    pixels[x+y*width] = rgbRange[width-x-1];
                }
            }
        }else if (alignment==LINEAR_BOTTOM_TO_TOP){
            int[] rgbRange = loadRGBRange(height, rgbs, positions);
            for (int y=0;y<height;y++){
                for (int x=0;x<width;x++){
                    pixels[x+y*width] = rgbRange[height-y-1];
                }
            }
        }else if (alignment==LINEAR_TOP_TO_BOTTOM){
            int[] rgbRange = loadRGBRange(height, rgbs, positions);
            for (int y=0;y<height;y++){
                for (int x=0;x<width;x++){
                    pixels[x+y*width] = rgbRange[y];
                }
            }
        }else if (alignment==RADIAL_FROM_TOP_LEFT_CORNER){
            int[] rgbRange = loadRGBRange((int) Math.sqrt((width-1)*(width-1)+(height-1)*(height-1)), rgbs, positions);
            for (int x=0;x<width;x++){
                for (int y=0;y<height;y++){
                    pixels[x+y*width] = rgbRange[(int) Math.sqrt((x-1)*(x-1)+(y-1)*(y-1))];
                }
            }
        }else if (alignment==RADIAL_FROM_BOTTOM_LEFT_CORNER){
            int[] rgbRange = loadRGBRange((int) Math.sqrt((width-1)*(width-1)+(height-1)*(height-1)), rgbs, positions);
            for (int x=0;x<width;x++){
                for (int y=0;y<height;y++){
                    pixels[x+(height-y-1)*width] = rgbRange[(int) Math.sqrt((x-1)*(x-1)+(y-1)*(y-1))];
                }
            }
        }else if (alignment==RADIAL_FROM_TOP_RIGHT_CORNER){
            int[] rgbRange = loadRGBRange((int) Math.sqrt((width-1)*(width-1)+(height-1)*(height-1)), rgbs, positions);
            for (int x=0;x<width;x++){
                for (int y=0;y<height;y++){
                    pixels[(width-x-1)+y*width] = rgbRange[(int) Math.sqrt((x-1)*(x-1)+(y-1)*(y-1))];
                }
            }
        }else if (alignment==RADIAL_FROM_BOTTOM_RIGHT_CORNER){
            int[] rgbRange = loadRGBRange((int) Math.sqrt((width-1)*(width-1)+(height-1)*(height-1)), rgbs, positions);
            for (int x=0;x<width;x++){
                for (int y=0;y<height;y++){
                    pixels[(width-x-1)+(height-y-1)*width] = rgbRange[(int) Math.sqrt((x-1)*(x-1)+(y-1)*(y-1))];
                }
            }
        }else if (alignment==RADIAL_FROM_CENTER){
            int[] divArray = divideArray(positions, 2);
            BufferedImage quad1 = new GradientImage(width>>1, height>>1, colors, divArray, GradientImage.RADIAL_FROM_BOTTOM_RIGHT_CORNER).getImage();
            BufferedImage quad2 = new GradientImage(width>>1, height>>1, colors, divArray, GradientImage.RADIAL_FROM_BOTTOM_LEFT_CORNER).getImage();
            BufferedImage quad3 = new GradientImage(width>>1, height>>1, colors, divArray, GradientImage.RADIAL_FROM_TOP_RIGHT_CORNER).getImage();
            BufferedImage quad4 = new GradientImage(width>>1, height>>1, colors, divArray, GradientImage.RADIAL_FROM_TOP_LEFT_CORNER).getImage();
            Graphics2D g = image.createGraphics();
            g.drawImage(quad1, 0, 0, null);
            g.drawImage(quad2, width>>1, 0, null);
            g.drawImage(quad3, 0, height>>1, null);
            g.drawImage(quad4, width>>1, height>>1, null);
            g.dispose();
        }else if (alignment==RADIAL_FROM_CORNERS){
            int[] divArray = divideArray(positions, 2);
            BufferedImage quad1 = new GradientImage(width>>1, height>>1, colors, divArray, GradientImage.RADIAL_FROM_TOP_LEFT_CORNER).getImage();
            BufferedImage quad2 = new GradientImage(width>>1, height>>1, colors, divArray, GradientImage.RADIAL_FROM_TOP_RIGHT_CORNER).getImage();
            BufferedImage quad3 = new GradientImage(width>>1, height>>1, colors, divArray, GradientImage.RADIAL_FROM_BOTTOM_LEFT_CORNER).getImage();
            BufferedImage quad4 = new GradientImage(width>>1, height>>1, colors, divArray, GradientImage.RADIAL_FROM_BOTTOM_RIGHT_CORNER).getImage();
            Graphics2D g = image.createGraphics();
            g.drawImage(quad1, 0, 0, null);
            g.drawImage(quad2, width>>1, 0, null);
            g.drawImage(quad3, 0, height>>1, null);
            g.drawImage(quad4, width>>1, height>>1, null);
            g.dispose();
        }else if (alignment==LINEAR_DIAGONAL_UP){
            int[] rgbRange = loadRGBRange((int) Math.sqrt((width-1)*(width-1)+(height-1)*(height-1)), rgbs, positions);
            for (int x=0;x<width;x++){
                for (int y=0;y<height;y++){
                    pixels[x+(height-y-1)*width] = rgbRange[Math.max(y-x, x-y)];
                }
            }
        }else if (alignment==LINEAR_DIAGONAL_DOWN){
            int[] rgbRange = loadRGBRange((int) Math.sqrt((width-1)*(width-1)+(height-1)*(height-1)), rgbs, positions);
            for (int x=0;x<width;x++){
                for (int y=0;y<height;y++){
                    pixels[x+y*width] = rgbRange[Math.max(y-x, x-y)];
                }
            }
        }else if (alignment==LINEAR_FROM_TOP_RIGHT_CORNER){
            int[] rgbRange = loadRGBRange((width+height)>>1, rgbs, positions);
            for (int x=0;x<width;x++){
                for (int y=0;y<height;y++){
                    pixels[x+(height-y-1)*width] = rgbRange[rgbRange.length-((x+y)>>1)-1];
                }
            }
        }else if (alignment==LINEAR_FROM_TOP_LEFT_CORNER){
            int[] rgbRange = loadRGBRange((width+height)>>1, rgbs, positions);
            for (int x=0;x<width;x++){
                for (int y=0;y<height;y++){
                    pixels[(width-x-1)+(height-y-1)*width] = rgbRange[rgbRange.length-((x+y)>>1)-1];
                }
            }
        }else if (alignment==LINEAR_FROM_BOTTOM_RIGHT_CORNER){
            int[] rgbRange = loadRGBRange((width+height)>>1, rgbs, positions);
            for (int x=0;x<width;x++){
                for (int y=0;y<height;y++){
                    pixels[x+y*width] = rgbRange[rgbRange.length-((x+y)>>1)-1];
                }
            }
        }else if (alignment==LINEAR_FROM_BOTTOM_LEFT_CORNER){
            int[] rgbRange = loadRGBRange((width+height)>>1, rgbs, positions);
            for (int x=0;x<width;x++){
                for (int y=0;y<height;y++){
                    pixels[(width-x-1)+y*width] = rgbRange[rgbRange.length-((x+y)>>1)-1];
                }
            }
        }else if (alignment==LINEAR_FROM_CENTER){
            int[] divArray = divideArray(positions, 2);
            BufferedImage quad1 = new GradientImage(width>>1, height>>1, colors, divArray, GradientImage.LINEAR_FROM_BOTTOM_RIGHT_CORNER).getImage();
            BufferedImage quad2 = new GradientImage(width>>1, height>>1, colors, divArray, GradientImage.LINEAR_FROM_BOTTOM_LEFT_CORNER).getImage();
            BufferedImage quad3 = new GradientImage(width>>1, height>>1, colors, divArray, GradientImage.LINEAR_FROM_TOP_RIGHT_CORNER).getImage();
            BufferedImage quad4 = new GradientImage(width>>1, height>>1, colors, divArray, GradientImage.LINEAR_FROM_TOP_LEFT_CORNER).getImage();
            Graphics2D g = image.createGraphics();
            g.drawImage(quad1, 0, 0, null);
            g.drawImage(quad2, width>>1, 0, null);
            g.drawImage(quad3, 0, height>>1, null);
            g.drawImage(quad4, width>>1, height>>1, null);
            g.dispose();
        }else if (alignment==LINEAR_FROM_CORNERS){
            int[] divArray = divideArray(positions, 2);
            BufferedImage quad1 = new GradientImage(width>>1, height>>1, colors, divArray, GradientImage.LINEAR_FROM_TOP_LEFT_CORNER).getImage();
            BufferedImage quad2 = new GradientImage(width>>1, height>>1, colors, divArray, GradientImage.LINEAR_FROM_TOP_RIGHT_CORNER).getImage();
            BufferedImage quad3 = new GradientImage(width>>1, height>>1, colors, divArray, GradientImage.LINEAR_FROM_BOTTOM_LEFT_CORNER).getImage();
            BufferedImage quad4 = new GradientImage(width>>1, height>>1, colors, divArray, GradientImage.LINEAR_FROM_BOTTOM_RIGHT_CORNER).getImage();
            Graphics2D g = image.createGraphics();
            g.drawImage(quad1, 0, 0, null);
            g.drawImage(quad2, width>>1, 0, null);
            g.drawImage(quad3, 0, height>>1, null);
            g.drawImage(quad4, width>>1, height>>1, null);
            g.dispose();
        }else if (alignment==PATH_FROM_TOP_LEFT_CORNER){
            int[] rgbRange = loadRGBRange(Math.max(width, height), rgbs, positions);
            for (int x=0;x<width;x++){
                for (int y=0;y<height;y++){
                    pixels[x+y*width] = rgbRange[Math.max(x, y)];
                }
            }
        }else if (alignment==PATH_FROM_TOP_RIGHT_CORNER){
            int[] rgbRange = loadRGBRange(Math.max(width, height), rgbs, positions);
            for (int x=0;x<width;x++){
                for (int y=0;y<height;y++){
                    pixels[(width-x-1)+y*width] = rgbRange[Math.max(x, y)];
                }
            }
        }else if (alignment==PATH_FROM_BOTTOM_LEFT_CORNER){
            int[] rgbRange = loadRGBRange(Math.max(width, height), rgbs, positions);
            for (int x=0;x<width;x++){
                for (int y=0;y<height;y++){
                    pixels[x+(height-y-1)*width] = rgbRange[Math.max(x, y)];
                }
            }
        }else if (alignment==PATH_FROM_BOTTOM_RIGHT_CORNER){
            int[] rgbRange = loadRGBRange(Math.max(width, height), rgbs, positions);
            for (int x=0;x<width;x++){
                for (int y=0;y<height;y++){
                    pixels[(width-x-1)+(height-y-1)*width] = rgbRange[Math.max(x, y)];
                }
            }
        }else if (alignment==PATH_FROM_CENTER){
            int[] divArray = divideArray(positions, 2);
            BufferedImage quad1 = new GradientImage(width>>1, height>>1, colors, divArray, GradientImage.PATH_FROM_BOTTOM_RIGHT_CORNER).getImage();
            BufferedImage quad2 = new GradientImage(width>>1, height>>1, colors, divArray, GradientImage.PATH_FROM_BOTTOM_LEFT_CORNER).getImage();
            BufferedImage quad3 = new GradientImage(width>>1, height>>1, colors, divArray, GradientImage.PATH_FROM_TOP_RIGHT_CORNER).getImage();
            BufferedImage quad4 = new GradientImage(width>>1, height>>1, colors, divArray, GradientImage.PATH_FROM_TOP_LEFT_CORNER).getImage();
            Graphics2D g = image.createGraphics();
            g.drawImage(quad1, 0, 0, null);
            g.drawImage(quad2, width>>1, 0, null);
            g.drawImage(quad3, 0, height>>1, null);
            g.drawImage(quad4, width>>1, height>>1, null);
            g.dispose();
        }else if (alignment==PATH_FROM_CORNERS){
            int[] divArray = divideArray(positions, 2);
            BufferedImage quad1 = new GradientImage(width>>1, height>>1, colors, divArray, GradientImage.PATH_FROM_TOP_LEFT_CORNER).getImage();
            BufferedImage quad2 = new GradientImage(width>>1, height>>1, colors, divArray, GradientImage.PATH_FROM_TOP_RIGHT_CORNER).getImage();
            BufferedImage quad3 = new GradientImage(width>>1, height>>1, colors, divArray, GradientImage.PATH_FROM_BOTTOM_LEFT_CORNER).getImage();
            BufferedImage quad4 = new GradientImage(width>>1, height>>1, colors, divArray, GradientImage.PATH_FROM_BOTTOM_RIGHT_CORNER).getImage();
            Graphics2D g = image.createGraphics();
            g.drawImage(quad1, 0, 0, null);
            g.drawImage(quad2, width>>1, 0, null);
            g.drawImage(quad3, 0, height>>1, null);
            g.drawImage(quad4, width>>1, height>>1, null);
            g.dispose();
        }
    }
    public int[] divideArray(int[] array, int div){
        if (array==null){
            return null;
        }
        int[] arr = new int[array.length];
        if (div==2){
            for (int i=0;i<arr.length;i++){
                arr[i] = array[i]>>1;
            }
        }else{
            for (int i=0;i<arr.length;i++){
                arr[i] = array[i]/div;
            }
        }
        return arr;
    }
    public int[] loadRGBRange(int length, int[] rgbs) throws Exception {
        if (rgbs==null){
            throw new Exception("RGB[]'s cannot be null");
        }
        if (length==0){
            throw new Exception("Length cannot be 0");
        }
        if (rgbs.length==0){
            throw new Exception("RGB[]'s length cannot be 0");
        }
        int[] rgbRange = new int[length];
        if (rgbs.length==1){
            for (int i=0;i<rgbRange.length;i++){
                rgbRange[i] = rgbs[0];
            }
            return rgbRange;
        }
        int[] positions = new int[rgbs.length];
        double pos = 0;
        double block = (double) length/(rgbs.length-1);
        for (int i=0;i<positions.length;i++){
            positions[i] = (int) pos;
            pos+=block;
        }
        int[] as = new int[rgbs.length];
        int[] rs = new int[rgbs.length];
        int[] gs = new int[rgbs.length];
        int[] bs = new int[rgbs.length];
        for (int i=0;i<rgbs.length;i++){
            as[i] = (rgbs[i]>>24) & 0xff;
            rs[i] = (rgbs[i]>>16) & 0xff;
            gs[i] = (rgbs[i]>>8) & 0xff;
            bs[i] = (rgbs[i]) & 0xff;
        }
        int[] adifs = new int[rgbs.length-1];
        int[] rdifs = new int[rgbs.length-1];
        int[] gdifs = new int[rgbs.length-1];
        int[] bdifs = new int[rgbs.length-1];
        for (int i=0;i<rgbs.length-1;i++){
            adifs[i] = as[i]-as[i+1];
            rdifs[i] = rs[i]-rs[i+1];
            gdifs[i] = gs[i]-gs[i+1];
            bdifs[i] = bs[i]-bs[i+1];
        }
        double[] ab = new double[rgbs.length-1];
        double[] rb = new double[rgbs.length-1];
        double[] gb = new double[rgbs.length-1];
        double[] bb = new double[rgbs.length-1];
        for (int i=0;i<rgbs.length-1;i++){
            int l = positions[i+1]-positions[i];
            ab[i] = (double) adifs[i]/l;
            rb[i] = (double) rdifs[i]/l;
            gb[i] = (double) gdifs[i]/l;
            bb[i] = (double) bdifs[i]/l;
        }
        double a = as[0];
        double r = rs[0];
        double g = gs[0];
        double b = bs[0];
        int color = 0;
        for (int i=0;i<rgbRange.length;i++){
            rgbRange[i] = ((int)a<<24)|((int)r<<16)|((int)g<<8)|((int)b);
            if (i+1>positions[0] && i+1<positions[positions.length-1]){
                if (i==positions[color+1]){
                    color++;
                    a = as[color];
                    r = rs[color];
                    g = gs[color];
                    b = bs[color];
                }else{
                    a-=ab[color];
                    r-=rb[color];
                    g-=gb[color];
                    b-=bb[color];
                }
            }
        }
        return rgbRange;
    }
    public int[] loadRGBRange(int length, int[] rgbs, int[] positions) throws Exception {
        if (positions==null){
            return loadRGBRange(length, rgbs);
        }
        if (rgbs==null){
            throw new Exception("RGB[]'s cannot be null");
        }
        if (length==0){
            throw new Exception("Length cannot be 0");
        }
        if (rgbs.length==0 || positions.length==0){
            return null;
        }
        if (positions.length!=rgbs.length){
            throw new Exception("The length of Positions[] must equals the length of RGB[]'s");
        }
        for (int i=0;i<positions.length;i++){
            if (positions[i]>length){
                throw new Exception("Any positions cannot be greater than the length");
            }
        }
        int[] rgbRange = new int[length];
        if (rgbs.length==1){
            for (int i=0;i<rgbRange.length;i++){
                rgbRange[i] = rgbs[0];
            }
            return rgbRange;
        }
        int[] as = new int[rgbs.length];
        int[] rs = new int[rgbs.length];
        int[] gs = new int[rgbs.length];
        int[] bs = new int[rgbs.length];
        for (int i=0;i<rgbs.length;i++){
            as[i] = (rgbs[i]>>24) & 0xff;
            rs[i] = (rgbs[i]>>16) & 0xff;
            gs[i] = (rgbs[i]>>8) & 0xff;
            bs[i] = (rgbs[i]) & 0xff;
        }
        int[] adifs = new int[rgbs.length-1];
        int[] rdifs = new int[rgbs.length-1];
        int[] gdifs = new int[rgbs.length-1];
        int[] bdifs = new int[rgbs.length-1];
        for (int i=0;i<rgbs.length-1;i++){
            adifs[i] = as[i]-as[i+1];
            rdifs[i] = rs[i]-rs[i+1];
            gdifs[i] = gs[i]-gs[i+1];
            bdifs[i] = bs[i]-bs[i+1];
        }
        double[] ab = new double[rgbs.length-1];
        double[] rb = new double[rgbs.length-1];
        double[] gb = new double[rgbs.length-1];
        double[] bb = new double[rgbs.length-1];
        for (int i=0;i<rgbs.length-1;i++){
            int l = positions[i+1]-positions[i];
            ab[i] = (double) adifs[i]/l;
            rb[i] = (double) rdifs[i]/l;
            gb[i] = (double) gdifs[i]/l;
            bb[i] = (double) bdifs[i]/l;
        }
        double a = as[0];
        double r = rs[0];
        double g = gs[0];
        double b = bs[0];
        int color = 0;
        for (int i=0;i<rgbRange.length;i++){
            rgbRange[i] = ((int)a<<24)|((int)r<<16)|((int)g<<8)|((int)b);
            if (i+1>positions[0] && i+1<positions[positions.length-1]){
                if (i==positions[color+1]){
                    color++;
                    a = as[color];
                    r = rs[color];
                    g = gs[color];
                    b = bs[color];
                }else{
                    a-=ab[color];
                    r-=rb[color];
                    g-=gb[color];
                    b-=bb[color];
                }
            }
        }
        return rgbRange;
    }
}

A: I use the method at http://real-me.net/ddyer/java/imagedemo/imagedemo.java
to apply arbitrary transparency to corresponding jpg images.  Sorry, there
used to be a demo applet but oracle nuked it in their security mania.  You
can see the method in action in all the games at http://boardspace.net/

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to make a vector that contain all possibilities of characters I want to make a vector which contains all possibilities of specific characters in selected length. For example, characters are A, B, M, and selected length are two, then the output should be AA, AB, AM, BA, BB, BM, MA, MB, MM.
Thank you

A: Try the following approach which would give all the possible combinations of 2-Letters from the given list of letters.
do.call(paste0,expand.grid(rep(list(c('A', 'B', 'M')), 2)))
# [1] "AA" "BA" "MA" "AB" "BB" "MB" "AM" "BM" "MM"


text:
Q: Python CLI tool - general parsing question If possible I would like to use the following structure for a command however I can't seem to figure out how to achieve this in Python:
./somescript.py arg <optional argument> -- "some long argument"
Would it be possible to achieve this in a feasible manner without too much dirty code? Or should I just reconsider the syntax (which is primarily preference).
Thanks!

A: I think optparse can do this.

A: If you don't want to use dashes in front of your arg and optional_argument, that's kind of strange by typical Unix command-line behavior, but I don't understand why every answer appears to believe you have to use the dashes.  Avoiding them is kind of trivial, actually...:
import sys

def before_and_after_doubledashes(args=sys.argv):
    where_doubledashes = args.index('--') if '--' in args else len(args)
    return args[:where_doubledashes], args[where_doubledashes+1:]

This completely ignores whether args start with dashes or not, just singles out the first occurrence of an arg that's exactly a double dash (if any) and returns a tuple of two lists, one all the args that are before that double dash if any, one all the args that are after it (empty if there's no double dash argument).  You can assign these lists from the call:
before, after = before_and_after_doubledashes()

then treat them as you will (check their lengths, assign variables from part of them, etc).

A: You just need to stick something like this on the first line:
    #/usr/local/bin/python
Just make yours be wherever your python binary is located.
As for args look at getopt or optparser
And remember to chmod your file to make it executable.


text:
Q: Returning values for Stored Procedures in PostgreSQL I was reading this on PostgreSQL Tutorials:

In case you want to return a value from a stored procedure, you can use output parameters. The final values of the output parameters will be returned to the caller.

And then I found a difference between function and stored procedure at DZone:

Stored procedures do not return a value, but stored functions return a single value

Can anyone please help me resolve this.
If we can return anything from stored procedures, please also let me know how to do that from a SELECT statement inside the body.
If I am wrong somewhere please inform.

A: Procedure are a new thing in Postgresql as of version 11,   there are two big differences between Procedures and Functions
One Procedures can issue a  commit or rollback and keep processing,  Functions can not issue a commit or rollback.
Functions create an implicit transaction any exception that occurs will cause a rollback, unless there is  an Exception Block
Procedure can return a value via INOUT argument   see create functions how that works
create procedure increase(inout i integer )
LANGUAGE 'plpgsql'
AS $$
begin
    i = i+1;
    return;
end ;
$$;

call increase(1);

2nd biggest difference is
select increase () -- fails with an error
-- must use CALL to use a procedure
call increase (3) ;

Unless there is a need to commit or rollback use Functions, there are more features for calling and return values...

A: Both your sources are plain wrong.

*

*A FUNCTION basically always returns something. void at the minimum, a single value, a row, or a set of rows ("set-returning function", a.k.a. "table-function") - the only variant that can return nothing, i.e. no row. Called from within plpgsql code, you have to actively dismiss results if you don't want them. See:

*

*SELECT raises exception in PL/pgSQL function

*A PROCEDURE (Postgres 11 or later) returns a single row if it has any arguments with the INOUT mode (or OUT mode since in Postgres 14). zsheep provided an example.
Consider a DO statement to run ad-hoc PL/pgSQL code without passing or returning anything.

*

*Use PL/pgSQL in PostgreSQL outside of a stored procedure or function?
To address your core question:

If we can return anything from stored procedures, please also let me know how to do that from a SELECT statement inside the body.

The same way as in functions.
In a PL/pgSQL procedure, assign to the parameter with the INTO keyword:
CREATE PROCEDURE assign_demo(INOUT _val text DEFAULT null)
  LANGUAGE plpgsql AS
$proc$
BEGIN
   SELECT val FROM tbl WHERE id = 2
   INTO _val;                              -- !!!
END
$proc$;

In an SQL procedure the last command returning values determines the return value:
CREATE PROCEDURE lang_sql_demo(INOUT _val text DEFAULT null)
  LANGUAGE sql AS
$proc$
SELECT val FROM tbl WHERE id = 2;
$proc$;

Similar in a standard SQL procedure:
CREATE OR REPLACE PROCEDURE lang_std_sql_demo(INOUT _val text DEFAULT null)
  LANGUAGE sql
BEGIN ATOMIC
SELECT val FROM tbl WHERE id = 2;
END;

See:

*

*What does BEGIN ATOMIC ... END mean in a PostgreSQL SQL function / procedure?
db<>fiddle here
Related:

*

*Struggling to create a "stored procedure" beyond INSERT

*How to return a value from a stored procedure (not function)?


text:
Q: How to ignore AddTrace() for FirebasePerf during testing     @AddTrace(name = "getCustomers")
    override suspend fun getCustomers(isDeleted: Boolean): List<Customer> {}

The code requires FirebaseApp and FirebasePerf but I don't need them. I am mocking the other Firebase properties required.
How would I ignore @addTrace when calling the function during test.


text:
Q: Robot Framework: All subsequent tests fail after one test fails Once one of my robot test fail, all further tests fail, I can't seem to find out why this happens.
I just execute a simple nslookup on my device and check if the output contains the word 'Name:'
Example:
*** Settings ***
Library  SSHLibrary

Suite Setup            Open Connection And Log In
Suite Teardown         Close All Connections

*** Variables ***
${HOST}        localhost
${LOGIN}       testUser
${PASSWORD}    testUser

*** Keywords ***
Open Connection And Log In
    Open Connection     ${HOST}
    Login               ${LOGIN}        ${PASSWORD}

*** Test Cases ***
resolve dns domain on google:
  Write   nslookup qsdf.ft 8.8.4.4
  ${output}=   Read   delay=0.5s
  Should Contain  ${output}  Name:

resolve dns domain google.com:
  Write  nslookup google.com 8.8.4.4
  ${output}=  Read   delay=0.5s
  Should Contain  ${output}  Name:

The first test should fail and the second should pass.
It seems like the first test is stil waiting for its output while the other tests continue
my output on both tests:
'' does not contain 'Name:'


text:
Q: How to get the path from input$.. or output$.. and use it to list.files and then copy/cut the files I am learing Shiny. I want to make a simple app that allows for dynamic paths that the user enters. The app should then list csv files in folder A and then copy them from folder A to folder B (the working directory). Then the app does some operations in folder B using an external exe program. Afterwards the folder will cut the results files (.txt) from B and copies them into A.
The structure of my app is as follows ( I have also attached a picture). the problem is explained in the comments in the code.
library(shiny)

ui<-fluidPage(
  textInput("prg","Program",getwd()),
  verbatimTextOutput("prg"),
  textInput("prj","Project","Project"),
  verbatimTextOutput("prj")
)

server<-function(input, output,session) {
  output$prg=renderText(input$prg)
  renderPrint(output$prg)

  output$prj=renderText(paste0(input$prg,"/",input$prj))

  #This is where my challenge is
  #I want to
  #list.files(path=path-shown-in-text-box-Project,pattern=".csv")
  #Then i want to copy csv files from A to B as described above and run the following program

  #This works
observeEvent(input$run,
                   {
                     system("my.exe") #exe not shared
                   })
#Finally I want to cut and paste the results (.txt) from B back into A

}

shinyApp(ui,server)

I want to list.files(path=path-shown-in-text-box-Project,pattern=".csv")

A: Here's code you can use to browse any directory for a particular CSV file, read that file and display its contents.
library(shiny)

# Define UI
ui <- pageWithSidebar(

  # App title ----
  headerPanel("Open a File and Show Contents"),

  # Sidebar panel for inputs ----
  sidebarPanel(
    label="Data Source",fileInput("fileName", "File Name",accept=c(".csv"))),

  # Main panel for displaying outputs ----
  mainPanel(
    tableOutput(outputId = "table")
  )
)

# Define server logic
server <- function(input, output) {

  inputData <- reactive ({
    if (is.null(input$fileName)) return(NULL)
    inFile <- input$fileName
    conInFile <- file(inFile$datapath,open='read')
    inData <- read.csv(conInFile,stringsAsFactors = FALSE)
    close (conInFile)
  return (inData)
  })

  output$table <- renderTable ({
    inData <- inputData()
    if (length(inData) > 0) inData
  })
}

shinyApp(ui, server)


text:
Q: BeautifulSoup can't find specific table My goal is to parse through a webpage which has 5 possible customers on the page, and get their name from each CustomerTable. Since there is 1 CustomerTable per customer, my thought was to first get the table from within the soup, and then parse through the tables' contents to get the customer's name.
I am getting the html of the web page using Python's request package. When parsing the plain text of the response, I can find the table with the class="CustomerTable" attribute. However, when I do
response = session.get(customersPage)
soup = BeautifulSoup(response.text)
for table in soup.find_all('table'):
  print(table.get('class'))

the table with CustomerTable as the class name is not found. In fact, of the 52 tables that are in the response.text, this snippet prints 'None' only 4 times. Is there a better way to go about my overall goal? And what is causing the tables in this page to not be found? The CustomerTables would have been generated by javascript, so is it possible that this is what causing the table to not be found in the soup?
Sorry I am unable to post the full contents of the webpage, however I can try to give as much context as possible. The contents are through a paid service and bought by my company.


text:
Q: regular expression for start and end of username I need to make regular expression that:

*

*should be at least 6 alphanumeric characters and combine it with symbols

*only symbols allowed are .(dot), -(dash) or _(underscore).

*Must not begin with any symbols.

*Must not end with any symbols.

*Must not include consecutive symbols.
This regex is for first two items on the list ^[a-zA-Z0-9._-]{6,}$
How can I exclude those symbols on start and the end of string?

A: see if this helps
^[a-zA-Z0-9][a-zA-Z0-9.-_]{4,}[a-zA-Z0-9]$

A: Expanding on @Kratnik's answer, to express that the string does not start or end with special characters we can explicitly use the other alternatives. Hence a simpler version:
^[a-zA-Z0-9](?!.*[._-]{2})[\w.-]{4,}[a-zA-Z0-9]$

*

*[a-zA-Z0-9] - alphanumeric at start and end

*(?!.*[._-]{2}) a guarantee that no two special characters follow consequently

*[\w.-]{4,} - 4 or more of the possible characters in the middle


text:
Q: how to use crop and overlay properly? Is crop and overlay have bug when chain too many? i got inconsistent function. for test, i create horizontal flip builder command. i try to flip the video. but its like something wrong with overlay filter. the filter not overlay in specific location.
let me explain my understanding of crop filter first. crop take 4 parameters: width:height:xPosition:yPosition. in first crop=16:480:0:0. how about if i want to crop 2nd image. is right with this crop=16:480:16:0? or it should crop=16:480:17:0 always add 1 after first crop?
and overlay, the first overlay. overlay=x=0:y=0. how about the 2nd overlay and so on? is it right overlay=x=16:y=0 or it should overlay=x=17:y=0. always add 1 after first overlay.
i tested it, always theres glitch in video.
const { spawn } = require('child_process');

function hflip(width) {
    let filterCommands = '';
    const length = Math.floor(width / 16);

    for (let i=0; i < length; i++) {
        filterCommands += `[0]crop=16:480:${i*16}:0[c${i}];`;
    }

    for (let i=0; i < length; i++) {
        if (i == 0) filterCommands += '[0]';
        if (i != 0) filterCommands += `[o${i}]`;

        filterCommands += `[c${i}]overlay=x=${832-(i*16)}:y=0`;

        if (i != (length - 1)) filterCommands += `[o${i+1}];`;
    }

    return filterCommands;
}

const crops = spawn('ffmpeg', [
    '-i',
    'C:/Software Development/project/input.mp4',
    '-filter_complex',
    hflip(854),
    '-c:a',
    'copy',
    '-c:v',
    'libx264',
    '-crf',
    '30',
    '-preset',
    'ultrafast',
    'C:/Software Development/project/output.mp4',
    '-y'
], {
    cwd: 'C:/Software Development/ffmpeg'
})


text:
Q: Can I delete an SSH key? I have accidentally generated a pair of SSH key and saved in in my local file. I will not use them for any function. Can I just delete the private key and public key file? Will that cause any problem to my computer?
I have done a few research but no one telling me will it cause any problem to my computer.


text:
Q: How to convert ElasticSearch query to ES7 We are having a tremendous amount of trouble converting an old ElasticSearch query to a newer version of ElasticSearch. The original query for ES 1.8 is:
{
  "query": {
    "filtered": {
      "query": {
        "query_string": {
          "query": "*",
          "default_operator": "AND"
        }
      },
      "filter": {
        "and": [
          {
            "terms": {
              "organization_id": [
                "fred"
              ]
            }
          }
        ]
      }
    }
  },
  "size": 50,
  "sort": {
    "updated": "desc"
  },
  "aggs": {
    "status": {
      "terms": {
        "size": 0,
        "field": "status"
      }
    },
    "tags": {
      "terms": {
        "size": 0,
        "field": "tags"
      }
    }
  }
}

and we are trying to convert it to ES version 7. Does anyone know how to do that?

A: The Elasicsearch docs for Filtered query in 6.8 (the latest version of the docs I can find that has the page) state that you should move the query and filter to the must and filter parameters in the bool query.
Also, the terms aggregation no longer support setting size to 0 to get Integer.MAX_VALUE. If you really want all the terms, you need to set it to the max value (2147483647) explicitly. However, the documentation for Size recommends using the Composite aggregation instead and paginate.
Below is the closest query I could make to the original that will work with Elasticsearch 7.
{
  "query": {
    "bool": {
      "must": {
        "query_string": {
          "query": "*",
          "default_operator": "AND"
        }
      },
      "filter": {
        "terms": {
          "organization_id": [
            "fred"
          ]
        }
      }
    }
  },
  "size": 50,
  "sort": {
    "updated": "desc"
  },
  "aggs": {
    "status": {
      "terms": {
        "size": 2147483647,
        "field": "status"
      }
    },
    "tags": {
      "terms": {
        "size": 2147483647,
        "field": "tags"
      }
    }
  }
}


text:
Q: Facebook Pixel No Catalog Events I have Pixel installed on my website. My Catalog is updated. Pixel Helper is showing events with a blue check.  Event manager is showing all the events with right parameters. Still there are no events in Catalog Manager->Events Tab. My Pixel is connected to the catalog.
Catalog Events:

Check Standard Code on Catalog Event:

Events Manager Showing events:

Pixel Helper Showing Events:

A: Facebook says that it might take upto 24hrs for the pixel to update or setup. I waited for the given time but still had no events showing but apparently it can take even more time so, I finally started seeing those events in Catalog Manager after 3 days of initial setup.


text:
Q: Python dict.update vs initializing completely in starting I have to define a dict with about 50,000 keys and value -1. Each key is updated based on if condition. Also not all keys will be updated.
One way to do this is to initialize complete dict and then use for loop to update values.
Another way can be to initialize an empty dict and then update it only for values updated.
My question is whether it takes same amount of time/computation to initialize a very large dict or update it on the fly. Is update too much expensive ?

A: You could use a defaultdict which in the case of a missing key, returns a default value.
Note: defaultdict needs a callable for initialization, that's why I use this lambda function,
which simply returns the initialization value.
from collections import defaultdict
def_dict = defaultdict(lambda:-1)
def_dict[500] = 2

print(def_dict[0])
print(def_dict[500])

So instead of iterating all 50.000 keys to initialize them, you could just iterate the desired subset, without worrying about the rest.
Output:
-1
2


text:
Q: Why do I get an Segmentation fault error My code works fine on codeblocks compiler on my computer but when I upload it to an online editor I get an Segmentation fault error and I don't know why.
#include <iostream>
#include <string.h>
#include <stdlib.h>
#include <fstream>
using namespace std;
int main(int argc, char *argv[]) {
    ifstream stream(argv[1]);
    char line[1000];
    int x,last=-1;
    while (stream>>line)
    {
        x = atoi(strtok(line,","));
        cout<<x;
        last=x;
        while(x=atoi(strtok(NULL,",")))
        {
            if(x!=last)
            {
                cout<<","<<x;
                last=x;
            }
        }
        cout<<endl;
    }
    return 0;
}

You are given a sorted list of numbers with duplicates. Print out the sorted list with duplicates removed.

And this is the input
6,7,8,9,9,10,11,12,13,14,15
11,12,13,14,15,16,17,18,19,20
2,2,2,2,2
10,11,12,13,14,15,16,16,17
13,14,14,15,16,17,17,17,18
15,16,17,17,18,18,18,18,19,19,20
2,3,4,5,5
13,14,15,16,17
10,11,12,13,14,15,15,15,15,16,16,16
12,13,14,15,16,17,17,18
5,6,7,8,9,10,11
14,14,14,15,15,16,17,17,18,19,19,20,21,22
13,14,15,16,16,17,17,18
15,16,17,18,19,20,21,21,21,21,22,22
6,6,6,7,8,9,10,11,11,11,12,12,13
12,12,13,14,15,15,16,17,17,18,19,19,20,21
8,9,9,9,10,10,11,12,13,13,14,15
12,13,14,15,16,17,18
1,1,1,2,2,3,3,4,4
1,2,3,4

A: Since you're asking us to guess, let's start at the top ....
The code doesn't check that argv[1] is valid. If not, then you just dereferenced a null-pointer, and that caused your segmentation fault.
Does your "online editor" pass parameters? I suggest checking argc > 1.

Next, your code looks like it will pass a null pointer to atoi at the end of every line. That's another segmentation fault.

A: You are calling atoi with the result of strtok.
If strtok doesn't find anything it returns a null pointer.
This is the case at the end of the line.
So you are passing a null pointer to atoi which then leads to a crash.
Using your example this should work:
    #define  _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string.h>
#include <stdlib.h>
#include <fstream>

using namespace std;
int main(int argc, char *argv[])
{
    ifstream stream(argv[1]);
    char line[1000];
    char* ln;
    char* num;
    int x;
    int last;

    while (stream >> line)
    {
        ln = line;
        last = -1;
        while (num = strtok(ln, ","))
        {
            x = atoi(num);
            if (x != last)
            {
                if(last != -1) cout << "," << x;
                else cout << x;
                last = x;
            }
            ln = NULL;
        }
        cout << endl;
    }
    return 0;
}

EDIT: Another solution with checking for valid paramters and w/o strtok and atoi:
#define  _CRT_SECURE_NO_WARNINGS

#include <iostream>
#include <string.h>
#include <stdlib.h>
#include <fstream>

using namespace std;
int main(int argc, char *argv[])
{
    if (argc < 2) {
        cout << "Usage: " << argv[0] << " <file>";
        return 1;
    }

    ifstream stream(argv[1]);
    if (!stream.is_open())
    {
        cout << "Failed to open file \"" << argv[1] << "\"";
        return 2;
    }

    char line[1000];
    while (stream >> line)
    {
        int last = -1;
        int x = 0;
        for (char* pos = line; pos < line + strlen(line); pos++)
        {
            if (*pos >= '0' && *pos <= '9')
            {
                x = (x * 10) + (*pos - '0');
            }
            else
            {
                if (last != x)
                {
                    if (last != -1) {
                        cout << ',';
                    }
                    cout << x;
                    last = x;
                }
                x = 0;
            }
        }
        cout << endl;
    }
    return 0;
}


text:
Q: JMS with CompletableFuture I'm stuck when using Java's CompletableFuture with JMS (ActiveMQ). When I send a request for which I expect a reply, I create a CompletableFuture and put that in a Map with the correlation ID as key.
This works perfectly as long as I get a reply. When I don't get a reply, zombie start to pile up in the map.
I tried to attach cleanup code to CompletableFuture using whenComplete() but the code isn't called at all when CompletableFuture.get(long,TimeUnit) times out (the Java code in timedGet() will just throw the exception without calling anything else).
This looks like such an obvious place to use the Future API. Does someone have a working example or an idea how to clean up dead entries in the map?
Note: It can take up to three hours until the response arrives.
Note 2: Java 8


text:
Q: Cart bulk quantity discount for specific products in Woocommerce In woocommerce I am trying to make a custom cart item quantity discount for a specific product ID only.  This is what I am trying to do:
If a customer add to cart a specific product, I would like to keep the original price for the first item and set a discounted custom price for each additional item quantity.
For example:

*

*The product active price is 40 (we keep this price for 1st quantity item)

*For quantities up to 2 (additional items quantity) the price is 12.

So if customer add the product with a quantity 5 items, then the price will be:
40 + 12 + 12 + 12 + 12 = 88
So I tried changing this answer code  a bit:
Cart item quantity progressive percentage discount in Woocommerce 3
But couldn't make it work correctly.
Any help is appreciated.

A: For your case use the following instead:
add_filter('woocommerce_add_cart_item_data', 'add_items_default_price_as_custom_data', 20, 3 );
function add_items_default_price_as_custom_data( $cart_item_data, $product_id, $variation_id ){

    ## Your settings her below ##
    $product_ids = array(37); // <=== Your specific product(s) ID(s) in the array
    $discounted_price = 12; // <=== The specific product discounted price

    // The WC_Product Object
    $product = wc_get_product($variation_id > 0 ? $variation_id : $product_id);

    if( array_intersect( $product_ids, array($product_id, $variation_id) ) && ! $product->is_on_sale() ){
        // We set the Product discounted price
        $cart_item_data['pricing']['discounted'] = $discounted_price;

        // Set the Product default base price as custom cart item data
        $cart_item_data['pricing']['active'] = $product->get_price();
    }

    return $cart_item_data;
}

// Display the product original price
add_filter('woocommerce_cart_item_price', 'display_cart_items_default_price', 20, 3 );
function display_cart_items_default_price( $product_price, $cart_item, $cart_item_key ){
    if( isset($cart_item['pricing']['active']) && $cart_item['quantity'] > 1 ) {
        $product_price  = wc_price( wc_get_price_to_display( $cart_item['data'], array( 'price' => $cart_item['pricing']['active'] ) ) );
    }
    return $product_price;
}

// Display the product name with the a custom "discount" label
add_filter( 'woocommerce_cart_item_name', 'append_custom_label_to_item_name', 20, 3 );
function append_custom_label_to_item_name( $product_name, $cart_item, $cart_item_key ){
    if( isset($cart_item['pricing']['discounted']) && $cart_item['data']->get_price() != $cart_item['pricing']['discounted'] ) {
        $discounted_price = (float) $cart_item['pricing']['discounted'];
        $default_price    = (float) $cart_item['pricing']['active'];
        $quantity         = (int)   $cart_item['quantity'];

        // Calculate new product price
        $new_price = ($default_price + ($discounted_price * ($quantity - 1))) / $quantity;

        // Get the discount percentage (if needed)
        $percent = 100 - ($new_price / $default_price * 100);

        $product_name .= ' <em>(' . __('quantity discounted', 'woocommerce') . ')</em>';
    }
    return $product_name;
}

// Set the new discounted price
add_action( 'woocommerce_before_calculate_totals', 'set_custom_discount_cart_item_price', 25, 1 );
function set_custom_discount_cart_item_price( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;

    foreach( $cart->get_cart() as $cart_item ){

        // For items non on sale set a discount based on quantity
        if( isset($cart_item['pricing']['discounted']) && $cart_item['quantity'] > 1 ) {
            $discounted_price = (float) $cart_item['pricing']['discounted'];
            $default_price    = (float) $cart_item['pricing']['active'];
            $quantity         = (int)   $cart_item['quantity'];

            // Calculate new product price
            $new_price = ($default_price + ($discounted_price * ($quantity - 1))) / $quantity;

            // Set cart item calculated price
            $cart_item['data']->set_price($new_price);
        }
    }
}

Code goes in function.php file of your active child theme (or active theme). Tested and works.


text:
Q: Xcode cannot compile if there are too many modifiers I have noticed that Xcode fails to compile with
The compiler is unable to type-check this expression in reasonable time; try breaking up the expression into distinct sub-expressions
You can execute the below demo project to recreate the error. Once you uncomment confirmationDialog entries 11+ it fails to compile.
//
//  ContentView.swift
//  confDialogTest
//
//  Created by Max on 13.06.22.
//

import SwiftUI

struct ContentView: View {
    @State private var showingConf1 = false
    @State private var showingConf2 = false
    @State private var showingConf3 = false
    @State private var showingConf4 = false
    @State private var showingConf5 = false

    var body: some View {
        Button(role: .destructive) {

            self.showingConf1.toggle()
        } label: {
            Label("Conf 1", systemImage: "trash.fill")
        }
        .padding()
        Button(role: .destructive) {

            self.showingConf2.toggle()
        } label: {
            Label("Conf 2", systemImage: "trash.fill")
        }
        .padding()
        Button(role: .destructive) {

            self.showingConf3.toggle()
        } label: {
            Label("Conf 3", systemImage: "trash.fill")
        }
        .padding()
        Button(role: .destructive) {

            self.showingConf4.toggle()
        } label: {
            Label("Conf 4", systemImage: "trash.fill")
        }
        .padding()

        Button(role: .destructive) {

            self.showingConf5.toggle()
        } label: {
            Label("Conf 5", systemImage: "trash.fill")
        }
//        .padding()
        .confirmationDialog("Select location", isPresented: $showingConf1, titleVisibility: .visible) {
            Text("Conf")
        }
        .confirmationDialog("Select location", isPresented: $showingConf2, titleVisibility: .visible) {
            Text("Conf")
        }
        .confirmationDialog("Select location", isPresented: $showingConf3, titleVisibility: .visible) {
            Text("Conf")
        }
        .confirmationDialog("Select location", isPresented: $showingConf4, titleVisibility: .visible) {
            Text("Conf")
        }
        .confirmationDialog("Select location", isPresented: $showingConf5, titleVisibility: .visible) {
            Text("Conf")
        }
        //next group is dialogs 6-10
        .confirmationDialog("Select location", isPresented: $showingConf5, titleVisibility: .visible) {
            Text("Conf")
        }
        .confirmationDialog("Select location", isPresented: $showingConf5, titleVisibility: .visible) {
            Text("Conf")
        }
        .confirmationDialog("Select location", isPresented: $showingConf5, titleVisibility: .visible) {
            Text("Conf")
        }
        .confirmationDialog("Select location", isPresented: $showingConf5, titleVisibility: .visible) {
            Text("Conf")
        }
        .confirmationDialog("Select location", isPresented: $showingConf5, titleVisibility: .visible) {
            Text("Conf")
        }
        //next group is dialogs 11-15
//        .confirmationDialog("Select location", isPresented: $showingConf5, titleVisibility: .visible) {
//            Text("Conf")
//        }
//        .confirmationDialog("Select location", isPresented: $showingConf5, titleVisibility: .visible) {
//            Text("Conf")
//        }
//        .confirmationDialog("Select location", isPresented: $showingConf5, titleVisibility: .visible) {
//            Text("Conf")
//        }
//        .confirmationDialog("Select location", isPresented: $showingConf5, titleVisibility: .visible) {
//            Text("Conf")
//        }
//        .confirmationDialog("Select location", isPresented: $showingConf5, titleVisibility: .visible) {
//            Text("Conf")
//        }
        //next group is dialogs 16-20
//        .confirmationDialog("Select location", isPresented: $showingConf5, titleVisibility: .visible) {
//            Text("Conf")
//        }
//        .confirmationDialog("Select location", isPresented: $showingConf5, titleVisibility: .visible) {
//            Text("Conf")
//        }
//        .confirmationDialog("Select location", isPresented: $showingConf5, titleVisibility: .visible) {
//            Text("Conf")
//        }
//        .confirmationDialog("Select location", isPresented: $showingConf5, titleVisibility: .visible) {
//            Text("Conf")
//        }
//        .confirmationDialog("Select location", isPresented: $showingConf5, titleVisibility: .visible) {
//            Text("Conf")
//        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Whiel it is easy to fix here if I just move some confirmationDialogs to another Button view, I have the same problem in another problem where I have to add many modifiers to a NavigationLink in a List View and there I cannot move it around ... :/
Any ideas what to do here?

A: Think I found the root cause of the issue. In my other project with the same problem, I have a structure like
Zstack{
  List{
    ForEach(sectionArray){
      Section{
        ForEach(array){
          NavigationLink{
            RowView
          }
          .confirmationDialog()
        }
      }
    }
  }
}

so I was attaching the confirmationDialog to every single NavigationLink and that seems to have killed it. Once I rearranged it to
Zstack{
  List{
    ForEach(sectionArray){
      Section{
        ForEach(array){
          NavigationLink{
            RowView
          }
        }
      }
    }
  }
}
.confirmationDialog()

the problem was gone.


text:
Q: REDIS-STACK FT SEARCH with hypen as special character not working I am implementing redis stack search in which my keys has some special character ,
Below is java code for creating schema of the index:
Client client = new Client("my_queue", "localhost", 6379,10000,100,"mypassword");

    Schema sc = new Schema()
            .addSortableNumericField("id")
            .addSortableNumericField("task_id")
            .addSortableNumericField("org_id")
            .addSortableTextField("callsid", 5.0)
            .addSortableTextField("request_id", 10.0)
            .addSortableTextField("status", 15.0)
            .addSortableTextField("source", 20.0)
            .addSortableTextField("message", 25.0)
            .addSortableTextField("created_at", 30.0)
            .addSortableTextField("updated_at", 35.0)
            .addSortableTextField("scheduled_at", 40.0)
            .addSortableTextField("completed_at", 45.0)
            .addSortableTextField("processed_at", 50.0)
            .addSortableNumericField("retry_count");;

    client.createIndex(sc, Client.IndexOptions.Default());
    client.close();

I have inserted five key as below :

*

*"1266ab40-1025-43be-9a75-c803a8e9f83c"

*"37910e73-23dd-4f37-99bf-020cf532493f"

*"28e04d99-eeb2-48ce-8deb-7ed6b22134bf"

*"fe656174-2959-44ef-b952-2fb4cd96b143"

*"06f2b6d1-f4a6-4dbd-9615-01e0e26441ce"

When i am running the command as below ,
127.0.0.1:6379> FT.SEARCH my_queue "1266ab40-1025-43be-9a75-c803a8e9f83c"
1) (integer) 0
127.0.0.1:6379> FT.SEARCH my_queue 1266ab40-1025-43be-9a75-c803a8e9f83c
1) (integer) 0
127.0.0.1:6379> FT.SEARCH my_queue "1266ab40\-1025\-43be\-9a75\-c803a8e9f83c"
1) (integer) 0
127.0.0.1:6379> FT.SEARCH my_queue "1266ab40\-\1025\-\43be\-9a75\-\c803a8e9f83c"
1) (integer) 0
127.0.0.1:6379> FT.SEARCH my_queue "1266ab40\-\1025\-\43be\-9a75\-\c803a8e9f83c"

i am not able to get the expected output. How can i search the key with special characters ?


text:
Q: speed up a sql query to mysql? in my mysql database i've got the geonames database, containing all countries, states and cities.
i am using this to create a cascading menu so the user could select where he is from: country -> state -> county -> city.
but the main problem is that the query will search through all the 7 millions rows in that table each time i want to get the list of children rows, and that is taking a while 10-15 seconds.
i wonder how i could speed this up: caching? table views? reorganizing table structure somehow?
and most important, how do i do these things? are there good tutorials you could link to me?
i appreciate all help and feedback discussing smart ways of handling this issue!
UPDATE: here is my table structure:
CREATE TABLE `geonames_copy` (
  `geoname_id` mediumint(9) NOT NULL,
  `parent_id` mediumint(9) DEFAULT NULL,
  `name` varchar(200) DEFAULT NULL,
  `ascii_name` varchar(200) DEFAULT NULL,
  `alternate_names` varchar(4000) DEFAULT NULL,
  `latitude` decimal(10,7) DEFAULT NULL,
  `longitude` decimal(10,7) DEFAULT NULL,
  `feature_class` char(1) DEFAULT NULL,
  `feature_code` varchar(10) DEFAULT NULL,
  `country_code` varchar(2) DEFAULT NULL,
  `cc2` varchar(60) DEFAULT NULL,
  `admin1_code` varchar(20) DEFAULT NULL,
  `admin2_code` varchar(80) DEFAULT NULL,
  `admin3_code` varchar(20) DEFAULT NULL,
  `admin4_code` varchar(20) DEFAULT NULL,
  `population` bigint(20) DEFAULT NULL,
  `elevation` int(11) DEFAULT NULL,
  `gtopo30` smallint(6) DEFAULT NULL,
  `time_zone` varchar(40) DEFAULT NULL,
  `modification_date` date DEFAULT NULL,
  PRIMARY KEY (`geoname_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

and here is the sql query:
            $query = "SELECT geoname_id, name
                    FROM geonames
                    WHERE parent_id = '$geoname_id'
                    AND (feature_class = 'A')";

should i just create index for 2 columns: parent_id and feature_class?
one question: isn´t it better to create an index with solr instead of using mysql? one benefit is that im already using solr and another is that it supports full text search. so maybe it's better so i dont use both solr and mysql (2 things to be good at)?

A: As mentioned, more info would be helpful (Sql, database structure).
The AJAX suggestion is a good one, though you could also do this without ajax.
Do NOT execute a select at any point that selects all of the data. This will be extremely slow.
First, populate the only list of countries. Allow the user to make a selection from this list. After the user selects a country, either via AJAX, or by refreshing the entire page, populate the list of states for that country only - something like (select state from geonames where country = @country). When the user selects a state, populate the list of counties for that country and state - something like (select country from geonames where country = @country and state = @state). Continue in this manner for the city.
I'm not very familiar with MySql, but in SqlServer I would create an index on (Country, State, County, City) to speed up this set of queries. I'm not sure if MySql would be able to accelerate the entire set of queries with this index or not.
Of course, I'm making some assumptions about how your data is structured here, so this info may or may not be relevant.

A: Post your SQL for a better reply, but in general:

*

*Make indexes on fields that you do joins/wheres on.

*Do not use "SELECT *" -- only select the fields you need.

*Hydrate as arrays instead of objects.

Also, if the menu never changes, cache the HTML in a file. You could even only cache the country/state HTML, then fetch cities via AJAX if they change often.

A: I believe stuff like this is usually done with AJAX. At the beginning, you only load the country names, and after one is selected, you dynamically load the state names in that country, then repeat for each subdivision after that.

A: This is a good scenario for partitioning a table and even having sub-partitions.  You could partition the table by country, and then sub-partitioning by state.  This will significantly reduce the amount of data your query will have to search through as huge segments of data can be removed from the execution plan.
Here is a good place to start for information on MySQL partitioning.
Along with the partitioning (and even if you choose not to partition), you'll want to create indexes on the columns your searching on as this will further enhance the performance of the queries.
Here is the MySQL documentation on HOW to create indexes, but really the tough part about making indexes is knowing what to index.  Typically you'll target the columns that show up in the WHERE clauses in your query or on columns you JOIN on.  This is pretty general, and you don't (and in many cases shouldn't) have to index every column in your where clauses, but this is a good place to start.  Based on the limited data given in the question, you will most likely want a composite index on country and region in order to speed the selection of the cities.  You'll want to use explain plan in order to determine when an index is necessary and whether or not it is actually being used by the query.  Do a search on SO for "MySQL indexing" and you'll find more than enough information on the when, where, and hows of indexing tables.
If you haven't already, it will help to normalize your data.  For example, if your table currently looks something like:
usa;fl;miami;....
usa;fl;orlando;....

It should be changed to something like:
COUNTRY Table:
--------------
COUNTRY_KEY            1
THREE_LETTER           'usa'
COUNTRY_NAME           'united states'
..OTHER COLUMNS....

REGION Table:
--------------
COUNTRY_KEY            1
REGION_KEY             10
REGION_CODE            'fl'
REGION_NAME            'florida'
..OTHER COLUMNS....

CITY Table:
--------------
REGION_KEY             10
CITY_KEY               20
CITY_NAME              'miami'
LAT                    123.12
LONG                   123.12
..OTHER COLUMNS----

From the standpoint of the UI, you'll want to write it in a manner where you're only populating the data necessary and then generating the other data entry points with the matching criteria.  So on initial load, you'll populate the country input with a:
SELECT country_key, three_letter
FROM COUNTRY
ORDER BY three_letter;

When the user selects the country they are interested in, then you select out all the regions with that country key.
SELECT region_key, region_code
FROM REGION WHERE country_key = :input_country_key
ORDER BY region_code;

So on and so forth until you retrieve the users data.
Hope this helps.

A: ALTER TABLE geonames_copy ADD INDEX (parent_id, feature_class);

should do the trick.  An index on just parent_id will probably work fine as well.


text:
Q: The connection to the server localhost:8080 was refused - did you specify the right host or port? I created a second context in my local kind-cluster:
The first context works:
kubectl get pods

NAME                                              READY   STATUS    RESTARTS      AGE
dashboard-kubernetes-dashboard-76bd8dc445-wp9l6   1/1     Running   5 (26h ago)   10d
foo-5c9ff58bf4-c5mgh                              1/1     Running   3 (26h ago)   14d

I created a second context, but this can't connect:
kubectl --context=DevDan-context get pods

The connection to the server localhost:8080 was refused - did you specify the right host or port?

What could be wrong?

A: I found the solution by looking at .kube/config
apiVersion: v1
clusters:
- cluster:
    certificate-authority-data: LS...==
    server: https://127.0.0.1:43437
  name: kind-kind
contexts:
- context:
    cluster: kubernetes
    namespace: development
    user: DevDan
  name: DevDan-context
- context:
    cluster: kind-kind
    user: kind-kind
  name: kind-kind
...

The DevCan context uses a cluster called "kubernetes", while the other context uses the "kind-kind".
The cluster "kubernetes" is not configured in the config. After changing it to "kind-kind" it worked.
It is a bit strange, that kubectl does not complain, that the cluster named "kubernetes" is not configured. It seems to default to localhost:8080.


text:
Q: GWT Request Factory - Several entity locators for the same entity type I want to be able to use different entity locators for the same domain object. I use Twig and it has an option to load an object fully or partially. When I run the lite request fetchRangeLite, the locator TwigLocator is used instead of TwigLiteLocator. My current implementation is:
Proxies
@ProxyFor(value = MyDomain.class, locator = TwigLocator.class)
public interface MyDomainProxy extends EntityProxy {}

@ProxyFor(value = MyDomain.class, locator = TwigLiteLocator.class)
public interface MyDomainLiteProxy extends EntityProxy {}

Request
@Service(value = MyDao.class, locator = DaoServiceLocator.class)
public interface MyRequest extends RequestContext {
    Request<List<MyDomainProxy>> fetchRange(Integer start, Integer length);
    Request<Integer> getCount();
    Request<List<MyDomainLiteProxy>> fetchRangeLite(Integer start, Integer length);
}

DAO
public List<MyDomain> fetchRange(Integer start, Integer length) {
  ...
}

public List<MyDomain> fetchRangeLite(Integer start, Integer length) {
  ...
}

I was expecting the lite locator to be used but it's not the case. So how does RF choose which locator it should use for a specific domain type?
UPDATE
My domain object is composed by list of lists.
public class MyDomain extends DatastoreObject {
  private List<A> a;
}

public class A {
  private List<B> b;
}

When a proxy of my MyDomain object is sent from the server to the client, Twig also loads all the A's and all the B's which takes time. I am only interested by a property in the MyDomain object, that's why I want to use a "lite" locator.
TwigLocator
@Override
public DatastoreObject find(Class< ? extends DatastoreObject> clazz, Long id) {
    ObjectDatastore myDatastore = datastoreProvider.get();
    DatastoreObject object = myDatastore.load(clazz, id);
    return object;
}

TwigLiteLocator
@Override
public DatastoreObject find(Class< ? extends DatastoreObject> clazz, Long id) {
    ObjectDatastore myDatastore = datastoreProvider.get();
    myDatastore.setActivationDepth(0);
    DatastoreObject object = myDatastore.load(clazz, id);
    return object;
}

myDatastore.setActivationDepth(0); tells the datastore to load only the properties in MyDomain and not the sublevel (List) properties.
The DAO implementation is the same, so the ID and version are the same for both proxies.

A: I'm not sure why RF isn't using the "lite" locator, but I'm not sure why it could be an issue either: shouldn't the ID and version be the same for MyDomain whichever the proxy being used?
Actually, I don't understand why you do need two different locators in this case: the "complete" or "lite" fetches are done in your DAO, not in the locators. The only reason for having two distinct locators would be to implement find differently, when a proxy is sent from the client to the server (find is also used by the default implementation of isLive but it's generally a good idea to override it with your own implementation, unless the default one is already the "best optimized" one: find(obj.getClass(), getId(obj)) != null)


text:
Q: Rails 2.1 belongs_to primary key I have a basic database with a structure like this.
products
------------------
id
serial

order
------------------
id
product_serial

Unfortunately, I cannot change structure of the DB. I looked at the docs for Rails 2.1 and it said I could setup a relationship like this.
belongs_to :product,
           :class_name => 'Product',
           :foreign_key => 'product_serial',
           :primary_key => 'serial'

However, that gives me this error.
Unknown key: primary_key

Without the primary key it produces this SQL
SELECT * FROM `products` WHERE (`products`.`id` = #{serial})

How do I setup a belongs_to relationship on this?
EDIT For the record, I am working in Rails 2.1. (I know, don't tell me).

A: If you check the available options for the belongs_to association for the Rails 2 branch, you'll see that :primary_key is not one of them.
It should be enough, in your case, to simply state the foreign key as you did in the previous line.

A: Your order model does not have a field (and thus method) which is called serial. You don't need to specify it, then it defaults to id (which you do have).


text:
Q: Как понять, что присылает подписка Xsi-events АТС Билайн на указанный для нее URL? Оформлена подписка Xsi-event через PUT запрос в API АТС Билайн. В параметре URL был указан адрес, который принимает POST запросы. Сервер на NodeJs(Express). Когда происходят звонки, подписка отправляет пустое тело запроса. Как получать информацию о звонке? Или как разобрать тот запрос, что она присылает.

A: Пустым тело запроса было, потому что ответ приходил потоком. Формировать данные нужно было посло того, как заканчивается поток. В среде NodeJs + Express это выглядит так
app.post('/path/to/api', (request, response)=>{
    response.status(200); // ответ должен быть обязательно со статусом 200
    let body = '';
    request.on('data', (chunk) => {
        body += chunk;
    });
    request.on('end', () => {
        response.write('OK');
        response.end();
    });
})

Проблема для среды NodeJS и программирования на Js заключается в том, что ответ приходит в формате XML. Для удобной обработки информации, можно использовать конвертер в json формат. Дополнив код, получим следующее:
app.post('/api/beeline/subscription', (request, response)=>{
    console.log(request.method, request.url, request.headers);
    console.log("------------------------------");
    response.status(200);
    let body = '';
    request.on('data', (chunk) => {
        body += chunk;
    });
    request.on('end', () => {
        let option = {
            elementNameFn: function(val) {return val.replace('xsi:','');},
            compact: true,
            spaces: 4,
            ignoreInstruction:true,
            ignoreDeclaration: true,
            ignoreAttributes: true,
            ignoreCdata:true,
            instructionHasAttributes: true,
            textKey: 'text'
        }
        let body_JSON = convert.xml2json(body, option);
        response.write('OK');
        response.send();
    });
})


text:
Q: Endless Errors when trying to set cors on azure storage account / Blob I am trying to set up cors on an azure storage blob account, that I have added a CDN to.
the reason is so that I can serve the web fonts from there and get the caching.
I have installed latest software from nuget:
Successfully added 'Microsoft.Data.Services.Client 5.6.0' to Impulse.
Adding 'Microsoft.WindowsAzure.ConfigurationManager 1.8.0.0' to Impulse.
Successfully added 'Microsoft.WindowsAzure.ConfigurationManager 1.8.0.0' to Impulse.
Adding 'WindowsAzure.Storage 4.2.1' to Impulse.
Successfully added 'WindowsAzure.Storage 4.2.1' to Impulse.
I have then used this C# code :
private void AzureCors()
        {
            CloudStorageAccount storageAccount = new CloudStorageAccount(new StorageCredentials("removed","removed"), true);
            var blobClient = storageAccount.CreateCloudBlobClient();
            ServiceProperties blobServiceProperties = new ServiceProperties();
            blobServiceProperties.Cors.CorsRules.Add(new CorsRule(){
                AllowedHeaders = new List<string>() { "*" },
                AllowedMethods = CorsHttpMethods.Put | CorsHttpMethods.Get | CorsHttpMethods.Head | CorsHttpMethods.Post,
                AllowedOrigins = new List<string>() { "*" },
                ExposedHeaders = new List<string>() { "*" },
                MaxAgeInSeconds = 3600 // 30 minutes
            });

            blobClient.SetServiceProperties(blobServiceProperties);
        }

This first error is The logging version is null or empty.    however this according to MS is no longer required, but I added it anyway.   Then I get an error that the Metrics Version is null or empty, however this too is not supposed to be required, but not only that, but is actually discontinued from 4.2.1 and I am unable to set metrics anyway, and the code to now use is HourMetrics, however, filling in an hour metrics still gives an error for metrics.
So what is going on, how the hell am I supposed to connect to azure storage, if none off the libraries actually work?
as a sidenote   I have installed the latest azure SDK into visual studio 2013 Yesterday
not sure if this could be an issue?

A: Try this code:
    private void AzureCors()
    {
        CloudStorageAccount storageAccount = new CloudStorageAccount(new StorageCredentials("removed", "removed"), true);
        var blobClient = storageAccount.CreateCloudBlobClient();
        ServiceProperties blobServiceProperties = new ServiceProperties()
        {
            HourMetrics = null,
            MinuteMetrics = null,
            Logging = null,
        };
        blobServiceProperties.Cors.CorsRules.Add(new CorsRule()
        {
            AllowedHeaders = new List<string>() { "*" },
            AllowedMethods = CorsHttpMethods.Put | CorsHttpMethods.Get | CorsHttpMethods.Head | CorsHttpMethods.Post,
            AllowedOrigins = new List<string>() { "*" },
            ExposedHeaders = new List<string>() { "*" },
            MaxAgeInSeconds = 3600 // 30 minutes
        });

        blobClient.SetServiceProperties(blobServiceProperties);
    }

Basically when you create an instance of ServiceProperties, all properties like HourMetrics etc. get initialized. What you need to do is forcefully set the properties you don't want to change to null and this is what I did in the constructor.


text:
Q: Application of neural network for use with log file data I've been following Andrew NG's coursera AI course , specifically the section on neural networks and I'm planning on implementing a neural network on log file data.
My log file contains data of this type :
<IP OF MACHINE INITIATING REQUEST><DATE OF REQUEST><TIME OF REQUEST><NAME OF RESOUCE BEING ACCESSED ON SERVER><RESPONSE CODE><TIME TAKEN FOR SERVER TO SERVE PAGE>

I'm aware there are other classification algorithms that could be used for this task such as naïve bayes and local outlier factor but want to gain exposure with neural networks using a real world applicable problem.
I have read about neural network self-organizing maps and this seems to be more suited to this type of problem as the log file does not have any structure, but seems to be a more advanced topic.
Instead of using a self-organizing map neural network I plan to create the training data from log file data by grouping the data into a key value pair where the key is the <IP OF MACHINE INITIATING REQUEST> and the value for each key is [<NAME OF RESOUCE BEING ACCESSED ON SERVER>, ><TIME TAKEN FOR SERVER TO SERVE PAGE>]
From above log file data I'm aiming to use a neural network(s) :
To classify similar IP behaviors based on what resources are being accessed.
Classify behavior at specific periods / moments in time, so what IP's are behaving similarly and specific moment in time.

I'm not sure where to start with above. I've implemented very basic neural networks that perform integer arithmetic but now want to implement a network that is of use based on the data I have.
Based on log data format is this a good use case ?
Any pointers on where to being with this task ?
I hope this question is not too generic , I'm just unsure what questions to consider when beginning implementation of a neural network.
Update :
I would like to output data that is best suited to be generated from a neural network.
For this I think outputting a classification of users based over periods of time based on similarity score.
To generate the similarity score I could generate a count of times each IP address accesses a resource :
e.g :
1.2.3.A,4,3,1
1.2.3.B,0,1,2
1.2.3.C,3,7,3

from this then generate :
<HOUR OF DAY>,<IP ADDRESS X>,<IP ADDRESS Y>,<SIMMILARITY SCORE>

:
1,1.2.3.A,1.2.3.B,.3
1,1.2.3.C,1.2.3.B,.2
1,1.2.3.B,1.2.3.B,0
2,1.2.3.D,1.2.3.B,.764
2,1.2.3.E,1.2.3.B,.332
3,1.2.3.F,1.2.3.B,.631

So then can begin to correlate how users behave over course of day.
Is applicable to neural network?
I realise I'm asking about a neural network looking for a problem, but is this a suitable problem ?

A:
Based on log data format is this a good use case ?

You can use it as a dataset to train a neural network to predict future values or classify them in labels (or categories). For some types of neural network (specially, Multi-Layer Perceptron) it depends how you organize your dataset to use during the training of neural network. There are other cases you can group the sample (also known as clustering).
Neural Network Concept
Since you have a historical data separated in fields (or properties), you can create a model of neural network to classify or predict possible future values.
Given a neural network is a mathematical model that is defined by training steps, you have to define input and output sets to use during the training to define this model (neural network). Given that, your qualitative values (texts, chars, letters, etc) have to be converted as quantitative values, for sample:
A you convert to 1
B you convert to 2
C you convert to 3
...
Z you convert to N

After this, you can arrange your dataset in samples in order to separate it in an input list and the ideal output for each sample. For sample, let's suppose you have a dataset that define houses in the real estate market and their prices. You have the task to define a price (suggest) for new future houses, a sample of your training set could be like this:
Input:
Bedrooms ; Bathrooms ; Garage ; Near Subway
1        ; 1         ; 0      ; 1
3        ; 2         ; 2      ; 1
2        ; 2         ; 1      ; 0

Ideal Output (for each sample of input respectively)
Price
100.000
150.000
230.000

And use these sets to train a neural network to suggest a price for a future  house providing the characteristics
Your problem
In your case, the IPs fields, could be converted to quantitative values. For sample:
1.2.3 convert to 1
1.2.4 convert to 2
1.2.5 convert to 3

Let's suppose you want to classify the SIMILARITY SCORE field, so, you can use the the columns HOUR OF DAY, IP ADDRESS X and IP ADDRESS Y as input set and the output set you have just SIMILARITY SCORE. The image bellow draws how to led with it (a simple feed-forward neural network).

There are many tools that allows you to work easily with neural networks, you can use arrays of double values to define these sets and the object will be trained for you. I have been using the Encog Framework from Heaton Research and it support Java, C#, C++ and other. There is also another one called Accord Framework but it is just for .Net.
A very sample of how to implement a Feed-forward Neural Network using Encog for Java:
BasicNetwork network = new BasicNetwork();

// add layers in the neural network
network.addLayer(new BasicLayer(null, true, 3));
network.addLayer(new BasicLayer(new ActivationTANH(), true, 4));
network.addLayer(new BasicLayer(new ActivationTANH(), true, 1));

// finalize and randomize the neural network
network.getStructure().finalizeStructure();
network.reset();

// define a random training set.
// You can define using your double arrays here
MLDataSet training = RandomTrainingFactory.generate(1000, 5, network.getInputCount(), network.getOutputCount(), -1, 1);

ResilientPropagation train = new ResilientPropagation(network, training);
double error = 0;
Integer epochs = 0;

//starting training
do
{
    //train
    train.iteration();

    //count how many iterations the loop has
    epochs++;

    // get the error of neural network in the training set
    error = train.getError();

// condition for stop training
} while (epochs < 1000 && error > 0.01);

Obs: I did not test this code.
If you are starting with neural networks, I recommend you to implement your model and try it out using the datasets from UCI Machine Learning Repository. There are too many datasets for classification, regression and clustering problems you can test your implementation.


text:
Q: What is the use case for Oracle DB_UNIQUE_NAME and Global Database names Oracle database documentation defines the  global database name as below:

The Oracle Database software identifies a database by its global database name. A global database name consists of the database name and database domain. Usually, the database domain is the same as the network domain, but it need not be. The global database name uniquely distinguishes a database from any other database in the same network. You specify the global database name when you create a database during the installation or using the Oracle Database Configuration Assistant.
  Oracle Database Installation Guide

Question: How does Oracle enforce unique global database name? For example, say I have a server named ServerA in  my network with an Oracle database called DatabaseA, and I try to install another database with same name on ServerB, will the installation error out ?
How does Oracle find out about the other database ?
I am sure there is some design goal and some use cases for these confusing names. Looking for a proper explanation with sample scenarios.


text:
Q: Proof $\;\frac{\sin x}{x} \xrightarrow[x\to 0]{}1$ I read this proof https://www.dropbox.com/s/wo2dvhk2hqa6sk1/Screenshot%202014-05-03%2016.22.45.png and I wonder: how do we know that
$$x < \tan x?$$
also, we assume that $x>0$, is this because we take the right hand limit?

A:
$$x=\frac{\text{arc}}{\text{radius}}$$
$$\sin{x}=\frac{\text{perpendicular}}{\text{radius}}$$
As $x\to 0,\text{arc}\to \text{perpendicular}$
Hence, $\lim_{x\to 0}\frac{\sin x}{x}= 0$
Now you can find derivatives of trigonometric functions and prove that derivative of $\tan x =\sec^2 x$
And then analyse the function $\tan x-x$ and see that it is non negative in $[0,\pi/2)$ and hence $x<\tan x$
Now you can proceed in your proof.
PS: I have a strange feeling that you might not want to go through the proof now.


text:
Q: Find the index number of given value from the list using TCL Need to find the index number of given value from list. I have a value from the list ,But i need to find the index number of of the value.
set i 0.0001646481396164745
set X [list 1.215647671415354e-7 1.1284486163276597e-6 4.538622670224868e-5 4.4706815970130265e-5 8.492852430208586e-6 6.077577836549608e-6 3.1041158763400745e-6 0.00015045881445985287 4.1016753016265284e-7 1.165599314845167e-6 1.8736355968940188e-6 2.9444883693940938e-5 2.5420340534765273e-5 2.0819682049477706e-6 9.529731869406532e-6 8.549810104341304e-7 1.558014082547743e-5 8.079621693468653e-6 4.868444739258848e-5 0.0001646481396164745]

have to find the index value of i from list X using TCL.

A: It can be easily solved with lsearch:
set c [lsearch $X $i]

A: If you're looking for a floating point value in a list where you only know the approximate value, you can't use lsearch. Instead you have to do it yourself:
proc findApprox {theList theValue {epsilon 1e-9}} {
    set idx 0
    foreach x $theList {
        # Found if the difference between the list item and the target is less than epsilon
        if {abs($theValue - $x) < $epsilon} {
            return $idx
        }
        incr idx
    }
    return -1
    # Or [error "not found"] if you prefer
}

set x [findApprox $X $i]

Note the epsilon optional argument. That's because how close you have to get depends on knowledge of the domain of the input data; it's not something that it is easy for a basic algorithm to determine for you.


text:
Q: BadPaddingException when trying to decrypt a text in Base64 encrypted in AES in ECB i'm trying to do the 7° challeng of cryptopals and i have to decrypt a file Base64 that was encrypted with the AES in ECB mode. So, i found this code that work with the tutoria stirngs, but when i try with the given data in exercise it give me back the error:

Error while decrypting: javax.crypto.BadPaddingException: Given final
block not properly padded. Such issues can arise if a bad key is used
during decryption.
Process finished with exit code 0
this is the code:

public class ES7 {
    private static SecretKeySpec secretKey;
    private static byte[] key;

    public static void main(String[] args) throws InvalidAlgorithmParameterException, NoSuchPaddingException, IllegalBlockSizeException, IOException, NoSuchAlgorithmException, BadPaddingException, InvalidKeyException {
        String file = readBase64("C:\\Users\\Huawei\\OneDrive\\Desktop\\Lavoro\\Esercizi\\src\\ES7.txt");
        String res = decrypt(file,"YELLOW SUBMARINE"); --> this gave error of key

        // final String secretKey = "ssshhhhhhhhhhh!!!!";
        // String encryptedString= "Tg2Nn7wUZOQ6Xc+1lenkZTQ9ZDf9a2/RBRiqJBCIX6o=";
        // String decryptedString = decrypt(encryptedString, secretKey) ; --> this work
    }

    public static void setKey(final String myKey) {
        MessageDigest sha = null;
        try {
            key = myKey.getBytes("UTF-8");
            sha = MessageDigest.getInstance("SHA-1");
            key = sha.digest(key);
            key = Arrays.copyOf(key, 16);
            secretKey = new SecretKeySpec(key, "AES");
        } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    public static String decrypt(final String strToDecrypt, final String secret) {
        try {
            setKey(secret);
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
            cipher.init(Cipher.DECRYPT_MODE, secretKey);
            return new String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt)));
        } catch (Exception e) {
            System.out.println("Error while decrypting: " + e.toString());
        }
        return null;
    }
    private static String readBase64(String file) {
        String filetext = "";
        String line;
        try
        {
            BufferedReader input = new BufferedReader(new FileReader(new File(file)));
            while ((line = input.readLine()) != null)
            {
                filetext += line;
            }
            input.close();
        } catch (IOException e){
            e.printStackTrace();
        }

        return filetext;
    }
}


text:
Q: How to type the ' character on Windows 10 login screen? Out of stupidity, I have used the ' character in my Windows 10 login password via copy-paste, thinking that it is either ', ` or ' and now can't login to my Windows 10 account (am using Linux Mint right now). Neither over the German, nor English keyboard setting, ' seems to be accessible. So any idea how to type ' on the Windows 10 login screen?

A: Solution

*

*Hold Alt

*Press 0146 (on the numeric keypad)

*Release Alt
Explanation
First, I used the ASCII Value Tool to get the decimal value of '.  It is 146.

Inserting ASCII characters - Office Support
To insert an ASCII character, press and hold down ALT while typing the
  character code. For example, to insert the degree (º) symbol, press
  and hold down ALT while typing 0176 on the numeric keypad.

EliteBook Specific (similar for other laptops)
You mentioned in your comment that you have an HP EliteBook 8460 Laptop.  Like most laptops without a dedicated number pad, you can use the Fn key to access the number-pad keys on the right side of the keyboard.
I found this image of an HP EliteBook 8460p keyboard.

*

*Hold Fn and Alt

*Press Mfor 0, J for 1, U for 4, O for 6

*Release Fn and Alt
Note: This assumes the keyboard layout below.


text:
Q: How to pass from seconds to time How can I pass from seconds to time on mysql?
the date format of out is hh:mm:ss.ms
Sorry. I need for example 0.98 sec -> 00:00:00.980; With sec_to_tiem return 00:00:01.
thanks.
I have implemeted of this way:
select concat(if(floor(seconds/(60 * 60)) = 0,'00',lpad(floor(seconds/(60 * 60)),2,'0')),
':',
if(floor(seconds/60) = 0,'00',lpad(floor(seconds / 60),2,'0')),
':',
seconds % 60)

but it have to exist other way more efficient
other way:
CONCAT(lpad(floor(seconds / 3600), 2, '0'), ':',
      lpad(floor(seconds / 60), 2, '0'), ':',
      lpad(floor(seconds  % 60), 2, '0'), '.',
      lpad(SUBSTRING_INDEX((seconds * 1000) % 1000, '.', 1), 3, '0'))

A: SELECT MAKETIME (<yourseconds>/(60*24), <yourseconds>/60, <yourseconds>%60)

or with format
SELECT TIME_FORMAT( MAKETIME( <yourseconds>/ ( 60 *24 ) , <yourseconds>/60, <yourseconds>%60 ) ,  '%T.%f' )


text:
Q: Copy-Item in PowerShell; The given path's format is not supported I'm relatively new to PowerShell, and I was trying to copy files using a text file formatted like this:
file1.pdf
dir1\dir2\dir3\dir 4

file2.pdf
dir1\dir5\dir7\di r8

file3.pdf
...etc.

Where the first line of each entry is a file name, and the second is the file path from C:\Users. For example, the full path to the first entry in the file would be:
C:\Users\dir1\dir2\dir3\dir 4\file1.pdf

The code below is what I currently have but I'm getting the error: 'The given path's format is not supported.' and another error after that telling me it can't find the path, which I assume a result of the first error. I've played around with it a bit, and I'm getting the impression that it's something to do with passing a string to Copy-Item.
    $file = Get-Content C:\Users\AJ\Desktop\gdocs.txt
    for ($i = 0; $i -le $file.length - 1; $i+=3)
    {
        $copyCommand = "C:\Users\" + $file[$i+1] + "\" + $file[$i]
        $copyCommand = $copyCommand +  " C:\Users\AJ\Desktop\gdocs\"
        $copyCommand
        Copy-Item $copyCommand

    }

A: You can read the file in chunks of three lines, join the first two elements to form a path and use copy-item to copy the files.
$to = "C:\Users\AJ\Desktop\gdocs\"

Get-Content C:\Users\AJ\Desktop\gdocs.txt -ReadCount 3 | foreach-object{
    $from = "C:\Users\" + (join-path $_[1] $_[0] )
    Copy-Item -Path $from -Destination $to
}

A: Try this (inside the cycle):
$from = "C:\Users\" + $file[$i+1] + "\" + $file[$i]
$to = "C:\Users\AJ\Desktop\gdocs\"
Copy-Item $from $to

$from and $to are arguments for Copy-Item cmdlet. They are bound to parameters -Path and -Destinattion. You can check this via this code:
Trace-Command -pshost -name parameterbinding {
   Copy-Item $from $to
}


text:
Q: Please tell me how to write condition in php class method my code now:
if ($condition) {
      $result = ORM::for_table($tableName)
         ->order_by_ACS($columnSort)
         ->findArray();
} else {
      $result = ORM::for_table($tableName)
         ->order_by_DESC($columnSort)
         ->findArray();
}

question how to write like
$result = ORM::for_table($tableName)
// if (true) {
            ->order_by_asc($columnSort)
// } else { ->order_by_desc($columnSort) }
            ->findArray();

/** nothing. just some comment to post this post) **/

A: You can build method invocations by string identifiers.
class TestClass
{
  function test1() { echo 'first method
'; }
  function test2() { echo 'second method
'; }
}

$test = new TestClass();

for($i = 0; $i<=1 ; $i++)
  $test->{'test' . ($i === 0 ? '1' : '2')}();

So your example would become
$result = ORM::for_table($tableName)
  ->{ $condition ? 'order_by_asc' : 'order_by_desc' }($columnSort)
  ->findArray()
;


text:
Q: What gem do you advise me to use to implement a simple "Contact us" form? I am using Ruby on Rails 3.0.9 and I am planning to add a simple "Contact us" form to my application in order to make it possible that a user can contact our team. For that I would like to run validation and "friends" functionalities and (to avoid to implement that myself and) to use a third party software, but...
... what gem (or plugin) do you advice to use? what is the most widely "approved" gem for this kind of things?
Of course I would like to use a gem in "active developing" (that is, whose developers are active).

A: Generally I would go with a rails engine to add this functionality and the contact_us plugin an excellent example, it's also under active development (last commit 5 days ago) so you can be sure it's not abandon-ware.

A: I think it's not to complicated to do it on your own (pretty fast)? I hardly think it needs a separate gem to do this (especially if for example contact_us requires additional dependencies (formtastic)).
As for me, it's just a simple form, with action directed to your own Rails mailer.
See: ActionMailer in Rails 3, Form helpers in Rails 3

A: You can use Contact Us gem via this link: https://github.com/JDutil/contact_us The documentation is clear and you can use it simply.
As I know by using it, it doesn't need any additional dependency like "formtastic".
Features:

*

*Validation

*Easy/Add remove fields

*Simple configuration