问:
React router v4 nesting
My routes config looks like this:

```<code>[
    {
        path: '/',
        exact: true,
        component: Dashboard
    },
    {
        path: '/stories/:storyId',
        component: Story,
    },
    {
        component: Dashboard,
        status: 404
    }
]
</code>```

Now inside of the Story component I want to render a gallery and every photo needs to have its own url. Did something like this:

```<code><Switch>
    <Redirect from={match.url} to={`${match.url}/1`} />
    <Route path={`${match.url}/:photoId`} render={this.renderGallery } />
</Switch>
</code>```

Unfortunately it goes into an infinite loop cause match.url never changes after the redirect.

Can somebody help me with this? Thank you

答:
The from on <Redirect> matches loosely by default. As you have it, it will match anything that starts with whatever's in match.url, which includes your ${match.url}/1 path.

Inside of Switch, it's actually reading the props of its children directly and doesn't distinguish the type of component. So, you can use exact and strict like you can on a Route.

Therefore, this should work for you:

```<code><Switch>
  <Redirect exact from={match.url} to={`${match.url}/1`} />
  <Route path={`${match.url}/:photoId`} render={this.renderGallery } />
</Switch>
</code>```

Title: React router v4 nesting

Body:
My routes config looks like this:

[
    {
        path: '/',
        exact: true,
        component: Dashboard
    },
    {
        path: '/stories/:storyId',
        component: Story,
    },
    {
        component: Dashboard,
        status: 404
    }
]

Now inside of the Story component I want to render a gallery and every photo needs to have its own url. Did something like this:

<Switch>
    <Redirect from={match.url} to={`${match.url}/1`} />
    <Route path={`${match.url}/:photoId`} render={this.renderGallery } />
</Switch>

Unfortunately it goes into an infinite loop cause match.url never changes after the redirect.

Can somebody help me with this? Thank you

Body:
The from on <Redirect> matches loosely by default. As you have it, it will match anything that starts with whatever's in match.url, which includes your ${match.url}/1 path.

Inside of Switch, it's actually reading the props of its children directly and doesn't distinguish the type of component. So, you can use exact and strict like you can on a Route.

Therefore, this should work for you:

<Switch>
  <Redirect exact from={match.url} to={`${match.url}/1`} />
  <Route path={`${match.url}/:photoId`} render={this.renderGallery } />
</Switch>


来源: stackexchange

问:
Error in import lstm fromhttp://mxnet.io/tutorials/python/char_lstm.html
I follow the Character Level LSTM Tutorial on http://mxnet.io/tutorials/python/char_lstm.html.  After run this line
 `

import lstm`

I get the error:

ImportError: No module named lstm

How to make this work? Thank you.

答:
The tutorial mentioned in the link is currently removed from the page. So, alternatively, you can check its notebook version here.

The error you were getting was because your program was not able to find "lstm" module which is defined in lstm.py file. It has LSTM cell implementation and it also has lstm_unroll function which is used later in the program. So, you should have lstm.py file in the same folder where you are running char_lstm tutorial. This way you won't get this error.

ContentLicense: CC BY-SA 3.0


问:
Question about combo box and labels
I have a combo box that contains 5 items. I have one label on the window. What i would like to do is whenever a user clicks on one of the items in the combobox, text will populate that label. I would like to show information about whichever item is selected (IP address, etc.). Any help is appreciated. Thanks.

Code:

```<code>private void cmbGroups_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    //Combo box selection changed. Re-bind data
    string selectedGroup = (string)cmbGroups.SelectedItem;
    BindGrid(selectedGroup);
}
</code>```

Code:

```<code>    private void BindGrid(string selectedGroup)
    {
        //Re-bind the grid
        dgPortStatus.DataContext = _dicPortStatus[selectedGroup].Portstatus.DefaultView;

        InitializeColumns();
    }
</code>```

Code:

```<code>private void _UpdatePortStatus()
    {
        string[] files = Directory.GetFiles(System.Configuration.ConfigurationSettings.AppSettings["portStatusDir"], "PortStatus.*");

        foreach (string file in files)
        {

            PortStatus ps = new PortStatus();
            ps.ReadXml(new StreamReader(file));
            //ps.ReadXml(new FileStream(file, FileMode.Open, FileAccess.Read));

            if (!_dicPortStatus.ContainsKey(ps.General[0].Group))
            {
                _dicPortStatus.Add(ps.General[0].Group, ps);
            }

            PortStatus psOrig = _dicPortStatus[ps.General[0].Group];

            foreach (PortStatus.PortstatusRow psr in ps.Portstatus.Rows)
            {
                DataRow[] drs = psOrig.Portstatus.Select("PortNumber = '" + psr.PortNumber + "'");

                if (drs.Length == 1)
                {
                    DateTime curDt = DateTime.Parse(drs[0]["LastUpdateDateTimeUTC"].ToString());
                    DateTime newDt = psr.LastUpdateDateTimeUTC;

                    if (newDt > curDt)
                    {
                        drs[0]["LastUpdateDateTimeUTC"] = newDt;
                    }
                }
                else if (drs.Length == 0)
                {
                    psOrig.Portstatus.ImportRow(psr);
                }
                else
                {
                    throw new Exception("More than one of the same portnumber on PortStatus file: " + file);
                }
            }
        }

        foreach (string groupName in _dicPortStatus.Keys)
        {
            if (!cmbGroups.Items.Contains(groupName))
            {
                cmbGroups.Items.Add(groupName);
                cmbGroups.SelectedItem = groupName;
            }
        }
</code>```

Code:

```<code>private Dictionary<string, PortStatus> _dicPortStatus = new Dictionary<string, PortStatus>()
</code>```

答:
Hi you can try something like this</p>

```<code>private void ComboBox1_SelectedIndexChanged(object sender,
    System.EventArgs e)
{

    ComboBox comboBox = (ComboBox) sender;

    string myItemText = (string) ComboBox1.SelectedItem;

    // populate
    MyTextBox.Text = myItemText;

}
</code>```

ContentLicense: CC BY-SA 2.5

Title: Question about combo box and labels

Body:
I have a combo box that contains 5 items. I have one label on the window. What i would like to do is whenever a user clicks on one of the items in the combobox, text will populate that label. I would like to show information about whichever item is selected (IP address, etc.). Any help is appreciated. Thanks.

Code:

private void cmbGroups_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    //Combo box selection changed. Re-bind data
    string selectedGroup = (string)cmbGroups.SelectedItem;
    BindGrid(selectedGroup);
}

Code:

    private void BindGrid(string selectedGroup)
    {
        //Re-bind the grid
        dgPortStatus.DataContext = _dicPortStatus[selectedGroup].Portstatus.DefaultView;

        InitializeColumns();
    }

Code:

private void _UpdatePortStatus()
    {
        string[] files = Directory.GetFiles(System.Configuration.ConfigurationSettings.AppSettings["portStatusDir"], "PortStatus.*");

        foreach (string file in files)
        {

            PortStatus ps = new PortStatus();
            ps.ReadXml(new StreamReader(file));
            //ps.ReadXml(new FileStream(file, FileMode.Open, FileAccess.Read));

            if (!_dicPortStatus.ContainsKey(ps.General[0].Group))
            {
                _dicPortStatus.Add(ps.General[0].Group, ps);
            }

            PortStatus psOrig = _dicPortStatus[ps.General[0].Group];

            foreach (PortStatus.PortstatusRow psr in ps.Portstatus.Rows)
            {
                DataRow[] drs = psOrig.Portstatus.Select("PortNumber = '" + psr.PortNumber + "'");

                if (drs.Length == 1)
                {
                    DateTime curDt = DateTime.Parse(drs[0]["LastUpdateDateTimeUTC"].ToString());
                    DateTime newDt = psr.LastUpdateDateTimeUTC;

                    if (newDt > curDt)
                    {
                        drs[0]["LastUpdateDateTimeUTC"] = newDt;
                    }
                }
                else if (drs.Length == 0)
                {
                    psOrig.Portstatus.ImportRow(psr);
                }
                else
                {
                    throw new Exception("More than one of the same portnumber on PortStatus file: " + file);
                }
            }
        }

        foreach (string groupName in _dicPortStatus.Keys)
        {
            if (!cmbGroups.Items.Contains(groupName))
            {
                cmbGroups.Items.Add(groupName);
                cmbGroups.SelectedItem = groupName;
            }
        }

Code:

private Dictionary<string, PortStatus> _dicPortStatus = new Dictionary<string, PortStatus>()

Body:
Hi you can try something like this

private void ComboBox1_SelectedIndexChanged(object sender,
    System.EventArgs e)
{

    ComboBox comboBox = (ComboBox) sender;

    string myItemText = (string) ComboBox1.SelectedItem;

    // populate
    MyTextBox.Text = myItemText;

}


问:
How do I programmatically move an ARAnchor?
I'm trying out the new ARKit to replace another similar solution I have. It's pretty great! But I can't seem to figure out how to move an ARAnchor programmatically. I want to slowly move the anchor to the left of the user.

Creating the anchor to be 2 meters in front of the user:

```<code>        var translation = matrix_identity_float4x4
        translation.columns.3.z = -2.0
        let transform = simd_mul(currentFrame.camera.transform, translation)

        let anchor = ARAnchor(transform: transform)
        sceneView.session.add(anchor: anchor)
</code>```

later, moving the object to the left/right of the user (x-axis)...

```<code>anchor.transform.columns.3.x = anchor.transform.columns.3.x + 0.1
</code>```

repeated every 50 milliseconds (or whatever).

The above does not work because transform is a get-only property.

I need a way to change the position of an AR object in space relative to the user in a way that keeps the AR experience intact - meaning, if you move your device, the AR object will be moving but also won't be "stuck" to the camera like it's simply painted on, but moves like you would see a person move while you were walking by - they are moving and you are moving and it looks natural.

Please note the scope of this question relates only to how to move an object in space in relation to the user (ARAnchor), not in relation to a plane (ARPlaneAnchor) or to another detected surface (ARHitTestResult).

Thanks!

答:
You don't need to move anchors. (hand wave) That's not the API you're looking for...

Adding ARAnchor objects to a session is effectively about "labeling" a point in real-world space so that you can refer to it later. The point (1,1,1) (for example) is always the point (1,1,1) — you can't move it someplace else because then it's not the point (1,1,1) anymore.

To make a 2D analogy: anchors are reference points sort of like the bounds of a view. The system (or another piece of your code) tells the view where it's boundaries are, and the view draws its content relative to those boundaries. Anchors in AR give you reference points you can use for drawing content in 3D.

What you're asking is really about moving (and animating the movement of) virtual content between two points. And ARKit itself really isn't about displaying or animating virtual content — there are plenty of great graphics engines out there, so ARKit doesn't need to reinvent that wheel. What ARKit does is provide a real-world frame of reference for you to display or animate content using an existing graphics technology like SceneKit or SpriteKit (or Unity or Unreal, or a custom engine built with Metal or GL).

Since you mentioned trying to do this with SpriteKit... beware, it gets messy. SpriteKit is a 2D engine, and while ARSKView provides some ways to shoehorn a third dimension in there, those ways have their limits.

ARSKView automatically updates the xScale, yScale, and zRotation of each sprite associated with an ARAnchor, providing the illusion of 3D perspective. But that applies only to nodes attached to anchors, and as noted above, anchors are static.

You can, however, add other nodes to your scene, and use those same properties to make those nodes match the ARSKView-managed nodes. Here's some code you can add/replace in the ARKit/SpriteKit Xcode template project to do that. We'll start with some basic logic to run a bouncing animation on the third tap (after using the first two taps to place anchors).

```<code>var anchors: [ARAnchor] = []
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

    // Start bouncing on touch after placing 2 anchors (don't allow more)
    if anchors.count > 1 {
        startBouncing(time: 1)
        return
    }
    // Create anchor using the camera's current position
    guard let sceneView = self.view as? ARSKView else { return }
    if let currentFrame = sceneView.session.currentFrame {

        // Create a transform with a translation of 30 cm in front of the camera
        var translation = matrix_identity_float4x4
        translation.columns.3.z = -0.3
        let transform = simd_mul(currentFrame.camera.transform, translation)

        // Add a new anchor to the session
        let anchor = ARAnchor(transform: transform)
        sceneView.session.add(anchor: anchor)
        anchors.append(anchor)
    }
}
</code>```

Then, some SpriteKit fun for making that animation happen:

```<code>var ballNode: SKLabelNode = {
    let labelNode  = SKLabelNode(text: "")
    labelNode.horizontalAlignmentMode = .center
    labelNode.verticalAlignmentMode = .center
    return labelNode
}()
func startBouncing(time: TimeInterval) {
    guard
        let sceneView = self.view as? ARSKView,
        let first = anchors.first, let start = sceneView.node(for: first),
        let last = anchors.last, let end = sceneView.node(for: last)
        else { return }

    if ballNode.parent == nil {
        addChild(ballNode)
    }
    ballNode.setScale(start.xScale)
    ballNode.zRotation = start.zRotation
    ballNode.position = start.position

    let scale = SKAction.scale(to: end.xScale, duration: time)
    let rotate = SKAction.rotate(toAngle: end.zRotation, duration: time)
    let move = SKAction.move(to: end.position, duration: time)

    let scaleBack = SKAction.scale(to: start.xScale, duration: time)
    let rotateBack = SKAction.rotate(toAngle: start.zRotation, duration: time)
    let moveBack = SKAction.move(to: start.position, duration: time)

    let action = SKAction.repeatForever(.sequence([
        .group([scale, rotate, move]),
        .group([scaleBack, rotateBack, moveBack])
        ]))
    ballNode.removeAllActions()
    ballNode.run(action)
}
</code>```

Here's a video so you can see this code in action. You'll notice that the illusion only works as long as you don't move the camera — not so great for AR. When using SKAction, we can't adjust the start/end states of the animation while animating, so the ball keeps bouncing back and forth between its original (screen-space) positions/rotations/scales.

You could do better by animating the ball directly, but it's a lot of work. You'd need to, on every frame (or every view(_:didUpdate:for:) delegate callback):

Save off the updated position, rotation, and scale values for the anchor-based nodes at each end of the animation. You'll need to do this twice per didUpdate callback, because you'll get one callback for each node.

Work out position, rotation, and scale values for the node being animated, by interpolating between the two endpoint values based on the current time.

Set the new attributes on the node. (Or maybe animate it to those attributes over a very short duration, so it doesn't jump too much in one frame?)

That's kind of a lot of work to shoehorn a fake 3D illusion into a 2D graphics toolkit — hence my comments about SpriteKit not being a great first step into ARKit.

If you want 3D positioning and animation for your AR overlays, it's a lot easier to use a 3D graphics toolkit. Here's a repeat of the previous example, but using SceneKit instead. Start with the ARKit/SceneKit Xcode template, take the spaceship out, and paste the same touchesBegan function from above into the ViewController. (Change the as ARSKView casts to as ARSCNView, too.)

Then, some quick code for placing 2D billboarded sprites, matching via SceneKit the behavior of the ARKit/SpriteKit template:

```<code>// in global scope
func makeBillboardNode(image: UIImage) -> SCNNode {
    let plane = SCNPlane(width: 0.1, height: 0.1)
    plane.firstMaterial!.diffuse.contents = image
    let node = SCNNode(geometry: plane)
    node.constraints = [SCNBillboardConstraint()]
    return node
}

// inside ViewController
func renderer(_ renderer: SCNSceneRenderer, didAdd node: SCNNode, for anchor: ARAnchor) {
    // emoji to image based on https://stackoverflow.com/a/41021662/957768
    let billboard = makeBillboardNode(image: "⛹".image())
    node.addChildNode(billboard)
}
</code>```

Finally, adding the animation for the bouncing ball:

```<code>let ballNode = makeBillboardNode(image: "".image())
func startBouncing(time: TimeInterval) {
    guard
        let sceneView = self.view as? ARSCNView,
        let first = anchors.first, let start = sceneView.node(for: first),
        let last = anchors.last, let end = sceneView.node(for: last)
        else { return }

    if ballNode.parent == nil {
        sceneView.scene.rootNode.addChildNode(ballNode)
    }

    let animation = CABasicAnimation(keyPath: #keyPath(SCNNode.transform))
    animation.fromValue = start.transform
    animation.toValue = end.transform
    animation.duration = time
    animation.autoreverses = true
    animation.repeatCount = .infinity
    ballNode.removeAllAnimations()
    ballNode.addAnimation(animation, forKey: nil)
}
</code>```

This time the animation code is a lot shorter than the SpriteKit version.
Here's how it looks in action.

Because we're working in 3D to start with, we're actually animating between two 3D positions — unlike in the SpriteKit version, the animation stays where it's supposed to. (And without the extra work for directly interpolating and animating attributes.)

Body:
I'm trying out the new ARKit to replace another similar solution I have. It's pretty great! But I can't seem to figure out how to move an ARAnchor programmatically. I want to slowly move the anchor to the left of the user.

Creating the anchor to be 2 meters in front of the user:

        var translation = matrix_identity_float4x4
        translation.columns.3.z = -2.0
        let transform = simd_mul(currentFrame.camera.transform, translation)

        let anchor = ARAnchor(transform: transform)
        sceneView.session.add(anchor: anchor)

later, moving the object to the left/right of the user (x-axis)...

anchor.transform.columns.3.x = anchor.transform.columns.3.x + 0.1

repeated every 50 milliseconds (or whatever).

The above does not work because transform is a get-only property.

I need a way to change the position of an AR object in space relative to the user in a way that keeps the AR experience intact - meaning, if you move your device, the AR object will be moving but also won't be "stuck" to the camera like it's simply painted on, but moves like you would see a person move while you were walking by - they are moving and you are moving and it looks natural.

Please note the scope of this question relates only to how to move an object in space in relation to the user (ARAnchor), not in relation to a plane (ARPlaneAnchor) or to another detected surface (ARHitTestResult).

Thanks!

Body:
You don't need to move anchors. (hand wave) That's not the API you're looking for...

Adding ARAnchor objects to a session is effectively about "labeling" a point in real-world space so that you can refer to it later. The point (1,1,1) (for example) is always the point (1,1,1) — you can't move it someplace else because then it's not the point (1,1,1) anymore.

To make a 2D analogy: anchors are reference points sort of like the bounds of a view. The system (or another piece of your code) tells the view where it's boundaries are, and the view draws its content relative to those boundaries. Anchors in AR give you reference points you can use for drawing content in 3D.

What you're asking is really about moving (and animating the movement of) virtual content between two points. And ARKit itself really isn't about displaying or animating virtual content — there are plenty of great graphics engines out there, so ARKit doesn't need to reinvent that wheel. What ARKit does is provide a real-world frame of reference for you to display or animate content using an existing graphics technology like SceneKit or SpriteKit (or Unity or Unreal, or a custom engine built with Metal or GL).

Since you mentioned trying to do this with SpriteKit... beware, it gets messy. SpriteKit is a 2D engine, and while ARSKView provides some ways to shoehorn a third dimension in there, those ways have their limits.

ARSKView automatically updates the xScale, yScale, and zRotation of each sprite associated with an ARAnchor, providing the illusion of 3D perspective. But that applies only to nodes attached to anchors, and as noted above, anchors are static.

You can, however, add other nodes to your scene, and use those same properties to make those nodes match the ARSKView-managed nodes. Here's some code you can add/replace in the ARKit/SpriteKit Xcode template project to do that. We'll start with some basic logic to run a bouncing animation on the third tap (after using the first two taps to place anchors).

var anchors: [ARAnchor] = []
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

    // Start bouncing on touch after placing 2 anchors (don't allow more)
    if anchors.count > 1 {
        startBouncing(time: 1)
        return
    }
    // Create anchor using the camera's current position
    guard let sceneView = self.view as? ARSKView else { return }
    if let currentFrame = sceneView.session.currentFrame {

        // Create a transform with a translation of 30 cm in front of the camera
        var translation = matrix_identity_float4x4
        translation.columns.3.z = -0.3
        let transform = simd_mul(currentFrame.camera.transform, translation)

        // Add a new anchor to the session
        let anchor = ARAnchor(transform: transform)
        sceneView.session.add(anchor: anchor)
        anchors.append(anchor)
    }
}

Then, some SpriteKit fun for making that animation happen:

var ballNode: SKLabelNode = {
    let labelNode  = SKLabelNode(text: "")
    labelNode.horizontalAlignmentMode = .center
    labelNode.verticalAlignmentMode = .center
    return labelNode
}()
func startBouncing(time: TimeInterval) {
    guard
        let sceneView = self.view as? ARSKView,
        let first = anchors.first, let start = sceneView.node(for: first),
        let last = anchors.last, let end = sceneView.node(for: last)
        else { return }

    if ballNode.parent == nil {
        addChild(ballNode)
    }
    ballNode.setScale(start.xScale)
    ballNode.zRotation = start.zRotation
    ballNode.position = start.position

    let scale = SKAction.scale(to: end.xScale, duration: time)
    let rotate = SKAction.rotate(toAngle: end.zRotation, duration: time)
    let move = SKAction.move(to: end.position, duration: time)

    let scaleBack = SKAction.scale(to: start.xScale, duration: time)
    let rotateBack = SKAction.rotate(toAngle: start.zRotation, duration: time)
    let moveBack = SKAction.move(to: start.position, duration: time)

    let action = SKAction.repeatForever(.sequence([
        .group([scale, rotate, move]),
        .group([scaleBack, rotateBack, moveBack])
        ]))
    ballNode.removeAllActions()
    ballNode.run(action)
}

Here's a video so you can see this code in action. You'll notice that the illusion only works as long as you don't move the camera — not so great for AR. When using SKAction, we can't adjust the start/end states of the animation while animating, so the ball keeps bouncing back and forth between its original (screen-space) positions/rotations/scales.

You could do better by animating the ball directly, but it's a lot of work. You'd need to, on every frame (or every view(_:didUpdate:for:) delegate callback):

Save off the updated position, rotation, and scale values for the anchor-based nodes at each end of the animation. You'll need to do this twice per didUpdate callback, because you'll get one callback for each node.

Work out position, rotation, and scale values for the node being animated, by interpolating between the two endpoint values based on the current time.

Set the new attributes on the node. (Or maybe animate it to those attributes over a very short duration, so it doesn't jump too much in one frame?)

That's kind of a lot of work to shoehorn a fake 3D illusion into a 2D graphics toolkit — hence my comments about SpriteKit not being a great first step into ARKit.

If you want 3D positioning and animation for your AR overlays, it's a lot easier to use a 3D graphics toolkit. Here's a repeat of the previous example, but using SceneKit instead. Start with the ARKit/SceneKit Xcode template, take the spaceship out, and paste the same touchesBegan function from above into the ViewController. (Change the as ARSKView casts to as ARSCNView, too.)

Then, some quick code for placing 2D billboarded sprites, matching via SceneKit the behavior of the ARKit/SpriteKit template:

// in global scope
func makeBillboardNode(image: UIImage) -> SCNNode {
    let plane = SCNPlane(width: 0.1, height: 0.1)
    plane.firstMaterial!.diffuse.contents = image
    let node = SCNNode(geometry: plane)
    node.constraints = [SCNBillboardConstraint()]
    return node
}

// inside ViewController
func renderer(_ renderer: SCNSceneRenderer, didAdd node: SCNNode, for anchor: ARAnchor) {
    // emoji to image based on https://stackoverflow.com/a/41021662/957768
    let billboard = makeBillboardNode(image: "⛹".image())
    node.addChildNode(billboard)
}

Finally, adding the animation for the bouncing ball:

let ballNode = makeBillboardNode(image: "".image())
func startBouncing(time: TimeInterval) {
    guard
        let sceneView = self.view as? ARSCNView,
        let first = anchors.first, let start = sceneView.node(for: first),
        let last = anchors.last, let end = sceneView.node(for: last)
        else { return }

    if ballNode.parent == nil {
        sceneView.scene.rootNode.addChildNode(ballNode)
    }

    let animation = CABasicAnimation(keyPath: #keyPath(SCNNode.transform))
    animation.fromValue = start.transform
    animation.toValue = end.transform
    animation.duration = time
    animation.autoreverses = true
    animation.repeatCount = .infinity
    ballNode.removeAllAnimations()
    ballNode.addAnimation(animation, forKey: nil)
}

This time the animation code is a lot shorter than the SpriteKit version.
Here's how it looks in action.

Because we're working in 3D to start with, we're actually animating between two 3D positions — unlike in the SpriteKit version, the animation stays where it's supposed to. (And without the extra work for directly interpolating and animating attributes.)


问:
Python3 - TypeError: list indices must be integers or slices, not str - List
I've just recently started exploring Python and can't seem to figure out a way to code this. I'm guessing the fix is fairly simple. Can someone help me?</p>

```<code>temp = 0
for i in list[::-1]:
    temp = temp + 1.11
    list[i].append("{0:.2f}".format(temp))
</code>```

答:
You already have the list item as i and you can just append to it. list[i] is indexing the list with the list item (which I think is another list) and not index.

So instead of

```<code>list[i].append("{0:.2f}".format(temp))
</code>```

you should do

```<code>i.append("{0:.2f}".format(temp))
</code>```

Body:
I've just recently started exploring Python and can't seem to figure out a way to code this. I'm guessing the fix is fairly simple. Can someone help me?

temp = 0
for i in list[::-1]:
    temp = temp + 1.11
    list[i].append("{0:.2f}".format(temp))

Body:
You already have the list item as i and you can just append to it. list[i] is indexing the list with the list item (which I think is another list) and not index.

So instead of

list[i].append("{0:.2f}".format(temp))

you should do

i.append("{0:.2f}".format(temp))


问:
NLmeans / ffmpeg: is it really SO slow?
I'm trying to encode DVD-quality video with ffmpeg and nlmeans filtering (well, that's what the title says). But even on the top Core i7 CPU I have barely 12 frames per sec, and only one core is in use (75% idle). On older machines it's less than 1-2 fps.

Is it really so slow, or it's just me? No multithreading? No GPU optimization?

Default settings, windows7x64, zeranoe build.

答:
I've used FFMpeg and I can confirm that you can see surprisingly slow frame times.  I've experienced 30% total usage on an i7 core with 2 solid cores.  Adding another compression stream bumped the CPU up to 70% at which point I abandoned that approach (4 streams were needed and a maxed-out CPU was not an option).
I think that as FFMpeg is written with very low-level requirements (ie you can run it on microcontrollers if you wish!) it doesn't natively use all your MMX/SIMD magic extensions etc.  Also you're likely to be compressing on only a single thread.

Good Luck!

Title: NLmeans / ffmpeg: is it really SO slow?


问:
transpose a matrix using c pointer, memory access error
Without newly allocating memory to 'transposed' I tried to realloc on 'matrix' https://codepad.remoteinterview.io/WGIBSKENXV when I run it on web it works fine but on visual basic 2017, it gives me access violation error at double for loop part.
The way that just allocates new memory to 'transposed' also works okay on web, but on visual basic 2017 it gives access violation error.
What is wrong??

When I allocate memory in a defined function, should I free it in the main function? as with 'matrix'(the one that I allocated in main function)? Did I do it correctly?

```<code> # include <stdio.h>
 # include <stdlib.h>

 int** transpose (int **matrix, int m, int n);
 void printMatrix(int **matrix, int m, int n);

 int main (void){
 int rows, cols;
 int r, c, i;
 int **matrix;

 printf("Number of Rows : ");
 scanf("%d", &rows);
 printf("Number of Cols : ");
 scanf("%d", &cols);

 matrix = (int **)malloc(rows*sizeof(int*));
 for(i = 0; i < rows; i++){
 matrix[i] = (int*)malloc(cols*sizeof(int));
 }

 srand(2016);
 for( r = 0; r < rows; r++ ){
      for( c = 0; c < cols; c++ ){
           *(*(matrix + r)+c) = rand() % 99 + 1;
      }
 }

 printf("Matrix produced with seed number 2016\n");
 printMatrix(matrix, rows, cols);

 matrix = transpose(matrix, rows, cols);

 printf("Transposed Matrix\n");
 printMatrix(matrix, rows, cols);

         i = 0;
 while(matrix[i] != 0){
        free(matrix[i]);
        ++i;
 }
    free(matrix);
  /*
    i = 0;
    while(transposed[i] != 0){
         free(transposed[i]);
         ++i;
    }
    free(transposed);
  */
    return 0;
 }
       //When I allocate memory in a defined function, should I free it in the main function? as with 'matrix'? Did I do it correctly?

 int** transpose (int **matrix, int rows, int cols){

 int i ,j;

 if( rows < cols ){
 for(i = 0; i < rows; i++){
 matrix[i] = (int*)realloc(matrix[i], rows*sizeof(int));
 }
 }
 else if(cols < rows){
 matrix = (int **)realloc(matrix, cols*sizeof(int*));
 }

   for (i = 0; i < rows; i++) {
    for (j = i +1 ; j < cols ; j++) {
     tmp= *(*(matrix + i) + j);
     *(*(matrix + i) + j) = *(*(matrix + j) + i);
     *(*(matrix + j) + i) = tmp;
    }
 }
      return matrix;

 // Without newly allocating memory to 'transposed' I tried to realloc on 'matrix'
 https://codepad.remoteinterview.io/WGIBSKENXV when I run it on web it works fine but on visual basic 2017, it gives me access violation error at double for loop part.

  /*
 int ** transposed;
 transposed = (int **)malloc(cols*sizeof(int*));
 for(i = 0; i < cols; i++){
 transposed[i] = (int*)malloc(rows*sizeof(int));
 }

 for (i = 0; i < rows; i++) {
    for (j = 0 ; j < cols; j++) {
     *(*(transposed + j )+ i )= *(*(matrix + i) + j);
     *(*(transposed + i) + j) = *(*(matrix + j) + i);
    }
 }
 return transposed;
 */

 // Just allocating new memory to 'transposed' works okay on web https://codepad.remoteinterview.io/WGIBSKENXV, but on visual basic 2017 it gives access violation error. When I allocate memory in a defined function, should I free it in the main function? as with 'matrix'? Did I do it correctly?
 }
 void printMatrix(int **matrix, int m, int n){
 int i, j;

 for( i = 0; i < m; i++ ){
 for( j = 0; j < n; j++ ){
 printf("%4d", *(*(matrix + i )+j) );
 }
 printf("\n");
 }

 }
</code>```

答:
```<code> else if(cols < rows){
 matrix = (int **)realloc(matrix, cols*sizeof(int*));
 }
</code>```

In this case you are reallocating matrix with lesser rows, but the loop that follows it still accesses it till rows

```<code>   for (i = 0; i < rows; i++) {
    for (j = i +1 ; j < cols ; j++) {
     tmp= *(*(matrix + i) + j);
     *(*(matrix + i) + j) = *(*(matrix + j) + i);
     *(*(matrix + j) + i) = tmp;
    }
 }
</code>```

*(*(matrix + i) + j); when i > cols will result in access to invalid memory, as matrix is reallocated to cols number of addresses

Body:
Without newly allocating memory to 'transposed' I tried to realloc on 'matrix' https://codepad.remoteinterview.io/WGIBSKENXV when I run it on web it works fine but on visual basic 2017, it gives me access violation error at double for loop part.
The way that just allocates new memory to 'transposed' also works okay on web, but on visual basic 2017 it gives access violation error.
What is wrong??

When I allocate memory in a defined function, should I free it in the main function? as with 'matrix'(the one that I allocated in main function)? Did I do it correctly?

 # include <stdio.h>
 # include <stdlib.h>

 int** transpose (int **matrix, int m, int n);
 void printMatrix(int **matrix, int m, int n);

 int main (void){
 int rows, cols;
 int r, c, i;
 int **matrix;

 printf("Number of Rows : ");
 scanf("%d", &rows);
 printf("Number of Cols : ");
 scanf("%d", &cols);

 matrix = (int **)malloc(rows*sizeof(int*));
 for(i = 0; i < rows; i++){
 matrix[i] = (int*)malloc(cols*sizeof(int));
 }

 srand(2016);
 for( r = 0; r < rows; r++ ){
      for( c = 0; c < cols; c++ ){
           *(*(matrix + r)+c) = rand() % 99 + 1;
      }
 }

 printf("Matrix produced with seed number 2016\n");
 printMatrix(matrix, rows, cols);

 matrix = transpose(matrix, rows, cols);

 printf("Transposed Matrix\n");
 printMatrix(matrix, rows, cols);

         i = 0;
 while(matrix[i] != 0){
        free(matrix[i]);
        ++i;
 }
    free(matrix);
  /*
    i = 0;
    while(transposed[i] != 0){
         free(transposed[i]);
         ++i;
    }
    free(transposed);
  */
    return 0;
 }
       //When I allocate memory in a defined function, should I free it in the main function? as with 'matrix'? Did I do it correctly?

 int** transpose (int **matrix, int rows, int cols){

 int i ,j;

 if( rows < cols ){
 for(i = 0; i < rows; i++){
 matrix[i] = (int*)realloc(matrix[i], rows*sizeof(int));
 }
 }
 else if(cols < rows){
 matrix = (int **)realloc(matrix, cols*sizeof(int*));
 }

   for (i = 0; i < rows; i++) {
    for (j = i +1 ; j < cols ; j++) {
     tmp= *(*(matrix + i) + j);
     *(*(matrix + i) + j) = *(*(matrix + j) + i);
     *(*(matrix + j) + i) = tmp;
    }
 }
      return matrix;

 // Without newly allocating memory to 'transposed' I tried to realloc on 'matrix'
 https://codepad.remoteinterview.io/WGIBSKENXV when I run it on web it works fine but on visual basic 2017, it gives me access violation error at double for loop part.

  /*
 int ** transposed;
 transposed = (int **)malloc(cols*sizeof(int*));
 for(i = 0; i < cols; i++){
 transposed[i] = (int*)malloc(rows*sizeof(int));
 }

 for (i = 0; i < rows; i++) {
    for (j = 0 ; j < cols; j++) {
     *(*(transposed + j )+ i )= *(*(matrix + i) + j);
     *(*(transposed + i) + j) = *(*(matrix + j) + i);
    }
 }
 return transposed;
 */

 // Just allocating new memory to 'transposed' works okay on web https://codepad.remoteinterview.io/WGIBSKENXV, but on visual basic 2017 it gives access violation error. When I allocate memory in a defined function, should I free it in the main function? as with 'matrix'? Did I do it correctly?
 }
 void printMatrix(int **matrix, int m, int n){
 int i, j;

 for( i = 0; i < m; i++ ){
 for( j = 0; j < n; j++ ){
 printf("%4d", *(*(matrix + i )+j) );
 }
 printf("\n");
 }

 }

Body:
 else if(cols < rows){
 matrix = (int **)realloc(matrix, cols*sizeof(int*));
 }

In this case you are reallocating matrix with lesser rows, but the loop that follows it still accesses it till rows

   for (i = 0; i < rows; i++) {
    for (j = i +1 ; j < cols ; j++) {
     tmp= *(*(matrix + i) + j);
     *(*(matrix + i) + j) = *(*(matrix + j) + i);
     *(*(matrix + j) + i) = tmp;
    }
 }

*(*(matrix + i) + j); when i > cols will result in access to invalid memory, as matrix is reallocated to cols number of addresses


问:
No implicit conversion of Symbol into Integer only happening sometimes
Can someone explain what I'm doing wrong!?

```<code>   if response[:result]
      response[:credentials].each do |cred|

        AntHQ.logger.debug "==> #{cred}"
        c = app_instance.credentials.find_by(name: cred[:name])

        if c && cred[:value]
          c.value = cred[:value]
          c.expiry = cred[:expiry]
          c.save!
        end
      end
    end
</code>```

Error

```<code>TypeError: no implicit conversion of Symbol into Integer

File "/usr/local/lib/ruby/gems/2.1.0/bundler/gems/ant_light_tasks-01095a3ea065/lib/ant_light_tasks/app/update_credentials.rb" line 16 in []
</code>```

Line 16:

```<code> c.value = cred[:value]
</code>```

Example "response":

```<code>{:result=>true, :credentials=>[{:name=>"access_token", :value=>"...", :expiry=>"..."}]}
</code>```

答:
Hi guys I appreciate your answers.

The real cause was because our jenkins agent wasn't deploying the code to all our instances.

Body:
Can someone explain what I'm doing wrong!?

   if response[:result]
      response[:credentials].each do |cred|

        AntHQ.logger.debug "==> #{cred}"
        c = app_instance.credentials.find_by(name: cred[:name])

        if c && cred[:value]
          c.value = cred[:value]
          c.expiry = cred[:expiry]
          c.save!
        end
      end
    end

Error

TypeError: no implicit conversion of Symbol into Integer

File "/usr/local/lib/ruby/gems/2.1.0/bundler/gems/ant_light_tasks-01095a3ea065/lib/ant_light_tasks/app/update_credentials.rb" line 16 in []

Line 16:

 c.value = cred[:value]

Example "response":

{:result=>true, :credentials=>[{:name=>"access_token", :value=>"...", :expiry=>"..."}]}


问:
cannot set UILabel padding in tableViewcell
I have set my UILabel padding using StackOverflow's popular thread for resolving auto-layout issue.
This thread is basically a UILabel extension.

Part of the answer is:

```<code>class NRLabel : UILabel {

    var textInsets = UIEdgeInsets.zero {
        didSet { invalidateIntrinsicContentSize() }
    }

    override func textRect(forBounds bounds: CGRect, limitedToNumberOfLines numberOfLines: Int) -> CGRect {
        let insetRect = UIEdgeInsetsInsetRect(bounds, textInsets)
        let textRect = super.textRect(forBounds: insetRect, limitedToNumberOfLines: numberOfLines)
        let invertedInsets = UIEdgeInsets(top: -textInsets.top,
                                          left: -textInsets.left,
                                          bottom: -textInsets.bottom,
                                          right: -textInsets.right)
        return UIEdgeInsetsInsetRect(textRect, invertedInsets)
    }

    override func drawText(in rect: CGRect) {
        super.drawText(in: UIEdgeInsetsInsetRect(rect, textInsets))
    }
}
</code>```

Everything is working fine, padding has been added but i need to reload the tableViewcell to see the effect.

I have  overridden my customCell's viewWillLayoutSubviews() function like this for padding

```<code> self.chatLabel.textInsets = UIEdgeInsets.init(top: 10, left: 10, bottom: 10, right: 10)
</code>```

And the effect is like this.

You see, first label is getting it's padding after reloading the cell.

Pls suggest how to  achieve UILabel padding by using the extension mentioned above so that this issue is resolved.

答:
After some long tiring hours i just found the solution which i never tried and i don't know why. :(

In cellForRowAtIndexPath i just wrote the line which was in customCell's file.

Just call this line before returning cell.

```<code>cell.chatLabel.textInsets = UIEdgeInsets.init(top: 10, left: 10, bottom: 10, right: 10)
</code>```

The reason behind it may be, Cell is drawn with all the functionality but it didn't get much to refresh it's UI.
So calling the line just before showing the cell resolve the problem.

Body:
I have set my UILabel padding using StackOverflow's popular thread for resolving auto-layout issue.
This thread is basically a UILabel extension.

Part of the answer is:

class NRLabel : UILabel {

    var textInsets = UIEdgeInsets.zero {
        didSet { invalidateIntrinsicContentSize() }
    }

    override func textRect(forBounds bounds: CGRect, limitedToNumberOfLines numberOfLines: Int) -> CGRect {
        let insetRect = UIEdgeInsetsInsetRect(bounds, textInsets)
        let textRect = super.textRect(forBounds: insetRect, limitedToNumberOfLines: numberOfLines)
        let invertedInsets = UIEdgeInsets(top: -textInsets.top,
                                          left: -textInsets.left,
                                          bottom: -textInsets.bottom,
                                          right: -textInsets.right)
        return UIEdgeInsetsInsetRect(textRect, invertedInsets)
    }

    override func drawText(in rect: CGRect) {
        super.drawText(in: UIEdgeInsetsInsetRect(rect, textInsets))
    }
}

Everything is working fine, padding has been added but i need to reload the tableViewcell to see the effect.

I have  overridden my customCell's viewWillLayoutSubviews() function like this for padding

 self.chatLabel.textInsets = UIEdgeInsets.init(top: 10, left: 10, bottom: 10, right: 10)

And the effect is like this.

You see, first label is getting it's padding after reloading the cell.

Pls suggest how to  achieve UILabel padding by using the extension mentioned above so that this issue is resolved.

Body:
After some long tiring hours i just found the solution which i never tried and i don't know why. :(

In cellForRowAtIndexPath i just wrote the line which was in customCell's file.

Just call this line before returning cell.

cell.chatLabel.textInsets = UIEdgeInsets.init(top: 10, left: 10, bottom: 10, right: 10)

The reason behind it may be, Cell is drawn with all the functionality but it didn't get much to refresh it's UI.
So calling the line just before showing the cell resolve the problem.


问:
How would I go about making this error message appear when form field is not right?
I have an if statement and I already have it working so if certain fields are not filled in it will not send. I then have an else, and I put it like so:

```<code>if(isset($_POST['submit'])) {
    if (!empty($name) && (!empty($email) || !empty($phone))) {
    mail( "EMAIL@hotmail.com", "Monthly Specials Email",
    "Name: $name
     Email: $email
     Phone Number: $phone
     Comment: $comment", "From: $email" );

    $error = "";

   } else {
    $error = "Please fill in the required fields.";
   }
}
</code>```

In the form, I have a span class like so:

```<code><span class="error">'.$error.'</span>
</code>```

I have it so the action of the form is set to blank so it will stay on the same page when sent, and all of the functions are in the same page as the form. How would I go about updating the error span?

Thanks so much for any help or tips!

答:
Following your current model, I am assuming you do not mean AJAX and that you merely mean the server side code and form cohabitate on the same script.  You can set the action of the form to $_SERVER['PHP_SELF'] first to ensure the proper action attribute is set.

Are you echoing out the error message within the span, or is all that output being placed after an echo statement?

```<code>echo '<span class="error">'.$error.'</span>'
</code>```

Or, if not in the PHP context outside of script

```<code><span class="error"><? echo $error; ?></span>
</code>```

Also, you may want to consider using a mature php mailing solution like PHP Mailer to help set headers and ensure more effective delivery.

Body:
I have an if statement and I already have it working so if certain fields are not filled in it will not send. I then have an else, and I put it like so:

if(isset($_POST['submit'])) {
    if (!empty($name) && (!empty($email) || !empty($phone))) {
    mail( "EMAIL@hotmail.com", "Monthly Specials Email",
    "Name: $name
     Email: $email
     Phone Number: $phone
     Comment: $comment", "From: $email" );

    $error = "";

   } else {
    $error = "Please fill in the required fields.";
   }
}

In the form, I have a span class like so:

'.$error.'

I have it so the action of the form is set to blank so it will stay on the same page when sent, and all of the functions are in the same page as the form. How would I go about updating the error span?

Thanks so much for any help or tips!

Body:
Following your current model, I am assuming you do not mean AJAX and that you merely mean the server side code and form cohabitate on the same script.  You can set the action of the form to $_SERVER['PHP_SELF'] first to ensure the proper action attribute is set.

Are you echoing out the error message within the span, or is all that output being placed after an echo statement?

echo '<span class="error">'.$error.'</span>'

Or, if not in the PHP context outside of script

<span class="error"><? echo $error; ?></span>

Also, you may want to consider using a mature php mailing solution like PHP Mailer to help set headers and ensure more effective delivery.


问:
Receiving data through PeerJS
I'm working on a small PeerJS project, and I'm a little confused. I'm able to open a connection and confirm that the clients are connected, but I cannot figure out the proper method or syntax for receiving anything. Or perhaps I'm just missing something simple. I have tried so many variations trying to get this to work. JS and HTML below.

JS:

```<code>var peer = new Peer({
  key: 'lwjd5qra8257b9'
// I use my own API key for testing, this is the public PeerJS key
//you'll have to generate your own if this doesn't work.
});

peer.on('open', function(id) {
  $('body').append('<br/>Your personal peer ID is: ' + id + '<br/>Be careful who you share it with.');
});
peer.on('connection', connect);

function connect(succ) {
  conn = succ;
  //input changes on successful connect
  $('#peerKeyEnter').val(conn.peer);
  $('#peerKeyEnter').prop('disabled',true);
}

$(document).ready(function() {

  $('#peerKeySubmit').on('click', function() {
    var buddy = document.getElementById('peerKeyEnter').value;
    var buddyConn = peer.connect(buddy); //send connection request
    connect(buddyConn); //connect to peer

    //sending data
    buddyConn.on('open', function() {
      buddyConn.send('this is supposed to work')
    });

    //receiving data
    buddyConn.on('connection', function(conn) {
      buddyConn.on('data', function(data) {
        console.log(data);
      });
    });
  }); //end peerKeySubmit.click
}); //end doc.ready()
</code>```

HTML:

```<code><html>
<head>
  <script
  src="https://code.jquery.com/jquery-3.2.1.js"
  integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE="
  crossorigin="anonymous"></script>
  <!--script src='peer.js'></script-->
<script src="http://cdn.peerjs.com/0.3/peer.js"></script>
  <script src='app.js'></script>
</head>
<body>

<input type='text' id='peerKeyEnter' placeholder="Enter peer's ID"></input>
<button id='peerKeySubmit' value='Send'>Select Peer</button>

</body>
</html>
</code>```

答:
You were almost there, actually. Your buddyConn.on('data'... should be in the connect function using that function's argument name for the connection. Also, the second call to connect should not be in the #peerKeySubmit.on callback function. Here's the modified (working) code:

```<code>var peer = new Peer({
  key: 'lwjd5qra8257b9'
// I use my own API key for testing, this is the public PeerJS key
//you'll have to generate your own if this doesn't work.
});

peer.on('open', function(id) {
  $('body').append('<br/>Your personal peer ID is: ' + id + '<br/>Be careful who you share it with.');
});
peer.on('connection', connect);

function connect(succ) {
  conn = succ;
  conn.on('data', function (data) {
    console.log('Received from ' + conn.peer + ': ' + data);
  });

  //input changes on successful connect
  $('#peerKeyEnter').val(conn.peer);
  $('#peerKeyEnter').prop('disabled',true);
}

$(document).ready(function() {

  $('#peerKeySubmit').on('click', function() {
    var buddy = document.getElementById('peerKeyEnter').value;
    var buddyConn = peer.connect(buddy); //send connection request

    //sending data
    buddyConn.on('open', function() {
      buddyConn.send('this is supposed to work')
    });

  }); //end peerKeySubmit.click
}); //end doc.ready()
</code>```

Title: Receiving data through PeerJS

Body:
I'm working on a small PeerJS project, and I'm a little confused. I'm able to open a connection and confirm that the clients are connected, but I cannot figure out the proper method or syntax for receiving anything. Or perhaps I'm just missing something simple. I have tried so many variations trying to get this to work. JS and HTML below.

JS:

var peer = new Peer({
  key: 'lwjd5qra8257b9'
// I use my own API key for testing, this is the public PeerJS key
//you'll have to generate your own if this doesn't work.
});

peer.on('open', function(id) {
  $('body').append('
Your personal peer ID is: ' + id + '
Be careful who you share it with.');
});
peer.on('connection', connect);

function connect(succ) {
  conn = succ;
  //input changes on successful connect
  $('#peerKeyEnter').val(conn.peer);
  $('#peerKeyEnter').prop('disabled',true);
}

$(document).ready(function() {

  $('#peerKeySubmit').on('click', function() {
    var buddy = document.getElementById('peerKeyEnter').value;
    var buddyConn = peer.connect(buddy); //send connection request
    connect(buddyConn); //connect to peer

    //sending data
    buddyConn.on('open', function() {
      buddyConn.send('this is supposed to work')
    });

    //receiving data
    buddyConn.on('connection', function(conn) {
      buddyConn.on('data', function(data) {
        console.log(data);
      });
    });
  }); //end peerKeySubmit.click
}); //end doc.ready()

HTML:

<input type='text' id='peerKeyEnter' placeholder="Enter peer's ID"></input>
<button id='peerKeySubmit' value='Send'>Select Peer</button>

Body:
You were almost there, actually. Your buddyConn.on('data'... should be in the connect function using that function's argument name for the connection. Also, the second call to connect should not be in the #peerKeySubmit.on callback function. Here's the modified (working) code:

var peer = new Peer({
  key: 'lwjd5qra8257b9'
// I use my own API key for testing, this is the public PeerJS key
//you'll have to generate your own if this doesn't work.
});

peer.on('open', function(id) {
  $('body').append('<br/>Your personal peer ID is: ' + id + '<br/>Be careful who you share it with.');
});
peer.on('connection', connect);

function connect(succ) {
  conn = succ;
  conn.on('data', function (data) {
    console.log('Received from ' + conn.peer + ': ' + data);
  });

  //input changes on successful connect
  $('#peerKeyEnter').val(conn.peer);
  $('#peerKeyEnter').prop('disabled',true);
}

$(document).ready(function() {

  $('#peerKeySubmit').on('click', function() {
    var buddy = document.getElementById('peerKeyEnter').value;
    var buddyConn = peer.connect(buddy); //send connection request

    //sending data
    buddyConn.on('open', function() {
      buddyConn.send('this is supposed to work')
    });

  }); //end peerKeySubmit.click
}); //end doc.ready()


问:
How do I make my navigation dropdown activate on hover in Bootstrap 4?
I'm looking for a way to activate my navigation menu on hover on desktop.

I've found snippets for Bootstrap v3, but I've found none of those codes translate to v4.

Here is my nav HTML & CSS for http://beaudeelashbar.com:

```<code>    <nav class="navbar navbar-dark fixed-top scrolling-navbar">
    <div class="container">
        <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#collapseEx2" aria-controls="collapseEx2" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
        </button>
        <a class="navbar-brand" href="index.html">
        </a>
        <div class="collapse navbar-collapse" id="collapseEx2">
            <ul class="navbar-nav mr-auto">
                <li class="nav-item">
                    <a class="nav-link" href="http://beaudeelashbar.com/">Home</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="http://beaudeelashbar.com/about">About</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="http://beaudeelashbar.com/packages">Packages & Services</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="http://beaudeelashbar.com/faq">FAQ</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="http://beaudeelashbar.com/#contact">Contact</a>
                </li>
            </ul>
        </div>
    </div>
</nav>

.navbar:hover .nabvar-collapse {
display: block;
}

.navbar .navbar-collapse {
background-color: rgba(0, 0, 0, 0.2);
width: 200px;
float: right;
margin-top: 47px;
margin-right: -17px;
}

.navbar-dark .navbar-nav .nav-link {
color: #fff;
}

.nav-item {
padding-right: 15px;
}

.nav-link {
float: right;
}

.scrolling-navbar {
    -webkit-transition: background .5s ease-in-out, padding .5s ease-in-out;
    -moz-transition: background .5s ease-in-out, padding .5s ease-in-out;
    transition: background .5s ease-in-out, padding .5s ease-in-out;
    height: 55px;
    background-color: rgba(0, 0, 0, 0.2);
    box-shadow: none;
}

.top-nav-collapse {
background-color: transparent;
}
</code>```

答:
Try this code

```<code>button.navbar-toggler:hover ~ .navbar-collapse {
    display: block;
}
</code>```

better to try with
 and
 for dropdown because dropdown appears only when we hover the button element.That is not what we need. so it's better to create a dropdown using
 and
 elements.

Hope this works..

Body:
I'm looking for a way to activate my navigation menu on hover on desktop.

I've found snippets for Bootstrap v3, but I've found none of those codes translate to v4.

Here is my nav HTML & CSS for http://beaudeelashbar.com:

        <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#collapseEx2" aria-controls="collapseEx2" aria-expanded="false" aria-label="Toggle navigation">

        </button>

                    Home

                    About

                    Packages & Services

                    FAQ

                    Contact

.navbar:hover .nabvar-collapse {
display: block;
}

.navbar .navbar-collapse {
background-color: rgba(0, 0, 0, 0.2);
width: 200px;
float: right;
margin-top: 47px;
margin-right: -17px;
}

.navbar-dark .navbar-nav .nav-link {
color: #fff;
}

.nav-item {
padding-right: 15px;
}

.nav-link {
float: right;
}

.scrolling-navbar {
    -webkit-transition: background .5s ease-in-out, padding .5s ease-in-out;
    -moz-transition: background .5s ease-in-out, padding .5s ease-in-out;
    transition: background .5s ease-in-out, padding .5s ease-in-out;
    height: 55px;
    background-color: rgba(0, 0, 0, 0.2);
    box-shadow: none;
}

.top-nav-collapse {
background-color: transparent;
}

Body:
Try this code

button.navbar-toggler:hover ~ .navbar-collapse {
    display: block;
}

better to try with <ul> and <li> for dropdown because dropdown appears only when we hover the button element.That is not what we need. so it's better to create a dropdown using <ul> and <li> elements.

Hope this works..


问:
Understanding Rails validation: what does allow_blank do?
I'm quite new to Rails and found a little snippet to validate presence and uniqueness step by step: first check presence, then check uniqueness.

```<code>validates :email, :presence => true, :allow_blank => true, :uniqueness => { :case_sensitive => false }
</code>```

I'm a little bit confused about using presence => true and allow_blank => true together.

Without using allow_blank => true both rules will be checked at the same time and not step by step.

Why does allow_blank => true do this magic?

答:
from Rails annotation

```<code># * <tt>:allow_nil</tt> - Skip validation if the attribute is +nil+.
# * <tt>:allow_blank</tt> - Skip validation if the attribute is blank.
</code>```

so, it means when we use allow_blank on email, if the email is nil, only one error added to errors object, jump the uniqueness validates.

Body:
I'm quite new to Rails and found a little snippet to validate presence and uniqueness step by step: first check presence, then check uniqueness.

validates :email, :presence => true, :allow_blank => true, :uniqueness => { :case_sensitive => false }

I'm a little bit confused about using presence => true and allow_blank => true together.

Without using allow_blank => true both rules will be checked at the same time and not step by step.

Why does allow_blank => true do this magic?

Body:
from Rails annotation

# * <tt>:allow_nil</tt> - Skip validation if the attribute is +nil+.
# * <tt>:allow_blank</tt> - Skip validation if the attribute is blank.

so, it means when we use allow_blank on email, if the email is nil, only one error added to errors object, jump the uniqueness validates.


问:
#NAME? in every textbox of Access 2016 Form, SQL Server linked table
I have an access form with a fairly complex query displaying raw test values and the resulting test calculations on a large MS Access Form that was created in access 2007. Every once in a while my data entry guys are complaining that upon leaving and returning to their database form they see an error with text "This expression is typed incorrectly or it is too complex to be evaluated. For example, a numeric expression may contain too many complicated elements...". After this error appears every textbox is populated with the "#NAME?" error code.

I am curious if anyone has experience with this. I recently migrated the backend table from another MS Access database to SQL Server. My table has a primary key in SQL Server and also a timestamp column. Lastly, I have tried to reduce the size of the query that produces the calculations displayed on the form. On top of that not working, it previously worked  within Access , so I don't see how simply moving the table to SQL server would cause the size of the query to now be too much.

Any help is appreciated, thanks.

答:
This is a late response but I've recently experienced a similar issue and found it to be data type related.

Check if your SQL Server table's primary key data type is "bigint". If it is this may cause problems reading the data in Access.  Access 2016 supports large number types but it needs to be set in Options-->Current Database-->Data Type Support Options. Note that setting large number support will prevent your Access app from working in version prior to 2016.


问:
Why would SQL be very slow when doing updates?
Suddenly doing updates into a few tables have gotten 10 times slower than they used to be.  What are some good recommendations to determine root cause and optimization?  Could it be that indexing certain columns are causing updates to be slow?  Any other recommendations?

I guess more important than guesses would be help on the process of identifying the root cause or metrics around performance.

Is there anything in Fluent NHibernate that you can use to help identify the root cause of performance issues?

答:
First try updating your statistics.

Then, look into your indexing, and make sure you have only what you need. Additional indexes can most definitely slow down inserts.

Then, try rebuilding the indexes.

Without knowing the schema, query, or amount of data, it is hard to say more than that.


问:
using purrr to loop query a server and populate a column
I am trying to use purrr to populate a new column in a data frame.

The frame contains a list of endpoint from a server I then have a function that uses httr to get the endpoint status but I can't seem to get it to work?

example is:

```<code>require(tibble)
require(purrr)
require(httr)
require(RCurl)
require(dplyr)

example = tibble(
  processor = c('A', 'B', 'C'),
  code = c('s3zsf3', 'a2ssf3', 'g6zsf6')
  )

GetStatusOfProcessing <- function(identifier, tserver) {
      url = paste0( tserver,identifier )
      data = content(GET(url))
      data$runStatus # this is a string
}

server = 'http://localhost:8080/'

Output <- example %>%
  map(GetStatusOfProcessing(., server))

Expected_Output_example = tibble(
      processor = c('A', 'B', 'C'),
      code = c('s3zsf3', 'a2ssf3', 'g6zsf6'),
      Status = c('RUNNING', 'RUNNING', 'RUNNING')
    )
</code>```

How can I use map to properly feed in the row by row id or is that the wrong function to use?

答:
Maybe something like this:</p>

```<code>Output <- example %>%
            mutate(Status = map_chr2(processor, code, GetStatusOfProcessing))
</code>```

Body:
I am trying to use purrr to populate a new column in a data frame.

The frame contains a list of endpoint from a server I then have a function that uses httr to get the endpoint status but I can't seem to get it to work?

example is:

require(tibble)
require(purrr)
require(httr)
require(RCurl)
require(dplyr)

example = tibble(
  processor = c('A', 'B', 'C'),
  code = c('s3zsf3', 'a2ssf3', 'g6zsf6')
  )

GetStatusOfProcessing <- function(identifier, tserver) {
      url = paste0( tserver,identifier )
      data = content(GET(url))
      data$runStatus # this is a string
}

server = 'http://localhost:8080/'

Output <- example %>%
  map(GetStatusOfProcessing(., server))

Expected_Output_example = tibble(
      processor = c('A', 'B', 'C'),
      code = c('s3zsf3', 'a2ssf3', 'g6zsf6'),
      Status = c('RUNNING', 'RUNNING', 'RUNNING')
    )

How can I use map to properly feed in the row by row id or is that the wrong function to use?

Body:
Maybe something like this:

Output <- example %>%
            mutate(Status = map_chr2(processor, code, GetStatusOfProcessing))


问:
react:Uncaught DOMException: Failed to execute 'pushState' on 'History': A history state object with URL
I have a react project, I now open through webstorm no problem, but directly open the folder inside the index.html, the main page can be out, but a click will be being given, click on the link I used reactor。
Trouble who can help me solve, thank you！

Error message：

Uncaught DOMException: Failed to execute 'pushState' on 'History': A
  history state object with URL
  'file:///Users/qinchen/Desktop/change/dist/integralpage' cannot be
  created in a document with origin 'null' and URL
  'file:///Users/qinchen/Desktop/change/dist/index.html'.
      at finishTransition (file:///Users/qinchen/Desktop/change/dist/bundle.js:25897:24)
      at file:///Users/qinchen/Desktop/change/dist/bundle.js:13142:13
      at file:///Users/qinchen/Desktop/change/dist/bundle.js:13118:9
      at next (file:///Users/qinchen/Desktop/change/dist/bundle.js:25765:7)
      at Object.loopAsync (file:///Users/qinchen/Desktop/change/dist/bundle.js:25769:3)
      at confirmTransitionTo (file:///Users/qinchen/Desktop/change/dist/bundle.js:13104:17)
      at transitionTo (file:///Users/qinchen/Desktop/change/dist/bundle.js:13130:5)
      at Object.push (file:///Users/qinchen/Desktop/change/dist/bundle.js:13153:5)
      at Object.push (file:///Users/qinchen/Desktop/change/dist/bundle.js:13395:15)
      at Object.push (file:///Users/qinchen/Desktop/change/dist/bundle.js:6535:15)

答:
You cannot use pushState when loading up a local file (a file:/// URL in your browser), which is for security reasons. Instead, you have two options:

Use a Hash history instead. This will work fine on a local file.

Start up a simple web server to serve up your file instead. If you don't want to build a small server application, here is a list of simple ones. You can take your pick and they will all give you a http:// URL in your browser that supports the Browser history.


问:
How do I generate code in STM32 CUBEMX?
I have downloaded Keil and STM32 CUBEMX (Together with firmware library for my microcontroller).

I don't understand how do I put my c code to see what is really going on?
I tried connecting Keil with STM32 Cubemx when creatning new project, but when I go to device there is no STM32 Cube, what should I do?

答:
You can't just drop a preexisting project into CubeMX and expect it to sort out what you're trying to do - CubeMX is a code generator for initialization of the hardware, and that's it.

To do what you're trying to do, you need to configure the peripherals as you'd like for your project in CubeMX, have CubeMX generate the project from that (CubeMX can generate projects for a variety of IDEs, including Keil), and then open that project in your IDE and edit in the specifics of your project as you'd like, starting from the generated main function.

Remember to only modify the parts of the generated files between the "USER CODE" comment lines, and not modify those comments if you think you'll ever want to change the project settings you set up in CubeMX - the generator uses those comments to ensure that it doesn't overwrite user code while regenerating the project.

Title: How do I generate code in STM32 CUBEMX?


问:
system format error when converting to decimals
error code at: Decimal price = Decimal.Parse(txtprice.Text);

```<code>private void button1_Click(object sender, EventArgs e)
    {
        decimal height1 = decimal.Parse(txtnorthheight.Text);

        decimal length1 = decimal.Parse(txtnorthlength.Text);

        decimal area1 = height1 * length1;

        lblnortharea.Text = area1.ToString("n");

        decimal height2 = decimal.Parse(txtsouthheight.Text);

        decimal length2 = decimal.Parse(txtsouthlength.Text);

        decimal area2 = height2 * length2;

        lblsoutharea.Text = area2.ToString("n");

        decimal height3 = decimal.Parse(txteasthheight.Text);

        decimal length3 = decimal.Parse(txteasthlength.Text);

        decimal area3 = height3 * length3;

        lbleastarea.Text = area3.ToString("n");

        decimal height4 = decimal.Parse(txtwesthheight.Text);

        decimal length4 = decimal.Parse(txtwestlength.Text);

        decimal area4 = height4 * length4;

        lblwestharea.Text = area4.ToString("n");

        decimal height5 = decimal.Parse(txtwinheight.Text);

        decimal length5 = decimal.Parse(txtwinlength.Text);

        decimal area5 = height5 * length5;

        lblwinharea.Text = area5.ToString("n");

        decimal areatotal = (area1 + area2 + area3 + area4) - area5;

        lbltotalarea.Text = areatotal.ToString("n");

        decimal Heightt = (height1 + height2 + height3 + height4) - height5;
        decimal Legntht = (length1 + length2 + length3 + length4) - length5;

        Height2.Text = Heightt.ToString("n");
        Legnth.Text = Legntht.ToString("n");

        Decimal price = Decimal.Parse(txtprice.Text);

        Decimal undercoat = Decimal.Parse(txtunder.Text);

        decimal roomcost = (Heightt * Legntht) * price * undercoat;

        txtprice.Text = roomcost.ToString("c");

        decimal Vattotal = (25 % roomcost);

        lblvat.Text = Vattotal.ToString("c");

        Decimal vt = Vattotal + roomcost;

        lblbt.Text = vt.ToString("c");
    }
</code>```

the worked without issue but now that i am rebuilding the program due to some errors this line of code does not want to work. any ideas ?

if requested i can post the whole 269 lines of code and also the visual studio error code.

答:
Decimal.Parse(string s) throws a FormatException if the input string isn't in a format that can be parsed as a decimal.

You can use Decimal.TryParse(string s, out Decimal d) instead.

```<code>decimal d = 0;
if(Decimal.TryParse(txtnorthheight.Text, out d))
{
    // If the string could be parsed, d contains the value.
    // otherwise TryParse returns false.
}
</code>```

In order for that to be manageable you'd probably want to break your function down into smaller pieces and parse your inputs first. Otherwise the logic gets messy if there are multiple points throughout the method where you might have to exit because of invalid inputs.

Another approach is to use validation to ensure that only values of certain types can be entered. Here is some documentation on Windows Forms validation. (I can't tell for sure if you're using Forms or ASP.NET.)

Body:
error code at: Decimal price = Decimal.Parse(txtprice.Text);

private void button1_Click(object sender, EventArgs e)
    {
        decimal height1 = decimal.Parse(txtnorthheight.Text);

        decimal length1 = decimal.Parse(txtnorthlength.Text);

        decimal area1 = height1 * length1;

        lblnortharea.Text = area1.ToString("n");

        decimal height2 = decimal.Parse(txtsouthheight.Text);

        decimal length2 = decimal.Parse(txtsouthlength.Text);

        decimal area2 = height2 * length2;

        lblsoutharea.Text = area2.ToString("n");

        decimal height3 = decimal.Parse(txteasthheight.Text);

        decimal length3 = decimal.Parse(txteasthlength.Text);

        decimal area3 = height3 * length3;

        lbleastarea.Text = area3.ToString("n");

        decimal height4 = decimal.Parse(txtwesthheight.Text);

        decimal length4 = decimal.Parse(txtwestlength.Text);

        decimal area4 = height4 * length4;

        lblwestharea.Text = area4.ToString("n");

        decimal height5 = decimal.Parse(txtwinheight.Text);

        decimal length5 = decimal.Parse(txtwinlength.Text);

        decimal area5 = height5 * length5;

        lblwinharea.Text = area5.ToString("n");

        decimal areatotal = (area1 + area2 + area3 + area4) - area5;

        lbltotalarea.Text = areatotal.ToString("n");

        decimal Heightt = (height1 + height2 + height3 + height4) - height5;
        decimal Legntht = (length1 + length2 + length3 + length4) - length5;

        Height2.Text = Heightt.ToString("n");
        Legnth.Text = Legntht.ToString("n");

        Decimal price = Decimal.Parse(txtprice.Text);

        Decimal undercoat = Decimal.Parse(txtunder.Text);

        decimal roomcost = (Heightt * Legntht) * price * undercoat;

        txtprice.Text = roomcost.ToString("c");

        decimal Vattotal = (25 % roomcost);

        lblvat.Text = Vattotal.ToString("c");

        Decimal vt = Vattotal + roomcost;

        lblbt.Text = vt.ToString("c");
    }

the worked without issue but now that i am rebuilding the program due to some errors this line of code does not want to work. any ideas ?

if requested i can post the whole 269 lines of code and also the visual studio error code.

Body:
Decimal.Parse(string s) throws a FormatException if the input string isn't in a format that can be parsed as a decimal.

You can use Decimal.TryParse(string s, out Decimal d) instead.

decimal d = 0;
if(Decimal.TryParse(txtnorthheight.Text, out d))
{
    // If the string could be parsed, d contains the value.
    // otherwise TryParse returns false.
}

In order for that to be manageable you'd probably want to break your function down into smaller pieces and parse your inputs first. Otherwise the logic gets messy if there are multiple points throughout the method where you might have to exit because of invalid inputs.

Another approach is to use validation to ensure that only values of certain types can be entered. Here is some documentation on Windows Forms validation. (I can't tell for sure if you're using Forms or ASP.NET.)


问:
numbers not allowed (0-9) - Regex Expression in javascript
I want a regex pattern which will allow me any chars, but it will not allow (0-9) numbers?</p>

答: Something as simple as [a-z]+, or perhaps [\S]+, or even [a-zA-Z]+?

ContentLicense: CC BY-SA 4.0


问:
How do I forcefully close a connection from a connection pool when it's taking too much time to close?
There are times closing connections takes a lot of time, like more than 10 minutes upto 1 hour, or worse, even for indefinite time, depending on how heavy or slow the query was.

In a situation where the client cancels the query because it has been taking too much time, I would want to free up the underlying connection used as soon as possible.

I tried cancelling the PreparedStatement, closing it, then closing the resultset, and then finally closing the connection. Cancelling took almost instantly. Closing the PreparedStatement and ResultSet took too much time that I had to wrap it in a Callable with timeout to skip that process in due time and proceed with closing the connection itself. I haven't got any much luck on what else to try out.

How do I deal with this? I can't simply let the connections unclosed and I can't let the users wait for 10 minutes before they can make another similar query.

Also, what's causing the closure of connection to take too much time? Is there anything else I could do? Do you think Oracle query hints would help?

I'm using Oracle JDBC via thin type of driver by the way.

UPDATE:

Apparently, it's possible to close the connection forcefully by configuring TimeToLive property in the connectionCacheProperties which closes the connection for a specific amount of time. However, what I need is on as-needed basis. This is worth mentioning because this proves that it is possible to forcefully close it as the Connection Pool just did. In fact, I even got the following message on my logs.

```<code>ORA-01013: user requested cancel..
</code>```

答:
This is what we use at my POW instead of "grant alter system to $UID" as a SYS-owned procedure (simplified working version):

```<code>CREATE OR REPLACE procedure SYS.kill_session(in_sid varchar2)
as
  l_serial number;
  l_runsql varchar2(1000) := 'alter system kill session ''$1,$2'' immediate';
begin
  begin
  select serial# into l_serial from v$session where username =
  (
    SELECT USER FROM DUAL
  ) and sid=in_sid and rownum<=1;
  exception when no_data_found then
    raise_application_error( -20001, 'Kill candidate not found');
  end;
  l_runsql := replace( l_runsql, '$1', in_sid);
  l_runsql := replace( l_runsql, '$2', l_serial);
  execute immediate l_runsql;
end;
/
</code>```

This way you can only kill your own sessions.

Body:
There are times closing connections takes a lot of time, like more than 10 minutes upto 1 hour, or worse, even for indefinite time, depending on how heavy or slow the query was.

In a situation where the client cancels the query because it has been taking too much time, I would want to free up the underlying connection used as soon as possible.

I tried cancelling the PreparedStatement, closing it, then closing the resultset, and then finally closing the connection. Cancelling took almost instantly. Closing the PreparedStatement and ResultSet took too much time that I had to wrap it in a Callable with timeout to skip that process in due time and proceed with closing the connection itself. I haven't got any much luck on what else to try out.

How do I deal with this? I can't simply let the connections unclosed and I can't let the users wait for 10 minutes before they can make another similar query.

Also, what's causing the closure of connection to take too much time? Is there anything else I could do? Do you think Oracle query hints would help?

I'm using Oracle JDBC via thin type of driver by the way.

UPDATE:

Apparently, it's possible to close the connection forcefully by configuring TimeToLive property in the connectionCacheProperties which closes the connection for a specific amount of time. However, what I need is on as-needed basis. This is worth mentioning because this proves that it is possible to forcefully close it as the Connection Pool just did. In fact, I even got the following message on my logs.

ORA-01013: user requested cancel..

Body:
This is what we use at my POW instead of "grant alter system to $UID" as a SYS-owned procedure (simplified working version):

CREATE OR REPLACE procedure SYS.kill_session(in_sid varchar2)
as
  l_serial number;
  l_runsql varchar2(1000) := 'alter system kill session ''$1,$2'' immediate';
begin
  begin
  select serial# into l_serial from v$session where username =
  (
    SELECT USER FROM DUAL
  ) and sid=in_sid and rownum<=1;
  exception when no_data_found then
    raise_application_error( -20001, 'Kill candidate not found');
  end;
  l_runsql := replace( l_runsql, '$1', in_sid);
  l_runsql := replace( l_runsql, '$2', l_serial);
  execute immediate l_runsql;
end;
/

This way you can only kill your own sessions.


问:
How to not error on cmdlets that are missing
I have a lot of powershell scripts so I created a custom logging Powershell module with a couple of cmdlets. The problem is that we have had trouble getting all of the users to download and put the custom module in their PSModulePath.

Ideally I'd like the script to continue silently and not show any errors if the cmdlet cannot be found, but I haven't found a good way to do it. Right now we get messages like this:

```<code>C:> foo-bar
foo-bar : The term 'foo-bar' is not recognized as the name of a cmdlet, function, script file, or operable program...
</code>```

Setting ErrorActionPreference will suppress the message, but it also suppresses all other error messages which isn't desirable.

I could write a custom function in every script that checks to see if the module is loading before calling the custom cmdlets, but it seems like there should be a better way to do it.

答:
For a given cmdlet foo-bar, you can do the following, once, at the beginning of the script:

```<code>if (-not (Get-Command foo-bar -ErrorAction Ignore)) {
  # Define a dummy function that will be a no-op when invoked.
  function foo-bar { }
}
</code>```

All subsequent calls to foo-bar then either call the actual cmdlet, if available, or the dummy function, resulting in a quiet no-op.

Body:
I have a lot of powershell scripts so I created a custom logging Powershell module with a couple of cmdlets. The problem is that we have had trouble getting all of the users to download and put the custom module in their PSModulePath.

Ideally I'd like the script to continue silently and not show any errors if the cmdlet cannot be found, but I haven't found a good way to do it. Right now we get messages like this:

C:> foo-bar
foo-bar : The term 'foo-bar' is not recognized as the name of a cmdlet, function, script file, or operable program...

Setting ErrorActionPreference will suppress the message, but it also suppresses all other error messages which isn't desirable.

I could write a custom function in every script that checks to see if the module is loading before calling the custom cmdlets, but it seems like there should be a better way to do it.

Body:
For a given cmdlet foo-bar, you can do the following, once, at the beginning of the script:

if (-not (Get-Command foo-bar -ErrorAction Ignore)) {
  # Define a dummy function that will be a no-op when invoked.
  function foo-bar { }
}

All subsequent calls to foo-bar then either call the actual cmdlet, if available, or the dummy function, resulting in a quiet no-op.


问:
Canvas doesn't draw colors with an alpha as they supposed to be drawn
After days of trying, I am just frustrated.

I've wanted to make a simple app that draws a color gradient from completely transparent to white on top of a background.
For testing, I just used a background with black, white and some greys.

But when I started the app to see the result I saw this:

Some colors turn out to be darker or more colored than they should be. For example, the left bar should be completely white.

I quickly made an image that shows how it should look like:

This is the code in my draw function:

```<code>        for(int i = 0; i < 5; i++) {
            p.setARGB(255, (255/4*(4-i)), (255/4*(4-i)), (255/4*(4-i)));
            canvas.drawRect(canvas.getWidth()/5*i, 0, canvas.getWidth()/5*(i+1), canvas.getHeight(), p);
        }
        for(int i = 0; i < 256; i++) {
            p.setARGB(i, 255, 255, 255);
            canvas.drawRect(0, i*(canvas.getHeight()/256), canvas.getWidth(), (i+1)*(canvas.getHeight()/256), p);
        }
</code>```

What am I missing? Is this just how the Canvas works? How can I fix this so that it looks like my example I made in GIMP?

答:
(canvas.getHeight()/256) cause precision problem.

use float gHeight = canvas.getHeight() / 256f; instead of (canvas.getHeight()/256)

full code:

private Paint p = new Paint(Paint.ANTI_ALIAS_FLAG);

@Override
protected void onDraw(Canvas canvas) {
    for (int i = 0; i < 5; i++) {
        p.setARGB(255, (255 / 4 * (4 - i)), (255 / 4 * (4 - i)), (255 / 4 * (4 - i)));
        canvas.drawRect(canvas.getWidth() / 5 * i, 0, canvas.getWidth() / 5 * (i + 1), canvas.getHeight(), p);
    }
    float gHeight = canvas.getHeight() / 256f;
    for (int i = 0; i < 256; i++) {
        p.setARGB(i, 255, 255, 255);

        canvas.drawRect(0, i * gHeight, canvas.getWidth(), (i + 1) * gHeight, p);
    }
}
```

image compress cause some problem ,on phone everything is ok

Body:
After days of trying, I am just frustrated.

I've wanted to make a simple app that draws a color gradient from completely transparent to white on top of a background.
For testing, I just used a background with black, white and some greys.

But when I started the app to see the result I saw this:

Some colors turn out to be darker or more colored than they should be. For example, the left bar should be completely white.

I quickly made an image that shows how it should look like:

This is the code in my draw function:

        for(int i = 0; i < 5; i++) {
            p.setARGB(255, (255/4*(4-i)), (255/4*(4-i)), (255/4*(4-i)));
            canvas.drawRect(canvas.getWidth()/5*i, 0, canvas.getWidth()/5*(i+1), canvas.getHeight(), p);
        }
        for(int i = 0; i < 256; i++) {
            p.setARGB(i, 255, 255, 255);
            canvas.drawRect(0, i*(canvas.getHeight()/256), canvas.getWidth(), (i+1)*(canvas.getHeight()/256), p);
        }

What am I missing? Is this just how the Canvas works? How can I fix this so that it looks like my example I made in GIMP?

Body:
(canvas.getHeight()/256) cause precision problem.

use float gHeight = canvas.getHeight() / 256f; instead of (canvas.getHeight()/256)

full code:

private Paint p = new Paint(Paint.ANTI_ALIAS_FLAG);

@Override
protected void onDraw(Canvas canvas) {
    for (int i = 0; i < 5; i++) {
        p.setARGB(255, (255 / 4 * (4 - i)), (255 / 4 * (4 - i)), (255 / 4 * (4 - i)));
        canvas.drawRect(canvas.getWidth() / 5 * i, 0, canvas.getWidth() / 5 * (i + 1), canvas.getHeight(), p);
    }
    float gHeight = canvas.getHeight() / 256f;
    for (int i = 0; i < 256; i++) {
        p.setARGB(i, 255, 255, 255);

        canvas.drawRect(0, i * gHeight, canvas.getWidth(), (i + 1) * gHeight, p);
    }
}

image compress cause some problem ,on phone everything is ok


问:
How to remove blue underline under text in google chrome?
This only happens in Google chrome ,I am using chrome 17.0.928 version. This works fine in firefox , but blue underline in google chrome .

```<code>.thumbnail:hover{z-index: 50;text-decoration: none;position:relative;}
.thumbnail span{  position: absolute;background:#000;padding: 5px;left: -1000px;
 border: 0px solid #ddd;visibility: hidden;color: #fff;width:388px;height:190px;text-decoration: none;}
.thumbnail:hover span{ text-align:left;visibility: visible;top: 0;left: 110px;text- decoration:none;
 top:-120px;-webkit-box-shadow: 0 8px 6px -6px #aaa; -moz-box-shadow: 0 8px 6px -6px   #aaa;box-shadow: 0 8px 6px -6px #aaa;}
.hoverbold {
text-decoration: none;
font-family: verdana;
font-size: 11px;
color: #B09F6E;
}
</code>```

http://jsfiddle.net/NW8Nw/3/

答:
Well I had the same problem and since I couldn't find a possible solution I did this.

```<code>div {
      text-decoration:underline;
      text-decoration-color:white;
    }
</code>```

Here your text-decoration-color and background-color should be same thereby hiding the blue underline.
Hope this helps

Body:
This only happens in Google chrome ,I am using chrome 17.0.928 version. This works fine in firefox , but blue underline in google chrome .

.thumbnail:hover{z-index: 50;text-decoration: none;position:relative;}
.thumbnail span{  position: absolute;background:#000;padding: 5px;left: -1000px;
 border: 0px solid #ddd;visibility: hidden;color: #fff;width:388px;height:190px;text-decoration: none;}
.thumbnail:hover span{ text-align:left;visibility: visible;top: 0;left: 110px;text- decoration:none;
 top:-120px;-webkit-box-shadow: 0 8px 6px -6px #aaa; -moz-box-shadow: 0 8px 6px -6px   #aaa;box-shadow: 0 8px 6px -6px #aaa;}
.hoverbold {
text-decoration: none;
font-family: verdana;
font-size: 11px;
color: #B09F6E;
}

http://jsfiddle.net/NW8Nw/3/

Body:
Well I had the same problem and since I couldn't find a possible solution I did this.

div {
      text-decoration:underline;
      text-decoration-color:white;
    }

Here your text-decoration-color and background-color should be same thereby hiding the blue underline.
Hope this helps


问:
How can you safely pass a session variable to javascript?
I have this account balance variable:

```<code>$_SESSION["bitcoin-balance"] = 0;
</code>```

I need to pass it to a javascript function, which will append the variable in a URL to send to my RESTAPI.

```<code>function getAccountBalace(username, hash){
//Send to restapi
}
</code>```

How could I do this? Normally, I would just make PHP echo javascript code with the parameters, when the page loads, but I need this function to run when a user clicks a button; and I cannot have the web page to reload.

答:
Try this</p>

```<code><button onclick="myFunction('<?php echo $_SESSION["bitcoin-balance"]; ?>');" />
</code>```

Body:
I have this account balance variable:

$_SESSION["bitcoin-balance"] = 0;

I need to pass it to a javascript function, which will append the variable in a URL to send to my RESTAPI.

function getAccountBalace(username, hash){
//Send to restapi
}

How could I do this? Normally, I would just make PHP echo javascript code with the parameters, when the page loads, but I need this function to run when a user clicks a button; and I cannot have the web page to reload.

Body:
Try this

<button onclick="myFunction('<?php echo $_SESSION["bitcoin-balance"]; ?>');" />


问:
How to Get mac address in Universal Apps?
I need to get the MAC address in a Universal Windows Application.
   I searched for an equivalent code but I did not succeed.
   Could someone guide me how to do this?

Ricardo Souza.

答:
How to Get mac address in Universal Apps?

AFAIK, currently there is no API can get the local machine MAC address directly in UWP app. In Win32 application we use NetworkInterface.GetPhysicalAddress method which is currently not implemented in UWP. But it seems like it is plan to support UWP, details please reference this issue.

So, temporary for a workaround you may try to use the GetAdaptersAddresses method of PInvoke as @ChristophvanderFecht mentioned. For a  sample about GetAdaptersAddress you may reference this thread.


问:
react native 100+ items flatlist very slow performance
I have a list just simple text that rendering into flatlist on react native but I am experiencing very very slow performance which makes app unusable.

How can I solve this? My code is:

```<code><FlatList
  data={[{key: 'a'}, {key: 'b'} ... +400]}
  renderItem={({item}) => <Text>{item.key}</Text>}
/>
</code>```

答:
Here is my suggestions:

A. Avoid anonymous arrow function on renderItem props.

Move out the renderItem function to the outside of render function, so it won't recreate itself each time render function called.

B. Try add initialNumToRender prop on your FlatList

It will define how many items will be rendered for the first time, it could save some resources with lot of data.

C. Define the key prop on your Item Component

Simply it will avoid re-render on dynamically added/removed items with defined key on each item. Make sure it is unique, don't use index as the key! You can also using keyExtractor as an alternative.

D. Optional optimization

Try use getItemLayout to skip measurement of dynamic content. Also there is some prop called maxToRenderPerBatch, windowSize that you can use to limit how many items you will rendered. Refer to the official doc to VirtualizedList or FlatList.

E. Talk is Cheap, show me the code!

// render item function, outside from class's `render()`
const renderItem = ({ item }) => (<Text key={item.key}>{item.key}</Text>);

// we set the height of item is fixed
const getItemLayout = (data, index) => (
  {length: ITEM_HEIGHT, offset: ITEM_HEIGHT * index, index}
);

const items = [{ key: 'a' }, { key: 'b'}, ...+400];

function render () => (
  <FlatList
    data={items}
    renderItem={renderItem}
    getItemLayout={getItemLayout}
    initialNumToRender={5}
    maxToRenderPerBatch={10}
    windowSize={10}
  />
);```

Body:
I have a list just simple text that rendering into flatlist on react native but I am experiencing very very slow performance which makes app unusable.

How can I solve this? My code is:

<FlatList
  data={[{key: 'a'}, {key: 'b'} ... +400]}
  renderItem={({item}) => <Text>{item.key}</Text>}
/>


问:
Git Merge Resolution Version Explanation
This is a simple question, or so I would have thought before trying to find the answer and as such please someone explain this to me.

When you fetch from remote and merge in the changes, when there are conflicts it informs you of such and that the files require merge resolution. (This is in Git GUI)

I know that of the files that are conflicting, I want the copies that I have done work on prior to the merge are the ones that I want. And can see them as follows.

```<code><<<<<<< HEAD
+  Code that I have added
  =======
+  Code that I replaced
 >>>>>>> origin/master
</code>```

The question that I have is when I right click I get the options to:

Use Remote Version

Use Local Version

What I want to know is which direction of < or > applies to which version. As I have been in an instance which I had stashed some changes, done a fetch, then popped my changes and apparently my stashed changes became the remote version rather than the local version. And basically it's messing with my head and just want a crib sheet for knowing which option applies to which direction of angle brackets.

答:
The words HEAD and origin/master answer your question.

The first block of code (after <<<<<) pertains to the HEAD (latest commit in local branch). The second block of code pertains to your remote branch.

The angled brackets always indicate which commit the code relates to.

Body:
This is a simple question, or so I would have thought before trying to find the answer and as such please someone explain this to me.

When you fetch from remote and merge in the changes, when there are conflicts it informs you of such and that the files require merge resolution. (This is in Git GUI)

I know that of the files that are conflicting, I want the copies that I have done work on prior to the merge are the ones that I want. And can see them as follows.

<<<<<<>>>>>> origin/master

The question that I have is when I right click I get the options to:

Use Remote Version

Use Local Version

What I want to know is which direction of < or > applies to which version. As I have been in an instance which I had stashed some changes, done a fetch, then popped my changes and apparently my stashed changes became the remote version rather than the local version. And basically it's messing with my head and just want a crib sheet for knowing which option applies to which direction of angle brackets.


答:
Simply:

```<code>/^([^0-9]*)$/
</code>```

That pattern matches any number of characters that is not 0 through 9.

I recommend checking out http://regexpal.com/.  It will let you easily test out a regex.

Title: numbers not allowed (0-9) - Regex Expression in javascript

Body: I want a regex pattern which will allow me any chars, but it will not allow (0-9) numbers?

Body:
Simply:

/^([^0-9]*)$/

That pattern matches any number of characters that is not 0 through 9.

I recommend checking out http://regexpal.com/.  It will let you easily test out a regex.


问:
How to convert URL parameters to a JavaScript object?
I have a string like this:

```<code>abc=foo&def=%5Basf%5D&xyz=5
</code>```

How can I convert it into a JavaScript object like this?

```<code>{
  abc: 'foo',
  def: '[asf]',
  xyz: 5
}
</code>```

答:
```<code>//under ES6
const getUrlParamAsObject = (url = window.location.href) => {
    let searchParams = url.split('?')[1];
    const result = {};
    //in case the queryString is empty
    if (searchParams!==undefined) {
        const paramParts = searchParams.split('&');
        for(let part of paramParts) {
            let paramValuePair = part.split('=');
            //exclude the case when the param has no value
            if(paramValuePair.length===2) {
                result[paramValuePair[0]] = decodeURIComponent(paramValuePair[1]);
            }
        }

    }
    return result;
}
</code>```

Body:
I have a string like this:

abc=foo&def=%5Basf%5D&xyz=5

How can I convert it into a JavaScript object like this?

{
  abc: 'foo',
  def: '[asf]',
  xyz: 5
}