问:
How to sort a dataframe columns by the median of all its columns
How can I sort this datfarame by the median of its columns?

```<code>A    B    C

1    2    3
4    5    6
7    8    9
10   11   12
</code>```

So, the output would be

```<code>C    B    A
3    2    1
6    5    4
9    8    7
12   11   10

</code>```

I know, with this example, is easy to sort the dataframe by reverting the order of the columns, but, I would like to know how to sort the columns of this dataframe by the median of all of them.

Thanks!

答:
An option with tidyverse

```<code>library(dplyr)
library(tidyr)
df %>%
    summarise(across(everything(), median)) %>%
    pivot_longer(everything()) %>%
    arrange(desc(value)) %>%
    pull(name) %>%
    select(df, .)
</code>```

Or using base R with apply

```<code>df[order(-apply(df, 2, median))]
#   C  B  A
#1  3  2  1
#2  6  5  4
#3  9  8  7
#4 12 11 10
</code>```

Body:
How can I sort this datfarame by the median of its columns?

A    B    C

1    2    3
4    5    6
7    8    9
10   11   12

So, the output would be

C    B    A
3    2    1
6    5    4
9    8    7
12   11   10

I know, with this example, is easy to sort the dataframe by reverting the order of the columns, but, I would like to know how to sort the columns of this dataframe by the median of all of them.

Thanks!

Body:
An option with tidyverse

library(dplyr)
library(tidyr)
df %>%
    summarise(across(everything(), median)) %>%
    pivot_longer(everything()) %>%
    arrange(desc(value)) %>%
    pull(name) %>%
    select(df, .)

Or using base R with apply

df[order(-apply(df, 2, median))]
#   C  B  A
#1  3  2  1
#2  6  5  4
#3  9  8  7
#4 12 11 10


来源: stackexchange

问:
How to Retrieve data from selected ListBox?
In C#.Net ,I'm trying to retrieve data from selected ListBox.

Eg. First I displayed many data in ListBox that retrieved from MSSQL 2008 Database.
    When i select single data from that listbox , i want to show that selected data into textbox...
How can i do that?
I need yours answers because i'm just beginner ,
Please answer me if you know..
Thanks

答:
It really depends on how you stored your data into the list. Is that simple string or some complex object, is either case you can cast the selected item to it's appropriate type.
For example.
If your list box contains only string type items, you will get the selected item by

```<code>string value=(string) this.listBox1.SelectedItem;
</code>```

If your listbox contains other Complex type, you will get the selected item by

```<code>SomeComplexObject value=(SomeComplexObject) this.listBox1.SelectedItem;
</code>```

Or if you have binded listbox to some sort of datatable or dataset.
you can get the value of the selected item using

```<code>string value=listBox1.SelectedValue.ToString();
</code>```

So now,
When listbox selected index changed. you can set textbox value using.
First, subscribe to listbox index changed event

```<code> this.listBox1.SelectedIndexChanged+=new EventHandler(changed);
</code>```

And your handler.

```<code> private void changed(object sender,EventArgs args)
        {
            //set your text box text property here
            //with the code provided earlier
        }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
It really depends on how you stored your data into the list. Is that simple string or some complex object, is either case you can cast the selected item to it's appropriate type.
For example.
If your list box contains only string type items, you will get the selected item by

string value=(string) this.listBox1.SelectedItem;

If your listbox contains other Complex type, you will get the selected item by

SomeComplexObject value=(SomeComplexObject) this.listBox1.SelectedItem;

Or if you have binded listbox to some sort of datatable or dataset.
you can get the value of the selected item using

string value=listBox1.SelectedValue.ToString();

So now,
When listbox selected index changed. you can set textbox value using.
First, subscribe to listbox index changed event

 this.listBox1.SelectedIndexChanged+=new EventHandler(changed);

And your handler.

 private void changed(object sender,EventArgs args)
        {
            //set your text box text property here
            //with the code provided earlier
        }


问:
How do I retrieve information online using python?
So this is basically the problem: I have this application that receives information and saves it using a json file, but I want to save it in a way that, if someone elses have the same app in their computer, they will receive the things I update in my own.

I think I can use Http and make some import to python, but I know nothing about http, so if theres a solution in python for this it would be better. If there's nothing in python, what do you think is the more simple way of doing it ?

Anyway, thanks ahead for those responding.

edit: That's the code, now the only problem is to upload it online.

```<code>import json
import requests
import atexit

r = requests.get('https://github.com/Gevez/gameficacao/blob/master/data-teste.json')

with open('data-teste.json','wb') as f:
    f.write(r.content)

def exit_handler():
    url = 'https://github.com/Gevez/gameficacao/blob/master/'
    contents = open('data-teste.json', 'rb').read()
    r = requests.post(url, data=contents, headers=headers)

atexit.register(exit_handler)
</code>```

答: Check out requests. Making http requests with this library is pretty easy, if that's what you're looking to do.</p>

ContentLicense: CC BY-SA 4.0

Body:
So this is basically the problem: I have this application that receives information and saves it using a json file, but I want to save it in a way that, if someone elses have the same app in their computer, they will receive the things I update in my own.

I think I can use Http and make some import to python, but I know nothing about http, so if theres a solution in python for this it would be better. If there's nothing in python, what do you think is the more simple way of doing it ?

Anyway, thanks ahead for those responding.

edit: That's the code, now the only problem is to upload it online.

import json
import requests
import atexit

r = requests.get('https://github.com/Gevez/gameficacao/blob/master/data-teste.json')

with open('data-teste.json','wb') as f:
    f.write(r.content)

def exit_handler():
    url = 'https://github.com/Gevez/gameficacao/blob/master/'
    contents = open('data-teste.json', 'rb').read()
    r = requests.post(url, data=contents, headers=headers)

atexit.register(exit_handler)


问:
SetInterval messages not changing
I'm making a loading screen for a game I'm creating with html and JS.  I want various messages to display, about every three seconds.  The SetInterval function doesn't seem to be rotating the messages, even though it works with something else (like an alert every three seconds).  here's the code I've written for the changing messages.</p>

```<code><!doctype html>
<html>
<head><title>Loading screen</title></head>
<script>
let messageNum = 1;

setInterval(function(){
  messageNum++
 }, 1000);

if (messageNum >3) {
  messageNum = 1;
}

if (messageNum === 1) {
  document.write('Message number ONE');
}

if (messageNum === 2) {
  document.write('Message number TWO');
}

if (messageNum === 3) {
  document.write('Message number THREE');
}
</script>
</html>
</code>```

答:
With the current code, setInterval would still be working. i.e., messageNum++ will keep on incrementing, however, you're not capturing any feedback or output from there, . That's why when you add an alert you'll see that the messageNum would have increased with each alert. (try console.log(messageNum), it would work too.)

If your aim is to keep incrementing the messageNum with setInterval, and show different message based on the current value of the messageNum, you will have to check the conditions inside the setInterval.

setInterval will have to do the following things together.
1. increment the variable
2. check the variable's current value and show a message.

```<code>let messageNum = 1;

setInterval(() => {
 if (messageNum > 3) {
  messageNum = 1;
 }

 if (messageNum === 1) {
  document.write('Message number ONE');
 } else if (messageNum === 2) {
  document.write('Message number TWO');
 } else {
  document.write('Message number THREE');
 }
}, 1000)
</code>```

NOTE:

Use if-else condition effectively so that, once one condition is satisfied, the other conditions will not be needlessly checked.

In its current form, even if the messageNum === 1 is satisfied, the program will check the remaining 2 if conditions (messageNum === 2, messageNum === 3) unnecessarily.

Title: SetInterval messages not changing

Body:
I'm making a loading screen for a game I'm creating with html and JS.  I want various messages to display, about every three seconds.  The SetInterval function doesn't seem to be rotating the messages, even though it works with something else (like an alert every three seconds).  here's the code I've written for the changing messages.

<!doctype html>

<title>Loading screen</title>

Body:
With the current code, setInterval would still be working. i.e., messageNum++ will keep on incrementing, however, you're not capturing any feedback or output from there, . That's why when you add an alert you'll see that the messageNum would have increased with each alert. (try console.log(messageNum), it would work too.)

If your aim is to keep incrementing the messageNum with setInterval, and show different message based on the current value of the messageNum, you will have to check the conditions inside the setInterval.

setInterval will have to do the following things together.
1. increment the variable
2. check the variable's current value and show a message.

let messageNum = 1;

setInterval(() => {
 if (messageNum > 3) {
  messageNum = 1;
 }

 if (messageNum === 1) {
  document.write('Message number ONE');
 } else if (messageNum === 2) {
  document.write('Message number TWO');
 } else {
  document.write('Message number THREE');
 }
}, 1000)

NOTE:

Use if-else condition effectively so that, once one condition is satisfied, the other conditions will not be needlessly checked.

In its current form, even if the messageNum === 1 is satisfied, the program will check the remaining 2 if conditions (messageNum === 2, messageNum === 3) unnecessarily.


问:
Is it possible to fire a .then() block without a return value from a promise?
Curious issue I'm having dealing with some callback functions. I need to make a series of API calls that all return promises  then  I'm trying to take that data and map it to an array that exists on the global scope followed by a function to export the new data as a pdf - my issue is that the then() block is firing before the other function finishes and far before the first API call finshes.  `

```<code> let fireWatson = async () => {
        let watsonClassifed = []
        let watsonCallIndex = 0;
        let returnedArr = []
        for (let i = 0; i < watsonData.length; i++) {
            let params = {
                classifierId: '***********',
                collection: watsonData[i]
            }
            naturalLanguageClassifier.classifyCollection(params,
                 function (err, response) {
                    if (err)
                        console.log('error:', err);
                    else
                        console.log("data returned")
                        console.log(response.result.collection)
                    watsonClassifed.push(response.result.collection);
                    console.log(watsonClassifed)
                })

    }
}

fireWatson(watsonData).then(res =>
        console.log("firing stupid callbback after data")
    )
</code>```

I realize this function isnt actually returning anything but is it possible to still make use of a promise without a return value or is this the main issue im hitting?  Ideally - i want the then function to wait until the data is back - mapped to the global array and then outputted but this of course depends on proper synchronicity.

output:

```<code>[Done] exited with code=0 in 1.526 seconds

[Running] node "index.js"
firing stupid callbback
data returned
all my sweet sweet data
</code>```

答:
All functions in JavaScript have returns, it's just that they are implicit if you don't say return explicitly

It's always a bit tricky to mix promises with callbacks. Here is a way you can fireWatson without using any utilities.

let fireWatson = async watsonData => Promise.all(watsonData.map(collection => new Promise((resolve, reject) => {
  let params = {
    classifierId: '***********',
    collection: collection,
  }
  return naturalLanguageClassifier.classifyCollection(params, function(err, response) => {
    if (err) {
      reject(err)
    } else {
      resolve(response)
    }
  })
})))
```

<p>Of course, you can simplify this tremendously using a utility I created</p>

<pre class="lang-js prettyprint-override"><code>const { map } = require('rubico')

let fireWatson = map(collection => new Promise((resolve, reject) => {
  let params = {
    classifierId: '***********',
    collection: watsonData[i]
  }
  return naturalLanguageClassifier.classifyCollection(params, function(err, response) => {
    if (err) {
      reject(err)
    } else {
      resolve(response)
    }
  })
}))
</code>```

Body:
Curious issue I'm having dealing with some callback functions. I need to make a series of API calls that all return promises  then  I'm trying to take that data and map it to an array that exists on the global scope followed by a function to export the new data as a pdf - my issue is that the then() block is firing before the other function finishes and far before the first API call finshes.  `

 let fireWatson = async () => {
        let watsonClassifed = []
        let watsonCallIndex = 0;
        let returnedArr = []
        for (let i = 0; i < watsonData.length; i++) {
            let params = {
                classifierId: '***********',
                collection: watsonData[i]
            }
            naturalLanguageClassifier.classifyCollection(params,
                 function (err, response) {
                    if (err)
                        console.log('error:', err);
                    else
                        console.log("data returned")
                        console.log(response.result.collection)
                    watsonClassifed.push(response.result.collection);
                    console.log(watsonClassifed)
                })

    }
}

fireWatson(watsonData).then(res =>
        console.log("firing stupid callbback after data")
    )

I realize this function isnt actually returning anything but is it possible to still make use of a promise without a return value or is this the main issue im hitting?  Ideally - i want the then function to wait until the data is back - mapped to the global array and then outputted but this of course depends on proper synchronicity.

output:

[Done] exited with code=0 in 1.526 seconds

[Running] node "index.js"
firing stupid callbback
data returned
all my sweet sweet data

Body:
All functions in JavaScript have returns, it's just that they are implicit if you don't say return explicitly

It's always a bit tricky to mix promises with callbacks. Here is a way you can fireWatson without using any utilities.

let fireWatson = async watsonData => Promise.all(watsonData.map(collection => new Promise((resolve, reject) => {
  let params = {
    classifierId: '***********',
    collection: collection,
  }
  return naturalLanguageClassifier.classifyCollection(params, function(err, response) => {
    if (err) {
      reject(err)
    } else {
      resolve(response)
    }
  })
})))

Of course, you can simplify this tremendously using a utility I created

const { map } = require('rubico')

let fireWatson = map(collection => new Promise((resolve, reject) => {
  let params = {
    classifierId: '***********',
    collection: watsonData[i]
  }
  return naturalLanguageClassifier.classifyCollection(params, function(err, response) => {
    if (err) {
      reject(err)
    } else {
      resolve(response)
    }
  })
}))


问:
Java: Generating a random double between the range of a negative double and a positive double
I am not very familiar with how to alter the range of both Math.random or a new Random() to generate a double like this. I need to be able to generate a double between -10 and 25 cents (my program is dealing with money; hence why I said cents). And a separate instance is generating a random double between 90 and -75 cents. I saw this when I was searching for my answer:

double result = Math.random() * (upper - lower) + lower;

But when I implemented the idea into my code, the range didn't seem to work when using a range between a positive and a negative number...
I tested it with the upper limit of 0.25 and lower of -0.10, but noticed it printed 0.3567587946356543 at one instance of the test I did. So by this I concluded that I obviously didn't adjust the range correctly..

Please help :(

This is my first time using stackoverflow so please go easy on me, I will elaborate if anything I said didn't make sense..

This is my existing method using this code:

```<code>public double variation(double price){
    //formula: (Math.random() * range) + min; where range = max - min
    //80% of the time returns amount between -10 & 25 cents
    if(Math.random() > 0.19){
        return (Math.random() * 0.35) - 0.10;
    }
    //20% of the time returns amount between -75 & 90 cents
    return (Math.random() * 1.65) - 0.75;
}
</code>```

I know the method takes in a double price that it doesn't use; it's part of the teacher's requirements to take in a double price but to disregard its value. So ignore that please.

Body:
I am not very familiar with how to alter the range of both Math.random or a new Random() to generate a double like this. I need to be able to generate a double between -10 and 25 cents (my program is dealing with money; hence why I said cents). And a separate instance is generating a random double between 90 and -75 cents. I saw this when I was searching for my answer:

double result = Math.random() * (upper - lower) + lower;

But when I implemented the idea into my code, the range didn't seem to work when using a range between a positive and a negative number...
I tested it with the upper limit of 0.25 and lower of -0.10, but noticed it printed 0.3567587946356543 at one instance of the test I did. So by this I concluded that I obviously didn't adjust the range correctly..

Please help :(

This is my first time using stackoverflow so please go easy on me, I will elaborate if anything I said didn't make sense..

This is my existing method using this code:

public double variation(double price){
    //formula: (Math.random() * range) + min; where range = max - min
    //80% of the time returns amount between -10 & 25 cents
    if(Math.random() > 0.19){
        return (Math.random() * 0.35) - 0.10;
    }
    //20% of the time returns amount between -75 & 90 cents
    return (Math.random() * 1.65) - 0.75;
}

I know the method takes in a double price that it doesn't use; it's part of the teacher's requirements to take in a double price but to disregard its value. So ignore that please.

Body:
I took 400.0 and - 400.0 for example.

double min = 400.0;
  double max = 2 * min;
  System.out.println(Math.random() * max - min);

And the output is

138.0921773815627
212.7567891431654
9.063135840057157
-256.8594518458244
-99.84573995806142
116.53331370219462
33.29613621235126


问:
Latest Value from the KStream for a given key
I have KTable like below

```<code>KTable<productId1,productValue1>
KTable<productId2,productValue2>
KTable<productId3,productValue2>
</code>```

Then i have KStream<custId,productId>, the productId is of any of productId1, productId2, productId3. I want to have the corresponding productValue.

The response would be like KStream<custId, productValueN>

If the KStream receives productId as productId2, then the response would be KStream<custId, productValue2>

How this could be possible?
Thanks

答:
You can accomplish this using a GlobalKTable for products, and then joining the customers KStream with it as follows:

```<code>Serde<String> stringSerde = new Serdes.StringSerde();

StreamsBuilder streamsBuilder = new StreamsBuilder();

GlobalKTable<String, String> productsTable =
        streamsBuilder.globalTable(PRODUCTS_TOPIC, Consumed.with(stringSerde, stringSerde),
                Materialized.<String, String, KeyValueStore<Bytes, byte[]>>as("products")
                        .withKeySerde(stringSerde)
                        .withValueSerde(stringSerde));

streamsBuilder.stream(CUSTOMERS_TOPIC, Consumed.with(stringSerde, stringSerde))
        .join(productsTable,
                (customerId, productId) -> productId,
                (productName1, productName2) -> productName2,
                Named.as("customersProducts"))
        .print(Printed.toSysOut());
</code>```

Body:
I have KTable like below

KTable<productId1,productValue1>
KTable<productId2,productValue2>
KTable<productId3,productValue2>

Then i have KStream<custId,productId>, the productId is of any of productId1, productId2, productId3. I want to have the corresponding productValue.

The response would be like KStream<custId, productValueN>

If the KStream receives productId as productId2, then the response would be KStream<custId, productValue2>

How this could be possible?
Thanks

Body:
You can accomplish this using a GlobalKTable for products, and then joining the customers KStream with it as follows:

Serde<String> stringSerde = new Serdes.StringSerde();

StreamsBuilder streamsBuilder = new StreamsBuilder();

GlobalKTable<String, String> productsTable =
        streamsBuilder.globalTable(PRODUCTS_TOPIC, Consumed.with(stringSerde, stringSerde),
                Materialized.<String, String, KeyValueStore<Bytes, byte[]>>as("products")
                        .withKeySerde(stringSerde)
                        .withValueSerde(stringSerde));

streamsBuilder.stream(CUSTOMERS_TOPIC, Consumed.with(stringSerde, stringSerde))
        .join(productsTable,
                (customerId, productId) -> productId,
                (productName1, productName2) -> productName2,
                Named.as("customersProducts"))
        .print(Printed.toSysOut());


问:
setting div as a background

I have a div like which has an background, i like to set this div as an transparent background to certain dialog, like a jquery dialog. But the issue here is when the user scrolls the transparent div is also moving. i want this transparent div to be fixed even the scroll bar   moves. How can i achieve this? Thanks.

Sample Code:

doc is an instance of html document. [doc  instanceof HTMLDocument]

```<code><div id=hiox1002  align=center style='display: none; z-index:3;opacity:0.4;\
            filter:alpha(opacity=40);background-image:url(http://funflys.com/images/bg.png);background-repeat:repeat;\
            width: "+doc.defaultView.innerWidth+"px; height: "+doc.defaultView.innerHeight+"px;/></div>
</code>```

I am trying this for an firefox add on

答: add position:fixed in your css..and have a look on this tutorial

Title: setting div as a background

Body:
I have a div like which has an background, i like to set this div as an transparent background to certain dialog, like a jquery dialog. But the issue here is when the user scrolls the transparent div is also moving. i want this transparent div to be fixed even the scroll bar   moves. How can i achieve this? Thanks.

Sample Code:

doc is an instance of html document. [doc  instanceof HTMLDocument]

I am trying this for an firefox add on


问:
splitted normalized dataset logistic regression
I was given a dataset that was already splitted into two files, a test data file and a train data file. The data in the both files is normalized.
I was asked to do binomial logistic regression and evaluate the model using some metrics and create a training summary using Spark. I am using python in combination with Spark.

The goal is to develop a Spark application that will first build a classification model using the train dataset and then test it using the test dataset.
Finally, I will execute the Spark application and study the model performance while varying the maximum iterations allowed during training.
I must execute the application with five values of my choice for the number of maximum iterations. For each execution, I need to record at least three
model performance metrics such as area under the ROC curve, accuracy, precision, recall, etc

```<code>Train: https://pastebin.com/KWsp6jAp
Test: https://pastebin.com/KVYEWZeA
</code>```

I already finished coding but I am confused because the dataset is already splitted.

My questions are:

Do I:

need to check both files, train and test for missing values or 0 and
replace them with NaN (because they are already normalized)?

imputer for both files?

put in two different single vectors (one for each file) all the features?

StandardScaler to scalerize feature column for both vectors?

check whether there is an imbalance in the train data and handle it?

how to find out which five number of iterations should I run?

I followed this guide here: https://github.com/dhirajprai/SparkML/blob/master/SparkML/logisticregression.ipynb
(the dataset used here seems to have different values/not normalized)

答:
This is more a common sense question.

Look at this example http://www.semspirit.com/artificial-intelligence/machine-learning/preparing-the-data/preparing-the-data-in-python/splitting-the-dataset-into-training-and-test-sets/. I just googled and found this although I know from machine learning courses the same I will state. Also, your own reference alludes to the same.

You see from these 2 sources the general approach:

They do all the manipulations you reference.

Then they split.

Why your data is delivered as train & test up front is not clear to me as it not that usual.

All the aspects you mention have already been done more than likely - as you state data is normalized.

Normalization is a scaling technique in which values are shifted and re-scaled so that they end up ranging between 0 and 1. It is also known as Min-Max scaling. So you need not do anything about 0(something) values. Some debate on this aspect BTW in some cases.

Step 3 and 6 only required therefore.

Body:
I was given a dataset that was already splitted into two files, a test data file and a train data file. The data in the both files is normalized.
I was asked to do binomial logistic regression and evaluate the model using some metrics and create a training summary using Spark. I am using python in combination with Spark.

The goal is to develop a Spark application that will first build a classification model using the train dataset and then test it using the test dataset.
Finally, I will execute the Spark application and study the model performance while varying the maximum iterations allowed during training.
I must execute the application with five values of my choice for the number of maximum iterations. For each execution, I need to record at least three
model performance metrics such as area under the ROC curve, accuracy, precision, recall, etc

Train: https://pastebin.com/KWsp6jAp
Test: https://pastebin.com/KVYEWZeA

I already finished coding but I am confused because the dataset is already splitted.

My questions are:

Do I:

need to check both files, train and test for missing values or 0 and
replace them with NaN (because they are already normalized)?

imputer for both files?

put in two different single vectors (one for each file) all the features?

StandardScaler to scalerize feature column for both vectors?

check whether there is an imbalance in the train data and handle it?

how to find out which five number of iterations should I run?

I followed this guide here: https://github.com/dhirajprai/SparkML/blob/master/SparkML/logisticregression.ipynb
(the dataset used here seems to have different values/not normalized)


问:
Redirect of domain to Amazon EC2 without Route53
I have a website hosted in Amazon EC2.I have set my A record to point to my Elastic IP. I have also set my www to point to A record.

The problem is that both homepages exist now (the one with the domain I have in godaddy and the one with the amazon url)

I would like the ec2-.....compute.com to redirect to the homepage of my domain.

Could you help me on how to do it? Should I use somehow httpd.conf?

答: I know this question is bit old. Just wanted to know if anybody has found a solution to this question. I registered a domain in GoDaddy and have setup a VPC in Amazon EC2. Tried several means like pointing A record to Elastic IP address and updating CNAME record. But could not make  my domain accessible.</p>


问:
MeteorJS not displaying anything on running application in localhost:3000
I am new to MeteorJS, and I am using Linux. As a basic newbie, I decided to stick to the tutorials on their official website. I went to follow the to-do list tutorial and selected the blaze option. At around step 6 or 7 the tutorial mentioned that you should start to see your application come together in your localhost:3000 when running it. After starting meteor and waiting for it to build the application I opened up localhost:3000. it looked like this:
AppImage. I thought there was an issue with my meteor installation so I ran

```<code>meteor npm install
</code>```

to check if my installation was up to date and the output was:

```<code>up to date in 12.362s
</code>```

I couldn't figure out what was wrong since the terminal wasn't sending any requests either so I opened the console in my browser and was greeted by the following errors:

Uncaught Error: Cannot find module './main.html'
      at makeMissingError (modules-runtime.js?hash=23fe92393aa44a7b01bb53a510a9cab5fb43037c:232)
      at Module.resolve (modules-runtime.js?hash=23fe92393aa44a7b01bb53a510a9cab5fb43037c:238)
      at Module.moduleLink [as link] (modules.js?hash=20efd7567f62601be7ae21d11e21baf9bd63c715:307)
      at module (main.js:1)
      at fileEvaluate (modules-runtime.js?hash=23fe92393aa44a7b01bb53a510a9cab5fb43037c:346)
      at Module.require (modules-runtime.js?hash=23fe92393aa44a7b01bb53a510a9cab5fb43037c:248)
      at require (modules-runtime.js?hash=23fe92393aa44a7b01bb53a510a9cab5fb43037c:268)
      at app.js?hash=b426fd76718daefbb34707a544746de2f90dc26c:258

Is there any way to fix this?

Thanks a lot.

edit

Some of you wanted to take a look at the main HTML and js files in the client directory, so I've included them here:

main HTML and JS:

import { Template } from 'meteor/templating';
import { ReactiveVar } from 'meteor/reactive-var';

import './main.html';
import '../imports/ui/body.js';

Template.hello.onCreated(function helloOnCreated() {
  // counter starts at 0
  this.counter = new ReactiveVar(0);
});

Template.hello.helpers({
  counter() {
    return Template.instance().counter.get();
  },
});

Template.hello.events({
  'click button'(event, instance) {
    // increment the counter when button is clicked
    instance.counter.set(instance.counter.get() + 1);
  },
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><head>
  <title>simple-todos</title>
</head></code>```

答:
How to read the stack trace:

at module (main.js:1)

In main.js on line 1 you are trying to import your main.html file.

Cannot find module './main.html'

Your main.js file likely has a statement like import './main.html'; on the first line.

This means that you must not have a main.html file adjacent to your JS file and so it cannot include it in the build.

Verify spelling, case, and location of the file (what folder it belongs in). They need to be siblings in the same folder.

Body:
I am new to MeteorJS, and I am using Linux. As a basic newbie, I decided to stick to the tutorials on their official website. I went to follow the to-do list tutorial and selected the blaze option. At around step 6 or 7 the tutorial mentioned that you should start to see your application come together in your localhost:3000 when running it. After starting meteor and waiting for it to build the application I opened up localhost:3000. it looked like this:
AppImage. I thought there was an issue with my meteor installation so I ran

meteor npm install

to check if my installation was up to date and the output was:

up to date in 12.362s

I couldn't figure out what was wrong since the terminal wasn't sending any requests either so I opened the console in my browser and was greeted by the following errors:

Uncaught Error: Cannot find module './main.html'
      at makeMissingError (modules-runtime.js?hash=23fe92393aa44a7b01bb53a510a9cab5fb43037c:232)
      at Module.resolve (modules-runtime.js?hash=23fe92393aa44a7b01bb53a510a9cab5fb43037c:238)
      at Module.moduleLink [as link] (modules.js?hash=20efd7567f62601be7ae21d11e21baf9bd63c715:307)
      at module (main.js:1)
      at fileEvaluate (modules-runtime.js?hash=23fe92393aa44a7b01bb53a510a9cab5fb43037c:346)
      at Module.require (modules-runtime.js?hash=23fe92393aa44a7b01bb53a510a9cab5fb43037c:248)
      at require (modules-runtime.js?hash=23fe92393aa44a7b01bb53a510a9cab5fb43037c:268)
      at app.js?hash=b426fd76718daefbb34707a544746de2f90dc26c:258

Is there any way to fix this?

Thanks a lot.

edit

Some of you wanted to take a look at the main HTML and js files in the client directory, so I've included them here:

main HTML and JS:

import { Template } from 'meteor/templating';
import { ReactiveVar } from 'meteor/reactive-var';

import './main.html';
import '../imports/ui/body.js';

Template.hello.onCreated(function helloOnCreated() {
  // counter starts at 0
  this.counter = new ReactiveVar(0);
});

Template.hello.helpers({
  counter() {
    return Template.instance().counter.get();
  },
});

Template.hello.events({
  'click button'(event, instance) {
    // increment the counter when button is clicked
    instance.counter.set(instance.counter.get() + 1);
  },
});

  <title>simple-todos</title>


问:
check a int/string contains specific digits in it using regex
I have a string/integer X: 912035374356789

i want to check if X contains : 1, 2, 3, 4, 5, 6, 7, 8, 9, 0

occurrence order is not matter

How do check it using regular expression.
if there is any algorithm please mention, because i want to do it in minimum time complexity

```<code>Example
ex1: 61243456092 //false 7 & 8 not present
ex2: 864123456789 //false 0 is not present
ex3: 987601234567 //true all present
</code>```

答:
You can use the following regex blocks that ensure 1 is there at least once.

```<code>(?=.*1)
</code>```

Now, in your case, you can combine all of them (positive look ahead)

```<code>(?=.*0)(?=.*1)(?=.*2)(?=.*3)(?=.*4)(?=.*5)(?=.*6)(?=.*7)(?=.*8)(?=.*9)
</code>```

Demo: demo

Body:
I have a string/integer X: 912035374356789

i want to check if X contains : 1, 2, 3, 4, 5, 6, 7, 8, 9, 0

occurrence order is not matter

How do check it using regular expression.
if there is any algorithm please mention, because i want to do it in minimum time complexity

Example
ex1: 61243456092 //false 7 & 8 not present
ex2: 864123456789 //false 0 is not present
ex3: 987601234567 //true all present

Body:
You can use the following regex blocks that ensure 1 is there at least once.

(?=.*1)

Now, in your case, you can combine all of them (positive look ahead)

(?=.*0)(?=.*1)(?=.*2)(?=.*3)(?=.*4)(?=.*5)(?=.*6)(?=.*7)(?=.*8)(?=.*9)

Demo: demo


问:
JavaScript returns undefined instead of value in recursive function
I have a simple function to get value from nested arrays:

```<code>function getVal(arr){
  var el = arr[0];
  console.log(el);
  console.log(Array.isArray(el));
  if(Array.isArray(el)){
    getVal(el);
  }else{
    return el;
  }
}
</code>```

And I get undefined all the time. Here is the console output:

```<code>getVal([["a"]]);
["a"]
true
"a"
false
undefined
</code>```

As far as I understand, when el === "a" condition if(Array.isArray(el)) is satisfied and I get recursive call with getVal("a"), which gives undefined result. What's happening there? And why "a" is not returned?

答:
replace </p>

```<code>getVal(el);
</code>```

<p>with </p>

```<code>return getVal(el);
</code>```

Body:
I have a simple function to get value from nested arrays:

function getVal(arr){
  var el = arr[0];
  console.log(el);
  console.log(Array.isArray(el));
  if(Array.isArray(el)){
    getVal(el);
  }else{
    return el;
  }
}

And I get undefined all the time. Here is the console output:

getVal([["a"]]);
["a"]
true
"a"
false
undefined

As far as I understand, when el === "a" condition if(Array.isArray(el)) is satisfied and I get recursive call with getVal("a"), which gives undefined result. What's happening there? And why "a" is not returned?

Body:
replace

getVal(el);

with

return getVal(el);


问:
Formatting a date is giving me a different one from the passed one
I need to get the first and last day of the current month, this works perfectly but when I format the date to looks like this yyyy/mm/dd it changes from the one I passed

For example, if a passed the 1 May 2020 when I format the date returns me the 30 April 2020

var startID = document.getElementById('start');
var datenow = new Date();
var firstday = new Date(datenow.getFullYear(), datenow.getMonth(), 1);
firstday = firstday.toISOString().slice(0, 10);
startID.value = firstday;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="date" name="start" class="form-control" id="start" required autofocus>
<label for="start">Start Date</label></code>```

This is how I get the first day of the current month:

var datenow = new Date();
var firstday = new Date(datenow.getFullYear(),datenow.getMonth(), 1);
```

<p>This is how I format the date to looks like <code>yyyy/mm/dd</code> in this part is where I get another wrong date from the passed one:</p>

<pre class="lang-js prettyprint-override"><code>firstday = firstday.toISOString().slice(0,10);
</code>```

答:
The root cause of the problem is in the use of getMonth() method to obtain the month number.

The getMonth() method returns integers from 0 to 11 (January = 0, ...Dec = 11).

The problem can be fixed by adding 1 to getMonth().

Here is a working example to show current date, first day and last day:

```<code>var now = new Date()
console.log("Today = " + now)

let month = (now.getMonth() + 1)
let year = now.getFullYear()

firstDay = ("1/" + month + "/" + year)
lastDay = ((new Date(year, month, 0)).getDate() + "/" + month + "/" + year)

console.log("First day = " + firstDay)
console.log("Last day = " + lastDay)
</code>```

Output:

```<code>Today = Sat May 30 2020 20:54:56 GMT+0100 (British Summer Time)
First day = 1/5/2020
Last day = 31/5/2020
</code>```

More information:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getMonth

Body:
I need to get the first and last day of the current month, this works perfectly but when I format the date to looks like this yyyy/mm/dd it changes from the one I passed

For example, if a passed the 1 May 2020 when I format the date returns me the 30 April 2020

var startID = document.getElementById('start');
var datenow = new Date();
var firstday = new Date(datenow.getFullYear(), datenow.getMonth(), 1);
firstday = firstday.toISOString().slice(0, 10);
startID.value = firstday;

<input type="date" name="start" class="form-control" id="start" required autofocus>
Start Date

This is how I get the first day of the current month:

var datenow = new Date();
var firstday = new Date(datenow.getFullYear(),datenow.getMonth(), 1);

This is how I format the date to looks like yyyy/mm/dd in this part is where I get another wrong date from the passed one:

firstday = firstday.toISOString().slice(0,10);

Body:
The root cause of the problem is in the use of getMonth() method to obtain the month number.

The getMonth() method returns integers from 0 to 11 (January = 0, ...Dec = 11).

The problem can be fixed by adding 1 to getMonth().

Here is a working example to show current date, first day and last day:

var now = new Date()
console.log("Today = " + now)

let month = (now.getMonth() + 1)
let year = now.getFullYear()

firstDay = ("1/" + month + "/" + year)
lastDay = ((new Date(year, month, 0)).getDate() + "/" + month + "/" + year)

console.log("First day = " + firstDay)
console.log("Last day = " + lastDay)

Output:

Today = Sat May 30 2020 20:54:56 GMT+0100 (British Summer Time)
First day = 1/5/2020
Last day = 31/5/2020

More information:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getMonth


答:
You haven't return the value from the recursive function call when Array.isArray(el) is true. Return it like return getVal(el);

function getVal(arr){
  var el = arr[0];
  if(Array.isArray(el)){
    return getVal(el);
  }else{
    return el;
  }
}

console.log(getVal([["a"]]));```

Title: JavaScript returns undefined instead of value in recursive function


问:
Windows Form being regarded as a "type, which is not valid in the given context"
I'm trying to teach myself the fundamentals of windows form applications using .net framework, and so I decided to pick the empty project template on visual studio 19 so I could practically learn what the auto generated code in a .net core app is all about and rely on nothing.

Anyway I made a form.cs file by adding a new "class" file for the form but in making my main method in the program.cs file the "Application.run" line generates an error as the "MainForm" is apparently "a type, which is not valid in the given context". I understand .net core is different from .net framework but I thought a lot of the windows form code would look the same from what I've seen. Sorry if this sounds stupid but I don't know how to resolve the issue.

答:
Welcome to StackOverflow

You <s>might be</s> are missing the new and the brackets.

Write
Application.Run(new myForm());

instead of
Application.Run(myForm);

What the first line is doing is creating an object of the form myForm and passing it as parameter to the Application.Run(...) function.

2nd Line will give a compile time error (the one that you are getting)

Gyaan

The Run function of Application class requires an object of the form, which is created when you call the new operator on your form class (myForm in above code)

The type name (form class name without new being called) is used when you want to specify another object of that class type. For example:
myForm frm1;

Here, the variable frm1 is created in stack and is specified to be of type myForm.
When you initialize this variable, you will need it to assign to an object. The object is created by calling the new operator on the class:
new myForm()

The above line creates an object of type myForm in the heap.
To use this object, you need a variable that can point to this object (reference in C# and pointer in C/C++). For that, you can combine the two codes in 2 lines or 1 line as shown below

2 Lines Code:

```<code>myForm frm1;`
frm1 = new myForm();
</code>```

1 Line Code

myForm1 frm1 = new myForm();

Now when you write code like

frm1.Title = "My Form Title";

This will change the value of Title property of the object created in heap.

Body:
Welcome to StackOverflow

You <s>might be</s> are missing the new and the brackets.

Write
Application.Run(new myForm());

instead of
Application.Run(myForm);

What the first line is doing is creating an object of the form myForm and passing it as parameter to the Application.Run(...) function.

2nd Line will give a compile time error (the one that you are getting)

Gyaan

The Run function of Application class requires an object of the form, which is created when you call the new operator on your form class (myForm in above code)

The type name (form class name without new being called) is used when you want to specify another object of that class type. For example:
myForm frm1;

Here, the variable frm1 is created in stack and is specified to be of type myForm.
When you initialize this variable, you will need it to assign to an object. The object is created by calling the new operator on the class:
new myForm()

The above line creates an object of type myForm in the heap.
To use this object, you need a variable that can point to this object (reference in C# and pointer in C/C++). For that, you can combine the two codes in 2 lines or 1 line as shown below

2 Lines Code:

myForm frm1;`
frm1 = new myForm();

1 Line Code

myForm1 frm1 = new myForm();

Now when you write code like

frm1.Title = "My Form Title";

This will change the value of Title property of the object created in heap.


答:
If the string contains only digits then you can count the number of unique digits in it

```<code>long count = string.chars().distinct().count();
</code>```

and check if count is 10

Example

```<code>String ex1 = "61243456092";
String ex2 = "864123456789";
String ex3 = "987601234567";

System.out.println(ex1.chars().distinct().count());
System.out.println(ex2.chars().distinct().count());
System.out.println(ex3.chars().distinct().count());
</code>```

yields

8

  9

  10

Title: check a int/string contains specific digits in it using regex

Body:
If the string contains only digits then you can count the number of unique digits in it

long count = string.chars().distinct().count();

and check if count is 10

Example

String ex1 = "61243456092";
String ex2 = "864123456789";
String ex3 = "987601234567";

System.out.println(ex1.chars().distinct().count());
System.out.println(ex2.chars().distinct().count());
System.out.println(ex3.chars().distinct().count());

yields

8

  9

  10


问:
How to take subarray from 2d Boost.MultiArray?
I am working on a program where I need to use 2d Boost.MultiArray. I managed to initialize it and fill it with data. But I don't understand how to take subarray of size i,j if multiarray is of size m,n. Where i<=m and j<=n. Can anyone help me?

Code:

matrix_type matrix(boost::extents[width][height]);
        read_matrix_from_file(file_content, matrix);
for (int rank = 1; rank < workers; rank++) {
            auto subarray_size = (rest > 0) ? lines_per_worker + 1 : lines_per_worker;
            rest--;

            typedef boost::multi_array_types::index_range range;

            size_t finish_line = subarray_size + bias - 1;
            finish_line = (finish_line==bias)? finish_line+1:finish_line;

            matrix_type::array_view<2>::type
                    current_process_batch = matrix[boost::indices[range(bias, subarray_size + bias - 1)][range(0, width)]];
}
```

答:
Documentation https://www.boost.org/doc/libs/1_73_0/libs/multi_array/doc/user.html#sec_generators

Boost.MultiArray provides the facilities for creating a sub-view of an
  already existing array component. It allows you to create a sub-view
  that retains the same number of dimensions as the original array or
  one that has less dimensions than the original as well.

Sub-view
  creation occurs by placing a call to operator[], passing it an
  index_gen type. The index_gen is populated by passing index_range
  objects to its operator[]. The index_range and index_gen types are
  defined in the multi_array_types namespace and as nested members of
  every array type. Similar to boost::extents, the library by default
  constructs the object boost::indices. You can suppress this object by
  defining BOOST_MULTI_ARRAY_NO_GENERATORS before including the library
  header. A simple sub-view creation example follows.

Sample:

Live On Coliru

```<code>#include <boost/multi_array.hpp>
#include <iostream>

template <typename Ma>
auto dump(Ma const& r) -> std::enable_if_t<1 == Ma::dimensionality> {
    for (auto c: r)
        std::cout << " " << c;
    std::cout << "\n";
}

template <typename Ma>
auto dump(Ma const& ma) -> std::enable_if_t<2 == Ma::dimensionality> {
    for (auto const& r: ma)
        dump(r);
}

int main() {using range = boost::multi_array_types::index_range;
    using boost::extents;
    using boost::indices;

    auto mn = extents[7][4];
    boost::multi_array<int, 2> ma(mn);

    // fill with numbers from 10..37
    std::iota(ma.data(), ma.data() + ma.num_elements(), 10);

    dump(ma);

    std::cout << "Slice [3..5][1..3]\n";
    dump(ma[ indices[range(3,5)][range(1,3)] ]);

    std::cout << "Slice [2..4][2..3]\n";
    dump(ma[ indices[range(2,4)][range(2,3)] ]);

    std::cout << "Slice [1,3,5][2..3]\n";
    dump(ma[ indices[range(1,7,2)][range(2,3)] ]);

    std::cout << "Degenerate views (reduced dimensionality):\n";
    std::cout << "Slice [1,3,5][2]\n";
    dump(ma[ indices[range(1,7,2)][2] ]);

    std::cout << "Slice [0][1,3]\n";
    dump(ma[ indices[0][range(1,4,2)] ]);
}
</code>```

Prints

```<code> 10 11 12 13
 14 15 16 17
 18 19 20 21
 22 23 24 25
 26 27 28 29
 30 31 32 33
 34 35 36 37
Slice [3..5][1..3]
 23 24
 27 28
Slice [2..4][2..3]
 20
 24
Slice [1,3,5][2..3]
 16
 24
 32
Degenerate views (reduced dimensionality):
Slice [1,3,5][2]
 16 24 32
Slice [0][1,3]
 11 13
</code>```

UPDATE

Re. Comment:

if you want to avoid the degenerate dimensions, here's how:

Live On Coliru

```<code>std::cout << "Degenerate views (reduced dimensionality):\n";
std::cout << "Slice [1,3,5][2]\n";
dump(ma[ indices[range(1,7,2)][2] ]);

std::cout << "Slice [0][1,3]\n";
dump(ma[ indices[0][range(1,4,2)] ]);

// RE: Comment
std::cout << "NON-Degenerate views (reduced dimensionality):\n";
std::cout << "Slice [1,3,5][2]\n";
dump(ma[ indices[range(1,7,2)][range(2,3)] ]);

std::cout << "Slice [0][1,3]\n";
dump(ma[ indices[range(0,1)][range(1,4,2)] ]);
</code>```

Prints

```<code>Degenerate views (reduced dimensionality):
Slice [1,3,5][2]
 16 24 32
Slice [0][1,3]
 11 13
NON-Degenerate views (reduced dimensionality):
Slice [1,3,5][2]
 16
 24
 32
Slice [0][1,3]
 11 13
</code>```

Basically, don't use literals [i][j] but [range(i,i+1)][range(j,j+1)]

Body:
Documentation https://www.boost.org/doc/libs/1_73_0/libs/multi_array/doc/user.html#sec_generators

Boost.MultiArray provides the facilities for creating a sub-view of an
  already existing array component. It allows you to create a sub-view
  that retains the same number of dimensions as the original array or
  one that has less dimensions than the original as well.

Sub-view
  creation occurs by placing a call to operator[], passing it an
  index_gen type. The index_gen is populated by passing index_range
  objects to its operator[]. The index_range and index_gen types are
  defined in the multi_array_types namespace and as nested members of
  every array type. Similar to boost::extents, the library by default
  constructs the object boost::indices. You can suppress this object by
  defining BOOST_MULTI_ARRAY_NO_GENERATORS before including the library
  header. A simple sub-view creation example follows.

Sample:

Live On Coliru

#include <boost/multi_array.hpp>
#include <iostream>

template <typename Ma>
auto dump(Ma const& r) -> std::enable_if_t<1 == Ma::dimensionality> {
    for (auto c: r)
        std::cout << " " << c;
    std::cout << "\n";
}

template <typename Ma>
auto dump(Ma const& ma) -> std::enable_if_t<2 == Ma::dimensionality> {
    for (auto const& r: ma)
        dump(r);
}

int main() {using range = boost::multi_array_types::index_range;
    using boost::extents;
    using boost::indices;

    auto mn = extents[7][4];
    boost::multi_array<int, 2> ma(mn);

    // fill with numbers from 10..37
    std::iota(ma.data(), ma.data() + ma.num_elements(), 10);

    dump(ma);

    std::cout << "Slice [3..5][1..3]\n";
    dump(ma[ indices[range(3,5)][range(1,3)] ]);

    std::cout << "Slice [2..4][2..3]\n";
    dump(ma[ indices[range(2,4)][range(2,3)] ]);

    std::cout << "Slice [1,3,5][2..3]\n";
    dump(ma[ indices[range(1,7,2)][range(2,3)] ]);

    std::cout << "Degenerate views (reduced dimensionality):\n";
    std::cout << "Slice [1,3,5][2]\n";
    dump(ma[ indices[range(1,7,2)][2] ]);

    std::cout << "Slice [0][1,3]\n";
    dump(ma[ indices[0][range(1,4,2)] ]);
}

Prints

 10 11 12 13
 14 15 16 17
 18 19 20 21
 22 23 24 25
 26 27 28 29
 30 31 32 33
 34 35 36 37
Slice [3..5][1..3]
 23 24
 27 28
Slice [2..4][2..3]
 20
 24
Slice [1,3,5][2..3]
 16
 24
 32
Degenerate views (reduced dimensionality):
Slice [1,3,5][2]
 16 24 32
Slice [0][1,3]
 11 13

UPDATE

Re. Comment:

if you want to avoid the degenerate dimensions, here's how:

Live On Coliru

std::cout << "Degenerate views (reduced dimensionality):\n";
std::cout << "Slice [1,3,5][2]\n";
dump(ma[ indices[range(1,7,2)][2] ]);

std::cout << "Slice [0][1,3]\n";
dump(ma[ indices[0][range(1,4,2)] ]);

// RE: Comment
std::cout << "NON-Degenerate views (reduced dimensionality):\n";
std::cout << "Slice [1,3,5][2]\n";
dump(ma[ indices[range(1,7,2)][range(2,3)] ]);

std::cout << "Slice [0][1,3]\n";
dump(ma[ indices[range(0,1)][range(1,4,2)] ]);

Prints

Degenerate views (reduced dimensionality):
Slice [1,3,5][2]
 16 24 32
Slice [0][1,3]
 11 13
NON-Degenerate views (reduced dimensionality):
Slice [1,3,5][2]
 16
 24
 32
Slice [0][1,3]
 11 13

Basically, don't use literals [i][j] but [range(i,i+1)][range(j,j+1)]


问:
Custom View Scrolling issues Android
I've been designing an application that requires the use of a scrollbar on a custom view. The problem that I have run into is that my custom view's height will constantly change when new items are added by the user. I suspect that this isn't a very unusual problem, but to complicate things, I'm not actually adding new objects to my custom view, I'm just drawing Bitmap images on the canvas. The reason this is troublesome to me is when Android inflates the layout, it sets the size to be whatever I tell it (0dip) and as I add the Bitmaps, it simply changes the size to fill the Scrollview; thereby, whenever the Custom View draws an image beyond the current height constraints, instead of scrolling, the app simply cuts the picture off to maintain the current height.

(This is for a card game app, so I wanted to fan out your current deck in a easy to view and edit fashion.)

Here is the relevant code :

```<code>public class DeckEdit extends Activity implements FilterQueryProvider  {

static final int PROGRESS_DIALOG = 0;
private Deck deck;
private CardListAdapter lstAdpt;
private ArrayList<CardImage> cards;
private ProgressDialog progressDialog;
private ProgressThread progressThread;
private String[] cardList;
private DeckEditCardView deckGrid;
private ScrollView sc;
protected Cursor cursor;

private EditText filterText = null;
ArrayAdapter<String> adapter = null;

public void onCreate(Bundle savedInstanceBundle){
    super.onCreate(savedInstanceBundle);
    deck = new Deck();
//This is what stores the Card Images that I draw to the canvas with
    cards = new ArrayList<CardImage>();

    setContentView(R.layout.deck_edit_layout);

    sc = (ScrollView) findViewById(R.id.deck_scroller);
    deckGrid = (DeckEditCardView) findViewById(R.id.deck_grid);

    filterText = (EditText) findViewById(R.id.card_search_box);
    filterText.addTextChangedListener(filterTextWatcher);

    pickDeck();
}
</code>```

And then this is called after I load the deck

```<code>private void finishSetup(){
    //this is where I set up the deckGrid to have all the cards and then
    deckGrid.setCards(cards);
    //draw them to the screen
    deckGrid.invalidate();
    //This is where I realized that the height value might be causing the problem
    Log.d("finishSetup()", "deckGrid width: "+deckGrid.getWidth());
    Log.d("finishSetup()", "deckGrid height: "+deckGrid.getHeight());
}
</code>```

The DeckEditCardView class contains this

```<code>public class DeckEditCardView extends View implements OnTouchListener {
private ArrayList<CardImage> cards;

private int X_COLS;
@SuppressWarnings("unused")
private int Y_ROWS;
private final int COL_WIDTH;
private final int ROW_HEIGHT;
private Context context;

private final int X_PADDING = 2;
private final int Y_PADDING = 2;
private final int X_CARD_OVERLAY = 7;
private final int Y_CARD_OVERLAY = 5;

public DeckEditCardView(Context context) {
    super(context);
    cards = new ArrayList<CardImage>();
    int cardWidth = getResources().getDrawable(R.drawable.back).getIntrinsicWidth();
    int cardHeight = getResources().getDrawable(R.drawable.back).getIntrinsicHeight();
    COL_WIDTH = (X_PADDING+(X_CARD_OVERLAY*3)+cardWidth);
    Log.d("DECV","COLWIDTH 1: "+COL_WIDTH);
    ROW_HEIGHT = (Y_PADDING+(Y_CARD_OVERLAY*3)+cardHeight);
    Log.d("DECV","ROWE_HEIGHT 1: "+ROW_HEIGHT);
}

public DeckEditCardView(Context context, AttributeSet attrs) {
    super(context, attrs);
    cards = new ArrayList<CardImage>();

    int cardWidth = getResources().getDrawable(R.drawable.back).getIntrinsicWidth();
    int cardHeight = getResources().getDrawable(R.drawable.back).getIntrinsicHeight();
    COL_WIDTH = (X_PADDING+(X_CARD_OVERLAY*3)+cardWidth);
    Log.d("DECV","COLWIDTH 2 : "+COL_WIDTH);
    ROW_HEIGHT = (Y_PADDING+(Y_CARD_OVERLAY*3)+cardHeight);
    Log.d("DECV","ROWE_HEIGHT 2: "+ROW_HEIGHT);
}

/*
public DeckEditCardView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    cards = new ArrayList<CardImage>();
    int width = getWidth();
    int height = getHeight();
    int cardWidth = getResources().getDrawable(R.drawable.back).getIntrinsicWidth();
    int cardHeight = getResources().getDrawable(R.drawable.back).getIntrinsicHeight();
    COL_WIDTH = (X_PADDING+(X_CARD_OVERLAY*3)+cardWidth);
    Log.d("DECV","COLWIDTH 3: "+COL_WIDTH);
    ROW_HEIGHT = (Y_PADDING+(Y_CARD_OVERLAY*3)+cardHeight);
    Log.d("DECV","ROWE_HEIGHT 3: "+ROW_HEIGHT);
    X_COLS = (width/COL_WIDTH);
    Y_ROWS = (height/ROW_HEIGHT);

}
*/
@Override
public void onFinishInflate(){
    super.onFinishInflate();
    //this.
}

public void onSizeChanged(int w, int h, int oldw, int oldh){
    int width = getWidth();
    int height = getHeight();
    X_COLS = (width/COL_WIDTH);
    Y_ROWS = (height/ROW_HEIGHT);

}

public Point getNextCardPoint(Point curP, boolean sameCard){
    Point p=null;
    if (sameCard)
        p = new Point(curP.x+X_CARD_OVERLAY,curP.y+Y_CARD_OVERLAY);
    else { //need to be on the same column
        if (point2Col(curP)+1<X_COLS)
            p = new Point(COL_WIDTH*(point2Col(curP)+1)+X_PADDING,
                ROW_HEIGHT*(point2Row(curP))+Y_PADDING);
        else {//add to new column
            if (point2Row(curP)+1 > Y_ROWS)
                Y_ROWS++;

            p = new Point(X_PADDING,
                    ROW_HEIGHT*(point2Row(curP)+1)+Y_PADDING);
        }
    }
    return p;
}

public void setCards(ArrayList<CardImage> cards){
    this.cards = cards;
}

private int point2Col(Point p){
    return p.x / COL_WIDTH;
}
private int point2Row(Point p){
    return p.y / ROW_HEIGHT;
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    //ScrollView s = new ScrollView(context);
    //s.addView(canvas);
    int length = cards.size();
    CardImage c;
    for (int i = 0; i < length; i++) {
        //Log.d("onDraw", "output a card");
        c = cards.get(i);
        canvas.drawBitmap(c.getBitmap(), c.getX(), c.getY(), null);
    }
}

@Override
public boolean onTouch(View arg0, MotionEvent arg1) {
    // TODO Auto-generated method stub
    return false;
}
}
</code>```

So in conclusion, I don't know how to allow the user to scroll and see the cards that don't fit on the screen (its almost guaranteed that a fully built deck will take a scrollbar to see all of them. At most with this code it'll put in all the card images I need, but the ones that go of screen I don't know what to do :/

And lastly my Layout.xml file

```<code><com.xeroxchange.ydd.DeckEditCardView android:layout_weight="2"
     android:id="@+id/deck_grid"
     android:layout_width="fill_parent"
     android:layout_height="0dip"></com.xeroxchange.ydd.DeckEditCardView>
</ScrollView>
<LinearLayout android:layout_weight="1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

        <!-- Pretty hint text, and maxLines -->
<EditText android:id="@+id/card_search_box"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:hint="type to filter"
    android:inputType="text"
    android:maxLines="1"/>

    <!-- Set height to 0, and let the weight param expand it -->
    <!-- Note the use of the default ID! This lets us use a
         ListActivity still! -->
    <ListView android:id="@+id/card_list"
        android:layout_width="fill_parent"
        android:layout_height="0dip"
        android:layout_weight="2"
    />

</LinearLayout>

</LinearLayout>
</code>```

答: Your layout doesn't work properly because the DeckEditCardView doesn't measure itself. You must override the View.onMeasure() method in the DeckEditCardView class and set measured size depending on view's content. In your layout xml file you must specify wrap_content as a height of the DeckEditCardView.

Title: Custom View Scrolling issues Android

Body:
I've been designing an application that requires the use of a scrollbar on a custom view. The problem that I have run into is that my custom view's height will constantly change when new items are added by the user. I suspect that this isn't a very unusual problem, but to complicate things, I'm not actually adding new objects to my custom view, I'm just drawing Bitmap images on the canvas. The reason this is troublesome to me is when Android inflates the layout, it sets the size to be whatever I tell it (0dip) and as I add the Bitmaps, it simply changes the size to fill the Scrollview; thereby, whenever the Custom View draws an image beyond the current height constraints, instead of scrolling, the app simply cuts the picture off to maintain the current height.

(This is for a card game app, so I wanted to fan out your current deck in a easy to view and edit fashion.)

Here is the relevant code :

public class DeckEdit extends Activity implements FilterQueryProvider  {

static final int PROGRESS_DIALOG = 0;
private Deck deck;
private CardListAdapter lstAdpt;
private ArrayList<CardImage> cards;
private ProgressDialog progressDialog;
private ProgressThread progressThread;
private String[] cardList;
private DeckEditCardView deckGrid;
private ScrollView sc;
protected Cursor cursor;

private EditText filterText = null;
ArrayAdapter<String> adapter = null;

public void onCreate(Bundle savedInstanceBundle){
    super.onCreate(savedInstanceBundle);
    deck = new Deck();
//This is what stores the Card Images that I draw to the canvas with
    cards = new ArrayList<CardImage>();

    setContentView(R.layout.deck_edit_layout);

    sc = (ScrollView) findViewById(R.id.deck_scroller);
    deckGrid = (DeckEditCardView) findViewById(R.id.deck_grid);

    filterText = (EditText) findViewById(R.id.card_search_box);
    filterText.addTextChangedListener(filterTextWatcher);

    pickDeck();
}

And then this is called after I load the deck

private void finishSetup(){
    //this is where I set up the deckGrid to have all the cards and then
    deckGrid.setCards(cards);
    //draw them to the screen
    deckGrid.invalidate();
    //This is where I realized that the height value might be causing the problem
    Log.d("finishSetup()", "deckGrid width: "+deckGrid.getWidth());
    Log.d("finishSetup()", "deckGrid height: "+deckGrid.getHeight());
}

The DeckEditCardView class contains this

public class DeckEditCardView extends View implements OnTouchListener {
private ArrayList<CardImage> cards;

private int X_COLS;
@SuppressWarnings("unused")
private int Y_ROWS;
private final int COL_WIDTH;
private final int ROW_HEIGHT;
private Context context;

private final int X_PADDING = 2;
private final int Y_PADDING = 2;
private final int X_CARD_OVERLAY = 7;
private final int Y_CARD_OVERLAY = 5;

public DeckEditCardView(Context context) {
    super(context);
    cards = new ArrayList<CardImage>();
    int cardWidth = getResources().getDrawable(R.drawable.back).getIntrinsicWidth();
    int cardHeight = getResources().getDrawable(R.drawable.back).getIntrinsicHeight();
    COL_WIDTH = (X_PADDING+(X_CARD_OVERLAY*3)+cardWidth);
    Log.d("DECV","COLWIDTH 1: "+COL_WIDTH);
    ROW_HEIGHT = (Y_PADDING+(Y_CARD_OVERLAY*3)+cardHeight);
    Log.d("DECV","ROWE_HEIGHT 1: "+ROW_HEIGHT);
}

public DeckEditCardView(Context context, AttributeSet attrs) {
    super(context, attrs);
    cards = new ArrayList<CardImage>();

    int cardWidth = getResources().getDrawable(R.drawable.back).getIntrinsicWidth();
    int cardHeight = getResources().getDrawable(R.drawable.back).getIntrinsicHeight();
    COL_WIDTH = (X_PADDING+(X_CARD_OVERLAY*3)+cardWidth);
    Log.d("DECV","COLWIDTH 2 : "+COL_WIDTH);
    ROW_HEIGHT = (Y_PADDING+(Y_CARD_OVERLAY*3)+cardHeight);
    Log.d("DECV","ROWE_HEIGHT 2: "+ROW_HEIGHT);
}

/*
public DeckEditCardView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    cards = new ArrayList<CardImage>();
    int width = getWidth();
    int height = getHeight();
    int cardWidth = getResources().getDrawable(R.drawable.back).getIntrinsicWidth();
    int cardHeight = getResources().getDrawable(R.drawable.back).getIntrinsicHeight();
    COL_WIDTH = (X_PADDING+(X_CARD_OVERLAY*3)+cardWidth);
    Log.d("DECV","COLWIDTH 3: "+COL_WIDTH);
    ROW_HEIGHT = (Y_PADDING+(Y_CARD_OVERLAY*3)+cardHeight);
    Log.d("DECV","ROWE_HEIGHT 3: "+ROW_HEIGHT);
    X_COLS = (width/COL_WIDTH);
    Y_ROWS = (height/ROW_HEIGHT);

}
*/
@Override
public void onFinishInflate(){
    super.onFinishInflate();
    //this.
}

public void onSizeChanged(int w, int h, int oldw, int oldh){
    int width = getWidth();
    int height = getHeight();
    X_COLS = (width/COL_WIDTH);
    Y_ROWS = (height/ROW_HEIGHT);

}

public Point getNextCardPoint(Point curP, boolean sameCard){
    Point p=null;
    if (sameCard)
        p = new Point(curP.x+X_CARD_OVERLAY,curP.y+Y_CARD_OVERLAY);
    else { //need to be on the same column
        if (point2Col(curP)+1<X_COLS)
            p = new Point(COL_WIDTH*(point2Col(curP)+1)+X_PADDING,
                ROW_HEIGHT*(point2Row(curP))+Y_PADDING);
        else {//add to new column
            if (point2Row(curP)+1 > Y_ROWS)
                Y_ROWS++;

            p = new Point(X_PADDING,
                    ROW_HEIGHT*(point2Row(curP)+1)+Y_PADDING);
        }
    }
    return p;
}

public void setCards(ArrayList<CardImage> cards){
    this.cards = cards;
}

private int point2Col(Point p){
    return p.x / COL_WIDTH;
}
private int point2Row(Point p){
    return p.y / ROW_HEIGHT;
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    //ScrollView s = new ScrollView(context);
    //s.addView(canvas);
    int length = cards.size();
    CardImage c;
    for (int i = 0; i < length; i++) {
        //Log.d("onDraw", "output a card");
        c = cards.get(i);
        canvas.drawBitmap(c.getBitmap(), c.getX(), c.getY(), null);
    }
}

@Override
public boolean onTouch(View arg0, MotionEvent arg1) {
    // TODO Auto-generated method stub
    return false;
}
}

So in conclusion, I don't know how to allow the user to scroll and see the cards that don't fit on the screen (its almost guaranteed that a fully built deck will take a scrollbar to see all of them. At most with this code it'll put in all the card images I need, but the ones that go of screen I don't know what to do :/

And lastly my Layout.xml file

<com.xeroxchange.ydd.DeckEditCardView android:layout_weight="2"
     android:id="@+id/deck_grid"
     android:layout_width="fill_parent"
     android:layout_height="0dip"></com.xeroxchange.ydd.DeckEditCardView>
</ScrollView>
<LinearLayout android:layout_weight="1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

<EditText android:id="@+id/card_search_box"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:hint="type to filter"
    android:inputType="text"
    android:maxLines="1"/>

    <ListView android:id="@+id/card_list"
        android:layout_width="fill_parent"
        android:layout_height="0dip"
        android:layout_weight="2"
    />

</LinearLayout>

</LinearLayout>


问:
react_dom_development is undefined in Deno React project
I wanted to try out Deno, so I decided to make a simple single-page React app.
But, when I try to pull in ReactDOM from the CDN, I get a console error: react_dom_development_js_2 is undefined.

I think what's going on is it can't resolve the ReactDOM CDN, but I can reach it from my browser? I also tried replacing it with what the browser resolves it to (https://unpkg.com/react-dom@16.13.1/umd/react-dom.development.js), but I still end up with the same error. Maybe I'm using the deno bundle wrong?

index.jsx

```<code>import { React } from "https://unpkg.com/react@16/umd/react.development.js";
import { ReactDOM } from "https://unpkg.com/react-dom@16/umd/react-dom.development.js";

ReactDOM.render(<p>Hello</p>, document.findElementById("app"));
</code>```

index.html

```<code><html>
  <head>
    <title>Test with Deno</title>
  </head>
  <body>

    <div id="app"></div>
    <script src="index.bundle.js"></script>
  </body>
</html>
</code>```

I run deno bundle index.jsx index.bundle.js to create my bundle,

index.bundle.js

```<code>// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.

// This is a specialised implementation of a System module loader.

// @ts-nocheck
/* eslint-disable */
let System, __instantiateAsync, __instantiate;

(() => {
  const r = new Map();

  System = {
    register(id, d, f) {
      r.set(id, { d, f, exp: {} });
    },
  };

  async function dI(mid, src) {
    let id = mid.replace(/\.\w+$/i, "");
    if (id.includes("./")) {
      const [o, ...ia] = id.split("/").reverse(),
        [, ...sa] = src.split("/").reverse(),
        oa = [o];
      let s = 0,
        i;
      while ((i = ia.shift())) {
        if (i === "..") s++;
        else if (i === ".") break;
        else oa.push(i);
      }
      if (s < sa.length) oa.push(...sa.slice(s));
      id = oa.reverse().join("/");
    }
    return r.has(id) ? gExpA(id) : import(mid);
  }

  function gC(id, main) {
    return {
      id,
      import: (m) => dI(m, id),
      meta: { url: id, main },
    };
  }

  function gE(exp) {
    return (id, v) => {
      v = typeof id === "string" ? { [id]: v } : id;
      for (const [id, value] of Object.entries(v)) {
        Object.defineProperty(exp, id, {
          value,
          writable: true,
          enumerable: true,
        });
      }
    };
  }

  function rF(main) {
    for (const [id, m] of r.entries()) {
      const { f, exp } = m;
      const { execute: e, setters: s } = f(gE(exp), gC(id, id === main));
      delete m.f;
      m.e = e;
      m.s = s;
    }
  }

  async function gExpA(id) {
    if (!r.has(id)) return;
    const m = r.get(id);
    if (m.s) {
      const { d, e, s } = m;
      delete m.s;
      delete m.e;
      for (let i = 0; i < s.length; i++) s[i](await gExpA(d[i]));
      const r = e();
      if (r) await r;
    }
    return m.exp;
  }

  function gExp(id) {
    if (!r.has(id)) return;
    const m = r.get(id);
    if (m.s) {
      const { d, e, s } = m;
      delete m.s;
      delete m.e;
      for (let i = 0; i < s.length; i++) s[i](gExp(d[i]));
      e();
    }
    return m.exp;
  }

  __instantiateAsync = async (m) => {
    System = __instantiateAsync = __instantiate = undefined;
    rF(m);
    return gExpA(m);
  };

  __instantiate = (m) => {
    System = __instantiateAsync = __instantiate = undefined;
    rF(m);
    return gExp(m);
  };
})();

System.register(
  "index",
  [
    "https://unpkg.com/react@16/umd/react.development.js",
    "https://unpkg.com/react-dom@16/umd/react-dom.development.js",
  ],
  function (exports_1, context_1) {
    "use strict";
    var react_development_js_1, react_dom_development_js_1;
    var __moduleName = context_1 && context_1.id;
    return {
      setters: [
        function (react_development_js_1_1) {
          react_development_js_1 = react_development_js_1_1;
        },
        function (react_dom_development_js_1_1) {
          react_dom_development_js_1 = react_dom_development_js_1_1;
        },
      ],
      execute: function () {
        react_dom_development_js_1.ReactDOM.render(
          react_development_js_1.React.createElement("p", null, "Hello"),
          document.findElementById("app"),
        );
      },
    };
  },
);

__instantiate("index");
</code>```

答:
TypeScript does not allow imports from html or that end in a file extension.
So for now you can ignore them using // @ts-ignore which will allow deno to work.

There is a visual studio code extension for deno but at the time of writing it seems to be a bit unstable.
If and when its working correctly you would be able to config deno to work on a per project basis by defining a settings folder in the root of your project e.g. .vscode/settings.json.

```<code>{
  "deno.enable": true
}
</code>```

Body:
I wanted to try out Deno, so I decided to make a simple single-page React app.
But, when I try to pull in ReactDOM from the CDN, I get a console error: react_dom_development_js_2 is undefined.

I think what's going on is it can't resolve the ReactDOM CDN, but I can reach it from my browser? I also tried replacing it with what the browser resolves it to (https://unpkg.com/react-dom@16.13.1/umd/react-dom.development.js), but I still end up with the same error. Maybe I'm using the deno bundle wrong?

index.jsx

import { React } from "https://unpkg.com/react@16/umd/react.development.js";
import { ReactDOM } from "https://unpkg.com/react-dom@16/umd/react-dom.development.js";

ReactDOM.render(
Hello
, document.findElementById("app"));

index.html

    <title>Test with Deno</title>

I run deno bundle index.jsx index.bundle.js to create my bundle,

index.bundle.js

// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.

// This is a specialised implementation of a System module loader.

// @ts-nocheck
/* eslint-disable */
let System, __instantiateAsync, __instantiate;

(() => {
  const r = new Map();

  System = {
    register(id, d, f) {
      r.set(id, { d, f, exp: {} });
    },
  };

  async function dI(mid, src) {
    let id = mid.replace(/\.\w+$/i, "");
    if (id.includes("./")) {
      const [o, ...ia] = id.split("/").reverse(),
        [, ...sa] = src.split("/").reverse(),
        oa = [o];
      let s = 0,
        i;
      while ((i = ia.shift())) {
        if (i === "..") s++;
        else if (i === ".") break;
        else oa.push(i);
      }
      if (s < sa.length) oa.push(...sa.slice(s));
      id = oa.reverse().join("/");
    }
    return r.has(id) ? gExpA(id) : import(mid);
  }

  function gC(id, main) {
    return {
      id,
      import: (m) => dI(m, id),
      meta: { url: id, main },
    };
  }

  function gE(exp) {
    return (id, v) => {
      v = typeof id === "string" ? { [id]: v } : id;
      for (const [id, value] of Object.entries(v)) {
        Object.defineProperty(exp, id, {
          value,
          writable: true,
          enumerable: true,
        });
      }
    };
  }

  function rF(main) {
    for (const [id, m] of r.entries()) {
      const { f, exp } = m;
      const { execute: e, setters: s } = f(gE(exp), gC(id, id === main));
      delete m.f;
      m.e = e;
      m.s = s;
    }
  }

  async function gExpA(id) {
    if (!r.has(id)) return;
    const m = r.get(id);
    if (m.s) {
      const { d, e, s } = m;
      delete m.s;
      delete m.e;
      for (let i = 0; i < s.length; i++) s[i](await gExpA(d[i]));
      const r = e();
      if (r) await r;
    }
    return m.exp;
  }

  function gExp(id) {
    if (!r.has(id)) return;
    const m = r.get(id);
    if (m.s) {
      const { d, e, s } = m;
      delete m.s;
      delete m.e;
      for (let i = 0; i < s.length; i++) s[i](gExp(d[i]));
      e();
    }
    return m.exp;
  }

  __instantiateAsync = async (m) => {
    System = __instantiateAsync = __instantiate = undefined;
    rF(m);
    return gExpA(m);
  };

  __instantiate = (m) => {
    System = __instantiateAsync = __instantiate = undefined;
    rF(m);
    return gExp(m);
  };
})();

System.register(
  "index",
  [
    "https://unpkg.com/react@16/umd/react.development.js",
    "https://unpkg.com/react-dom@16/umd/react-dom.development.js",
  ],
  function (exports_1, context_1) {
    "use strict";
    var react_development_js_1, react_dom_development_js_1;
    var __moduleName = context_1 && context_1.id;
    return {
      setters: [
        function (react_development_js_1_1) {
          react_development_js_1 = react_development_js_1_1;
        },
        function (react_dom_development_js_1_1) {
          react_dom_development_js_1 = react_dom_development_js_1_1;
        },
      ],
      execute: function () {
        react_dom_development_js_1.ReactDOM.render(
          react_development_js_1.React.createElement("p", null, "Hello"),
          document.findElementById("app"),
        );
      },
    };
  },
);

__instantiate("index");

Body:
TypeScript does not allow imports from html or that end in a file extension.
So for now you can ignore them using // @ts-ignore which will allow deno to work.

There is a visual studio code extension for deno but at the time of writing it seems to be a bit unstable.
If and when its working correctly you would be able to config deno to work on a per project basis by defining a settings folder in the root of your project e.g. .vscode/settings.json.

{
  "deno.enable": true
}


问:
MySQL - Data Deletion Based on Amount and ID
Question please, I have the three tables shown below

I am trying to delete the rows in Table A that are also in table B, to arrive at data in table C.
But note that if there are 2 instances with the same amount in table A (that is in table B), only delete one of them.

I am not sure how to do this efficiently as the amounts is a DOUBLE type.
I have considered adding the elements of table B to table A with a negative sign which is ok, since I will be eventually applying a summing on table A Grouped by ID for the final Results, but I am not sure if that is the most efficient way.

Thank you

```<code>CREATE TABLE A (id VARCHAR(1),
                sub_id INT,
                amount DOUBLE,
                CONSTRAINT pk_a PRIMARY KEY (id,sub_id));
CREATE TABLE B (id VARCHAR(1),
                amount DOUBLE,
                CONSTRAINT pk_b PRIMARY KEY (id));
CREATE TABLE C (id VARCHAR(1),
                sub_id INT,
                amount DOUBLE,
                CONSTRAINT pk_c PRIMARY KEY (id,sub_id));

INSERT INTO A
  (id,sub_id,amount)
VALUES
  ('A',1,40),
  ('A',2,43),
  ('A',3,91),
  ('A',4,71),
  ('B',1,90),
  ('B',2,88),
  ('B',3,88),
  ('C',1,21),
  ('C',2,22);

INSERT INTO B
  (id,amount)
VALUES
  ('A',40),
  ('B',88);

INSERT INTO C
  (id,sub_id,amount)
VALUES
  ('A',2,43),
  ('A',3,91),
  ('A',4,71),
  ('B',1,90),
  ('B',3,88),
  ('C',1,21),
  ('C',2,22);
</code>```

答:
You can join the tables with an another join to a query that returns row numbers for the rows of the table A that are duplicates for the columns id and amount.

These row numbers will be used so only 1 row of the duplicates is deleted:

```<code>DELETE A
FROM A
INNER JOIN (
  SELECT *, ROW_NUMBER() OVER(PARTITION BY id, amount ORDER BY id, sub_id) rn
  FROM A
) r ON r.id = A.id AND r.sub_id = A.sub_id AND r.rn = 1
INNER JOIN B
ON B.ID = A.ID AND B.Amount = A.Amount
</code>```

See the demo.

Results:

```<code>> id | sub_id | amount
> :- | -----: | -----:
> A  |      2 |     43
> A  |      3 |     91
> A  |      4 |     71
> B  |      1 |     90
> B  |      3 |     88
> C  |      1 |     21
> C  |      2 |     22
</code>```

Body:
Question please, I have the three tables shown below

I am trying to delete the rows in Table A that are also in table B, to arrive at data in table C.
But note that if there are 2 instances with the same amount in table A (that is in table B), only delete one of them.

I am not sure how to do this efficiently as the amounts is a DOUBLE type.
I have considered adding the elements of table B to table A with a negative sign which is ok, since I will be eventually applying a summing on table A Grouped by ID for the final Results, but I am not sure if that is the most efficient way.

Thank you

CREATE TABLE A (id VARCHAR(1),
                sub_id INT,
                amount DOUBLE,
                CONSTRAINT pk_a PRIMARY KEY (id,sub_id));
CREATE TABLE B (id VARCHAR(1),
                amount DOUBLE,
                CONSTRAINT pk_b PRIMARY KEY (id));
CREATE TABLE C (id VARCHAR(1),
                sub_id INT,
                amount DOUBLE,
                CONSTRAINT pk_c PRIMARY KEY (id,sub_id));

INSERT INTO A
  (id,sub_id,amount)
VALUES
  ('A',1,40),
  ('A',2,43),
  ('A',3,91),
  ('A',4,71),
  ('B',1,90),
  ('B',2,88),
  ('B',3,88),
  ('C',1,21),
  ('C',2,22);

INSERT INTO B
  (id,amount)
VALUES
  ('A',40),
  ('B',88);

INSERT INTO C
  (id,sub_id,amount)
VALUES
  ('A',2,43),
  ('A',3,91),
  ('A',4,71),
  ('B',1,90),
  ('B',3,88),
  ('C',1,21),
  ('C',2,22);

Body:
You can join the tables with an another join to a query that returns row numbers for the rows of the table A that are duplicates for the columns id and amount.

These row numbers will be used so only 1 row of the duplicates is deleted:

DELETE A
FROM A
INNER JOIN (
  SELECT *, ROW_NUMBER() OVER(PARTITION BY id, amount ORDER BY id, sub_id) rn
  FROM A
) r ON r.id = A.id AND r.sub_id = A.sub_id AND r.rn = 1
INNER JOIN B
ON B.ID = A.ID AND B.Amount = A.Amount

See the demo.

Results:

> id | sub_id | amount
> :- | -----: | -----:
> A  |      2 |     43
> A  |      3 |     91
> A  |      4 |     71
> B  |      1 |     90
> B  |      3 |     88
> C  |      1 |     21
> C  |      2 |     22


问:
How to start a ZeroMQ thread in an MFC application?
(Visual Studio 2017, C++ 17, cppzmq 4.6.0)

I'm new to MFC programming. I simply want to make a ZeroMQ reply server on a thread, that will always be ready to receive user requests and run certain functions, in my MFC program.

```<code>void zmq_server() {
    zmq::context_t context{ 1 };
    zmq::socket_t socket{ context, zmq::socket_type::rep };
    socket.bind("tcp://*:5555");

    const std::string data{ "Hi" };

    while (1) {
        zmq::message_t request;

        socket.recv(request, zmq::recv_flags::none);
        //std::cout << "Received " << request.to_string() << std::endl;

        socket.send(zmq::buffer(data), zmq::send_flags::none);
    }
}
</code>```

I thought I could run it as a thread if I just put it in where the dialogue is initialized:

```<code>BOOL CMFCApplication2Dlg::OnInitDialog()
{
    CDialogEx::OnInitDialog();

    ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
    ASSERT(IDM_ABOUTBOX < 0xF000);

    CMenu* pSysMenu = GetSystemMenu(FALSE);
    if (pSysMenu != nullptr)
    {
        BOOL bNameValid;
        CString strAboutMenu;
        bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);
        ASSERT(bNameValid);

        if (!strAboutMenu.IsEmpty())
        {
            pSysMenu->AppendMenu(MF_SEPARATOR);
            pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
        }
    }
    SetIcon(m_hIcon, TRUE);
    SetIcon(m_hIcon, FALSE);

    // TODO
    // thread t1(zmq_server )             <============== PROGRAM DOESN'T RUN WITH THIS LINE

    return TRUE;
}
</code>```

But the dialogue doesn't even start and I wonder if it's because it's not the right way to run a ZMQ server on a thread. How can I run it on a thread in an MFC program?

答: You should make std:: thread a member variable of your dialog class and initialise it in onInit. That way you keep the thread in scope for the duration of your program (and crucially you can stop the thread gracefully when your program exits).</p>

Body:
(Visual Studio 2017, C++ 17, cppzmq 4.6.0)

I'm new to MFC programming. I simply want to make a ZeroMQ reply server on a thread, that will always be ready to receive user requests and run certain functions, in my MFC program.

void zmq_server() {
    zmq::context_t context{ 1 };
    zmq::socket_t socket{ context, zmq::socket_type::rep };
    socket.bind("tcp://*:5555");

    const std::string data{ "Hi" };

    while (1) {
        zmq::message_t request;

        socket.recv(request, zmq::recv_flags::none);
        //std::cout << "Received " << request.to_string() << std::endl;

        socket.send(zmq::buffer(data), zmq::send_flags::none);
    }
}

I thought I could run it as a thread if I just put it in where the dialogue is initialized:

BOOL CMFCApplication2Dlg::OnInitDialog()
{
    CDialogEx::OnInitDialog();

    ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
    ASSERT(IDM_ABOUTBOX < 0xF000);

    CMenu* pSysMenu = GetSystemMenu(FALSE);
    if (pSysMenu != nullptr)
    {
        BOOL bNameValid;
        CString strAboutMenu;
        bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);
        ASSERT(bNameValid);

        if (!strAboutMenu.IsEmpty())
        {
            pSysMenu->AppendMenu(MF_SEPARATOR);
            pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
        }
    }
    SetIcon(m_hIcon, TRUE);
    SetIcon(m_hIcon, FALSE);

    // TODO
    // thread t1(zmq_server )             <============== PROGRAM DOESN'T RUN WITH THIS LINE

    return TRUE;
}

But the dialogue doesn't even start and I wonder if it's because it's not the right way to run a ZMQ server on a thread. How can I run it on a thread in an MFC program?


问:
AAPT: error: resource drawable/example (aka com.app:drawable/example) not found
I added one shape to the drawable folder as follows;

```<code><?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <stroke android:color="#7A828D" android:width="1dp"/>
    <solid android:color="@color/white" />
    <corners android:radius="8dp"/>
</shape>
</code>```

Then I included this in my layout;

```<code><androidx.constraintlayout.widget.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="64dp"
            android:background="@drawable/shape_info_bg_1"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintBottom_toTopOf="@id/sl_userid"
            android:layout_marginBottom="20dp">
            <ImageView
                android:id="@+id/img_info"
                android:layout_width="24dp"
                android:layout_height="24dp"
                android:src="@drawable/ico_info"
                app:layout_constraintTop_toTopOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintBottom_toBottomOf="parent"
                android:layout_marginStart="20dp"
                />
            <TextView
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                tools:text="asdasdasdasda"
                android:fontFamily="@font/medium"
                android:layout_marginEnd="50dp"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toEndOf="@id/img_info"
                app:layout_constraintTop_toTopOf="@id/img_info"
                app:layout_constraintBottom_toBottomOf="@+id/img_info"
                android:layout_marginStart="15dp"/>
        </androidx.constraintlayout.widget.ConstraintLayout>
</code>```

and when i get build on real device i get the following errors;

```<code>...\src\main\res\layout\activity_login.xml:41: AAPT: error: resource drawable/shape_info_bg_1 (aka com.xxxxx:drawable/shape_info_bg_1) not found.

    AGPBI: {"kind":"error","text":"Android resource linking failed","sources":[{"file":"C:\\Users\\xxxx\\Documents\\xxxx\\app\\src\\main\\res\\layout\\activity_login.xml","position":{"startLine":40}}],"original":"C:\\Users\\xxxx\\Documents\\xxxx\\app\\src\\main\\res\\layout\\activity_login.xml:41: AAPT: error: resource drawable/shape_info_bg_1 (aka com.xxxx:drawable/shape_info_bg_1) not found.\n    ","tool":"AAPT"}

> Task :app:mergeExtDexDebug

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:processDebugResources'.
> A failure occurred while executing com.android.build.gradle.internal.tasks.Workers$ActionFacade
   > Android resource linking failed
     C:\Users\xxxxx\Documents\xxxxx\app\src\main\res\layout\activity_login.xml:41: AAPT: error: resource drawable/shape_info_bg_1 (aka com.xxxxx/shape_info_bg_1) not found.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BU�LD FAILED in 12s
</code>```

I always add shape in this way and there is no problem. I could not solve this problem. I have never met before, can you help me?

答:
Just hit clean the project
Then make a rebuild

It will surely fix your problem. If it wont, just delete the file you added, rebuild the project, add file again and build the project

Body:
I added one shape to the drawable folder as follows;

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <stroke android:color="#7A828D" android:width="1dp"/>
    <solid android:color="@color/white" />
    <corners android:radius="8dp"/>
</shape>

Then I included this in my layout;

<androidx.constraintlayout.widget.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="64dp"
            android:background="@drawable/shape_info_bg_1"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintBottom_toTopOf="@id/sl_userid"
            android:layout_marginBottom="20dp">
            <ImageView
                android:id="@+id/img_info"
                android:layout_width="24dp"
                android:layout_height="24dp"
                android:src="@drawable/ico_info"
                app:layout_constraintTop_toTopOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintBottom_toBottomOf="parent"
                android:layout_marginStart="20dp"
                />
            <TextView
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                tools:text="asdasdasdasda"
                android:fontFamily="@font/medium"
                android:layout_marginEnd="50dp"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toEndOf="@id/img_info"
                app:layout_constraintTop_toTopOf="@id/img_info"
                app:layout_constraintBottom_toBottomOf="@+id/img_info"
                android:layout_marginStart="15dp"/>
        </androidx.constraintlayout.widget.ConstraintLayout>

and when i get build on real device i get the following errors;

...\src\main\res\layout\activity_login.xml:41: AAPT: error: resource drawable/shape_info_bg_1 (aka com.xxxxx:drawable/shape_info_bg_1) not found.

    AGPBI: {"kind":"error","text":"Android resource linking failed","sources":[{"file":"C:\\Users\\xxxx\\Documents\\xxxx\\app\\src\\main\\res\\layout\\activity_login.xml","position":{"startLine":40}}],"original":"C:\\Users\\xxxx\\Documents\\xxxx\\app\\src\\main\\res\\layout\\activity_login.xml:41: AAPT: error: resource drawable/shape_info_bg_1 (aka com.xxxx:drawable/shape_info_bg_1) not found.\n    ","tool":"AAPT"}

> Task :app:mergeExtDexDebug

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:processDebugResources'.
> A failure occurred while executing com.android.build.gradle.internal.tasks.Workers$ActionFacade
   > Android resource linking failed
     C:\Users\xxxxx\Documents\xxxxx\app\src\main\res\layout\activity_login.xml:41: AAPT: error: resource drawable/shape_info_bg_1 (aka com.xxxxx/shape_info_bg_1) not found.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BU�LD FAILED in 12s

I always add shape in this way and there is no problem. I could not solve this problem. I have never met before, can you help me?


Title: Calculate the difference in time in Days for Character Dates and also with Blank Spaces in one of the column

Body:
I have the following data, Both columns are dates & have to take the difference in days. However most of the values in one of date column is blank so I have to return NA for them.

a              b
02-07-2012

18-08-2012

13-08-2012

16-04-2012

26-04-2012

03-05-2012  12-05-2012

09-06-2012

30-05-2012

22-06-2012

05-07-2012

30-06-2012

09-05-2012

22-06-2012

02-07-2012

17-07-2012

17-08-2012

16-07-2012

01-08-2012

05-08-2012

17-08-2012

30-04-2012

05-07-2012

07-04-2012

27-04-2012

21-06-2012

03-07-2012

21-07-2012

24-04-2012

05-06-2012

03-07-2012

02-04-2012  01-06-2012

06-04-2012

15-04-2012

16-06-2012

01-08-2012

13-05-2012

09-07-2012

09-07-2012

18-04-2012

09-08-2012

10-04-2012

12-05-2012

04-04-2012

04-06-2012  04-06-2012

15-06-2012

02-07-2012

05-07-2012

21-08-2012

19-07-2012

06-08-2012

15-06-2012

06-04-2012

04-06-2012

23-07-2012

06-04-2012

12-04-2012  11-06-2012

24-05-2012

03-08-2012

04-05-2012  09-05-2012

07-05-2012

07-06-2012

06-07-2012

13-07-2012

26-07-2012

26-04-2012

22-06-2012

26-07-2012

12-04-2012

07-08-2012

27-06-2012

03-04-2012  02-06-2012

13-04-2012

28-07-2012

07-05-2012

29-06-2012

03-04-2012  02-06-2012

04-04-2012

04-04-2012  24-05-2012

04-04-2012

05-04-2012

07-04-2012

10-04-2012

11-04-2012

13-04-2012

13-04-2012

13-04-2012

13-04-2012

14-04-2012

14-04-2012

14-04-2012

18-04-2012

19-04-2012

21-04-2012

25-04-2012

25-04-2012

26-04-2012

26-04-2012

26-04-2012

27-04-2012

30-04-2012

04-06-2012

04-06-2012

05-06-2012

05-06-2012

05-06-2012

05-06-2012

05-06-2012  16-07-2012

06-06-2012  29-06-2012

I tried the following but couldnt succeed

date_strings[date_strings==""]<-NA      # Replaced blank spaces with NA & removed them
head(date_strings)
newdata<-na.omit(date_strings)
str(newdata)

newdata$a<-as.Date(newdata$a,"%m%d%y")
newdata$b<-as.Date(newdata$b,"%m%d%y")

diff_in_days = difftime(newdata$a, newdata$b, units = "days") # days

Body:
With tidyverse, we can do

library(dplyr)
library(lubridate)
date_strings %>%
    mutate(across(everything(), dmy)) %>%
    mutate(diff_in_days = b - a)
#           a          b diff_in_days
#1 2012-07-02       <NA>      NA days
#2 2012-08-18       <NA>      NA days
#3 2012-08-13       <NA>      NA days
#4 2012-04-16       <NA>      NA days
#5 2012-04-26       <NA>      NA days
#6 2012-05-03 2012-05-12       9 days

data

date_strings <- structure(list(a = c("02-07-2012", "18-08-2012", "13-08-2012",
"16-04-2012", "26-04-2012", "03-05-2012"), b = c("", "", "",
"", "", "12-05-2012")), class = "data.frame", row.names = c(NA, -6L))


问:
Is it possible, using PHPUnit mock objects, to expect a call to a magic __call() method?
I've got a mock object in a test. The real object, PageRepository, implements a magic method using __call(), so if you call $pageRepository->findOneByXXXX($value_of_field_XXXX), it will search the database for records matching that parameter.

Is there a way to mock that method?

The real method call would look something like this:

```<code>$homepage = $pageRepository->findOneBySlug('homepage');
</code>```

The test would look like this:

```<code>$mockPageRepository->expects($this->any())
    ->method('findOneBySlug')
    ->will($this->returnValue(new Page()));
</code>```

But it doesn't work -- PHPUnit doesn't spot the method call. The only way to get it to see the method is to define the method explicitly in PageRepository.

答:
PHPUnit's getMock() takes a second argument, an array with the names of methods to be mocked.
If you include a method name in this array, the mock object will contain a method with that name, which expects() and friends will work on.

This applies even for methods that are not defined in the "real" class, so something like the following should do the trick:

```<code>$mockPageRepository = $this->getMock('PageRepository', array('findOneBySlug'));
</code>```

Keep in mind that you'll have to explicitly include any other methods that also need to be mocked, since only the methods named in the array are defined for the mock object.

Body:
I've got a mock object in a test. The real object, PageRepository, implements a magic method using __call(), so if you call $pageRepository->findOneByXXXX($value_of_field_XXXX), it will search the database for records matching that parameter.

Is there a way to mock that method?

The real method call would look something like this:

$homepage = $pageRepository->findOneBySlug('homepage');

The test would look like this:

$mockPageRepository->expects($this->any())
    ->method('findOneBySlug')
    ->will($this->returnValue(new Page()));

But it doesn't work -- PHPUnit doesn't spot the method call. The only way to get it to see the method is to define the method explicitly in PageRepository.

Body:
PHPUnit's getMock() takes a second argument, an array with the names of methods to be mocked.
If you include a method name in this array, the mock object will contain a method with that name, which expects() and friends will work on.

This applies even for methods that are not defined in the "real" class, so something like the following should do the trick:

$mockPageRepository = $this->getMock('PageRepository', array('findOneBySlug'));

Keep in mind that you'll have to explicitly include any other methods that also need to be mocked, since only the methods named in the array are defined for the mock object.


问:
How to count the numbers where the absolute value is greater than LOG2 cutoff with COUNTIFS in Excel?
I have an excel sheet with some numbers and I want to count the numbers where its absolute value is >=LOG(y,2).

I know COUNTIFS can be used to find the numbers greater than a value, but I don't know how to include the LOG  and ABS functions into the formula.

For example my numbers, x= 12,34,-15,-23,-5,45,-50
and I want to count the numbers where the ABS(x)>=LOG(y,2) where Y can be variable, for example y=3.

答:
Thats my best way:

English Excel Version

```<code>=SUMPRODUCT(--(ABS(A1:A7)>=LOG(32768,2)))
</code>```

German Excel Version:

```<code>=SUMMENPRODUKT(--(ABS(A1:A7)>=LOG(32768;2)))
</code>```

Body:
Thats my best way:

English Excel Version

=SUMPRODUCT(--(ABS(A1:A7)>=LOG(32768,2)))

German Excel Version:

=SUMMENPRODUKT(--(ABS(A1:A7)>=LOG(32768;2)))