问:
Can't decode a JSON file from web in VB.NET
I have some code below, which gets a response from a website fine, my code works until it gets to the decoding bit, but returns no objects.
This is my first attempt at JSON and web related data.

It works fine until:
Dim dict As Object
which returns nothing, I've tried several alternatives from the web, but am stumpt.

here is the URL of the website for the JSON:
https://www.metcheck.com/OTHER/json_data.asp?zipcode=wv12+4qz&locationID=60883&lat=52.6&lon=-2

Here is he URL that will show the JSON File:
http://ws1.metcheck.com/ENGINE/v9_0/json.asp?lat=52.6&lon=-2&lid=60883&Fc=No

```<code>Imports System.IO
Imports System.Net
Imports System.Web.Script.Serialization

Public Class Weather
    Private Sub Weather_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Dim uriString As String = "http://ws1.metcheck.com/ENGINE/v9_0/json.asp?lat=52.6&lon=-2&lid=60883&Fc=No"
    Dim uri As New Uri(uriString)

    Dim request As HttpWebRequest = HttpWebRequest.Create(uri)
    request.Method = "GET"

    Dim response As HttpWebResponse = request.GetResponse()

    Dim read As New StreamReader(response.GetResponseStream())
    Dim raw As String = read.ReadToEnd

    Dim dict As Object = New JavaScriptSerializer().Deserialize(Of List(Of Object))(raw)

    For Each item As Object In dict
        TextBox1.Text = item("temperature").ToString & vbCrLf
        TextBox1.Text = item("dewpoint").ToString & vbCrLf
        TextBox1.Text = item("rain").ToString & vbCrLf
    Next

End Sub
End Class
</code>```

答:
The real issue here is that you are trying to deserialize into a List but your JSON actually represents a single object containing a data property which then contains a list of objects. That is why you are getting this error. Json.Net can't deserialize a single object into a list. I think what you really want to do is define a container class

```<code>Public Class Metdata
    Public Property myDictionary As List(Of Dictionary(Of String, Object))
End Class
</code>```

And then your sub will look like:

```<code>    Private Sub Weather_Load(sender As Object, e As EventArgs) 'Handles MyBase.Load
    Dim uriString As String = "http://ws1.metcheck.com/ENGINE/v9_0/json.asp?lat=52.6&lon=-2&lid=60883&Fc=No"
    Dim uri As New Uri(uriString)

    Dim request As HttpWebRequest = HttpWebRequest.Create(uri)
    request.Method = "GET"

    Dim response As HttpWebResponse = request.GetResponse()

    Dim read As New StreamReader(response.GetResponseStream())
    Dim raw As String = read.ReadToEnd

    Dim dict As Metdata
    dict = JsonConvert.DeserializeObject(Of Metdata)(raw)

End Sub

Partial Public Class Metdata
    Public Property myDictionary As List(Of Dictionary(Of String, Object))
End Class
Public Class Forecast

        <JsonProperty("temperature")>
        Public Property Temperature As String

        <JsonProperty("dewpoint")>
        Public Property Dewpoint As String

        <JsonProperty("rain")>
        Public Property Rain As String

        <JsonProperty("freezinglevel")>
        Public Property Freezinglevel As String

        <JsonProperty("uvIndex")>
        Public Property UvIndex As String

        <JsonProperty("totalcloud")>
        Public Property Totalcloud As String

        <JsonProperty("lowcloud")>
        Public Property Lowcloud As String

        <JsonProperty("medcloud")>
        Public Property Medcloud As String

        <JsonProperty("highcloud")>
        Public Property Highcloud As String

        <JsonProperty("humidity")>
        Public Property Humidity As String

        <JsonProperty("windspeed")>
        Public Property Windspeed As String

        <JsonProperty("meansealevelpressure")>
        Public Property Meansealevelpressure As String

        <JsonProperty("windgustspeed")>
        Public Property Windgustspeed As String

        <JsonProperty("winddirection")>
        Public Property Winddirection As String

        <JsonProperty("windletter")>
        Public Property Windletter As String

        <JsonProperty("icon")>
        Public Property Icon As String

        <JsonProperty("iconName")>
        Public Property IconName As String

        <JsonProperty("chanceofrain")>
        Public Property Chanceofrain As String

        <JsonProperty("chanceofsnow")>
        Public Property Chanceofsnow As String

        <JsonProperty("dayOfWeek")>
        Public Property DayOfWeek As String

        <JsonProperty("weekday")>
        Public Property Weekday As String

        <JsonProperty("sunrise")>
        Public Property Sunrise As String

        <JsonProperty("sunset")>
        Public Property Sunset As String

        <JsonProperty("dayOrNight")>
        Public Property DayOrNight As String

        <JsonProperty("utcTime")>
        Public Property UtcTime As DateTime
    End Class

Public Class ForecastLocation

    <JsonProperty("forecast")>
    Public Property Forecast As Forecast()

    <JsonProperty("continent")>
    Public Property Continent As String

    <JsonProperty("country")>
    Public Property Country As String

    <JsonProperty("location")>
    Public Property Location As String

    <JsonProperty("latitude")>
    Public Property Latitude As Double

    <JsonProperty("longitude")>
    Public Property Longitude As Double

    <JsonProperty("timezone")>
    Public Property Timezone As Integer
End Class

Public Class MetcheckData

    <JsonProperty("forecastLocation")>
    Public Property ForecastLocation As ForecastLocation
End Class

Public Class Metdata

    <JsonProperty("metcheckData")>
    Public Property MetcheckData As MetcheckData

    <JsonProperty("feedCreation")>
    Public Property FeedCreation As DateTime

    <JsonProperty("feedCreator")>
    Public Property FeedCreator As String

    <JsonProperty("feedModel")>
    Public Property FeedModel As String

    <JsonProperty("feedModelRun")>
    Public Property FeedModelRun As String

    <JsonProperty("feedModelRunInitialTime")>
    Public Property FeedModelRunInitialTime As DateTime

    <JsonProperty("feedResolution")>
    Public Property FeedResolution As String
End Class
</code>```

dict.Metcheckdata.Forecastlocation.Forecast will contain your 155 records.

Body:
I have some code below, which gets a response from a website fine, my code works until it gets to the decoding bit, but returns no objects.
This is my first attempt at JSON and web related data.

It works fine until:
Dim dict As Object
which returns nothing, I've tried several alternatives from the web, but am stumpt.

here is the URL of the website for the JSON:
https://www.metcheck.com/OTHER/json_data.asp?zipcode=wv12+4qz&locationID=60883&lat=52.6&lon=-2

Here is he URL that will show the JSON File:
http://ws1.metcheck.com/ENGINE/v9_0/json.asp?lat=52.6&lon=-2&lid=60883&Fc=No

Imports System.IO
Imports System.Net
Imports System.Web.Script.Serialization

Public Class Weather
    Private Sub Weather_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Dim uriString As String = "http://ws1.metcheck.com/ENGINE/v9_0/json.asp?lat=52.6&lon=-2&lid=60883&Fc=No"
    Dim uri As New Uri(uriString)

    Dim request As HttpWebRequest = HttpWebRequest.Create(uri)
    request.Method = "GET"

    Dim response As HttpWebResponse = request.GetResponse()

    Dim read As New StreamReader(response.GetResponseStream())
    Dim raw As String = read.ReadToEnd

    Dim dict As Object = New JavaScriptSerializer().Deserialize(Of List(Of Object))(raw)

    For Each item As Object In dict
        TextBox1.Text = item("temperature").ToString & vbCrLf
        TextBox1.Text = item("dewpoint").ToString & vbCrLf
        TextBox1.Text = item("rain").ToString & vbCrLf
    Next

End Sub
End Class

Body:
The real issue here is that you are trying to deserialize into a List but your JSON actually represents a single object containing a data property which then contains a list of objects. That is why you are getting this error. Json.Net can't deserialize a single object into a list. I think what you really want to do is define a container class

Public Class Metdata
    Public Property myDictionary As List(Of Dictionary(Of String, Object))
End Class

And then your sub will look like:

    Private Sub Weather_Load(sender As Object, e As EventArgs) 'Handles MyBase.Load
    Dim uriString As String = "http://ws1.metcheck.com/ENGINE/v9_0/json.asp?lat=52.6&lon=-2&lid=60883&Fc=No"
    Dim uri As New Uri(uriString)

    Dim request As HttpWebRequest = HttpWebRequest.Create(uri)
    request.Method = "GET"

    Dim response As HttpWebResponse = request.GetResponse()

    Dim read As New StreamReader(response.GetResponseStream())
    Dim raw As String = read.ReadToEnd

    Dim dict As Metdata
    dict = JsonConvert.DeserializeObject(Of Metdata)(raw)

End Sub

Partial Public Class Metdata
    Public Property myDictionary As List(Of Dictionary(Of String, Object))
End Class
Public Class Forecast

        <JsonProperty("temperature")>
        Public Property Temperature As String

        <JsonProperty("dewpoint")>
        Public Property Dewpoint As String

        <JsonProperty("rain")>
        Public Property Rain As String

        <JsonProperty("freezinglevel")>
        Public Property Freezinglevel As String

        <JsonProperty("uvIndex")>
        Public Property UvIndex As String

        <JsonProperty("totalcloud")>
        Public Property Totalcloud As String

        <JsonProperty("lowcloud")>
        Public Property Lowcloud As String

        <JsonProperty("medcloud")>
        Public Property Medcloud As String

        <JsonProperty("highcloud")>
        Public Property Highcloud As String

        <JsonProperty("humidity")>
        Public Property Humidity As String

        <JsonProperty("windspeed")>
        Public Property Windspeed As String

        <JsonProperty("meansealevelpressure")>
        Public Property Meansealevelpressure As String

        <JsonProperty("windgustspeed")>
        Public Property Windgustspeed As String

        <JsonProperty("winddirection")>
        Public Property Winddirection As String

        <JsonProperty("windletter")>
        Public Property Windletter As String

        <JsonProperty("icon")>
        Public Property Icon As String

        <JsonProperty("iconName")>
        Public Property IconName As String

        <JsonProperty("chanceofrain")>
        Public Property Chanceofrain As String

        <JsonProperty("chanceofsnow")>
        Public Property Chanceofsnow As String

        <JsonProperty("dayOfWeek")>
        Public Property DayOfWeek As String

        <JsonProperty("weekday")>
        Public Property Weekday As String

        <JsonProperty("sunrise")>
        Public Property Sunrise As String

        <JsonProperty("sunset")>
        Public Property Sunset As String

        <JsonProperty("dayOrNight")>
        Public Property DayOrNight As String

        <JsonProperty("utcTime")>
        Public Property UtcTime As DateTime
    End Class

Public Class ForecastLocation

    <JsonProperty("forecast")>
    Public Property Forecast As Forecast()

    <JsonProperty("continent")>
    Public Property Continent As String

    <JsonProperty("country")>
    Public Property Country As String

    <JsonProperty("location")>
    Public Property Location As String

    <JsonProperty("latitude")>
    Public Property Latitude As Double

    <JsonProperty("longitude")>
    Public Property Longitude As Double

    <JsonProperty("timezone")>
    Public Property Timezone As Integer
End Class

Public Class MetcheckData

    <JsonProperty("forecastLocation")>
    Public Property ForecastLocation As ForecastLocation
End Class

Public Class Metdata

    <JsonProperty("metcheckData")>
    Public Property MetcheckData As MetcheckData

    <JsonProperty("feedCreation")>
    Public Property FeedCreation As DateTime

    <JsonProperty("feedCreator")>
    Public Property FeedCreator As String

    <JsonProperty("feedModel")>
    Public Property FeedModel As String

    <JsonProperty("feedModelRun")>
    Public Property FeedModelRun As String

    <JsonProperty("feedModelRunInitialTime")>
    Public Property FeedModelRunInitialTime As DateTime

    <JsonProperty("feedResolution")>
    Public Property FeedResolution As String
End Class

dict.Metcheckdata.Forecastlocation.Forecast will contain your 155 records.


来源: stackexchange

问:
Java scanner to read character frequency from file
I'm trying to get a scanner to read the frequency of characters in the filepath, while using a scanner. What should I add to complete this method to do what I've described. Using a priority Queue.</p>

```<code>public static Huffman build(String filePath) throws IOException {
    if (filePath == null) {
        throw new NullPointerException("File doesn't exist");
    } else {
        try {
            Scanner file = new Scanner(new File(filePath));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        while (file.hasNextLine()) {
            Scanner s2 = new Scanner(file.nextLine());
            while (s2.hasNext()) {
                String s = s2.next();
                System.out.println(s);
            }
        }
    }
}
</code>```

答:
Well, this is an alternative solution if you don't want to use HasMap or PriorityQueue, You can use a simple frequency array of integer to store the no. of occurrence of all the letters. I have used integer array of size 128 to cover all type of characters including uppercase, lowercase, special character or numbers. (You can add this piece of code right after storing user's input to String s) </p>

```<code>    int[] count = new int[128]; // initially they all will be zero
    for(char ch:s.toCharArray()){
        count[ch]++;
    }
    for(int i=0;i<128;i++){
        if(count[i]!=0){
            System.out.println((char)i+":"+count[i]);
        }
    }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to get a scanner to read the frequency of characters in the filepath, while using a scanner. What should I add to complete this method to do what I've described. Using a priority Queue.

public static Huffman build(String filePath) throws IOException {
    if (filePath == null) {
        throw new NullPointerException("File doesn't exist");
    } else {
        try {
            Scanner file = new Scanner(new File(filePath));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        while (file.hasNextLine()) {
            Scanner s2 = new Scanner(file.nextLine());
            while (s2.hasNext()) {
                String s = s2.next();
                System.out.println(s);
            }
        }
    }
}

Body:
Well, this is an alternative solution if you don't want to use HasMap or PriorityQueue, You can use a simple frequency array of integer to store the no. of occurrence of all the letters. I have used integer array of size 128 to cover all type of characters including uppercase, lowercase, special character or numbers. (You can add this piece of code right after storing user's input to String s)

    int[] count = new int[128]; // initially they all will be zero
    for(char ch:s.toCharArray()){
        count[ch]++;
    }
    for(int i=0;i<128;i++){
        if(count[i]!=0){
            System.out.println((char)i+":"+count[i]);
        }
    }


问:
How to initialize the redux-form with dirty set true?
I have a save button binded to the dirty state, when form is dirty, enable the button, otherwise disable it.

This is good for editing an item. But when I add an item, the save button is disabled by default, because dirty is false by default.

Is there a way to set the form to dirty state?

答: You can control the save button state yourself. All you need to do is to not enable the Save/Submit button</p>

ContentLicense: CC BY-SA 3.0


问:
How can I call two external .js and two external .css to just one div?
How can I call two external .js and two external .css to just one div?

For example, "https://code.xxx.xx/xxx-3.1.0.min.js", "https://code.xxx.xx/xxx-3.1.0.js", "https://xxx.xx/xxx/xxx.css" and "https://yyy.yy/yyy/yyy.css" for only what is inside this div

Note 1, I do not want these external js and css to work on the rest of the page, just inside that div.

note 2, that I also do not want the js and css I use on the rest of the page to work inside that div with id = "test"

答:
What you are probably looking for are iframes:

Put the code you wanted in that div onto another page of your website, for example into an iframes path.
Then use an iframe instead of your div element:

```<code><iframe src="/iframes/test.html" frameborder="0"></iframe>
</code>```

Body:
What you are probably looking for are iframes:

Put the code you wanted in that div onto another page of your website, for example into an iframes path.
Then use an iframe instead of your div element:

<iframe src="/iframes/test.html" frameborder="0"></iframe>


问:
is there any way to trim words in _e() function
wp_trim_words is it works with _e() functions for translated text to limit the shown text ?

i have tried wordpress trim functions , and php trim wordpress length functions and did not works for me

```<code><?php
                         $txt = _e(' Lorem ipsum dolor sit amet, consectetur adipisicing elit. Consequuntur, distinctio, dolore! Amet atque, commodi consequuntur delectus deleniti eveniet expedita inventore laboriosam laborum, mollitia odit quia quidem recusandae repellendus suscipit tenetur.','domain');
                        echo wp_trim_words( $txt, 5 );
                        ?>
</code>```

expecting the translated text appear with words limits of 20 words for example

答:
Function _e( $text, $domain ) just print text and return null.
If you want to do something with txt you need to use function __( $text, $domain ) that return edited txt.

Change your code like that:

```<code><?php
$txt = __(' Lorem ipsum dolor sit amet, consectetur adipisicing elit. Consequuntur, distinctio, dolore! Amet atque, commodi consequuntur delectus deleniti eveniet expedita inventore laboriosam laborum, mollitia odit quia quidem recusandae repellendus suscipit tenetur.','domain');
echo wp_trim_words( $txt, 5 );
?>
</code>```

Body:
wp_trim_words is it works with _e() functions for translated text to limit the shown text ?

i have tried wordpress trim functions , and php trim wordpress length functions and did not works for me

<?php
                         $txt = _e(' Lorem ipsum dolor sit amet, consectetur adipisicing elit. Consequuntur, distinctio, dolore! Amet atque, commodi consequuntur delectus deleniti eveniet expedita inventore laboriosam laborum, mollitia odit quia quidem recusandae repellendus suscipit tenetur.','domain');
                        echo wp_trim_words( $txt, 5 );
                        ?>

expecting the translated text appear with words limits of 20 words for example

Body:
Function _e( $text, $domain ) just print text and return null.
If you want to do something with txt you need to use function __( $text, $domain ) that return edited txt.

Change your code like that:

<?php
$txt = __(' Lorem ipsum dolor sit amet, consectetur adipisicing elit. Consequuntur, distinctio, dolore! Amet atque, commodi consequuntur delectus deleniti eveniet expedita inventore laboriosam laborum, mollitia odit quia quidem recusandae repellendus suscipit tenetur.','domain');
echo wp_trim_words( $txt, 5 );
?>


问:
Simple Java name based locks?
MySQL has a handy function:

```<code>SELECT GET_LOCK("SomeName")
</code>```

This can be used to create simple, but very specific, name-based locks for an application. However, it requires a database connection.

I have many situations like:

```<code>someMethod() {
    // do stuff to user A for their data for feature X
}
</code>```

It doesn't make sense to simply synchronize this method, because, for example, if this method is called for user B in the meantime, user B does not need to wait for user A to finish before it starts, only operations for the user A and feature X combination need to wait.

With the MySql lock I could do something like:

```<code>someMethod() {
    executeQuery("SELECT GET_LOCK('userA-featureX')")
    // only locked for user A for their data for feature X
    executeQuery("SELECT RELEASE_LOCK('userA-featureX')")
}
</code>```

Since Java locking is based on objects, it seems like I would need to create a new object to represent the situation for this lock and then put it in a static cache somewhere so all the threads can see it. Subsequent requests to lock for that situation would then locate the lock object in the cache and acquire its lock. I tried to create something like this, but then the lock cache itself needs synchronization. Also, it is difficult to detect when a lock object is no longer being used so that it can be removed from the cache.

I have looked at the Java concurrent packages, but nothing stands out as being able to handle something like this. Is there an easy way to implement this, or am I looking at this from the wrong perspective?

Edit:

To clarify, I am not looking to create a predefined pool of locks ahead of time, I would like to create them on demand. Some pseudo-code for what I am thinking of is:

```<code>LockManager.acquireLock(String name) {
    Lock lock;

    synchronized (map) {
        lock = map.get(name);

        // doesn't exist yet - create and store
        if(lock == null) {
            lock = new Lock();
            map.put(name, lock);
        }
    }

    lock.lock();
}

LockManager.releaseLock(String name) {
    // unlock
    // if this was the last hold on the lock, remove it from the cache
}
</code>```

答:
For locking on something like a user name, in-memory Locks in a map might be a bit leaky. As an alternative, you could look at using WeakReferences with WeakHashMap to create mutex objects that can be garbage collected when nothing refers to them. This avoids you having to do any manual reference counting to free up memory.

You can find an implementation here. Note that if you're doing frequent lookups on the map you may run into contention issues acquiring the mutex.

Title: Simple Java name based locks?

Body:
MySQL has a handy function:

SELECT GET_LOCK("SomeName")

This can be used to create simple, but very specific, name-based locks for an application. However, it requires a database connection.

I have many situations like:

someMethod() {
    // do stuff to user A for their data for feature X
}

It doesn't make sense to simply synchronize this method, because, for example, if this method is called for user B in the meantime, user B does not need to wait for user A to finish before it starts, only operations for the user A and feature X combination need to wait.

With the MySql lock I could do something like:

someMethod() {
    executeQuery("SELECT GET_LOCK('userA-featureX')")
    // only locked for user A for their data for feature X
    executeQuery("SELECT RELEASE_LOCK('userA-featureX')")
}

Since Java locking is based on objects, it seems like I would need to create a new object to represent the situation for this lock and then put it in a static cache somewhere so all the threads can see it. Subsequent requests to lock for that situation would then locate the lock object in the cache and acquire its lock. I tried to create something like this, but then the lock cache itself needs synchronization. Also, it is difficult to detect when a lock object is no longer being used so that it can be removed from the cache.

I have looked at the Java concurrent packages, but nothing stands out as being able to handle something like this. Is there an easy way to implement this, or am I looking at this from the wrong perspective?

Edit:

To clarify, I am not looking to create a predefined pool of locks ahead of time, I would like to create them on demand. Some pseudo-code for what I am thinking of is:

LockManager.acquireLock(String name) {
    Lock lock;

    synchronized (map) {
        lock = map.get(name);

        // doesn't exist yet - create and store
        if(lock == null) {
            lock = new Lock();
            map.put(name, lock);
        }
    }

    lock.lock();
}

LockManager.releaseLock(String name) {
    // unlock
    // if this was the last hold on the lock, remove it from the cache
}


问:
ERROR: (gcloud.sql.instances.describe) HTTPError 404: The Cloud SQL instance does not exist, but it does exist?
I'm getting this error:

ERROR: (gcloud.sql.instances.describe) HTTPError 404: The Cloud SQL instance does not exist.

When calling:

gcloud sql instances describe my-project

from my windows cmd within the Google Cloud SDK Shell. However, when I look at my instances on my Google Cloud Platform interface I can see that the corresponding instance. All indicates that it DOES exist. Anyone have a solution?

答: LundinCast had the right answer in comments. Your problem can be resolved by following the instance name with --project="[projectname]".


问:
When using open() as f: does f represent a new variable being created?
I am new(ish) to Python and I'm just trying to figure out how things work. When I use:

```<code>with open('C:\\Users\\KB\\Documents\\DataProcessing.txt', 'r') as f:
</code>```

is f a new variable being created? Could I use any variable in its place? I've seen 'file' used as-well so I'm just wondering if this is an arbitrary name being assigned to a newly created variable? Could it be named anything or does it have to be f?

答:
is f a new variable being created? Could I use any variable in its place?

Yes

```<code>with open('testfile.txt') as f:
    print(f.read())
</code>```

is equivalent to

```<code>with open('testfile.txt') as lmnopqrstuvwxyz:
    print(lmnopqrstuvwxyz.read())
</code>```

Body:
I am new(ish) to Python and I'm just trying to figure out how things work. When I use:

with open('C:\\Users\\KB\\Documents\\DataProcessing.txt', 'r') as f:

is f a new variable being created? Could I use any variable in its place? I've seen 'file' used as-well so I'm just wondering if this is an arbitrary name being assigned to a newly created variable? Could it be named anything or does it have to be f?

Body:
is f a new variable being created? Could I use any variable in its place?

Yes

with open('testfile.txt') as f:
    print(f.read())

is equivalent to

with open('testfile.txt') as lmnopqrstuvwxyz:
    print(lmnopqrstuvwxyz.read())


问:
Javamelody with Struts 2 . No action mapped for monitoring
I got a Struts 2 , Java 8 web application running on Wildfly 10 and wanted to integrate Javamelody but i am unable to access the monitoring page no matter my configuration in the web.xml and struts.xml

I use the following maven dependency

```<code><dependency>
    <groupId>net.bull.javamelody</groupId>
    <artifactId>javamelody-core</artifactId>
    <version>1.77.0</version>
</dependency>
</code>```

In my web.xml (web-app version="3.0" ) i have the following configuration:

```<code><filter>
    <filter-name>monitoring</filter-name>
    <filter-class>net.bull.javamelody.MonitoringFilter</filter-class>
    <async-supported>true</async-supported>
</filter>
<filter-mapping>
    <filter-name>monitoring</filter-name>
    <url-pattern>/*</url-pattern>
    <dispatcher>REQUEST</dispatcher>
    <dispatcher>ASYNC</dispatcher>
</filter-mapping>
<listener>
    <listener-class>net.bull.javamelody.SessionListener</listener-class>
</listener>
</code>```

In my struts configuration following

```<code><interceptor-stack name="myStack">
    <interceptor-ref name="monitoring"/>
    <interceptor-ref name="defaultStack"/>
</interceptor-stack>
</code>```

and set myStack as default

```<code><default-interceptor-ref name="myStack" />
</code>```

When i try to access http://localhost:8080/myapp/monitoring i get following error:
[org.apache.struts2.dispatcher.Dispatcher] (default task-3) Could not find action or result: There is no Action mapped for namespace / and action name monitoring. - [unknown location]

I cannot find many resources on the web concerning this issue or configuration with Struts . Any ideas ?

Note: I am one step closer, but i don't get why this is happening.
I had to remove all filter that had a url-pattern /* for this to work.
Is there a workaround on this?  Of course with this configuration i cannot access any of my pages anymore.

答:
The javamelody user's guide says to write the javamelody MonitoringFilter in WEB-INF/web.xml before your servlet. But in the case of Struts 2, there is no more servlet and Struts 2 is controlled by a filter.

So you have to write the javamelody MonitoringFilter in WEB-INF/web.xml before your Struts 2 filter.

Body:
I got a Struts 2 , Java 8 web application running on Wildfly 10 and wanted to integrate Javamelody but i am unable to access the monitoring page no matter my configuration in the web.xml and struts.xml

I use the following maven dependency

<dependency>
    <groupId>net.bull.javamelody</groupId>
    <artifactId>javamelody-core</artifactId>
    <version>1.77.0</version>
</dependency>

In my web.xml (web-app version="3.0" ) i have the following configuration:

<filter>
    <filter-name>monitoring</filter-name>
    <filter-class>net.bull.javamelody.MonitoringFilter</filter-class>
    <async-supported>true</async-supported>
</filter>
<filter-mapping>
    <filter-name>monitoring</filter-name>
    <url-pattern>/*</url-pattern>
    <dispatcher>REQUEST</dispatcher>
    <dispatcher>ASYNC</dispatcher>
</filter-mapping>
<listener>
    <listener-class>net.bull.javamelody.SessionListener</listener-class>
</listener>

In my struts configuration following

<interceptor-stack name="myStack">
    <interceptor-ref name="monitoring"/>
    <interceptor-ref name="defaultStack"/>
</interceptor-stack>

and set myStack as default

<default-interceptor-ref name="myStack" />

When i try to access http://localhost:8080/myapp/monitoring i get following error:
[org.apache.struts2.dispatcher.Dispatcher] (default task-3) Could not find action or result: There is no Action mapped for namespace / and action name monitoring. - [unknown location]

I cannot find many resources on the web concerning this issue or configuration with Struts . Any ideas ?

Note: I am one step closer, but i don't get why this is happening.
I had to remove all filter that had a url-pattern /* for this to work.
Is there a workaround on this?  Of course with this configuration i cannot access any of my pages anymore.


问:
How to refuse a websocket handshake in a tornado websocket handler
So I'm doing a unittest of a tornado server I programmed which has a websocketHandler. This is my testing code:

```<code>def test_unauthorized_websocket(self):
    message = "Hey bro"
    ws = websocket.create_connection('ws://localhost:8888/ws', header=['Authorization: false'])
    send_dict = {'command': test_command, 'message': message}
    serialized_dict = json.dumps(send_dict)
    ws.send(serialized_dict)
    response = ws.recv()
    #test response with assert
</code>```

My goal with this test was to prove that my tornado server correctly refuses and closes this websocket connection because of wrong authentication header.
This is my tornado websocketHandler code:

```<code>class WebSocketHandler(tornado.websocket.WebSocketHandler):

   def open(self):
      #some code
      headers = self.request.headers
      try:
          auth = headers['Authorization']
      except KeyError:
          self.close(code = 1002, reason = "Unauthorized websocket")
          print("IT'S CLOSED")
          return

       if auth == "true":
          print("Authorized Websocket!")
          #some code
       else:
          print("Unauthorized Websocket... :-(")
          self.close(code = 1002, reason = "Unauthorized websocket")
</code>```

So when the authentication is wrong, self.close() is called (not sure I need code and reason). This should close the websocket. But this doesn't actually happens in the "client" side. After I call create_connection() in the "client" the ws.connected variable is still True, and when I do ws.send() the on_message method of the websocketHandler is still called and when it tries to make a response with self.write_message() it raises a WebSocketClosedError. And only then the "client" actually closes its side of the websocket, ws.recv() returns nothing and ws.connected turns to False after that.
Is there a way I can communicate to the client side (through handshake headers or something) that the websocket is meant to be closed earlier on its side?

答: You can override prepare() and raise a tornado.web.HTTPError, instead of overriding open() and calling self.close(). This will reject the connection at the first opportunity and this will be reported on the client side as a part of create_connection() instead of on a later read.

Body:
So I'm doing a unittest of a tornado server I programmed which has a websocketHandler. This is my testing code:

def test_unauthorized_websocket(self):
    message = "Hey bro"
    ws = websocket.create_connection('ws://localhost:8888/ws', header=['Authorization: false'])
    send_dict = {'command': test_command, 'message': message}
    serialized_dict = json.dumps(send_dict)
    ws.send(serialized_dict)
    response = ws.recv()
    #test response with assert

My goal with this test was to prove that my tornado server correctly refuses and closes this websocket connection because of wrong authentication header.
This is my tornado websocketHandler code:

class WebSocketHandler(tornado.websocket.WebSocketHandler):

   def open(self):
      #some code
      headers = self.request.headers
      try:
          auth = headers['Authorization']
      except KeyError:
          self.close(code = 1002, reason = "Unauthorized websocket")
          print("IT'S CLOSED")
          return

       if auth == "true":
          print("Authorized Websocket!")
          #some code
       else:
          print("Unauthorized Websocket... :-(")
          self.close(code = 1002, reason = "Unauthorized websocket")

So when the authentication is wrong, self.close() is called (not sure I need code and reason). This should close the websocket. But this doesn't actually happens in the "client" side. After I call create_connection() in the "client" the ws.connected variable is still True, and when I do ws.send() the on_message method of the websocketHandler is still called and when it tries to make a response with self.write_message() it raises a WebSocketClosedError. And only then the "client" actually closes its side of the websocket, ws.recv() returns nothing and ws.connected turns to False after that.
Is there a way I can communicate to the client side (through handshake headers or something) that the websocket is meant to be closed earlier on its side?


问:
Cocoa-Touch internals: How does the view know its controller?
If you add a subview to a view or add a view to a window, how does iOS know which controller this view belongs too?

Easy example:
Have a UIView without UIViewController and add it to the window [window addSubView:myView] --> it will not rotate.
Now use a UIViewController, have it implement shouldAutoRotateToInterfaceOrientation: and add the controller's view to the window: [window addSubView:myController.view] --> magically, the view will adjust to interface orientation.

But look at the code: in both cases a UIView was added. How can iOS possibly be aware that in the second case a UIViewController was involved?

I'm interested in how this is done internally. My best guess is that UIViewController.view is a setter which adds the controller to an internal array of controllers or assigns itself to some internal variable which holds the currently active controller.

答: Simple.  Look in UIView.h.  It's right there.  Each UIView has a pointer back to a UIViewController (which is apparently referred to as the "viewDelegate").


问:
Reverse the pointers in a linked list
Hello guys could you please help me in writing a procedure to reverse the pointers in a linked list . for example A->B->C->D would become A<-B<-C<-D without using extra linked list .

Edit:
------ okay guys so i have been looking for solution for this problem here is the code in case u want it :

```<code>    void reverse_list(){
    struct node *next, *current,*previous;
    previous = NULL;
    current =head;
    while(current != NULL){
    next = current->next;
    current->next = previous;
    previous=current;
    current = next;
    }
    head = previous;
    }
</code>```

答:
As you didn't mention if you are implementing the linked list yourself or not.

So firstly I am assuming that you are doing it by yourself. So following is an implementation of linked list and again its pointers are reversed to make the link list reverse. You can take an idea from it.

```<code>#include<stdio.h>
#include<stdlib.h>//for using malloc

struct Node//Defining a structure for linked list's node
{
    int info;//assuming it is an integer linked list
    struct Node *link;//this pointer links a node to it's immediate neighbor node
};

struct Node *head=NULL,*temp;//some initializations and declarations

void insertion(int data)//To insert elements to linked list
{
    struct Node *ptr;
    ptr=malloc(sizeof(*ptr));//creating a new node for the newcomer
    ptr->info=data;//taking the given integer value for the node to hold

    //initializing with null as the current node may be the last node and
    //if it is then it will point nobody
    //...but if it is not when a new node comes in the future it will eventually be
    //replaced to point the newcomer
    ptr->link=NULL;

    if(head==NULL)//head still null means we are creating the first node
    {             //handling the head separately as it has no parent node
        head=ptr;
        temp=ptr;//copying the current node's pointer to temp such that we can
        //find it as a parent of next node
    }
    else//for the rest of the nodes' creation
    {
        //as temp is the pointer to the previous node, so previous node is linking
        //to its next node, i.e, the current node
        temp->link=ptr;

        //updating the temp to point the current node such that it can act as a parent node
        //when the next node comes
        temp=ptr;
    }
}

void reversePointers()
{
    struct Node *trav,*from=NULL,*temp;
    for(trav=head;;)
    {
        if(trav->link==NULL)//if we have reached to the end
        {
            head=trav;//then the reverse linked list's head should point to the last element
            trav->link=from;//and making the second last node as it's next node
            break;
        }
        temp=trav;//saving current node pointer to update the "from" pointer
        trav=trav->link;//advancing current node pointer to forward
        temp->link=from;//making the current node to point to it's previous node
        from=temp;//saving current node's pointer which will be used in next iteration
    }
}

void traverse()//to traverse the nodes
{
    struct Node *ptr=head;
    while(ptr!=NULL)
    {
        printf("%d ",ptr->info);
        ptr=ptr->link;
    }
    printf("\n");
}

int main(void)
{
    int i,n,t;

    printf("Enter Number of elements: ");
    scanf("%d",&n);

    printf("Enter Elements: ");
    for(i=0;i<n;i++)
    {
        scanf("%d",&t);
        insertion(t);
    }
    printf("Before reversing the pointers the elements are: ");
    traverse();

    //let's reverse the pointers to make the list to go backward
    reversePointers();

    printf("After reversing the pointers the elements are: ");
    traverse();

}
</code>```

Secondly if you are using STL list then the approach is quite straightforward. Just use,

```<code>your_list_name.reverse()
</code>```

Again if you want to reverse the STL list just for iteration purpose then there is no need to actually reverse it. Instead you can use reverse iterator as following (say for an integer list):

```<code>for(list<int>::reverse_iterator it=your_list_name.rbegin();it!=your_list_name.rend();it++)
{
    //do whatever you want
}
</code>```

Title: Reverse the pointers in a linked list

Body:
Hello guys could you please help me in writing a procedure to reverse the pointers in a linked list . for example A->B->C->D would become A<-B<-C<-D without using extra linked list .

Edit:
------ okay guys so i have been looking for solution for this problem here is the code in case u want it :

    void reverse_list(){
    struct node *next, *current,*previous;
    previous = NULL;
    current =head;
    while(current != NULL){
    next = current->next;
    current->next = previous;
    previous=current;
    current = next;
    }
    head = previous;
    }

Body:
As you didn't mention if you are implementing the linked list yourself or not.

So firstly I am assuming that you are doing it by yourself. So following is an implementation of linked list and again its pointers are reversed to make the link list reverse. You can take an idea from it.

#include<stdio.h>
#include<stdlib.h>//for using malloc

struct Node//Defining a structure for linked list's node
{
    int info;//assuming it is an integer linked list
    struct Node *link;//this pointer links a node to it's immediate neighbor node
};

struct Node *head=NULL,*temp;//some initializations and declarations

void insertion(int data)//To insert elements to linked list
{
    struct Node *ptr;
    ptr=malloc(sizeof(*ptr));//creating a new node for the newcomer
    ptr->info=data;//taking the given integer value for the node to hold

    //initializing with null as the current node may be the last node and
    //if it is then it will point nobody
    //...but if it is not when a new node comes in the future it will eventually be
    //replaced to point the newcomer
    ptr->link=NULL;

    if(head==NULL)//head still null means we are creating the first node
    {             //handling the head separately as it has no parent node
        head=ptr;
        temp=ptr;//copying the current node's pointer to temp such that we can
        //find it as a parent of next node
    }
    else//for the rest of the nodes' creation
    {
        //as temp is the pointer to the previous node, so previous node is linking
        //to its next node, i.e, the current node
        temp->link=ptr;

        //updating the temp to point the current node such that it can act as a parent node
        //when the next node comes
        temp=ptr;
    }
}

void reversePointers()
{
    struct Node *trav,*from=NULL,*temp;
    for(trav=head;;)
    {
        if(trav->link==NULL)//if we have reached to the end
        {
            head=trav;//then the reverse linked list's head should point to the last element
            trav->link=from;//and making the second last node as it's next node
            break;
        }
        temp=trav;//saving current node pointer to update the "from" pointer
        trav=trav->link;//advancing current node pointer to forward
        temp->link=from;//making the current node to point to it's previous node
        from=temp;//saving current node's pointer which will be used in next iteration
    }
}

void traverse()//to traverse the nodes
{
    struct Node *ptr=head;
    while(ptr!=NULL)
    {
        printf("%d ",ptr->info);
        ptr=ptr->link;
    }
    printf("\n");
}

int main(void)
{
    int i,n,t;

    printf("Enter Number of elements: ");
    scanf("%d",&n);

    printf("Enter Elements: ");
    for(i=0;i<n;i++)
    {
        scanf("%d",&t);
        insertion(t);
    }
    printf("Before reversing the pointers the elements are: ");
    traverse();

    //let's reverse the pointers to make the list to go backward
    reversePointers();

    printf("After reversing the pointers the elements are: ");
    traverse();

}

Secondly if you are using STL list then the approach is quite straightforward. Just use,

your_list_name.reverse()

Again if you want to reverse the STL list just for iteration purpose then there is no need to actually reverse it. Instead you can use reverse iterator as following (say for an integer list):

for(list<int>::reverse_iterator it=your_list_name.rbegin();it!=your_list_name.rend();it++)
{
    //do whatever you want
}


问:
Why does my jumping algorithm not work FPS-independent?
I am trying to implement a simple algorithm for jumping, which should be FPS-independent. Unfortunately, the player jumps 1.6-1.9 blocks at 1-5 FPS, but 1.2 blocks at 60 FPS.

First of all, the acceleration becomes reduced by GRAVITY * time for the last frame. If the y-position is less than 0.15, the player is starting a new jump (yAcceleration is set to JUMP_POWER).

```<code>private static final float GRAVITY = 9;
private static final float JUMP_POWER = 4.4f;
private static final float TOLERANCE = 0.15f;

private float yAccleration;
private float positionY;

//delta is in seconds
private void update(float delta) {
    yAccleration -= GRAVITY * delta;

    if(positionY <= TOLERANCE) {
        yAccleration = JUMP_POWER;
    }

    float newYPosition = positionY + yAccleration * delta;
    if(newYPosition > 0) positionY = newYPosition;

}
</code>```

This is the code which I use to call update() in my test example:

```<code>final float fps = 60;
final float deltaSeconds = 1f / fps;
while(true) {
    update(deltaSeconds);
    Thread.sleep((int) Math.round(deltaSeconds * 1000));
}
</code>```

What do I have to change in order to make my algorithm FPS-independent?

答:
```<code>final float fps = 60;
final float deltaSeconds = 1f / fps;
</code>```

When i read this it was "WTF" right away. You cannot assume that delta will be 1/60th of a second. Moreover, it WILL BE NOT!

1/60 of a second is just your wait time. What about calculation? What about time required to actually get current time? What about redraw time? It all counts!

Insteed of using fixed unreal delta, just calculate actual time on every iteration.

```<code>final float fps = 60;
final float deltaSeconds = 1f / fps;
float t0=System.currentMilisecond();
while(true) {
    float t=Sytem.currentMiliseconds();
    float delta=t-t0;
    t0=t;
    update(delta);
    Thread.sleep((int) Math.round(deltaSeconds * 1000));
}
</code>```

You can try to force your framerate, but you always have to calculate actual time difference.

Body:
I am trying to implement a simple algorithm for jumping, which should be FPS-independent. Unfortunately, the player jumps 1.6-1.9 blocks at 1-5 FPS, but 1.2 blocks at 60 FPS.

First of all, the acceleration becomes reduced by GRAVITY * time for the last frame. If the y-position is less than 0.15, the player is starting a new jump (yAcceleration is set to JUMP_POWER).

private static final float GRAVITY = 9;
private static final float JUMP_POWER = 4.4f;
private static final float TOLERANCE = 0.15f;

private float yAccleration;
private float positionY;

//delta is in seconds
private void update(float delta) {
    yAccleration -= GRAVITY * delta;

    if(positionY <= TOLERANCE) {
        yAccleration = JUMP_POWER;
    }

    float newYPosition = positionY + yAccleration * delta;
    if(newYPosition > 0) positionY = newYPosition;

}

This is the code which I use to call update() in my test example:

final float fps = 60;
final float deltaSeconds = 1f / fps;
while(true) {
    update(deltaSeconds);
    Thread.sleep((int) Math.round(deltaSeconds * 1000));
}

What do I have to change in order to make my algorithm FPS-independent?

Body:
final float fps = 60;
final float deltaSeconds = 1f / fps;

When i read this it was "WTF" right away. You cannot assume that delta will be 1/60th of a second. Moreover, it WILL BE NOT!

1/60 of a second is just your wait time. What about calculation? What about time required to actually get current time? What about redraw time? It all counts!

Insteed of using fixed unreal delta, just calculate actual time on every iteration.

final float fps = 60;
final float deltaSeconds = 1f / fps;
float t0=System.currentMilisecond();
while(true) {
    float t=Sytem.currentMiliseconds();
    float delta=t-t0;
    t0=t;
    update(delta);
    Thread.sleep((int) Math.round(deltaSeconds * 1000));
}

You can try to force your framerate, but you always have to calculate actual time difference.


问:
regarding two dimensional arrays
if i have created an array like
int marks[4][2];
then the name of the array must give me the address of the first element,as is in case of one dimensional array,but it is not so?
& also

printf("%d",marks[0]);
&
printf("%d",marks);
 yield the same result?????????

答:
It behaves as expected for me:

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

int main(int argC,char* argV[])
{

  int marks[4][2]={0};
  printf("%x %x %x\n"
         "%x %x %x\n"
         "%x %x\n",
         marks,marks[0],marks[0][0],
         *marks,&marks,**marks,
         &marks[0],&marks[0][0]);
  return 0;
}
</code>```

Has output:

```<code>12ff44 12ff44 0
12ff44 12ff44 0
12ff44 12ff44
</code>```

All pointers to the first element of the list (except the zero which is the first element of the list).

Title: regarding two dimensional arrays

Body:
It behaves as expected for me:

#include <stdio.h>

int main(int argC,char* argV[])
{

  int marks[4][2]={0};
  printf("%x %x %x\n"
         "%x %x %x\n"
         "%x %x\n",
         marks,marks[0],marks[0][0],
         *marks,&marks,**marks,
         &marks[0],&marks[0][0]);
  return 0;
}

Has output:

12ff44 12ff44 0
12ff44 12ff44 0
12ff44 12ff44

All pointers to the first element of the list (except the zero which is the first element of the list).


问:
git commit error: version inconsistency between python 2 and python 3.7
I am using Python 3.7 for my project. Then when I tried to do

```<code>edamame$ git commit --amend --no-edit
</code>```

I got the follow error (git status works fine though):

```<code>Your PYTHONPATH points to a site-packages dir for Python 3.x but you are running Python 2.x!
     PYTHONPATH is currently: "/Users/edamame/tools/sim/scripting/:/usr/local/lib/python3.7/:/usr/local/lib/python3.7/site-packages/"
     You should `unset PYTHONPATH` to fix this.
</code>```

I tried the below but no luck:

```<code>edamame$ pip3 install git

Collecting git
  Could not find a version that satisfies the requirement git (from versions: )
No matching distribution found for git
</code>```

So I have to set the PYTHONPATH each time manually like below, which is very inconvenient. Any advise? Thanks!

```<code>edamame$ export PYTHONPATH=
</code>```

答:
The problem is that either your pre-commit or your post-commit hook uses Python 2.7.

You should open each of those in an editor and see if they're using Python 2.7 (by looking at the shebang), either a custom version, or one of /usr/bin/python, /usr/bin/python2, or /usr/bin/python2.7. If so, you should convert it to use Python 3 with an appropriate shebang or remove it (simply deleting it is sufficient).

If it came from another project or repository, you could try reinstalling a Python 3 version of that project instead, which would likely install a Python 3 version of your hook.

Body:
I am using Python 3.7 for my project. Then when I tried to do

edamame$ git commit --amend --no-edit

I got the follow error (git status works fine though):

Your PYTHONPATH points to a site-packages dir for Python 3.x but you are running Python 2.x!
     PYTHONPATH is currently: "/Users/edamame/tools/sim/scripting/:/usr/local/lib/python3.7/:/usr/local/lib/python3.7/site-packages/"
     You should `unset PYTHONPATH` to fix this.

I tried the below but no luck:

edamame$ pip3 install git

Collecting git
  Could not find a version that satisfies the requirement git (from versions: )
No matching distribution found for git

So I have to set the PYTHONPATH each time manually like below, which is very inconvenient. Any advise? Thanks!

edamame$ export PYTHONPATH=


问:
Why is Entity Framework generating the [Required] attribute on my computed column?
Simplified example: I have a computed column defined as a field in my Azure SQL server table.

```<code>CREATE TABLE [dbo].[MyTable]
(
  [Id] INT NOT NULL PRIMARY KEY IDENTITY,
  [CancelledOn] DATETIME NULL,
  [MyComputedColumn] AS CASE WHEN ([CancelledOn] IS NOT NULL) THEN 'Cancelled' ELSE 'Draft' END
)
</code>```

But when I generate a code-first ADO.NET Entity Data Model in Visual Studio 2017, the property gets generated with both [Required] and [DatabaseGenerated(DatabaseGeneratedOption.Computed)] attributes.

```<code>[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
[Required]
[StringLength(19)]
public string MyComputedColumn { get; set; }
</code>```

Of course, this then causes entity validation errors and various other problems.

Why would EF mark this property as [Required] when it also knows that it's a computed field?

I understand I can just delete the attribute, but I'm looking for a cleaner solution than having to manually delete the [Required] attribute from all my computed columns every time I regenerate my entity model.  Can I declare the column differently in SQL, for example?

答:
Thanks to @Shan's comment for nudging me in the right direction:

By the logic of MyComputedColumn its a not null, so EF marked it as
  required.

I couldn't just make the column NULLABLE as others suggested, so I had to add an impossible NULL case to the computed column:

```<code>[MyComputedColumn] AS CASE
  WHEN 2 = 1 THEN NULL
  WHEN [CancelledOn] IS NOT NULL THEN 'Cancelled'
  ELSE 'Draft' END
</code>```

It's a bit of a hack and I wish EF was smarter, but it no longer generates [Required], so it works for my purposes.

Body:
Simplified example: I have a computed column defined as a field in my Azure SQL server table.

CREATE TABLE [dbo].[MyTable]
(
  [Id] INT NOT NULL PRIMARY KEY IDENTITY,
  [CancelledOn] DATETIME NULL,
  [MyComputedColumn] AS CASE WHEN ([CancelledOn] IS NOT NULL) THEN 'Cancelled' ELSE 'Draft' END
)

But when I generate a code-first ADO.NET Entity Data Model in Visual Studio 2017, the property gets generated with both [Required] and [DatabaseGenerated(DatabaseGeneratedOption.Computed)] attributes.

[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
[Required]
[StringLength(19)]
public string MyComputedColumn { get; set; }

Of course, this then causes entity validation errors and various other problems.

Why would EF mark this property as [Required] when it also knows that it's a computed field?

I understand I can just delete the attribute, but I'm looking for a cleaner solution than having to manually delete the [Required] attribute from all my computed columns every time I regenerate my entity model.  Can I declare the column differently in SQL, for example?

Body:
Thanks to @Shan's comment for nudging me in the right direction:

By the logic of MyComputedColumn its a not null, so EF marked it as
  required.

I couldn't just make the column NULLABLE as others suggested, so I had to add an impossible NULL case to the computed column:

[MyComputedColumn] AS CASE
  WHEN 2 = 1 THEN NULL
  WHEN [CancelledOn] IS NOT NULL THEN 'Cancelled'
  ELSE 'Draft' END

It's a bit of a hack and I wish EF was smarter, but it no longer generates [Required], so it works for my purposes.


问:
Karma tests succeed but PhantomJS returns "An error was thrown in afterAll" SyntaxError: Unexpected token ','
All our karma unit tests seem to succeed in our automated build, but the PhantomJS runner returns a non-zero result to the build framework (TeamCity). The only error I can find in the logs is:

```<code>[17:53:31][JavaScript Unit Tests] PhantomJS 2.1.1 (Windows 8.0.0) ERROR
[17:53:31][JavaScript Unit Tests]   An error was thrown in afterAll
[17:53:31][JavaScript Unit Tests]   SyntaxError: Unexpected token ','
</code>```

The project is using:

AngularJS@1.4.8

karma@4.1.0

npm@6.9.0

Node.js@v12.3.1

karma.conf.js:

```<code>// Karma Configuration
module.exports = function (config) {
    config.set({
        browsers: ["PhantomJS"],
        files: [
            "scripts/vendor/angularjs/1.4.8/angular.js",
            "scripts/vendor/angularjs/1.4.8/angular-animate.js",
            "scripts/vendor/*.js",
            "scripts/angular/**/*.module.js",
            "scripts/angular/**/*.app.js",
            "scripts/angular/**/*.js",
            "scripts/angular/**/spec/*.spec.js"
        ],
        exclude: [
            "scripts/vendor/angular-1*.js",
            "scripts/vendor/angular-animate.js",
            "scripts/angular/anycastManagementApp/anycastManagement.app.js",
            "scripts/angular/cart/**/.js",
            "scripts/angular/cart/*.js",
            "scripts/vendor/bootstrap.min.js",
            "scripts/angular/angular-bootstrap-datetimepicker/**/*.*"
        ],
        plugins: [
            "karma-jasmine",
            "karma-jasmine-matchers",
            "karma-chrome-launcher",
            "karma-phantomjs-launcher",
            "karma-teamcity-reporter",
            "karma-spec-reporter",
            "karma-coverage"
        ],
        frameworks: ["jasmine", "jasmine-matchers"],
        port: 9000,
        logLevel: config.LOG_DEBUG,
        client: {
            jasmine: {
                random: false
            }
        }
    });
}
</code>```

Things I've tried:

Several different versions of karma/Node.js.

Some similar questions suggested that there is a race condition in our tests, and we should disable karma's default random ordering, but that didn't help.

There is no async anywhere in our .spec.js files.

My next steps: I suppose I'll begin disabling individual tests to see if any of them have an influence on this afterAll outcome.

Update: disabling all the tests via xdescribe didn't resolve the error. So I know the error is not related to the tests themselves but to some bug or incompatibility in the plugins/libraries.

答:
Apparently PhantomJS hasn't been updated since 2016 (v2.1.1) and is not an active project. It seems that the recommendation is to replace PhantomJS in your projects with ChromeHeadless.

Even the PhantomJS maintainer, Vitaliy Slobodin, said about ChromeHeadless:

I think people will switch to it, eventually. Chrome is faster and
  more stable than PhantomJS. And it doesn’t eat memory like crazy.

It would have been nice to find a headless browser that wasn't dependent on Google, but apparently PhantomJS was using a WebKit-based engine anyway, so we're not really losing any browser variety/breadth by making this change.

Following the instructions in the linked articles, my issue went away, sort of. I did run into another similar afterAll error related to a missing library reference. I suspect that this was the same error as with PhantomJS but was not being reported correctly. After switching to ChromeHeadless, the error was reported correctly and was easy to fix.

Body:
All our karma unit tests seem to succeed in our automated build, but the PhantomJS runner returns a non-zero result to the build framework (TeamCity). The only error I can find in the logs is:

[17:53:31][JavaScript Unit Tests] PhantomJS 2.1.1 (Windows 8.0.0) ERROR
[17:53:31][JavaScript Unit Tests]   An error was thrown in afterAll
[17:53:31][JavaScript Unit Tests]   SyntaxError: Unexpected token ','

The project is using:

AngularJS@1.4.8

karma@4.1.0

npm@6.9.0

Node.js@v12.3.1

karma.conf.js:

// Karma Configuration
module.exports = function (config) {
    config.set({
        browsers: ["PhantomJS"],
        files: [
            "scripts/vendor/angularjs/1.4.8/angular.js",
            "scripts/vendor/angularjs/1.4.8/angular-animate.js",
            "scripts/vendor/*.js",
            "scripts/angular/**/*.module.js",
            "scripts/angular/**/*.app.js",
            "scripts/angular/**/*.js",
            "scripts/angular/**/spec/*.spec.js"
        ],
        exclude: [
            "scripts/vendor/angular-1*.js",
            "scripts/vendor/angular-animate.js",
            "scripts/angular/anycastManagementApp/anycastManagement.app.js",
            "scripts/angular/cart/**/.js",
            "scripts/angular/cart/*.js",
            "scripts/vendor/bootstrap.min.js",
            "scripts/angular/angular-bootstrap-datetimepicker/**/*.*"
        ],
        plugins: [
            "karma-jasmine",
            "karma-jasmine-matchers",
            "karma-chrome-launcher",
            "karma-phantomjs-launcher",
            "karma-teamcity-reporter",
            "karma-spec-reporter",
            "karma-coverage"
        ],
        frameworks: ["jasmine", "jasmine-matchers"],
        port: 9000,
        logLevel: config.LOG_DEBUG,
        client: {
            jasmine: {
                random: false
            }
        }
    });
}

Things I've tried:

Several different versions of karma/Node.js.

Some similar questions suggested that there is a race condition in our tests, and we should disable karma's default random ordering, but that didn't help.

There is no async anywhere in our .spec.js files.

My next steps: I suppose I'll begin disabling individual tests to see if any of them have an influence on this afterAll outcome.

Update: disabling all the tests via xdescribe didn't resolve the error. So I know the error is not related to the tests themselves but to some bug or incompatibility in the plugins/libraries.


问:
Data Studio line chart baseline average
In Data Studio I want to create a line chart that shows two lines.  The first line is the average quantity from the previous year.  This is a single value calculated from last year's data that shows as a horizontal line.  The second line displays the running daily quantity for the current year.  My data source is BigQuery

I have the second line plotted with date as the dimension and current year's daily quantity as the metric.

I don't know how to plot the first line - the single number average from the previous year.

I tried creating a second data source for the average through a view and BigQuery Connector Custom Query.  I am unable to link the second data source through the date dimension because it is a single value

How do I plot the average?

答:
I instead added a running average by:

I Added the quantity again as a second metric with a "Sum" aggregation

In the editor of this new metric under "Apply Running Calculation" I selected "Running Average"

This at least gives me some type of baseline for comparison of current quantity.

Title: Data Studio line chart baseline average


问:
Simple CSS Positioning Question
Basically I'm trying to create a small div (header class) that sits on top of a main banner image div (banner class). I've been able to position it correctly when my browser window is maximized, but when I resize the browser the header div maintains the margins and shrinks down to much less than the banner's width. I realize this is because I have the margins set at fixed positions on the left and right so they're maintaining those positions... I'm just new to CSS and am not sure exactly what to do to prevent this from happening. I've been messing around with positioning for about an hour and just can't get it right.

CSS:

```<code><style type = "text/css">

body {
    background-color: #595959;
}

.header {
   background-color: #4CBB17;
    padding: 12px 0px 12px 0px;
    margin: 0px 137px 0px; 137px;
}

.banner {
    text-align: center;
}

</style>
</code>```

HTML:

```<code><html>
<head>
    <title>Thanks!</title>
    <link type="text/css" rel="stylesheet" href="style.css" />
</head>

<body>

    <div class="header">
    </div>

    <div class="banner">
        <img src="banner.jpg" />
    </div>

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

Any help would be much appreciated!

答:
either put the banner into the header div

or create a "wrapper" div for the whole site, if your banner image, for example, is 960px wide and that how wide you want the site to be a wrapper many be beneficial as you can center the wrapper and forget about trying to center everything inside it.. or even if then your banner is less you can then center it inside the #wrapper.. options ;)

CSS:

```<code>body {
  background-color: #595959;
}

#wrapper {
  width: 960px;
  margin: 0 auto;
}

.header {
  background-color: #4CBB17;
  padding: 12px 0;
}

.banner {
  text-align: center;
}
</code>```

HTML:

```<code><div id="wrapper">
    <div class="header">header text</div>

    <div class="banner">
        <img src="banner.jpg" style="width: 960px; height: 230px;" />
    </div>
</div>
</code>```

Title: Simple CSS Positioning Question

Body:
Basically I'm trying to create a small div (header class) that sits on top of a main banner image div (banner class). I've been able to position it correctly when my browser window is maximized, but when I resize the browser the header div maintains the margins and shrinks down to much less than the banner's width. I realize this is because I have the margins set at fixed positions on the left and right so they're maintaining those positions... I'm just new to CSS and am not sure exactly what to do to prevent this from happening. I've been messing around with positioning for about an hour and just can't get it right.

CSS:

HTML:

    <title>Thanks!</title>
    <link type="text/css" rel="stylesheet" href="style.css" />

Any help would be much appreciated!

Body:
either put the banner into the header div

or create a "wrapper" div for the whole site, if your banner image, for example, is 960px wide and that how wide you want the site to be a wrapper many be beneficial as you can center the wrapper and forget about trying to center everything inside it.. or even if then your banner is less you can then center it inside the #wrapper.. options ;)

CSS:

body {
  background-color: #595959;
}

#wrapper {
  width: 960px;
  margin: 0 auto;
}

.header {
  background-color: #4CBB17;
  padding: 12px 0;
}

.banner {
  text-align: center;
}

HTML:

<div id="wrapper">
    <div class="header">header text</div>

    <div class="banner">
        <img src="banner.jpg" style="width: 960px; height: 230px;" />
    </div>
</div>


问:
Why does jupyter notebook server keeps crashing when .ipynb files are opened?
I was able to use jupyter notebook 4 days ago. The only thing that changed was there was a firefox version update.

After that the server crashes everytime .ipynb files are opened. Even the directory will have a server error. I tried it both on Firefox and Google Chrome, both browsers will crash the server.

My only kernel is python3 and it always says "Kernel Busy". I tried resetting my pc and the jupyter notebook, but nothing seems to work.

The console showed:

The last 2 lines are causing the crash but I don't know how to fix it

When I type conda install jupyter in the anaconda prompt, I get something before it finishes as shown below. Maybe it might have a cause as to why it is having issues:

I created a new python environment and installed python, matplotlib, pandas, jupyter and it still crashes

答:
Do you let Jupyter start the browser? If so, disable that and start the browser manually. I don't see how the zmq error messages could be related to the browser startup, but since you say that the only change was a browser update, that's worth a shot.

Check which version of pyzmq is installed. If Jupyter Notebook and the kernel are in different conda envs, check both and make sure they are on the same version and build. Try upgrading or downgrading to different versions. According to Anaconda issue 8932, there are problems with pyzmq on Windows. And a new build for win32 was released about two weeks ago - though I would expect win64 builds to be used nowadays.

I also found some recommendations for a similar error message to yours in Spyder issue 6097. The first one is to try without firewall and/or antivirus. You might have picked up a new firewall rule unknowingly. Trying different versions of pyzmq is also mentioned there.


问:
Pandas: Handling Dataframes
A certain dataframe, has a similar break with the one below:

```<code>import pandas as pd

df = pd.DataFrame({'name': ['John', 'Elvis', 'Gerrard', 'Pitty'],
              'age': [22,23,24,25],
              'document': [111,222,333,4444]})
</code>```

How can I make a filter to return only the rows where the values in the document column are only 3 digits?

答:
log

```<code>df.query('2 <= log10(document) < 3')

      name  age  document
0     John   22       111
1    Elvis   23       222
2  Gerrard   24       333
</code>```

Expanded example

```<code>df = pd.DataFrame({
    'name': ['John', 'Elvis', 'Gerrard', 'Pitty'],
    'age': [22, 23, 24, 25],
    'document': [11, 222, 999, 1000]
})

df

      name  age  document
0     John   22        11  # 2 digit number
1    Elvis   23       222  # 3 digit number
2  Gerrard   24       999  # 3 digit number | edge case
3    Pitty   25      1000  # 4 digit number | edge case
</code>```

Let's get only 3 digit numbers

```<code>df.query('2 <= log10(document) < 3')

      name  age  document
1    Elvis   23       222
2  Gerrard   24       999
</code>```

Title: Pandas: Handling Dataframes

Body:
A certain dataframe, has a similar break with the one below:

import pandas as pd

df = pd.DataFrame({'name': ['John', 'Elvis', 'Gerrard', 'Pitty'],
              'age': [22,23,24,25],
              'document': [111,222,333,4444]})

How can I make a filter to return only the rows where the values in the document column are only 3 digits?

Body:
log

df.query('2 <= log10(document) < 3')

      name  age  document
0     John   22       111
1    Elvis   23       222
2  Gerrard   24       333

Expanded example

df = pd.DataFrame({
    'name': ['John', 'Elvis', 'Gerrard', 'Pitty'],
    'age': [22, 23, 24, 25],
    'document': [11, 222, 999, 1000]
})

df

      name  age  document
0     John   22        11  # 2 digit number
1    Elvis   23       222  # 3 digit number
2  Gerrard   24       999  # 3 digit number | edge case
3    Pitty   25      1000  # 4 digit number | edge case

Let's get only 3 digit numbers

df.query('2 <= log10(document) < 3')

      name  age  document
1    Elvis   23       222
2  Gerrard   24       999


问:
SQL Server stored procedure for updating a table in SQL Server 2012 with incorrect syntax error
I have the below stored procedure, and I am getting this error message:

Incorrect syntax near '01'

I have other stored procedures which begin with '01,' and they work ok. I'm not sure where the incorrect syntax is.

Thanks for any leads.

Here is my table structure:

```<code>CREATE TABLE [dbo].[01_news_test]
(
     [interestid] [INT] IDENTITY(1, 1) NOT FOR REPLICATION NOT NULL,
     [username]   [VARCHAR](50) NULL,
     [approval]   [BIT] NULL,

     CONSTRAINT [PK_news_test]
         PRIMARY KEY CLUSTERED ([interestid] DESC)
                     WITH (pad_index = OFF, statistics_norecompute = OFF,
                           ignore_dup_key = OFF, allow_row_locks = on,
                           allow_page_locks = on, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
</code>```

Here is the code for the stored procedure (below):

```<code>ALTER PROCEDURE [dbo].[01_cms_news_mgr_bull_appr_update]
    @InterestID INT,
    @Approval BIT
AS
    DECLARE @sql NVARCHAR(4000)

    SELECT @sql = ' UPDATE [01_news_test] ' +
              ' SET ' +
              ' Approval = @Approval ' +
              ' WHERE '

    IF @InterestID IS NOT NULL
        SELECT @sql = @sql + ' InterestID = @InterestID'

    SELECT @sql = @sql + '; '

    EXEC sp_executesql @sql, N'@InterestID INT, @Approval BIT', InterestID, Approval
</code>```

And, here is the code upon execution of the stored procedure in SQL Server Management Studio:

```<code>DECLARE @return_value INT

EXEC    @return_value = [dbo].[01_cms_news_mgr_bull_appr_update]
               @InterestID = 1,
               @Approval = 0

SELECT  'Return Value' = @return_value
GO
</code>```

Finally, the resulting error msg:

Msg 102, Level 15, State 1, Line 1

  Incorrect syntax near '01'

Update: adding a bracket around the table name fixed the 'incorrect syntax error,' although I now am getting an error

Error converting data type nvarchar to int

答:
Your 01_cms_new_mgr_bull_appr_update stored proc doesn't explicitly return a value, so, it is probably returning either 0 or -1, indicating the proc completed or failed for some reason.

Then, your statement:

```<code>SELECT  'Return Value' = @return_value
GO
</code>```

Would not be returning a column named [Return Value] with a value of @return_value.  It would probably be trying to assign the @return_value (int) to the const char string 'Return Value'.  You could try:

```<code>SELECT @return_value AS return_value
GO
</code>```

OR

```<code>SELECT 'Return Value = ' + @return_value AS return_string
GO
</code>```

Body:
I have the below stored procedure, and I am getting this error message:

Incorrect syntax near '01'

I have other stored procedures which begin with '01,' and they work ok. I'm not sure where the incorrect syntax is.

Thanks for any leads.

Here is my table structure:

CREATE TABLE [dbo].[01_news_test]
(
     [interestid] [INT] IDENTITY(1, 1) NOT FOR REPLICATION NOT NULL,
     [username]   [VARCHAR](50) NULL,
     [approval]   [BIT] NULL,

     CONSTRAINT [PK_news_test]
         PRIMARY KEY CLUSTERED ([interestid] DESC)
                     WITH (pad_index = OFF, statistics_norecompute = OFF,
                           ignore_dup_key = OFF, allow_row_locks = on,
                           allow_page_locks = on, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

Here is the code for the stored procedure (below):

ALTER PROCEDURE [dbo].[01_cms_news_mgr_bull_appr_update]
    @InterestID INT,
    @Approval BIT
AS
    DECLARE @sql NVARCHAR(4000)

    SELECT @sql = ' UPDATE [01_news_test] ' +
              ' SET ' +
              ' Approval = @Approval ' +
              ' WHERE '

    IF @InterestID IS NOT NULL
        SELECT @sql = @sql + ' InterestID = @InterestID'

    SELECT @sql = @sql + '; '

    EXEC sp_executesql @sql, N'@InterestID INT, @Approval BIT', InterestID, Approval

And, here is the code upon execution of the stored procedure in SQL Server Management Studio:

DECLARE @return_value INT

EXEC    @return_value = [dbo].[01_cms_news_mgr_bull_appr_update]
               @InterestID = 1,
               @Approval = 0

SELECT  'Return Value' = @return_value
GO

Finally, the resulting error msg:

Msg 102, Level 15, State 1, Line 1

  Incorrect syntax near '01'

Update: adding a bracket around the table name fixed the 'incorrect syntax error,' although I now am getting an error

Error converting data type nvarchar to int

Body:
Your 01_cms_new_mgr_bull_appr_update stored proc doesn't explicitly return a value, so, it is probably returning either 0 or -1, indicating the proc completed or failed for some reason.

Then, your statement:

SELECT  'Return Value' = @return_value
GO

Would not be returning a column named [Return Value] with a value of @return_value.  It would probably be trying to assign the @return_value (int) to the const char string 'Return Value'.  You could try:

SELECT @return_value AS return_value
GO

OR

SELECT 'Return Value = ' + @return_value AS return_string
GO


问:
MySQL, recover database after mysqlbinlog loading error?
I am copying a MySQL DB from an initial dump file and the set of binlogs created after the dump.

The initial load from the dump is fine. Then, while loading the binlogs using mysqlbinlog, what happens is that one of the files will fail, for example, with a "server has gone away" error.

Is there any way to recover from a failed mysqlbinlog run, or is the database copy now irreparably corrupted? I know which log has failed, but I can't just rerun that log since the error could have occurred at any query within the log.

Is there a way to handle this moving forward?

I can look into minimizing the chances that there will be an error in the first place, but it doesn't seem like much of a recovery process (or master/slave process) if any MySQL issue during the loading completely ruins the database. I feel that I must be missing something.

答:
I'd check the configuration value for max_allowed_packet. This is pretty small by default (4MB or 64MB depending on MySQL version). You might need to increase it.

Note that you need to increase that option both in the server and in the client that is applying binlogs. The effective limit on packet size is the lesser of the server and client's configuration value.

Even if the binlog succeeded through replication, it might not succeed when replaying binlogs, because you need to replay with mysql while specifying  the --max-allowed-packet option.

See https://dev.mysql.com/doc/refman/8.0/en/gone-away.html for more explanation of the error you got.

If you don't know the binlog coordinates of the last binlog event that succeeded, you'll have to start over: remove the partially-restored instance and restore from the backup again, then apply the binlog.