问:
Calculate Median on Sql
I am very new to SQL. I am trying to use the code below and it keeps giving me the following error -

Msg The ORDER BY clause is invalid in
  views, inline functions, derived
  tables, subqueries, and common table
  expressions, unless TOP or FOR XML is
  also specified.

Incorrect syntax near '2'.

Please can someone help - where am I going wrong?

I am just trying to calculate median.

Could someone please suggest amendment to this code as I have picked up someone else's work.

Any help will be greatly appreciated.

```<code>SELECT
    TOP (100) PERCENT Name, Sales Median
FROM
    (SELECT
         a1.Name, a1.Sales, COUNT(a1.Sales) Rank
     FROM
         PSE.vw_EM_Data a1, PSE.vw_EM_Data a2
     WHERE
         a1.Sales < a2.Sales OR
         (a1.Sales = a2.Sales AND a1.Name <= a2.Name)
     GROUP BY
         a1.Name, a1.Sales
     ORDER BY
         a1.Sales DESC) a3
WHERE
    Rank = (SELECT (COUNT(*) + 1) DIV 2 FROM Total_Sales);
WHERE
    (Name LIKE 'John%')
    AND (DISPOSAL = '1')
    AND (DATE BETWEEN CONVERT(DATETIME, '2010-04-01 00:00:00', 102) AND CONVERT(DATETIME, '2011-03-30 00:00:00', 102))
</code>```

答:
Couple things to point out:

1) I would never use the "old-style" JOIN syntax that you use in your inner SELECT - it can easily lead to unwanted cartesian products - as it does in your case (though I'm not sure whether that's wanted or not....)

So instead of:

```<code>FROM
   PSE.vw_EM_Data a1, PSE.vw_EM_Data a2
</code>```

I would recommend to use the proper ANSI JOIN syntax

```<code>FROM
   PSE.vw_EM_Data a1
INNER JOIN           -- or possibly: LEFT OUTER JOIN or even FULL OUTER JOIN
   PSE.vw_EM_Data a2 ON a1.Sales = a2.Sales
</code>```

which makes it much clearer what it is you really want, and avoids any unnecessary problems.

2) In your second WHERE clause, you first of all don't need all those parenthesis, really - and most of all, you definitely shouldn't be converting a DATE or DATETIME column into a string to then compare it - so instead of this:

```<code>WHERE
    (Name LIKE 'John%')
    AND (DISPOSAL = '1')
    AND (DATE BETWEEN CONVERT(DATETIME, '2010-04-01 00:00:00', 102) AND CONVERT(DATETIME, '2011-03-30 00:00:00', 102))
</code>```

use this instead:

```<code>WHERE
    Name LIKE 'John%'
    AND DISPOSAL = '1'
    AND [DATE] BETWEEN '2010-04-01T00:00:00' AND '2011-03-30T00:00:00'
</code>```

and I would also try to avoid calling a column by a name that's a keyword in SQL like DATE - you'll have to use square brackets around it to make things clear to SQL Server.

Title: Calculate Median on Sql

Body:
I am very new to SQL. I am trying to use the code below and it keeps giving me the following error -

Msg The ORDER BY clause is invalid in
  views, inline functions, derived
  tables, subqueries, and common table
  expressions, unless TOP or FOR XML is
  also specified.

Incorrect syntax near '2'.

Please can someone help - where am I going wrong?

I am just trying to calculate median.

Could someone please suggest amendment to this code as I have picked up someone else's work.

Any help will be greatly appreciated.

SELECT
    TOP (100) PERCENT Name, Sales Median
FROM
    (SELECT
         a1.Name, a1.Sales, COUNT(a1.Sales) Rank
     FROM
         PSE.vw_EM_Data a1, PSE.vw_EM_Data a2
     WHERE
         a1.Sales < a2.Sales OR
         (a1.Sales = a2.Sales AND a1.Name <= a2.Name)
     GROUP BY
         a1.Name, a1.Sales
     ORDER BY
         a1.Sales DESC) a3
WHERE
    Rank = (SELECT (COUNT(*) + 1) DIV 2 FROM Total_Sales);
WHERE
    (Name LIKE 'John%')
    AND (DISPOSAL = '1')
    AND (DATE BETWEEN CONVERT(DATETIME, '2010-04-01 00:00:00', 102) AND CONVERT(DATETIME, '2011-03-30 00:00:00', 102))

Body:
Couple things to point out:

1) I would never use the "old-style" JOIN syntax that you use in your inner SELECT - it can easily lead to unwanted cartesian products - as it does in your case (though I'm not sure whether that's wanted or not....)

So instead of:

FROM
   PSE.vw_EM_Data a1, PSE.vw_EM_Data a2

I would recommend to use the proper ANSI JOIN syntax

FROM
   PSE.vw_EM_Data a1
INNER JOIN           -- or possibly: LEFT OUTER JOIN or even FULL OUTER JOIN
   PSE.vw_EM_Data a2 ON a1.Sales = a2.Sales

which makes it much clearer what it is you really want, and avoids any unnecessary problems.

2) In your second WHERE clause, you first of all don't need all those parenthesis, really - and most of all, you definitely shouldn't be converting a DATE or DATETIME column into a string to then compare it - so instead of this:

WHERE
    (Name LIKE 'John%')
    AND (DISPOSAL = '1')
    AND (DATE BETWEEN CONVERT(DATETIME, '2010-04-01 00:00:00', 102) AND CONVERT(DATETIME, '2011-03-30 00:00:00', 102))

use this instead:

WHERE
    Name LIKE 'John%'
    AND DISPOSAL = '1'
    AND [DATE] BETWEEN '2010-04-01T00:00:00' AND '2011-03-30T00:00:00'

and I would also try to avoid calling a column by a name that's a keyword in SQL like DATE - you'll have to use square brackets around it to make things clear to SQL Server.


来源: stackexchange

问:
MongoDB findOne funtion returns null when comparing with id
I am using the following code to get the details of a user when I pass their id as a parameter:

```<code>   server.get("/users/:id", (req, res) => {
        const itemId = req.params.id;

        dbCollection.findOne({ _id: itemId }, (error, result) => {
            if (error) throw error;
            // return item
            res.json(result);
        });
    });
</code>```

However, this doesn't seem to work, as whenever I run the code, I get returned with a null value.
My question is not the same as many previously asked questions because I have ObjectId('randomId') as my id, and not a string. How can I fix my code?

答:
MongoDB wouldn't consider the "itemId" as a MongoDB id, therefore you need to transform it as shown below:

```<code>new mongodb.ObjectId(itemId)
</code>```

This implies that:

```<code>const mongodb = require('mongodb')
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am using the following code to get the details of a user when I pass their id as a parameter:

   server.get("/users/:id", (req, res) => {
        const itemId = req.params.id;

        dbCollection.findOne({ _id: itemId }, (error, result) => {
            if (error) throw error;
            // return item
            res.json(result);
        });
    });

However, this doesn't seem to work, as whenever I run the code, I get returned with a null value.
My question is not the same as many previously asked questions because I have ObjectId('randomId') as my id, and not a string. How can I fix my code?

Body:
MongoDB wouldn't consider the "itemId" as a MongoDB id, therefore you need to transform it as shown below:

new mongodb.ObjectId(itemId)

This implies that:

const mongodb = require('mongodb')


问:
Laravel flatten and pluck from multidimensional collection
I have to retrieve just an array of id from the given collection, something like [10,54,61,21,etc].
I've tried flatten, pluck, but nothing seems to work apart from a foreach which is something I would like to remove at this step.

```<code>// Model
class Children extends Eloquent {
    public function directChildrens(){
        return $this->hasMany('App\Children','father_id','id')->select('id','father_id');
    }

    public function childrens(){
        return $this->directChildrens()->with('childrens');
    }
}

// Controller
return $children->childrens()->get();
</code>```

As expected it works fine. Here a result:

```<code>[{
"id": 10,
"father_id": 2,
"childrens": [
    {
        "id": 54,
        "father_id": 10,
        "childrens": [
            {
                "id": 61,
                "father_id": 54,
                "childrens": []
            }
        ]
    },
    {
        "id": 21,
        "father_id": 10,
        "childrens": []
    }
]
}]
</code>```

How can I perform a pluck('id') of this collection in order to get [10,54,61,21] ?

答:
Not sure you want pluck('id') mean but pluck doesn't works on recursive array. So i use recursive to get the id values.

$result->map(function ($item) {
  $ids = [];
  array_walk_recursive($item['childrens'], function ($item, $key) use(&$ids) {
     if($key === 'id') $ids[] = $item;
  });
  return array_merge([$item['id']], $ids);
});
```

Body:
I have to retrieve just an array of id from the given collection, something like [10,54,61,21,etc].
I've tried flatten, pluck, but nothing seems to work apart from a foreach which is something I would like to remove at this step.

// Model
class Children extends Eloquent {
    public function directChildrens(){
        return $this->hasMany('App\Children','father_id','id')->select('id','father_id');
    }

    public function childrens(){
        return $this->directChildrens()->with('childrens');
    }
}

// Controller
return $children->childrens()->get();

As expected it works fine. Here a result:

[{
"id": 10,
"father_id": 2,
"childrens": [
    {
        "id": 54,
        "father_id": 10,
        "childrens": [
            {
                "id": 61,
                "father_id": 54,
                "childrens": []
            }
        ]
    },
    {
        "id": 21,
        "father_id": 10,
        "childrens": []
    }
]
}]

How can I perform a pluck('id') of this collection in order to get [10,54,61,21] ?


问:
Why is my fs error returning an empty object in Node.js?
I am currently trying to read a file using fs in Node v12.16.2. I currently have a function setup like so:

const fs = require('fs');
var JSONData;
const read = function(path){
    fs.readFile(path, 'utf8', (data, err) => {
        if(err){
            console.log(err);
            console.log('there was an error');
        }
        JSONData = data;
    })
}
read('./path/to/file.json');
```

<p>In the console, I simply get</p>

```{}
there was an error
```

I also tried console.loging err.message, err.valueOf, and using throw err, none of which gave me any more data on the error. I'd appreciate if someone could help either discover my problem or knows it already.

答:
Callbacks in Node.js receive the error as the first argument:</p>

```<code>const fs = require('fs');
var JSONData;
function read (path) {
    fs.readFile(path, 'utf8', (err, data) => { // <-- Look here
        if (err) {
            console.log(err);
            console.log('there was an error');
        }
        JSONData = data;
    })
}
read('./path/to/file.json');
</code>```

Body:
I am currently trying to read a file using fs in Node v12.16.2. I currently have a function setup like so:

const fs = require('fs');
var JSONData;
const read = function(path){
    fs.readFile(path, 'utf8', (data, err) => {
        if(err){
            console.log(err);
            console.log('there was an error');
        }
        JSONData = data;
    })
}
read('./path/to/file.json');

In the console, I simply get

{}
there was an error

I also tried console.loging err.message, err.valueOf, and using throw err, none of which gave me any more data on the error. I'd appreciate if someone could help either discover my problem or knows it already.

Body:
Callbacks in Node.js receive the error as the first argument:

const fs = require('fs');
var JSONData;
function read (path) {
    fs.readFile(path, 'utf8', (err, data) => { // <-- Look here
        if (err) {
            console.log(err);
            console.log('there was an error');
        }
        JSONData = data;
    })
}
read('./path/to/file.json');


问:
Error: app.database is not a function using Firebase
I'm trying to use the Firebase realtime database with Vue. I'm getting the following error:

TypeError: app.database is not a function

My code:

Firebase.js:

```<code>var firebase = require('firebase');
export default firebase.initializeApp({
    apiKey: "HIDDEN",
    authDomain: "HIDDEN",
    databaseURL: "HIDDEN",
    projectId: "HIDDEN",
    storageBucket: "HIDDEN",
    messagingSenderId: "HIDDEN",
    appId: "HIDDEN"
});

export const db = app.database();
export const wordRef = db.ref('Word');
</code>```

I'm trying to use it on a  button.

```<code><b-field label="Word">
  <b-input
            v-model="Word"
            :value="Word"
            @input="Word = $event.target.value"
            ></b-input>
        </b-field>
       <b-button @click="submitData">Submit Me</b-button>
</code>```

```<code><script>
import { wordRef } from '../firebase';

export default {
  data() {
    return {
      Word: ""
    }
  },

  methods: {
    submitData() {
      wordRef.push({Word: this.Word})
    }
  },
}
</script>
</code>```

答: It's not clear from your question what app is - it's never defined.  However, I think you meant to say firebase.database() instead of app.database().

Body:
I'm trying to use the Firebase realtime database with Vue. I'm getting the following error:

TypeError: app.database is not a function

My code:

Firebase.js:

var firebase = require('firebase');
export default firebase.initializeApp({
    apiKey: "HIDDEN",
    authDomain: "HIDDEN",
    databaseURL: "HIDDEN",
    projectId: "HIDDEN",
    storageBucket: "HIDDEN",
    messagingSenderId: "HIDDEN",
    appId: "HIDDEN"
});

export const db = app.database();
export const wordRef = db.ref('Word');

I'm trying to use it on a  button.

       Submit Me


问:
Tips for studying Android
I joined a company recently and they have requested me to develop a few applications for Android. I've never seen it before - though I'm familiar with Java, so the programmatic syntax is familiar to me - and I'd like to know if there is a good site/textbook/whatever where I could learn how to program for Android OS - the simpler the better!

In particular, I'm searching for some way to allow me to use Android to do 2 things - to get a GPS location on a regular basis and to get an application connecting with a remote database. These are my priorities at the moment, but this doesn't mean you can't indicate me a knowledge source that doesn't have these on it. I do need to learn to program on this system, and I'll be thankful for whatever you indicate me. But if you happen to know where I could find these 2 items, please don't be shy and let me know.

Thanks in advance for your replies.

答:
I haven't find any better source of information than the official android developers page: http://developer.android.com/index.html

And here SO has a lot of interesting topics...

I also recomend you to investigate scripting in android with python, it's awesome the easy way to get things working...

Look at this code:

```<code>import android, time
droid = android.Android()
droid.startLocating()
time.sleep(10)
location = droid.readLocation()
</code>```

now location is an dictionary with your latitude, longitude, altitude, speed, and some other information... you'll find everything about scripting in android here: http://code.google.com/p/android-scripting/

ContentLicense: CC BY-SA 3.0

Title: Tips for studying Android

Body:
I haven't find any better source of information than the official android developers page: http://developer.android.com/index.html

And here SO has a lot of interesting topics...

I also recomend you to investigate scripting in android with python, it's awesome the easy way to get things working...

Look at this code:

import android, time
droid = android.Android()
droid.startLocating()
time.sleep(10)
location = droid.readLocation()

now location is an dictionary with your latitude, longitude, altitude, speed, and some other information... you'll find everything about scripting in android here: http://code.google.com/p/android-scripting/


问:
Why does copying eval change its behaviour?
According to the rollupjs documentation:

Simply 'copying' eval provides you with a function that does exactly the same thing, but which runs in the global scope rather than the local one:

```<code>var eval2 = eval;
(function () {
   var foo = 42;
   eval('console.log("with eval:",foo)');  // logs 'with eval: 42'
   eval2('console.log("with eval2:",foo)'); // throws ReferenceError
})();
</code>```

Can anyone explain exactly how this works? I haven't been able to find anything specific about eval() in the ECMAScript spec.

Perhaps eval is not actually a function, but a magic token that gets replaced by a function that executes code in that scope, a bit like this:

```<code>var eval2 = CREATE_EVAL(CURRENT_SCOPE);
(function () {
   var foo = 42;
   CREATE_EVAL(CURRENT_SCOPE)('console.log("with eval:",foo)');  // logs 'with eval: 42'
   eval2('console.log("with eval2:",foo)'); // throws ReferenceError
})();
</code>```

However, since we're dealing with modules here (commonJS or ES6), this would imply that eval2 actually runs in the module scope. The rollupjs documentation specifically says it runs in global scope - I figured this was just an oversight, but when I tested this, it does actually appear to run in the global scope:

```<code>var x = 1;
var eval2 = eval;
(function () {
    eval2('console.log("with eval2:", x)'); // throws ReferenceError
})();
</code>```

That's very confusing! How in the world does this work? Why does copying the reference to eval change its behaviour so drastically?

答:
Because the ECMAScript 5 language specification says that direct references to eval will execute in the local scope, while indirect references will use the global scope.

A more English-friendly description can be found on MDN:

If you use the eval function indirectly, by invoking it via a reference other than eval, as of ECMAScript 5 it works in the global scope rather than the local scope. This means, for instance, that function declarations create global functions, and that the code being evaluated doesn't have access to local variables within the scope where it's being called.

Body:
According to the rollupjs documentation:

Simply 'copying' eval provides you with a function that does exactly the same thing, but which runs in the global scope rather than the local one:

var eval2 = eval;
(function () {
   var foo = 42;
   eval('console.log("with eval:",foo)');  // logs 'with eval: 42'
   eval2('console.log("with eval2:",foo)'); // throws ReferenceError
})();

Can anyone explain exactly how this works? I haven't been able to find anything specific about eval() in the ECMAScript spec.

Perhaps eval is not actually a function, but a magic token that gets replaced by a function that executes code in that scope, a bit like this:

var eval2 = CREATE_EVAL(CURRENT_SCOPE);
(function () {
   var foo = 42;
   CREATE_EVAL(CURRENT_SCOPE)('console.log("with eval:",foo)');  // logs 'with eval: 42'
   eval2('console.log("with eval2:",foo)'); // throws ReferenceError
})();

However, since we're dealing with modules here (commonJS or ES6), this would imply that eval2 actually runs in the module scope. The rollupjs documentation specifically says it runs in global scope - I figured this was just an oversight, but when I tested this, it does actually appear to run in the global scope:

var x = 1;
var eval2 = eval;
(function () {
    eval2('console.log("with eval2:", x)'); // throws ReferenceError
})();

That's very confusing! How in the world does this work? Why does copying the reference to eval change its behaviour so drastically?


问:
Is there any standard Java Component with a notification count
I am wondering if there is a Standard Java Component (Icon or JLabel) that offers the abillity to show a notification count like the example below. I am not doing Android Development. I just want to show something similar in a Java desktop client application

The following code in a JLabel subclass would get the same result, but I am more interested in a standard solution. Which automatically derives the correct font size and automatically adjust to the visible space.

```<code>public void paintComponent(Graphics g)
{
  super.paintComponent(g);
  Graphics2D g2d = (Graphics2D) g;
  int w = getWidth();
  Font orgFont = g.getFont();
  Font deriveFont = orgFont.deriveFont(8.5f);
  g2d.setPaint(Color.RED);
  g2d.fillOval(w - 12, 0, 12, 12);
  g2d.setPaint(Color.BLACK);
  g2d.setFont(deriveFont);
  g2d.drawString("99", w-10, 10);
  g2d.setFont(orgFont);
}
</code>```

答:
if there is a Standard Java Component (Icon or JLabel)

No there is no standard component.

You might be able to:

Use the Compound Icon. It allows you to combine multiple icons into one.

Add a second JLabel with the notification Icon to the first JLabel. By default a JLabel doesn't have a layout manager but there is no reason you can't use one.

So for example to add the label in the top/right corner you could do:

```<code>JLabel main = new JLabel(…);
main.setLayout( new FlowLayout(FlowLayout.FlowLayout.RIGHT, 5, 5) );

JLabel notify = new JLabel(…);
main.add( notify );
</code>```

Body:
I am wondering if there is a Standard Java Component (Icon or JLabel) that offers the abillity to show a notification count like the example below. I am not doing Android Development. I just want to show something similar in a Java desktop client application

The following code in a JLabel subclass would get the same result, but I am more interested in a standard solution. Which automatically derives the correct font size and automatically adjust to the visible space.

public void paintComponent(Graphics g)
{
  super.paintComponent(g);
  Graphics2D g2d = (Graphics2D) g;
  int w = getWidth();
  Font orgFont = g.getFont();
  Font deriveFont = orgFont.deriveFont(8.5f);
  g2d.setPaint(Color.RED);
  g2d.fillOval(w - 12, 0, 12, 12);
  g2d.setPaint(Color.BLACK);
  g2d.setFont(deriveFont);
  g2d.drawString("99", w-10, 10);
  g2d.setFont(orgFont);
}

Body:
if there is a Standard Java Component (Icon or JLabel)

No there is no standard component.

You might be able to:

Use the Compound Icon. It allows you to combine multiple icons into one.

Add a second JLabel with the notification Icon to the first JLabel. By default a JLabel doesn't have a layout manager but there is no reason you can't use one.

So for example to add the label in the top/right corner you could do:

JLabel main = new JLabel(…);
main.setLayout( new FlowLayout(FlowLayout.FlowLayout.RIGHT, 5, 5) );

JLabel notify = new JLabel(…);
main.add( notify );


问:
how to get parent folder name in spark?
file:/C:/workspace/Spark_Scala_Exercise2/src/main/Resources/exercise-2/input/run_1/batch_id=73/part-00000-7489f493-c825-469a-9877-0b0e2c75cd4b.c000.snappy.parquet like i have many files

from this
i only want batch_id column with 73

答:
Try this for all the run_1, run_2, run_3, etc at once:</p>

```<code>val df = spark.read.parquet("file:/C:/workspace/Spark_Scala_Exercise2/src/main/Resources/exercise-2/input/*/*")
df.select("batch_id").distinct.show
</code>```

Title: how to get parent folder name in spark?

Body:
Try this for all the run_1, run_2, run_3, etc at once:

val df = spark.read.parquet("file:/C:/workspace/Spark_Scala_Exercise2/src/main/Resources/exercise-2/input/*/*")
df.select("batch_id").distinct.show


问:
Unable to execute loop in react
I am trying to run a react loop to display time, and am running into an issue, please assist.
Below is my code

```<code>    populateDefaultTime() {
        alert("inside default time");
        for (let i = 1; i < 24; i++) {
            this.times.push(i);
        }
    }

    componentDidMount() {
         this.populateDefaultTime();
    }
</code>```

Below is my error

```<code>populateDefaultTime() {
  35 |     alert("inside default time");
  36 |     for (let i = 1; i < 24; i++) {
> 37 |         this.times.push(i);
     | ^  38 |     }
  39 |
  40 | }
</code>```

答:
this.times is not defined so you can't push to it. Should be:

```<code>this.state.times.push(i);
</code>```

As @swapnesh has stated though you should not mutate state directly. It would be better to do something like

```<code>this.setState({ times: this.state.times.concat(i) });
</code>```

Title: Unable to execute loop in react

Body:
I am trying to run a react loop to display time, and am running into an issue, please assist.
Below is my code

    populateDefaultTime() {
        alert("inside default time");
        for (let i = 1; i < 24; i++) {
            this.times.push(i);
        }
    }

    componentDidMount() {
         this.populateDefaultTime();
    }

Below is my error

populateDefaultTime() {
  35 |     alert("inside default time");
  36 |     for (let i = 1; i < 24; i++) {
> 37 |         this.times.push(i);
     | ^  38 |     }
  39 |
  40 | }

Body:
this.times is not defined so you can't push to it. Should be:

this.state.times.push(i);

As @swapnesh has stated though you should not mutate state directly. It would be better to do something like

this.setState({ times: this.state.times.concat(i) });


问:
How to get pass this error "Value cannot be null. Parameter name: entity"
```<code>        private void button1_Click(object sender, EventArgs e)
    {

        DataClasses1DataContext dc = new DataClasses1DataContext();
        var rec = dc.reportsSents.FirstOrDefault();
        int rowCount = dc.reportsSents.Count();

        if (rec != null)
            {

            for(int i = 0; i <= rowCount;)
                {

                    var matchedCaseNumber = (from CaseNumberKey in dc.GetTable<reportsSent>()
                                     select CaseNumberKey).FirstOrDefault();

                    (new MyReportRenderer()).RenderTest(Convert.ToString(matchedCaseNumber));

                    dc.reportsSents.DeleteOnSubmit(matchedCaseNumber);
                    dc.SubmitChanges();

                    i = (i +1);

                }

             }
</code>```

When the code above is executed I get this error:

Value cannot be null. Parameter name:
  entity

and matchedCaseNumber is highlighted in this line:

dc.reportsSents.DeleteOnSubmit(matchedCaseNumber);

What does this mean and why am I getting it.  What I am trying to do is pass MatchedCaseNumber to the method and then delete it after the method is executed and then step through the table.  Any help would be appreciated.

Thanks.

答:
matchedCaseNumber is probably null when passed to DeleteOnSubmit

```<code>if(matchedCaseNumber != null)
{
  dc.reportsSents.DeleteOnSubmit(matchedCaseNumber);
  dc.SubmitChanges();
}
</code>```

EDIT:
If I understand correctly what you're trying to do, this would be better:

```<code>private void button1_Click(object sender, EventArgs e)
{

    DataClasses1DataContext dc = new DataClasses1DataContext();

    foreach (var item in dc.reportsSents)
    {
        (new MyReportRenderer()).RenderTest(Convert.ToString(item));
        dc.reportsSents.DeleteOnSubmit(item);
    }
    dc.SubmitChanges();
}
</code>```

Body:
        private void button1_Click(object sender, EventArgs e)
    {

        DataClasses1DataContext dc = new DataClasses1DataContext();
        var rec = dc.reportsSents.FirstOrDefault();
        int rowCount = dc.reportsSents.Count();

        if (rec != null)
            {

            for(int i = 0; i <= rowCount;)
                {

                    var matchedCaseNumber = (from CaseNumberKey in dc.GetTable<reportsSent>()
                                     select CaseNumberKey).FirstOrDefault();

                    (new MyReportRenderer()).RenderTest(Convert.ToString(matchedCaseNumber));

                    dc.reportsSents.DeleteOnSubmit(matchedCaseNumber);
                    dc.SubmitChanges();

                    i = (i +1);

                }

             }

When the code above is executed I get this error:

Value cannot be null. Parameter name:
  entity

and matchedCaseNumber is highlighted in this line:

dc.reportsSents.DeleteOnSubmit(matchedCaseNumber);

What does this mean and why am I getting it.  What I am trying to do is pass MatchedCaseNumber to the method and then delete it after the method is executed and then step through the table.  Any help would be appreciated.

Thanks.

Body:
matchedCaseNumber is probably null when passed to DeleteOnSubmit

if(matchedCaseNumber != null)
{
  dc.reportsSents.DeleteOnSubmit(matchedCaseNumber);
  dc.SubmitChanges();
}

EDIT:
If I understand correctly what you're trying to do, this would be better:

private void button1_Click(object sender, EventArgs e)
{

    DataClasses1DataContext dc = new DataClasses1DataContext();

    foreach (var item in dc.reportsSents)
    {
        (new MyReportRenderer()).RenderTest(Convert.ToString(item));
        dc.reportsSents.DeleteOnSubmit(item);
    }
    dc.SubmitChanges();
}


问:
Dockerfile execution permission denied
I have this dockerfile

```<code>FROM alpine:3.8
ENV LANG C.UTF-8
RUN set -x && \
    apk add --no-cache \
              openrc \
              bash \
              libreswan \
              xl2tpd \
              ppp \
    && mkdir -p /var/run/pluto \
    && mkdir -p /var/run/xl2tpd \
    && touch /var/run/xl2tpd/l2tp-control
COPY ipsec.conf /etc/ipsec.conf
COPY ipsec.secrets /etc/ipsec.secrets
COPY xl2tpd.conf /etc/xl2tpd/xl2tpd.conf
COPY options.l2tpd.client /etc/ppp/options.l2tpd.client
COPY startup.sh /
RUN ["chmod", "+x", "/startup.sh"]

CMD ["./startup.sh"]
</code>```

When I run that in local everything works ok. but I'm trying to execute the image generated in a gcp vm (ubuntu) and I get the following error

```<code>/bin/sh: can't open './startup.sh': Permission denied
</code>```

Can someone help me with this error?

note: I also tried to modify permissions with:

```<code>RUN ["chmod", "777", "/startup.sh"]
RUN chmod +x /startup.sh
RUN chmod 777 /startup.sh
</code>```

And execute the script with:

```<code>ENTRYPOINT ["./startup.sh"]
RUN ["./startup.sh"]
RUN ./startup.sh
</code>```

答:
Try this add these lines in your docker file.

```<code>RUN chown -R admin:admin /
RUN chmod 755 /
</code>```

Just give the Admin rights to / root directory.

and your docker file will look like this

```<code>FROM alpine:3.8
ENV LANG C.UTF-8
RUN set -x && \
    apk add --no-cache \
              openrc \
              bash \
              libreswan \
              xl2tpd \
              ppp \
    && mkdir -p /var/run/pluto \
    && mkdir -p /var/run/xl2tpd \
    && touch /var/run/xl2tpd/l2tp-control
COPY ipsec.conf /etc/ipsec.conf
COPY ipsec.secrets /etc/ipsec.secrets
COPY xl2tpd.conf /etc/xl2tpd/xl2tpd.conf
COPY options.l2tpd.client /etc/ppp/options.l2tpd.client
COPY startup.sh /
RUN chown -R admin:admin /
RUN chmod 755 /
CMD ["./startup.sh"]
</code>```

Title: Dockerfile execution permission denied

Body:
I have this dockerfile

FROM alpine:3.8
ENV LANG C.UTF-8
RUN set -x && \
    apk add --no-cache \
              openrc \
              bash \
              libreswan \
              xl2tpd \
              ppp \
    && mkdir -p /var/run/pluto \
    && mkdir -p /var/run/xl2tpd \
    && touch /var/run/xl2tpd/l2tp-control
COPY ipsec.conf /etc/ipsec.conf
COPY ipsec.secrets /etc/ipsec.secrets
COPY xl2tpd.conf /etc/xl2tpd/xl2tpd.conf
COPY options.l2tpd.client /etc/ppp/options.l2tpd.client
COPY startup.sh /
RUN ["chmod", "+x", "/startup.sh"]

CMD ["./startup.sh"]

When I run that in local everything works ok. but I'm trying to execute the image generated in a gcp vm (ubuntu) and I get the following error

/bin/sh: can't open './startup.sh': Permission denied

Can someone help me with this error?

note: I also tried to modify permissions with:

RUN ["chmod", "777", "/startup.sh"]
RUN chmod +x /startup.sh
RUN chmod 777 /startup.sh

And execute the script with:

ENTRYPOINT ["./startup.sh"]
RUN ["./startup.sh"]
RUN ./startup.sh

Body:
Try this add these lines in your docker file.

RUN chown -R admin:admin /
RUN chmod 755 /

Just give the Admin rights to / root directory.

and your docker file will look like this

FROM alpine:3.8
ENV LANG C.UTF-8
RUN set -x && \
    apk add --no-cache \
              openrc \
              bash \
              libreswan \
              xl2tpd \
              ppp \
    && mkdir -p /var/run/pluto \
    && mkdir -p /var/run/xl2tpd \
    && touch /var/run/xl2tpd/l2tp-control
COPY ipsec.conf /etc/ipsec.conf
COPY ipsec.secrets /etc/ipsec.secrets
COPY xl2tpd.conf /etc/xl2tpd/xl2tpd.conf
COPY options.l2tpd.client /etc/ppp/options.l2tpd.client
COPY startup.sh /
RUN chown -R admin:admin /
RUN chmod 755 /
CMD ["./startup.sh"]


问:
Golang concurrent R/W to database
I'm writing some Go software that is responsible for downloading and parsing a large number of JSON files and writing that parsed data to a sqlite database. My current design has 10 go routines simultaneously downloading/parsing these JSONs and communicating them to another go routine whose sole job is to listen on a specific channel and write the channel contents to the DB.

The system does some additional read operations after all writing should have been completed, which leads to an issue where queries return incorrect results because not all of the data has been written to the table. Because the JSON data I'm pulling is dynamic, I have no easy way to know when all the data has been written.

I've considered two possibilities for solving this, though I'm not super happy with either solution:

Listen on the channel and wait for it to be empty. This should work in principle, however, it does not ensure that the data has been written, all it ensures is it's been received on the channel.

Synchronize access to the DB. This again should work in principle, however, I would still need to order the query operation to be after all the write operations.

Are there any other design decisions I should consider to rectify this issue? For reference the libraries I'm using to pull this data are go-colly and the go-sqlite3. Appreciate all the help!

答:
You can use a sync.WaitGroup

e.g.

package main

import "sync"

func main() {
    // Some sort of job queue for your workers to process. This job queue should be closed by the process
    // that populates it with items. Once the job channel is closed, any for loops ranging over the channel
    // will read items until there are no more items, and then break.
    jobChan := make(chan JobInfo)

    // Populate the job queue here...
    // ...
    close(jobChan)

    // We now have a full queue of jobs that can't accept new jobs because the channel is closed.

    // Number of concurrent workers.
    workerCount := 10

    // Initialize the WaitGroup.
    wg := sync.WaitGroup{}
    wg.Add(workerCount)

    // Create the worker goroutines.
    for i := 0; i < workerCount; i++ {
        go func() {
            // When the jobChan is closed, and no more jobs are available on the queue, the for loop
            // will exit, causing wg.Done() to be called, and the anonymous function to exit.
            for job := range jobChan {
                // Process job.
            }
            wg.Done()
        }()
    }

    // Wait for all workers to call wg.Done()
    wg.Wait()

    // Whatever you want to do after all queue items have been processed goes here.
    // ...
}
```

Title: Golang concurrent R/W to database


问:
UseState to update multiple properties in object array
Using destructuring, I can update multiple object properties with one function:

```<code>const [serverRequest, setServerRequest] = useState({ ID: "", RAM: "", CPU: "", appInstaller: [{}] });

return (
  <div className="App">
    <label className="label">ID</label>
    <input
      className="input"
      type="text"
      name="ID"
      value={serverRequest?.ID}
      onChange={e =>
        setServerRequest({
          ...serverRequest,
          ID: e.target.value
        })
      }
    />
    <input
      className="input"
      type="text"
      name="RAM"
      value={serverRequest?.RAM}
      onChange={e =>
        setServerRequest({
          ...serverRequest,
          RAM: e.target.value
        })
      }
    />
  </div>
);
</code>```

However, I'd like to do this on a object array. How can I do this?

Using

```<code>const [serverRequests, setServerRequests] = useState([{ ID: "", RAM: "", CPU: "", appInstaller: [{}] }]);
const [selectedServer, setSelectedServer] = useState(0);

onChange={e =>
  setServerRequests({
    ...serverRequests[selectedServer],
    ID: e.target.value
  })
}
</code>```

Will convert the array into a single object on the first change, and then remove all other properties on the second change.

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

```<code>onChange={e =>
  setServerRequests(oldValue => {
    // first spread value
    oldValue[selectedServer] = {
      ...oldValue[selectedServer],
      ID: e.target.value
    }

    // and now spread and return array
    return [...oldValue]
  })
}
</code>```

Body:
Using destructuring, I can update multiple object properties with one function:

const [serverRequest, setServerRequest] = useState({ ID: "", RAM: "", CPU: "", appInstaller: [{}] });

return (

    ID
    <input
      className="input"
      type="text"
      name="ID"
      value={serverRequest?.ID}
      onChange={e =>
        setServerRequest({
          ...serverRequest,
          ID: e.target.value
        })
      }
    />
    <input
      className="input"
      type="text"
      name="RAM"
      value={serverRequest?.RAM}
      onChange={e =>
        setServerRequest({
          ...serverRequest,
          RAM: e.target.value
        })
      }
    />

);

However, I'd like to do this on a object array. How can I do this?

Using

const [serverRequests, setServerRequests] = useState([{ ID: "", RAM: "", CPU: "", appInstaller: [{}] }]);
const [selectedServer, setSelectedServer] = useState(0);

onChange={e =>
  setServerRequests({
    ...serverRequests[selectedServer],
    ID: e.target.value
  })
}

Will convert the array into a single object on the first change, and then remove all other properties on the second change.

Body:
you can do something like this

onChange={e =>
  setServerRequests(oldValue => {
    // first spread value
    oldValue[selectedServer] = {
      ...oldValue[selectedServer],
      ID: e.target.value
    }

    // and now spread and return array
    return [...oldValue]
  })
}


问:
Getting accurate file size in megabytes?
How can I get the accurate file size in MB? I tried this:

```<code>compressed_file_size = File.size("Compressed/#{project}.tar.bz2") / 1024000

puts "file size is #{compressed_file_size} MB"
</code>```

But it chopped the 0.9 and showed 2 MB instead of 2.9 MB

答:
Try:</p>

```<code>compressed_file_size = File.size("Compressed/#{project}.tar.bz2").to_f / 1024000
</code>```

Body:
How can I get the accurate file size in MB? I tried this:

compressed_file_size = File.size("Compressed/#{project}.tar.bz2") / 1024000

puts "file size is #{compressed_file_size} MB"

But it chopped the 0.9 and showed 2 MB instead of 2.9 MB

Body:
Try:

compressed_file_size = File.size("Compressed/#{project}.tar.bz2").to_f / 1024000


问:
My basic redux store does not console.log state changes
I am currently working on NetNinja's redux playlist. Unfortunately, I've hit an issue that I'm struggling to overcome. I started working on dispatching multiple actions to my reducer, and now I can no longer get my store.subscribe method to execute a console.log of updated state. I've spent about 40 minutes trying to sole the issue, and any help would be very appreciated.

Here is a direct link to the CodePen I am working on: https://codepen.io/davidreke/pen/MWKWYdd

If you prefer, here is my code in Stack Overflow

const {
  createStore
} = Redux;

console.log('the basics work')

const initState = {
  todos: [],
  posts: []
}
// 2. add a spread operator to include all the state in a reducer
function myReducer(state = initState, action) {
  if (action.type == 'ADD_TODO') {
    return {
      ...state,
      todos: [...state.todos, action.todo]
    }

    if (action.type == 'ADD_POST') {
      return {
        ...state,
        posts: [...state.posts, action.post]
      }
    }
  }

  const store = createStore(myReducer)

  // 1. add a subscription to the store and then preview it in the console.log

  store.subscribe(() => {
    console.log('state updated');
    console.log(store.getState())
  })

  store.dispatch({
    type: 'ADD_TODO',
    todo: 'sleep some more'
  })

  store.dispatch({
    type: 'ADD_TODO',
    todo: 'prepare node.js'
  })

  store.dispatch({
    type: 'ADD_POST',
    post: 'Hello world!'
  })```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/redux/4.0.5/redux.min.js"></script></code>```

答:
I was missing a curly bracket in my reducer function that broke the code.</p>

```<code>function myreducer(state = initState, action){
  if (action.type =='ADD_TODO') {
    return {
      ...state,
      todos: [...state.todos, action.todo]
    }
  }

  if (action.type =='ADD_POST') {
    return {
      ...state,
      posts: [...state.posts, action.post]
    }
  }
}
</code>```

Body:
I was missing a curly bracket in my reducer function that broke the code.

function myreducer(state = initState, action){
  if (action.type =='ADD_TODO') {
    return {
      ...state,
      todos: [...state.todos, action.todo]
    }
  }

  if (action.type =='ADD_POST') {
    return {
      ...state,
      posts: [...state.posts, action.post]
    }
  }
}


问:
How to properly use the predict function in R
First I'm going to give you some starter code:

```<code>library(ggplot2)

y = c(0, 0, 1, 2, 0,  0, 1,  3,  0,  0,  3, 0, 6, 2, 8, 16, 21, 39, 48, 113, 92, 93 ,127, 159, 137, 46, 238, 132 ,124, 185 ,171, 250, 250 ,187, 119 ,151, 292,  94, 281, 146, 163 ,104, 156, 272, 273, 212, 210, 135, 187, 208, 310, 276 ,235, 246, 190, 232, 254, 446,
314, 402 ,276, 279, 386 ,402, 238, 581, 434, 159, 261, 356, 440, 498, 495, 462 ,306, 233, 396, 331, 418, 293 ,431 ,300, 222, 222, 479 ,501, 702
,790, 681)
x = 1:length(y)
</code>```

Now, I'm trying to predict the 90th data point will be using polynomial regression, wherein the data, #1 is 0, and #89 is 681. I've tested my model and I've decided that a polynomial curve to the 8th degree is the perfect fit.

I've tried the code predict(formula=y~poly(x,8),90) and it's giving some strange error (which doesn't make sense to me) about how there is no applicable method.

```<code>Error in UseMethod("predict") :
  no applicable method for 'predict' applied to an object of class "c('double', 'numeric')"
</code>```

Why doesn't this work? After scouring countless R documentations, blogs and forums, it seemed to me that this should work properly.

What does work, instead? I've tried other ways of using the predict method, and I think that this is the closest solution to what I want: The predicted value for the 90th data point.

Any other suggestions? I'm not sure that my model is the best, and I would welcome any suggestions you may have. For example, you may argue that it's better to use a 6th degree than an 8th degree polynomial for modeling, and if you have a valid reason, I would agree with you.

Thank you!

NOTE: Please, PLEASE don't remove the thanks. I know some Stack Overflowers hate it, but I feel it gives a personal touch.

答:
predict works on models. You have a formula, but not a model. You need to fit a model first, and then predict on that.

Usually this is done in two steps, because usually people want to save the model so it can be used for more than just a single prediction - perhaps to examine coefficients, check assumptions, get model fit diagnostics, make a different prediction - without re-fitting the model.

Here I'll use the simplest model that can take your formula, lm, which stands for "linear model". You could also use a GLM, or loess, or a random forest, a GAM, a neural net, or ... many many many different models.

```<code>my_model = lm(formula=y~poly(x,8))
predict(my_model, newdata = list(x = 90))
#        1
# 977.9421
</code>```

You could, of course, combine this into a single line, never bothering to save and name my_model:

```<code>predict(lm(formula=y~poly(x,8)), newdata = list(x = 90))
</code>```

I'm not sure that my model is the best,

It's not. Almost certainly. But that's okay - it's very hard to know that a model is best in any sense of the word.

and I would welcome any suggestions you may have. For example, you may argue that it's better to use a 6th degree than an 8th degree polynomial for modeling,

I don't think I've ever seen an 8th degree polynomial used. (Or even 6th.) It's absurdly high. I have no idea what your data is, so I can't say much. If you have a reason to think that 8th degree polynomial is accurate, then go for it. But if you just want to fit a wiggly curve and extrapolate forward a tiny bit, then a cubic spline using mgcv::gam or a stats::loess model would be a much more standard choice.

Body:
First I'm going to give you some starter code:

library(ggplot2)

y = c(0, 0, 1, 2, 0,  0, 1,  3,  0,  0,  3, 0, 6, 2, 8, 16, 21, 39, 48, 113, 92, 93 ,127, 159, 137, 46, 238, 132 ,124, 185 ,171, 250, 250 ,187, 119 ,151, 292,  94, 281, 146, 163 ,104, 156, 272, 273, 212, 210, 135, 187, 208, 310, 276 ,235, 246, 190, 232, 254, 446,
314, 402 ,276, 279, 386 ,402, 238, 581, 434, 159, 261, 356, 440, 498, 495, 462 ,306, 233, 396, 331, 418, 293 ,431 ,300, 222, 222, 479 ,501, 702
,790, 681)
x = 1:length(y)

Now, I'm trying to predict the 90th data point will be using polynomial regression, wherein the data, #1 is 0, and #89 is 681. I've tested my model and I've decided that a polynomial curve to the 8th degree is the perfect fit.

I've tried the code predict(formula=y~poly(x,8),90) and it's giving some strange error (which doesn't make sense to me) about how there is no applicable method.

Error in UseMethod("predict") :
  no applicable method for 'predict' applied to an object of class "c('double', 'numeric')"

Why doesn't this work? After scouring countless R documentations, blogs and forums, it seemed to me that this should work properly.

What does work, instead? I've tried other ways of using the predict method, and I think that this is the closest solution to what I want: The predicted value for the 90th data point.

Any other suggestions? I'm not sure that my model is the best, and I would welcome any suggestions you may have. For example, you may argue that it's better to use a 6th degree than an 8th degree polynomial for modeling, and if you have a valid reason, I would agree with you.

Thank you!

NOTE: Please, PLEASE don't remove the thanks. I know some Stack Overflowers hate it, but I feel it gives a personal touch.

Body:
predict works on models. You have a formula, but not a model. You need to fit a model first, and then predict on that.

Usually this is done in two steps, because usually people want to save the model so it can be used for more than just a single prediction - perhaps to examine coefficients, check assumptions, get model fit diagnostics, make a different prediction - without re-fitting the model.

Here I'll use the simplest model that can take your formula, lm, which stands for "linear model". You could also use a GLM, or loess, or a random forest, a GAM, a neural net, or ... many many many different models.

my_model = lm(formula=y~poly(x,8))
predict(my_model, newdata = list(x = 90))
#        1
# 977.9421

You could, of course, combine this into a single line, never bothering to save and name my_model:

predict(lm(formula=y~poly(x,8)), newdata = list(x = 90))

I'm not sure that my model is the best,

It's not. Almost certainly. But that's okay - it's very hard to know that a model is best in any sense of the word.

and I would welcome any suggestions you may have. For example, you may argue that it's better to use a 6th degree than an 8th degree polynomial for modeling,

I don't think I've ever seen an 8th degree polynomial used. (Or even 6th.) It's absurdly high. I have no idea what your data is, so I can't say much. If you have a reason to think that 8th degree polynomial is accurate, then go for it. But if you just want to fit a wiggly curve and extrapolate forward a tiny bit, then a cubic spline using mgcv::gam or a stats::loess model would be a much more standard choice.


问:
Django media files not showing with Debug = False on production - Django 1.10
I currently have two kind of files static files and media files.The static files contain my css,js and other static content. The media files contain stuff that the user uploads.The static folder is right next to the media folder.Now on my deployed machine. If I set the DEBUG = False my static files are presented just fine however my media content is never displayed. I get a 404 not found error.
My quuestion is how do I display media content in production environment when DEBUG = False. With DEBUG= True everything seems to work fine ? I read the following page and tried these things out.

1-Tried creating a separate folder for static media just like static content.
Currently my static content is being managed by the collectstatic command. I am using apache on webfaction.I have a static folder called static_content when I ran ./manage.py collectstatic all of my content in static folder was copied to the static_content folder.I tried creating another static folder called static_media. However when I ran ./manage.py collectstatic the content of my media folder got copied to static_content and not to static_media like it should have. Can anyone tell me why the collectstatic command did not paste the content to static_media instead ?

This is what my configuration looks like

```<code>ALLOWED_HOSTS = [
   "*",
   'mywebsite.com',
   'www.mywebsite.com.com',
]

STATIC_URL = 'http://mywebsite.com.com/static/'
STATIC_ROOT = '/home/admin/webapps/static_content'
STATICFILES_DIRS = (
                        '/home/admin/webapps/mainfolder/mainapp/static',
                        '/home/admin/webapps/mainfolder/mainapp/media',
                   )
PROJECT_PATH = os.path.join(BASE_DIR, 'static')

MEDIA_URL = 'http://mywebsite.com.com/media/'
MEDIA_ROOT = '/home/admin/webapps/static_media'
</code>```

This is what my urls.py looks like

```<code>admin.autodiscover()
urlpatterns = [
....
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
</code>```

Am I using the correct approach creating a separate folder for managing my media content just like for my static content for when DEBUG=False ? If so then why is collectstatic command dumping all my media content into my static_content folder instead of static_media folder ? Also if I use a static folder for managing my media content when a user uploads data where will that be uploaded to media or static_media.

答:
In Pythonanywhere server
Just
add Static file url and Directory

URL

/static/

/media/

Directory path

/home/taukir707/myblog/static

/home/taukir707/myblog/media

Body:
I currently have two kind of files static files and media files.The static files contain my css,js and other static content. The media files contain stuff that the user uploads.The static folder is right next to the media folder.Now on my deployed machine. If I set the DEBUG = False my static files are presented just fine however my media content is never displayed. I get a 404 not found error.
My quuestion is how do I display media content in production environment when DEBUG = False. With DEBUG= True everything seems to work fine ? I read the following page and tried these things out.

1-Tried creating a separate folder for static media just like static content.
Currently my static content is being managed by the collectstatic command. I am using apache on webfaction.I have a static folder called static_content when I ran ./manage.py collectstatic all of my content in static folder was copied to the static_content folder.I tried creating another static folder called static_media. However when I ran ./manage.py collectstatic the content of my media folder got copied to static_content and not to static_media like it should have. Can anyone tell me why the collectstatic command did not paste the content to static_media instead ?

This is what my configuration looks like

ALLOWED_HOSTS = [
   "*",
   'mywebsite.com',
   'www.mywebsite.com.com',
]

STATIC_URL = 'http://mywebsite.com.com/static/'
STATIC_ROOT = '/home/admin/webapps/static_content'
STATICFILES_DIRS = (
                        '/home/admin/webapps/mainfolder/mainapp/static',
                        '/home/admin/webapps/mainfolder/mainapp/media',
                   )
PROJECT_PATH = os.path.join(BASE_DIR, 'static')

MEDIA_URL = 'http://mywebsite.com.com/media/'
MEDIA_ROOT = '/home/admin/webapps/static_media'

This is what my urls.py looks like

admin.autodiscover()
urlpatterns = [
....
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Am I using the correct approach creating a separate folder for managing my media content just like for my static content for when DEBUG=False ? If so then why is collectstatic command dumping all my media content into my static_content folder instead of static_media folder ? Also if I use a static folder for managing my media content when a user uploads data where will that be uploaded to media or static_media.


问:
Methode sendMessageViaCloudSync strike through in codename one
im working with codenameone and i was trying to send an email via codenameone cloud when updating dog table everything works fine but its not sending any mail  I got strikethrough on the method sendMessageViaCloudSync() I know that means this methodes is replaced but I cant find any documentation so whats the new methodes and how can I work with it ?

```<code>public void updateDog(int id,int note) {
       Dialog d=new Dialog();
         if(d.show("Noter chien","vous voulez vraiment attribuer cette note?","Oui","Non"))
            {
                String url=Statics.BASE_URL+"/api/chiens/notechien/"+id+"/"+note;
                req.setUrl(url);
                NetworkManager.getInstance().addToQueueAndWait(req);
                Message m = new Message("<html><body>Check out <a href=\"https://www.codenameone.com/\">Codename One</a></body></html>");

                m.setMimeType(Message.MIME_HTML);

                boolean success = m.sendMessageViaCloudSync("Codename One", "louay.gourrida@esprit.tn", "Name Of User", "Message Subject",

                            "Check out Codename One at https://www.codenameone.com/");

        /*
                Message m = new Message("Hello \nWe want to inform you that your dog just got a new rating open Mobile app and check out");

                Display.getInstance().sendMessage(new String[] {"louay.gourrida@esprit.tn"}, "New Rating", m);
                */
                d.dispose();
            }

    }
</code>```

that the function that updates dog table and send the email

答:
When you hover over a method that's deprecated you should get a hint that includes the suggested alternative.

In this case we removed the method entirely since the concept was problematic. It caused spam issues where outgoing emails were sent to spam folders.

As a replacement we introduced the SendGrid cn1lib which you can use to send emails via sendgrid.

Body:
im working with codenameone and i was trying to send an email via codenameone cloud when updating dog table everything works fine but its not sending any mail  I got strikethrough on the method sendMessageViaCloudSync() I know that means this methodes is replaced but I cant find any documentation so whats the new methodes and how can I work with it ?

public void updateDog(int id,int note) {
       Dialog d=new Dialog();
         if(d.show("Noter chien","vous voulez vraiment attribuer cette note?","Oui","Non"))
            {
                String url=Statics.BASE_URL+"/api/chiens/notechien/"+id+"/"+note;
                req.setUrl(url);
                NetworkManager.getInstance().addToQueueAndWait(req);
                Message m = new Message("Check out Codename One");

                m.setMimeType(Message.MIME_HTML);

                boolean success = m.sendMessageViaCloudSync("Codename One", "louay.gourrida@esprit.tn", "Name Of User", "Message Subject",

                            "Check out Codename One at https://www.codenameone.com/");

        /*
                Message m = new Message("Hello \nWe want to inform you that your dog just got a new rating open Mobile app and check out");

                Display.getInstance().sendMessage(new String[] {"louay.gourrida@esprit.tn"}, "New Rating", m);
                */
                d.dispose();
            }

    }

that the function that updates dog table and send the email


问:
Get a variable from SimpleXMLElement
How can I select the variable from this SimpleXMLElement?

If I type:

```<code>var_dump($var);
</code>```

I get:

```<code>object(SimpleXMLElement)#7423 (2) {["@attributes"]=>array(1) {["type"]=>string(3) "119"}[0]=>string(12) "10869715.jpg"}
</code>```

I need to get the result like "10869715.jpg".

Thanks!

答:
If I read your dump correctly, you don't need to do something special because your item is the top level item.

```<code><?php

$xml = "
<item type='119'>10869715.jpg</item>
";

$element = new SimpleXMLElement($xml);

echo ($element);
</code>```

This would output:

```<code>10869715.jpg
</code>```

Title: Get a variable from SimpleXMLElement

Body:
How can I select the variable from this SimpleXMLElement?

If I type:

var_dump($var);

I get:

object(SimpleXMLElement)#7423 (2) {["@attributes"]=>array(1) {["type"]=>string(3) "119"}[0]=>string(12) "10869715.jpg"}

I need to get the result like "10869715.jpg".

Thanks!

Body:
If I read your dump correctly, you don't need to do something special because your item is the top level item.

<?php

$xml = "
<item type='119'>10869715.jpg</item>
";

$element = new SimpleXMLElement($xml);

echo ($element);

This would output:

10869715.jpg


问:
Stopping scripters from slamming your website

I've accepted an answer, but sadly, I believe we're stuck with our original worst case scenario: CAPTCHA everyone on purchase attempts of the crap. Short explanation: caching / web farms make it impossible to track hits, and any workaround (sending a non-cached web-beacon, writing to a unified table, etc.) slows the site down worse than the bots would. There is likely some pricey hardware from Cisco or the like that can help at a high level, but it's hard to justify the cost if CAPTCHA-ing everyone is an alternative. I'll attempt a more full explanation later, as well as cleaning this up for future searchers (though others are welcome to try, as it's community wiki).

Situation

This is about the bag o' crap sales on woot.com. I'm the president of Woot Workshop, the subsidiary of Woot that does the design, writes the product descriptions, podcasts, blog posts, and moderates the forums. I work with CSS/HTML and am only barely familiar with other technologies. I work closely with the developers and have talked through all of the answers here (and many other ideas we've had).

Usability is a massive part of my job, and making the site exciting and fun is most of the rest of it. That's where the three goals below derive. CAPTCHA harms usability, and bots steal the fun and excitement out of our crap sales.

Bots are slamming our front page tens of times a second screen scraping (and/or scanning our RSS) for the Random Crap sale. The moment they see that, it triggers a second stage of the program that logs in, clicks I want One, fills out the form, and buys the crap.

Evaluation

lc: On stackoverflow and other sites that use this method, they're almost always dealing with authenticated (logged in) users, because the task being attempted requires that.

On Woot, anonymous (non-logged) users can view our home page. In other words, the slamming bots can be non-authenticated (and essentially non-trackable except by IP address).

So we're back to scanning for IPs, which a) is fairly useless in this age of cloud networking and spambot zombies and b) catches too many innocents given the number of businesses that come from one IP address (not to mention the issues with non-static IP ISPs and potential performance hits to trying to track this).

Oh, and having people call us would be the worst possible scenario. Can we have them call you?

BradC: Ned Batchelder's methods look pretty cool, but they're pretty firmly designed to defeat bots built for a network of sites. Our problem is bots are built specifically to defeat our site. Some of these methods could likely work for a short time until the scripters evolved their bots to ignore the honeypot, screen-scrape for nearby label names instead of form ids, and use a javascript-capable browser control.

lc again: "Unless, of course, the hype is part of your marketing scheme." Yes, it definitely is. The surprise of when the item appears, as well as the excitement if you manage to get one is probably as much or more important than the crap you actually end up getting. Anything that eliminates first-come/first-serve is detrimental to the thrill of 'winning' the crap.

novatrust: And I, for one, welcome our new bot overlords. We actually do offer RSSfeeds to allow 3rd party apps to scan our site for product info, but not ahead of the main site HTML. If I'm interpreting it right, your solution does help goal 2 (performance issues) by completely sacrificing goal 1, and just resigning the fact that bots will be buying most of the crap. I up-voted your response, because your last paragraph pessimism feels accurate to me. There seems to be no silver bullet here.

The rest of the responses generally rely on IP tracking, which, again, seems to both be useless (with botnets/zombies/cloud networking) and detrimental (catching many innocents who come from same-IP destinations).

Any other approaches / ideas? My developers keep saying "let's just do CAPTCHA" but I'm hoping there's less intrusive methods to all actual humans wanting some of our crap.

Original question

Say you're selling something cheap that has a very high perceived value, and you have a very limited amount. No one knows exactly when you will sell this item. And over a million people regularly come by to see what you're selling.

You end up with scripters and bots attempting to programmatically [a] figure out when you're selling said item, and [b] make sure they're among the first to buy it. This sucks for two reasons:

Your site is slammed by non-humans, slowing everything down for everyone.

The scripters end up 'winning' the product, causing the regulars to feel cheated.

A seemingly obvious solution is to create some hoops for your users to jump through before placing their order, but there are at least three problems with this:

The user experience sucks for humans, as they have to decipher CAPTCHA, pick out the cat, or solve a math problem.

If the perceived benefit is high enough, and the crowd large enough, some group will find their way around any tweak, leading to an arms race. (This is especially true the simpler the tweak is; hidden 'comments' form, re-arranging the form elements, mis-labeling them, hidden 'gotcha' text all will work once and then need to be changed to fight targeting this specific form.)

Even if the scripters can't 'solve' your tweak it doesn't prevent them from slamming your front page, and then sounding an alarm for the scripter to fill out the order, manually. Given they get the advantage from solving [a], they will likely still win [b] since they'll be the first humans reaching the order page. Additionally, 1. still happens, causing server errors and a decreased performance for everyone.

Another solution is to watch for IPs hitting too often, block them from the firewall, or otherwise prevent them from ordering. This could solve 2. and prevent [b] but the performance hit from scanning for IPs is massive and would likely cause more problems like 1. than the scripters were causing on their own. Additionally, the possibility of cloud networking and spambot zombies makes IP checking fairly useless.

A third idea, forcing the order form to be loaded for some time (say, half a second) would potentially slow the progress of the speedy orders, but again, the scripters would still be the first people in, at any speed not detrimental to actual users.

Goals

Sell the item to non-scripting humans.

Keep the site running at a speed not slowed by bots.

Don't hassle the 'normal' users with any tasks to complete to prove they're human.

答:
If I understand right, your biggest problem is with the screen scraping, not the automated purchase itself.

If so, your most effective step would be to defeat screen scraping by randomly encoding the page so that it look the same (kind of) but is always different at code level. (use hex codes, java encoding, pictures, change surrounding code structure...)

That would force them to constantly rewrite their scraping code and therefore make it that much more expensive for them to buy your "crap" automatically. If they can manage. They would probably continue to hit your website for a while until they realize they can't gain anything from it and drop it.

The downside of confusing the hell out of bots is that it will also confuse the hell out of search engine crawlers.

OwnerDisplayName: davebug

LastEditorDisplayName: Jeff Atwood

OwnerDisplayName: Sylverdrag

ContentLicense: CC BY-SA 2.5


问:
MySQL update with subselect too slow
Having an issue with an update query taking more than 20 minutes (I kill it after that).

Scenario:

Table one has some 300K records.

Table two contains the same set of records (copied over), but with an extra field that needs to contain the id of the record that matches a number of fields, and has the highest value of another (a score). To clarify, the end result should be table two containing 300K records with each record having the id of another record that has the same set of basic properties, and the highest score within the set of records with those properties.

The below completes in ~5s when I only copy 2K records instead of the full 300k records into table two.

UPDATE vtable2 v1 SET v1.buddy = (
    SELECT v2.id FROM vtable1 v2
    WHERE
    v2.group_id = v1.group_id AND
    // 6 more basic comparisons
    ORDER BY score DESC LIMIT 1
)
```

I need to find buddies for the full 300K records. All fields involved in joining and sorting have indexes.

Help much appreciated.

答:
You can use an exclusion join to find the row in vtable1 such that no other row in vtable1 with a higher score can be found.

```<code>UPDATE vtable2 AS v1
INNER JOIN vtable1 AS v2a ON v1.group_id = v2a.group_id AND (...conditions...)
LEFT OUTER JOIN vtable1 AS v2b ON v1.group_id = v2b.group_id
  AND v2a.score < v2b.score AND (...conditions...)
SET v1.buddy = v2.id
WHERE v2b.group_id IS NULL;
</code>```

You do have to duplicate all the other conditions in the expression for the outer join; you can't put them into the WHERE clause.

Title: MySQL update with subselect too slow

Body:
Having an issue with an update query taking more than 20 minutes (I kill it after that).

Scenario:

Table one has some 300K records.

Table two contains the same set of records (copied over), but with an extra field that needs to contain the id of the record that matches a number of fields, and has the highest value of another (a score). To clarify, the end result should be table two containing 300K records with each record having the id of another record that has the same set of basic properties, and the highest score within the set of records with those properties.

The below completes in ~5s when I only copy 2K records instead of the full 300k records into table two.

UPDATE vtable2 v1 SET v1.buddy = (
    SELECT v2.id FROM vtable1 v2
    WHERE
    v2.group_id = v1.group_id AND
    // 6 more basic comparisons
    ORDER BY score DESC LIMIT 1
)

I need to find buddies for the full 300K records. All fields involved in joining and sorting have indexes.

Help much appreciated.

Body:
You can use an exclusion join to find the row in vtable1 such that no other row in vtable1 with a higher score can be found.

UPDATE vtable2 AS v1
INNER JOIN vtable1 AS v2a ON v1.group_id = v2a.group_id AND (...conditions...)
LEFT OUTER JOIN vtable1 AS v2b ON v1.group_id = v2b.group_id
  AND v2a.score < v2b.score AND (...conditions...)
SET v1.buddy = v2.id
WHERE v2b.group_id IS NULL;

You do have to duplicate all the other conditions in the expression for the outer join; you can't put them into the WHERE clause.


问:
VSCode Chrome Debugger disable web security
I'm developing a remote application which need the web security disabled on Chrome, which I have a windows shortcut that takes the following runtime argument:

```<code>"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" -incognito --disable-web-security --user-data-dir=C:\Program
</code>```

For vscode, I have the following launch.json

```<code>{
    "version": "0.2.0",
    "configurations": [
        {
            "type": "chrome",
            "request": "launch",
            "name": "web-security-disabled-chrome",
            "url": "http://localhost:8000",
            "runtimeArgs": [
                "--disable-web-security --user-data-dir=C:\\Program",
                "-incognito"
            ],
            "webRoot": "${workspaceFolder}"
        }
    ]
}
</code>```

and it doesn't disable web-security.

```<code>Failed to load resource: net::ERR_CERT_AUTHORITY_INVALID [https://my.remote.ip/restapp/...
</code>```

I also tried the following:

Give vscode a new directory for user data. I saw the folder got populated, but web-security is not disabled.

Put -user-data-dir into it's own string. VSCode shows error

```<code>Cannot connect to runtime process, timeout after 10000ms -(reason: Can't find a valid target taht matches: about:blank. Available pages: ["chrome-ex...://ceimgagkkofjoalgojpkdcmhmbljbbaa/_generated_background_page.html"]).
</code>```

Does anyone know if it is possible to configure Chrome debugger to run web-secruity-disabled?

答:
this worked for me:</p>

```<code>"runtimeArgs": ["--auto-ssl-client-auth"]
</code>```

Body:
I'm developing a remote application which need the web security disabled on Chrome, which I have a windows shortcut that takes the following runtime argument:

"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" -incognito --disable-web-security --user-data-dir=C:\Program

For vscode, I have the following launch.json

{
    "version": "0.2.0",
    "configurations": [
        {
            "type": "chrome",
            "request": "launch",
            "name": "web-security-disabled-chrome",
            "url": "http://localhost:8000",
            "runtimeArgs": [
                "--disable-web-security --user-data-dir=C:\\Program",
                "-incognito"
            ],
            "webRoot": "${workspaceFolder}"
        }
    ]
}

and it doesn't disable web-security.

Failed to load resource: net::ERR_CERT_AUTHORITY_INVALID [https://my.remote.ip/restapp/...

I also tried the following:

Give vscode a new directory for user data. I saw the folder got populated, but web-security is not disabled.

Put -user-data-dir into it's own string. VSCode shows error

Cannot connect to runtime process, timeout after 10000ms -(reason: Can't find a valid target taht matches: about:blank. Available pages: ["chrome-ex...://ceimgagkkofjoalgojpkdcmhmbljbbaa/_generated_background_page.html"]).

Does anyone know if it is possible to configure Chrome debugger to run web-secruity-disabled?

Body:
this worked for me:

"runtimeArgs": ["--auto-ssl-client-auth"]


问:
How do I stop returning -0 in Javascript?
I created an event listener with a button that has a code onclick, but sometimes when I click the button over and over again it returns undefined I set it to return random things from an array.
Anyways, I found out that since i put my array.length -1 it sometimes returns -0 or undefined instead of just 0 in the console. What would be the best way for me to fix this?

This is my code the button listener is in the main.js file:

HTML

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <title>Document</title>
</head>
<body>
    <div class="root">
        <div>
            <button id="btn1">sleep</button>
        </div>
    </div>

    <script type="module" src="main.js"></script>
</body>
</html>
</code>```

main.js

```<code>import { v1, v2, v3 ,v4 } from './main2.js';

let btn = document.getElementById('btn1');

console.log(v3);
/////////////////////////////////////////////////

btn.addEventListener('click', () => {
    console.log(`${v4[Math.round(Math.random() * v4.length -1
      )]}`)
})

</code>```

main2.js

```<code>
let log = {
    One: 'one',
    Two: 'two',
    Three: 'three',
    Four: ['tester1', 'tester2', 'tester3'],
}

export let {One: v1, Two: v2, Three: v3, Four: v4} = log;

</code>```

答:
```<code>console.log(`${v4[Math.round(Math.random() * v4.length -1)]}`);
</code>```

Is choosing an number between -1 and 3

It should be this

```<code>console.log(`${v4[Math.random() * v4.length | 0]}`);
</code>```

Which choses a number between 0 and 3. Math.random() returns a number between 0 and 0.9999999999999999999 so Math.random() * v4.length will return a number between 0 and 3.99999999999999999999

Then | 0 will turn the result into an integer.

| 0 is faster than Math.floor and more idiomatic. See Using bitwise OR 0 to floor a number

Body:
I created an event listener with a button that has a code onclick, but sometimes when I click the button over and over again it returns undefined I set it to return random things from an array.
Anyways, I found out that since i put my array.length -1 it sometimes returns -0 or undefined instead of just 0 in the console. What would be the best way for me to fix this?

This is my code the button listener is in the main.js file:

HTML

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <title>Document</title>

            <button id="btn1">sleep</button>

main.js

import { v1, v2, v3 ,v4 } from './main2.js';

let btn = document.getElementById('btn1');

console.log(v3);
/////////////////////////////////////////////////

btn.addEventListener('click', () => {
    console.log(`${v4[Math.round(Math.random() * v4.length -1
      )]}`)
})

main2.js

let log = {
    One: 'one',
    Two: 'two',
    Three: 'three',
    Four: ['tester1', 'tester2', 'tester3'],
}

export let {One: v1, Two: v2, Three: v3, Four: v4} = log;

Body:
console.log(`${v4[Math.round(Math.random() * v4.length -1)]}`);

Is choosing an number between -1 and 3

It should be this

console.log(`${v4[Math.random() * v4.length | 0]}`);

Which choses a number between 0 and 3. Math.random() returns a number between 0 and 0.9999999999999999999 so Math.random() * v4.length will return a number between 0 and 3.99999999999999999999

Then | 0 will turn the result into an integer.

| 0 is faster than Math.floor and more idiomatic. See Using bitwise OR 0 to floor a number


问:
Manually clearing an Android ViewModel?
Edit: This question is a bit out of date now that Google has given us the ability to scope ViewModel to navigation graphs. The better approach (rather than trying to clear activity-scoped models) would be to create specific navigation graphs for the right amount of screens, and scope to those.

With reference to the android.arch.lifecycle.ViewModel class.

ViewModel is scoped to the lifecycle of the UI component it relates to, so in a Fragment-based app, that will be the fragment lifecycle. This is a good thing.

In some cases one wants to share a ViewModel instance between multiple fragments. Specifically I am interested in the case where many screens relate to the same underlying data.

(The docs suggest similar approach when multiple related fragments are displayed on the same screen but this can be worked around by using a single host fragment as per answer below.)

This is discussed in the official ViewModel documentation:

ViewModels can also be used as a communication layer between different
  Fragments of an Activity. Each Fragment can acquire the ViewModel
  using the same key via their Activity. This allows communication
  between Fragments in a de-coupled fashion such that they never need to
  talk to the other Fragment directly.

In other words, to share information between fragments that represent different screens, the ViewModel should be scoped to the Activity lifecycle (and according to Android docs this can also be used in other shared instances).

Now in the new Jetpack Navigation pattern, it is recommended to use a "One Activity / Many Fragments" architecture. This means that the activity lives for the whole time the app is being used.

i.e. any shared ViewModel instances that are scoped to Activity lifecycle will never be cleared - the memory remains in constant use.

With a view to preserving memory and using as little as required at any point in time, it would be nice to be able to clear shared ViewModel instances when no longer required.

How can one manually clear a ViewModel from it's ViewModelStore or holder fragment?

答:
It seems like it has been already solved in the latest architecture components version.

ViewModelProvider has a following constructor:

```<code>    /**
 * Creates {@code ViewModelProvider}, which will create {@code ViewModels} via the given
 * {@code Factory} and retain them in a store of the given {@code ViewModelStoreOwner}.
 *
 * @param owner   a {@code ViewModelStoreOwner} whose {@link ViewModelStore} will be used to
 *                retain {@code ViewModels}
 * @param factory a {@code Factory} which will be used to instantiate
 *                new {@code ViewModels}
 */
public ViewModelProvider(@NonNull ViewModelStoreOwner owner, @NonNull Factory factory) {
    this(owner.getViewModelStore(), factory);
}
</code>```

Which, in case of Fragment, would use scoped ViewModelStore.

androidx.fragment.app.Fragment#getViewModelStore

```<code>    /**
 * Returns the {@link ViewModelStore} associated with this Fragment
 * <p>
 * Overriding this method is no longer supported and this method will be made
 * <code>final</code> in a future version of Fragment.
 *
 * @return a {@code ViewModelStore}
 * @throws IllegalStateException if called before the Fragment is attached i.e., before
 * onAttach().
 */
@NonNull
@Override
public ViewModelStore getViewModelStore() {
    if (mFragmentManager == null) {
        throw new IllegalStateException("Can't access ViewModels from detached fragment");
    }
    return mFragmentManager.getViewModelStore(this);
}
</code>```

androidx.fragment.app.FragmentManagerViewModel#getViewModelStore

```<code>    @NonNull
ViewModelStore getViewModelStore(@NonNull Fragment f) {
    ViewModelStore viewModelStore = mViewModelStores.get(f.mWho);
    if (viewModelStore == null) {
        viewModelStore = new ViewModelStore();
        mViewModelStores.put(f.mWho, viewModelStore);
    }
    return viewModelStore;
}
</code>```

Title: Manually clearing an Android ViewModel?

Body:
It seems like it has been already solved in the latest architecture components version.

ViewModelProvider has a following constructor:

    /**
 * Creates {@code ViewModelProvider}, which will create {@code ViewModels} via the given
 * {@code Factory} and retain them in a store of the given {@code ViewModelStoreOwner}.
 *
 * @param owner   a {@code ViewModelStoreOwner} whose {@link ViewModelStore} will be used to
 *                retain {@code ViewModels}
 * @param factory a {@code Factory} which will be used to instantiate
 *                new {@code ViewModels}
 */
public ViewModelProvider(@NonNull ViewModelStoreOwner owner, @NonNull Factory factory) {
    this(owner.getViewModelStore(), factory);
}

Which, in case of Fragment, would use scoped ViewModelStore.

androidx.fragment.app.Fragment#getViewModelStore

    /**
 * Returns the {@link ViewModelStore} associated with this Fragment
 * <p>
 * Overriding this method is no longer supported and this method will be made
 * <code>final</code> in a future version of Fragment.
 *
 * @return a {@code ViewModelStore}
 * @throws IllegalStateException if called before the Fragment is attached i.e., before
 * onAttach().
 */
@NonNull
@Override
public ViewModelStore getViewModelStore() {
    if (mFragmentManager == null) {
        throw new IllegalStateException("Can't access ViewModels from detached fragment");
    }
    return mFragmentManager.getViewModelStore(this);
}

androidx.fragment.app.FragmentManagerViewModel#getViewModelStore

    @NonNull
ViewModelStore getViewModelStore(@NonNull Fragment f) {
    ViewModelStore viewModelStore = mViewModelStores.get(f.mWho);
    if (viewModelStore == null) {
        viewModelStore = new ViewModelStore();
        mViewModelStores.put(f.mWho, viewModelStore);
    }
    return viewModelStore;
}


问:
Rcpp Function - SegFault Error & Memory management
I need to loop through columns in a matrix and sum all values in each row where column index is higher.

I've done it fine using a for loop and rowSums without issue as I'm familiar with basic R code. I wrote a C++ function to speed up runtime - code below.
When I run in RStudio I encounter a fatal error.
When I run in R I get a segfault error as memory is not mapped.

Error doesn't occur when I run matrix of say 10 rows - but ideally want to run 10k.

Do I need to allocate memory somewhere?

```<code>#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
Rcpp::NumericVector PVCalc_cpp(Rcpp::NumericMatrix x, int y) {
int nrow = x.nrow(), ncol = x.ncol();
RNGScope scope;

Rcpp::NumericVector out(nrow);
double total = 0;

      for (int i = 0; i < nrow; i++) {
        total = 0;
        for (int j = y; j < ncol; j++){
          total += x(i, j+1);
        }
        out(i) =  floor((100. * total)+.5)/100;
      }
  return out;
}
</code>```

答:
The problem is that when j = ncol - 1, trying to access x(i, j+1) in the line

```<code>total += x(i, j+1);
</code>```

is the same as trying to access x(i, ncol), and you are out of bounds. If I understand your problem correctly, you can just change j+1 to j, assuming y is passed correctly. So, we could change your code to the following:

#include <Rcpp.h>

// [[Rcpp::export]]
Rcpp::NumericVector PVCalc_cpp(const Rcpp::NumericMatrix& x, int y) {
    int nrow = x.nrow(), ncol = x.ncol();
    Rcpp::NumericVector out(nrow);
    double total = 0;
    for (int i = 0; i < nrow; i++) {
        total = 0;
        for (int j = y; j < ncol; j++){
            total += x(i, j);
        }
        /* The following will always be equal to total but rounded;
           to type less R code for the R comparison,
           I omit the rounding here.
           Notice also the use of [] access operator instead of ();
           this is more efficient.
         */
        // out[i] = floor((100. * total)+.5)/100;
        out[i] = total;
    }
    return out;
}
```

<p>We can then verify that this both works, and is faster than <code>rowSums()</code>:</p>

<pre class="lang-r prettyprint-override"><code>## Load required packages
library(Rcpp)
library(microbenchmark)
## Source C++ code
sourceCpp("so.cpp")
## Generate example data
x <- matrix(1:9, nrow = 3)
x
</code>```

     [,1] [,2] [,3]
[1,]    1    4    7
[2,]    2    5    8
[3,]    3    6    9
```

<pre class="lang-r prettyprint-override"><code>## Check results are the same
rowSums(x[ , -1])
</code>```

[1] 11 13 15
```

<pre class="lang-r prettyprint-override"><code>PVCalc_cpp(x, 1)
</code>```

[1] 11 13 15
```

<pre class="lang-r prettyprint-override"><code>## Benchmark small example
library(microbenchmark)
microbenchmark(base = rowSums(x[ , -1]),
               rcpp = PVCalc_cpp(x, 1))
</code>```

Unit: microseconds
 expr   min     lq     mean median    uq      max neval
 base 5.591 5.9210  8.61073  6.475 6.786  137.125   100
 rcpp 2.337 2.5795 19.90118  3.035 3.222 1651.094   100
```

<pre class="lang-r prettyprint-override"><code>## Check larger example
set.seed(123)
x <- matrix(rnorm(1e6), nrow = 1e3)
y <- sample(seq_len(ncol(x)), size = 1)
all.equal(rowSums(x[ , -(1:y)]), PVCalc_cpp(x, y))
</code>```

[1] TRUE
```

<pre class="lang-r prettyprint-override"><code>microbenchmark(base = rowSums(x[ , -(1:y)]),
               rcpp = PVCalc_cpp(x, y))
</code>```

Unit: milliseconds
 expr      min       lq     mean   median       uq       max neval
 base 5.377342 6.052347 6.954338 6.482907 7.834190 11.580706   100
 rcpp 1.447596 1.909504 2.085185 2.023343 2.158256  3.159366   100
```

Body:
I need to loop through columns in a matrix and sum all values in each row where column index is higher.

I've done it fine using a for loop and rowSums without issue as I'm familiar with basic R code. I wrote a C++ function to speed up runtime - code below.
When I run in RStudio I encounter a fatal error.
When I run in R I get a segfault error as memory is not mapped.

Error doesn't occur when I run matrix of say 10 rows - but ideally want to run 10k.

Do I need to allocate memory somewhere?

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
Rcpp::NumericVector PVCalc_cpp(Rcpp::NumericMatrix x, int y) {
int nrow = x.nrow(), ncol = x.ncol();
RNGScope scope;

Rcpp::NumericVector out(nrow);
double total = 0;

      for (int i = 0; i < nrow; i++) {
        total = 0;
        for (int j = y; j < ncol; j++){
          total += x(i, j+1);
        }
        out(i) =  floor((100. * total)+.5)/100;
      }
  return out;
}

Body:
The problem is that when j = ncol - 1, trying to access x(i, j+1) in the line

total += x(i, j+1);

is the same as trying to access x(i, ncol), and you are out of bounds. If I understand your problem correctly, you can just change j+1 to j, assuming y is passed correctly. So, we could change your code to the following:

#include <Rcpp.h>

// [[Rcpp::export]]
Rcpp::NumericVector PVCalc_cpp(const Rcpp::NumericMatrix& x, int y) {
    int nrow = x.nrow(), ncol = x.ncol();
    Rcpp::NumericVector out(nrow);
    double total = 0;
    for (int i = 0; i < nrow; i++) {
        total = 0;
        for (int j = y; j < ncol; j++){
            total += x(i, j);
        }
        /* The following will always be equal to total but rounded;
           to type less R code for the R comparison,
           I omit the rounding here.
           Notice also the use of [] access operator instead of ();
           this is more efficient.
         */
        // out[i] = floor((100. * total)+.5)/100;
        out[i] = total;
    }
    return out;
}

We can then verify that this both works, and is faster than rowSums():

## Load required packages
library(Rcpp)
library(microbenchmark)
## Source C++ code
sourceCpp("so.cpp")
## Generate example data
x <- matrix(1:9, nrow = 3)
x

     [,1] [,2] [,3]
[1,]    1    4    7
[2,]    2    5    8
[3,]    3    6    9

## Check results are the same
rowSums(x[ , -1])

[1] 11 13 15

PVCalc_cpp(x, 1)

[1] 11 13 15

## Benchmark small example
library(microbenchmark)
microbenchmark(base = rowSums(x[ , -1]),
               rcpp = PVCalc_cpp(x, 1))

Unit: microseconds
 expr   min     lq     mean median    uq      max neval
 base 5.591 5.9210  8.61073  6.475 6.786  137.125   100
 rcpp 2.337 2.5795 19.90118  3.035 3.222 1651.094   100

## Check larger example
set.seed(123)
x <- matrix(rnorm(1e6), nrow = 1e3)
y <- sample(seq_len(ncol(x)), size = 1)
all.equal(rowSums(x[ , -(1:y)]), PVCalc_cpp(x, y))

[1] TRUE

microbenchmark(base = rowSums(x[ , -(1:y)]),
               rcpp = PVCalc_cpp(x, y))

Unit: milliseconds
 expr      min       lq     mean   median       uq       max neval
 base 5.377342 6.052347 6.954338 6.482907 7.834190 11.580706   100
 rcpp 1.447596 1.909504 2.085185 2.023343 2.158256  3.159366   100


问:
Aggregation pipeline "latest for all distinct id" is very slow, need to create proper indexes?
Considering the following aggregation pipeline code to return newest entry for all distinct "internal_id":

```<code>db.locations.aggregate({$sort: {timestamp: -1}}, {$group: {_id: "$internal_id", doc: {$first: "$$ROOT"}}})
</code>```

This call takes up to 10 seconds, which is not acceptable. The collection is not so huge:

```<code>db.locations.count()
1513671
</code>```

So I guess there's something wrong with the indexes, however I tried to create many indexes and none of them made an improvement, currently I kept those two that were supposed to be enough imho: {timestamp: -1, internal_id: 1}  and {internal_id: 1, timestamp: -1}.

MongoDB is NOT sharded, and running a 3 hosts replicaset running version 3.6.14.

MongoDB log show the following:

```<code>2020-05-30T12:21:18.598+0200 I COMMAND  [conn12652918] command mydb.locations appName: "MongoDB Shell" command: aggregate { aggregate: "locations", pipeline: [ { $sort: { timestamp: -1.0 } }, { $group: { _id: "$internal_id", doc: { $first: "$$ROOT" } } } ], cursor: {}, lsid: { id: UUID("70fea740-9665-4068-a2b5-b7b0f10dcde9") }, $clusterTime: { clusterTime: Timestamp(1590834060, 34), signature: { hash: BinData(0, 9DFB6DBCEE52CFA3A5832DC209519A8E9D6F1204), keyId: 6783976096153993217 } }, $db: "mydb" } planSummary: IXSCAN { timestamp: -1, ms_id: 1 } cursorid:8337712045451536023 keysExamined:1513708 docsExamined:1513708 numYields:11838 nreturned:101 reslen:36699 locks:{ Global: { acquireCount: { r: 24560 } }, Database: { acquireCount: { r: 12280 } }, Collection: { acquireCount: { r: 12280 } } } protocol:op_msg 7677msms
</code>```

答:
So finally I've been able to do all the testing, here is all version I wrote, thanks to willis answer and the result:

Original aggregate query

mongo_query = [
  {"$match": group_filter},
  {"$sort": {"timestamp": -1}},
  {"$group": {"_id": "$internal_id", "doc": {"$first": "$$ROOT"}}},
]

res = mongo.db[self.factory.config.mongo_collection].aggregate(mongo_query)
res = await res.to_list(None)
```

<p>9.61 seconds</p>

<h1>Give MongoDB a hint to use proper index (filter internal_id first)</h1>

<pre class="lang-py prettyprint-override"><code>from bson.son import SON

cursor = mongo.db[self.factory.config.mongo_collection].aggregate(mongo_query, hint=SON([("internal_id", 1), ("timestamp", -1)]))
res = await cursor.to_list(None)
</code>```

Not working, MongoDB replies with an exception, saying sorting consume too much memory

Split aggregation, to first find latest timestamp for each internal_id

cursor = mongo.db[self.factory.config.mongo_collection].aggregate([{"$group": {"_id": "$internal_id", "timestamp": {"$max": "$timestamp"}}}])
res = await cursor.to_list(None)

or_query = []
for entry in res:
    or_query.append({"internal_id": entry["_id"], "timestamp": entry["timestamp"]})
cursor = mongo.db[self.factory.config.mongo_collection].find({"$or": or_query})
fixed_res = await cursor.to_list(None)
```

<p>1.88 seconds, a lot better but still not that fast</p>

<h1>Parallel coroutines (and the winner is....)</h1>

<p>In the meanwhile, as I already have the list of internal_id, and I'm using asynchronous Python, I went for parallel coroutine, getting latest entry for a single internal_id at once:</p>

<pre class="lang-py prettyprint-override"><code>fixed_res: List[Dict] = []

async def get_one_result(db_filter: Dict) -> None:
    """ Coroutine getting one result for each known internal ID """

    cursor = mongo.db[self.factory.config.mongo_collection].find(db_filter).sort("timestamp", -1).limit(1)
    res = await cursor.to_list(1)
    if res:
        fixed_res.append(res[0])

coros: List[Awaitable] = []
for internal_id in self.list_of_internal_ids:
    coro = get_one_result({"internal_id": internal_id})
    coros.append(coro)
await asyncio.gather(*coros)
</code>```

0.5s, way better than others

If you don't have a list of internal_id

There's an alternative I did not implement but I confirmed the call is very fast: use lowlevel distinct command against {internal_id: 1} index to retrieve list of individual IDs, then use parallel calls.

Body:
Considering the following aggregation pipeline code to return newest entry for all distinct "internal_id":

db.locations.aggregate({$sort: {timestamp: -1}}, {$group: {_id: "$internal_id", doc: {$first: "$$ROOT"}}})

This call takes up to 10 seconds, which is not acceptable. The collection is not so huge:

db.locations.count()
1513671

So I guess there's something wrong with the indexes, however I tried to create many indexes and none of them made an improvement, currently I kept those two that were supposed to be enough imho: {timestamp: -1, internal_id: 1}  and {internal_id: 1, timestamp: -1}.

MongoDB is NOT sharded, and running a 3 hosts replicaset running version 3.6.14.

MongoDB log show the following:

2020-05-30T12:21:18.598+0200 I COMMAND  [conn12652918] command mydb.locations appName: "MongoDB Shell" command: aggregate { aggregate: "locations", pipeline: [ { $sort: { timestamp: -1.0 } }, { $group: { _id: "$internal_id", doc: { $first: "$$ROOT" } } } ], cursor: {}, lsid: { id: UUID("70fea740-9665-4068-a2b5-b7b0f10dcde9") }, $clusterTime: { clusterTime: Timestamp(1590834060, 34), signature: { hash: BinData(0, 9DFB6DBCEE52CFA3A5832DC209519A8E9D6F1204), keyId: 6783976096153993217 } }, $db: "mydb" } planSummary: IXSCAN { timestamp: -1, ms_id: 1 } cursorid:8337712045451536023 keysExamined:1513708 docsExamined:1513708 numYields:11838 nreturned:101 reslen:36699 locks:{ Global: { acquireCount: { r: 24560 } }, Database: { acquireCount: { r: 12280 } }, Collection: { acquireCount: { r: 12280 } } } protocol:op_msg 7677msms

Body:
So finally I've been able to do all the testing, here is all version I wrote, thanks to willis answer and the result:

Original aggregate query

mongo_query = [
  {"$match": group_filter},
  {"$sort": {"timestamp": -1}},
  {"$group": {"_id": "$internal_id", "doc": {"$first": "$$ROOT"}}},
]

res = mongo.db[self.factory.config.mongo_collection].aggregate(mongo_query)
res = await res.to_list(None)

9.61 seconds

Give MongoDB a hint to use proper index (filter internal_id first)

from bson.son import SON

cursor = mongo.db[self.factory.config.mongo_collection].aggregate(mongo_query, hint=SON([("internal_id", 1), ("timestamp", -1)]))
res = await cursor.to_list(None)

Not working, MongoDB replies with an exception, saying sorting consume too much memory

Split aggregation, to first find latest timestamp for each internal_id

cursor = mongo.db[self.factory.config.mongo_collection].aggregate([{"$group": {"_id": "$internal_id", "timestamp": {"$max": "$timestamp"}}}])
res = await cursor.to_list(None)

or_query = []
for entry in res:
    or_query.append({"internal_id": entry["_id"], "timestamp": entry["timestamp"]})
cursor = mongo.db[self.factory.config.mongo_collection].find({"$or": or_query})
fixed_res = await cursor.to_list(None)

1.88 seconds, a lot better but still not that fast

Parallel coroutines (and the winner is....)

In the meanwhile, as I already have the list of internal_id, and I'm using asynchronous Python, I went for parallel coroutine, getting latest entry for a single internal_id at once:

fixed_res: List[Dict] = []

async def get_one_result(db_filter: Dict) -> None:
    """ Coroutine getting one result for each known internal ID """

    cursor = mongo.db[self.factory.config.mongo_collection].find(db_filter).sort("timestamp", -1).limit(1)
    res = await cursor.to_list(1)
    if res:
        fixed_res.append(res[0])

coros: List[Awaitable] = []
for internal_id in self.list_of_internal_ids:
    coro = get_one_result({"internal_id": internal_id})
    coros.append(coro)
await asyncio.gather(*coros)

0.5s, way better than others

If you don't have a list of internal_id

There's an alternative I did not implement but I confirmed the call is very fast: use lowlevel distinct command against {internal_id: 1} index to retrieve list of individual IDs, then use parallel calls.


问:
angular 2 - how to set <select> default selected option
My template is like this

```<code><select>
  <option>AM</option>
  <option>PM</option>
</select>
</code>```

How can I set option AM selected by default?

答:
I noticed no one gave the non-ngModel solution, which is this:

html:

```<code>    <select (change)="valueSelected($event.target.value)">
        <option *ngFor="let option of options">{{option}}</option>
    </select>
</code>```

typescript:

```<code>valueSelected(value:string) {
  console.log(value);
}
</code>```

Body:
My template is like this

<select>
  <option>AM</option>
  <option>PM</option>
</select>

How can I set option AM selected by default?

Body:
I noticed no one gave the non-ngModel solution, which is this:

html:

    <select (change)="valueSelected($event.target.value)">
        <option *ngFor="let option of options">{{option}}</option>
    </select>

typescript:

valueSelected(value:string) {
  console.log(value);
}


问:
Link between HTML and CSS not functioning

body {
  background-color: grey;
}

hr {
  border-style: none;
  border-top-style: dotted;
  border-color: #12947f;
  border-width: 4px;
  width: 50%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>Donald's Personal Site</title>
  <link rel="stylesheet" href="css/style.css">
</head>
<body>
</body>
</html></code>```

I am new to coding and I've spent three days trying to figure out what was wrong with my page. Could someone please help me to resolve this issue, so that I can continue to improve on my coding?

答:
Some reasons why your code isn't working:

Wrong path: if your path in href attribute is incorrect then it won't work.

Fix: make sure your path is correct, this is done by referencing the folder or directory where your CSS file is located.
To simply debug this as a beginner still learning paths and directory linking, put your CSS file in root directory and simply link to it by this:

```<code>  <link rel="stylesheet" type="text/css" href="style.css">
</code>```

Wrong spelling: you may have spelt the CSS file name wrongly in href.

Fix: crosscheck the filename and correct spelling in href

Maybe adding type attribute to your code might help for reasons i have limited knowledge of, so try adding type attribute.

```<code><link rel="stylesheet" type="text/css" href="/path/style.css">
</code>```

Body:
body {
  background-color: grey;
}

hr {
  border-style: none;
  border-top-style: dotted;
  border-color: #12947f;
  border-width: 4px;
  width: 50%;
}

<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Donald's Personal Site</title>
  <link rel="stylesheet" href="css/style.css">

I am new to coding and I've spent three days trying to figure out what was wrong with my page. Could someone please help me to resolve this issue, so that I can continue to improve on my coding?

Body:
Some reasons why your code isn't working:

Wrong path: if your path in href attribute is incorrect then it won't work.

Fix: make sure your path is correct, this is done by referencing the folder or directory where your CSS file is located.
To simply debug this as a beginner still learning paths and directory linking, put your CSS file in root directory and simply link to it by this:

  <link rel="stylesheet" type="text/css" href="style.css">

Wrong spelling: you may have spelt the CSS file name wrongly in href.

Fix: crosscheck the filename and correct spelling in href

Maybe adding type attribute to your code might help for reasons i have limited knowledge of, so try adding type attribute.

<link rel="stylesheet" type="text/css" href="/path/style.css">