问:
Creation of multi-frame dicom image using DCM4CHE3(JAVA)
i am trying to create a multiframe dicom file from multiple JPEG file by writing them using Imagewriter but  writer.canWriteSequence() is always giving false so not able to write jpeg file to the multiframe dicom file so is there any way i can create the multiframe dicom file from jpeg image or bufferedimage

```<code> public Attributes createDicomHeader(BufferedImage sampleFrame, int numberOfFrames) {

        // Get some image information from the sample image:
        // All frames should have the same information so we will get it only once.

     int colorComponents = sampleFrame.getColorModel().getNumColorComponents();
        int bitsPerPixel = sampleFrame.getColorModel().getPixelSize();
        int bitsAllocated = (bitsPerPixel / colorComponents);
        int samplesPerPixel = colorComponents;

        // The DICOM object that will hold our frames
        Attributes dicom = new Attributes();

        // Add patient related information to the DICOM dataset
        dicom.getString(Tag.PatientName, "Aditya^G");
        dicom.getString(Tag.PatientID, "1234ID");
        dicom.getDate(Tag.PatientBirthDate, new java.util.Date());
        dicom.getString(Tag.PatientSex, "M");

        // Add study related information to the DICOM dataset
        dicom.getString(Tag.AccessionNumber, "1234AC");
        dicom.getString(Tag.StudyID, "1");
        dicom.getString(Tag.StudyDescription, "MULTIFRAME STUDY");
        dicom.setDate(Tag.StudyDate, new java.util.Date());
        dicom.setDate(Tag.StudyTime, new java.util.Date());

        // Add series related information to the DICOM dataset
        dicom.setInt(Tag.SeriesNumber,VR.US, 1);
        dicom.setDate(Tag.SeriesDate, new java.util.Date());
        dicom.setDate(Tag.SeriesTime, new java.util.Date());
        dicom.getString(Tag.SeriesDescription, "MULTIFRAME SERIES");
        dicom.getString(Tag.Modality, "SC"); // secondary capture

        // Add image related information to the DICOM dataset
        dicom.setInt(Tag.InstanceNumber, VR.US, 1);
        dicom.setInt(Tag.SamplesPerPixel, VR.US, samplesPerPixel);
        dicom.setString(Tag.PhotometricInterpretation, VR.CS, "YBR_FULL_422");
        dicom.setInt(Tag.Rows, VR.US, sampleFrame.getHeight());
        dicom.setInt(Tag.Columns, VR.US, sampleFrame.getWidth());
        dicom.setInt(Tag.BitsAllocated, VR.US, bitsAllocated);
        dicom.setInt(Tag.BitsStored, VR.US, bitsAllocated);
        dicom.setInt(Tag.HighBit, VR.US, bitsAllocated-1);
        dicom.setInt(Tag.PixelRepresentation, VR.US, 0);

        // Add the unique identifiers
        dicom.setString(Tag.SOPClassUID, VR.UI, UID.SecondaryCaptureImageStorage);
        dicom.setString(Tag.StudyInstanceUID, VR.UI, UIDUtils.createUID());
        dicom.setString(Tag.SeriesInstanceUID, VR.UI, UIDUtils.createUID());
        dicom.setString(Tag.SOPInstanceUID, VR.UI, UIDUtils.createUID());

        //Start of multiframe information:
        dicom.setInt(Tag.StartTrim, VR.US, 1);
        dicom.setInt(Tag.StopTrim, VR.US, numberOfFrames);
        dicom.getString(Tag.FrameTime, 0, "33.33");
        dicom.getString(Tag.FrameDelay, "0.0");
        dicom.setInt(Tag.NumberOfFrames, VR.US, numberOfFrames); // The number of frames
        dicom.setInt(Tag.RecommendedDisplayFrameRate, VR.US, 3);
        dicom.setInt(Tag.FrameIncrementPointer, VR.US, Tag.FrameTime);
        //End of multiframe information.

        // Add the default character set
        dicom.setString(Tag.SpecificCharacterSet, VR.CS, "ISO_IR 100");

        // Init the meta information with JPEG Lossless transfer syntax
        dicom.createFileMetaInformation(UID.JPEGBaseline1);

        return dicom;
    }

     public void encodeMultiframe(File[] frames, File dest)
     throws IOException {
        // Status message
        System.out.println("Creating Multiframe File...");

        // Create DICOM image writer instance and set its output

        ImageReadParam dicomr=new DicomImageReadParam();
        ImageWriter writer =  ImageWriterFactory.getImageWriter(ImageWriterFactory.getImageWriterParam(UID.JPEGBaseline1));

        FileImageOutputStream output = new FileImageOutputStream(dest);
        writer.setOutput(output);

        // Get an image sample from the array of images
        BufferedImage sample = ImageIO.read(frames[0]);

        // Create a new dataset (header/metadata) for our DICOM image writer
        Attributes ds = this.createDicomHeader(sample, frames.length);
        Attributes fmi = ds.createFileMetaInformation(UID.JPEGBaseline1);
        // Set the metadata to our DICOM image writer and prepare to encode the multiframe sequence
     //  ImageWriteParam iwp= writer.getDefaultWriteParam() ;
       DicomMetaData writeMeta = new DicomMetaData(fmi, ds);
        writeMeta.getAttributes().addAll(ds);

        if(writer.canWriteSequence())
        writer.prepareWriteSequence(writeMeta);

        else
            System.out.println("can not write to sequence");

        // DicomMetaData writeMeta = (DicomMetaData) writer.getDefaultStreamMetadata(null);
     //   writeMeta.getAttributes().addAll(ds);
     //   writer.prepareWriteSequence(writeMeta);

        // Status message
        System.out.println("Start of Write Sequence...");

        // For each extracted JPEG images...
        for (int i = 0; i < frames.length; i++) {

            // Status message
            System.out.println("Encoding frame # "+ (i+1));

            // Read the JPEG file to a BufferedImage object
            BufferedImage frame = ImageIO.read(frames[i]);

            // Create a new IIOImage to be saved to the DICOM multiframe sequence
            IIOImage iioimage = new IIOImage(frame, null, null);

            // Write our image to the DICOM multiframe sequence
            writer.writeToSequence(iioimage, null);
        }

        // Status message
        System.out.println("End of Write Sequence.");

        // Our multiframe file was created. End the sequence and close the output stream.
        writer.endWriteSequence();
        output.close();

        // Status message
        System.out.println("Multiframe File Created.");
    }

/**
 * @param args
 * @throws IOException
 */
public static void main(String[] args) throws IOException {
    MultiframeImageCreation mf=new MultiframeImageCreation();

    File[] frames = new File("/root/Desktop/multi").listFiles();

    // Create the DICOM multiframe file
    mf.encodeMultiframe(frames, new File("/root/Desktop/multiframe.dcm"));

}
</code>```

}

答:
Try to use this code

```<code>import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriter;
import javax.imageio.stream.FileImageOutputStream;

import org.dcm4che2.data.BasicDicomObject;
import org.dcm4che2.data.DicomObject;
import org.dcm4che2.data.Tag;
import org.dcm4che2.data.UID;
import org.dcm4che2.data.VR;
import org.dcm4che2.imageio.plugins.dcm.DicomStreamMetaData;
import org.dcm4che2.imageioimpl.plugins.dcm.DicomImageWriterSpi;
import org.dcm4che2.util.UIDUtils;

public class Mpeg2Dicom {

    public Mpeg2Dicom() {

    }

    public DicomObject createDicomHeader(BufferedImage sampleFrame, int numberOfFrames) {
        int colorComponents = sampleFrame.getColorModel().getNumColorComponents();
        int bitsPerPixel = sampleFrame.getColorModel().getPixelSize();
        int bitsAllocated = (bitsPerPixel / colorComponents);
        int samplesPerPixel = colorComponents;
        // The DICOM object that will hold our frames
        DicomObject dicom = new BasicDicomObject();
        // Add patient related information to the DICOM dataset
        dicom.putString(Tag.PatientName, null, "Patient Name");
        dicom.putString(Tag.PatientID, null, "1234ID");
        dicom.putDate(Tag.PatientBirthDate, null, new java.util.Date());
        dicom.putString(Tag.PatientSex, null, "M");
        // Add study related information to the DICOM dataset
        dicom.putString(Tag.AccessionNumber, null, "1234AC");
        dicom.putString(Tag.StudyID, null, "1");
        dicom.putString(Tag.StudyDescription, null, "MULTIFRAME STUDY");
        dicom.putDate(Tag.StudyDate, null, new java.util.Date());
        dicom.putDate(Tag.StudyTime, null, new java.util.Date());
        // Add series related information to the DICOM dataset
        dicom.putInt(Tag.SeriesNumber, null, 1);
        dicom.putDate(Tag.SeriesDate, null, new java.util.Date());
        dicom.putDate(Tag.SeriesTime, null, new java.util.Date());
        dicom.putString(Tag.SeriesDescription, null, "MULTIFRAME SERIES");
        dicom.putString(Tag.Modality, null, "SC"); // secondary capture
        // Add image related information to the DICOM dataset
        dicom.putInt(Tag.InstanceNumber, null, 1);
        dicom.putInt(Tag.SamplesPerPixel, null, samplesPerPixel);
        dicom.putString(Tag.PhotometricInterpretation, VR.CS, "YBR_FULL_422");
        dicom.putInt(Tag.Rows, null, sampleFrame.getHeight());
        dicom.putInt(Tag.Columns, null, sampleFrame.getWidth());
        dicom.putInt(Tag.BitsAllocated, null, bitsAllocated);
        dicom.putInt(Tag.BitsStored, null, bitsAllocated);
        dicom.putInt(Tag.HighBit, null, bitsAllocated-1);
        dicom.putInt(Tag.PixelRepresentation, null, 0);
       // Add the unique identifiers
        dicom.putString(Tag.SOPClassUID, null, UID.SecondaryCaptureImageStorage);
        dicom.putString(Tag.StudyInstanceUID, null, UIDUtils.createUID());
        dicom.putString(Tag.SeriesInstanceUID, null, UIDUtils.createUID());
        dicom.putString(Tag.SOPInstanceUID, VR.UI, UIDUtils.createUID());
        //Start of multiframe information:
        dicom.putInt(Tag.StartTrim, null, 1);                   // Start at frame 1
        dicom.putInt(Tag.StopTrim, null, numberOfFrames);       // Stop at frame N
        dicom.putString(Tag.FrameTime, null, "33.33");          // Milliseconds (30 frames per second)
        dicom.putString(Tag.FrameDelay, null, "0.0");           // No frame dalay
        dicom.putInt(Tag.NumberOfFrames, null, numberOfFrames); // The number of frames
        dicom.putInt(Tag.RecommendedDisplayFrameRate, null, 3);
        dicom.putInt(Tag.FrameIncrementPointer, null, Tag.FrameTime);
        //End of multiframe information.
        // Add the default character set
        dicom.putString(Tag.SpecificCharacterSet, VR.CS, "ISO_IR 100");
        // Init the meta information with JPEG Lossless transfer syntax
       // dicom.initFileMetaInformation(UID.JPEGLossless);
        dicom.initFileMetaInformation(UID.JPEGBaseline1);
        return dicom;
    }

     public void encodeMultiframe(File[] frames, File dest) throws IOException {
        // Status message
        System.out.println("Creating Multiframe File...");
        // Create DICOM image writer instance and set its output
        ImageWriter writer = new DicomImageWriterSpi().createWriterInstance();
        FileImageOutputStream output = new FileImageOutputStream(dest);
        writer.setOutput(output);
        // Get an image sample from the array of images
        BufferedImage sample = ImageIO.read(frames[0]);
        // Create a new dataset (header/metadata) for our DICOM image writer
        DicomObject ds = this.createDicomHeader(sample, frames.length);
        // Set the metadata to our DICOM image writer and prepare to encode the multiframe sequence
        DicomStreamMetaData writeMeta = (DicomStreamMetaData) writer.getDefaultStreamMetadata(null);
        writeMeta.setDicomObject(ds);
        writer.prepareWriteSequence(writeMeta);

        System.out.println("Start of Write Sequence...");

        for (int i = 0; i < frames.length; i++) {
            // Status message
            System.out.println("Encoding frame # "+ (i+1));
            // Read the PNG file to a BufferedImage object
            BufferedImage frame = ImageIO.read(frames[i]);
            // Create a new IIOImage to be saved to the DICOM multiframe sequence
            IIOImage iioimage = new IIOImage(frame, null, null);
            // Write our image to the DICOM multiframe sequence
            writer.writeToSequence(iioimage, null);
        }
        // Status message
        System.out.println("End of Write Sequence.");
        // Our multiframe file was created. End the sequence and close the output stream.
        writer.endWriteSequence();
        output.close();
        // Status message
        System.out.println("Multiframe File Created.");
    }

    public static void main(String[] args) {
        try {
            // Create an instance of our class
            Mpeg2Dicom f = new Mpeg2Dicom();

            // Create the array of files for the extracted FFMPEG images
            File[] frames = new File("d://AAA").listFiles();

            // Create the DICOM multiframe file
            f.encodeMultiframe(frames, new File("d:///multiframe.dcm"));

        } catch (Exception e) {
            // Print exceptions
            e.printStackTrace();
        }
    }
}
</code>```

Before run this code please install Java Advanced Imaging Image I/O Tools 32 Bit version 1.0_01 Java Advanced Imaging Image and also try to run this code using Java 32 Bit version

a) JAI ImageIO library is not installed;

b) JAI ImageIO is installed but has no values set in the PATH environment variable;

c) DLL files with JAI native code cannot be found (wrong installation);

d) Your Windows is 64bits (it will work only for Win32);

Body:
i am trying to create a multiframe dicom file from multiple JPEG file by writing them using Imagewriter but  writer.canWriteSequence() is always giving false so not able to write jpeg file to the multiframe dicom file so is there any way i can create the multiframe dicom file from jpeg image or bufferedimage

 public Attributes createDicomHeader(BufferedImage sampleFrame, int numberOfFrames) {

        // Get some image information from the sample image:
        // All frames should have the same information so we will get it only once.

     int colorComponents = sampleFrame.getColorModel().getNumColorComponents();
        int bitsPerPixel = sampleFrame.getColorModel().getPixelSize();
        int bitsAllocated = (bitsPerPixel / colorComponents);
        int samplesPerPixel = colorComponents;

        // The DICOM object that will hold our frames
        Attributes dicom = new Attributes();

        // Add patient related information to the DICOM dataset
        dicom.getString(Tag.PatientName, "Aditya^G");
        dicom.getString(Tag.PatientID, "1234ID");
        dicom.getDate(Tag.PatientBirthDate, new java.util.Date());
        dicom.getString(Tag.PatientSex, "M");

        // Add study related information to the DICOM dataset
        dicom.getString(Tag.AccessionNumber, "1234AC");
        dicom.getString(Tag.StudyID, "1");
        dicom.getString(Tag.StudyDescription, "MULTIFRAME STUDY");
        dicom.setDate(Tag.StudyDate, new java.util.Date());
        dicom.setDate(Tag.StudyTime, new java.util.Date());

        // Add series related information to the DICOM dataset
        dicom.setInt(Tag.SeriesNumber,VR.US, 1);
        dicom.setDate(Tag.SeriesDate, new java.util.Date());
        dicom.setDate(Tag.SeriesTime, new java.util.Date());
        dicom.getString(Tag.SeriesDescription, "MULTIFRAME SERIES");
        dicom.getString(Tag.Modality, "SC"); // secondary capture

        // Add image related information to the DICOM dataset
        dicom.setInt(Tag.InstanceNumber, VR.US, 1);
        dicom.setInt(Tag.SamplesPerPixel, VR.US, samplesPerPixel);
        dicom.setString(Tag.PhotometricInterpretation, VR.CS, "YBR_FULL_422");
        dicom.setInt(Tag.Rows, VR.US, sampleFrame.getHeight());
        dicom.setInt(Tag.Columns, VR.US, sampleFrame.getWidth());
        dicom.setInt(Tag.BitsAllocated, VR.US, bitsAllocated);
        dicom.setInt(Tag.BitsStored, VR.US, bitsAllocated);
        dicom.setInt(Tag.HighBit, VR.US, bitsAllocated-1);
        dicom.setInt(Tag.PixelRepresentation, VR.US, 0);

        // Add the unique identifiers
        dicom.setString(Tag.SOPClassUID, VR.UI, UID.SecondaryCaptureImageStorage);
        dicom.setString(Tag.StudyInstanceUID, VR.UI, UIDUtils.createUID());
        dicom.setString(Tag.SeriesInstanceUID, VR.UI, UIDUtils.createUID());
        dicom.setString(Tag.SOPInstanceUID, VR.UI, UIDUtils.createUID());

        //Start of multiframe information:
        dicom.setInt(Tag.StartTrim, VR.US, 1);
        dicom.setInt(Tag.StopTrim, VR.US, numberOfFrames);
        dicom.getString(Tag.FrameTime, 0, "33.33");
        dicom.getString(Tag.FrameDelay, "0.0");
        dicom.setInt(Tag.NumberOfFrames, VR.US, numberOfFrames); // The number of frames
        dicom.setInt(Tag.RecommendedDisplayFrameRate, VR.US, 3);
        dicom.setInt(Tag.FrameIncrementPointer, VR.US, Tag.FrameTime);
        //End of multiframe information.

        // Add the default character set
        dicom.setString(Tag.SpecificCharacterSet, VR.CS, "ISO_IR 100");

        // Init the meta information with JPEG Lossless transfer syntax
        dicom.createFileMetaInformation(UID.JPEGBaseline1);

        return dicom;
    }

     public void encodeMultiframe(File[] frames, File dest)
     throws IOException {
        // Status message
        System.out.println("Creating Multiframe File...");

        // Create DICOM image writer instance and set its output

        ImageReadParam dicomr=new DicomImageReadParam();
        ImageWriter writer =  ImageWriterFactory.getImageWriter(ImageWriterFactory.getImageWriterParam(UID.JPEGBaseline1));

        FileImageOutputStream output = new FileImageOutputStream(dest);
        writer.setOutput(output);

        // Get an image sample from the array of images
        BufferedImage sample = ImageIO.read(frames[0]);

        // Create a new dataset (header/metadata) for our DICOM image writer
        Attributes ds = this.createDicomHeader(sample, frames.length);
        Attributes fmi = ds.createFileMetaInformation(UID.JPEGBaseline1);
        // Set the metadata to our DICOM image writer and prepare to encode the multiframe sequence
     //  ImageWriteParam iwp= writer.getDefaultWriteParam() ;
       DicomMetaData writeMeta = new DicomMetaData(fmi, ds);
        writeMeta.getAttributes().addAll(ds);

        if(writer.canWriteSequence())
        writer.prepareWriteSequence(writeMeta);

        else
            System.out.println("can not write to sequence");

        // DicomMetaData writeMeta = (DicomMetaData) writer.getDefaultStreamMetadata(null);
     //   writeMeta.getAttributes().addAll(ds);
     //   writer.prepareWriteSequence(writeMeta);

        // Status message
        System.out.println("Start of Write Sequence...");

        // For each extracted JPEG images...
        for (int i = 0; i < frames.length; i++) {

            // Status message
            System.out.println("Encoding frame # "+ (i+1));

            // Read the JPEG file to a BufferedImage object
            BufferedImage frame = ImageIO.read(frames[i]);

            // Create a new IIOImage to be saved to the DICOM multiframe sequence
            IIOImage iioimage = new IIOImage(frame, null, null);

            // Write our image to the DICOM multiframe sequence
            writer.writeToSequence(iioimage, null);
        }

        // Status message
        System.out.println("End of Write Sequence.");

        // Our multiframe file was created. End the sequence and close the output stream.
        writer.endWriteSequence();
        output.close();

        // Status message
        System.out.println("Multiframe File Created.");
    }

/**
 * @param args
 * @throws IOException
 */
public static void main(String[] args) throws IOException {
    MultiframeImageCreation mf=new MultiframeImageCreation();

    File[] frames = new File("/root/Desktop/multi").listFiles();

    // Create the DICOM multiframe file
    mf.encodeMultiframe(frames, new File("/root/Desktop/multiframe.dcm"));

}

}

Body:
Try to use this code

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriter;
import javax.imageio.stream.FileImageOutputStream;

import org.dcm4che2.data.BasicDicomObject;
import org.dcm4che2.data.DicomObject;
import org.dcm4che2.data.Tag;
import org.dcm4che2.data.UID;
import org.dcm4che2.data.VR;
import org.dcm4che2.imageio.plugins.dcm.DicomStreamMetaData;
import org.dcm4che2.imageioimpl.plugins.dcm.DicomImageWriterSpi;
import org.dcm4che2.util.UIDUtils;

public class Mpeg2Dicom {

    public Mpeg2Dicom() {

    }

    public DicomObject createDicomHeader(BufferedImage sampleFrame, int numberOfFrames) {
        int colorComponents = sampleFrame.getColorModel().getNumColorComponents();
        int bitsPerPixel = sampleFrame.getColorModel().getPixelSize();
        int bitsAllocated = (bitsPerPixel / colorComponents);
        int samplesPerPixel = colorComponents;
        // The DICOM object that will hold our frames
        DicomObject dicom = new BasicDicomObject();
        // Add patient related information to the DICOM dataset
        dicom.putString(Tag.PatientName, null, "Patient Name");
        dicom.putString(Tag.PatientID, null, "1234ID");
        dicom.putDate(Tag.PatientBirthDate, null, new java.util.Date());
        dicom.putString(Tag.PatientSex, null, "M");
        // Add study related information to the DICOM dataset
        dicom.putString(Tag.AccessionNumber, null, "1234AC");
        dicom.putString(Tag.StudyID, null, "1");
        dicom.putString(Tag.StudyDescription, null, "MULTIFRAME STUDY");
        dicom.putDate(Tag.StudyDate, null, new java.util.Date());
        dicom.putDate(Tag.StudyTime, null, new java.util.Date());
        // Add series related information to the DICOM dataset
        dicom.putInt(Tag.SeriesNumber, null, 1);
        dicom.putDate(Tag.SeriesDate, null, new java.util.Date());
        dicom.putDate(Tag.SeriesTime, null, new java.util.Date());
        dicom.putString(Tag.SeriesDescription, null, "MULTIFRAME SERIES");
        dicom.putString(Tag.Modality, null, "SC"); // secondary capture
        // Add image related information to the DICOM dataset
        dicom.putInt(Tag.InstanceNumber, null, 1);
        dicom.putInt(Tag.SamplesPerPixel, null, samplesPerPixel);
        dicom.putString(Tag.PhotometricInterpretation, VR.CS, "YBR_FULL_422");
        dicom.putInt(Tag.Rows, null, sampleFrame.getHeight());
        dicom.putInt(Tag.Columns, null, sampleFrame.getWidth());
        dicom.putInt(Tag.BitsAllocated, null, bitsAllocated);
        dicom.putInt(Tag.BitsStored, null, bitsAllocated);
        dicom.putInt(Tag.HighBit, null, bitsAllocated-1);
        dicom.putInt(Tag.PixelRepresentation, null, 0);
       // Add the unique identifiers
        dicom.putString(Tag.SOPClassUID, null, UID.SecondaryCaptureImageStorage);
        dicom.putString(Tag.StudyInstanceUID, null, UIDUtils.createUID());
        dicom.putString(Tag.SeriesInstanceUID, null, UIDUtils.createUID());
        dicom.putString(Tag.SOPInstanceUID, VR.UI, UIDUtils.createUID());
        //Start of multiframe information:
        dicom.putInt(Tag.StartTrim, null, 1);                   // Start at frame 1
        dicom.putInt(Tag.StopTrim, null, numberOfFrames);       // Stop at frame N
        dicom.putString(Tag.FrameTime, null, "33.33");          // Milliseconds (30 frames per second)
        dicom.putString(Tag.FrameDelay, null, "0.0");           // No frame dalay
        dicom.putInt(Tag.NumberOfFrames, null, numberOfFrames); // The number of frames
        dicom.putInt(Tag.RecommendedDisplayFrameRate, null, 3);
        dicom.putInt(Tag.FrameIncrementPointer, null, Tag.FrameTime);
        //End of multiframe information.
        // Add the default character set
        dicom.putString(Tag.SpecificCharacterSet, VR.CS, "ISO_IR 100");
        // Init the meta information with JPEG Lossless transfer syntax
       // dicom.initFileMetaInformation(UID.JPEGLossless);
        dicom.initFileMetaInformation(UID.JPEGBaseline1);
        return dicom;
    }

     public void encodeMultiframe(File[] frames, File dest) throws IOException {
        // Status message
        System.out.println("Creating Multiframe File...");
        // Create DICOM image writer instance and set its output
        ImageWriter writer = new DicomImageWriterSpi().createWriterInstance();
        FileImageOutputStream output = new FileImageOutputStream(dest);
        writer.setOutput(output);
        // Get an image sample from the array of images
        BufferedImage sample = ImageIO.read(frames[0]);
        // Create a new dataset (header/metadata) for our DICOM image writer
        DicomObject ds = this.createDicomHeader(sample, frames.length);
        // Set the metadata to our DICOM image writer and prepare to encode the multiframe sequence
        DicomStreamMetaData writeMeta = (DicomStreamMetaData) writer.getDefaultStreamMetadata(null);
        writeMeta.setDicomObject(ds);
        writer.prepareWriteSequence(writeMeta);

        System.out.println("Start of Write Sequence...");

        for (int i = 0; i < frames.length; i++) {
            // Status message
            System.out.println("Encoding frame # "+ (i+1));
            // Read the PNG file to a BufferedImage object
            BufferedImage frame = ImageIO.read(frames[i]);
            // Create a new IIOImage to be saved to the DICOM multiframe sequence
            IIOImage iioimage = new IIOImage(frame, null, null);
            // Write our image to the DICOM multiframe sequence
            writer.writeToSequence(iioimage, null);
        }
        // Status message
        System.out.println("End of Write Sequence.");
        // Our multiframe file was created. End the sequence and close the output stream.
        writer.endWriteSequence();
        output.close();
        // Status message
        System.out.println("Multiframe File Created.");
    }

    public static void main(String[] args) {
        try {
            // Create an instance of our class
            Mpeg2Dicom f = new Mpeg2Dicom();

            // Create the array of files for the extracted FFMPEG images
            File[] frames = new File("d://AAA").listFiles();

            // Create the DICOM multiframe file
            f.encodeMultiframe(frames, new File("d:///multiframe.dcm"));

        } catch (Exception e) {
            // Print exceptions
            e.printStackTrace();
        }
    }
}

Before run this code please install Java Advanced Imaging Image I/O Tools 32 Bit version 1.0_01 Java Advanced Imaging Image and also try to run this code using Java 32 Bit version

a) JAI ImageIO library is not installed;

b) JAI ImageIO is installed but has no values set in the PATH environment variable;

c) DLL files with JAI native code cannot be found (wrong installation);

d) Your Windows is 64bits (it will work only for Win32);


来源: stackexchange

问:
Echo arrays with regular text
How would I write this so I'm only using one echo? </p>

```<code>echo "<div class='post'>";
echo $row['title'];
echo "</div>";
</code>```

<p>I'm using an array to echo out a table's values but it would be a lot easier on the eyes if I could combine these into one echo statement. However, when I try to the page goes blank. </p>

答:
```<code><?php
echo "<div class='post'".$row['title']."</div>";
?>
</code>```

ContentLicense: CC BY-SA 2.5

Title: Echo arrays with regular text

Body:
How would I write this so I'm only using one echo?

echo "
";
echo $row['title'];
echo "
";

I'm using an array to echo out a table's values but it would be a lot easier on the eyes if I could combine these into one echo statement. However, when I try to the page goes blank.


问:
Extract Integers, Decimals, and Fractional Numbers from sentence of a string
How to extract the array of string with Integers, Decimals, and Fractions from a sentence?
Please find below input and output in iOS Swift.

Input :  array of String["width 32.3", "Length 61 1/4", "height 23 4/5", "measure 5.23"]

Output : ["32.3", "61 1/4", "23 4/5", "5.23"]

答:
Add this for supporting regex matches for string:

```<code>extension String {
    mutating func stringByRemovingRegexMatches(pattern: String, replaceWith: String = "") {
        do {
            let regex = try NSRegularExpression(pattern: pattern, options: NSRegularExpression.Options.caseInsensitive)
            let range = NSMakeRange(0, self.characters.count)
            self = regex.stringByReplacingMatches(in: self, options: [], range: range, withTemplate: replaceWith)
        } catch {
            return
        }
    }
}
</code>```

And then:

```<code>var str = ["width 32.3", "Length 61 1/4", "height 23 4/5", "measure 5.23"]
var vreturn:[String]=[]

for var s in str {
    s.stringByRemovingRegexMatches(pattern:"[a-zA-Z]", replaceWith: "")
    vreturn.append(s)
}

print( vreturn)
</code>```

Source : Swift replace substring regex

ContentLicense: CC BY-SA 3.0

Body:
Add this for supporting regex matches for string:

extension String {
    mutating func stringByRemovingRegexMatches(pattern: String, replaceWith: String = "") {
        do {
            let regex = try NSRegularExpression(pattern: pattern, options: NSRegularExpression.Options.caseInsensitive)
            let range = NSMakeRange(0, self.characters.count)
            self = regex.stringByReplacingMatches(in: self, options: [], range: range, withTemplate: replaceWith)
        } catch {
            return
        }
    }
}

And then:

var str = ["width 32.3", "Length 61 1/4", "height 23 4/5", "measure 5.23"]
var vreturn:[String]=[]

for var s in str {
    s.stringByRemovingRegexMatches(pattern:"[a-zA-Z]", replaceWith: "")
    vreturn.append(s)
}

print( vreturn)

Source : Swift replace substring regex


问:
Using VS 2012, project properties, Signing tab, upper section is disabled
In my visual studio project, the upper part of the siging tab in the project's properties page is disabled.  How do I enable it?

image of this phenomenon

答: The project properties which you are checking doesnt have Void Main (entry point).Hence,the checkbox (Sign the clickonce manifests) is disabled.Try to sign on the project which contains void main class.</p>


问:
Plot multiple columns of pandas DataFrame using Seaborn
suppose I have DataFrame with columns ['X_Axis','col_2','col_3',...,'col_n',]

I need to plot the first column on X-Axis and rest on Y-Axis.
FYI : all the values have been grouped according to X-Axis, the X-Axis values range from 0-25 and all other column values have been normalized to the scale of 0 - 1. I want it on same graph plot, not subplots.

Preferred : FactorPlot , normal line graph.

答:
Some seaborn plots will accept a wide dataframe, sns.pointplot(data=df, x='X_Axis', y='col_2'), but not sns.pointplot(data=df, x='X_Axis', y=['col_2', 'col_3']), so it's better to reshape the DataFrame.

Reshape the DataFrame from wide to long with pandas.DataFrame.melt.

Converting the dataframe from a wide to long form is standard for all seaborn plots, not just the examples shown.

Tested in python 3.8.12, pandas 1.3.4, matplotlib 3.4.3, seaborn 0.11.2

Sample DataFrame

import pandas as pd
import seaborn as sns

df = pd.DataFrame({'X_Axis':[1,3,5,7,10,20],
                   'col_2':[.4,.5,.4,.5,.5,.4],
                   'col_3':[.7,.8,.9,.4,.2,.3],
                   'col_4':[.1,.3,.5,.7,.1,.0],
                   'col_5':[.5,.3,.6,.9,.2,.4]})

# display(df)
   X_Axis  col_2  col_3  col_4  col_5
0       1    0.4    0.7    0.1    0.5
1       3    0.5    0.8    0.3    0.3
2       5    0.4    0.9    0.5    0.6
3       7    0.5    0.4    0.7    0.9
4      10    0.5    0.2    0.1    0.2
5      20    0.4    0.3    0.0    0.4

# convert to long (tidy) form
dfm = df.melt('X_Axis', var_name='cols', value_name='vals')

# display(dfm.head())
   X_Axis   cols  vals
0       1  col_2   0.4
1       3  col_2   0.5
2       5  col_2   0.4
3       7  col_2   0.5
4      10  col_2   0.5
```
<h2>Current Plot Methods</h2>
<h3><code>catplot</code>: figure-level</h3>
<p>Use <code>seaborn.catplot</code> with <code>kind=</code> (e.g. <code>kind='point'</code> to reproduce the <code>FactorPlot</code> default):</p>
<pre class="lang-py prettyprint-override"><code>g = sns.catplot(x="X_Axis", y="vals", hue='cols', data=dfm, kind='point')
</code>```

pointplot: axes-level

sns.pointplot(x="X_Axis", y="vals", hue='cols', data=dfm)
```
<p><img src="https://i.stack.imgur.com/qdcAq.png" alt="enter image description here" /></p>
<h2>Original</h2>
<h3><code>factorplot</code>: was renamed to <code>catplot</code> v0.9.0 (July 2018)</h3>
<p>New versions of seaborn get warning:</p>
<blockquote>
<p>The <code>factorplot</code> function has been renamed to <code>catplot</code>. The original name will be removed in a future release. Please update your code. Note that the default <code>kind</code> in <code>factorplot</code> (<code>'point'</code>) has changed <code>'strip'</code> in <code>catplot</code>.</p>
</blockquote>
<pre class="lang-py prettyprint-override"><code>g = sns.factorplot(x="X_Axis", y="vals", hue='cols', data=dfm)

# using pd.melt instead of pd.DataFrame.melt for pandas < 0.20.0
# dfm = pd.melt(df, 'X_Axis', var_name='cols',  value_name='vals')
# g = sns.factorplot(x="X_Axis", y="vals", hue='cols', data=dfm)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Some seaborn plots will accept a wide dataframe, sns.pointplot(data=df, x='X_Axis', y='col_2'), but not sns.pointplot(data=df, x='X_Axis', y=['col_2', 'col_3']), so it's better to reshape the DataFrame.

Reshape the DataFrame from wide to long with pandas.DataFrame.melt.

Converting the dataframe from a wide to long form is standard for all seaborn plots, not just the examples shown.

Tested in python 3.8.12, pandas 1.3.4, matplotlib 3.4.3, seaborn 0.11.2

Sample DataFrame

import pandas as pd
import seaborn as sns

df = pd.DataFrame({'X_Axis':[1,3,5,7,10,20],
                   'col_2':[.4,.5,.4,.5,.5,.4],
                   'col_3':[.7,.8,.9,.4,.2,.3],
                   'col_4':[.1,.3,.5,.7,.1,.0],
                   'col_5':[.5,.3,.6,.9,.2,.4]})

# display(df)
   X_Axis  col_2  col_3  col_4  col_5
0       1    0.4    0.7    0.1    0.5
1       3    0.5    0.8    0.3    0.3
2       5    0.4    0.9    0.5    0.6
3       7    0.5    0.4    0.7    0.9
4      10    0.5    0.2    0.1    0.2
5      20    0.4    0.3    0.0    0.4

# convert to long (tidy) form
dfm = df.melt('X_Axis', var_name='cols', value_name='vals')

# display(dfm.head())
   X_Axis   cols  vals
0       1  col_2   0.4
1       3  col_2   0.5
2       5  col_2   0.4
3       7  col_2   0.5
4      10  col_2   0.5

Current Plot Methods

catplot: figure-level

Use seaborn.catplot with kind= (e.g. kind='point' to reproduce the FactorPlot default):

g = sns.catplot(x="X_Axis", y="vals", hue='cols', data=dfm, kind='point')

pointplot: axes-level

sns.pointplot(x="X_Axis", y="vals", hue='cols', data=dfm)

Original

factorplot: was renamed to catplot v0.9.0 (July 2018)

New versions of seaborn get warning:

The factorplot function has been renamed to catplot. The original name will be removed in a future release. Please update your code. Note that the default kind in factorplot ('point') has changed 'strip' in catplot.

g = sns.factorplot(x="X_Axis", y="vals", hue='cols', data=dfm)

# using pd.melt instead of pd.DataFrame.melt for pandas < 0.20.0
# dfm = pd.melt(df, 'X_Axis', var_name='cols',  value_name='vals')
# g = sns.factorplot(x="X_Axis", y="vals", hue='cols', data=dfm)


问:
How do I get value after selected from dropdown menu with Python?
I want the last value from this dropdown menu.

```<code><select id="VersionValue">
  <option value="0">Select Version</option>
  <option value="1110.0">1110.0</option>
  <option value="1111.0">1111.0</option>
  <option value="1112.0">1112.0</option>
  <option value="1113.0">1113.0</option>
  <option value="1114.0">1114.0</option>
</select>
</code>```

My code in python to get last dropdown menu

```<code>    select = Select(driver.find_element_by_id("VersionValue"))
    selectLen = len(select.options)
    select.select_by_index(selectLen - 1)
</code>```

How do I get value after selected from dropdown menu with Python?
I use selenium library for python.

答:
Here is the Answer to your Question:

```<code>select = Select(driver.find_element_by_id("VersionValue"))
select.select_by_value("1114.0")
</code>```

Let me know if this Answers your Question.

Body:
I want the last value from this dropdown menu.

<select id="VersionValue">
  <option value="0">Select Version</option>
  <option value="1110.0">1110.0</option>
  <option value="1111.0">1111.0</option>
  <option value="1112.0">1112.0</option>
  <option value="1113.0">1113.0</option>
  <option value="1114.0">1114.0</option>
</select>

My code in python to get last dropdown menu

    select = Select(driver.find_element_by_id("VersionValue"))
    selectLen = len(select.options)
    select.select_by_index(selectLen - 1)

How do I get value after selected from dropdown menu with Python?
I use selenium library for python.

Body:
Here is the Answer to your Question:

select = Select(driver.find_element_by_id("VersionValue"))
select.select_by_value("1114.0")

Let me know if this Answers your Question.


问:
Cannot run peer because cannot init crypto
I want to run the facbar-samples on windows10,reference the http://hyperledger-fabric.readthedocs.io/en/latest/write_first_app.html but get the error:

```<code>$ ./startFabric.sh
orderer.example.com is up-to-date
couchdb is up-to-date
peer0.org1.example.com is up-to-date
cli is up-to-date
2017-07-05 08:17:06.550 UTC [main] main -> ERRO 001 Cannot run peer because
cannot init crypto, missing /etc/hyperledger/fabric/C:/Program
Files/Git/etc/hyperledger/msp/users/Admin@org1.example.com/msp folder
</code>```

some that I have installed:

```<code>$ npm -v
5.0.4
$ node -v
v6.11.0
$ curl -V
curl 7.54.0 (x86_64-w64-mingw32) libcurl/7.54.0 OpenSSL/1.0.2l zlib/1.2.11
libssh2/1.8.0 nghttp2/1.23.1 librtmp/2.3
Protocols: dict file ftp ftps gopher http https imap imaps ldap ldaps pop3
pop3s rtmp rtsp scp sftp smtp smtps telnet tftp
Features: IPv6 Largefile SSPI Kerberos SPNEGO NTLM SSL libz TLS-SRP HTTP2
HTTPS-proxy Metalink

$ docker --version
Docker version 17.06.0-ce, build 02c1d87

$ docker-compose --version
docker-compose version 1.14.0, build c7bdf9e3

$ git --version
git version 2.13.1.windows.2
</code>```

Please help ,Thanks.

答:
Before you run the fabcar-samples, I think that you have to execute some steps from the "Building Your First Network" chapter. It seems that you haven't got the required certificates to start the network. Also, you should generate the genesis block, the channel configuration transaction and the anchor peers.

You can do it by executing the ./byfn.sh -m generate command. For more information: http://hyperledger-fabric.readthedocs.io/en/latest/build_network.html#generate-network-artifacts

Body:
I want to run the facbar-samples on windows10,reference the http://hyperledger-fabric.readthedocs.io/en/latest/write_first_app.html but get the error:

$ ./startFabric.sh
orderer.example.com is up-to-date
couchdb is up-to-date
peer0.org1.example.com is up-to-date
cli is up-to-date
2017-07-05 08:17:06.550 UTC [main] main -> ERRO 001 Cannot run peer because
cannot init crypto, missing /etc/hyperledger/fabric/C:/Program
Files/Git/etc/hyperledger/msp/users/Admin@org1.example.com/msp folder

some that I have installed:

$ npm -v
5.0.4
$ node -v
v6.11.0
$ curl -V
curl 7.54.0 (x86_64-w64-mingw32) libcurl/7.54.0 OpenSSL/1.0.2l zlib/1.2.11
libssh2/1.8.0 nghttp2/1.23.1 librtmp/2.3
Protocols: dict file ftp ftps gopher http https imap imaps ldap ldaps pop3
pop3s rtmp rtsp scp sftp smtp smtps telnet tftp
Features: IPv6 Largefile SSPI Kerberos SPNEGO NTLM SSL libz TLS-SRP HTTP2
HTTPS-proxy Metalink

$ docker --version
Docker version 17.06.0-ce, build 02c1d87

$ docker-compose --version
docker-compose version 1.14.0, build c7bdf9e3

$ git --version
git version 2.13.1.windows.2

Please help ,Thanks.


问:
.Net SslStream works normally in desktop but not in session 0 (Windows Service Session)
I have this code, which establishes a SSL encrypted Stream to a server over TCP:

```<code>var client = new TcpClient(host, port);

var stream = new SslStream(client.GetStream(), false, ValidateServerCertificate);

var clientCertificates = new X509CertificateCollection {clientCertificate};

stream.AuthenticateAsClient(host, clientCertificates, sslProtocols, false);

var isAuthenticated = stream.IsAuthenticated; //This is true in both Console and Windows Service

var lenghtBytes = new byte[4];

int read = 0;

while (read < 4)
{
    read = read + stream.Read(lenghtBytes, read, 4 - read);
}
</code>```

Which works perfectly fine when running as a regular Console app as Administrator user.

However the same code keeps looping in the while loop meant for reading the first 4 bytes of the stream when the app is registered and ran as a Windows Service (in Session 0), as Local System user.

While debugging, as the Console app, the while loop receives all 4 bytes on the first loop and exits the loop right after the first turn, however when ran as a Windows Service, stream doesn't receive any bytes (read is always 0) and just keeps looping forever.

Code is running on a Windows Server 2012 R2 machine with latest updates installed, on .Net Framework v4.6.2.

Any hint is highly appreciated.

答:
When you run as a Local System,the ssl handshake can run into error based on the Root certificate availability ,proxy settings etc as these are User specific for windows.It will be difficult to understand where the problem is without debugging the issue.

You can run any process under Local System using sys internal utility PsExec. The command you have to use is psexec -s <programpath>

```<code>C:\windows\system32>psexec -s cmd.exe

PsExec v2.2 - Execute processes remotely
Copyright (C) 2001-2016 Mark Russinovich
Sysinternals - www.sysinternals.com

Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

C:\windows\system32>whoami
nt authority\system
</code>```

Once u have run your tool under local system,you can debug it to find out what is happening.If that does not help,you can also capture a system.net  this   or this

Hope it helps!

Body:
I have this code, which establishes a SSL encrypted Stream to a server over TCP:

var client = new TcpClient(host, port);

var stream = new SslStream(client.GetStream(), false, ValidateServerCertificate);

var clientCertificates = new X509CertificateCollection {clientCertificate};

stream.AuthenticateAsClient(host, clientCertificates, sslProtocols, false);

var isAuthenticated = stream.IsAuthenticated; //This is true in both Console and Windows Service

var lenghtBytes = new byte[4];

int read = 0;

while (read < 4)
{
    read = read + stream.Read(lenghtBytes, read, 4 - read);
}

Which works perfectly fine when running as a regular Console app as Administrator user.

However the same code keeps looping in the while loop meant for reading the first 4 bytes of the stream when the app is registered and ran as a Windows Service (in Session 0), as Local System user.

While debugging, as the Console app, the while loop receives all 4 bytes on the first loop and exits the loop right after the first turn, however when ran as a Windows Service, stream doesn't receive any bytes (read is always 0) and just keeps looping forever.

Code is running on a Windows Server 2012 R2 machine with latest updates installed, on .Net Framework v4.6.2.

Any hint is highly appreciated.

Body:
When you run as a Local System,the ssl handshake can run into error based on the Root certificate availability ,proxy settings etc as these are User specific for windows.It will be difficult to understand where the problem is without debugging the issue.

You can run any process under Local System using sys internal utility PsExec. The command you have to use is psexec -s <programpath>

C:\windows\system32>psexec -s cmd.exe

PsExec v2.2 - Execute processes remotely
Copyright (C) 2001-2016 Mark Russinovich
Sysinternals - www.sysinternals.com

Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

C:\windows\system32>whoami
nt authority\system

Once u have run your tool under local system,you can debug it to find out what is happening.If that does not help,you can also capture a system.net  this   or this

Hope it helps!


问:
Terminate a loop with specific characters
I want to write a program that will terminate a loop with a specific character such as "Q" or "//" but can't seem to figure it out. here is the specifics

"A program that will compute the average of a set of decimal
  numbers provided by the user. The program will ask the user to enter
  numbers one at a time, and when the user enters q it stops and spits out the sum"

But this requires the user to enter in integers and if I enter a "Q" or "//" the program breaks and spits out junk. How do I do this?

The problem im running into is how to do this without asking for two different inputs

```<code>#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;

//variables
double avg, num;
char q;

int main()
{
    double sum = 0;
    int count1 = 0;
    while (q != 'q') {
        cout << "Enter a number" << endl;
        cin >> num;
        cin >> q;
        sum += num;
        count1 += 1;
    }
    avg = sum / count1;
    cout << "Sum: " << sum << endl;
    cout << "Count: " << count1 << endl;
    cout << "Average: " << avg << endl;
    return 0;
}
</code>```

答:
Assuming your assignment is really what you describe, then you will need to read a string, and then convert to double.

Something like this will work:

```<code>std::string s;
std::cin >> s;
if (s == "Q" || s == "//") { ... do stuff ... }
else
{
    std::stringstream ss(s);
    double d;
    if (!(ss >> d))
    {
        std::cout << s << " doesn't appear to be a number..." << std::endl;
    }
    ... do whatever with d ...
}
</code>```

I'm not writing the code for you, just providing some snippets to help you along.

Body:
I want to write a program that will terminate a loop with a specific character such as "Q" or "//" but can't seem to figure it out. here is the specifics

"A program that will compute the average of a set of decimal
  numbers provided by the user. The program will ask the user to enter
  numbers one at a time, and when the user enters q it stops and spits out the sum"

But this requires the user to enter in integers and if I enter a "Q" or "//" the program breaks and spits out junk. How do I do this?

The problem im running into is how to do this without asking for two different inputs

#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;

//variables
double avg, num;
char q;

int main()
{
    double sum = 0;
    int count1 = 0;
    while (q != 'q') {
        cout << "Enter a number" << endl;
        cin >> num;
        cin >> q;
        sum += num;
        count1 += 1;
    }
    avg = sum / count1;
    cout << "Sum: " << sum << endl;
    cout << "Count: " << count1 << endl;
    cout << "Average: " << avg << endl;
    return 0;
}

Body:
Assuming your assignment is really what you describe, then you will need to read a string, and then convert to double.

Something like this will work:

std::string s;
std::cin >> s;
if (s == "Q" || s == "//") { ... do stuff ... }
else
{
    std::stringstream ss(s);
    double d;
    if (!(ss >> d))
    {
        std::cout << s << " doesn't appear to be a number..." << std::endl;
    }
    ... do whatever with d ...
}

I'm not writing the code for you, just providing some snippets to help you along.


问:
How to read a VSTS tokenised secret build variable from a bash shell script?
Creating a build definition to build Xamarin.Android project and looking for an option to update the config file with app secrets using a bash shell script. The example given in Microsoft docs indicates that reading a secret build variable from a bash shell script is not possible. </p>

<p>Has anyone tried this before?
The build agent we are using is a Mac so we need a bash shell script rather than a powershell. </p>

答:
You need to pass the secret variable through the Arguments. The sample form that article:

Batch (But I can read %secretSauceArgument%):

Arguments:

```<code>"$(sauce)" "$(secretSauce)"
</code>```

Scripts:

```<code> @echo off
 set sauceArgument=%~1
    set secretSauceArgument=%~2
    @echo No problem reading %sauceArgument% or %SAUCE%
    @echo But I cannot read %SECRETSAUCE%
    @echo But I can read %secretSauceArgument% (but the log is redacted so I do not spoil the secret)
</code>```

Shell (But I can read $2):

Arguments:

```<code>"$(sauce)" "$(secretSauce)"
</code>```

Scripts:

```<code> #!/bin/bash
    echo "No problem reading $1 or $SAUCE"
    echo "But I cannot read $SECRETSAUCE"
    echo "But I can read $2 (but the log is redacted so I do not spoil the secret)"
</code>```

Body:
Creating a build definition to build Xamarin.Android project and looking for an option to update the config file with app secrets using a bash shell script. The example given in Microsoft docs indicates that reading a secret build variable from a bash shell script is not possible.

Has anyone tried this before?
The build agent we are using is a Mac so we need a bash shell script rather than a powershell.

Body:
You need to pass the secret variable through the Arguments. The sample form that article:

Batch (But I can read %secretSauceArgument%):

Arguments:

"$(sauce)" "$(secretSauce)"

Scripts:

 @echo off
 set sauceArgument=%~1
    set secretSauceArgument=%~2
    @echo No problem reading %sauceArgument% or %SAUCE%
    @echo But I cannot read %SECRETSAUCE%
    @echo But I can read %secretSauceArgument% (but the log is redacted so I do not spoil the secret)

Shell (But I can read $2):

Arguments:

"$(sauce)" "$(secretSauce)"

Scripts:

 #!/bin/bash
    echo "No problem reading $1 or $SAUCE"
    echo "But I cannot read $SECRETSAUCE"
    echo "But I can read $2 (but the log is redacted so I do not spoil the secret)"


问:
Generate heatmap in R (multiple independent variable)
There are a few similar questions but they are not asking what I am looking for.
I have a gene expression data with multiple independent variables. I want to visualize it using a heatmap in R. I am not able to include all the three variables together on the heatmap. Below is the example code:

```<code>species <- rep(c("st", "rt"), each = 18)
life <- rep(c("5d", "15d", "45d"), 2, each = 6)
concentration <- rep(c("c1", "c2", "c3"), 6, each = 2)
gene <- rep(c("gene1", "gene2"), 36, each = 1)
response <- runif(36, -4, 4)
data1 <- data.frame(species, life, concentration, gene, response)
</code>```

I am open to use any package. Please see below image which is from a different dataset. I wish to visualize my data in a similar manner.

example_data_visualized

Many thanks in advance!

答:
I am not sure which of the variables in your code correspond to which of the dimensions in your chart but, using the ggplot2 package, it's quite easy to do it:

```<code>library(ggplot2)

ggplot(data1, aes(x = factor(life, levels = c("5d", "15d", "45d")),
                  y = concentration,
                  fill = response)) +
  geom_tile() +
  facet_wrap(~species + gene, nrow = 1) +
  scale_fill_gradient(low = "red", high = "green", guide = FALSE) +
  scale_x_discrete(name = "life")
</code>```

Of course, you can adjust the titles, labels, colours etc accordingly.

Body:
There are a few similar questions but they are not asking what I am looking for.
I have a gene expression data with multiple independent variables. I want to visualize it using a heatmap in R. I am not able to include all the three variables together on the heatmap. Below is the example code:

species <- rep(c("st", "rt"), each = 18)
life <- rep(c("5d", "15d", "45d"), 2, each = 6)
concentration <- rep(c("c1", "c2", "c3"), 6, each = 2)
gene <- rep(c("gene1", "gene2"), 36, each = 1)
response <- runif(36, -4, 4)
data1 <- data.frame(species, life, concentration, gene, response)

I am open to use any package. Please see below image which is from a different dataset. I wish to visualize my data in a similar manner.

example_data_visualized

Many thanks in advance!

Body:
I am not sure which of the variables in your code correspond to which of the dimensions in your chart but, using the ggplot2 package, it's quite easy to do it:

library(ggplot2)

ggplot(data1, aes(x = factor(life, levels = c("5d", "15d", "45d")),
                  y = concentration,
                  fill = response)) +
  geom_tile() +
  facet_wrap(~species + gene, nrow = 1) +
  scale_fill_gradient(low = "red", high = "green", guide = FALSE) +
  scale_x_discrete(name = "life")

Of course, you can adjust the titles, labels, colours etc accordingly.


问:
NodeJS Async - Continue execution for multiple http requests even if some fail
I am trying to make multiple HTTP requests and cumulate, display the results in NodeJS using the following code:

```<code>const async = require('async');
const request = require('request');

function httpGet(url, callback) {
  const options = {
    url :  url,
    json : true
  };
  request(options,
    function(err, res, body) {
      console.log("invoked")
      callback(err, body);
    }
  ).on('error', function(err) {
    console.log(err)
  });
}

const urls= [
  "http://1.2.3.4:30500/status/health/summary",
  "http://5.6.7.8:30505/status/health/summary"
];

async.map(urls, httpGet, function (err, res){
  if (err)
    console.log(err);
  else
    console.log(res);
});
</code>```

The problem here is, if the first request(http://1.2.3.4:30500/status/health/summary) fails (like connection refused etc.), the second one does not go through. I know that I am making a silly mistake but cannot find it. Any help appreciated !

答:
In async.map if one of the calls passes an error to its callback, the main callback (for the map function) is immediately called with the error(this is the problem in your case). In order not to terminate on the first error, don't call the callback with err param in your httpGet.

Use async each, it receives a list of arguments and a function, and calls the function with each element, make sure in your httpGet inside on error you call the callback, without the err, this will make rest of the calls to continue even if there was an error in some of the calls. This can work for map too but, I think the more suitable function for your case is async.each, instead of map, also you can limit the number of concurrent calls with eachLimit method.

Check https://caolan.github.io/async/docs.html#each

```<code>const async = require('async');
const request = require('request');

function httpGet(url, callback) {
    const options = {
        url :  url,
        json : true
    };
    request(options,
        function(err, res, body) {
            if (err){
                console.log(err);
                callback();
                return;
            }
            console.log("invoked")
            callback(null, body);
        }
    ).on('error', function(err) {
        console.log(err);
        callback();
    });
}

const urls= [
    "http://1.2.3.4:30500/status/health/summary",
    "http://5.6.7.8:30505/status/health/summary"
];

async.each(urls, httpGet, function (err, res) {
}, function (err, res) {

});
</code>```

Body:
I am trying to make multiple HTTP requests and cumulate, display the results in NodeJS using the following code:

const async = require('async');
const request = require('request');

function httpGet(url, callback) {
  const options = {
    url :  url,
    json : true
  };
  request(options,
    function(err, res, body) {
      console.log("invoked")
      callback(err, body);
    }
  ).on('error', function(err) {
    console.log(err)
  });
}

const urls= [
  "http://1.2.3.4:30500/status/health/summary",
  "http://5.6.7.8:30505/status/health/summary"
];

async.map(urls, httpGet, function (err, res){
  if (err)
    console.log(err);
  else
    console.log(res);
});

The problem here is, if the first request(http://1.2.3.4:30500/status/health/summary) fails (like connection refused etc.), the second one does not go through. I know that I am making a silly mistake but cannot find it. Any help appreciated !

Body:
In async.map if one of the calls passes an error to its callback, the main callback (for the map function) is immediately called with the error(this is the problem in your case). In order not to terminate on the first error, don't call the callback with err param in your httpGet.

Use async each, it receives a list of arguments and a function, and calls the function with each element, make sure in your httpGet inside on error you call the callback, without the err, this will make rest of the calls to continue even if there was an error in some of the calls. This can work for map too but, I think the more suitable function for your case is async.each, instead of map, also you can limit the number of concurrent calls with eachLimit method.

Check https://caolan.github.io/async/docs.html#each

const async = require('async');
const request = require('request');

function httpGet(url, callback) {
    const options = {
        url :  url,
        json : true
    };
    request(options,
        function(err, res, body) {
            if (err){
                console.log(err);
                callback();
                return;
            }
            console.log("invoked")
            callback(null, body);
        }
    ).on('error', function(err) {
        console.log(err);
        callback();
    });
}

const urls= [
    "http://1.2.3.4:30500/status/health/summary",
    "http://5.6.7.8:30505/status/health/summary"
];

async.each(urls, httpGet, function (err, res) {
}, function (err, res) {

});


问:
Flask jsonify print results on new lines
First time using Flask, I have created a very basic app and I am trying to print the results of a recommender system. The first set of code is from my python function (print_most_similar) and is creating a formatted string in hopes to print every REC on a new line. The second section of code is obviously my flask routing. You can see that the flask part calls the function, so it is returned 'y'.
I believe the jsonify will not take the \n characters.
I have tried using just '\n' in the string formatting, but it just appears as a string. As does '\t'.

```<code>for k in range(len(sugg)):
    x = str("REC {}: {}\\n".format(k+1, sugg[k]))
    y += x
return y

@app.route("/getrecomm",methods=['GET','POST'])
def getrecomm():
    restname = request.args.get('restname', type=str)
    number = request.args.get('number', type=int)
    i = getBusIndex(restname, names)
return make_response(jsonify(result=(print_most_similar(rating, names, i, number))),200)
</code>```

Currently, the results print like this:
REC 1: Harbor House Cafe & Lounge\nREC 2: Starbucks\nREC 3: McDonald's\nREC 4: Taco Bell\nREC 5: Panda Express\n

I would like them to print like this:
REC 1: Harbor House Cafe & Lounge
REC 2: Starbucks
REC 3: McDonald's
REC 4: Taco Bell
REC 5: Panda Express

I'm using python 3, fyi. Any suggestions would be super appreciated!

答:
Summary

Answer:

Alternative: JSONView Chrome Extension

The only one that give me good results was
:

Example

```<code>from flask import Flask, jsonify

app = Flask(__name__)

tasks = [
    {
        '<br>id': 1,
        'title': u'Buy groceries',
        'description': u'Milk, Cheese, Pizza, Fruit, Tylenol',
        'done': False
    },
    {
        '<br>id': 2,
        'title': u'Learn Python',
        'description': u'Need to find a good Python tutorial on the web',
        'done': False
    }
]

@app.route('/todo/api/v1.0/tasks', methods=['GET'])
def get_tasks():
    return jsonify({'tasks': tasks})

if __name__ == '__main__':
    app.run(debug=True)
</code>```

In your browser the
 character will be rendered as html and reproduce a new line.

Result:

 "creates" new lines in json

Jsonify can't help you because it takes the values (integer,boolean,float, etc) as a string and avoid special characters like \n, \t, etc

Finally, if you just want a fancy way to visualize json files in your browser, you could use JSONView, is a Chrome extension that render Json files in a more understandable way, like this.

rendering with JSONView

Body:
First time using Flask, I have created a very basic app and I am trying to print the results of a recommender system. The first set of code is from my python function (print_most_similar) and is creating a formatted string in hopes to print every REC on a new line. The second section of code is obviously my flask routing. You can see that the flask part calls the function, so it is returned 'y'.
I believe the jsonify will not take the \n characters.
I have tried using just '\n' in the string formatting, but it just appears as a string. As does '\t'.

for k in range(len(sugg)):
    x = str("REC {}: {}\\n".format(k+1, sugg[k]))
    y += x
return y

@app.route("/getrecomm",methods=['GET','POST'])
def getrecomm():
    restname = request.args.get('restname', type=str)
    number = request.args.get('number', type=int)
    i = getBusIndex(restname, names)
return make_response(jsonify(result=(print_most_similar(rating, names, i, number))),200)

Currently, the results print like this:
REC 1: Harbor House Cafe & Lounge\nREC 2: Starbucks\nREC 3: McDonald's\nREC 4: Taco Bell\nREC 5: Panda Express\n

I would like them to print like this:
REC 1: Harbor House Cafe & Lounge
REC 2: Starbucks
REC 3: McDonald's
REC 4: Taco Bell
REC 5: Panda Express

I'm using python 3, fyi. Any suggestions would be super appreciated!

Body:
Summary

Answer: <br>

Alternative: JSONView Chrome Extension

The only one that give me good results was <br>:

Example

from flask import Flask, jsonify

app = Flask(__name__)

tasks = [
    {
        '<br>id': 1,
        'title': u'Buy groceries',
        'description': u'Milk, Cheese, Pizza, Fruit, Tylenol',
        'done': False
    },
    {
        '<br>id': 2,
        'title': u'Learn Python',
        'description': u'Need to find a good Python tutorial on the web',
        'done': False
    }
]

@app.route('/todo/api/v1.0/tasks', methods=['GET'])
def get_tasks():
    return jsonify({'tasks': tasks})

if __name__ == '__main__':
    app.run(debug=True)

In your browser the <br> character will be rendered as html and reproduce a new line.

Result:

 "creates" new lines in json

Jsonify can't help you because it takes the values (integer,boolean,float, etc) as a string and avoid special characters like \n, \t, etc

Finally, if you just want a fancy way to visualize json files in your browser, you could use JSONView, is a Chrome extension that render Json files in a more understandable way, like this.

rendering with JSONView


问:
datepicker not working after making ajax call
//here the code for calling date picker

```<code> <script type="text/javascript">
     $(function () {
       $(".datepicker").datepicker({
        constrainInput: true,
        showOn: 'button',
        buttonText: 'Select...'
    });

});
</script>
<input class="datepicker" disabled="disabled" />
</code>```

//Here Im making an ajax call

```<code>function reFresh(name){
            $.ajax({
            type:"GET",
            url:"Phase",
            data:{projectName:name},
            async: false,
            dataType:"html",
            success:function(data) {
               $("#Left_Panel").html(data);

            },
            error:function() {
                alert("Error ! In fetching data.");
            }
        })

}
</code>```

// After coming to the first page again using ajax , now datepicker not working .

答:
Assuming the element holding the datepicker is contained in the #Left_Panel element, then the issue is because that element is destroyed and re-created, hence the original event handler is lost. To fix this, you need to reinstantiate the library on the element after the AJAX completes.

Also note that using aysnc: false is very bad practice - in fact the browser will be giving you a warning in the console telling you not to do it.

Try this:

```<code>function reFresh(name){
  $.ajax({
    type: "GET",
    url: "Phase",
    data: { projectName: name },
    dataType: "html",
    success: function(data) {
      $("#Left_Panel").html(data).find('.datepicker').datepicker({
        constrainInput: true,
        showOn: 'button',
        buttonText: 'Select...'
      });
    },
    error: function() {
      alert("Error ! In fetching data.");
    }
  })
}
</code>```

Body:
//here the code for calling date picker

<input class="datepicker" disabled="disabled" />

//Here Im making an ajax call

function reFresh(name){
            $.ajax({
            type:"GET",
            url:"Phase",
            data:{projectName:name},
            async: false,
            dataType:"html",
            success:function(data) {
               $("#Left_Panel").html(data);

            },
            error:function() {
                alert("Error ! In fetching data.");
            }
        })

}

// After coming to the first page again using ajax , now datepicker not working .

Body:
Assuming the element holding the datepicker is contained in the #Left_Panel element, then the issue is because that element is destroyed and re-created, hence the original event handler is lost. To fix this, you need to reinstantiate the library on the element after the AJAX completes.

Also note that using aysnc: false is very bad practice - in fact the browser will be giving you a warning in the console telling you not to do it.

Try this:

function reFresh(name){
  $.ajax({
    type: "GET",
    url: "Phase",
    data: { projectName: name },
    dataType: "html",
    success: function(data) {
      $("#Left_Panel").html(data).find('.datepicker').datepicker({
        constrainInput: true,
        showOn: 'button',
        buttonText: 'Select...'
      });
    },
    error: function() {
      alert("Error ! In fetching data.");
    }
  })
}


问:
Use a sub-domain for a API-gateway/Lambda
I am integrating a web-relay into AWS-service which makes call-outs to a predefined path (
/some-fixed-path and it can not be configured) and I want to intercept it using a lambda on dedicated sub-domain, to keep this separated from the rest of our service, so I want the call-out to be http://subdomain.example.com/some-fixed-path.

I have a domain (lets call it example.com) registered and I have a hosted-zone defined. How can i create a record-set in the hosted-zone and use it in the API-gateway definition? (The url must not contain the stage...)

In the API-gateway definition, there is a "Custom domain name" option, but I can't figure out how to point to a record from my hosted-zone.

答:
AWS has a detailed guide about how to do that exactly.

A few more things to pay attention to are:

Make sure you remember to re-deploy when you make any change to the API.

When you set up Base Path Mapping, make sure double check the API resource path and method. (For example, if you create the API gateway through lambda template, the API resource will be created under /{API name} instead of /).

A lot of people see Missing Authentication Token when they use API gateway for the first time due to those reasons.


问:
Jquery still running the previous code and ignoring changes
I have a .js file that whatever changes I do (I even delete all the codes) it doesn't recognize or run the new changes, it just run the last code I saved days ago.

Here is what I did before encountering this problem.

I made a copy of my project and save it in different folder(location) and now I deleted the original and used the copied one. I made some changes on the .js file but doesn't run the new changes. Anyone know the solution to this?

I tried cleaning and building the solution but it doesn't work.

答:
Sounds like a caching problem, did you try reloading without cache or doing a "hard reload"?

Open devtools (F12), right click the refresh button then press "Empty Cache and Hard Reload".


问:
Quartz.NET RemoteScheduler with AdoJobStore unable to find assembly
HI All,

I have successfully created a Quartz.NET remote server running inside a windows service. I followed examples 12 in the source and slightly modified it to use AdoJobStore with sqlite.

On remote client I created a windows form application and successfully connected with the server. Everything went fine until the point where I'm trying to actually add jobs.

```<code>        JobDetail detail = new JobDetail(job.JobName, "default", typeof(NativeJob));
        detail.Description = job.Description;
        JobDataMap map = new JobDataMap();
        map.Put(NativeJob.PropertyCommand, job.Command);
        map.Put(NativeJob.PropertyParameters, job.Arguments);
        detail.JobDataMap = map;

        // create trigger
        Trigger trigger = new CronTrigger(job.JobName, "default", job.CronExpression);

        //Add job w/ trigger
        _scheduler.ScheduleJob(detail, trigger);
</code>```

The last line above failed with Exception :

Unable to find assembly 'System.Data.SQLite, Version=1.0.66.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139'.

The SQLite assembly is there. Oddly enough this doesn't happen when I'm using RamJobStore. Anybody please help.

答: You're probably running into the SQlite x86 vs x64 issue or the SQlite on .NET 4 issue.</p>

Body:
HI All,

I have successfully created a Quartz.NET remote server running inside a windows service. I followed examples 12 in the source and slightly modified it to use AdoJobStore with sqlite.

On remote client I created a windows form application and successfully connected with the server. Everything went fine until the point where I'm trying to actually add jobs.

        JobDetail detail = new JobDetail(job.JobName, "default", typeof(NativeJob));
        detail.Description = job.Description;
        JobDataMap map = new JobDataMap();
        map.Put(NativeJob.PropertyCommand, job.Command);
        map.Put(NativeJob.PropertyParameters, job.Arguments);
        detail.JobDataMap = map;

        // create trigger
        Trigger trigger = new CronTrigger(job.JobName, "default", job.CronExpression);

        //Add job w/ trigger
        _scheduler.ScheduleJob(detail, trigger);

The last line above failed with Exception :

Unable to find assembly 'System.Data.SQLite, Version=1.0.66.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139'.

The SQLite assembly is there. Oddly enough this doesn't happen when I'm using RamJobStore. Anybody please help.


问:
Self registering Classes
I am currently starting developing an Alexa Skill in C#. As I did not want to have a messy if block checking the intent type of an incoming request I got the following idea:
Writing a static class RequestHandler which stores a list of all possible intents (List of IIntent interface which will be implemented by classes which represent an intent).

I know have the conceptional problem, that I do not know what the best way to register those intents might be. My first idea was to just write

```<code>internal static void RegisterIntent(IIntent intent) => Intents.Add(intent);
</code>```

and call this in static constructors of each intent. At this point I didn´t know static constructors only will be executed the first time the class will be accessed. So this idea is not working as I thought.
The other ideas I for know can think of, are:

adding a static Initialize / Register method to each intent class in which it creates an instance which will be added into the static intent list --> this will result in a lot of initiliaze methods I would have to add manually to the executed lambda function.

adding an Initialize method to the static RequestHandler which will add an instance of each intent class to the static list --> I still would have to manually write the RegisterIntent(new ABCIntent()) command for each intent class.

Is there a way to get all intent classes be added into the static list without adding code for this register action manually? Or are there better ways to achieve this than those two ones I had so far? Maybe with reflection (tbh: I am quite new to AWS lamda development and I do not know if this will work).

答:
I meanwhile changed the registration using reflection. So I can search for all classes implementing the IIntent interface in the static constructor of the request handler.

```<code>    static RequestHandler()
    {
        var assembly = typeof(RequestHandler).GetTypeInfo().Assembly;

        foreach (var t in assembly.GetTypes())
        {
            if (t.GetInterfaces().Contains(typeof(IIntent)))
            {
                Intents.Add(Activator.CreateInstance(t) as IIntent);
            }
        }
    }
</code>```

Or are there any better proposals?

Title: Self registering Classes

Body:
I am currently starting developing an Alexa Skill in C#. As I did not want to have a messy if block checking the intent type of an incoming request I got the following idea:
Writing a static class RequestHandler which stores a list of all possible intents (List of IIntent interface which will be implemented by classes which represent an intent).

I know have the conceptional problem, that I do not know what the best way to register those intents might be. My first idea was to just write

internal static void RegisterIntent(IIntent intent) => Intents.Add(intent);

and call this in static constructors of each intent. At this point I didn´t know static constructors only will be executed the first time the class will be accessed. So this idea is not working as I thought.
The other ideas I for know can think of, are:

adding a static Initialize / Register method to each intent class in which it creates an instance which will be added into the static intent list --> this will result in a lot of initiliaze methods I would have to add manually to the executed lambda function.

adding an Initialize method to the static RequestHandler which will add an instance of each intent class to the static list --> I still would have to manually write the RegisterIntent(new ABCIntent()) command for each intent class.

Is there a way to get all intent classes be added into the static list without adding code for this register action manually? Or are there better ways to achieve this than those two ones I had so far? Maybe with reflection (tbh: I am quite new to AWS lamda development and I do not know if this will work).

Body:
I meanwhile changed the registration using reflection. So I can search for all classes implementing the IIntent interface in the static constructor of the request handler.

    static RequestHandler()
    {
        var assembly = typeof(RequestHandler).GetTypeInfo().Assembly;

        foreach (var t in assembly.GetTypes())
        {
            if (t.GetInterfaces().Contains(typeof(IIntent)))
            {
                Intents.Add(Activator.CreateInstance(t) as IIntent);
            }
        }
    }

Or are there any better proposals?


问:
Compare passwords if hashed using random salt with sha512?
I think there is a contradiction about the recommendations how to store password in database.
We hash the password and store it in DB, and when a user tries login, we hash his input string the same way and compare to the DB. that's fine.
But there are recommendations to strengthen that hash by adding a random salt.
here is the problem:
So we lose the whole point of comparison, because the salt values will be different between the first hash to store in DB and the salt when login??
If to store in Db the salt, so what is the benefit is salting at all?</p>

答:
The reason why we generate a random salt for each password is, that one cannot build a single rainbowtable to get all passwords at once. Instead an attacker has to build a rainbowtable for each salt/password. Building a rainbowtable to get a single password is pointless, because you can stop searching if you found a match.

In other words, salting prevents the usage of rainbowtables. This purpose is fulfilled even if the salt is known, one still has to build a rainbowtable per password, that's why we can store the salt together with the hash in the database.

Btw: The SHA-* hash functions are not appropriate to hash passwords, instead one should use a password-hash function like BCrypt, SCrypt, PBKDF2 or Argon2. They all have a cost factor to make hashing slow.

Edit

Following examples are only for better understanding, the salt should not be added this way:

```<code>1. Example with the same (global) salt for all passwords:

hash("Password1"+"o9*eiwrC49YAS2395%tu") => hash1
hash("Password2"+"o9*eiwrC49YAS2395%tu") => hash2
hash("Password3"+"o9*eiwrC49YAS2395%tu") => hash3
</code>```

To find out Password1, we can build 1 lookup table with all reasonable passwords and the global salt. To find out Password2 we can reuse the same lookup table, because all passwords use the same global salt.

```<code>2. Example with unique salts for each password:

hash("Password4"+"ierukElasidj42Swiekq") => hash4
hash("Password5"+"oeuoElwWPJckfk212344") => hash5
hash("Password6"+"PoiMnmdvhas98akd73lk") => hash6
</code>```

To find out Password4 we would have to build 1 lookup table with all reasonable passwords and the salt "ierukElasidj42Swiekq". To find out the Password5 one has to build another lookup table with the salt "oeuoElwWPJckfk212344" and so on. The first example required 1 lookup table, the second example requires as many lookup tables as passwords.

Body:
The reason why we generate a random salt for each password is, that one cannot build a single rainbowtable to get all passwords at once. Instead an attacker has to build a rainbowtable for each salt/password. Building a rainbowtable to get a single password is pointless, because you can stop searching if you found a match.

In other words, salting prevents the usage of rainbowtables. This purpose is fulfilled even if the salt is known, one still has to build a rainbowtable per password, that's why we can store the salt together with the hash in the database.

Btw: The SHA-* hash functions are not appropriate to hash passwords, instead one should use a password-hash function like BCrypt, SCrypt, PBKDF2 or Argon2. They all have a cost factor to make hashing slow.

Edit

Following examples are only for better understanding, the salt should not be added this way:

1. Example with the same (global) salt for all passwords:

hash("Password1"+"o9*eiwrC49YAS2395%tu") => hash1
hash("Password2"+"o9*eiwrC49YAS2395%tu") => hash2
hash("Password3"+"o9*eiwrC49YAS2395%tu") => hash3

To find out Password1, we can build 1 lookup table with all reasonable passwords and the global salt. To find out Password2 we can reuse the same lookup table, because all passwords use the same global salt.

2. Example with unique salts for each password:

hash("Password4"+"ierukElasidj42Swiekq") => hash4
hash("Password5"+"oeuoElwWPJckfk212344") => hash5
hash("Password6"+"PoiMnmdvhas98akd73lk") => hash6

To find out Password4 we would have to build 1 lookup table with all reasonable passwords and the salt "ierukElasidj42Swiekq". To find out the Password5 one has to build another lookup table with the salt "oeuoElwWPJckfk212344" and so on. The first example required 1 lookup table, the second example requires as many lookup tables as passwords.


问:
ASP.Net Custom Errors is not working
I placed thin on my web.config file

```<code><customErrors mode="On" defaultRedirect="~/ErrorPages/Oops.aspx">
<error statusCode="404" redirect="~/ErrorPages/PageNotFound.html" />
</customErrors>
</code>```

to redirect my custom 404 page not found on the file above. But its not working.

Do I need to add other configurations and code to make this work? Am I missing something? That's the only configuration I did.

答:
try this code</p>

```<code>  <system.webServer>
<httpErrors errorMode="Custom" existingResponse="Auto"   >
  <remove statusCode="404" subStatusCode="-1" />
  <remove statusCode="500" subStatusCode="-1" />
  <error statusCode="404" path="/ErrorPage.aspx" responseMode="ExecuteURL"  />
  <error statusCode="500" path="/ErrorPage.aspx" responseMode="Redirect" />
</httpErrors>
  </system.webServer>
</code>```

Title: ASP.Net Custom Errors is not working

Body:
I placed thin on my web.config file

<customErrors mode="On" defaultRedirect="~/ErrorPages/Oops.aspx">
<error statusCode="404" redirect="~/ErrorPages/PageNotFound.html" />
</customErrors>

to redirect my custom 404 page not found on the file above. But its not working.

Do I need to add other configurations and code to make this work? Am I missing something? That's the only configuration I did.

Body:
try this code

  <system.webServer>
<httpErrors errorMode="Custom" existingResponse="Auto"   >
  <remove statusCode="404" subStatusCode="-1" />
  <remove statusCode="500" subStatusCode="-1" />
  <error statusCode="404" path="/ErrorPage.aspx" responseMode="ExecuteURL"  />
  <error statusCode="500" path="/ErrorPage.aspx" responseMode="Redirect" />
</httpErrors>
  </system.webServer>


问:
Missing "access-control-allow-origin" in PUT response header of GCS resumable upload
I am currently trying to implement resumable upload from a web browser to a google cloud storage bucket. I am using the documented procedure as follows:

1) initiate the resumable upload via a http POST send from the web server to GCS.

2) send the returned upload url to the browser and issue a Http PUT via XmlHttpRequest to upload the data.

Everything seems to work well until the very end. I.e. the browser first sends  the OPTIONS preflight request which returns OK (200) and then a PUT request during which the file is uploaded. The PUT also return OK(200) but contains no Access-Control-Allow-Origin in the header. This will then cause the XmlHttpRequest to trigger an error.

I cannot figure out why this header field is not returned. I think from the GCS side the upload was successful as the file actually appears in the bucket. However, the browser believes an error occurred. Here is HTTP record taken right out of the Chrome developer console.

OPTIONS Request

Request URL: "https://" BUCKET.storage-upload.googleapis.com/1485967698353.e57?upload_id=AEnB2UohgRBG272hoHLZ9i-wLeTn45KKoMjTDEQGu-GoUl-1JQf5_sOnf7IjtpN0wuYzHgzEu3Qi9tpVHGrru--cwY7q2jNQdw

Request Method:OPTIONS

Status Code:200

Remote Address:[2607:f8b0:4009:811::2010]:443

OPTIONS Response Header

access-control-allow-credentials:true

access-control-allow-headers:content-range, content-type, x-upload-content-type

access-control-allow-methods:PUT

access-control-allow-origin:http://www.example.com

alt-svc:quic=":443"; ma=2592000; v="35,34"

content-length:0

content-type:text/html; charset=UTF-8

date:Wed, 01 Feb 2017 16:48:18 GMT

server:UploadServer

status:200

PUT Request

Request URL: "https:"//BUCKET.storage-upload.googleapis.com/1485967698353.e57?upload_id=AEnB2UohgRBG272hoHLZ9i-wLeTn45KKoMjTDEQGu-GoUl-1JQf5_sOnf7IjtpN0wuYzHgzEu3Qi9tpVHGrru--cwY7q2jNQdw

Request Method:PUT

Status Code:200

Remote Address:[2607:f8b0:4009:811::2010]:443

PUT Response Headers

alt-svc:quic=":443"; ma=2592000; v="35,34"

content-length:0

content-type:text/html; charset=UTF-8

date:Wed, 01 Feb 2017 16:48:19 GMT

etag:"c6f30652db5986aec4c00e80a9d00f25"

server:UploadServer

status:200

vary:Origin

x-goog-generation:1485967699029000

x-goog-hash:md5=xvMGUttZhq7EwA6AqdAPJQ==

x-goog-hash:crc32c=/vx4zQ==

x-goog-metageneration:1

x-goog-stored-content-encoding:identity

x-goog-stored-content-length:743424

x-guploader-uploadid:AEnB2UohgRBG272hoHLZ9i-wLeTn45KKoMjTDEQGu-GoUl-1JQf5_sOnf7IjtpN0wuYzHgzEu3Qi9tpVHGrru--cwY7q2jNQdw

So, there is no "access-control-allow-origin" in the PUT response. When I use a signed URL to perform an upload GCS actually returns the "Access-Control-Allow-Origin". However this will not be a resumable upload which I absolutely need.

This problem is almost identical to

XMLHttpRequest CORS to Google Cloud Storage only working in preflight request

but the solution given there has no effect. Here is the original request to initiate the upload (tokens are no real and there are quotes around "http/s" to scramble links). The "origin" is in the request.

POST "https"://BUCKET.storage-upload.googleapis.com/1485967698353.e57

Accept-Encoding: gzip

Authorization: Bearer 2342342234234234234234234234-234234234234234234234234234234234234234234234234sxx-FSpWkCqI0BCRWoG2342423s423423423A4234_234E23s423i423423423423423423423423423234234234234234234234234234234234234234234234234X

User-Agent: Google-HTTP-Java-Client/1.22.0 (gzip)

x-goog-resumable: start

origin: "http:"/www.example.com

Content-Length: 0

I can probably work around this by simply ignoring the XmlHttpRequest error, but that would result in some strange coding on the client. Ideally there is an answer to this...

答:
When you initially request a resumable upload url (usually from your server, this is the "POST" above), you need to specify an "origin". This needs to be whatever the origin is that the browser will send when it starts to send the file, ie: the value of location.origin in the browser. And it needs to be exact.

In my code, I achieved this by implementing the request resumable upload function on the server, but getting the browser to pass location.origin to this function.

Note that in the question above, origin is being passed, but it doesn't look right (has some weird double quotes in it).


问:
Create Custom Camera view using Ionic
I want to create a Photo Capture app using Ionic. I have gone through Cordova Camera Plugin and the examples only shows how to open native camera on button click.

Is there a way to load the Camera view directly in the app (like default camera app, snapchat etc.)?
I want to open camera inside the app because I want to further add options to the camera, open gallery when user slides the camera etc.

Any help is much appreciated.

Thanks

The problem is similar to this question but the response does not solve my problem.

答: You can use cordova-plugin-camera-preview that allows camera interaction from inside the application.</p>

Title: Create Custom Camera view using Ionic


问:
MySQL Daemon Failed to Start - centos 6
EDIT: Look at the checkmarked answer comments to get your issue solved.

Whenever I try to start the SQLD service I get MySQL Daemon Failed to Start. I infact tried to "start" the service by doing the following:

```<code>service mysqld start
</code>```

Also

When I type: mysql

I get:

```<code>ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)
</code>```

I know that there should be a mysql.sock file in that directory, so I create one. But the file just auto removes its self and I continue to get the error 2002.

I am also unable to log into PHPMyAdmin due to the error. I can access phpmyadmin page but when logging in I get: #2002 Cannot log in to the MySQL server

EDIT:

Here is my mysql.log file:

```<code>131201 13:05:07 mysqld_safe mysqld from pid file /var/run/mysqld/mysqld.pid ended
131201 13:18:18 mysqld_safe Starting mysqld daemon with databases from /var/lib/mysql
131201 13:18:18 [Note] Plugin 'FEDERATED' is disabled.
/usr/libexec/mysqld: Can't find file: './mysql/plugin.frm' (errno: 13)
131201 13:18:18 [ERROR] Can't open the mysql.plugin table. Please run mysql_upgrade to create it.
131201 13:18:18 InnoDB: The InnoDB memory heap is disabled
131201 13:18:18 InnoDB: Mutexes and rw_locks use GCC atomic builtins
131201 13:18:18 InnoDB: Compressed tables use zlib 1.2.3
131201 13:18:18 InnoDB: Using Linux native AIO
131201 13:18:18 InnoDB: Initializing buffer pool, size = 128.0M
131201 13:18:18 InnoDB: Completed initialization of buffer pool
131201 13:18:18  InnoDB: Operating system error number 13 in a file operation.
InnoDB: The error means mysqld does not have the access rights to
InnoDB: the directory.
InnoDB: File name ./ibdata1
InnoDB: File operation call: 'open'.
InnoDB: Cannot continue operation.
131201 13:18:18 mysqld_safe mysqld from pid file /var/run/mysqld/mysqld.pid ended
</code>```

I ran mysql_upgrade and got

```<code>Looking for 'mysql' as: mysql
Looking for 'mysqlcheck' as: mysqlcheck
FATAL ERROR: Upgrade failed
</code>```

答:
Your database was shut down because of insufficient memory！
You can edit the  file my.cnf base below graph to resolve it</p>

```<code>performance_schema_max_table_instances=200
table_definition_cache=200
table_open_cache=128
</code>```

Title: MySQL Daemon Failed to Start - centos 6

Body:
EDIT: Look at the checkmarked answer comments to get your issue solved.

Whenever I try to start the SQLD service I get MySQL Daemon Failed to Start. I infact tried to "start" the service by doing the following:

service mysqld start

Also

When I type: mysql

I get:

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)

I know that there should be a mysql.sock file in that directory, so I create one. But the file just auto removes its self and I continue to get the error 2002.

I am also unable to log into PHPMyAdmin due to the error. I can access phpmyadmin page but when logging in I get: #2002 Cannot log in to the MySQL server

EDIT:

Here is my mysql.log file:

131201 13:05:07 mysqld_safe mysqld from pid file /var/run/mysqld/mysqld.pid ended
131201 13:18:18 mysqld_safe Starting mysqld daemon with databases from /var/lib/mysql
131201 13:18:18 [Note] Plugin 'FEDERATED' is disabled.
/usr/libexec/mysqld: Can't find file: './mysql/plugin.frm' (errno: 13)
131201 13:18:18 [ERROR] Can't open the mysql.plugin table. Please run mysql_upgrade to create it.
131201 13:18:18 InnoDB: The InnoDB memory heap is disabled
131201 13:18:18 InnoDB: Mutexes and rw_locks use GCC atomic builtins
131201 13:18:18 InnoDB: Compressed tables use zlib 1.2.3
131201 13:18:18 InnoDB: Using Linux native AIO
131201 13:18:18 InnoDB: Initializing buffer pool, size = 128.0M
131201 13:18:18 InnoDB: Completed initialization of buffer pool
131201 13:18:18  InnoDB: Operating system error number 13 in a file operation.
InnoDB: The error means mysqld does not have the access rights to
InnoDB: the directory.
InnoDB: File name ./ibdata1
InnoDB: File operation call: 'open'.
InnoDB: Cannot continue operation.
131201 13:18:18 mysqld_safe mysqld from pid file /var/run/mysqld/mysqld.pid ended

I ran mysql_upgrade and got

Looking for 'mysql' as: mysql
Looking for 'mysqlcheck' as: mysqlcheck
FATAL ERROR: Upgrade failed

Body:
Your database was shut down because of insufficient memory！
You can edit the  file my.cnf base below graph to resolve it

performance_schema_max_table_instances=200
table_definition_cache=200
table_open_cache=128


问:
Projects with browsable source using dependency injection w/ guice?
I often read about dependency injection and I did research on google and I understand in theory what it can do and how it works, but I'd like to see an actual code base using it (Java/guice would be preferred).

Can anyone point me to an open source project, where I can see, how it's really used? I think browsing the code and seeing the whole setup shows me more than the ususal snippets in the introduction articles you find around the web. Thanks in advance!

答:
I struggled a bit with this exact issue. It's so abstract and simple I was always worried I was "doing it wrong".

I've had been using it in the main project which has dependencies on other projects because the Guice module which sets the bindings was part of the main project.

I finally realized the libraries should be supplying the Modules themselves. At that point you can depend only on an instance of a Module (not a specific one), and the interfaces that are bound by it.

Taking it one step better, you can use the new ServiceLoader mechanism in Java 6 to automatically locate and install all Guice modules available on the classpath. Then you can swap in dependencies just by changing class path (db-real.jar vs. db-mock.jar).

OwnerDisplayName: André

OwnerDisplayName: tweakt


问:
Echo arrays with regular text
How would I write this so I'm only using one echo? </p>

```<code>echo "<div class='post'>";
echo $row['title'];
echo "</div>";
</code>```

<p>I'm using an array to echo out a table's values but it would be a lot easier on the eyes if I could combine these into one echo statement. However, when I try to the page goes blank. </p>

答:
Enclose the array reference in brackets:</p>

```<code>echo "<div class='post'{$row['title']}</div>";
</code>```

Title: Echo arrays with regular text

Body:
How would I write this so I'm only using one echo?

echo "
";
echo $row['title'];
echo "
";

I'm using an array to echo out a table's values but it would be a lot easier on the eyes if I could combine these into one echo statement. However, when I try to the page goes blank.

Body:
Enclose the array reference in brackets:

echo "<div class='post'{$row['title']}</div>";


问:
Is there anyway to write the following as a C++ macro?
```<code>my_macro << 1 << "hello world" << blah->getValue() << std::endl;
</code>```

should expand into:

```<code>std::ostringstream oss;
oss << 1 << "hello world" << blah->getValue() << std::endl;
ThreadSafeLogging(oss.str());
</code>```

答:
The logging setup I have is quite similar:

```<code>bool ShouldLog(const char* file, size_t line, Priority prio);

class LoggerOutput : public std::stringstream {
public:
  LoggerOutput(const char* file, size_t line, Priority prio)
  : prio(prio)
  {
    Prefix(file, line, prio);
  }
  void Prefix(const char* file, size_t line, Priority prio);
  ~LoggerOutput() {
    Flush();
  }
  void Flush();
private:
  Priority prio;
};

#define LOG(Prio) if (!Logging::ShouldLog(__FILE__, __LINE__, Prio)) {} else Logging::LoggerOutput(__FILE__, __LINE__, Prio)
</code>```

If your logging is disabled, the ostream is never created and little overhead exists. You can configure logging on file name & line number(s) or priority levels. The ShouldLog function can change between invocations, so you could throttle or limit output. The log output uses two functions to modify itself, Prefix that adds a "file:line: (PRIO) " prefix to the line, and Flush() which both flushes it to the log output as a single command and adds a newline to it. In my implementation it always does, but you can make that conditional if one is not already there.

Body:
my_macro << 1 << "hello world" << blah->getValue() << std::endl;

should expand into:

std::ostringstream oss;
oss << 1 << "hello world" << blah->getValue() << std::endl;
ThreadSafeLogging(oss.str());

Body:
The logging setup I have is quite similar:

bool ShouldLog(const char* file, size_t line, Priority prio);

class LoggerOutput : public std::stringstream {
public:
  LoggerOutput(const char* file, size_t line, Priority prio)
  : prio(prio)
  {
    Prefix(file, line, prio);
  }
  void Prefix(const char* file, size_t line, Priority prio);
  ~LoggerOutput() {
    Flush();
  }
  void Flush();
private:
  Priority prio;
};

#define LOG(Prio) if (!Logging::ShouldLog(__FILE__, __LINE__, Prio)) {} else Logging::LoggerOutput(__FILE__, __LINE__, Prio)

If your logging is disabled, the ostream is never created and little overhead exists. You can configure logging on file name & line number(s) or priority levels. The ShouldLog function can change between invocations, so you could throttle or limit output. The log output uses two functions to modify itself, Prefix that adds a "file:line: (PRIO) " prefix to the line, and Flush() which both flushes it to the log output as a single command and adds a newline to it. In my implementation it always does, but you can make that conditional if one is not already there.


问:
How to change angular port from 4200 to any other
I want to use 5000 instead of 4200.

I have tried to create a file on root name ember-cli and put JSON according to the code below:

```<code>{
   "port": 5000
}
</code>```

But my app still runs on 4200 instead of 5000

答:
You can change your application port by entering the following command,

ng serve --port 4200

Also, for a permanent setup you can change the port by editing angular-cli.json file

```<code> "defaults": {
    "serve": {
      "port": 8080
    }
  }
</code>```

Body:
I want to use 5000 instead of 4200.

I have tried to create a file on root name ember-cli and put JSON according to the code below:

{
   "port": 5000
}

But my app still runs on 4200 instead of 5000

Body:
You can change your application port by entering the following command,

ng serve --port 4200

Also, for a permanent setup you can change the port by editing angular-cli.json file

 "defaults": {
    "serve": {
      "port": 8080
    }
  }