问:
Align lists vertically under multiple headers
I am working angular and i have to create this: .

So far i was able to just create the 'headers' in same 'row' but now i need to show a list under each header. I will be getting data to show under Reattempt, Returned and Delivered. But i do not know how can i align the list under each header.

I will have three different arrays in three different variables. So how can i show list under each header? Also i am not well versed with frontend development since its not my area of expertise.

Here is what i am doing to show headers in a row

```<code><div fxLayout="row" fxLayoutAlign="space-evenly center">
    <div *ngFor = "let item of statuses">
        <h1>{{item.header}}</h1>
    </div>
</div>
</code>```

I don't know what i need to do next. Your help will be much appreciated.

答:
I would add list items to your statuses array:</p>

```<code>statuses[0].list = reattemptList;
statuses[1].list = returnedList;
// etc.
</code>```

```<code><div fxLayout="row" fxLayoutAlign="space-evenly center">
    <div *ngFor = "let item of statuses">
        <h1>{{item.header}}</h1>
        <div class="list-items">
          <div *ngFor = "let listItem of item.list">
             // Here you do something with your list items
             // {{listItem.name}}
          </div>
        </div>
    </div>
</div>
</code>```

Body:
I am working angular and i have to create this: .

So far i was able to just create the 'headers' in same 'row' but now i need to show a list under each header. I will be getting data to show under Reattempt, Returned and Delivered. But i do not know how can i align the list under each header.

I will have three different arrays in three different variables. So how can i show list under each header? Also i am not well versed with frontend development since its not my area of expertise.

Here is what i am doing to show headers in a row

{{item.header}}

I don't know what i need to do next. Your help will be much appreciated.

Body:
I would add list items to your statuses array:

statuses[0].list = reattemptList;
statuses[1].list = returnedList;
// etc.

<div fxLayout="row" fxLayoutAlign="space-evenly center">
    <div *ngFor = "let item of statuses">
        <h1>{{item.header}}</h1>
        <div class="list-items">
          <div *ngFor = "let listItem of item.list">
             // Here you do something with your list items
             // {{listItem.name}}
          </div>
        </div>
    </div>
</div>


来源: stackexchange

问:
How to Threshold a video in python?
I'm trying to read a video into python (be it live or pre-recorded is irrelevant) then have each frame processed using a thresholding algorithm to convert the video to a 2 colour format.

with a simple thresholding method, i get this error:

cv2.imshow('newFrame',newFrame)
TypeError: Expected Ptr<cv::UMat> for argument 'mat'

Thresholding for images seems simple but i cant seem to convert the data produced from the thresholding method into a format that is recognised by anything further down the line.
I have included the full code below.

import numpy as np
import cv2

cap = cv2.VideoCapture('Loop_1.mov')

while(cap.isOpened()):
    ret, frame = cap.read()
    if ret==True:

        threshed = cv2.threshold(frame,50,255,cv2.THRESH_BINARY)
        newFrame = np.array(threshed)

        cv2.imshow('newFrame',newFrame)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    else:
        break

# Release everything if job is finished
cap.release()
#out.release()
cv2.destroyAllWindows()
```

答:
The threshold function should return two parameters

retval, threshold = cv2.threshold(frame, 50, 255, cv2.THRESH_BINARY)

ContentLicense: CC BY-SA 4.0

Title: How to Threshold a video in python?


问:
Turning the Nth (input from user) number into Uppercase and the rest will be in Lowercase
I will ask this again. I have this problem which is to create a program that would read a string input from the user (sentence or word). And the Nth number (from the user) will turn into upper case and the rest will be in lowercase.
Example:

string = "good morning everyone"

n = 2

Output = gOod mOrning eVeryone

```<code>    for (int x = 0; x < s.length(); x++)
        if (x == n-1){
            temp+=(""+s.charAt(x)).toUpperCase();
        }else{
            temp+=(""+s.charAt(x)).toLowerCase();
        }
    s=temp;
    System.out.println(s);
}
</code>```

Output: gOod morning everyone

答:
You can do this with two for loops. Iterate over each word and within the iteration iterate over each character.

```<code>toUpperCase(2, "good morning everyone");

private static void toUpperCase(int nth, String sentence) {
    StringBuilder result = new StringBuilder();
    for(String word : sentence.split(" ")) {
        for(int i = 0; i < word.length(); i++) {
            if(i > 0 && i % nth - 1 == 0) {
                result.append(Character.toString(word.charAt(i)).toUpperCase());
            } else {
                result.append(word.charAt(i));
            }
        }
        result.append(" ");
    }
    System.out.println(result);
}
</code>```

gOoD mOrNiNg eVeRyOnE

Body:
I will ask this again. I have this problem which is to create a program that would read a string input from the user (sentence or word). And the Nth number (from the user) will turn into upper case and the rest will be in lowercase.
Example:

string = "good morning everyone"

n = 2

Output = gOod mOrning eVeryone

    for (int x = 0; x < s.length(); x++)
        if (x == n-1){
            temp+=(""+s.charAt(x)).toUpperCase();
        }else{
            temp+=(""+s.charAt(x)).toLowerCase();
        }
    s=temp;
    System.out.println(s);
}

Output: gOod morning everyone

Body:
You can do this with two for loops. Iterate over each word and within the iteration iterate over each character.

toUpperCase(2, "good morning everyone");

private static void toUpperCase(int nth, String sentence) {
    StringBuilder result = new StringBuilder();
    for(String word : sentence.split(" ")) {
        for(int i = 0; i < word.length(); i++) {
            if(i > 0 && i % nth - 1 == 0) {
                result.append(Character.toString(word.charAt(i)).toUpperCase());
            } else {
                result.append(word.charAt(i));
            }
        }
        result.append(" ");
    }
    System.out.println(result);
}

gOoD mOrNiNg eVeRyOnE


问:
Is it possible to share an Office 365 Outlook Calendar with the beta version of the Graph API?
As part of our new onboarding process, I was looking at using the new (beta) Graph API to share an Outlook calendar. The Microsoft documentation here shows how to get the permissions already established, how to update those permissions, and how to revoke permissions, but I don't see a way of actually setting up the initial permissions and sending the invite. </p>

<p>Does anyone have an idea what the https call would like to share a calendar with basic read permissions to a new user? </p>

答:
The docs are actually published here based on that github source https://learn.microsoft.com/en-us/graph/versioning-and-support

There are two stages.
- when YOUR application needs to define the permission scopes it requires either at App Registration within portal.azure.com OR in code
- when the USER signs into your application and then is prompted to consent the permissions for the application to access Graph APIs on behalf of their user identity

If you are using MSAL libraries, this is all done for you. I'd encourage you to take a look at the Getting Started https://developer.microsoft.com/en-us/graph/get-started pages where there are tutorials that start from scratch or quick starts you can download to look at. There are also some great training modules here https://learn.microsoft.com/en-us/learn/browse/?products=m365%2Cms-graph&resource_type=module&roles=developer

Body:
As part of our new onboarding process, I was looking at using the new (beta) Graph API to share an Outlook calendar. The Microsoft documentation here shows how to get the permissions already established, how to update those permissions, and how to revoke permissions, but I don't see a way of actually setting up the initial permissions and sending the invite.

Does anyone have an idea what the https call would like to share a calendar with basic read permissions to a new user?


问:
Get .Net Core 3.1 single-file executable version number
I have a .Net Core application that has been published as a single file executable.  When I run any of the following code from within Visual Studio, I get the expected result:

```<code>Assembly.GetAssembly(typeof(Installer)).GetName().Version.ToString();
Assembly.GetEntryAssembly().GetName().Version.ToString();
Assembly.GetExecutingAssembly().GetName().Version.ToString();
</code>```

But when the above code is run within the published application (in production) it always returns "0.0.0.0"

答:
The assembly version should be set in the properties of the project which you're compiling.

Right-click project -> Properties -> Package:

Body:
I have a .Net Core application that has been published as a single file executable.  When I run any of the following code from within Visual Studio, I get the expected result:

Assembly.GetAssembly(typeof(Installer)).GetName().Version.ToString();
Assembly.GetEntryAssembly().GetName().Version.ToString();
Assembly.GetExecutingAssembly().GetName().Version.ToString();

But when the above code is run within the published application (in production) it always returns "0.0.0.0"


问:
Makefile with Java
I realize the make isn't the best tool to be using with Java, but I just wanted to experiment with it. I have this script but I'm not sure why it isn't working:

```<code>JFLAGS = -g
JC = javac
SRC_DIR = $(PWD)
.SUFFIXES:  .java .class
.java.class:
    $(JC) $(JFLAGS) $*.java

CLASSES = \
$(SRC_DIR)/Fibonacci_Methods.java \
$(SRC_DIR)/Fibonacci_Methods_Test.java \

default: classes

classes:
    $(CLASSES:.java=.class)

clean:
    $(RM) *.class
</code>```

I get this error:

```<code>/path/to/make_test/Fibonacci_Methods.class
/path/to/make_test/Fibonacci_Methods_Test.class
make: /path/to/make_test/Fibonacci_Methods.class: No such file or directory
make: *** [classes] Error 1
</code>```

I'm not sure why. My understanding is that this script should define CLASSES, which should call .java.class target because I'm defining files ending with .java. I don't know the purpose of $(CLASSES:.java=.class) because I would have thought the compilation be done already before this step.

I have not yet compiled the java code, by the way (so I'm running make with .java files only, if that makes a difference).

答:
This is wrong:

```<code>classes:
        $(CLASSES:.java=.class)
</code>```

Here you've defined a target with no prerequisites and recipe (which is supposed to be a command that is used to rebuild the target) that consists of a list of .class filenames, so you're getting the error you see because you can't "run" a list of .class files.

You want this:

```<code>classes: $(CLASSES:.java=.class)
</code>```

which defines a target classes with a set of prerequisites which are the .class files you want to build, and no recipe because you don't want to create a target named classes.

Title: Makefile with Java

Body:
I realize the make isn't the best tool to be using with Java, but I just wanted to experiment with it. I have this script but I'm not sure why it isn't working:

JFLAGS = -g
JC = javac
SRC_DIR = $(PWD)
.SUFFIXES:  .java .class
.java.class:
    $(JC) $(JFLAGS) $*.java

CLASSES = \
$(SRC_DIR)/Fibonacci_Methods.java \
$(SRC_DIR)/Fibonacci_Methods_Test.java \

default: classes

classes:
    $(CLASSES:.java=.class)

clean:
    $(RM) *.class

I get this error:

/path/to/make_test/Fibonacci_Methods.class
/path/to/make_test/Fibonacci_Methods_Test.class
make: /path/to/make_test/Fibonacci_Methods.class: No such file or directory
make: *** [classes] Error 1

I'm not sure why. My understanding is that this script should define CLASSES, which should call .java.class target because I'm defining files ending with .java. I don't know the purpose of $(CLASSES:.java=.class) because I would have thought the compilation be done already before this step.

I have not yet compiled the java code, by the way (so I'm running make with .java files only, if that makes a difference).

Body:
This is wrong:

classes:
        $(CLASSES:.java=.class)

Here you've defined a target with no prerequisites and recipe (which is supposed to be a command that is used to rebuild the target) that consists of a list of .class filenames, so you're getting the error you see because you can't "run" a list of .class files.

You want this:

classes: $(CLASSES:.java=.class)

which defines a target classes with a set of prerequisites which are the .class files you want to build, and no recipe because you don't want to create a target named classes.


问:
how to make a Text prevent the inputs more than 'x' number of digits?
My question is:

I want the Text field in Eclipse RCP to allow only the digits to be keyed in as inputs and the requirement is that it should allow only up to 'x' (let's say x=5) characters.

How can I accomplish it in RCP ?

I've tried the code like:

```<code>txtInput.addListener(SWT.Verify, new DecimalText(
                txtInsuranceValue, 8, 1000.00));
</code>```

where txtInputis a Text field. But this listener failed when I made repeated input into this field at run time.

Any alternatives please ?

答:
This will set the maximum number of characters in your Text control to five and allow only digits to be entered:

```<code>    txtInput.setTextLimit(5);

    txtInput.addVerifyListener(new VerifyListener() {
        public void verifyText(VerifyEvent event) {
            // Assume we allow it
            event.doit = true;

            String text = event.text;
            char[] chars = text.toCharArray();

            //Don't allow if text contains non-digit characters
            for (int i = 0; i < chars.length; i++) {
                if (!Character.isDigit(chars[i])) {
                    event.doit = false;
                    break;
                }
            }
        }
    });
</code>```

EDIT: I've modified my answer to allow a user to also set text with "setText(String string)"  while still disallowing non-digit characters.

ContentLicense: CC BY-SA 3.0

Body:
My question is:

I want the Text field in Eclipse RCP to allow only the digits to be keyed in as inputs and the requirement is that it should allow only up to 'x' (let's say x=5) characters.

How can I accomplish it in RCP ?

I've tried the code like:

txtInput.addListener(SWT.Verify, new DecimalText(
                txtInsuranceValue, 8, 1000.00));

where txtInputis a Text field. But this listener failed when I made repeated input into this field at run time.

Any alternatives please ?

Body:
This will set the maximum number of characters in your Text control to five and allow only digits to be entered:

    txtInput.setTextLimit(5);

    txtInput.addVerifyListener(new VerifyListener() {
        public void verifyText(VerifyEvent event) {
            // Assume we allow it
            event.doit = true;

            String text = event.text;
            char[] chars = text.toCharArray();

            //Don't allow if text contains non-digit characters
            for (int i = 0; i < chars.length; i++) {
                if (!Character.isDigit(chars[i])) {
                    event.doit = false;
                    break;
                }
            }
        }
    });

EDIT: I've modified my answer to allow a user to also set text with "setText(String string)"  while still disallowing non-digit characters.


问:
Ignoring return value of function declared with "warn_unused_result" attribute
We start having this warning on all the becomeFirstResponder function call in our Objective-C code.

Ignoring return value of function declared with "warn_unused_result" attribute

```<code>[self.phoneNumberField becomeFirstResponder]; // warning here!!!
</code>```

What's the best way to suppress this warning here?

Edit: I also tried this,

```<code>BOOL ignore = [self.emailField becomeFirstResponder];
</code>```

But with that, Xcode has warning about the variable ignore is not used :(

I also tried this,

```<code>BOOL ignore = [self.phoneNumberField becomeFirstResponder];
if (ignore) {

}
</code>```

The warnings is gone in this case. But I don't think I can even past my own code review. It is too ugly!

答:
You could get this warning if you have a Swift function that you call from Objective-C code. You can silence it by adding @discardableResult before the function in Swift, like this:

```<code>@objc @discardableResult func yourFanzyFuncInSwift(argument: String) -> Bool { ... }
</code>```

Seems like warn_unused_result is the default setting in Swift, meaning that you shouldn't write code that ignores return values.

Body:
We start having this warning on all the becomeFirstResponder function call in our Objective-C code.

Ignoring return value of function declared with "warn_unused_result" attribute

[self.phoneNumberField becomeFirstResponder]; // warning here!!!

What's the best way to suppress this warning here?

Edit: I also tried this,

BOOL ignore = [self.emailField becomeFirstResponder];

But with that, Xcode has warning about the variable ignore is not used :(

I also tried this,

BOOL ignore = [self.phoneNumberField becomeFirstResponder];
if (ignore) {

}

The warnings is gone in this case. But I don't think I can even past my own code review. It is too ugly!

Body:
You could get this warning if you have a Swift function that you call from Objective-C code. You can silence it by adding @discardableResult before the function in Swift, like this:

@objc @discardableResult func yourFanzyFuncInSwift(argument: String) -> Bool { ... }

Seems like warn_unused_result is the default setting in Swift, meaning that you shouldn't write code that ignores return values.


问:
Problem in sizeof() operator and poiner declaration
This question was asked in my Sem-2 examination. Question asked us to give the desired output.

```<code>int main(void)
{
    int a[] = {10,20,30,40,50,60};

    int (*p1)[2]=a , (*p2)[3]= a;

    if(sizeof(p1)==sizeof(p2))
    printf("%d",*(*p1+2));

    if(sizeof(*p1)==sizeof(*p2))
    printf("%d",*(*(p2+1)));

    return(0);
}
</code>```

Compiler warnings:

```<code>Warning: initialization from incompatible pointer type [-Wincompatible-pointer-types]
         initialization from incompatible pointer type [-Wincompatible-pointer-types]
</code>```

Output that I expect: 20

Output that I get when I run it: 30

Using : gcc (Ubuntu 7.4.0-1ubuntu1~18.04.1) 7.4.0

答:
Let's ignore the undefined behavior to work out what is probably happening.

p1 and p2 are both pointing to a[0] (ignoring the incompatible pointer types).

p1 and p2 are both pointers. Pointers to object types are generally the same size (assume this is the case), so sizeof(p1)==sizeof(p2) will be true.

p1 is of type int (*)[2], so *p1 is of type int[2]. In most expressions, an array will decay to a pointer to its first element, so in the expression *(*p1+2), *p1 will decay to an int * and will be pointing to a[0]. Therefore *p1+2 will be pointing to a[2]. Therefore *(*p1+2) will be the same as a[2], which has the value 30. Therefore the program prints 30.

An array does not decay to a pointer when it is the operand of the sizeof operator. *p1 is of type int[2] and *p2 is of type int[3], so sizeof(*p1)==sizeof(*p2) is equivalent to sizeof(int[2])==sizeof(int[3]), which is false. Therefore the second printf call that prints the value of *(*p2+1) is not evaluated.

(Let's pretend the second printf is called and that *(*p2+1) is evaluated. *p2 is of type int[3] and in this expression it decays to an int * pointing to a[0]. Therefore *p2+1 points to a[1]. Therefore, *(*p2+1) will be the same as a[1], which has the value 20.)

Body:
This question was asked in my Sem-2 examination. Question asked us to give the desired output.

int main(void)
{
    int a[] = {10,20,30,40,50,60};

    int (*p1)[2]=a , (*p2)[3]= a;

    if(sizeof(p1)==sizeof(p2))
    printf("%d",*(*p1+2));

    if(sizeof(*p1)==sizeof(*p2))
    printf("%d",*(*(p2+1)));

    return(0);
}

Compiler warnings:

Warning: initialization from incompatible pointer type [-Wincompatible-pointer-types]
         initialization from incompatible pointer type [-Wincompatible-pointer-types]

Output that I expect: 20

Output that I get when I run it: 30

Using : gcc (Ubuntu 7.4.0-1ubuntu1~18.04.1) 7.4.0


问:
Install MariaDB in Windows subsystem Linux (WSL)
I'm trying to start MariaDB in the windows linux subsystem using

```<code>sudo apt-get update
sudo apt-get install mariadb-server
sudo service mysql start
</code>```

but getting the following error:

```<code>ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2 "No such file or directory")
</code>```

I know, this is not a new question, I read a lot about other solutions under Ubuntu to fix this, but nothing worked so far. Has anybody an idea how to get it going?

Merci A

答:
I'm encountered with the same problem. Fortunately I found a solution at https://github.com/microsoft/WSL/issues/745#issuecomment-237412792

```<code>sudo /etc/init.d/mysql start
</code>```

which works for me. Hope it works for you too.

Body:
I'm trying to start MariaDB in the windows linux subsystem using

sudo apt-get update
sudo apt-get install mariadb-server
sudo service mysql start

but getting the following error:

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2 "No such file or directory")

I know, this is not a new question, I read a lot about other solutions under Ubuntu to fix this, but nothing worked so far. Has anybody an idea how to get it going?

Merci A

Body:
I'm encountered with the same problem. Fortunately I found a solution at https://github.com/microsoft/WSL/issues/745#issuecomment-237412792

sudo /etc/init.d/mysql start

which works for me. Hope it works for you too.


问:
Can't Upload python script on Google Cloud Console. (Error response [13] && Error response [9])
I have been trying last day to deploy my script to Google Cloud console but without success!
Gcloud Version:

```<code>Google Cloud SDK 204.0.0
beta 2017.09.15
bq 2.0.34
core 2018.06.04
gsutil 4.31
</code>```

yaml file:

```<code>runtime: python
env: flex
entrypoint: gunicorn -b :$PORT main:app

runtime_config:
  python_version: 3
manual_scaling:
  instances: 1
resources:
  cpu: 1
  memory_gb: 1
  disk_size_gb: 10
</code>```

requirements.txt file:

```<code>Flask==0.12.2
gunicorn==19.8.1
</code>```

I tried deploying with gcloud beta app deploy and I am getting the following error:

```<code>ERROR: (gcloud.app.deploy) Error Response: [9]
Application startup error:
[2018-06-06 09:28:47 +0000] [1] [INFO] Starting gunicorn 19.8.1
[2018-06-06 09:28:47 +0000] [1] [INFO] Listening at: http://0.0.0.0:8080 (1)
[2018-06-06 09:28:47 +0000] [1] [INFO] Using worker: sync
[2018-06-06 09:28:47 +0000] [7] [INFO] Booting worker with pid: 7
[2018-06-06 09:28:47 +0000] [7] [ERROR] Exception in worker process
Traceback (most recent call last):
  File "/env/lib/python3.6/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker
    worker.init_process()
  File "/env/lib/python3.6/site-packages/gunicorn/workers/base.py", line 129, in init_process
    self.load_wsgi()
  File "/env/lib/python3.6/site-packages/gunicorn/workers/base.py", line 138, in load_wsgi
    self.wsgi = self.app.wsgi()
  File "/env/lib/python3.6/site-packages/gunicorn/app/base.py", line 67, in wsgi
    self.callable = self.load()
  File "/env/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 52, in load
    return self.load_wsgiapp()
  File "/env/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 41, in load_wsgiapp
    return util.import_app(self.app_uri)
  File "/env/lib/python3.6/site-packages/gunicorn/util.py", line 350, in import_app
    __import__(module)
  File "/home/vmagent/app/main.py", line 5, in <module>
    import firebase_admin
ModuleNotFoundError: No module named 'firebase_admin'
[2018-06-06 09:28:47 +0000] [7] [INFO] Worker exiting (pid: 7)
[2018-06-06 09:28:47 +0000] [1] [INFO] Shutting down: Master
[2018-06-06 09:28:47 +0000] [1] [INFO] Reason: Worker failed to boot.
</code>```

I also have all my modules installed into a virtual env...

However, I also tried deploying with gcloud app deploy and I am getting a different error -> ERROR: (gcloud.beta.app.deploy) Error Response: [13] Error while processing files. Referring to a similar issue which is closed now (https://github.com/GoogleCloudPlatform/getting-started-java/issues/281) I did this command gcloud config set app/use_deprecated_preparation True, as the majority of people are saying that is working but for me is NOT!

Code snipet from my main.py

```<code># [START app]
import logging
import sys

import firebase_admin
import moment

from datetime import datetime
from firebase_admin import credentials, db
from flask import Flask, json, make_response, render_template, request

from apiclient.discovery import build, build_from_document
from firebase import firebase
from httplib2 import Http
from oauth2client.service_account import ServiceAccountCredentials

service_account = 'FIREBASE-ADMIN-SDK-KEY'
database_url = 'FIRABE-DB-URL'

cred = credentials.Certificate(service_account)

# Initialize the app with a service account, granting admin privileges
firebase_admin.initialize_app(cred, {
    'databaseURL': database_url
})

firebase = firebase.FirebaseApplication(database_url, None)

user_id = ""

rootDB = db.reference()
messagesDb = rootDB.child('messages')

app = Flask(__name__)

if sys.version_info.major < 3:
    reload(sys)
sys.setdefaultencoding('utf8')

scopes = ['https://www.googleapis.com/auth/chat.bot']

credentials = ServiceAccountCredentials.from_json_keyfile_name(
    'Google-Serviced-Account-KEY', scopes)

http_auth = credentials.authorize(Http())

chat = build('chat', 'v1', http=http_auth, cache_discovery=False)

# Using the rest api (send message function)
@app.route('/receiver', methods=['POST'])
def message_responses():

    #Some Code here

    return 'OK'

# [END message_response]

@app.route('/getMeasages', methods=['POST'])
def get_messages():

    # Some Code here

    return 'OK'

# [END get_messages]

@app.route('/test', methods=['POST'])
def resp_get():

    event_data = request.get_json()
    print(event_data)

    return 'OK'

@app.route('/', methods=['GET'])
def home_get():

    return render_template('home.html')

if __name__ == '__main__':
    # This is used when running locally. Gunicorn is used to run the
    # application on Google App Engine. See entrypoint in app.yaml.
    app.run(host='localhost', port=8080, debug=True)
# [END app]
</code>```

答:
You are using fairly low versions of gunicorn and Flask. I would upgrade them accordingly (google example) and add firebase-admin, firebase and some other dependencies as well. Example requirements.txt:

```<code>Flask==1.1.1
gunicorn==20.0.4
moment==0.8.2
firebase==3.0.1
firebase-admin==3.2.1
google-api-python-client==1.7.11
</code>```

I would recommend you put those dependencies in your requirements.txt file and only install from that file in a virtualenv.

```<code>pip3 install -r requirements.txt
</code>```

Body:
I have been trying last day to deploy my script to Google Cloud console but without success!
Gcloud Version:

Google Cloud SDK 204.0.0
beta 2017.09.15
bq 2.0.34
core 2018.06.04
gsutil 4.31

yaml file:

runtime: python
env: flex
entrypoint: gunicorn -b :$PORT main:app

runtime_config:
  python_version: 3
manual_scaling:
  instances: 1
resources:
  cpu: 1
  memory_gb: 1
  disk_size_gb: 10

requirements.txt file:

Flask==0.12.2
gunicorn==19.8.1

I tried deploying with gcloud beta app deploy and I am getting the following error:

ERROR: (gcloud.app.deploy) Error Response: [9]
Application startup error:
[2018-06-06 09:28:47 +0000] [1] [INFO] Starting gunicorn 19.8.1
[2018-06-06 09:28:47 +0000] [1] [INFO] Listening at: http://0.0.0.0:8080 (1)
[2018-06-06 09:28:47 +0000] [1] [INFO] Using worker: sync
[2018-06-06 09:28:47 +0000] [7] [INFO] Booting worker with pid: 7
[2018-06-06 09:28:47 +0000] [7] [ERROR] Exception in worker process
Traceback (most recent call last):
  File "/env/lib/python3.6/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker
    worker.init_process()
  File "/env/lib/python3.6/site-packages/gunicorn/workers/base.py", line 129, in init_process
    self.load_wsgi()
  File "/env/lib/python3.6/site-packages/gunicorn/workers/base.py", line 138, in load_wsgi
    self.wsgi = self.app.wsgi()
  File "/env/lib/python3.6/site-packages/gunicorn/app/base.py", line 67, in wsgi
    self.callable = self.load()
  File "/env/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 52, in load
    return self.load_wsgiapp()
  File "/env/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 41, in load_wsgiapp
    return util.import_app(self.app_uri)
  File "/env/lib/python3.6/site-packages/gunicorn/util.py", line 350, in import_app
    __import__(module)
  File "/home/vmagent/app/main.py", line 5, in <module>
    import firebase_admin
ModuleNotFoundError: No module named 'firebase_admin'
[2018-06-06 09:28:47 +0000] [7] [INFO] Worker exiting (pid: 7)
[2018-06-06 09:28:47 +0000] [1] [INFO] Shutting down: Master
[2018-06-06 09:28:47 +0000] [1] [INFO] Reason: Worker failed to boot.

I also have all my modules installed into a virtual env...

However, I also tried deploying with gcloud app deploy and I am getting a different error -> ERROR: (gcloud.beta.app.deploy) Error Response: [13] Error while processing files. Referring to a similar issue which is closed now (https://github.com/GoogleCloudPlatform/getting-started-java/issues/281) I did this command gcloud config set app/use_deprecated_preparation True, as the majority of people are saying that is working but for me is NOT!

Code snipet from my main.py

# [START app]
import logging
import sys

import firebase_admin
import moment

from datetime import datetime
from firebase_admin import credentials, db
from flask import Flask, json, make_response, render_template, request

from apiclient.discovery import build, build_from_document
from firebase import firebase
from httplib2 import Http
from oauth2client.service_account import ServiceAccountCredentials

service_account = 'FIREBASE-ADMIN-SDK-KEY'
database_url = 'FIRABE-DB-URL'

cred = credentials.Certificate(service_account)

# Initialize the app with a service account, granting admin privileges
firebase_admin.initialize_app(cred, {
    'databaseURL': database_url
})

firebase = firebase.FirebaseApplication(database_url, None)

user_id = ""

rootDB = db.reference()
messagesDb = rootDB.child('messages')

app = Flask(__name__)

if sys.version_info.major < 3:
    reload(sys)
sys.setdefaultencoding('utf8')

scopes = ['https://www.googleapis.com/auth/chat.bot']

credentials = ServiceAccountCredentials.from_json_keyfile_name(
    'Google-Serviced-Account-KEY', scopes)

http_auth = credentials.authorize(Http())

chat = build('chat', 'v1', http=http_auth, cache_discovery=False)

# Using the rest api (send message function)
@app.route('/receiver', methods=['POST'])
def message_responses():

    #Some Code here

    return 'OK'

# [END message_response]

@app.route('/getMeasages', methods=['POST'])
def get_messages():

    # Some Code here

    return 'OK'

# [END get_messages]

@app.route('/test', methods=['POST'])
def resp_get():

    event_data = request.get_json()
    print(event_data)

    return 'OK'

@app.route('/', methods=['GET'])
def home_get():

    return render_template('home.html')

if __name__ == '__main__':
    # This is used when running locally. Gunicorn is used to run the
    # application on Google App Engine. See entrypoint in app.yaml.
    app.run(host='localhost', port=8080, debug=True)
# [END app]

Body:
You are using fairly low versions of gunicorn and Flask. I would upgrade them accordingly (google example) and add firebase-admin, firebase and some other dependencies as well. Example requirements.txt:

Flask==1.1.1
gunicorn==20.0.4
moment==0.8.2
firebase==3.0.1
firebase-admin==3.2.1
google-api-python-client==1.7.11

I would recommend you put those dependencies in your requirements.txt file and only install from that file in a virtualenv.

pip3 install -r requirements.txt


问:
Extract substring from row in SQL table and convert to date
I am trying to extract one row of data from a SQL Server table via PowerShell and convert the extracted value into a date.

The first 8 chars of the string should be in yyyymmdd format.

Firstly, I am having problems extracting the row...

As per various posts I've seen, it appears that when you grab a row, the data type that is returned is System.Data.DataRow. You then need to convert it into an Array. How do I grab the values from the array/datarow? Ideally, I'd like the value to come back as a String - as there will only be one value returned.
I am currently using something like this - but the content is null (even though the statement in SSMS returns one row)...

[array]$lastSQLdateArray = Invoke-Sqlcmd -ServerInstance INSTANCE -Database DATABASE -Query "SELECT TOP 1 LEFT(Column, 8) FROM [dbo].[Table] ORDER BY ID DESC"

```<code>for ($i=0; $i -le $lastSQLdateArray.Length; $i++)
{
  $formatOut = $formatOut + ($lastSQLdateArray[$i].ItemArray -join ",")
}
</code>```

Then there is the question of converting the extracted yyyymmdd value (which ever data type it is) and convert it to a date.

How can I do this please?

答:
Welcome, warnerj79. First of all, your SQL statement is a bit ambiguous.  I would recommend always specifying AS ColumnName when calculating parameters.  It will help later on.  I also like to put my SQL in a variable for readability.
So your SQL line becomes:

```<code>$strSQL = "SELECT TOP 1 LEFT(Column, 8) AS 'DateTimeString' FROM [dbo].[Table] ORDER BY ID DESC"
[array]$lastSQLdateArray = Invoke-Sqlcmd -ServerInstance INSTANCE -Database DATABASE -Query $strSQL
</code>```

Then, your results variable ([array]$lastSQLdateArray) will contain one row (due to your use of TOP 1, so you would access the YYYYMMDD property like this:

```<code>$lastSQLdateArray[0].DateTimeString
</code>```

Or because it is only one element in the array, this will work also:

```<code>$lastSQLdateArray.DateTimeString
</code>```

That value is in a string format.  In order to convert that to a [datetime] variable, I would use the parseexact method like so:

```<code>$DateTimeVariable = [datetime]::ParseExact($lastSQLdateArray[0].DateTimeString,'yyyyMMdd',$null)
</code>```

EDIT: Added the following test data:

I created a test table in my SQL server called "m_test1" with the following data:

ID      Column

1       20200218junk

I used these statements:

```<code>$strSQL = 'SELECT TOP 1 LEFT([Column],8) as COL FROM [TEST].[dbo].[m_test1] ORDER BY ID'
$lastSQLDateArray = Invoke-Sqlcmd -ServerInstance 'servername' -Database 'TEST' -Query $strSQL
</code>```

And I got the following:

```<code>PS C:> $returnvalue

COL
---
20200218

PS C:> $returnvalue.COL
20200218

PS C:> [datetime]::ParseExact($returnvalue.COL,'yyyyMMdd',$null)

Tuesday, February 18, 2020 12:00:00 AM
</code>```

Hope this helps!  If it does, please don't forget to accept the answer using the check mark to the left.

Body:
I am trying to extract one row of data from a SQL Server table via PowerShell and convert the extracted value into a date.

The first 8 chars of the string should be in yyyymmdd format.

Firstly, I am having problems extracting the row...

As per various posts I've seen, it appears that when you grab a row, the data type that is returned is System.Data.DataRow. You then need to convert it into an Array. How do I grab the values from the array/datarow? Ideally, I'd like the value to come back as a String - as there will only be one value returned.
I am currently using something like this - but the content is null (even though the statement in SSMS returns one row)...

[array]$lastSQLdateArray = Invoke-Sqlcmd -ServerInstance INSTANCE -Database DATABASE -Query "SELECT TOP 1 LEFT(Column, 8) FROM [dbo].[Table] ORDER BY ID DESC"

for ($i=0; $i -le $lastSQLdateArray.Length; $i++)
{
  $formatOut = $formatOut + ($lastSQLdateArray[$i].ItemArray -join ",")
}

Then there is the question of converting the extracted yyyymmdd value (which ever data type it is) and convert it to a date.

How can I do this please?

Body:
Welcome, warnerj79. First of all, your SQL statement is a bit ambiguous.  I would recommend always specifying AS ColumnName when calculating parameters.  It will help later on.  I also like to put my SQL in a variable for readability.
So your SQL line becomes:

$strSQL = "SELECT TOP 1 LEFT(Column, 8) AS 'DateTimeString' FROM [dbo].[Table] ORDER BY ID DESC"
[array]$lastSQLdateArray = Invoke-Sqlcmd -ServerInstance INSTANCE -Database DATABASE -Query $strSQL

Then, your results variable ([array]$lastSQLdateArray) will contain one row (due to your use of TOP 1, so you would access the YYYYMMDD property like this:

$lastSQLdateArray[0].DateTimeString

Or because it is only one element in the array, this will work also:

$lastSQLdateArray.DateTimeString

That value is in a string format.  In order to convert that to a [datetime] variable, I would use the parseexact method like so:

$DateTimeVariable = [datetime]::ParseExact($lastSQLdateArray[0].DateTimeString,'yyyyMMdd',$null)

EDIT: Added the following test data:

I created a test table in my SQL server called "m_test1" with the following data:

ID      Column

1       20200218junk

I used these statements:

$strSQL = 'SELECT TOP 1 LEFT([Column],8) as COL FROM [TEST].[dbo].[m_test1] ORDER BY ID'
$lastSQLDateArray = Invoke-Sqlcmd -ServerInstance 'servername' -Database 'TEST' -Query $strSQL

And I got the following:

PS C:> $returnvalue

COL
---
20200218

PS C:> $returnvalue.COL
20200218

PS C:> [datetime]::ParseExact($returnvalue.COL,'yyyyMMdd',$null)

Tuesday, February 18, 2020 12:00:00 AM

Hope this helps!  If it does, please don't forget to accept the answer using the check mark to the left.


问:
Append item to list, which is dict value
I'm trying to create the dict which is "key": [value...]. When I use update function for dict and append for list of values, I get None:

The code block is:

```<code>some_items = ["val1", "val2", "val3"]

my_dict = {}
some_it = 0
test_list = []
for item in some_items:
    my_dict.update(
        {
            some_it : [].append(item)
        }
    )
    test_list.append(item)
    some_it +=1

</code>```

Finally I'd like to get sorting function, that filters data types for some criteria (key) and append all found values as value list to my dict.

答:
[].append(item) appends an item to the empty list, then throws away the result. What you probably wanted to do is:

```<code>for some_it, item in enumerate(some_items):
    my_dict.setdefault(some_it, []).append(item)
</code>```

Body:
I'm trying to create the dict which is "key": [value...]. When I use update function for dict and append for list of values, I get None:

The code block is:

some_items = ["val1", "val2", "val3"]

my_dict = {}
some_it = 0
test_list = []
for item in some_items:
    my_dict.update(
        {
            some_it : [].append(item)
        }
    )
    test_list.append(item)
    some_it +=1

Finally I'd like to get sorting function, that filters data types for some criteria (key) and append all found values as value list to my dict.

Body:
[].append(item) appends an item to the empty list, then throws away the result. What you probably wanted to do is:

for some_it, item in enumerate(some_items):
    my_dict.setdefault(some_it, []).append(item)


问:
java force an extending class
In Java, can I somehow force a class that extends an abstract class to implement its constructor with a Object as a parameter?

Something like

```<code>public abstract class Points {

    //add some abstract method to force constructor to have object.
}

public class ExtendPoints extends Points {

    /**
     * I want the abstract class to force this implementation to have
     *  a constructor with an object in it?
     * @param o
     */
    public ExtendPoints(Object o){

    }
}
</code>```

答:
EDIT

Well, no, its not possible to force the implementation of a constructor with argument.

Title: java force an extending class

Body:
In Java, can I somehow force a class that extends an abstract class to implement its constructor with a Object as a parameter?

Something like

public abstract class Points {

    //add some abstract method to force constructor to have object.
}

public class ExtendPoints extends Points {

    /**
     * I want the abstract class to force this implementation to have
     *  a constructor with an object in it?
     * @param o
     */
    public ExtendPoints(Object o){

    }
}


问:
Exporting Colors In React using TypeScript
Hey so I am using React with Typescript, and I have created a colors library to store all of our colors so they can be callable by importing LibraryColors and then doing LibraryColors.orange.primary for example. I want this to be easy to use for my team and so I want to give them intellisense when using it. I believe that is possible with an interface but I have no idea what that interface would look like.

```<code>interface ILibraryColors{

}
const LibraryColors: ILibraryColors = {
    black: {
        primary: "#000000",
    },
    green: {
        light: {
            60: "#40C0C0",
        },
        primary: "#00AEA9",
        dark: {
            40: "#00867C",
        }
    },
    grey: {
        light: {
            80: "#fafafa",
            70: "#dddddd",
            60: "#C4C7C5",
        },
        primary: "#707373",
        dark: {
            40: "#353735"
        }
    },
    orange: {
        light: {
            60: "#FFBB11",
        },
        primary: "#FAA21B",
        dark: {
            40: "#F58220"
        }
    },
    red: {
        light: {
            60: "F15B5D",
        },
        primary: "#E63E51",
        dark: {
            40: "#BC3A4B",
        }
    },
    white: {
        primary: "#ffffff",
    },
    pink: {
        primary: "#f434ed",
    },
    purple: {
        primary: "#1E4286",
    },
    blue: {
        light: {
            60: "#6BC3E7",
        },
        primary: "#06A7E0",
        dark: {
            40: "#005DA6",
        }
    }
}
</code>```

Any help is greatly appreciated, thank you! Also I know I could forget the primary, dark, and light and simply do 0-100 on the colors, but I think it is easier to remember which way gets lighter and darker this way.

答:
You can do something like this:

```<code>interface IColor {
    [key: number]: string;
}

interface IColorVariant {
    light?: IColor;
    dark?: IColor;
    primary?: string;
}

interface ILibraryColors{
    [key: string]: IColorVariant;
}
</code>```

But if you prefer a more explicit color variant use this:

```<code>interface IColor {
    10?: string;
    20?: string;
    30?: string;
    40?: string;
    50?: string;
    60?: string;
    70?: string;
    80?: string;
    90?: string;
    100?: string;
}

interface IColorVariant {
    light?: IColor;
    dark?: IColor;
    primary?: string;
}

interface ILibraryColors{
    [key: string]: IColorVariant;
}
</code>```

Body:
Hey so I am using React with Typescript, and I have created a colors library to store all of our colors so they can be callable by importing LibraryColors and then doing LibraryColors.orange.primary for example. I want this to be easy to use for my team and so I want to give them intellisense when using it. I believe that is possible with an interface but I have no idea what that interface would look like.

interface ILibraryColors{

}
const LibraryColors: ILibraryColors = {
    black: {
        primary: "#000000",
    },
    green: {
        light: {
            60: "#40C0C0",
        },
        primary: "#00AEA9",
        dark: {
            40: "#00867C",
        }
    },
    grey: {
        light: {
            80: "#fafafa",
            70: "#dddddd",
            60: "#C4C7C5",
        },
        primary: "#707373",
        dark: {
            40: "#353735"
        }
    },
    orange: {
        light: {
            60: "#FFBB11",
        },
        primary: "#FAA21B",
        dark: {
            40: "#F58220"
        }
    },
    red: {
        light: {
            60: "F15B5D",
        },
        primary: "#E63E51",
        dark: {
            40: "#BC3A4B",
        }
    },
    white: {
        primary: "#ffffff",
    },
    pink: {
        primary: "#f434ed",
    },
    purple: {
        primary: "#1E4286",
    },
    blue: {
        light: {
            60: "#6BC3E7",
        },
        primary: "#06A7E0",
        dark: {
            40: "#005DA6",
        }
    }
}

Any help is greatly appreciated, thank you! Also I know I could forget the primary, dark, and light and simply do 0-100 on the colors, but I think it is easier to remember which way gets lighter and darker this way.

Body:
You can do something like this:

interface IColor {
    [key: number]: string;
}

interface IColorVariant {
    light?: IColor;
    dark?: IColor;
    primary?: string;
}

interface ILibraryColors{
    [key: string]: IColorVariant;
}

But if you prefer a more explicit color variant use this:

interface IColor {
    10?: string;
    20?: string;
    30?: string;
    40?: string;
    50?: string;
    60?: string;
    70?: string;
    80?: string;
    90?: string;
    100?: string;
}

interface IColorVariant {
    light?: IColor;
    dark?: IColor;
    primary?: string;
}

interface ILibraryColors{
    [key: string]: IColorVariant;
}


问:
How to "rearrange" an Aeson.Object using lenses?
It seems I keep getting stuck whenever I reach out for lenses to transform some JSON.

After parsing this into an Aeson.Value...

```<code>{
  "action": {
    "action": "reply",
    "replies": [
      "Does this work?",
      "What about this?"
    ]
  },
  "suggestions": [...],
  "inputs": [...]
}

</code>```

...I'm trying to transform it into...

```<code>{
  "action": "reply",
  "replies": [
    "Does this work?",
    "What about this?"
  ]
  "suggestions": [...],
  "inputs": [...]
}
</code>```

Basically I'm trying to bring all keys-value pairs nested inside the top-level action-key to the top-level itself, and finally remove the top-level action key. (Note, there is a nested action key inside the top-level action key -- it is not a typo).

答:
Using lenses from the lens-aeson package, I guess what you want is something like:

```<code>Object $ (x ^. _Object & sans "action") <> (x ^. key "action"._Object)
</code>```

Here, sans comes from Control.Lens.At and removes the top-level "action", leaving an Object (i.e., HashMap Text Value) with the remaining top-level keys.  The key "action"._Object getter selects the top-level "action" value and extracts an Object.  The two Objects can be concatenated using <> and wrapped into a Value with the Object constructor.

Full code:

```<code>{-# LANGUAGE OverloadedStrings #-}

module AesonLens where

import Data.Aeson
import Data.Aeson.Lens     -- from lens-aeson
import Control.Lens

ex1 :: IO Value
ex1 = do Just val <- decodeFileStrict "aesonlens.json"
         return val

main = do
  x <- ex1
  print $ Object $ (x ^. _Object & sans "action") <> (x ^. key "action"._Object)
</code>```

with input file "aesonlens.json":

```<code>{
  "action": {
    "action": "reply",
    "replies": [
      "Does this work?",
      "What about this?"
    ]
  },
  "suggestions": [1,2,3],
  "inputs": [4,5,6]
}
</code>```

yields:

```<code>> main
Object (fromList [("inputs",Array [Number 4.0,Number 5.0,Number 6.0]),
("action",String "reply"),("replies",Array [String "Does this work?",
String "What about this?"]),("suggestions",Array [Number 1.0,Number 2.0,
Number 3.0])])
</code>```

Body:
It seems I keep getting stuck whenever I reach out for lenses to transform some JSON.

After parsing this into an Aeson.Value...

{
  "action": {
    "action": "reply",
    "replies": [
      "Does this work?",
      "What about this?"
    ]
  },
  "suggestions": [...],
  "inputs": [...]
}

...I'm trying to transform it into...

{
  "action": "reply",
  "replies": [
    "Does this work?",
    "What about this?"
  ]
  "suggestions": [...],
  "inputs": [...]
}

Basically I'm trying to bring all keys-value pairs nested inside the top-level action-key to the top-level itself, and finally remove the top-level action key. (Note, there is a nested action key inside the top-level action key -- it is not a typo).

Body:
Using lenses from the lens-aeson package, I guess what you want is something like:

Object $ (x ^. _Object & sans "action") <> (x ^. key "action"._Object)

Here, sans comes from Control.Lens.At and removes the top-level "action", leaving an Object (i.e., HashMap Text Value) with the remaining top-level keys.  The key "action"._Object getter selects the top-level "action" value and extracts an Object.  The two Objects can be concatenated using <> and wrapped into a Value with the Object constructor.

Full code:

{-# LANGUAGE OverloadedStrings #-}

module AesonLens where

import Data.Aeson
import Data.Aeson.Lens     -- from lens-aeson
import Control.Lens

ex1 :: IO Value
ex1 = do Just val <- decodeFileStrict "aesonlens.json"
         return val

main = do
  x <- ex1
  print $ Object $ (x ^. _Object & sans "action") <> (x ^. key "action"._Object)

with input file "aesonlens.json":

{
  "action": {
    "action": "reply",
    "replies": [
      "Does this work?",
      "What about this?"
    ]
  },
  "suggestions": [1,2,3],
  "inputs": [4,5,6]
}

yields:

> main
Object (fromList [("inputs",Array [Number 4.0,Number 5.0,Number 6.0]),
("action",String "reply"),("replies",Array [String "Does this work?",
String "What about this?"]),("suggestions",Array [Number 1.0,Number 2.0,
Number 3.0])])


问:
How to combine column groups in PrimeNg Tree table with unscrollable column?
I'm using primeng 7.1.3.

What I'm trying to create is a scrollable tree table (horizontal and vertical) with:

the 1st column not scrollable

2 groups of column excluding the 1st one

I managed to get something like this: StackBlitz code.

Begin of Edit ---------------------------------------------------

I found a way around so I have updated the Stackblitz link to correct the problem. If you want to see the original problem, comment the ngAfterViewInit() in the app-component.ts file. Also updated tags of the question because of said solution.

End of Edit -------------------------------------------------------

From what I understand, it puts the 2 groups above the first column - instead of leaving an empty cell the size of 2 rows - and the other columns as it should be.

Documentation for tree tables: PrimeNg Tree Table documentation

Column group

Scroll

Any hint on how to solve this?

Thanks.

答:
So I came up with a solution but it's not very clean.

Instead of going deep in PrimeNg framework and tinkering with its code, I decided to use ngAfterViewInit and work on the produced DOM. From here, I just looked for the cells that shouldn't have been here and deleted them. I also updated the height of the empty cell.

Below is the function used in ngAfterViewInit():

```<code>correctDOM(): void {
  function cleanFixedHeader(tagName: string, element: Element): Element {
    const listElementsByTagName = element.getElementsByTagName(tagName);

    if (listElementsByTagName.length === 0) {
      return null;
    }

    for (let i = 0; i < listElementsByTagName.length - 1; i++) {
      element.removeChild(listElementsByTagName[i]);
    }
    return listElementsByTagName[listElementsByTagName.length - 1];
  }

  const treeTableFixedHead: Element = this.elRef.nativeElement
                                  .getElementsByClassName('ui-treetable-frozen-view')[0]
                                  .getElementsByClassName('ui-treetable-thead')[0];

  const treeTableFixedRow = cleanFixedHeader('TR', treeTableFixedHead);
  if (treeTableFixedRow !== null) {
    const treeTableFixedHeaderCell = cleanFixedHeader('TH', treeTableFixedRow);
    treeTableFixedHeaderCell.setAttribute('height', String(treeTableFixedHeaderCell.getBoundingClientRect().height * 2));
  }
}
</code>```

Stackblitz link, same as in the question. I will edit said question to indicate how to see the original issue.

Hope it'll help someone as it doesn't seem many questions are asked about PrimeNg. Still, keep in mind that this solution is really not a clean one. But it saved me a lot of time so...

Body:
So I came up with a solution but it's not very clean.

Instead of going deep in PrimeNg framework and tinkering with its code, I decided to use ngAfterViewInit and work on the produced DOM. From here, I just looked for the cells that shouldn't have been here and deleted them. I also updated the height of the empty cell.

Below is the function used in ngAfterViewInit():

correctDOM(): void {
  function cleanFixedHeader(tagName: string, element: Element): Element {
    const listElementsByTagName = element.getElementsByTagName(tagName);

    if (listElementsByTagName.length === 0) {
      return null;
    }

    for (let i = 0; i < listElementsByTagName.length - 1; i++) {
      element.removeChild(listElementsByTagName[i]);
    }
    return listElementsByTagName[listElementsByTagName.length - 1];
  }

  const treeTableFixedHead: Element = this.elRef.nativeElement
                                  .getElementsByClassName('ui-treetable-frozen-view')[0]
                                  .getElementsByClassName('ui-treetable-thead')[0];

  const treeTableFixedRow = cleanFixedHeader('TR', treeTableFixedHead);
  if (treeTableFixedRow !== null) {
    const treeTableFixedHeaderCell = cleanFixedHeader('TH', treeTableFixedRow);
    treeTableFixedHeaderCell.setAttribute('height', String(treeTableFixedHeaderCell.getBoundingClientRect().height * 2));
  }
}

Stackblitz link, same as in the question. I will edit said question to indicate how to see the original issue.

Hope it'll help someone as it doesn't seem many questions are asked about PrimeNg. Still, keep in mind that this solution is really not a clean one. But it saved me a lot of time so...


问:
Hide/show element on click or mediaqueries
On mobile > hide content and add a display button, click on the button display the content.
On Dekstop > display content hide the button.

```<code>var trickvis = true;
if (trickvis) {
    $('.trick').show(); // Affiche
 } else {
    $('.trick').hide();
   console.log('HIDE THE TRICKS');
 }

function myFunction(x) {

 if (x.matches) { // If media query matches
   var trickvis = false; // Cache les tricks
   $('.bttest').show(); // Ajout du bouton

 } else {
   trickvis = true;
   $('.bttest').hide();
 }
}

$( ".bttest" ).click(function() {
 trickvis = true ;
});
var x = window.matchMedia("(max-width: 700px)")
myFunction(x) // Call listener function at run time
x.addListener(myFunction) // Attach listener function on state changes

</code>```

Codepen : https://codepen.io/gloreau/pen/XWbKzab

I tried using a true false option for the hide show and modifying the true false if mobile dekstop or if the button was clicked but this don't seems to work :(.

```<code><article class="trick">
  loilul
</article>
<article class="trick">
  loilul
</article>
<article class="trick">
  loilul
</article>
<button class="bttest"  type="button">Show </button>
</code>```

答:
You can do this with css media queries without the need for any JS. Give a 'content' class to the 'content' DOM element and a 'display-button' class to the display button element, and use the css visibility property as follows. You may optionally use the display property as which ever is appropriate for you. With display, however, the values are either block or none, among others omitted for simplicity.

```<code>.content {
   visibility: hidden;
}
.display-button {
   visibility: visible;
}

@media only screen and (min-width: 768px) {
   .display-button {
      visibility: hidden;
   }
   .content  {
      visibility: visible;
   }
}
</code>```

UPDATE:

The reason your code is not behaving as required is because you are showing/hiding only the "show button" on screen size change, you're not doing anything on the content( class="trick" ). Hide/shown the content as well depending on the screen size.

function myFunction(x) {

  if (x.matches) { // If media query matches
    var trickvis = false; // Cache les tricks
    $('.trick').hide(); // Ajout du bouton
    $('.bttest').show();
  }
  else {
    trickvis = true;
    $('.bttest').hide();
    $('.trick').show();
  }
}

$( ".bttest" ).click(function() {
  $('.trick').show(); // Affiche
});

var x = window.matchMedia("(max-width: 700px)")
myFunction(x) // Call listener function at run time
x.addListener(myFunction) // Attach listener function on state changes```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* CSS a retirer */
.trick {
  width:50px;
  height:50px;
  background:red;
  margin:1em;
}</code>```

  loilul

  loilul

  loilul

<button class="bttest"  type="button">Show </button>```

Body:
On mobile > hide content and add a display button, click on the button display the content.
On Dekstop > display content hide the button.

var trickvis = true;
if (trickvis) {
    $('.trick').show(); // Affiche
 } else {
    $('.trick').hide();
   console.log('HIDE THE TRICKS');
 }

function myFunction(x) {

 if (x.matches) { // If media query matches
   var trickvis = false; // Cache les tricks
   $('.bttest').show(); // Ajout du bouton

 } else {
   trickvis = true;
   $('.bttest').hide();
 }
}

$( ".bttest" ).click(function() {
 trickvis = true ;
});
var x = window.matchMedia("(max-width: 700px)")
myFunction(x) // Call listener function at run time
x.addListener(myFunction) // Attach listener function on state changes

Codepen : https://codepen.io/gloreau/pen/XWbKzab

I tried using a true false option for the hide show and modifying the true false if mobile dekstop or if the button was clicked but this don't seems to work :(.

  loilul

  loilul

  loilul

<button class="bttest"  type="button">Show </button>

Body:
You can do this with css media queries without the need for any JS. Give a 'content' class to the 'content' DOM element and a 'display-button' class to the display button element, and use the css visibility property as follows. You may optionally use the display property as which ever is appropriate for you. With display, however, the values are either block or none, among others omitted for simplicity.

.content {
   visibility: hidden;
}
.display-button {
   visibility: visible;
}

@media only screen and (min-width: 768px) {
   .display-button {
      visibility: hidden;
   }
   .content  {
      visibility: visible;
   }
}

UPDATE:

The reason your code is not behaving as required is because you are showing/hiding only the "show button" on screen size change, you're not doing anything on the content( class="trick" ). Hide/shown the content as well depending on the screen size.

function myFunction(x) {

  if (x.matches) { // If media query matches
    var trickvis = false; // Cache les tricks
    $('.trick').hide(); // Ajout du bouton
    $('.bttest').show();
  }
  else {
    trickvis = true;
    $('.bttest').hide();
    $('.trick').show();
  }
}

$( ".bttest" ).click(function() {
  $('.trick').show(); // Affiche
});

var x = window.matchMedia("(max-width: 700px)")
myFunction(x) // Call listener function at run time
x.addListener(myFunction) // Attach listener function on state changes

/* CSS a retirer */
.trick {
  width:50px;
  height:50px;
  background:red;
  margin:1em;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<article class="trick">
  loilul
</article>
<article class="trick">
  loilul
</article>
<article class="trick">
  loilul
</article>
<button class="bttest"  type="button">Show </button>


问:
using thread local to avoid map creation to reduce GC but failed
To avoid online GC issues.

Background

The original map will be copied to the thread (contained in a thread pool) and within that thread, the copied map could be updated and after the update, some copied maps might feed back to the original map.

Experient considerations

The online conditions have two typical conditions compared to my local mac book:

much better performant servers (CPU, memory, and IO)

high throughputs (million-level QPS)

The size info for the origMap could be: 50 keys, and each value is about 50 chars.

Current solution

I am now using a ThreadLocal to build up a ReusableMap to ensure each map is bond to the thread and when the copy is required, and the map to the thread is already created, we can directly use the map.

of course, we will need to clear the map first and copy the content from the original map.

I thought it would reduce the GC, but as I run some test using jmh and monitor the result in Visual GC via jvisualvm; I sadly found it was not as I expected. Still there are lots of GCs as before.

Updated 2020-02-21

First, really thanks to the help of @Holger and @GotoFinal, I tried other different options with my limited understanding. But so far, so bad, nothing works with my local test.

Nothing beneficial comes out, and I think I will try something different to dig deeper related to JVM optimisation and caching tech.

Just for the reference, the tests I've run as follows:

adjust the map size in key aspect, value size in length aspect;

use plain huge loop by removing jmh to eliminate lurking influences;

use several maps (instead of just one - since there are scenarios, we need to pass several);

make restrictive changes in child thread to maintain higher re-use in entry and node aspect if using

```<code>cacheMap.putAll(origMap)
cacheMap.keySet().retainAll(origMap.keySet())
</code>```

run the tests longer from 10 mins to 2h30m;

Some code to demonstrate what I just mentioned:

```<code>public class ReusableHashMapTwoCopy {
    private static final String DEFAULT_MAP_KEY = "defaultMap";
    /**
     * weak or soft reference perhaps could be used: https://stackoverflow.com/a/299702/2361308
     * <p>
     * via the static ThreadLocal initialized, each thread will only see the value it set itself;
     */
    private static ThreadLocal<Map> theCache = new ThreadLocal<>();

    /**
     * the default usage when there is only one map passed from parent
     * thread to child thread.
     *
     * @param origMap the parent map
     * @param <K>     generic type for the key
     * @param <V>     generic type for the value
     * @return a map used within the child thread - the reusable map
     */
    public static <K, V> Map<K, V> getMap(Map<K, V> origMap) {
        return getMap(DEFAULT_MAP_KEY, origMap);
    }

    public static <K, V> Map<K, V> getMap() {
        return getMap(DEFAULT_MAP_KEY);
    }

    /**
     * clone the parent-thread map at the beginning of the child thread,
     * after which you can use the map as usual while it's thread-localized;
     * <p>
     * no extra map is created for the thread any more - preventing us from creating
     * map instance all the time.
     *
     * @param theMapKey the unique key to specify the map to be passed into the child thread;
     * @param origMap   the parent map
     * @param <K>       generic type for the key
     * @param <V>       generic type for the value
     * @return the cached map reused within the child thread
     */
    public static <K, V> Map<K, V> getMap(String theMapKey, Map<K, V> origMap) {
        Map<String, Map<K, V>> threadCache = theCache.get();
        if (Objects.isNull(threadCache)) {
//            System.out.println("## creating thread cache");
            threadCache = new HashMap<>();
            theCache.set(threadCache);
        } else {
//            System.out.println("**## reusing thread cache");
        }
        Map<K, V> cacheMap = threadCache.get(theMapKey);
        if (Objects.isNull(cacheMap)) {
//            System.out.println("  ## creating thread map cache for " + theMapKey);
            cacheMap = new HashMap<>();
        } else {
//            System.out.println("  **## reusing thread map cache for " + theMapKey);
            cacheMap.clear();
        }
        if (MapUtils.isNotEmpty(origMap)) {
            cacheMap.putAll(origMap);
            cacheMap.keySet().retainAll(origMap.keySet());
        }
        threadCache.put(theMapKey, cacheMap);
        return cacheMap;
    }

    public static <K, V> Map<K, V> getMap(String theMapKey) {
        return getMap(theMapKey, null);
    }

    public static void main(String[] args) throws Exception {
        org.openjdk.jmh.Main.main(args);
//        print(MyState.parentMapMedium_0);
//        print(MyState.parentMapSmall_0);
    }

    private static void blackhole(Object o) {

    }

    @Benchmark
    @Fork(value = 1, warmups = 0, jvmArgs = {"-Xms50M", "-Xmx50M"})
    @Warmup(iterations = 1, time = 5)
    @Timeout(time = 3, timeUnit = TimeUnit.HOURS)
    @BenchmarkMode(Mode.Throughput)
    @OutputTimeUnit(TimeUnit.MINUTES)
    @Measurement(iterations = 1, time = 150, timeUnit = TimeUnit.MINUTES)
    public void testMethod() throws Exception {
        final Map<String, String> theParentMap0 = MyState.parentMapSmall_0;
        final Map<String, String> theParentMap1 = MyState.parentMapSmall_1;
//        final Map<String, String> theParentMap0 = MyState.parentMapMedium_0;
//        final Map<String, String> theParentMap1 = MyState.parentMapMedium_1;
        ThreadUtils.getTheSharedPool().submit(() -> {
            try {
                Map<String, String> theChildMap0 = new HashMap<>(theParentMap0);
                theChildMap0.put("test0", "child");

                Map<String, String> theChildMap1 = new HashMap<>(theParentMap1);
                theChildMap1.put("test1", "child");

                for (int j = 0; j < 1_0; ++j) {
                    blackhole(theChildMap0);
                    blackhole(theChildMap1);
                    sleep(10);
                }
            } catch (Exception e) {
                System.err.println(e.getMessage());
            }
        }).get();
    }

    private static void print(Object o) {
        print(o, "");
    }

    private static void print(Object o, String content) {
        String s = String
                .format("%s: current thread: %s map: %s", content, Thread.currentThread().getName(), toJson(o));
        System.out.println(s);
    }

    @State(Scope.Benchmark)
    public static class MyState {
        // 20 & 100 -> 2.5k
        static Map<String, String> parentMapSmall_0 = generateAMap(20, 100);
        static Map<String, String> parentMapSmall_1 = generateAMap(20, 100);
        // 200 & 200 -> 45k
        static Map<String, String> parentMapMedium_0 = generateAMap(200, 200);
        static Map<String, String> parentMapMedium_1 = generateAMap(200, 200);
    }

    private static Map<String, String> generateAMap(int size, int lenLimit) {
        Map<String, String> res = new HashMap<>();
        String aKey = "key - ";
        String aValue = "value - ";
        for (int i = 0; i < size; ++i) {
            aKey = i + " - " + LocalDateTime.now().toString();
            aValue = i + " - " + LocalDateTime.now().toString() + aValue;
            res.put(aKey.substring(0, Math.min(aKey.length(), lenLimit)),
                    aValue.substring(0, Math.min(aValue.length(), lenLimit)));
        }
        return res;
    }
}
</code>```

答:
HashMap contains array of Node object inside, and if you call hashMap.clear() this array is cleared, so all the Node objects are now available for Garbage collection.

So caching map like that will not help at all.

If you want to limit about of GC maybe you could just use ConcurrentHashMap? If you need to split work between threads you could just pass list/array of keys to each thread that they should operate on and return list of updated values.
Hard to tell more without exact description of problem you are trying to solve.

But first you also should think if you really need this, you really need to stress java a lot to get real issues with GC that can't be solved by some simple tuning, as long as you will give some normal amount of memory to java process.

Another solution is one proposed by Holger:

Instead of using cacheMap.clear() just do:

```<code>cacheMap.putAll(origMap)
cacheMap.keySet().retainAll(origMap.keySet())
</code>```

Each time you want to use this map.

Additionally if you don't need to worry about leaking keys - so all keys can be present in memory all time - then you could also use a bit more risky solution that would get rid of all allocations but would require to use map in special way:

```<code>cacheMap.replaceAll((key, value) -> null);
</code>```

Then all keys are still present in map, but values are null, so then when using a map you can just ignore null values. You could also use some kind of null object if needed/possible.

Body:
To avoid online GC issues.

Background

The original map will be copied to the thread (contained in a thread pool) and within that thread, the copied map could be updated and after the update, some copied maps might feed back to the original map.

Experient considerations

The online conditions have two typical conditions compared to my local mac book:

much better performant servers (CPU, memory, and IO)

high throughputs (million-level QPS)

The size info for the origMap could be: 50 keys, and each value is about 50 chars.

Current solution

I am now using a ThreadLocal to build up a ReusableMap to ensure each map is bond to the thread and when the copy is required, and the map to the thread is already created, we can directly use the map.

of course, we will need to clear the map first and copy the content from the original map.

I thought it would reduce the GC, but as I run some test using jmh and monitor the result in Visual GC via jvisualvm; I sadly found it was not as I expected. Still there are lots of GCs as before.

Updated 2020-02-21

First, really thanks to the help of @Holger and @GotoFinal, I tried other different options with my limited understanding. But so far, so bad, nothing works with my local test.

Nothing beneficial comes out, and I think I will try something different to dig deeper related to JVM optimisation and caching tech.

Just for the reference, the tests I've run as follows:

adjust the map size in key aspect, value size in length aspect;

use plain huge loop by removing jmh to eliminate lurking influences;

use several maps (instead of just one - since there are scenarios, we need to pass several);

make restrictive changes in child thread to maintain higher re-use in entry and node aspect if using

cacheMap.putAll(origMap)
cacheMap.keySet().retainAll(origMap.keySet())

run the tests longer from 10 mins to 2h30m;

Some code to demonstrate what I just mentioned:

public class ReusableHashMapTwoCopy {
    private static final String DEFAULT_MAP_KEY = "defaultMap";
    /**
     * weak or soft reference perhaps could be used: https://stackoverflow.com/a/299702/2361308
     *

     * via the static ThreadLocal initialized, each thread will only see the value it set itself;
     */
    private static ThreadLocal<Map> theCache = new ThreadLocal<>();

    /**
     * the default usage when there is only one map passed from parent
     * thread to child thread.
     *
     * @param origMap the parent map
     * @param <K>     generic type for the key
     * @param <V>     generic type for the value
     * @return a map used within the child thread - the reusable map
     */
    public static <K, V> Map<K, V> getMap(Map<K, V> origMap) {
        return getMap(DEFAULT_MAP_KEY, origMap);
    }

    public static <K, V> Map<K, V> getMap() {
        return getMap(DEFAULT_MAP_KEY);
    }

    /**
     * clone the parent-thread map at the beginning of the child thread,
     * after which you can use the map as usual while it's thread-localized;
     *

     * no extra map is created for the thread any more - preventing us from creating
     * map instance all the time.
     *
     * @param theMapKey the unique key to specify the map to be passed into the child thread;
     * @param origMap   the parent map
     * @param <K>       generic type for the key
     * @param <V>       generic type for the value
     * @return the cached map reused within the child thread
     */
    public static <K, V> Map<K, V> getMap(String theMapKey, Map<K, V> origMap) {
        Map<String, Map<K, V>> threadCache = theCache.get();
        if (Objects.isNull(threadCache)) {
//            System.out.println("## creating thread cache");
            threadCache = new HashMap<>();
            theCache.set(threadCache);
        } else {
//            System.out.println("**## reusing thread cache");
        }
        Map<K, V> cacheMap = threadCache.get(theMapKey);
        if (Objects.isNull(cacheMap)) {
//            System.out.println("  ## creating thread map cache for " + theMapKey);
            cacheMap = new HashMap<>();
        } else {
//            System.out.println("  **## reusing thread map cache for " + theMapKey);
            cacheMap.clear();
        }
        if (MapUtils.isNotEmpty(origMap)) {
            cacheMap.putAll(origMap);
            cacheMap.keySet().retainAll(origMap.keySet());
        }
        threadCache.put(theMapKey, cacheMap);
        return cacheMap;
    }

    public static <K, V> Map<K, V> getMap(String theMapKey) {
        return getMap(theMapKey, null);
    }

    public static void main(String[] args) throws Exception {
        org.openjdk.jmh.Main.main(args);
//        print(MyState.parentMapMedium_0);
//        print(MyState.parentMapSmall_0);
    }

    private static void blackhole(Object o) {

    }

    @Benchmark
    @Fork(value = 1, warmups = 0, jvmArgs = {"-Xms50M", "-Xmx50M"})
    @Warmup(iterations = 1, time = 5)
    @Timeout(time = 3, timeUnit = TimeUnit.HOURS)
    @BenchmarkMode(Mode.Throughput)
    @OutputTimeUnit(TimeUnit.MINUTES)
    @Measurement(iterations = 1, time = 150, timeUnit = TimeUnit.MINUTES)
    public void testMethod() throws Exception {
        final Map<String, String> theParentMap0 = MyState.parentMapSmall_0;
        final Map<String, String> theParentMap1 = MyState.parentMapSmall_1;
//        final Map<String, String> theParentMap0 = MyState.parentMapMedium_0;
//        final Map<String, String> theParentMap1 = MyState.parentMapMedium_1;
        ThreadUtils.getTheSharedPool().submit(() -> {
            try {
                Map<String, String> theChildMap0 = new HashMap<>(theParentMap0);
                theChildMap0.put("test0", "child");

                Map<String, String> theChildMap1 = new HashMap<>(theParentMap1);
                theChildMap1.put("test1", "child");

                for (int j = 0; j < 1_0; ++j) {
                    blackhole(theChildMap0);
                    blackhole(theChildMap1);
                    sleep(10);
                }
            } catch (Exception e) {
                System.err.println(e.getMessage());
            }
        }).get();
    }

    private static void print(Object o) {
        print(o, "");
    }

    private static void print(Object o, String content) {
        String s = String
                .format("%s: current thread: %s map: %s", content, Thread.currentThread().getName(), toJson(o));
        System.out.println(s);
    }

    @State(Scope.Benchmark)
    public static class MyState {
        // 20 & 100 -> 2.5k
        static Map<String, String> parentMapSmall_0 = generateAMap(20, 100);
        static Map<String, String> parentMapSmall_1 = generateAMap(20, 100);
        // 200 & 200 -> 45k
        static Map<String, String> parentMapMedium_0 = generateAMap(200, 200);
        static Map<String, String> parentMapMedium_1 = generateAMap(200, 200);
    }

    private static Map<String, String> generateAMap(int size, int lenLimit) {
        Map<String, String> res = new HashMap<>();
        String aKey = "key - ";
        String aValue = "value - ";
        for (int i = 0; i < size; ++i) {
            aKey = i + " - " + LocalDateTime.now().toString();
            aValue = i + " - " + LocalDateTime.now().toString() + aValue;
            res.put(aKey.substring(0, Math.min(aKey.length(), lenLimit)),
                    aValue.substring(0, Math.min(aValue.length(), lenLimit)));
        }
        return res;
    }
}

Body:
HashMap contains array of Node object inside, and if you call hashMap.clear() this array is cleared, so all the Node objects are now available for Garbage collection.

So caching map like that will not help at all.

If you want to limit about of GC maybe you could just use ConcurrentHashMap? If you need to split work between threads you could just pass list/array of keys to each thread that they should operate on and return list of updated values.
Hard to tell more without exact description of problem you are trying to solve.

But first you also should think if you really need this, you really need to stress java a lot to get real issues with GC that can't be solved by some simple tuning, as long as you will give some normal amount of memory to java process.

Another solution is one proposed by Holger:

Instead of using cacheMap.clear() just do:

cacheMap.putAll(origMap)
cacheMap.keySet().retainAll(origMap.keySet())

Each time you want to use this map.

Additionally if you don't need to worry about leaking keys - so all keys can be present in memory all time - then you could also use a bit more risky solution that would get rid of all allocations but would require to use map in special way:

cacheMap.replaceAll((key, value) -> null);

Then all keys are still present in map, but values are null, so then when using a map you can just ignore null values. You could also use some kind of null object if needed/possible.


问:
Regarding usage of Task.Start() , Task.Run() and Task.Factory.StartNew()
I just saw 3 routines regarding TPL usage which do the same job; here is the code:

```<code>public static void Main()
{
    Thread.CurrentThread.Name = "Main";

    // Create a task and supply a user delegate by using a lambda expression.
    Task taskA = new Task( () => Console.WriteLine("Hello from taskA."));
    // Start the task.
    taskA.Start();

    // Output a message from the calling thread.
    Console.WriteLine("Hello from thread '{0}'.",
                  Thread.CurrentThread.Name);
    taskA.Wait();
}

public static void Main()
{
    Thread.CurrentThread.Name = "Main";

    // Define and run the task.
    Task taskA = Task.Run( () => Console.WriteLine("Hello from taskA."));

    // Output a message from the calling thread.
    Console.WriteLine("Hello from thread '{0}'.",
                      Thread.CurrentThread.Name);
    taskA.Wait();
}

public static void Main()
{
    Thread.CurrentThread.Name = "Main";

    // Better: Create and start the task in one operation.
    Task taskA = Task.Factory.StartNew(() => Console.WriteLine("Hello from taskA."));

    // Output a message from the calling thread.
    Console.WriteLine("Hello from thread '{0}'.",
                    Thread.CurrentThread.Name);

    taskA.Wait();
}
</code>```

I just do not understand why MS gives 3 different ways to run jobs in TPL because they all work the same: Task.Start(), Task.Run() and Task.Factory.StartNew().

Tell me, are Task.Start(), Task.Run() and Task.Factory.StartNew() all used for the same purpose or do they have different significance?

When should one use Task.Start(), when should one use Task.Run() and when should one use Task.Factory.StartNew()?

Please help me to understand their real usage as per scenario in great detail with examples, thanks.

答:
Short answer:

If you are not using nested children's tasks and always want your tasks to be executed on Thread Pool it is better to use Task.Run.

Long answer:

Task.Run and  Task.Factory.StartNew both provides support for creating and scheduling Task objects so we don't need to create a Task and call Start()

```<code>Task.Run(action);
</code>```

Is equivalent to:

```<code>Task.Factory.StartNew(action, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
</code>```

And

```<code>Task.Factory.StartNew(action);
</code>```

Is equivalent to:

```<code>Task.Factory.StartNew(action, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Current);
</code>```

Task.Run uses TaskCreationOptions.DenyChildAttach which means that children's tasks can not be attached to the parent and it uses TaskScheduler.Default which means that the one that runs tasks on Thread Pool will always be used to run tasks.

Task.Factory.StartNew uses TaskScheduler.Current which means scheduler of the current thread, it might be TaskScheduler.Default but not always.

Body:
I just saw 3 routines regarding TPL usage which do the same job; here is the code:

public static void Main()
{
    Thread.CurrentThread.Name = "Main";

    // Create a task and supply a user delegate by using a lambda expression.
    Task taskA = new Task( () => Console.WriteLine("Hello from taskA."));
    // Start the task.
    taskA.Start();

    // Output a message from the calling thread.
    Console.WriteLine("Hello from thread '{0}'.",
                  Thread.CurrentThread.Name);
    taskA.Wait();
}

public static void Main()
{
    Thread.CurrentThread.Name = "Main";

    // Define and run the task.
    Task taskA = Task.Run( () => Console.WriteLine("Hello from taskA."));

    // Output a message from the calling thread.
    Console.WriteLine("Hello from thread '{0}'.",
                      Thread.CurrentThread.Name);
    taskA.Wait();
}

public static void Main()
{
    Thread.CurrentThread.Name = "Main";

    // Better: Create and start the task in one operation.
    Task taskA = Task.Factory.StartNew(() => Console.WriteLine("Hello from taskA."));

    // Output a message from the calling thread.
    Console.WriteLine("Hello from thread '{0}'.",
                    Thread.CurrentThread.Name);

    taskA.Wait();
}

I just do not understand why MS gives 3 different ways to run jobs in TPL because they all work the same: Task.Start(), Task.Run() and Task.Factory.StartNew().

Tell me, are Task.Start(), Task.Run() and Task.Factory.StartNew() all used for the same purpose or do they have different significance?

When should one use Task.Start(), when should one use Task.Run() and when should one use Task.Factory.StartNew()?

Please help me to understand their real usage as per scenario in great detail with examples, thanks.

Body:
Short answer:

If you are not using nested children's tasks and always want your tasks to be executed on Thread Pool it is better to use Task.Run.

Long answer:

Task.Run and  Task.Factory.StartNew both provides support for creating and scheduling Task objects so we don't need to create a Task and call Start()

Task.Run(action);

Is equivalent to:

Task.Factory.StartNew(action, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);

And

Task.Factory.StartNew(action);

Is equivalent to:

Task.Factory.StartNew(action, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Current);

Task.Run uses TaskCreationOptions.DenyChildAttach which means that children's tasks can not be attached to the parent and it uses TaskScheduler.Default which means that the one that runs tasks on Thread Pool will always be used to run tasks.

Task.Factory.StartNew uses TaskScheduler.Current which means scheduler of the current thread, it might be TaskScheduler.Default but not always.


问:
Issues with pydatatable frame output in google colab
I'm doing data wrangling on a dataset using pydatatable in google colab notebooks, on executing code chunks its displaying two different output formats of a frame, where as the same dataframe with pandas displays a single output, i'm attaching hera a screenshot of it for reference.

Could you please let me know any options should be configured in dt displays to have a correct output format?. or something is wrong in google colab notebooks?.

答: It's been clarified to me by pydatatable team, and i would have to contact google colab team for this issue. and for now i'm not going to use this in Colab notebooks.</p>


问:
R: unite every distinct value in one column into another
I have a data that looks something like this (but actually much larger, around 100000 lines).

```<code>  ID CODE
1  A   F1
2  A   F2
3  B   F3
4  B   F1
5  C   F1
6  C   F1
7  C   F2
</code>```

I need to write all different CODEs for each ID into one column. I have gotten half the way by doing:

```<code>Data %>% arrange(ID) %>% group_by(ID) %>% distinct(CODE)
  CODE  ID
  <fct> <fct>
1 F1    A
2 F2    A
3 F3    B
4 F1    B
5 F1    C
6 F2    C
</code>```

But what I need should look something like this (where column all_CODEs holds all codes for each ID written into string):

```<code>  ID all_CODEs
1  A     F1 F2
2  B     F3 F1
3  C     F1 F2
</code>```

Can anyone help?

答:
If you are up for a base R solution, Assuming df is your dataframe:

```<code>df1 <- df[!duplicated(df),] ## removing duplicates basis df

aggregate( CODE ~ ID, data=df1, paste0, collapse=" ")
</code>```

Output:

```<code>#  ID  CODE
#1  A F1 F2
#2  B F3 F1
#3  C F1 F2
</code>```

Body:
I have a data that looks something like this (but actually much larger, around 100000 lines).

  ID CODE
1  A   F1
2  A   F2
3  B   F3
4  B   F1
5  C   F1
6  C   F1
7  C   F2

I need to write all different CODEs for each ID into one column. I have gotten half the way by doing:

Data %>% arrange(ID) %>% group_by(ID) %>% distinct(CODE)
  CODE  ID
  <fct> <fct>
1 F1    A
2 F2    A
3 F3    B
4 F1    B
5 F1    C
6 F2    C

But what I need should look something like this (where column all_CODEs holds all codes for each ID written into string):

  ID all_CODEs
1  A     F1 F2
2  B     F3 F1
3  C     F1 F2

Can anyone help?

Body:
If you are up for a base R solution, Assuming df is your dataframe:

df1 <- df[!duplicated(df),] ## removing duplicates basis df

aggregate( CODE ~ ID, data=df1, paste0, collapse=" ")

Output:

#  ID  CODE
#1  A F1 F2
#2  B F3 F1
#3  C F1 F2


问:
how can manipulate the different kind of array (string, int, char) as same format such as string in C#?
I have a collection of objects that each object would contains a different kind of array (string[],int[],char[]) or even single value as different types.

I want to get the values of each array as single format such as string  and convert it to a comma text value.

here is the code that manipulates an object of collection as "UInt16[]"

```<code>UInt16[] arrCapabilities = (UInt16[])(queryObj["Capabilities"]);
foreach (UInt16 arrValue in arrCapabilities)
{
    Console.WriteLine("Capabilities: {0}", arrValue);
}
</code>```

答:
To Expand on Daniels answer and get the csv string you are after:</p>

```<code>IEnumerable array = queryObj["Capabilities"] as IEnumerable;
if(array != null)
{
     var csvString = String.Join(", ", array.Cast<object>().Select(x => x.ToString()));
     Console.WriteLine(csvString);
}
else
{
    Console.WriteLine(queryObj["Capabilities"].ToString());
}
</code>```

Body:
I have a collection of objects that each object would contains a different kind of array (string[],int[],char[]) or even single value as different types.

I want to get the values of each array as single format such as string  and convert it to a comma text value.

here is the code that manipulates an object of collection as "UInt16[]"

UInt16[] arrCapabilities = (UInt16[])(queryObj["Capabilities"]);
foreach (UInt16 arrValue in arrCapabilities)
{
    Console.WriteLine("Capabilities: {0}", arrValue);
}

Body:
To Expand on Daniels answer and get the csv string you are after:

IEnumerable array = queryObj["Capabilities"] as IEnumerable;
if(array != null)
{
     var csvString = String.Join(", ", array.Cast<object>().Select(x => x.ToString()));
     Console.WriteLine(csvString);
}
else
{
    Console.WriteLine(queryObj["Capabilities"].ToString());
}


问:
How to get date time from UTC date time fromat?
I am getting date time from rest api as like this  "2020-02-13T16:57:13.04 . How can i convert in java for android? So that i can use only date or time separately?

I have tried by this way

```<code>String dateStr = rowsArrayList.get(position).getDisplayDate();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ENGLISH);
df.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = null;
try {
    date = df.parse(dateStr);
    df.setTimeZone(TimeZone.getDefault());
    String formattedDate = df.format(date);
    Log.d("testDate",formattedDate);

} catch (ParseException e) {
    e.printStackTrace();
    Log.d("testDate",e.toString());
}
</code>```

But getting the error

java.text.ParseException: Unparseable date: "2020-02-13T16:57:13.04"

答:
SimpleDateFormat cannot parse your date-time string correctly.

SimpleDateFormat is notoriously troublesome and long outdated. Neither for this nor for any other purpose should you use it. Instead just use the LocalDateTime class from java.time, the modern Java date and time API. It parses your string wothout any explicit formatter.

You can’t with SimpleDateFormat

Your string has two decimals on the second of minute, .04, signifying 4 hundredths of a second. SimpleDateFormat only supports exactly three decimals on the seconds, not two or four or any other number. So there is no way that it can parse your string correctly.

java.time

It seems that you are assuming that the string you parse is in UTC and you want to convert it to the default time zone of your device. Your string is in ISO 8601 format, the format that the classes of java.time parse as their default, so we don’t need to specify any formatter.

```<code>    String dateStr = "2020-02-13T16:57:13.04";
    LocalDateTime dateTime = LocalDateTime.parse(dateStr);
    ZonedDateTime inDefaultTimeZone = dateTime.atOffset(ZoneOffset.UTC)
            .atZoneSameInstant(ZoneId.systemDefault());
    System.out.println(inDefaultTimeZone);
</code>```

On my computer in Europe/Copenhagen time zone the output from this snippet is:

2020-02-13T17:57:13.040+01:00[Europe/Copenhagen]

Question: Doesn’t java.time require Android API level 26?

java.time works nicely on both older and newer Android devices. It just requires at least Java 6.

In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.

In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).

On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.

Links

Oracle tutorial: Date Time explaining how to use java.time.

Java Specification Request (JSR) 310, where java.time was first described.

ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310).

ThreeTenABP, Android edition of ThreeTen Backport

Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.

Wikipedia article: ISO 8601

Body:
I am getting date time from rest api as like this  "2020-02-13T16:57:13.04 . How can i convert in java for android? So that i can use only date or time separately?

I have tried by this way

String dateStr = rowsArrayList.get(position).getDisplayDate();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ENGLISH);
df.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = null;
try {
    date = df.parse(dateStr);
    df.setTimeZone(TimeZone.getDefault());
    String formattedDate = df.format(date);
    Log.d("testDate",formattedDate);

} catch (ParseException e) {
    e.printStackTrace();
    Log.d("testDate",e.toString());
}

But getting the error

java.text.ParseException: Unparseable date: "2020-02-13T16:57:13.04"

Body:
SimpleDateFormat cannot parse your date-time string correctly.

SimpleDateFormat is notoriously troublesome and long outdated. Neither for this nor for any other purpose should you use it. Instead just use the LocalDateTime class from java.time, the modern Java date and time API. It parses your string wothout any explicit formatter.

You can’t with SimpleDateFormat

Your string has two decimals on the second of minute, .04, signifying 4 hundredths of a second. SimpleDateFormat only supports exactly three decimals on the seconds, not two or four or any other number. So there is no way that it can parse your string correctly.

java.time

It seems that you are assuming that the string you parse is in UTC and you want to convert it to the default time zone of your device. Your string is in ISO 8601 format, the format that the classes of java.time parse as their default, so we don’t need to specify any formatter.

    String dateStr = "2020-02-13T16:57:13.04";
    LocalDateTime dateTime = LocalDateTime.parse(dateStr);
    ZonedDateTime inDefaultTimeZone = dateTime.atOffset(ZoneOffset.UTC)
            .atZoneSameInstant(ZoneId.systemDefault());
    System.out.println(inDefaultTimeZone);

On my computer in Europe/Copenhagen time zone the output from this snippet is:

2020-02-13T17:57:13.040+01:00[Europe/Copenhagen]

Question: Doesn’t java.time require Android API level 26?

java.time works nicely on both older and newer Android devices. It just requires at least Java 6.

In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.

In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).

On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.

Links

Oracle tutorial: Date Time explaining how to use java.time.

Java Specification Request (JSR) 310, where java.time was first described.

ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310).

ThreeTenABP, Android edition of ThreeTen Backport

Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.

Wikipedia article: ISO 8601


问:
Unable to export a variable from a node module and use that variable across my node-express application
I've isolated my database connection and GridfsStorage code into its own file because I need to be able to access gridfs storage and multer upload across my application. The problem I'm facing here is that I'm unable to export the gfs variable, as shown below. I can successfully access and use the dbInstance and upload variables, just not the gfs variable, and I'm struggling to understand why that is the case.

When I try accessing gfs in my controller or in my route file, it is undefined and no methods associated with it are available.

I'm looking for a pointer to what is happening here and possible solutions. Any help is appreciated.

db.js:

```<code>const express = require('express');
const path = require('path');
const crypto = require('crypto');
const dotenv = require('dotenv');
const multer = require('multer');
const GridFsStorage = require('multer-gridfs-storage');
const Grid = require('gridfs-stream');
const mongoose = require('mongoose');

dotenv.config();

// Set up mongoose connection
const mongoDB = process.env.DB_URL;

const conn = mongoose.connect(mongoDB, {
  useNewUrlParser: true,
  useUnifiedTopology: true,
  useCreateIndex: true,
});

mongoose.Promise = global.Promise;
const dbInstance = mongoose.connection;

let gfs;

dbInstance.once('open', () => {
  gfs = Grid(dbInstance.db, mongoose.mongo);
  gfs.collection('fileUploads');
});

const storage = new GridFsStorage({
  //url: mongoDB,
  db: dbInstance,
  file: (req, file) => {
    return new Promise((resolve, reject) => {
      crypto.randomBytes(32, (err, buff) => {
        if (err) return reject(err);
        const filename = buff.toString('hex') + path.extname(file.originalname);
        const fileInfo = {
          filename: filename,
          bucketName: 'fileUploads',
        };
        resolve(fileInfo);
      });
    });
  },
});

var upload = multer({ storage });

module.exports = {
  dbInstance,
  upload,
  gfs,
};
</code>```

答:
Export an object and set a property on it. Objects are passed by reference.

So:

```<code>const gfs = {grid: undefined}

dbInstance.once('open', () => {
  gfs.grid = Grid(dbInstance.db, mongoose.mongo);
  gfs.grid.collection('fileUploads');
});

...
module.exports = {
  dbInstance,
  upload,
  gfs,
};
</code>```

Body:
I've isolated my database connection and GridfsStorage code into its own file because I need to be able to access gridfs storage and multer upload across my application. The problem I'm facing here is that I'm unable to export the gfs variable, as shown below. I can successfully access and use the dbInstance and upload variables, just not the gfs variable, and I'm struggling to understand why that is the case.

When I try accessing gfs in my controller or in my route file, it is undefined and no methods associated with it are available.

I'm looking for a pointer to what is happening here and possible solutions. Any help is appreciated.

db.js:

const express = require('express');
const path = require('path');
const crypto = require('crypto');
const dotenv = require('dotenv');
const multer = require('multer');
const GridFsStorage = require('multer-gridfs-storage');
const Grid = require('gridfs-stream');
const mongoose = require('mongoose');

dotenv.config();

// Set up mongoose connection
const mongoDB = process.env.DB_URL;

const conn = mongoose.connect(mongoDB, {
  useNewUrlParser: true,
  useUnifiedTopology: true,
  useCreateIndex: true,
});

mongoose.Promise = global.Promise;
const dbInstance = mongoose.connection;

let gfs;

dbInstance.once('open', () => {
  gfs = Grid(dbInstance.db, mongoose.mongo);
  gfs.collection('fileUploads');
});

const storage = new GridFsStorage({
  //url: mongoDB,
  db: dbInstance,
  file: (req, file) => {
    return new Promise((resolve, reject) => {
      crypto.randomBytes(32, (err, buff) => {
        if (err) return reject(err);
        const filename = buff.toString('hex') + path.extname(file.originalname);
        const fileInfo = {
          filename: filename,
          bucketName: 'fileUploads',
        };
        resolve(fileInfo);
      });
    });
  },
});

var upload = multer({ storage });

module.exports = {
  dbInstance,
  upload,
  gfs,
};

Body:
Export an object and set a property on it. Objects are passed by reference.

So:

const gfs = {grid: undefined}

dbInstance.once('open', () => {
  gfs.grid = Grid(dbInstance.db, mongoose.mongo);
  gfs.grid.collection('fileUploads');
});

...
module.exports = {
  dbInstance,
  upload,
  gfs,
};