问:
Wamp rewrites url automatically?
I am facing some issues with url rewrite on windows wamp. The problem is whenever i access below urls

```<code>http://localhost/test/index

or

http://localhost/test/index.php
</code>```

It loads the home page. The problem is that wamp automatically hides php extention from urls, even after disabling mod_rewrite module.
I'm also not using .htaccess file.
This is very strange behaviour, This is the first time i got this issue.

```<code>Softwares:
        - WAMPSERVER 64BIT - 3.1.4
        - PHP Version 7.2.10
        - Apache Version 2.4.35
</code>```

httpd-vhosts.conf

```<code># Virtual Hosts
<VirtualHost *:80>
  ServerName localhost
  ServerAlias localhost
  DocumentRoot "${INSTALL_DIR}/www"
  <Directory "${INSTALL_DIR}/www/">
    Options +Indexes +Includes +FollowSymLinks +MultiViews
    AllowOverride All
    #Require local
    Require all granted
  </Directory>
</VirtualHost>
</code>```

Any solution to turn off this automatic rewrites, so that i can do it myself via htaccess file. Thanks in advance.

答:
Finally solved the problem. The problem was with wamp 3 software, it uses +MultiViews directive by default.

To solve the problem just replace,

```<code>Options +Indexes +Includes +FollowSymLinks +MultiViews
</code>```

with

```<code>Options +Indexes +Includes +FollowSymLinks -MultiViews
</code>```

Hope it helps someone!

Title: Wamp rewrites url automatically?

Body:
I am facing some issues with url rewrite on windows wamp. The problem is whenever i access below urls

http://localhost/test/index

or

http://localhost/test/index.php

It loads the home page. The problem is that wamp automatically hides php extention from urls, even after disabling mod_rewrite module.
I'm also not using .htaccess file.
This is very strange behaviour, This is the first time i got this issue.

Softwares:
        - WAMPSERVER 64BIT - 3.1.4
        - PHP Version 7.2.10
        - Apache Version 2.4.35

httpd-vhosts.conf

# Virtual Hosts
<VirtualHost *:80>
  ServerName localhost
  ServerAlias localhost
  DocumentRoot "${INSTALL_DIR}/www"
  <Directory "${INSTALL_DIR}/www/">
    Options +Indexes +Includes +FollowSymLinks +MultiViews
    AllowOverride All
    #Require local
    Require all granted
  </Directory>
</VirtualHost>

Any solution to turn off this automatic rewrites, so that i can do it myself via htaccess file. Thanks in advance.

Body:
Finally solved the problem. The problem was with wamp 3 software, it uses +MultiViews directive by default.

To solve the problem just replace,

Options +Indexes +Includes +FollowSymLinks +MultiViews

with

Options +Indexes +Includes +FollowSymLinks -MultiViews

Hope it helps someone!


来源: stackexchange

问:
Trailing 0 decimal after casting to string to float
In redshift I'm trying to convert a string to a float and round to 2 decimal places. But when I do that I get a lot of trailing 0's at at the end.

```<code>select
'1.99'
, '1.99'::float
, round('1.99'::float , 2)
</code>```

Seems like the round function doesn't do anything.
I want to just get 1.99 as a float and not 1.9900000000000

I'm using DBeaver btw

答:
I think its just the format you see using your client software that is the issue here.

if you DO want to reformat it inside your sql (to 1.99) then you could use to_char like this.

```<code>select to_char('1.99'::float,'99999D99');
</code>```

ContentLicense: CC BY-SA 4.0

Body:
In redshift I'm trying to convert a string to a float and round to 2 decimal places. But when I do that I get a lot of trailing 0's at at the end.

select
'1.99'
, '1.99'::float
, round('1.99'::float , 2)

Seems like the round function doesn't do anything.
I want to just get 1.99 as a float and not 1.9900000000000

I'm using DBeaver btw

Body:
I think its just the format you see using your client software that is the issue here.

if you DO want to reformat it inside your sql (to 1.99) then you could use to_char like this.

select to_char('1.99'::float,'99999D99');


问:
Finding matching keys in two large dictionaries and doing it fast
I am trying to find corresponding keys in two different dictionaries.  Each has about 600k entries.

Say for example:

```<code>    myRDP = { 'Actinobacter': 'GATCGA...TCA', 'subtilus sp.': 'ATCGATT...ACT' }
    myNames = { 'Actinobacter': '8924342' }
</code>```

I want to print out the value for Actinobacter (8924342) since it matches a value in myRDP.

The following code works, but is very slow:

```<code>    for key in myRDP:
        for jey in myNames:
            if key == jey:
                print key, myNames[key]
</code>```

I've tried the following but it always results in a KeyError:

```<code>    for key in myRDP:
        print myNames[key]
</code>```

Is there perhaps a function implemented in C for doing this?  I've googled around but nothing seems to work.

答:
Best and easiest way would be simply perform common set operations(Python 3).

```<code>a = {"a": 1, "b":2, "c":3, "d":4}
b = {"t1": 1, "b":2, "e":5, "c":3}
res = a.items() & b.items() # {('b', 2), ('c', 3)} For common Key and Value
res = {i[0]:i[1] for i in res}  # In dict format
common_keys = a.keys() & b.keys()  # {'b', 'c'}
</code>```

Cheers!

Body:
I am trying to find corresponding keys in two different dictionaries.  Each has about 600k entries.

Say for example:

    myRDP = { 'Actinobacter': 'GATCGA...TCA', 'subtilus sp.': 'ATCGATT...ACT' }
    myNames = { 'Actinobacter': '8924342' }

I want to print out the value for Actinobacter (8924342) since it matches a value in myRDP.

The following code works, but is very slow:

    for key in myRDP:
        for jey in myNames:
            if key == jey:
                print key, myNames[key]

I've tried the following but it always results in a KeyError:

    for key in myRDP:
        print myNames[key]

Is there perhaps a function implemented in C for doing this?  I've googled around but nothing seems to work.

Body:
Best and easiest way would be simply perform common set operations(Python 3).

a = {"a": 1, "b":2, "c":3, "d":4}
b = {"t1": 1, "b":2, "e":5, "c":3}
res = a.items() & b.items() # {('b', 2), ('c', 3)} For common Key and Value
res = {i[0]:i[1] for i in res}  # In dict format
common_keys = a.keys() & b.keys()  # {'b', 'c'}

Cheers!


问:
Align output numbers in tkinter Text widget
I'm learning to use tkinter developing an application that at the end of calculation make a final report putting numbers in columns.

```<code>from tkinter import *

a = 5
b = 0.223
c = 0.1
a1 = 0.55556
b1 = 1.57
c1 = 785869
a2 = 785698
b2 = 0.55875968547854
c2 = 8696

root=Tk()
output_text = Text(root, width=200, height=30)
output_text.grid(row=10,column=10)
output_text.insert("end-1c", str(a) + ' ' + str(b) + ' ' + str(c)+'\n')
output_text.insert("end-1c", str(a1) + ' ' + str(b1) + ' ' +str(c1)+'\n')
output_text.insert("end-1c", str(a2) + ' ' + str(b2) + ' ' +str(c2)+'\n')

root.mainloop()
</code>```

I want to align numbers in every column because every row has different number of digits so the output is not well organized. How can I obtain this result? Thanks!

答:
The way to do it is the way we used to do it with typewriters: create and use tabstops, which are explicitly designed to allow you to line data up in columns.

The following example sets tabstop every 200 pixels:

```<code>output_text.configure(tabs=["200"])
...
output_text.insert("end-1c", str(a) + '\t' + str(b) + '\t' + str(c)+'\n')
output_text.insert("end-1c", str(a1) + '\t' + str(b1) + '\t' +str(c1)+'\n')
output_text.insert("end-1c", str(a2) + '\t' + str(b2) + '\t' +str(c2)+'\n')
</code>```

You can specify the alignment of the tabstops by supplying one of the following values after the tab width: "left", "right", "center", or "numeric". "numeric" means that the decimal point will be placed at the tab stop.

```<code>output_text.configure(tabs=["200", "numeric"])
</code>```

For the canonical definition of the tabs option, see the tcl/tk documentation here: http://tcl.tk/man/tcl8.5/TkCmd/text.htm#M-tabs

note: the python tkinter documentation gives a nice overview of how to translate tcl/tk documentation into python in the section titled Tkinter life Preserver

Body:
I'm learning to use tkinter developing an application that at the end of calculation make a final report putting numbers in columns.

from tkinter import *

a = 5
b = 0.223
c = 0.1
a1 = 0.55556
b1 = 1.57
c1 = 785869
a2 = 785698
b2 = 0.55875968547854
c2 = 8696

root=Tk()
output_text = Text(root, width=200, height=30)
output_text.grid(row=10,column=10)
output_text.insert("end-1c", str(a) + ' ' + str(b) + ' ' + str(c)+'\n')
output_text.insert("end-1c", str(a1) + ' ' + str(b1) + ' ' +str(c1)+'\n')
output_text.insert("end-1c", str(a2) + ' ' + str(b2) + ' ' +str(c2)+'\n')

root.mainloop()

I want to align numbers in every column because every row has different number of digits so the output is not well organized. How can I obtain this result? Thanks!

Body:
The way to do it is the way we used to do it with typewriters: create and use tabstops, which are explicitly designed to allow you to line data up in columns.

The following example sets tabstop every 200 pixels:

output_text.configure(tabs=["200"])
...
output_text.insert("end-1c", str(a) + '\t' + str(b) + '\t' + str(c)+'\n')
output_text.insert("end-1c", str(a1) + '\t' + str(b1) + '\t' +str(c1)+'\n')
output_text.insert("end-1c", str(a2) + '\t' + str(b2) + '\t' +str(c2)+'\n')

You can specify the alignment of the tabstops by supplying one of the following values after the tab width: "left", "right", "center", or "numeric". "numeric" means that the decimal point will be placed at the tab stop.

output_text.configure(tabs=["200", "numeric"])

For the canonical definition of the tabs option, see the tcl/tk documentation here: http://tcl.tk/man/tcl8.5/TkCmd/text.htm#M-tabs

note: the python tkinter documentation gives a nice overview of how to translate tcl/tk documentation into python in the section titled Tkinter life Preserver


问:
What should my JSON string look like in my Action?
in .NET MVC my action looks like:

```<code>public ActionResult TestAjax(string testID)
{

    return Content(@"{first: ""1"", second : ""2""}");
}
</code>```

In my JavaScript I am doing:

```<code>function(data)
{
      alert(data.first);
}
</code>```

I am getting [object Object] as the output, why is that?

Is my JSON string wrong?

答:
You want to do a return with Json not Content</p>

```<code>return Json(new { first = "1", second ="2" });
</code>```

ContentLicense: CC BY-SA 3.0

Body:
in .NET MVC my action looks like:

public ActionResult TestAjax(string testID)
{

    return Content(@"{first: ""1"", second : ""2""}");
}

In my JavaScript I am doing:

function(data)
{
      alert(data.first);
}

I am getting [object Object] as the output, why is that?

Is my JSON string wrong?

Body:
You want to do a return with Json not Content

return Json(new { first = "1", second ="2" });

OwnerDisplayName: Mainstay

ContentLicense: CC BY-SA 2.5


问:
Azure Functions App yields errors after setting App Settings
I have an Azure Functions App running on a consumption plan. It was handed over to me without any app settings. I manually setup the app settings using the Microsoft documentation as follows:

```<code>  {
    "name": "APPINSIGHTS_INSTRUMENTATIONKEY",
    "value": "{id}",
    "slotSetting": false
  },
  {
    "name": "AzureWebJobsStorage",
    "value": "DefaultEndpointsProtocol=https;AccountName={name};AccountKey={key}",
    "slotSetting": false
  },
  {
    "name": "FUNCTIONS_EXTENSION_VERSION",
    "value": "~2",
    "slotSetting": false
  },
  {
    "name": "FUNCTIONS_WORKER_RUNTIME",
    "value": "dotnet",
    "slotSetting": false
  },
  {
    "name": "WEBSITE_CONTENTAZUREFILECONNECTIONSTRING",
    "value": "DefaultEndpointsProtocol=https;AccountName={name};AccountKey={key}",
    "slotSetting": false
  },
  {
    "name": "WEBSITE_CONTENTSHARE",
    "value": "{name of Functions App added to 32 chars}",
    "slotSetting": false
  },
  {
    "name": "WEBSITE_NODE_DEFAULT_VERSION",
    "value": "10.14.1",
    "slotSetting": false
  },
  {
    "name": "WEBSITE_RUN_FROM_PACKAGE",
    "value": "1",
    "slotSetting": false
  }
]
</code>```

Where the connection strings both share the same Storage Account that is otherwise empty and not in use by any other application.

It however yields an error already when trying to view it from the portal. Removing the WEBSITE_CONTENTAZUREFILECONNECTIONSTRING, WEBSITE_CONTENTSHARE and AzureWebJobsStorage seem to make it run although no host keys are saved, but otherwise functions seem to trigger.

How do I properly setup the Functions App to use the Storage?

答:
I have observed this issue when you create a function app without any app settings (e.g. via ARM). It will have the functions runtime v1 by default.

You can try switching the runtime version manually via the portal.

https://learn.microsoft.com/en-us/azure/azure-functions/set-runtime-version

Although the runtime version is determined by the FUNCTIONS_EXTENSION_VERSION setting, you should make this change in the Azure portal and not by changing the setting directly. This is because the portal validates your changes and makes other related changes as needed.

If this does not help, you will need to recreate it completely with basic app settings already in place (mainly FUNCTIONS_EXTENSION_VERSION being set to ~2).
Unfortunately, I don't remember if there was an open Github issue for it - you could also post your issue there:
https://github.com/Azure/azure-functions-host/issues

It might be that your app works even though an error is shown in the Azure Portal - but I would recommend recreating it in this case.

Body:
I have an Azure Functions App running on a consumption plan. It was handed over to me without any app settings. I manually setup the app settings using the Microsoft documentation as follows:

  {
    "name": "APPINSIGHTS_INSTRUMENTATIONKEY",
    "value": "{id}",
    "slotSetting": false
  },
  {
    "name": "AzureWebJobsStorage",
    "value": "DefaultEndpointsProtocol=https;AccountName={name};AccountKey={key}",
    "slotSetting": false
  },
  {
    "name": "FUNCTIONS_EXTENSION_VERSION",
    "value": "~2",
    "slotSetting": false
  },
  {
    "name": "FUNCTIONS_WORKER_RUNTIME",
    "value": "dotnet",
    "slotSetting": false
  },
  {
    "name": "WEBSITE_CONTENTAZUREFILECONNECTIONSTRING",
    "value": "DefaultEndpointsProtocol=https;AccountName={name};AccountKey={key}",
    "slotSetting": false
  },
  {
    "name": "WEBSITE_CONTENTSHARE",
    "value": "{name of Functions App added to 32 chars}",
    "slotSetting": false
  },
  {
    "name": "WEBSITE_NODE_DEFAULT_VERSION",
    "value": "10.14.1",
    "slotSetting": false
  },
  {
    "name": "WEBSITE_RUN_FROM_PACKAGE",
    "value": "1",
    "slotSetting": false
  }
]

Where the connection strings both share the same Storage Account that is otherwise empty and not in use by any other application.

It however yields an error already when trying to view it from the portal. Removing the WEBSITE_CONTENTAZUREFILECONNECTIONSTRING, WEBSITE_CONTENTSHARE and AzureWebJobsStorage seem to make it run although no host keys are saved, but otherwise functions seem to trigger.

How do I properly setup the Functions App to use the Storage?


问:
Easiest way to compare two Excel files in Java?
I'm writing a JUnit test for some code that produces an Excel file (which is binary). I have another Excel file that contains my expected output. What's the easiest way to compare the actual file to the expected file?

Sure I could write the code myself, but I was wondering if there's an existing method in a trusted third-party library (e.g. Spring or Apache Commons) that already does this.

答:
To test only content of the first sheets in Kotlin (easily can be converted to java).

```<code>private fun checkEqualityExcelDocs(doc : XSSFWorkbook, doc1 : XSSFWorkbook) : Boolean{
        val mapOfCellDoc = doc.toList().first().toList().flatMap { row -> row.map { Pair(PivotExcelCreator.IndexInThePivotTable(it.rowIndex,it.columnIndex),it.stringCellValue) }}.toMap()
        val mapOfCellDoc1 = doc1.toList().first().toList().flatMap { row -> row.map { Pair(PivotExcelCreator.IndexInThePivotTable(it.rowIndex,it.columnIndex),it.stringCellValue) }}.toMap()
        if(mapOfCellDoc.size == mapOfCellDoc1.size){
            return mapOfCellDoc.entries.all { mapOfCellDoc1.containsKey(it.key) && mapOfCellDoc[it.key] == mapOfCellDoc1[it.key]}
        }
        return false
    }

data class IndexInThePivotTable(val row: Int, val col: Int)
</code>```

and in your code add assert

```<code>    assertTrue(checkEqualityExcelDocs(expected, actual), "Docs aren't equal!")
</code>```

as you can see doc.toList().first() will take only the first sheet of document, if you need to compare each sheet respectively change code a little.

Also it is quite good idea to not take into account "" empty strings cells, I didn't need this functionality (As well, simply add this part, if you need).

also it can be useful information

```<code>//first doc I've got from outputstream such way
val out = ByteArrayOutputStream()
//some method which writes excel to outputstream
val firstDoc = XSSFWorkbook(ByteArrayInputStream(out.toByteArray()))
</code>```

and second doc from file to compare with

```<code>val secondDoc = XSSFWorkbook(Test::class.java.getClassLoader().getResource("yourfile.xlsx").path)
</code>```

Body:
To test only content of the first sheets in Kotlin (easily can be converted to java).

private fun checkEqualityExcelDocs(doc : XSSFWorkbook, doc1 : XSSFWorkbook) : Boolean{
        val mapOfCellDoc = doc.toList().first().toList().flatMap { row -> row.map { Pair(PivotExcelCreator.IndexInThePivotTable(it.rowIndex,it.columnIndex),it.stringCellValue) }}.toMap()
        val mapOfCellDoc1 = doc1.toList().first().toList().flatMap { row -> row.map { Pair(PivotExcelCreator.IndexInThePivotTable(it.rowIndex,it.columnIndex),it.stringCellValue) }}.toMap()
        if(mapOfCellDoc.size == mapOfCellDoc1.size){
            return mapOfCellDoc.entries.all { mapOfCellDoc1.containsKey(it.key) && mapOfCellDoc[it.key] == mapOfCellDoc1[it.key]}
        }
        return false
    }

data class IndexInThePivotTable(val row: Int, val col: Int)

and in your code add assert

    assertTrue(checkEqualityExcelDocs(expected, actual), "Docs aren't equal!")

as you can see doc.toList().first() will take only the first sheet of document, if you need to compare each sheet respectively change code a little.

Also it is quite good idea to not take into account "" empty strings cells, I didn't need this functionality (As well, simply add this part, if you need).

also it can be useful information

//first doc I've got from outputstream such way
val out = ByteArrayOutputStream()
//some method which writes excel to outputstream
val firstDoc = XSSFWorkbook(ByteArrayInputStream(out.toByteArray()))

and second doc from file to compare with

val secondDoc = XSSFWorkbook(Test::class.java.getClassLoader().getResource("yourfile.xlsx").path)


问:
librdkafka consumer and ssl configuration
I'm using librdkafka as a client consumer, and I have configured the broker and the client to support SSL, for the broker:

```<code>listeners = PLAINTEXT://172.20.54.9:9092,SSL://172.20.54.9:9093
ssl.keystore.location=E:/project_files/Project/kafka_2.11-2.1.0/config/kafka.server.keystore.jks
ssl.keystore.password=ismail
ssl.key.password=ismail
ssl.truststore.location=E:/project_files/Project/kafka_2.11-2.1.0/config/kafka.server.truststore.jks
ssl.truststore.password=password
</code>```

in  the client side I'm using this configuration:

```<code>rd_kafka_conf_set(conf, "metadata.broker.list", "172.20.54.9:9093",
                      NULL, 0);
rd_kafka_conf_set(conf, "security.protocol", "ssl",
                      NULL, 0);
rd_kafka_conf_set(conf, "ssl.ca.location", "/usr/bin/NetSens/CARoot.pem",
                      NULL, 0);
rd_kafka_conf_set(conf, "ssl.certificate.location", "/usr/bin/NetSens/certificate.pem",
                      NULL, 0);
rd_kafka_conf_set(conf, "ssl.key.location", "/usr/bin/NetSens/key.pem",
                      NULL, 0);
rd_kafka_conf_set(conf, "ssl.key.password", "password",
                      NULL, 0);
</code>```

And I'm receiving this error:

```<code>1559309856.897 RDKAFKA-3-ERROR: rdkafka#consumer-1: [thrd:ssl://172.20.54.9:9093/bootstrap]: ssl://172.20.54.9:9093/bootstrap: SSL handshake failed: ../ssl/record/ssl3_record.c:252: error:1408F10B:SSL routines:ssl3_get_record:wrong version number:  (after 7ms in state CONNECT)
</code>```

For more information, I have in parallel another python kafka client using the same certificates and keys and it works fine.
I will be so grateful for any help.

答:
I believe your problem is related to this issue.

You can fix it by including -keyalg RSA when invoking keytool -genkey to generate the certificates.

Body:
I'm using librdkafka as a client consumer, and I have configured the broker and the client to support SSL, for the broker:

listeners = PLAINTEXT://172.20.54.9:9092,SSL://172.20.54.9:9093
ssl.keystore.location=E:/project_files/Project/kafka_2.11-2.1.0/config/kafka.server.keystore.jks
ssl.keystore.password=ismail
ssl.key.password=ismail
ssl.truststore.location=E:/project_files/Project/kafka_2.11-2.1.0/config/kafka.server.truststore.jks
ssl.truststore.password=password

in  the client side I'm using this configuration:

rd_kafka_conf_set(conf, "metadata.broker.list", "172.20.54.9:9093",
                      NULL, 0);
rd_kafka_conf_set(conf, "security.protocol", "ssl",
                      NULL, 0);
rd_kafka_conf_set(conf, "ssl.ca.location", "/usr/bin/NetSens/CARoot.pem",
                      NULL, 0);
rd_kafka_conf_set(conf, "ssl.certificate.location", "/usr/bin/NetSens/certificate.pem",
                      NULL, 0);
rd_kafka_conf_set(conf, "ssl.key.location", "/usr/bin/NetSens/key.pem",
                      NULL, 0);
rd_kafka_conf_set(conf, "ssl.key.password", "password",
                      NULL, 0);

And I'm receiving this error:

1559309856.897 RDKAFKA-3-ERROR: rdkafka#consumer-1: [thrd:ssl://172.20.54.9:9093/bootstrap]: ssl://172.20.54.9:9093/bootstrap: SSL handshake failed: ../ssl/record/ssl3_record.c:252: error:1408F10B:SSL routines:ssl3_get_record:wrong version number:  (after 7ms in state CONNECT)

For more information, I have in parallel another python kafka client using the same certificates and keys and it works fine.
I will be so grateful for any help.


问:
decision tree algorithm on feature set
I'm trying to predict the no.of updates('sys_mod_count')based on the text description('eng')

I have predefined the 'sys_mod_count' into two classes if >=17 as 1; <17 as 0.

But I want to remove this condition as this value is not available at decision time in real world.

I'm thinking to do this in Decision tree/ Random forest method to train the classifier on feature set.

def train_model(classifier, feature_vector_train, label, feature_vector_valid, is_neural_net=False):
    # fit the training dataset on the classifier
    classifier.fit(feature_vector_train, label)
    # predict the labels on validation dataset
    predictions = classifier.predict(feature_vector_valid)
    # return metrics.accuracy_score(predictions, valid_y)
    return predictions
```

<pre class="lang-py prettyprint-override"><code>
import pandas as pd
from sklearn import model_selection, preprocessing, linear_model, naive_bayes, metrics, svm
from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer

df_3 =pd.read_csv('processedData.csv', sep=";")
st_new = df_3[['sys_mod_count','eng','ger']]
st_new['updates_binary'] = st_new['sys_mod_count'].apply(lambda x: 1 if x >= 17 else 0)
st_org = st_new[['eng','updates_binary']]
st_org = st_org.dropna(axis=0, subset=['eng']) #Determine if column 'eng'contain missing values are removed
train_x, valid_x, train_y, valid_y = model_selection.train_test_split(st_org['eng'], st_org['updates_binary'],stratify=st_org['updates_binary'],test_size=0.20)
tfidf_vect = TfidfVectorizer(analyzer='word', token_pattern=r'\w{1,}', max_features=5000)
tfidf_vect.fit(st_org['eng'])
xtrain_tfidf =  tfidf_vect.transform(train_x)
xvalid_tfidf =  tfidf_vect.transform(valid_x)

# Naive Bayes on Word Level TF IDF Vectors
accuracy = train_model(naive_bayes.MultinomialNB(), xtrain_tfidf, train_y, xvalid_tfidf)
print ("NB, WordLevel TF-IDF: ", metrics.accuracy_score(accuracy, valid_y))

</code>```

答:
This seems to be a threshold setting problem - you would like to set a threshold at which a certain classification is made. No supervised classifier can set the threshold for you because if it does not have any training data with binary classes, then you cannot train the cvlassifier, and to create training data, you need to set the threshold to begin with. It's a chicken and egg problem.

If you have some way of identifying which binary label is correct, then you can vary the threshold and measure errors similar to how it's suggested here. Then you can either run a Classifier on your binary labels based on the threshold or a Regressor on sys_mod_count and convert to binary based on the identified threshold.

The above approach does not work if you have no way to identify what the correct binary label should be. Then, the problem you are trying to solve is creating some boundary between points based on the value of your sys_mod_count variable. This is unsupervised learning. So, techniques like clustering will be helpful here. You can cluster your data into two clusters based on the distance of points from each other, and then label each cluster, which becomes your binary label.

Title: decision tree algorithm on feature set

Body:
I'm trying to predict the no.of updates('sys_mod_count')based on the text description('eng')

I have predefined the 'sys_mod_count' into two classes if >=17 as 1; <17 as 0.

But I want to remove this condition as this value is not available at decision time in real world.

I'm thinking to do this in Decision tree/ Random forest method to train the classifier on feature set.

def train_model(classifier, feature_vector_train, label, feature_vector_valid, is_neural_net=False):
    # fit the training dataset on the classifier
    classifier.fit(feature_vector_train, label)
    # predict the labels on validation dataset
    predictions = classifier.predict(feature_vector_valid)
    # return metrics.accuracy_score(predictions, valid_y)
    return predictions

import pandas as pd
from sklearn import model_selection, preprocessing, linear_model, naive_bayes, metrics, svm
from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer

df_3 =pd.read_csv('processedData.csv', sep=";")
st_new = df_3[['sys_mod_count','eng','ger']]
st_new['updates_binary'] = st_new['sys_mod_count'].apply(lambda x: 1 if x >= 17 else 0)
st_org = st_new[['eng','updates_binary']]
st_org = st_org.dropna(axis=0, subset=['eng']) #Determine if column 'eng'contain missing values are removed
train_x, valid_x, train_y, valid_y = model_selection.train_test_split(st_org['eng'], st_org['updates_binary'],stratify=st_org['updates_binary'],test_size=0.20)
tfidf_vect = TfidfVectorizer(analyzer='word', token_pattern=r'\w{1,}', max_features=5000)
tfidf_vect.fit(st_org['eng'])
xtrain_tfidf =  tfidf_vect.transform(train_x)
xvalid_tfidf =  tfidf_vect.transform(valid_x)

# Naive Bayes on Word Level TF IDF Vectors
accuracy = train_model(naive_bayes.MultinomialNB(), xtrain_tfidf, train_y, xvalid_tfidf)
print ("NB, WordLevel TF-IDF: ", metrics.accuracy_score(accuracy, valid_y))


问:
Copy output of a JavaScript variable to the clipboard
I have no knowledge of JavaScript, but I managed to put this code together using bits and bolts from various Stack Overflow answers. It works OK, and it outputs an array of all selected checkboxes in a document via an alert box.

```<code>function getSelectedCheckboxes(chkboxName) {
  var checkbx = [];
  var chkboxes = document.getElementsByName(chkboxName);
  var nr_chkboxes = chkboxes.length;
  for(var i=0; i<nr_chkboxes; i++) {
    if(chkboxes[i].type == 'checkbox' && chkboxes[i].checked == true) checkbx.push(chkboxes[i].value);
  }
  return checkbx;
}
</code>```

And to call it I use:

```<code><button id="btn_test" type="button" >Check</button>
<script>
    document.getElementById('btn_test').onclick = function() {
        var checkedBoxes = getSelectedCheckboxes("my_id");
        alert(checkedBoxes);
    }
</script>
</code>```

Now I would like to modify it so when I click the btn_test button the output array checkbx is copied to the clipboard. I tried adding:

```<code>checkbx = document.execCommand("copy");
</code>```

or

```<code>checkbx.execCommand("copy");
</code>```

at the end of the function and then calling it like:

```<code><button id="btn_test" type="button" onclick="getSelectedCheckboxes('my_id')">Check</button>
</code>```

But it does not work. No data is copied to clipboard.

答:
I managed to copy text to the clipboard (without showing any text boxes)  by adding a hidden input element to body,  i.e.:

 function copy(txt){
  var cb = document.getElementById("cb");
  cb.value = txt;
  cb.style.display='block';
  cb.select();
  document.execCommand('copy');
  cb.style.display='none';
 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button onclick="copy('Hello Clipboard!')"> copy </button>
<input id="cb" type="text" hidden></code>```

Body:
I have no knowledge of JavaScript, but I managed to put this code together using bits and bolts from various Stack Overflow answers. It works OK, and it outputs an array of all selected checkboxes in a document via an alert box.

function getSelectedCheckboxes(chkboxName) {
  var checkbx = [];
  var chkboxes = document.getElementsByName(chkboxName);
  var nr_chkboxes = chkboxes.length;
  for(var i=0; i<nr_chkboxes; i++) {
    if(chkboxes[i].type == 'checkbox' && chkboxes[i].checked == true) checkbx.push(chkboxes[i].value);
  }
  return checkbx;
}

And to call it I use:

<button id="btn_test" type="button" >Check</button>

Now I would like to modify it so when I click the btn_test button the output array checkbx is copied to the clipboard. I tried adding:

checkbx = document.execCommand("copy");

or

checkbx.execCommand("copy");

at the end of the function and then calling it like:

<button id="btn_test" type="button" onclick="getSelectedCheckboxes('my_id')">Check</button>

But it does not work. No data is copied to clipboard.

Body:
I managed to copy text to the clipboard (without showing any text boxes)  by adding a hidden input element to body,  i.e.:

 function copy(txt){
  var cb = document.getElementById("cb");
  cb.value = txt;
  cb.style.display='block';
  cb.select();
  document.execCommand('copy');
  cb.style.display='none';
 }

<button onclick="copy('Hello Clipboard!')"> copy </button>
<input id="cb" type="text" hidden>


问:
How to create a pandas dataframe where columns are filled with random strings?
I want to create a Pandas dataframe with 2 columns and x number rows that contain random strings.

I have found code to generate a pandas dataframe with random ints and a random stringer generator. I still don't see a clear path to create a pandas data frame with random strings.

Code for random int dataframe

import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))
```

<p>Code for random strings</p>

<pre class="lang-py prettyprint-override"><code>import string
import random
def id_generator(size=1500, chars=string.ascii_uppercase + string.digits):
    return ''.join(random.choice(chars) for _ in range(size))

id_generator()
</code>```

I would like destiredDataframe.head() to output two columns of random text and x number of rows.

答:
you can do something like below:</p>

```<code>>>> pd.DataFrame(np.arange(12).reshape(4,3)).applymap(lambda x: np.random.choice(list(string.ascii_letters)))
   0  1  2
0  w  c  c
1  o  B  I
2  n  T  q
3  l  X  K
</code>```

Body:
I want to create a Pandas dataframe with 2 columns and x number rows that contain random strings.

I have found code to generate a pandas dataframe with random ints and a random stringer generator. I still don't see a clear path to create a pandas data frame with random strings.

Code for random int dataframe

import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))

Code for random strings

import string
import random
def id_generator(size=1500, chars=string.ascii_uppercase + string.digits):
    return ''.join(random.choice(chars) for _ in range(size))

id_generator()

I would like destiredDataframe.head() to output two columns of random text and x number of rows.

Body:
you can do something like below:

>>> pd.DataFrame(np.arange(12).reshape(4,3)).applymap(lambda x: np.random.choice(list(string.ascii_letters)))
   0  1  2
0  w  c  c
1  o  B  I
2  n  T  q
3  l  X  K


问:
Cannot access javascript variable inside symfony controller
On my symfony (v3.4) project, I need to pass some javascript variables from my view to my controller containing a form : I used Jquery and Ajax to send my variable to the right route but for some reason I cannot access it from my controller.

Here is the script part in my twig view:

$(".month").click(function() {

  var click = $(this);

  var month = click.val();
  var year = $("#years").val();

  var url = "{{ path('av_platform_saisie') }}";

  $.ajax(url, {
    type: 'POST',
    data: {
      'month': month,
      'year': year
    },
    success: function(data) {
      alert('OK');
    },
    error: function(jqXHR, textStatus, errorThrown) {}
  });

});
```

<p>And my controller: </p>

<pre class="lang-php prettyprint-override"><code>public function saisieAction(Request $request)
{

    $user = $this->getUser();
    $thisyear = date("Y");

    $em = $this->getDoctrine()->getManager();

    // Create the form
    $form = $this->get('form.factory')->createBuilder(FormType::class)
        ->add('ndf', CollectionType::class, array(
            'entry_type' => NoteDeFraisType::class,
            'label' => false,
            'allow_add' => true,
            'allow_delete' => true,
        ))
        ->getForm();

    // if the form has been submited
    if ($request->isMethod('POST') && $form->handleRequest($request)->isValid()) {

        if($request->isXMLHttpRequest()){

            $month = $request->get('month');
            $year = $request->get('year');
            $sub_date = $month .'/' .$year;

        }

        $notesDeFrais = $form['ndf']->getData();

        foreach ($notesDeFrais as $ndf) {
            $ndf->setUser($user);
            $ndf->setMonth($sub_date);
            $em->persist($ndf);
        }

        $em->flush();

    }

    return $this->render('AvPlatformBundle:Platform:saisie.html.twig',
        array(
            'year' => $thisyear,  'form' => $form->createView()
        ));
}
</code>```

The weird thing is: I tried to send my js variables from a new Twig view that is not rendered by my controller and it's working just fine with exactly the same code so maybe it is a normal behavior ?

EDIT:
I did some debugging and actually and the code inside my if($request->isXMLHttpRequest()) is not executed

答:
You're not using the right syntax to get your parameters, this is how it should be :

```<code>if($request->isXMLHttpRequest()) {
    $month=$request->request->get('month');
    $year=$request->request->get('year');
    $sub_date=$month .'/' .$year;
}
</code>```

And in case you want to get GET parametrers, it's this :

```<code>$request->query->get('get_param');
</code>```

Body:
On my symfony (v3.4) project, I need to pass some javascript variables from my view to my controller containing a form : I used Jquery and Ajax to send my variable to the right route but for some reason I cannot access it from my controller.

Here is the script part in my twig view:

$(".month").click(function() {

  var click = $(this);

  var month = click.val();
  var year = $("#years").val();

  var url = "{{ path('av_platform_saisie') }}";

  $.ajax(url, {
    type: 'POST',
    data: {
      'month': month,
      'year': year
    },
    success: function(data) {
      alert('OK');
    },
    error: function(jqXHR, textStatus, errorThrown) {}
  });

});

And my controller:

public function saisieAction(Request $request)
{

    $user = $this->getUser();
    $thisyear = date("Y");

    $em = $this->getDoctrine()->getManager();

    // Create the form
    $form = $this->get('form.factory')->createBuilder(FormType::class)
        ->add('ndf', CollectionType::class, array(
            'entry_type' => NoteDeFraisType::class,
            'label' => false,
            'allow_add' => true,
            'allow_delete' => true,
        ))
        ->getForm();

    // if the form has been submited
    if ($request->isMethod('POST') && $form->handleRequest($request)->isValid()) {

        if($request->isXMLHttpRequest()){

            $month = $request->get('month');
            $year = $request->get('year');
            $sub_date = $month .'/' .$year;

        }

        $notesDeFrais = $form['ndf']->getData();

        foreach ($notesDeFrais as $ndf) {
            $ndf->setUser($user);
            $ndf->setMonth($sub_date);
            $em->persist($ndf);
        }

        $em->flush();

    }

    return $this->render('AvPlatformBundle:Platform:saisie.html.twig',
        array(
            'year' => $thisyear,  'form' => $form->createView()
        ));
}

The weird thing is: I tried to send my js variables from a new Twig view that is not rendered by my controller and it's working just fine with exactly the same code so maybe it is a normal behavior ?

EDIT:
I did some debugging and actually and the code inside my if($request->isXMLHttpRequest()) is not executed

Body:
You're not using the right syntax to get your parameters, this is how it should be :

if($request->isXMLHttpRequest()) {
    $month=$request->request->get('month');
    $year=$request->request->get('year');
    $sub_date=$month .'/' .$year;
}

And in case you want to get GET parametrers, it's this :

$request->query->get('get_param');


问:
Alternative to using subqueries in SQL statements?
I have two tables:

```<code>TableA: (a temporary table)
ItemId (int)

TableB:
ItemId (int), ParentID (int)
</code>```

I want to retrieve all items in Table A where the ParentID of any of the items in Table A doesn't exist as an ItemID. (i.e. I want to get the root of the items in TableA)

This query does what I want:

```<code>SELECT a.ItemID
FROM TableA a
INNER JOIN TableB b ON a.ItemId = b.ItemID
WHERE b.ParentID NOT IN ( SELECT * from TableA )
</code>```

as does this one:

```<code>SELECT b.ItemID
FROM TableB b
WHERE b.ItemID IN ( SELECT * FROM TableA)
AND b.ParentID NOT IN ( SELECT * FROM TableA )
</code>```

I am not satisfied with either of the queries, particularly because of the use of NOT IN/IN. Is there a way to do this without them? Perhaps a cleaner way that doesn't require subqueries?

Sample Data:

```<code>Table A
-------
2
3
5
6

Table B
--------
1 | NULL
2 | 1
3 | 1
4 | 3
5 | 3
6 | 3
</code>```

Desired Result:

```<code>2
3
</code>```

Thanks

答:
You can use outer joins. Something like this:</p>

```<code>SELECT a.ItemID
FROM TableA a
INNER JOIN TableB b ON a.ItemId = b.ItemID
LEFT JOIN TableB parentB on a.ItemID = parentB.ParentID
WHERE parentB.ParentID IS NULL
</code>```

Body:
I have two tables:

TableA: (a temporary table)
ItemId (int)

TableB:
ItemId (int), ParentID (int)

I want to retrieve all items in Table A where the ParentID of any of the items in Table A doesn't exist as an ItemID. (i.e. I want to get the root of the items in TableA)

This query does what I want:

SELECT a.ItemID
FROM TableA a
INNER JOIN TableB b ON a.ItemId = b.ItemID
WHERE b.ParentID NOT IN ( SELECT * from TableA )

as does this one:

SELECT b.ItemID
FROM TableB b
WHERE b.ItemID IN ( SELECT * FROM TableA)
AND b.ParentID NOT IN ( SELECT * FROM TableA )

I am not satisfied with either of the queries, particularly because of the use of NOT IN/IN. Is there a way to do this without them? Perhaps a cleaner way that doesn't require subqueries?

Sample Data:

Table A
-------
2
3
5
6

Table B
--------
1 | NULL
2 | 1
3 | 1
4 | 3
5 | 3
6 | 3

Desired Result:

2
3

Thanks

Body:
You can use outer joins. Something like this:

SELECT a.ItemID
FROM TableA a
INNER JOIN TableB b ON a.ItemId = b.ItemID
LEFT JOIN TableB parentB on a.ItemID = parentB.ParentID
WHERE parentB.ParentID IS NULL


问:
Necessity of const specifier in cast
Suppose I have some code like this:

```<code>void foo (void *ptr) {
    const struct some *azaza = (const struct some *)ptr;
    azaza->some_field = 123; // inadvertently assignment => error
    // ...
</code>```

Is the const specifier really needed in cast?

EDIT: foo is callback function with a particular prototype that I can't change (it's not in my code).

答:
In your specific case you don't even need a cast. In case of void * cast is needed only when dereferencing. So it is sufficient to do:

```<code>const struct some *azaza = ptr;
</code>```

But for the sake of interest,

#gcc test.c:

```<code>// 1)
const struct some *azaza = ptr;
azaza->some_field = 123; // error: assignment in read-only object

// 2)
struct some *azaza = (const struct some *)ptr; // (!)warning: initialization discards ‘const’ qualifier

azaza->some_field = 123;
</code>```

#gcc test.c -pedantic-errors:

```<code>// 1)
const struct some *azaza = ptr;
azaza->some_field = 123; // error: assignment in read-only object

// 2)
struct some *azaza = (const struct some *)ptr; // error: initialization
                                               // discards ‘const’ qualifier

azaza->some_field = 123;
</code>```

To sum up:

You need no const in cast.

If you use const only in cast (for some odd reason ._.) and without -pedantic-errors - an accidently assignment will not result in an error what is fraught with consequences.

Title: Necessity of const specifier in cast

Body:
Suppose I have some code like this:

void foo (void *ptr) {
    const struct some *azaza = (const struct some *)ptr;
    azaza->some_field = 123; // inadvertently assignment => error
    // ...

Is the const specifier really needed in cast?

EDIT: foo is callback function with a particular prototype that I can't change (it's not in my code).

Body:
In your specific case you don't even need a cast. In case of void * cast is needed only when dereferencing. So it is sufficient to do:

const struct some *azaza = ptr;

But for the sake of interest,

#gcc test.c:

// 1)
const struct some *azaza = ptr;
azaza->some_field = 123; // error: assignment in read-only object

// 2)
struct some *azaza = (const struct some *)ptr; // (!)warning: initialization discards ‘const’ qualifier

azaza->some_field = 123;

#gcc test.c -pedantic-errors:

// 1)
const struct some *azaza = ptr;
azaza->some_field = 123; // error: assignment in read-only object

// 2)
struct some *azaza = (const struct some *)ptr; // error: initialization
                                               // discards ‘const’ qualifier

azaza->some_field = 123;

To sum up:

You need no const in cast.

If you use const only in cast (for some odd reason ._.) and without -pedantic-errors - an accidently assignment will not result in an error what is fraught with consequences.


问:
PostgreSql: 'utf8' codec can't decode byte 0xe9 in position 42: invalid continuation byte
I recently installed PostgreSql and I am trying to create a new database.
Unfortunetly I got and error while creating the database:

"'utf8' codec can't decode byte 0xe9 in position 42: invalid continuation byte"

What is the problem exactly
thank you

答:
I had a similar error when upgrading from 4.5 to 4.7, the solution was to restart the pgAdmin server.

My error was:
Error: 'utf-8' codec can't decode byte 0xe9 in position 0: invalid continuation byte


问:
"Call to a member function fetch_assoc() on boolean"
I've seen a bunch of questions about this error, but none of them seemed to have an answer that solved my problem... Sorry if I missed one.

My script keeps giving me an error saying

Call to a member function fetch_assoc() on boolean

but I don't see how this is the case.

Both $mysqli_query and $mysqli_query->fetch_assoc() are objects. Those respectively being:

```<code>object(mysqli_result)#4 (5) {
["current_field"]=>
  int(0)
["field_count"]=>
  int(2)
["lengths"]=>
  NULL
["num_rows"]=>
  int(1)
["type"]=>
  int(0)
}
</code>```

and

```<code>array(2) {
["date"]=>
  string(10) "2016-11-19"
["roles"]=>
  string(241) "{"eu":{"host":{"max":2,"0":"U0SEMUG8L"},"chat":{"max":1,"0":"U0SEMUG8L"},"bg":{"max":2,"0":"U0SEMUG8L"}},"us":{"host":{"max":2,"0":"U0SEMUG8L","1":"U0SEMUG8L","2":"U0SEMUG8L"},"chat":{"max":1,"0":"U0SEMUG8L","1":"U0SEMUG8L"},"bg":{"max":2}}}"
}
</code>```

These also produce the same error:

```<code>SELECT * FROM `hosting_signups`
SELECT * FROM `hosting_signups` WHERE 1
</code>```

When the following is run in PhpMyAdmin, it works fine:

```<code>SELECT * FROM `hosting_signups` WHERE `date`='2016-11-19'
</code>```

Does anyone know what I'm doing wrong? Here is the relevant code:

```<code>$mysqli_cmd = "SELECT * FROM `hosting_signups` WHERE `date`='" . $next_karaoke->format("Y-m-d") . "'";
$mysqli_query = $mysqli->query($mysqli_cmd);
//var_dump($mysqli_query->fetch_assoc()); // Oddly, when uncommented this terminates the
                                          // whole while loop below, and the error is not
                                          // produced but my code inside does not run. I'm
                                          // not sure if this is at all related to my problem.

while($row = $mysqli_query->fetch_assoc()) {}
</code>```

EDIT:
I've modified my code a bit, with some more debugging, to be:

```<code>$mysqli_cmd = "SELECT * FROM `hosting_signups` WHERE `date`='" . $next_karaoke->format("Y-m-d") . "'";
$mysqli_query = $mysqli->query($mysqli_cmd);

var_dump($mysqli_cmd);
var_dump($mysqli->error);

while($row = $mysqli_query->fetch_assoc()) {}
</code>```

The output is:

```<code>string(57) "SELECT * FROM `hosting_signups` WHERE `date`='2016-11-19'"
string(0) ""
Fatal error:  Call to a member function fetch_assoc() on boolean in
/home2/bugfroggy/public_html/hosting_signup.php on line 63
</code>```

EDIT 2:
Was a stupid mistake on my end.. I was accidentally changing the value of $mysqli_query in the while loop instead of the query variable for another query I was doing inside of the loop. Problem solved!

答: For me the error was the table name; It was 'user' instead of 'User' which I didn't expect because even with the upper case it worked on my local wamp, the error began when I uploaded my project on LWS</p>

Body:
I've seen a bunch of questions about this error, but none of them seemed to have an answer that solved my problem... Sorry if I missed one.

My script keeps giving me an error saying

Call to a member function fetch_assoc() on boolean

but I don't see how this is the case.

Both $mysqli_query and $mysqli_query->fetch_assoc() are objects. Those respectively being:

object(mysqli_result)#4 (5) {
["current_field"]=>
  int(0)
["field_count"]=>
  int(2)
["lengths"]=>
  NULL
["num_rows"]=>
  int(1)
["type"]=>
  int(0)
}

and

array(2) {
["date"]=>
  string(10) "2016-11-19"
["roles"]=>
  string(241) "{"eu":{"host":{"max":2,"0":"U0SEMUG8L"},"chat":{"max":1,"0":"U0SEMUG8L"},"bg":{"max":2,"0":"U0SEMUG8L"}},"us":{"host":{"max":2,"0":"U0SEMUG8L","1":"U0SEMUG8L","2":"U0SEMUG8L"},"chat":{"max":1,"0":"U0SEMUG8L","1":"U0SEMUG8L"},"bg":{"max":2}}}"
}

These also produce the same error:

SELECT * FROM `hosting_signups`
SELECT * FROM `hosting_signups` WHERE 1

When the following is run in PhpMyAdmin, it works fine:

SELECT * FROM `hosting_signups` WHERE `date`='2016-11-19'

Does anyone know what I'm doing wrong? Here is the relevant code:

$mysqli_cmd = "SELECT * FROM `hosting_signups` WHERE `date`='" . $next_karaoke->format("Y-m-d") . "'";
$mysqli_query = $mysqli->query($mysqli_cmd);
//var_dump($mysqli_query->fetch_assoc()); // Oddly, when uncommented this terminates the
                                          // whole while loop below, and the error is not
                                          // produced but my code inside does not run. I'm
                                          // not sure if this is at all related to my problem.

while($row = $mysqli_query->fetch_assoc()) {}

EDIT:
I've modified my code a bit, with some more debugging, to be:

$mysqli_cmd = "SELECT * FROM `hosting_signups` WHERE `date`='" . $next_karaoke->format("Y-m-d") . "'";
$mysqli_query = $mysqli->query($mysqli_cmd);

var_dump($mysqli_cmd);
var_dump($mysqli->error);

while($row = $mysqli_query->fetch_assoc()) {}

The output is:

string(57) "SELECT * FROM `hosting_signups` WHERE `date`='2016-11-19'"
string(0) ""
Fatal error:  Call to a member function fetch_assoc() on boolean in
/home2/bugfroggy/public_html/hosting_signup.php on line 63

EDIT 2:
Was a stupid mistake on my end.. I was accidentally changing the value of $mysqli_query in the while loop instead of the query variable for another query I was doing inside of the loop. Problem solved!


问:
Finding on which element a particular keyboard listener is waiting on
In a website which I visit everyday, when I press the key b, it opens a form. I have been trying to open the form using jQuery, but I don't seem to get it working.

Since the below code is not opening up the form, can I conclude they did not add the event listener on any of the DOM elements?

Appreciate any help figuring out on which element the listener is on..

$("*").each(function() {

  $(this).trigger(
    jQuery.Event('keydown', {
      keyCode: "98",
      which: "98"
    })

  )

  $(this).trigger(
    jQuery.Event('keyup', {
      keyCode: "98",
      which: "98"
    })
  )

  $(this).trigger(
    jQuery.Event('keypress', {
      keyCode: "98",
      which: "98"
    })
  )
})```

答:
Ok so this may not directly answer your question but it should definitely help!

If you add the "Visual Event" bookmarklet and use it to visualise the events.

http://www.sprymedia.co.uk/article/Visual+Event

You probably want to be looking for the keydown keyup keypress icons which will most likely be in the top left of the window.


问:
Webpack: transpiling of assets transferred to dist directory using copy-webpack-plugin
I am integrating an SPA built predominantly using d3.js into Webpack. I'm transpiling with Babel, and using the latest versions of everything..

Before integration, d3.js allowed me (event-driven) to inject scripts dynamically, entirely reusably, recursively and hence effortlessly into the served-up html file. The only thing I had to provide were the foundational JSON files.

For example (just for info, not critical to understanding the question), for a menu-building javascript file:

```<code>case "js":
  files_to_attach
  .insert("script") // --> inject into html file
  .attr("src", function() {
    return "frontend/" + filetype + "/" + menu_group + "/" + menu + "/" + filename + "." + filetype;
  })
  .attr("type", "text/javascript") // Also tried using type "module" here
  .attr("class", menu)
  .attr("id", menu_item);
break;
</code>```

This approach was used across all loaded assets.

Webpack has it's own mechanisms for dynamic loading, but I chose (by importing all external scripts, then selecting, on-demand, from their assigned constant names) to stick with the above, again direct-injecting them into the dist/index.html file.

I did this so that these loading actions can, in the future, be easily converted to database calls.

To allow all this to happen, I had to transfer the scripts en bloc from the frontend (normally 'src') to the dist directory using the 'copy-webpack-plugin'.

This differs from the prescribed Webpack lazy loading approach in that these scripts are external to, rather than an integral part of, index.js.

The problem? These files still contain the untranspiled import statements, provoking the following:

```<code>SyntaxError: import declarations may only appear at top level of a module
</code>```

These import statements lie, needless to say, at the head of each module.

The question, then, is:

Given the scripts are correctly injected into the final html, how do I ensure they are also (pre- or post-) transpiled?

The configuration is simple and the question a general one, so to show more code seems superfluous. I imagine there may be a few approaches to this.

SUMMARY THUS FAR

Webpack ruthlessly blocks all attempts at non-'import'-or-'require'-style file system access, but neither import nor require can return a direct reference to a file (as opposed to the file's contents). So import statements (which do lead to transpiling) cannot be leveraged to inject a script to HTML.

Script injections using libraries such as d3.js are simply left un-transpiled. Is there some means of 'force'-transpiling them?

The only documented means of script injection is effectively static, using multiple entry points. Furthermore, no plugin seems to exist that can assist with dynamic script injection. (The nearest I've found to a solution is inject-html-webpack-plugin, but the plugin's documentation is brutally terse, with no example of so-called 'transducer' use).

Truly dynamic, transpiled script injection into HTML seems blocked on all fronts.

No files copied using copy-webpack-plugin are transpiled, but do I see mention here of a tortuous workaround ("copy the files from the src files into the module, process them and then move the generated/processed files").

答:
copy-webpack-plugin is literally a fs.move command. Since some plugins run first than loaders, specially in this case, they aren't being transpiled.

To do that you'll have to add the external files as a new entrypoint, where the source code is going to be generated and created at the end, and you can add them to index as well

Body:
I am integrating an SPA built predominantly using d3.js into Webpack. I'm transpiling with Babel, and using the latest versions of everything..

Before integration, d3.js allowed me (event-driven) to inject scripts dynamically, entirely reusably, recursively and hence effortlessly into the served-up html file. The only thing I had to provide were the foundational JSON files.

For example (just for info, not critical to understanding the question), for a menu-building javascript file:

case "js":
  files_to_attach
  .insert("script") // --> inject into html file
  .attr("src", function() {
    return "frontend/" + filetype + "/" + menu_group + "/" + menu + "/" + filename + "." + filetype;
  })
  .attr("type", "text/javascript") // Also tried using type "module" here
  .attr("class", menu)
  .attr("id", menu_item);
break;

This approach was used across all loaded assets.

Webpack has it's own mechanisms for dynamic loading, but I chose (by importing all external scripts, then selecting, on-demand, from their assigned constant names) to stick with the above, again direct-injecting them into the dist/index.html file.

I did this so that these loading actions can, in the future, be easily converted to database calls.

To allow all this to happen, I had to transfer the scripts en bloc from the frontend (normally 'src') to the dist directory using the 'copy-webpack-plugin'.

This differs from the prescribed Webpack lazy loading approach in that these scripts are external to, rather than an integral part of, index.js.

The problem? These files still contain the untranspiled import statements, provoking the following:

SyntaxError: import declarations may only appear at top level of a module

These import statements lie, needless to say, at the head of each module.

The question, then, is:

Given the scripts are correctly injected into the final html, how do I ensure they are also (pre- or post-) transpiled?

The configuration is simple and the question a general one, so to show more code seems superfluous. I imagine there may be a few approaches to this.

SUMMARY THUS FAR

Webpack ruthlessly blocks all attempts at non-'import'-or-'require'-style file system access, but neither import nor require can return a direct reference to a file (as opposed to the file's contents). So import statements (which do lead to transpiling) cannot be leveraged to inject a script to HTML.

Script injections using libraries such as d3.js are simply left un-transpiled. Is there some means of 'force'-transpiling them?

The only documented means of script injection is effectively static, using multiple entry points. Furthermore, no plugin seems to exist that can assist with dynamic script injection. (The nearest I've found to a solution is inject-html-webpack-plugin, but the plugin's documentation is brutally terse, with no example of so-called 'transducer' use).

Truly dynamic, transpiled script injection into HTML seems blocked on all fronts.

No files copied using copy-webpack-plugin are transpiled, but do I see mention here of a tortuous workaround ("copy the files from the src files into the module, process them and then move the generated/processed files").


问:
Writing the results in html file by passing the values in java - any help would be greatly appreciated
Placed the reports have overrided all the resultsi would like to print in a table with results but when i printed it overriding the results and it is printing only one line

am passing the values form other class file to print the results

i have tried using Buffered  writer for writing the code

public void createTestSummaryHTMLTable(String sample,String samp[le,String sample,String passedText,String status) throws IOException {

    File file=new File("C:\\AutomationResults\\Forms\\",foldername);
    if(!file.exists()){
        file.mkdir();}

    final String FILE_PATH =(file+"/"+formname);

    //final String FILE_PATH = "C:\\AutomationResults\\Forms\\"+formname;
    final String FILE_EXTENSION = "html";
    DateFormat df = new SimpleDateFormat("yyyyMMdd"); // add S if you need milliseconds
    String filename = FILE_PATH + "_"+ df.format(new Date()) + "." + FILE_EXTENSION;

    File file2 = new File(filename);

    // if file doesnt exists, then create it
    if (!file2.exists()) {
        file2.createNewFile();
    }
    BufferedWriter html = new BufferedWriter(new FileWriter(file2));
    html.write("
");
    html.write("<title>Automation Summary report </title>");
    html.write("
");
    html.write("Batch report heading");
    html.write(""+new Date().toString()+"");
    html.write("
");
    addlabel1(html,"Test Step Name");
    addlabel1(html,"Test Step Description");
    addlabel1(html,"Status");
    addlabel1(html,"Screenshot");
    html.write("
");

    html.write("
");
    html.newLine();
    addlabel(html,sample);

    addlabel(html,sample);

    String status1 = "Passed";
    if (status1.equals(status))
    {
        html.write(""+status+"	");
    } else {
        html.write(""+status+"	");
    }

    addlabel(html,"Screenshot");

    html.write("
");
    html.write("
");
    html.close();
}
```

答:
the actualresult

header is displaying for every row i dont need the header to display for all the rows result am getting is
expected result is

header should display only once


问:
Same format different results. Help me understand why CONTAINS returns differently to essentially the same query
I have the following query:

```<code>select*
from dbo.Users
where CONTAINS(UEmailLogin,'"email1@mail.com*"')

select *
from dbo.Users
where CONTAINS(UEmailLogin,'"email2@mail.com*"')
</code>```

The first query returns nothing.

The second returns the expected results.

When I remove the asterisk from the search term

i.e

```<code>'"email1@mail.com"'
</code>```

vs

```<code>'"email1@mail.com*"'
</code>```

I obtain the expected results.

I am trying to understand what is happening. Both rows returned from the query search of email1 and email2 are almost identical. The only significant difference is the date of their creation. The row containing EmailLogin email2 was created a few months ago, whereas email1 is much more recent.

I have been reading the CONTAINS microsoft documentation and I have been thinking it might have to do with indexing.

Anyone with knowledge able to provide some insight?

答:
CONTAINS is for full text search

Does your UEmailLogin has value email2@mail.com* or just email2@mail.com ?

You have option to use like query also.

Body:
I have the following query:

select*
from dbo.Users
where CONTAINS(UEmailLogin,'"email1@mail.com*"')

select *
from dbo.Users
where CONTAINS(UEmailLogin,'"email2@mail.com*"')

The first query returns nothing.

The second returns the expected results.

When I remove the asterisk from the search term

i.e

'"email1@mail.com"'

vs

'"email1@mail.com*"'

I obtain the expected results.

I am trying to understand what is happening. Both rows returned from the query search of email1 and email2 are almost identical. The only significant difference is the date of their creation. The row containing EmailLogin email2 was created a few months ago, whereas email1 is much more recent.

I have been reading the CONTAINS microsoft documentation and I have been thinking it might have to do with indexing.

Anyone with knowledge able to provide some insight?


问:
Task.WaitAll seems bugged
I'm developing a simulation tool that performs various mathematical operations. So far I have not had the need to do parallel operations, but now I really need them. Among the various methods of parallelism I have read that best performance should be achieved using the Tasks.

I wrote this simple program, but I realized that something is wrong.

private static int taskCounter { get; set; }
private static void SimpleTest() { taskCounter--; }

static void Main(string[] args)
{
    for (int N = 0; N < 100; N++)
    {
        taskCounter = 0;
        List<Task> taskList = new List<Task>();
        for (int i = 0; i < 100; i++)
        {
            taskCounter++;
            Task task = Task.Factory.StartNew(() => SimpleTest());
            taskList.Add(task);
        }
        Task.WaitAll(taskList.ToArray());
        Console.WriteLine("Unsolved: {0}", taskCounter);
    }
}
```

<p>Expected: Unsolved: 0 for all iterations.
Result:</p>

```[...]
Unsolved: 0
Unsolved: 0
Unsolved: 2
Unsolved: -4
Unsolved: -1
Unsolved: -1
Unsolved: 0
Unsolved: 0
Unsolved: 2
Unsolved: -1
[...]
```

答:
As noted by elgonzo in his comment. The two operations taskCounter++ and taskCounter-- are not atomic, meaning they actually consist of several steps (read the variable from memory, add or substract one to it, then write the result back to memory.

With several threads performing those sequences simultaneously the final result can become incorrect.
Say thread 1 and thread 2 read the variable from memory at the same time increment their respective copies independently then try to write the result back to memory. In that case, the final value that was written to memory is not the same as if those two sequences were performed one after the other.

The cache memory of modern CPU makes it very likely that those operations performed in parallel produce an incorrect result. If as suggested you use  Interlocked.Increment / Interlocked.Decrement you will get a consistent result. Those two operations use hardware support to guarantee atomicity.

Title: Task.WaitAll seems bugged

Body:
I'm developing a simulation tool that performs various mathematical operations. So far I have not had the need to do parallel operations, but now I really need them. Among the various methods of parallelism I have read that best performance should be achieved using the Tasks.

I wrote this simple program, but I realized that something is wrong.

private static int taskCounter { get; set; }
private static void SimpleTest() { taskCounter--; }

static void Main(string[] args)
{
    for (int N = 0; N < 100; N++)
    {
        taskCounter = 0;
        List<Task> taskList = new List<Task>();
        for (int i = 0; i < 100; i++)
        {
            taskCounter++;
            Task task = Task.Factory.StartNew(() => SimpleTest());
            taskList.Add(task);
        }
        Task.WaitAll(taskList.ToArray());
        Console.WriteLine("Unsolved: {0}", taskCounter);
    }
}

Expected: Unsolved: 0 for all iterations.
Result:

[...]
Unsolved: 0
Unsolved: 0
Unsolved: 2
Unsolved: -4
Unsolved: -1
Unsolved: -1
Unsolved: 0
Unsolved: 0
Unsolved: 2
Unsolved: -1
[...]


问:
How can I delay splash launch screen programmatically in Swift Xcode iOS
I have put an image in imageView in LaunchStoreyboard. How can I delay the time of image programmatically?

Here is the Launch Screen Guideline from Apple.

Here is code for Launch Screen View controller:

```<code>import UIKit
class LaunshViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        self.delay(0.4)
    }

    func delay(_ delay:Double, closure:@escaping ()->()) {
        let when = DispatchTime.now() + delay
        DispatchQueue.main.asyncAfter(deadline: when, execute: closure)
    }
}
</code>```

答:
Definitely your app should not be put to sleep as it may be killed by the OS for being unresponsive for so long.

If you're using a static image for your launch screen, what works for me is to use the image in the LaunchScreen.storyboard, and then when your main controller launches, modally present a VC with the same image as the background in the ViewDidAppear of your main controller (with animated set to false).

You can then use your logic to know when to dismiss the launch screen (dismiss method in the VC with animated set to false).

The transition from the actual LaunchScreen to my VC presenting the same screen looks to me imperceptible.

PS: the ViewDidAppear method might be called more than once, in which case you need to use logic to not present the VC with the launch screen a second time.

Body:
I have put an image in imageView in LaunchStoreyboard. How can I delay the time of image programmatically?

Here is the Launch Screen Guideline from Apple.

Here is code for Launch Screen View controller:

import UIKit
class LaunshViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        self.delay(0.4)
    }

    func delay(_ delay:Double, closure:@escaping ()->()) {
        let when = DispatchTime.now() + delay
        DispatchQueue.main.asyncAfter(deadline: when, execute: closure)
    }
}


问:
Why does this acquire and release memory fence not give a consistent value?
im just exploring the use of acquire and release memory fences and  dont understand why i get the value output to zero sometimes and not the value of 2 all the time

I ran the program a number of times , and assumed the atomic store before the release barrier and the atomic load after the acquire barrier would ensure the values always would synchronise

```<code>#include <iostream>
#include <thread>
#include <atomic>

std::atomic<int>x;

void write()
{

    x.store(2,std::memory_order_relaxed);

    std::atomic_thread_fence(std::memory_order_release);

}

void read()
{

    std::atomic_thread_fence(std::memory_order_acquire);

    // THIS DOES NOT GIVE THE EXPECTED VALUE OF 2 SOMETIMES
    std::cout<<x.load(std::memory_order_relaxed)<<std::endl;

}

int main()
{

std::thread t1(write);
std::thread t2(read);
t1.join();
t2.join();
return 0;
}
</code>```

the atomic varible x gives a value of 0 sometimes

答:
I think you are misunderstanding the purpose of fences. Fences only enforce a certain ordering of memory operations for the compiler and processor in a single thread of execution. Your acquire fence will not magically make the thread wait until the óther thread performs the release.

Some literature will describe that a release operation in one thread "synchronizes with" a subsequent acquire operation in another thread. The key to this is that the acquire action is a subsequent action (i.e. the acquire is ordered "after" the release). If the release action is ordered after your acquire action, then there is no synchronizes-with relation between the write and read operations.

The reason why your code doesn't consistently return what you're expecting is because the thread interleavings sometimes order the write before the read, sometimes the read before the write.

If you want to guarantee that thread t2 reads the value 2 that thread t1 publishes, you're going to have to force t2 to wait for the publish to happen. The textbook example almost invariably uses a guard variable that notifies t2 that the data is ready to be consumed.

I recommend you read a very well-written blog post about release and acquire semantics and the synchronizes-with relation at Preshing on Programming's The Synchronizes-With Relation.

Body:
im just exploring the use of acquire and release memory fences and  dont understand why i get the value output to zero sometimes and not the value of 2 all the time

I ran the program a number of times , and assumed the atomic store before the release barrier and the atomic load after the acquire barrier would ensure the values always would synchronise

#include <iostream>
#include <thread>
#include <atomic>

std::atomic<int>x;

void write()
{

    x.store(2,std::memory_order_relaxed);

    std::atomic_thread_fence(std::memory_order_release);

}

void read()
{

    std::atomic_thread_fence(std::memory_order_acquire);

    // THIS DOES NOT GIVE THE EXPECTED VALUE OF 2 SOMETIMES
    std::cout<<x.load(std::memory_order_relaxed)<<std::endl;

}

int main()
{

std::thread t1(write);
std::thread t2(read);
t1.join();
t2.join();
return 0;
}

the atomic varible x gives a value of 0 sometimes


问:
React Native: Remove Expo Cookies
I'm building a Expo/React Native app where I use fetch and credentials (cookies) to log into a server.

The code works properly and looks like this:

```<code>login = async (email, password) => {
    try {
        var body = JSON.stringify({ email, password });

        const response = await fetch('http://10.0.2.2/login', {
            method: 'POST',
            credentials: 'include',
            headers: {
              'Accept': 'application/json',
              'Content-Type': 'application/json'
            },
            body: JSON.stringify({
              username: username,
              password: password
            })
        });

        if(response.hasOwnProperty('accessToken'))
        {
          console.log('login successfull');
          console.log(response);
        }
        else if(response.hasOwnProperty('error'))
        {
          console.log('login failed');
          console.log(response)
        }
    }
    catch(e) {
      console.log('error: ' + e);
    }
};
</code>```

My problem is, that React Native does not log out when I stop the app. I dont want to manually logout by API call.

Is there a way like in React Web, where I simply removed the cookies from Chrome and then I am logged out?

答:
if you are using expo then you could try :

```<code>expo r -c
</code>```

this would clear your project's cache and run expo

Title: React Native: Remove Expo Cookies

Body:
I'm building a Expo/React Native app where I use fetch and credentials (cookies) to log into a server.

The code works properly and looks like this:

login = async (email, password) => {
    try {
        var body = JSON.stringify({ email, password });

        const response = await fetch('http://10.0.2.2/login', {
            method: 'POST',
            credentials: 'include',
            headers: {
              'Accept': 'application/json',
              'Content-Type': 'application/json'
            },
            body: JSON.stringify({
              username: username,
              password: password
            })
        });

        if(response.hasOwnProperty('accessToken'))
        {
          console.log('login successfull');
          console.log(response);
        }
        else if(response.hasOwnProperty('error'))
        {
          console.log('login failed');
          console.log(response)
        }
    }
    catch(e) {
      console.log('error: ' + e);
    }
};

My problem is, that React Native does not log out when I stop the app. I dont want to manually logout by API call.

Is there a way like in React Web, where I simply removed the cookies from Chrome and then I am logged out?

Body:
if you are using expo then you could try :

expo r -c

this would clear your project's cache and run expo


问:
How to add successfully pcl library to a qt project with qmake
i am trying to include pcl library to my qt application project using qmake. I found some similar questions, however none of the answers help to solve my problem.

I have tried to add to the .pro file the paths from pcl lib as well as the 3rd party libraries which are used by pcl. Here is the include lines of my .pro file.

```<code>win32:CONFIG(release, debug|release): LIBS += -LD:/Libraries/PCL_1.6.0/lib
win32:CONFIG(release, debug|release): LIBS += -LD:/Libraries/PCL_1.6.0/3rdParty/Eigen/bin
win32:CONFIG(release, debug|release): LIBS += -LD:/Libraries/PCL_1.6.0/3rdParty/Boost/lib

INCLUDEPATH +=  D:/Libraries/PCL_1.6.0/include/pcl-1.6
DEPENDPATH += D:/Libraries/PCL_1.6.0/include/pcl-1.6

INCLUDEPATH +=  D:/Libraries/PCL_1.6.0/3rdParty/Eigen/include
DEPENDPATH += D:/Libraries/PCL_1.6.0/3rdParty/Eigen/include

INCLUDEPATH +=  D:/Libraries/PCL_1.6.0/3rdParty/Boost/include
DEPENDPATH += D:/Libraries/PCL_1.6.0/3rdParty/Boost/include
</code>```

After that, i am just trying put this include to one of my files:

```<code>include pcl/io/pcd_io.h
</code>```

And these are the errors i am getting back:

D:\Libraries\PCL_1.6.0\3rdParty\Eigen\include\Eigen\src\Core\products\GeneralBlockPanelKernel.h:604: error: unable to find string literal operator 'operator""X' with 'const char [2]', 'long long unsigned int' arguments
   EIGEN_ASM_COMMENT("mybegin2");

D:\Libraries\PCL_1.6.0\3rdParty\Eigen\include\Eigen\src\Core\products\GeneralBlockPanelKernel.h:640: error: unable to find string literal operator 'operator""X' with 'const char [2]', 'long long unsigned int' arguments
   EIGEN_ASM_COMMENT("myend");

D:\Libraries\PCL_1.6.0\3rdParty\Eigen\include\Eigen\src\Core\products\GeneralBlockPanelKernel.h:644: error: unable to find string literal operator 'operator""X' with 'const char [2]', 'long long unsigned int' arguments
   EIGEN_ASM_COMMENT("mybegin4");

Can you please help me to solve the problem?

答:
I suggest to use CMake. See the links below:

These are two examples provided by PointCloudLibrary with CMake: qt_colorize_cloud and qt_visualizer.

Here is the explanation for the configuration in Qt.

The CMakeList.txt is as follows:

```<code>cmake_minimum_required(VERSION 2.8.11)

project(pcl_visualizer)

# init_qt: Let's do the CMake job for us
set(CMAKE_AUTOMOC ON) # For meta object compiler
set(CMAKE_AUTORCC ON) # Resource files
set(CMAKE_AUTOUIC ON) # UI files

# Find includes in corresponding build directories
set(CMAKE_INCLUDE_CURRENT_DIR ON)

# Find the QtWidgets library
find_package(Qt5 REQUIRED Widgets)

find_package(VTK REQUIRED)
find_package(PCL 1.7.1 REQUIRED)

# Fix a compilation bug under ubuntu 16.04 (Xenial)
list(REMOVE_ITEM PCL_LIBRARIES "vtkproj4")

include_directories(${PCL_INCLUDE_DIRS})
add_definitions(${PCL_DEFINITIONS})

set(project_SOURCES main.cpp pclviewer.cpp)

add_executable(${PROJECT_NAME} ${project_SOURCES})

target_link_libraries(${PROJECT_NAME} ${PCL_LIBRARIES} Qt5::Widgets)
</code>```

Hope it will help you.

Body:
i am trying to include pcl library to my qt application project using qmake. I found some similar questions, however none of the answers help to solve my problem.

I have tried to add to the .pro file the paths from pcl lib as well as the 3rd party libraries which are used by pcl. Here is the include lines of my .pro file.

win32:CONFIG(release, debug|release): LIBS += -LD:/Libraries/PCL_1.6.0/lib
win32:CONFIG(release, debug|release): LIBS += -LD:/Libraries/PCL_1.6.0/3rdParty/Eigen/bin
win32:CONFIG(release, debug|release): LIBS += -LD:/Libraries/PCL_1.6.0/3rdParty/Boost/lib

INCLUDEPATH +=  D:/Libraries/PCL_1.6.0/include/pcl-1.6
DEPENDPATH += D:/Libraries/PCL_1.6.0/include/pcl-1.6

INCLUDEPATH +=  D:/Libraries/PCL_1.6.0/3rdParty/Eigen/include
DEPENDPATH += D:/Libraries/PCL_1.6.0/3rdParty/Eigen/include

INCLUDEPATH +=  D:/Libraries/PCL_1.6.0/3rdParty/Boost/include
DEPENDPATH += D:/Libraries/PCL_1.6.0/3rdParty/Boost/include

After that, i am just trying put this include to one of my files:

include pcl/io/pcd_io.h

And these are the errors i am getting back:

D:\Libraries\PCL_1.6.0\3rdParty\Eigen\include\Eigen\src\Core\products\GeneralBlockPanelKernel.h:604: error: unable to find string literal operator 'operator""X' with 'const char [2]', 'long long unsigned int' arguments
   EIGEN_ASM_COMMENT("mybegin2");

D:\Libraries\PCL_1.6.0\3rdParty\Eigen\include\Eigen\src\Core\products\GeneralBlockPanelKernel.h:640: error: unable to find string literal operator 'operator""X' with 'const char [2]', 'long long unsigned int' arguments
   EIGEN_ASM_COMMENT("myend");

D:\Libraries\PCL_1.6.0\3rdParty\Eigen\include\Eigen\src\Core\products\GeneralBlockPanelKernel.h:644: error: unable to find string literal operator 'operator""X' with 'const char [2]', 'long long unsigned int' arguments
   EIGEN_ASM_COMMENT("mybegin4");

Can you please help me to solve the problem?

Body:
I suggest to use CMake. See the links below:

These are two examples provided by PointCloudLibrary with CMake: qt_colorize_cloud and qt_visualizer.

Here is the explanation for the configuration in Qt.

The CMakeList.txt is as follows:

cmake_minimum_required(VERSION 2.8.11)

project(pcl_visualizer)

# init_qt: Let's do the CMake job for us
set(CMAKE_AUTOMOC ON) # For meta object compiler
set(CMAKE_AUTORCC ON) # Resource files
set(CMAKE_AUTOUIC ON) # UI files

# Find includes in corresponding build directories
set(CMAKE_INCLUDE_CURRENT_DIR ON)

# Find the QtWidgets library
find_package(Qt5 REQUIRED Widgets)

find_package(VTK REQUIRED)
find_package(PCL 1.7.1 REQUIRED)

# Fix a compilation bug under ubuntu 16.04 (Xenial)
list(REMOVE_ITEM PCL_LIBRARIES "vtkproj4")

include_directories(${PCL_INCLUDE_DIRS})
add_definitions(${PCL_DEFINITIONS})

set(project_SOURCES main.cpp pclviewer.cpp)

add_executable(${PROJECT_NAME} ${project_SOURCES})

target_link_libraries(${PROJECT_NAME} ${PCL_LIBRARIES} Qt5::Widgets)

Hope it will help you.


问:
Need help creating a formula for dynamic average of last 4 weeks expenses
I am looking to create a spreadsheet that my staff fill out, it then gives me a master sheet with all the data, then I import dynamically to my financial spreadsheet telling me the average cost of my client over the last 30 days.

I am looking to create an AVERAGE formula of the last 30 days when Date = Today (Monday) (I want the weekday Monday as that's when staff hand in invoices)

Hope this makes sense, it's really tough!

Here's a video of me explaining my desired outcome

https://www.loom.com/share/3a9cb75052b246d1af2ba2f9ce9180a7

I've followed several guides & can't figure it out.

```<code>=ArrayFormula(iferror(query(average(if(today() - weekday(today(),3)-30)))))
</code>```

I expected $90 average and I just get blank

答:
```<code>=INDEX(QUERY({INDIRECT("A2:D"&ROW()-1)},
 "select avg(Col2),avg(Col3),avg(Col4)
  where Col1 <= date '"&TEXT(TODAY(),    "yyyy-MM-dd")&"'
    and Col1 >= date '"&TEXT(TODAY()-30, "yyyy-MM-dd")&"'"), 2, )
</code>```

Body:
I am looking to create a spreadsheet that my staff fill out, it then gives me a master sheet with all the data, then I import dynamically to my financial spreadsheet telling me the average cost of my client over the last 30 days.

I am looking to create an AVERAGE formula of the last 30 days when Date = Today (Monday) (I want the weekday Monday as that's when staff hand in invoices)

Hope this makes sense, it's really tough!

Here's a video of me explaining my desired outcome

https://www.loom.com/share/3a9cb75052b246d1af2ba2f9ce9180a7

I've followed several guides & can't figure it out.

=ArrayFormula(iferror(query(average(if(today() - weekday(today(),3)-30)))))

I expected $90 average and I just get blank


问:
Why Jenkins says in SSH host key matches key seen previously for this host. Connection will be allowed. ERROR: Server rejected the 1 private key(s)
I'm trying to connect to Windows agent use SSh(Launch agent agents via SSH)
Jenkins master(in  Linux)
log:
[SSH] Opening SSH connection to 192.168.0.122:22.
[SSH] SSH host key matches key seen previously for this host. Connection will be allowed.
ERROR: Server rejected the 1 private key(s) for my_bot (**********)
 [SSH] Authentication failed.
Authentication failed.
Launch failed - cleaning up connection
[SSH] Connection closed.
I tried to add key to  authorized_keys.. but it did not help</p>

答:
When ssh says "SSH host key" it means the keys in known_hosts.
Check .ssh/known_hosts to see that key.
Although "Connection will be allowed" implies this is not a problem for you.
So ignore that part of the error message.

Your real problem is "ERROR: Server rejected the 1 private key"...

Is they key exchanged ok?
Private key needs to be in jenkins. Also check file permissions.
Public key needs to be on server side. Probably .ssh/authorized_keys. Also check file permissions. Ssh will not allow keys to be used if permissions on .ssh or files contained inside are too open.

More information is needed to help solve the question:

In your question please show the ssh command you use - the full command - do you specify key with -i parameter ?

From jenkins command-line, can you ssh to the host using the same ssh command ?

Do ls -al on jenkins home .ssh dir and on server side .ssh dir to check permissions.

To get more verbose/debug information add -v or -vv or -vvv to your ssh command.
Also look at ssh logs on server side if possible.

In your question you could tidy up the log messages.

Same error seen on this question here and I can see they did chown 744 .ssh/authorized_keys in dockerfile which is the wrong way to set permissions for an authorized_keys file.
https://superuser.com/questions/1403715/why-i-am-getting-error-server-rejected-the-1-private-key-error-on-setting-up-s/1443503#1443503


问:
Python: Converting excel file to JSON format
I am creating a ML model that will use a JSON file to understand the pattern and response format. As I have my data in excel format I converted it to JSON in python.

Here is the code:

```<code>import xlrd
from collections import OrderedDict
import simplejson as json
# Open the workbook and select the first worksheet
wb = xlrd.open_workbook('D:\\android\\testdata2.xlsx')
sh = wb.sheet_by_index(0)
# List to hold dictionaries
data_list = []
# Iterate through each row in worksheet and fetch values into dict
for rownum in range(1, sh.nrows):
    data = OrderedDict()
    row_values = sh.row_values(rownum)
    data['pattern'] = row_values[0]
    data['response'] = row_values[1]
    data_list.append(data)
# Serialize the list of dicts to JSON
j = json.dumps(data_list)
# Write to file
with open('data1.json', 'w') as f:
    f.write(j)
</code>```

I am the getting the output as:

```<code>[{
    "pattern": "WALLSTENT NON COUVERTE ",
    "response": "ENDOPROTHESE STENT  VASCULAIRE "
}, {
    "pattern": "PRIMEADVANCED SURSCAN MRI ",
    "response": "NEUROSTIMULATEUR NERF VAGUE GAUCHE "
}, {
    "pattern": "AVASTIN  FLACON DE",
    "response": "BEVACIZUMAB"
}, {
    "pattern": "PERJETA SOLUTION A DILUER POUR PERFUSION",
    "response": "BRENTUXIMAB VEDOTIN"
}]
</code>```

The desired output I am looking for is like this:

```<code>{
    "intents": [{
        "pattern": ["WALLSTENT, NON, COUVERTE "],
        "response": ["ENDOPROTHESE STENT  VASCULAIRE] "
    }, {
        "pattern": ["PRIMEADVANCED ,SURSCAN ,MRI"] ,
        "response": ["NEUROSTIMULATEUR NERF VAGUE GAUCHE "]
    }, {
        "pattern": ["AVASTIN , FLACON ,DE"],
        "response": ["BEVACIZUMAB"]
    }, {
        "pattern": ["PERJETA, SOLUTION, A, DILUER, POUR ,PERFUSION"],
        "response": ["BRENTUXIMAB VEDOTIN"]
    }]
}
</code>```

What modification can I do in my function to get the output I am looking for.

答:
Give a shot to pyexcel_xlsx library in python. I have used this for converting xlsx to json. Sweet and simple one. And fast also as compared to other python libraries.

Sample code:

```<code>from pyexcel_xlsx import get_data;
import time;
import json;

data = get_data("D:\\android\\testdata2.xlsx")
sheetName = "Table A";

data_list = []
# Iterate through each row and append in above list
for i in range(0, len(data[sheetName])):
    data_list.append({
        'pattern' : data[sheetName][i][0],
        'response' : data[sheetName][i][1]
    })
data_list = {'intents': data_list} # Converting to required object
j = json.dumps(data_list)
# Write to file
with open('data1.json', 'w') as f:
    f.write(j)
</code>```

Body:
I am creating a ML model that will use a JSON file to understand the pattern and response format. As I have my data in excel format I converted it to JSON in python.

Here is the code:

import xlrd
from collections import OrderedDict
import simplejson as json
# Open the workbook and select the first worksheet
wb = xlrd.open_workbook('D:\\android\\testdata2.xlsx')
sh = wb.sheet_by_index(0)
# List to hold dictionaries
data_list = []
# Iterate through each row in worksheet and fetch values into dict
for rownum in range(1, sh.nrows):
    data = OrderedDict()
    row_values = sh.row_values(rownum)
    data['pattern'] = row_values[0]
    data['response'] = row_values[1]
    data_list.append(data)
# Serialize the list of dicts to JSON
j = json.dumps(data_list)
# Write to file
with open('data1.json', 'w') as f:
    f.write(j)

I am the getting the output as:

[{
    "pattern": "WALLSTENT NON COUVERTE ",
    "response": "ENDOPROTHESE STENT  VASCULAIRE "
}, {
    "pattern": "PRIMEADVANCED SURSCAN MRI ",
    "response": "NEUROSTIMULATEUR NERF VAGUE GAUCHE "
}, {
    "pattern": "AVASTIN  FLACON DE",
    "response": "BEVACIZUMAB"
}, {
    "pattern": "PERJETA SOLUTION A DILUER POUR PERFUSION",
    "response": "BRENTUXIMAB VEDOTIN"
}]

The desired output I am looking for is like this:

{
    "intents": [{
        "pattern": ["WALLSTENT, NON, COUVERTE "],
        "response": ["ENDOPROTHESE STENT  VASCULAIRE] "
    }, {
        "pattern": ["PRIMEADVANCED ,SURSCAN ,MRI"] ,
        "response": ["NEUROSTIMULATEUR NERF VAGUE GAUCHE "]
    }, {
        "pattern": ["AVASTIN , FLACON ,DE"],
        "response": ["BEVACIZUMAB"]
    }, {
        "pattern": ["PERJETA, SOLUTION, A, DILUER, POUR ,PERFUSION"],
        "response": ["BRENTUXIMAB VEDOTIN"]
    }]
}

What modification can I do in my function to get the output I am looking for.

Body:
Give a shot to pyexcel_xlsx library in python. I have used this for converting xlsx to json. Sweet and simple one. And fast also as compared to other python libraries.

Sample code:

from pyexcel_xlsx import get_data;
import time;
import json;

data = get_data("D:\\android\\testdata2.xlsx")
sheetName = "Table A";

data_list = []
# Iterate through each row and append in above list
for i in range(0, len(data[sheetName])):
    data_list.append({
        'pattern' : data[sheetName][i][0],
        'response' : data[sheetName][i][1]
    })
data_list = {'intents': data_list} # Converting to required object
j = json.dumps(data_list)
# Write to file
with open('data1.json', 'w') as f:
    f.write(j)


问:
Specific cast not valid
I use Linq-to-SQL to insert data in vb.net. When I insert data into SQL Server through a DataGridView it gives error of which column data type is "integer" but when I insert data through textbox it not give any error

So I face problem of datatype "integer" to error of specific cast not valid

答:
Try using CType

```<code>someObject.IntegerProperty = CType(myTextBox.Value, Int32)
</code>```

CType Function

Returns the result of explicitly converting an expression to a specified data type, object, structure, class, or interface.

Title: Specific cast not valid

Body:
Try using CType

someObject.IntegerProperty = CType(myTextBox.Value, Int32)

CType Function

Returns the result of explicitly converting an expression to a specified data type, object, structure, class, or interface.


问:
How to format x-axis for multiple plots in matplotlib
I'm currently generating three different figures and I'm having trouble trying to set the format for the x-axis for all three plots. This is what I have currently.

    fig, ax = plt.subplots()

    plt.figure(1)
    formatter = DateFormatter('%m/%d/%y')
    ax.xaxis.set_major_formatter(formatter)
    ax.xaxis.set_tick_params(rotation=30)
    plt.plot_date(dates1, y1)
    plt.show()

    plt.figure(2)
    formatter = DateFormatter('%m/%d/%y')
    ax.xaxis.set_major_formatter(formatter)
    ax.xaxis.set_tick_params(rotation=30)
    plt.plot_date(dates2, y2)
    plt.show()

    plt.figure(3)
    formatter = DateFormatter('%m/%d/%y')
    ax.xaxis.set_major_formatter(formatter)
    ax.xaxis.set_tick_params(rotation=30)
    plt.plot_date(dates3, y3)
    plt.show()
```

The first figure is formatted as desired but the second and third figure can't seem to detect the x-axis formatting specified. What is the correct way of doing this and is there a way to set the formatting for all three graphs at once?

答:
You can use plt.close() to discard plot instances. Or assign each to it's own variable.</p>

```<code>    plt.figure(1)
    formatter = DateFormatter('%m/%d/%y')
    ax.xaxis.set_major_formatter(formatter)
    ax.xaxis.set_tick_params(rotation=30)
    plt.plot_date(dates1, y1)
    plt.show()
    plt.close()

    plt.figure(2)
    formatter = DateFormatter('%m/%d/%y')
    ax.xaxis.set_major_formatter(formatter)
    ax.xaxis.set_tick_params(rotation=30)
    plt.plot_date(dates2, y2)
    plt.show()
    plt.close()

    plt.figure(3)
    formatter = DateFormatter('%m/%d/%y')
    ax.xaxis.set_major_formatter(formatter)
    ax.xaxis.set_tick_params(rotation=30)
    plt.plot_date(dates3, y3)
    plt.show()
    plt.close()
</code>```

Body:
I'm currently generating three different figures and I'm having trouble trying to set the format for the x-axis for all three plots. This is what I have currently.

    fig, ax = plt.subplots()

    plt.figure(1)
    formatter = DateFormatter('%m/%d/%y')
    ax.xaxis.set_major_formatter(formatter)
    ax.xaxis.set_tick_params(rotation=30)
    plt.plot_date(dates1, y1)
    plt.show()

    plt.figure(2)
    formatter = DateFormatter('%m/%d/%y')
    ax.xaxis.set_major_formatter(formatter)
    ax.xaxis.set_tick_params(rotation=30)
    plt.plot_date(dates2, y2)
    plt.show()

    plt.figure(3)
    formatter = DateFormatter('%m/%d/%y')
    ax.xaxis.set_major_formatter(formatter)
    ax.xaxis.set_tick_params(rotation=30)
    plt.plot_date(dates3, y3)
    plt.show()

The first figure is formatted as desired but the second and third figure can't seem to detect the x-axis formatting specified. What is the correct way of doing this and is there a way to set the formatting for all three graphs at once?

Body:
You can use plt.close() to discard plot instances. Or assign each to it's own variable.

    plt.figure(1)
    formatter = DateFormatter('%m/%d/%y')
    ax.xaxis.set_major_formatter(formatter)
    ax.xaxis.set_tick_params(rotation=30)
    plt.plot_date(dates1, y1)
    plt.show()
    plt.close()

    plt.figure(2)
    formatter = DateFormatter('%m/%d/%y')
    ax.xaxis.set_major_formatter(formatter)
    ax.xaxis.set_tick_params(rotation=30)
    plt.plot_date(dates2, y2)
    plt.show()
    plt.close()

    plt.figure(3)
    formatter = DateFormatter('%m/%d/%y')
    ax.xaxis.set_major_formatter(formatter)
    ax.xaxis.set_tick_params(rotation=30)
    plt.plot_date(dates3, y3)
    plt.show()
    plt.close()


问:
Can't run "npm install expo-cli --global"
I am a newbie in all this stuff. Hope for your understanding.

Let me clarify the issue:
I am trying to start react native app through expo cli. So tried to start npm install expo-cli --global to install npm globally. I got these errors:

Screen_1

Screen_2

It also says that I lack permissions to access it. How can I allow permissions?
Even when I try to start it locally I got the same issue. Your help is appreciated.

答:
although this solution is not the best and the safest solution exists, this worked for me and that make sense because all the problem we had with the errors is the permission problems. so you can use this command and ignore those permission problems :</p>
```<code>sudo npm install expo-cli -g --unsafe-perm
</code>```

Body:
although this solution is not the best and the safest solution exists, this worked for me and that make sense because all the problem we had with the errors is the permission problems. so you can use this command and ignore those permission problems :

sudo npm install expo-cli -g --unsafe-perm


问:
Necessity of const specifier in cast
Suppose I have some code like this:

```<code>void foo (void *ptr) {
    const struct some *azaza = (const struct some *)ptr;
    azaza->some_field = 123; // inadvertently assignment => error
    // ...
</code>```

Is the const specifier really needed in cast?

EDIT: foo is callback function with a particular prototype that I can't change (it's not in my code).

答:
if the value pointed by ptr was declared as const, then what you are trying to do is undefined behaviour. you should not change const values. you can remove const with cast and modify value only if it was not declared with const initially.

```<code>int modify(void *ptr) {
    some_t *value = ptr;
    value->member = 0; // here where UB could happen
}

int main(void)
{
   some_t obj0 = {0};
   const some_t obj1 = {0};
   modify(&obj0); // OK
   modify(&obj1); // leads to undefined behaviour
   return 0;
}
</code>```

otherwise, if it's not declared with const, why just not to:
struct some *azaza = ptr;

Title: Necessity of const specifier in cast

Body:
Suppose I have some code like this:

void foo (void *ptr) {
    const struct some *azaza = (const struct some *)ptr;
    azaza->some_field = 123; // inadvertently assignment => error
    // ...

Is the const specifier really needed in cast?

EDIT: foo is callback function with a particular prototype that I can't change (it's not in my code).

Body:
if the value pointed by ptr was declared as const, then what you are trying to do is undefined behaviour. you should not change const values. you can remove const with cast and modify value only if it was not declared with const initially.

int modify(void *ptr) {
    some_t *value = ptr;
    value->member = 0; // here where UB could happen
}

int main(void)
{
   some_t obj0 = {0};
   const some_t obj1 = {0};
   modify(&obj0); // OK
   modify(&obj1); // leads to undefined behaviour
   return 0;
}

otherwise, if it's not declared with const, why just not to:
struct some *azaza = ptr;


问:
Creating a DataFrame from a list of float values
I have a list containing float values and I want to make a DataFrame out of it. But I am getting an error    TypeError: 'float' object is not iterable </p>

```<code>    '''python
       newlist = []
       for i in path.toolpath:
            newlist = [i.x, i.y,i.z, i.e, i.moveSpd]
            labels = ['x_coordinate' , 'y_coordinate', 'z_coordinate', 'e', 'speed']
       df1 = pd.DataFrame.from_records(newlist, columns = labels)
       print(df1)
    '''

A part of newlist is as follows.
    [-40.8629, 2.28, 44.3492, 1698.7625, 300]
    [-40.788, 2.28, 43.352, 1699.0625, 300]
    [-40.7131, 2.28, 42.3548, 1699.3625, 300]
    [-40.6382, 2.28, 41.3576, 1699.6625, 300]
    [-40.5633, 2.28, 40.3604, 1699.9625, 300]
</code>```

答:
your new_list variable is getting overwritten, you need to append the value.
Like this</p>

```<code>newlist = []
for i in path.toolpath:
    temp = [i.x, i.y,i.z, i.e, i.moveSpd]
    new_list.append(temp)
labels = ['x_coordinate' , 'y_coordinate', 'z_coordinate', 'e', 'speed']
df1 = pd.DataFrame(newlist, columns = labels)
print(df1)
</code>```

Body:
I have a list containing float values and I want to make a DataFrame out of it. But I am getting an error    TypeError: 'float' object is not iterable

    '''python
       newlist = []
       for i in path.toolpath:
            newlist = [i.x, i.y,i.z, i.e, i.moveSpd]
            labels = ['x_coordinate' , 'y_coordinate', 'z_coordinate', 'e', 'speed']
       df1 = pd.DataFrame.from_records(newlist, columns = labels)
       print(df1)
    '''

A part of newlist is as follows.
    [-40.8629, 2.28, 44.3492, 1698.7625, 300]
    [-40.788, 2.28, 43.352, 1699.0625, 300]
    [-40.7131, 2.28, 42.3548, 1699.3625, 300]
    [-40.6382, 2.28, 41.3576, 1699.6625, 300]
    [-40.5633, 2.28, 40.3604, 1699.9625, 300]

Body:
your new_list variable is getting overwritten, you need to append the value.
Like this

newlist = []
for i in path.toolpath:
    temp = [i.x, i.y,i.z, i.e, i.moveSpd]
    new_list.append(temp)
labels = ['x_coordinate' , 'y_coordinate', 'z_coordinate', 'e', 'speed']
df1 = pd.DataFrame(newlist, columns = labels)
print(df1)