问:
Closing MySQL Database Connections in java
I am having issues with my software becoming slow after some minutes of use. I figured out that the problems could be because I'm having numerous connections which i don't close. I have one java class with my Database connection from which i call the connect function to the various parts of the software that I need to execute queries. I don't know at which point I should close my connections because if I attempt to close after each query I can't have the query redone since I get the error 'Query cant be done after database connection is closed'. When I put it in my DB connection class, immediately after login, I cant execute any query. At what point should I put the db close function?
The following is my connection class.

```<code>public class databaseConnection {
   public static Connection connection(){
       Connection con = null;
       try{
           //test server
          //con = DriverManager.getConnection("jdbc:mysql://194.5.156.94:3306/u843360242_tukule?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC","user","password");
          //real server
        con = DriverManager.getConnection("jdbc:mysql://254gamers2.softether.net:3306/tukule_kwanza?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC","user","password");
       //localhost server
         //con = DriverManager.getConnection("jdbc:mysql://localhost:3306/tukule?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC","root","password");
       }catch (SQLException ex) {
            try{
           //test server
          //con = DriverManager.getConnection("jdbc:mysql://194.5.156.94:3306/u843360242_tukule?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC","user","password");
          //real server
          con = DriverManager.getConnection("jdbc:mysql://kwanzatukule.ddns.net:3306/tukule_kwanza?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC","user","password");
       }catch (SQLException x) {
            Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
        }
        }
       return con;
   }
}
</code>```

I need the queries in various parts of the software as follows.

```<code>public ArrayList categoriesQuery() {
       String query2 = "SELECT * FROM category";
        ArrayList categories = new ArrayList();
    try {
            pst = connect.prepareStatement(query2);
            rs=pst.executeQuery();
            while(rs.next()){
                Object o[]={rs.getInt("id"),
                            rs.getString("Category_Name")
                            };
                categories.add(o);
            }
          } catch (SQLException ex) {
            Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
        }
    return categories;
    }
</code>```

At what point should I put my db connect function.

答:
The code for closing connection should be written in finally block, so that if there is some error while performing database operations, then also the connection gets closed. You can do as follows :</p>

```<code>public ArrayList categoriesQuery() {
       //your code
       Connection connect=null;
    try {
            connect = databaseConnection.connection();
            if(connect!=null){
                //your code for database operations
            }
          } catch (SQLException ex) {
            Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
        }
        finally{
            if(connect!=null){
                connect.close();
            }
        }
    return categories;
}
</code>```

Body:
I am having issues with my software becoming slow after some minutes of use. I figured out that the problems could be because I'm having numerous connections which i don't close. I have one java class with my Database connection from which i call the connect function to the various parts of the software that I need to execute queries. I don't know at which point I should close my connections because if I attempt to close after each query I can't have the query redone since I get the error 'Query cant be done after database connection is closed'. When I put it in my DB connection class, immediately after login, I cant execute any query. At what point should I put the db close function?
The following is my connection class.

public class databaseConnection {
   public static Connection connection(){
       Connection con = null;
       try{
           //test server
          //con = DriverManager.getConnection("jdbc:mysql://194.5.156.94:3306/u843360242_tukule?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC","user","password");
          //real server
        con = DriverManager.getConnection("jdbc:mysql://254gamers2.softether.net:3306/tukule_kwanza?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC","user","password");
       //localhost server
         //con = DriverManager.getConnection("jdbc:mysql://localhost:3306/tukule?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC","root","password");
       }catch (SQLException ex) {
            try{
           //test server
          //con = DriverManager.getConnection("jdbc:mysql://194.5.156.94:3306/u843360242_tukule?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC","user","password");
          //real server
          con = DriverManager.getConnection("jdbc:mysql://kwanzatukule.ddns.net:3306/tukule_kwanza?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC","user","password");
       }catch (SQLException x) {
            Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
        }
        }
       return con;
   }
}

I need the queries in various parts of the software as follows.

public ArrayList categoriesQuery() {
       String query2 = "SELECT * FROM category";
        ArrayList categories = new ArrayList();
    try {
            pst = connect.prepareStatement(query2);
            rs=pst.executeQuery();
            while(rs.next()){
                Object o[]={rs.getInt("id"),
                            rs.getString("Category_Name")
                            };
                categories.add(o);
            }
          } catch (SQLException ex) {
            Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
        }
    return categories;
    }

At what point should I put my db connect function.

Body:
The code for closing connection should be written in finally block, so that if there is some error while performing database operations, then also the connection gets closed. You can do as follows :

public ArrayList categoriesQuery() {
       //your code
       Connection connect=null;
    try {
            connect = databaseConnection.connection();
            if(connect!=null){
                //your code for database operations
            }
          } catch (SQLException ex) {
            Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
        }
        finally{
            if(connect!=null){
                connect.close();
            }
        }
    return categories;
}


来源: stackexchange

问:
TensorFlow: 'tf.image.rgb_to_yuv' not working
Currently I'm working on an image encoder implementation with tensorflow, and in order to transform from RGB- to YUV-colorspace, I wanted to use the tensorflow function tf.image.rgb_to_yuv, which appears not to exist (although it's documented here: https://www.tensorflow.org/api_docs/python/tf/image/rgb_to_yuv), since I get the error message:

AttributeError: module 'tensorflow.python.ops.image_ops' has no attribute 'rgb_to_yuv'

I'm using Tensorflow 1.8. For example, the analogue HSV-transformation  tf.image.rgb_to_hsv works properly, so it appears to be a special issue related only to the rgb_to_yuv transform. Maybe it has something to do with the transition to the 1.x versions of Tensorflow, in which certain functions got new names, but I could not find anything about it. Does someone know, what's going on here?

Thanks in advance

答:
I believe the documentation is incorrect. The range of U and V are supposed to be [-0.436, 0.436] and [-0.615, 0.615].

https://en.wikipedia.org/wiki/YUV#Conversion_to/from_RGB

The kernel used in the TF source allows the U to go beyond that range, all the way to [-0.43601035, 0.43601035].

https://github.com/tensorflow/tensorflow/blob/v2.2.0/tensorflow/python/ops/image_ops_impl.py

Finally, The YUV-RGB matrix used in the TF source is for linear RGB, not the gamma corrected sRGB we are used to using online.

Based on my initial research, my hypothesis is that the best approach is probably to implement your own sRGB to YCbCR conversion. YCbCr was designed for gamma corrected sRGB. I'm working on it and I'll repost here once I've tested it.

ContentLicense: CC BY-SA 4.0


问:
Polling online printer Queue via Android background service Kotlin
I'm having issues with trying to poll a print queue which is hosted online

Essentially the point of the print queue is that when you call the url address if there is an item in the queue it returns it, if not it returns nothing i.e. timeout
The print queue is emptied by 1 on each call

-- Removed --

** Edit ** Tested this code actually works if the app is open and in the background, but not when the app is closed. I would ideally like to cover that

Alternate solutions welcome here is my code:

Printer Service

```<code>override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        super.onStartCommand(intent, flags, startId)
        mRunning = true
        Thread{
            while(mRunning){
                Thread.sleep(30000)
                val response = transmit
                    .sendRequestManual("printerURL")
                if (response != null){
                    val openData = response.getElementsByTagName("printdata")
                    if(openData.length > 0){
                        for (socket in sockets) {
                            /* Bluetooth Printers */
                            write(openData.item(0).textContent, socket)
                        }
                    }
                }
            }
        }.start()
        return START_STICKY
    }
</code>```

where mRunning is set to false if the service is destroyed

Transmit

```<code>fun sendRequestManual(sendURL: String): Document?{
        /* create the XML form to be sent */
        val client = OkHttpClient()
        val blockingQueue: BlockingQueue<Document> = ArrayBlockingQueue(1)

        val request = Request.Builder()
            .url(sendURL)
            .get()
            .build()

        client.newCall(request).enqueue(object: Callback{
            override fun onFailure(call: Call, e: IOException){
                /* onFailure is called each time */
            }

            override fun onResponse(call: Call, response: Response) {
                if(!response.isSuccessful){

                } else {
                    responseXML = response.body?.string()
                    blockingQueue.add(parseStringXMLDoc(responseXML!!))
                }
            }
        })
        return blockingQueue.poll(10,TimeUnit.SECONDS)
    }
</code>```

Manifest

```<code>       <service
            android:name=".services.PrintService"
            android:enabled="true"
            android:exported="false"
            android:stopWithTask="false"/>
</code>```

答:
<s>My code was not polling correctly, still seeking answer for polling on app close</s>

<s>Increased blocking queue time to 90 seconds</s>

So I have solved this issue, to correctly poll a server using okHTTP we need to set the response and connection time via the builder

```<code>var client = OkHttpClient().newBuilder()
        .connectTimeout(90,TimeUnit.SECONDS)
        .readTimeout(15,TimeUnit.SECONDS)
        .build()
</code>```

Essentially when the request is made the app will try to connect for up to 90 seconds, if a connection is made the server has 15 seconds to send it's data.

I removed

```<code>Thread.sleep(30000)
</code>```

because it was causing a gap in the polling, making me think it wasn't working.

I increased

```<code>blockingQueue.poll(10,TimeUnit.SECONDS)
</code>```

to 90 seconds to match the server connection time, the blocking queue will stop waiting as soon as data is received

So Essentially whenever a request is made the server has 90 seconds to connect, if not the app sends a new request.
If the server does respond, after processing the result, a new request is made and sent, which is perfect for this intended purpose (reading off a printer queue)

Body:
I'm having issues with trying to poll a print queue which is hosted online

Essentially the point of the print queue is that when you call the url address if there is an item in the queue it returns it, if not it returns nothing i.e. timeout
The print queue is emptied by 1 on each call

-- Removed --

** Edit ** Tested this code actually works if the app is open and in the background, but not when the app is closed. I would ideally like to cover that

Alternate solutions welcome here is my code:

Printer Service

override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        super.onStartCommand(intent, flags, startId)
        mRunning = true
        Thread{
            while(mRunning){
                Thread.sleep(30000)
                val response = transmit
                    .sendRequestManual("printerURL")
                if (response != null){
                    val openData = response.getElementsByTagName("printdata")
                    if(openData.length > 0){
                        for (socket in sockets) {
                            /* Bluetooth Printers */
                            write(openData.item(0).textContent, socket)
                        }
                    }
                }
            }
        }.start()
        return START_STICKY
    }

where mRunning is set to false if the service is destroyed

Transmit

fun sendRequestManual(sendURL: String): Document?{
        /* create the XML form to be sent */
        val client = OkHttpClient()
        val blockingQueue: BlockingQueue<Document> = ArrayBlockingQueue(1)

        val request = Request.Builder()
            .url(sendURL)
            .get()
            .build()

        client.newCall(request).enqueue(object: Callback{
            override fun onFailure(call: Call, e: IOException){
                /* onFailure is called each time */
            }

            override fun onResponse(call: Call, response: Response) {
                if(!response.isSuccessful){

                } else {
                    responseXML = response.body?.string()
                    blockingQueue.add(parseStringXMLDoc(responseXML!!))
                }
            }
        })
        return blockingQueue.poll(10,TimeUnit.SECONDS)
    }

Manifest

       <service
            android:name=".services.PrintService"
            android:enabled="true"
            android:exported="false"
            android:stopWithTask="false"/>

Body:
<s>My code was not polling correctly, still seeking answer for polling on app close</s>

<s>Increased blocking queue time to 90 seconds</s>

So I have solved this issue, to correctly poll a server using okHTTP we need to set the response and connection time via the builder

var client = OkHttpClient().newBuilder()
        .connectTimeout(90,TimeUnit.SECONDS)
        .readTimeout(15,TimeUnit.SECONDS)
        .build()

Essentially when the request is made the app will try to connect for up to 90 seconds, if a connection is made the server has 15 seconds to send it's data.

I removed

Thread.sleep(30000)

because it was causing a gap in the polling, making me think it wasn't working.

I increased

blockingQueue.poll(10,TimeUnit.SECONDS)

to 90 seconds to match the server connection time, the blocking queue will stop waiting as soon as data is received

So Essentially whenever a request is made the server has 90 seconds to connect, if not the app sends a new request.
If the server does respond, after processing the result, a new request is made and sent, which is perfect for this intended purpose (reading off a printer queue)


问:
How to display java swing on X11 when running on Mac
I would really like to be able to run our test suite on Xvfb so that swing windows don't keep popping up in the way of my work. Unfortunately I cannot seem to find a way to get the java runtime to use the display specified in the DISPLAY environment variable. I suppose this is because the Mac JDK is hardwired to use the (non-X-based) Mac display.

I can't find any switches for the java command that say to use X either.

Thanks in advance for any help you can give!
Matt

答:
I am doing it, but I am cheating by using Docker.

Download and install latest docker desktop.

docker pull this
image:

docker pull openjdk

If you want to display on mac, make sure to install XQuartz.

Ditto: In preferences, security, check both boxes for authentication and allow network

Ditto from mac or system with xwindows: (you have set DISPLAY environment variable)

xhost + $DISPLAY
(on Mac OS X this command will also launch XQuartz)

Run Java in docker (lots of information on the docker hub web page)

docker run  -e DISPLAY /bin/bash
(this line passes the contents of the DISPLAY environment variable)

It is also possible to install alternate forms of java into various docker images. In this example you won't be able to display in xwindows unless you additionally :

```<code>apt-get install  -y libxext-dev libxrender-dev libxtst-dev
</code>```

as part of your "RUN" section in the docker file. using the update-alternatives script does not handle dependencies. I have gotten Java 7 working following those instructions and adding the X libraries.

-

ContentLicense: CC BY-SA 2.5

Body:
I am doing it, but I am cheating by using Docker.

Download and install latest docker desktop.

docker pull this
image:

docker pull openjdk

If you want to display on mac, make sure to install XQuartz.

Ditto: In preferences, security, check both boxes for authentication and allow network

Ditto from mac or system with xwindows: (you have set DISPLAY environment variable)

xhost + $DISPLAY
(on Mac OS X this command will also launch XQuartz)

Run Java in docker (lots of information on the docker hub web page)

docker run  -e DISPLAY /bin/bash
(this line passes the contents of the DISPLAY environment variable)

It is also possible to install alternate forms of java into various docker images. In this example you won't be able to display in xwindows unless you additionally :

apt-get install  -y libxext-dev libxrender-dev libxtst-dev

as part of your "RUN" section in the docker file. using the update-alternatives script does not handle dependencies. I have gotten Java 7 working following those instructions and adding the X libraries.

-


问:
How will you convert method to single line in java8
I am having following method which converts single line to map

And want to convert it to single line statement using java8

input pipe separated string
e.g.:
status:MYSTATUS|data1:value1

```<code>public Map<String, String> getMap(String attributeUpdate){
    Map<String, String> attr = new HashMap<>();
    if(StringUtils.isNotEmpty(attributeUpdate)){
        List<String> a = Arrays.asList(attributeUpdate.split("\\|"));
        for (String s : a) {
            String[] key_val = s.split(":");
            if(key_val.length == 2) {
                attr.put(key_val[0], key_val[1]);
            }
        }
    }
    return attr;
}
</code>```

答:
You can try as below,</p>

```<code>Arrays.stream(attributeUpdate.split("\\|"))   //convert directly to stream
    .map(e->e.split(":"))
    .filter(e->e.length==2)
    .collect(toMap(s->s[0], s->s[1], (o, n)->n));  // collect map, handle duplicates
</code>```

Body:
I am having following method which converts single line to map

And want to convert it to single line statement using java8

input pipe separated string
e.g.:
status:MYSTATUS|data1:value1

public Map<String, String> getMap(String attributeUpdate){
    Map<String, String> attr = new HashMap<>();
    if(StringUtils.isNotEmpty(attributeUpdate)){
        List<String> a = Arrays.asList(attributeUpdate.split("\\|"));
        for (String s : a) {
            String[] key_val = s.split(":");
            if(key_val.length == 2) {
                attr.put(key_val[0], key_val[1]);
            }
        }
    }
    return attr;
}

Body:
You can try as below,

Arrays.stream(attributeUpdate.split("\\|"))   //convert directly to stream
    .map(e->e.split(":"))
    .filter(e->e.length==2)
    .collect(toMap(s->s[0], s->s[1], (o, n)->n));  // collect map, handle duplicates


问:
Create checkout session NBG
I would like to make a Basic HTTP authentication call request via javascript but I do not know how to do it.. I have a javascript code and inside of it there is a session parameter. Thus, I need to make first this call, get the session_id from this call as a response and continue my javascript code. This is the doc of this basic http auth: https://ibanke-commerce.nbg.gr/api/documentation/apiDocumentation/rest-json/version/latest/operation/Session%3a%20Create%20Checkout%20Session.html?locale=en_US

It is about payment option between bank and ecommerce.

How will this be written in javascript?
My code structure is like this for now:

```<code><script
//need call auth somewhere here I guess

Payment.Config({
... ... ..
Url: "...",
Name: "...",
session: "here I need the response of the call"
...
...
});
</script>
</code>```

Any help/guidelines would be appreciated

答:
You need three things:

1. Create you Basic Header for your authentication

The Basic Header is an Base64 encoded string of your user and
    password. To get that you should encode your credentials as shown below.

```<code>user_id:password
</code>```

In you case user_id is the merchantId

You can use online services like this to encode your credentials strings

Or

You can encode it in your javascript code like this

```<code>var clientId = "user_id";
var clientSecret = "password";

// var authorizationBasic = $.base64.btoa(clientId + ':' + clientSecret); // jQuery
var authorizationBasic = window.btoa(clientId + ':' + clientSecret); // Javascript
</code>```

I would recommend the first option.

2. Make your post request with the Basic Header

You can follow this answer on how to make an HTTP POST authentication basic request using Javascript

3. Use the response from the authentication request in your code

So your final code would be something like this

```<code>var url = 'your_url_server';
var authorizationBasic = 'the_created_basic_header';

var request = new XMLHttpRequest();
request.open('POST', url, true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.setRequestHeader('Authorization', 'Basic ' + authorizationBasic);
request.setRequestHeader('Accept', 'application/json'); // Modify according to the response format
request.send("parameter1=parameter1_value&parameter2=parameter2_value"); // Any parameter you might need

request.onreadystatechange = function () {
    if (request.readyState === 4) {
       alert(request.responseText);
       Payment.Config({
          ... ... ..
          Url: "...",
          Name: "...",
          session: request.responseText // Here is the response of the call
          ...
          ...
       });
    }
};
</code>```

Title: Create checkout session NBG

Body:
I would like to make a Basic HTTP authentication call request via javascript but I do not know how to do it.. I have a javascript code and inside of it there is a session parameter. Thus, I need to make first this call, get the session_id from this call as a response and continue my javascript code. This is the doc of this basic http auth: https://ibanke-commerce.nbg.gr/api/documentation/apiDocumentation/rest-json/version/latest/operation/Session%3a%20Create%20Checkout%20Session.html?locale=en_US

It is about payment option between bank and ecommerce.

How will this be written in javascript?
My code structure is like this for now:

Any help/guidelines would be appreciated

Body:
You need three things:

1. Create you Basic Header for your authentication

The Basic Header is an Base64 encoded string of your user and
    password. To get that you should encode your credentials as shown below.

user_id:password

In you case user_id is the merchantId

You can use online services like this to encode your credentials strings

Or

You can encode it in your javascript code like this

var clientId = "user_id";
var clientSecret = "password";

// var authorizationBasic = $.base64.btoa(clientId + ':' + clientSecret); // jQuery
var authorizationBasic = window.btoa(clientId + ':' + clientSecret); // Javascript

I would recommend the first option.

2. Make your post request with the Basic Header

You can follow this answer on how to make an HTTP POST authentication basic request using Javascript

3. Use the response from the authentication request in your code

So your final code would be something like this

var url = 'your_url_server';
var authorizationBasic = 'the_created_basic_header';

var request = new XMLHttpRequest();
request.open('POST', url, true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.setRequestHeader('Authorization', 'Basic ' + authorizationBasic);
request.setRequestHeader('Accept', 'application/json'); // Modify according to the response format
request.send("parameter1=parameter1_value&parameter2=parameter2_value"); // Any parameter you might need

request.onreadystatechange = function () {
    if (request.readyState === 4) {
       alert(request.responseText);
       Payment.Config({
          ... ... ..
          Url: "...",
          Name: "...",
          session: request.responseText // Here is the response of the call
          ...
          ...
       });
    }
};


问:
facing problem in panda column modification
I am facing a weird scenario.
I have a data frame with having 3 largest scores for unique row like this:

```<code>id   rid   code  score
1    9    67    43
1    8    87    22
1    4    32    20
2    3    56    43
3    10.  22    100
3.   5    67.    50
</code>```

Here  id column is same but row wise it is different.

I want to make my data frame like this:

```<code>id   first_code  second_code    third_code
1     67          87            32
2.    56.         none.         none
3     22.         67.           none
</code>```

So I have made my dataframe which is showing highest top 3 scores. If there is not top 3 value I am taking top 2 or the only value which is the score. So depending on score value, I want to re-arrange the code column into three different columns as example first_code is representing the highest_score, second_score is representing second-highest, third_code is representing the third highest value. If not found then I will make those blanks.

Kindly help me to solve this.

答:
Use GroupBy.cumcount for counter, create MultiIndex and reshape by Series.unstack:

```<code>df = df.set_index(['id',df.groupby('id').cumcount()])['code'].unstack()
df.columns=['first_code', 'second_code', 'third_code']
df = df.reset_index()
print (df)
    id  first_code  second_code  third_code
0  1.0        67.0         87.0        32.0
1  2.0        56.0          NaN         NaN
2  3.0        22.0         67.0         NaN
</code>```

Btw, cumcount should be used also in previous code for filter top3 values.

Body:
I am facing a weird scenario.
I have a data frame with having 3 largest scores for unique row like this:

id   rid   code  score
1    9    67    43
1    8    87    22
1    4    32    20
2    3    56    43
3    10.  22    100
3.   5    67.    50

Here  id column is same but row wise it is different.

I want to make my data frame like this:

id   first_code  second_code    third_code
1     67          87            32
2.    56.         none.         none
3     22.         67.           none

So I have made my dataframe which is showing highest top 3 scores. If there is not top 3 value I am taking top 2 or the only value which is the score. So depending on score value, I want to re-arrange the code column into three different columns as example first_code is representing the highest_score, second_score is representing second-highest, third_code is representing the third highest value. If not found then I will make those blanks.

Kindly help me to solve this.

Body:
Use GroupBy.cumcount for counter, create MultiIndex and reshape by Series.unstack:

df = df.set_index(['id',df.groupby('id').cumcount()])['code'].unstack()
df.columns=['first_code', 'second_code', 'third_code']
df = df.reset_index()
print (df)
    id  first_code  second_code  third_code
0  1.0        67.0         87.0        32.0
1  2.0        56.0          NaN         NaN
2  3.0        22.0         67.0         NaN

Btw, cumcount should be used also in previous code for filter top3 values.


问:
Why does this edge detector not work correctly when bitmap width not divisible by 4?
Using the Sobel edge detector code below I find that the output bitmap has a diagonal line of zero values superimposed over detected edges if the input bitmap has a width not divisible by 4. The red square marked in the output bitmap at co-ords (80,80) is broken up and incorrectly placed in this case. Why is this and how can I make the code work with any bitmap width?</p>

```<code>        private Bitmap SobelEdgeDetect2(Bitmap original, byte Threshold = 128)
    {

        // https://stackoverflow.com/questions/16747257/edge-detection-with-lockbits-c-sharp

        int width = original.Width;
        int height = original.Height;

        int BitsPerPixel = Image.GetPixelFormatSize(original.PixelFormat);
        int OneColorBits = BitsPerPixel / 8;

        BitmapData bmpData = original.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, original.PixelFormat);
        int position;
        int[,] gx = new int[,] { { -1, 0, 1 }, { -2, 0, 2 }, { -1, 0, 1 } };
        int[,] gy = new int[,] { { 1, 2, 1 }, { 0, 0, 0 }, { -1, -2, -1 } };

        Bitmap dstBmp = new Bitmap(width, height, original.PixelFormat);
        BitmapData dstData = dstBmp.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, dstBmp.PixelFormat);

        int byteCount = dstData.Stride * dstBmp.Height;
        byte[] input = new byte[byteCount];
        byte[] processed = new byte[byteCount];
        IntPtr ptr = bmpData.Scan0;
        IntPtr dst = dstData.Scan0;
        Marshal.Copy(ptr, input, 0, input.Length);
        Marshal.Copy(dst,processed, 0, input.Length);

        int BlackPoints = 0;
        int WhitePoints = 0;

        for (int i = 1; i < height - 1; i++) // y
        {
            for (int j = 1; j < width - 1; j++)  // x
                 {
                int NewX = 0, NewY = 0;

                for (int ii = 0; ii < 3; ii++)
                {
                    for (int jj = 0; jj < 3; jj++)
                    {
                        int I = i + ii - 1;
                        int J = j + jj - 1;

                            byte Current = input[(I * (width) + J) * OneColorBits];
                            NewX += gx[ii, jj] * Current;
                            NewY += gy[ii, jj] * Current;
                    }
                }
                position = (i * (width) + j) * OneColorBits;

                if (NewX * NewX + NewY * NewY > Threshold * Threshold)
                {
                    processed[position] = 255;
                    processed[position + 1] = 255;
                    processed[position + 2] = 255;
                    WhitePoints++;
                }
                else
                {
                    processed[position] = 0;
                    processed[position + 1] = 0;
                    processed[position + 2] = 0;
                    BlackPoints++;
                }

                if (j >= 78 && j <= 82 && i >= 78 && i <= 82)
                {
                    processed[position] = 0;
                    processed[position + 1] = 0;
                    processed[position + 2] = 255;
                }

            }

        }

        Marshal.Copy(processed, 0, dst, input.Length);
        dstBmp.UnlockBits(dstData);

        return dstBmp;
    }
</code>```

答:
For a 201 pixel wide bitmap, dstData.Stride was 604. For a 200 pixel wide bitmap dstData.Stride was 612, which explains why width had to be divisible by 4 for my code.

Replacing

```<code>position = (i * (width) + j) * OneColorBits;
</code>```

by

```<code>position = i * dstData.Stride + j * OneColorBits;
</code>```

and

```<code>byte Current = input[(I * (width) + J) * OneColorBits];
</code>```

by

```<code>byte Current = input[I * dstData.Stride + J * OneColorBits];
</code>```

fixed the problem.

Body:
Using the Sobel edge detector code below I find that the output bitmap has a diagonal line of zero values superimposed over detected edges if the input bitmap has a width not divisible by 4. The red square marked in the output bitmap at co-ords (80,80) is broken up and incorrectly placed in this case. Why is this and how can I make the code work with any bitmap width?

        private Bitmap SobelEdgeDetect2(Bitmap original, byte Threshold = 128)
    {

        // https://stackoverflow.com/questions/16747257/edge-detection-with-lockbits-c-sharp

        int width = original.Width;
        int height = original.Height;

        int BitsPerPixel = Image.GetPixelFormatSize(original.PixelFormat);
        int OneColorBits = BitsPerPixel / 8;

        BitmapData bmpData = original.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, original.PixelFormat);
        int position;
        int[,] gx = new int[,] { { -1, 0, 1 }, { -2, 0, 2 }, { -1, 0, 1 } };
        int[,] gy = new int[,] { { 1, 2, 1 }, { 0, 0, 0 }, { -1, -2, -1 } };

        Bitmap dstBmp = new Bitmap(width, height, original.PixelFormat);
        BitmapData dstData = dstBmp.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, dstBmp.PixelFormat);

        int byteCount = dstData.Stride * dstBmp.Height;
        byte[] input = new byte[byteCount];
        byte[] processed = new byte[byteCount];
        IntPtr ptr = bmpData.Scan0;
        IntPtr dst = dstData.Scan0;
        Marshal.Copy(ptr, input, 0, input.Length);
        Marshal.Copy(dst,processed, 0, input.Length);

        int BlackPoints = 0;
        int WhitePoints = 0;

        for (int i = 1; i < height - 1; i++) // y
        {
            for (int j = 1; j < width - 1; j++)  // x
                 {
                int NewX = 0, NewY = 0;

                for (int ii = 0; ii < 3; ii++)
                {
                    for (int jj = 0; jj < 3; jj++)
                    {
                        int I = i + ii - 1;
                        int J = j + jj - 1;

                            byte Current = input[(I * (width) + J) * OneColorBits];
                            NewX += gx[ii, jj] * Current;
                            NewY += gy[ii, jj] * Current;
                    }
                }
                position = (i * (width) + j) * OneColorBits;

                if (NewX * NewX + NewY * NewY > Threshold * Threshold)
                {
                    processed[position] = 255;
                    processed[position + 1] = 255;
                    processed[position + 2] = 255;
                    WhitePoints++;
                }
                else
                {
                    processed[position] = 0;
                    processed[position + 1] = 0;
                    processed[position + 2] = 0;
                    BlackPoints++;
                }

                if (j >= 78 && j <= 82 && i >= 78 && i <= 82)
                {
                    processed[position] = 0;
                    processed[position + 1] = 0;
                    processed[position + 2] = 255;
                }

            }

        }

        Marshal.Copy(processed, 0, dst, input.Length);
        dstBmp.UnlockBits(dstData);

        return dstBmp;
    }

Body:
For a 201 pixel wide bitmap, dstData.Stride was 604. For a 200 pixel wide bitmap dstData.Stride was 612, which explains why width had to be divisible by 4 for my code.

Replacing

position = (i * (width) + j) * OneColorBits;

by

position = i * dstData.Stride + j * OneColorBits;

and

byte Current = input[(I * (width) + J) * OneColorBits];

by

byte Current = input[I * dstData.Stride + J * OneColorBits];

fixed the problem.


问:
Can I get the name of the current controller in the view?
Is there a way to figure out what the current controller is from within the view?

For an example of why I would want to know this: if several controllers share the same layout, I may have a part in the layout ERB file where I want to highlight the current page's menu item based on the controller.

Maybe that is a bad approach. If so, what is the more preferred way to do this?

I'm interested to know about getting the name of the current controller either way, though.

(Obviously I could put something like @controller_name = 'users' in each controller; but that seems like the sort of thing Rails would've already done behind the scenes. So I'm just wondering if there's a built-in way.)

答:
If you want to use all stylesheet in your app just adds this line in application.html.erb. Insert it inside   tag

```<code>  <%= stylesheet_link_tag  controller.controller_name , media: 'all', 'data-turbolinks-track': 'reload' %>
</code>```

Also, to specify the same class CSS on a different controller

Add this line in the body of application.html.erb

```<code>  <body class="<%= controller.controller_name %>-<%= controller.action_name %>">
</code>```

So, now for example I would like to change the p tag in 'home' controller and 'index' action.
Inside index.scss file adds.

```<code>.nameOfController-nameOfAction <tag> { }
</code>```

```<code> .home-index p {
        color:red !important;
      }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
If you want to use all stylesheet in your app just adds this line in application.html.erb. Insert it inside <head>  tag

  <%= stylesheet_link_tag  controller.controller_name , media: 'all', 'data-turbolinks-track': 'reload' %>

Also, to specify the same class CSS on a different controller

Add this line in the body of application.html.erb

  <body class="<%= controller.controller_name %>-<%= controller.action_name %>">

So, now for example I would like to change the p tag in 'home' controller and 'index' action.
Inside index.scss file adds.

.nameOfController-nameOfAction <tag> { }

 .home-index p {
        color:red !important;
      }


问:
Getting latest lines of streaming stdout from a Python subprocess
My goal : To read the latest "chunk" (N lines) of streaming stdout every M seconds from a subprocess.

Current code:

start the subprocess

reads stdout

once I have a chunk of N lines, print it out (or save as current chunk)

wait M seconds

repeat

I have also put code for the moment to terminate the subprocess (which is an endless stream until you hit Ctrl-C)

What I want to achieve is after I wait for M seconds, if for it to always read the latest N lines and not the subsequent N lines in stdout (they can be discarded as I'm only interested in the latest)

My end goal would be to spawn a thread to run the process and keep saving the latest lines and then call from the main process whenever I need the latest results of the stream.

Any help would be greatly appreciated!

```<code>#!/usr/bin/env python3
import signal
import time
from subprocess import Popen, PIPE

sig = signal.SIGTERM

N=9
M=5

countlines=0
p = Popen(["myprogram"], stdout=PIPE, bufsize=1, universal_newlines=True)

chunk=[]

for line in p.stdout:
    countlines+=1
    chunk.append(line)

    if len(chunk)==N:
        print(chunk)
        chunk=[]
        time.sleep(M)

    if countlines>100:
        p.send_signal(sig)
        break

print("done")
</code>```

答:
Here is another possible solution.  It is a program that you would run as a separate process in the pipeline, which presents a REST API that when queried will return the last N lines that it read on stdin (where N and the port number are supplied on stdin).  It is using run in flask so should not be used in situations where the outside world has access to the local server port to make requests, though this could be adapted.

```<code>import sys
import time
import threading
import argparse
from flask import Flask, request
from flask_restful import Resource, Api

class Server:

    def __init__(self):
        self.data = {'at_eof': False,
                     'lines_read': 0,
                     'latest_lines': []}
        self.thread = None
        self.args = None
        self.stop = False

    def parse_args(self):
        parser = argparse.ArgumentParser()
        parser.add_argument("num_lines", type=int,
                            help="number of lines to cache")
        parser.add_argument("port", type=int,
                            help="port to serve on")
        self.args = parser.parse_args()

    def start_updater(self):
        def updater():
            lines = self.data['latest_lines']
            while True:
                if self.stop:
                    return
                line = sys.stdin.readline()
                if not line:
                    break
                self.data['lines_read'] += 1
                lines.append(line)
                while len(lines) > self.args.num_lines:
                    lines.pop(0)
            self.data['at_eof'] = True
        self.thread = threading.Thread(target=updater)
        self.thread.start()

    def get_data(self):
        return self.data

    def shutdown(self):
        self.stop = True
        func = request.environ.get('werkzeug.server.shutdown')
        if func:
            func()
            return 'Shutting down'
        else:
            return 'shutdown failed'

    def add_apis(self, app):

        class GetData(Resource):
            get = self.get_data

        class Shutdown(Resource):
            get = self.shutdown

        api = Api(app)
        api.add_resource(GetData, "/getdata")
        api.add_resource(Shutdown, "/shutdown")

    def run(self):
        self.parse_args()
        self.start_updater()
        app = Flask(__name__)
        self.add_apis(app)
        app.run(port=self.args.port)

server = Server()
server.run()
</code>```

Example usage: here is a test program whose output we want to serve:

```<code>import sys
import time

for i in range(100):
    print("this is line {}".format(i))
    sys.stdout.flush()
    time.sleep(.1)
</code>```

And a simple pipeline to launch it (here from the linux shell prompt but could be done via subprocess.Popen), serving the last 5 lines, on port 8001:

```<code>python ./writer.py  | python ./server.py 5 8001
</code>```

An example query, here using curl as the client but it could be done via Python requests:

```<code>$ curl -s http://localhost:8001/getdata
{"at_eof": false, "lines_read": 30, "latest_lines": ["this is line 25\n", "this is line 26\n", "this is line 27\n", "this is line 28\n", "this is line 29\n"]}
</code>```

The server also provides an http://localhost:<port>/shutdown URL to terminate it, though if you call it before you first see "at_eof": true, then expect the writer to die with a broken pipe.

Body:
My goal : To read the latest "chunk" (N lines) of streaming stdout every M seconds from a subprocess.

Current code:

start the subprocess

reads stdout

once I have a chunk of N lines, print it out (or save as current chunk)

wait M seconds

repeat

I have also put code for the moment to terminate the subprocess (which is an endless stream until you hit Ctrl-C)

What I want to achieve is after I wait for M seconds, if for it to always read the latest N lines and not the subsequent N lines in stdout (they can be discarded as I'm only interested in the latest)

My end goal would be to spawn a thread to run the process and keep saving the latest lines and then call from the main process whenever I need the latest results of the stream.

Any help would be greatly appreciated!

#!/usr/bin/env python3
import signal
import time
from subprocess import Popen, PIPE

sig = signal.SIGTERM

N=9
M=5

countlines=0
p = Popen(["myprogram"], stdout=PIPE, bufsize=1, universal_newlines=True)

chunk=[]

for line in p.stdout:
    countlines+=1
    chunk.append(line)

    if len(chunk)==N:
        print(chunk)
        chunk=[]
        time.sleep(M)

    if countlines>100:
        p.send_signal(sig)
        break

print("done")

Body:
Here is another possible solution.  It is a program that you would run as a separate process in the pipeline, which presents a REST API that when queried will return the last N lines that it read on stdin (where N and the port number are supplied on stdin).  It is using run in flask so should not be used in situations where the outside world has access to the local server port to make requests, though this could be adapted.

import sys
import time
import threading
import argparse
from flask import Flask, request
from flask_restful import Resource, Api

class Server:

    def __init__(self):
        self.data = {'at_eof': False,
                     'lines_read': 0,
                     'latest_lines': []}
        self.thread = None
        self.args = None
        self.stop = False

    def parse_args(self):
        parser = argparse.ArgumentParser()
        parser.add_argument("num_lines", type=int,
                            help="number of lines to cache")
        parser.add_argument("port", type=int,
                            help="port to serve on")
        self.args = parser.parse_args()

    def start_updater(self):
        def updater():
            lines = self.data['latest_lines']
            while True:
                if self.stop:
                    return
                line = sys.stdin.readline()
                if not line:
                    break
                self.data['lines_read'] += 1
                lines.append(line)
                while len(lines) > self.args.num_lines:
                    lines.pop(0)
            self.data['at_eof'] = True
        self.thread = threading.Thread(target=updater)
        self.thread.start()

    def get_data(self):
        return self.data

    def shutdown(self):
        self.stop = True
        func = request.environ.get('werkzeug.server.shutdown')
        if func:
            func()
            return 'Shutting down'
        else:
            return 'shutdown failed'

    def add_apis(self, app):

        class GetData(Resource):
            get = self.get_data

        class Shutdown(Resource):
            get = self.shutdown

        api = Api(app)
        api.add_resource(GetData, "/getdata")
        api.add_resource(Shutdown, "/shutdown")

    def run(self):
        self.parse_args()
        self.start_updater()
        app = Flask(__name__)
        self.add_apis(app)
        app.run(port=self.args.port)

server = Server()
server.run()

Example usage: here is a test program whose output we want to serve:

import sys
import time

for i in range(100):
    print("this is line {}".format(i))
    sys.stdout.flush()
    time.sleep(.1)

And a simple pipeline to launch it (here from the linux shell prompt but could be done via subprocess.Popen), serving the last 5 lines, on port 8001:

python ./writer.py  | python ./server.py 5 8001

An example query, here using curl as the client but it could be done via Python requests:

$ curl -s http://localhost:8001/getdata
{"at_eof": false, "lines_read": 30, "latest_lines": ["this is line 25\n", "this is line 26\n", "this is line 27\n", "this is line 28\n", "this is line 29\n"]}

The server also provides an http://localhost:<port>/shutdown URL to terminate it, though if you call it before you first see "at_eof": true, then expect the writer to die with a broken pipe.


问:
How can I get PCA cumulative proportion with Tidymodels?
I can apply PCA on the classic Iris dataset to obtain the cumulative proportion per dimension:

```<code>library(tidyverse)
x <- iris[,1:4] %>% as.matrix()
pca <- prcomp(x)
summary(pca)
</code>```

But I don't know how can I do that with tidymodels. My code so far is:

```<code>library(tidymodels)
iris_vars <- iris %>% select(-Species)
iris_rec <- recipe(~., iris_vars) %>%
  step_pca(all_predictors())
iris_prep <- prep(iris_rec)
iris_tidy <- tidy(iris_prep,1)
iris_tidy
summary(iris_tidy)
</code>```

I would like to obtain this with tidymodels:

```<code>Importance of components:
                          PC1     PC2    PC3     PC4
Standard deviation     2.0563 0.49262 0.2797 0.15439
Proportion of Variance 0.9246 0.05307 0.0171 0.00521
Cumulative Proportion  0.9246 0.97769 0.9948 1.00000
</code>```

Any help will be greatly appreciated.

答:
You can get the same results, if you use the same model. prcomp() defaults to center = TRUE, whereas step_pca() defaults to center = FALSE. In the following, I use centering and scaling for both (since this is often recommended).

library("tidymodels")

x <- iris[,1:4] %>% as.matrix()
pca <- prcomp(x, scale. = TRUE)
summary(pca)
#> Importance of components:
#>                           PC1    PC2     PC3     PC4
#> Standard deviation     1.7084 0.9560 0.38309 0.14393
#> Proportion of Variance 0.7296 0.2285 0.03669 0.00518
#> Cumulative Proportion  0.7296 0.9581 0.99482 1.00000

iris_rec <- recipe(Species ~ ., iris) %>%
    step_normalize(all_predictors()) %>%
    step_pca(all_predictors())
iris_prep <- prep(iris_rec)

summary(iris_prep$steps[[2]]$res)
#> Importance of components:
#>                           PC1    PC2     PC3     PC4
#> Standard deviation     1.7084 0.9560 0.38309 0.14393
#> Proportion of Variance 0.7296 0.2285 0.03669 0.00518
#> Cumulative Proportion  0.7296 0.9581 0.99482 1.00000
```

Created on 2020-05-29 by the reprex package (v0.3.0)

Body:
I can apply PCA on the classic Iris dataset to obtain the cumulative proportion per dimension:

library(tidyverse)
x <- iris[,1:4] %>% as.matrix()
pca <- prcomp(x)
summary(pca)

But I don't know how can I do that with tidymodels. My code so far is:

library(tidymodels)
iris_vars <- iris %>% select(-Species)
iris_rec <- recipe(~., iris_vars) %>%
  step_pca(all_predictors())
iris_prep <- prep(iris_rec)
iris_tidy <- tidy(iris_prep,1)
iris_tidy
summary(iris_tidy)

I would like to obtain this with tidymodels:

Importance of components:
                          PC1     PC2    PC3     PC4
Standard deviation     2.0563 0.49262 0.2797 0.15439
Proportion of Variance 0.9246 0.05307 0.0171 0.00521
Cumulative Proportion  0.9246 0.97769 0.9948 1.00000

Any help will be greatly appreciated.

Body:
You can get the same results, if you use the same model. prcomp() defaults to center = TRUE, whereas step_pca() defaults to center = FALSE. In the following, I use centering and scaling for both (since this is often recommended).

library("tidymodels")

x <- iris[,1:4] %>% as.matrix()
pca <- prcomp(x, scale. = TRUE)
summary(pca)
#> Importance of components:
#>                           PC1    PC2     PC3     PC4
#> Standard deviation     1.7084 0.9560 0.38309 0.14393
#> Proportion of Variance 0.7296 0.2285 0.03669 0.00518
#> Cumulative Proportion  0.7296 0.9581 0.99482 1.00000

iris_rec <- recipe(Species ~ ., iris) %>%
    step_normalize(all_predictors()) %>%
    step_pca(all_predictors())
iris_prep <- prep(iris_rec)

summary(iris_prep$steps[[2]]$res)
#> Importance of components:
#>                           PC1    PC2     PC3     PC4
#> Standard deviation     1.7084 0.9560 0.38309 0.14393
#> Proportion of Variance 0.7296 0.2285 0.03669 0.00518
#> Cumulative Proportion  0.7296 0.9581 0.99482 1.00000

Created on 2020-05-29 by the reprex package (v0.3.0)


问:
C How to capture closing a Terminal
Any idea on how to capture closing the terminal window that my program is running in?
While I'm at it, any way to capture when the computer is shutting down but the program is still running, or if the user logs off?</p>

答:
Try catching SIGTERM. Note that you can not capture SIGKILL which might be what happens during shutdown after a certain amount of time. I found this really nice post that explains some differences too.

[update] Longshot here but what about testing if std-in/out is still open and good? When the terminal dies those file descriptors should be scrapped. Disclaimer, this is a guess at best.

Title: C How to capture closing a Terminal


问:
BootStrap DatePicker Calendar Input Change Not Updating Calendar
I have an input element with an attached datepicker created using bootstrap-datepicker.
When the user changes the date by typing directly into the input element, and then clicks the calendar icon, the changed date is not reflected in the calendar</p>

```<code> <div class="col-lg-6 col-md-6 col-sm-6">

    <div class="input-append date" id="calendar_toDate" data-date="12/31/2999" data-date-format="mm/dd/yyyy"><input type="Text" alt="toDate" id="toDate" name="toDate" enabled="" onblur="Javascript:checkDate(this, '', 'R');" value="12/31/2999" size="10" maxlength="10" class="input input-small" data-req="Y" aria-required="true" data-type="d">

<span class="add-on" title="Date Picker"><i class="icon icon-calendar"></i></span>
</div>

<script type="text/javascript">
    $(function(){
    window.prettyPrint && prettyPrint();
    $('#calendar_toDate').datepicker();
    });
    function calenderDataChange(){
    javascript:dataChangeCheckRoleDate();}
    $('#calendar_toDate').datepicker({
    format : 'mm/dd/yyyy',
    startDate:'01/01/1900',
    endDate:'12/31/2999',
    autoClose:true ,
    orientation:'auto right'
    }).on('changeDate',function(ev){
    $(this).datepicker('hide');
    });
    </script>
    <span class="required"></span>

    </div>
</code>```

答:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <link rel="stylesheet" href="/resources/demos/style.css">

  <title>Document</title>

Date: <input type="text" id="datepicker">

```

Body:
I have an input element with an attached datepicker created using bootstrap-datepicker.
When the user changes the date by typing directly into the input element, and then clicks the calendar icon, the changed date is not reflected in the calendar

<input type="Text" alt="toDate" id="toDate" name="toDate" enabled="" onblur="Javascript:checkDate(this, '', 'R');" value="12/31/2999" size="10" maxlength="10" class="input input-small" data-req="Y" aria-required="true" data-type="d">

Body:
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <link rel="stylesheet" href="/resources/demos/style.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
  <script>
    $(function() {
      $("#datepicker").datepicker();
    });
  </script>
  <title>Document</title>
</head>

<body>
  <div class="col-lg-6 col-md-6 col-sm-6">
    <p>Date: <input type="text" id="datepicker"></p>

  </div>
</body>

</html>


问:
How to run python environment through node.js
I am developing a web application that will use python model.I have created environment for python model as well.But the problem i am facing is i have no idea how to execute that python environment through node js because i am using node.js at backend.</p>

答:
you can run python virtual environment inside nodejs, you need call python environment from bin directory where you install python virtual environment, and then you can use child_process for run python code inside nodejs, see this example:

```<code>const express = require('express')
const app = express()

app.get('/', (req, res) => {

    const { spawn } = require('child_process');
    const pyProg = spawn('~/py3env/bin/python', ['test.py']);

    pyProg.stdout.on('data', function(data) {

        console.log(data.toString());
        res.write(data);
        res.end('end');
    });
})

app.listen(3000, () => console.log('listening on port 3000'))
</code>```

even you can excecute command line with shelljs, and in this moment you can run pm2: see this:

```<code>const shell = require('shelljs');

shell.exec('pm2 start test.py --interpreter=./py3env/bin/python', function(code, output) {
  console.log('Exit code:', code);
  console.log('Program output:', output);
});
</code>```

Body:
you can run python virtual environment inside nodejs, you need call python environment from bin directory where you install python virtual environment, and then you can use child_process for run python code inside nodejs, see this example:

const express = require('express')
const app = express()

app.get('/', (req, res) => {

    const { spawn } = require('child_process');
    const pyProg = spawn('~/py3env/bin/python', ['test.py']);

    pyProg.stdout.on('data', function(data) {

        console.log(data.toString());
        res.write(data);
        res.end('end');
    });
})

app.listen(3000, () => console.log('listening on port 3000'))

even you can excecute command line with shelljs, and in this moment you can run pm2: see this:

const shell = require('shelljs');

shell.exec('pm2 start test.py --interpreter=./py3env/bin/python', function(code, output) {
  console.log('Exit code:', code);
  console.log('Program output:', output);
});


问:
Can't access V1::JobSerializer inside of V1::JobsController
I am using ActiveModelSerializers gem with my Rails API project.

I created a JobsController inside of app/controllers/v1/jobs_controller.rb because of API versioning.

I also created a JobSerializer inside of app/serializers/v1/job_serializer.rb also because of API versioning.

When I try to access V1::JobSerializer inside of the controller like this:

  def today_jobs
    todays_jobs = Job.where(created_at: Time.zone.now.beginning_of_day..Time.zone.now.end_of_day).all.order('created_at DESC').page(params[:page] ? params[:page].to_i : 1).per(10)

    render json: {objects: ActiveModel::Serializer::CollectionSerializer.new(todays_jobs, each_serializer: V1::JobSerializer), meta: pagination_meta(todays_jobs)}
  end
```

<p>Don't mind the pagination, this part is important:</p>

<pre class="lang-rb prettyprint-override"><code>objects: ActiveModel::Serializer::CollectionSerializer.new(todays_jobs, each_serializer: V1::JobSerializer)
</code>```

When I try to return this it says uncaught throw :no_serializer because I think it doesn't know what V1::JobSerializer is.

Just to make sure:
jobs_controller.rb is defined like this:

class V1::JobsController < ApplicationController
end
```

<p>and <code>job_serializer.rb</code> is defined like this:</p>

<pre class="lang-rb prettyprint-override"><code>class V1::JobSerializer < ActiveModel::Serializer
end
</code>```

What should I do to be able to access V1::JobSerializer inside of my jobs controller?

答:
The scope resolution operator :: should never be used when declaring nested classes / modules. Always use explicit nesting:

```<code># Bad:
class V1::JobsController < ApplicationController
  puts JobSerializer.inspect # missing constant error
end

class V1::JobSerializer < ActiveModel::Serializer
end
</code>```

```<code># Good:
module V1
  class JobsController < ApplicationController
    puts JobSerializer.inspect # resolves to V1::JobSerializer
  end
end

module V1
  class JobSerializer < ActiveModel::Serializer
  end
end
</code>```

Why? Because when you use the scope resolution operator the module nesting is resolved to the place of definition. And this can lead to extremely suprising constant lookup:

```<code>A = "I'm in the main scope"

module B
  A = "I'm in B"
  D = "Hello"
end

class B::C
  puts A # outputs "I'm in the main scope"
  puts D # Missing constant error
end
</code>```

When you use explicit nesting you actually reopen the module/class and set the correct module nesting so that constants are resolved in the same module:

```<code>module B
  class C
    puts A # outputs "I'm in B"
    puts D # outputs "Hello"
  end
end
</code>```

Body:
I am using ActiveModelSerializers gem with my Rails API project.

I created a JobsController inside of app/controllers/v1/jobs_controller.rb because of API versioning.

I also created a JobSerializer inside of app/serializers/v1/job_serializer.rb also because of API versioning.

When I try to access V1::JobSerializer inside of the controller like this:

  def today_jobs
    todays_jobs = Job.where(created_at: Time.zone.now.beginning_of_day..Time.zone.now.end_of_day).all.order('created_at DESC').page(params[:page] ? params[:page].to_i : 1).per(10)

    render json: {objects: ActiveModel::Serializer::CollectionSerializer.new(todays_jobs, each_serializer: V1::JobSerializer), meta: pagination_meta(todays_jobs)}
  end

Don't mind the pagination, this part is important:

objects: ActiveModel::Serializer::CollectionSerializer.new(todays_jobs, each_serializer: V1::JobSerializer)

When I try to return this it says uncaught throw :no_serializer because I think it doesn't know what V1::JobSerializer is.

Just to make sure:
jobs_controller.rb is defined like this:

class V1::JobsController < ApplicationController
end

and job_serializer.rb is defined like this:

class V1::JobSerializer < ActiveModel::Serializer
end

What should I do to be able to access V1::JobSerializer inside of my jobs controller?

Body:
The scope resolution operator :: should never be used when declaring nested classes / modules. Always use explicit nesting:

# Bad:
class V1::JobsController < ApplicationController
  puts JobSerializer.inspect # missing constant error
end

class V1::JobSerializer < ActiveModel::Serializer
end

# Good:
module V1
  class JobsController < ApplicationController
    puts JobSerializer.inspect # resolves to V1::JobSerializer
  end
end

module V1
  class JobSerializer < ActiveModel::Serializer
  end
end

Why? Because when you use the scope resolution operator the module nesting is resolved to the place of definition. And this can lead to extremely suprising constant lookup:

A = "I'm in the main scope"

module B
  A = "I'm in B"
  D = "Hello"
end

class B::C
  puts A # outputs "I'm in the main scope"
  puts D # Missing constant error
end

When you use explicit nesting you actually reopen the module/class and set the correct module nesting so that constants are resolved in the same module:

module B
  class C
    puts A # outputs "I'm in B"
    puts D # outputs "Hello"
  end
end


问:
Use Include method to show specific fields in a jount table
I am working on RestAPI and i am trying to use the Include method (include joint table) in Get request by HobbyId to show specific fileds from this table not everything.

Tables:
User,
Hobby.
Joint Table is : HobbyUsers which i want to show only HobbyId and SkillsLevel fiels from this table.

public async Task<User[]> GetUsersByHobby(int hobbyID)
{
    _logger.LogInformation($"Getting Users for hobby with ID:{hobbyID}");
    IQueryable<User> query =
                  _context.Users
                  .Include(a => a.HobbyUsers.Select(a => new
                      {
                          Id = a.HobbyId,
                          SkillLevel = a.SkillLevel
                      }))
                  .Where(h => h.HobbyUsers.Any(u => u.Hobby.HobbyId == hobbyID))
                  .OrderBy(u => u.HobbyUsers.First().SkillLevel);

    return await query.ToArrayAsync();
}
```

答:
You cannot add conditions in the Include method in ef core, so to filter the fields displayed in the results, you need to select the whole after the where condition.

But because you want to remove some fields in the result, then the content returned by the query will not be accepted as User type (has been changed to a custom type), you need to use var to receive.

Here is the demo:

```<code>var query = _context.Users
              .Include(a => a.HobbyUsers)
              .Where(h => h.HobbyUsers.Any(u => u.Hobby.HobbyId == hobbyID))
              .Select(x => new
              {
                  //here are Users class fields, you can change to what your class has.
                  Id = x.Id,
                  Name = x.Name,
                  HobbyUsers = x.HobbyUsers.Select(a => new
                  {
                      Id = a.HobbyId,
                      SkillLevel = a.SkillLevel
                  })
              }).OrderBy(u => u.HobbyUsers.First().SkillLevel).ToList();
</code>```

Body:
You cannot add conditions in the Include method in ef core, so to filter the fields displayed in the results, you need to select the whole after the where condition.

But because you want to remove some fields in the result, then the content returned by the query will not be accepted as User type (has been changed to a custom type), you need to use var to receive.

Here is the demo:

var query = _context.Users
              .Include(a => a.HobbyUsers)
              .Where(h => h.HobbyUsers.Any(u => u.Hobby.HobbyId == hobbyID))
              .Select(x => new
              {
                  //here are Users class fields, you can change to what your class has.
                  Id = x.Id,
                  Name = x.Name,
                  HobbyUsers = x.HobbyUsers.Select(a => new
                  {
                      Id = a.HobbyId,
                      SkillLevel = a.SkillLevel
                  })
              }).OrderBy(u => u.HobbyUsers.First().SkillLevel).ToList();


问:
How do you encode an apostrophe so that it's searchable in mysql?
I don't think that was the most clear question, but an example should make it a little clearer.

I have a table filled with movie names, some of which contain apostrophes. I have a search box which is used to find movies.

If I perform searches via

```<code>mov_title = '$search_keywords'
</code>```

it all works, but this method will not yield any results for partial searches, so I have to use this

```<code>mov_title LIKE '%$search_keywords%'
</code>```

This method works fine for titles that are A-Za-z0-9, but if a title has an apostrophe, it's not able to find the movie, even if I do an exact match.

Before the titles are stored in the DB, I put them through this:

```<code>$search_keywords = htmlspecialchars(mysql_escape_string($_GET["search_keywords"]));
</code>```

So in the DB, there is a forward slash before every single apostrophe.

The only way to match a movie title with an apostrophe is to physically put a forward slash in front of the apostrophe, in the search box.

This seems so trivial, and I'm sure the solution is painfully obvious, but I'm just not seeing it.

答:
This only happens because you escaped the data for html output before doing the output! You should only do it right before doing the output, i.e.:

```<code><li><?php echo htmlspecialchars($some_var); ?></li></code>```

Unescape the values in your database and change the application to escape only on output. You currently have no other way than also doing htmlspecialchars(mysql_real_escape_string()) on the $search_string.

Even if it made sense to escape for HTML already on inserting into the database, mysql_real_escape_string() would be the outer function and not the inner function.

LastEditorDisplayName: Jonathan Leffler

Body:
I don't think that was the most clear question, but an example should make it a little clearer.

I have a table filled with movie names, some of which contain apostrophes. I have a search box which is used to find movies.

If I perform searches via

mov_title = '$search_keywords'

it all works, but this method will not yield any results for partial searches, so I have to use this

mov_title LIKE '%$search_keywords%'

This method works fine for titles that are A-Za-z0-9, but if a title has an apostrophe, it's not able to find the movie, even if I do an exact match.

Before the titles are stored in the DB, I put them through this:

$search_keywords = htmlspecialchars(mysql_escape_string($_GET["search_keywords"]));

So in the DB, there is a forward slash before every single apostrophe.

The only way to match a movie title with an apostrophe is to physically put a forward slash in front of the apostrophe, in the search box.

This seems so trivial, and I'm sure the solution is painfully obvious, but I'm just not seeing it.

Body:
This only happens because you escaped the data for html output before doing the output! You should only do it right before doing the output, i.e.:

<li><?php echo htmlspecialchars($some_var); ?></li>

Unescape the values in your database and change the application to escape only on output. You currently have no other way than also doing htmlspecialchars(mysql_real_escape_string()) on the $search_string.

Even if it made sense to escape for HTML already on inserting into the database, mysql_real_escape_string() would be the outer function and not the inner function.

OwnerDisplayName: sikx

LastEditorDisplayName: sikx


问:
How to add onBackPressedCallback to fragment?
I've seen this mentioned in a couple of places but cant quite work out how to implement it as there are no example online, I'm wondering whether I've misinterpreted its meaning.

the android developer link for addOnBackPressedCallback

I was wondering whether this means I can add a callback inside my fragment to pick up the onBackPressed() before it hits the activity.

In my fragment I've implemented

```<code>implements OnBackPressedCallBack
</code>```

then implemented the method

```<code>@Override
public boolean handleOnBackPressed() {
    Log.d(TAG, "handleOnBackPressed: hello");
    return true;
}
</code>```

But its not picking it up and going straight to main activity onBackPressed().

I read on further and saw that My fragment needed to extend from FragmentActivity

```<code>public class MainExampleFragment extends FragmentActivity implements View.OnClickListener, OnBackPressedCallback {
</code>```

and instead of

```<code>appCompatActivity.getSuppportFragmentManager
</code>```

to call

```<code>FragmentActivity.getSupportFragmentManager
</code>```

instead, but this throws and error in the Fragment.newInstance method when trying to set the bundle.

Has anyone info on doing this please thanks

答:
if anybody dont know i am update OnBackPressedCallBack for both fragment and AppCompacTActivity and I have Nested Fragment here

in Fragment

```<code>public class MessageFragment extends Fragment  {

public MessageFragment() {
    // Required empty public constructor
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    // This callback will only be called when MyFragment is at least Started.
    OnBackPressedCallback callback = new OnBackPressedCallback(true ) {
        @Override
        public void handleOnBackPressed() {
            // Handle the back button event
            FragmentManager fm= getFragmentManager();
            if (fm != null) {
                if (fm.getBackStackEntryCount() > 0) {
                    fm.popBackStack();
                    Log.e( "backpress Frag","back" );

                }

                List<Fragment> fragList = fm.getFragments();
                if (fragList != null && fragList.size() > 0) {
                    for (Fragment frag : fragList) {
                        if (frag == null) {
                            continue;
                        }
                        if (frag.isVisible()) {
                          Log.e( "backpress Frag","Visible" );
                        }
                    }
                }
            }

        }
    };
    requireActivity().getOnBackPressedDispatcher().addCallback(this, callback);
    super.onCreate( savedInstanceState );
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View root=inflater.inflate( R.layout.fragment_listning, container, false );

    return root;
}
</code>```

and you in MainActivity remove your OnBackpressed() method and add this new Method

```<code>OnBackPressedCallback onBackPressedCallback = new OnBackPressedCallback( true ) {
    boolean doubleBackToExitPressedOnce=false;
    @Override
    public void handleOnBackPressed() {

        if (doubleBackToExitPressedOnce) {
            ActivityCompat.finishAffinity( FirstActivity.this );
            Log.e( "Click", "double back" );
            return;
        }

        this.doubleBackToExitPressedOnce = true;
        Toast.makeText(FirstActivity.this,getStrin(R.string.exitapp),Toast.LENGTH_SHORT).show();

        new Handler().postDelayed( new Runnable() {

            @Override
            public void run() {
                doubleBackToExitPressedOnce=false;
            }
        }, 2000);

    }
};

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate( savedInstanceState );
    setContentView( R.layout.activity_first );
    //getting bottom navigation view and attaching the listener

    getOnBackPressedDispatcher().addCallback( this, onBackPressedCallback );

}
</code>```

Body:
I've seen this mentioned in a couple of places but cant quite work out how to implement it as there are no example online, I'm wondering whether I've misinterpreted its meaning.

the android developer link for addOnBackPressedCallback

I was wondering whether this means I can add a callback inside my fragment to pick up the onBackPressed() before it hits the activity.

In my fragment I've implemented

implements OnBackPressedCallBack

then implemented the method

@Override
public boolean handleOnBackPressed() {
    Log.d(TAG, "handleOnBackPressed: hello");
    return true;
}

But its not picking it up and going straight to main activity onBackPressed().

I read on further and saw that My fragment needed to extend from FragmentActivity

public class MainExampleFragment extends FragmentActivity implements View.OnClickListener, OnBackPressedCallback {

and instead of

appCompatActivity.getSuppportFragmentManager

to call

FragmentActivity.getSupportFragmentManager

instead, but this throws and error in the Fragment.newInstance method when trying to set the bundle.

Has anyone info on doing this please thanks

Body:
if anybody dont know i am update OnBackPressedCallBack for both fragment and AppCompacTActivity and I have Nested Fragment here

in Fragment

public class MessageFragment extends Fragment  {

public MessageFragment() {
    // Required empty public constructor
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    // This callback will only be called when MyFragment is at least Started.
    OnBackPressedCallback callback = new OnBackPressedCallback(true ) {
        @Override
        public void handleOnBackPressed() {
            // Handle the back button event
            FragmentManager fm= getFragmentManager();
            if (fm != null) {
                if (fm.getBackStackEntryCount() > 0) {
                    fm.popBackStack();
                    Log.e( "backpress Frag","back" );

                }

                List<Fragment> fragList = fm.getFragments();
                if (fragList != null && fragList.size() > 0) {
                    for (Fragment frag : fragList) {
                        if (frag == null) {
                            continue;
                        }
                        if (frag.isVisible()) {
                          Log.e( "backpress Frag","Visible" );
                        }
                    }
                }
            }

        }
    };
    requireActivity().getOnBackPressedDispatcher().addCallback(this, callback);
    super.onCreate( savedInstanceState );
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View root=inflater.inflate( R.layout.fragment_listning, container, false );

    return root;
}

and you in MainActivity remove your OnBackpressed() method and add this new Method

OnBackPressedCallback onBackPressedCallback = new OnBackPressedCallback( true ) {
    boolean doubleBackToExitPressedOnce=false;
    @Override
    public void handleOnBackPressed() {

        if (doubleBackToExitPressedOnce) {
            ActivityCompat.finishAffinity( FirstActivity.this );
            Log.e( "Click", "double back" );
            return;
        }

        this.doubleBackToExitPressedOnce = true;
        Toast.makeText(FirstActivity.this,getStrin(R.string.exitapp),Toast.LENGTH_SHORT).show();

        new Handler().postDelayed( new Runnable() {

            @Override
            public void run() {
                doubleBackToExitPressedOnce=false;
            }
        }, 2000);

    }
};

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate( savedInstanceState );
    setContentView( R.layout.activity_first );
    //getting bottom navigation view and attaching the listener

    getOnBackPressedDispatcher().addCallback( this, onBackPressedCallback );

}


问:
Timestamp subtraction must have the same timezones or no timezones but they are both UTC
There are questions that addresses the same error TypeError: Timestamp subtraction must have the same timezones or no timezones but none faces the same issue as this one.

I have 2 UTC Timestamps that throw that error when substracted.

```<code>print(date, type(date), date.tzinfo)
>>> 2020-07-17 00:00:00+00:00 <class 'pandas._libs.tslibs.timestamps.Timestamp'> UTC
print(date2, type(date2), date2.tzinfo)
>>> 2020-04-06 00:00:00.000000001+00:00 <class 'pandas._libs.tslibs.timestamps.Timestamp'> UTC
date - date2
>>> TypeError: Timestamp subtraction must have the same timezones or no timezones
</code>```

Edit: I'm using Python 3.6.9 and Pandas 1.0.1

答:
Had same problem. If you're reading data using pandas read_csv, it uses <class 'pytz.UTC'>. So solution for me was to simply use same class everywhere.

Sample code generating error

```<code>from datetime import datetime, timedelta, timezone
import pandas as pd

now = datetime.now(tz=timezone.utc)
some_time_ago = now - timedelta(7)

print('Timezone info before reading_csv')
print(some_time_ago.tzinfo, type(some_time_ago.tzinfo))

time_passed = now - some_time_ago
print (time_passed)

df = pd.DataFrame([some_time_ago], columns=['date'])
df.to_csv('dates.csv', index=False)

df2 = pd.read_csv('dates.csv', parse_dates=['date'])
print('\nTimezone info after reading_csv')
print(df2.iloc[0,0].tzinfo, type(df2.iloc[0,0].tzinfo))

now = datetime.now(tz=timezone.utc)
some_time_ago = now - df2.iloc[0,0]
print(some_time_ago)
</code>```

```<code>Timezone info before reading_csv
UTC <class 'datetime.timezone'>
7 days, 0:00:00

Timezone info after reading_csv
UTC <class 'pytz.UTC'>
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-23-b2815e32e8b7> in <module>
     19
     20 now = datetime.now(tz=timezone.utc)
---> 21 some_time_ago = now - df2.iloc[0,0]
     22 print(some_time_ago)

pandas/_libs/tslibs/c_timestamp.pyx in pandas._libs.tslibs.c_timestamp._Timestamp.__sub__()

TypeError: Timestamp subtraction must have the same timezones or no timezones
</code>```

Correct code with pytz

```<code>import pytz
from datetime import datetime, timedelta
import pandas as pd

now = datetime.now(tz=pytz.UTC)
some_time_ago = now - timedelta(7)

print('Timezone info before reading_csv')
print(some_time_ago.tzinfo, type(some_time_ago.tzinfo))

time_passed = now - some_time_ago
print (time_passed)

df = pd.DataFrame([some_time_ago], columns=['date'])
df.to_csv('dates.csv', index=False)

df2 = pd.read_csv('dates.csv', parse_dates=['date'])
print('\nTimezone info after reading_csv')
print(df2.iloc[0,0].tzinfo, type(df2.iloc[0,0].tzinfo))

now = datetime.now(tz=pytz.UTC)
some_time_ago = now - df2.iloc[0,0]
print(some_time_ago)
</code>```

```<code>Timezone info before reading_csv
UTC <class 'pytz.UTC'>
7 days, 0:00:00

Timezone info after reading_csv
UTC <class 'pytz.UTC'>
7 days 00:00:00.024021
</code>```

Body:
There are questions that addresses the same error TypeError: Timestamp subtraction must have the same timezones or no timezones but none faces the same issue as this one.

I have 2 UTC Timestamps that throw that error when substracted.

print(date, type(date), date.tzinfo)
>>> 2020-07-17 00:00:00+00:00 <class 'pandas._libs.tslibs.timestamps.Timestamp'> UTC
print(date2, type(date2), date2.tzinfo)
>>> 2020-04-06 00:00:00.000000001+00:00 <class 'pandas._libs.tslibs.timestamps.Timestamp'> UTC
date - date2
>>> TypeError: Timestamp subtraction must have the same timezones or no timezones

Edit: I'm using Python 3.6.9 and Pandas 1.0.1

Body:
Had same problem. If you're reading data using pandas read_csv, it uses <class 'pytz.UTC'>. So solution for me was to simply use same class everywhere.

Sample code generating error

from datetime import datetime, timedelta, timezone
import pandas as pd

now = datetime.now(tz=timezone.utc)
some_time_ago = now - timedelta(7)

print('Timezone info before reading_csv')
print(some_time_ago.tzinfo, type(some_time_ago.tzinfo))

time_passed = now - some_time_ago
print (time_passed)

df = pd.DataFrame([some_time_ago], columns=['date'])
df.to_csv('dates.csv', index=False)

df2 = pd.read_csv('dates.csv', parse_dates=['date'])
print('\nTimezone info after reading_csv')
print(df2.iloc[0,0].tzinfo, type(df2.iloc[0,0].tzinfo))

now = datetime.now(tz=timezone.utc)
some_time_ago = now - df2.iloc[0,0]
print(some_time_ago)

Timezone info before reading_csv
UTC <class 'datetime.timezone'>
7 days, 0:00:00

Timezone info after reading_csv
UTC <class 'pytz.UTC'>
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-23-b2815e32e8b7> in <module>
     19
     20 now = datetime.now(tz=timezone.utc)
---> 21 some_time_ago = now - df2.iloc[0,0]
     22 print(some_time_ago)

pandas/_libs/tslibs/c_timestamp.pyx in pandas._libs.tslibs.c_timestamp._Timestamp.__sub__()

TypeError: Timestamp subtraction must have the same timezones or no timezones

Correct code with pytz

import pytz
from datetime import datetime, timedelta
import pandas as pd

now = datetime.now(tz=pytz.UTC)
some_time_ago = now - timedelta(7)

print('Timezone info before reading_csv')
print(some_time_ago.tzinfo, type(some_time_ago.tzinfo))

time_passed = now - some_time_ago
print (time_passed)

df = pd.DataFrame([some_time_ago], columns=['date'])
df.to_csv('dates.csv', index=False)

df2 = pd.read_csv('dates.csv', parse_dates=['date'])
print('\nTimezone info after reading_csv')
print(df2.iloc[0,0].tzinfo, type(df2.iloc[0,0].tzinfo))

now = datetime.now(tz=pytz.UTC)
some_time_ago = now - df2.iloc[0,0]
print(some_time_ago)

Timezone info before reading_csv
UTC <class 'pytz.UTC'>
7 days, 0:00:00

Timezone info after reading_csv
UTC <class 'pytz.UTC'>
7 days 00:00:00.024021


问:
How to handle bug fixes in Trunk Based Development?

Let’s say I have only one main branch and I successfully released sprint 1 to the production.

Now I’m working on sprint 2 which spans 4 weeks, during this span, I have committed several user stories to the main branch and on to the QA for demo.

Now, I have an urgent bug from the original sprint 1 release, but how do I fix that bug without including the sprint 2 user stories in the main branch? The main trunk already has many sprint 2 user stories.

How do I apply the fix to the original sprint 1 release and then release to production? There is no production branch for me to branch off for the fix. Any suggestions?

答: Since you only have one branch, you may try to find the changeset that release to sprint 1, and branch from this changeset to fix the bug.


问:
Oracle-Apex process for insert into two tables
I have dialog page, with items from two tables.

I want to fill v_row_table2.fk_id with the value that P23_ID(identity column) will get

I use process for insert:

```<code>-- all variables are declared

IF :P23_ID IS NULL THEN
--INSERT

v_row.active                      := :P23_ACTIVE;
v_row.date                        := :P23_DATE;
v_row.start_time                  := :P23_START_TIME;
v_row.current_time                := :P23_CURRENT_TIME;
v_row_table2.logdate              := :P23_LOGDATE;
v_row_table2.filename             := :P23_FILENAME;
v_row_table2.fk_id                --

v_id  := pck_table.fn_ins_table_name(table_row => v_row);
v_id2 := pck_table2.fn_ins_table_name(table_row => v_row_table2);
</code>```

I try to add:

```<code>SELECT identity_name.nextval
INTO v_fk_id
FROM dual;
</code>```

And add v_fk_id into code but, It didn't work.

Insert function:

```<code>FUNCTION fn_ins_table_name (
        table_row IN table2%rowtype
    ) RETURN table2.table_id%TYPE
    IS
        v_table2_id table2.table_id%TYPE;
    BEGIN
        INSERT INTO table2 VALUES table_row RETURNING
        table_id INTO v_table2_id;  -- table_id is identity

        RETURN v_table2_id;
    END fn_ins_table_name;
</code>```

Thanks in advance

答:
This isn't really an apex issue, but a pure pl/sql question. Your question is: "how do i get the generated value of a column as result of an insert". You can use the "RETURNING INTO" clause for that. It returns the value of a column into a variable. Plenty of examples everywhere of this clause.

You have not provided the description of your function fn_ins_table_name but it should return the newly generated id for that row. Your code would then look like this:

```<code>IF :P23_ID IS NULL THEN
--INSERT

v_row.active                      := :P23_ACTIVE;
v_row.date                        := :P23_DATE;
v_row.start_time                  := :P23_START_TIME;
v_row.current_time                := :P23_CURRENT_TIME;

v_id  := pck_table.fn_ins_table_name(table_row => v_row);

v_row_table2.logdate              := :P23_LOGDATE;
v_row_table2.filename             := :P23_FILENAME;
v_row_table2.fk_id                := v_id;

v_id2 := pck_table2.fn_ins_table_name(table_row => v_row_table2);
</code>```

Body:
I have dialog page, with items from two tables.

I want to fill v_row_table2.fk_id with the value that P23_ID(identity column) will get

I use process for insert:

-- all variables are declared

IF :P23_ID IS NULL THEN
--INSERT

v_row.active                      := :P23_ACTIVE;
v_row.date                        := :P23_DATE;
v_row.start_time                  := :P23_START_TIME;
v_row.current_time                := :P23_CURRENT_TIME;
v_row_table2.logdate              := :P23_LOGDATE;
v_row_table2.filename             := :P23_FILENAME;
v_row_table2.fk_id                --

v_id  := pck_table.fn_ins_table_name(table_row => v_row);
v_id2 := pck_table2.fn_ins_table_name(table_row => v_row_table2);

I try to add:

SELECT identity_name.nextval
INTO v_fk_id
FROM dual;

And add v_fk_id into code but, It didn't work.

Insert function:

FUNCTION fn_ins_table_name (
        table_row IN table2%rowtype
    ) RETURN table2.table_id%TYPE
    IS
        v_table2_id table2.table_id%TYPE;
    BEGIN
        INSERT INTO table2 VALUES table_row RETURNING
        table_id INTO v_table2_id;  -- table_id is identity

        RETURN v_table2_id;
    END fn_ins_table_name;

Thanks in advance

Body:
This isn't really an apex issue, but a pure pl/sql question. Your question is: "how do i get the generated value of a column as result of an insert". You can use the "RETURNING INTO" clause for that. It returns the value of a column into a variable. Plenty of examples everywhere of this clause.

You have not provided the description of your function fn_ins_table_name but it should return the newly generated id for that row. Your code would then look like this:

IF :P23_ID IS NULL THEN
--INSERT

v_row.active                      := :P23_ACTIVE;
v_row.date                        := :P23_DATE;
v_row.start_time                  := :P23_START_TIME;
v_row.current_time                := :P23_CURRENT_TIME;

v_id  := pck_table.fn_ins_table_name(table_row => v_row);

v_row_table2.logdate              := :P23_LOGDATE;
v_row_table2.filename             := :P23_FILENAME;
v_row_table2.fk_id                := v_id;

v_id2 := pck_table2.fn_ins_table_name(table_row => v_row_table2);