问:
Aggregating categorical variables to one variable in python 3 pandas
I have a pandas dataframe with 4 columns. like this

```<code>ID  col1                        col2                col3
1   Strongly Positive   Strongly Positive   Weekly Positive
2   Strongly Positive   Strongly Positive   Neutral
3   Strongly Negative   Strongly Negative   Weekly Negative
4   Weekly Negative      Strongly Negative  Neutral
5   Neutral              Neutral            Neutral
6   Strongly Positive   Strongly Negative   Strongly Negative
7   Strongly Negative   Weekly Positive     Neutral
8   Neutral               Weekly Negative   Weekly Positive
</code>```

Each of the columns can take values like (strongly positive, weekly positive, Neutral, weekly negative and strongly negative and an ID column.
I need to create a new column with these logic

If all the column has positive values or atleast one positive and two neutral values then aggregate that record in the new column as positive

If all the three column has neutral value then flag as neutral

If all the columns have negative values or atleast one negative and two neutral values then flag it as negative

If both positive and negative values are thre then flag it as both
by positive i mean either strong or weekly positive and the same for negative as well.

I need the the final data frame to be like this

```<code>ID  col1                  col2          col3        Aggregated_Col
1   Strongly Positive  Strongly Positive Weekly Positive    Positive
2   Strongly Positive  Strongly Positive Neutral            Positive
3   Strongly Negative  Strongly Negative Weekly Negative    Negative
4   Weekly Negative    Strongly Negative Neutral            Negative
5   Neutral            Neutral       Neutral                Neutral
6   Strongly Positive  Strongly Negative Strongly Negative  Both
7   Strongly Negative  Weekly Positive   Neutral            Both
8   Neutral Weekly     Negative      Weekly Positive        Both
</code>```

Not able to think of a logic

```<code>ID  col1                  col2          col3        Aggregated_Col
1   Strongly Positive  Strongly Positive Weekly Positive    Positive
2   Strongly Positive  Strongly Positive Neutral            Positive
3   Strongly Negative  Strongly Negative Weekly Negative    Negative
4   Weekly Negative    Strongly Negative Neutral            Negative
5   Neutral            Neutral       Neutral            Neutral
6   Strongly Positive  Strongly Negative Strongly Negative  Both
7   Strongly Negative  Weekly Positive   Neutral            Both
8   Neutral Weekly     Negative      Weekly Positive    Both
</code>```

答:
You can mask the respective elements like this:</p>

```<code># set index as ID:
df.set_index('ID', inplace=True)

has_pos = df.apply(lambda x: x.str.contains('Positive')).any(axis=1)
has_neg = df.apply(lambda x: x.str.contains('Negative')).any(axis=1)
has_both = has_pos & has_neg

# update
df['Agg_Col'] = 'Neutral'
df.loc[has_pos,'Agg_Col'] = 'Positive'
df.loc[has_neg,'Agg_Col'] = 'Negative'

df.loc[has_both,'Agg_Col'] = 'Both'
</code>```

Body:
I have a pandas dataframe with 4 columns. like this

ID  col1                        col2                col3
1   Strongly Positive   Strongly Positive   Weekly Positive
2   Strongly Positive   Strongly Positive   Neutral
3   Strongly Negative   Strongly Negative   Weekly Negative
4   Weekly Negative      Strongly Negative  Neutral
5   Neutral              Neutral            Neutral
6   Strongly Positive   Strongly Negative   Strongly Negative
7   Strongly Negative   Weekly Positive     Neutral
8   Neutral               Weekly Negative   Weekly Positive

Each of the columns can take values like (strongly positive, weekly positive, Neutral, weekly negative and strongly negative and an ID column.
I need to create a new column with these logic

If all the column has positive values or atleast one positive and two neutral values then aggregate that record in the new column as positive

If all the three column has neutral value then flag as neutral

If all the columns have negative values or atleast one negative and two neutral values then flag it as negative

If both positive and negative values are thre then flag it as both
by positive i mean either strong or weekly positive and the same for negative as well.

I need the the final data frame to be like this

ID  col1                  col2          col3        Aggregated_Col
1   Strongly Positive  Strongly Positive Weekly Positive    Positive
2   Strongly Positive  Strongly Positive Neutral            Positive
3   Strongly Negative  Strongly Negative Weekly Negative    Negative
4   Weekly Negative    Strongly Negative Neutral            Negative
5   Neutral            Neutral       Neutral                Neutral
6   Strongly Positive  Strongly Negative Strongly Negative  Both
7   Strongly Negative  Weekly Positive   Neutral            Both
8   Neutral Weekly     Negative      Weekly Positive        Both

Not able to think of a logic

ID  col1                  col2          col3        Aggregated_Col
1   Strongly Positive  Strongly Positive Weekly Positive    Positive
2   Strongly Positive  Strongly Positive Neutral            Positive
3   Strongly Negative  Strongly Negative Weekly Negative    Negative
4   Weekly Negative    Strongly Negative Neutral            Negative
5   Neutral            Neutral       Neutral            Neutral
6   Strongly Positive  Strongly Negative Strongly Negative  Both
7   Strongly Negative  Weekly Positive   Neutral            Both
8   Neutral Weekly     Negative      Weekly Positive    Both

Body:
You can mask the respective elements like this:

# set index as ID:
df.set_index('ID', inplace=True)

has_pos = df.apply(lambda x: x.str.contains('Positive')).any(axis=1)
has_neg = df.apply(lambda x: x.str.contains('Negative')).any(axis=1)
has_both = has_pos & has_neg

# update
df['Agg_Col'] = 'Neutral'
df.loc[has_pos,'Agg_Col'] = 'Positive'
df.loc[has_neg,'Agg_Col'] = 'Negative'

df.loc[has_both,'Agg_Col'] = 'Both'


来源: stackexchange

问:
How to modify a subset of data without using variables
Using functional Javascript like Underscore, Lodhash, Ramda, Immutable JS, if I have some (semi-accurate) data like this:

```<code>var data = {
  people: [
    {name: 'Vishwanathan Anand', age: 46},
    {name: 'Garry Kasparov', age: 52},
    {name: 'Magnus Carlsen', age: 25},
  ],
  computers: [
    {name: 'Deep Blue', age: 26},
    {name: 'Deep Fritz', age: 21},
    {name: 'Deep Thought', age: 28},
  ]
}
</code>```

I wish to transform it to

```<code>var data = {
  people: [
    {name: 'Vishwanathan Anand', age: 46, rank: 0},
    {name: 'Garry Kasparov', age: 52, rank: 1},
    {name: 'Magnus Carlsen', age: 25, rank 2},
  ],
  computers: [
    {name: 'Deep Blue', age: 26},
    {name: 'Deep Fritz', age: 21},
    {name: 'Deep Thought', age: 28},
  ]
}
</code>```

Note how only the people substructure got rank.

I know I can,

```<code>_.extend({
  computers: _.map(data.people, (p, i) => {
    p.rank = i;
    return p;
  })}, {
    computers: data.computers
  })
</code>```

But what if I need to do this without using any variables (no more access to data!) using underscore's chain?

Something like

```<code>_.chain(data).subset('people').map((p, i) => {
  p.rank = i;
  return p;
})
</code>```

NOTE This is a real problem and not a matter of convenience. I am working on a project that involves creating a sort of environment for functional operators and variables are not allowed.

It seems Underscore and the like operate on the entire structure (Array / List). is there any way I can ask it to operate on a substructure while preserving the rest?

答:
With Ramda you can use R.evolve to create a function, that accepts a key and an callback (cb), and maps the items of key to the required form:

const { evolve, addIndex, map } = R

const mapPart = (cb, key) => evolve({
  [key]: addIndex(map)(cb)
})

const data = {"people":[{"name":"Vishwanathan Anand","age":46},{"name":"Garry Kasparov","age":52},{"name":"Magnus Carlsen","age":25}],"computers":[{"name":"Deep Blue","age":26},{"name":"Deep Fritz","age":21},{"name":"Deep Thought","age":28}]}

const result = mapPart((o, rank) => ({ ...o, rank }), 'people')(data)

console.log(result)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.js"></script></code>```

ContentLicense: CC BY-SA 3.0

Body:
Using functional Javascript like Underscore, Lodhash, Ramda, Immutable JS, if I have some (semi-accurate) data like this:

var data = {
  people: [
    {name: 'Vishwanathan Anand', age: 46},
    {name: 'Garry Kasparov', age: 52},
    {name: 'Magnus Carlsen', age: 25},
  ],
  computers: [
    {name: 'Deep Blue', age: 26},
    {name: 'Deep Fritz', age: 21},
    {name: 'Deep Thought', age: 28},
  ]
}

I wish to transform it to

var data = {
  people: [
    {name: 'Vishwanathan Anand', age: 46, rank: 0},
    {name: 'Garry Kasparov', age: 52, rank: 1},
    {name: 'Magnus Carlsen', age: 25, rank 2},
  ],
  computers: [
    {name: 'Deep Blue', age: 26},
    {name: 'Deep Fritz', age: 21},
    {name: 'Deep Thought', age: 28},
  ]
}

Note how only the people substructure got rank.

I know I can,

_.extend({
  computers: _.map(data.people, (p, i) => {
    p.rank = i;
    return p;
  })}, {
    computers: data.computers
  })

But what if I need to do this without using any variables (no more access to data!) using underscore's chain?

Something like

_.chain(data).subset('people').map((p, i) => {
  p.rank = i;
  return p;
})

NOTE This is a real problem and not a matter of convenience. I am working on a project that involves creating a sort of environment for functional operators and variables are not allowed.

It seems Underscore and the like operate on the entire structure (Array / List). is there any way I can ask it to operate on a substructure while preserving the rest?

Body:
With Ramda you can use R.evolve to create a function, that accepts a key and an callback (cb), and maps the items of key to the required form:

const { evolve, addIndex, map } = R

const mapPart = (cb, key) => evolve({
  [key]: addIndex(map)(cb)
})

const data = {"people":[{"name":"Vishwanathan Anand","age":46},{"name":"Garry Kasparov","age":52},{"name":"Magnus Carlsen","age":25}],"computers":[{"name":"Deep Blue","age":26},{"name":"Deep Fritz","age":21},{"name":"Deep Thought","age":28}]}

const result = mapPart((o, rank) => ({ ...o, rank }), 'people')(data)

console.log(result)

<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.js"></script>

ContentLicense: CC BY-SA 4.0


问:
Why list of pd.Interval doesn't recognized by DataFrame automatically?

intervals = [pd.Interval(0, 0.1), pd.Interval(1, 5)]
pd.DataFrame({'d':intervals}).dtypes
```

<p>Produces dtype as <em>Object</em> not <em>Interval</em>:</p>

<pre class="lang-py prettyprint-override"><code>>>> d    object
>>> dtype: object
</code>```

But at the same time list of, for example, DateTimes is recognized on the fly:

datetimes = [pd.Timestamp('2013-01-02'), pd.Timestamp('2016-10-20')]
pd.DataFrame({'d':datetimes}).dtypes
>>> d    datetime64[ns]
>>> dtype: object
```

Is situation with intervals somewhat like with list of strings - default type of column in the DataFrame will be object as well, because DataFrame doesn't 'know' if we want to treat this column as objects (for dumping to disk, ..), or as strings (for concatenation, ..) or even as elements of category type? If so - what different use cases with intervals may be? If not what is the case here?

答:
This is a bug in pandas: https://github.com/pandas-dev/pandas/issues/23563

For now, the cleanest workaround is to wrap the list with pd.array:

```<code>In [1]: import pandas as pd; pd.__version__
Out[1]: '0.24.2'

In [2]: intervals = [pd.Interval(0, 0.1), pd.Interval(1, 5)]

In [3]: pd.DataFrame({'d': pd.array(intervals)}).dtypes
Out[3]:
d    interval[float64]
dtype: object
</code>```

Body:
intervals = [pd.Interval(0, 0.1), pd.Interval(1, 5)]
pd.DataFrame({'d':intervals}).dtypes

Produces dtype as Object not Interval:

>>> d    object
>>> dtype: object

But at the same time list of, for example, DateTimes is recognized on the fly:

datetimes = [pd.Timestamp('2013-01-02'), pd.Timestamp('2016-10-20')]
pd.DataFrame({'d':datetimes}).dtypes
>>> d    datetime64[ns]
>>> dtype: object

Is situation with intervals somewhat like with list of strings - default type of column in the DataFrame will be object as well, because DataFrame doesn't 'know' if we want to treat this column as objects (for dumping to disk, ..), or as strings (for concatenation, ..) or even as elements of category type? If so - what different use cases with intervals may be? If not what is the case here?

Body:
This is a bug in pandas: https://github.com/pandas-dev/pandas/issues/23563

For now, the cleanest workaround is to wrap the list with pd.array:

In [1]: import pandas as pd; pd.__version__
Out[1]: '0.24.2'

In [2]: intervals = [pd.Interval(0, 0.1), pd.Interval(1, 5)]

In [3]: pd.DataFrame({'d': pd.array(intervals)}).dtypes
Out[3]:
d    interval[float64]
dtype: object


问:
why is mySQL missing a column?
This statement is not populating the image_path column. I have copied and pasted column names from phpMyAdmin to ensure accuracy.</p>

```<code>INSERT INTO (theme_name, theme_path, image_path)
VALUES ('',
        '/Applications/MAMP/htdocs/waggleb/wp-content/plugins/app-switcher/themes/Original/',
        '/Applications/MAMP/htdocs/waggleb/wp-content/plugins/app-switcher/thumbnails/original.png')
</code>```

答:
You're missing a table name. If you look at the MySQL INSERT syntax, you'll see that it's mandatory to include a table name.

As such, if you alter your query to become..

```<code>INSERT INTO <TABLE NAME> (theme_name, theme_path, image_path) VALUES...
</code>```

...all should be well.

Title: why is mySQL missing a column?

Body:
This statement is not populating the image_path column. I have copied and pasted column names from phpMyAdmin to ensure accuracy.

INSERT INTO (theme_name, theme_path, image_path)
VALUES ('',
        '/Applications/MAMP/htdocs/waggleb/wp-content/plugins/app-switcher/themes/Original/',
        '/Applications/MAMP/htdocs/waggleb/wp-content/plugins/app-switcher/thumbnails/original.png')

Body:
You're missing a table name. If you look at the MySQL INSERT syntax, you'll see that it's mandatory to include a table name.

As such, if you alter your query to become..

INSERT INTO <TABLE NAME> (theme_name, theme_path, image_path) VALUES...

...all should be well.


问:
Querying the same column for 3 different values
I'm trying hard to extract the data in the format I need, but unsuccessful til now.

I have the following table

id_ticket, date_ticket, office_ticket, status_ticket

I need the query to return me, for EVERY MONTH, and always for the same OFFICE:

the number of tickets (COUNT) with any status

the number of tickets (COUNT) with status = 5

the number of tickets (COUNT) with status = 6

Month

Year

The query I made to return ONLY the total amount of tickets with any status was this. It worked!

```<code>SELECT
COUNT (id_ticket) as TotalTicketsPerMonth,
'sYear' = YEAR (date_ticket),
'sMonth' = MONTH (date_ticket)
FROM crm_vw_Tickets
WHERE office_ticket = 1
GROUP BY
YEAR (date_ticket), MONTH (date_ticket)
ORDER BY sYear ASC, sMonth ASC
</code>```

Returning the total amount of ticket with status=5

```<code>SELECT
COUNT (id_ticket) as TotalTicketsPerMonth,
'sYear' = YEAR (date_ticket),
'sMonth' = MONTH (date_ticket)
FROM crm_vw_Tickets
WHERE office_ticket = 1 AND status_ticket = 5
GROUP BY
YEAR (date_ticket), MONTH (date_ticket)
ORDER BY sYear ASC, sMonth ASC
</code>```

But I need the return to be something like:

```<code>Year Month Total Status5 Status6
2018   1     15      5        3

2018   2     14      4        5

2018   3     19      2        8
</code>```

Thank you for your help.

答:
You are close. You can use a CASE Expression to get what you need:

```<code>SELECT
    COUNT (id_ticket) as TotalTicketsPerMonth,
    SUM(CASE WHEN status_ticket = 5 THEN 1 END) as Status5,
    SUM(CASE WHEN status_ticket = 6 THEN 1 END) as Status6,
    'sYear' = YEAR (date_ticket),
    'sMonth' = MONTH (date_ticket)
FROM crm_vw_Tickets
WHERE office_ticket = 1
GROUP BY YEAR (date_ticket), MONTH (date_ticket)
ORDER BY sYear ASC, sMonth ASC
</code>```

Body:
I'm trying hard to extract the data in the format I need, but unsuccessful til now.

I have the following table

id_ticket, date_ticket, office_ticket, status_ticket

I need the query to return me, for EVERY MONTH, and always for the same OFFICE:

the number of tickets (COUNT) with any status

the number of tickets (COUNT) with status = 5

the number of tickets (COUNT) with status = 6

Month

Year

The query I made to return ONLY the total amount of tickets with any status was this. It worked!

SELECT
COUNT (id_ticket) as TotalTicketsPerMonth,
'sYear' = YEAR (date_ticket),
'sMonth' = MONTH (date_ticket)
FROM crm_vw_Tickets
WHERE office_ticket = 1
GROUP BY
YEAR (date_ticket), MONTH (date_ticket)
ORDER BY sYear ASC, sMonth ASC

Returning the total amount of ticket with status=5

SELECT
COUNT (id_ticket) as TotalTicketsPerMonth,
'sYear' = YEAR (date_ticket),
'sMonth' = MONTH (date_ticket)
FROM crm_vw_Tickets
WHERE office_ticket = 1 AND status_ticket = 5
GROUP BY
YEAR (date_ticket), MONTH (date_ticket)
ORDER BY sYear ASC, sMonth ASC

But I need the return to be something like:

Year Month Total Status5 Status6
2018   1     15      5        3

2018   2     14      4        5

2018   3     19      2        8

Thank you for your help.

Body:
You are close. You can use a CASE Expression to get what you need:

SELECT
    COUNT (id_ticket) as TotalTicketsPerMonth,
    SUM(CASE WHEN status_ticket = 5 THEN 1 END) as Status5,
    SUM(CASE WHEN status_ticket = 6 THEN 1 END) as Status6,
    'sYear' = YEAR (date_ticket),
    'sMonth' = MONTH (date_ticket)
FROM crm_vw_Tickets
WHERE office_ticket = 1
GROUP BY YEAR (date_ticket), MONTH (date_ticket)
ORDER BY sYear ASC, sMonth ASC


问:
Linq that Aggregates distinct IDs
I am having trouble getting the correct Linq query for the following issue:
I have a List<> of storypoints that contains the following data:

```<code>ParentID    TaskID      Points
--------    ------    -----------
    1         100          2
    1         101          1
    1         103          1
    2         102          1
    2         104          4
    3         105          1
</code>```

I'm looking to get a list of distinct ParentIDs with an Aggregate count of StoryPoints:

```<code>ParentID    Count
--------    -----
   1          4
   2          5
   3          1
</code>```

I've tried this block but the syntax is throwing an error:

```<code>var storytaskpoints =
                        from u in storypoints
                        group u by u.ParentID into g
                        select new
                        {
                            ParentID = g.Key,
                            Count = (from u in g select u.Points).Count();
                        }
</code>```

My Class for StoryTaskPoint:

```<code>class StoryTaskPoint
    {
        public int ParentID { get; set; }
        public int Points { get; set; }
        public int TaskID { get; set; }

        public StoryTaskPoint()
        { }

        StoryTaskPoint(
            int taskID,
            int parentID,
            int points)
        {
            TaskID = taskID;
            ParentID = parentID;
            Points = points;
        }
    }
</code>```

Any help would be appreciated....

答:
```<code> from u in storypoints
                        group u by u.ParentID into g
                        select new
                        {
                            ParentID = g.Key,
                            Count = g.Sum(gg=>gg.Points)
                        }
</code>```

Use .Sum instead of .Count

Title: Linq that Aggregates distinct IDs

Body:
I am having trouble getting the correct Linq query for the following issue:
I have a List<> of storypoints that contains the following data:

ParentID    TaskID      Points
--------    ------    -----------
    1         100          2
    1         101          1
    1         103          1
    2         102          1
    2         104          4
    3         105          1

I'm looking to get a list of distinct ParentIDs with an Aggregate count of StoryPoints:

ParentID    Count
--------    -----
   1          4
   2          5
   3          1

I've tried this block but the syntax is throwing an error:

var storytaskpoints =
                        from u in storypoints
                        group u by u.ParentID into g
                        select new
                        {
                            ParentID = g.Key,
                            Count = (from u in g select u.Points).Count();
                        }

My Class for StoryTaskPoint:

class StoryTaskPoint
    {
        public int ParentID { get; set; }
        public int Points { get; set; }
        public int TaskID { get; set; }

        public StoryTaskPoint()
        { }

        StoryTaskPoint(
            int taskID,
            int parentID,
            int points)
        {
            TaskID = taskID;
            ParentID = parentID;
            Points = points;
        }
    }

Any help would be appreciated....

Body:
 from u in storypoints
                        group u by u.ParentID into g
                        select new
                        {
                            ParentID = g.Key,
                            Count = g.Sum(gg=>gg.Points)
                        }

Use .Sum instead of .Count


问:
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client in Node JS
I am trying to update a data using a specific ID which is not working but gives above error.

When I update, first I search the database for that specific id and then save the data to MongoDB

here is my server.js

```<code>const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const mongoose = require('mongoose');

//importing MongoDB model schema
let ToDo = require('./todo.model');

const app = express();
const todoRoutes = express.Router();

const PORT = 4000;

//middlewares
app.use(bodyParser.json());
app.use(cors());
app.use('/todos', todoRoutes);

//connection to the MongoDB database
mongoose.connect('mongodb://127.0.0.1:27017/todos', {useNewUrlParser: true});
const connection = mongoose.connection;
connection.once('open', () =>{
    console.log("Connected to the MongoDB through port: 27017");
 });

app.listen(PORT, () => {
    console.log(`Listening to port: ${PORT}`);
});

//get all data - removed to show only the code snippet I am getting errors

//get data by an ID - removed to show only the code snippet I am getting errors

//add items to database -removed to show only the code snippet I am getting errors

//update items
todoRoutes.route('/update/:id').post((req, res) => {
    let id = req.params.id;
    ToDo.findById(id, (err, todo) => {
        if(err) throw err;
        if(!todo) res.status(400).send("No data found");

        todo.todo_description = req.body.todo_description;
        todo.todo_responsible = req.body.todo_responsible;
        todo.todo_priority = req.body.todo_priority;
        todo.todo_completed = req.body.todo_completed;
        res.end();

        todo.save().then(todo => {
            res.json(200).send("Data Updated! " + todo);
            res.end();
        }).catch(err => {
            res.status(400).send("Error occured! " + err);
        });
    });
});
</code>```

This is the error I am getting...

Can someone please help me?

答:
In the '/update/:id' route, you're sending a res.end() then doing it again 3 lines later.  If you remove the first res.end(), it should work.

You should also return if todo is missing:

```<code>todoRoutes.route('/update/:id').post((req, res) => {
    let id = req.params.id;
    ToDo.findById(id, (err, todo) => {
        if(err) throw err;
        if(!todo) return res.status(400).send("No data found");

        todo.todo_description = req.body.todo_description;
        todo.todo_responsible = req.body.todo_responsible;
        todo.todo_priority = req.body.todo_priority;
        todo.todo_completed = req.body.todo_completed;

        todo.save().then(todo => {
            res.status(200).send("Data Updated! " + todo);
        }).catch(err => {
            res.status(400).send("Error occured! " + err);
        });
    });
});
</code>```

Body:
I am trying to update a data using a specific ID which is not working but gives above error.

When I update, first I search the database for that specific id and then save the data to MongoDB

here is my server.js

const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const mongoose = require('mongoose');

//importing MongoDB model schema
let ToDo = require('./todo.model');

const app = express();
const todoRoutes = express.Router();

const PORT = 4000;

//middlewares
app.use(bodyParser.json());
app.use(cors());
app.use('/todos', todoRoutes);

//connection to the MongoDB database
mongoose.connect('mongodb://127.0.0.1:27017/todos', {useNewUrlParser: true});
const connection = mongoose.connection;
connection.once('open', () =>{
    console.log("Connected to the MongoDB through port: 27017");
 });

app.listen(PORT, () => {
    console.log(`Listening to port: ${PORT}`);
});

//get all data - removed to show only the code snippet I am getting errors

//get data by an ID - removed to show only the code snippet I am getting errors

//add items to database -removed to show only the code snippet I am getting errors

//update items
todoRoutes.route('/update/:id').post((req, res) => {
    let id = req.params.id;
    ToDo.findById(id, (err, todo) => {
        if(err) throw err;
        if(!todo) res.status(400).send("No data found");

        todo.todo_description = req.body.todo_description;
        todo.todo_responsible = req.body.todo_responsible;
        todo.todo_priority = req.body.todo_priority;
        todo.todo_completed = req.body.todo_completed;
        res.end();

        todo.save().then(todo => {
            res.json(200).send("Data Updated! " + todo);
            res.end();
        }).catch(err => {
            res.status(400).send("Error occured! " + err);
        });
    });
});

This is the error I am getting...

Can someone please help me?

Body:
In the '/update/:id' route, you're sending a res.end() then doing it again 3 lines later.  If you remove the first res.end(), it should work.

You should also return if todo is missing:

todoRoutes.route('/update/:id').post((req, res) => {
    let id = req.params.id;
    ToDo.findById(id, (err, todo) => {
        if(err) throw err;
        if(!todo) return res.status(400).send("No data found");

        todo.todo_description = req.body.todo_description;
        todo.todo_responsible = req.body.todo_responsible;
        todo.todo_priority = req.body.todo_priority;
        todo.todo_completed = req.body.todo_completed;

        todo.save().then(todo => {
            res.status(200).send("Data Updated! " + todo);
        }).catch(err => {
            res.status(400).send("Error occured! " + err);
        });
    });
});


问:
negative percentage color condition in cross table
enter image description hereI used cross table . in cross table i try to apply color condition on percentage column with the help of Color scheme grouping  option in cross table color property.

cross table -->color -->Color Scheme grouping -->Percentage.

here i appy fixed color mode and Addrule(percentage>25% with "GREEN" color), i took another Addrule(Percentage<25% with "RED" color)

now i am geeting wrong color code as like attachment.

for negative percentage -73% it should in "RED" color as per my condition.

how to over come this issue .

i would like to show percentage>25% in "GREEN" and percentage<25%(with negative values) in "RED" color.

答:
If the value axis of your crosstable is the percentage, then you can get the behavior you are looking for by entering a rule in the coloring of the crosstable like:

[Axis.Color]<.25

The rule should be entered under the percentage color scheme grouping.


问:
How can I optimize the performance of my application based on a profile?
I have profiled my application and found out that not my functions are causing the delay I see but the winform functions. How can I correct this? For explanation see this:

And this is the result of the profiling:

答:
You can't fix that.

The framework is calling down to the DispatchMessage function exposed by the Windows API, which is used to dispatch a message retrieved by a call to the GetMessage function to the window procedure for a particular window.

The "slow" part here is Windows itself. When that becomes your bottleneck, your application is sufficiently optimized, and there's nothing more you can do.

Also, those profile results aren't necessarily telling you that this function is slow. Rather, they're telling you that it gets called a lot ("Hit Count"). The idea is that functions that get called a lot are "hot points" in your code, and it's worth taking some extra time to optimize their implementation (more bang for your buck). In this case, though, that function gets called a lot because it's how Windows processes messages for your app. In the world of unmanaged code and the native Windows API, messages are kind of like the events you use in .NET code. Since an event has to be raised for anything interesting to happen, the function that's responsible for calling or dispatching those events (messages) is bound to get called a lot.


问:
Replace spaces with colons in python
I have a string which is in keys-value pair format and separated by space. I want to separated by comma instead of space.

I tried replace function but its also replacing my values spaces with comma.

```<code>val = 'name=Ajay age=21 company=abc PVT LTD empid=12345'
</code>```

my desired output:

```<code>'name=Ajay,age=21,company=abc PVT LTD,empid=12345'
</code>```

答:
You could just match the <word>= pattern then replace them instead:

```<code>import re
val = 'name=Ajay age=21 company=abc PVT LTD empid=12345'

pattern = re.compile(r' \w+=')
pattern.sub(lambda match: match.group().replace(' ', ','), val)

# Output
# 'name=Ajay,age=21,company=abc PVT LTD,empid=12345'
</code>```

This should also be a good reference for how the sub works with the lambda

Title: Replace spaces with colons in python

Body:
I have a string which is in keys-value pair format and separated by space. I want to separated by comma instead of space.

I tried replace function but its also replacing my values spaces with comma.

val = 'name=Ajay age=21 company=abc PVT LTD empid=12345'

my desired output:

'name=Ajay,age=21,company=abc PVT LTD,empid=12345'

Body:
You could just match the <word>= pattern then replace them instead:

import re
val = 'name=Ajay age=21 company=abc PVT LTD empid=12345'

pattern = re.compile(r' \w+=')
pattern.sub(lambda match: match.group().replace(' ', ','), val)

# Output
# 'name=Ajay,age=21,company=abc PVT LTD,empid=12345'

This should also be a good reference for how the sub works with the lambda


问:
java.lang.NoClassDefFoundError: org/apache/kafka/clients/producer/Producer
I'm trying to use Kafka:

```<code>import java.util.Properties;
import org.apache.kafka.clients.producer.Producer;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;

public class SimpleProducer {
    public static void main(String[] args) {
        Properties props = new Properties();
        Producer<String, String> producer = new KafkaProducer<String, String>(props);
    }
}
</code>```

But getting the following error:

java.lang.NoClassDefFoundError:
  org/apache/kafka/clients/producer/Producer

build.gradle:

```<code>...

dependencies {
    testCompile group: 'junit', name: 'junit', version: '4.12'
    compile group: 'org.apache.kafka', name: 'kafka-clients', version: '2.2.0'
}

...
</code>```

答:
I had tried with the following dependency in gradle.

```<code>compile group: 'org.apache.kafka', name: 'kafka-clients', version: '2.1.0'
</code>```

Also, I provide below the code snippet for which I tested.

```<code>import java.util.Properties;
import org.apache.kafka.clients.producer.Callback;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.clients.producer.RecordMetadata;

public class Producer {

    public static void main(String[] args){
        Properties properties = new Properties();
        properties.put("bootstrap.servers", "192.168.119.139:9092");
        properties.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
        properties.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");

        KafkaProducer kafkaProducer = new KafkaProducer(properties);
        TestCallback callback = new TestCallback();
        try{
            for(int i = 0; i < 100; i++){
                System.out.println("----->"+i);
                kafkaProducer.send(new ProducerRecord("test", Integer.toString(i), "test message - " + i ));
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            kafkaProducer.close();
        }
    }

    private static class TestCallback implements Callback {
        @Override
        public void onCompletion(RecordMetadata recordMetadata, Exception e) {
            if (e != null) {
                System.out.println("Error while producing message to topic :" + recordMetadata);
                e.printStackTrace();
            } else {
                String message = String.format("sent message to topic:%s partition:%s  offset:%s", recordMetadata.topic(), recordMetadata.partition(), recordMetadata.offset());
                System.out.println(message);
            }
        }
    }
}
</code>```

I have tested this code using Eclipse IDE. Also remember, apache kafka client also downloads the following dependencies.

zstd-jni-1.3.5-4.jar

lz4-java-1.5.0.jar

snappy-java-1.1.7.2.jar

slf4j-api-1.7.25.jar

If you want to run using command you have to run by specifying the -classpath with a set of jar files. I provide an example below.

```<code>java.exe -Dfile.encoding=UTF-8 -classpath somelocation/a.jar;somelocation/b.jar;somelocation/c.jar
</code>```

If it still does not solve your problem, provide the application structure, post code details so that others can help you.

Body:
I'm trying to use Kafka:

import java.util.Properties;
import org.apache.kafka.clients.producer.Producer;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;

public class SimpleProducer {
    public static void main(String[] args) {
        Properties props = new Properties();
        Producer<String, String> producer = new KafkaProducer<String, String>(props);
    }
}

But getting the following error:

java.lang.NoClassDefFoundError:
  org/apache/kafka/clients/producer/Producer

build.gradle:

...

dependencies {
    testCompile group: 'junit', name: 'junit', version: '4.12'
    compile group: 'org.apache.kafka', name: 'kafka-clients', version: '2.2.0'
}

...

Body:
I had tried with the following dependency in gradle.

compile group: 'org.apache.kafka', name: 'kafka-clients', version: '2.1.0'

Also, I provide below the code snippet for which I tested.

import java.util.Properties;
import org.apache.kafka.clients.producer.Callback;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.clients.producer.RecordMetadata;

public class Producer {

    public static void main(String[] args){
        Properties properties = new Properties();
        properties.put("bootstrap.servers", "192.168.119.139:9092");
        properties.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
        properties.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");

        KafkaProducer kafkaProducer = new KafkaProducer(properties);
        TestCallback callback = new TestCallback();
        try{
            for(int i = 0; i < 100; i++){
                System.out.println("----->"+i);
                kafkaProducer.send(new ProducerRecord("test", Integer.toString(i), "test message - " + i ));
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            kafkaProducer.close();
        }
    }

    private static class TestCallback implements Callback {
        @Override
        public void onCompletion(RecordMetadata recordMetadata, Exception e) {
            if (e != null) {
                System.out.println("Error while producing message to topic :" + recordMetadata);
                e.printStackTrace();
            } else {
                String message = String.format("sent message to topic:%s partition:%s  offset:%s", recordMetadata.topic(), recordMetadata.partition(), recordMetadata.offset());
                System.out.println(message);
            }
        }
    }
}

I have tested this code using Eclipse IDE. Also remember, apache kafka client also downloads the following dependencies.

zstd-jni-1.3.5-4.jar

lz4-java-1.5.0.jar

snappy-java-1.1.7.2.jar

slf4j-api-1.7.25.jar

If you want to run using command you have to run by specifying the -classpath with a set of jar files. I provide an example below.

java.exe -Dfile.encoding=UTF-8 -classpath somelocation/a.jar;somelocation/b.jar;somelocation/c.jar

If it still does not solve your problem, provide the application structure, post code details so that others can help you.


问:
How to resolve SAML response error invalid name id policy
I'm setting up sso trough SAML using ADFS as identity provider and Nextcloud as service provider and I'm getting following errors: http://prntscr.com/nvba8f on nextcloud and http://prntscr.com/nvbb3w and http://prntscr.com/nvbbfp on adfs. This is my adfs claim issuer configuration 1) http://prntscr.com/nvbc8n
2) added rule on Claimes Provider Trusts http://prntscr.com/nvd5hl
Any and every answer is very appreciated  </p>

```<code><samlp:Response ID="_dba1e442-d44b-42da-a10b-b16d4daad325"
                Version="2.0"
                IssueInstant="2019-05-30T08:58:04.396Z"
                Destination="https://192.168.1.136/index.php/apps/user_saml/saml/acs"
                Consent="urn:oasis:names:tc:SAML:2.0:consent:unspecified"
                InResponseTo="ONELOGIN_5375bf1eef470709c2c4f2808e9d04f8c396518b"
                xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol">
  <Issuer xmlns="urn:oasis:names:tc:SAML:2.0:assertion">http://WindowsServer19.server.net/adfs/services/trust</Issuer>
  <ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
    <ds:SignedInfo>
      <ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#" />
      <ds:SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1" />
      <ds:Reference URI="#_dba1e442-d44b-42da-a10b-b16d4daad325">
        <ds:Transforms>
          <ds:Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" />
          <ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#" /></ds:Transforms>
        <ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" />
        <ds:DigestValue>eh+azCJ1VN90c8Oqm5m+ilgUndA=</ds:DigestValue>
      </ds:Reference>
    </ds:SignedInfo>
    <ds:SignatureValue>
2MjM+rjCAyqUKOedfJJpUFxJ/0YHV3SuaWl1t/tooXIeVaSoei38DzrbVW7aMBKh8xGD/4bJa2Wkaljb2UvY1RRWUbeFP7GrOjOwYhXzGnOyFKW3hCvy9DRpe+aWwk2iMNmjCJbJY28i5E5v2UjhsjNXZB08/LiapYjoEvA95xp3q0DKf1EPJHFeUnVw1wwHlvrdhgWOUsV/vuf1kAKM2IiRbzOkxH//ChSH0BplrUqN64ed3Qs97XGzuPTOKuDpUxXz8B28lacC6y9YoQzwNnIiCuAPN6Tw4Xk8kJDn/J93TLJXyUNFe9NwJGr3VYTegG16G7lcLxyERFWdtUMrOA==
</ds:SignatureValue>
    <KeyInfo
    xmlns="http://www.w3.org/2000/09/xmldsig#">
      <ds:X509Data>
        <ds:X509Certificate>
MIIC8DCCAdigAwIBAgIQMCGuwW//8oZPRuZYDplwVTANBgkqhkiG9w0BAQsFADA0MTIwMAYDVQQDEylBREZTIFNpZ25pbmcgLSBXaW5kb3dzU2VydmVyMTkuc2VydmVyLm5ldDAeFw0xOTA1MjMwMTM1MjJaFw0yMDA1MjIwMTM1MjJaMDQxMjAwBgNVBAMTKUFERlMgU2lnbmluZyAtIFdpbmRvd3NTZXJ2ZXIxOS5zZXJ2ZXIubmV0MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA7VQR25k7qgmSYMhh40HYEdaki0Itff0QfjpABaNLJJYLB51ikpK/PctqXDy2StJqo4ai3wcrM2xjcLKm7pOGpNYYF2Brdf8ae3i+gjh3Ej6vDYWs/YWve2yZarBkUxTSFlCLsUACIu5nuo7JmVU9ptPcmcKqEZamU1U04qt6RJzxKvLOdFa4nT2Nx1jM8lGyo+x4oJ0agaSORURdQQVSfIJMUuEXWufp0qeCRt3KrQHf6NzJYGvDCdF6bu5lsrXma+nEIxvs88qg7P15ntA+HTdxut3M9vLm+P2nvZMfxU+BKScBWpBfKDAkABF3PibCjnlr0pJ0ZUwPGsya180NAQIDAQABMA0GCSqGSIb3DQEBCwUAA4IBAQAl1f4+rQ3jG+8TfTNtnT/VX8DgXLCop8yrypU/i5AHeS9Xwmi2vqPwEkJQLd84ictIVU43NxtQPvj9RT6IjrwSaDqQcwVOcL0ectlp4cy9DsJsGfMPc3LczX6n07dRweCibRT7+aOGUNuBAi5Qwa63e68DEaHbg+hZkAd0G5gfVLvuKLWcGNUhdGAyHSUCZEXKNeWAVcpeL0JQeEAdPoTR1LA78RUW5PH/VMiEwXrB22T535m3z6YoPyrrWQnDBcXWJ5rIHtJPT58sB3VVHnV2VjNSBH+hS5fFOQ8pABmW+Z5ajpfy2DxdhtTaLt0hXuLpFon7b7/5XJI8ut57yG0E
</ds:X509Certificate>
      </ds:X509Data>
      </KeyInfo>
  </ds:Signature>
  <samlp:Status>
    <samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Requester">
      <samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:InvalidNameIDPolicy" /></samlp:StatusCode>
  </samlp:Status>
</samlp:Response>
</code>```

答:
The NameID needs to be in the format of "X509 Subject Name".

So take the attribute that you are using for NameID and do a Transform rule with an output of NameID and format of "X509 Subject Name".

Your current format is "email".

Body:
I'm setting up sso trough SAML using ADFS as identity provider and Nextcloud as service provider and I'm getting following errors: http://prntscr.com/nvba8f on nextcloud and http://prntscr.com/nvbb3w and http://prntscr.com/nvbbfp on adfs. This is my adfs claim issuer configuration 1) http://prntscr.com/nvbc8n
2) added rule on Claimes Provider Trusts http://prntscr.com/nvd5hl
Any and every answer is very appreciated

<samlp:Response ID="_dba1e442-d44b-42da-a10b-b16d4daad325"
                Version="2.0"
                IssueInstant="2019-05-30T08:58:04.396Z"
                Destination="https://192.168.1.136/index.php/apps/user_saml/saml/acs"
                Consent="urn:oasis:names:tc:SAML:2.0:consent:unspecified"
                InResponseTo="ONELOGIN_5375bf1eef470709c2c4f2808e9d04f8c396518b"
                xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol">
  <Issuer xmlns="urn:oasis:names:tc:SAML:2.0:assertion">http://WindowsServer19.server.net/adfs/services/trust</Issuer>
  <ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
    <ds:SignedInfo>
      <ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#" />
      <ds:SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1" />
      <ds:Reference URI="#_dba1e442-d44b-42da-a10b-b16d4daad325">
        <ds:Transforms>
          <ds:Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" />
          <ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#" /></ds:Transforms>
        <ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" />
        <ds:DigestValue>eh+azCJ1VN90c8Oqm5m+ilgUndA=</ds:DigestValue>
      </ds:Reference>
    </ds:SignedInfo>
    <ds:SignatureValue>
2MjM+rjCAyqUKOedfJJpUFxJ/0YHV3SuaWl1t/tooXIeVaSoei38DzrbVW7aMBKh8xGD/4bJa2Wkaljb2UvY1RRWUbeFP7GrOjOwYhXzGnOyFKW3hCvy9DRpe+aWwk2iMNmjCJbJY28i5E5v2UjhsjNXZB08/LiapYjoEvA95xp3q0DKf1EPJHFeUnVw1wwHlvrdhgWOUsV/vuf1kAKM2IiRbzOkxH//ChSH0BplrUqN64ed3Qs97XGzuPTOKuDpUxXz8B28lacC6y9YoQzwNnIiCuAPN6Tw4Xk8kJDn/J93TLJXyUNFe9NwJGr3VYTegG16G7lcLxyERFWdtUMrOA==
</ds:SignatureValue>
    <KeyInfo
    xmlns="http://www.w3.org/2000/09/xmldsig#">
      <ds:X509Data>
        <ds:X509Certificate>
MIIC8DCCAdigAwIBAgIQMCGuwW//8oZPRuZYDplwVTANBgkqhkiG9w0BAQsFADA0MTIwMAYDVQQDEylBREZTIFNpZ25pbmcgLSBXaW5kb3dzU2VydmVyMTkuc2VydmVyLm5ldDAeFw0xOTA1MjMwMTM1MjJaFw0yMDA1MjIwMTM1MjJaMDQxMjAwBgNVBAMTKUFERlMgU2lnbmluZyAtIFdpbmRvd3NTZXJ2ZXIxOS5zZXJ2ZXIubmV0MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA7VQR25k7qgmSYMhh40HYEdaki0Itff0QfjpABaNLJJYLB51ikpK/PctqXDy2StJqo4ai3wcrM2xjcLKm7pOGpNYYF2Brdf8ae3i+gjh3Ej6vDYWs/YWve2yZarBkUxTSFlCLsUACIu5nuo7JmVU9ptPcmcKqEZamU1U04qt6RJzxKvLOdFa4nT2Nx1jM8lGyo+x4oJ0agaSORURdQQVSfIJMUuEXWufp0qeCRt3KrQHf6NzJYGvDCdF6bu5lsrXma+nEIxvs88qg7P15ntA+HTdxut3M9vLm+P2nvZMfxU+BKScBWpBfKDAkABF3PibCjnlr0pJ0ZUwPGsya180NAQIDAQABMA0GCSqGSIb3DQEBCwUAA4IBAQAl1f4+rQ3jG+8TfTNtnT/VX8DgXLCop8yrypU/i5AHeS9Xwmi2vqPwEkJQLd84ictIVU43NxtQPvj9RT6IjrwSaDqQcwVOcL0ectlp4cy9DsJsGfMPc3LczX6n07dRweCibRT7+aOGUNuBAi5Qwa63e68DEaHbg+hZkAd0G5gfVLvuKLWcGNUhdGAyHSUCZEXKNeWAVcpeL0JQeEAdPoTR1LA78RUW5PH/VMiEwXrB22T535m3z6YoPyrrWQnDBcXWJ5rIHtJPT58sB3VVHnV2VjNSBH+hS5fFOQ8pABmW+Z5ajpfy2DxdhtTaLt0hXuLpFon7b7/5XJI8ut57yG0E
</ds:X509Certificate>
      </ds:X509Data>
      </KeyInfo>
  </ds:Signature>
  <samlp:Status>
    <samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Requester">
      <samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:InvalidNameIDPolicy" /></samlp:StatusCode>
  </samlp:Status>
</samlp:Response>


问:
How change a iframe content?

Possible Duplicate:

  How to change style of iframe content cross-domain?

Hi everybody.

Is it possible to change an iframe content if it comes from another site?
e.g.

```<code><html>
<head></head>
 <body>
  <iframe src="http://www.google.com"></iframe>
 </body>
</html>
</code>```

Thanks.

答: No, but you can communicate if both pages agree to do so, such as with window.postMessage. This is a security feature for your protection. Here's a link to a jquery plugin window.postMessage wrapper with location.hash fallback support.

Title: How change a iframe content?

Body:
Possible Duplicate:

  How to change style of iframe content cross-domain?

Hi everybody.

Is it possible to change an iframe content if it comes from another site?
e.g.

Thanks.


问:
Are character constants always positive?
I'm curious if I can compile

```<code>int map [] = { [ /*(unsigned char)*/ 'a' ]=1 };
</code>```

regardless of platform or if it's better to cast character constants to unsigned char prior to using them as indices.

答:
A character constant is a positive values of int, if it is based on a member of the basic execution-time character set.

Since a is in that basic character set, we know that 'a' is required to be positive.

On the other hand, for example, '\xFF' might not be positive. The FF value will be regarded as the bit pattern for a char†, which could be signed, giving us a -1 due to two's complement. Similar reasoning will apply if instead of a numeric escape, we use a character that corresponds to a negative value of type char, like characters corresponding to the 0x80-0xFF byte range on 8-bit systems.

It was like this in ANSI C89 and C90, where I'm relying on my memory; but the requirements persist through newer drafts and standards. In the n1570 draft, we have these items:

6.4.4.4 Character Constants, paragraph 10: "If an integer character constant contains a single character or escape sequence, its value is the one that results when an object with type char whose value is that of the single character or escape sequence is converted to type int."

6.2.5 Types, paragraph 3: "If a member of the basic execution character set is stored in a char object, its value is guaranteed to be nonnegative."

A character constant is not a "char object", but the requirements in 6.4.4.4 specify that the value of a character constant is determined using the char representation: "... one that results when an object with type char whose value ...".

† The numeric escape sequences for an unprefixed character constants and those prefixed with L have an associated "corresponding type" which is unsigned and are required to be in that type's range (6.4.4.4 9). The idea is that character values are specified as an unsigned value, which gives their bit-wise representation which is then interpreted as char. This intent is also conveyed in Example 2 (6.4.4.4 13).

Body:
I'm curious if I can compile

int map [] = { [ /*(unsigned char)*/ 'a' ]=1 };

regardless of platform or if it's better to cast character constants to unsigned char prior to using them as indices.


问:
Creating table with dimension as rows and days between dates as columns
I have a data set of tickets broken into categories based on their operational category. I also calculated the time in between the start date and resolve date for each of these tickets. I want to display the count of each number of days to resolve per category.

Such as this:

I have tried including my calculated days to resolve variable as a column header but it is not working.

答:
You might find this simpler formula helpful, for this or other cases:

```<code>IF DATEDIFF('day',[reported_date_DT],[last_resolved_date_DT]) < 30 THEN
    str(DATEDIFF('day',[reported_date_DT],[last_resolved_date_DT]))
ELSEIF DATEDIFF('day',[reported_date_DT],[last_resolved_date_DT]) >= 30 THEN "30+"
ELSE "Still Open"
END
</code>```

You might also find it useful to create another calculated field, such as [Time to Resolution] with formula

```<code>DATEDIFF('day',[reported_date_DT],[last_resolved_date_DT])
</code>```

It should default to being a Measure but you'll sometimes want to use it as a Dimension, such as in this question.  You can drag it to the Dimensions area on the left, or, when it is being used in a visualization, right-click it and choose the Discrete option.  (Note that Measure vs. Dimension isn't exactly the same as Continuous vs. Discrete, but usually line up...if things are weird play with both of them until you get what you want!)

This would probably help with analyzing the data in general, and simplify the original formula to

```<code>IF [Time to Resolution] < 30 THEN str([Time to Resolution])
ELSEIF [Time to Resolution] >= 30 THEN "30+"
ELSE "Still Open"
END
</code>```

(Note that the choice of 30+ vs. >30 is just aesthetic.  I find that the "+" is more eye-catching and intuitive, especially for business users, it sorts a bit better and lines up left-justified numbers.  Obviously the >= needs to change to just > if you go with >.)

Body:
You might find this simpler formula helpful, for this or other cases:

IF DATEDIFF('day',[reported_date_DT],[last_resolved_date_DT]) < 30 THEN
    str(DATEDIFF('day',[reported_date_DT],[last_resolved_date_DT]))
ELSEIF DATEDIFF('day',[reported_date_DT],[last_resolved_date_DT]) >= 30 THEN "30+"
ELSE "Still Open"
END

You might also find it useful to create another calculated field, such as [Time to Resolution] with formula

DATEDIFF('day',[reported_date_DT],[last_resolved_date_DT])

It should default to being a Measure but you'll sometimes want to use it as a Dimension, such as in this question.  You can drag it to the Dimensions area on the left, or, when it is being used in a visualization, right-click it and choose the Discrete option.  (Note that Measure vs. Dimension isn't exactly the same as Continuous vs. Discrete, but usually line up...if things are weird play with both of them until you get what you want!)

This would probably help with analyzing the data in general, and simplify the original formula to

IF [Time to Resolution] < 30 THEN str([Time to Resolution])
ELSEIF [Time to Resolution] >= 30 THEN "30+"
ELSE "Still Open"
END

(Note that the choice of 30+ vs. >30 is just aesthetic.  I find that the "+" is more eye-catching and intuitive, especially for business users, it sorts a bit better and lines up left-justified numbers.  Obviously the >= needs to change to just > if you go with >.)


问:
How to correctly design a regular expression in pymongo?
I use python 3.7.1 (default, Dec 14 2018, 19:28:38), and pymongo 3.7.2.

In mongodb this works:

```<code>db.collection.find(
    {$and:[
    {"field":{$regex:"bon?"}},
    {"field":{$not:{$regex:"bon souple"}}},
    {"field":{$not:{$regex:"bon léger"}}}
    ]}
    )
</code>```

So in pymongo I did the same as:

```<code>db.collection.find(
    {"$and":[
    {"field":{"$regex":"bon?"}},
    {"field":{"$not":{"$regex":"bon souple"}}},
    {"field":{"$not":{"$regex":"bon léger"}}}
    ]}
    )
</code>```

but it indicatespymongo.errors.OperationFailure: $regex has to be a string.

So I tried this as proposed here:

```<code>liste_reg=[
{'field': {'$regex': {'$not': re.compile('bon souple')}}},
{'field': {'$regex': {'$not': re.compile('bon léger')}}},
{'field': {'$regex': re.compile('bon?')}}
]
rslt=list(
    db.collection.find({"$and":liste_reg})
)
</code>```

I noticed that even when there is no special character it indicates the same error:

```<code>liste_reg=[
{'field': {'$regex': {'$not': re.compile('bon souple')}}} #where no special char is present
]
rslt=list(
    db.collection.find({"$and":liste_reg})
)
</code>```

So I tried to use "/" as:

```<code>liste_reg=[
{'field': {'$regex': {'$not':'/bon souple/'}}} #where no special char is present
#even tried re.compile('/bon souple/')
]
rslt=list(
    db.collection.find({"$and":liste_reg})
)
</code>```

the same error pymongo.errors.OperationFailure: $regex has to be a string still occurs.

What can I do?

SOME UPDATE OF MY RESEARCH OF SOLUTION

the core of the issue seems to be with $not because when I do:

```<code>liste_reg=[{'field': {'$regex': 'bon?'}}]
rslt=list(
    db.collection.find({"$and":liste_reg})
)
len(rslt)#gives 23 013, what is ok.
</code>```

There is no error.

SOME SAMPLES

As asked by Emma I can give a sample, and it will explicit my request in mongo.
Normally I must have these modalities in the field:

sec

très léger

léger

bon léger

bon

bon souple

souple

très souple

collant

lourd

très Lourd

profond

The main problem for me is my spider did not parse correctly because I did not write a strong enough script for that.
Instead of obtaining just "bon", I obtain this kind of result:

```<code>{"_id":"ID1",
"field":"bon\r\n\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\tnon",
...}
</code>```

and that's an example between many others wrong parsing.
So that's why I want result that begins with "bon?" but not "bon souple" or "bon léger" because they have correct values, no \n or \t.

So as samples:

```<code>[{"_id":"ID1",
"field":"bon\r\n\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\tnon"},
{"_id":"ID2",
"field":"bon\r\n\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\tpremière"},
{"_id":"ID3",
"field":"bon\r\n\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\t2ème"},
{"_id":"ID4",
"field":"bon souple"},
{"_id":"ID5",
"field":"bon léger"}]
</code>```

答:
I just ran into this same issue.

Try doing this:

```<code>liste_reg=[
{'field': {'$not': re.compile('bon souple')}},
{'field': {'$not': re.compile('bon léger')}},
{'field': {'$regex': re.compile('bon?')}}
]
rslt=list(
    db.collection.find({"$and":liste_reg})
)
</code>```

I just removed the $regex part of the query.

Background

I tried doing {item["type"]: {"$not": item['name']}} and pymongo returned a $not needs a regex or a document error.

So, I tried: {item["type"]: {"$not": {"$regex": item['name']}}} and pymongo returned a $not cannot have a regex error.

I found this SO https://stackoverflow.com/a/20175230/9069964 and here's what finally worked for me:

```<code>item_name = item["name"]
{item["type"]: {"$not": re.compile(item_name)}}
</code>```

I had to ditch the "$regex" part and give "$not" my regex stuff.

Body:
I use python 3.7.1 (default, Dec 14 2018, 19:28:38), and pymongo 3.7.2.

In mongodb this works:

db.collection.find(
    {$and:[
    {"field":{$regex:"bon?"}},
    {"field":{$not:{$regex:"bon souple"}}},
    {"field":{$not:{$regex:"bon léger"}}}
    ]}
    )

So in pymongo I did the same as:

db.collection.find(
    {"$and":[
    {"field":{"$regex":"bon?"}},
    {"field":{"$not":{"$regex":"bon souple"}}},
    {"field":{"$not":{"$regex":"bon léger"}}}
    ]}
    )

but it indicatespymongo.errors.OperationFailure: $regex has to be a string.

So I tried this as proposed here:

liste_reg=[
{'field': {'$regex': {'$not': re.compile('bon souple')}}},
{'field': {'$regex': {'$not': re.compile('bon léger')}}},
{'field': {'$regex': re.compile('bon?')}}
]
rslt=list(
    db.collection.find({"$and":liste_reg})
)

I noticed that even when there is no special character it indicates the same error:

liste_reg=[
{'field': {'$regex': {'$not': re.compile('bon souple')}}} #where no special char is present
]
rslt=list(
    db.collection.find({"$and":liste_reg})
)

So I tried to use "/" as:

liste_reg=[
{'field': {'$regex': {'$not':'/bon souple/'}}} #where no special char is present
#even tried re.compile('/bon souple/')
]
rslt=list(
    db.collection.find({"$and":liste_reg})
)

the same error pymongo.errors.OperationFailure: $regex has to be a string still occurs.

What can I do?

SOME UPDATE OF MY RESEARCH OF SOLUTION

the core of the issue seems to be with $not because when I do:

liste_reg=[{'field': {'$regex': 'bon?'}}]
rslt=list(
    db.collection.find({"$and":liste_reg})
)
len(rslt)#gives 23 013, what is ok.

There is no error.

SOME SAMPLES

As asked by Emma I can give a sample, and it will explicit my request in mongo.
Normally I must have these modalities in the field:

sec

très léger

léger

bon léger

bon

bon souple

souple

très souple

collant

lourd

très Lourd

profond

The main problem for me is my spider did not parse correctly because I did not write a strong enough script for that.
Instead of obtaining just "bon", I obtain this kind of result:

{"_id":"ID1",
"field":"bon\r\n\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\tnon",
...}

and that's an example between many others wrong parsing.
So that's why I want result that begins with "bon?" but not "bon souple" or "bon léger" because they have correct values, no \n or \t.

So as samples:

[{"_id":"ID1",
"field":"bon\r\n\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\tnon"},
{"_id":"ID2",
"field":"bon\r\n\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\tpremière"},
{"_id":"ID3",
"field":"bon\r\n\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\t2ème"},
{"_id":"ID4",
"field":"bon souple"},
{"_id":"ID5",
"field":"bon léger"}]

Body:
I just ran into this same issue.

Try doing this:

liste_reg=[
{'field': {'$not': re.compile('bon souple')}},
{'field': {'$not': re.compile('bon léger')}},
{'field': {'$regex': re.compile('bon?')}}
]
rslt=list(
    db.collection.find({"$and":liste_reg})
)

I just removed the $regex part of the query.

Background

I tried doing {item["type"]: {"$not": item['name']}} and pymongo returned a $not needs a regex or a document error.

So, I tried: {item["type"]: {"$not": {"$regex": item['name']}}} and pymongo returned a $not cannot have a regex error.

I found this SO https://stackoverflow.com/a/20175230/9069964 and here's what finally worked for me:

item_name = item["name"]
{item["type"]: {"$not": re.compile(item_name)}}

I had to ditch the "$regex" part and give "$not" my regex stuff.


问:
How to divide string by comma into new columns?
I researched a lot and didn't find exactly what I am trying to do. I am trying to divide a string into new columns. Most articles I found divide up in new rows, that is not my goal. I am pulling the data from a Redshift db.

Here is sample string in Column 1 in CURRENT STATE:

```<code>Column 1='a,b,c,1,2,3'
</code>```

Here is the DESIRED structure:

```<code>Column 2='a'
Column 3='b'
Column 4='c'
Column 5='1'
...
</code>```

How can this be achieved?

答:
If the number of columns being outputted is fixed then you can use Redshift's String_Part function.

```<code>SELECT col1,
    STRING_PART(col1, ',', 1) as Col2,
    STRING_PART(col1, ',', 2) as Col3,
    STRING_PART(col1, ',', 3) as Col4
FROM yourtable
</code>```

That would split col1 from yourtable into 3 columns containing the 1st, 2nd, and 3rd item from the list delimited by a comma.

Body:
I researched a lot and didn't find exactly what I am trying to do. I am trying to divide a string into new columns. Most articles I found divide up in new rows, that is not my goal. I am pulling the data from a Redshift db.

Here is sample string in Column 1 in CURRENT STATE:

Column 1='a,b,c,1,2,3'

Here is the DESIRED structure:

Column 2='a'
Column 3='b'
Column 4='c'
Column 5='1'
...

How can this be achieved?

Body:
If the number of columns being outputted is fixed then you can use Redshift's String_Part function.

SELECT col1,
    STRING_PART(col1, ',', 1) as Col2,
    STRING_PART(col1, ',', 2) as Col3,
    STRING_PART(col1, ',', 3) as Col4
FROM yourtable

That would split col1 from yourtable into 3 columns containing the 1st, 2nd, and 3rd item from the list delimited by a comma.


问:
Update database from view
View.py

```<code>@login_required
def UnosPosudbe(request):
    if request.method == 'GET':
        forma = PosudbaForma()
    elif request.method == 'POST':
        forma = PosudbaForma(request.POST,request.FILES)
        if forma.is_valid():
            #Dohvacanje Kolicine
            kolicinaKnjige = str(forma.cleaned_data['nazivKnjige'])
            IDKnjige = kolicinaKnjige

            kolicinaKnjige = kolicinaKnjige[-1:]
            IDKnjige = IDKnjige[:1]

            unesenaKolicina = forma.cleaned_data['kolicina']
            if(int(kolicinaKnjige)>=unesenaKolicina and unesenaKolicina > 0):
                #update kolicine
                knjiga = Knjiga.objects.get(pk=IDKnjige)
                knjiga.kolicina = int(knjiga.kolicina) - int(unesenaKolicina)
                print(knjiga)
                knjiga_forma = KnjigaForma(request.POST, instance = knjiga)
                knjiga_forma.save()
                #
                forma.save()
                return redirect('pregledPosudbe')
    return render(request, 'unosPosudbe.html', {'forma':forma})
</code>```

I am trying to update database with part of code but I am keep getting error:

```<code>knjiga = Knjiga.objects.get(pk=IDKnjige)
                knjiga.kolicina = int(knjiga.kolicina) - int(unesenaKolicina)
                print(knjiga)
                knjiga_forma = KnjigaForma(request.POST, instance = knjiga)
                knjiga_forma.save()
</code>```

Error:

ValueError at /UnosPosudbe/ The Knjiga could not be changed because
  the data didn't validate.

I am not sure what I am doing wrong?

Models.py

```<code>class Knjiga(models.Model):
    naziv = models.CharField(null=False, blank=True, max_length=120)
    autor = models.ForeignKey(Autor, on_delete=models.CASCADE, null=True)
    datumObjave = models.DateField(null=True, blank=False)
    izdanje = models.CharField(null=True, blank=True, max_length=120)
    slika= models.FileField(upload_to='images/', null=True, verbose_name="") #videofile
    kolicina = models.IntegerField(null=False, blank=False)

    def __str__(self):
        return str(self.id) + ', ' +str(self.naziv) + ', ' + str(self.autor) + ', Kolicina:' + str(self.kolicina)
</code>```

-----UPDATE----

Everything works for above problem.
But now I want to do when I delete created line that it gets quantity back to my "knjiga.kolicina".

Delete works like:

@login_required
def deletePosudbe(request, id):
    data = Posudba.objects.get(id=id)

```<code>IDKnjige = data
kolicinaKnjige = IDKnjige[-1:]
IDKnjige = IDKnjige[:1]

print(kolicinaKnjige)
print(IDKnjige)

data.delete()
return redirect('pregledPosudbe')
</code>```

I get error:

TypeError at /deletePosudbe/22 'Posudba' object is not subscriptable

I am trying to do same to fetch ID and quantity and update it back.

答:
Where is validation of KnjigaForma(request.POST, instance=knjiga) ? you need it...

```<code>from django.db.models import F
@login_required
def UnosPosudbe(request):
    if request.method == 'GET':
        forma = PosudbaForma()
    elif request.method == 'POST':
        forma = PosudbaForma(request.POST,request.FILES)
        if forma.is_valid():
            #Dohvacanje Kolicine
            kolicinaKnjige = str(forma.cleaned_data['nazivKnjige'])
            IDKnjige = kolicinaKnjige

            kolicinaKnjige = kolicinaKnjige[-1:]
            IDKnjige = IDKnjige[:1]

            unesenaKolicina = forma.cleaned_data['kolicina']
            if(int(kolicinaKnjige)>=unesenaKolicina and unesenaKolicina > 0):
                #update kolicine
                knjiga = Knjiga.objects.get(pk=IDKnjige)
                knjiga.kolicina = int(knjiga.kolicina) - int(unesenaKolicina) # This is better option (Everything happens on the database side. more safe) => knjiga.kolicina = F('kolicina') - int(unesenaKolicina)
                knjiga.save() # add save method here
                print(knjiga)
                knjiga_forma = KnjigaForma(request.POST, instance = knjiga)
                if knjiga_forma.is_valid(): # add this line
                    knjiga_forma.save()
                forma.save()
                return redirect('pregledPosudbe')
    return render(request, 'unosPosudbe.html', {'forma':forma})
</code>```

and your delete view

```<code>from django.http import HttpResponseNotFound

@login_required
def deletePosudbe(request, id):
    try
        data = Posudba.objects.get(id=id)
    except Posudba.DoesNotExist:
        return HttpResponseNotFound('Resource does not exist!')
    else:
        print('data => ', data)
        print('data.__dict__ => ', data.__dict__)
        data.delete() # you can delete safe way now.
    return redirect('pregledPosudbe')
</code>```

I hope, this code will work. Good luck.

Title: Update database from view

Body:
View.py

@login_required
def UnosPosudbe(request):
    if request.method == 'GET':
        forma = PosudbaForma()
    elif request.method == 'POST':
        forma = PosudbaForma(request.POST,request.FILES)
        if forma.is_valid():
            #Dohvacanje Kolicine
            kolicinaKnjige = str(forma.cleaned_data['nazivKnjige'])
            IDKnjige = kolicinaKnjige

            kolicinaKnjige = kolicinaKnjige[-1:]
            IDKnjige = IDKnjige[:1]

            unesenaKolicina = forma.cleaned_data['kolicina']
            if(int(kolicinaKnjige)>=unesenaKolicina and unesenaKolicina > 0):
                #update kolicine
                knjiga = Knjiga.objects.get(pk=IDKnjige)
                knjiga.kolicina = int(knjiga.kolicina) - int(unesenaKolicina)
                print(knjiga)
                knjiga_forma = KnjigaForma(request.POST, instance = knjiga)
                knjiga_forma.save()
                #
                forma.save()
                return redirect('pregledPosudbe')
    return render(request, 'unosPosudbe.html', {'forma':forma})

I am trying to update database with part of code but I am keep getting error:

knjiga = Knjiga.objects.get(pk=IDKnjige)
                knjiga.kolicina = int(knjiga.kolicina) - int(unesenaKolicina)
                print(knjiga)
                knjiga_forma = KnjigaForma(request.POST, instance = knjiga)
                knjiga_forma.save()

Error:

ValueError at /UnosPosudbe/ The Knjiga could not be changed because
  the data didn't validate.

I am not sure what I am doing wrong?

Models.py

class Knjiga(models.Model):
    naziv = models.CharField(null=False, blank=True, max_length=120)
    autor = models.ForeignKey(Autor, on_delete=models.CASCADE, null=True)
    datumObjave = models.DateField(null=True, blank=False)
    izdanje = models.CharField(null=True, blank=True, max_length=120)
    slika= models.FileField(upload_to='images/', null=True, verbose_name="") #videofile
    kolicina = models.IntegerField(null=False, blank=False)

    def __str__(self):
        return str(self.id) + ', ' +str(self.naziv) + ', ' + str(self.autor) + ', Kolicina:' + str(self.kolicina)

-----UPDATE----

Everything works for above problem.
But now I want to do when I delete created line that it gets quantity back to my "knjiga.kolicina".

Delete works like:

@login_required
def deletePosudbe(request, id):
    data = Posudba.objects.get(id=id)

IDKnjige = data
kolicinaKnjige = IDKnjige[-1:]
IDKnjige = IDKnjige[:1]

print(kolicinaKnjige)
print(IDKnjige)

data.delete()
return redirect('pregledPosudbe')

I get error:

TypeError at /deletePosudbe/22 'Posudba' object is not subscriptable

I am trying to do same to fetch ID and quantity and update it back.

Body:
Where is validation of KnjigaForma(request.POST, instance=knjiga) ? you need it...

from django.db.models import F
@login_required
def UnosPosudbe(request):
    if request.method == 'GET':
        forma = PosudbaForma()
    elif request.method == 'POST':
        forma = PosudbaForma(request.POST,request.FILES)
        if forma.is_valid():
            #Dohvacanje Kolicine
            kolicinaKnjige = str(forma.cleaned_data['nazivKnjige'])
            IDKnjige = kolicinaKnjige

            kolicinaKnjige = kolicinaKnjige[-1:]
            IDKnjige = IDKnjige[:1]

            unesenaKolicina = forma.cleaned_data['kolicina']
            if(int(kolicinaKnjige)>=unesenaKolicina and unesenaKolicina > 0):
                #update kolicine
                knjiga = Knjiga.objects.get(pk=IDKnjige)
                knjiga.kolicina = int(knjiga.kolicina) - int(unesenaKolicina) # This is better option (Everything happens on the database side. more safe) => knjiga.kolicina = F('kolicina') - int(unesenaKolicina)
                knjiga.save() # add save method here
                print(knjiga)
                knjiga_forma = KnjigaForma(request.POST, instance = knjiga)
                if knjiga_forma.is_valid(): # add this line
                    knjiga_forma.save()
                forma.save()
                return redirect('pregledPosudbe')
    return render(request, 'unosPosudbe.html', {'forma':forma})

and your delete view

from django.http import HttpResponseNotFound

@login_required
def deletePosudbe(request, id):
    try
        data = Posudba.objects.get(id=id)
    except Posudba.DoesNotExist:
        return HttpResponseNotFound('Resource does not exist!')
    else:
        print('data => ', data)
        print('data.__dict__ => ', data.__dict__)
        data.delete() # you can delete safe way now.
    return redirect('pregledPosudbe')

I hope, this code will work. Good luck.


问:
How access event listeners of an object instantiated on runtime in java swing
I have a custom made JPanel itemSmallCard(String prodID, String productName, String price, String retailer), using this I created multiple instances of it in another JPanel with different parameters on the ActionPerformed event of a button as follows:

JPanel iC = new itemSmallCard("123456789ab", "Inspiron 7567 Intel Core i5 DELL Laptop", "48957", "Cloudtail Pvt. Ltd.");
        mainContentPane.add(iC);
        mainContentPane.revalidate();
        mainContentPane.repaint();
```

However as all the new JPanels were created with this same code using the same variable iC,  I don't know how to access a particular JPanel variable from them, thus also unable to access its event listeners.
How can I achieve that?

答:
You need to write a generic listener:

in the listener code you use the getSource() method to get the source of the event.

Once you know the source component you can use the getParent() method of the component.

Now you have access to the panel and you can access any method/variable of the panel.

Body:
I have a custom made JPanel itemSmallCard(String prodID, String productName, String price, String retailer), using this I created multiple instances of it in another JPanel with different parameters on the ActionPerformed event of a button as follows:

JPanel iC = new itemSmallCard("123456789ab", "Inspiron 7567 Intel Core i5 DELL Laptop", "48957", "Cloudtail Pvt. Ltd.");
        mainContentPane.add(iC);
        mainContentPane.revalidate();
        mainContentPane.repaint();

However as all the new JPanels were created with this same code using the same variable iC,  I don't know how to access a particular JPanel variable from them, thus also unable to access its event listeners.
How can I achieve that?


问:
Flask-migrate can't find custom modules
I've made some changes to my SQLAlchemy models and I want to migrate them to my db. When I try to migrate, I get the following error:

```<code>$ flask db migrate
Usage: flask db migrate [OPTIONS]

Error: While importing "minerva.dashboard.app", an ImportError was raised:

Traceback (most recent call last):
  File "/home/mattfred/Minerva/envs/dashboard/lib/python3.7/site-packages/flask/cli.py", line 235, in locate_app
    __import__(module_name)
  File "/home/mattfred/Minerva/minerva/dashboard/app.py", line 13, in <module>
    from templates.nav_layout import *
ModuleNotFoundError: No module named 'templates'
</code>```

I don't know what has changed since I first initialized the db, other than moving the views into separate files instead of 1.

I can actually resolve this by changing the import statement to

```<code>from .templates.nav_layout import *
</code>```

but then I get this error when trying to run the app:

```<code>Traceback (most recent call last):
  File "app.py", line 13, in <module>
    from .templates.nav_layout import *
ModuleNotFoundError: No module named '__main__.templates'; '__main__' is not a package
</code>```

I've tried the solution presented here: Flask-Migrate "ModuleNotFoundError"

but that runs with no errors and doesn't change my db.

If I remove that line, it just moves to the next templates file and then the Config file, so I don't think there's anything wrong with the templates file.

```<code># app.py
import os

from flask import Flask, redirect
from flask_login import login_required, LoginManager
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_socketio import SocketIO, emit, disconnect

from werkzeug.wsgi import DispatcherMiddleware

from dash import Dash

from templates.nav_layout import *
from templates.dash_app_layout import *

from Config import Config, DEBUG

# Setup the Flask server
server = Flask(__name__)
server.config.from_object(Config)

db = SQLAlchemy(server)
migrate = Migrate(server, db)

@server.shell_context_processor
def make_shell_context():
    from Models import Users, Company
    return {'db': db, 'Users': Users, 'Company': Company}
</code>```

I'm fairly certain this has something to do with the project structure

```<code>├── app.py
├── Config.py
├── Forms.py
├── __init__.py
├── manage.py
├── migrations/
├── Models.py
├── requirements.txt
├── templates
│   ├── change_profile.html
│   ├── dash_app_layout.py
│   ├── default_login.html
│   ├── default_logout.html
│   ├── _formhelpers.html
│   ├── header.html
│   ├── index.html
│   ├── __init__.py
│   ├── nav_layout.py
│   ├── record_meeting.html
│   ├── register_user.html
│   ├── upload_meeting.html
│   └── voice_enroll.html
├── utils
│   ├── audio_processor
│   │   ├── AudioProcessor.py
│   │   ├── audio_type_converter.py
│   │   ├── Deidentifier.py
│   │   ├── Identification
│   │   │   ├── CreateProfile.py
│   │   │   ├── DeleteProfile.py
│   │   ├── __init__.py
│   │   ├── Utterance.py
│   │   └── voice_enroll.py
│   ├── db_operations.py
│   ├── __init__.py
│   ├── interim_result_processor.py
│   └── utils.py
└── views
    ├── auth.py
    ├── dash_callbacks.py
    ├── __init__.py
    ├── meeting_upload.py
    ├── profile.py
    └── record_meeting.py
</code>```

答: Based on the discussion in the comments, the issue was that the top-level directory had a __init__.py file. Removing that file addressed the weird import behavior.

Title: Flask-migrate can't find custom modules

Body:
I've made some changes to my SQLAlchemy models and I want to migrate them to my db. When I try to migrate, I get the following error:

$ flask db migrate
Usage: flask db migrate [OPTIONS]

Error: While importing "minerva.dashboard.app", an ImportError was raised:

Traceback (most recent call last):
  File "/home/mattfred/Minerva/envs/dashboard/lib/python3.7/site-packages/flask/cli.py", line 235, in locate_app
    __import__(module_name)
  File "/home/mattfred/Minerva/minerva/dashboard/app.py", line 13, in <module>
    from templates.nav_layout import *
ModuleNotFoundError: No module named 'templates'

I don't know what has changed since I first initialized the db, other than moving the views into separate files instead of 1.

I can actually resolve this by changing the import statement to

from .templates.nav_layout import *

but then I get this error when trying to run the app:

Traceback (most recent call last):
  File "app.py", line 13, in <module>
    from .templates.nav_layout import *
ModuleNotFoundError: No module named '__main__.templates'; '__main__' is not a package

I've tried the solution presented here: Flask-Migrate "ModuleNotFoundError"

but that runs with no errors and doesn't change my db.

If I remove that line, it just moves to the next templates file and then the Config file, so I don't think there's anything wrong with the templates file.

# app.py
import os

from flask import Flask, redirect
from flask_login import login_required, LoginManager
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_socketio import SocketIO, emit, disconnect

from werkzeug.wsgi import DispatcherMiddleware

from dash import Dash

from templates.nav_layout import *
from templates.dash_app_layout import *

from Config import Config, DEBUG

# Setup the Flask server
server = Flask(__name__)
server.config.from_object(Config)

db = SQLAlchemy(server)
migrate = Migrate(server, db)

@server.shell_context_processor
def make_shell_context():
    from Models import Users, Company
    return {'db': db, 'Users': Users, 'Company': Company}

I'm fairly certain this has something to do with the project structure

├── app.py
├── Config.py
├── Forms.py
├── __init__.py
├── manage.py
├── migrations/
├── Models.py
├── requirements.txt
├── templates
│   ├── change_profile.html
│   ├── dash_app_layout.py
│   ├── default_login.html
│   ├── default_logout.html
│   ├── _formhelpers.html
│   ├── header.html
│   ├── index.html
│   ├── __init__.py
│   ├── nav_layout.py
│   ├── record_meeting.html
│   ├── register_user.html
│   ├── upload_meeting.html
│   └── voice_enroll.html
├── utils
│   ├── audio_processor
│   │   ├── AudioProcessor.py
│   │   ├── audio_type_converter.py
│   │   ├── Deidentifier.py
│   │   ├── Identification
│   │   │   ├── CreateProfile.py
│   │   │   ├── DeleteProfile.py
│   │   ├── __init__.py
│   │   ├── Utterance.py
│   │   └── voice_enroll.py
│   ├── db_operations.py
│   ├── __init__.py
│   ├── interim_result_processor.py
│   └── utils.py
└── views
    ├── auth.py
    ├── dash_callbacks.py
    ├── __init__.py
    ├── meeting_upload.py
    ├── profile.py
    └── record_meeting.py


问:
why is mySQL missing a column?
This statement is not populating the image_path column. I have copied and pasted column names from phpMyAdmin to ensure accuracy.</p>

```<code>INSERT INTO (theme_name, theme_path, image_path)
VALUES ('',
        '/Applications/MAMP/htdocs/waggleb/wp-content/plugins/app-switcher/themes/Original/',
        '/Applications/MAMP/htdocs/waggleb/wp-content/plugins/app-switcher/thumbnails/original.png')
</code>```

答:
you missed the table name</p>

```<code>INSERT INTO  TABLENAME(theme_name, theme_path, image_path)
VALUES ('',
        '/Applications/MAMP/htdocs/waggleb/wp-content/plugins/app-switcher/themes/Original/',
        '/Applications/MAMP/htdocs/waggleb/wp-content/plugins/app-switcher/thumbnails/original.png')
</code>```

Title: why is mySQL missing a column?

Body:
This statement is not populating the image_path column. I have copied and pasted column names from phpMyAdmin to ensure accuracy.

INSERT INTO (theme_name, theme_path, image_path)
VALUES ('',
        '/Applications/MAMP/htdocs/waggleb/wp-content/plugins/app-switcher/themes/Original/',
        '/Applications/MAMP/htdocs/waggleb/wp-content/plugins/app-switcher/thumbnails/original.png')

Body:
you missed the table name

INSERT INTO  TABLENAME(theme_name, theme_path, image_path)
VALUES ('',
        '/Applications/MAMP/htdocs/waggleb/wp-content/plugins/app-switcher/themes/Original/',
        '/Applications/MAMP/htdocs/waggleb/wp-content/plugins/app-switcher/thumbnails/original.png')


问:
How to connect an ASP.NET site in IIS to its SQL Server database
I am running my ASP.NET application in IIS as a site. When I go to login to the website through the SQL Server database, it returns an error. I can run the web application through Visual Studio using IIS Express without any issues.

I have looked at tutorials saying to check my connection string.

<connectionStrings>
    <add name="DefaultConnection"
         connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-VideoStore-20190515111127.mdf;Initial Catalog=aspnet-VideoStore-20190515111127;Integrated Security=True"
         providerName="System.Data.SqlClient" />
</connectionStrings>
```

This is the error:

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 50 - Local Database Runtime error occurred. Cannot create an automatic instance. See the Windows Application event log for error details.)

I use the Server Explorer to look at the Data Connections>Default Connection (Video Store) to see the database in Visual Studio. Can someone point me in the right direction?

答: The user that the application is running as under IIS does not have permission to the database you have specified in your connection string. When you are running the site under VS the user is running as your local windows user. When you deploy to IIS it is running as the application pool user. Check what user this is running under by going to IIS > Sites > Right Click The Site > Manage WebSite > Advanced Settings. That is the user it is running as and that user may need to have SQL access.</p>

Body:
I am running my ASP.NET application in IIS as a site. When I go to login to the website through the SQL Server database, it returns an error. I can run the web application through Visual Studio using IIS Express without any issues.

I have looked at tutorials saying to check my connection string.

<connectionStrings>
    <add name="DefaultConnection"
         connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-VideoStore-20190515111127.mdf;Initial Catalog=aspnet-VideoStore-20190515111127;Integrated Security=True"
         providerName="System.Data.SqlClient" />
</connectionStrings>

This is the error:

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 50 - Local Database Runtime error occurred. Cannot create an automatic instance. See the Windows Application event log for error details.)

I use the Server Explorer to look at the Data Connections>Default Connection (Video Store) to see the database in Visual Studio. Can someone point me in the right direction?


问:
How to add array of object to an entry of odata array
I want to add a array of objects to a specific entry of an odata array.
It is a JSON-Model in sapui5 and I wanted to do oModel.getData()[j].setProperty(""), but this does not. Can anyone help?

I have:

```<code>    [{
            attributes: (5) [{…}, {…}, {…}, {…}, {…}]
            creationDate: "2019-05-20T09:14:16.622Z"
            deleted: false
            eventDate: "20.05.19"
            message: "Aufgabe xyz"
            object: "Aufgabe"
    },
{
            attributes: (5) [{…}, {…}, {…}, {…}, {…}]
            creationDate: "2019-05-20T09:14:16.622Z"
            deleted: false
            eventDate: "21.05.19"
            message: "Aufgabe"
            object: "Aufgabe"    }
]
</code>```

And I want to add a new Item:

```<code>[{
        description: "Ereignisgruppe"
        key: "objectGroup"
        value: "Aufgaben"
    },{
        description: "Ereignis"
        key: "object"
        value: "Aufgabe"
   }]
</code>```

To get this:

```<code> [{
                attributes: (5) [{…}, {…}, {…}, {…}, {…}]
                creationDate: "2019-05-20T09:14:16.622Z"
                deleted: false
                eventDate: "20.05.19"
                message: "Aufgabe xyz"
                object: "Aufgabe",
                masterAttributes: (2) [{…}, {…}]        <-------------- new
        },
    {
                attributes: (5) [{…}, {…}, {…}, {…}, {…}]
                creationDate: "2019-05-20T09:14:16.622Z"
                deleted: false
                eventDate: "21.05.19"
                message: "Aufgabe"
                object: "Aufgabe"
   }]
</code>```

Best regards!

答:
```<code>    // es6
let oModel= [{
                        attributes: [],
                        creationDate: "2019-05-20T09:14:16.622Z",
                        deleted: false,
                        eventDate: "20.05.19"  ,
                        message: "Aufgabe xyz",
                        object: "Aufgabe"
                },
            {
                        attributes: [],
                        creationDate: "2019-05-20T09:14:16.622Z",
                        deleted: false,
                        eventDate: "21.05.19",
                        message: "Aufgabe",
                        object: "Aufgabe"    }
            ];

            let masterAttributes = [{
                description: "Ereignisgruppe",
                key: "objectGroup",
                value: "Aufgaben"
            },{
                description: "Ereignis",
                key: "object",
                value: "Aufgabe",
           }];
           let newData = { ...oModel, [0]: { ...oModel[0], masterAttributes: masterAttributes}};
           console.log(newData);
</code>```

Body:
I want to add a array of objects to a specific entry of an odata array.
It is a JSON-Model in sapui5 and I wanted to do oModel.getData()[j].setProperty(""), but this does not. Can anyone help?

I have:

    [{
            attributes: (5) [{…}, {…}, {…}, {…}, {…}]
            creationDate: "2019-05-20T09:14:16.622Z"
            deleted: false
            eventDate: "20.05.19"
            message: "Aufgabe xyz"
            object: "Aufgabe"
    },
{
            attributes: (5) [{…}, {…}, {…}, {…}, {…}]
            creationDate: "2019-05-20T09:14:16.622Z"
            deleted: false
            eventDate: "21.05.19"
            message: "Aufgabe"
            object: "Aufgabe"    }
]

And I want to add a new Item:

[{
        description: "Ereignisgruppe"
        key: "objectGroup"
        value: "Aufgaben"
    },{
        description: "Ereignis"
        key: "object"
        value: "Aufgabe"
   }]

To get this:

 [{
                attributes: (5) [{…}, {…}, {…}, {…}, {…}]
                creationDate: "2019-05-20T09:14:16.622Z"
                deleted: false
                eventDate: "20.05.19"
                message: "Aufgabe xyz"
                object: "Aufgabe",
                masterAttributes: (2) [{…}, {…}]        <-------------- new
        },
    {
                attributes: (5) [{…}, {…}, {…}, {…}, {…}]
                creationDate: "2019-05-20T09:14:16.622Z"
                deleted: false
                eventDate: "21.05.19"
                message: "Aufgabe"
                object: "Aufgabe"
   }]

Best regards!


问:
Why std::get does not work with variables?
I am running into a trouble of understanding how functions, especially template functions and local variables behave during the compilation time.

So this code works well with std::get:

```<code>enum class UserInfoFields{name, email, address};

using UserInfo = std::tuple<std::string, std::string, std::string>;

int main()
{
    UserInfo s{"Edmund", "edmund@page.me", "Denver street 19"};
    std::cout << std::get<static_cast<size_t>(UserInfoFields::name)>(s) << std::endl;
    return 0;
}
</code>```

This from my understanding is because std::get is a template function and it requires a template argument to be known during the compilation. That makes sense as static_cast<... gives us the value during the compilation time.

What I do not understand, if I change the main() code to this:

```<code> int main()
{
    UserInfo s{"Edmund", "edmund@page.me", "Denver street 19"};
    auto a = static_cast<size_t>(UserInfoFields::name);
    std::cout << std::get<a>(s) << std::endl;
    return 0;
}
</code>```

This is not allowed. I know that I have to use constexpr but I want to know, why exactly the second code does not work?

答:
Template non-type parameters, like the size_t that std::get<> takes, must be compile time constants.

Your auto a is not a compile time constant.  In your specific case, you can prove that the value a has at that point will never vary and always be 0.

But C++ is a strongly typed language that relies on explicit types provided by the programmer.  At the point where std::get is evaluated, the only thing C++ permits itself to know about a is that it is a non-const non-constexpr local variable of type std::size_t.

Thus if std::get works, so must:

```<code>int main(int argv, char ** argc) {
  UserInfo s{"Edmund", "edmund@page.me", "Denver street 19"};
  std::size_t a = argv; // number of arguments
  std::cout << std::get<a>(s) << std::endl;
}
</code>```

std::get<std::size_t> is a nothrow function, and it is not permitted to fail at runtime.  If you call this code with 100 arguments, the above code cannot possibly work.

Second, while your UserInfo is 3 identical types, std::get<size_t>(tuple) works when the types are not the same.  So

```<code>using UserInfo = std::tuple<int, std::string, double>;
</code>```

then std::get< argv >( some_user_info ) also has to work.  And in this case, the type it returns can be any one of three types -- but C++ demands that all expressions have one type.

The short version is "the language standard says so".  The longer version is "In the general case, your code doesn't work".

Now, you can solve your code in your specific case with a few changes.

```<code>using UserInfo = std::array<std::string, 3>;
</code>```

now UserInfo is known to have 3 uniform types.

```<code>std::cout << s[a] << std::endl;
</code>```

and now you pass in the index, and as the argument to [] isn't a template non-type parameter, it can vary at runtime.

[] is permitted to execute UB if the index is out of bounds.  (std::get is not).

Now, the C++ could evolve and the new standard could throw some magic and somehow detect your special case and permit std get to fail at runtime etc.  But then every call to std::get is a possible runtime failure, while before it was not; the testing surface of your application just exploded.

Heck, it could auto-detect that auto a = blah was initialized with a constant expression on the previous line, and make its use on the next line automatically be a constant expression.

But then a programmer who knew what they are doing who replaced a call to get_proper_a() with 3 for debugging could have their code spuriously change behaviour as secret type information "leaks" into the code.  And when get_proper_a() which actually returns 3 (but the compiler cannot prove it) runs, the code breaks at runtime.

Body:
I am running into a trouble of understanding how functions, especially template functions and local variables behave during the compilation time.

So this code works well with std::get:

enum class UserInfoFields{name, email, address};

using UserInfo = std::tuple<std::string, std::string, std::string>;

int main()
{
    UserInfo s{"Edmund", "edmund@page.me", "Denver street 19"};
    std::cout << std::get<static_cast<size_t>(UserInfoFields::name)>(s) << std::endl;
    return 0;
}

This from my understanding is because std::get is a template function and it requires a template argument to be known during the compilation. That makes sense as static_cast<... gives us the value during the compilation time.

What I do not understand, if I change the main() code to this:

 int main()
{
    UserInfo s{"Edmund", "edmund@page.me", "Denver street 19"};
    auto a = static_cast<size_t>(UserInfoFields::name);
    std::cout << std::get(s) << std::endl;
    return 0;
}

This is not allowed. I know that I have to use constexpr but I want to know, why exactly the second code does not work?

Body:
Template non-type parameters, like the size_t that std::get<> takes, must be compile time constants.

Your auto a is not a compile time constant.  In your specific case, you can prove that the value a has at that point will never vary and always be 0.

But C++ is a strongly typed language that relies on explicit types provided by the programmer.  At the point where std::get<a> is evaluated, the only thing C++ permits itself to know about a is that it is a non-const non-constexpr local variable of type std::size_t.

Thus if std::get<a> works, so must:

int main(int argv, char ** argc) {
  UserInfo s{"Edmund", "edmund@page.me", "Denver street 19"};
  std::size_t a = argv; // number of arguments
  std::cout << std::get<a>(s) << std::endl;
}

std::get<std::size_t> is a nothrow function, and it is not permitted to fail at runtime.  If you call this code with 100 arguments, the above code cannot possibly work.

Second, while your UserInfo is 3 identical types, std::get<size_t>(tuple<a,b,c>) works when the types are not the same.  So

using UserInfo = std::tuple<int, std::string, double>;

then std::get< argv >( some_user_info ) also has to work.  And in this case, the type it returns can be any one of three types -- but C++ demands that all expressions have one type.

The short version is "the language standard says so".  The longer version is "In the general case, your code doesn't work".

Now, you can solve your code in your specific case with a few changes.

using UserInfo = std::array<std::string, 3>;

now UserInfo is known to have 3 uniform types.

std::cout << s[a] << std::endl;

and now you pass in the index, and as the argument to [] isn't a template non-type parameter, it can vary at runtime.

[] is permitted to execute UB if the index is out of bounds.  (std::get<a> is not).

Now, the C++ could evolve and the new standard could throw some magic and somehow detect your special case and permit std get to fail at runtime etc.  But then every call to std::get is a possible runtime failure, while before it was not; the testing surface of your application just exploded.

Heck, it could auto-detect that auto a = blah was initialized with a constant expression on the previous line, and make its use on the next line automatically be a constant expression.

But then a programmer who knew what they are doing who replaced a call to get_proper_a() with 3 for debugging could have their code spuriously change behaviour as secret type information "leaks" into the code.  And when get_proper_a() which actually returns 3 (but the compiler cannot prove it) runs, the code breaks at runtime.


问:
make/Makefile: CLI option to "disable" a dependency from a target
I'm exploring a feature of some software that's used in a very mature Makefile to see if that feature can be incorporated into the flow. There is a target like the following:

```<code>my_target: dependency_1 dependency_2
        echo foo
        touch bar
        # etc...
</code>```

In regular use, dependency_2 would always be called before my_target's commands were executed. But for my exploration purposes, I want to selectively call dependency_2 from its own make command. And then make my_target after, possibly several times, without re-doing dependency_2 each time.

For the time being I just copy/pasted my_target into my_target_2 and removed the dependency from my_target_2 (easy enough), but I'm wondering if there's a command-line option to disable a target's dependency without modifying the file.

EDIT: dependency_2 is a PHONY target

答:
There's no way to do this without editing the makefile, that I can think of.

You can put dependency_2 into a variable then use the variable in the prerequisite list of my_target:

```<code>dependency_2 = dependency_2

my_target : dependency_1 $(dependency_2)
</code>```

then when you don't want to rebuild it, run make dependency_2= to reset the variable to empty.

Body:
I'm exploring a feature of some software that's used in a very mature Makefile to see if that feature can be incorporated into the flow. There is a target like the following:

my_target: dependency_1 dependency_2
        echo foo
        touch bar
        # etc...

In regular use, dependency_2 would always be called before my_target's commands were executed. But for my exploration purposes, I want to selectively call dependency_2 from its own make command. And then make my_target after, possibly several times, without re-doing dependency_2 each time.

For the time being I just copy/pasted my_target into my_target_2 and removed the dependency from my_target_2 (easy enough), but I'm wondering if there's a command-line option to disable a target's dependency without modifying the file.

EDIT: dependency_2 is a PHONY target

Body:
There's no way to do this without editing the makefile, that I can think of.

You can put dependency_2 into a variable then use the variable in the prerequisite list of my_target:

dependency_2 = dependency_2

my_target : dependency_1 $(dependency_2)

then when you don't want to rebuild it, run make dependency_2= to reset the variable to empty.


问:
How to override Spring Boot library properties?
I would like to override the library properties that I've written in project that is using it. I'm using this Spring guide on creating library: https://spring.io/guides/gs/multi-module/

I would like to know how to override for example my.properties file in the project that uses my library.

Is it even possible?

答:
Depends on how the library property file specifies properties. If the properties are looked up from environment/system first, then you can override in your code. If hard-coded, then not.
For example:

```<code>prop=${ENV_VAR:abc}
</code>```

You can set ENV_VAR environment variable, or env-var system variable in your code to override the value of prop. If you don’t, the default value abc will be used.

Body:
Depends on how the library property file specifies properties. If the properties are looked up from environment/system first, then you can override in your code. If hard-coded, then not.
For example:

prop=${ENV_VAR:abc}

You can set ENV_VAR environment variable, or env-var system variable in your code to override the value of prop. If you don’t, the default value abc will be used.