问:
How to end java program
Do I have to add some exit statement?

Code seems to be running well, but after it finish its task I still can't interact with console.

```<code>/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package excelb;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
import javax.swing.JFileChooser;
import javax.swing.JFrame;

/**
 *
 * @author hp
 */
public class Excelb {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws FileNotFoundException, IOException {
        // TODO code application logic here
        String row;
        String row2;
        File fn = null;
        int counter = 0;

        Scanner in = new Scanner(System.in);
        System.out.println("Enter the run identifier for output file");
        String output = in.nextLine();

        //input
        JFileChooser jFileChooser = new JFileChooser();
        jFileChooser.setCurrentDirectory(new File("C:/"));

        int result = jFileChooser.showOpenDialog(new JFrame());

        if (result == JFileChooser.APPROVE_OPTION) {
             fn=jFileChooser.getSelectedFile();
            System.out.println("Data file: " + fn.getAbsolutePath());
            //System.out.println("Data file: " + fn.getTitle());
        }

        BufferedReader csvReader = new BufferedReader(new FileReader("Keywords.csv"));
        BufferedReader csvReader2 = new BufferedReader(new FileReader(fn.getAbsolutePath()));

        row = csvReader.readLine();
        String[] data = row.split(",");
        while (counter < data.length) {
            while ((row2 = csvReader2.readLine()) != null) {
                String[] data2 = row2.split(",");
                for (int j = 0; j < data.length; j++) {
                    if ((data2[data2.length - 1].contains(data[j]))) {
                        //DateFormat df = new SimpleDateFormat("dd/MM/yy");
                        //Date dateobj = new Date();
                        //String d = df.format(dateobj);
                        //d = d.replaceAll("/", "");
                        String newFile = data[j] + "_" + output + ".csv";
                        FileWriter csvWriter = new FileWriter(newFile, true);
                        for (int i = 0; i < data2.length; i++) {
                           csvWriter.append(data2[i]);
                            csvWriter.append(",");
                        }
                        csvWriter.append("\n");
                        csvWriter.close();
                    }
                }
            }
            counter++;
        }
        System.out.println("Finished");
        csvReader.close();
        csvReader2.close();
    }

}
</code>```

答:
Problem:

Your application consists of two separate threads:

handling main method

handling events from swing events.

Even if main thread will end its execution, swing thread is still running and doesn't allow your application to exit.

BTW that is a good thing. We are building GUI components like frames with buttons, labels, etc. in main method. Now, when main method/thread ends, should application be closed and along with it all built GUI? That wouldn't make much sense.

Why problem appeared?

Because you used new JFrame() which started swing thread responsible for handling events related to swing/AWT components (like button clicks, etc.).

Solutions:

Approach 1: Prevent problem from happening

Don't start swing thread with new JFrame() if you are not planning to create application based on swing GUI.

In your case simple solution would be passing null instead of new JFrame() to jFileChooser.showOpenDialog. This would also let that dialog be placed at the center of the screen:

```<code>int result = jFileChooser.showOpenDialog(null);
</code>```

Approach 2: Forceful exit

To forcefully close your application you can use System.exit(0).

But generally it is better to prevent problems from happening than solving them.

Title: How to end java program

Body:
Do I have to add some exit statement?

Code seems to be running well, but after it finish its task I still can't interact with console.

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package excelb;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
import javax.swing.JFileChooser;
import javax.swing.JFrame;

/**
 *
 * @author hp
 */
public class Excelb {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws FileNotFoundException, IOException {
        // TODO code application logic here
        String row;
        String row2;
        File fn = null;
        int counter = 0;

        Scanner in = new Scanner(System.in);
        System.out.println("Enter the run identifier for output file");
        String output = in.nextLine();

        //input
        JFileChooser jFileChooser = new JFileChooser();
        jFileChooser.setCurrentDirectory(new File("C:/"));

        int result = jFileChooser.showOpenDialog(new JFrame());

        if (result == JFileChooser.APPROVE_OPTION) {
             fn=jFileChooser.getSelectedFile();
            System.out.println("Data file: " + fn.getAbsolutePath());
            //System.out.println("Data file: " + fn.getTitle());
        }

        BufferedReader csvReader = new BufferedReader(new FileReader("Keywords.csv"));
        BufferedReader csvReader2 = new BufferedReader(new FileReader(fn.getAbsolutePath()));

        row = csvReader.readLine();
        String[] data = row.split(",");
        while (counter < data.length) {
            while ((row2 = csvReader2.readLine()) != null) {
                String[] data2 = row2.split(",");
                for (int j = 0; j < data.length; j++) {
                    if ((data2[data2.length - 1].contains(data[j]))) {
                        //DateFormat df = new SimpleDateFormat("dd/MM/yy");
                        //Date dateobj = new Date();
                        //String d = df.format(dateobj);
                        //d = d.replaceAll("/", "");
                        String newFile = data[j] + "_" + output + ".csv";
                        FileWriter csvWriter = new FileWriter(newFile, true);
                        for (int i = 0; i < data2.length; i++) {
                           csvWriter.append(data2[i]);
                            csvWriter.append(",");
                        }
                        csvWriter.append("\n");
                        csvWriter.close();
                    }
                }
            }
            counter++;
        }
        System.out.println("Finished");
        csvReader.close();
        csvReader2.close();
    }

}

Body:
Problem:

Your application consists of two separate threads:

handling main method

handling events from swing events.

Even if main thread will end its execution, swing thread is still running and doesn't allow your application to exit.

BTW that is a good thing. We are building GUI components like frames with buttons, labels, etc. in main method. Now, when main method/thread ends, should application be closed and along with it all built GUI? That wouldn't make much sense.

Why problem appeared?

Because you used new JFrame() which started swing thread responsible for handling events related to swing/AWT components (like button clicks, etc.).

Solutions:

Approach 1: Prevent problem from happening

Don't start swing thread with new JFrame() if you are not planning to create application based on swing GUI.

In your case simple solution would be passing null instead of new JFrame() to jFileChooser.showOpenDialog. This would also let that dialog be placed at the center of the screen:

int result = jFileChooser.showOpenDialog(null);

Approach 2: Forceful exit

To forcefully close your application you can use System.exit(0).

But generally it is better to prevent problems from happening than solving them.


来源: stackexchange

问:
Stop propagation of 'click' event in Leaflet
In one of our projects we're using Leaflet along with Leaflet.markercluster plugin. Looking through the Leaflet's sources I found that it appends _collapse() function to the map's click event, so whenever I click on the map it contracts previously expanded cluster.

Now, I want to disable this behavior. If the cluster is expanded, then I just want to deselect all of its markers on click event (and don't contract the cluster itself). Here is the piece of my code:

```<code>map.on('click', function(e) {
    scope.deselectAllMarkers();
});
</code>```

I tried to add the following lines in the end of this one-line callback in order to stop propagation of click event:

scope.L.DomEvent.stopPropagation(e);

scope.L.DomEvent.preventDefault(e);

scope.L.DomEvent.stop(e);

scope.L.DomEvent.stopPropagation(e.originalEvent);

scope.L.DomEvent.preventDefault(e.originalEvent);

scope.L.DomEvent.stop(e.originalEvent);

And none of them works. Default listener which is hidden inside of the Leaflet sources keeps its invocation whenever I click on the map. Am I missing something?

答:
I know that this answer is event more quite late, but as in jquery you can use .off

```<code>map.on('click', doSomething);
map.off('click');
</code>```

It works fine for any leaflet events.

I use it for 'zoomend' event to be triggered one time only.

```<code>map.on('moveend', function(e){
    console.log("any code");
    map.off('moveend');
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
In one of our projects we're using Leaflet along with Leaflet.markercluster plugin. Looking through the Leaflet's sources I found that it appends _collapse() function to the map's click event, so whenever I click on the map it contracts previously expanded cluster.

Now, I want to disable this behavior. If the cluster is expanded, then I just want to deselect all of its markers on click event (and don't contract the cluster itself). Here is the piece of my code:

map.on('click', function(e) {
    scope.deselectAllMarkers();
});

I tried to add the following lines in the end of this one-line callback in order to stop propagation of click event:

scope.L.DomEvent.stopPropagation(e);

scope.L.DomEvent.preventDefault(e);

scope.L.DomEvent.stop(e);

scope.L.DomEvent.stopPropagation(e.originalEvent);

scope.L.DomEvent.preventDefault(e.originalEvent);

scope.L.DomEvent.stop(e.originalEvent);

And none of them works. Default listener which is hidden inside of the Leaflet sources keeps its invocation whenever I click on the map. Am I missing something?

Body:
I know that this answer is event more quite late, but as in jquery you can use .off

map.on('click', doSomething);
map.off('click');

It works fine for any leaflet events.

I use it for 'zoomend' event to be triggered one time only.

map.on('moveend', function(e){
    console.log("any code");
    map.off('moveend');
});

ContentLicense: CC BY-SA 4.0


问:
Firebase test lab displaying the message about exceeding quota
Hello Stackoverflow community!
I am trying to test with the Spark plan Robo test for Firebase Test Lab.
But it's showing that I already have exceeded quota for 5 devices, despite the fact, that I haven't tested anything yet. But I have 5 in sum for previous year. Can this be the issue? Thanks for the help

答: Daily quota is per Firebase project, not per app. Are you sure a different app wasn't tested with this Spark project?</p>


问:
Differences between format long and format long g
I searched differences between format long and format long g in Matlab.But I'm not sure exactly what the differences are between them.Does the difference between them affect accuracy?

Thank you...

答:
The commands format X in Matlab affect the display of text.

So format short will display 4 digits after the decimal point. This is the default display option. The command format long will display more digits after the decimal point. The addition of a G will tell Matlab to additionally display in scientific notation if it is more compact.

There is not difference in terms of computed values or accuracy, just display. From the doc format or here Display Format Matlab article:

format does not affect how MATLAB computations are done. Computations
      on float variables, namely single or double, are done in appropriate
      floating point precision, no matter how those variables are displayed.
      Computations on integer variables are done natively in integer.


问:
PowerShell: Add every sub-directory to path
On Windows 10 and via PowerShell, how do you add every sub-directory to the PATH variable?

I fine some method for Linux (e.g., this one), and "adapting" them to PowerShell, I came across the following.

```<code>'$env:PATH = $env:PATH + (find C:\Users\appveyor\ -type d -printf "\";%pbuild\\"")'
</code>```

This throws The filename, directory name, or volume label syntax is incorrect.

A bit more context: I am running this on appveyor, and trying to add every path under appveyor (simplified for clarity) such as C:\Users\appveyor\*\build\ to path.

答:
The find command on Linux is very different from the Find command on Windows.

In your case, I would use Get-ChildItem in PowerShell (which can also be used via the aliases gci, dir, ls), to return an array of directory objects, added to the current path casted as an array, and then -join them with the Windows path separator, which is a semicolon ;.

That might look like this:

$env:PATH = (
    @($env:PATH) + (
        Get-ChildItem -LiteralPath 'C:\Users\appveyor' -Directory -Recurse
    )
) -join [System.IO.Path]::PathSeparator # <- that could just be a literal string ';'
```

Body:
On Windows 10 and via PowerShell, how do you add every sub-directory to the PATH variable?

I fine some method for Linux (e.g., this one), and "adapting" them to PowerShell, I came across the following.

'$env:PATH = $env:PATH + (find C:\Users\appveyor\ -type d -printf "\";%pbuild\\"")'

This throws The filename, directory name, or volume label syntax is incorrect.

A bit more context: I am running this on appveyor, and trying to add every path under appveyor (simplified for clarity) such as C:\Users\appveyor\*\build\ to path.


问:
How to set the number of decimals of results in Python
I'm doing matrix factorization whose output matrix has non-integer entries. To make the display more compact, I would like to ask how to limit the number of decimals of results. Thank you so much!

```<code>import numpy as np
import scipy.linalg as la

A = np.array([[1, 0, 8, 7, 8, 1],
              [0, 1, 2, 8, 9, 2],
              [5, 1, 0, 6, 10, 3],
              [5, 4, 4, 8, 10, 4]])

(P, L, U) = la.lu(A)

F = np.array(sorted(U, key=lambda x: tuple(x!=0), reverse=False))
print(F)

[[ 0.          0.          0.          6.85483871  8.51612903  1.62903226]
 [ 0.          0.          8.26666667  5.93333333  6.          0.46666667]
 [ 0.          3.          4.          2.          0.          1.        ]
 [ 5.          1.          0.          6.         10.          3.        ]]
</code>```

PS: I would like to ask for a global setting instead of repeating apply the function round to each output.

答:
You can use numpy.around:</p>

```<code>import numpy as np
import scipy.linalg as la

A = np.array([[1, 0, 8, 7, 8, 1],
              [0, 1, 2, 8, 9, 2],
              [5, 1, 0, 6, 10, 3],
              [5, 4, 4, 8, 10, 4]])

(P, L, U) = la.lu(A)

F = np.array(sorted(U, key=lambda x: tuple(x!=0), reverse=False))
F = list(map(lambda x: np.around(x,2),F)) # 2 here is the number of decimals
print(F)
</code>```

Body:
I'm doing matrix factorization whose output matrix has non-integer entries. To make the display more compact, I would like to ask how to limit the number of decimals of results. Thank you so much!

import numpy as np
import scipy.linalg as la

A = np.array([[1, 0, 8, 7, 8, 1],
              [0, 1, 2, 8, 9, 2],
              [5, 1, 0, 6, 10, 3],
              [5, 4, 4, 8, 10, 4]])

(P, L, U) = la.lu(A)

F = np.array(sorted(U, key=lambda x: tuple(x!=0), reverse=False))
print(F)

[[ 0.          0.          0.          6.85483871  8.51612903  1.62903226]
 [ 0.          0.          8.26666667  5.93333333  6.          0.46666667]
 [ 0.          3.          4.          2.          0.          1.        ]
 [ 5.          1.          0.          6.         10.          3.        ]]

PS: I would like to ask for a global setting instead of repeating apply the function round to each output.

Body:
You can use numpy.around:

import numpy as np
import scipy.linalg as la

A = np.array([[1, 0, 8, 7, 8, 1],
              [0, 1, 2, 8, 9, 2],
              [5, 1, 0, 6, 10, 3],
              [5, 4, 4, 8, 10, 4]])

(P, L, U) = la.lu(A)

F = np.array(sorted(U, key=lambda x: tuple(x!=0), reverse=False))
F = list(map(lambda x: np.around(x,2),F)) # 2 here is the number of decimals
print(F)


问:
Flask Problem: RuntimeError: The session is unavailable because no secret key was set
So I was using flask_login for my login system on my mac, and I seem to have run into a problem. When I ran the code, it says I have not set my secret key even if I had done so.

My code was:

from flask import Flask, render_template, request, session, redirect, url_for, jsonify
from flask_session import Session
from flask_login import LoginManager, login_user,logout_user, login_required, current_user
from models.model import *
from sqlalchemy import or_, and_

app = Flask(__name__)
app.secret_key = "<Some secret key>"
app.config["SQLALCHEMY_DATABASE_URI"] = '<Some Uri>'
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
db.init_app(app)
Session(app)

login_manager = LoginManager()
login_manager.login_view = 'index'
login_manager.init_app(app)

@app.route("/")
def index():
    if current_user.is_authenticated:
        return render_template("home.html")
    return render_template("login.html", tip="You have to log in first.")

@login_manager.user_loader
def load_user(user_id):
    return User.query.get(int(user_id))

@app.route("/login", methods=['POST'])
def verif():
    """ Gets name and password from form  """
    username = request.form.get("username")
    password = request.form.get("password")

    """ Checks user and password. """

    userpassCheck = User.query.filter(and_(User.username == username, User.password == password)).first()
    if not userpassCheck:
        return render_template("index.html", tip="Incorrect Username or Password.")

    login_user(userpassCheck)

    return redirect(url_for('index'))

if __name__ == '__main__':
    app.run(debug=True, use_reloader=True)

```

<p>The whole error traceback was:</p>

```Traceback (most recent call last):
  File "/Users/scythia/Desktop/Project1/venv/lib/python3.7/site-packages/flask/app.py", line 2464, in __call__
    return self.wsgi_app(environ, start_response)
  File "/Users/scythia/Desktop/Project1/venv/lib/python3.7/site-packages/flask/app.py", line 2450, in wsgi_app
    response = self.handle_exception(e)
  File "/Users/scythia/Desktop/Project1/venv/lib/python3.7/site-packages/flask/app.py", line 1867, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "/Users/scythia/Desktop/Project1/venv/lib/python3.7/site-packages/flask/_compat.py", line 39, in reraise
    raise value
  File "/Users/scythia/Desktop/Project1/venv/lib/python3.7/site-packages/flask/app.py", line 2447, in wsgi_app
    response = self.full_dispatch_request()
  File "/Users/scythia/Desktop/Project1/venv/lib/python3.7/site-packages/flask/app.py", line 1952, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/Users/scythia/Desktop/Project1/venv/lib/python3.7/site-packages/flask/app.py", line 1821, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/Users/scythia/Desktop/Project1/venv/lib/python3.7/site-packages/flask/_compat.py", line 39, in reraise
    raise value
  File "/Users/scythia/Desktop/Project1/venv/lib/python3.7/site-packages/flask/app.py", line 1950, in full_dispatch_request
    rv = self.dispatch_request()
  File "/Users/scythia/Desktop/Project1/venv/lib/python3.7/site-packages/flask/app.py", line 1936, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/Users/scythia/Desktop/Project1/application.py", line 54, in verif
    login_user(userpassCheck)
  File "/Users/scythia/Desktop/Project1/venv/lib/python3.7/site-packages/flask_login/utils.py", line 170, in login_user
    session['_user_id'] = user_id
  File "/Users/scythia/Desktop/Project1/venv/lib/python3.7/site-packages/werkzeug/local.py", line 350, in __setitem__
    self._get_current_object()[key] = value
  File "/Users/scythia/Desktop/Project1/venv/lib/python3.7/site-packages/flask/sessions.py", line 103, in _fail
    "The session is unavailable because no secret "
RuntimeError: The session is unavailable because no secret key was set.  Set the secret_key on the application to something unique and secret.
```

My expectations for the code was for it to be completely able to run. I haven't included the two HTML files because I think it is not related. I can add it if you think it is.

Using:
Python 3.7.7;
Flask 1.1.2;

答: As @Harmandeep Kalsi said in the comments, I added app.config['SESSION_TYPE'] and it worked.

Body:
So I was using flask_login for my login system on my mac, and I seem to have run into a problem. When I ran the code, it says I have not set my secret key even if I had done so.

My code was:

from flask import Flask, render_template, request, session, redirect, url_for, jsonify
from flask_session import Session
from flask_login import LoginManager, login_user,logout_user, login_required, current_user
from models.model import *
from sqlalchemy import or_, and_

app = Flask(__name__)
app.secret_key = "<Some secret key>"
app.config["SQLALCHEMY_DATABASE_URI"] = '<Some Uri>'
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
db.init_app(app)
Session(app)

login_manager = LoginManager()
login_manager.login_view = 'index'
login_manager.init_app(app)

@app.route("/")
def index():
    if current_user.is_authenticated:
        return render_template("home.html")
    return render_template("login.html", tip="You have to log in first.")

@login_manager.user_loader
def load_user(user_id):
    return User.query.get(int(user_id))

@app.route("/login", methods=['POST'])
def verif():
    """ Gets name and password from form  """
    username = request.form.get("username")
    password = request.form.get("password")

    """ Checks user and password. """

    userpassCheck = User.query.filter(and_(User.username == username, User.password == password)).first()
    if not userpassCheck:
        return render_template("index.html", tip="Incorrect Username or Password.")

    login_user(userpassCheck)

    return redirect(url_for('index'))

if __name__ == '__main__':
    app.run(debug=True, use_reloader=True)

The whole error traceback was:

Traceback (most recent call last):
  File "/Users/scythia/Desktop/Project1/venv/lib/python3.7/site-packages/flask/app.py", line 2464, in __call__
    return self.wsgi_app(environ, start_response)
  File "/Users/scythia/Desktop/Project1/venv/lib/python3.7/site-packages/flask/app.py", line 2450, in wsgi_app
    response = self.handle_exception(e)
  File "/Users/scythia/Desktop/Project1/venv/lib/python3.7/site-packages/flask/app.py", line 1867, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "/Users/scythia/Desktop/Project1/venv/lib/python3.7/site-packages/flask/_compat.py", line 39, in reraise
    raise value
  File "/Users/scythia/Desktop/Project1/venv/lib/python3.7/site-packages/flask/app.py", line 2447, in wsgi_app
    response = self.full_dispatch_request()
  File "/Users/scythia/Desktop/Project1/venv/lib/python3.7/site-packages/flask/app.py", line 1952, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/Users/scythia/Desktop/Project1/venv/lib/python3.7/site-packages/flask/app.py", line 1821, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/Users/scythia/Desktop/Project1/venv/lib/python3.7/site-packages/flask/_compat.py", line 39, in reraise
    raise value
  File "/Users/scythia/Desktop/Project1/venv/lib/python3.7/site-packages/flask/app.py", line 1950, in full_dispatch_request
    rv = self.dispatch_request()
  File "/Users/scythia/Desktop/Project1/venv/lib/python3.7/site-packages/flask/app.py", line 1936, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/Users/scythia/Desktop/Project1/application.py", line 54, in verif
    login_user(userpassCheck)
  File "/Users/scythia/Desktop/Project1/venv/lib/python3.7/site-packages/flask_login/utils.py", line 170, in login_user
    session['_user_id'] = user_id
  File "/Users/scythia/Desktop/Project1/venv/lib/python3.7/site-packages/werkzeug/local.py", line 350, in __setitem__
    self._get_current_object()[key] = value
  File "/Users/scythia/Desktop/Project1/venv/lib/python3.7/site-packages/flask/sessions.py", line 103, in _fail
    "The session is unavailable because no secret "
RuntimeError: The session is unavailable because no secret key was set.  Set the secret_key on the application to something unique and secret.

My expectations for the code was for it to be completely able to run. I haven't included the two HTML files because I think it is not related. I can add it if you think it is.

Using:
Python 3.7.7;
Flask 1.1.2;


问:
React: onClick on Mobile (iPhone) requires 2 taps?
Video demonstrating issue

I have a bunch of clickable components that, when clicked, adds a "card" to a row. On desktop, it works fine, but on mobile (tested on iPhone, does not seem to be an issue for Android tablet), it requires 2 consecutive taps of the same button to fire the onClick function.

These components also have onMouseEnter/onMouseLeave effects on them, to control a global state, which in turn decides if several components should have additional CSS applied (so I can't make it a simple CSS hover effect).

I believe that the mouse effects are interfering with the click event, but I have no idea how I could fix that. Here is the relevant code for this component:

```<code>const CardSource = ({ addCard, note, setHoveredNote, hoveredNote }) => {
  return (
    <Source
      onClick={() => addCard(note)}
      onMouseEnter={() => setHoveredNote(note)}
      onMouseLeave={() => setHoveredNote(null)}
      className={
        hoveredNote && hoveredNote.index === note.index ? "highlight" : null
      }
    >
      {note.letters[0]}
    </Source>
  );
};
</code>```

Furthermore, once a button has been tapped twice, the hover effect CSS "sticks" to that button, and never moves to another button. This seems to happen on both iPhone and Android tablet. I would love to have this not happen anymore either.

I've created a working demonstration of this issue in a sandbox, which if viewed on mobile you should be able to recreate these issues: https://codesandbox.io/s/mobile-requires-2-taps-i9zri?file=/src/Components/CardSource/CardSource.js

答:
You could just use css hover rather than adding a class via onMouseEnter event, It fixes the two taps issue.

Link to sandbox

If you were to programatically use trigger for hover. You could solve the two clicks issue by using onTouchEnd event (commented in sandbox).

Hope that helps.

Body:
Video demonstrating issue

I have a bunch of clickable components that, when clicked, adds a "card" to a row. On desktop, it works fine, but on mobile (tested on iPhone, does not seem to be an issue for Android tablet), it requires 2 consecutive taps of the same button to fire the onClick function.

These components also have onMouseEnter/onMouseLeave effects on them, to control a global state, which in turn decides if several components should have additional CSS applied (so I can't make it a simple CSS hover effect).

I believe that the mouse effects are interfering with the click event, but I have no idea how I could fix that. Here is the relevant code for this component:

const CardSource = ({ addCard, note, setHoveredNote, hoveredNote }) => {
  return (
    <Source
      onClick={() => addCard(note)}
      onMouseEnter={() => setHoveredNote(note)}
      onMouseLeave={() => setHoveredNote(null)}
      className={
        hoveredNote && hoveredNote.index === note.index ? "highlight" : null
      }
    >
      {note.letters[0]}
    </Source>
  );
};

Furthermore, once a button has been tapped twice, the hover effect CSS "sticks" to that button, and never moves to another button. This seems to happen on both iPhone and Android tablet. I would love to have this not happen anymore either.

I've created a working demonstration of this issue in a sandbox, which if viewed on mobile you should be able to recreate these issues: https://codesandbox.io/s/mobile-requires-2-taps-i9zri?file=/src/Components/CardSource/CardSource.js


问:
Record Date values based on another cell's value
I am a beginner in VBA.

I have a Column "A" can have multiple values, of which 2 are "Impact Assessed" or "Ready for retesting".

Problem Statement - I want to record the dates when cell's value is changed to Impact Assessed and Ready for Retesting in 2 separate columns - Column B and Column C, respectively.

Below is my code -

```<code>Private Sub Worksheet_Calculate()

Dim rng As Range
  If Target.CountLarge > 1 Then Exit Sub
Set rng = Application.Intersect(Me.Range("AA:AA"), Target)

If Not rng Is Nothing Then
    Select Case (rng.Value)
        Case "2 - Impact Assessed": rng.Offset(0, 1).Value = Date
        Case "4 - Ready for retesting": rng.Offset(0, 2).Value = Date
    End Select
End If
</code>```

End Sub

答:
I have made the code as versatile as possible. Just change the constants and, if need be, the search criteria in the Criteria variable to suit your worksheet and you can change your sheet as you like without needing to modify the code.

```<code>Private Sub Worksheet_Change(ByVal Target As Range)
    ' 040

    Const TriggerClm    As String = "A"         ' change to suit
    Const WriteToClm    As String = "B"         ' the second one is next to this

    Dim Rng             As Range                ' working range
    Dim C               As Long                 ' WriteToClm
    Dim Criteria()      As String               ' selected values from TriggerClm
    Dim i               As Integer              ' index to Criteria()

    ' don't respond to changes of multiple cells such as Paste or Delete
    If Target.CountLarge > 1 Then Exit Sub

    ' respond to changes in cells from row 2 to
    ' one cell below the last used row in the trigger column
    Set Rng = Range(Cells(2, TriggerClm), _
                    Cells(Rows.Count, TriggerClm).End(xlUp).Offset(1))

    If Not Application.Intersect(Rng, Target) Is Nothing Then
        ' intentionally all lower case because comparison
        ' is carried out case insensitive
        ' First item's date is in WriteToClm
        Criteria = Split("impact assessed,ready for retesting", ",")

        For i = UBound(Criteria) To 0 Step -1
            If StrComp(Target.Value, Criteria(i), vbTextCompare) = 0 Then Exit For
        Next i

        ' i = -1 if no match was found
        If i >= 0 Then
            C = Columns(WriteToClm).Column + i
            Cells(Target.Row, C).Value = Date
        End If
 End If
End Sub
</code>```

Body:
I am a beginner in VBA.

I have a Column "A" can have multiple values, of which 2 are "Impact Assessed" or "Ready for retesting".

Problem Statement - I want to record the dates when cell's value is changed to Impact Assessed and Ready for Retesting in 2 separate columns - Column B and Column C, respectively.

Below is my code -

Private Sub Worksheet_Calculate()

Dim rng As Range
  If Target.CountLarge > 1 Then Exit Sub
Set rng = Application.Intersect(Me.Range("AA:AA"), Target)

If Not rng Is Nothing Then
    Select Case (rng.Value)
        Case "2 - Impact Assessed": rng.Offset(0, 1).Value = Date
        Case "4 - Ready for retesting": rng.Offset(0, 2).Value = Date
    End Select
End If

End Sub

Body:
I have made the code as versatile as possible. Just change the constants and, if need be, the search criteria in the Criteria variable to suit your worksheet and you can change your sheet as you like without needing to modify the code.

Private Sub Worksheet_Change(ByVal Target As Range)
    ' 040

    Const TriggerClm    As String = "A"         ' change to suit
    Const WriteToClm    As String = "B"         ' the second one is next to this

    Dim Rng             As Range                ' working range
    Dim C               As Long                 ' WriteToClm
    Dim Criteria()      As String               ' selected values from TriggerClm
    Dim i               As Integer              ' index to Criteria()

    ' don't respond to changes of multiple cells such as Paste or Delete
    If Target.CountLarge > 1 Then Exit Sub

    ' respond to changes in cells from row 2 to
    ' one cell below the last used row in the trigger column
    Set Rng = Range(Cells(2, TriggerClm), _
                    Cells(Rows.Count, TriggerClm).End(xlUp).Offset(1))

    If Not Application.Intersect(Rng, Target) Is Nothing Then
        ' intentionally all lower case because comparison
        ' is carried out case insensitive
        ' First item's date is in WriteToClm
        Criteria = Split("impact assessed,ready for retesting", ",")

        For i = UBound(Criteria) To 0 Step -1
            If StrComp(Target.Value, Criteria(i), vbTextCompare) = 0 Then Exit For
        Next i

        ' i = -1 if no match was found
        If i >= 0 Then
            C = Columns(WriteToClm).Column + i
            Cells(Target.Row, C).Value = Date
        End If
 End If
End Sub


问:
Plotting sorted data
I would need to plot accounts through time, by sorting opening account.

I have the following two columns, one for the Accounts and one for OpenTime (it is datetime):

```<code>Account Name          OpenTime
ABC                 2002/05/20
BAB                 2012/07/24
CMN                 2012/07/24
GKS                 2001/12/05
EIR                 2018/04/21
</code>```

I would like to see on the chart Account Names in the following order:

```<code>GKS    ABC     BAB,CMN      EIR
</code>```

How can I get this result?

答:
First we need convert the date to datetime , then sort_values

```<code>df.OpenTime=pd.to_datetime(df.OpenTime)
df=df.sort_values('OpenTime')
print(df['Account Name'].tolist())
</code>```

Title: Plotting sorted data

Body:
I would need to plot accounts through time, by sorting opening account.

I have the following two columns, one for the Accounts and one for OpenTime (it is datetime):

Account Name          OpenTime
ABC                 2002/05/20
BAB                 2012/07/24
CMN                 2012/07/24
GKS                 2001/12/05
EIR                 2018/04/21

I would like to see on the chart Account Names in the following order:

GKS    ABC     BAB,CMN      EIR

How can I get this result?

Body:
First we need convert the date to datetime , then sort_values

df.OpenTime=pd.to_datetime(df.OpenTime)
df=df.sort_values('OpenTime')
print(df['Account Name'].tolist())


问:
list of regular expressions
I'm looking for a concise list of all the regular expression syntax (sort of like a cheatsheet) and I found this tool: http://erik.eae.net/playground/regexp/regexp.html

in which if you click on the question mark on the top right corner it will display some sort of dictionary of regular expressions...

my question is....is this list comprehensive or is it missing something?

if anyone knows a better list, please let me know as well

答:
http://rubular.com/ has a short cheat sheet at the bottom of the page and the great thing about that site is that you can try out the expression you are forming along with some example text to parse.  This has found lots of errors in my code and allowed my to sandbox RegEx really quickly.  </p>

<p>If the site does not respond inside 30s you may have a very poor network connection or more likely your RegRx is very inefficient or just plane invalid... I may have done that a few times.  </p>

Title: list of regular expressions

Body:
http://rubular.com/ has a short cheat sheet at the bottom of the page and the great thing about that site is that you can try out the expression you are forming along with some example text to parse.  This has found lots of errors in my code and allowed my to sandbox RegEx really quickly.

If the site does not respond inside 30s you may have a very poor network connection or more likely your RegRx is very inefficient or just plane invalid... I may have done that a few times.


问:
Android Studio tools to show CPU registers and instructions
In Eclipse with CDT we have Window->Show View->Registers and Window->Show View->Disassembly windows allowing to watch CPU instructions flow and CPU registers values. I used to use those to debug CPU and NEON code. I am able to debug native code in Eclipse, but I can't see such functionality in Android Studio (1.5.1)

Is there any plug-in or functionality available to debug CPU instruction level code under Android Studio?

答:
When your breakpoint is hit, simply click on the LLDB window, and enter disassemble to see the CPU instructions:

To see the registers, enter register read:


问:
Component not matching Store data right in Vue.js
I have an component that tries to match the route param to an array of objects in the store to see if the route name/variable is in an object and then display data from the object if it matches. However, no matter what, it returns false always. It is pulling its data from an external JS file, so could this be something with it being passed by reference rather than hard defining it?

Here is my store

```<code>import Vue from "vue";
import Vuex from "vuex";
import { productList } from "../assets/db.js";

Vue.use(Vuex);

const store = new Vuex.Store({
  state: {
    productList: productList
  },
  mutations: {},
  actions: {},
  modules: {}
});

export default store;
</code>```

Here is the function inside the component

```<code>created: function() {
        for (let type in this.$store.state.productList) {
          console.log(type.includes(this.$route.params.ptype))
        }
}
</code>```

The route is dynamic and matches ptype (this.$route.params.ptype)

However it always returns false in console. Is there something wrong with the loop? Also, if there is a better way to display data using routes like this please let me know! Thanks!

答:
We are lacking some information here, productList is supposedly an Array of Objects? then inside of your loop, type would be an Integer? Are you sure that it isnt a string?. Incase i misunderstood and productList is just an Object, then that would mean type is a string. Now, String.protoype.includes() is case-sensitive, so perhaps this is an Issue of case-sensitivity? If not i would go ahead and double check the shape of your data, perhaps youve mixed something up.

In your vue-router config, there is a flag you can set the flag per route props, if you set that to true, all params will be set as props and you can access them with this.myProp inside of your component.
You can also pass in an Object which will pass in static props.
Or you can pass a function, which takes the route object youve been using in your component as parameter to do whatever you wish with it before passing them as props.

More about that in the vue-router docs

Body:
I have an component that tries to match the route param to an array of objects in the store to see if the route name/variable is in an object and then display data from the object if it matches. However, no matter what, it returns false always. It is pulling its data from an external JS file, so could this be something with it being passed by reference rather than hard defining it?

Here is my store

import Vue from "vue";
import Vuex from "vuex";
import { productList } from "../assets/db.js";

Vue.use(Vuex);

const store = new Vuex.Store({
  state: {
    productList: productList
  },
  mutations: {},
  actions: {},
  modules: {}
});

export default store;

Here is the function inside the component

created: function() {
        for (let type in this.$store.state.productList) {
          console.log(type.includes(this.$route.params.ptype))
        }
}

The route is dynamic and matches ptype (this.$route.params.ptype)

However it always returns false in console. Is there something wrong with the loop? Also, if there is a better way to display data using routes like this please let me know! Thanks!


问:
tensorflow-gpu is not working with Blas GEMM launch failed
I installed tensorflow-gpu to run my tensorflow code on my GPU. But I can't make it run. It keeps on giving the above mentioned error. Following is my sample code followed by the error stack trace:

```<code>import tensorflow as tf
import numpy as np

def check(W,X):
    return tf.matmul(W,X)

def main():
    W = tf.Variable(tf.truncated_normal([2,3], stddev=0.01))
    X = tf.placeholder(tf.float32, [3,2])
    check_handle = check(W,X)
    with tf.Session() as sess:
        tf.initialize_all_variables().run()
        num = sess.run(check_handle, feed_dict =
            {X:np.reshape(np.arange(6), (3,2))})
        print(num)
if __name__ == '__main__':
    main()
</code>```

My GPU is pretty good GeForce GTX 1080 Ti with 11 GB vram and there is nothing else significant running on it(just chrome) as you can see in the    nvidia-smi    :

```<code>Fri Aug  4 16:34:49 2017
+-----------------------------------------------------------------------------+
| NVIDIA-SMI 381.22                 Driver Version: 381.22                    |
|-------------------------------+----------------------+----------------------+
| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|===============================+======================+======================|
|   0  GeForce GTX 108...  Off  | 0000:07:00.0      On |                  N/A |
| 30%   55C    P0    79W / 250W |    711MiB / 11169MiB |      0%      Default |
+-------------------------------+----------------------+----------------------+

+-----------------------------------------------------------------------------+
| Processes:                                                       GPU Memory |
|  GPU       PID  Type  Process name                               Usage      |
|=============================================================================|
|    0      7650    G   /usr/lib/xorg/Xorg                             380MiB |
|    0      8233    G   compiz                                         192MiB |
|    0     24226    G   ...el-token=963C169BB38ADFD67B444D57A299CE0A   136MiB |
+-----------------------------------------------------------------------------+
</code>```

Following is the error stack trace:

```<code>2017-08-04 15:44:21.585091: W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.1 instructions, but these are available on your machine and could speed up CPU computations.
2017-08-04 15:44:21.585110: W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.2 instructions, but these are available on your machine and could speed up CPU computations.
2017-08-04 15:44:21.585114: W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use AVX instructions, but these are available on your machine and could speed up CPU computations.
2017-08-04 15:44:21.585118: W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use AVX2 instructions, but these are available on your machine and could speed up CPU computations.
2017-08-04 15:44:21.585122: W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use FMA instructions, but these are available on your machine and could speed up CPU computations.
2017-08-04 15:44:21.853700: I tensorflow/core/common_runtime/gpu/gpu_device.cc:940] Found device 0 with properties:
name: GeForce GTX 1080 Ti
major: 6 minor: 1 memoryClockRate (GHz) 1.582
pciBusID 0000:07:00.0
Total memory: 10.91GiB
Free memory: 9.89GiB
2017-08-04 15:44:21.853724: I tensorflow/core/common_runtime/gpu/gpu_device.cc:961] DMA: 0
2017-08-04 15:44:21.853728: I tensorflow/core/common_runtime/gpu/gpu_device.cc:971] 0:   Y
2017-08-04 15:44:21.853734: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1030] Creating TensorFlow device (/gpu:0) -> (device: 0, name: GeForce GTX 1080 Ti, pci bus id: 0000:07:00.0)
2017-08-04 15:44:24.948616: E tensorflow/stream_executor/cuda/cuda_blas.cc:365] failed to create cublas handle: CUBLAS_STATUS_NOT_INITIALIZED
2017-08-04 15:44:24.948640: W tensorflow/stream_executor/stream.cc:1601] attempting to perform BLAS operation using StreamExecutor without BLAS support
2017-08-04 15:44:24.948805: W tensorflow/core/framework/op_kernel.cc:1158] Internal: Blas GEMM launch failed : a.shape=(1, 5), b.shape=(5, 10), m=1, n=10, k=5
     [[Node: layer1/MatMul = MatMul[T=DT_FLOAT, transpose_a=false, transpose_b=false, _device="/job:localhost/replica:0/task:0/gpu:0"](_arg_Placeholder_0_0/_11, layer1/weights/read)]]
Traceback (most recent call last):
  File "test.py", line 51, in <module>
    _, loss_out, res_out = sess.run([train_op, loss, res], feed_dict)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 789, in run
    run_metadata_ptr)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 997, in _run
    feed_dict_string, options, run_metadata)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 1132, in _do_run
    target_list, options, run_metadata)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 1152, in _do_call
    raise type(e)(node_def, op, message)
tensorflow.python.framework.errors_impl.InternalError: Blas GEMM launch failed : a.shape=(1, 5), b.shape=(5, 10), m=1, n=10, k=5
     [[Node: layer1/MatMul = MatMul[T=DT_FLOAT, transpose_a=false, transpose_b=false, _device="/job:localhost/replica:0/task:0/gpu:0"](_arg_Placeholder_0_0/_11, layer1/weights/read)]]
     [[Node: layer2/MatMul/_17 = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/cpu:0", send_device="/job:localhost/replica:0/task:0/gpu:0", send_device_incarnation=1, tensor_name="edge_158_layer2/MatMul", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/cpu:0"]()]]

Caused by op u'layer1/MatMul', defined at:
  File "test.py", line 18, in <module>
    pre_activation = tf.matmul(input_ph, weights)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/math_ops.py", line 1816, in matmul
    a, b, transpose_a=transpose_a, transpose_b=transpose_b, name=name)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/gen_math_ops.py", line 1217, in _mat_mul
    transpose_b=transpose_b, name=name)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/op_def_library.py", line 767, in apply_op
    op_def=op_def)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 2506, in create_op
    original_op=self._default_original_op, op_def=op_def)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 1269, in __init__
    self._traceback = _extract_stack()

InternalError (see above for traceback): Blas GEMM launch failed : a.shape=(1, 5), b.shape=(5, 10), m=1, n=10, k=5
     [[Node: layer1/MatMul = MatMul[T=DT_FLOAT, transpose_a=false, transpose_b=false, _device="/job:localhost/replica:0/task:0/gpu:0"](_arg_Placeholder_0_0/_11, layer1/weights/read)]]
     [[Node: layer2/MatMul/_17 = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/cpu:0", send_device="/job:localhost/replica:0/task:0/gpu:0", send_device_incarnation=1, tensor_name="edge_158_layer2/MatMul", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/cpu:0"]()]]
</code>```

To add to it, my previous installation of tensorflow cpu worked pretty well. Any help is appreciated. Thanks!

Note-  I have cuda-8.0 with cudnn-5.1 installed and their paths added in my bashrc profile .

答: Installing the right NVIDIA driver and CUDA versions for the my NVIDIA graphics card(For eg. NVIDIA RTX 2070 in my case) worked for me.</p>

Body:
I installed tensorflow-gpu to run my tensorflow code on my GPU. But I can't make it run. It keeps on giving the above mentioned error. Following is my sample code followed by the error stack trace:

import tensorflow as tf
import numpy as np

def check(W,X):
    return tf.matmul(W,X)

def main():
    W = tf.Variable(tf.truncated_normal([2,3], stddev=0.01))
    X = tf.placeholder(tf.float32, [3,2])
    check_handle = check(W,X)
    with tf.Session() as sess:
        tf.initialize_all_variables().run()
        num = sess.run(check_handle, feed_dict =
            {X:np.reshape(np.arange(6), (3,2))})
        print(num)
if __name__ == '__main__':
    main()

My GPU is pretty good GeForce GTX 1080 Ti with 11 GB vram and there is nothing else significant running on it(just chrome) as you can see in the    nvidia-smi    :

Fri Aug  4 16:34:49 2017
+-----------------------------------------------------------------------------+
| NVIDIA-SMI 381.22                 Driver Version: 381.22                    |
|-------------------------------+----------------------+----------------------+
| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|===============================+======================+======================|
|   0  GeForce GTX 108...  Off  | 0000:07:00.0      On |                  N/A |
| 30%   55C    P0    79W / 250W |    711MiB / 11169MiB |      0%      Default |
+-------------------------------+----------------------+----------------------+

+-----------------------------------------------------------------------------+
| Processes:                                                       GPU Memory |
|  GPU       PID  Type  Process name                               Usage      |
|=============================================================================|
|    0      7650    G   /usr/lib/xorg/Xorg                             380MiB |
|    0      8233    G   compiz                                         192MiB |
|    0     24226    G   ...el-token=963C169BB38ADFD67B444D57A299CE0A   136MiB |
+-----------------------------------------------------------------------------+

Following is the error stack trace:

2017-08-04 15:44:21.585091: W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.1 instructions, but these are available on your machine and could speed up CPU computations.
2017-08-04 15:44:21.585110: W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.2 instructions, but these are available on your machine and could speed up CPU computations.
2017-08-04 15:44:21.585114: W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use AVX instructions, but these are available on your machine and could speed up CPU computations.
2017-08-04 15:44:21.585118: W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use AVX2 instructions, but these are available on your machine and could speed up CPU computations.
2017-08-04 15:44:21.585122: W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use FMA instructions, but these are available on your machine and could speed up CPU computations.
2017-08-04 15:44:21.853700: I tensorflow/core/common_runtime/gpu/gpu_device.cc:940] Found device 0 with properties:
name: GeForce GTX 1080 Ti
major: 6 minor: 1 memoryClockRate (GHz) 1.582
pciBusID 0000:07:00.0
Total memory: 10.91GiB
Free memory: 9.89GiB
2017-08-04 15:44:21.853724: I tensorflow/core/common_runtime/gpu/gpu_device.cc:961] DMA: 0
2017-08-04 15:44:21.853728: I tensorflow/core/common_runtime/gpu/gpu_device.cc:971] 0:   Y
2017-08-04 15:44:21.853734: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1030] Creating TensorFlow device (/gpu:0) -> (device: 0, name: GeForce GTX 1080 Ti, pci bus id: 0000:07:00.0)
2017-08-04 15:44:24.948616: E tensorflow/stream_executor/cuda/cuda_blas.cc:365] failed to create cublas handle: CUBLAS_STATUS_NOT_INITIALIZED
2017-08-04 15:44:24.948640: W tensorflow/stream_executor/stream.cc:1601] attempting to perform BLAS operation using StreamExecutor without BLAS support
2017-08-04 15:44:24.948805: W tensorflow/core/framework/op_kernel.cc:1158] Internal: Blas GEMM launch failed : a.shape=(1, 5), b.shape=(5, 10), m=1, n=10, k=5
     [[Node: layer1/MatMul = MatMul[T=DT_FLOAT, transpose_a=false, transpose_b=false, _device="/job:localhost/replica:0/task:0/gpu:0"](_arg_Placeholder_0_0/_11, layer1/weights/read)]]
Traceback (most recent call last):
  File "test.py", line 51, in <module>
    _, loss_out, res_out = sess.run([train_op, loss, res], feed_dict)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 789, in run
    run_metadata_ptr)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 997, in _run
    feed_dict_string, options, run_metadata)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 1132, in _do_run
    target_list, options, run_metadata)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 1152, in _do_call
    raise type(e)(node_def, op, message)
tensorflow.python.framework.errors_impl.InternalError: Blas GEMM launch failed : a.shape=(1, 5), b.shape=(5, 10), m=1, n=10, k=5
     [[Node: layer1/MatMul = MatMul[T=DT_FLOAT, transpose_a=false, transpose_b=false, _device="/job:localhost/replica:0/task:0/gpu:0"](_arg_Placeholder_0_0/_11, layer1/weights/read)]]
     [[Node: layer2/MatMul/_17 = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/cpu:0", send_device="/job:localhost/replica:0/task:0/gpu:0", send_device_incarnation=1, tensor_name="edge_158_layer2/MatMul", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/cpu:0"]()]]

Caused by op u'layer1/MatMul', defined at:
  File "test.py", line 18, in <module>
    pre_activation = tf.matmul(input_ph, weights)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/math_ops.py", line 1816, in matmul
    a, b, transpose_a=transpose_a, transpose_b=transpose_b, name=name)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/gen_math_ops.py", line 1217, in _mat_mul
    transpose_b=transpose_b, name=name)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/op_def_library.py", line 767, in apply_op
    op_def=op_def)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 2506, in create_op
    original_op=self._default_original_op, op_def=op_def)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 1269, in __init__
    self._traceback = _extract_stack()

InternalError (see above for traceback): Blas GEMM launch failed : a.shape=(1, 5), b.shape=(5, 10), m=1, n=10, k=5
     [[Node: layer1/MatMul = MatMul[T=DT_FLOAT, transpose_a=false, transpose_b=false, _device="/job:localhost/replica:0/task:0/gpu:0"](_arg_Placeholder_0_0/_11, layer1/weights/read)]]
     [[Node: layer2/MatMul/_17 = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/cpu:0", send_device="/job:localhost/replica:0/task:0/gpu:0", send_device_incarnation=1, tensor_name="edge_158_layer2/MatMul", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/cpu:0"]()]]

To add to it, my previous installation of tensorflow cpu worked pretty well. Any help is appreciated. Thanks!

Note-  I have cuda-8.0 with cudnn-5.1 installed and their paths added in my bashrc profile .


问:
are there any pitfalls to using lockfile over sshfs?
I have inherited a project that involves setting up a test environment (based on amazon ec2 instances).

Here's the architecture:

A single always-on instance contains a folder foo that contains various setup scripts;

N other instances are booted on demand. N can be anything from 10 to 1000;

These N instances, at boot time, mount "foo" over sshfs;

They then run various setup (bash) scripts - one of which writes to a common {{/etc/hosts}} file.

One logical concern is that the N instances could hit some kind of race condition while writing to the same file concurrently. So I want to do some kind of file-locking. I found out about lockfile but I do not know enough about sshfs or file-locking.

So:

Are there any possible pitfalls to using lockfile on a file mounted over sshfs? I have not found any literature online for/against this.

Any suggestions to completely avoid this situation altogether?

答: A simple test with mounting a directory over sshfs and locking a file therein and then locking the same file on the host server showed me that the LOCK IS NOT RECOGNIZED.  Now the disclaimer is that I am using perl on both machines, and I am not 100% certain what it is using as flock() since the documentation says that it uses a variety of OS calls.  I am however using the same OS, ubuntu 20.04 and the same perl, 5.30.</p>


问:
Javascript object retaining "old" properties, can't override?
I have the following code:

```<code>    const readDataFromSql = () => {
        // going to have to iterate through all known activities + load them here
        let sql = "[...]"
        return new Promise((resolve, reject) => {
            executeSqlQuery(sql).then((dict) => {
                let loadedData = [];
                for (let key in dict) {
                    let newItemVal = new ItemVal("reading hw", 7121, progress.DONE);
                    loadedData.push(newItemVal);
                }
                resolve(loadedData);
            });
        });
    }
</code>```

ItemVal implementation:

```<code>class ItemVal {
   constructor(name, time, type) {
      this.name = name
      this.time = time
      this.type = type
   }
}
</code>```

Let's assume that newItemVal = "reading hwj", 5081, progress.PAUSED when readDataFromSql() first runs.

readDataFromSql() is then again called after some state changes -- where it repulls some information from a database and generates new values. What is perplexing, however, is that when it is called the second time, newItemVal still retains its old properties (attaching screenshot below).

Am I misusing the new keyword?

答:
```<code>const readDataFromSql = async () => {
        let sql = "[...]"
------> await executeSqlQuery(sql).then((dict) => {
</code>```

Use the await keyword instead of creating a new promise.

Body:
I have the following code:

    const readDataFromSql = () => {
        // going to have to iterate through all known activities + load them here
        let sql = "[...]"
        return new Promise((resolve, reject) => {
            executeSqlQuery(sql).then((dict) => {
                let loadedData = [];
                for (let key in dict) {
                    let newItemVal = new ItemVal("reading hw", 7121, progress.DONE);
                    loadedData.push(newItemVal);
                }
                resolve(loadedData);
            });
        });
    }

ItemVal implementation:

class ItemVal {
   constructor(name, time, type) {
      this.name = name
      this.time = time
      this.type = type
   }
}

Let's assume that newItemVal = "reading hwj", 5081, progress.PAUSED when readDataFromSql() first runs.

readDataFromSql() is then again called after some state changes -- where it repulls some information from a database and generates new values. What is perplexing, however, is that when it is called the second time, newItemVal still retains its old properties (attaching screenshot below).

Am I misusing the new keyword?

Body:
const readDataFromSql = async () => {
        let sql = "[...]"
------> await executeSqlQuery(sql).then((dict) => {

Use the await keyword instead of creating a new promise.


问:
Check if a file exists in azure blob container
I have an azure blob container name "x" and I want to check if a file name "a.jpg" exists in that blob or not and return true or false based on that. It seems easy but there isn't a clear answer when I google it.</p>

答:
You can also use REST Api if you want.

https://learn.microsoft.com/en-us/rest/api/storageservices/get-blob-metadata

A lot more trouble... but works too.

Request The Get Blob Metadata request may be constructed as follows.
  HTTPS is recommended. Replace myaccount with the name of your storage
  account:

TABLE 1 GET or HEAD Method Request URI    HTTP Version
  https://myaccount.blob.core.windows.net/mycontainer/myblob?comp=metadata

https://myaccount.blob.core.windows.net/mycontainer/myblob?comp=metadata&snapshot=


问:
useEffect causing infinite loop
I have looked at every infinite loop answer in SO and I cannot figure out what I'm doing wrong.

I'm trying to fetch some data and set my productList state with the data but it causes an infinite loop.

```<code>export default (props) => {
  const [productsList, setProductsList] = useState([]);

  const getProducts = async () => {
    try {
      await axios
        .get("https://api.stripe.com/v1/skus", {
          headers: {
            "Content-Type": "application/json",
            Authorization: `Bearer ${StripeKey}`,
          },
        })
        .then(({ data }) => {
          setProductsList(data.data);
        });
    } catch {
      (error) => {
        console.log(error);
      };
    }
  };

  useEffect(() => {
    getProducts();
  }, [productList]);

  return (
    <ProductsContext.Provider value={{ products: productsList }}>
      {props.children}
    </ProductsContext.Provider>
  );
};

</code>```

I have also tried with having an empty array at the end of useEffect and that causes it to not set the state at all.

What am I missing?

EDIT:

I removed the try/catch and [productList] from useEffect

```<code>import React, { useState, useEffect } from "react";
import axios from "axios";

const StripeKey = "TEST_KEY";

export const ProductsContext = React.createContext({ products: [] });

export default (props) => {
  const [productsList, setProductsList] = useState([]);

  useEffect(() => {
    axios({
      method: "get",
      url: "https://api.stripe.com/v1/skus",
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${StripeKey}`,
      },
    })
      .then((response) => {
        setProductsList(response.data.data)
      })
      .catch((error) => {
        console.log(error);
      });
  }, []);

  return (
    <ProductsContext.Provider value={{ products: productsList }}>
      {props.children}
    </ProductsContext.Provider>
  );
};
</code>```

答:
About how you fetch your data:
I think the problem might be on how you are fetching data:

As stated in docs I think you should not be using try catch here, but something like:

```<code>function MyComponent() {
  const [error, setError] = useState(null);
  const [isLoaded, setIsLoaded] = useState(false);
  const [items, setItems] = useState([]);

  // Note: the empty deps array [] means
  // this useEffect will run once
  // similar to componentDidMount()
  useEffect(() => {
    fetch("https://api.example.com/items")
      .then(res => res.json())
      .then(
        (result) => {
          setIsLoaded(true);
          setItems(result.items);
        },
        // Note: it's important to handle errors here
        // instead of a catch() block so that we don't swallow
        // exceptions from actual bugs in components.
        (error) => {
          setIsLoaded(true);
          setError(error);
        }
      )
  }, [])

  if (error) {
    return <div>Error: {error.message}</div>;
  } else if (!isLoaded) {
    return <div>Loading...</div>;
  } else {
    return (
      <ul>
        {items.map(item => (
          <li key={item.name}>
            {item.name} {item.price}
          </li>
        ))}
      </ul>
    );
  }
}
</code>```

About the useEffect callback:

I don't think you should use [productList] as its the item you are updating, so it would trigger again once you do the setProducts. You might want to do the fetching again when a prop of the request changes or just on component did mount (empty array as you said)

Also, there might be other side effects we cannot see with that sample of code. Maybe you could share an stackblitz to be sure

Title: useEffect causing infinite loop

Body:
I have looked at every infinite loop answer in SO and I cannot figure out what I'm doing wrong.

I'm trying to fetch some data and set my productList state with the data but it causes an infinite loop.

export default (props) => {
  const [productsList, setProductsList] = useState([]);

  const getProducts = async () => {
    try {
      await axios
        .get("https://api.stripe.com/v1/skus", {
          headers: {
            "Content-Type": "application/json",
            Authorization: `Bearer ${StripeKey}`,
          },
        })
        .then(({ data }) => {
          setProductsList(data.data);
        });
    } catch {
      (error) => {
        console.log(error);
      };
    }
  };

  useEffect(() => {
    getProducts();
  }, [productList]);

  return (
    <ProductsContext.Provider value={{ products: productsList }}>
      {props.children}
    </ProductsContext.Provider>
  );
};

I have also tried with having an empty array at the end of useEffect and that causes it to not set the state at all.

What am I missing?

EDIT:

I removed the try/catch and [productList] from useEffect

import React, { useState, useEffect } from "react";
import axios from "axios";

const StripeKey = "TEST_KEY";

export const ProductsContext = React.createContext({ products: [] });

export default (props) => {
  const [productsList, setProductsList] = useState([]);

  useEffect(() => {
    axios({
      method: "get",
      url: "https://api.stripe.com/v1/skus",
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${StripeKey}`,
      },
    })
      .then((response) => {
        setProductsList(response.data.data)
      })
      .catch((error) => {
        console.log(error);
      });
  }, []);

  return (
    <ProductsContext.Provider value={{ products: productsList }}>
      {props.children}
    </ProductsContext.Provider>
  );
};

Body:
About how you fetch your data:
I think the problem might be on how you are fetching data:

As stated in docs I think you should not be using try catch here, but something like:

function MyComponent() {
  const [error, setError] = useState(null);
  const [isLoaded, setIsLoaded] = useState(false);
  const [items, setItems] = useState([]);

  // Note: the empty deps array [] means
  // this useEffect will run once
  // similar to componentDidMount()
  useEffect(() => {
    fetch("https://api.example.com/items")
      .then(res => res.json())
      .then(
        (result) => {
          setIsLoaded(true);
          setItems(result.items);
        },
        // Note: it's important to handle errors here
        // instead of a catch() block so that we don't swallow
        // exceptions from actual bugs in components.
        (error) => {
          setIsLoaded(true);
          setError(error);
        }
      )
  }, [])

  if (error) {
    return <div>Error: {error.message}</div>;
  } else if (!isLoaded) {
    return <div>Loading...</div>;
  } else {
    return (
      <ul>
        {items.map(item => (
          <li key={item.name}>
            {item.name} {item.price}
          </li>
        ))}
      </ul>
    );
  }
}

About the useEffect callback:

I don't think you should use [productList] as its the item you are updating, so it would trigger again once you do the setProducts. You might want to do the fetching again when a prop of the request changes or just on component did mount (empty array as you said)

Also, there might be other side effects we cannot see with that sample of code. Maybe you could share an stackblitz to be sure


问:
When to use pkg_check_modules as a fallback to find<package>?
I use find<package> to probe for packages (ZLIB, PNG, ...) and pkg_check_modules as a fallback if FindPackage fails to set up a superbuild with external dependencies:

```<code>find_package(PkgConfig)

## find_package(ZLIB) is a bit redundant; find_package(PNG) seems to probe for ZLIB
## in newer versions of FindPNG.cmake...
find_package(ZLIB)
find_package(PNG)

if (PKG_CONFIG_FOUND)
    if (NOT ZLIB_FOUND)
        pkg_check_modules(ZLIB IMPORTED_TARGET zlib)
    endif (NOT ZLIB_FOUND)
    if (NOT PNG_FOUND)
        pkg_check_modules(PNG IMPORTED_TARGET libpng)
    endif (NOT PNG_FOUND)
endif ()

if (NOT ZLIB_FOUND)
    ## Set up external project dependency build
else ()
    ## Found it, incorporate into target's link stage
endif ()
</code>```

The problem is when MinGWw64 is installed and CMake uses the VS2019 compiler -- pkg_check_modules finds MinGWw64's zlib, which can't be used due to the different library naming convention.

I've added MSVC to the condition, since this seems to only impact MSVC-based builds:

```<code>if (PKG_CONFIG_FOUND AND NOT (MSVC))
    # ...
endif()
</code>```

Since I'm aiming to be as cross-platform as possible (*nix, MSVC, MinGW), is there a better way to fall back to pkg_check_modules when find<package> doesn't succeed? Or should I avoid pkg_check_modules altogether?

答: Avoid stupid: Let find_package do the work, as some Find<package>.cmake scripts (recipes) use PkgConfig.cmake internally as a fallback.

Body:
I use find<package> to probe for packages (ZLIB, PNG, ...) and pkg_check_modules as a fallback if FindPackage fails to set up a superbuild with external dependencies:

find_package(PkgConfig)

## find_package(ZLIB) is a bit redundant; find_package(PNG) seems to probe for ZLIB
## in newer versions of FindPNG.cmake...
find_package(ZLIB)
find_package(PNG)

if (PKG_CONFIG_FOUND)
    if (NOT ZLIB_FOUND)
        pkg_check_modules(ZLIB IMPORTED_TARGET zlib)
    endif (NOT ZLIB_FOUND)
    if (NOT PNG_FOUND)
        pkg_check_modules(PNG IMPORTED_TARGET libpng)
    endif (NOT PNG_FOUND)
endif ()

if (NOT ZLIB_FOUND)
    ## Set up external project dependency build
else ()
    ## Found it, incorporate into target's link stage
endif ()

The problem is when MinGWw64 is installed and CMake uses the VS2019 compiler -- pkg_check_modules finds MinGWw64's zlib, which can't be used due to the different library naming convention.

I've added MSVC to the condition, since this seems to only impact MSVC-based builds:

if (PKG_CONFIG_FOUND AND NOT (MSVC))
    # ...
endif()

Since I'm aiming to be as cross-platform as possible (*nix, MSVC, MinGW), is there a better way to fall back to pkg_check_modules when find<package> doesn't succeed? Or should I avoid pkg_check_modules altogether?


问:
Select specific levels of factor in R
I imagine this is a relatively simple issue for this audience, at least it would be for me had I still been working with SAS...
I have a character factor ("Trap") with 15 levels and I only want 3 of those levels (Weka, Rat, Stoat) for a data frame I want to summarize/analyze.  I don't want to use droplevels and have to write-out every level I DON'T want in the data frame, but I can't seem to get the coding right to select just the levels I want.  Please help.  Here's what I've most recently tried, to no avail. Any help would be greatly appreciated.

```<code>CatchbySpecies <- CatchbySpecies [!CatchbySpecies$Trap == "Weka", "Rat", "Stoat"]
</code>```

答:
Should you want to explore data.table. This will reduce your code significantly

```<code>library(data.table)
CatchbySpecies <- CatchbySpecies[Trap %in% c("Weka", "Rat", "Stoat")]
</code>```

You can subset your rows similar to a data.frame

Title: Select specific levels of factor in R

Body:
I imagine this is a relatively simple issue for this audience, at least it would be for me had I still been working with SAS...
I have a character factor ("Trap") with 15 levels and I only want 3 of those levels (Weka, Rat, Stoat) for a data frame I want to summarize/analyze.  I don't want to use droplevels and have to write-out every level I DON'T want in the data frame, but I can't seem to get the coding right to select just the levels I want.  Please help.  Here's what I've most recently tried, to no avail. Any help would be greatly appreciated.

CatchbySpecies <- CatchbySpecies [!CatchbySpecies$Trap == "Weka", "Rat", "Stoat"]

Body:
Should you want to explore data.table. This will reduce your code significantly

library(data.table)
CatchbySpecies <- CatchbySpecies[Trap %in% c("Weka", "Rat", "Stoat")]

You can subset your rows similar to a data.frame


问:
Traversing DOM with javascript
I have a piece of HTML like this:

```<code><div id="contentblock">
    <div id="producttile_137" class="producttile">
        <a href="#" class="tile">
        <img src="images/Bony A-Booster.jpg" alt="Bony A-Booster - 50 ml">
            Bony A-Booster
            <span class="price">€10.95</span>
        </a>
    </div>
    <div id="producttile_138" class="producttile">
        <a href="#" class="tile">
        <img src="images/Bony B-Booster.jpg" blt="Bony B-Booster - 50 ml">
            Bony B-Booster
            <span class="price">€20.95</span>
        </a>
    </div>
    <div>Aditional info</div>
</div>
</code>```

I need to get all  sources but with pure Javascript. I can get element by class name document.getElementsByClassName('producttile') but is it possible to traversing in pure JS to  ang get src="" value?

答:
You can use document.getElementsByTagName() to fetch all the img tags as a HTMLCollection. And then, you can iterate over the HTMLCollection and get the src attribute value by using getAttribute() method as below:

const imgElements = document.getElementsByTagName("img");

Array.from(imgElements).forEach(function(element){
  console.log(element.getAttribute("src"));
});
```

Title: Traversing DOM with javascript

Body:
I have a piece of HTML like this:

            Bony A-Booster
            €10.95

            Bony B-Booster
            €20.95

Aditional info

I need to get all  sources but with pure Javascript. I can get element by class name document.getElementsByClassName('producttile') but is it possible to traversing in pure JS to  ang get src="" value?


问:
Kube-aws: Template format error: Unresolved resource dependencies [IAMRoleController]
I'm using kube-aws v0.15.2 to setup a Kubernetes cluster in AWS. I have predefined IAM roles and instance profiles for controller, etcd and workers. I have another cluster that is using the same IAM roles and instance profiles which was created using kube-aws v0.9.x. With the newly generated cluster.yaml I generated certs and rendered stack. But while performing validate I'm getting the following error:

```<code>$ kube-aws validate
Validating UserData and stack template...
generating assets for control-plane, network, etcd, nodepoolA
Error: failed to validate control plane: invalid cloudformation stack template https://s3.amazonaws.com/.../mycluster/exported/stacks/control-plane/stack.json:
ValidationError: Template format error: Unresolved resource dependencies [IAMRoleController] in the Resources block of the template
</code>```

In cluster.yaml, IAM block of controller would look like this:

```<code> iam:
#    role:
#      name: "yourManagedRole"
#      # strictName: true
     manageExternally: true
#      managedPolicies:
#      - arn: "arn:aws:iam::aws:policy/AdministratorAccess"
#      - arn: "arn:aws:iam::YOURACCOUNTID:policy/YOURPOLICYNAME"
     instanceProfile:
       arn: "arn:aws:iam::xxxxxx:instance-profile/MyKubernetesIAMInstanceProfileController"
</code>```

Addons like kube2iam, kiam etc are disabled.

Please let me know how to fix it.

Thanks in advance

答:
It looks like kube-aws will target the fix for 0.16.2 and 0.15.3 as well.

Created ticket in github: https://github.com/kubernetes-incubator/kube-aws/issues/1855

Body:
I'm using kube-aws v0.15.2 to setup a Kubernetes cluster in AWS. I have predefined IAM roles and instance profiles for controller, etcd and workers. I have another cluster that is using the same IAM roles and instance profiles which was created using kube-aws v0.9.x. With the newly generated cluster.yaml I generated certs and rendered stack. But while performing validate I'm getting the following error:

$ kube-aws validate
Validating UserData and stack template...
generating assets for control-plane, network, etcd, nodepoolA
Error: failed to validate control plane: invalid cloudformation stack template https://s3.amazonaws.com/.../mycluster/exported/stacks/control-plane/stack.json:
ValidationError: Template format error: Unresolved resource dependencies [IAMRoleController] in the Resources block of the template

In cluster.yaml, IAM block of controller would look like this:

 iam:
#    role:
#      name: "yourManagedRole"
#      # strictName: true
     manageExternally: true
#      managedPolicies:
#      - arn: "arn:aws:iam::aws:policy/AdministratorAccess"
#      - arn: "arn:aws:iam::YOURACCOUNTID:policy/YOURPOLICYNAME"
     instanceProfile:
       arn: "arn:aws:iam::xxxxxx:instance-profile/MyKubernetesIAMInstanceProfileController"

Addons like kube2iam, kiam etc are disabled.

Please let me know how to fix it.

Thanks in advance


问:
Can someone explain what will happen in the following function if the array is out of index?
```<code>function remove(items, item){
    for (let i =0; i < items.length; i++) {
        if (items[i] === item){
            return [ ...items.slice(0, i), ...items.slice(i+1)]
        }
    }
}
</code>```

My code is above. I'm curious about the return statement.

答:
function remove(items, item) {
  for (let i = 0; i < items.length; i++) {
    if (items[i] === item) {
      return items.slice(0, i).concat(items.slice(i + 1, items.length));
    }
  }
}```

Body:
function remove(items, item){
    for (let i =0; i < items.length; i++) {
        if (items[i] === item){
            return [ ...items.slice(0, i), ...items.slice(i+1)]
        }
    }
}

My code is above. I'm curious about the return statement.


问:
Detect multiple zeroes in a string
I have a list of numbers coming in mostly looking like this: 1234567912345.

But some of them have a big number of zeroes both before and after the usual number.
Making them look like this: "000000001765032019308000000".
For the moment I will call them special numbers.

My initial try was using strpos to check if it contains "00000" which should be enough to confirm that this is indeed one of the special numbers but that doesn't work.

It's also not possible to just check the length of the number.

So my question is, how do I detect if a number is one the special numbers?

Title: Detect multiple zeroes in a string

Body:
You can use preg_match to determine whether there are 6-8 0's at the beginning and end of the number:

$numbers = array('1234567912345', '000000001765032019308000000',
                 '000000000000445000000', '0000004000000');

foreach ($numbers as $num) {
    echo "$num is " . (preg_match('/^0{6,8}[1-9](\d*[1-9])?0{6,8}$/', $num) ? '' : 'not ') . "special\n";
}

Output:

1234567912345 is not special
000000001765032019308000000 is special
000000000000445000000 is not special
0000004000000 is special


问:
NiFi - New attribute to create a new one with a previous attribute + harcoded text
I'm trying to add a new "attributeX" to create an URL (using UpdateAttribute). This URL will be like this:
Part 1: harcoded value (eg.: "www.google.com/")
Part 2: evaluate attribute 1; if empty, use attribute 2: if not, use attribute 1.
Part 3: harcoded value (eg.: "/tests/")
Part 4: attribute3

Attributes 1,2 and 3 are present in the flow file from previous processors.
So, my goal is to get an url like this:
www.google.com/attribute1 OR attribute2/tests/attribute3

BUT; this "attributeX" needs a condition: if attribute3 is empty, I need to set the value as "empty": if NOT empty, I need to create that URL.

I was trying with regex expression but I couldn't get this done. My "isEmpty" and "ifElse" evaluations fails when I'm trying to set the the "ifElse" with harcoded values+attributes.

Any help is much appreciated, thanks in advance!

EDIT: I didn't specify any of my tests because I did a lot of attempts and couldn't get the expected attribute.
I'm trying to do something like this:

```<code>${attributeA:isEmpty():ifElse(${literal("")},hardcodedText+${attributeB}+${attributeA})}
</code>```

The expression works fine until the argument after the comma; if I use only 1 attribute/variable it works fine; but if I try with more than 1 attribute it's not recognized as as valid expression.

答:
As long as all of the component attributes are defined prior to this expression (i.e. populated in an earlier component, or empty is ok), you can use an expression like this:

${attributeA:isEmpty():ifElse(${literal("")},${literal("hardcodedText"):append(${attributeB}):append(${attributeA})})}

The problems with the statement you tried (offered for learning, not criticism of what you tried):

attributeA:isEmpty():ifElse(${literal(""),...} has a secondary clause which uses raw string concatenation, which is not supported by Apache NiFi Expression Language. You need to use the append() function here, or string interpolation outside of a clause (i.e. if attributeA = x and attributeB = y,  ${attributeA}_${attributeB} -> x_y).

When multiple "clauses" are combined, each needs the expression language syntax of ${} to denote the clause so it can be interpreted. Otherwise it can be registered as a "token" which is unknown. So in the above case, you have multiple levels of EL clauses (in pseudocode for succinctness):

```<code>if (attributeA is empty) { (1)
    use "" (2)
} else {
    use "hardcodedText" + attributeB + attributeA (3)
}
</code>```

Expression 3 is where additional EL clauses are necessary.

If the elements you were combining were all attributes, you could use the ${allAttributes(attributeA, attributeB, ...):join("")} construction as well.

Body:
I'm trying to add a new "attributeX" to create an URL (using UpdateAttribute). This URL will be like this:
Part 1: harcoded value (eg.: "www.google.com/")
Part 2: evaluate attribute 1; if empty, use attribute 2: if not, use attribute 1.
Part 3: harcoded value (eg.: "/tests/")
Part 4: attribute3

Attributes 1,2 and 3 are present in the flow file from previous processors.
So, my goal is to get an url like this:
www.google.com/attribute1 OR attribute2/tests/attribute3

BUT; this "attributeX" needs a condition: if attribute3 is empty, I need to set the value as "empty": if NOT empty, I need to create that URL.

I was trying with regex expression but I couldn't get this done. My "isEmpty" and "ifElse" evaluations fails when I'm trying to set the the "ifElse" with harcoded values+attributes.

Any help is much appreciated, thanks in advance!

EDIT: I didn't specify any of my tests because I did a lot of attempts and couldn't get the expected attribute.
I'm trying to do something like this:

${attributeA:isEmpty():ifElse(${literal("")},hardcodedText+${attributeB}+${attributeA})}

The expression works fine until the argument after the comma; if I use only 1 attribute/variable it works fine; but if I try with more than 1 attribute it's not recognized as as valid expression.

Body:
As long as all of the component attributes are defined prior to this expression (i.e. populated in an earlier component, or empty is ok), you can use an expression like this:

${attributeA:isEmpty():ifElse(${literal("")},${literal("hardcodedText"):append(${attributeB}):append(${attributeA})})}

The problems with the statement you tried (offered for learning, not criticism of what you tried):

attributeA:isEmpty():ifElse(${literal(""),...} has a secondary clause which uses raw string concatenation, which is not supported by Apache NiFi Expression Language. You need to use the append() function here, or string interpolation outside of a clause (i.e. if attributeA = x and attributeB = y,  ${attributeA}_${attributeB} -> x_y).

When multiple "clauses" are combined, each needs the expression language syntax of ${} to denote the clause so it can be interpreted. Otherwise it can be registered as a "token" which is unknown. So in the above case, you have multiple levels of EL clauses (in pseudocode for succinctness):

if (attributeA is empty) { (1)
    use "" (2)
} else {
    use "hardcodedText" + attributeB + attributeA (3)
}

Expression 3 is where additional EL clauses are necessary.

If the elements you were combining were all attributes, you could use the ${allAttributes(attributeA, attributeB, ...):join("")} construction as well.


问:
Need explanation for C++ code
```<code>namespace Stack {
  struct Rep; // definition of stack layout is elsewhere
  typedef Rep& stack;
  stack create(); // make a new stack
  void destroy(stack s); // delete s
  void push(stack s, char c); // push c onto s
  char pop(stack s); // pop s
}
</code>```

This is in the "A Tour of C++" Unit, before even the basic material like functions, loops, and fundamental datatypes...I don't know if/how I'm supposed to understand this code or not.

Anyway, can someone please explain it? It's supposed to be part of an explanation on how to "define a stack manager with an interface"

For starters, I specifically don't know what "typedef Rep& stack" means.

答:
typedef Rep& stack means that stack will be a synonym for Rep&. So instead of

```<code>Rep &r;
</code>```

you can write

```<code>stack r;
</code>```

Update: Rep &r means that r is a reference to object of type Rep.

For example:

```<code>Rep rep; // object of type (class) Rep
Rep &ref = rep; // reference to rep
</code>```

BTW. I don't like the code you have posted.

typedefing something just to make it a reference is not a good idea; it should be clearly visible that something is a pointer or reference, because then it behaves in much other way than it looks like.

push() and pop() should be methods of class Rep (or better Stack), or it is more C code than C++ :)

memory management; you have to care that destroy() will be called for every stack you got from create(). Usually smart pointers are used to ensure proper memory management.

Title: Need explanation for C++ code

Body:
namespace Stack {
  struct Rep; // definition of stack layout is elsewhere
  typedef Rep& stack;
  stack create(); // make a new stack
  void destroy(stack s); // delete s
  void push(stack s, char c); // push c onto s
  char pop(stack s); // pop s
}

This is in the "A Tour of C++" Unit, before even the basic material like functions, loops, and fundamental datatypes...I don't know if/how I'm supposed to understand this code or not.

Anyway, can someone please explain it? It's supposed to be part of an explanation on how to "define a stack manager with an interface"

For starters, I specifically don't know what "typedef Rep& stack" means.

Body:
typedef Rep& stack means that stack will be a synonym for Rep&. So instead of

Rep &r;

you can write

stack r;

Update: Rep &r means that r is a reference to object of type Rep.

For example:

Rep rep; // object of type (class) Rep
Rep &ref = rep; // reference to rep

BTW. I don't like the code you have posted.

typedefing something just to make it a reference is not a good idea; it should be clearly visible that something is a pointer or reference, because then it behaves in much other way than it looks like.

push() and pop() should be methods of class Rep (or better Stack), or it is more C code than C++ :)

memory management; you have to care that destroy() will be called for every stack you got from create(). Usually smart pointers are used to ensure proper memory management.


问:
SUMPRODUCT function with IF logic
I am attempting to multiple two arrays, but only if array 2 meets a greater than or equal to criteria. That criteria is >=243

| Array 1      | Array 2            |

| 5         | 200 |

| 5    | 240 |

| 5 | 280 |

| 5 | 320 |

I have attempted to use the following formula:
=SUMPRODUCT(--(Program!F4:F8>=(VLOOKUP(Results!$C$10,Start!$B$3:$H$8,4,0)*Results!E22)),Program!E4:E8)

Which is simplified to:
=SUMPRODUCT(--(Program!F4:F8>=243)),Program!E4:E8)

This returns the number 10, which I assume is because it returns the true values as 1, and then are multiplied by 5 and summed.

How may I fix this to return 3000?

答:
This is the same as Variatus's post except it avoids the, in my opinion, odd choice to multiply the parameters inside the sumproduct function, which handles the multiplication. I've also explicitly converted the first logical array to number.

=SUMPRODUCT(N(F2:F5>=243),E2:E5,F2:F5)

Title: SUMPRODUCT function with IF logic


问:
How to divide each column with a different number
I used the "table" function of R to summarize data and got the following result:

Summarized Data

Now, I want to divide all the numbers in the first column with 32, all the numbers in the second column with 51, and all the numbers in the third column with 54. Then these numbers will form a new 3*5 matrix, and I'll use the new matrix to continue to draw a barplot.

Does anyone here know how I can write the command in R?

答:
We can use sweep :

```<code>sweep(data,2,c(32, 51, 54), `/`)
</code>```

Body:
We can use sweep :

sweep(data,2,c(32, 51, 54), `/`)


问:
How to find the min value of a specific field in MongoDB using C# driver 2.10.4
Hi i am new in mongoDB and in C#. I want to find the min value of a specific filed from my collection.

I have created the following class

```<code>     public class GlobalUrbanPoint
        {
            [BsonId]
            public ObjectId  Id{ get; set; }
            public double LATITUDE { get; set; }
            public double LONGITUDE { get; set; }
            ...
        }
</code>```

For the operation I have following function for the connection and other.

```<code>     public class MongoCRUD
        {
            private IMongoDatabase db;

            public MongoCRUD(string database)
            {
                var client = new MongoClient();
                db = client.GetDatabase(database);
            }
            ...
            public void NormalizeCoordinates<T>(string table)
            {
                var collection = db.GetCollection<T>(table);
                // something is wrong the selection
                var result = collection.AsQueryable<T>().Select(LATITUDE => LATITUDE).Min<T>();
                Console.WriteLine(result);
            }
        }
</code>```

This is the Main function:

```<code>    using System;
    using System.Collections.Generic;
    using MongoDB.Bson;
    using MongoDB.Bson.Serialization.Attributes;
    using MongoDB.Driver;
    using MongoDB.Driver.Linq;

    static void Main(string[] args)
        {
            MongoCRUD db = new MongoCRUD("testClass");

            var newTable = "points";

            /* find The min value*/
            db.NormalizeCoordinates<GlobalUrbanPoint>(newTable);
         }
</code>```

If I run this I get an exception : System.NotSupportedException: '$project or $group does not support {document}.'

I have try and a different approach that i found here with the use of FindAs().

```<code>    var cursor =  collection.FindAs<T>(Query.And()).SetSortOrder(SortBy.Ascending(fieldName)).SetLimit(1).SetFields(fieldName);
</code>```

Again, I have the same luck.

Can someone explain me how to get the min value properly from my collection.
Thank you, for your time.

答:
What you're returning from MongoDB's query/aggregation needs to be an object and if you want to get min/max values from entire collection you need to $group that collection by a constant value:</p>

```<code>var q = collection.Aggregate()
                  .Group(
                      x => 1,
                      gr => new {MinVal = gr.Min(f => f.LONGITUDE)});

var result = q.First().MinVal;
</code>```

Body:
Hi i am new in mongoDB and in C#. I want to find the min value of a specific filed from my collection.

I have created the following class

     public class GlobalUrbanPoint
        {
            [BsonId]
            public ObjectId  Id{ get; set; }
            public double LATITUDE { get; set; }
            public double LONGITUDE { get; set; }
            ...
        }

For the operation I have following function for the connection and other.

     public class MongoCRUD
        {
            private IMongoDatabase db;

            public MongoCRUD(string database)
            {
                var client = new MongoClient();
                db = client.GetDatabase(database);
            }
            ...
            public void NormalizeCoordinates<T>(string table)
            {
                var collection = db.GetCollection<T>(table);
                // something is wrong the selection
                var result = collection.AsQueryable<T>().Select(LATITUDE => LATITUDE).Min<T>();
                Console.WriteLine(result);
            }
        }

This is the Main function:

    using System;
    using System.Collections.Generic;
    using MongoDB.Bson;
    using MongoDB.Bson.Serialization.Attributes;
    using MongoDB.Driver;
    using MongoDB.Driver.Linq;

    static void Main(string[] args)
        {
            MongoCRUD db = new MongoCRUD("testClass");

            var newTable = "points";

            /* find The min value*/
            db.NormalizeCoordinates<GlobalUrbanPoint>(newTable);
         }

If I run this I get an exception : System.NotSupportedException: '$project or $group does not support {document}.'

I have try and a different approach that i found here with the use of FindAs().

    var cursor =  collection.FindAs<T>(Query.And()).SetSortOrder(SortBy.Ascending(fieldName)).SetLimit(1).SetFields(fieldName);

Again, I have the same luck.

Can someone explain me how to get the min value properly from my collection.
Thank you, for your time.

Body:
What you're returning from MongoDB's query/aggregation needs to be an object and if you want to get min/max values from entire collection you need to $group that collection by a constant value:

var q = collection.Aggregate()
                  .Group(
                      x => 1,
                      gr => new {MinVal = gr.Min(f => f.LONGITUDE)});

var result = q.First().MinVal;