问:
How can I add and remove JLabels to a JPane?
I am trying to make a little GUI. It has three checkboxes and a button. (picture below) I have an image of a head that I want other images to be put over the top of. This way as I select them and push the button they will change. Currently in my handler I have only one ImageIcon.
When I run the code as it is the "coolBrows.png" image doesn't show up. I've seen some examples on here of adding a JFrame to a JFrame they said that I need to add a layout for it to work. I've done that and it still wont show up... any help is appreciated!
Note: Each image has the same dimensions but the ones that will be overlayed have a transparent background.

Sorry if I broke with any conventions I've never posted here before.

The GUI

```<code>package AssignmentFace;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;

public class AssignmentFace extends JFrame {

    private JPanel contentPane;
    private ImageIcon head;
    private JCheckBox checkBoxBrows;
    private static ImageIcon brows;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    AssignmentFace frame = new AssignmentFace();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
    /**
     * Create the frame.
     */
    public AssignmentFace() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        contentPane.setLayout(new BorderLayout(1,2));
        setContentPane(contentPane);

        JPanel selectionPanel = new JPanel();
        selectionPanel.setLayout(new GridLayout(7,1));
        contentPane.add(selectionPanel, BorderLayout.WEST);

        // Contains the checkboxes
        checkBoxBrows= new JCheckBox("brows");
        selectionPanel.add(checkBoxBrows);

        JCheckBox checkBoxNose = new JCheckBox("Nose");
        selectionPanel.add(checkBoxNose);

        JCheckBox checkBoxMouth = new JCheckBox("Mouth");
        selectionPanel.add(checkBoxMouth);

        Handler handler = new Handler();

        JButton btnCycle = new JButton("Cycle ...");
        btnCycle.addActionListener(handler);
        selectionPanel.add(btnCycle);

        JPanel facePanel = new JPanel();
        facePanel.setOpaque(true);
        contentPane.add(facePanel, BorderLayout.CENTER);

        //  Head
        head = new ImageIcon(getClass().getResource("/images/head.png"));
        JLabel headLabel = new JLabel(head, JLabel.CENTER);
        headLabel.setLayout(new BorderLayout());
        facePanel.add( headLabel, BorderLayout.CENTER );

        //  Brows
        brows = new ImageIcon();
        JLabel browsLabel = new JLabel(brows, JLabel.CENTER);
        headLabel.add(browsLabel, BorderLayout.CENTER);

        //  Nose
        //ImageIcon nose = new ImageIcon();
        //JLabel noseLabel = new JLabel(nose, JLabel.CENTER);
        //facePanel.add(noseLabel, BorderLayout.CENTER);

        // Mouth
        //ImageIcon mouth = new ImageIcon();
        //JLabel mouthLabel = new JLabel(nose, JLabel.CENTER);
        //facePanel.add(mouthLabel, BorderLayout.CENTER);
    }

    public class Handler implements ActionListener
    {

        @Override
        public void actionPerformed(ActionEvent e)
        {
            if(checkBoxBrows.isSelected())
            {
                brows = new ImageIcon(getClass().getResource("/images/coolBrows.png"));
                System.out.println("here"); //For testing purposes. This does come through in the console
            }
        }
    }
}
</code>```

答:
So it seems like you need to layer Icons or JLabels.

So maybe you can use:

A JLayeredPane to layer the labels. So you create a layer for each facial feature and add a label to the layer. Then you can add/remove the Icon from the label based on the value of the check box. Read the section from the Swing tutorial on How to Use Layered Panes for more information and working examples.

Use the Compound Icon to layer the icons. This allows you to stack Icons on top of one another and then display the resulting Icon on a single JLabel. So every time an event is generated by clicking on a check box you can rebuild the CompoundIcon with the selected features and reset the Icon on the JLabel.

Body:
I am trying to make a little GUI. It has three checkboxes and a button. (picture below) I have an image of a head that I want other images to be put over the top of. This way as I select them and push the button they will change. Currently in my handler I have only one ImageIcon.
When I run the code as it is the "coolBrows.png" image doesn't show up. I've seen some examples on here of adding a JFrame to a JFrame they said that I need to add a layout for it to work. I've done that and it still wont show up... any help is appreciated!
Note: Each image has the same dimensions but the ones that will be overlayed have a transparent background.

Sorry if I broke with any conventions I've never posted here before.

The GUI

package AssignmentFace;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;

public class AssignmentFace extends JFrame {

    private JPanel contentPane;
    private ImageIcon head;
    private JCheckBox checkBoxBrows;
    private static ImageIcon brows;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    AssignmentFace frame = new AssignmentFace();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
    /**
     * Create the frame.
     */
    public AssignmentFace() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        contentPane.setLayout(new BorderLayout(1,2));
        setContentPane(contentPane);

        JPanel selectionPanel = new JPanel();
        selectionPanel.setLayout(new GridLayout(7,1));
        contentPane.add(selectionPanel, BorderLayout.WEST);

        // Contains the checkboxes
        checkBoxBrows= new JCheckBox("brows");
        selectionPanel.add(checkBoxBrows);

        JCheckBox checkBoxNose = new JCheckBox("Nose");
        selectionPanel.add(checkBoxNose);

        JCheckBox checkBoxMouth = new JCheckBox("Mouth");
        selectionPanel.add(checkBoxMouth);

        Handler handler = new Handler();

        JButton btnCycle = new JButton("Cycle ...");
        btnCycle.addActionListener(handler);
        selectionPanel.add(btnCycle);

        JPanel facePanel = new JPanel();
        facePanel.setOpaque(true);
        contentPane.add(facePanel, BorderLayout.CENTER);

        //  Head
        head = new ImageIcon(getClass().getResource("/images/head.png"));
        JLabel headLabel = new JLabel(head, JLabel.CENTER);
        headLabel.setLayout(new BorderLayout());
        facePanel.add( headLabel, BorderLayout.CENTER );

        //  Brows
        brows = new ImageIcon();
        JLabel browsLabel = new JLabel(brows, JLabel.CENTER);
        headLabel.add(browsLabel, BorderLayout.CENTER);

        //  Nose
        //ImageIcon nose = new ImageIcon();
        //JLabel noseLabel = new JLabel(nose, JLabel.CENTER);
        //facePanel.add(noseLabel, BorderLayout.CENTER);

        // Mouth
        //ImageIcon mouth = new ImageIcon();
        //JLabel mouthLabel = new JLabel(nose, JLabel.CENTER);
        //facePanel.add(mouthLabel, BorderLayout.CENTER);
    }

    public class Handler implements ActionListener
    {

        @Override
        public void actionPerformed(ActionEvent e)
        {
            if(checkBoxBrows.isSelected())
            {
                brows = new ImageIcon(getClass().getResource("/images/coolBrows.png"));
                System.out.println("here"); //For testing purposes. This does come through in the console
            }
        }
    }
}


来源: stackexchange

问:
Pointer static method that points to no static method
I've been trying to make a pointer function that points to a method doing something like this(visual C++):

```<code>struct test
{
  int tst(int a)
  {
    return a * 4;
  }
};
// ok, this the visual C++ compiler does not accept it... (mingw accept it)

int(*tstptr)(int) = (int(*)(int))&test::tst;
</code>```

Then I've done something like this:

```<code>struct Dx
{
    int SomeMethod()
    {
        return 4;
    }
};

struct Dy
{
    static int(*pSomeMethod)();
};

int(Dy::*pSomeMethod)() = (int( Dy::*)())&Dx::SomeMethod;
</code>```

So far so good, this compiles without problems, but if I try call her:

```<code>Dy::pSomeMethod();
</code>```

The compiler returns me:

Error 1 error LNK2001: external symbol "public: static int (__stdcall
  * Dy::pSomeMethod) (void)" (? PSomeMethod@Dy@@2P6GHXZA) unresolved

which I do not understand, because  it is not suppose pSomeMethod he is not pointing at SomeMethod ?

答:
The type of &test::tst is int (test::*) (int), which is a member function pointer.

You are trying to convert it to a regular pointer type, which is not possible because they are completely different.

That's why you will have this type cast error:

```<code>error C2440: 'type cast' :
cannot convert from 'int (__thiscall test::* )(int)' to 'int (__cdecl *)(int)'
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I've been trying to make a pointer function that points to a method doing something like this(visual C++):

struct test
{
  int tst(int a)
  {
    return a * 4;
  }
};
// ok, this the visual C++ compiler does not accept it... (mingw accept it)

int(*tstptr)(int) = (int(*)(int))&test::tst;

Then I've done something like this:

struct Dx
{
    int SomeMethod()
    {
        return 4;
    }
};

struct Dy
{
    static int(*pSomeMethod)();
};

int(Dy::*pSomeMethod)() = (int( Dy::*)())&Dx::SomeMethod;

So far so good, this compiles without problems, but if I try call her:

Dy::pSomeMethod();

The compiler returns me:

Error 1 error LNK2001: external symbol "public: static int (__stdcall
  * Dy::pSomeMethod) (void)" (? PSomeMethod@Dy@@2P6GHXZA) unresolved

which I do not understand, because  it is not suppose pSomeMethod he is not pointing at SomeMethod ?

Body:
The type of &test::tst is int (test::*) (int), which is a member function pointer.

You are trying to convert it to a regular pointer type, which is not possible because they are completely different.

That's why you will have this type cast error:

error C2440: 'type cast' :
cannot convert from 'int (__thiscall test::* )(int)' to 'int (__cdecl *)(int)'


问:
Apache Forbidden error on clean CentOS install
I have a clean copy of CentOS.

Just installed Apache, PHP and MySQL. Everything works like a charm.

Except for I created a new user, let's call it 'demo'.

I created a new virtual directory in httpd.conf and pointed it to '/home/demo/www'. I created an empty index.html under '/home/demo/www'.

Apache is running under user 'apache' and group 'apache'.

Maybe user 'apache' does not have access to user 'demo's file, that's why I get the Forbidden problem?

Do you have any ideas how to solve this problem?

Thanks,

James

答:
You need to add:

```<code><Directory "/home/demo/www">
   # Allow open access:
   Require all granted
/Directory>
</code>```

To your Virtual Host definition.

OwnerDisplayName: James

ContentLicense: CC BY-SA 2.5

Body:
You need to add:

<Directory "/home/demo/www">
   # Allow open access:
   Require all granted
/Directory>

To your Virtual Host definition.


问:
std::function with lambda error for SDL event callbacks
I simply want to pass a lambda function to a function for callbacks. I am using std::function for callbacks. I need to pass data to this function and this is where I am running into problems. The code below errors saying "cannot convert to the expected type". The goal is to use callbacks for events with SDL. I am not sure if this is even the right way to go about doing this. I am storing the callback function in a unordered_map with the key being an SDL_Event.type and a vector of std::function.

I call the dispatch() in the event polling and subscribe in the setup. The error occurs in the [] of the subscribe() lambda

```<code>// main.cpp
window->subscribe(SDL_KEYDOWN, [](SDL_Event& ev) -> void {
    std::cout << "key pressed" << std::endl;
});

// eventhandler.cpp
void EventHandler::subscribe(int _event, std::function<void(const SDL_Event&)> _callback)
{
    m_callbacks[_event].push_back(_callback);
}
</code>```

答:
Very stupid mistake made... The parameters did not match. The correct code that works is below. I.e. I did not have the const in the lambda...

```<code>window->subscribe(SDL_KEYDOWN, [](const SDL_Event& ev) -> void {
    std::cout << "key pressed" << std::endl;
});

void EventHandler::subscribe(int _event, std::function<void(const SDL_Event&)> _callback)
{
    m_callbacks[_event].push_back(_callback);
}
</code>```

Body:
I simply want to pass a lambda function to a function for callbacks. I am using std::function for callbacks. I need to pass data to this function and this is where I am running into problems. The code below errors saying "cannot convert to the expected type". The goal is to use callbacks for events with SDL. I am not sure if this is even the right way to go about doing this. I am storing the callback function in a unordered_map with the key being an SDL_Event.type and a vector of std::function.

I call the dispatch() in the event polling and subscribe in the setup. The error occurs in the [] of the subscribe() lambda

// main.cpp
window->subscribe(SDL_KEYDOWN, [](SDL_Event& ev) -> void {
    std::cout << "key pressed" << std::endl;
});

// eventhandler.cpp
void EventHandler::subscribe(int _event, std::function<void(const SDL_Event&)> _callback)
{
    m_callbacks[_event].push_back(_callback);
}

Body:
Very stupid mistake made... The parameters did not match. The correct code that works is below. I.e. I did not have the const in the lambda...

window->subscribe(SDL_KEYDOWN, [](const SDL_Event& ev) -> void {
    std::cout << "key pressed" << std::endl;
});

void EventHandler::subscribe(int _event, std::function<void(const SDL_Event&)> _callback)
{
    m_callbacks[_event].push_back(_callback);
}


问:
Translate Python function to apply mask to image into Java
I'm trying to translate the following Python function, that applies a mask to an image, into Java:

# Applies an image mask.
def region_of_interest(img, vertices):
    #defining a blank mask to start with
    mask = np.zeros_like(img)

    #defining a 3 channel or 1 channel color to fill the mask with depending on the input image
    if len(img.shape) > 2:
        channel_count = img.shape[2]  # i.e. 3 or 4 depending on your image
        ignore_mask_color = (255,) * channel_count
    else:
        ignore_mask_color = 255

    #filling pixels inside the polygon defined by "vertices" with the fill color
    cv2.fillPoly(mask, vertices, ignore_mask_color)

    #returning the image only where mask pixels are nonzero
    masked_image = cv2.bitwise_and(img, mask)
    return masked_image
```

<p>So far, this is what I've got:</p>

```public static opencv_core.Mat applyMask(opencv_core.Mat image, opencv_core.MatVector vertices) {
  opencv_core.Mat mask = opencv_core.Mat.zeros(image.size(), opencv_core.CV_8U).asMat();

  opencv_core.Scalar color = new opencv_core.Scalar(image.channels()); // 3
  double[] colors = new double[] {
    255.0, 255.0, 255.0, 255.0,
    255.0, 255.0, 255.0, 255.0,
    255.0, 255.0, 255.0, 255.0};
  color.put(colors, 0, colors.length);

  opencv_imgproc.fillPoly(mask, vertices, color);

  opencv_core.Mat dst = new opencv_core.Mat();
  opencv_core.bitwise_and(image, mask, dst);
  return dst;
}
```

<p>But, it isn't working. When I try invoking this method like in the following example:</p>

```opencv_core.MatVector points = new opencv_core.MatVector(
  new opencv_core.Mat(2, 3, opencv_core.CV_32F, new IntPointer(1, 2, 3, 4, 5, 6))
);

opencv_core.MatVector vertices = new opencv_core.MatVector(points);
opencv_core.Mat masked = LaneManager.applyMask(src, vertices);
```

<p>(I'm assuming this is the right way to build a 2x3 matrix of three points with two coordinates each <code>(1,2)</code>, <code>(3, 4)</code> and <code>(5,6)</code>)</p>

<p>I get an exception:</p>

```java.lang.RuntimeException: std::bad_alloc
at org.bytedeco.javacpp.opencv_imgproc.fillPoly(Native Method)
```

I'm using OpenCV as provided by org.bytedeco.javacpp-presets:opencv-platform:3.2.0-1.3 via Maven Central.

I must admit that I'm at a loss here: What's the idiomatic Java way of doing the same thing as the Python function above?

答:
Alright, I finally figured it out. If you define your coordinates with:

```<code>int[] points = new int[] {x1, y1, x2, y2, ...};
</code>```

Then you can simply apply a mask with the following code:

```<code>opencv_core.Mat mask = new opencv_core.Mat(image.size(), image.type());

// Array of polygons where each polygon is represented as an array of points
opencv_core.Point polygon = new opencv_core.Point();
polygon.put(points, 0, points.length);
opencv_imgproc.fillPoly(mask, polygon, new int[] {points.length / 2}, 1, new opencv_core.Scalar(255, 255, 255, 0));

opencv_core.Mat masked = new opencv_core.Mat(image.size(), image.type());
opencv_core.bitwise_and(image, mask, masked);
</code>```

Where image is the original image, and masked is the masked result.

The problem was that the original list of points wasn't defined properly.

Body:
I'm trying to translate the following Python function, that applies a mask to an image, into Java:

# Applies an image mask.
def region_of_interest(img, vertices):
    #defining a blank mask to start with
    mask = np.zeros_like(img)

    #defining a 3 channel or 1 channel color to fill the mask with depending on the input image
    if len(img.shape) > 2:
        channel_count = img.shape[2]  # i.e. 3 or 4 depending on your image
        ignore_mask_color = (255,) * channel_count
    else:
        ignore_mask_color = 255

    #filling pixels inside the polygon defined by "vertices" with the fill color
    cv2.fillPoly(mask, vertices, ignore_mask_color)

    #returning the image only where mask pixels are nonzero
    masked_image = cv2.bitwise_and(img, mask)
    return masked_image

So far, this is what I've got:

public static opencv_core.Mat applyMask(opencv_core.Mat image, opencv_core.MatVector vertices) {
  opencv_core.Mat mask = opencv_core.Mat.zeros(image.size(), opencv_core.CV_8U).asMat();

  opencv_core.Scalar color = new opencv_core.Scalar(image.channels()); // 3
  double[] colors = new double[] {
    255.0, 255.0, 255.0, 255.0,
    255.0, 255.0, 255.0, 255.0,
    255.0, 255.0, 255.0, 255.0};
  color.put(colors, 0, colors.length);

  opencv_imgproc.fillPoly(mask, vertices, color);

  opencv_core.Mat dst = new opencv_core.Mat();
  opencv_core.bitwise_and(image, mask, dst);
  return dst;
}

But, it isn't working. When I try invoking this method like in the following example:

opencv_core.MatVector points = new opencv_core.MatVector(
  new opencv_core.Mat(2, 3, opencv_core.CV_32F, new IntPointer(1, 2, 3, 4, 5, 6))
);

opencv_core.MatVector vertices = new opencv_core.MatVector(points);
opencv_core.Mat masked = LaneManager.applyMask(src, vertices);

(I'm assuming this is the right way to build a 2x3 matrix of three points with two coordinates each (1,2), (3, 4) and (5,6))

I get an exception:

java.lang.RuntimeException: std::bad_alloc
at org.bytedeco.javacpp.opencv_imgproc.fillPoly(Native Method)

I'm using OpenCV as provided by org.bytedeco.javacpp-presets:opencv-platform:3.2.0-1.3 via Maven Central.

I must admit that I'm at a loss here: What's the idiomatic Java way of doing the same thing as the Python function above?

Body:
Alright, I finally figured it out. If you define your coordinates with:

int[] points = new int[] {x1, y1, x2, y2, ...};

Then you can simply apply a mask with the following code:

opencv_core.Mat mask = new opencv_core.Mat(image.size(), image.type());

// Array of polygons where each polygon is represented as an array of points
opencv_core.Point polygon = new opencv_core.Point();
polygon.put(points, 0, points.length);
opencv_imgproc.fillPoly(mask, polygon, new int[] {points.length / 2}, 1, new opencv_core.Scalar(255, 255, 255, 0));

opencv_core.Mat masked = new opencv_core.Mat(image.size(), image.type());
opencv_core.bitwise_and(image, mask, masked);

Where image is the original image, and masked is the masked result.

The problem was that the original list of points wasn't defined properly.


问:
WWF or WPF for flowcharts?
I want to be able to present my data using a flowchart. I can use wpf to do this, but I dont want to have to code all the arrows, connectors etc - I would like to use a library if possible..

Also could I use windows workflow foundation to do this in any way? Would this help? I get the impression although WWF is workflow, its more to do with the process as opposed to presenting data.

It appears that I might have to obtain a third party control to do this....any recommendations - the component should be able to draw a flowchart at the minimum!

Thanks

答: Why don't you use a tool like Visio to present your data instead of creating a tool from scratch?</p>

Title: WWF or WPF for flowcharts?


问:
VB6 Run time error 424
I am getting error 424 on this line, can anyone help me please.

```<code>lblprvbal.Text = Val(NewItem.SubItems(11))
</code>```

```<code>Private Sub cmdShow_Click()
'lblTotPur/lblTotPayRet/lblBalance
Dim strShow, mSlNo
Dim rsShow As New ADODB.Recordset
Dim NewItem As Variant
If Trim(txtCustomer.Text) = "" Then
    MsgBox "Please select customer to proceed...", vbCritical, POPUP_COMP
    Exit Sub
End If

Dim recCnt
pgrPartyLedger.Min = 0
recCnt = 0
'VOUCHMST_P//VNO,DATED,VTYPE,REMARKS,byUser CASH PURCHASE RETURN
strShow = "select Count(*) as mCnt from VOUCHMST A,VOUCHDAT B, Prevbal C  "
strShow = strShow & " where A.VNO=B.VNO and B.IDNO=C.obd and (A.REMARKS='CASH SALE RETURN' OR A.REMARKS='CREDIT SALE RETURN' OR A.REMARKS='CREDIT SALE' OR A.REMARKS='CASH SALE' OR A.REMARKS='RECEIPT' OR A.REMARKS='CREDIT NOTE') "
strShow = strShow & " and A.DATED between #" & Format(dtFrom.Value, "MM/dd/yyyy") & "# "
strShow = strShow & " and #" & Format(dtTo.Value, "MM/dd/yyyy") & "# "
strShow = strShow & " and B.IDNO = '" & Trim(txtCustomerId.Text) & "' "
'strShow = strShow & " order by A.ID,A.DATED,A.VNO"
rsShow.Open strShow, cn
recCnt = rsShow("mCnt")
rsShow.Close
pgrPartyLedger.Max = recCnt + 1

'VOUCHMST_P//VNO,DATED,VTYPE,REMARKS,byUser
strShow = "select A.Id,A.cmnt,A.ADV,A.VNO,A.DATED,B.IDNO,B.IDNAME,B.AMOUNT,B.DR_CR,B.VNARRATION,A.REMARKS,B.CQ_TYPE, B.BANKNAME, B.BANKBRANCH, B.CQ_NO, C.amnt from VOUCHMST A,VOUCHDAT B, Prevbal C "
strShow = strShow & " where A.VNO=B.VNO and B.IDNO=C.obd and (A.REMARKS='CASH SALE RETURN' OR A.REMARKS='CREDIT SALE RETURN' OR A.REMARKS='CREDIT SALE' OR A.REMARKS='CASH SALE' OR A.REMARKS='RECEIPT' OR A.REMARKS='CREDIT NOTE') "
strShow = strShow & " and A.DATED between #" & Format(dtFrom.Value, "MM/dd/yyyy") & "# "
strShow = strShow & " and #" & Format(dtTo.Value, "MM/dd/yyyy") & "# "
strShow = strShow & " and B.IDNO = '" & Trim(txtCustomerId.Text) & "' "
strShow = strShow & " order by A.ID,A.DATED,A.VNO"
rsShow.Open strShow, cn

Dim mPur, mPayRet, mAnyAdv, mTempVNO
mPur = 0
mPayRet = 0
mAnyAdv = 0

mSlNo = 1
ShowPaymentHeader
Do While Not rsShow.EOF
    mTempVNO = rsShow("VNO")

    Set NewItem = listViewPayment.ListItems.Add(, "C" & mSlNo, Format(rsShow("DATED"), "dd/MM/yyyy"))
    NewItem.SubItems(1) = mTempVNO
    NewItem.SubItems(2) = IIf(IsNull(rsShow("IDNAME")), "", CommaFilterText(rsShow("IDNAME"), 1))
    NewItem.SubItems(11) = rsShow("amnt")
    If Trim(rsShow("REMARKS")) = "CASH SALE" Then
        NewItem.SubItems(3) = FormatTakaPaisa(rsShow("AMOUNT"))
        NewItem.SubItems(4) = FormatTakaPaisa(rsShow("AMOUNT"))
    ElseIf Trim(rsShow("REMARKS")) = "CREDIT SALE" Then
        mAnyAdv = ShowPartialAdvance(rsShow("VNO"))
        NewItem.SubItems(3) = FormatTakaPaisa(rsShow("AMOUNT") + Val(mAnyAdv))

        If Val(mAnyAdv) > 0 Then
            NewItem.SubItems(4) = FormatTakaPaisa(mAnyAdv)

        Else
            NewItem.SubItems(4) = ""

        End If
    Else
        NewItem.SubItems(3) = ""
        NewItem.SubItems(4) = FormatTakaPaisa(rsShow("AMOUNT"))
        NewItem.SubItems(7) = rsShow("CQ_TYPE")
        NewItem.SubItems(8) = rsShow("BANKNAME")
        NewItem.SubItems(9) = rsShow("BANKBRANCH")
        NewItem.SubItems(10) = rsShow("CQ_NO")

        NewItem.SubItems(13) = "" & rsShow("cmnt")

    End If
    NewItem.SubItems(6) = rsShow("IDNO")

    mPur = mPur + Val(NewItem.SubItems(3))
    mPayRet = mPayRet + Val(NewItem.SubItems(4))

    NewItem.SubItems(5) = rsShow("REMARKS")

    NewItem.SubItems(12) = GetVoucherRefNo(mTempVNO)

    pgrPartyLedger.Value = mSlNo

    mSlNo = mSlNo + 1
    rsShow.MoveNext
Loop
rsShow.Close

lblprvbal.Text = Val(NewItem.SubItems(11))
lblTotPur.Caption = FormatTakaPaisa(mPur) + Val(lblprvbal.Text)
lblTotPayRet.Caption = FormatTakaPaisa(mPayRet)
lblBalance.Caption = FormatTakaPaisa(mPur - mPayRet) + Val(lblprvbal.Text)

pgrPartyLedger.Value = 0
End Sub
</code>```

答:
Try below. value in the sub item is null and hence the error.</p>

```<code>If IsDBNull(NewItem.SubItems(11)) Then
    lblprvbal.Text = ""
Else
    lblprvbal.Text = Val(NewItem.SubItems(11))
End If
</code>```

Title: VB6 Run time error 424

Body:
I am getting error 424 on this line, can anyone help me please.

lblprvbal.Text = Val(NewItem.SubItems(11))

Private Sub cmdShow_Click()
'lblTotPur/lblTotPayRet/lblBalance
Dim strShow, mSlNo
Dim rsShow As New ADODB.Recordset
Dim NewItem As Variant
If Trim(txtCustomer.Text) = "" Then
    MsgBox "Please select customer to proceed...", vbCritical, POPUP_COMP
    Exit Sub
End If

Dim recCnt
pgrPartyLedger.Min = 0
recCnt = 0
'VOUCHMST_P//VNO,DATED,VTYPE,REMARKS,byUser CASH PURCHASE RETURN
strShow = "select Count(*) as mCnt from VOUCHMST A,VOUCHDAT B, Prevbal C  "
strShow = strShow & " where A.VNO=B.VNO and B.IDNO=C.obd and (A.REMARKS='CASH SALE RETURN' OR A.REMARKS='CREDIT SALE RETURN' OR A.REMARKS='CREDIT SALE' OR A.REMARKS='CASH SALE' OR A.REMARKS='RECEIPT' OR A.REMARKS='CREDIT NOTE') "
strShow = strShow & " and A.DATED between #" & Format(dtFrom.Value, "MM/dd/yyyy") & "# "
strShow = strShow & " and #" & Format(dtTo.Value, "MM/dd/yyyy") & "# "
strShow = strShow & " and B.IDNO = '" & Trim(txtCustomerId.Text) & "' "
'strShow = strShow & " order by A.ID,A.DATED,A.VNO"
rsShow.Open strShow, cn
recCnt = rsShow("mCnt")
rsShow.Close
pgrPartyLedger.Max = recCnt + 1

'VOUCHMST_P//VNO,DATED,VTYPE,REMARKS,byUser
strShow = "select A.Id,A.cmnt,A.ADV,A.VNO,A.DATED,B.IDNO,B.IDNAME,B.AMOUNT,B.DR_CR,B.VNARRATION,A.REMARKS,B.CQ_TYPE, B.BANKNAME, B.BANKBRANCH, B.CQ_NO, C.amnt from VOUCHMST A,VOUCHDAT B, Prevbal C "
strShow = strShow & " where A.VNO=B.VNO and B.IDNO=C.obd and (A.REMARKS='CASH SALE RETURN' OR A.REMARKS='CREDIT SALE RETURN' OR A.REMARKS='CREDIT SALE' OR A.REMARKS='CASH SALE' OR A.REMARKS='RECEIPT' OR A.REMARKS='CREDIT NOTE') "
strShow = strShow & " and A.DATED between #" & Format(dtFrom.Value, "MM/dd/yyyy") & "# "
strShow = strShow & " and #" & Format(dtTo.Value, "MM/dd/yyyy") & "# "
strShow = strShow & " and B.IDNO = '" & Trim(txtCustomerId.Text) & "' "
strShow = strShow & " order by A.ID,A.DATED,A.VNO"
rsShow.Open strShow, cn

Dim mPur, mPayRet, mAnyAdv, mTempVNO
mPur = 0
mPayRet = 0
mAnyAdv = 0

mSlNo = 1
ShowPaymentHeader
Do While Not rsShow.EOF
    mTempVNO = rsShow("VNO")

    Set NewItem = listViewPayment.ListItems.Add(, "C" & mSlNo, Format(rsShow("DATED"), "dd/MM/yyyy"))
    NewItem.SubItems(1) = mTempVNO
    NewItem.SubItems(2) = IIf(IsNull(rsShow("IDNAME")), "", CommaFilterText(rsShow("IDNAME"), 1))
    NewItem.SubItems(11) = rsShow("amnt")
    If Trim(rsShow("REMARKS")) = "CASH SALE" Then
        NewItem.SubItems(3) = FormatTakaPaisa(rsShow("AMOUNT"))
        NewItem.SubItems(4) = FormatTakaPaisa(rsShow("AMOUNT"))
    ElseIf Trim(rsShow("REMARKS")) = "CREDIT SALE" Then
        mAnyAdv = ShowPartialAdvance(rsShow("VNO"))
        NewItem.SubItems(3) = FormatTakaPaisa(rsShow("AMOUNT") + Val(mAnyAdv))

        If Val(mAnyAdv) > 0 Then
            NewItem.SubItems(4) = FormatTakaPaisa(mAnyAdv)

        Else
            NewItem.SubItems(4) = ""

        End If
    Else
        NewItem.SubItems(3) = ""
        NewItem.SubItems(4) = FormatTakaPaisa(rsShow("AMOUNT"))
        NewItem.SubItems(7) = rsShow("CQ_TYPE")
        NewItem.SubItems(8) = rsShow("BANKNAME")
        NewItem.SubItems(9) = rsShow("BANKBRANCH")
        NewItem.SubItems(10) = rsShow("CQ_NO")

        NewItem.SubItems(13) = "" & rsShow("cmnt")

    End If
    NewItem.SubItems(6) = rsShow("IDNO")

    mPur = mPur + Val(NewItem.SubItems(3))
    mPayRet = mPayRet + Val(NewItem.SubItems(4))

    NewItem.SubItems(5) = rsShow("REMARKS")

    NewItem.SubItems(12) = GetVoucherRefNo(mTempVNO)

    pgrPartyLedger.Value = mSlNo

    mSlNo = mSlNo + 1
    rsShow.MoveNext
Loop
rsShow.Close

lblprvbal.Text = Val(NewItem.SubItems(11))
lblTotPur.Caption = FormatTakaPaisa(mPur) + Val(lblprvbal.Text)
lblTotPayRet.Caption = FormatTakaPaisa(mPayRet)
lblBalance.Caption = FormatTakaPaisa(mPur - mPayRet) + Val(lblprvbal.Text)

pgrPartyLedger.Value = 0
End Sub

Body:
Try below. value in the sub item is null and hence the error.

If IsDBNull(NewItem.SubItems(11)) Then
    lblprvbal.Text = ""
Else
    lblprvbal.Text = Val(NewItem.SubItems(11))
End If


问:
Improve Powershell Performance to Generate a Random File
I'd like to user Powershell to create a random text file for use in basic system testing (upload, download, checksum, etc). I've used the following articles and come up with my own code snippet to create a random text file but the performance is terrible.

Generating Random Files in Windows (stackoverflow.com)

PowerShell – Creating Dummy files (verboon.info)

Create large files with Powershell (chris-nullpayload.rhcloud.com based on verboon code above)

Here is my code sample that takes approximately 227 seconds to generate a 1MB random text file on a modern Windows 7 Dell laptop. Run time was determined using the Measure-Command cmdlet. I repeated the test several times during different system load with similar long runtime results.

```<code># select characters from 0-9, A-Z, and a-z
$chars = [char[]] ([char]'0'..[char]'9' + [char]'A'..[char]'Z' + [char]'a'..[char]'z')
# write file using 128 byte lines each with 126 random characters
1..(1mb/128) | %{-join (1..126 | %{get-random -InputObject $chars }) } `
  | out-file test.txt -Encoding ASCII
</code>```

I am looking for answers that discuss why this code has poor performance and suggestions for simple changes I can make to improve the runtime for generating a similar random text file (ASCII text lines of 126 random alphanumeric characters - 128 bytes with "\r\n" EOL, output file an even number of megabytes such as the above 1MB sample). I would like file output to be written in pieces (one or more lines at a time) so that we never need a string the size of the output file stored in memory.

答:
Instead of using Get-Random to generate the text as per mjolinor suggestions, I improved the speed by using GUIDs.

```<code>Function New-RandomFile {
    Param(
        $Path = '.',
        $FileSize = 1kb,
        $FileName = [guid]::NewGuid().Guid + '.txt'
        )
    (1..($FileSize/128)).foreach({-join ([guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid -Replace "-").SubString(1, 126) }) | set-content "$Path\$FileName"
}
</code>```

I've ran both versions with Measure-Command. The original code took 1.36 seconds.

This one took 491 milliseconds. Running:

```<code>New-RandomFile -FileSize 1mb
</code>```

UPDATE:

I've updated my function to use a ScriptBlock, so you can replace the 'NewGuid()' method with anything you want.

In this scenario, I make 1kb chunks, since I know I'm never creating smaller files. This improved the speed of my function drastically!

Set-Content forces a NewLine at the end, which is why you need to remove 2 Characters each time you write to file. I've replaced it with [io.file]::WriteAllText() instead.

```<code>Function New-RandomFile_1kChunks {
    Param(
        $Path = (Resolve-Path '.').Path,
        $FileSize = 1kb,
        $FileName = [guid]::NewGuid().Guid + '.txt'
        )

    $Chunk = { [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid +
               [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid +
               [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid +
               [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid +
               [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid +
               [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid +
               [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid +
               [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid -Replace "-" }

    $Chunks = [math]::Ceiling($FileSize/1kb)

    [io.file]::WriteAllText("$Path\$FileName","$(-Join (1..($Chunks)).foreach({ $Chunk.Invoke() }))")

    Write-Warning "New-RandomFile: $Path\$FileName"

}
</code>```

If you dont care that all chunks are random, you can simply Invoke() the generation of the 1kb chunk once.. this improves the speed drastically, but won't make the entire file random.

```<code>Function New-RandomFile_Fast {
    Param(
        $Path = (Resolve-Path '.').Path,
        $FileSize = 1kb,
        $FileName = [guid]::NewGuid().Guid + '.txt'
        )

    $Chunk = { [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid +
               [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid +
               [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid +
               [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid +
               [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid +
               [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid +
               [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid +
               [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid -Replace "-" }
    $Chunks = [math]::Ceiling($FileSize/1kb)
    $ChunkString = $Chunk.Invoke()

    [io.file]::WriteAllText("$Path\$FileName","$(-Join (1..($Chunks)).foreach({ $ChunkString }))")

    Write-Warning "New-RandomFile: $Path\$FileName"

}
</code>```

Measure-Command all these changes to generate a 10mb file:

Executing New-RandomFile: 35.7688241 seconds.

Executing New-RandomFile_1kChunks: 25.1463777 seconds.

Executing New-RandomFile_Fast: 1.1626236 seconds.

Body:
I'd like to user Powershell to create a random text file for use in basic system testing (upload, download, checksum, etc). I've used the following articles and come up with my own code snippet to create a random text file but the performance is terrible.

Generating Random Files in Windows (stackoverflow.com)

PowerShell – Creating Dummy files (verboon.info)

Create large files with Powershell (chris-nullpayload.rhcloud.com based on verboon code above)

Here is my code sample that takes approximately 227 seconds to generate a 1MB random text file on a modern Windows 7 Dell laptop. Run time was determined using the Measure-Command cmdlet. I repeated the test several times during different system load with similar long runtime results.

# select characters from 0-9, A-Z, and a-z
$chars = [char[]] ([char]'0'..[char]'9' + [char]'A'..[char]'Z' + [char]'a'..[char]'z')
# write file using 128 byte lines each with 126 random characters
1..(1mb/128) | %{-join (1..126 | %{get-random -InputObject $chars }) } `
  | out-file test.txt -Encoding ASCII

I am looking for answers that discuss why this code has poor performance and suggestions for simple changes I can make to improve the runtime for generating a similar random text file (ASCII text lines of 126 random alphanumeric characters - 128 bytes with "\r\n" EOL, output file an even number of megabytes such as the above 1MB sample). I would like file output to be written in pieces (one or more lines at a time) so that we never need a string the size of the output file stored in memory.

Body:
Instead of using Get-Random to generate the text as per mjolinor suggestions, I improved the speed by using GUIDs.

Function New-RandomFile {
    Param(
        $Path = '.',
        $FileSize = 1kb,
        $FileName = [guid]::NewGuid().Guid + '.txt'
        )
    (1..($FileSize/128)).foreach({-join ([guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid -Replace "-").SubString(1, 126) }) | set-content "$Path\$FileName"
}

I've ran both versions with Measure-Command. The original code took 1.36 seconds.

This one took 491 milliseconds. Running:

New-RandomFile -FileSize 1mb

UPDATE:

I've updated my function to use a ScriptBlock, so you can replace the 'NewGuid()' method with anything you want.

In this scenario, I make 1kb chunks, since I know I'm never creating smaller files. This improved the speed of my function drastically!

Set-Content forces a NewLine at the end, which is why you need to remove 2 Characters each time you write to file. I've replaced it with [io.file]::WriteAllText() instead.

Function New-RandomFile_1kChunks {
    Param(
        $Path = (Resolve-Path '.').Path,
        $FileSize = 1kb,
        $FileName = [guid]::NewGuid().Guid + '.txt'
        )

    $Chunk = { [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid +
               [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid +
               [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid +
               [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid +
               [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid +
               [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid +
               [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid +
               [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid -Replace "-" }

    $Chunks = [math]::Ceiling($FileSize/1kb)

    [io.file]::WriteAllText("$Path\$FileName","$(-Join (1..($Chunks)).foreach({ $Chunk.Invoke() }))")

    Write-Warning "New-RandomFile: $Path\$FileName"

}

If you dont care that all chunks are random, you can simply Invoke() the generation of the 1kb chunk once.. this improves the speed drastically, but won't make the entire file random.

Function New-RandomFile_Fast {
    Param(
        $Path = (Resolve-Path '.').Path,
        $FileSize = 1kb,
        $FileName = [guid]::NewGuid().Guid + '.txt'
        )

    $Chunk = { [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid +
               [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid +
               [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid +
               [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid +
               [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid +
               [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid +
               [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid +
               [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid -Replace "-" }
    $Chunks = [math]::Ceiling($FileSize/1kb)
    $ChunkString = $Chunk.Invoke()

    [io.file]::WriteAllText("$Path\$FileName","$(-Join (1..($Chunks)).foreach({ $ChunkString }))")

    Write-Warning "New-RandomFile: $Path\$FileName"

}

Measure-Command all these changes to generate a 10mb file:

Executing New-RandomFile: 35.7688241 seconds.

Executing New-RandomFile_1kChunks: 25.1463777 seconds.

Executing New-RandomFile_Fast: 1.1626236 seconds.


问:
Should I nest immutable.js Map and List in redux application?
I am using immutable.js in a redux application and I am wondering whether I should always use immutable.js datastructures where I would have used JSON object or array in a normal application.

Otherwise said, should the store of a redux application be a pure immutable.js datastructure or it's okay to mix with plain old javascript objects and arrays?

答: It's totally okay to use "old" javascript objects or array. If you use immutable.js everywhere, you will get more advantages than using "old" js objects. From their website, immutable.js is leading to much simpler application development, no defensive copying, and enabling advanced memoization and change detection techniques with simple logic.. It will enforce the use of functional programming patterns like pure function, which redux use a lot. You will avoid useless object mutation and related bugs. Your code will be more along the lines of the redux way of thinking. It might take more time to code with immutable.js, but your code will be better, faster and easier to update overall. Since you're using react. You won't get a lot of benefits using immutable.js inside a component because react has a great way to handle object change easily. I will suggest you to try to keep your redux store as pure immutable.js data structure as possible to avoid strange side effects and bugs. You will become used to it, but like I said before, it's totally fine to use non immutable-js data structure. Sometimes it will be easier not to use it. I will suggest you to try using it everywhere and you will be able to see by yourself if it's a waste of time or not.


问:
Core Spotlight Userinfo is always empty
I am using a combination of CoreSpotlight api and NSUserActivity api to index app content. Everything goes well until I tap a search result. The userInfo passed with userActivity in continueUserActivity method contains only one item i.e kCSSearchableItemActivityIdentifier. My other custom keys are nil.

Here is my code for indexing items..

```<code>class MyTestViewController:UIViewController{
     viewDidLoad(){
        searchHandler = SearchHandler()
        searchHandler.index(items)
     }
 }

 class  SearchHandler{
         var activity: NSUserActivity!

         func index(items:[Item]){
            for item in items{
         let attributeSet = getSearchItemAttribute(item)
                if let attributeSet =  attributeSet{
                    let searchableItem = CSSearchableItem(uniqueIdentifier: item.uniqueId, domainIdentifier:itemType.groupId(), attributeSet: attributeSet)
                    searchableItem.expirationDate = item.expirationDate
                    addToSpotlight([searchableItem])
                }

            activity = NSUserActivity(activityType: searchPrivacy.activity())
            activity.delegate = delegate

            //meta data
            activity.title = item.title

            var userInfoDic = [NSObject:AnyObject]()
            userInfoDic["indexItemType"] = itemType.rawValue
            userInfoDic["address"] = item.title
            activity.userInfo = userInfoDic

            if item.expirationDate != nil { activity.expirationDate = item.expirationDate! }
            if item.keywords != nil { activity.keywords = item.keywords! }
            activity.contentAttributeSet = attributeSet

            //eligibility
            activity.eligibleForHandoff = false
            activity.eligibleForSearch = true
            activity.eligibleForPublicIndexing = true
            activity.requiredUserInfoKeys = Set(["indexItemType","address"])

            activity.becomeCurrent()
            }
 }

 private  func getSearchItemAttribute(item:Item) ->CSSearchableItemAttributeSet?{
    if item.contentType != nil { // add an entry to core spot light
        let attributeSet = CSSearchableItemAttributeSet(itemContentType: item.contentType!)
        attributeSet.relatedUniqueIdentifier = item.uniqueId
        HALog.i("item.uniqueId= \(item.uniqueId)")
        attributeSet.title = item.title
        attributeSet.thumbnailData = item.thumbnailData
        attributeSet.thumbnailURL = item.thumbnailUrl
        attributeSet.rating = item.ratings
        attributeSet.ratingDescription = item.ratingDescription
        attributeSet.contentDescription = item.contentDescription
        return attributeSet
    }
    return nil
}

private  func addToSpotlight(searchableItems:[CSSearchableItem]) {

    CSSearchableIndex.defaultSearchableIndex().indexSearchableItems(searchableItems) { (error) -> Void in
        if let error = error {
            HALog.e("Deindexing error: \(error.localizedDescription)")
        } else {
            HALog.i("Search item successfully indexed!")
        }
    }

   }
}
</code>```

Whenever I try to access indexItemType or address keys in userInfo its always nil.

I have tried all the solutions  from these threads:

iOS 9 - NSUserActivity userinfo property showing null

http://helpprogramming.xyz/question/31328032/ios-9-nsuseractivity-userinfo-property-showing-null

None of the above solved my problem.
I am currently using Xcode 7 with iOS 9.

答:
I had the same issue here, and i searched so many answers not working for me...
fortunately i got my solution in ios-9-tutorial-series-search-api

I recommend you read all the content above. I will give you two alternative solutions:

use NSUserActivity instead of CSSearchableItem: when you done your data setting, call userActivity.becomeCurrent, then your can found your data in spotlight(just two more things: I don't have a iOS 9 device, so only tested in iOS 10 Device, and the article I mentioned above said NSUserActivity is limited to one activity per navigation point, but I don't have such kind issue...)

use CSSearchableItem, set the uniqueIdentifier to a JSON string that contains your custom userInfo.

NOTE: Do not index a CSSearchableItem and call userActivity.becomeCurrent both, otherwise you will got two spotlight results. One of them is com.apple.corespotlightitem, other one is your custom activityType

Title: Core Spotlight Userinfo is always empty

Body:
I am using a combination of CoreSpotlight api and NSUserActivity api to index app content. Everything goes well until I tap a search result. The userInfo passed with userActivity in continueUserActivity method contains only one item i.e kCSSearchableItemActivityIdentifier. My other custom keys are nil.

Here is my code for indexing items..

class MyTestViewController:UIViewController{
     viewDidLoad(){
        searchHandler = SearchHandler()
        searchHandler.index(items)
     }
 }

 class  SearchHandler{
         var activity: NSUserActivity!

         func index(items:[Item]){
            for item in items{
         let attributeSet = getSearchItemAttribute(item)
                if let attributeSet =  attributeSet{
                    let searchableItem = CSSearchableItem(uniqueIdentifier: item.uniqueId, domainIdentifier:itemType.groupId(), attributeSet: attributeSet)
                    searchableItem.expirationDate = item.expirationDate
                    addToSpotlight([searchableItem])
                }

            activity = NSUserActivity(activityType: searchPrivacy.activity())
            activity.delegate = delegate

            //meta data
            activity.title = item.title

            var userInfoDic = [NSObject:AnyObject]()
            userInfoDic["indexItemType"] = itemType.rawValue
            userInfoDic["address"] = item.title
            activity.userInfo = userInfoDic

            if item.expirationDate != nil { activity.expirationDate = item.expirationDate! }
            if item.keywords != nil { activity.keywords = item.keywords! }
            activity.contentAttributeSet = attributeSet

            //eligibility
            activity.eligibleForHandoff = false
            activity.eligibleForSearch = true
            activity.eligibleForPublicIndexing = true
            activity.requiredUserInfoKeys = Set(["indexItemType","address"])

            activity.becomeCurrent()
            }
 }

 private  func getSearchItemAttribute(item:Item) ->CSSearchableItemAttributeSet?{
    if item.contentType != nil { // add an entry to core spot light
        let attributeSet = CSSearchableItemAttributeSet(itemContentType: item.contentType!)
        attributeSet.relatedUniqueIdentifier = item.uniqueId
        HALog.i("item.uniqueId= \(item.uniqueId)")
        attributeSet.title = item.title
        attributeSet.thumbnailData = item.thumbnailData
        attributeSet.thumbnailURL = item.thumbnailUrl
        attributeSet.rating = item.ratings
        attributeSet.ratingDescription = item.ratingDescription
        attributeSet.contentDescription = item.contentDescription
        return attributeSet
    }
    return nil
}

private  func addToSpotlight(searchableItems:[CSSearchableItem]) {

    CSSearchableIndex.defaultSearchableIndex().indexSearchableItems(searchableItems) { (error) -> Void in
        if let error = error {
            HALog.e("Deindexing error: \(error.localizedDescription)")
        } else {
            HALog.i("Search item successfully indexed!")
        }
    }

   }
}

Whenever I try to access indexItemType or address keys in userInfo its always nil.

I have tried all the solutions  from these threads:

iOS 9 - NSUserActivity userinfo property showing null

http://helpprogramming.xyz/question/31328032/ios-9-nsuseractivity-userinfo-property-showing-null

None of the above solved my problem.
I am currently using Xcode 7 with iOS 9.


问:
JAVA making time to decrease to zero by swing timer
I have a milliseconds and i convert it hh:mm:ss now i want to make it to automatically decrease value overtime.. something like countdown timer

for example, when user sees it, 2:11 0 -> 2:10 59 -> 2:10 58 ...

Below is my code..

```<code>        Timer t = new Timer(1000, new ActionListener() {
            public void actionPerformed(ActionEvent e) {

                int s = ((TIMER/1000) % 60);
                int m = (((TIMER/1000) / 60) % 60);
                int h = ((((TIMER/1000) / 60) /60) % 60);

                timing.setText(hour + " hours, " + min + " minutes" + sec + " seconds");
                timing.repaint();
}
}
t.start();
</code>```

is it possible?

答:
As Peter mentioned in his answer, you shouldn't relay on decreasing a number, since there are not guarantees that actionPerformed is invoked right in every second. The below is a working example, which stops the timer on finishing (detailed and therefor code):

```<code>import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Test extends JFrame {
  private JTextField text;
  private Timer timer;
  private JButton start;

  public Test() {
    super("Countdown timer");
    text = new JTextField("2", 8);
    start = new JButton("Start");
    start.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent click) {
        final long current = System.currentTimeMillis();
        try {
          final long limit = Integer.parseInt(text.getText().trim())* 1000; // X seconds
          timer = new Timer(1000, new ActionListener() {
            public void actionPerformed(ActionEvent event) {
              long time = System.currentTimeMillis();
              long passed = time - current;
              long remaining = limit - passed;
              if(remaining <= 0) {
                text.setText("2");
                timer.stop();
              } else {
                long seconds = remaining/1000;
                long minutes = seconds/60;
                long hours = minutes/60;
                text.setText(String.format("%02d:%02d:%02d", hours, minutes, seconds%60));
              }
            }
            });
          timer.start();
        } catch(NumberFormatException nfe) {
          // debug/report here
          nfe.printStackTrace();
        }
      }});
    JPanel panel = new JPanel();
    panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
    panel.add(text);
    panel.add(new JLabel(" seconds"));
    panel.add(start);
    add(panel);
  }

  public static void main(String [] args) throws Exception {
    Test frame = new Test();
    frame.setDefaultCloseOperation(Test.EXIT_ON_CLOSE);
    frame.pack();
    frame.setVisible(true);
  }
}
</code>```

Body:
I have a milliseconds and i convert it hh:mm:ss now i want to make it to automatically decrease value overtime.. something like countdown timer

for example, when user sees it, 2:11 0 -> 2:10 59 -> 2:10 58 ...

Below is my code..

        Timer t = new Timer(1000, new ActionListener() {
            public void actionPerformed(ActionEvent e) {

                int s = ((TIMER/1000) % 60);
                int m = (((TIMER/1000) / 60) % 60);
                int h = ((((TIMER/1000) / 60) /60) % 60);

                timing.setText(hour + " hours, " + min + " minutes" + sec + " seconds");
                timing.repaint();
}
}
t.start();

is it possible?

Body:
As Peter mentioned in his answer, you shouldn't relay on decreasing a number, since there are not guarantees that actionPerformed is invoked right in every second. The below is a working example, which stops the timer on finishing (detailed and therefor code):

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Test extends JFrame {
  private JTextField text;
  private Timer timer;
  private JButton start;

  public Test() {
    super("Countdown timer");
    text = new JTextField("2", 8);
    start = new JButton("Start");
    start.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent click) {
        final long current = System.currentTimeMillis();
        try {
          final long limit = Integer.parseInt(text.getText().trim())* 1000; // X seconds
          timer = new Timer(1000, new ActionListener() {
            public void actionPerformed(ActionEvent event) {
              long time = System.currentTimeMillis();
              long passed = time - current;
              long remaining = limit - passed;
              if(remaining <= 0) {
                text.setText("2");
                timer.stop();
              } else {
                long seconds = remaining/1000;
                long minutes = seconds/60;
                long hours = minutes/60;
                text.setText(String.format("%02d:%02d:%02d", hours, minutes, seconds%60));
              }
            }
            });
          timer.start();
        } catch(NumberFormatException nfe) {
          // debug/report here
          nfe.printStackTrace();
        }
      }});
    JPanel panel = new JPanel();
    panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
    panel.add(text);
    panel.add(new JLabel(" seconds"));
    panel.add(start);
    add(panel);
  }

  public static void main(String [] args) throws Exception {
    Test frame = new Test();
    frame.setDefaultCloseOperation(Test.EXIT_ON_CLOSE);
    frame.pack();
    frame.setVisible(true);
  }
}


问:
How to print string by awk in special format?
it's that able to convert following string

```
3.840527449999989,6A3,06,67,07,DF,0D,63,81,AA
4.306243875,601,02,3E,80,00,00,00,00,00
```

to format string like below

```
3.840527449999989,6A3,06 67 07 DF 0D 63 81 AA
4.306243875000000,601,02 3E 80 00 00 00 00 00
```

Note that:

timestamps should postfix 0 if necessary

data bytes should remove , between them

Body:
it's that able to convert following string

3.840527449999989,6A3,06,67,07,DF,0D,63,81,AA
4.306243875,601,02,3E,80,00,00,00,00,00

to format string like below

3.840527449999989,6A3,06 67 07 DF 0D 63 81 AA
4.306243875000000,601,02 3E 80 00 00 00 00 00

Note that:

timestamps should postfix 0 if necessary

data bytes should remove , between them

Body:
Use printf:

awk -F, '{printf("%.15f,%s,%s %s %s %s %s %s %s %s\n", $1, $2, $3, $4, $5, $6, $7, $8, $9, $10)}' file

Output:

3.840527449999989,6A3,06 67 07 DF 0D 63 81 AA
4.306243875000000,601,02 3E 80 00 00 00 00 00


问:
Erlang: programmatically get application version
I have an OTP application. The version of this application is found in two places: the src/application_name.src file (standard with OTP applications), and in my rebar.config.

Is there an "official" way for an application to get it's own version, or does this need to be hacked via sed/grep etc? I want to have an "info" endpoint in my application that prints it's own version. Of course I can always do something like grep the version out of my rebar.config, but it seems hacky.

答:
According to the Erlang documentation you can use API of application module.

Example:

```<code>Erlang/OTP 19 [erts-8.2.2] [source-1ca84a4] [64-bit] [smp:4:4] [async-threads:10] [hipe] [kernel-poll:false]

Eshell V8.2.2  (abort with ^G)
1> application:loaded_applications().
[{stdlib,"ERTS  CXC 138 10","3.2"},
{kernel,"ERTS  CXC 138 10","5.1.1"}]

2> GetVer =
fun(App) ->
    case lists:keyfind(App, 1, application:loaded_applications()) of
        {_, _, Ver} ->
            Ver;
        false ->
            not_found
    end
end.
#Fun<erl_eval.6.52032458>

3> GetVer(stdlib).
"3.2"

4> GetVer(eunit).
not_found

5> application:load(eunit).
ok

6> GetVer(eunit).
"2.3.2"

7>
</code>```

Body:
According to the Erlang documentation you can use API of application module.

Example:

Erlang/OTP 19 [erts-8.2.2] [source-1ca84a4] [64-bit] [smp:4:4] [async-threads:10] [hipe] [kernel-poll:false]

Eshell V8.2.2  (abort with ^G)
1> application:loaded_applications().
[{stdlib,"ERTS  CXC 138 10","3.2"},
{kernel,"ERTS  CXC 138 10","5.1.1"}]

2> GetVer =
fun(App) ->
    case lists:keyfind(App, 1, application:loaded_applications()) of
        {_, _, Ver} ->
            Ver;
        false ->
            not_found
    end
end.
#Fun<erl_eval.6.52032458>

3> GetVer(stdlib).
"3.2"

4> GetVer(eunit).
not_found

5> application:load(eunit).
ok

6> GetVer(eunit).
"2.3.2"

7>


问:
Is there a terminology for 'making a struct inaccessible directly' in C?
I've found a certain code in hostap. The below is a simplified one:

a.h

```<code>// it just declares 'there is a struct a'
struct a;

// it seems like an accessor to a private member b
int get_b(struct a);
</code>```

a.c

```<code>// definition is seprated from a header file
struct a {
    int b;
};

int get_b(struct a) {
    return a.b;
}
</code>```

An object file a.o is generated with these two files.

And if other source codes want to use struct a, it cannot directly access to a member b, with a compiler complaining dereferencing incomplete type. I only can access to a member b with get_b().

First time, I am very frustrated by such a pattern. But finally, I feel that it is very a well-designed pattern if someone wants to protect the integrity of struct a (e.g., values of memebers must be set in certain criteria, or members are dependent to each other so that change of one member will affect the others)

Is there a terminology for this kind of pattern?

答:
Information hiding, typically a component of Encapsulation.

As noted by dbush and dasblinkenlight, this specific instance would be an opaque data type.

Body:
I've found a certain code in hostap. The below is a simplified one:

a.h

// it just declares 'there is a struct a'
struct a;

// it seems like an accessor to a private member b
int get_b(struct a);

a.c

// definition is seprated from a header file
struct a {
    int b;
};

int get_b(struct a) {
    return a.b;
}

An object file a.o is generated with these two files.

And if other source codes want to use struct a, it cannot directly access to a member b, with a compiler complaining dereferencing incomplete type. I only can access to a member b with get_b().

First time, I am very frustrated by such a pattern. But finally, I feel that it is very a well-designed pattern if someone wants to protect the integrity of struct a (e.g., values of memebers must be set in certain criteria, or members are dependent to each other so that change of one member will affect the others)

Is there a terminology for this kind of pattern?


问:
I cant compile program that uses class and list
I wrote a program that allows the user to enter 3 names, and then displays the list of the names.

I cant compile this program. The error message says "error: request for member ‘list’ in ‘input’, which is of non-class type ‘Name()’
  input.list(); "

I dont understand what I did wrong.

```<code>#include <iostream>
#include<list>
#include<string>
using namespace std;

class Name
{
    std::list<string> namelist;
    public:
    Name();
    void list();
};

Name::Name()
{
    int i;
    string input[i];
    for(i=0; i<3; i++)
    {

        cout<<"Insert name: "<<input[i]<<endl;
        namelist.push_front(input[i]);
    }

}

void Name::list()
{

    for (std::list<string>::iterator NL = namelist.begin(); NL !=  namelist.end(); NL++)
    std::cout << *NL << ' ';
    std::cout << '\n';
}

int main()
{

    Name input();
    input.list();
    return 0;
}
</code>```

答:
In your main(), Name input(); is not a definition of object, should be:

```<code>Name input;
</code>```

I think what you want to do in constructor of Name is:

```<code>Name::Name()
{
    const int SIZE = 3;
    string input[SIZE]; // size of array should be const
    for (int i = 0; i<SIZE; i++)
    {
        cout << "Insert name: " << endl;
        cin >> input[i];
        namelist.push_front(input[i]);
    }
}
</code>```

And can be improved. Since input only used to store temporary value, there is no need to use array:

```<code>Name::Name()
{
    const int SIZE = 3;
    string input; // only stores temporary value, no need to use array
    for (int i = 0; i<SIZE; i++)
    {
        cout << "Insert name: "  << endl;
        cin >> input;
        namelist.push_front(input);
    }
}
</code>```

Body:
I wrote a program that allows the user to enter 3 names, and then displays the list of the names.

I cant compile this program. The error message says "error: request for member ‘list’ in ‘input’, which is of non-class type ‘Name()’
  input.list(); "

I dont understand what I did wrong.

#include <iostream>
#include<list>
#include<string>
using namespace std;

class Name
{
    std::list<string> namelist;
    public:
    Name();
    void list();
};

Name::Name()
{
    int i;
    string input[i];
    for(i=0; i<3; i++)
    {

        cout<<"Insert name: "<<input[i]<<endl;
        namelist.push_front(input[i]);
    }

}

void Name::list()
{

    for (std::list<string>::iterator NL = namelist.begin(); NL !=  namelist.end(); NL++)
    std::cout << *NL << ' ';
    std::cout << '\n';
}

int main()
{

    Name input();
    input.list();
    return 0;
}

Body:
In your main(), Name input(); is not a definition of object, should be:

Name input;

I think what you want to do in constructor of Name is:

Name::Name()
{
    const int SIZE = 3;
    string input[SIZE]; // size of array should be const
    for (int i = 0; i<SIZE; i++)
    {
        cout << "Insert name: " << endl;
        cin >> input[i];
        namelist.push_front(input[i]);
    }
}

And can be improved. Since input only used to store temporary value, there is no need to use array:

Name::Name()
{
    const int SIZE = 3;
    string input; // only stores temporary value, no need to use array
    for (int i = 0; i<SIZE; i++)
    {
        cout << "Insert name: "  << endl;
        cin >> input;
        namelist.push_front(input);
    }
}


问:
List comprehension not working
I want to put the unique items from one list to another list, i.e eliminating duplicate items. When I do it by the longer method I am able to do it see for example.

```<code>>>>new_list = []
>>>a = ['It', 'is', 'the', 'east', 'and', 'Juliet', 'is', 'the', 'sun']

>>> for word in a:
    if word not in a:
        new_list.append(word)

>>> new_list
['It', 'is', 'the', 'east', 'and', 'Juliet', 'sun']
</code>```

But when try to accomplish this using list comprehension in a single line the each iteration returns value "None"

```<code>>>> new_list = []
>>> a = ['It', 'is', 'the', 'east', 'and', 'Juliet', 'is', 'the', 'sun']
>>> new_list = [new_list.append(word) for word in a if word not in new_list]
</code>```

Can someone please help in understanding whats going wrong in the list comprehension.

Thanks in Advance
Umesh

答:
List comprehensions provide a concise way to create lists. Common
  applications are to make new lists where each element is the result of
  some operations applied to each member of another sequence or
  iterable, or to create a subsequence of those elements that satisfy a
  certain condition.

Maybe you can try this:

```<code>>>> new_list = []
>>> a = ['It', 'is', 'the', 'east', 'and', 'Juliet', 'is', 'the', 'sun']
>>> unused=[new_list.append(word) for word in a if word not in new_list]
>>> new_list
['It', 'is', 'the', 'east', 'and', 'Juliet', 'sun']
>>> unused
[None, None, None, None, None, None, None]
</code>```

Notice:

append() returns None if the inserted operation is successful.

Another way, you can try to use set to remove duplicate item:

```<code>>>> a = ['It', 'is', 'the', 'east', 'and', 'Juliet', 'is', 'the', 'sun']
>>> list(set(a))
['and', 'sun', 'is', 'It', 'the', 'east', 'Juliet']
</code>```

Title: List comprehension not working

Body:
I want to put the unique items from one list to another list, i.e eliminating duplicate items. When I do it by the longer method I am able to do it see for example.

>>>new_list = []
>>>a = ['It', 'is', 'the', 'east', 'and', 'Juliet', 'is', 'the', 'sun']

>>> for word in a:
    if word not in a:
        new_list.append(word)

>>> new_list
['It', 'is', 'the', 'east', 'and', 'Juliet', 'sun']

But when try to accomplish this using list comprehension in a single line the each iteration returns value "None"

>>> new_list = []
>>> a = ['It', 'is', 'the', 'east', 'and', 'Juliet', 'is', 'the', 'sun']
>>> new_list = [new_list.append(word) for word in a if word not in new_list]

Can someone please help in understanding whats going wrong in the list comprehension.

Thanks in Advance
Umesh

Body:
List comprehensions provide a concise way to create lists. Common
  applications are to make new lists where each element is the result of
  some operations applied to each member of another sequence or
  iterable, or to create a subsequence of those elements that satisfy a
  certain condition.

Maybe you can try this:

>>> new_list = []
>>> a = ['It', 'is', 'the', 'east', 'and', 'Juliet', 'is', 'the', 'sun']
>>> unused=[new_list.append(word) for word in a if word not in new_list]
>>> new_list
['It', 'is', 'the', 'east', 'and', 'Juliet', 'sun']
>>> unused
[None, None, None, None, None, None, None]

Notice:

append() returns None if the inserted operation is successful.

Another way, you can try to use set to remove duplicate item:

>>> a = ['It', 'is', 'the', 'east', 'and', 'Juliet', 'is', 'the', 'sun']
>>> list(set(a))
['and', 'sun', 'is', 'It', 'the', 'east', 'Juliet']


问:
Ubuntu Logs and Monitoring
I am writing simple program for my Ubuntu 10.04.
I want to see which files were used by processes. Where I can see what file was requested by the process?</p>

答:
I don't know of any log files which list past files that had been opened by a process but I know of a couple ways to determine what files a process opens.

Using strace (system call trace) you can find out what files a program opens:

```<code>strace -e trace=open <path_to_executable>
</code>```

You could also try using lsof (list open files) to determine what files are currently open by running processes.

Title: Ubuntu Logs and Monitoring

Body:
I don't know of any log files which list past files that had been opened by a process but I know of a couple ways to determine what files a process opens.

Using strace (system call trace) you can find out what files a program opens:

strace -e trace=open <path_to_executable>

You could also try using lsof (list open files) to determine what files are currently open by running processes.


问:
Original array still changes after editing a sliced copy
I'm trying to save a copy of the original coordinates of the vertices of a Geometry object. I tried to copy the object the way I found lots of answers for here on stackoverflow.

// create a Geometry object from a BufferGeometry
cityGeometry = new THREE.Geometry().fromBufferGeometry( child.geometry );

// properly copy the cityGeometry.vertices array
var originalPositions = cityGeometry.vertices.slice(0);

// change an element of the copy
originalPositions[0].z = 1000;
console.log(originalPositions[0]);
console.log(cityGeometry.vertices[0]);

// now change the original object
cityGeometry.vertices[0].z = 123;
console.log(originalPositions[0]);
console.log(cityGeometry.vertices[0]);
```

<p>However, if I do this, both objects always change at the same time. The console output reads:</p>

<pre class="lang-html prettyprint-override"><code>Vector3 {x: 0.8206260204315186, y: -0.4336470067501068, z: 1000}
Vector3 {x: 0.8206260204315186, y: -0.4336470067501068, z: 1000}
Vector3 {x: 0.8206260204315186, y: -0.4336470067501068, z: 123}
Vector3 {x: 0.8206260204315186, y: -0.4336470067501068, z: 123}
</code>```

Am I missing something here? Thanks!

答:
The problem here is that Array#slice only returns a shallow copy of an array -- thus, while the array references are themselves different, the vector objects within are actually the same. Since these Vector3 references are shared, modifying any vector via the copied array will mean those changes are reflected in the original array, giving the appearance that the array was never copied at all.

You can create a deep copy of your vertices array using Array#map and Vector3#clone:

```<code>var originalPositions = cityGeometry.vertices.map(function (v) { return v.clone() })
</code>```

Full Code:

// create a Geometry object from a BufferGeometry
cityGeometry = new THREE.Geometry().fromBufferGeometry( child.geometry );

// properly copy the cityGeometry.vertices array
var originalPositions = cityGeometry.vertices.map(function (v) { return v.clone() });

// change an element of the copy
originalPositions[0].z = 1000;
console.log(originalPositions[0]);
console.log(cityGeometry.vertices[0]);

// now change the original object
cityGeometry.vertices[0].z = 123;
console.log(originalPositions[0]);
console.log(cityGeometry.vertices[0]);
```

<pre class="lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/84/three.min.js"></script>
</code>```

Body:
I'm trying to save a copy of the original coordinates of the vertices of a Geometry object. I tried to copy the object the way I found lots of answers for here on stackoverflow.

// create a Geometry object from a BufferGeometry
cityGeometry = new THREE.Geometry().fromBufferGeometry( child.geometry );

// properly copy the cityGeometry.vertices array
var originalPositions = cityGeometry.vertices.slice(0);

// change an element of the copy
originalPositions[0].z = 1000;
console.log(originalPositions[0]);
console.log(cityGeometry.vertices[0]);

// now change the original object
cityGeometry.vertices[0].z = 123;
console.log(originalPositions[0]);
console.log(cityGeometry.vertices[0]);

However, if I do this, both objects always change at the same time. The console output reads:

Vector3 {x: 0.8206260204315186, y: -0.4336470067501068, z: 1000}
Vector3 {x: 0.8206260204315186, y: -0.4336470067501068, z: 1000}
Vector3 {x: 0.8206260204315186, y: -0.4336470067501068, z: 123}
Vector3 {x: 0.8206260204315186, y: -0.4336470067501068, z: 123}

Am I missing something here? Thanks!

Body:
The problem here is that Array#slice only returns a shallow copy of an array -- thus, while the array references are themselves different, the vector objects within are actually the same. Since these Vector3 references are shared, modifying any vector via the copied array will mean those changes are reflected in the original array, giving the appearance that the array was never copied at all.

You can create a deep copy of your vertices array using Array#map and Vector3#clone:

var originalPositions = cityGeometry.vertices.map(function (v) { return v.clone() })

Full Code:

// create a Geometry object from a BufferGeometry
cityGeometry = new THREE.Geometry().fromBufferGeometry( child.geometry );

// properly copy the cityGeometry.vertices array
var originalPositions = cityGeometry.vertices.map(function (v) { return v.clone() });

// change an element of the copy
originalPositions[0].z = 1000;
console.log(originalPositions[0]);
console.log(cityGeometry.vertices[0]);

// now change the original object
cityGeometry.vertices[0].z = 123;
console.log(originalPositions[0]);
console.log(cityGeometry.vertices[0]);

<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/84/three.min.js"></script>

ContentLicense: CC BY-SA 4.0


问:
Generating Random Files in Windows
Does anyone have a way to generate files of random data in Windows?  I would like to generate 50,000 small (2K) files as an example.</p>

答:
Instead of using Get-Random to generate the text as per user188737 & mguassa suggestions, I improved the speed by using GUIDs.

```<code>Function New-RandomFile {
    Param(
        $Path = '.',
        $FileSize = 1kb,
        $FileName = [guid]::NewGuid().Guid + '.txt'
        )
    (1..($FileSize/128)).foreach({-join ([guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid -Replace "-").SubString(1, 126) }) | set-content "$Path\$FileName"
}
</code>```

This took 491 milliseconds to generate a 1mb file. Running:

```<code>New-RandomFile -FileSize 1mb
</code>```

UPDATE:

I've updated my function to use a ScriptBlock, so you can replace the 'NewGuid()' method with anything you want.

In this scenario, I make 1kb chunks, since I know I'm never creating smaller files. This improved the speed of my function drastically!

Set-Content forces a NewLine at the end, which is why you need to remove 2 Characters each time you write to file. I've replaced it with [io.file]::WriteAllText() instead.

```<code>Function New-RandomFile_1kChunks {
    Param(
        $Path = (Resolve-Path '.').Path,
        $FileSize = 1kb,
        $FileName = [guid]::NewGuid().Guid + '.txt'
        )

    $Chunk = { [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid +
               [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid +
               [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid +
               [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid +
               [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid +
               [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid +
               [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid +
               [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid -Replace "-" }

    $Chunks = [math]::Ceiling($FileSize/1kb)

    [io.file]::WriteAllText("$Path\$FileName","$(-Join (1..($Chunks)).foreach({ $Chunk.Invoke() }))")

    Write-Warning "New-RandomFile: $Path\$FileName"

}
</code>```

If you dont care that all chunks are random, you can simply Invoke() the generation of the 1kb chunk once.. this improves the speed drastically, but won't make the entire file random.

```<code>Function New-RandomFile_Fast {
    Param(
        $Path = (Resolve-Path '.').Path,
        $FileSize = 1kb,
        $FileName = [guid]::NewGuid().Guid + '.txt'
        )

    $Chunk = { [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid +
               [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid +
               [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid +
               [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid +
               [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid +
               [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid +
               [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid +
               [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid -Replace "-" }
    $Chunks = [math]::Ceiling($FileSize/1kb)
    $ChunkString = $Chunk.Invoke()

    [io.file]::WriteAllText("$Path\$FileName","$(-Join (1..($Chunks)).foreach({ $ChunkString }))")

    Write-Warning "New-RandomFile: $Path\$FileName"

}
</code>```

Measure-Command all these changes to generate a 10mb file:

Executing New-RandomFile: 35.7688241 seconds.

Executing New-RandomFile_1kChunks: 25.1463777 seconds.

Executing New-RandomFile_Fast: 1.1626236 seconds.

OwnerDisplayName: Jeff

Title: Generating Random Files in Windows

Body:
Instead of using Get-Random to generate the text as per user188737 & mguassa suggestions, I improved the speed by using GUIDs.

Function New-RandomFile {
    Param(
        $Path = '.',
        $FileSize = 1kb,
        $FileName = [guid]::NewGuid().Guid + '.txt'
        )
    (1..($FileSize/128)).foreach({-join ([guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid -Replace "-").SubString(1, 126) }) | set-content "$Path\$FileName"
}

This took 491 milliseconds to generate a 1mb file. Running:

New-RandomFile -FileSize 1mb

UPDATE:

I've updated my function to use a ScriptBlock, so you can replace the 'NewGuid()' method with anything you want.

In this scenario, I make 1kb chunks, since I know I'm never creating smaller files. This improved the speed of my function drastically!

Set-Content forces a NewLine at the end, which is why you need to remove 2 Characters each time you write to file. I've replaced it with [io.file]::WriteAllText() instead.

Function New-RandomFile_1kChunks {
    Param(
        $Path = (Resolve-Path '.').Path,
        $FileSize = 1kb,
        $FileName = [guid]::NewGuid().Guid + '.txt'
        )

    $Chunk = { [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid +
               [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid +
               [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid +
               [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid +
               [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid +
               [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid +
               [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid +
               [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid -Replace "-" }

    $Chunks = [math]::Ceiling($FileSize/1kb)

    [io.file]::WriteAllText("$Path\$FileName","$(-Join (1..($Chunks)).foreach({ $Chunk.Invoke() }))")

    Write-Warning "New-RandomFile: $Path\$FileName"

}

If you dont care that all chunks are random, you can simply Invoke() the generation of the 1kb chunk once.. this improves the speed drastically, but won't make the entire file random.

Function New-RandomFile_Fast {
    Param(
        $Path = (Resolve-Path '.').Path,
        $FileSize = 1kb,
        $FileName = [guid]::NewGuid().Guid + '.txt'
        )

    $Chunk = { [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid +
               [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid +
               [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid +
               [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid +
               [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid +
               [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid +
               [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid +
               [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid -Replace "-" }
    $Chunks = [math]::Ceiling($FileSize/1kb)
    $ChunkString = $Chunk.Invoke()

    [io.file]::WriteAllText("$Path\$FileName","$(-Join (1..($Chunks)).foreach({ $ChunkString }))")

    Write-Warning "New-RandomFile: $Path\$FileName"

}

Measure-Command all these changes to generate a 10mb file:

Executing New-RandomFile: 35.7688241 seconds.

Executing New-RandomFile_1kChunks: 25.1463777 seconds.

Executing New-RandomFile_Fast: 1.1626236 seconds.


答:
If you want a unique list of words, you can use set().

```<code>list(set(a))
# returns:
# ['It', 'is', 'east', 'and', 'the', 'sun', 'Juliet']
</code>```

If the order is important, try:

```<code>new_list = []
for word in a:
    if not a in new_list:
        new_list.append(word)
</code>```

Title: List comprehension not working

Body:
If you want a unique list of words, you can use set().

list(set(a))
# returns:
# ['It', 'is', 'east', 'and', 'the', 'sun', 'Juliet']

If the order is important, try:

new_list = []
for word in a:
    if not a in new_list:
        new_list.append(word)


问:
How expensive is it to dereference a pointer?
How expensive is it to perform the dereference operation on a pointer?

I can imagine that the memory transfer is somehow proportional to the object size, but I want to know how expensive the dereference operation part is.

答:
Dereferencing(multiple) cost CPU cycles.

Instead of writing:

```<code>string name = first->next->next->next->name;
int age = first->next->next->next->age;

this is O(n)
</code>```

Write it as:

```<code>node* billy_block = first->next->next->next;

string name = billy_block->name;
int age = billy_block->age;

this is O(1)
</code>```

So your code will not "ask" each and every block just to get to the fourth block.

Multiple dereferencing is like having a neighborhood who only knows a neighbor next to them.

Imagine if you ask a person from the first block where does your friend Billy resides, he will tell you he doesn't know your friend, he'll tell you he only know the neighbor next to them, then he'll just tell you to ask his neighbor, then you'll ask his neighbor, he'll answer the same thing as the first block did, you keep asking until you arrive at your friend's block.  Not very efficient

OwnerDisplayName: Tunnuz

LastEditorDisplayName: ChrisN

Body:
Dereferencing(multiple) cost CPU cycles.

Instead of writing:

string name = first->next->next->next->name;
int age = first->next->next->next->age;

this is O(n)

Write it as:

node* billy_block = first->next->next->next;

string name = billy_block->name;
int age = billy_block->age;

this is O(1)

So your code will not "ask" each and every block just to get to the fourth block.

Multiple dereferencing is like having a neighborhood who only knows a neighbor next to them.

Imagine if you ask a person from the first block where does your friend Billy resides, he will tell you he doesn't know your friend, he'll tell you he only know the neighbor next to them, then he'll just tell you to ask his neighbor, then you'll ask his neighbor, he'll answer the same thing as the first block did, you keep asking until you arrive at your friend's block.  Not very efficient

OwnerDisplayName: Michael Buen

LastEditorDisplayName: Michael Buen


问:
Smarty : evaluate a template stored in a PHP variable
i have a php variable which has html/smarty code in it

```<code>$x='<a href="{$link}" >{$title}</a>';
</code>```

This data is fetched from database , i want to evaluate it using smarty and put the output into a php variable (to print it out or to save it to the database again) .

Thanks

Edit :

i want the content of X to be evaluated using smarty , as if the content of x is stored in a file.tpl then $y=$smarty->fetch('file.tpl'); ... want to do it without the need to save the content of x into a file

答:
If I am following you, you mean that the whole string was in the database, that is, with {$link} as part of the string. I'm not sure how smarty works exactly, but it seems to me that if it even can do this, that string will have to have eval() run on it. (Unless smarty is doing something funky that I'm missing, again, I don't work with smarty)

What this means is you have a VERY insecure setup here. Should your database ever suffer an SQL injection, your whole server could be compromised.

Running these off a file that was hard coded into the app is not a huge security concern, since you have control over the code that called the .tpl, and you have control over the .tpl itself. That is a 'safe' use of eval, as you'd have to have some serious access to the server already to be able to exploit it, the kind of access that would be the reason to exploit it.

But once you access that data from a database, presumably with some kind of admin system that let's you add new dynamic templates, you have created a window into your system that an attacker might sneak into.

Body:
i have a php variable which has html/smarty code in it

$x='{$title}';

This data is fetched from database , i want to evaluate it using smarty and put the output into a php variable (to print it out or to save it to the database again) .

Thanks

Edit :

i want the content of X to be evaluated using smarty , as if the content of x is stored in a file.tpl then $y=$smarty->fetch('file.tpl'); ... want to do it without the need to save the content of x into a file