问:
SQL injection login bypass
I am preparing SQL injection vulnerable page to test skills, here is my code:

```<code><?php
    echo "<center><h1>Login Bypass</h1></center>";
    include 'config.php';
    mysql_connect($host, $user, $password) or die(mysql_error());
    mysql_select_db($database) or die(mysql_error());

    $name = $_REQUEST['name'];
    $passwd = $_REQUEST['passwd'];
    $query_string = "SELECT * FROM users WHERE username = '$name' AND password = '$passwd'";
    echo "<center>".$query_string."</center><br/>";
    $query = mysql_query($query_string) or die(mysql_error());
    $row = mysql_fetch_array($query);
    if(mysql_num_rows($query)>0)
        echo "<center>SUCCESS</center><br/>";
    else echo "<center>ACCESS DENIED</center><br/>";
    echo "<center>".$row['email']."</center><br/>";
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>
    <title>Login Bypass</title>
    <meta http-equiv="content-type" content="text/html;charset=utf-8" />
    <meta name="generator" content="Geany 0.19.1" />
</head>

<body>
    <center>
    <form action="login_bypass.php" method="get">
        Login: <input name="name">
        Password: <input name="passwd" >
        <input type="submit" value="CHECK">
    </form>
    </center>
</body>

</html>
</code>```

I have also table users where I have username='agajan' and password='12345' email='torayeff@gmail.com'.
I know that this query is vulnerable:

```<code>$query_string = "SELECT * FROM users WHERE username = '$name' AND password = '$passwd'";
</code>```

But when I insert instead of username the following "agajan' /*" and leave password field empty I  get:

```<code>SELECT * FROM users WHERE username = 'agajan' /* ' AND password = ' '
</code>```

...but It gives me mysql error.  Can anyone explain me why I can not inject sql?

答: You forgot ";" before $username</p>

Title: SQL injection login bypass

Body:
I am preparing SQL injection vulnerable page to test skills, here is my code:

<?php
    echo "
Login Bypass
";
    include 'config.php';
    mysql_connect($host, $user, $password) or die(mysql_error());
    mysql_select_db($database) or die(mysql_error());

    $name = $_REQUEST['name'];
    $passwd = $_REQUEST['passwd'];
    $query_string = "SELECT * FROM users WHERE username = '$name' AND password = '$passwd'";
    echo "".$query_string."
";
    $query = mysql_query($query_string) or die(mysql_error());
    $row = mysql_fetch_array($query);
    if(mysql_num_rows($query)>0)
        echo "SUCCESS
";
    else echo "ACCESS DENIED
";
    echo "".$row['email']."
";
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

    <title>Login Bypass</title>
    <meta http-equiv="content-type" content="text/html;charset=utf-8" />
    <meta name="generator" content="Geany 0.19.1" />

    <form action="login_bypass.php" method="get">
        Login: <input name="name">
        Password: <input name="passwd" >
        <input type="submit" value="CHECK">
    </form>

I have also table users where I have username='agajan' and password='12345' email='torayeff@gmail.com'.
I know that this query is vulnerable:

$query_string = "SELECT * FROM users WHERE username = '$name' AND password = '$passwd'";

But when I insert instead of username the following "agajan' /*" and leave password field empty I  get:

SELECT * FROM users WHERE username = 'agajan' /* ' AND password = ' '

...but It gives me mysql error.  Can anyone explain me why I can not inject sql?

Body: You forgot ";" before $username


来源: stackexchange

问:
How to add checkbox to my recyclerviewer xml?
I created Recyclerviewer inside the fragment. Viewer consists of 2 textviews - vertical and I have underline divider under those textviews. How can I add checkbox which will be right of my first textview, but keep second textview as a same group so I don't get 2 underline dividers? More details on this image:

item_tab1 xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">
    <TextView
        android:id="@+id/Item1Name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Ïtem 1"
        android:textSize="30dp"
        android:textStyle="bold"></TextView>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="SubName"
        android:textSize="15dp"
        android:id="@+id/Item1SubName">
    </TextView>
</LinearLayout>
</code>```

答:
You need to wrap your layout in a RelativeLayout like below:</p>

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical">
    <TextView
        android:id="@+id/Item1Name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Ïtem 1"
        android:textSize="30dp"
        android:textStyle="bold"></TextView>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="SubName"
        android:textSize="15dp"
        android:id="@+id/Item1SubName">
    </TextView>
    </LinearLayout>
    <CheckBox
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_marginTop="10dp"
        android:layout_marginEnd="10dp"
        />
</RelativeLayout>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I created Recyclerviewer inside the fragment. Viewer consists of 2 textviews - vertical and I have underline divider under those textviews. How can I add checkbox which will be right of my first textview, but keep second textview as a same group so I don't get 2 underline dividers? More details on this image:

item_tab1 xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">
    <TextView
        android:id="@+id/Item1Name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Ïtem 1"
        android:textSize="30dp"
        android:textStyle="bold"></TextView>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="SubName"
        android:textSize="15dp"
        android:id="@+id/Item1SubName">
    </TextView>
</LinearLayout>

Body:
You need to wrap your layout in a RelativeLayout like below:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical">
    <TextView
        android:id="@+id/Item1Name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Ïtem 1"
        android:textSize="30dp"
        android:textStyle="bold"></TextView>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="SubName"
        android:textSize="15dp"
        android:id="@+id/Item1SubName">
    </TextView>
    </LinearLayout>
    <CheckBox
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_marginTop="10dp"
        android:layout_marginEnd="10dp"
        />
</RelativeLayout>


问:
Amazon Elastic Beanstalk ebextension adds nginx config parameter into default config
I'm deploying my app using a zip file which contains my app jar, docker config file and a .ebextensions folder which includes a nginx/conf.d/custom.config file.

In my custom.config, there is only one line to increase nginx upload file size limit:

```<code>client_max_body_size: 16M
</code>```

But the console displays:

Error processing file (Skipping): '.ebextensions/nginx/conf.d/custom.config' - Contains invalid key: 'client_max_body_size'. For information about valid keys, see http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/ebextensions.html

The guide that I followed to extends the default nginx setting.
Quote:

To extend Elastic Beanstalk's default nginx configuration, add .conf configuration files to a folder named .ebextensions/nginx/conf.d/ in your application source bundle. Elastic Beanstalk's nginx configuration includes .conf files in this folder automatically.

I changed .conf to .config because the first one does not even trigger ELB environment updating during deployment.

答:
I have tried all .ebextensions method of adding implementation level configuration and it didn't help me in the latest Amazon Linux AMI. for the latest Amazon Linux AMI, You need to follow this structure to increase the upload size. You need to follow this structure to increase the upload size limit.

Add the below folder setup in the root level of your project folder.

Folder structure (.platform/nginx/conf.d/proxy.conf)

```<code>.platform/
         nginx/
              conf.d/
                    proxy.conf
</code>```

Add this line to proxy.conf (Inside .platform/nginx/conf.d/ folder)

```<code>client_max_body_size 50M;
</code>```

commit this file and deploy again using eb deploy.

Body:
I'm deploying my app using a zip file which contains my app jar, docker config file and a .ebextensions folder which includes a nginx/conf.d/custom.config file.

In my custom.config, there is only one line to increase nginx upload file size limit:

client_max_body_size: 16M

But the console displays:

Error processing file (Skipping): '.ebextensions/nginx/conf.d/custom.config' - Contains invalid key: 'client_max_body_size'. For information about valid keys, see http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/ebextensions.html

The guide that I followed to extends the default nginx setting.
Quote:

To extend Elastic Beanstalk's default nginx configuration, add .conf configuration files to a folder named .ebextensions/nginx/conf.d/ in your application source bundle. Elastic Beanstalk's nginx configuration includes .conf files in this folder automatically.

I changed .conf to .config because the first one does not even trigger ELB environment updating during deployment.

Body:
I have tried all .ebextensions method of adding implementation level configuration and it didn't help me in the latest Amazon Linux AMI. for the latest Amazon Linux AMI, You need to follow this structure to increase the upload size. You need to follow this structure to increase the upload size limit.

Add the below folder setup in the root level of your project folder.

Folder structure (.platform/nginx/conf.d/proxy.conf)

.platform/
         nginx/
              conf.d/
                    proxy.conf

Add this line to proxy.conf (Inside .platform/nginx/conf.d/ folder)

client_max_body_size 50M;

commit this file and deploy again using eb deploy.


问:
How to graph nodes on a grid in networkx
Just started learning Network Science and I'm a novice in Python so I've been having a hard time figuring this out even after reading a good bit of the networkx documentation. I need to compare the distance between all the nodes and generate an edge in the event the distance is less than d.

1) How to I compare node 1 to nodes (2...99) and then compare node 2 to nodes (3...99), etc. If there's a better way to do it than O(n^2) please show me.

2) How can I use the x,y coordinates stored in node_loc{} to graph each node to a coordinate plane?

```<code>import random, math
import matplotlib.pyplot as plt
import numpy as np
import networkx as nx
import pylab

# Calc distance given (x1,x2,y1,y2)
def distance(x1,x2,y1,y2):
    return math.sqrt(((x2-x1)**2)+((y2-y1)**2))

# Generate coordinate value
def coord_val():
    # node needs x and y coordinates (floats) from 0->100
    return random.uniform(0.0,100.0)

def main():
    # The distance that applies to link generation
    d = 20

    # Make a graph and name it
    g = nx.Graph(name = "100x100 Field Random Network")

    # Generate 100 nodes
    for num in range(0,100):

        # generate a dict with the node's location
        node_loc = {'x': coord_val(), 'y': coord_val()}

        # Add node with x,y dict
        g.add_node(num,node_loc)

    # Check node n against node n+1
    for n,d in g.nodes(data=True):
        if n == 99:
            break

        # I don't think this loop is correct
        for rl in g.nodes(data=True):
            # Don't go out of bounds on the loop
            if n == 99:
                break

            # grab coordinates from nodes
            y1=g.node[n]['y']
            x1=g.node[n]['x']
            y2=g.node[n+1]['y']
            x2=g.node[n+1]['x']

            # Check the distance, if < d, generate edge
            if distance(x1,x2,y1,y2) < d:
                # add edge
                g.add_edge(n,n+1)

    # plot
    # draw_random draws it on a plane, but randomly :(
    nx.draw_random(g,node_size=50)

    plt.show()

if __name__ == '__main__':
    main()
</code>```

答:
NetworkX has nx.grid_2d_graph, a Graph generator, that returns the 2d grid graph of mxn nodes, each being connected to its nearest neighbors. By default its labels will be the coordinates of the grid.

If we were interested in having the nodes as coordinates, we could rotate the positions so the origin is at the top left corner. Otherwise you can just leave it as is. Here's an example:

```<code>import networkx as nx
from matplotlib import pyplot as plt

G = nx.grid_2d_graph(3,3)

plt.figure(figsize=(6,6))
pos = {(x,y):(y,-x) for x,y in G.nodes()}
nx.draw(G, pos=pos,
        node_color='lightgreen',
        with_labels=True,
        node_size=600)
</code>```

Note that nx.grid_2d_graph will generate grid graphs with up to an arbitrarily large m and n, an by positioning the labels you can also plot the grid of coordinates just as above:

ContentLicense: CC BY-SA 3.0

Body:
Just started learning Network Science and I'm a novice in Python so I've been having a hard time figuring this out even after reading a good bit of the networkx documentation. I need to compare the distance between all the nodes and generate an edge in the event the distance is less than d.

1) How to I compare node 1 to nodes (2...99) and then compare node 2 to nodes (3...99), etc. If there's a better way to do it than O(n^2) please show me.

2) How can I use the x,y coordinates stored in node_loc{} to graph each node to a coordinate plane?

import random, math
import matplotlib.pyplot as plt
import numpy as np
import networkx as nx
import pylab

# Calc distance given (x1,x2,y1,y2)
def distance(x1,x2,y1,y2):
    return math.sqrt(((x2-x1)**2)+((y2-y1)**2))

# Generate coordinate value
def coord_val():
    # node needs x and y coordinates (floats) from 0->100
    return random.uniform(0.0,100.0)

def main():
    # The distance that applies to link generation
    d = 20

    # Make a graph and name it
    g = nx.Graph(name = "100x100 Field Random Network")

    # Generate 100 nodes
    for num in range(0,100):

        # generate a dict with the node's location
        node_loc = {'x': coord_val(), 'y': coord_val()}

        # Add node with x,y dict
        g.add_node(num,node_loc)

    # Check node n against node n+1
    for n,d in g.nodes(data=True):
        if n == 99:
            break

        # I don't think this loop is correct
        for rl in g.nodes(data=True):
            # Don't go out of bounds on the loop
            if n == 99:
                break

            # grab coordinates from nodes
            y1=g.node[n]['y']
            x1=g.node[n]['x']
            y2=g.node[n+1]['y']
            x2=g.node[n+1]['x']

            # Check the distance, if < d, generate edge
            if distance(x1,x2,y1,y2) < d:
                # add edge
                g.add_edge(n,n+1)

    # plot
    # draw_random draws it on a plane, but randomly :(
    nx.draw_random(g,node_size=50)

    plt.show()

if __name__ == '__main__':
    main()

Body:
NetworkX has nx.grid_2d_graph, a Graph generator, that returns the 2d grid graph of mxn nodes, each being connected to its nearest neighbors. By default its labels will be the coordinates of the grid.

If we were interested in having the nodes as coordinates, we could rotate the positions so the origin is at the top left corner. Otherwise you can just leave it as is. Here's an example:

import networkx as nx
from matplotlib import pyplot as plt

G = nx.grid_2d_graph(3,3)

plt.figure(figsize=(6,6))
pos = {(x,y):(y,-x) for x,y in G.nodes()}
nx.draw(G, pos=pos,
        node_color='lightgreen',
        with_labels=True,
        node_size=600)

Note that nx.grid_2d_graph will generate grid graphs with up to an arbitrarily large m and n, an by positioning the labels you can also plot the grid of coordinates just as above:


问:
Is there a way to run a linter on a React project every time the code is saved?
Rather simple question really.

I come from a background of VueJS, where this is all setup for the user automatically. I'd like my linter (tslint, if that matters) to just run automatically when any file is saved in the project, but all the resources I've found stop at adding a command to the package.json file. Having a separate command for the linter is great and all, but I want those lint warnings to come up in the terminal while the dev server is running.

Edit: Not a duplicate of "How do I get tslint to watch for changes in a specific folder?" as that does not address what I'm looking to do. I can see that I can have a file watcher run separately from the server, but I do not want that. I'd like running the server to start the linter.

答:
Maybe is little too late for the answer but since some CRA version you can extend "standard" eslint configuration with EXTEND_ESLINT environment variable. You can read about it in official docs and in this tutorial.

Linter configured this way is running with dev server.


问:
MJPEG Stream from iPhone to Server
I am writing an app to make an MJPEG-Stream from the iPhone to the Server.
My problem is that the JPEG's I see are a weird collection of colored lines.
I can post the specific code if more information is needed.

These are the Steps:

Get the frames via AVCaptureVideoDataOutput

Convert them to an UIImage

Get NSData UIImageJPEGRepresentation() from it

Make an NSMutableData and wrap the Image with "Content-Type: image/jpeg" and --BOUNDARY

Now i want to send them as UDP Packets to my server. I use asyncudpsocket on the iPhone and a small java datagrammserver on the PC.The first problem is the mtu. Asyncudpsocket says message too long if the nsdata is larger than 9kb.
Therefore:

Split the image into 9kb chunks

Send them with asyncudp socket

Accept an TCP Socket on port 2020 on the PC

Receive the DatagrammPackets and stream them to the connected TCP Socket

Open Firefox with localhost:2020 and watch the MJPEG

I've tested each part seperated and can tell that they're okay. I can show the images in a UIImageView, I can send, receive and show the bytes from the socket and I can stream JPEG's over a serversocket and watch them in Firefox.

The image fits in one datagrammpacket if they're small enough (that's sometimes the case),
and I can see the header, bytes and the boundary.. but why is my MJPEG stream still showing me a weird colored image (instead of a black or white image, which should be the case)?

答:
I'm finally finished with this app.

My problem was that I converted the DatagrammPacket.getBytes() first to a String and wrote it rather than with writeBytes().
Now I'm writing the bytes directly with the OutputStream.

Title: MJPEG Stream from iPhone to Server


问:
Unable to display parent table with child table in a for loop with template tagging in Django
I want to display an unordered list of NBA teams from my teams table database. Within each team, I want an ordered list of players on that team. So basically I want to produce a list of all objects from my parent table and for each object from the parent table I want a list of all objects from the child table related the parent table. I understand that the problem is methods are not allowed in template tagging, so 'team.players_set.all()' would not be allowed. How else can I get the results that I want?</p>

```<code>class Teams(models.Model):
    name = models.CharField(max_length=20, unique=True)
    num_of_plyrs = models.IntegerField()

    def __str__(self):
        return f"{self.name} have {self.num_of_plyrs} players."

    class Meta:
        verbose_name_plural = "Teams"

class Players(models.Model):
    name = models.CharField(max_length=20)
    team = models.ForeignKey(Teams, on_delete=models.CASCADE)

    def __str__(self):
        return f"{self.name} plays for {self.team}"

    class Meta:
        verbose_name_plural = 'Players'
__________________________________________________________________________________

def teams(request):
teams = Teams.objects.all()
context = {'teams': teams}
return render(request, 'one_app/teams.html', context)
__________________________________________________________________________________

<h3>NBA Teams</h3>
<ul>
  {% for team in teams %}
    <li>
  <p>Team: {{ team.name }}</p>
  <p>Number of players: {{ team.num_of_plyrs }}</p>
  <ol>
  {% for plyr in team.players_set.all() %}
    <li>{{ plyr.name }}</li>
  {% endfor %}
  </ol>
</li>
  {% empty %}
    <li>There are no teams listed.</li>
  {% endfor %}
</ul>
</code>```

答:
```<code>  {% for player in team.players_set.all %}
</code>```

table name should be singular

you can set related_name and use players instead players_set

```<code>team = models.ForeignKey(Teams, related_name='players',on_delete=models.CASCADE)
</code>```

make use of select_related

Body:
I want to display an unordered list of NBA teams from my teams table database. Within each team, I want an ordered list of players on that team. So basically I want to produce a list of all objects from my parent table and for each object from the parent table I want a list of all objects from the child table related the parent table. I understand that the problem is methods are not allowed in template tagging, so 'team.players_set.all()' would not be allowed. How else can I get the results that I want?

class Teams(models.Model):
    name = models.CharField(max_length=20, unique=True)
    num_of_plyrs = models.IntegerField()

    def __str__(self):
        return f"{self.name} have {self.num_of_plyrs} players."

    class Meta:
        verbose_name_plural = "Teams"

class Players(models.Model):
    name = models.CharField(max_length=20)
    team = models.ForeignKey(Teams, on_delete=models.CASCADE)

    def __str__(self):
        return f"{self.name} plays for {self.team}"

    class Meta:
        verbose_name_plural = 'Players'
__________________________________________________________________________________

def teams(request):
teams = Teams.objects.all()
context = {'teams': teams}
return render(request, 'one_app/teams.html', context)
__________________________________________________________________________________

NBA Teams

  {% for team in teams %}

Team: {{ team.name }}

Number of players: {{ team.num_of_plyrs }}

  {% for plyr in team.players_set.all() %}

{{ plyr.name }}

  {% endfor %}

  {% empty %}

There are no teams listed.

  {% endfor %}

Body:
  {% for player in team.players_set.all %}

table name should be singular

you can set related_name and use players instead players_set

team = models.ForeignKey(Teams, related_name='players',on_delete=models.CASCADE)

make use of select_related


问:
Minimum cart amount for specific product categories in WooCommerce
In WooCommerce I use an OUTLET category with on sale products and I would like to set a minimum subtotal (30 €) for customers purchasing any "Outlet" product.

I tried to hook into woocommerce_after_calculate_totals to:

check cart items for a specific product category

display a notice when a specific product category is found and the order is lower than  30 €

and eventually redirect to cart page when user tries to checkout with an order lower than 30 €.

Here is my code:

add_action( 'woocommerce_after_calculate_totals', 'check_order_outlet_items', 10, 0 );

function check_order_outlet_items() {

    global $woocommerce;

    if (is_cart() || is_checkout()) {

        // Check if cart contains items in Outlet cat.

        $items = $woocommerce->cart->get_cart();

        foreach($items as $item => $values) {

            $product_id = $values['product_id'];

            $terms = get_the_terms( $product_id, 'product_cat' );

            foreach ($terms as $term) {
                if ($term->name == "OUTLET") {
                    $outlet_found = 1;
                    break;
                }
            }
            if ($outlet_found) {break;}

        }

        if ($outlet_found) {

            // Calculate order amount including discount

            $cart_subtotal = $woocommerce->cart->subtotal;
            $discount_excl_tax_total = $woocommerce->cart->get_cart_discount_total();
            $discount_tax_total = $woocommerce->cart->get_cart_discount_tax_total();
            $discount_total = $discount_excl_tax_total + $discount_tax_total;
            $order_net_amount = $cart_subtotal - $discount_total;

            // Check if condition met

            if ($order_net_amount < 30) {

                if (is_checkout()) {

                    wp_redirect(WC()->cart->get_cart_url());
                    exit();

                } else {

                    wc_add_notice( __( 'You must order at least 30 €', 'error' ) );

                }
            }
        }
    }
}
```

This code works perfectly in the cart page (displaying notice if cart's amount < 30 even if carts amount goes below 30 after adding a coupon) and redirecting to cart if users wants to go to checkout.

But If I go to checkout page with an amount >= 30 and then add a coupon (to lower cart amount below 30), then the Ajax recalculating totals loops and the page is blocked. But then if I reload the checkout page I'm correctly redirected to cart page.

答:
The right hook to be used in this case is woocommerce_check_cart_items this way:

```<code>add_action( 'woocommerce_check_cart_items', 'check_cart_outlet_items' );
function check_cart_outlet_items() {
    $categories = array('OUTLET'); // Defined targeted product categories
    $threshold  = 30; // Defined threshold amount

    $cart       = WC()->cart;
    $cart_items = $cart->get_cart();
    $subtotal   = $cart->subtotal;
    $subtotal  -= $cart->get_cart_discount_total() + $cart->get_cart_discount_tax_total();
    $found      = false;

    foreach( $cart_items as $cart_item_key => $cart_item ) {
        // Check for specific product categories
        if ( has_term( $categories, 'product_cat', $cart_item['product_id'] ) ) {
            $found = true; // A category is found
            break; // Stop the loop
        }
    }

    if ( $found && $subtotal < $threshold ) {
        // Display an error notice (and avoid checkout)
        wc_add_notice( sprintf( __( "You must order at least %s" ), wc_price($threshold) ), 'error' );
    }
}
</code>```

Code goes in functions.php file of your active child theme (or active theme). Tested and works.

Body:
In WooCommerce I use an OUTLET category with on sale products and I would like to set a minimum subtotal (30 €) for customers purchasing any "Outlet" product.

I tried to hook into woocommerce_after_calculate_totals to:

check cart items for a specific product category

display a notice when a specific product category is found and the order is lower than  30 €

and eventually redirect to cart page when user tries to checkout with an order lower than 30 €.

Here is my code:

add_action( 'woocommerce_after_calculate_totals', 'check_order_outlet_items', 10, 0 );

function check_order_outlet_items() {

    global $woocommerce;

    if (is_cart() || is_checkout()) {

        // Check if cart contains items in Outlet cat.

        $items = $woocommerce->cart->get_cart();

        foreach($items as $item => $values) {

            $product_id = $values['product_id'];

            $terms = get_the_terms( $product_id, 'product_cat' );

            foreach ($terms as $term) {
                if ($term->name == "OUTLET") {
                    $outlet_found = 1;
                    break;
                }
            }
            if ($outlet_found) {break;}

        }

        if ($outlet_found) {

            // Calculate order amount including discount

            $cart_subtotal = $woocommerce->cart->subtotal;
            $discount_excl_tax_total = $woocommerce->cart->get_cart_discount_total();
            $discount_tax_total = $woocommerce->cart->get_cart_discount_tax_total();
            $discount_total = $discount_excl_tax_total + $discount_tax_total;
            $order_net_amount = $cart_subtotal - $discount_total;

            // Check if condition met

            if ($order_net_amount < 30) {

                if (is_checkout()) {

                    wp_redirect(WC()->cart->get_cart_url());
                    exit();

                } else {

                    wc_add_notice( __( 'You must order at least 30 €', 'error' ) );

                }
            }
        }
    }
}

This code works perfectly in the cart page (displaying notice if cart's amount < 30 even if carts amount goes below 30 after adding a coupon) and redirecting to cart if users wants to go to checkout.

But If I go to checkout page with an amount >= 30 and then add a coupon (to lower cart amount below 30), then the Ajax recalculating totals loops and the page is blocked. But then if I reload the checkout page I'm correctly redirected to cart page.

Body:
The right hook to be used in this case is woocommerce_check_cart_items this way:

add_action( 'woocommerce_check_cart_items', 'check_cart_outlet_items' );
function check_cart_outlet_items() {
    $categories = array('OUTLET'); // Defined targeted product categories
    $threshold  = 30; // Defined threshold amount

    $cart       = WC()->cart;
    $cart_items = $cart->get_cart();
    $subtotal   = $cart->subtotal;
    $subtotal  -= $cart->get_cart_discount_total() + $cart->get_cart_discount_tax_total();
    $found      = false;

    foreach( $cart_items as $cart_item_key => $cart_item ) {
        // Check for specific product categories
        if ( has_term( $categories, 'product_cat', $cart_item['product_id'] ) ) {
            $found = true; // A category is found
            break; // Stop the loop
        }
    }

    if ( $found && $subtotal < $threshold ) {
        // Display an error notice (and avoid checkout)
        wc_add_notice( sprintf( __( "You must order at least %s" ), wc_price($threshold) ), 'error' );
    }
}

Code goes in functions.php file of your active child theme (or active theme). Tested and works.


问:
Bash Script Efficiency / Logic
I have a very specific script I wrote about two years ago.  It runs fantastically and has never failed ...  However the more websites we put into the system the script gets slower and slower (as expected) ... The cron that runs the script every 10 mins now takes about 3 minutes to complete.  I am looking to reduce that time.  So let me explain what the script does.

1) Here is the MAIN LOOP -- It checks the database for all websites for paying customers:

```<code>mysql --login-path=main-data -e "SELECT user_file FROM database" | while read user_file; do
</code>```

2) Inside the main loop I build the individual conf files :

```<code>p=$user_file
echo "<VirtualHost *:80>" > /etc/apache2/sites-available/$p.conf
.........
</code>```

3) Still inside the main loop, I check to see if they have extra domains and create their aliases :

```<code>mysql --login-path=main-data -e "SELECT domain
    FROM database
    WHERE user_file = '$user_file';" | while read domain; do
        echo "  ServerAlias $domain" >> /etc/apache2/sites-available/$p.conf
        echo "  ServerAlias www.$domain" >> /etc/apache2/sites-available/$p.conf
    done
</code>```

4) Still inside the main loop -- I check for SSL and create that part of the conf file.  NOTE that there's some openssl config tests here that may slow things down:

```<code>mysql --login-path=main-data --skip-column-names -e"SELECT ssl FROM database
    WHERE user_file = '$user_file'
    AND a.primary_domain = '1'
    AND b.https = '1'" | while read ssl; do

    if [ $ssl = 1 ]
    then
        ########################### START SSL TEST
        crt="/var/www/liveSites/websites/$user_file/ssl/$domain.crt"
        key="/var/www/liveSites/websites/$user_file/ssl/$domain.key"

       key_test=$(openssl x509 -in $crt -pubkey -noout -outform pem | sha256sum 2>&1)
       crt_test=$(openssl pkey -in $key -pubout -outform pem | sha256sum 2>&1)

       if [ "$key_test" = "$crt_test" ]
       then
           echo "\n - Matched -- Cert Good - \n";
       else
           echo "SSL match failed for $user_file -> $domain" > /etc/apache2/websitesCron/ssl_fail.txt
           cat /etc/apache2/websitesCron/ssl_fail.txt | mail -s "SSL INSTALLATION ERROR" it@mycompany.com
        fi
        ####################### END SSL TEST

       echo "<VirtualHost *:443>
             ServerName    $domain
             ServerAlias   www.$domain
             DocumentRoot /var/www/liveSites/websites/$user_file/public_html
             ........
    fi
done
</code>```

5) Finally, still inside main loop I check to see if the site is enabled, if not enable it

```<code>if test -f "/etc/apache2/sites-enabled/$p.conf"; then
    echo "Configuration exists \n"
else
    A2ENSITE=/usr/sbin/a2ensite
    ${A2ENSITE} $p.conf
fi
</code>```

After the main loop -- I check the Apache config, to make sure it will reload gracefully and I check that ssl didn't fail the openssl comparison check:

```<code>/usr/sbin/apachectl configtest > /etc/apache2/websitesCron/configtest 2>&1

if grep "failed" /etc/apache2/websitesCron/configtest
then
    # Do failed stuff stop script and turn cron off
elif grep "failed" /etc/apache2/websitesCron/ssl_fail.txt
then
    # Do failed SSL stuff stop script and turn cron off
else
    # gracefully reload Apache
    /etc/init.d/apache2 reload
fi
</code>```

It's a pretty simple script, but there's a few moving parts -- For 1,000+ websites, does it seem like 3 mins for it to run is reasonable?  Should I fork?  Is there logic changes that could "clean it up"?

答:
Avoid long tests you have done before. You can look for different ways, something like</p>

```<code>sha_dir=/var/shadir
crt="/var/www/liveSites/websites/$user_file/ssl/$domain.crt"
key="/var/www/liveSites/websites/$user_file/ssl/$domain.key"
sha_crt="${sha_dir}/${user_file}_${domain}.crt"
sha_key="${sha_dir}/${user_file}_${domain}.key"
if [[ "${crt}" -nt "${sha_crt}" ]]; then
   crt_test=$(openssl pkey -in $key -pubout -outform pem | sha256sum 2>&1 | tee "${sha_crt}")
else
   crt_test=$(cat ${sha_crt})
fi
if [[ "${key}" -nt "${sha_key}" ]]; then
   key_test=$(openssl x509 -in $crt -pubkey -noout -outform pem | sha256sum 2>&1 | tee "${sha_key}")
else
   key_test=$(cat ${sha_key})
fi
</code>```

Title: Bash Script Efficiency / Logic

Body:
I have a very specific script I wrote about two years ago.  It runs fantastically and has never failed ...  However the more websites we put into the system the script gets slower and slower (as expected) ... The cron that runs the script every 10 mins now takes about 3 minutes to complete.  I am looking to reduce that time.  So let me explain what the script does.

1) Here is the MAIN LOOP -- It checks the database for all websites for paying customers:

mysql --login-path=main-data -e "SELECT user_file FROM database" | while read user_file; do

2) Inside the main loop I build the individual conf files :

p=$user_file
echo "<VirtualHost *:80>" > /etc/apache2/sites-available/$p.conf
.........

3) Still inside the main loop, I check to see if they have extra domains and create their aliases :

mysql --login-path=main-data -e "SELECT domain
    FROM database
    WHERE user_file = '$user_file';" | while read domain; do
        echo "  ServerAlias $domain" >> /etc/apache2/sites-available/$p.conf
        echo "  ServerAlias www.$domain" >> /etc/apache2/sites-available/$p.conf
    done

4) Still inside the main loop -- I check for SSL and create that part of the conf file.  NOTE that there's some openssl config tests here that may slow things down:

mysql --login-path=main-data --skip-column-names -e"SELECT ssl FROM database
    WHERE user_file = '$user_file'
    AND a.primary_domain = '1'
    AND b.https = '1'" | while read ssl; do

    if [ $ssl = 1 ]
    then
        ########################### START SSL TEST
        crt="/var/www/liveSites/websites/$user_file/ssl/$domain.crt"
        key="/var/www/liveSites/websites/$user_file/ssl/$domain.key"

       key_test=$(openssl x509 -in $crt -pubkey -noout -outform pem | sha256sum 2>&1)
       crt_test=$(openssl pkey -in $key -pubout -outform pem | sha256sum 2>&1)

       if [ "$key_test" = "$crt_test" ]
       then
           echo "\n - Matched -- Cert Good - \n";
       else
           echo "SSL match failed for $user_file -> $domain" > /etc/apache2/websitesCron/ssl_fail.txt
           cat /etc/apache2/websitesCron/ssl_fail.txt | mail -s "SSL INSTALLATION ERROR" it@mycompany.com
        fi
        ####################### END SSL TEST

       echo "<VirtualHost *:443>
             ServerName    $domain
             ServerAlias   www.$domain
             DocumentRoot /var/www/liveSites/websites/$user_file/public_html
             ........
    fi
done

5) Finally, still inside main loop I check to see if the site is enabled, if not enable it

if test -f "/etc/apache2/sites-enabled/$p.conf"; then
    echo "Configuration exists \n"
else
    A2ENSITE=/usr/sbin/a2ensite
    ${A2ENSITE} $p.conf
fi

After the main loop -- I check the Apache config, to make sure it will reload gracefully and I check that ssl didn't fail the openssl comparison check:

/usr/sbin/apachectl configtest > /etc/apache2/websitesCron/configtest 2>&1

if grep "failed" /etc/apache2/websitesCron/configtest
then
    # Do failed stuff stop script and turn cron off
elif grep "failed" /etc/apache2/websitesCron/ssl_fail.txt
then
    # Do failed SSL stuff stop script and turn cron off
else
    # gracefully reload Apache
    /etc/init.d/apache2 reload
fi

It's a pretty simple script, but there's a few moving parts -- For 1,000+ websites, does it seem like 3 mins for it to run is reasonable?  Should I fork?  Is there logic changes that could "clean it up"?

Body:
Avoid long tests you have done before. You can look for different ways, something like

sha_dir=/var/shadir
crt="/var/www/liveSites/websites/$user_file/ssl/$domain.crt"
key="/var/www/liveSites/websites/$user_file/ssl/$domain.key"
sha_crt="${sha_dir}/${user_file}_${domain}.crt"
sha_key="${sha_dir}/${user_file}_${domain}.key"
if [[ "${crt}" -nt "${sha_crt}" ]]; then
   crt_test=$(openssl pkey -in $key -pubout -outform pem | sha256sum 2>&1 | tee "${sha_crt}")
else
   crt_test=$(cat ${sha_crt})
fi
if [[ "${key}" -nt "${sha_key}" ]]; then
   key_test=$(openssl x509 -in $crt -pubkey -noout -outform pem | sha256sum 2>&1 | tee "${sha_key}")
else
   key_test=$(cat ${sha_key})
fi


问:
How to get the error message in Controller or Route after handling exception in errorHandler?
I had to customized Sftp Inbound default handler LoggingHandler and using my own CustomizedErrorHandler which extends ErrorHandler. But I can't return any message to my controller after handling exceptions.

I was researching couple of days and I found nothing to show my customized message to my UI using Controller. Below are some code snippet from my CustomizedErrorHandler, SftpInboundConfiguration.

SftpInboundConfiguration

```<code>public IntegrationFlow fileFlow() {
    SftpInboundChannelAdapterSpec spec = Sftp
            .inboundAdapter(getSftpSessionFactory())
            .preserveTimestamp(true)
            .remoteDirectory(getSourceLocation())
            .autoCreateLocalDirectory(true)
            .deleteRemoteFiles(false)
            .localDirectory(new File(getDestinationLocation()));

    return IntegrationFlows
            .from(spec, e -> e.id(BEAN_ID)
                    .autoStartup(false)
                    .poller(sftpPoller())
            )
            .channel(sftpReceiverChannel())
            .handle(sftpInboundMessageHandler())
            .get();
}
</code>```

... ... ...

```<code>public PollerMetadata sftpPoller() {
        PollerMetadata pollerMetadata = new PollerMetadata();
        List<Advice> adviceChain = new ArrayList<>();
        pollerMetadata.setErrorHandler(customErrorMessageHandler());
        pollerMetadata.setTrigger(new PeriodicTrigger(5000));
        return pollerMetadata;
}
</code>```

... ... ...

```<code>private CustomErrorMessageHandler customErrorMessageHandler() {
        return new CustomErrorMessageHandler(
                controlChannel(),
                BEAN_ID
        );
}
</code>```

CustomErrorMessageHandler

```<code>public class CustomErrorMessageHandler implements ErrorHandler {
    private final MessageChannel CONTROL_CHANNEL;
    private final String BEAN_ID;

    public CustomErrorMessageHandler(
                  MessageChannel controlChannel,
                  String beanID
    ) {
        this.CONTROL_CHANNEL = controlChannel;
        this.BEAN_ID = beanID;
    }

    public void handleError(@NotNull Throwable throwable) {
        final Throwable rootCause = ExceptionUtils.getRootCause(throwable);
        if (rootCause instanceof MessagingException) {
            log.error("MessagingException : {} ", rootCause.getMessage());
        } else if (rootCause instanceof SftpException) {
            log.error("SftpException : {}", rootCause.getMessage());
        }   ... ... ...
        else {
            log.error("Unknown : Cause : {} , Error : {}",
                                 rootCause, rootCause.getMessage());
        }

        log.info("Stopping SFTP Inbound");
        boolean is_stopped = CONTROL_CHANNEL.send(
                 new GenericMessage<>("@" + BEAN_ID + ".stop()"));
        if (is_stopped) {
            log.info("SFTP Inbound Stopped.");
        } else {
            log.info("SFTP Inbound Stop Failed.");
        }
    }
}
</code>```

Now I want to save some customized message from if-else statements and need to show it in UI. Is there any way to save the message and show it using Route or Controller ?

答:
Don't customize the error handler, use poller.errorChannel("myErrorChannel") instead.

Then add an error channel flow

@Bean
IntegrationFlow errors() {
    return IntegrationFLows.from("myErrorChannel")
        .handle(...)
        ...
        .get();
```

The message sent to the handler is an ErrorMessage with a MessagingException payload, with cause and failedMessage which was the message at the point of the failure and originalMessage which is the original message emitted by the adapter.

After handling the exception, you can simply call a method on your controller to tell it the state.

Body:
I had to customized Sftp Inbound default handler LoggingHandler and using my own CustomizedErrorHandler which extends ErrorHandler. But I can't return any message to my controller after handling exceptions.

I was researching couple of days and I found nothing to show my customized message to my UI using Controller. Below are some code snippet from my CustomizedErrorHandler, SftpInboundConfiguration.

SftpInboundConfiguration

public IntegrationFlow fileFlow() {
    SftpInboundChannelAdapterSpec spec = Sftp
            .inboundAdapter(getSftpSessionFactory())
            .preserveTimestamp(true)
            .remoteDirectory(getSourceLocation())
            .autoCreateLocalDirectory(true)
            .deleteRemoteFiles(false)
            .localDirectory(new File(getDestinationLocation()));

    return IntegrationFlows
            .from(spec, e -> e.id(BEAN_ID)
                    .autoStartup(false)
                    .poller(sftpPoller())
            )
            .channel(sftpReceiverChannel())
            .handle(sftpInboundMessageHandler())
            .get();
}

... ... ...

public PollerMetadata sftpPoller() {
        PollerMetadata pollerMetadata = new PollerMetadata();
        List<Advice> adviceChain = new ArrayList<>();
        pollerMetadata.setErrorHandler(customErrorMessageHandler());
        pollerMetadata.setTrigger(new PeriodicTrigger(5000));
        return pollerMetadata;
}

... ... ...

private CustomErrorMessageHandler customErrorMessageHandler() {
        return new CustomErrorMessageHandler(
                controlChannel(),
                BEAN_ID
        );
}

CustomErrorMessageHandler

public class CustomErrorMessageHandler implements ErrorHandler {
    private final MessageChannel CONTROL_CHANNEL;
    private final String BEAN_ID;

    public CustomErrorMessageHandler(
                  MessageChannel controlChannel,
                  String beanID
    ) {
        this.CONTROL_CHANNEL = controlChannel;
        this.BEAN_ID = beanID;
    }

    public void handleError(@NotNull Throwable throwable) {
        final Throwable rootCause = ExceptionUtils.getRootCause(throwable);
        if (rootCause instanceof MessagingException) {
            log.error("MessagingException : {} ", rootCause.getMessage());
        } else if (rootCause instanceof SftpException) {
            log.error("SftpException : {}", rootCause.getMessage());
        }   ... ... ...
        else {
            log.error("Unknown : Cause : {} , Error : {}",
                                 rootCause, rootCause.getMessage());
        }

        log.info("Stopping SFTP Inbound");
        boolean is_stopped = CONTROL_CHANNEL.send(
                 new GenericMessage<>("@" + BEAN_ID + ".stop()"));
        if (is_stopped) {
            log.info("SFTP Inbound Stopped.");
        } else {
            log.info("SFTP Inbound Stop Failed.");
        }
    }
}

Now I want to save some customized message from if-else statements and need to show it in UI. Is there any way to save the message and show it using Route or Controller ?

Body:
Don't customize the error handler, use poller.errorChannel("myErrorChannel") instead.

Then add an error channel flow

@Bean
IntegrationFlow errors() {
    return IntegrationFLows.from("myErrorChannel")
        .handle(...)
        ...
        .get();

The message sent to the handler is an ErrorMessage with a MessagingException payload, with cause and failedMessage which was the message at the point of the failure and originalMessage which is the original message emitted by the adapter.

After handling the exception, you can simply call a method on your controller to tell it the state.


问:
Cannot choose from an empty sequence Locust Error
I am attempting to run a Locust file and am repeatedly facing the following error:

```<code>    Traceback (most recent call last):
  File "/Applications/anaconda/lib/python3.6/site-packages/locust/user/task.py", line 280, in run
    self.schedule_task(self.get_next_task())
  File "/Applications/anaconda/lib/python3.6/site-packages/locust/user/task.py", line 408, in get_next_task
    return random.choice(self.user.tasks)
  File "/Applications/anaconda/lib/python3.6/random.py", line 260, in choice
    raise IndexError('Cannot choose from an empty sequence') from None
IndexError: Cannot choose from an empty sequence

</code>```

My locust file looks like this:

```<code>import base64

from locust import HttpUser, TaskSet, task
from random import randint, choice

class WebTasks(TaskSet):

    @task
    def load(self):
        base64string = base64.encodebytes(('%s:%s' % ('user', 'password')).encode()).decode().replace('\n', '')

        catalogue = self.client.get("/catalogue").json()
        category_item = choice(catalogue)
        item_id = category_item["id"]

        self.client.get("/")
        self.client.get("/login", headers={"Authorization":"Basic %s" % base64string})
        self.client.get("/category.html")
        self.client.get("/detail.html?id={}".format(item_id))
        self.client.delete("/cart")
        self.client.post("/cart", json={"id": item_id, "quantity": 1})
        self.client.get("/basket.html")
        self.client.post("/orders")

class Web(HttpUser):
    task_set = WebTasks
    min_wait = 0
    max_wait = 0
</code>```

I believe the issue normally arises from not having any tasks defined, but I do have a task defined here so I am not sure why I would be getting this error. I am running on Python 3.6.8 and Locust 1.0.2 on Mac OS.

答:
The error message is for one of these lines:

```<code>category_item = choice(catalogue)
# or
item_id = choice(self.client.get("/catalogue").json())["id"]
</code>```

So the call to catalogue = self.client.get("/catalogue").json() returned an empty list/iterable. Both the "catalogue get" are the same call.

This section doesn't make sense:

```<code>catalogue = self.client.get("/catalogue").json()  # 1A
print(catalogue)
category_item = choice(catalogue)                 # 1B
item_id = category_item["id"]

item_id = choice(self.client.get("/catalogue").json())["id"]  #2
</code>```

You get the catalogue in '1A' and then make a random choice in '1B', which is then ignored/unused, and then you get the same catalogue again and make a random choice in '#2', but this time you select the item's "id". Just skip to the 2nd one.

And you've not created task_set correctly:

```<code>class Web(HttpUser):
    task_set = WebTasks  # is just a reference to the WebTasks class
</code>```

Should be:

```<code>class Web(HttpUser):
    task_set = WebTasks()  # to *create an object* of the WebTasks class
</code>```

Body:
I am attempting to run a Locust file and am repeatedly facing the following error:

    Traceback (most recent call last):
  File "/Applications/anaconda/lib/python3.6/site-packages/locust/user/task.py", line 280, in run
    self.schedule_task(self.get_next_task())
  File "/Applications/anaconda/lib/python3.6/site-packages/locust/user/task.py", line 408, in get_next_task
    return random.choice(self.user.tasks)
  File "/Applications/anaconda/lib/python3.6/random.py", line 260, in choice
    raise IndexError('Cannot choose from an empty sequence') from None
IndexError: Cannot choose from an empty sequence

My locust file looks like this:

import base64

from locust import HttpUser, TaskSet, task
from random import randint, choice

class WebTasks(TaskSet):

    @task
    def load(self):
        base64string = base64.encodebytes(('%s:%s' % ('user', 'password')).encode()).decode().replace('\n', '')

        catalogue = self.client.get("/catalogue").json()
        category_item = choice(catalogue)
        item_id = category_item["id"]

        self.client.get("/")
        self.client.get("/login", headers={"Authorization":"Basic %s" % base64string})
        self.client.get("/category.html")
        self.client.get("/detail.html?id={}".format(item_id))
        self.client.delete("/cart")
        self.client.post("/cart", json={"id": item_id, "quantity": 1})
        self.client.get("/basket.html")
        self.client.post("/orders")

class Web(HttpUser):
    task_set = WebTasks
    min_wait = 0
    max_wait = 0

I believe the issue normally arises from not having any tasks defined, but I do have a task defined here so I am not sure why I would be getting this error. I am running on Python 3.6.8 and Locust 1.0.2 on Mac OS.

Body:
The error message is for one of these lines:

category_item = choice(catalogue)
# or
item_id = choice(self.client.get("/catalogue").json())["id"]

So the call to catalogue = self.client.get("/catalogue").json() returned an empty list/iterable. Both the "catalogue get" are the same call.

This section doesn't make sense:

catalogue = self.client.get("/catalogue").json()  # 1A
print(catalogue)
category_item = choice(catalogue)                 # 1B
item_id = category_item["id"]

item_id = choice(self.client.get("/catalogue").json())["id"]  #2

You get the catalogue in '1A' and then make a random choice in '1B', which is then ignored/unused, and then you get the same catalogue again and make a random choice in '#2', but this time you select the item's "id". Just skip to the 2nd one.

And you've not created task_set correctly:

class Web(HttpUser):
    task_set = WebTasks  # is just a reference to the WebTasks class

Should be:

class Web(HttpUser):
    task_set = WebTasks()  # to *create an object* of the WebTasks class


问:
error code 401000 from documentation Translator text 3.0
```<code>curl -X POST "https://api.cognitive.microsofttranslator.com/translate?api-version=3.0&to=zh-Hans" -H "Ocp-Apim-Subscription-Key: 972e6070611c4f8a93baae1b263276ea" -H "Content-Type: application/json; charset=UTF-8" -d "[{'Text':'Hello, what is your name?'}]"
</code>```

i try this code and i have this code error 401000 from the documentation microsoft translator text 3.0

```<code>{"error":{"code":401000,"message":"The request is not authorized because credentials are missing or invalid."}}
</code>```

i don't know why please help

答:
Did you create a Translator Text resource (https://learn.microsoft.com/en-us/azure/cognitive-services/cognitive-services-apis-create-account?tabs=singleservice%2Cwindows) or a multi-service resource (https://learn.microsoft.com/en-us/azure/cognitive-services/cognitive-services-apis-create-account?tabs=multiservice%2Cwindows)?

If you are using the multi-service resource, please ensure you pass in the region header - 'Ocp-Apim-Subscription-Region: YOUR_SUBSCRIPTION_REGION'

Body:
curl -X POST "https://api.cognitive.microsofttranslator.com/translate?api-version=3.0&to=zh-Hans" -H "Ocp-Apim-Subscription-Key: 972e6070611c4f8a93baae1b263276ea" -H "Content-Type: application/json; charset=UTF-8" -d "[{'Text':'Hello, what is your name?'}]"

i try this code and i have this code error 401000 from the documentation microsoft translator text 3.0

{"error":{"code":401000,"message":"The request is not authorized because credentials are missing or invalid."}}

i don't know why please help


问:
Does dplyr 0.8.5 provide `unnest()`?
```<code>> library(dplyr)

Attaching package: ‘dplyr’

The following objects are masked from ‘package:stats’:

    filter, lag

The following objects are masked from ‘package:base’:

    intersect, setdiff, setequal, union

> help(unnest)
No documentation for ‘unnest’ in specified packages and libraries:
you could try ‘??unnest’

> packageVersion("dplyr")
[1] ‘0.8.5’
</code>```

I have installed dplyr and loaded it, but unnest() seems missing. Does dplyr 0.8.5 provide unnest()?  How shall I have access to unnest()?

答:
The unnest function is apart of the tidyr R package.

Install the tidyr package with install.packages("tidyr") and then call the library at the beginning of your code with library(tidyr).

I hope this helps!

Title: Does dplyr 0.8.5 provide `unnest()`?

Body:
> library(dplyr)

Attaching package: ‘dplyr’

The following objects are masked from ‘package:stats’:

    filter, lag

The following objects are masked from ‘package:base’:

    intersect, setdiff, setequal, union

> help(unnest)
No documentation for ‘unnest’ in specified packages and libraries:
you could try ‘??unnest’

> packageVersion("dplyr")
[1] ‘0.8.5’

I have installed dplyr and loaded it, but unnest() seems missing. Does dplyr 0.8.5 provide unnest()?  How shall I have access to unnest()?


问:
Why does aggregate GROUPBY() COUNT(*) of 0's not show up in the query?
This is a problem I'm not sure I've run into before (and frankly didn't know it existed). I am grouping by YEAR and MONTH for monthly time-series analysis but COUNTs of 0's are not showing up in the output. Here is the query:

```<code>SELECT
    ROW_NUMBER() OVER(
        ORDER BY YEAR(order_date), MONTH(order_date)) AS 'Index',
    YEAR(order_date) AS 'Year',
    MONTH(order_date) AS 'Month',
    CONCAT(CASE
                WHEN MONTH(order_date) = 1 THEN 'Jan'
                WHEN MONTH(order_date) = 2 THEN 'Feb'
                WHEN MONTH(order_date) = 3 THEN 'Mar'
                WHEN MONTH(order_date) = 4 THEN 'Apr'
                WHEN MONTH(order_date) = 5 THEN 'May'
                WHEN MONTH(order_date) = 6 THEN 'Jun'
                WHEN MONTH(order_date) = 7 THEN 'Jul'
                WHEN MONTH(order_date) = 8 THEN 'Aug'
                WHEN MONTH(order_date) = 9 THEN 'Sep'
                WHEN MONTH(order_date) = 10 THEN 'Oct'
                WHEN MONTH(order_date) = 11 THEN 'Nov'
                WHEN MONTH(order_date) = 12 THEN 'Dec'
            END,
            ' ',
            YEAR(order_date)) AS 'Timeline',
    COUNT(*) AS 'Pending Cases'
FROM dbo.result_management_report
WHERE final_reported_date IS NULL
AND order_type = 'Commercial'
AND test_name = 'CTC-FISH'
GROUP BY YEAR(order_date), MONTH(order_date)
ORDER BY YEAR(order_date), MONTH(order_date)
</code>```

Here is the output. You can see that where Jan 2020, it is missing instead of the Pending Cases being "0"

I've tried IIF and NULLIF and ISNULL but to no avail. If someone knows a trick to help me here it would be greatly appreciated.

答: Don't use in where final_reported_date IS NULL it will get all the data

Body:
This is a problem I'm not sure I've run into before (and frankly didn't know it existed). I am grouping by YEAR and MONTH for monthly time-series analysis but COUNTs of 0's are not showing up in the output. Here is the query:

SELECT
    ROW_NUMBER() OVER(
        ORDER BY YEAR(order_date), MONTH(order_date)) AS 'Index',
    YEAR(order_date) AS 'Year',
    MONTH(order_date) AS 'Month',
    CONCAT(CASE
                WHEN MONTH(order_date) = 1 THEN 'Jan'
                WHEN MONTH(order_date) = 2 THEN 'Feb'
                WHEN MONTH(order_date) = 3 THEN 'Mar'
                WHEN MONTH(order_date) = 4 THEN 'Apr'
                WHEN MONTH(order_date) = 5 THEN 'May'
                WHEN MONTH(order_date) = 6 THEN 'Jun'
                WHEN MONTH(order_date) = 7 THEN 'Jul'
                WHEN MONTH(order_date) = 8 THEN 'Aug'
                WHEN MONTH(order_date) = 9 THEN 'Sep'
                WHEN MONTH(order_date) = 10 THEN 'Oct'
                WHEN MONTH(order_date) = 11 THEN 'Nov'
                WHEN MONTH(order_date) = 12 THEN 'Dec'
            END,
            ' ',
            YEAR(order_date)) AS 'Timeline',
    COUNT(*) AS 'Pending Cases'
FROM dbo.result_management_report
WHERE final_reported_date IS NULL
AND order_type = 'Commercial'
AND test_name = 'CTC-FISH'
GROUP BY YEAR(order_date), MONTH(order_date)
ORDER BY YEAR(order_date), MONTH(order_date)

Here is the output. You can see that where Jan 2020, it is missing instead of the Pending Cases being "0"

I've tried IIF and NULLIF and ISNULL but to no avail. If someone knows a trick to help me here it would be greatly appreciated.


问:
window.history.pushState function reloads the page when used
i am trying to go from page to page without reloading, i read on other questions that i can use

```<code>    window.history.pushState()
</code>```

to not reload the page, but it is still reloading the page.

i also tried using this function but kept giving me a syntax error

```<code>  function changeurl(url, title) {
   var new_url = '/' + url;
   window.history.pushState('data', 'Title', new_url);
   document.title = title;
    }
</code>```

the syntax error occurs and it reads: "unexpected token ,"

here is an example of my HTML:

```<code> <a class="ac" href=""  onclick="window.history.pushState('data', 'Title', 'index?a=recieved');"></a></td>
        <li>

         <a class="" href="index?b=favorites" onclick=""></a></td>
        </li>
        <li>
           <a class="" href="index?a=sent" onclick=""></a></td>
        </li>
</code>```

what can i do to get my pages not to reload?

答:
Try this href="javascript:void(0)" in tag a

```<code><a class="ac" href="javascript:void(0)"
onclick="window.history.pushState('data', 'Title', 'index?a=recieved');">
Link
</a>
</code>```

Body:
i am trying to go from page to page without reloading, i read on other questions that i can use

    window.history.pushState()

to not reload the page, but it is still reloading the page.

i also tried using this function but kept giving me a syntax error

  function changeurl(url, title) {
   var new_url = '/' + url;
   window.history.pushState('data', 'Title', new_url);
   document.title = title;
    }

the syntax error occurs and it reads: "unexpected token ,"

here is an example of my HTML:

what can i do to get my pages not to reload?

Body:
Try this href="javascript:void(0)" in tag a

<a class="ac" href="javascript:void(0)"
onclick="window.history.pushState('data', 'Title', 'index?a=recieved');">
Link
</a>


问:
Js Audio Volume Slider
I am new to this and I have a question. how can i put a volume slider? Thank you!!
I can't find any code for the moment that works for me, I hope your help

HTML:  id="play-pause-button" class="fa fa-play">

JavaScript:

```<code><script type="text/javascript">
  var audio = new Audio("http://21273.live.streamtheworld.com/LOS40_DANCE.mp3");
$('#play-pause-button').on("click",function(){
  if($(this).hasClass('fa-play'))
   {
     $(this).removeClass('fa-play');
     $(this).addClass('fa-pause');
     autoplay = true;
     audio.play();
     audio.muted = false;
   }
  else
   {
    audio.muted = true;
     $(this).removeClass('fa-pause');
     $(this).addClass('fa-play');
   }
});

audio.onended = function() {
     $("#play-pause-button").removeClass('fa-pause');
     $("#play-pause-button").addClass('fa-play');
};

</script>
</code>```

答:
You can either use an input range and I think control the volume with js or use the native controls

So why not just use an <audio> element on the html? you can give the attribute controls and then you won't even need $("#play-pause-button")

<audio src="your_src" controls="true">
```

<p>Or is it due to styling? If so then here's an alternative:</p>

<pre class="lang-html prettyprint-override"><code><input id="volume-control" type="range" min="0" max="100" value="50">
</code>```

const audio = new Audio("http://21273.live.streamtheworld.com/LOS40_DANCE.mp3");
const configure = $("#play-pause-button");
const range = $("#volume-control");
configure.on("click", function () {
    const hasPlayClass = configure.hasClass("fa-play");

    //in nativejs its .classList.toggle() idk about jquery but here's my guess
    configure.toggleClass("fa-play");
    configure.toggleClass("fa-pause");

    audio.muted = hasPlayClass;

    if (hasPlayClass) {
        //did you mean audio.autoplay? Used to be autoplay
        audio.autoplay = true;
        audio.play();
    } else {
        audio.pause();
    }
});

range.on("change", () => {
  audio.volume = range.value;
});

audio.on("ended", function () {
    configure.removeClass('fa-pause');
    configure.addClass('fa-play');
});
```

Last option: use a library for audio controls.

On a different note this code was very bad and repetitive, would recommend not using jquery any further since it barely shortened the code here

Title: Js Audio Volume Slider

Body:
I am new to this and I have a question. how can i put a volume slider? Thank you!!
I can't find any code for the moment that works for me, I hope your help

HTML:

JavaScript:

Body:
You can either use an input range and I think control the volume with js or use the native controls

So why not just use an <audio> element on the html? you can give the attribute controls and then you won't even need $("#play-pause-button")

<audio src="your_src" controls="true">

Or is it due to styling? If so then here's an alternative:

<input id="volume-control" type="range" min="0" max="100" value="50">

const audio = new Audio("http://21273.live.streamtheworld.com/LOS40_DANCE.mp3");
const configure = $("#play-pause-button");
const range = $("#volume-control");
configure.on("click", function () {
    const hasPlayClass = configure.hasClass("fa-play");

    //in nativejs its .classList.toggle() idk about jquery but here's my guess
    configure.toggleClass("fa-play");
    configure.toggleClass("fa-pause");

    audio.muted = hasPlayClass;

    if (hasPlayClass) {
        //did you mean audio.autoplay? Used to be autoplay
        audio.autoplay = true;
        audio.play();
    } else {
        audio.pause();
    }
});

range.on("change", () => {
  audio.volume = range.value;
});

audio.on("ended", function () {
    configure.removeClass('fa-pause');
    configure.addClass('fa-play');
});

Last option: use a library for audio controls.

On a different note this code was very bad and repetitive, would recommend not using jquery any further since it barely shortened the code here


问:
See if Dictionary Item is the last one in the dictionary
Given the code ..

```<code>var dictionary = new Dictionary<string, string>{
  { "something", "something-else" },
  { "another", "another-something-else" }
};

dictionary.ForEach( item => {
  bool isLast = // ... ?

  // do something if this is the last item
});
</code>```

I basically want to see if the item I am working with inside of the ForEach iteration is the last item in the dictionary. I tried

```<code>bool isLast = dictionary[ item.Key ].Equals( dictionary.Last() ) ? true : false;
</code>```

but that did not work...

答:
You will want to use an OrderedDictionary<TKey, TValue>. Check MSDN ref.

With the standard Dictionary, items are not guaranteed to be persisted in any specific order.

Body:
Given the code ..

var dictionary = new Dictionary<string, string>{
  { "something", "something-else" },
  { "another", "another-something-else" }
};

dictionary.ForEach( item => {
  bool isLast = // ... ?

  // do something if this is the last item
});

I basically want to see if the item I am working with inside of the ForEach iteration is the last item in the dictionary. I tried

bool isLast = dictionary[ item.Key ].Equals( dictionary.Last() ) ? true : false;

but that did not work...


问:
receiving an entity error after using a db.find
I'm running into an entity error and I have searched for answers but I can't find one for my specific situation.

here is my code

```<code>[RestrictAccess(restriction = AccessRestrictions.ModifyWorkOrder)]
        [HttpPost]
        [ValidateAntiForgeryToken]
        [Audit]
        public ActionResult Edit([Bind(Include = "ID,JobOrderID,StartDate,CompleteDate,jobSection,ItemID,item_qty,actual_item_qty,ComponentID,comp_qty,actual_comp_qty,PartID,part_qty,actual_part_qty,Notes,subDetail")] JODetails jODetails)
        {
            if (ModelState.IsValid)
            {
                JobOrder jo = db.JobOrders.Find(jODetails.JobOrderID);
                if (jo.hasBeenStarted)
                {

                    JODetails currentData = db.JODetails.Find(jODetails.ID);

                    int oldItemCount = currentData.item_qty != null ? (int)currentData.item_qty : 0;
                    int oldCompCount = currentData.comp_qty != null ? (int)currentData.comp_qty : 0;
                    db.Entry(jODetails).State = EntityState.Modified;
                }
            }
         }

</code>```

It returns an error at the db.entry saying

'Attaching an entity of type 'PIC_Program_1._0.Models.JODetails' failed because another entity of the same type already has the same primary key value

I have noticed people have added AsNoTracking() to their .Where cases but I don't know how I can do something like that for a .Find

答:
Can you map the changes from jODetails to the currentData object?

Entity Framework is already tracking the entity in the currentData variable. When you attempt to track it in the db.Entry(jODetails), you are attempting to track another entity with the same id. Mapping from the user defined object to the existing object will change the values being tracked without trying to track two entities with the same Id.

Edit:

Its worth noting that the object coming from your endpoint input should probably be a DTO model instead of the DB object, but its not necessary to get a working solution.

Your solution might look something like this:

```<code>[RestrictAccess(restriction = AccessRestrictions.ModifyWorkOrder)]
[HttpPost]
[ValidateAntiForgeryToken]
[Audit]
public ActionResult Edit([Bind(Include = "ID,JobOrderID,StartDate,CompleteDate,jobSection,ItemID,item_qty,actual_item_qty,ComponentID,comp_qty,actual_comp_qty,PartID,part_qty,actual_part_qty,Notes,subDetail")] JODetails jODetails)
{
    if (ModelState.IsValid)
    {
        JobOrder jo = db.JobOrders.Find(jODetails.JobOrderID);
        if (jo.hasBeenStarted)
        {

            JODetails currentData = db.JODetails.Find(jODetails.ID);

            currentData.oldItemCount = currentData.item_qty;
            currentData.oldCompCount = currentData.comp_qty;

            currentData.item_qty = jODetails.item_qty;
            currentData.comp_qty = jODetails.comp_qty;
            //add any other fields, including dates, that you'd need to update.
            //This part of assigning jODetails to currentData could be simplified with AutoMapper.
        }
    }
 }
</code>```

Body:
I'm running into an entity error and I have searched for answers but I can't find one for my specific situation.

here is my code

[RestrictAccess(restriction = AccessRestrictions.ModifyWorkOrder)]
        [HttpPost]
        [ValidateAntiForgeryToken]
        [Audit]
        public ActionResult Edit([Bind(Include = "ID,JobOrderID,StartDate,CompleteDate,jobSection,ItemID,item_qty,actual_item_qty,ComponentID,comp_qty,actual_comp_qty,PartID,part_qty,actual_part_qty,Notes,subDetail")] JODetails jODetails)
        {
            if (ModelState.IsValid)
            {
                JobOrder jo = db.JobOrders.Find(jODetails.JobOrderID);
                if (jo.hasBeenStarted)
                {

                    JODetails currentData = db.JODetails.Find(jODetails.ID);

                    int oldItemCount = currentData.item_qty != null ? (int)currentData.item_qty : 0;
                    int oldCompCount = currentData.comp_qty != null ? (int)currentData.comp_qty : 0;
                    db.Entry(jODetails).State = EntityState.Modified;
                }
            }
         }

It returns an error at the db.entry saying

'Attaching an entity of type 'PIC_Program_1._0.Models.JODetails' failed because another entity of the same type already has the same primary key value

I have noticed people have added AsNoTracking() to their .Where cases but I don't know how I can do something like that for a .Find

Body:
Can you map the changes from jODetails to the currentData object?

Entity Framework is already tracking the entity in the currentData variable. When you attempt to track it in the db.Entry(jODetails), you are attempting to track another entity with the same id. Mapping from the user defined object to the existing object will change the values being tracked without trying to track two entities with the same Id.

Edit:

Its worth noting that the object coming from your endpoint input should probably be a DTO model instead of the DB object, but its not necessary to get a working solution.

Your solution might look something like this:

[RestrictAccess(restriction = AccessRestrictions.ModifyWorkOrder)]
[HttpPost]
[ValidateAntiForgeryToken]
[Audit]
public ActionResult Edit([Bind(Include = "ID,JobOrderID,StartDate,CompleteDate,jobSection,ItemID,item_qty,actual_item_qty,ComponentID,comp_qty,actual_comp_qty,PartID,part_qty,actual_part_qty,Notes,subDetail")] JODetails jODetails)
{
    if (ModelState.IsValid)
    {
        JobOrder jo = db.JobOrders.Find(jODetails.JobOrderID);
        if (jo.hasBeenStarted)
        {

            JODetails currentData = db.JODetails.Find(jODetails.ID);

            currentData.oldItemCount = currentData.item_qty;
            currentData.oldCompCount = currentData.comp_qty;

            currentData.item_qty = jODetails.item_qty;
            currentData.comp_qty = jODetails.comp_qty;
            //add any other fields, including dates, that you'd need to update.
            //This part of assigning jODetails to currentData could be simplified with AutoMapper.
        }
    }
 }


问:
English NER Annotator for Stanford CoreNLP v 4.0.0 missing some entity types compared to v 3.9.2
I recently upgrade to Stanford CoreNLP v 4.0.0 from v 3.9.2 and noticing that it seems to have reduced performance in regards to NER. In particular, v4 seems to not recognize as many entities and not recognizing URLs, or EMAILs at all. Version 4 also doesn't recognize Google as an ORGANIZATION anymore (still recognizes Microsoft but I havent done many tests on other organizations yet). I was wondering if there is a change in how v4 should be used? The documentation doesn't seem to indicate any differences in usage from what I can see.

The change log at https://stanfordnlp.github.io/CoreNLP/history.html doesn't seem to imply that NER in English should be affected (although it does state that there is a new UDv2 tokenization that affects tagging and parsing). I did notice that the jar files between v4 and v3.9.2 are different with v4 being significantly smaller.

To demonstrate the differences, consider for example the basic following input datafile that includes all entity types and has the following text on each line (i.e. two files basic.txt and basic4.txt are identical and contain the string elements on each line listed below).

```<code>he
cancer.
Los Angeles
California
Google
two days
Convention
night actor
special interest
todays ego
$1 million
100%
tonight, not sure
10/10
Islam
Nicole.
Europe
https://www.tom.com
fans@tom.com
@therealdeal
USA
</code>```

Running the following two commands (where the environment variables $CORENLP and $CORENLP4 point to the directory containing versions 3.9.2 and 4.0.0 respectively, each of which has the english models jar file relevant for each version). The output for the two versions is computed with the two commands

```<code> java -mx2g -cp "$CORENLP4/*" edu.stanford.nlp.pipeline.StanfordCoreNLP -ssplit.eolonly true -annotators tokenize,ssplit,pos,lemma,ner -file basic4.txt -outputFormat text

 java -mx2g -cp "$CORENLP/*" edu.stanford.nlp.pipeline.StanfordCoreNLP -ssplit.eolonly true -annotators tokenize,ssplit,pos,lemma,ner -file basic.txt -outputFormat text
</code>```

Giving two output files. basic4.txt.out and basic.txt.out respectively. The newer 4.0.0 version of CORENLP doesnt seem to be able to identify URL, emails and also doesnt recognize Google as an Organization.

To succinctly demonstrate, the output of the diff command is given below. It shows that the different versions identify most of the entities (with extra details in v4). However, v4 misses the URL, EMAIL and Google as an ORGANIZATION as mentioned earlier.

```<code>diff basic.txt.out basic4.txt.out > corenlp.diff

1c1
< Document: ID=basic.txt (21 sentences, 34 tokens)
---
> Document: ID=basic4.txt (21 sentences, 34 tokens)
10c10
< he    PERSON
---
> he    PERSON  -
20c20
< cancer    CAUSE_OF_DEATH
---
> cancer    CAUSE_OF_DEATH  -
30c30
< Los Angeles   CITY
---
> Los Angeles   CITY    LOCATION:0.9501291593275937
39c39
< California    STATE_OR_PROVINCE
---
> California    STATE_OR_PROVINCE   LOCATION:0.558758796557467
45c45
< [Text=Google CharacterOffsetBegin=35 CharacterOffsetEnd=41 PartOfSpeech=NNP Lemma=Google NamedEntityTag=ORGANIZATION]
---
> [Text=Google CharacterOffsetBegin=35 CharacterOffsetEnd=41 PartOfSpeech=NNP Lemma=Google NamedEntityTag=O]
48d47
< Google    ORGANIZATION
58c57
< two days  DURATION
---
> two days  DURATION    DURATION:-1.0
64c63
< [Text=Convention CharacterOffsetBegin=51 CharacterOffsetEnd=61 PartOfSpeech=NNP Lemma=Convention NamedEntityTag=O]
---
> [Text=Convention CharacterOffsetBegin=51 CharacterOffsetEnd=61 PartOfSpeech=NN Lemma=convention NamedEntityTag=O]
76,77c75,76
< night TIME
< actor TITLE
---
> night TIME    TIME:-1.0
> actor TITLE   -
87c86
< special interest  IDEOLOGY
---
> special interest  IDEOLOGY    -
97c96
< todays    SET
---
> todays    SET SET:-1.0
108c107
< $1 million    MONEY
---
> $1 million    MONEY   MONEY:0.999511595823616
118c117
< 100%  PERCENT
---
> 100%  PERCENT PERCENT:0.9157902320089298
124c123
< [Text=tonight CharacterOffsetBegin=118 CharacterOffsetEnd=125 PartOfSpeech=RB Lemma=tonight NamedEntityTag=DATE NormalizedNamedEntityTag=THIS NI Timex=<TIMEX3 alt_value="THIS NI" anchorTimeID="t0" temporalFunction="true" tid="t4" type="DATE" valueFromFunction="tf0">tonight</TIMEX3>]
---
> [Text=tonight CharacterOffsetBegin=118 CharacterOffsetEnd=125 PartOfSpeech=NN Lemma=tonight NamedEntityTag=DATE NormalizedNamedEntityTag=THIS NI Timex=<TIMEX3 alt_value="THIS NI" anchorTimeID="t0" temporalFunction="true" tid="t4" type="DATE" valueFromFunction="tf0">tonight</TIMEX3>]
130c129
< tonight   DATE
---
> tonight   DATE    DATE:-1.0
139c138
< 10/10 NUMBER
---
> 10/10 NUMBER  NUMBER:-1.0
148c147
< Islam RELIGION
---
> Islam RELIGION    ORGANIZATION:0.4330241395436507
158c157
< Nicole    PERSON
---
> Nicole    PERSON  PERSON:0.8292894556058169
167c166
< Europe    LOCATION
---
> Europe    LOCATION    LOCATION:0.8992206702193217
173c172
< [Text=https://www.tom.com CharacterOffsetBegin=163 CharacterOffsetEnd=182 PartOfSpeech=NNP Lemma=https://www.tom.com NamedEntityTag=URL]
---
> [Text=https://www.tom.com CharacterOffsetBegin=163 CharacterOffsetEnd=182 PartOfSpeech=ADD Lemma=https://www.tom.com NamedEntityTag=O]
176d174
< https://www.tom.com   URL
182c180
< [Text=fans@tom.com CharacterOffsetBegin=183 CharacterOffsetEnd=195 PartOfSpeech=NNP Lemma=fans@tom.com NamedEntityTag=EMAIL]
---
> [Text=fans@tom.com CharacterOffsetBegin=183 CharacterOffsetEnd=195 PartOfSpeech=ADD Lemma=fans@tom.com NamedEntityTag=O]
185d182
< fans@tom.com  EMAIL
191c188
< [Text=@therealdeal CharacterOffsetBegin=196 CharacterOffsetEnd=208 PartOfSpeech=NN Lemma=@therealdeal NamedEntityTag=HANDLE]
---
> [Text=@therealdeal CharacterOffsetBegin=196 CharacterOffsetEnd=208 PartOfSpeech=JJ Lemma=@therealdeal NamedEntityTag=HANDLE]
194c191
< @therealdeal  HANDLE
---
> @therealdeal  HANDLE  -
203c200
< USA   COUNTRY
---
> USA   COUNTRY LOCATION:0.7231044794961725
</code>```

答:
In general, single word sentences aren't handled well by the NER models, since those models use the surrounding context to process the text.  The hard coded expressions for high precision NER don't include google or Google, but you could make that change if you like.  Note that sometimes it can identify Google as an ORG by itself as there is a mechanism for remembering which words it sees in a lowercase or uppercase context first.  If you ask 3.9.2 for "Google" and then "google", it will identify "Google" as an ORG.  If you ask in the reverse order, it will identify neither as ORG.

The issue with not recognizing emails or urls is that the high precision NER is only set to apply to nouns or adjectives, and the new version introduced a new POS tag for addresses.  We can change the code on our end so that in the future this will be detected by default.  In the meantime, you can add this option to your command line and it should once again detect urls and emails:

-ner.fine.regexner.mapping "ignorecase=true,validpospattern=^(NN|JJ|ADD).*,edu/stanford/nlp/models/kbp/english/gazetteers/regexner_caseless.tab;edu/stanford/nlp/models/kbp/english/gazetteers/regexner_cased.tab"

Body:
I recently upgrade to Stanford CoreNLP v 4.0.0 from v 3.9.2 and noticing that it seems to have reduced performance in regards to NER. In particular, v4 seems to not recognize as many entities and not recognizing URLs, or EMAILs at all. Version 4 also doesn't recognize Google as an ORGANIZATION anymore (still recognizes Microsoft but I havent done many tests on other organizations yet). I was wondering if there is a change in how v4 should be used? The documentation doesn't seem to indicate any differences in usage from what I can see.

The change log at https://stanfordnlp.github.io/CoreNLP/history.html doesn't seem to imply that NER in English should be affected (although it does state that there is a new UDv2 tokenization that affects tagging and parsing). I did notice that the jar files between v4 and v3.9.2 are different with v4 being significantly smaller.

To demonstrate the differences, consider for example the basic following input datafile that includes all entity types and has the following text on each line (i.e. two files basic.txt and basic4.txt are identical and contain the string elements on each line listed below).

he
cancer.
Los Angeles
California
Google
two days
Convention
night actor
special interest
todays ego
$1 million
100%
tonight, not sure
10/10
Islam
Nicole.
Europe
https://www.tom.com
fans@tom.com
@therealdeal
USA

Running the following two commands (where the environment variables $CORENLP and $CORENLP4 point to the directory containing versions 3.9.2 and 4.0.0 respectively, each of which has the english models jar file relevant for each version). The output for the two versions is computed with the two commands

 java -mx2g -cp "$CORENLP4/*" edu.stanford.nlp.pipeline.StanfordCoreNLP -ssplit.eolonly true -annotators tokenize,ssplit,pos,lemma,ner -file basic4.txt -outputFormat text

 java -mx2g -cp "$CORENLP/*" edu.stanford.nlp.pipeline.StanfordCoreNLP -ssplit.eolonly true -annotators tokenize,ssplit,pos,lemma,ner -file basic.txt -outputFormat text

Giving two output files. basic4.txt.out and basic.txt.out respectively. The newer 4.0.0 version of CORENLP doesnt seem to be able to identify URL, emails and also doesnt recognize Google as an Organization.

To succinctly demonstrate, the output of the diff command is given below. It shows that the different versions identify most of the entities (with extra details in v4). However, v4 misses the URL, EMAIL and Google as an ORGANIZATION as mentioned earlier.

diff basic.txt.out basic4.txt.out > corenlp.diff

1c1
< Document: ID=basic.txt (21 sentences, 34 tokens)
---
> Document: ID=basic4.txt (21 sentences, 34 tokens)
10c10
< he    PERSON
---
> he    PERSON  -
20c20
< cancer    CAUSE_OF_DEATH
---
> cancer    CAUSE_OF_DEATH  -
30c30
< Los Angeles   CITY
---
> Los Angeles   CITY    LOCATION:0.9501291593275937
39c39
< California    STATE_OR_PROVINCE
---
> California    STATE_OR_PROVINCE   LOCATION:0.558758796557467
45c45
< [Text=Google CharacterOffsetBegin=35 CharacterOffsetEnd=41 PartOfSpeech=NNP Lemma=Google NamedEntityTag=ORGANIZATION]
---
> [Text=Google CharacterOffsetBegin=35 CharacterOffsetEnd=41 PartOfSpeech=NNP Lemma=Google NamedEntityTag=O]
48d47
< Google    ORGANIZATION
58c57
< two days  DURATION
---
> two days  DURATION    DURATION:-1.0
64c63
< [Text=Convention CharacterOffsetBegin=51 CharacterOffsetEnd=61 PartOfSpeech=NNP Lemma=Convention NamedEntityTag=O]
---
> [Text=Convention CharacterOffsetBegin=51 CharacterOffsetEnd=61 PartOfSpeech=NN Lemma=convention NamedEntityTag=O]
76,77c75,76
< night TIME
< actor TITLE
---
> night TIME    TIME:-1.0
> actor TITLE   -
87c86
< special interest  IDEOLOGY
---
> special interest  IDEOLOGY    -
97c96
< todays    SET
---
> todays    SET SET:-1.0
108c107
< $1 million    MONEY
---
> $1 million    MONEY   MONEY:0.999511595823616
118c117
< 100%  PERCENT
---
> 100%  PERCENT PERCENT:0.9157902320089298
124c123
< [Text=tonight CharacterOffsetBegin=118 CharacterOffsetEnd=125 PartOfSpeech=RB Lemma=tonight NamedEntityTag=DATE NormalizedNamedEntityTag=THIS NI Timex=<TIMEX3 alt_value="THIS NI" anchorTimeID="t0" temporalFunction="true" tid="t4" type="DATE" valueFromFunction="tf0">tonight</TIMEX3>]
---
> [Text=tonight CharacterOffsetBegin=118 CharacterOffsetEnd=125 PartOfSpeech=NN Lemma=tonight NamedEntityTag=DATE NormalizedNamedEntityTag=THIS NI Timex=<TIMEX3 alt_value="THIS NI" anchorTimeID="t0" temporalFunction="true" tid="t4" type="DATE" valueFromFunction="tf0">tonight</TIMEX3>]
130c129
< tonight   DATE
---
> tonight   DATE    DATE:-1.0
139c138
< 10/10 NUMBER
---
> 10/10 NUMBER  NUMBER:-1.0
148c147
< Islam RELIGION
---
> Islam RELIGION    ORGANIZATION:0.4330241395436507
158c157
< Nicole    PERSON
---
> Nicole    PERSON  PERSON:0.8292894556058169
167c166
< Europe    LOCATION
---
> Europe    LOCATION    LOCATION:0.8992206702193217
173c172
< [Text=https://www.tom.com CharacterOffsetBegin=163 CharacterOffsetEnd=182 PartOfSpeech=NNP Lemma=https://www.tom.com NamedEntityTag=URL]
---
> [Text=https://www.tom.com CharacterOffsetBegin=163 CharacterOffsetEnd=182 PartOfSpeech=ADD Lemma=https://www.tom.com NamedEntityTag=O]
176d174
< https://www.tom.com   URL
182c180
< [Text=fans@tom.com CharacterOffsetBegin=183 CharacterOffsetEnd=195 PartOfSpeech=NNP Lemma=fans@tom.com NamedEntityTag=EMAIL]
---
> [Text=fans@tom.com CharacterOffsetBegin=183 CharacterOffsetEnd=195 PartOfSpeech=ADD Lemma=fans@tom.com NamedEntityTag=O]
185d182
< fans@tom.com  EMAIL
191c188
< [Text=@therealdeal CharacterOffsetBegin=196 CharacterOffsetEnd=208 PartOfSpeech=NN Lemma=@therealdeal NamedEntityTag=HANDLE]
---
> [Text=@therealdeal CharacterOffsetBegin=196 CharacterOffsetEnd=208 PartOfSpeech=JJ Lemma=@therealdeal NamedEntityTag=HANDLE]
194c191
< @therealdeal  HANDLE
---
> @therealdeal  HANDLE  -
203c200
< USA   COUNTRY
---
> USA   COUNTRY LOCATION:0.7231044794961725


问:
QtQuick drawing shapes and colors but not text
I've just tried running my qtquick2 application, my application opens successfully but no text is drawn.</p>

答:
Fonts are probably missing on your target.
You can add them to your layer by appending IMAGE_INSTALL_append with  ttf-dejavu-sans, ttf-ubuntu-mono, ttf-ubuntu-sans or any other font.


答: If fuel flow <= 0 then engine braking.</p>

Title: Engine braking from obd2 data

Body:
so i have this data frame comming from OBD2 :

    Time    Engine RPM [RPM]    Vehicle Speed Sensor [km/h]     Air Flow Rate from Mass Flow Sensor [g/s]   pke     fuelflow    fuelcons
0   2020-06-01 06:58:41.245     0.0     0.0     0.88    0.000000    2.451724    0.000000
1   2020-06-01 06:58:42.026     0.0     0.0     0.88    0.000000    2.451724    0.000000
2   2020-06-01 06:58:43.045     0.0     0.0     0.88    0.000000    2.451724    0.000000
3   2020-06-01 06:58:44.035     180.0   0.0     12.02   0.000000    2.451724    0.000000
4   2020-06-01 06:58:45.085     1010.0  0.0     16.91   0.000000    2.451724    0.000000
5   2020-06-01 06:58:46.047     925.0   0.0     16.30   0.000000    2.451724    0.000000
6   2020-06-01 06:58:47.005     904.0   0.0     15.27   0.000000    2.451724    0.000000
7   2020-06-01 06:58:48.087     883.0   0.0     14.58   0.000000    2.451724    0.000000
8   2020-06-01 06:58:49.045     896.0   0.0     14.72   0.000000    2.451724    0.000000
9   2020-06-01 06:58:50.035     948.0   0.0     15.72   0.000000    2.451724    0.000000
10  2020-06-01 06:58:51.026     927.0   0.0     15.49   0.000000    2.451724    0.000000
11  2020-06-01 06:58:52.015     961.0   0.0     15.72   0.000000    2.451724    0.000000
12  2020-06-01 06:58:53.065     939.0   1.0     16.02   0.009643    2.451724    5.524138
13  2020-06-01 06:58:54.025     984.0   2.0     15.94   0.028930    2.451724    2.748276
14  2020-06-01 06:58:55.046     944.0   1.0     17.02   -0.028930   2.451724    5.868966
15  2020-06-01 06:58:56.035     952.0   1.0     16.49   0.000000    2.451724    5.686207
16  2020-06-01 06:58:57.085     952.0   1.0     16.52   0.000000    2.451724    5.696552
17  2020-06-01 06:58:58.046     956.0   1.0     16.49   0.000000    2.451724    5.686207
18  2020-06-01 06:58:59.005     934.0   1.0     16.02   0.000000    2.451724    5.524138
19  2020-06-01 06:59:00.085     981.0   1.0     16.83   0.000000    2.451724    5.803448
20  2020-06-01 06:59:01.076     940.0   1.0     16.08   0.000000    2.451724    5.544828
21  2020-06-01 06:59:02.065     915.0   1.0     15.69   0.000000    2.451724    5.410345
22  2020-06-01 06:59:03.085     909.0   3.0     15.63   0.077147    2.451724    1.796552
23  2020-06-01 06:59:04.076     1015.0  6.0     15.47   0.260370    2.451724    0.889080
24  2020-06-01 06:59:05.005     1377.0  9.0     19.77   0.433950    2.451724    0.757471

i want to detect engine braking event from this data. i really didnt try any thing?
any help ?

Body: If fuel flow <= 0 then engine braking.


问:
Kotlin - custom dialog in Android
I want to create a custom dialog in Kotlin. I looked through questions on this theme on Stack Overflow, but I could not find any useful information. How can I do it?

答:
Below my solution as a kind of "message box".
I have not implemented an "OK" button. The message box should close after clicking on it.

Here the layout element (*/layout/message_box.xml)

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="300dp"
        android:orientation="vertical">

        <TextView
            android:id="@+id/message_box_header"
            android:layout_width="match_parent"
            android:layout_height="30dp"
            android:textAlignment="center"
            android:textSize="20sp" />

        <TextView
            android:id="@+id/message_box_content"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textAlignment="center"
            android:textSize="20sp" />

    </LinearLayout>
</LinearLayout>
</code>```

This function I've implement in a Fragment class. It is written in Kotlin.

```<code>fun showMessageBox(text: String){

    //Inflate the dialog as custom view
    val messageBoxView = LayoutInflater.from(activity).inflate(R.layout.message_box, null)

    //AlertDialogBuilder
    val messageBoxBuilder = AlertDialog.Builder(activity).setView(messageBoxView)

    //setting text values
    messageBoxView.message_box_header.text = "This is message header"
    messageBoxView.message_box_content.text = "This is message content"

    //show dialog
    val  messageBoxInstance = messageBoxBuilder.show()

    //set Listener
    messageBoxView.setOnClickListener(){
        //close dialog
        messageBoxInstance.dismiss()
    }
}
</code>```

Title: Kotlin - custom dialog in Android

Body:
Below my solution as a kind of "message box".
I have not implemented an "OK" button. The message box should close after clicking on it.

Here the layout element (*/layout/message_box.xml)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="300dp"
        android:orientation="vertical">

        <TextView
            android:id="@+id/message_box_header"
            android:layout_width="match_parent"
            android:layout_height="30dp"
            android:textAlignment="center"
            android:textSize="20sp" />

        <TextView
            android:id="@+id/message_box_content"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textAlignment="center"
            android:textSize="20sp" />

    </LinearLayout>
</LinearLayout>

This function I've implement in a Fragment class. It is written in Kotlin.

fun showMessageBox(text: String){

    //Inflate the dialog as custom view
    val messageBoxView = LayoutInflater.from(activity).inflate(R.layout.message_box, null)

    //AlertDialogBuilder
    val messageBoxBuilder = AlertDialog.Builder(activity).setView(messageBoxView)

    //setting text values
    messageBoxView.message_box_header.text = "This is message header"
    messageBoxView.message_box_content.text = "This is message content"

    //show dialog
    val  messageBoxInstance = messageBoxBuilder.show()

    //set Listener
    messageBoxView.setOnClickListener(){
        //close dialog
        messageBoxInstance.dismiss()
    }
}


问:
Using nconf in the browser?
I'm looking to use https://github.com/flatiron/nconf in the browser. I have tried to use it with browserify but because nconf calls fs.readdirSync when it is required to scan directories for configuration, it fails in the browser.

```<code>// config.js
'use strict';

var nconf = require('nconf'); // this triggers the fs.readdirSync

var globalConfig = { my: { global: 1 }};
nconf.use('global', { type: 'literal', store: globalConfig });

var envConfig = { my: { env: 2 }};
nconf.use('env', { type: 'literal', store: envConfig });

module.exports = nconf;
</code>```

Is it possible to use some sort of browserify transform (I didn't see a way to make it force the use of BRFS in nconf) or a way to use nconf (or some other similar library) to manage client side configuration?

If not nconf itself, then just something that would allow me to do something similar to this:

```<code>config.load('user-settings', { my : { user: 1 } });
config.load('global-settings', { my: { global: 2 } } );

config.get('my.user'); // 1
config.get('my.global'); // 2

config.unload('global-settings');

config.get('my.global'); // undefined
</code>```

答:
I recently had this issue myself. I decided to just put together my own config file, rather than pull in another library. here's what I ended up with:

```<code>/*
 This file determines which environment we're in, and provides the app with the appropriate config
 */
export const defaults = {
  searchURI: 'http://www.google.com/',
  anotherURI: 'https://stackoverflow.com/',
};

export const dev = {
  searchURI: 'https://www.bing.com/',
};

export const test = {
  searchURI: 'https://www.yahoo.com/',
};

export const prod = {
  searchURI: 'https://duckduckgo.com/',
};

const config = () => {
  switch (process.env.YOUR_ENV_NAME) {
    case 'dev':
      return dev;
    case 'test':
      return test;
    default:
      return prod;
  }
};

export default {
  ...defaults,
  ...config(),
};

</code>```

using this pattern, you can import config just like you would nconf:

```<code>import config from './path/to/above/file.js';

const { searchURI, anotherURI } = config;
// OR
const searchURI = config.searchURI;
const anotherURI = config.anotherURI;
</code>```

Title: Using nconf in the browser?

Body:
I'm looking to use https://github.com/flatiron/nconf in the browser. I have tried to use it with browserify but because nconf calls fs.readdirSync when it is required to scan directories for configuration, it fails in the browser.

// config.js
'use strict';

var nconf = require('nconf'); // this triggers the fs.readdirSync

var globalConfig = { my: { global: 1 }};
nconf.use('global', { type: 'literal', store: globalConfig });

var envConfig = { my: { env: 2 }};
nconf.use('env', { type: 'literal', store: envConfig });

module.exports = nconf;

Is it possible to use some sort of browserify transform (I didn't see a way to make it force the use of BRFS in nconf) or a way to use nconf (or some other similar library) to manage client side configuration?

If not nconf itself, then just something that would allow me to do something similar to this:

config.load('user-settings', { my : { user: 1 } });
config.load('global-settings', { my: { global: 2 } } );

config.get('my.user'); // 1
config.get('my.global'); // 2

config.unload('global-settings');

config.get('my.global'); // undefined

Body:
I recently had this issue myself. I decided to just put together my own config file, rather than pull in another library. here's what I ended up with:

/*
 This file determines which environment we're in, and provides the app with the appropriate config
 */
export const defaults = {
  searchURI: 'http://www.google.com/',
  anotherURI: 'https://stackoverflow.com/',
};

export const dev = {
  searchURI: 'https://www.bing.com/',
};

export const test = {
  searchURI: 'https://www.yahoo.com/',
};

export const prod = {
  searchURI: 'https://duckduckgo.com/',
};

const config = () => {
  switch (process.env.YOUR_ENV_NAME) {
    case 'dev':
      return dev;
    case 'test':
      return test;
    default:
      return prod;
  }
};

export default {
  ...defaults,
  ...config(),
};

using this pattern, you can import config just like you would nconf:

import config from './path/to/above/file.js';

const { searchURI, anotherURI } = config;
// OR
const searchURI = config.searchURI;
const anotherURI = config.anotherURI;