问:
I have a picture that when I drag it to the red circle it copies. I want it so it stays where it is copied, not snap to the upper-left corner
I have a picture that when I drag it to the red circle it copies. I want it so it stays where it is copied, not snap to the upper-left corner. How do I do this?

HTML:

```<code><span class="box" ondrop="drop(event)" ondragover="allowDrop(event)"></span>
<br />
<div id="picture" ondrop="drop(event)">
   <img src="https://www.w3schools.com/html/img_w3slogo.gif" draggable="true" ondragstart="drag(event)" id="drag1" width="88" height="31">
</div>
</code>```

CSS:

```<code>.box {
   display: block;
   height: 300px;
   width: 300px;
   background-color: red;
}
</code>```

JavaScript:

```<code>function allowDrop(ev) {
   ev.preventDefault();
}

function drag(ev) {
   ev.dataTransfer.setData("text", ev.target.id);
}

function drop(ev) {
   ev.preventDefault();
   var data = ev.dataTransfer.getData("text");
   var nodeCopy = document.getElementById(data).cloneNode(true);
   nodeCopy.id = "newId";
   ev.target.appendChild(nodeCopy);
}
</code>```

Or see a TryIt here: https://www.w3schools.com/code/tryit.asp?Filename=GBY2BVYBXUPW

答:
The events have variables you can use.

In this example im using x and y and im positioning the image with absolute position with this line of code

```<code> nodeCopy.setAttribute("style", "position:absolute; left:"+ ev.x +"px;top:"+ ev.y+"px");
</code>```

function allowDrop(ev) {
  ev.preventDefault();
}

function drag(ev) {
  ev.dataTransfer.setData("text", ev.target.id);
}

function drop(ev) {
  ev.preventDefault();
  var data = ev.dataTransfer.getData("text");
  var nodeCopy = document.getElementById(data);
  if (nodeCopy.classList.contains('insideBox')){
    nodeCopy.setAttribute("style", "position:absolute; left:"+ ev.x +"px;top:"+ ev.y+"px;transform:translate(-"+nodeCopy.width/2+"px,-"+nodeCopy.height/2+"px)");
    }
    else{
      nodeCopy=nodeCopy.cloneNode(true)
      nodeCopy.classList.add("insideBox");
      nodeCopy.id = "newId"+Math.random(100);
      nodeCopy.setAttribute("style", "position:absolute; left:"+ ev.x +"px;top:"+ ev.y+"px;transform:translate(-"+nodeCopy.width/2+"px,-"+nodeCopy.height/2+"px)");
      ev.target.appendChild(nodeCopy);
    }

}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>*{
  margin:0;
  padding:0;
}
.box {
  display: block;
  height: 300px;
  width: 300px;
  background-color: red;
}</code>```

```

Body:
I have a picture that when I drag it to the red circle it copies. I want it so it stays where it is copied, not snap to the upper-left corner. How do I do this?

HTML:

CSS:

.box {
   display: block;
   height: 300px;
   width: 300px;
   background-color: red;
}

JavaScript:

function allowDrop(ev) {
   ev.preventDefault();
}

function drag(ev) {
   ev.dataTransfer.setData("text", ev.target.id);
}

function drop(ev) {
   ev.preventDefault();
   var data = ev.dataTransfer.getData("text");
   var nodeCopy = document.getElementById(data).cloneNode(true);
   nodeCopy.id = "newId";
   ev.target.appendChild(nodeCopy);
}

Or see a TryIt here: https://www.w3schools.com/code/tryit.asp?Filename=GBY2BVYBXUPW

Body:
The events have variables you can use.

In this example im using x and y and im positioning the image with absolute position with this line of code

 nodeCopy.setAttribute("style", "position:absolute; left:"+ ev.x +"px;top:"+ ev.y+"px");

function allowDrop(ev) {
  ev.preventDefault();
}

function drag(ev) {
  ev.dataTransfer.setData("text", ev.target.id);
}

function drop(ev) {
  ev.preventDefault();
  var data = ev.dataTransfer.getData("text");
  var nodeCopy = document.getElementById(data);
  if (nodeCopy.classList.contains('insideBox')){
    nodeCopy.setAttribute("style", "position:absolute; left:"+ ev.x +"px;top:"+ ev.y+"px;transform:translate(-"+nodeCopy.width/2+"px,-"+nodeCopy.height/2+"px)");
    }
    else{
      nodeCopy=nodeCopy.cloneNode(true)
      nodeCopy.classList.add("insideBox");
      nodeCopy.id = "newId"+Math.random(100);
      nodeCopy.setAttribute("style", "position:absolute; left:"+ ev.x +"px;top:"+ ev.y+"px;transform:translate(-"+nodeCopy.width/2+"px,-"+nodeCopy.height/2+"px)");
      ev.target.appendChild(nodeCopy);
    }

}

*{
  margin:0;
  padding:0;
}
.box {
  display: block;
  height: 300px;
  width: 300px;
  background-color: red;
}

<span class="box" ondrop="drop(event)" ondragover="allowDrop(event)"></span>
 <br />
  <div id="picture" ondrop="drop(event)">
      <img src="https://www.w3schools.com/html/img_w3slogo.gif" draggable="true" ondragstart="drag(event)" id="drag1" width="88" height="31">
  </div>


来源: stackexchange

问:
Problem in calculating the symmetric normalised laplacian matrix
I found some problems in calculating the symmetric normalised laplacian matrix in python.
Suppose to have the matrix S and its diagonal degree matrix D:

```<code>    [ [ 1 , 0.5, 0.2]        [ [1.7, 0, 0 ]
S =   [0.5,  1 , 0.5]     D =  [ 0 , 2, 0 ]
      [0.2, 0.5,  1 ] ]        [ 0 , 0,1.7] ]
</code>```

When calculating L as

I obtain this result:

```<code>       [[ 0.41176471 -0.27116307 -0.11764706]
    L = [-0.27116307  0.5        -0.27116307]
        [-0.11764706 -0.27116307  0.41176471]]
</code>```

Using this code:

```<code>S = np.array([[1,0.5,0.2],[0.5,1,0.5],[0.2,0.5,1]])

print("Similiarity Matrix: \n",S)
print("\n\n")

D = np.zeros((len(S), len(S)))
#H = np.sum(G[0])
for id, x in enumerate(S):
    D[id][id] = np.sum(x)

I = np.identity(len(S))

L = I - ((sqrtm(inv(D))).dot(S)).dot(sqrtm(inv(D)))
print("\n\n")
print("Laplacian normalized: \n",L)
</code>```

This differ from using the function csgraph.laplacian(S, normed=True) that return:

```<code>       [[[ 1.        -0.5976143  -0.28571429]
    L = [-0.5976143   1.         -0.5976143 ]
        [-0.28571429 -0.5976143   1.        ]]
</code>```

why this happen? Am i doing something wrong?

答:
I noticed that the ratio between the unnormalized and normalized matrixes returned by csgraph.laplacian is closely related to the ratio of the unnormalized matrix and your L:

```<code>In [20]: csgraph.laplacian(S, normed=False) / L - 1
Out[20]:
array([[0.7       , 0.84390889, 0.7       ],
       [0.84390889, 1.        , 0.84390889],
       [0.7       , 0.84390889, 0.7       ]])

In [21]: csgraph.laplacian(S, normed=False) / csgraph.laplacian(S, normed=True)
Out[21]:
array([[0.7       , 0.83666003, 0.7       ],
       [0.83666003, 1.        , 0.83666003],
       [0.7       , 0.83666003, 0.7       ]])
</code>```

0.84390889 ≠ 0.83666003 but other numbers match. Could the difference be simply due to normalization?

ContentLicense: CC BY-SA 4.0

Body:
I found some problems in calculating the symmetric normalised laplacian matrix in python.
Suppose to have the matrix S and its diagonal degree matrix D:

    [ [ 1 , 0.5, 0.2]        [ [1.7, 0, 0 ]
S =   [0.5,  1 , 0.5]     D =  [ 0 , 2, 0 ]
      [0.2, 0.5,  1 ] ]        [ 0 , 0,1.7] ]

When calculating L as

I obtain this result:

       [[ 0.41176471 -0.27116307 -0.11764706]
    L = [-0.27116307  0.5        -0.27116307]
        [-0.11764706 -0.27116307  0.41176471]]

Using this code:

S = np.array([[1,0.5,0.2],[0.5,1,0.5],[0.2,0.5,1]])

print("Similiarity Matrix: \n",S)
print("\n\n")

D = np.zeros((len(S), len(S)))
#H = np.sum(G[0])
for id, x in enumerate(S):
    D[id][id] = np.sum(x)

I = np.identity(len(S))

L = I - ((sqrtm(inv(D))).dot(S)).dot(sqrtm(inv(D)))
print("\n\n")
print("Laplacian normalized: \n",L)

This differ from using the function csgraph.laplacian(S, normed=True) that return:

       [[[ 1.        -0.5976143  -0.28571429]
    L = [-0.5976143   1.         -0.5976143 ]
        [-0.28571429 -0.5976143   1.        ]]

why this happen? Am i doing something wrong?

Body:
I noticed that the ratio between the unnormalized and normalized matrixes returned by csgraph.laplacian is closely related to the ratio of the unnormalized matrix and your L:

In [20]: csgraph.laplacian(S, normed=False) / L - 1
Out[20]:
array([[0.7       , 0.84390889, 0.7       ],
       [0.84390889, 1.        , 0.84390889],
       [0.7       , 0.84390889, 0.7       ]])

In [21]: csgraph.laplacian(S, normed=False) / csgraph.laplacian(S, normed=True)
Out[21]:
array([[0.7       , 0.83666003, 0.7       ],
       [0.83666003, 1.        , 0.83666003],
       [0.7       , 0.83666003, 0.7       ]])

0.84390889 ≠ 0.83666003 but other numbers match. Could the difference be simply due to normalization?


答:
You're adding a new line inside the inner for loop which is actually required after it. I've modified your code as follows:</p>

```<code>for (row in 0 until board.size) {
    if(row % 3 == 0 && row != 0) {
        println(" - - - - - - - - - " )
    }
    for(col in 0 until board.size) {
        if(col % 3 == 0 && col != 0) {
            print(" |")
        }
        print(" " +board[row][col])
    }
    println()
}
</code>```

Title: Printing a simple sudoku board array

Body:
So my code is currently missing the 8th index of the array and pushing it down 1 row. I'm new to kotlin but I honestly have no clue why its doing that.

fun main() {
    val board = arrayOf(
        arrayOf(7, 8, 0, 4, 0, 0, 1, 2, 0),
        arrayOf(6, 0, 0, 0, 7, 5, 0, 0, 9),
        arrayOf(0, 0, 0, 6, 0, 1, 0, 7, 8),
        arrayOf(0, 0, 7, 0, 4, 0, 2, 6, 0),
        arrayOf(0, 0, 1, 0, 5, 0, 9, 3, 0),
        arrayOf(9, 0, 4, 0, 6, 0, 0, 0, 5),
        arrayOf(0, 7, 0, 3, 0, 0, 0, 1, 2),
        arrayOf(1, 2, 0, 0, 0, 7, 4, 0, 0),
        arrayOf(0, 4, 9, 2, 0, 6, 0, 0, 7)
    )
    for (row in 0 until board.size) {
        if(row % 3 == 0 && row != 0) {
        println(" - - - - - - - - - " )
        }
            for(col in 0 until board.size) {
               if(col == 8){
                    println(" ")
                }
                if(col % 3 == 0 && col != 0) {
                print(" |")
                }
                print(" ")
                print(board[row][col])
            }
    }
}

With the output being

7 8 0 | 4 0 0 | 1 2
 0 6 0 0 | 0 7 5 | 0 0
 9 0 0 0 | 6 0 1 | 0 7
 8 - - - - - - - - -
 0 0 7 | 0 4 0 | 2 6
 0 0 0 1 | 0 5 0 | 9 3
 0 9 0 4 | 0 6 0 | 0 0
 5 - - - - - - - - -
 0 7 0 | 3 0 0 | 0 1
 2 1 2 0 | 0 0 7 | 4 0
 0 0 4 9 | 2 0 6 | 0 0
 7

Body:
You're adding a new line inside the inner for loop which is actually required after it. I've modified your code as follows:

for (row in 0 until board.size) {
    if(row % 3 == 0 && row != 0) {
        println(" - - - - - - - - - " )
    }
    for(col in 0 until board.size) {
        if(col % 3 == 0 && col != 0) {
            print(" |")
        }
        print(" " +board[row][col])
    }
    println()
}


问:
How does the client knows which transport protocol to use?
Let's assume that I start a server at one of the computers in my private network (192.168.10.10:9900).

Now when making a request from some other computer in the same network, how does the client computer (OS?) knows which protocol to use / which protocol the server follows ? [TCP or UDP]

EDIT: As mentioned in the answers, I was basically looking for a default protocol which will be used by the client in the absence of any transport protocol information.

答:
TCP / UDP protocols work at the transport layer level (TCP / IP MODEL) and its main difference is that TCP has a method to ensure the arrival of messages while UDP is lighter because of its virtue is to be faster in Information delivery. The use of one protocol or another is always defined by the application that will use it.

So the reference you put on the private server with ip: port 192.168.10.10:9900 is very vague to be more precise we could say that we have an Apache web server running on the ip: port 192.168.10.10:9900 (the port for default is 80 when installing the server, but it can be changed in the configuration).

Now the web servers (apache, IIS, etc.) work using the TCP protocol because when a client (computer, cell phone, etc.) consults a page through a browser (Chrome, Firefox, etc.), the ideal thing is that all the website and not just some pieces. This is why this type of servers chose and use this protocol in the first instance since they seek that in the end the result is that the user obtains the complete page regardless of whether a few more milliseconds are sacrificed in the validations involved in using TPC.

Now going to the client side. The user when visiting a web page from any browser (Chrome, Firefox, etc.) will use TCP since this protocol is already configured in the browser to send the query messages and subsequently receive the messages with the same form Website information.

Now this behavior is going to be repeated for any client / server application. For example, to change the type of application on the UDP side, we can observe the operation of DHCP services which are used to receive an IP when connecting any device to a Wi-Fi network. In this case, this service seeks to be as fast as possible (instead of the most reliable) since you want the device to connect as quickly as possible to the network, so use the UDP protocol and in this case any equipment when connecting To a WIFI network you will send your messages using this protocol.

Finally, if you want to know promptly about the type of TCP / UDP protocol used by a specific application, you can search on the Wireshark application which allows you to scan the messages that leave the device or show the protocol used in the different layers of the application.


问:
Conversion between Cartesian vs. Polar Coordinates. Hoping the result is positive
I have several points that I need to covert them from Cartesian to Polar Coordinates. But for some points, the results I got were negative values.

For example, the origin or the center of the system is (50,50), and the point I want to covert is (10, 43). The angle I got from my code is -170.07375449, but I wish the angle is 189.92624551. (I hope all of the angles after conversion are between 0~360 degree)

How I fix this?

Thanks!!!

```<code>import numpy as np
points = np.array([(10, 43), (10, 44), (10, 45), (10, 46), (10, 47)])
#Set the center (origin) at (50, 50). Not (0, 0)
def cart_to_pol(coords, center = [50,50], deg = True):
    complex_format = np.array(coords, dtype = float).view(dtype = np.complex) -\
                     np.array(center, dtype = float).view(dtype = np.complex)
    # return np.abs(complex_format).squeeze(), np.angle(complex_format, deg = deg).squeeze()
    return np.angle(complex_format, deg=deg).squeeze()

print(cart_to_pol(points))
</code>```

答:
Combining some of the other solutions here...

If you specify the origin and/or points as float, you can us a view to operate on them as complex numbers, and then simply return the angle modulo 360 degrees:

```<code>points = points - origin
np.angle(points.view(np.complex), deg=True) % 360
>>> array([[189.92624551],
           [188.53076561],
           [187.12501635],
           [185.71059314],
           [184.28915333]])
</code>```

Or, with in-place operations, assuming that points is already floating point:

```<code>np.subtract(points, origin, out=points)
v = points.view(np.complex)
np.arctan2(v.imag, v.real, out=v.real)
np.degrees(v.real, out=v.real)
np.mod(v.real, 360, out=v.real)
print(points[0])  # or print(v.real)
>>> array([[189.92624551],
           [188.53076561],
           [187.12501635],
           [185.71059314],
           [184.28915333]])
</code>```

In this case we can't use angle because there is no out option, but we can compute arctan2 in-place in points[0], via our view. This uses no more memory than the original (floating point) points array, and while I didn't time it, should not take more operations to compute.

Body:
I have several points that I need to covert them from Cartesian to Polar Coordinates. But for some points, the results I got were negative values.

For example, the origin or the center of the system is (50,50), and the point I want to covert is (10, 43). The angle I got from my code is -170.07375449, but I wish the angle is 189.92624551. (I hope all of the angles after conversion are between 0~360 degree)

How I fix this?

Thanks!!!

import numpy as np
points = np.array([(10, 43), (10, 44), (10, 45), (10, 46), (10, 47)])
#Set the center (origin) at (50, 50). Not (0, 0)
def cart_to_pol(coords, center = [50,50], deg = True):
    complex_format = np.array(coords, dtype = float).view(dtype = np.complex) -\
                     np.array(center, dtype = float).view(dtype = np.complex)
    # return np.abs(complex_format).squeeze(), np.angle(complex_format, deg = deg).squeeze()
    return np.angle(complex_format, deg=deg).squeeze()

print(cart_to_pol(points))

Body:
Combining some of the other solutions here...

If you specify the origin and/or points as float, you can us a view to operate on them as complex numbers, and then simply return the angle modulo 360 degrees:

points = points - origin
np.angle(points.view(np.complex), deg=True) % 360
>>> array([[189.92624551],
           [188.53076561],
           [187.12501635],
           [185.71059314],
           [184.28915333]])

Or, with in-place operations, assuming that points is already floating point:

np.subtract(points, origin, out=points)
v = points.view(np.complex)
np.arctan2(v.imag, v.real, out=v.real)
np.degrees(v.real, out=v.real)
np.mod(v.real, 360, out=v.real)
print(points[0])  # or print(v.real)
>>> array([[189.92624551],
           [188.53076561],
           [187.12501635],
           [185.71059314],
           [184.28915333]])

In this case we can't use angle because there is no out option, but we can compute arctan2 in-place in points[0], via our view. This uses no more memory than the original (floating point) points array, and while I didn't time it, should not take more operations to compute.


问:
Workaround to "selectFiles" function call on Flash object
I'm more of a server-side and javascript programmer. I have never done much with Flash.

I have a robust html form based on flash based swfuploader and I need to test it with Selenium 2 / WebDriver.

The problem is, that

```<code>movieContent.CallFunction('<invoke name="selectFiles" returntype="javascript">' + __flash__argumentsToXML(argumentArray, 0) + '</invoke>');
</code>```

is not supported in Flash 10 ...

What are we supposed to do ? If it was possible I could js.executeScript(script);

But now I have to do some sort of movieContent.click() in my java junit/selenium tests but it doesn't trigger the select file window, it doesn't do anything.

It is possible to move the mouse to specified co-ordinates and click using the MoveToOffsetAction, but I didn't manage to do that with FirefoxDriver neither chromeDriver 2.0b3 ...

答:
This is a security feature to prevent a website from accessing the local client side file system. The file system and only be accessed with with a user interaction in the stack trace. IE: a mouse click.

Taking control of the mouse would also be a security violation.

You best bet would be to initiate selenium from the flash function with your onclick event.

This function would first allow you to select the "test" files to upload and then have the function trigger selenium tests.

ContentLicense: CC BY-SA 3.0

Body:
I'm more of a server-side and javascript programmer. I have never done much with Flash.

I have a robust html form based on flash based swfuploader and I need to test it with Selenium 2 / WebDriver.

The problem is, that

movieContent.CallFunction('<invoke name="selectFiles" returntype="javascript">' + __flash__argumentsToXML(argumentArray, 0) + '</invoke>');

is not supported in Flash 10 ...

What are we supposed to do ? If it was possible I could js.executeScript(script);

But now I have to do some sort of movieContent.click() in my java junit/selenium tests but it doesn't trigger the select file window, it doesn't do anything.

It is possible to move the mouse to specified co-ordinates and click using the MoveToOffsetAction, but I didn't manage to do that with FirefoxDriver neither chromeDriver 2.0b3 ...


问:
Where do Internal testers download Google Play Android apps?
I thought I need just this link https://play.google.com/store/apps/details?id=com.here.myapp.name to download an app from Play Store, but when I click on it from tester account (which in tester list) I can only see

答:
Here's how I found it (with help from Scar Coder's answer)

Log into the Google Play Console and select the app from the list, then click the App releases option in the left sidebar, then click the 'Manage' button for your internal test release:

Expand the 'Manage testers area'

Copy the Opt-in URL:


问:
apply uipangesture to uitextfield
My swift code below applies a pangesture to a textfield that's it. The problem is when I type something into the textfield. The textfield goes back to its orginal constraind position. I just don't want it to revert when text is typed into the textfield. This is a constraint problem. If I remove the constraints I want it to. So to see this effect just copy the code into Xcode and apply storyboard constraints and you will see what I mean.</p>

```<code>import UIKit
class fullScreen : UIViewController {

@IBOutlet var i : UItextField!

var g11 = UIPanGestureRecognizer()

override func viewDidLoad() {

    g11 = UIPanGestureRecognizer(target: self, action: #selector(fullScreen.g1Method))

    i.isUserInteractionEnabled = true

    i.addGestureRecognizer(g11)

}

@objc func g1Method(_ sender: UIPanGestureRecognizer){

let tranistioon = sender.translation(in: self.view)
sender.view!.center = CGPoint(x: sender.view!.center.x + tranistioon.x, y: sender.view!.center.y + tranistioon.y)
sender.setTranslation(CGPoint.zero,in: self.view)    }

}
</code>```

答:
The problem you're running into is that the Storyboard constraints are remaining active with no changes to the constant field of the class object.  Here's how to solve it:

I added two IBOutlet references to the constraints in question on the storyboard:

```<code>@IBOutlet var leadingConstraint: NSLayoutConstraint!
@IBOutlet var topConstraint: NSLayoutConstraint!
</code>```

Additionally, right below those constraints, I added a reference for the textField origin like so:
var textFieldOrigin = CGPoint.zero

Finally, I changed the gesture recognizer method to differentiate between the states of the UIPanGestureRecognizer.  Here's what I did:

```<code>    @objc func g1Method(_ sender: UIPanGestureRecognizer) {
        if sender.state == .began {
            textFieldOrigin = sender.location(in: i)
        } else if sender.state == .ended {
            topConstraint.constant = i.frame.origin.y - i.frame.height
            leadingConstraint.constant = i.frame.origin.x
            topConstraint.isActive = true
            leadingConstraint.isActive = true
        } else {
            let location = sender.location(in: view)
            i.frame.origin = CGPoint(x: location.x - textFieldOrigin.x, y: location.y - textFieldOrigin.y)
            topConstraint.isActive = false
            leadingConstraint.isActive = false
        }
    }
</code>```

The key points in this code is turning off the constraints, updating their constants, and then turning them back on after the gesture recognizer is complete.

Title: apply uipangesture to uitextfield

Body:
My swift code below applies a pangesture to a textfield that's it. The problem is when I type something into the textfield. The textfield goes back to its orginal constraind position. I just don't want it to revert when text is typed into the textfield. This is a constraint problem. If I remove the constraints I want it to. So to see this effect just copy the code into Xcode and apply storyboard constraints and you will see what I mean.

import UIKit
class fullScreen : UIViewController {

@IBOutlet var i : UItextField!

var g11 = UIPanGestureRecognizer()

override func viewDidLoad() {

    g11 = UIPanGestureRecognizer(target: self, action: #selector(fullScreen.g1Method))

    i.isUserInteractionEnabled = true

    i.addGestureRecognizer(g11)

}

@objc func g1Method(_ sender: UIPanGestureRecognizer){

let tranistioon = sender.translation(in: self.view)
sender.view!.center = CGPoint(x: sender.view!.center.x + tranistioon.x, y: sender.view!.center.y + tranistioon.y)
sender.setTranslation(CGPoint.zero,in: self.view)    }

}

Body:
The problem you're running into is that the Storyboard constraints are remaining active with no changes to the constant field of the class object.  Here's how to solve it:

I added two IBOutlet references to the constraints in question on the storyboard:

@IBOutlet var leadingConstraint: NSLayoutConstraint!
@IBOutlet var topConstraint: NSLayoutConstraint!

Additionally, right below those constraints, I added a reference for the textField origin like so:
var textFieldOrigin = CGPoint.zero

Finally, I changed the gesture recognizer method to differentiate between the states of the UIPanGestureRecognizer.  Here's what I did:

    @objc func g1Method(_ sender: UIPanGestureRecognizer) {
        if sender.state == .began {
            textFieldOrigin = sender.location(in: i)
        } else if sender.state == .ended {
            topConstraint.constant = i.frame.origin.y - i.frame.height
            leadingConstraint.constant = i.frame.origin.x
            topConstraint.isActive = true
            leadingConstraint.isActive = true
        } else {
            let location = sender.location(in: view)
            i.frame.origin = CGPoint(x: location.x - textFieldOrigin.x, y: location.y - textFieldOrigin.y)
            topConstraint.isActive = false
            leadingConstraint.isActive = false
        }
    }

The key points in this code is turning off the constraints, updating their constants, and then turning them back on after the gesture recognizer is complete.


问:
kivy.uix.screenmanager.ScreenManagerException: ScreenManager accepts only Screen widget
I am trying to create a splash screen.

Here are the codes.

```<code>from kivy.app import App
from kivy.uix.image import Image
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.animation import Animation

class ScreenOne(Screen):

        wing1 = Image(source="F:\PyCharm Python Works\Kivy Test\opencityicon.png", pos=(0, 0), opacity=0)
        anim1 = Animation(duration=4, opacity=1)
        anim1.start(wing1)

class ScreenTwo(Screen):

        wing = Image(source="F:\PyCharm Python Works\Kivy Test\opencityicon.png", pos=(0, 0), opacity=1)
        animation = Animation(duration=2, opacity=0)
        animation.start(wing)

sm = ScreenManager()
sm.add_widget(ScreenOne)
sm.add_widget(ScreenTwo)
sm.current = ScreenOne

class Arge(App):

    def build(self):
        pass

if __name__ == "__main__":
    Arge().run()
</code>```

error:

```<code>[INFO   ] [Logger      ] Record log in C:\Users\kanna\.kivy\logs\kivy_20-02-16_16.txt
[INFO   ] [deps        ] Successfully imported "kivy_deps.gstreamer" 0.2.0
[INFO   ] [deps        ] Successfully imported "kivy_deps.glew" 0.2.0
[INFO   ] [deps        ] Successfully imported "kivy_deps.sdl2" 0.1.23
[INFO   ] [Kivy        ] v1.11.1
[INFO   ] [Kivy        ] Installed at "F:\Python Kivy\lib\site-packages\kivy\__init__.py"
[INFO   ] [Python      ] v3.7.6 (tags/v3.7.6:43364a7ae0, Dec 18 2019, 23:46:00) [MSC v.1916 32 bit (Intel)]
[INFO   ] [Python      ] Interpreter at "F:\Python Kivy\Scripts\python.exe"
[INFO   ] [Factory     ] 184 symbols loaded
[INFO   ] [Image       ] Providers: img_tex, img_dds, img_sdl2, img_gif (img_pil, img_ffpyplayer ignored)
[INFO   ] [Window      ] Provider: sdl2
[INFO   ] [GL          ] Using the "OpenGL" graphics system
[INFO   ] [GL          ] GLEW initialization succeeded
[INFO   ] [GL          ] Backend used <glew>
[INFO   ] [GL          ] OpenGL version <b'4.6.0 - Build 26.20.100.7262'>
[INFO   ] [GL          ] OpenGL vendor <b'Intel'>
[INFO   ] [GL          ] OpenGL renderer <b'Intel(R) UHD Graphics 630'>
[INFO   ] [GL          ] OpenGL parsed version: 4, 6
[INFO   ] [GL          ] Shading version <b'4.60 - Build 26.20.100.7262'>
[INFO   ] [GL          ] Texture max size <16384>
[INFO   ] [GL          ] Texture max units <32>
[INFO   ] [Window      ] auto add sdl2 input provider
[INFO   ] [Window      ] virtual keyboard not allowed, single mode, not docked
[INFO   ] [GL          ] NPOT texture support is available
 Traceback (most recent call last):
   File "F:/PyCharm Python Works/Kivy Test/splashscreen.py", line 25, in <module>
     sm.add_widget(ScreenOne)
   File "F:\Python Kivy\lib\site-packages\kivy\uix\screenmanager.py", line 979, in add_widget
     'ScreenManager accepts only Screen widget.')
 kivy.uix.screenmanager.ScreenManagerException: ScreenManager accepts only Screen widget.
</code>```

This is the error log. Why does it shows like this. I tried editing but it doesn't work at all.
So given the code that it doesn't working when edited.
Thanks in advance.
I tried using the Animation only. but it doesn't work also.

答:
Your code has the following problems:

ScreenManager expects Screen type objects, does not wait for the Screen class.

A name must be set for each screen and that name must be passed to current.

The Image must be placed inside the screen through a layout.

The animation must be started in the on_enter method that is executed when the screen is displayed.

The build method of the App must return a widget.

If you want 2 animations sequentially then you must use the "+" operator.

Considering the above the solution is:

import os

from kivy.app import App

from kivy.uix.image import Image
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.screenmanager import ScreenManager, Screen

from kivy.animation import Animation

current_dir = os.path.dirname(os.path.realpath(__file__))

class ScreenOne(Screen):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.img = Image(source=os.path.join(current_dir, "opencityicon.png"))
        box_layout = BoxLayout()
        self.add_widget(box_layout)
        box_layout.add_widget(self.img)

    def on_enter(self):
        self.img.opacity = 0
        animation = Animation(duration=4, opacity=1) + Animation(duration=4, opacity=0)
        animation.start(self.img)

sm = ScreenManager()
sm.add_widget(ScreenOne(name="screen_one"))
sm.current = "screen_one"

class Arge(App):
    def build(self):
        return sm

if __name__ == "__main__":
    Arge().run()
```

Body:
I am trying to create a splash screen.

Here are the codes.

from kivy.app import App
from kivy.uix.image import Image
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.animation import Animation

class ScreenOne(Screen):

        wing1 = Image(source="F:\PyCharm Python Works\Kivy Test\opencityicon.png", pos=(0, 0), opacity=0)
        anim1 = Animation(duration=4, opacity=1)
        anim1.start(wing1)

class ScreenTwo(Screen):

        wing = Image(source="F:\PyCharm Python Works\Kivy Test\opencityicon.png", pos=(0, 0), opacity=1)
        animation = Animation(duration=2, opacity=0)
        animation.start(wing)

sm = ScreenManager()
sm.add_widget(ScreenOne)
sm.add_widget(ScreenTwo)
sm.current = ScreenOne

class Arge(App):

    def build(self):
        pass

if __name__ == "__main__":
    Arge().run()

error:

[INFO   ] [Logger      ] Record log in C:\Users\kanna\.kivy\logs\kivy_20-02-16_16.txt
[INFO   ] [deps        ] Successfully imported "kivy_deps.gstreamer" 0.2.0
[INFO   ] [deps        ] Successfully imported "kivy_deps.glew" 0.2.0
[INFO   ] [deps        ] Successfully imported "kivy_deps.sdl2" 0.1.23
[INFO   ] [Kivy        ] v1.11.1
[INFO   ] [Kivy        ] Installed at "F:\Python Kivy\lib\site-packages\kivy\__init__.py"
[INFO   ] [Python      ] v3.7.6 (tags/v3.7.6:43364a7ae0, Dec 18 2019, 23:46:00) [MSC v.1916 32 bit (Intel)]
[INFO   ] [Python      ] Interpreter at "F:\Python Kivy\Scripts\python.exe"
[INFO   ] [Factory     ] 184 symbols loaded
[INFO   ] [Image       ] Providers: img_tex, img_dds, img_sdl2, img_gif (img_pil, img_ffpyplayer ignored)
[INFO   ] [Window      ] Provider: sdl2
[INFO   ] [GL          ] Using the "OpenGL" graphics system
[INFO   ] [GL          ] GLEW initialization succeeded
[INFO   ] [GL          ] Backend used <glew>
[INFO   ] [GL          ] OpenGL version
[INFO   ] [GL          ] OpenGL vendor
[INFO   ] [GL          ] OpenGL renderer
[INFO   ] [GL          ] OpenGL parsed version: 4, 6
[INFO   ] [GL          ] Shading version
[INFO   ] [GL          ] Texture max size <16384>
[INFO   ] [GL          ] Texture max units <32>
[INFO   ] [Window      ] auto add sdl2 input provider
[INFO   ] [Window      ] virtual keyboard not allowed, single mode, not docked
[INFO   ] [GL          ] NPOT texture support is available
 Traceback (most recent call last):
   File "F:/PyCharm Python Works/Kivy Test/splashscreen.py", line 25, in <module>
     sm.add_widget(ScreenOne)
   File "F:\Python Kivy\lib\site-packages\kivy\uix\screenmanager.py", line 979, in add_widget
     'ScreenManager accepts only Screen widget.')
 kivy.uix.screenmanager.ScreenManagerException: ScreenManager accepts only Screen widget.

This is the error log. Why does it shows like this. I tried editing but it doesn't work at all.
So given the code that it doesn't working when edited.
Thanks in advance.
I tried using the Animation only. but it doesn't work also.


问:
How to add commas into a char array in C
So I have a char array that currently holds a struct of a person's information.
For example,

```<code>struct Person{
char first_name[100];
char last_name[100];
char phone[13];
};

struct Person* arr[] = {("John", "Doe", "831.563.3642"), ("Julie", "Dee", "542.865.4644") };
</code>```

And I am trying to have it end up printing to a file to look like this...

```<code>John, Doe, 831.563.3642
Julie, Dee, 542.865.4644
</code>```

So far this is the code I have (to try and add the commas while putting into a file)

```<code>void print(FILE* file_out, struct Person* p1[]){
   size_t len = sizeof(p1) / sizeof(p1[0]);
   for(i = 0; i < len; i++){
      fprintf(file_out, "%s, %s, %s\n", p1[i].first, p1[i].last, p1[i].phone);
   }
}
return;
</code>```

答:
You may be making things way harder on yourself than you need to. With your struct Person filled, in order to obtain the output you need, you simply need to output the struct members separated by a comma and space. A simple printf will do, e.g.

```<code>struct Person p1 = { "John", "Doe", "831.563.3642" };
...
printf ("%s, %s, %s", p1.first, p1.last, p1.phone);
</code>```

The output from above would be:

```<code>John, Doe, 831.563.3642
</code>```

You can never do char new[] = ""; -- which creates the array new of size 1 holding the '\0' character. (bad choice of names as well, new is a kewword in C++, its use as a variable name should be avoided). Once you declare and initialize the array with automatic storage duration of size 1 -- it's size is FIXED -- period, and cannot be expanded. You would need to dynamically allocate storage with malloc in order to be able to resize the storage later with realloc.

If you want to create an additional array holding the comma separated values, then you need to declare the array with storage to hold the largest first_name, last_name and phone initially, e.g. char buf[100 + 100 + 13 + 4]; (the +4 for the pair of ", " you want to insert as well) Now you can use sprintf to simply write to the new array.

Below is a short example which shows both the direct output with printf and the creation of a new array (buf) using sprintf. The results is the same regardless of whether you directly output the comma space separated values, or store them in a buffer first. The function csvperson() takes the destination array and a pointer to a filled struct as parameter to write the members of the struct separated by a comma and space to array, e.g.

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

#define MAXNM 100   /* if you need a constant, #define one (or mroe) */
#define MAXPH  13

typedef struct {            /* using a typedef allows you to later omit the */
    char first[MAXNM],      /* 'struct' prefix in your declarations and */
         last [MAXNM],      /* parameter lists */
        phone [MAXPH];
} person;

char *csvperson (char *dest, person *p)
{
    if (!dest)
        return NULL;

    sprintf (dest, "%s, %s, %s", p->first, p->last, p->phone);

    return dest;
}

int main (void) {

    char buf[2 * MAXNM + MAXPH + 4];
    person p1 = { "John", "Doe", "831.563.3642" };

    printf ("direct output : %s, %s, %s\nbuffer output : %s\n",
            p1.first, p1.last, p1.phone, csvperson (buf, &p1));
}
</code>```

Example Use/Output

```<code>$ ./bin/csvperson
direct output : John, Doe, 831.563.3642
buffer output : John, Doe, 831.563.3642
</code>```

Look things over and let me know if you have further questions.

Array Example

To use the same methods above with an array, you would do:

```<code>int main (void) {

    char buf[2 * MAXNM + MAXPH + 4];
    person p1[] = { {"John", "Doe", "831.563.3642"},
                    {"Jane", "Doe", "832.563.3643"},
                    {"Mary", "Jane", "303.331.3333"} };
    int n = sizeof p1 / sizeof *p1;

    for (int i = 0; i < n; i++)
        printf ("\ndirect output : %s, %s, %s\nbuffer output : %s\n",
                p1[i].first, p1[i].last, p1[i].phone, csvperson (buf, p1+i));
}
</code>```

You can simply use fprintf to output to a file without buffering the output first, e.g.

```<code>fprintf (fileptr, "%s, %s, %s\n", p1[i].first, p1[i].last, p1[i].phone);
</code>```

In general, don't worry about combining/concatenating/etc.. things you can simply write out (wherever be it a file, the terminal, etc..)

Body:
So I have a char array that currently holds a struct of a person's information.
For example,

struct Person{
char first_name[100];
char last_name[100];
char phone[13];
};

struct Person* arr[] = {("John", "Doe", "831.563.3642"), ("Julie", "Dee", "542.865.4644") };

And I am trying to have it end up printing to a file to look like this...

John, Doe, 831.563.3642
Julie, Dee, 542.865.4644

So far this is the code I have (to try and add the commas while putting into a file)

void print(FILE* file_out, struct Person* p1[]){
   size_t len = sizeof(p1) / sizeof(p1[0]);
   for(i = 0; i < len; i++){
      fprintf(file_out, "%s, %s, %s\n", p1[i].first, p1[i].last, p1[i].phone);
   }
}
return;

Body:
You may be making things way harder on yourself than you need to. With your struct Person filled, in order to obtain the output you need, you simply need to output the struct members separated by a comma and space. A simple printf will do, e.g.

struct Person p1 = { "John", "Doe", "831.563.3642" };
...
printf ("%s, %s, %s", p1.first, p1.last, p1.phone);

The output from above would be:

John, Doe, 831.563.3642

You can never do char new[] = ""; -- which creates the array new of size 1 holding the '\0' character. (bad choice of names as well, new is a kewword in C++, its use as a variable name should be avoided). Once you declare and initialize the array with automatic storage duration of size 1 -- it's size is FIXED -- period, and cannot be expanded. You would need to dynamically allocate storage with malloc in order to be able to resize the storage later with realloc.

If you want to create an additional array holding the comma separated values, then you need to declare the array with storage to hold the largest first_name, last_name and phone initially, e.g. char buf[100 + 100 + 13 + 4]; (the +4 for the pair of ", " you want to insert as well) Now you can use sprintf to simply write to the new array.

Below is a short example which shows both the direct output with printf and the creation of a new array (buf) using sprintf. The results is the same regardless of whether you directly output the comma space separated values, or store them in a buffer first. The function csvperson() takes the destination array and a pointer to a filled struct as parameter to write the members of the struct separated by a comma and space to array, e.g.

#include <stdio.h>

#define MAXNM 100   /* if you need a constant, #define one (or mroe) */
#define MAXPH  13

typedef struct {            /* using a typedef allows you to later omit the */
    char first[MAXNM],      /* 'struct' prefix in your declarations and */
         last [MAXNM],      /* parameter lists */
        phone [MAXPH];
} person;

char *csvperson (char *dest, person *p)
{
    if (!dest)
        return NULL;

    sprintf (dest, "%s, %s, %s", p->first, p->last, p->phone);

    return dest;
}

int main (void) {

    char buf[2 * MAXNM + MAXPH + 4];
    person p1 = { "John", "Doe", "831.563.3642" };

    printf ("direct output : %s, %s, %s\nbuffer output : %s\n",
            p1.first, p1.last, p1.phone, csvperson (buf, &p1));
}

Example Use/Output

$ ./bin/csvperson
direct output : John, Doe, 831.563.3642
buffer output : John, Doe, 831.563.3642

Look things over and let me know if you have further questions.

Array Example

To use the same methods above with an array, you would do:

int main (void) {

    char buf[2 * MAXNM + MAXPH + 4];
    person p1[] = { {"John", "Doe", "831.563.3642"},
                    {"Jane", "Doe", "832.563.3643"},
                    {"Mary", "Jane", "303.331.3333"} };
    int n = sizeof p1 / sizeof *p1;

    for (int i = 0; i < n; i++)
        printf ("\ndirect output : %s, %s, %s\nbuffer output : %s\n",
                p1[i].first, p1[i].last, p1[i].phone, csvperson (buf, p1+i));
}

You can simply use fprintf to output to a file without buffering the output first, e.g.

fprintf (fileptr, "%s, %s, %s\n", p1[i].first, p1[i].last, p1[i].phone);

In general, don't worry about combining/concatenating/etc.. things you can simply write out (wherever be it a file, the terminal, etc..)


问:
Issue with 'styled-component': Error: Invalid hook call
I am working through a tutorial where they are using a styled-component. The style is being assigned in the js file after the render and I am getting the Invalid hook call. This is my first react tutorial so I am struggling to just google the answer. Below is the code that I am running. The error only pops up when I call <MovieGrid>. Any help would be appreciated

```<code>/* eslint react/no-did-mount-set-state: 0 */
import React, { Component } from 'react';
import styled from 'styled-components';
import Movie from './Movie';

class MoviesList extends Component {
  state = {
    movies: [],
  }

  async componentDidMount() {
    try {
      const res = await fetch('url');
      const movies = await res.json();
      this.setState({
        movies: movies.results,
      });
    } catch (e) {
      console.log(e);
    }
  }

  render() {
    return (
      <MovieGrid>
        {this.state.movies.map(movie => <Movie key={movie.id} movie={movie} />)}
      </MovieGrid>
    );
  }
}

export default MoviesList;

const MovieGrid = styled.div`
  display: grid;
  padding: 1rem;
  grid-template-columns: repeat(6, 1fr);
  grid-row-gap: 1rem;
`;
</code>```

答:
So the issue ended up being in another file. I was attempting to import Movie, but I was unaware that variables will not export by default so I ended up adding export before declaring and that solved the issue.

```<code>export const Poster = styled.img`
  box-shadow: 0 0 35px black;
`;
</code>```

Body:
I am working through a tutorial where they are using a styled-component. The style is being assigned in the js file after the render and I am getting the Invalid hook call. This is my first react tutorial so I am struggling to just google the answer. Below is the code that I am running. The error only pops up when I call <MovieGrid>. Any help would be appreciated

/* eslint react/no-did-mount-set-state: 0 */
import React, { Component } from 'react';
import styled from 'styled-components';
import Movie from './Movie';

class MoviesList extends Component {
  state = {
    movies: [],
  }

  async componentDidMount() {
    try {
      const res = await fetch('url');
      const movies = await res.json();
      this.setState({
        movies: movies.results,
      });
    } catch (e) {
      console.log(e);
    }
  }

  render() {
    return (
      <MovieGrid>
        {this.state.movies.map(movie => <Movie key={movie.id} movie={movie} />)}
      </MovieGrid>
    );
  }
}

export default MoviesList;

const MovieGrid = styled.div`
  display: grid;
  padding: 1rem;
  grid-template-columns: repeat(6, 1fr);
  grid-row-gap: 1rem;
`;

Body:
So the issue ended up being in another file. I was attempting to import Movie, but I was unaware that variables will not export by default so I ended up adding export before declaring and that solved the issue.

export const Poster = styled.img`
  box-shadow: 0 0 35px black;
`;


问:
How can I protect a Mifare Classic Tag that contains a NDEF message?
It's easy to protect a Mifare Ultralight with Android, there is the Ndef.makeReadonly() method for that. But Mifare Classic tags return Ndef.canMakeReadonly() == false, so this is not possible. I heard that one can make such a tag readonly or at least protect it with a key by setting the a or b keys.

There's this methid in MifareClassic tech: authenticateSectorWithKeyB(int sectorIndex, byte[] key)

Does anyone know if this can be used to make a ndef message on a mifare classic tag read-only? Or how else could I write a ndef message onto the tag and then somehow lock it against new writes?

答:
It is possible using the authenticate methods.

First, here is the datasheet for the Mifare Classic 4k:

http://www.nxp.com/documents/data_sheet/MF1S703x.pdf

The important chapters for your are:

3.6 Memory Organization

3.6.3 Sector Trailer

In short a write protection works like this:

The Mifare Classic is divided into sectors of 4*16 bytes each (only applies to the first 1k or so... the higher blocks are a bit different, but thats documented in the spec). Of these 64 bytes 16 are used for authentication/protection. For each sector of the card you do the following:

Authenticate the sector using KeyA

Read the sector trailer.

Modify the access bits of the sector trailer.

Write the sector trailer back to the card.

The KeyA values for Mifare Classics are:

byte[] KEY_DEFAULT =
    {(byte)0xFF,(byte)0xFF,(byte)0xFF,(byte)0xFF,(byte)0xFF,(byte)0xFF};

For unformatted, factory fresh cards.

byte[] KEY_MIFARE_APPLICATION_DIRECTORY =
    {(byte)0xA0,(byte)0xA1,(byte)0xA2,(byte)0xA3,(byte)0xA4,(byte)0xA5};

For the first sector of the card

byte[] KEY_NFC_FORUM =

  {(byte)0xD3,(byte)0xF7,(byte)0xD3,(byte)0xF7,(byte)0xD3,(byte)0xF7};

For all other sectors.

Important: You have to write back the original KeyA keys to the card. If these differ from the keys shown above the card will not be Ndef compliant anymore.

For the modified access bits you have two choices:

Only enable Read for KeyA. This will give you a 100% write protection that can't be revoked.

Enable Read for KeyA and Read/Write for KeyB. Also store a secret key in KeyB. This will allow you to authenticate a write protected sector using your secret KeyB to unprotect the card.

Background: Android will only authenticate a Ndef formatted tag using the KeyA values shown above. The Ndef detection code never tries KeyB on its own, therefore you can use KeyB for your own purposes.


问:
Python - Date and Time: AttributeError: 'module' object has no attribute 'month'
This is my calendar code in Python and I have saved it to my folder as calendar.py.

```<code>import calendar
a = calendar.month(2016, 3)
print (a)
print ("The Calendar :")
</code>```

When I execute it, it raises an error :

```<code>Traceback (most recent call last):
  File "calendar.py", line 1, in <module>
    import calendar
  File "/opt/lampp/htdocs/py/calendar.py", line 2, in <module>
    a = calendar.month(2016, 3)
AttributeError: 'module' object has no attribute 'month'
</code>```

What's going on?

答:
You might have given your file name as calendar.py. This is imported instead of the module in the standard library.

Solution:
Rename the file. Also, make sure to delete "calendar.pyc" file located in the same path where you are running the script.

As a check, do the following to locate your module
import calendar
print(calendar)

Body:
This is my calendar code in Python and I have saved it to my folder as calendar.py.

import calendar
a = calendar.month(2016, 3)
print (a)
print ("The Calendar :")

When I execute it, it raises an error :

Traceback (most recent call last):
  File "calendar.py", line 1, in <module>
    import calendar
  File "/opt/lampp/htdocs/py/calendar.py", line 2, in <module>
    a = calendar.month(2016, 3)
AttributeError: 'module' object has no attribute 'month'

What's going on?


问:
Countdown works on localhost but on webserver shows wrong date
I have a countdown working perfect on my local host but on webserver it gives wrong date.
on local host it gives me 5 days and few hours remaining, but on webserver it gives me -271 days and few hours</p>

```<code><div class="col-md-6 pb-4 pb-lg-0 col-lg-4">
<div class="text">
<div id="timer" class="d-flex mb-0">
<div class="time pl-3" id="days"></div>
<div class="time pl-3" id="hours"></div>
<div class="time pl-3" id="minutes"></div>
<div class="time pl-3" id="seconds"></div>
</div>

$('.checkin_date, .checkout_date').datepicker({
  'format': 'm/d/yyyy',
  'autoclose': true
});

function makeTimer() {

    var endTime = new Date("21 February 2020 7:00:00 GMT+01:00");
    endTime = (Date.parse(endTime) / 1000);

    var now = new Date();
    now = (Date.parse(now) / 1000);

    var timeLeft = endTime - now;

    var days = Math.floor(timeLeft / 86400);
    var hours = Math.floor((timeLeft - (days * 86400)) / 3600);
    var minutes = Math.floor((timeLeft - (days * 86400) - (hours * 3600 )) / 60);
    var seconds = Math.floor((timeLeft - (days * 86400) - (hours * 3600) - (minutes * 60)));

    if (hours < "10") { hours = "0" + hours; }
    if (minutes < "10") { minutes = "0" + minutes; }
    if (seconds < "10") { seconds = "0" + seconds; }

    $("#days").html(days + "<span>Days</span>");
    $("#hours").html(hours + "<span>Hours</span>");
    $("#minutes").html(minutes + "<span>Minutes</span>");
    $("#seconds").html(seconds + "<span>Seconds</span>");

}

setInterval(function() { makeTimer(); }, 1000);

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

答: Your server probably has a wrong date</p>

Body:
I have a countdown working perfect on my local host but on webserver it gives wrong date.
on local host it gives me 5 days and few hours remaining, but on webserver it gives me -271 days and few hours

$('.checkin_date, .checkout_date').datepicker({
  'format': 'm/d/yyyy',
  'autoclose': true
});

function makeTimer() {

    var endTime = new Date("21 February 2020 7:00:00 GMT+01:00");
    endTime = (Date.parse(endTime) / 1000);

    var now = new Date();
    now = (Date.parse(now) / 1000);

    var timeLeft = endTime - now;

    var days = Math.floor(timeLeft / 86400);
    var hours = Math.floor((timeLeft - (days * 86400)) / 3600);
    var minutes = Math.floor((timeLeft - (days * 86400) - (hours * 3600 )) / 60);
    var seconds = Math.floor((timeLeft - (days * 86400) - (hours * 3600) - (minutes * 60)));

    if (hours < "10") { hours = "0" + hours; }
    if (minutes < "10") { minutes = "0" + minutes; }
    if (seconds < "10") { seconds = "0" + seconds; }

    $("#days").html(days + "Days");
    $("#hours").html(hours + "Hours");
    $("#minutes").html(minutes + "Minutes");
    $("#seconds").html(seconds + "Seconds");

}

setInterval(function() { makeTimer(); }, 1000);

})(jQuery);

Body: Your server probably has a wrong date


问:
How to set dynamic background image URL with linear gradient using custom CSS class in Angular
I would like to be able to set a background-image using a dynamically loaded image (from my server) along with a linear gradient overlay using a custom CSS class. On page load, the CSS should look like this:

```<code>.container {
    background-image: linear-gradient(transparent -30%,#121212), url(https://...)
}
</code>```

However, the color: #121212 needs to be set using a custom css variable called --ion-color-dark and the url is stored in an http response object: this.response.imageURL

So I would need something like this:

```<code>.container {
    background-image: linear-gradient(transparent -30%,var(--ion-color-dark)), url(`${this.response.imageURL}`)
}
</code>```

My solution so far:

I've figured out how to get the image url to load by doing the following in my HTML:

```<code><div class="container" [ngStyle]="{'background-image': getBackgroundImageURL()}"></div>
</code>```

Which calls getBackgroundImageURL() in my component:

```<code>getBackgroundImageURL() {
    return `linear-gradient(transparent -30%,#121212, url(${this.response.imageURL})`;
}
</code>```

Which is great, but I cannot figure out how to load the CSS variable to replace the hard coded #121212 using this method. It appears I can do either one or the other, but not both.

Any suggestions? Thanks!

答:
You can do this by defining the variable in this way-

getBackgroundImageURL() {
    return linear-gradient(transparent -30%,var(--my-variable-name)), url(${this.response.imageURL});
}

Body:
I would like to be able to set a background-image using a dynamically loaded image (from my server) along with a linear gradient overlay using a custom CSS class. On page load, the CSS should look like this:

.container {
    background-image: linear-gradient(transparent -30%,#121212), url(https://...)
}

However, the color: #121212 needs to be set using a custom css variable called --ion-color-dark and the url is stored in an http response object: this.response.imageURL

So I would need something like this:

.container {
    background-image: linear-gradient(transparent -30%,var(--ion-color-dark)), url(`${this.response.imageURL}`)
}

My solution so far:

I've figured out how to get the image url to load by doing the following in my HTML:

Which calls getBackgroundImageURL() in my component:

getBackgroundImageURL() {
    return `linear-gradient(transparent -30%,#121212, url(${this.response.imageURL})`;
}

Which is great, but I cannot figure out how to load the CSS variable to replace the hard coded #121212 using this method. It appears I can do either one or the other, but not both.

Any suggestions? Thanks!


问:
creating a function that takes in a string and returns that string with every even letter uppercase
I'm trying to make a function in python that takes in strings and returns every even letter uppercase and odd letter lowercase.
For instance,

```<code>def myfunc(my_string):
     #code

myfunc(Python)
</code>```

Returns: pYtHoN

```<code>(1, p) odd
(2, y) even
(3, t) odd
(4, h) even
(5, o) odd
(6, n) even
</code>```

As you can see all the even indexes are uppercase and odd lowercase.

答:
```<code>def alternating_case(s):
    return "".join(
        x.lower() if i % 2 == 0 else x.upper()
        for i, x in enumerate(s)
    )
</code>```

Body:
I'm trying to make a function in python that takes in strings and returns every even letter uppercase and odd letter lowercase.
For instance,

def myfunc(my_string):
     #code

myfunc(Python)

Returns: pYtHoN

(1, p) odd
(2, y) even
(3, t) odd
(4, h) even
(5, o) odd
(6, n) even

As you can see all the even indexes are uppercase and odd lowercase.


问:
Installing a tar.gz on Linux
I have downloaded Node.js from this link, which points to this link when clicking the button:

https://nodejs.org/dist/v4.1.2/node-v4.1.2-linux-x64.tar.gz

As advice from the Ubuntu community on installing the tar.gz, the following steps are followed.

```<code>$ ./configure
$ make
$ [sudo] make install
</code>```

The problem is the current file I have downloaded does not contain ./configure.

So how do I install this? Should I extract this to the usr/ folder?

My OS is Debian 8 (Jessie).

Should I include the Java package from Oracle? Is it safe to extract these files to the /usr folder?

答:
Download the .tar.xz file form https://nodejs.org/en/ and then press Ctrl + Alt + T.

Then go to the destination that you downloaded your file to. For me it's my downloads folder. Then hit this command and Node.js will get installed on your system:

sudo tar -xf node-v16.0.0-linux-x64.tar.xz --directory=/usr/local --strip-components=1
```

This was the answer I had posted over two years ago, and here is what I recommand you right now, decompress the tarball, and keep it anywhere where your system knows ( tell it via updating $PATH ), its just a binary file, its not necessary to keep it in some specific location, you can keep it in your home directory and andd your bin folder to your bashrc or whatever shell you are using, its .rc file, and it will work just fine, at the end of the day, its just a pre-compiled binary file (inside node) nothing much.

Somebody in the comment section was saying npm, needs to be installed sepretly, this was in the early days of node back in 2012, when npm used to not ship with node, if you look inside bin folder npm binary is also there, so you dont need to install npm sepretly.

Title: Installing a tar.gz on Linux

Body:
I have downloaded Node.js from this link, which points to this link when clicking the button:

https://nodejs.org/dist/v4.1.2/node-v4.1.2-linux-x64.tar.gz

As advice from the Ubuntu community on installing the tar.gz, the following steps are followed.

$ ./configure
$ make
$ [sudo] make install

The problem is the current file I have downloaded does not contain ./configure.

So how do I install this? Should I extract this to the usr/ folder?

My OS is Debian 8 (Jessie).

Should I include the Java package from Oracle? Is it safe to extract these files to the /usr folder?

Body:
Download the .tar.xz file form https://nodejs.org/en/ and then press Ctrl + Alt + T.

Then go to the destination that you downloaded your file to. For me it's my downloads folder. Then hit this command and Node.js will get installed on your system:

sudo tar -xf node-v16.0.0-linux-x64.tar.xz --directory=/usr/local --strip-components=1

This was the answer I had posted over two years ago, and here is what I recommand you right now, decompress the tarball, and keep it anywhere where your system knows ( tell it via updating $PATH ), its just a binary file, its not necessary to keep it in some specific location, you can keep it in your home directory and andd your bin folder to your bashrc or whatever shell you are using, its .rc file, and it will work just fine, at the end of the day, its just a pre-compiled binary file (inside node) nothing much.

Somebody in the comment section was saying npm, needs to be installed sepretly, this was in the early days of node back in 2012, when npm used to not ship with node, if you look inside bin folder npm binary is also there, so you dont need to install npm sepretly.


问:
Getting "value must be an integer" when trying to seed YAML data
I'm using Django 2, Python 3.7 and the django-address module (https://pypi.org/project/django-address/).  I'm trying to insert some seed data.  I have this YAML ...

```<code>- model: address.locality
  pk: 1
  fields:
    name: "Chicago"
    postal_code: "60053"
    state:
      name: IL
      country:
      - United States
</code>```

When I run my seed command

```<code>python manage.py loaddata maps/fixtures/seed_data.yaml
</code>```

I get this error ...

```<code>localhost:web davea$ python manage.py loaddata maps/fixtures/seed_data.yaml
Traceback (most recent call last):
  File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/db/models/fields/__init__.py", line 923, in to_python
    return int(value)
TypeError: int() argument must be a string, a bytes-like object or a number, not 'dict'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/core/serializers/python.py", line 157, in Deserializer
    data[field.attname] = model._meta.get_field(field_name).to_python(field_value)
  File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/db/models/fields/__init__.py", line 928, in to_python
    params={'value': value},
django.core.exceptions.ValidationError: ["'{'name': 'IL', 'country': ['United States']}' value must be an integer."]

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "manage.py", line 21, in <module>
    main()
  File "manage.py", line 17, in main
    execute_from_command_line(sys.argv)
  File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line
    utility.execute()
  File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 365, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/core/management/base.py", line 288, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/core/management/base.py", line 335, in execute
    output = self.handle(*args, **options)
  File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/core/management/commands/loaddata.py", line 72, in handle
    self.loaddata(fixture_labels)
  File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/core/management/commands/loaddata.py", line 113, in loaddata
    self.load_label(fixture_label)
  File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/core/management/commands/loaddata.py", line 168, in load_label
    for obj in objects:
  File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/core/serializers/pyyaml.py", line 73, in Deserializer
    yield from PythonDeserializer(yaml.load(stream, Loader=SafeLoader), **options)
  File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/core/serializers/python.py", line 159, in Deserializer
    raise base.DeserializationError.WithData(e, d['model'], d.get('pk'), field_value)
django.core.serializers.base.DeserializationError: Problem installing fixture '/Users/davea/Documents/workspace/chicommons/maps/web/maps/fixtures/seed_data.yaml': ["'{'name': 'IL', 'country': ['United States']}' value must be an integer."]: (address.locality:pk=1) field_value was '{'name': 'IL', 'country': ['United States']}'
</code>```

I have added this in the file maps/monkey_patching.py to help with auto-creating the entities based on unique identifiers ...

```<code>from address import State
from address import Country

def country_get_by_natural_key(self, name):
    return self.get_or_create(name=name)[0]

def state_get_by_natural_key(self, name, country_id):
    return self.get_or_create(name=name, country_id=country_id)[0]

Country.add_to_class("get_by_natural_key",country_get_by_natural_key)
State.add_to_class("get_by_natural_key",state_get_by_natural_key)
</code>```

Edit: including stack trace per Shivam's request ...

```<code>(venv) localhost:maps davea$ python web/manage.py loaddata web/maps/fixtures/seed_data.yaml
Traceback (most recent call last):
  File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/db/models/fields/__init__.py", line 923, in to_python
    return int(value)
TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/core/serializers/python.py", line 157, in Deserializer
    data[field.attname] = model._meta.get_field(field_name).to_python(field_value)
  File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/db/models/fields/__init__.py", line 928, in to_python
    params={'value': value},
django.core.exceptions.ValidationError: ["'['IL', 'United States']' value must be an integer."]

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "web/manage.py", line 21, in <module>
    main()
  File "web/manage.py", line 17, in main
    execute_from_command_line(sys.argv)
  File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line
    utility.execute()
  File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 365, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/core/management/base.py", line 288, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/core/management/base.py", line 335, in execute
    output = self.handle(*args, **options)
  File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/core/management/commands/loaddata.py", line 72, in handle
    self.loaddata(fixture_labels)
  File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/core/management/commands/loaddata.py", line 113, in loaddata
    self.load_label(fixture_label)
  File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/core/management/commands/loaddata.py", line 168, in load_label
    for obj in objects:
  File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/core/serializers/pyyaml.py", line 73, in Deserializer
    yield from PythonDeserializer(yaml.load(stream, Loader=SafeLoader), **options)
  File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/core/serializers/python.py", line 159, in Deserializer
    raise base.DeserializationError.WithData(e, d['model'], d.get('pk'), field_value)
django.core.serializers.base.DeserializationError: Problem installing fixture '/Users/davea/Documents/workspace/chicommons/maps/web/maps/fixtures/seed_data.yaml': ["'['IL', 'United States']' value must be an integer."]: (address.locality:pk=1) field_value was '['IL', 'United States']'
</code>```

答:
I would offer an alternative approach, which is just to write your own management command to import this data, instead of trying to make loaddata work - I think this is potentially much less effort.

This command works for the sample data you've provided - it may need some minor adjustments if you have more than just address.locality objects in your YAML file:

```<code>import yaml

from django.core.management.base import BaseCommand

from address.models import Country, State, Locality

class Command(BaseCommand):

    def add_arguments(self, parser):
        parser.add_argument('file', nargs=1, type=str)

    def handle(self, *args, **options):
        f = options['file'][0]
        with open(f, 'r') as yamlfile:
            data = yaml.load(yamlfile)

        for row in data:
            if row['model'] == 'address.locality':
                state_name = row['fields']['state']['name']
                country_name = row['fields']['state']['country'][0]

                country_obj, _ = Country.objects.get_or_create(name=country_name)
                state_obj, _ = State.objects.get_or_create(country=country_obj, name=state_name)

                Locality.objects.get_or_create(
                    pk=row['pk'],
                    state=state_obj,
                    postal_code=row['fields']['postal_code'],
                    name=row['fields']['name']
                )
</code>```

(Side note - the format of your YAML is a little weird, as it provides a list for country. I would have thought a state can only belong to a single country?).

Body:
I'm using Django 2, Python 3.7 and the django-address module (https://pypi.org/project/django-address/).  I'm trying to insert some seed data.  I have this YAML ...

- model: address.locality
  pk: 1
  fields:
    name: "Chicago"
    postal_code: "60053"
    state:
      name: IL
      country:
      - United States

When I run my seed command

python manage.py loaddata maps/fixtures/seed_data.yaml

I get this error ...

localhost:web davea$ python manage.py loaddata maps/fixtures/seed_data.yaml
Traceback (most recent call last):
  File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/db/models/fields/__init__.py", line 923, in to_python
    return int(value)
TypeError: int() argument must be a string, a bytes-like object or a number, not 'dict'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/core/serializers/python.py", line 157, in Deserializer
    data[field.attname] = model._meta.get_field(field_name).to_python(field_value)
  File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/db/models/fields/__init__.py", line 928, in to_python
    params={'value': value},
django.core.exceptions.ValidationError: ["'{'name': 'IL', 'country': ['United States']}' value must be an integer."]

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "manage.py", line 21, in <module>
    main()
  File "manage.py", line 17, in main
    execute_from_command_line(sys.argv)
  File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line
    utility.execute()
  File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 365, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/core/management/base.py", line 288, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/core/management/base.py", line 335, in execute
    output = self.handle(*args, **options)
  File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/core/management/commands/loaddata.py", line 72, in handle
    self.loaddata(fixture_labels)
  File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/core/management/commands/loaddata.py", line 113, in loaddata
    self.load_label(fixture_label)
  File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/core/management/commands/loaddata.py", line 168, in load_label
    for obj in objects:
  File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/core/serializers/pyyaml.py", line 73, in Deserializer
    yield from PythonDeserializer(yaml.load(stream, Loader=SafeLoader), **options)
  File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/core/serializers/python.py", line 159, in Deserializer
    raise base.DeserializationError.WithData(e, d['model'], d.get('pk'), field_value)
django.core.serializers.base.DeserializationError: Problem installing fixture '/Users/davea/Documents/workspace/chicommons/maps/web/maps/fixtures/seed_data.yaml': ["'{'name': 'IL', 'country': ['United States']}' value must be an integer."]: (address.locality:pk=1) field_value was '{'name': 'IL', 'country': ['United States']}'

I have added this in the file maps/monkey_patching.py to help with auto-creating the entities based on unique identifiers ...

from address import State
from address import Country

def country_get_by_natural_key(self, name):
    return self.get_or_create(name=name)[0]

def state_get_by_natural_key(self, name, country_id):
    return self.get_or_create(name=name, country_id=country_id)[0]

Country.add_to_class("get_by_natural_key",country_get_by_natural_key)
State.add_to_class("get_by_natural_key",state_get_by_natural_key)

Edit: including stack trace per Shivam's request ...

(venv) localhost:maps davea$ python web/manage.py loaddata web/maps/fixtures/seed_data.yaml
Traceback (most recent call last):
  File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/db/models/fields/__init__.py", line 923, in to_python
    return int(value)
TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/core/serializers/python.py", line 157, in Deserializer
    data[field.attname] = model._meta.get_field(field_name).to_python(field_value)
  File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/db/models/fields/__init__.py", line 928, in to_python
    params={'value': value},
django.core.exceptions.ValidationError: ["'['IL', 'United States']' value must be an integer."]

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "web/manage.py", line 21, in <module>
    main()
  File "web/manage.py", line 17, in main
    execute_from_command_line(sys.argv)
  File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line
    utility.execute()
  File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 365, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/core/management/base.py", line 288, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/core/management/base.py", line 335, in execute
    output = self.handle(*args, **options)
  File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/core/management/commands/loaddata.py", line 72, in handle
    self.loaddata(fixture_labels)
  File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/core/management/commands/loaddata.py", line 113, in loaddata
    self.load_label(fixture_label)
  File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/core/management/commands/loaddata.py", line 168, in load_label
    for obj in objects:
  File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/core/serializers/pyyaml.py", line 73, in Deserializer
    yield from PythonDeserializer(yaml.load(stream, Loader=SafeLoader), **options)
  File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/core/serializers/python.py", line 159, in Deserializer
    raise base.DeserializationError.WithData(e, d['model'], d.get('pk'), field_value)
django.core.serializers.base.DeserializationError: Problem installing fixture '/Users/davea/Documents/workspace/chicommons/maps/web/maps/fixtures/seed_data.yaml': ["'['IL', 'United States']' value must be an integer."]: (address.locality:pk=1) field_value was '['IL', 'United States']'

Body:
I would offer an alternative approach, which is just to write your own management command to import this data, instead of trying to make loaddata work - I think this is potentially much less effort.

This command works for the sample data you've provided - it may need some minor adjustments if you have more than just address.locality objects in your YAML file:

import yaml

from django.core.management.base import BaseCommand

from address.models import Country, State, Locality

class Command(BaseCommand):

    def add_arguments(self, parser):
        parser.add_argument('file', nargs=1, type=str)

    def handle(self, *args, **options):
        f = options['file'][0]
        with open(f, 'r') as yamlfile:
            data = yaml.load(yamlfile)

        for row in data:
            if row['model'] == 'address.locality':
                state_name = row['fields']['state']['name']
                country_name = row['fields']['state']['country'][0]

                country_obj, _ = Country.objects.get_or_create(name=country_name)
                state_obj, _ = State.objects.get_or_create(country=country_obj, name=state_name)

                Locality.objects.get_or_create(
                    pk=row['pk'],
                    state=state_obj,
                    postal_code=row['fields']['postal_code'],
                    name=row['fields']['name']
                )

(Side note - the format of your YAML is a little weird, as it provides a list for country. I would have thought a state can only belong to a single country?).


问:
Django: Related Objects for Authenticated User
In Django we can create related models:

```<code>class User(models.Model):
    pass

class TaskSet(models.Model):
    user = models.ForeignKey(User, related_name='tasksets')
    title = models.Charfield()

class Task(models.Model):
    user = models.ForeignKey(User, related_name='tasks')
    taskset = models.ForeignKey(TaskSet, related_name='tasks')
</code>```

Makes sense, I can call request.user.tasksets– but what's the correct way to get the tasks in the taskset? request.user.tasksets.first().tasks will return all of the tasks for the entire task set– but how can I get the tasks for that user only?

答:
You can call .filter() on that. So the whole query would be request.user.tasksets.first().tasks.filter(user=request.user). However, this is only useful if you want to get a task from the first task set of the user only and this structure would only be productive if the tasks defined inside each task set can belong to other users other than the task set owner.

If you just want to get a task belonging to that user regardless of whether it is in the first task set or not, you can do request.user.tasks.first().

Body:
In Django we can create related models:

class User(models.Model):
    pass

class TaskSet(models.Model):
    user = models.ForeignKey(User, related_name='tasksets')
    title = models.Charfield()

class Task(models.Model):
    user = models.ForeignKey(User, related_name='tasks')
    taskset = models.ForeignKey(TaskSet, related_name='tasks')

Makes sense, I can call request.user.tasksets– but what's the correct way to get the tasks in the taskset? request.user.tasksets.first().tasks will return all of the tasks for the entire task set– but how can I get the tasks for that user only?


问:
How can I access the ApplicationContext from within a JAX-WS web service?
Similar to How can I access the ServletContext from within a JAX-WS web service?, is there a way to access applicationContext, easier than this?</p>

```<code>import javax.annotation.Resource;
import javax.jws.WebService;
import javax.servlet.ServletContext;
import javax.xml.ws.WebServiceContext;
import javax.xml.ws.handler.MessageContext;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

@WebService
public class MyWebService {
    // boilerplate code begins :(

    @Resource
    private WebServiceContext context;
    private WebApplicationContext webApplicationContext = null;

    /**
     * @return
     * @throws IllegalStateException
     */
    private WebApplicationContext getWebApplicationContext()
            throws IllegalStateException {
        if (webApplicationContext != null)
            return webApplicationContext;
        ServletContext servletContext =
                (ServletContext) context.getMessageContext().get(
                        MessageContext.SERVLET_CONTEXT);
        webApplicationContext =
                WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
        return webApplicationContext;
    }
}
</code>```

答:
I don't think that the web service should have to know about web or servlet contexts or its application context.  I don't see why it should have to know any of that.  Shouldn't it be far more passive?  Inject what it needs and let it do its work.  The service interactions with a client should be based on a contract defined up front.  If it has to get unknown values from a context of some kind, how will clients know what needs to be set or how to set it?

I'd go further and say that a web service should be a wrapper for a Spring service interface.  It's just one more choice among all the possible ways to expose it.  Your web service should do little more than marshal and unmarshal the XML request/response objects and collaborate with Spring services.

OwnerDisplayName: pihentagy

ContentLicense: CC BY-SA 2.5

Body:
Similar to How can I access the ServletContext from within a JAX-WS web service?, is there a way to access applicationContext, easier than this?

import javax.annotation.Resource;
import javax.jws.WebService;
import javax.servlet.ServletContext;
import javax.xml.ws.WebServiceContext;
import javax.xml.ws.handler.MessageContext;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

@WebService
public class MyWebService {
    // boilerplate code begins :(

    @Resource
    private WebServiceContext context;
    private WebApplicationContext webApplicationContext = null;

    /**
     * @return
     * @throws IllegalStateException
     */
    private WebApplicationContext getWebApplicationContext()
            throws IllegalStateException {
        if (webApplicationContext != null)
            return webApplicationContext;
        ServletContext servletContext =
                (ServletContext) context.getMessageContext().get(
                        MessageContext.SERVLET_CONTEXT);
        webApplicationContext =
                WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
        return webApplicationContext;
    }
}


问:
Using a webservice from my Zend project
I'm working with an external API webservice that returns a json output true or false. I visit a URL like

```<code>http://site.com/api/valid
</code>```

and it gives me something like this, which looks like json

```<code>"true"
</code>```

Right now I'm visiting the url manually, but I want to now do it programmatically from within my zend project. What should I use to get the result correctly

答:
there are a lot of ways. The simplest is to use file_get_contents().

```<code>$result = file_get_contents("http://site.com/api/valid");
// if result is truly json
// data will be
//    array( 0 => true)
$data = json_decode($result);
</code>```

If it is a popular webservice . there might be a library written for it already. This is preferred since it will handle error conditions and corner cases. Google around for it first.

Title: Using a webservice from my Zend project

Body:
I'm working with an external API webservice that returns a json output true or false. I visit a URL like

http://site.com/api/valid

and it gives me something like this, which looks like json

"true"

Right now I'm visiting the url manually, but I want to now do it programmatically from within my zend project. What should I use to get the result correctly

Body:
there are a lot of ways. The simplest is to use file_get_contents().

$result = file_get_contents("http://site.com/api/valid");
// if result is truly json
// data will be
//    array( 0 => true)
$data = json_decode($result);

If it is a popular webservice . there might be a library written for it already. This is preferred since it will handle error conditions and corner cases. Google around for it first.


问:
PHP fails to create connection to mongoDB
I try to figure out why PHP  driver can't connect to mongoDB

PHP Version 5.3.16 (64bit)

MongoDB:    mongodb-linux-x86_64-2.4.3

OS: CentOS  release 5.2 (Final)

Added link: mongo -> mongodb-linux-i686-2.4.3

Created data folder: mkdir /home/max/mongo/data

initiated mongo:

mongo/bin/mongod --dbpath=mongo/data --fork --logpath /var/wefi/logs/feederliteRC/mongodb.log

All works fine and can connect with mongoVUE monitor tool. (from Windows7)

Now, I try to connect to BongoDB from PHP:

I installed driver for PHP:

sudo pecl install mongo

on: php -i | grep mongo I get:

```<code>mongo
mongo.allow_empty_keys => 0 => 0
mongo.chunk_size => 262144 => 262144
mongo.cmd => $ => $
mongo.default_host => localhost => localhost
mongo.default_port => 27017 => 27017
mongo.is_master_interval => 15 => 15
mongo.long_as_object => 0 => 0
mongo.native_long => 0 => 0
mongo.ping_interval => 5 => 5
OLDPWD => /usr/share/pear/doc/mongo
_SERVER["OLDPWD"] => /usr/share/pear/doc/mongo
</code>```

I added to php.ini (nano /etc/php.ini): extension=mongo.so

and restarted httpd: /etc/init.d/httpd restart

from code:

```<code> try {
        // open connection to MongoDB server
        $conn = new Mongo('localhost');
} catch (MongoConnectionException $e) {
        die('Error connecting to MongoDB server');
        } catch (MongoException $e) {
        die('Error: ' . $e->getMessage());
    }
</code>```

PHP sees new Mongo but I get exception: "Error connecting to MongoDB server.

Strange, mongoDB runs, driver for PHP works but it doesn't see mongoDB.

Can someone help me,

[EDIT]

"Error connecting to MongoDB server Failed to connect to: localhost:27017: Connection refused"

Do I need add smoething to php.ini?

答:
If you are running SELinux and command line connections work but PHP connections fail try the command below.

/usr/sbin/setsebool -P httpd_can_network_connect 1

Then restart Apache.

See https://www.php.net/manual/en/mongo.installation.php

Body:
I try to figure out why PHP  driver can't connect to mongoDB

PHP Version 5.3.16 (64bit)

MongoDB:    mongodb-linux-x86_64-2.4.3

OS: CentOS  release 5.2 (Final)

Added link: mongo -> mongodb-linux-i686-2.4.3

Created data folder: mkdir /home/max/mongo/data

initiated mongo:

mongo/bin/mongod --dbpath=mongo/data --fork --logpath /var/wefi/logs/feederliteRC/mongodb.log

All works fine and can connect with mongoVUE monitor tool. (from Windows7)

Now, I try to connect to BongoDB from PHP:

I installed driver for PHP:

sudo pecl install mongo

on: php -i | grep mongo I get:

mongo
mongo.allow_empty_keys => 0 => 0
mongo.chunk_size => 262144 => 262144
mongo.cmd => $ => $
mongo.default_host => localhost => localhost
mongo.default_port => 27017 => 27017
mongo.is_master_interval => 15 => 15
mongo.long_as_object => 0 => 0
mongo.native_long => 0 => 0
mongo.ping_interval => 5 => 5
OLDPWD => /usr/share/pear/doc/mongo
_SERVER["OLDPWD"] => /usr/share/pear/doc/mongo

I added to php.ini (nano /etc/php.ini): extension=mongo.so

and restarted httpd: /etc/init.d/httpd restart

from code:

 try {
        // open connection to MongoDB server
        $conn = new Mongo('localhost');
} catch (MongoConnectionException $e) {
        die('Error connecting to MongoDB server');
        } catch (MongoException $e) {
        die('Error: ' . $e->getMessage());
    }

PHP sees new Mongo but I get exception: "Error connecting to MongoDB server.

Strange, mongoDB runs, driver for PHP works but it doesn't see mongoDB.

Can someone help me,

[EDIT]

"Error connecting to MongoDB server Failed to connect to: localhost:27017: Connection refused"

Do I need add smoething to php.ini?


问:
Add new component view with CoreUI 2.1 Angular
I followed this SO post:
Adding new components with default layout

but can't get the dashboard to show the new component. I'm using the current CoreUI 2 release from GitHub. Am I supposed to update the nav and route as well? If so, could I get an example? Hacking at this doesn't seem to work, and the documentation is very lacking.

答:
TRY THIS

Just Create the new component using the below commands

ng generate component YOUR_COMPONENT_NAME

shortcut

ng g c YOUR_COMPONENT_NAME

Then it will create a component folder in your app directory.

Make sure you have imported in app module and declared in declarations array.

then put router-outlet in app.module.html

After that put your view code i.e html code in your app.YOUR_COMPONENT_NAME.html and style in app.YOUR_COMPONENT_NAME.css

for more info

https://angular.io/guide/architecture-components


问:
Error "not numeric" when using crosstalk package with EnhancedVolcano
I'd like to implement a cross-talk functionality between a table and plot in both directions:

select the row in the table which will be reflected in the plot

select a dot in the plot which will be reflected in the table. Same idea as here.

I've managed to implement a script, which works beautifully if I make scatter plot with ggplot() and  table (both objects cross-talk!). However, when used EnhancedVolcano() and table I got the following error:

```<code>Error in EnhancedVolcano(toptable = data_shared, lab = "disp", x = "qsec",  :
  qsec is not numeric!
</code>```

If I replace data_shared variable with df_orig, no error is raised, but there is no cross-talking between objects :(

Does this mean that SharedData$new() doesn't recognize numeric values as numeric? How to fix this error?

Any help is highly appreciated.
Thank you

Toy example:

```<code>  library(plotly)            # '4.9.1'
  library(DT)                # '0.11'
  library(crosstalk)         # ‘1.0.0’
  library(EnhancedVolcano)   # ‘1.4.0’
  # Input
  data1 = mtcars  #dim(data1)  # 32  11
  data_shared = SharedData$new(data1) #, key = c("qsec", "hp"))
  # df_orig = data_shared$origData()
  # V-Plot
  vp =EnhancedVolcano( toptable = data_shared,
                       lab  = 'disp',
                       x  =  'qsec',
                       y  =  'hp',
                       xlab  ='testX',
                       ylab = 'testY')
  bscols(
    ggplotly(vp + aes(x= qsec, y= -log10(hp/1000))),
    datatable(data_shared, style="bootstrap", class="compact", width="100%",
              options=list(deferRender=FALSE, dom='t')))
</code>```

Same script, which works with ggplot():

```<code>data1 = mtcars  #dim(data1)  # 32  11
data_shared = SharedData$new(data1)
vp = ggplot(data = data_shared, mapping = aes(qsec, hp)) +
  geom_point()
bscols(
  ggplotly(vp) ,
  datatable(data_shared, style="bootstrap", class="compact", width="100%",
            options=list(deferRender=FALSE, dom='t')))
</code>```

答:
tried to modify few things in volcano function, got following error:

```<code>Error in as.data.frame.default(toptable) :
  cannot coerce class ‘c("SharedData", "R6")’ to a data.frame
</code>```

not sure yet, how to fix it.

Body:
I'd like to implement a cross-talk functionality between a table and plot in both directions:

select the row in the table which will be reflected in the plot

select a dot in the plot which will be reflected in the table. Same idea as here.

I've managed to implement a script, which works beautifully if I make scatter plot with ggplot() and  table (both objects cross-talk!). However, when used EnhancedVolcano() and table I got the following error:

Error in EnhancedVolcano(toptable = data_shared, lab = "disp", x = "qsec",  :
  qsec is not numeric!

If I replace data_shared variable with df_orig, no error is raised, but there is no cross-talking between objects :(

Does this mean that SharedData$new() doesn't recognize numeric values as numeric? How to fix this error?

Any help is highly appreciated.
Thank you

Toy example:

  library(plotly)            # '4.9.1'
  library(DT)                # '0.11'
  library(crosstalk)         # ‘1.0.0’
  library(EnhancedVolcano)   # ‘1.4.0’
  # Input
  data1 = mtcars  #dim(data1)  # 32  11
  data_shared = SharedData$new(data1) #, key = c("qsec", "hp"))
  # df_orig = data_shared$origData()
  # V-Plot
  vp =EnhancedVolcano( toptable = data_shared,
                       lab  = 'disp',
                       x  =  'qsec',
                       y  =  'hp',
                       xlab  ='testX',
                       ylab = 'testY')
  bscols(
    ggplotly(vp + aes(x= qsec, y= -log10(hp/1000))),
    datatable(data_shared, style="bootstrap", class="compact", width="100%",
              options=list(deferRender=FALSE, dom='t')))

Same script, which works with ggplot():

data1 = mtcars  #dim(data1)  # 32  11
data_shared = SharedData$new(data1)
vp = ggplot(data = data_shared, mapping = aes(qsec, hp)) +
  geom_point()
bscols(
  ggplotly(vp) ,
  datatable(data_shared, style="bootstrap", class="compact", width="100%",
            options=list(deferRender=FALSE, dom='t')))

Body:
tried to modify few things in volcano function, got following error:

Error in as.data.frame.default(toptable) :
  cannot coerce class ‘c("SharedData", "R6")’ to a data.frame

not sure yet, how to fix it.