问:
c# async await confuses me, seems to do nothing
EDIT: Updating LongTask() to be await Task.Delay(2000); makes it work how I need, so thanks for the answers, y'all!

I am trying to call an async function from within a sync function to let the sync function keep going before the async function is finished. I don't know why the code below waits for LongTask() to complete before continuing. I thought it should only do that if I did await LongTask(). Can someone help me understand what I'm missing?

C# fiddle here

```<code>using System;
using System.Diagnostics;
using System.Threading.Tasks;

public class Program
{
    public static void Main()
    {
        var timer = new Stopwatch();
        timer.Start();
        LongTask();
        timer.Stop();

        long ms = timer.ElapsedMilliseconds;

        Console.WriteLine(ms.ToString());
    }

    async static void LongTask()
    {
        Task.Delay(2000).Wait();
    }
}
</code>```

答:
This will hopefully demonstrate it better:

```<code>static async Task Main(string[] args)
{
    var timer = Stopwatch.StartNew();
    var t1 = LongTask();
    var t2 = LongTask();
    Console.WriteLine("Started both tasks in {0}", timer.Elapsed);
    await Task.WhenAll(t1, t2);
    timer.Stop();
    Console.WriteLine("Tasks finished in {0}", timer.Elapsed);
}

async static Task LongTask()
{
    await Task.Delay(2000);
}
</code>```

Notice the change in return types of functions. Notice the output, too. Both task are waiting for something (in this case delay to expire) in parallel and at the same time, the Main function is able to continue running, printing text and then waiting for the outcome of those functions.

It is important to understand that the execution of an async function runs synchronously until it hits the await operator. If you don't have any await in an async function it will not run asynchronously (and compiler should warn about it). This is applied recursively (if you have several nested awaits) until you hit something that is actually going to be waited for. See example:

```<code>static async Task Main(string[] args)
{
    var timer = Stopwatch.StartNew();
    var t1 = LongTask(1);
    Console.WriteLine("t1 started in {0}", timer.Elapsed);
    var t2 = LongTask(2);
    Console.WriteLine("Started both tasks in {0}", timer.Elapsed);
    await Task.WhenAll(t1, t2);
    timer.Stop();
    Console.WriteLine("Tasks finished in {0}", timer.Elapsed);
}

async static Task LongTask(int id)
{
    Console.WriteLine("[{0}] Before subtask 1", id);
    await LongSubTask1();
    Console.WriteLine("[{0}] Before subtask 2", id);
    await LongSubTask2();
    Console.WriteLine("[{0}] After subtask 1", id);
}

async static Task LongSubTask1(int id)
{
    Console.WriteLine("[{0}] LongSubTask1", id);
    await Task.Delay(1000);
}
async static Task LongSubTask2(int id)
{
    Console.WriteLine("[{0}] LongSubTask2", id);
    await Task.Delay(1000);
}
</code>```

If you run it, you will see that the execution runs synchronously all the way down to Task.Delay call and only then it returns all the way back to the Main function.

In order to benefit from async/await, you have to use it all the way down to where it ends up calling some I/O (network, disk, etc.) you will need to wait for (or some other event that does not require constant polling to figure out, or artificially created like delay in that sample). If you need to do some expensive computation (that does not have anything async in it) without occupying some particular thread (say, UI thread in GUI application), you'd need to explicitly start new task with it, which at some later point you can await for to get its result.

Body:
EDIT: Updating LongTask() to be await Task.Delay(2000); makes it work how I need, so thanks for the answers, y'all!

I am trying to call an async function from within a sync function to let the sync function keep going before the async function is finished. I don't know why the code below waits for LongTask() to complete before continuing. I thought it should only do that if I did await LongTask(). Can someone help me understand what I'm missing?

C# fiddle here

using System;
using System.Diagnostics;
using System.Threading.Tasks;

public class Program
{
    public static void Main()
    {
        var timer = new Stopwatch();
        timer.Start();
        LongTask();
        timer.Stop();

        long ms = timer.ElapsedMilliseconds;

        Console.WriteLine(ms.ToString());
    }

    async static void LongTask()
    {
        Task.Delay(2000).Wait();
    }
}

Body:
This will hopefully demonstrate it better:

static async Task Main(string[] args)
{
    var timer = Stopwatch.StartNew();
    var t1 = LongTask();
    var t2 = LongTask();
    Console.WriteLine("Started both tasks in {0}", timer.Elapsed);
    await Task.WhenAll(t1, t2);
    timer.Stop();
    Console.WriteLine("Tasks finished in {0}", timer.Elapsed);
}

async static Task LongTask()
{
    await Task.Delay(2000);
}

Notice the change in return types of functions. Notice the output, too. Both task are waiting for something (in this case delay to expire) in parallel and at the same time, the Main function is able to continue running, printing text and then waiting for the outcome of those functions.

It is important to understand that the execution of an async function runs synchronously until it hits the await operator. If you don't have any await in an async function it will not run asynchronously (and compiler should warn about it). This is applied recursively (if you have several nested awaits) until you hit something that is actually going to be waited for. See example:

static async Task Main(string[] args)
{
    var timer = Stopwatch.StartNew();
    var t1 = LongTask(1);
    Console.WriteLine("t1 started in {0}", timer.Elapsed);
    var t2 = LongTask(2);
    Console.WriteLine("Started both tasks in {0}", timer.Elapsed);
    await Task.WhenAll(t1, t2);
    timer.Stop();
    Console.WriteLine("Tasks finished in {0}", timer.Elapsed);
}

async static Task LongTask(int id)
{
    Console.WriteLine("[{0}] Before subtask 1", id);
    await LongSubTask1();
    Console.WriteLine("[{0}] Before subtask 2", id);
    await LongSubTask2();
    Console.WriteLine("[{0}] After subtask 1", id);
}

async static Task LongSubTask1(int id)
{
    Console.WriteLine("[{0}] LongSubTask1", id);
    await Task.Delay(1000);
}
async static Task LongSubTask2(int id)
{
    Console.WriteLine("[{0}] LongSubTask2", id);
    await Task.Delay(1000);
}

If you run it, you will see that the execution runs synchronously all the way down to Task.Delay call and only then it returns all the way back to the Main function.

In order to benefit from async/await, you have to use it all the way down to where it ends up calling some I/O (network, disk, etc.) you will need to wait for (or some other event that does not require constant polling to figure out, or artificially created like delay in that sample). If you need to do some expensive computation (that does not have anything async in it) without occupying some particular thread (say, UI thread in GUI application), you'd need to explicitly start new task with it, which at some later point you can await for to get its result.


来源: stackexchange

问:
List posts with the same tag of current post in WordPress
I have a site with 500 000 posts and it's pretty slow.

In the bottom of every post on a WordPress site, I want to show only 3 random posts having the same tag of current post.

Note that every post has always 1 tag only (no more, no less).

I use the following code but the SELECT gets thousands of posts and it's extremely slow.

Using posts_per_page=3 it gets thousands of posts (with same tag) via query and after that, it shows 3 posts only but the MySQL load has been very high. Instead, the logic should be "find 3 posts only and then stop".

```<code>$posttags = get_the_tags();
foreach($posttags as $tag) {
$duot=$tag->slug;
$duot2=$tag->name;
}

$the_query = new WP_Query( 'tag='.$duot.'&posts_per_page=3' );
if ( $the_query->have_posts() ) {
echo '<h3>Other post with tag '.$duot2.'</h3><ul>';
while ( $the_query->have_posts() ) {
$the_query->the_post();
echo '<li >'.the_title().'</li>';
}
echo '</ul>';
}

wp_reset_postdata();
</code>```

How would you change the above code to reduce the loading time of MySQL queries?

答:
enhancement would be</p>
```<code>$post = get_post(); // if you don't have $post->ID already
$tag_ids = wp_get_post_tags( $post->ID, array( "fields" => "ids" ) ); // current tags
$args = array(
    "numberposts" => 3,
    "orderby" => "rand",
    "post__not_in" => array( $post->ID ), //exclude current
    "tax_query" => array(
        array(
            "taxonomy" => "post_tag",
            "field"    => "term_id",
            "terms"    => $tag_ids
        )
    )
);
$posts = get_posts( $args ); // getting posts
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a site with 500 000 posts and it's pretty slow.

In the bottom of every post on a WordPress site, I want to show only 3 random posts having the same tag of current post.

Note that every post has always 1 tag only (no more, no less).

I use the following code but the SELECT gets thousands of posts and it's extremely slow.

Using posts_per_page=3 it gets thousands of posts (with same tag) via query and after that, it shows 3 posts only but the MySQL load has been very high. Instead, the logic should be "find 3 posts only and then stop".

$posttags = get_the_tags();
foreach($posttags as $tag) {
$duot=$tag->slug;
$duot2=$tag->name;
}

$the_query = new WP_Query( 'tag='.$duot.'&posts_per_page=3' );
if ( $the_query->have_posts() ) {
echo '
Other post with tag '.$duot2.'

';
while ( $the_query->have_posts() ) {
$the_query->the_post();
echo '
'.the_title().'
';
}
echo '
';
}

wp_reset_postdata();

How would you change the above code to reduce the loading time of MySQL queries?

Body:
enhancement would be

$post = get_post(); // if you don't have $post->ID already
$tag_ids = wp_get_post_tags( $post->ID, array( "fields" => "ids" ) ); // current tags
$args = array(
    "numberposts" => 3,
    "orderby" => "rand",
    "post__not_in" => array( $post->ID ), //exclude current
    "tax_query" => array(
        array(
            "taxonomy" => "post_tag",
            "field"    => "term_id",
            "terms"    => $tag_ids
        )
    )
);
$posts = get_posts( $args ); // getting posts


问:
Python : tensorflow-gpu import errors
This is a question extended from the following question on the link:

python : cannot import tensorflow-gpu

I'm trying to implement tensorflow-gpu on my Windows 10 machine. I followed what this link told me to do. I have..

Successfully installed CUDA 8.0 Toolkit

Successfully installed cuDNN v5.1

Added Environmental variables : CUDA_Home & path variables

Installed Anaconda3 (I was formerly using Anaconda3)

Successfully carried out the following commands

```<code>>conda create -n tensorflow-gpu python=3.5.2
>activate tensorflow-gpu
>pip install tensorflow-gpu
>activate tensorflow-gpu
(tensorflow-gpu) >python
>>>
</code>```

However, if I try to import tensorflow,

```<code>>>>import tensorflow as tf
</code>```

I get the following error message

```<code>Traceback (most recent call last):
  File "C:\Users\Froilan\Anaconda3\envs\tensorflow-gpu\lib\site-
packages\tensorflow\python\platform\self_check.py", line 87, in preload_check
    ctypes.WinDLL(build_info.cudnn_dll_name)
  File "C:\Users\Froilan\Anaconda3\envs\tensorflow-gpu\lib\ctypes\__init__.py", line 347, in __init__
self._handle = _dlopen(self._name, mode)
OSError: [WinError 126] This specified module could not be found

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\Froilan\Anaconda3\envs\tensorflow-gpu\lib\site-packages\tensorflow\__init__.py", line 24, in <module>
from tensorflow.python import *
  File "C:\Users\Froilan\Anaconda3\envs\tensorflow-gpu\lib\site-packages\tensorflow\python\__init__.py", line 49, in <module>
from tensorflow.python import pywrap_tensorflow
  File "C:\Users\Froilan\Anaconda3\envs\tensorflow-gpu\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 30, in <module>
self_check.preload_check()
  File "C:\Users\Froilan\Anaconda3\envs\tensorflow-gpu\lib\site-packages\tensorflow\python\platform\self_check.py", line 97, in preload_check
% (build_info.cudnn_dll_name, build_info.cudnn_version_number))
ImportError: Could not find 'cudnn64_6.dll'. TensorFlow requires that this DLL be installed in a directory that is named in your %PATH% environment variable. Note that installing cuDNN is a separate step from installing CUDA, and this DLL is often found in a different directory from the CUDA DLLs. You may install the necessary DLL by downloading cuDNN 6 from this URL: https://developer.nvidia.com/cudnn
</code>```

I'm not sure what's causing the problem. I'm using an AMD ryzen 1700 CPU & GTX 1050 Ti GPU. Maybe one of those is causing the problem?

UPDATE : tensorflow with CPU works just fine. The one with the GPU is what's causing the problem

答: i had similar problem i installed lower verison of both cuda and cudnn and it solved the problem. check the tensorflow website for recommended versions of both cuda and cudnn. for me cuda 11.2 and cudnn 8.1 worked well</p>

ContentLicense: CC BY-SA 3.0

Title: Python : tensorflow-gpu import errors

Body:
This is a question extended from the following question on the link:

python : cannot import tensorflow-gpu

I'm trying to implement tensorflow-gpu on my Windows 10 machine. I followed what this link told me to do. I have..

Successfully installed CUDA 8.0 Toolkit

Successfully installed cuDNN v5.1

Added Environmental variables : CUDA_Home & path variables

Installed Anaconda3 (I was formerly using Anaconda3)

Successfully carried out the following commands

>conda create -n tensorflow-gpu python=3.5.2
>activate tensorflow-gpu
>pip install tensorflow-gpu
>activate tensorflow-gpu
(tensorflow-gpu) >python
>>>

However, if I try to import tensorflow,

>>>import tensorflow as tf

I get the following error message

Traceback (most recent call last):
  File "C:\Users\Froilan\Anaconda3\envs\tensorflow-gpu\lib\site-
packages\tensorflow\python\platform\self_check.py", line 87, in preload_check
    ctypes.WinDLL(build_info.cudnn_dll_name)
  File "C:\Users\Froilan\Anaconda3\envs\tensorflow-gpu\lib\ctypes\__init__.py", line 347, in __init__
self._handle = _dlopen(self._name, mode)
OSError: [WinError 126] This specified module could not be found

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\Froilan\Anaconda3\envs\tensorflow-gpu\lib\site-packages\tensorflow\__init__.py", line 24, in <module>
from tensorflow.python import *
  File "C:\Users\Froilan\Anaconda3\envs\tensorflow-gpu\lib\site-packages\tensorflow\python\__init__.py", line 49, in <module>
from tensorflow.python import pywrap_tensorflow
  File "C:\Users\Froilan\Anaconda3\envs\tensorflow-gpu\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 30, in <module>
self_check.preload_check()
  File "C:\Users\Froilan\Anaconda3\envs\tensorflow-gpu\lib\site-packages\tensorflow\python\platform\self_check.py", line 97, in preload_check
% (build_info.cudnn_dll_name, build_info.cudnn_version_number))
ImportError: Could not find 'cudnn64_6.dll'. TensorFlow requires that this DLL be installed in a directory that is named in your %PATH% environment variable. Note that installing cuDNN is a separate step from installing CUDA, and this DLL is often found in a different directory from the CUDA DLLs. You may install the necessary DLL by downloading cuDNN 6 from this URL: https://developer.nvidia.com/cudnn

I'm not sure what's causing the problem. I'm using an AMD ryzen 1700 CPU & GTX 1050 Ti GPU. Maybe one of those is causing the problem?

UPDATE : tensorflow with CPU works just fine. The one with the GPU is what's causing the problem


问:
HttpsUrlConnection SSLHandshakeException certificate_required
I am trying to access my api from java but I get the following error:

```<code>javax.net.ssl.SSLHandshakeException: Received fatal alert: certificate_required
</code>```

I do not get this error when I test the code on my personal Windows computer. But this error does occur on my linux production server running Ubuntu with openjdk 11.

The server is hosted on that same ubuntu server, and proxied with Cloudflare SSL Full

```<code>HttpsURLConnection con = null;
    try {
        URL url = new URL("https://www.example.com/");
        con = (HttpsURLConnection) url.openConnection();
        con.addRequestProperty("XF-Api-Key", "key");
        con.addRequestProperty("XF-Api-User", "1");
        con.setConnectTimeout(5000);
        con.setReadTimeout(5000);
        con.addRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");
        con.setRequestMethod("GET");
        con.setRequestProperty("Content-Type", "application/json");
        try {
            BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String inputLine;
            StringBuffer content = new StringBuffer();
            while ((inputLine = in.readLine()) != null)
                content.append(inputLine);
            in.close();

            System.out.println(content.toString());
        } catch (Exception e) {
            e.printStackTrace();
            BufferedReader in = new BufferedReader(new InputStreamReader(con.getErrorStream()));
            String inputLine;
            StringBuffer content = new StringBuffer();
            while ((inputLine = in.readLine()) != null) {
                content.append(inputLine);
            }
            in.close();
            System.out.println(content.toString());
        }
    } catch (Exception exp) {
        System.out.println("Cant load data from API");
        exp.printStackTrace();
    } finally {
        if (con != null)
            con.disconnect();
    }
</code>```

Is something not configured properly on my linux server?

Update: my problem has not been solved yet and I am still looking for an answer. I cannot find any informative blogs or information on the internet.

答: The server expects the client to present a certificate that it trusts, so the client needs to be configured with a Keystore - see https://www.baeldung.com/java-https-client-certificate-authentication</p>

Body:
I am trying to access my api from java but I get the following error:

javax.net.ssl.SSLHandshakeException: Received fatal alert: certificate_required

I do not get this error when I test the code on my personal Windows computer. But this error does occur on my linux production server running Ubuntu with openjdk 11.

The server is hosted on that same ubuntu server, and proxied with Cloudflare SSL Full

HttpsURLConnection con = null;
    try {
        URL url = new URL("https://www.example.com/");
        con = (HttpsURLConnection) url.openConnection();
        con.addRequestProperty("XF-Api-Key", "key");
        con.addRequestProperty("XF-Api-User", "1");
        con.setConnectTimeout(5000);
        con.setReadTimeout(5000);
        con.addRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");
        con.setRequestMethod("GET");
        con.setRequestProperty("Content-Type", "application/json");
        try {
            BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String inputLine;
            StringBuffer content = new StringBuffer();
            while ((inputLine = in.readLine()) != null)
                content.append(inputLine);
            in.close();

            System.out.println(content.toString());
        } catch (Exception e) {
            e.printStackTrace();
            BufferedReader in = new BufferedReader(new InputStreamReader(con.getErrorStream()));
            String inputLine;
            StringBuffer content = new StringBuffer();
            while ((inputLine = in.readLine()) != null) {
                content.append(inputLine);
            }
            in.close();
            System.out.println(content.toString());
        }
    } catch (Exception exp) {
        System.out.println("Cant load data from API");
        exp.printStackTrace();
    } finally {
        if (con != null)
            con.disconnect();
    }

Is something not configured properly on my linux server?

Update: my problem has not been solved yet and I am still looking for an answer. I cannot find any informative blogs or information on the internet.


问:
How to overwrite Response.Redirect to prevent port coming with it
I have a scenario that my load balancer translates port 80 from outside into port 801 which is local. And When it comes to server, server obviously sees port 801 and in Response.Redirect it tries to inject port 801 into the URL it redirects to but this is not the desired solution for me.

What I am thinking is to:
1. Overwrite Response.Redirect so that I remove the port from it.
2. Have some kind of configuration in web.config to ignore that port.
3. The most nasty way of fixing the problem is to change the whole application to use full URL's inside Response.Redirect which is a big pain.

Is there a good solution to this problem?

Environment:
Windows Vista, Windows 2003 Server, Windows 2008 Server
IIS 6, IIS 7
ASP.NET
C# & VB.NET

答:
My application had code that directly manipulated HttpContext.Current.Response.RedirectLocation. It was referencing HttpContext.Current.Request.Url.Authority, which includes the port information.

I looked at all of the Request properties, but I could not find anything that showed a difference between a port specified directly in the address bar vs one specified via the load balancer.

This application never needed to redirect to a non-standard port, so I replaced the reference of Authority to DnsSafeHost which does not include the port information.

ContentLicense: CC BY-SA 2.5


问:
Python server side AJAX library?
I want to have a browser page that updates some information on a timer or events. I'd like to use Python on the server side. It's quite simple, I don't need anything massively complex.

I can spend some time figuring out how to do all this the "AJAX way", but I'm sure someone has written a nice Python library to do all the heavy lifting. If you have used such a library please let me know the details.

Note: I saw how-to-implement-a-minimal-server-for-ajax-in-python but I want a library to hide the implementation details.

答:
I suggest you to implement the server part in Django, which is in my opinion a fantastic toolkit. Through Django, you produce your XML responses (although I suggest you to use JSON, which is easier to handle on the web browser side).

Once you have something that generates your reply on server side, you have to code the javascript code that invokes it (through the asynchronous call), gets the result (in JSON) and uses it to do something clever on the DOM tree of the page. For this, you need a JavaScript library.

I did some experience with various javascript libraries for "Web 2.0". Scriptaculous is cool, and Dojo as well, but my absolute favourite is MochiKit, because they focus on a syntax which is very pythonic, so it will hide you quite well the differences between javascript and python.

OwnerDisplayName: Nick

Title: Python server side AJAX library?

OwnerDisplayName: Stefano Borini


问:
How do I model a feature that tracks the verified absence of aggregate entities?
Let's say I have a Person table and a Song table and a Person_Song table that is a many-to-many join table between the two other tables.

If a person knows all the lyrics to a song, then a record is inserted into the Person_Song table.  If the person knows 3 songs, then 3 records are inserted.  Fine...easy stuff.

So let's say that we send out a survey to 100 people.  Most people will fill out the survey and they will enter 2 or 3 songs.  Some people will not fill out the survey at all.  And then there are some people who will fill out the survey and note "I don't know the lyrics to any songs".

I want to differentiate the situations where they did not specify any songs and when they explicitly state that they know zero songs.

What is the best way to track this condition in a database?  Is there a well known pattern for this?

Here are some thoughts that I have:

1) Create an entry in the Song table for "No Known Songs" (ID == 0 or something like that).  If they explicitly state that they don't know any songs, then insert a single record in the Person_Song table.  I would also need to enforce (via db constraints or code) that this record is NOT inserted if the person has other records assigned to him.  This is "hacky" for sure, but I think it would work.

2) Create a separate table called PersonNoKnownSongStatus which has a one-to-zero-or-one relationship to the Person table.  If this flag is set for a Person, then a record is inserted.  If we retroactively add records to the Person_Song table, then we would delete this record (or update a flag in the record).  This would work and seems less hacky, but it is about the same amount of work as the first solution.

What further complicates my need is that I need to track other aggreate entities as well.  So imagine we have a Movie table and a Person_Movie join table that keeps track of what movies a person has seen.  Also imagine that we have a Book table and Person_Book join table that keeps track of what books a person has read.  For all of these entities, I need to track whether a person has explicitly acknowledged that he is not familiar with any form of the aggregate entity.

So I suppose this opens the door for a third design:

3)  Create a separate table called PersonNoKnownEntityStatus, which has a many-to-many relationship between the Person table and Entity tables, where Entity contains the lookup records Song, Movie and Book.  If the person acknowledges that they have not seen any movies, then a record is inserted for the Person ID and the associated Entity record for the Movie row.  Ditto for Books and Songs...

Is there another design that I should consider?

(edit)
I forgot to mention the possibility of adding new columns to the Person table.  These could just be boolean flags or even a bitmask that represents the explicit absence of the entities.  I wanted to avoid this solution because there is already a lot of contention on the Person table.

答:
I dislike solutions where the client infers semantics from "special" records, so I would not choose your option 1.

Your option 3 seems to record exactly what we mean and as you've shown, it extends to many such negative responses.

One issue: the database is open to  being contradictory. The database could contain two records for a person one saying "I know song A" and one saying "I know no songs"; this should not happen but preventing it happening is a whole load of hassle.


问:
Partition by Range ERROR 1491 (HY000): The PARTITION function returns the wrong type
I am trying to partition a table by range. The column is type float. I know partitions do not work with float so I thought using a FLOOR() function would allow it to work see code below

```<code>
 ALTER TABLE tester_full
    -> PARTITION BY RANGE (FLOOR(Alt))
    -> (
    -> PARTITION p200 VALUES LESS THAN (FLOOR(300.0)),
    -> PARTITION p300 VALUES LESS THAN (FLOOR(400.0))
    -> );

</code>```

However when I run this I get the following error ERROR 1491 (HY000): The PARTITION function returns the wrong type
Can someone show me how to partition a column that has type float or what this error means?

答:
<pre class="lang-sql prettyprint-override"><code> ALTER TABLE tester_full
    -> PARTITION BY RANGE (CAST(Alt AS UNSIGNED INTEGER))
    -> (
    -> .....
    -> PARTITION p200 VALUES LESS THAN (300),
    -> PARTITION p300 VALUES LESS THAN (400),
    -> .....
    -> PARTITION pMAX VALUES LESS THAN MAXVALUE
    -> );
</code>```

Body:
I am trying to partition a table by range. The column is type float. I know partitions do not work with float so I thought using a FLOOR() function would allow it to work see code below

 ALTER TABLE tester_full
    -> PARTITION BY RANGE (FLOOR(Alt))
    -> (
    -> PARTITION p200 VALUES LESS THAN (FLOOR(300.0)),
    -> PARTITION p300 VALUES LESS THAN (FLOOR(400.0))
    -> );

However when I run this I get the following error ERROR 1491 (HY000): The PARTITION function returns the wrong type
Can someone show me how to partition a column that has type float or what this error means?


问:
How to convert xml to hashmap and ignore empty tags in Kotlin
I want to convert an xml value to a map, but empty tags also come into the map.
I don't want empty tags. maybe a has nested nodes. See below for an example

a = "<rootTag><name>Ali Tan</name><address><tag1>aaa</tag1><tag2></tag2></address></rootTag>"

```<code>  @Test
fun contextLoads() {
    var a = "<rootTag><name>Ali Tan</name><address></address></rootTag>"
    val xmlMapper = XmlMapper()
    val aa = xmlMapper.readValue(a, HashMap::class.java)
    println(aa)

}
</code>```

code result:

{address=, name=Ali Tan}

i want to see

{name=Ali Tan}

答:
If you want to delete all empty tags, you can do it using reccursion:

```<code>fun deleteAllEmptyTags(map: Map<*, *>): Map<*, *> {
    return map
        .mapValues { (_, value) ->
            when (value) {
                is Map<*, *> -> deleteAllEmptyTags(value)
                else -> value
            }
        }
        .filterValues {
            when (it) {
                is Map<*, *> -> it.isNotEmpty()
                is String -> it.isNotBlank()
                else -> true
            }
        }
}
</code>```

For every value in map that is also a map we recursively delete all its tags. After that we filter out empty maps and blank strings.

It even should work with clearing tags that contain only empty tags

Example

<rootTag><name>Ali Tan</name><address></address><outer><inner></inner></outer></rootTag>

Result before deleting

{address=, name=Ali Tan, outer={inner=}}

Result after deleting

{name=Ali Tan}

Body:
I want to convert an xml value to a map, but empty tags also come into the map.
I don't want empty tags. maybe a has nested nodes. See below for an example

a = "<rootTag><name>Ali Tan</name><address><tag1>aaa</tag1><tag2></tag2></address></rootTag>"

  @Test
fun contextLoads() {
    var a = "<rootTag><name>Ali Tan</name><address></address></rootTag>"
    val xmlMapper = XmlMapper()
    val aa = xmlMapper.readValue(a, HashMap::class.java)
    println(aa)

}

code result:

{address=, name=Ali Tan}

i want to see

{name=Ali Tan}

Body:
If you want to delete all empty tags, you can do it using reccursion:

fun deleteAllEmptyTags(map: Map<*, *>): Map<*, *> {
    return map
        .mapValues { (_, value) ->
            when (value) {
                is Map<*, *> -> deleteAllEmptyTags(value)
                else -> value
            }
        }
        .filterValues {
            when (it) {
                is Map<*, *> -> it.isNotEmpty()
                is String -> it.isNotBlank()
                else -> true
            }
        }
}

For every value in map that is also a map we recursively delete all its tags. After that we filter out empty maps and blank strings.

It even should work with clearing tags that contain only empty tags

Example

<rootTag><name>Ali Tan</name><address></address><outer><inner></inner></outer></rootTag>

Result before deleting

{address=, name=Ali Tan, outer={inner=}}

Result after deleting

{name=Ali Tan}


问:
Can I use git to find which commit is needed to fix a branch?
I have a git tree which looks like this:

```<code>master (test passes)
|
|
|  stable (test fails)
|   |
|   /
+---
|
</code>```

There is a test which fails when run against the stable branch, but passes when run against the master branch.  As it is a complicated multi-process test it's rather hard to debug.

Can I use git to find which commit from the master branch can be cherry-picked to the stable branch in order to fix the test?

There are many hundreds of commits on both branches so doing it manually would be painful.

答:
There are many hundreds of commits on both branches so doing it manually would be painful.

This is a job for git-bisect.

Start the bisect, git bisect start.

You know it's failing on stable, mark it as bad. git bisect bad stable.

You know it's passing on master, mark it as good: git bisect good master

Bisect will now select a commit between the two and check it out. Run your test. If it passes, git bisect good. It it fails, git bisect bad.

Bisect will pick another commit. Do the same thing.

Repeat until Git finds the commit where it started failing. Because it is doing a binary search, searching hundreds of commits should take about 20-30 commits. You can automate the process by writing a script to do the build and testing and passing it to git bisect run my_script <args>.

This depends on a single commit being the cause of the failure. If you have not been testing consistently during development there might be a newer commit which introduces the bug again (a regression). You may need to bisect again beginning with a newer "good" commit.

For more details, see the git-bisect documentation. They provide very clear instructions. Also this answer.

Body:
I have a git tree which looks like this:

master (test passes)
|
|
|  stable (test fails)
|   |
|   /
+---
|

There is a test which fails when run against the stable branch, but passes when run against the master branch.  As it is a complicated multi-process test it's rather hard to debug.

Can I use git to find which commit from the master branch can be cherry-picked to the stable branch in order to fix the test?

There are many hundreds of commits on both branches so doing it manually would be painful.


问:
Excel display Alerts despite Application.DisplayAlerts = False
I have a python script that every morning opens an excel file, refreshes it and saves as new file with todays date. Even though no changes occur between the .SaveAs and .Close and despite all precausions taken to not display save prompt, excel of course display a dialog prompting me to save or not before close. And to make this a bit more interesting, this doesn't happen every time, sometimes it can run for weeks without it happening, and then one day it just doesn't work.

Code sample:

import os
import datetime
import win32com.client as win32
from pywinauto.application import Application

# set todays date
dt = datetime.date.today()
# connect to Excel instance
xl = win32.dynamic.Dispatch("Excel.Application")
# open the excel template
wb = xl.Workbooks.Open([path to excel file])
# set report name
report_name = "Pending Report - INTERNAL - " + str(dt) + ".xlsx"

# refresh data
wb.RefreshAll()
# save as new file with todays date
wb.SaveAs(os.path.normpath(path + report_name))
# set excel not to display alerts - to not prompt for save before close
xl.DisplayAlerts = False
# disable Events - to not prompt for save before close
xl.EnableEvents = False
# set state of workbook to Saved to make sure excel sees the file as saved
xl.Workbooks(report_name).Saved = True
# close file and save changes set to true, ie. save the changes upon close
xl.Workbooks(report_name).Close(SaveChanges=1)

# looks for the save prompt - but the code never gets here, it halts on previous line waiting for input on dialog window
try:
    app = Application(backend="uia").connect(title_re=".*Workbook Before Close*")
    txt = app[u"Dialog"][u"Static"].window_text()
    if "Do you want to save the changes you made" in txt:
        app[u"Dialog"].YesButton.click()
except:
    log("l", "i", "Didn't find excel or dialog window, might not be an issue but the Save dialog check wasn't successful")
```

Anyone have any ideas, or know what I'm doing wrong here?
Just to be fully clear, I've tested different combinations of these xl.DisableEvents etc. also tried them separately, some seem to work for a while then one day suddenly it doesn't anymore. Since this is an automated scheduled task, when it halts, it just sits there until I get an angry email asking for the report.

Now I know a workaround would be to create another scheduled task that runs another py file, that checks for the dialog, but that's not the issue here, what I want to get working is excel to do as instructed - i.e. not displaying the save before close prompt.

Thanks everyone.

答:
Try the following:</p>
```<code>xl = win32.gencache.EnsureDispatch('Excel.Application')
</code>```

Body:
I have a python script that every morning opens an excel file, refreshes it and saves as new file with todays date. Even though no changes occur between the .SaveAs and .Close and despite all precausions taken to not display save prompt, excel of course display a dialog prompting me to save or not before close. And to make this a bit more interesting, this doesn't happen every time, sometimes it can run for weeks without it happening, and then one day it just doesn't work.

Code sample:

import os
import datetime
import win32com.client as win32
from pywinauto.application import Application

# set todays date
dt = datetime.date.today()
# connect to Excel instance
xl = win32.dynamic.Dispatch("Excel.Application")
# open the excel template
wb = xl.Workbooks.Open([path to excel file])
# set report name
report_name = "Pending Report - INTERNAL - " + str(dt) + ".xlsx"

# refresh data
wb.RefreshAll()
# save as new file with todays date
wb.SaveAs(os.path.normpath(path + report_name))
# set excel not to display alerts - to not prompt for save before close
xl.DisplayAlerts = False
# disable Events - to not prompt for save before close
xl.EnableEvents = False
# set state of workbook to Saved to make sure excel sees the file as saved
xl.Workbooks(report_name).Saved = True
# close file and save changes set to true, ie. save the changes upon close
xl.Workbooks(report_name).Close(SaveChanges=1)

# looks for the save prompt - but the code never gets here, it halts on previous line waiting for input on dialog window
try:
    app = Application(backend="uia").connect(title_re=".*Workbook Before Close*")
    txt = app[u"Dialog"][u"Static"].window_text()
    if "Do you want to save the changes you made" in txt:
        app[u"Dialog"].YesButton.click()
except:
    log("l", "i", "Didn't find excel or dialog window, might not be an issue but the Save dialog check wasn't successful")

Anyone have any ideas, or know what I'm doing wrong here?
Just to be fully clear, I've tested different combinations of these xl.DisableEvents etc. also tried them separately, some seem to work for a while then one day suddenly it doesn't anymore. Since this is an automated scheduled task, when it halts, it just sits there until I get an angry email asking for the report.

Now I know a workaround would be to create another scheduled task that runs another py file, that checks for the dialog, but that's not the issue here, what I want to get working is excel to do as instructed - i.e. not displaying the save before close prompt.

Thanks everyone.

Body:
Try the following:

xl = win32.gencache.EnsureDispatch('Excel.Application')


问:
Javascript get 100vh in pixels
```<code><html>
    <head>
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
        <div style='height:4000px;background:#EEE;'>
            <div id=vh style='height:100vh;background:#AFB'>
                100vh
                <br>
                <br>
                <br>
                <button onclick='show()' style='font-size:55px'>
                    Show
                </button>
            </div>
            more stuff
        </div>
        <script>
            var vh=document.getElementById('vh')
            function show()
            {
                alert('window.innerHeight='+window.innerHeight
                +', window.outerHeight='+window.outerHeight
                +', screen.height='+screen.height
                +', document.documentElement.clientHeight='+document.documentElement.clientHeight
                +', vh.clientHeight='+vh.clientHeight)
            }
        </script>
    </body>
</html>
</code>```

http://curtastic.com/testvh.html

On my iPad the 100vh div size is 1256 pixels. (if your most recent scroll was upward)

window.innerHeight is 1217.

screen.height is 1024.

window.outerHeight is 0.

documentElement.clientHeight is 4016.

Is there any way in javascript of getting this number 1256? Besides making a div and setting it to height:100vh then checking its clientHeight?

I also have my font size set to 10vh. What is that exactly in pixels?

I am not using jQuery.

I know that 100vh is taller than the visible viewport on purpose on mobile so that the browser bars can change size without altering vh. So I want the size of the screen regardless of the browser bars, which is what vh does.

答:
I know that 100vh is taller than the visible viewport on purpose on mobile so that the browser bars can change size without altering vh. So I want the size of the screen regardless of the browser bars, which is what vh does.

This is important context that shouldn't be ignored. window.innerHeight does not always give you the height of an element with a height of 100vh. window.innerHeight changes as the URL bar appears and disappears. In contrast, 100vh is the viewport height only when the URL bar is hidden. Here is a nice article from the developers at Google about this subject.

I've come up with a solution that works for me. The best way to get the height of an element with a height of 100vh is simply to create that element and measure it.

```
<p>And then in your JavaScript:</p>
<pre class="lang-js prettyprint-override"><code>/** Return the "largest possible viewport" height in px.
 *
 * What is the "largest possible viewport" height?
 * https://developers.google.com/web/updates/2016/12/url-bar-resizing
 */
const getFullVh = () => {
  return document.querySelector('#measure-vh').clientHeight
}
</code>```

I also have my font size set to 10vh. What is that exactly in pixels?

Using getFullVh():

const tenVh = getFullVh() * 0.1
```

Title: Javascript get 100vh in pixels

Body:
        <meta name="viewport" content="width=device-width, initial-scale=1.0">

                100vh

                <button onclick='show()' style='font-size:55px'>
                    Show
                </button>

            more stuff

http://curtastic.com/testvh.html

On my iPad the 100vh div size is 1256 pixels. (if your most recent scroll was upward)

window.innerHeight is 1217.

screen.height is 1024.

window.outerHeight is 0.

documentElement.clientHeight is 4016.

Is there any way in javascript of getting this number 1256? Besides making a div and setting it to height:100vh then checking its clientHeight?

I also have my font size set to 10vh. What is that exactly in pixels?

I am not using jQuery.

I know that 100vh is taller than the visible viewport on purpose on mobile so that the browser bars can change size without altering vh. So I want the size of the screen regardless of the browser bars, which is what vh does.

Body:
I know that 100vh is taller than the visible viewport on purpose on mobile so that the browser bars can change size without altering vh. So I want the size of the screen regardless of the browser bars, which is what vh does.

This is important context that shouldn't be ignored. window.innerHeight does not always give you the height of an element with a height of 100vh. window.innerHeight changes as the URL bar appears and disappears. In contrast, 100vh is the viewport height only when the URL bar is hidden. Here is a nice article from the developers at Google about this subject.

I've come up with a solution that works for me. The best way to get the height of an element with a height of 100vh is simply to create that element and measure it.

<!-- See: `getFullVh()` -->
<div style="overflow: hidden; height: 0">
 <div id="measure-vh" style="position: fixed; height: 100vh"></div>
</div>

And then in your JavaScript:

/** Return the "largest possible viewport" height in px.
 *
 * What is the "largest possible viewport" height?
 * https://developers.google.com/web/updates/2016/12/url-bar-resizing
 */
const getFullVh = () => {
  return document.querySelector('#measure-vh').clientHeight
}

I also have my font size set to 10vh. What is that exactly in pixels?

Using getFullVh():

const tenVh = getFullVh() * 0.1


问:
separating a string column, converting sub values into float and assigning column labels
I have a table t and vector times.

```<code>sym vals
-------------------
A   "3.6, 2.1, 1.8"
B   "2.1, 1.8, 1.6"
C   "2.2, 1.9, 1.6"
D   "1.9, 1.5, 1.3"
E   "2.6, 2.1, 1.9"

times: `0`1`2

</code>```

I want to separate the comma separated string in each row and convert each value into float. The column labels then need to be times. I also want to then drop the column vals. The following statement does this.

```<code>t_out: delete vals from t, 'flip exec times!("FFF";",")0:vals from t

sym 1   2   3
---------------
A   3.6 2.1 1.8
B   2.1 1.8 1.6
C   2.2 1.9 1.6
D   1.9 1.5 1.3
E   2.6 2.1 1.9

</code>```

why does exec times!("FFF";",")0:vals from t transpose the table after converting the values to float? Why do we need 'flip and not just flip? I appreciate your help. Are there alternative methods to achieve this?

答:
This is more of a curiosity but you can effectively force the "flip" to occur naturally by using a by grouping (even if the by grouping is meaningless)

```<code>q)exec times!raze("FFF";",")0:vals by sym:sym from t
sym| 0   1   2
---| -----------
A  | 3.6 2.1 1.8
B  | 2.1 1.8 1.6
C  | 2.2 1.9 1.6
D  | 1.9 1.5 1.3
E  | 2.6 2.1 1.9
</code>```

This also does away with the need to append-each (,') to sideways-join the result

Body:
I have a table t and vector times.

sym vals
-------------------
A   "3.6, 2.1, 1.8"
B   "2.1, 1.8, 1.6"
C   "2.2, 1.9, 1.6"
D   "1.9, 1.5, 1.3"
E   "2.6, 2.1, 1.9"

times: `0`1`2

I want to separate the comma separated string in each row and convert each value into float. The column labels then need to be times. I also want to then drop the column vals. The following statement does this.

t_out: delete vals from t, 'flip exec times!("FFF";",")0:vals from t

sym 1   2   3
---------------
A   3.6 2.1 1.8
B   2.1 1.8 1.6
C   2.2 1.9 1.6
D   1.9 1.5 1.3
E   2.6 2.1 1.9

why does exec times!("FFF";",")0:vals from t transpose the table after converting the values to float? Why do we need 'flip and not just flip? I appreciate your help. Are there alternative methods to achieve this?

Body:
This is more of a curiosity but you can effectively force the "flip" to occur naturally by using a by grouping (even if the by grouping is meaningless)

q)exec times!raze("FFF";",")0:vals by sym:sym from t
sym| 0   1   2
---| -----------
A  | 3.6 2.1 1.8
B  | 2.1 1.8 1.6
C  | 2.2 1.9 1.6
D  | 1.9 1.5 1.3
E  | 2.6 2.1 1.9

This also does away with the need to append-each (,') to sideways-join the result


问:
Value cannot be null. Parameter name: entity error
i have the view:

```<code>@model List<MVCCrud.Models.ViewModels.ListTablaViewModel>
@{
    ViewBag.Title = "Mis datos";
}

<h2>@ViewBag.Title</h2>

<div class="row" style="text-align:right;padding:5px;">
    <a href="~/Tabla/Nuevo" class="btn btn-primary">Nuevo</a>
</div>
<div class="row">
    <div class="col-md-12">
        <table class="table">
            <tr>
                <th>#</th>
                <th>Nombre</th>
                <th>Correo</th>
                <th></th>
            </tr>
            @foreach (var oElemento in Model)
            {
                <tr>
                    <td>@oElemento.Id</td>
                    <td>@oElemento.Nombre</td>
                    <td>@oElemento.Correo</td>
                    <td>
                        <a class="btn btn-default" href="~/Tabla/Editar/@oElemento.Id">Editar</a>
                        <a class="btn btn-danger" href="~/Tabla/Eliminar/@oElemento.Id">Eliminar</a>
                    </td>
                </tr>

            }
        </table>
    </div>

</div>
</code>```

And the method Eliminar on the controller:

```<code> [HttpDelete]
        public ActionResult Eliminar(int? cedula)
        {
            using (ClinicaEntities db = new ClinicaEntities())
            {

                var oTabla = db.Pacientes.Find(cedula);
                db.Pacientes.Remove(oTabla);
                db.SaveChanges();
            }
            return Redirect("~/Paciente/");
        }
</code>```

Once im trying to execute the method it gives me a "Value cannot be null.
Parameter name: entity" error, its like its not passing the "cedula" to the method

答:
You can use @Url.Action to send your cedula field to the Controller method:

```<code><a class="btn btn-default" href="@Url.Action("Editar","Tabla", new { cedula = oElemento.Id })">Editar</a>
<a class="btn btn-danger" href="@Url.Action("Eliminar","Tabla", new { cedula = oElemento.Id })">Eliminar</a>
</code>```

Body:
i have the view:

@model List<MVCCrud.Models.ViewModels.ListTablaViewModel>
@{
    ViewBag.Title = "Mis datos";
}

@ViewBag.Title

    Nuevo

                #
                Nombre
                Correo

            @foreach (var oElemento in Model)
            {

                    @oElemento.Id
                    @oElemento.Nombre
                    @oElemento.Correo

                        Editar
                        Eliminar

            }

And the method Eliminar on the controller:

 [HttpDelete]
        public ActionResult Eliminar(int? cedula)
        {
            using (ClinicaEntities db = new ClinicaEntities())
            {

                var oTabla = db.Pacientes.Find(cedula);
                db.Pacientes.Remove(oTabla);
                db.SaveChanges();
            }
            return Redirect("~/Paciente/");
        }

Once im trying to execute the method it gives me a "Value cannot be null.
Parameter name: entity" error, its like its not passing the "cedula" to the method

Body:
You can use @Url.Action to send your cedula field to the Controller method:

<a class="btn btn-default" href="@Url.Action("Editar","Tabla", new { cedula = oElemento.Id })">Editar</a>
<a class="btn btn-danger" href="@Url.Action("Eliminar","Tabla", new { cedula = oElemento.Id })">Eliminar</a>


问:
RXJS throttletime operator is not working in Angular
I have a method that is making http calls to the server. this method is being called like 500 times and leading page to crash. I want to separate the calls and make a 200ms delay between calls. I thought of using throttletime operator but it it is not working.

```<code>testSubject: Subject<number> = new Subject<number>();

testMethod(id){
   for(let i = 0; i < 500; i++){
     this.testSubject.next(this.counter);
     this.testSubject.pipe(throttleTime(200)).subscribe(
        (data:any) =>{
           return this.addRow(groupId);
         }
        )
        this.counter++;
    }
}
</code>```

I expect the code above to work as follow:

counter gets incremented by 1

Subject.next() fires to update the subject with the new value

Adding the throttletime when subscribing to the testSubject. so it should make 200ms delay

答:
This is how you might use concatMap to ensure only one request (to addRow) runs at a time.

// The Settup
const testSubject: Subject<number> = new Subject<number>();
testSubject.pipe(

  concatMap(_ => this.addRow(groupId))

).subscribe(JSONdataFromAddRow => {/* Do nothing */});

// Triggering 500 calls
let counter = 0;
for(let i = 0; i < 500; i++){
  testSubject.next(counter);
  counter++;
}
```

Body:
I have a method that is making http calls to the server. this method is being called like 500 times and leading page to crash. I want to separate the calls and make a 200ms delay between calls. I thought of using throttletime operator but it it is not working.

testSubject: Subject<number> = new Subject<number>();

testMethod(id){
   for(let i = 0; i < 500; i++){
     this.testSubject.next(this.counter);
     this.testSubject.pipe(throttleTime(200)).subscribe(
        (data:any) =>{
           return this.addRow(groupId);
         }
        )
        this.counter++;
    }
}

I expect the code above to work as follow:

counter gets incremented by 1

Subject.next() fires to update the subject with the new value

Adding the throttletime when subscribing to the testSubject. so it should make 200ms delay


问:
Subtract 1 from placeholder native pipe
Using the new pipe operator |> I would like to subtract 1 from the placeholder like so:

E.g. Suppose that, within a dplyr chain inside of a mutate() I would like to create a new field mpg_minus1 that is mpg - 1.

Pretend we cannot just do mpg_minus1 = mpg - 1, this has to be part of a pipe chain.

```<code># Error: function '-' not supported in RHS call of a pipe
mtcars |> mutate(mpg_minus1 = mpg |> `-`(1)) # vague recolection of seeing syntax like this somewhere

# Error: unexpected symbol in: "mtcars |> mutate(mpg_minus1 = mpg |> (\(.) . - 1)() mtcars"
mtcars |> mutate(mpg_minus1 = mpg |> (\(.) . - 1)())
</code>```

How can I grab the placeholder and subtract 1 before moving on to next pipe operation?

答:
You can "trick" the parser by wrapping the operator in parentheses:

1 |> `-`(1)
## Error: function '-' not supported in RHS call of a pipe

1 |> (`-`)(1)
## [1] 0

1 |> (\(.) . - 1)()
## [1] 0
```
<p>An easy way to test how your pipes are parsed is with <code>quote</code>:</p>
<pre class="lang-r prettyprint-override"><code>quote(1 |> `-`(1))
## Error: function '-' not supported in RHS call of a pipe

quote(1 |> (`-`)(1))
## (`-`)(1, 1)

quote(1 |> (\(.) . - 1)())
## (function(.) . - 1)(1)
</code>```

Title: Subtract 1 from placeholder native pipe

Body:
Using the new pipe operator |> I would like to subtract 1 from the placeholder like so:

E.g. Suppose that, within a dplyr chain inside of a mutate() I would like to create a new field mpg_minus1 that is mpg - 1.

Pretend we cannot just do mpg_minus1 = mpg - 1, this has to be part of a pipe chain.

# Error: function '-' not supported in RHS call of a pipe
mtcars |> mutate(mpg_minus1 = mpg |> `-`(1)) # vague recolection of seeing syntax like this somewhere

# Error: unexpected symbol in: "mtcars |> mutate(mpg_minus1 = mpg |> (\(.) . - 1)() mtcars"
mtcars |> mutate(mpg_minus1 = mpg |> (\(.) . - 1)())

How can I grab the placeholder and subtract 1 before moving on to next pipe operation?

Body:
You can "trick" the parser by wrapping the operator in parentheses:

1 |> `-`(1)
## Error: function '-' not supported in RHS call of a pipe

1 |> (`-`)(1)
## [1] 0

1 |> (\(.) . - 1)()
## [1] 0

An easy way to test how your pipes are parsed is with quote:

quote(1 |> `-`(1))
## Error: function '-' not supported in RHS call of a pipe

quote(1 |> (`-`)(1))
## (`-`)(1, 1)

quote(1 |> (\(.) . - 1)())
## (function(.) . - 1)(1)


问:
Selenium (Python) - NoSuchElementException: Message: no such element: Unable to locate element
I'm trying to make a simple script that goes to the homepage of The Whiskey Exchange, clicks on the following menu item, navigates to the new page and finally grabs a screenshot.

```<code>from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By

chrome_options = Options()

driver = webdriver.Chrome(options=chrome_options)
driver.get("https://www.thewhiskyexchange.com/")
driver.implicitly_wait(3)

search_bar = driver.find_element(
    By.XPATH, "/html/body/div[3]/nav/div/div[3]/div/div/div[2]/a[2]")
search_bar.click()
driver.implicitly_wait(3)

driver.save_screenshot('./image.png')
driver.quit()
</code>```

I've tried multiple approaches to get this to work, mainly by changing the type of finder, but with no luck. I've tried copying both XPATH and Full XPATH (directly from chrome), but that hasn't worked either. Maybe it's something to do with how the site is built, but no idea.

I'm getting the following error message:

```<code>NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"/html/body/div[3]/nav/div/div[3]/div/div/div[2]/a[2]"}
</code>```

First time using selenium, so the struggle is a bit real. Please help.

答:
CSS_SELECTOR

```<code>a.header-button.header-button--search.js-header-button--search
</code>```

XPATH

```<code>//a[@title='Search']
</code>```

You could simply use this css selector since I don't see an xpath like that.

Body:
I'm trying to make a simple script that goes to the homepage of The Whiskey Exchange, clicks on the following menu item, navigates to the new page and finally grabs a screenshot.

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By

chrome_options = Options()

driver = webdriver.Chrome(options=chrome_options)
driver.get("https://www.thewhiskyexchange.com/")
driver.implicitly_wait(3)

search_bar = driver.find_element(
    By.XPATH, "/html/body/div[3]/nav/div/div[3]/div/div/div[2]/a[2]")
search_bar.click()
driver.implicitly_wait(3)

driver.save_screenshot('./image.png')
driver.quit()

I've tried multiple approaches to get this to work, mainly by changing the type of finder, but with no luck. I've tried copying both XPATH and Full XPATH (directly from chrome), but that hasn't worked either. Maybe it's something to do with how the site is built, but no idea.

I'm getting the following error message:

NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"/html/body/div[3]/nav/div/div[3]/div/div/div[2]/a[2]"}

First time using selenium, so the struggle is a bit real. Please help.

Body:
CSS_SELECTOR

a.header-button.header-button--search.js-header-button--search

XPATH

//a[@title='Search']

You could simply use this css selector since I don't see an xpath like that.


问:
Filling the NaN values in the column dataframe based on condition python pandas
I am trying to update my dataframe column value based on the condition but when i check my data frame its value is not getting updated.

```<code>for i in titanic['Survived'].unique():
meanAge = titanic.Age[titanic['Survived'] == i].mean()
meanAge = "{:.1f}".format(meanAge)
df = titanic['Survived'] == i
df1 = titanic.Age[df];
df1.fillna(meanAge, inplace=True)
#print (df1) the value seems to be updated here
</code>```

but print(titanic still shows NAN values.

答:
With the exception of shallow copy operations, and operations with "inplace" as an argument, all operations generate a copy.

You can directly update the titanic DataFrame after:

for i in titanic['Survived'].unique():
    meanAge = titanic.Age[titanic['Survived'] == i].mean()
    meanAge = "{:.1f}".format(meanAge)
    df = titanic['Survived'] == i
    df1 = titanic.Age[df];
    df1.fillna(meanAge, inplace=True)
    titanic.loc[df, 'Age'] = df1
```

Body:
I am trying to update my dataframe column value based on the condition but when i check my data frame its value is not getting updated.

for i in titanic['Survived'].unique():
meanAge = titanic.Age[titanic['Survived'] == i].mean()
meanAge = "{:.1f}".format(meanAge)
df = titanic['Survived'] == i
df1 = titanic.Age[df];
df1.fillna(meanAge, inplace=True)
#print (df1) the value seems to be updated here

but print(titanic still shows NAN values.


问:
Code standard (not style) enforcer for Eclipse
Is there some coding standard enforcer for use with Eclipse (a plugin or something)? I know I can use "Window > Preferences > [Language] > Code Style" to suggest conventions, but these are not enforced.

In other words, I want Coding standard violations to be marked as "Errors" and Coding style violations as "Warnings".

Thanks and regards,
Karthick S.

答: have a look at http://pmd.sourceforge.net/</p>


问:
How to declare array size at runtime without using dynamic memory allocation
Can I declare an array of size n at runtime without using dynamic memory allocation (malloc etc.) in c?</p>

答:
Just use malloc, it's as easy as that:

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

int main(void)
{
    const int n = 10; // Your array size
    int* arr = (int*) malloc(n * sizeof(int));

    // Access the pointer like an array
    arr[0] = 100;
}
</code>```

Body:
Just use malloc, it's as easy as that:

#include <malloc.h>

int main(void)
{
    const int n = 10; // Your array size
    int* arr = (int*) malloc(n * sizeof(int));

    // Access the pointer like an array
    arr[0] = 100;
}


问:
Can't reload/refresh active route
I have recently updated to the new RC3 and Router3alpha and it seems some things have changed.

I noticed that a click on the link of an active route does no longer result in the component to be reloaded. How do I achieve this behaviour with the new router3?

My link looks like

```<code><a [routerLink]="['/link1']">Link1</a>
</code>```

And to test I simply used a random number in ngOnInit:

```<code>export class LinkoneComponent implements OnInit
{

    public foo: number;
    constructor() {}

    ngOnInit()
    {
        this.foo = Math.floor(Math.random() * 100) + 1;
    }

}
</code>```

It works just fine when switiching between routes, but a click on the currently active route does not result in a reload of the component.

答:
On Angular 12+, you can do the following:

```<code>this.router.routeReuseStrategy.shouldReuseRoute = () => false;
this.router.navigate(url);
</code>```

You can make this site-wide by creating a wrapper for Router.

Title: Can't reload/refresh active route

Body:
I have recently updated to the new RC3 and Router3alpha and it seems some things have changed.

I noticed that a click on the link of an active route does no longer result in the component to be reloaded. How do I achieve this behaviour with the new router3?

My link looks like

Link1

And to test I simply used a random number in ngOnInit:

export class LinkoneComponent implements OnInit
{

    public foo: number;
    constructor() {}

    ngOnInit()
    {
        this.foo = Math.floor(Math.random() * 100) + 1;
    }

}

It works just fine when switiching between routes, but a click on the currently active route does not result in a reload of the component.

Body:
On Angular 12+, you can do the following:

this.router.routeReuseStrategy.shouldReuseRoute = () => false;
this.router.navigate(url);

You can make this site-wide by creating a wrapper for Router.


问:
How to parse values from a C string into a struct timespec
My program will be receiving C string input in the format of Wed, 21 Oct 2015 07:28:00 GMT, e.g.

```<code>char * date = "Wed, 21 Oct 2015 07:28:00 GMT"
</code>```

How to convert this into a struct timespec so I can compare with the st_atim, st_mtim, and st_ctim struct timespec's returned from the stat() function?

This post talks about strptime and sscanf, and I also found strftime, but all these convert to a struct time_t or struct tm or integer values.

答:
Look at the definition of a timespec:

struct timespec
{
  time_t tv_sec;  // Seconds
  long   tv_nsec; // Nanoseconds
};
```
<p>So, it's nothing other than a <code>time_t</code> with an additional number of nanoseconds.</p>
<p>A string like you showed (<code>Wed, 21 Oct 2015 07:28:00 GMT</code>) doesn't even have anything more granular than seconds, so the nanoseconds will hardly matter, and you can just parse it into a <code>time_t</code> that goes into <code>tv_sec</code> and set <code>tv_nsec</code> to zero.</p>
<p>By the way the format you showed is most likely based on the specifications outlined in RFC 822 / RFC 1123 / RFC 2822. This should make it a lot easier to search for code that parses it, for example this. This is also informally known as "HTTP date" due to its use in HTTP headers. In fact, libcurl has a function <code>curl_getdate</code> that parses it. You can see its C source code here.</p>
<p>Example:</p>
<pre class="lang-cpp prettyprint-override"><code>#include <curl/curl.h>

timespec ts = {0};
ts.tv_sec = curl_getdate(inputString, NULL);
</code>```

Unless you already use libcurl elsewhere, this could be an unnecessarily large overhead, but you can take it as inspiration or look for other parsing methods that give you a time_t as well.

Body:
My program will be receiving C string input in the format of Wed, 21 Oct 2015 07:28:00 GMT, e.g.

char * date = "Wed, 21 Oct 2015 07:28:00 GMT"

How to convert this into a struct timespec so I can compare with the st_atim, st_mtim, and st_ctim struct timespec's returned from the stat() function?

This post talks about strptime and sscanf, and I also found strftime, but all these convert to a struct time_t or struct tm or integer values.

Body:
Look at the definition of a timespec:

struct timespec
{
  time_t tv_sec;  // Seconds
  long   tv_nsec; // Nanoseconds
};

So, it's nothing other than a time_t with an additional number of nanoseconds.

A string like you showed (Wed, 21 Oct 2015 07:28:00 GMT) doesn't even have anything more granular than seconds, so the nanoseconds will hardly matter, and you can just parse it into a time_t that goes into tv_sec and set tv_nsec to zero.

By the way the format you showed is most likely based on the specifications outlined in RFC 822 / RFC 1123 / RFC 2822. This should make it a lot easier to search for code that parses it, for example this. This is also informally known as "HTTP date" due to its use in HTTP headers. In fact, libcurl has a function curl_getdate that parses it. You can see its C source code here.

Example:

#include <curl/curl.h>

timespec ts = {0};
ts.tv_sec = curl_getdate(inputString, NULL);

Unless you already use libcurl elsewhere, this could be an unnecessarily large overhead, but you can take it as inspiration or look for other parsing methods that give you a time_t as well.


问:
Initialize class member from overloaded new operator
Is there any way to initialize value of member field of a class from it's overloaded new operator?
I can set values of object in operator new, but after it returns my pre-initialized object, class constructor overrides all uninitialized values (at least, in debug compilation).

What I'm trying to do: allocator that uses vector of buckets of my objects, where newly created objects fill buckets one by one. Each bucket stores amount of filled slots and index of next slot that would be filled, allocator increases that amount and deleter decreases it. When amount reaches zero, it moves bucket to the end of vector of buckets, so when allocator fills currently filling bucket it either reuses that emptied bucket (and moves it into begin of vector) or creates and adds a new one. But for deleter to know which bucket's amount to decrease, it needs a pointer to the bucket where this object was placed (otherwise, I'd need to search each bucket in vector to find object being deleted, or map object pointers to buckets).

So, I'm trying to write current bucket pointer into my objects itself from allocator. But constructor overwrites it with nullptr.

答:
If your object has a bucket ID/pointer as a member, it must be initialised in the object's constructor. No ifs, buts, or maybes here. One way to do this is as follows:

```<code> auto [bucket, slotAddress] = findFreeSlot(sizeof(MyObject));
 MyObject* newObject = new (slotAddress) MyObject{bucket}; // placement new
 // optionally
 someSmartPtr<MyObject, CustomDeleter> ptr{newObject, customDeleter};
</code>```

You don't need a custom overloaded operator new here.

If you absolutely positively must initialise the bucket in the overloaded operator new, do not make bucket a member of your object. Instead, allocate and initialise it as a piece of auxiliary information, much like standard operator new stores bookkeeping info about memory blocks. For example (untested, may have UB, but if you are writing cistom allocators you probably know how to do it right):

```<code>struct block {
   std::aligned_storage_t<sizeof(Bucket)> buck;
};

void* operator new (size_t size) {
   auto [bucket, slotAddress] = findFreeSlot(sizeof(block) + size);
   block* blk = new(slotAddress) block;
   Bucket* bck = new(&blk->buck) Bucket(bucket);
   return blk+1;
}
</code>```

Now you can go from the address of MyObject to the bucket ID/pointer:

```<code>Bucket bucketOfMyObject (MyObject* m) {
   block* b = reinterpret_cast<block*>(m) - 1;
   return *reinterpret_cast<Bucket*>(b->buck);
}
</code>```

Body:
If your object has a bucket ID/pointer as a member, it must be initialised in the object's constructor. No ifs, buts, or maybes here. One way to do this is as follows:

 auto [bucket, slotAddress] = findFreeSlot(sizeof(MyObject));
 MyObject* newObject = new (slotAddress) MyObject{bucket}; // placement new
 // optionally
 someSmartPtr<MyObject, CustomDeleter> ptr{newObject, customDeleter};

You don't need a custom overloaded operator new here.

If you absolutely positively must initialise the bucket in the overloaded operator new, do not make bucket a member of your object. Instead, allocate and initialise it as a piece of auxiliary information, much like standard operator new stores bookkeeping info about memory blocks. For example (untested, may have UB, but if you are writing cistom allocators you probably know how to do it right):

struct block {
   std::aligned_storage_t<sizeof(Bucket)> buck;
};

void* operator new (size_t size) {
   auto [bucket, slotAddress] = findFreeSlot(sizeof(block) + size);
   block* blk = new(slotAddress) block;
   Bucket* bck = new(&blk->buck) Bucket(bucket);
   return blk+1;
}

Now you can go from the address of MyObject to the bucket ID/pointer:

Bucket bucketOfMyObject (MyObject* m) {
   block* b = reinterpret_cast<block*>(m) - 1;
   return *reinterpret_cast<Bucket*>(b->buck);
}


问:
Boost::asio::strand merges multiple handlers into one
I am currently using boost 1.70 and I was trying to implement io service loop to have a custom call between each invoked handle, and I couldn't get it to work. After some examination, I gained suspicion there are multiples handles executed in one call of "run_one" function. So I wrote a test code:

```<code>#include <boost/asio/io_service.hpp>
#include <boost/asio/strand.hpp>
#include <boost/asio/post.hpp>

#include <thread>
#include <mutex>

class StrandPost
{
private:
    boost::asio::io_service           service_;
    boost::asio::io_service::work     work_;
    boost::asio::io_service::strand   strand_;

    std::thread                       module_thread_;
    void Run() {
        auto run_one = [this]() {
            std::cout << " ---- Running one ----" << std::endl;
            auto retval = service_.run_one();
            return retval;
        };

        while (run_one());
        std::cout << " ---- Ending run ----" << std::endl;
    }

public:
    StrandPost()
        : service_()
        , work_(service_)
        , strand_(service_)
        , module_thread_(&StrandPost::Run, this)
    {}

    ~StrandPost() {
        service_.stop();
        if (module_thread_.joinable()) {
            module_thread_.join();
        }
    }

    void PlanOutput(const std::string& string) {
        boost::asio::post(strand_,[string](){
            std::cout << string  <<std::endl;
        });
//        boost::asio::post(service_,[string](){
//            std::cout << string  <<std::endl;
//        });
    }
};

} // -----  end anonymous namespace   -----

int main() {
    StrandPost strand;

    strand.PlanOutput("First message");
    strand.PlanOutput("Second message");
    strand.PlanOutput("Third message");
    strand.PlanOutput("Fourth message");

    std::this_thread::sleep_for(std::chrono::seconds(1));
    return 0;
}
</code>```

And the output of that code confirmed my theory, because it was:

---- Running one ----

First message

---- Running one ----

Second message

Third message

Fourth message

---- Running one ----

---- Ending run ----

When using "io_service" directly, it works as expected, but when using "strand", after the first handle, multiple handles are executed as one.

So, the strand effectively merged several handlers into one.
My question is:

Is this bug or is this intentional? Am I doing something wrong?

If this is a bug, is it reported? Because I could not find a mention of this anywhere.

答:
This is, indeed, as intended. The strand_executor_service pops all ready handlers on the same strand:

```<code>void strand_executor_service::run_ready_handlers(implementation_type& impl)
{
  // Indicate that this strand is executing on the current thread.
  call_stack<strand_impl>::context ctx(impl.get());

  // Run all ready handlers. No lock is required since the ready queue is
  // accessed only within the strand.
  boost::system::error_code ec;
  while (scheduler_operation* o = impl->ready_queue_.front())
  {
    impl->ready_queue_.pop();
    o->complete(impl.get(), ec, 0);
  }
}
</code>```

It is quite obvious that this can have a great performance improving impact.

Well, its not that easy, since I also need to be guaranteed that handles posted for execution from a given thread will be executed in the order of posting. Preserving order between posts from different threads is irrelevant, however order of posts from a given thread must be preserved, and as far as I know, "io_service" does not guarantee this. But thanks for the answer, looking further into the boost implementation, it looks you are completely right. –
TStancek
6 hours ago

io_service does have the ordering guarantees of a strand (in fact, the strand's guarantees derive from that). In your case, there is - by definition  - only one thread, so everything on the service will be in an implicit strand (see Why do I need strand per connection when using boost::asio?).

Summary

You can do without the strand for the example code in your question.

If your situation is more involved and you need the one-by-one message processing control, you would do better to have a task queue that implements this explicitly, instead of depending on implementation details.

Body:
I am currently using boost 1.70 and I was trying to implement io service loop to have a custom call between each invoked handle, and I couldn't get it to work. After some examination, I gained suspicion there are multiples handles executed in one call of "run_one" function. So I wrote a test code:

#include <boost/asio/io_service.hpp>
#include <boost/asio/strand.hpp>
#include <boost/asio/post.hpp>

#include <thread>
#include <mutex>

class StrandPost
{
private:
    boost::asio::io_service           service_;
    boost::asio::io_service::work     work_;
    boost::asio::io_service::strand   strand_;

    std::thread                       module_thread_;
    void Run() {
        auto run_one = [this]() {
            std::cout << " ---- Running one ----" << std::endl;
            auto retval = service_.run_one();
            return retval;
        };

        while (run_one());
        std::cout << " ---- Ending run ----" << std::endl;
    }

public:
    StrandPost()
        : service_()
        , work_(service_)
        , strand_(service_)
        , module_thread_(&StrandPost::Run, this)
    {}

    ~StrandPost() {
        service_.stop();
        if (module_thread_.joinable()) {
            module_thread_.join();
        }
    }

    void PlanOutput(const std::string& string) {
        boost::asio::post(strand_,[string](){
            std::cout << string  <<std::endl;
        });
//        boost::asio::post(service_,[string](){
//            std::cout << string  <<std::endl;
//        });
    }
};

} // -----  end anonymous namespace   -----

int main() {
    StrandPost strand;

    strand.PlanOutput("First message");
    strand.PlanOutput("Second message");
    strand.PlanOutput("Third message");
    strand.PlanOutput("Fourth message");

    std::this_thread::sleep_for(std::chrono::seconds(1));
    return 0;
}

And the output of that code confirmed my theory, because it was:

---- Running one ----

First message

---- Running one ----

Second message

Third message

Fourth message

---- Running one ----

---- Ending run ----

When using "io_service" directly, it works as expected, but when using "strand", after the first handle, multiple handles are executed as one.

So, the strand effectively merged several handlers into one.
My question is:

Is this bug or is this intentional? Am I doing something wrong?

If this is a bug, is it reported? Because I could not find a mention of this anywhere.

Body:
This is, indeed, as intended. The strand_executor_service pops all ready handlers on the same strand:

void strand_executor_service::run_ready_handlers(implementation_type& impl)
{
  // Indicate that this strand is executing on the current thread.
  call_stack<strand_impl>::context ctx(impl.get());

  // Run all ready handlers. No lock is required since the ready queue is
  // accessed only within the strand.
  boost::system::error_code ec;
  while (scheduler_operation* o = impl->ready_queue_.front())
  {
    impl->ready_queue_.pop();
    o->complete(impl.get(), ec, 0);
  }
}

It is quite obvious that this can have a great performance improving impact.

Well, its not that easy, since I also need to be guaranteed that handles posted for execution from a given thread will be executed in the order of posting. Preserving order between posts from different threads is irrelevant, however order of posts from a given thread must be preserved, and as far as I know, "io_service" does not guarantee this. But thanks for the answer, looking further into the boost implementation, it looks you are completely right. –
TStancek
6 hours ago

io_service does have the ordering guarantees of a strand (in fact, the strand's guarantees derive from that). In your case, there is - by definition  - only one thread, so everything on the service will be in an implicit strand (see Why do I need strand per connection when using boost::asio?).

Summary

You can do without the strand for the example code in your question.

If your situation is more involved and you need the one-by-one message processing control, you would do better to have a task queue that implements this explicitly, instead of depending on implementation details.


问:
Use record rows as columns BigQuery
Suppose I have a table with rows like this table, where each row of the table has records in an array form.

Using Bigquery,
Is there a way I can turn this into a table that has 'a', 'b', 'c' as its own columns, with 100, 46, 29 as the values in the rows?

I.e.
turn

```<code>Row | abc_keys | abc_intValues
------------------------------
1   | a        | 100
    | b        | 46
    | c        | 29
2   | a        | 101
    | b        | 47
    | c        | 30

</code>```

into

```<code>Row | a   | b  | c
-------------------
1   | 100 | 46 | 29
2   | 101 | 47 | 30
</code>```

答:
Consider below approach

```<code>select * except(row_hash) from (
  select keys, intValues, to_json_string(t) row_hash
  from your_table t, unnest(abc)
)
pivot (any_value(intValues) for keys in ('a', 'b', 'c'))
</code>```

if applied to sample data in your question - output is

Title: Use record rows as columns BigQuery

Body:
Suppose I have a table with rows like this table, where each row of the table has records in an array form.

Using Bigquery,
Is there a way I can turn this into a table that has 'a', 'b', 'c' as its own columns, with 100, 46, 29 as the values in the rows?

I.e.
turn

Row | abc_keys | abc_intValues
------------------------------
1   | a        | 100
    | b        | 46
    | c        | 29
2   | a        | 101
    | b        | 47
    | c        | 30

into

Row | a   | b  | c
-------------------
1   | 100 | 46 | 29
2   | 101 | 47 | 30

Body:
Consider below approach

select * except(row_hash) from (
  select keys, intValues, to_json_string(t) row_hash
  from your_table t, unnest(abc)
)
pivot (any_value(intValues) for keys in ('a', 'b', 'c'))

if applied to sample data in your question - output is


问:
How can I sum a pandas data frame by only custom
I want to group the values by account and get summed rows but only where account is the same. I want a scalable version of it which can do this over 10,000 rows

What I have right now:

```<code>account  1      2
a       100     30
a       20      40
c       30      30
c       40      20
</code>```

What I want:

```<code>account 1     2
a       120   70
b       70    50
</code>```

答:
Use groupby + reset_index:

```<code>sums = df.groupby('account').sum().reset_index()
</code>```

Output:

```<code>>>> sums
  account    1   2
0       a  120  70
1       c   70  50
</code>```

Body:
I want to group the values by account and get summed rows but only where account is the same. I want a scalable version of it which can do this over 10,000 rows

What I have right now:

account  1      2
a       100     30
a       20      40
c       30      30
c       40      20

What I want:

account 1     2
a       120   70
b       70    50

Body:
Use groupby + reset_index:

sums = df.groupby('account').sum().reset_index()

Output:

>>> sums
  account    1   2
0       a  120  70
1       c   70  50


问:
help parsing tab file and custom formatting in perl
I have an output file that is \t delimited:

```<code>Data for 08/10/2011
Host    QueueName   Queue-id
test    123 Test Q  110
test    456 Test Q  120
test    789 Test Q  130
</code>```

I'm looking to remove the first line (date) and then I want the 2nd line (header columns) to
print out with the values like so as my final output file:

```<code>Host=test QueueName=123 Test Q Queue-id=110
Host=test QueueName=456 Test Q Queue-id=120
Host=test QueueName=789 Test Q Queue-id=130
</code>```

What is a good way/practice to do this in perl?

答:
I would recommend Text::CSV_XS for reading the file.

In this recent question, there was a similar problem: How can I use Perl extract a particular column from a tab-separated file? (See my answer)

```<code>use warnings;
use strict;
use Text::CSV_XS;
use autodie;

my $csv = Text::CSV_XS->new( { sep_char => "\t" } );
<DATA>;  # discard the first line
$csv->column_names ($csv->getline (*DATA));
my $hr = $csv->getline_hr_all(*DATA);

for my $hashref (@$hr) {
    my @list;
    for my $key ($csv->column_names()) {
        push @list, join '=', $key, $hashref->{$key};
    }
    print "@list\n";
}
__DATA__
Data for 08/10/2011
Host    QueueName   Queue-id
test    123 Test Q  110
test    456 Test Q  120
test    789 Test Q  130
</code>```

Body:
I have an output file that is \t delimited:

Data for 08/10/2011
Host    QueueName   Queue-id
test    123 Test Q  110
test    456 Test Q  120
test    789 Test Q  130

I'm looking to remove the first line (date) and then I want the 2nd line (header columns) to
print out with the values like so as my final output file:

Host=test QueueName=123 Test Q Queue-id=110
Host=test QueueName=456 Test Q Queue-id=120
Host=test QueueName=789 Test Q Queue-id=130

What is a good way/practice to do this in perl?

Body:
I would recommend Text::CSV_XS for reading the file.

In this recent question, there was a similar problem: How can I use Perl extract a particular column from a tab-separated file? (See my answer)

use warnings;
use strict;
use Text::CSV_XS;
use autodie;

my $csv = Text::CSV_XS->new( { sep_char => "\t" } );
<DATA>;  # discard the first line
$csv->column_names ($csv->getline (*DATA));
my $hr = $csv->getline_hr_all(*DATA);

for my $hashref (@$hr) {
    my @list;
    for my $key ($csv->column_names()) {
        push @list, join '=', $key, $hashref->{$key};
    }
    print "@list\n";
}
__DATA__
Data for 08/10/2011
Host    QueueName   Queue-id
test    123 Test Q  110
test    456 Test Q  120
test    789 Test Q  130


问:
Linking External Identity Users With Existing Users
I'm adding an external identity provider, Azure multi-tenant, as a login option. I have local accounts right now and they know nothing about Azure AD users.

I want to create an Azure Enterprise App that other tenants can use to set up SSO using OpenID Connect. Also I want the app to support User Provisioning by setting up a SCIM API.

I can't really find any documents on how to handle linking Azure AD users with the existing accounts in my IDP. I've seen examples where users can login using their local account, authenticate with Azure, and then their local account is updated to have the Azure AD User ID. This approach still seems pretty manual. Another thought was to have a step in the login journey, where if no local account has the Azure AD User ID then find a local account with the same email. I don't like this approach either since the emails might not always match. Is there an approach where an admin can automatically link all accounts with a sync or upload?

答:
SYSTEMS

First it's worth clarifying roles:

Role
Details

Authorization Server (AS)
Your UIs and APIs receive tokens from this. It is where accounts and linked accounts are stored. It is where you use SCIM to update account records. It is where you apply account linking logic.

Identity Provider (IDP)
There can be multiple of these. When your apps call the AS it manages connections to them, and exchanges IDP tokens for AS tokens that are returned to apps. It is not usual to use SCIM against an IDP.

You are using IdentityServer as the AS so your UIs and APIs will continue to use IdentityServer tokens and remain simple. Meanwhile Azure AD will become an alternative IDP. So on the data side of things your architecture is in a good place.

AUTHENTICATION ACTIONS

I would aim to solve your problems via custom authentication actions, and to design this in a vendor agnostic way. Not all providers support these concepts, but IdentityServer has some pretty good extensibility features, so hopefully it has what you need.

A bit of code, configuration and technical investigations in IdentityServer feel like the correct direction, with no complexity added to your applications. I will describe techniques in terms of Curity (where I work), but the same principles can apply to any system.

USERNAME AUTHENTICATOR

A great way to deal with user specific differences is to make the initial screen prompt only for an email. See this example for how that looks. Later, when authentication has completed, you could set a cookie so that this screen is not shown on subsequent logins.

Then, before asking for credentials, apply some scripted logic, eg to look up existing account attributes, and decide how the user should authenticate. You might decide to route unknown users to Azure AD or do something based on business partner email suffixes.

DATA UPDATES

Something simple that might work in advance of adding Azure AD support is to assign all users a Tenant ID, and perhaps existing users get a Tenant ID of 1. Only those users are allowed to sign in with Identity Server - all others have to use Azure AD.

SCRIPTED LOGIC AND ACCOUNT LINKING

For a worked example of how this looks, see this Account Linking with Facebook tutorial. In this example the objective is to update the main account with a new linked account. This account linking doc may give you some additional ideas for your scenario. It should be possible to run custom logic before triggering authentication or once your have the Azure IDP attributes.

INVOLVE THE USER IF NEEDED

It may also be useful to present a custom screen to ask the user if they have an existing account when they first login via Azure AD. If not then an Azure AD login can create the primary account in IdentityServer data in addition to a linked account.

USERS AND PARTNERS

How users onboard is interesting, and discussed in this detailed article. I always start by getting a feel for the type of assets involved:

Type
Description

Personal Assets
You allow any user to sign up and they only have access to their own assets

Corporate Assets
Users are provisioned by an administrator, eg a banker is granted access to financial data according to business rules

In your case it feels like users are from the second category, so to enable a user to fully  sign up you need data from the partner, either fed in manually or by getting them to call your API, before you can assign the user the correct tenant ID. This might eventually result in TenantID=23, but there is nothing to stop you initially allowing users to onboard and placing them in a default TenantID=0 bucket.

Ultimately this all comes down to data, claims and API authorization. Eg APIs could return certain data to TenantID=0 users but only return privileged data to users whose tenant ID has been asserted by an administrator. Not sure if these thoughts of mine match your scenario but hopefully they provide a useful hint or two.

SUMMARY

Reliable account linking is tricky, but it should be solvable via the building blocks of the Authorization Server, using the above techniques. The end result should be deterministic user data, with no duplicate users.


问:
How to get the common ordered characters between 2 strings in python?
How to get the common ordered characters between 2 strings in python?

for example:

```<code>str1 = 'AAA'
str2 = 'AXA'
</code>```

output should be 'AA'

答:
Compare each characters from 2 strings and keep it when they are the same:

```<code>str1 = 'AAA'
str2 = 'AXA'

str3 = ''.join(c1 for c1, c2 in zip(str1, str2) if c1 == c2)
print(str3)

# Output
'AA'
</code>```

Other example:

```<code>str1 = 'ABC'
str2 = 'AZB'

str3 = ''.join(c1 for c1, c2 in zip(str1, str2) if c1 == c2)
print(str3)

# Output
'A'
</code>```

Body:
How to get the common ordered characters between 2 strings in python?

for example:

str1 = 'AAA'
str2 = 'AXA'

output should be 'AA'

Body:
Compare each characters from 2 strings and keep it when they are the same:

str1 = 'AAA'
str2 = 'AXA'

str3 = ''.join(c1 for c1, c2 in zip(str1, str2) if c1 == c2)
print(str3)

# Output
'AA'

Other example:

str1 = 'ABC'
str2 = 'AZB'

str3 = ''.join(c1 for c1, c2 in zip(str1, str2) if c1 == c2)
print(str3)

# Output
'A'


问:
How can I move an element inside a flex div to the right?
i'm trying to move these bars to the right next to the logout button.

This is the current style.

.p-menubar-button {
    display: none;
    cursor: pointer;
    align-items: center;
    justify-content: center;
}
```

I have tried to align-content: flex-end but it doesn't move it.

This is what I'm trying to achieve

答:
This works

.p-menubar-button {
  margin-left: auto;
  order: 1;
}
```

And then for the class used on the logout button, I use order: 2.

Body:
i'm trying to move these bars to the right next to the logout button.

This is the current style.

.p-menubar-button {
    display: none;
    cursor: pointer;
    align-items: center;
    justify-content: center;
}

I have tried to align-content: flex-end but it doesn't move it.

This is what I'm trying to achieve

Body:
This works

.p-menubar-button {
  margin-left: auto;
  order: 1;
}

And then for the class used on the logout button, I use order: 2.


问:
Wordpress: trying to get posts by tag
I've written some code which automatically creates some posts and adds a tag to them.  I can see the tags in the 'All posts' admin panel and I can click on the posts 'Tag' link to get just those posts with the tags.

However, in a plugin that I'm writing using $wp_query no matter what parameters I pass in, I just get the complete list of posts back whether they have the tag that I am looking for or not.

Here's my code:

```<code>// Now retrieve all items matching this brand name . . .
$query=new WP_Query(array('posts_per_page=5', array('tag' => array($brand_name))));

// The Loop
while ( $query->have_posts() ) : $query->the_post();
    echo '<li>';
    the_title();
    echo '</li>';
endwhile;

// Reset Post Data
wp_reset_postdata();
</code>```

This produces 10 results when I've told it only to return 5.  In reality I should only get 2 posts back as that's the total number with the tag.

Looking around on the web there seems to be a lot of people having the same problem but no solutions.  I must have tried about 10 different ways of specifying the tag but the fact that the number of posts returned is wrong suggests I've either got something completely wrong or there is some kind of bug.  Wordpress version is 3.4.1 if it helps.

Can any Wordpress pro's shed light on this ?

Thanks in advance !

答:
Took me a while. This is how you get 3 random posts with one of the same tag from a post

```<code>$post = get_post(); // if you don't have $post->ID already
$tag_ids = wp_get_post_tags( $post->ID, array( "fields" => "ids" ) ); // current tags
$args = array(
    "numberposts" => 3,
    "orderby" => "rand",
    "post__not_in" => array( $post->ID ), //exclude current
    "post_type" => "article", // defaults to "post", also note "any" option
    "tax_query" => array(
        array(
            "taxonomy" => "post_tag",
            "field"    => "term_id",
            "terms"    => $tag_ids
        )
    )
);
$posts = get_posts( $args ); // getting posts
</code>```

if it still doesn't work for you may view sql request that generated by $args to troubleshoot it further

```<code>$q = new WP_Query($args);
echo $q->request;
</code>```

Title: Wordpress: trying to get posts by tag

Body:
I've written some code which automatically creates some posts and adds a tag to them.  I can see the tags in the 'All posts' admin panel and I can click on the posts 'Tag' link to get just those posts with the tags.

However, in a plugin that I'm writing using $wp_query no matter what parameters I pass in, I just get the complete list of posts back whether they have the tag that I am looking for or not.

Here's my code:

// Now retrieve all items matching this brand name . . .
$query=new WP_Query(array('posts_per_page=5', array('tag' => array($brand_name))));

// The Loop
while ( $query->have_posts() ) : $query->the_post();
    echo '
';
    the_title();
    echo '
';
endwhile;

// Reset Post Data
wp_reset_postdata();

This produces 10 results when I've told it only to return 5.  In reality I should only get 2 posts back as that's the total number with the tag.

Looking around on the web there seems to be a lot of people having the same problem but no solutions.  I must have tried about 10 different ways of specifying the tag but the fact that the number of posts returned is wrong suggests I've either got something completely wrong or there is some kind of bug.  Wordpress version is 3.4.1 if it helps.

Can any Wordpress pro's shed light on this ?

Thanks in advance !

Body:
Took me a while. This is how you get 3 random posts with one of the same tag from a post

$post = get_post(); // if you don't have $post->ID already
$tag_ids = wp_get_post_tags( $post->ID, array( "fields" => "ids" ) ); // current tags
$args = array(
    "numberposts" => 3,
    "orderby" => "rand",
    "post__not_in" => array( $post->ID ), //exclude current
    "post_type" => "article", // defaults to "post", also note "any" option
    "tax_query" => array(
        array(
            "taxonomy" => "post_tag",
            "field"    => "term_id",
            "terms"    => $tag_ids
        )
    )
);
$posts = get_posts( $args ); // getting posts

if it still doesn't work for you may view sql request that generated by $args to troubleshoot it further

$q = new WP_Query($args);
echo $q->request;


问:
How to point to the ARN of a dynamodb table instead of using the name when using boto3
I'm trying to access a dynamodb table in another account without having to make any code changes if possible. I've setup the IAM users, roles and policies to make this possible and have succeeded with other services such as sqs and s3.

The problem I have now is with dynamodb as the code to intialise the boto3.resource connection seems to only allow me to point to the name. docs

dynamodb = boto3.resource('dynamodb', region_name='us-east-2')

table = dynamodb.Table(config['dynamo_table_1'])
```

This causes the problem of the code trying to access a table with that particular name in the account the code is executing in which errors out as the table exists in a different AWS account.

Is there a way to pass the ARN of the table or some identifier that would allow me to specify the accountID?

答:
There's sample code at https://docs.aws.amazon.com/prescriptive-guidance/latest/patterns/configure-cross-account-access-to-amazon-dynamodb.html which shows how to do cross-account access. Here is a snippet from the the attached zip. I expect you could do .resource() as well as .client() with the same arguments.</p>
```<code>import boto3
from datetime import datetime

sts_client = boto3.client('sts')
sts_session = sts_client.assume_role(RoleArn='arn:aws:iam::<Account-A ID>::role/DynamoDB-FullAccess-For-Account-B',
                                      RoleSessionName='test-dynamodb-session')

KEY_ID = sts_session['Credentials']['AccessKeyId']
ACCESS_KEY = sts_session['Credentials']['SecretAccessKey']
TOKEN = sts_session['Credentials']['SessionToken']

dynamodb_client = boto3.client('dynamodb',
                                region_name='us-east-2',
                                aws_access_key_id=KEY_ID,
                                aws_secret_access_key=ACCESS_KEY,
                                aws_session_token=TOKEN)
</code>```

Body:
I'm trying to access a dynamodb table in another account without having to make any code changes if possible. I've setup the IAM users, roles and policies to make this possible and have succeeded with other services such as sqs and s3.

The problem I have now is with dynamodb as the code to intialise the boto3.resource connection seems to only allow me to point to the name. docs

dynamodb = boto3.resource('dynamodb', region_name='us-east-2')

table = dynamodb.Table(config['dynamo_table_1'])

This causes the problem of the code trying to access a table with that particular name in the account the code is executing in which errors out as the table exists in a different AWS account.

Is there a way to pass the ARN of the table or some identifier that would allow me to specify the accountID?

Body:
There's sample code at https://docs.aws.amazon.com/prescriptive-guidance/latest/patterns/configure-cross-account-access-to-amazon-dynamodb.html which shows how to do cross-account access. Here is a snippet from the the attached zip. I expect you could do .resource() as well as .client() with the same arguments.

import boto3
from datetime import datetime

sts_client = boto3.client('sts')
sts_session = sts_client.assume_role(RoleArn='arn:aws:iam::<Account-A ID>::role/DynamoDB-FullAccess-For-Account-B',
                                      RoleSessionName='test-dynamodb-session')

KEY_ID = sts_session['Credentials']['AccessKeyId']
ACCESS_KEY = sts_session['Credentials']['SecretAccessKey']
TOKEN = sts_session['Credentials']['SessionToken']

dynamodb_client = boto3.client('dynamodb',
                                region_name='us-east-2',
                                aws_access_key_id=KEY_ID,
                                aws_secret_access_key=ACCESS_KEY,
                                aws_session_token=TOKEN)