问:
Child div's height is shorter than the parent's, even with height set to 100%
I'm using bootstrap and I don't know why a child div's height is shorter on large screen and 100% on small screen. Here's a pciture of what it looks like on large screen . I want that white space at the bottom gone.I tried setting the height to 100% but it's not working. Here's how it looks like on small screen. You can notice that as the screen get smaller, the button is hiding behind the section below it.

Here's the html

```<code><div class="project">
    <div class="container-fluid">
        <div class="row">
            <div class="col-lg-6 col-md-6 col-sm-12 col-xs-12" id="project-description">
                <h3>Project</h3>
                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.<br> Nulla pretium varius velit, quis bibendum augue pharetra nec. Integer venenatis ipsum ex, quis euismod dui interdum non. Quisque lobortis magna in risus rutrum, vel dictum nulla pulvinar. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla pretium varius velit, quis bibendum augue pharetra nec. Integer venenatis ipsum ex, quis euismod dui interdum non. Quisque lobortis magna in risus rutrum, vel dictum nulla pulvinar. <br><br><a href="#" class="btn btn-default">More Info</a></p>
            </div>

            <div class="col-lg-6 col-md-6 col-sm-12 col-xs-12" id="project-picture">
            </div>
        </div>
    </div>
</div>
</code>```

And here's the css

```<code>    .project {
    height: 400px;
}

    .project .container-fluid {
    max-height: 100%;
}

    .project #project-description {
    background-color: #013051;
    max-height: 400px;
    color: #fff;
    font-family: Futura, "Trebuchet MS", Arial, sans-serif;
    font-size: 15px;
}

    .project #project-description h3 {
    margin-top: 60px;
}

    #project-description h3, #project-description p {
    margin-left:40px;
}

    #project-description p {
    border-left: 1px solid #f5f5f5;
    padding-left: 20px;
}

    #project-description p a {
    background-color: #013051;
    border: 1px solid #f5f5f5;
    color: #f5f5f5;
    padding: 10px 30px;
}

    #project-description p a:hover, .contact form button:hover {
    background-color: #f5f5f5;
    color: #000;
}

    .project #project-picture {
    background-image: url(file:///C:/Users/Nelson/Desktop/EsperAfrica/Images/jd-mason-43265.jpg);
    background-size: cover;
    background-position: center center;
    background-repeat: no-repeat;
    height: 400px;
}
</code>```

Thanks for your help

答: According to me the problem is that the parent div have some padding and margin. Which is not allowing the div to get its 100% height. Or maybe there could be any problem related bootst</p>

Body:
I'm using bootstrap and I don't know why a child div's height is shorter on large screen and 100% on small screen. Here's a pciture of what it looks like on large screen . I want that white space at the bottom gone.I tried setting the height to 100% but it's not working. Here's how it looks like on small screen. You can notice that as the screen get smaller, the button is hiding behind the section below it.

Here's the html

Project

Lorem ipsum dolor sit amet, consectetur adipiscing elit.
 Nulla pretium varius velit, quis bibendum augue pharetra nec. Integer venenatis ipsum ex, quis euismod dui interdum non. Quisque lobortis magna in risus rutrum, vel dictum nulla pulvinar. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla pretium varius velit, quis bibendum augue pharetra nec. Integer venenatis ipsum ex, quis euismod dui interdum non. Quisque lobortis magna in risus rutrum, vel dictum nulla pulvinar.

More Info

And here's the css

    .project {
    height: 400px;
}

    .project .container-fluid {
    max-height: 100%;
}

    .project #project-description {
    background-color: #013051;
    max-height: 400px;
    color: #fff;
    font-family: Futura, "Trebuchet MS", Arial, sans-serif;
    font-size: 15px;
}

    .project #project-description h3 {
    margin-top: 60px;
}

    #project-description h3, #project-description p {
    margin-left:40px;
}

    #project-description p {
    border-left: 1px solid #f5f5f5;
    padding-left: 20px;
}

    #project-description p a {
    background-color: #013051;
    border: 1px solid #f5f5f5;
    color: #f5f5f5;
    padding: 10px 30px;
}

    #project-description p a:hover, .contact form button:hover {
    background-color: #f5f5f5;
    color: #000;
}

    .project #project-picture {
    background-image: url(file:///C:/Users/Nelson/Desktop/EsperAfrica/Images/jd-mason-43265.jpg);
    background-size: cover;
    background-position: center center;
    background-repeat: no-repeat;
    height: 400px;
}

Thanks for your help


来源: stackexchange

问:
Java Swing: Rainbow border for a JComponent
I'm currently designing a title screen for a game. When designing the logo I decided to go with a rainbow border around the edges:

I figured after this I would like to implement the rest of my components on the title screen with a similar rainbow border (Specifically JButtons). While looking for ways to do this I came across the AbstractBorder class. My question is, is this even possible to do and if it is, What is the most effective way to use the Abstract border class to generate a rainbow border based on the size of the component?

答:
The basic approach is to use a LinearGradientPaint to paint the rainbow effect, for example...

```<code>public class RainbowBorder extends AbstractBorder {

    @Override
    public Insets getBorderInsets(Component c, Insets insets) {
        insets.bottom = insets.top = insets.left = insets.right = 1;
        return insets;
    }

    @Override
    public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
        Graphics2D g2d = (Graphics2D) g.create();
        LinearGradientPaint lpg = new LinearGradientPaint(
            new Point(x, y),
            new Point(x, y + height),
            new float[]{0.0f, 0.25f, 0.5f, 0.75f, 1.0f},
            new Color[]{Color.YELLOW, Color.GREEN, Color.CYAN, Color.BLUE, Color.MAGENTA});
        g2d.setPaint(lpg);
        g2d.draw(new Rectangle2D.Double(x, y, width - 1, height - 1));
        g2d.dispose();
    }

}
</code>```

And as a proof of concept

```<code>import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Insets;
import java.awt.LinearGradientPaint;
import java.awt.Point;
import java.awt.geom.Rectangle2D;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.AbstractBorder;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;

public class TextOutline {

    public static void main(String[] args) {
        new TextOutline();
    }

    public TextOutline() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class RainbowBorder extends AbstractBorder {

        @Override
        public Insets getBorderInsets(Component c) {
            return super.getBorderInsets(c); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public Insets getBorderInsets(Component c, Insets insets) {
            insets.bottom = insets.top = insets.left = insets.right = 1;
            return insets;
        }

        @Override
        public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
            Graphics2D g2d = (Graphics2D) g.create();
            LinearGradientPaint lpg = new LinearGradientPaint(
                new Point(x, y),
                new Point(x, y + height),
                new float[]{0.0f, 0.25f, 0.5f, 0.75f, 1.0f},
                new Color[]{Color.YELLOW,    Color.GREEN, Color.CYAN, Color.BLUE, Color.MAGENTA});
            g2d.setPaint(lpg);
            g2d.draw(new Rectangle2D.Double(x, y, width - 1, height - 1));
            g2d.dispose();
        }

    }

    class TestPane extends JPanel {

        public TestPane() {
            setLayout(new BorderLayout());
            setBorder(
                new CompoundBorder(
                    new EmptyBorder(10, 10, 10, 10),
                    new CompoundBorder(
                        new RainbowBorder(),
                        new EmptyBorder(10, 10, 10, 10))
            ));
            add(new JLabel("Rainbow and unicorns"));
        }
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
The basic approach is to use a LinearGradientPaint to paint the rainbow effect, for example...

public class RainbowBorder extends AbstractBorder {

    @Override
    public Insets getBorderInsets(Component c, Insets insets) {
        insets.bottom = insets.top = insets.left = insets.right = 1;
        return insets;
    }

    @Override
    public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
        Graphics2D g2d = (Graphics2D) g.create();
        LinearGradientPaint lpg = new LinearGradientPaint(
            new Point(x, y),
            new Point(x, y + height),
            new float[]{0.0f, 0.25f, 0.5f, 0.75f, 1.0f},
            new Color[]{Color.YELLOW, Color.GREEN, Color.CYAN, Color.BLUE, Color.MAGENTA});
        g2d.setPaint(lpg);
        g2d.draw(new Rectangle2D.Double(x, y, width - 1, height - 1));
        g2d.dispose();
    }

}

And as a proof of concept

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Insets;
import java.awt.LinearGradientPaint;
import java.awt.Point;
import java.awt.geom.Rectangle2D;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.AbstractBorder;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;

public class TextOutline {

    public static void main(String[] args) {
        new TextOutline();
    }

    public TextOutline() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class RainbowBorder extends AbstractBorder {

        @Override
        public Insets getBorderInsets(Component c) {
            return super.getBorderInsets(c); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public Insets getBorderInsets(Component c, Insets insets) {
            insets.bottom = insets.top = insets.left = insets.right = 1;
            return insets;
        }

        @Override
        public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
            Graphics2D g2d = (Graphics2D) g.create();
            LinearGradientPaint lpg = new LinearGradientPaint(
                new Point(x, y),
                new Point(x, y + height),
                new float[]{0.0f, 0.25f, 0.5f, 0.75f, 1.0f},
                new Color[]{Color.YELLOW,    Color.GREEN, Color.CYAN, Color.BLUE, Color.MAGENTA});
            g2d.setPaint(lpg);
            g2d.draw(new Rectangle2D.Double(x, y, width - 1, height - 1));
            g2d.dispose();
        }

    }

    class TestPane extends JPanel {

        public TestPane() {
            setLayout(new BorderLayout());
            setBorder(
                new CompoundBorder(
                    new EmptyBorder(10, 10, 10, 10),
                    new CompoundBorder(
                        new RainbowBorder(),
                        new EmptyBorder(10, 10, 10, 10))
            ));
            add(new JLabel("Rainbow and unicorns"));
        }
    }
}


问:
Is there a better way to write this navigation statement?
I know this is a redundant way to write these rules so I'm wondering if anyone knows a better way to write it. Thanks!</p>

```<code>$('.nav li a').eq(0).click(function() {

    $('.nav li a').eq(0).addClass("active");
    $('.nav li a').eq(1).removeClass("active");
    $('.nav li a').eq(2).removeClass("active");
    $('.nav li a').eq(3).removeClass("active");

});
$('.nav li a').eq(1).click(function() {

    $('.nav li a').eq(0).removeClass("active");
    $('.nav li a').eq(1).addClass("active");
    $('.nav li a').eq(2).removeClass("active");
    $('.nav li a').eq(3).removeClass("active");

});
$('.nav li a').eq(2).click(function() {

    $('.nav li a').eq(0).removeClass("active");
    $('.nav li a').eq(1).removeClass("active");
    $('.nav li a').eq(2).addClass("active");
    $('.nav li a').eq(3).removeClass("active");

});
$('.nav li a').eq(3).click(function() {

    $('.nav li a').eq(0).removeClass("active");
    $('.nav li a').eq(1).removeClass("active");
    $('.nav li a').eq(2).removeClass("active");
    $('.nav li a').eq(3).addClass("active");

});
</code>```

答:
I'd move the class to the
, like this:

```<code>$('.nav li').click(function() {
  $(this).addClass("active").siblings().removeClass("active");
});
</code>```

If you just changing the styling to match, for example:

```<code>li.active a { /* styles */ }
</code>```

...then it's much simpler overall to have the click handler on the
 elements, since those are the set you're dealing with.  There's also the more efficient .delegate() method:

```<code>$('.nav').delegate('li', 'click', function() {
  $(this).addClass("active").siblings().removeClass("active");
});
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I know this is a redundant way to write these rules so I'm wondering if anyone knows a better way to write it. Thanks!

$('.nav li a').eq(0).click(function() {

    $('.nav li a').eq(0).addClass("active");
    $('.nav li a').eq(1).removeClass("active");
    $('.nav li a').eq(2).removeClass("active");
    $('.nav li a').eq(3).removeClass("active");

});
$('.nav li a').eq(1).click(function() {

    $('.nav li a').eq(0).removeClass("active");
    $('.nav li a').eq(1).addClass("active");
    $('.nav li a').eq(2).removeClass("active");
    $('.nav li a').eq(3).removeClass("active");

});
$('.nav li a').eq(2).click(function() {

    $('.nav li a').eq(0).removeClass("active");
    $('.nav li a').eq(1).removeClass("active");
    $('.nav li a').eq(2).addClass("active");
    $('.nav li a').eq(3).removeClass("active");

});
$('.nav li a').eq(3).click(function() {

    $('.nav li a').eq(0).removeClass("active");
    $('.nav li a').eq(1).removeClass("active");
    $('.nav li a').eq(2).removeClass("active");
    $('.nav li a').eq(3).addClass("active");

});

Body:
I'd move the class to the <li>, like this:

$('.nav li').click(function() {
  $(this).addClass("active").siblings().removeClass("active");
});

If you just changing the styling to match, for example:

li.active a { /* styles */ }

...then it's much simpler overall to have the click handler on the <li> elements, since those are the set you're dealing with.  There's also the more efficient .delegate() method:

$('.nav').delegate('li', 'click', function() {
  $(this).addClass("active").siblings().removeClass("active");
});


问:
Java socket can client can not read the data
The client send a message, then the server receives the message and response the message. I don't know why the client can not read the response. If I remove the read part in client, the server can get the message. However for the following code, nothing work. Also I tried the flush(), it still doesn't work.

For client

```<code>public void run() {

    try (Socket echoSocket = new Socket(HOSTNAME, Integer.parseInt(PORTNUMBER));
            DataOutputStream dOut = new DataOutputStream(echoSocket.getOutputStream());
            DataInputStream dIn = new DataInputStream(echoSocket.getInputStream());
    ) {

        while (true) {

            command = UI.commandQueue.take()
            dOut.writeInt(Message.toByteArray(command).length);
            dOut.write(Message.toByteArray(command));

            int length;
            while((length = dIn.readInt()) != 0) {
            if (length > 0){
                byte[] messagebyte = new byte[length];
                dIn.readFully(messagebyte, 0, messagebyte.length);
                try {
                    msg = Message.fromByteArray(messagebyte);
                    testDisplay(msg);
                } catch (Exception e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                testDisplay(msg);
            }
            }

        }

    }catch (UnknownHostException e) {
        UI.display("Don't know about host " + HOSTNAME);
    } catch (IOException e) {
        UI.display("Couldn't get I/O for the connection to " + HOSTNAME);
    }
}
</code>```

For server

```<code>public void run() {

    try (ServerSocket serverSocket = new ServerSocket(Integer.parseInt(PORT_NUMBER));
            Socket clientSocket = serverSocket.accept();

            DataOutputStream dOut = new DataOutputStream(clientSocket.getOutputStream());
            DataInputStream dIn = new DataInputStream(clientSocket.getInputStream());) {
        int length;
        while ((length = dIn.readInt()) != 0) {
            if (length > 0) {
                byte[] messagebyte = new byte[length];
                dIn.readFully(messagebyte, 0, messagebyte.length); // read the
                                                                // message
                Message msg;
                try {
                    msg = Message.fromByteArray(messagebyte);
                    testDisplay(msg);
                    dOut.writeInt(Message.toByteArray(msg).length);
                    dOut.write(Message.toByteArray(msg));
                    UI.display("ack sent");
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    UI.display(e.getMessage());
                }

            }
            }
    } catch (IOException e) {
        UI.display(
                "Exception caught when trying to listen on port " + PORT_NUMBER + " or listening for a connection");
        UI.display(e.getMessage());
    }

}
</code>```

答: Your server is echoing one response per request, but your client is trying to read more than one response per request, which it will never get, so it blocks.</p>

Body:
The client send a message, then the server receives the message and response the message. I don't know why the client can not read the response. If I remove the read part in client, the server can get the message. However for the following code, nothing work. Also I tried the flush(), it still doesn't work.

For client

public void run() {

    try (Socket echoSocket = new Socket(HOSTNAME, Integer.parseInt(PORTNUMBER));
            DataOutputStream dOut = new DataOutputStream(echoSocket.getOutputStream());
            DataInputStream dIn = new DataInputStream(echoSocket.getInputStream());
    ) {

        while (true) {

            command = UI.commandQueue.take()
            dOut.writeInt(Message.toByteArray(command).length);
            dOut.write(Message.toByteArray(command));

            int length;
            while((length = dIn.readInt()) != 0) {
            if (length > 0){
                byte[] messagebyte = new byte[length];
                dIn.readFully(messagebyte, 0, messagebyte.length);
                try {
                    msg = Message.fromByteArray(messagebyte);
                    testDisplay(msg);
                } catch (Exception e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                testDisplay(msg);
            }
            }

        }

    }catch (UnknownHostException e) {
        UI.display("Don't know about host " + HOSTNAME);
    } catch (IOException e) {
        UI.display("Couldn't get I/O for the connection to " + HOSTNAME);
    }
}

For server

public void run() {

    try (ServerSocket serverSocket = new ServerSocket(Integer.parseInt(PORT_NUMBER));
            Socket clientSocket = serverSocket.accept();

            DataOutputStream dOut = new DataOutputStream(clientSocket.getOutputStream());
            DataInputStream dIn = new DataInputStream(clientSocket.getInputStream());) {
        int length;
        while ((length = dIn.readInt()) != 0) {
            if (length > 0) {
                byte[] messagebyte = new byte[length];
                dIn.readFully(messagebyte, 0, messagebyte.length); // read the
                                                                // message
                Message msg;
                try {
                    msg = Message.fromByteArray(messagebyte);
                    testDisplay(msg);
                    dOut.writeInt(Message.toByteArray(msg).length);
                    dOut.write(Message.toByteArray(msg));
                    UI.display("ack sent");
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    UI.display(e.getMessage());
                }

            }
            }
    } catch (IOException e) {
        UI.display(
                "Exception caught when trying to listen on port " + PORT_NUMBER + " or listening for a connection");
        UI.display(e.getMessage());
    }

}


问:
Datastax OpsCenter Install Cluster Error: 400 Client Error when retrieving package_information
I'm attempting to use OpsCenter 6.1 to install a new cluster. OpsCenter successfully ssh's to each of the nodes in the cluster then appears to nearly immediately error out on each node with the following message:

```<code>400 Client Error: Bad Request for url: http://<opscenter>:8888/api/v1/lcm/internal/nodes/<node-id>/package_information
</code>```

When attempting to reach that page myself I receive a 404 error with this message:

```<code>{"brief": "error", "message": "{\"type\":\"ApiException\",\"code\":404,\"msg\":\"Can't find object for given parameters: {:job-id nil, :node-id \\\"<node-id>\\\"}\"}", "type": "NoSuchResource"}
</code>```

Note that <opscenter> (above) is the IP address of my local install, and <node-id> is the ID of the node.

Considering that I don't receive the 400 error myself I'm assuming that I'm unable to replicate the scenario that occurs during the install because of some perviously executed steps that are rolled back.

Any insight into what might be causing this issue?

Thanks in advance!

答:
LCM developer here... It's hard to know exactly what's wrong based on the information provided. But here are some tips:

If there's an api error during a job, the error will be recorded in opscenterd.log (usually in /var/log/opscenter in package installs, or in something like ./log/ in tarball installs).

The internal api is private and is not publicly documented. It's authenticated via a per-node secret token that's only valid during the lifetime of a job, so it's fairly challenging to try to ping internal urls manually, we've never needed to have someone try to ping internal api's to successfully diagnose issues in the past. It's not something I'd recommend spending a lot of time on.

You might get more context about LCM is doing when the error happens by turning the "lcm" logger up to debug in opscenter's logback.xml and restarting opscenterd.

Body:
I'm attempting to use OpsCenter 6.1 to install a new cluster. OpsCenter successfully ssh's to each of the nodes in the cluster then appears to nearly immediately error out on each node with the following message:

400 Client Error: Bad Request for url: http://<opscenter>:8888/api/v1/lcm/internal/nodes/<node-id>/package_information

When attempting to reach that page myself I receive a 404 error with this message:

{"brief": "error", "message": "{\"type\":\"ApiException\",\"code\":404,\"msg\":\"Can't find object for given parameters: {:job-id nil, :node-id \\\"<node-id>\\\"}\"}", "type": "NoSuchResource"}

Note that <opscenter> (above) is the IP address of my local install, and <node-id> is the ID of the node.

Considering that I don't receive the 400 error myself I'm assuming that I'm unable to replicate the scenario that occurs during the install because of some perviously executed steps that are rolled back.

Any insight into what might be causing this issue?

Thanks in advance!


问:
How to install Clang and LLVM 3.9 on CentOS 7
I have taken rpm packages from
https://copr-be.cloud.fedoraproject.org/results/alonid/llvm-3.9.0/epel-7-x86_64/00505197-clang-3.9.0/ for Clang 3.9.

I am installing the rpm packages by the command

```<code>rpm -ivh clang-3.9.0-3.9.0-3.1.el7.centos.alonid.src.rpm
</code>```

But when I do

```<code>rpm -ivh clang-3.9.0-3.9.0-3.1.el7.centos.alonid.x86_64.rpm
</code>```

I get the following error :

```<code>error: Failed dependencies:
    clang-3.9.0-libs(x86-64) = 3.9.0-3.1.el7.centos.alonid is needed by clang-3.9.0-3.9.0-3.1.el7.centos.alonid.x86_64
    libLLVM-3.9.so()(64bit) is needed by clang-3.9.0-3.9.0-3.1.el7.centos.alonid.x86_64
    libclang.so.3.9()(64bit) is needed by clang-3.9.0-3.9.0-3.1.el7.centos.alonid.x86_64
    libclangAST.so()(64bit) is needed by clang-3.9.0-3.9.0-3.1.el7.centos.alonid.x86_64
    libclangBasic.so()(64bit) is needed by clang-3.9.0-3.9.0-3.1.el7.centos.alonid.x86_64
    libclangCodeGen.so()(64bit) is needed by clang-3.9.0-3.9.0-3.1.el7.centos.alonid.x86_64
    libclangDriver.so()(64bit) is needed by clang-3.9.0-3.9.0-3.1.el7.centos.alonid.x86_64
    libclangFormat.so()(64bit) is needed by clang-3.9.0-3.9.0-3.1.el7.centos.alonid.x86_64
    libclangFrontend.so()(64bit) is needed by clang-3.9.0-3.9.0-3.1.el7.centos.alonid.x86_64
    libclangFrontendTool.so()(64bit) is needed by clang-3.9.0-3.9.0-3.1.el7.centos.alonid.x86_64
    libclangIndex.so()(64bit) is needed by clang-3.9.0-3.9.0-3.1.el7.centos.alonid.x86_64
    libclangRewrite.so()(64bit) is needed by clang-3.9.0-3.9.0-3.1.el7.centos.alonid.x86_64
    libclangRewriteFrontend.so()(64bit) is needed by clang-3.9.0-3.9.0-3.1.el7.centos.alonid.x86_64
    libclangStaticAnalyzerFrontend.so()(64bit) is needed by clang-3.9.0-3.9.0-3.1.el7.centos.alonid.x86_64
    libclangTooling.so()(64bit) is needed by clang-3.9.0-3.9.0-3.1.el7.centos.alonid.x86_64
    libclangToolingCore.so()(64bit) is needed by clang-3.9.0-3.9.0-3.1.el7.centos.alonid.x86_64
</code>```

Where should I install all these dependencies from?

答:
Just open your link and look around, also go one level higher and find all necessary .rpm's. The following sequence worked for me:

```<code>yum install compiler-rt-3.9.0-3.9.0-3.el7.centos.alonid.x86_64.rpm
yum install clang-3.9.0-libs-3.9.0-3.1.el7.centos.alonid.x86_64.rpm
yum install clang-3.9.0-3.9.0-3.1.el7.centos.alonid.x86_64.rpm
yum install llvm-3.9.0-libs-3.9.0-7.el7.centos.alonid.x86_64.rpm
yum install llvm-3.9.0-3.9.0-7.el7.centos.alonid.x86_64.rpm
yum install llvm-3.9.0-devel-3.9.0-7.el7.centos.alonid.x86_64.rpm
</code>```

By just doing yum install without any flags Clang and LLVM will be installed to /opt/llvm-3.9.0:

```<code>$ ls -l /opt/llvm-3.9.0
total 12
drwxr-xr-x 2 root root 4096 Jun  3 23:48 bin
drwxr-xr-x 3 root root 4096 Jun  3 23:23 include
drwxr-xr-x 3 root root 4096 Jun  3 23:27 lib64
</code>```

Also notice that there are other packages like -devel, -static, -debuginfo.

Useful tip: Without installing -devel packages you only get bin and lib64 folders where only the executables like bin/clang and libraries like lib64/libLLVM-3.9.0.so are located. If you also want to develop something with LLVM/Clang you will need corresponding -devel packages. Then you will also get include/ folder with headers.

By the way, thanks to the maintainers of this repo. Nice to have LLVM 3.9 out of the box.

Body:
I have taken rpm packages from
https://copr-be.cloud.fedoraproject.org/results/alonid/llvm-3.9.0/epel-7-x86_64/00505197-clang-3.9.0/ for Clang 3.9.

I am installing the rpm packages by the command

rpm -ivh clang-3.9.0-3.9.0-3.1.el7.centos.alonid.src.rpm

But when I do

rpm -ivh clang-3.9.0-3.9.0-3.1.el7.centos.alonid.x86_64.rpm

I get the following error :

error: Failed dependencies:
    clang-3.9.0-libs(x86-64) = 3.9.0-3.1.el7.centos.alonid is needed by clang-3.9.0-3.9.0-3.1.el7.centos.alonid.x86_64
    libLLVM-3.9.so()(64bit) is needed by clang-3.9.0-3.9.0-3.1.el7.centos.alonid.x86_64
    libclang.so.3.9()(64bit) is needed by clang-3.9.0-3.9.0-3.1.el7.centos.alonid.x86_64
    libclangAST.so()(64bit) is needed by clang-3.9.0-3.9.0-3.1.el7.centos.alonid.x86_64
    libclangBasic.so()(64bit) is needed by clang-3.9.0-3.9.0-3.1.el7.centos.alonid.x86_64
    libclangCodeGen.so()(64bit) is needed by clang-3.9.0-3.9.0-3.1.el7.centos.alonid.x86_64
    libclangDriver.so()(64bit) is needed by clang-3.9.0-3.9.0-3.1.el7.centos.alonid.x86_64
    libclangFormat.so()(64bit) is needed by clang-3.9.0-3.9.0-3.1.el7.centos.alonid.x86_64
    libclangFrontend.so()(64bit) is needed by clang-3.9.0-3.9.0-3.1.el7.centos.alonid.x86_64
    libclangFrontendTool.so()(64bit) is needed by clang-3.9.0-3.9.0-3.1.el7.centos.alonid.x86_64
    libclangIndex.so()(64bit) is needed by clang-3.9.0-3.9.0-3.1.el7.centos.alonid.x86_64
    libclangRewrite.so()(64bit) is needed by clang-3.9.0-3.9.0-3.1.el7.centos.alonid.x86_64
    libclangRewriteFrontend.so()(64bit) is needed by clang-3.9.0-3.9.0-3.1.el7.centos.alonid.x86_64
    libclangStaticAnalyzerFrontend.so()(64bit) is needed by clang-3.9.0-3.9.0-3.1.el7.centos.alonid.x86_64
    libclangTooling.so()(64bit) is needed by clang-3.9.0-3.9.0-3.1.el7.centos.alonid.x86_64
    libclangToolingCore.so()(64bit) is needed by clang-3.9.0-3.9.0-3.1.el7.centos.alonid.x86_64

Where should I install all these dependencies from?

Body:
Just open your link and look around, also go one level higher and find all necessary .rpm's. The following sequence worked for me:

yum install compiler-rt-3.9.0-3.9.0-3.el7.centos.alonid.x86_64.rpm
yum install clang-3.9.0-libs-3.9.0-3.1.el7.centos.alonid.x86_64.rpm
yum install clang-3.9.0-3.9.0-3.1.el7.centos.alonid.x86_64.rpm
yum install llvm-3.9.0-libs-3.9.0-7.el7.centos.alonid.x86_64.rpm
yum install llvm-3.9.0-3.9.0-7.el7.centos.alonid.x86_64.rpm
yum install llvm-3.9.0-devel-3.9.0-7.el7.centos.alonid.x86_64.rpm

By just doing yum install without any flags Clang and LLVM will be installed to /opt/llvm-3.9.0:

$ ls -l /opt/llvm-3.9.0
total 12
drwxr-xr-x 2 root root 4096 Jun  3 23:48 bin
drwxr-xr-x 3 root root 4096 Jun  3 23:23 include
drwxr-xr-x 3 root root 4096 Jun  3 23:27 lib64

Also notice that there are other packages like -devel, -static, -debuginfo.

Useful tip: Without installing -devel packages you only get bin and lib64 folders where only the executables like bin/clang and libraries like lib64/libLLVM-3.9.0.so are located. If you also want to develop something with LLVM/Clang you will need corresponding -devel packages. Then you will also get include/ folder with headers.

By the way, thanks to the maintainers of this repo. Nice to have LLVM 3.9 out of the box.


问:
How to make CORS Request
I'm making a weather app with React.js and I want to make a CORS request for fetching data from weather underground website.
What I want is getting a city name, use autocomplete API for finding the city and fetch data for that city.

The problem is, everytime I give a city name (for example: tehran), the xhr.onerror event handler runs and I get this error:

XMLHttpRequest cannot load http://autocomplete.wunderground.com/aq?query=tehran. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.

This is my code for fetching data:

```<code>var axios = require('axios');

function createCORSRequest(method, url) {
    var xhr = new XMLHttpRequest();
    if ("withCredentials" in xhr) {
        xhr.open(method, url, true);
    }
    else if (typeof XDomainRequest != "undefined") {
        xhr = new XDomainRequest();
        xhr.open(method, url);
    }
    else {
        xhr = null;
    }
    return xhr;
}

function makeCorsRequest(url) {
    var autoCompleteText;
    var xhr = createCORSRequest('GET', url);
    if (!xhr) {
        alert('CORS not supported');
        return;
    }

    xhr.onload = function() {
        var text = xhr.responseText;
        autoCompleteText = text;
    }
    xhr.onerror = function() {
        alert('Woops, there was an error making the request.');
    }
    xhr.send();
    return autoCompleteText;
}

const WEATHER_UNDERGROUND_AUTOCOMPLETE = 'http://autocomplete.wunderground.com/aq?query=';
const WEATHER_UNDERGROUND_URL = 'http://api.wunderground.com/api/eda52d06d32d71e9/conditions/q/';

module.exports = {
    getTemp: function(city) {
        var encodedCity = encodeURIComponent(city);
        var requestAutoComplete = `${WEATHER_UNDERGROUND_AUTOCOMPLETE}${encodedCity}`;

        var autoCompleteText = makeCorsRequest(requestAutoComplete);
        var foundCity = autoCompleteText.RESULTS[0].name.split(', ');
        var requestUrl = `${WEATHER_UNDERGROUND_URL}${foundCity[1]}/${foundcity[0]}.json`;
        return axios.get(requestUrl).then(function(res) {
            return res.data.current_observation.temp_c;
        }, function(err) {
            throw new Error(res.data.error);
        });
    }
}
</code>```

Screenshot of the app:
localhost:3000/weather page

答:
Because http://autocomplete.wunderground.com/aq?query=tehran doesn’t send the Access-Control-Allow-Origin response header, you must change your frontend code to instead make the request through proxy. Do that by changing the WEATHER_UNDERGROUND_AUTOCOMPLETE value:

```<code>const WEATHER_UNDERGROUND_AUTOCOMPLETE =
  'https://cors-anywhere.herokuapp.com/http://autocomplete.wunderground.com/aq?query=';
</code>```

The https://cors-anywhere.herokuapp.com/http://autocomplete.wunderground.com/… URL will cause the request to go to https://cors-anywhere.herokuapp.com, a public CORS proxy which sends the request on to the http://autocomplete.wunderground.com… URL you want.

That proxy gets the response, takes it and adds the Access-Control-Allow-Origin response header to it, and then finally passes that back to your requesting frontend code as the response.

So in the end because the browser sees a response with the Access-Control-Allow-Origin response header, the browser allows your frontend JavaScript code to access the response.

Or use the code from https://github.com/Rob--W/cors-anywhere/ or such to set up your own proxy.

You need a proxy in this case because http://autocomplete.wunderground.com/… itself doesn’t send the Access-Control-Allow-Origin response header—and in that case your browser will not allow your frontend JavaScript code to access a response from that server cross-origin.

https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS has more details.

Incidentally, you can use curl or some other tool to verify that server isn’t sending the header:

$ curl -i -H 'Origin: http://localhost:3000' \
    'http://autocomplete.wunderground.com/aq?query=tehran'

HTTP/1.1 200 OK
Content-type: application/json; charset=utf-8
Content-Length: 2232
Connection: keep-alive

{ "RESULTS": [
    {
        "name": "Tehran Dasht, Iran",
        …
```

Notice there’s no Access-Control-Allow-Origin in the response headers there.

Title: How to make CORS Request

Body:
I'm making a weather app with React.js and I want to make a CORS request for fetching data from weather underground website.
What I want is getting a city name, use autocomplete API for finding the city and fetch data for that city.

The problem is, everytime I give a city name (for example: tehran), the xhr.onerror event handler runs and I get this error:

XMLHttpRequest cannot load http://autocomplete.wunderground.com/aq?query=tehran. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.

This is my code for fetching data:

var axios = require('axios');

function createCORSRequest(method, url) {
    var xhr = new XMLHttpRequest();
    if ("withCredentials" in xhr) {
        xhr.open(method, url, true);
    }
    else if (typeof XDomainRequest != "undefined") {
        xhr = new XDomainRequest();
        xhr.open(method, url);
    }
    else {
        xhr = null;
    }
    return xhr;
}

function makeCorsRequest(url) {
    var autoCompleteText;
    var xhr = createCORSRequest('GET', url);
    if (!xhr) {
        alert('CORS not supported');
        return;
    }

    xhr.onload = function() {
        var text = xhr.responseText;
        autoCompleteText = text;
    }
    xhr.onerror = function() {
        alert('Woops, there was an error making the request.');
    }
    xhr.send();
    return autoCompleteText;
}

const WEATHER_UNDERGROUND_AUTOCOMPLETE = 'http://autocomplete.wunderground.com/aq?query=';
const WEATHER_UNDERGROUND_URL = 'http://api.wunderground.com/api/eda52d06d32d71e9/conditions/q/';

module.exports = {
    getTemp: function(city) {
        var encodedCity = encodeURIComponent(city);
        var requestAutoComplete = `${WEATHER_UNDERGROUND_AUTOCOMPLETE}${encodedCity}`;

        var autoCompleteText = makeCorsRequest(requestAutoComplete);
        var foundCity = autoCompleteText.RESULTS[0].name.split(', ');
        var requestUrl = `${WEATHER_UNDERGROUND_URL}${foundCity[1]}/${foundcity[0]}.json`;
        return axios.get(requestUrl).then(function(res) {
            return res.data.current_observation.temp_c;
        }, function(err) {
            throw new Error(res.data.error);
        });
    }
}

Screenshot of the app:
localhost:3000/weather page

Body:
Because http://autocomplete.wunderground.com/aq?query=tehran doesn’t send the Access-Control-Allow-Origin response header, you must change your frontend code to instead make the request through proxy. Do that by changing the WEATHER_UNDERGROUND_AUTOCOMPLETE value:

const WEATHER_UNDERGROUND_AUTOCOMPLETE =
  'https://cors-anywhere.herokuapp.com/http://autocomplete.wunderground.com/aq?query=';

The https://cors-anywhere.herokuapp.com/http://autocomplete.wunderground.com/… URL will cause the request to go to https://cors-anywhere.herokuapp.com, a public CORS proxy which sends the request on to the http://autocomplete.wunderground.com… URL you want.

That proxy gets the response, takes it and adds the Access-Control-Allow-Origin response header to it, and then finally passes that back to your requesting frontend code as the response.

So in the end because the browser sees a response with the Access-Control-Allow-Origin response header, the browser allows your frontend JavaScript code to access the response.

Or use the code from https://github.com/Rob--W/cors-anywhere/ or such to set up your own proxy.

You need a proxy in this case because http://autocomplete.wunderground.com/… itself doesn’t send the Access-Control-Allow-Origin response header—and in that case your browser will not allow your frontend JavaScript code to access a response from that server cross-origin.

https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS has more details.

Incidentally, you can use curl or some other tool to verify that server isn’t sending the header:

$ curl -i -H 'Origin: http://localhost:3000' \
    'http://autocomplete.wunderground.com/aq?query=tehran'

HTTP/1.1 200 OK
Content-type: application/json; charset=utf-8
Content-Length: 2232
Connection: keep-alive

{ "RESULTS": [
    {
        "name": "Tehran Dasht, Iran",
        …

Notice there’s no Access-Control-Allow-Origin in the response headers there.


问:
Ho to write Select query for EAV - Entity Attribute Value model
I have following schema. In which

Types represent DB Table

TypeProperty represents Column of Table

TypeRow represent Row of table

I want to write a select query to which I will pass single Type and it should give me all its TypeProperty, TypeRow and TypeValue that are associated with these Properties and Rows.

I will be showing this data in a web application in which user will select a Type from dropdown and application will get Properties, Rows and associated values and will show them as a complete grid.

I am using SQL Server 2014.

Can anyone help me please?

答:
A simple join will work.. Are you looking this?

```<code>Select * --your required columns
   from Types t
   inner join TypesProperty tp
       on t.TypesId = tp.TypesId
   inner join TypeRow tr
       on t.TypesId = tr.TypesId
   Left join TypeValue tv
       on tp.TypesPropertyId = tv.TypesPrpertyId
</code>```

--You need to join using typeRowid with typeValue if your require value details

Body:
A simple join will work.. Are you looking this?

Select * --your required columns
   from Types t
   inner join TypesProperty tp
       on t.TypesId = tp.TypesId
   inner join TypeRow tr
       on t.TypesId = tr.TypesId
   Left join TypeValue tv
       on tp.TypesPropertyId = tv.TypesPrpertyId

--You need to join using typeRowid with typeValue if your require value details


问:
react-native-maps region not updating - map stuck on one region
I have a <MapView> and the region never updates when I scroll the map. The map is essentially stuck on one region. When I scroll it seems to pass the exact same region to this.props.onRegionChange which prevents the map from scrolling. How do I make it pass in a scrolled to region?

```<code><MapView
          style={styles.map}
          region={this.props.region}
          onRegionChange={this.props.onRegionChange}
        >
          {
            this.props.markers.map(marker => {
              return (
                <MapView.Marker
                  coordinate={{ latitude: marker.latitude, longitude: marker.longitude }}
                  title={marker.name}
                />
              )
            })}
        </MapView>
</code>```

full code:

Map.js

```<code>import { StyleSheet } from 'react-native'
import React, { Component } from 'react'
import MapView from 'react-native-maps'
import { connect } from 'react-redux'
import {
  Button,
  Container
} from 'native-base'

import selectMarkers from './markers.selector'

import { updateRegion } from './map.action'
import Icon from 'react-native-vector-icons/FontAwesome'
import { toggleMenu } from '../search-page/searchPage.action'
import mapStyle from './style'

const mapStateToProps = (state) => ({
  region: state.get('map').get('region'),
  markers: selectMarkers(state)
})

const mapDispatchToProps = (dispatch) => ({
  onRegionChange: (region) => {
    dispatch(updateRegion(region))
  },
  onToggleMenuClick: () => {
    dispatch(toggleMenu())
  }
})

class Map extends Component {

  componentDidMount() {
    const { store } = this.context
    this.unsubscribe = store.subscribe(() => { })
  }

  componentWillUnmount() {
    this.unsubscribe()
  }

  render() {
  console.log('map')
  console.log('markers', this.props.markers)
    return (
      <Container>
        <MapView
          style={styles.map}
          region={this.props.region}
          onRegionChange={this.props.onRegionChange}
        >
          {
            this.props.markers.map(marker => {
              return (
                <MapView.Marker
                  coordinate={{ latitude: marker.latitude, longitude: marker.longitude }}
                  title={marker.name}
                />
              )
            })}
        </MapView>
        <Button
          small
          icon
          style={mapStyle.toggleMenuButton}
          onPress={() => this.props.onToggleMenuClick()}>
          <Icon name="sliders" size={20} color="#FFFFFF" />
        </Button>
      </Container>
    )
  }
}

Map.contextTypes = {
  store: React.PropTypes.object
}

Map.propTypes = {
  region: React.PropTypes.shape({
    latitude: React.PropTypes.number,
    longitude: React.PropTypes.number,
    latitudeDelta: React.PropTypes.number,
    longitudeDelta: React.PropTypes.number
  }).isRequired,
  onRegionChange: React.PropTypes.func.isRequired,
  onToggleMenuClick: React.PropTypes.func.isRequired,
  markers: React.PropTypes.array
}

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(Map)

const styles = StyleSheet.create({
  map: {
    ...StyleSheet.absoluteFillObject,
    zIndex: -1
  }
})
</code>```

map.reducer

```<code>// @flow
import initialState from '../../config/config'
import { UPDATE_REGION } from './map.action'

const map = (
  initialMapState: [] = initialState.get('map'),
  action: Object): string => {
  switch (action.type) {
    case UPDATE_REGION: {
      if (action.payload) {
        return initialMapState.set('region', {
          latitudeDelta: 0.0922,
          longitudeDelta: 0.0421,
          latitude: action.payload.region.latitude,
          longitude: action.payload.region.longitude
        })
      } else {
        return initialMapState
      }
    }
    default:
      return initialMapState
  }
}

export default map
</code>```

答:
Use onRegionChangeComplete

```<code><MapView
  style={styles.map}
  region={this.props.region}
  onRegionChangeComplete={this.props.onRegionChange}>
</code>```

The examples in the docs use onRegionChange. So maybe onRegionChange works for most. Maybe it works without redux. Anyway easy fix is onRegionChangeComplete if getting the same issue.

Body:
I have a <MapView> and the region never updates when I scroll the map. The map is essentially stuck on one region. When I scroll it seems to pass the exact same region to this.props.onRegionChange which prevents the map from scrolling. How do I make it pass in a scrolled to region?

<MapView
          style={styles.map}
          region={this.props.region}
          onRegionChange={this.props.onRegionChange}
        >
          {
            this.props.markers.map(marker => {
              return (
                <MapView.Marker
                  coordinate={{ latitude: marker.latitude, longitude: marker.longitude }}
                  title={marker.name}
                />
              )
            })}
        </MapView>

full code:

Map.js

import { StyleSheet } from 'react-native'
import React, { Component } from 'react'
import MapView from 'react-native-maps'
import { connect } from 'react-redux'
import {
  Button,
  Container
} from 'native-base'

import selectMarkers from './markers.selector'

import { updateRegion } from './map.action'
import Icon from 'react-native-vector-icons/FontAwesome'
import { toggleMenu } from '../search-page/searchPage.action'
import mapStyle from './style'

const mapStateToProps = (state) => ({
  region: state.get('map').get('region'),
  markers: selectMarkers(state)
})

const mapDispatchToProps = (dispatch) => ({
  onRegionChange: (region) => {
    dispatch(updateRegion(region))
  },
  onToggleMenuClick: () => {
    dispatch(toggleMenu())
  }
})

class Map extends Component {

  componentDidMount() {
    const { store } = this.context
    this.unsubscribe = store.subscribe(() => { })
  }

  componentWillUnmount() {
    this.unsubscribe()
  }

  render() {
  console.log('map')
  console.log('markers', this.props.markers)
    return (
      <Container>
        <MapView
          style={styles.map}
          region={this.props.region}
          onRegionChange={this.props.onRegionChange}
        >
          {
            this.props.markers.map(marker => {
              return (
                <MapView.Marker
                  coordinate={{ latitude: marker.latitude, longitude: marker.longitude }}
                  title={marker.name}
                />
              )
            })}
        </MapView>
        <Button
          small
          icon
          style={mapStyle.toggleMenuButton}
          onPress={() => this.props.onToggleMenuClick()}>
          <Icon name="sliders" size={20} color="#FFFFFF" />
        </Button>
      </Container>
    )
  }
}

Map.contextTypes = {
  store: React.PropTypes.object
}

Map.propTypes = {
  region: React.PropTypes.shape({
    latitude: React.PropTypes.number,
    longitude: React.PropTypes.number,
    latitudeDelta: React.PropTypes.number,
    longitudeDelta: React.PropTypes.number
  }).isRequired,
  onRegionChange: React.PropTypes.func.isRequired,
  onToggleMenuClick: React.PropTypes.func.isRequired,
  markers: React.PropTypes.array
}

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(Map)

const styles = StyleSheet.create({
  map: {
    ...StyleSheet.absoluteFillObject,
    zIndex: -1
  }
})

map.reducer

// @flow
import initialState from '../../config/config'
import { UPDATE_REGION } from './map.action'

const map = (
  initialMapState: [] = initialState.get('map'),
  action: Object): string => {
  switch (action.type) {
    case UPDATE_REGION: {
      if (action.payload) {
        return initialMapState.set('region', {
          latitudeDelta: 0.0922,
          longitudeDelta: 0.0421,
          latitude: action.payload.region.latitude,
          longitude: action.payload.region.longitude
        })
      } else {
        return initialMapState
      }
    }
    default:
      return initialMapState
  }
}

export default map

Body:
Use onRegionChangeComplete

<MapView
  style={styles.map}
  region={this.props.region}
  onRegionChangeComplete={this.props.onRegionChange}>

The examples in the docs use onRegionChange. So maybe onRegionChange works for most. Maybe it works without redux. Anyway easy fix is onRegionChangeComplete if getting the same issue.


答:
```<code>$('.nav li a').click(function() {
    $('.nav li a.active').removeClass("active");
    $(this).addClass("active");
});
</code>```

Title: Is there a better way to write this navigation statement?


问:
Will Multi threading increase the speed of the calculation on Single Processor
On a single processor, Will multi-threading increse the speed of the calculation. As we all know that, multi-threading is used for Increasing the User responsiveness and achieved by sepating UI thread and calculation thread. But lets talk about only console application. Will multi-threading increases the speed of the calculation. Do we get culculation result faster when we calculate through multi-threading.

what about on multi cores, will multi threading increse the speed or not.

Please help me. If you have any material to learn more about threading. please post.

Edit:
I have been asked a question, At any given time, only one thread is allowed to run on a single core. If so, why people use multithreading in a console application.

Thanks in advance,
Harsha

答:
For single core CPU,
Actually the performance depends on the job you are referring.
In your case, for calculation done by CPU, in that case OverClocking would help if your parentBoard supports it. Otherwise there is no way for CPU to do calculations that are faster than the speed of CPU.

For the sake of Multicore CPU
As the above answers say, if properly designed the performance may increase, if all cores are fully used.

In single core CPU, if the threads are implemented in User Level then multithreading wont matter if there are blocking system calls in the thread, like an I/O operation. Because kernel won't know about the userlevel threads.

So if the process does I/O then you can implement the threads in Kernel space and then you can implement different threads for different job.
(The answer here is on theory based.)


问:
Only allow one instance of main activity
I have a single activity wear application with singleInstance set as launchMode.
When I swipe right or put the palm over the watch, the application goes to the background (pause/stop), then when I tap on its icon it opens again (resume) but it shows a new main activity and not the original one.
I would like the app to only have 1 main activity.

I did unsuccessfully try other values for the launchMode and I also unsuccessfully tried to set flags.

I do not post the code since it is just simple wear app with a TextView and a Button on the main activity. When the button is pressed a counter increases and updates the text. When the app resumes the counter shows zero as if the button was never pressed.

答:
You lose your data since the old activity gets destroyed when going to the background and gets restored when coming back. This is the normal behavior.
When you want to keep your data, you need to save and restore it e.g. save in onSaveInstanceState() and restore it in onCreate().


问:
Implementing INotifyPropertyChanged - does a better way exist?
Microsoft should have implemented something snappy for INotifyPropertyChanged, like in the automatic properties, just specify {get; set; notify;}
I think it makes a lot of sense to do it. Or are there any complications to do it?

Can we ourselves implement something like 'notify' in our properties. Is there a graceful solution for implementing INotifyPropertyChanged in your class or the only way to do it is by raising the PropertyChanged event in each property.

If not can we write something to auto-generate the piece of code to raise PropertyChanged  event?

答:
I came up with this base class to implement the observable pattern, pretty much does what you need ("automatically" implementing the set and get). I spent line an hour on this as prototype, so it doesn't have many unit tests, but proves the concept. Note it uses the Dictionary<string, ObservablePropertyContext> to remove the need for private fields.

```<code>  public class ObservableByTracking<T> : IObservable<T>
  {
    private readonly Dictionary<string, ObservablePropertyContext> _expando;
    private bool _isDirty;

    public ObservableByTracking()
    {
      _expando = new Dictionary<string, ObservablePropertyContext>();

      var properties = this.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance).ToList();
      foreach (var property in properties)
      {
        var valueContext = new ObservablePropertyContext(property.Name, property.PropertyType)
        {
          Value = GetDefault(property.PropertyType)
        };

        _expando[BuildKey(valueContext)] = valueContext;
      }
    }

    protected void SetValue<T>(Expression<Func<T>> expression, T value)
    {
      var keyContext = GetKeyContext(expression);
      var key = BuildKey(keyContext.PropertyName, keyContext.PropertyType);

      if (!_expando.ContainsKey(key))
      {
        throw new Exception($"Object doesn't contain {keyContext.PropertyName} property.");
      }

      var originalValue = (T)_expando[key].Value;
      if (EqualityComparer<T>.Default.Equals(originalValue, value))
      {
        return;
      }

      _expando[key].Value = value;
      _isDirty = true;
    }

    protected T GetValue<T>(Expression<Func<T>> expression)
    {
      var keyContext = GetKeyContext(expression);
      var key = BuildKey(keyContext.PropertyName, keyContext.PropertyType);

      if (!_expando.ContainsKey(key))
      {
        throw new Exception($"Object doesn't contain {keyContext.PropertyName} property.");
      }

      var value = _expando[key].Value;
      return (T)value;
    }

    private KeyContext GetKeyContext<T>(Expression<Func<T>> expression)
    {
      var castedExpression = expression.Body as MemberExpression;
      if (castedExpression == null)
      {
        throw new Exception($"Invalid expression.");
      }

      var parameterName = castedExpression.Member.Name;

      var propertyInfo = castedExpression.Member as PropertyInfo;
      if (propertyInfo == null)
      {
        throw new Exception($"Invalid expression.");
      }

      return new KeyContext {PropertyType = propertyInfo.PropertyType, PropertyName = parameterName};
    }

    private static string BuildKey(ObservablePropertyContext observablePropertyContext)
    {
      return $"{observablePropertyContext.Type.Name}.{observablePropertyContext.Name}";
    }

    private static string BuildKey(string parameterName, Type type)
    {
      return $"{type.Name}.{parameterName}";
    }

    private static object GetDefault(Type type)
    {
      if (type.IsValueType)
      {
        return Activator.CreateInstance(type);
      }
      return null;
    }

    public bool IsDirty()
    {
      return _isDirty;
    }

    public void SetPristine()
    {
      _isDirty = false;
    }

    private class KeyContext
    {
      public string PropertyName { get; set; }
      public Type PropertyType { get; set; }
    }
  }

  public interface IObservable<T>
  {
    bool IsDirty();
    void SetPristine();
  }
</code>```

Here's the usage

```<code>public class ObservableByTrackingTestClass : ObservableByTracking<ObservableByTrackingTestClass>
  {
    public ObservableByTrackingTestClass()
    {
      StringList = new List<string>();
      StringIList = new List<string>();
      NestedCollection = new List<ObservableByTrackingTestClass>();
    }

    public IEnumerable<string> StringList
    {
      get { return GetValue(() => StringList); }
      set { SetValue(() => StringIList, value); }
    }

    public IList<string> StringIList
    {
      get { return GetValue(() => StringIList); }
      set { SetValue(() => StringIList, value); }
    }

    public int IntProperty
    {
      get { return GetValue(() => IntProperty); }
      set { SetValue(() => IntProperty, value); }
    }

    public ObservableByTrackingTestClass NestedChild
    {
      get { return GetValue(() => NestedChild); }
      set { SetValue(() => NestedChild, value); }
    }

    public IList<ObservableByTrackingTestClass> NestedCollection
    {
      get { return GetValue(() => NestedCollection); }
      set { SetValue(() => NestedCollection, value); }
    }

    public string StringProperty
    {
      get { return GetValue(() => StringProperty); }
      set { SetValue(() => StringProperty, value); }
    }
  }
</code>```

Body:
I came up with this base class to implement the observable pattern, pretty much does what you need ("automatically" implementing the set and get). I spent line an hour on this as prototype, so it doesn't have many unit tests, but proves the concept. Note it uses the Dictionary<string, ObservablePropertyContext> to remove the need for private fields.

  public class ObservableByTracking<T> : IObservable<T>
  {
    private readonly Dictionary<string, ObservablePropertyContext> _expando;
    private bool _isDirty;

    public ObservableByTracking()
    {
      _expando = new Dictionary<string, ObservablePropertyContext>();

      var properties = this.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance).ToList();
      foreach (var property in properties)
      {
        var valueContext = new ObservablePropertyContext(property.Name, property.PropertyType)
        {
          Value = GetDefault(property.PropertyType)
        };

        _expando[BuildKey(valueContext)] = valueContext;
      }
    }

    protected void SetValue<T>(Expression<Func<T>> expression, T value)
    {
      var keyContext = GetKeyContext(expression);
      var key = BuildKey(keyContext.PropertyName, keyContext.PropertyType);

      if (!_expando.ContainsKey(key))
      {
        throw new Exception($"Object doesn't contain {keyContext.PropertyName} property.");
      }

      var originalValue = (T)_expando[key].Value;
      if (EqualityComparer<T>.Default.Equals(originalValue, value))
      {
        return;
      }

      _expando[key].Value = value;
      _isDirty = true;
    }

    protected T GetValue<T>(Expression<Func<T>> expression)
    {
      var keyContext = GetKeyContext(expression);
      var key = BuildKey(keyContext.PropertyName, keyContext.PropertyType);

      if (!_expando.ContainsKey(key))
      {
        throw new Exception($"Object doesn't contain {keyContext.PropertyName} property.");
      }

      var value = _expando[key].Value;
      return (T)value;
    }

    private KeyContext GetKeyContext<T>(Expression<Func<T>> expression)
    {
      var castedExpression = expression.Body as MemberExpression;
      if (castedExpression == null)
      {
        throw new Exception($"Invalid expression.");
      }

      var parameterName = castedExpression.Member.Name;

      var propertyInfo = castedExpression.Member as PropertyInfo;
      if (propertyInfo == null)
      {
        throw new Exception($"Invalid expression.");
      }

      return new KeyContext {PropertyType = propertyInfo.PropertyType, PropertyName = parameterName};
    }

    private static string BuildKey(ObservablePropertyContext observablePropertyContext)
    {
      return $"{observablePropertyContext.Type.Name}.{observablePropertyContext.Name}";
    }

    private static string BuildKey(string parameterName, Type type)
    {
      return $"{type.Name}.{parameterName}";
    }

    private static object GetDefault(Type type)
    {
      if (type.IsValueType)
      {
        return Activator.CreateInstance(type);
      }
      return null;
    }

    public bool IsDirty()
    {
      return _isDirty;
    }

    public void SetPristine()
    {
      _isDirty = false;
    }

    private class KeyContext
    {
      public string PropertyName { get; set; }
      public Type PropertyType { get; set; }
    }
  }

  public interface IObservable<T>
  {
    bool IsDirty();
    void SetPristine();
  }

Here's the usage

public class ObservableByTrackingTestClass : ObservableByTracking<ObservableByTrackingTestClass>
  {
    public ObservableByTrackingTestClass()
    {
      StringList = new List<string>();
      StringIList = new List<string>();
      NestedCollection = new List<ObservableByTrackingTestClass>();
    }

    public IEnumerable<string> StringList
    {
      get { return GetValue(() => StringList); }
      set { SetValue(() => StringIList, value); }
    }

    public IList<string> StringIList
    {
      get { return GetValue(() => StringIList); }
      set { SetValue(() => StringIList, value); }
    }

    public int IntProperty
    {
      get { return GetValue(() => IntProperty); }
      set { SetValue(() => IntProperty, value); }
    }

    public ObservableByTrackingTestClass NestedChild
    {
      get { return GetValue(() => NestedChild); }
      set { SetValue(() => NestedChild, value); }
    }

    public IList<ObservableByTrackingTestClass> NestedCollection
    {
      get { return GetValue(() => NestedCollection); }
      set { SetValue(() => NestedCollection, value); }
    }

    public string StringProperty
    {
      get { return GetValue(() => StringProperty); }
      set { SetValue(() => StringProperty, value); }
    }
  }


问:
How to detect user's timezone?
I need to know what time zone is currently my users are in based on their IP or http header.

I  got many answer regarding this issue, but i could not understood those answer. Some said use -new Date().getTimezoneOffset()/60 (from here). But what does it mean?

I have a date_default_timezone_set("Asia/Calcutta"); in the root of my (index.php) page. So for this I have to  get the timezone dynamically and set it  in place of Asia/Calcutta.

答:
Timezone is not available in the HTTP header, but country (abbreviation) is in the ACCEPT_LANGUAGE header. It'll be something like "en-US" (US is the country code). This can be combined with the JavaScript information to get a good idea of the user's timezone.

This is what I'm using in JS:

```<code>function timezone() {
  var now = new Date();
  var jano = new Date(now.getFullYear(), 0, 1).getTimezoneOffset()/-60;
  var julo = new Date(now.getFullYear(), 6, 1).getTimezoneOffset()/-60;
  var tz = Math.min(jano, julo);
  if (jano != julo) tz += ((jano < julo) ? 'S' : 'W') + Math.abs(jano - julo);
  return tz;
}
</code>```

This returns a string like "-6S1" for the central zone (standard time offset of -6 hours, DST active in the summer and adds 1 hour). I use a cookie to make this available to PHP. PHP searches the TZ database for zones that match this, and the country. For here (US, -6S1) there are 7 matching zones, the first is "America/Chicago".

BTW, there are 2 zones in the database where DST adds something other than 1 hour: Lord Howe Island (10.5W0.5) and Troll Station, Antarctica (0W2).

Title: How to detect user's timezone?

Body:
Timezone is not available in the HTTP header, but country (abbreviation) is in the ACCEPT_LANGUAGE header. It'll be something like "en-US" (US is the country code). This can be combined with the JavaScript information to get a good idea of the user's timezone.

This is what I'm using in JS:

function timezone() {
  var now = new Date();
  var jano = new Date(now.getFullYear(), 0, 1).getTimezoneOffset()/-60;
  var julo = new Date(now.getFullYear(), 6, 1).getTimezoneOffset()/-60;
  var tz = Math.min(jano, julo);
  if (jano != julo) tz += ((jano < julo) ? 'S' : 'W') + Math.abs(jano - julo);
  return tz;
}

This returns a string like "-6S1" for the central zone (standard time offset of -6 hours, DST active in the summer and adds 1 hour). I use a cookie to make this available to PHP. PHP searches the TZ database for zones that match this, and the country. For here (US, -6S1) there are 7 matching zones, the first is "America/Chicago".

BTW, there are 2 zones in the database where DST adds something other than 1 hour: Lord Howe Island (10.5W0.5) and Troll Station, Antarctica (0W2).


问:
How to access data in firebase from react-native?
I am having trouble rendering data from firebase.

Here is my current data structure on firebase:
{name: "sleep"}
ie. that's the only object the database contains atm.
Using a ListView, it renders a row (shows the background and border of the row according to the number of items in the database), however, there is no text inside the row..

ListView code:

```<code>             <ListView
              enableEmptySections={true}
              dataSource={this.state.dataSource}
              renderRow={this._renderItem.bind(this)}
               />

  _renderItem(task) {
    return (
    <ListItem task={task} />
    );
  }
</code>```

Code for ListItem:

```<code>class ListItem extends Component {
  render() {
    return (
      <View style={styles.listItem}>
        <Text style={styles.listItemTitle}>{this.props.task.name}</Text>
      </View>
    );
  }
}
</code>```

Code used to listen to tasks

```<code>listenForTasks(tasksRef) {
  tasksRef.on('value', (dataSnapshot) => {
    var tasks = [];

    dataSnapshot.forEach((child) => {
      tasks.push({
        name: child.val().name,
        _key: child.key
      });

console.log(dataSnapshot.val()); // returns JSON object of {name: 'sleep'}
console.log(tasks); // returns an array containing the object of {name: 'sleep'}
console.log(dataSnapshot.val().name); // returns 'sleep'

    });

    this.setState({
      dataSource: this.state.dataSource.cloneWithRows(tasks)
    });
  });
}
</code>```

答:
You need to setup a constructor for your ListItem Component:</p>

```<code>class ListItem extends Component {

//Add this....
constructor(props){
   super(props)
}
//--------------

  render() {
     return ( <View style={styles.listItem}>
        <Text style={styles.listItemTitle>
        {this.props.task.name}
        </Text>
      </View> );
  }
}
</code>```

Body:
I am having trouble rendering data from firebase.

Here is my current data structure on firebase:
{name: "sleep"}
ie. that's the only object the database contains atm.
Using a ListView, it renders a row (shows the background and border of the row according to the number of items in the database), however, there is no text inside the row..

ListView code:

             <ListView
              enableEmptySections={true}
              dataSource={this.state.dataSource}
              renderRow={this._renderItem.bind(this)}
               />

  _renderItem(task) {
    return (
    <ListItem task={task} />
    );
  }

Code for ListItem:

class ListItem extends Component {
  render() {
    return (
      <View style={styles.listItem}>
        <Text style={styles.listItemTitle}>{this.props.task.name}</Text>
      </View>
    );
  }
}

Code used to listen to tasks

listenForTasks(tasksRef) {
  tasksRef.on('value', (dataSnapshot) => {
    var tasks = [];

    dataSnapshot.forEach((child) => {
      tasks.push({
        name: child.val().name,
        _key: child.key
      });

console.log(dataSnapshot.val()); // returns JSON object of {name: 'sleep'}
console.log(tasks); // returns an array containing the object of {name: 'sleep'}
console.log(dataSnapshot.val().name); // returns 'sleep'

    });

    this.setState({
      dataSource: this.state.dataSource.cloneWithRows(tasks)
    });
  });
}

Body:
You need to setup a constructor for your ListItem Component:

class ListItem extends Component {

//Add this....
constructor(props){
   super(props)
}
//--------------

  render() {
     return ( <View style={styles.listItem}>
        <Text style={styles.listItemTitle>
        {this.props.task.name}
        </Text>
      </View> );
  }
}


问:
Why variables start out with random values in C
I think this is wrong, it should start as NULL and not with a random value. In the case that you have a pointer with a random memory address as its default value it could be a very dangerous thing, no?</p>

答:
The variables start out uninitialized because that's the fastest way - why waste the CPU cycles on initialization if you're going to write another value there anyway?

If you want a variable to be initialized after creation, just initialize it. :)

About it being a dangerous thing: Every good compiler will warn you if you try to use a variable without initialization.


问:
load the names of variables for estimations form a matrix which contains empty entys
I want to load the names of variables used for estimations form a matrix. This works quite well if all rows of the matrix contain variable names. However, I want to test all different combinations like shown in the code below. Here some rows only contain "". If one row does not contain a variable name I got an error.
Is there a method to load names from a matrix which contains empty entry’s?</p>

```<code>library("vars") # required for VAR analysis

Data <- data.table(
  A=c(1:100),
  B=c(2:102),
  C=c(3:103)
  )

VARIABLES.Matrix <- rbind(
c("A","B","C"),
c("A","B",""),
c("A","",""),
c("A","","C"),
c("","","C"),
c("","B","C")
)

for (i in 1:nrow(VARIABLES.Matrix)){
  VARselect(Data[, as.matrix(VARIABLES.Matrix)[i,1:3], with=F], lag.max = 3)
}

# This works fine
VARselect(Data[, as.matrix(VARIABLES.Matrix)[1,1:3], with=F], lag.max = 3)

# This does not work, which is related to ""
VARselect(Data[, as.matrix(VARIABLES.Matrix)[3,1:3], with=F], lag.max = 3)
</code>```

答:
My problem is: why do you need to stick to loading variables from matrix, why do you not load variables from a list, whose elements are just the names of variables you want to use? Like this:

```<code>library("data.table")
library("vars") # required for VAR analysis

Data <- data.table(
    A=c(1:101),
    B=c(2:102),
    C=c(3:103)
)

VARIABLES.List <- list(
    c("A","B","C"),
    c("A","B"),
    c("A"),
    c("A","C"),
    c("C"),
    c("B","C")
)

for (VARS in VARIABLES.List){
    VARselect(Data[, VARS], lag.max = 3)
}
</code>```

I think the VARIABLES.List is more concise and elegant to use. And you may also replace the for-loop with lapply.

```<code>lapply(VARIABLES.List, function(VARS) VARselect(Data[, VARS], lag.max = 3))
</code>```

Body:
I want to load the names of variables used for estimations form a matrix. This works quite well if all rows of the matrix contain variable names. However, I want to test all different combinations like shown in the code below. Here some rows only contain "". If one row does not contain a variable name I got an error.
Is there a method to load names from a matrix which contains empty entry’s?

library("vars") # required for VAR analysis

Data <- data.table(
  A=c(1:100),
  B=c(2:102),
  C=c(3:103)
  )

VARIABLES.Matrix <- rbind(
c("A","B","C"),
c("A","B",""),
c("A","",""),
c("A","","C"),
c("","","C"),
c("","B","C")
)

for (i in 1:nrow(VARIABLES.Matrix)){
  VARselect(Data[, as.matrix(VARIABLES.Matrix)[i,1:3], with=F], lag.max = 3)
}

# This works fine
VARselect(Data[, as.matrix(VARIABLES.Matrix)[1,1:3], with=F], lag.max = 3)

# This does not work, which is related to ""
VARselect(Data[, as.matrix(VARIABLES.Matrix)[3,1:3], with=F], lag.max = 3)

Body:
My problem is: why do you need to stick to loading variables from matrix, why do you not load variables from a list, whose elements are just the names of variables you want to use? Like this:

library("data.table")
library("vars") # required for VAR analysis

Data <- data.table(
    A=c(1:101),
    B=c(2:102),
    C=c(3:103)
)

VARIABLES.List <- list(
    c("A","B","C"),
    c("A","B"),
    c("A"),
    c("A","C"),
    c("C"),
    c("B","C")
)

for (VARS in VARIABLES.List){
    VARselect(Data[, VARS], lag.max = 3)
}

I think the VARIABLES.List is more concise and elegant to use. And you may also replace the for-loop with lapply.

lapply(VARIABLES.List, function(VARS) VARselect(Data[, VARS], lag.max = 3))


问:
How to get and include the CSRF token in the header when working with REST API
I am using python Django for creating the REST API's.The client side is developed in react and is made as a standalone app.I am uisng axios for triggering th http request.I nedd to pass th CSRF token with every post request,But not able to get the CSRF token from the browser.</p>

答:
How to pass your CSRF when doing Ajax request?

First, make sure you have the django.middleware.csrf.CsrfViewMiddleware in your middlewares list in your settings file. This middleware sets the CSRF_TOKEN in the cookie so you can retrieve it for your ajax request.

Second, Django can now store the CSRF in the session. However, in your particular case you don't want the CSRF_TOKEN in the session. Make sure you have CSRF_USE_SESSIONS = False (which is the default) to have the CSRF in the cookie.

If you check the cookies you should now have a CSRF_TOKEN in there. You can add it dynamically to your ajax request IF you are using jquery with the following code.

https://docs.djangoproject.com/en/1.11/ref/csrf/#setting-the-token-on-the-ajax-request

I'm saying IF you use Jquery because you are using React, which doesn't need Jquery to do Ajax request, it's up to you how you do them.


问:
ajax - incremental load of elements from one file
I've got an index.html with a container in which I want to load content via ajax on click. It looks like this:

```<code><div id="loadcontent"></div>
<div id="more">Load More</div>
</code>```

And there's only one content file with a lot of divs:

```<code><div id="1" class="content">One</div>
<div id="2" class="content">Two</div>
<div id="3" class="content">Three</div>
<div id="4" class="content">Four</div>
<div id="5" class="content">Five</div>
<div id="6" class="content">Six</div>
<div id="7" class="content">Seven</div>
<div id="8" class="content">Eight</div>
<div id="9" class="content">Nine</div>
<div id="10" class="content">Ten</div>
<div id="11" class="content">Eleven</div>
<div id="12" class="content">Twelve</div>
</code>```

Here's the jQuery code:

```<code>$(document).ready(function () {
    var countItem = 0;

    $('#more').click(function(){
        countItem ++;
        $('<div/>').appendTo('#loadcontent').load('content.html #' + countItem)
            .hide()
            .fadeIn(1000);
    });
});
</code>```

For now it loads just one div when the load more button is clicked, cause it counts the ids.

Is it possible to load the next three ore more divs using ajax and append them to divs which already have been loaded? If yes, how can I get this working?
For example: first click: 1-3, second click: 1-6, third click: 1-9, etc...

Any help will be greatly appreciated.

UPDATE:

I don't want to load the content at once and then showing it up using .show() or something similar. It should be an ajax request for each click.

答:
If you are planning to load one file which contains all content and then show it partically, you don't need to make request for each part, just load all content at once and show it when needed.

I made an example with a partial display of content by the click of a button, see working example here:

```<code>$(window).ready(function() {
  var $contentContainer = $('.loadcontent');
  var lastShownIndex = 0; // id of latest shown div
  var showPerClick = 3;
  var elementsCount = 0; // total available elements count

  // function to show elements with passed ids
  var showElements = function(ids) {
    ids.forEach(function(id) {
        $contentContainer.find('#' + id).fadeIn(500);
    });
  }
  // function to generate array [start, start + 1, ..., end]
  var range = function(start, end) {
    return Array.apply(null, Array(end - start + 1)).map(function (_, i) {
        return i + start;
    });
  }
  // function to generate array of unshown divs
  var generateIds = function() {
    if (lastShownIndex >= elementsCount) return [];
    var ids = range(lastShownIndex + 1, Math.min(lastShownIndex + showPerClick, elementsCount));
    lastShownIndex += showPerClick;
    return ids;
  }
  // load content into container
  $contentContainer.load('content.html', function() {
    elementsCount = $contentContainer.find('.content').length;
    showElements(generateIds()); // show elements after page load
  });
  // show items partially by clicking a button
  $('#more').click(function() {
    showElements(generateIds());
    if (lastShownIndex >= elementsCount) { // hide button when no elements are available
        $(this).hide();
    }
  });
});
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I've got an index.html with a container in which I want to load content via ajax on click. It looks like this:

Load More

And there's only one content file with a lot of divs:

One

Two

Three

Four

Five

Six

Seven

Eight

Nine

Ten

Eleven

Twelve

Here's the jQuery code:

$(document).ready(function () {
    var countItem = 0;

    $('#more').click(function(){
        countItem ++;
        $('
').appendTo('#loadcontent').load('content.html #' + countItem)
            .hide()
            .fadeIn(1000);
    });
});

For now it loads just one div when the load more button is clicked, cause it counts the ids.

Is it possible to load the next three ore more divs using ajax and append them to divs which already have been loaded? If yes, how can I get this working?
For example: first click: 1-3, second click: 1-6, third click: 1-9, etc...

Any help will be greatly appreciated.

UPDATE:

I don't want to load the content at once and then showing it up using .show() or something similar. It should be an ajax request for each click.

Body:
If you are planning to load one file which contains all content and then show it partically, you don't need to make request for each part, just load all content at once and show it when needed.

I made an example with a partial display of content by the click of a button, see working example here:

$(window).ready(function() {
  var $contentContainer = $('.loadcontent');
  var lastShownIndex = 0; // id of latest shown div
  var showPerClick = 3;
  var elementsCount = 0; // total available elements count

  // function to show elements with passed ids
  var showElements = function(ids) {
    ids.forEach(function(id) {
        $contentContainer.find('#' + id).fadeIn(500);
    });
  }
  // function to generate array [start, start + 1, ..., end]
  var range = function(start, end) {
    return Array.apply(null, Array(end - start + 1)).map(function (_, i) {
        return i + start;
    });
  }
  // function to generate array of unshown divs
  var generateIds = function() {
    if (lastShownIndex >= elementsCount) return [];
    var ids = range(lastShownIndex + 1, Math.min(lastShownIndex + showPerClick, elementsCount));
    lastShownIndex += showPerClick;
    return ids;
  }
  // load content into container
  $contentContainer.load('content.html', function() {
    elementsCount = $contentContainer.find('.content').length;
    showElements(generateIds()); // show elements after page load
  });
  // show items partially by clicking a button
  $('#more').click(function() {
    showElements(generateIds());
    if (lastShownIndex >= elementsCount) { // hide button when no elements are available
        $(this).hide();
    }
  });
});


问:
Calculate linear commission - Looking for a formula
Using R, Is there a formula that can help me calculate a sales commission based on this condition. For eg:

If the growth (in %) is between 5% and 7% then the salesman will receive a commission which will be linear from 10% to 12.5%

The variables:

```<code>TargetAmt<-100
Earned<-105.6
PctGrowth<-((Earned-TargetAmt)/TargetAmt)*100
PctGrowth
</code>```

5.6

Therefore, I now need to calculate his commission, which will be linear from 10% to 12.5%.

I can do this manually by calculating  slope of the line. However, how can I do this in R?

答:
Alternative Solution

Finding the equation of the line

Using y = mx + c:

```<code>m = (0.125 - 0.1)/(0.07-0.05)
m = 0.025/0.02
m = 1.25
</code>```

Substitute 0.1 (10%) and 0.05 (5%) into the equation to get c

```<code>y = 1.25x + c
0.1 = (1.25 * 0.05) + c
0.1 - (1.25 * 0.05) = c
c = 0.0375
</code>```

we now have our equation for the line:

```<code>y = 1.25x + 0.0375
</code>```

The code:

```<code>TargetAmt <- 100
Earned <- 105.6

profitAsDecimal = (Earned/TargetAmt) - 1
commission = (1.25 * profitAsDecimal) + 0.0375
commissionAsDecimal = (1.25 * profitAsDecimal) + 0.0375
</code>```

So for the growth of 5.6 your commissionAsDecimal would be 0.1075. multiply by 100 to get the percentage of 10.75.

This answer will give you a result linear from 5% to 7% equaling 10% to 12.5%. The answer above is going from 10% to 12%

Body:
Using R, Is there a formula that can help me calculate a sales commission based on this condition. For eg:

If the growth (in %) is between 5% and 7% then the salesman will receive a commission which will be linear from 10% to 12.5%

The variables:

TargetAmt<-100
Earned<-105.6
PctGrowth<-((Earned-TargetAmt)/TargetAmt)*100
PctGrowth

5.6

Therefore, I now need to calculate his commission, which will be linear from 10% to 12.5%.

I can do this manually by calculating  slope of the line. However, how can I do this in R?

Body:
Alternative Solution

Finding the equation of the line

Using y = mx + c:

m = (0.125 - 0.1)/(0.07-0.05)
m = 0.025/0.02
m = 1.25

Substitute 0.1 (10%) and 0.05 (5%) into the equation to get c

y = 1.25x + c
0.1 = (1.25 * 0.05) + c
0.1 - (1.25 * 0.05) = c
c = 0.0375

we now have our equation for the line:

y = 1.25x + 0.0375

The code:

TargetAmt <- 100
Earned <- 105.6

profitAsDecimal = (Earned/TargetAmt) - 1
commission = (1.25 * profitAsDecimal) + 0.0375
commissionAsDecimal = (1.25 * profitAsDecimal) + 0.0375

So for the growth of 5.6 your commissionAsDecimal would be 0.1075. multiply by 100 to get the percentage of 10.75.

This answer will give you a result linear from 5% to 7% equaling 10% to 12.5%. The answer above is going from 10% to 12%


问:
WooCommerce Additional Information - if empty, hide
I'm working on an eCommerce project at the moment.  I'm using WooCommerce in WordPress.

I've got ridden of the product data tabs and displayed product descriptions and additional information within the summary section.

I would like to know how to hide the additional information section if it's empty? Or even, generate a text saying 'None'?

Any help would be appreciated.  Mille merci!

答:
Thank you to the poster above.

I've been fiddling around and with reference to [Woocommerce Docs][1], I've found a solution to my problem.

Here goes:

First, I've removed the product data tabs completely.

```<code>//Removing product data tabs
add_action('init', 'tws_remove_product_tabs');

function tws_remove_product_tabs() {
  remove_action('woocommerce_after_single_product_summary', 'woocommerce_output_product_data_tabs', 10);
}
</code>```

Then:

```<code>//Adding product additional info in summary - if it's empty hide it
add_action('woocommerce_single_product_summary', 'woocommerce_product_additional_information_tab', 25);

function woocommerce_product_additional_information_tab() {
  global $product;
  if ($product - > has_attributes() || $product - > has_dimensions() || $product - > has_weight()) { // Check if product has attributes, dimensions or weight
    return $tabs;
    wc_get_template('single-product/tabs/additional-information.php');
  }
}
</code>```

It's working now.

```<code>   [1]: https://docs.woocommerce.com
</code>```

Body:
Thank you to the poster above.

I've been fiddling around and with reference to [Woocommerce Docs][1], I've found a solution to my problem.

Here goes:

First, I've removed the product data tabs completely.

//Removing product data tabs
add_action('init', 'tws_remove_product_tabs');

function tws_remove_product_tabs() {
  remove_action('woocommerce_after_single_product_summary', 'woocommerce_output_product_data_tabs', 10);
}

Then:

//Adding product additional info in summary - if it's empty hide it
add_action('woocommerce_single_product_summary', 'woocommerce_product_additional_information_tab', 25);

function woocommerce_product_additional_information_tab() {
  global $product;
  if ($product - > has_attributes() || $product - > has_dimensions() || $product - > has_weight()) { // Check if product has attributes, dimensions or weight
    return $tabs;
    wc_get_template('single-product/tabs/additional-information.php');
  }
}

It's working now.

   [1]: https://docs.woocommerce.com


问:
How can i convert string to double ? I'm getting exception
```<code>for(int i = 0; i < Rect.rectangles.Count; i++)
        {
            if (Rect.rectangles[i].transform != null && Rect.rectangles[i].transform != "")
            {
                string firstNumber = Rect.rectangles[i].transform.Substring(18, 10);
                string secondNumber = Rect.rectangles[i].transform.Substring(7, 10);
                double a = Convert.ToDouble(firstNumber);
                double b = Convert.ToDouble(secondNumber);
            }
        }
</code>```

The first number is 0.49052715 and the Convert.ToDouble of a is fine.
But when it's getting to the line:

```<code>double b = Convert.ToDouble(secondNumber);
</code>```

I'm getting exception:

FormatException: Unknown char: ,

But there is no any char/s at all the string in secondNumber is: 0.87142591

This is the whole string in transform: matrix(0.87142591,0.49052715,-0.49052715,0.87142591,0,0)

And i'm extracting the first two numbers: 0.49052715 and 0.87142591 and then trying to convert them to double. But getting the exception.

The code including the Rect.rectangles definition:

```<code>private void ParseSvgMap()
    {
        XDocument document = XDocument.Load(@"C:\Users\mysvg\Documents\my.svg");

        Rect.rectangles = document.Descendants().Where(x => x.Name.LocalName == "rect").Select(x => new Rect()
        {
            style = Rect.GetStyle((string)x.Attribute("style")),
            id = (string)x.Attribute("id"),
            width = (double)x.Attribute("width"),
            height = (double)x.Attribute("width"),
            x = (double?)x.Attribute("width"),
            y = (double?)x.Attribute("width"),
            transform = x.Attribute("transform") == null ? "" : (string)x.Attribute("transform")
        }).ToList();

        for(int i = 0; i < Rect.rectangles.Count; i++)
        {
            if (Rect.rectangles[i].transform != null && Rect.rectangles[i].transform != "")
            {
                string firstNumber = Rect.rectangles[i].transform.Substring(18, 10);
                string secondNumber = Rect.rectangles[i].transform.Substring(7, 10);
                double a = Convert.ToDouble(firstNumber);
                double b = Convert.ToDouble(secondNumber);
                float degree = FindDegree(a, b);
            }
        }
    }

    public static float FindDegree(double a, double b)
    {
        float value = (float)((System.Math.Atan2(a, b) / System.Math.PI) * 180f);
        if (value < 0) value += 360f;

        return value;
    }

    public class Rect
    {
        public static List<Rect> rectangles { get; set; }
        public Dictionary<string, string> style { get; set; }
        public string id { get; set; }
        public double width { get; set; }
        public double height { get; set; }
        public double? x { get; set; }
        public double? y { get; set; }
        public string transform { get; set; }
        public double degree { get; set; }

        public static Dictionary<string, string> GetStyle(string styles)
        {
            string pattern = @"(?'name'[^:]+):(?'value'.*)";
            string[] splitArray = styles.Split(new char[] { ';' });
            Dictionary<string, string> style = splitArray.Select(x => Regex.Match(x, pattern))
                .GroupBy(x => x.Groups["name"].Value, y => y.Groups["value"].Value)
                .ToDictionary(x => x.Key, y => y.FirstOrDefault());
            return style;
        }
    }
</code>```

答:
Code like .Substring(18, 10) is hopelessly brittle and (as you have discovered) is an accident waiting to happen. Numbers aren't guaranteed to be the same length. Just look at the sample data you provided.

You should use something like a regex to extract the numbers from the strings before attempting to parse them.

```<code>var regex  = new Regex(@"matrix\((?<num>-?(?:\d|\.)+)(?:,(?<num>-?(?:\d|\.)+))*\)");
var data   = "matrix(0.87142591,0.49052715,-0.49052715,0.87142591,0,0)";
var values = regex
              .Matches(data)
              .Cast<Match>()
              .SelectMany(m => m.Groups["num"]
                                .Captures
                                .Cast<Capture>()
                                .Select(c=>c.Value))
              .Select(double.Parse)
              .ToList();
</code>```

Then pick out the numbers you want with values[0] and values[1].

Body:
for(int i = 0; i < Rect.rectangles.Count; i++)
        {
            if (Rect.rectangles[i].transform != null && Rect.rectangles[i].transform != "")
            {
                string firstNumber = Rect.rectangles[i].transform.Substring(18, 10);
                string secondNumber = Rect.rectangles[i].transform.Substring(7, 10);
                double a = Convert.ToDouble(firstNumber);
                double b = Convert.ToDouble(secondNumber);
            }
        }

The first number is 0.49052715 and the Convert.ToDouble of a is fine.
But when it's getting to the line:

double b = Convert.ToDouble(secondNumber);

I'm getting exception:

FormatException: Unknown char: ,

But there is no any char/s at all the string in secondNumber is: 0.87142591

This is the whole string in transform: matrix(0.87142591,0.49052715,-0.49052715,0.87142591,0,0)

And i'm extracting the first two numbers: 0.49052715 and 0.87142591 and then trying to convert them to double. But getting the exception.

The code including the Rect.rectangles definition:

private void ParseSvgMap()
    {
        XDocument document = XDocument.Load(@"C:\Users\mysvg\Documents\my.svg");

        Rect.rectangles = document.Descendants().Where(x => x.Name.LocalName == "rect").Select(x => new Rect()
        {
            style = Rect.GetStyle((string)x.Attribute("style")),
            id = (string)x.Attribute("id"),
            width = (double)x.Attribute("width"),
            height = (double)x.Attribute("width"),
            x = (double?)x.Attribute("width"),
            y = (double?)x.Attribute("width"),
            transform = x.Attribute("transform") == null ? "" : (string)x.Attribute("transform")
        }).ToList();

        for(int i = 0; i < Rect.rectangles.Count; i++)
        {
            if (Rect.rectangles[i].transform != null && Rect.rectangles[i].transform != "")
            {
                string firstNumber = Rect.rectangles[i].transform.Substring(18, 10);
                string secondNumber = Rect.rectangles[i].transform.Substring(7, 10);
                double a = Convert.ToDouble(firstNumber);
                double b = Convert.ToDouble(secondNumber);
                float degree = FindDegree(a, b);
            }
        }
    }

    public static float FindDegree(double a, double b)
    {
        float value = (float)((System.Math.Atan2(a, b) / System.Math.PI) * 180f);
        if (value < 0) value += 360f;

        return value;
    }

    public class Rect
    {
        public static List<Rect> rectangles { get; set; }
        public Dictionary<string, string> style { get; set; }
        public string id { get; set; }
        public double width { get; set; }
        public double height { get; set; }
        public double? x { get; set; }
        public double? y { get; set; }
        public string transform { get; set; }
        public double degree { get; set; }

        public static Dictionary<string, string> GetStyle(string styles)
        {
            string pattern = @"(?'name'[^:]+):(?'value'.*)";
            string[] splitArray = styles.Split(new char[] { ';' });
            Dictionary<string, string> style = splitArray.Select(x => Regex.Match(x, pattern))
                .GroupBy(x => x.Groups["name"].Value, y => y.Groups["value"].Value)
                .ToDictionary(x => x.Key, y => y.FirstOrDefault());
            return style;
        }
    }

Body:
Code like .Substring(18, 10) is hopelessly brittle and (as you have discovered) is an accident waiting to happen. Numbers aren't guaranteed to be the same length. Just look at the sample data you provided.

You should use something like a regex to extract the numbers from the strings before attempting to parse them.

var regex  = new Regex(@"matrix\((?<num>-?(?:\d|\.)+)(?:,(?<num>-?(?:\d|\.)+))*\)");
var data   = "matrix(0.87142591,0.49052715,-0.49052715,0.87142591,0,0)";
var values = regex
              .Matches(data)
              .Cast<Match>()
              .SelectMany(m => m.Groups["num"]
                                .Captures
                                .Cast<Capture>()
                                .Select(c=>c.Value))
              .Select(double.Parse)
              .ToList();

Then pick out the numbers you want with values[0] and values[1].


问:
Is there a better way to write this navigation statement?
I know this is a redundant way to write these rules so I'm wondering if anyone knows a better way to write it. Thanks!</p>

```<code>$('.nav li a').eq(0).click(function() {

    $('.nav li a').eq(0).addClass("active");
    $('.nav li a').eq(1).removeClass("active");
    $('.nav li a').eq(2).removeClass("active");
    $('.nav li a').eq(3).removeClass("active");

});
$('.nav li a').eq(1).click(function() {

    $('.nav li a').eq(0).removeClass("active");
    $('.nav li a').eq(1).addClass("active");
    $('.nav li a').eq(2).removeClass("active");
    $('.nav li a').eq(3).removeClass("active");

});
$('.nav li a').eq(2).click(function() {

    $('.nav li a').eq(0).removeClass("active");
    $('.nav li a').eq(1).removeClass("active");
    $('.nav li a').eq(2).addClass("active");
    $('.nav li a').eq(3).removeClass("active");

});
$('.nav li a').eq(3).click(function() {

    $('.nav li a').eq(0).removeClass("active");
    $('.nav li a').eq(1).removeClass("active");
    $('.nav li a').eq(2).removeClass("active");
    $('.nav li a').eq(3).addClass("active");

});
</code>```

答:
```<code>$('.nav li a').click(function() {
  $('.nav li a').removeClass('active');
  $(this).addClass('active');
});
</code>```

Removes the active class from each a and then adds it to the clicked element.

Body:
I know this is a redundant way to write these rules so I'm wondering if anyone knows a better way to write it. Thanks!

$('.nav li a').eq(0).click(function() {

    $('.nav li a').eq(0).addClass("active");
    $('.nav li a').eq(1).removeClass("active");
    $('.nav li a').eq(2).removeClass("active");
    $('.nav li a').eq(3).removeClass("active");

});
$('.nav li a').eq(1).click(function() {

    $('.nav li a').eq(0).removeClass("active");
    $('.nav li a').eq(1).addClass("active");
    $('.nav li a').eq(2).removeClass("active");
    $('.nav li a').eq(3).removeClass("active");

});
$('.nav li a').eq(2).click(function() {

    $('.nav li a').eq(0).removeClass("active");
    $('.nav li a').eq(1).removeClass("active");
    $('.nav li a').eq(2).addClass("active");
    $('.nav li a').eq(3).removeClass("active");

});
$('.nav li a').eq(3).click(function() {

    $('.nav li a').eq(0).removeClass("active");
    $('.nav li a').eq(1).removeClass("active");
    $('.nav li a').eq(2).removeClass("active");
    $('.nav li a').eq(3).addClass("active");

});

Body:
$('.nav li a').click(function() {
  $('.nav li a').removeClass('active');
  $(this).addClass('active');
});

Removes the active class from each a and then adds it to the clicked element.