问:
Converting Scorm's lesson_location into its xAPI equivalent
I have a SCORM package which stores the current location the learner is on the content as follows

```<code>API.LMSSetValue("cmi.core.lesson_location", currentPage);
</code>```

I would want set the current location of the user in its tin Can Xapi version as well.

But I am confused verb is visiting a read only content page
Completed , Mastered or experienced ?

& what Activity could thatverb be associated with

Some one may answer please ....

答:
ADL created a SCORM Profile for xAPI. Its purpose is to give people using SCORM a way to convert that data to xAPI. Some of it can be converted into xAPI statements like your completed statement above. These statements tend to describe actions the learner is taking in the content (success, completion, answered a question, played a video).

Other SCORM data isn't as much about the learner as about the content, such as lesson_location. That stuff doesn't fit well in a statement. So xAPI also has API endpoints for this other stuff like activity state and activity profile information. The SCORM Profile uses activity state in xAPI to store that information because lesson_location is describing the state of the activity, see the lesson_location description in the SCORM Profile.

Hopefully that helps. As for your bookmarklet link, that is a small script you can bookmark in your browser that will post a statement that you visited that page, not a script that can be used to bookmark your SCORM lesson_location.

Body:
I have a SCORM package which stores the current location the learner is on the content as follows

API.LMSSetValue("cmi.core.lesson_location", currentPage);

I would want set the current location of the user in its tin Can Xapi version as well.

But I am confused verb is visiting a read only content page
Completed , Mastered or experienced ?

& what Activity could thatverb be associated with

Some one may answer please ....


来源: stackexchange

问:
sorting the array of objects keys from another array
How can i merge the array of objects based on the key

```<code>let data = [
  {
    "fields": [
      {
        "key": "terminal",
        "value": null
      },
      {
        "key": "status",
        "value": "Enabled"
      },
      {
        "key": "area",
        "value": null
      },
      {
        "key": "note",
        "value": "Some key notes"
      },
      {
        "key": "group",
        "value": "Medium"
      },
      {
        "key": "level",
        "value": null
      }
    ],
    "name": "test 1",
    "number": "123456127890",
    "id": "yqweyqweu213"
  },
  {
    "fields": [
      {
        "key": "terminal",
        "value": null
      },
      {
        "key": "status",
        "value": "Disabled"
      },
      {
        "key": "area",
        "value": "Delhi"
      },
      {
        "key": "note",
        "value": "Some key orginal notes"
      },
      {
        "key": "group",
        "value": "Medium"
      },
      {
        "key": "level",
        "value": "High"
      }
    ],
    "name": "test 2",
    "number": "173276123612",
    "id": "uqweyewueyyuqwe"
  },
  {
    "fields": [
      {
        "key": "terminal",
        "value": 1
      },
      {
        "key": "status",
        "value": "Enabled"
      },
      {
        "key": "area",
        "value": "Mumbai"
      },
      {
        "key": "note",
        "value": "Some key orginal sample notes"
      },
      {
        "key": "group",
        "value": "Low"
      },
      {
        "key": "level",
        "value": null
      }
    ],
    "name": "test 3",
    "number": "128737812381723",
    "id": "kasjdashdkaskjd"
  }
]

const orderArr = [
  "area",
  "terminal",
  "note",
  "status",
  "group",
  "level"
]
</code>```

Tried with the below snippet

```<code> data.forEach(o => {
  let keys = []
  o.fields.forEach(f => {
    keys.push(f.key)
  })
  let sortedKeys =  keys.sort(function(a, b) {
    return orderOfFields.indexOf(a) - orderOfFields.indexOf(b);
   })
   let obj = {}
   sortedKeys.forEach(s => {
     obj[s] = // how to get the value
   })
   return obj
 })
</code>```

expectedResult is

```<code>  let expectedData = [
    {
      "fields": [
        {
          "key": "area",
          "value": null
        },
        {
          "key": "terminal",
          "value": null
        },
        {
          "key": "note",
          "value": "Some key notes"
        },
        {
          "key": "status",
          "value": "Enabled"
        },
        {
          "key": "group",
          "value": "Medium"
        },
        {
          "key": "level",
          "value": null
        }
      ],
      "name": "test 1",
      "number": "123456127890",
      "id": "yqweyqweu213"
    },
    {
      "fields": [
        {
          "key": "area",
          "value": "Delhi"
        },
        {
          "key": "terminal",
          "value": null
        },

        {
          "key": "note",
          "value": "Some key orginal notes"
        },
        {
          "key": "status",
          "value": "Disabled"
        },

        {
          "key": "group",
          "value": "Medium"
        },
        {
          "key": "level",
          "value": "High"
        }
      ],
      "name": "test 2",
      "number": "173276123612",
      "id": "uqweyewueyyuqwe"
    },
    {
      "fields": [
        {
          "key": "area",
          "value": "Mumbai"
        },
        {
          "key": "terminal",
          "value": 1
        },
        {
          "key": "note",
          "value": "Some key orginal sample notes"
        },
        {
          "key": "status",
          "value": "Enabled"
        },

        {
          "key": "group",
          "value": "Low"
        },
        {
          "key": "level",
          "value": null
        }
      ],
      "name": "test 3",
      "number": "128737812381723",
      "id": "kasjdashdkaskjd"
    }
  ]
</code>```

答:
You don't have to get sortedKeys and then create an object. You could directly use indexOf inside sort's compareFunction. If a.key has a lower index in orderArrcomapred b.key, the subtraction will return -1 and a will be placed ahead of b.

const data=[{"fields":[{"key":"terminal","value":null},{"key":"status","value":"Enabled"},{"key":"area","value":null},{"key":"note","value":"Some key notes"},{"key":"group","value":"Medium"},{"key":"level","value":null}],"name":"test 1","number":"123456127890","id":"yqweyqweu213"},{"fields":[{"key":"terminal","value":null},{"key":"status","value":"Disabled"},{"key":"area","value":"Delhi"},{"key":"note","value":"Some key orginal notes"},{"key":"group","value":"Medium"},{"key":"level","value":"High"}],"name":"test 2","number":"173276123612","id":"uqweyewueyyuqwe"},{"fields":[{"key":"terminal","value":1},{"key":"status","value":"Enabled"},{"key":"area","value":"Mumbai"},{"key":"note","value":"Some key orginal sample notes"},{"key":"group","value":"Low"},{"key":"level","value":null}],"name":"test 3","number":"128737812381723","id":"kasjdashdkaskjd"}]
const orderArr=["area","terminal","note","status","group","level"]

data.forEach(o =>
  o.fields.sort((a, b) => orderArr.indexOf(a.key) - orderArr.indexOf(b.key))
)

console.log(data)```
</div>
</div>
</p>

<p>If you want a new array without mutating the original arary, you could use <code>map</code> like this:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const data=[{"fields":[{"key":"terminal","value":null},{"key":"status","value":"Enabled"},{"key":"area","value":null},{"key":"note","value":"Some key notes"},{"key":"group","value":"Medium"},{"key":"level","value":null}],"name":"test 1","number":"123456127890","id":"yqweyqweu213"},{"fields":[{"key":"terminal","value":null},{"key":"status","value":"Disabled"},{"key":"area","value":"Delhi"},{"key":"note","value":"Some key orginal notes"},{"key":"group","value":"Medium"},{"key":"level","value":"High"}],"name":"test 2","number":"173276123612","id":"uqweyewueyyuqwe"},{"fields":[{"key":"terminal","value":1},{"key":"status","value":"Enabled"},{"key":"area","value":"Mumbai"},{"key":"note","value":"Some key orginal sample notes"},{"key":"group","value":"Low"},{"key":"level","value":null}],"name":"test 3","number":"128737812381723","id":"kasjdashdkaskjd"}]
const orderArr=["area","terminal","note","status","group","level"]

const output = data.map(o => ({
  ...o,
  fields: [...o.fields].sort((a, b) => orderArr.indexOf(a.key) - orderArr.indexOf(b.key))
}))

console.log(output)</code>```

ContentLicense: CC BY-SA 4.0

Body:
How can i merge the array of objects based on the key

let data = [
  {
    "fields": [
      {
        "key": "terminal",
        "value": null
      },
      {
        "key": "status",
        "value": "Enabled"
      },
      {
        "key": "area",
        "value": null
      },
      {
        "key": "note",
        "value": "Some key notes"
      },
      {
        "key": "group",
        "value": "Medium"
      },
      {
        "key": "level",
        "value": null
      }
    ],
    "name": "test 1",
    "number": "123456127890",
    "id": "yqweyqweu213"
  },
  {
    "fields": [
      {
        "key": "terminal",
        "value": null
      },
      {
        "key": "status",
        "value": "Disabled"
      },
      {
        "key": "area",
        "value": "Delhi"
      },
      {
        "key": "note",
        "value": "Some key orginal notes"
      },
      {
        "key": "group",
        "value": "Medium"
      },
      {
        "key": "level",
        "value": "High"
      }
    ],
    "name": "test 2",
    "number": "173276123612",
    "id": "uqweyewueyyuqwe"
  },
  {
    "fields": [
      {
        "key": "terminal",
        "value": 1
      },
      {
        "key": "status",
        "value": "Enabled"
      },
      {
        "key": "area",
        "value": "Mumbai"
      },
      {
        "key": "note",
        "value": "Some key orginal sample notes"
      },
      {
        "key": "group",
        "value": "Low"
      },
      {
        "key": "level",
        "value": null
      }
    ],
    "name": "test 3",
    "number": "128737812381723",
    "id": "kasjdashdkaskjd"
  }
]

const orderArr = [
  "area",
  "terminal",
  "note",
  "status",
  "group",
  "level"
]

Tried with the below snippet

 data.forEach(o => {
  let keys = []
  o.fields.forEach(f => {
    keys.push(f.key)
  })
  let sortedKeys =  keys.sort(function(a, b) {
    return orderOfFields.indexOf(a) - orderOfFields.indexOf(b);
   })
   let obj = {}
   sortedKeys.forEach(s => {
     obj[s] = // how to get the value
   })
   return obj
 })

expectedResult is

  let expectedData = [
    {
      "fields": [
        {
          "key": "area",
          "value": null
        },
        {
          "key": "terminal",
          "value": null
        },
        {
          "key": "note",
          "value": "Some key notes"
        },
        {
          "key": "status",
          "value": "Enabled"
        },
        {
          "key": "group",
          "value": "Medium"
        },
        {
          "key": "level",
          "value": null
        }
      ],
      "name": "test 1",
      "number": "123456127890",
      "id": "yqweyqweu213"
    },
    {
      "fields": [
        {
          "key": "area",
          "value": "Delhi"
        },
        {
          "key": "terminal",
          "value": null
        },

        {
          "key": "note",
          "value": "Some key orginal notes"
        },
        {
          "key": "status",
          "value": "Disabled"
        },

        {
          "key": "group",
          "value": "Medium"
        },
        {
          "key": "level",
          "value": "High"
        }
      ],
      "name": "test 2",
      "number": "173276123612",
      "id": "uqweyewueyyuqwe"
    },
    {
      "fields": [
        {
          "key": "area",
          "value": "Mumbai"
        },
        {
          "key": "terminal",
          "value": 1
        },
        {
          "key": "note",
          "value": "Some key orginal sample notes"
        },
        {
          "key": "status",
          "value": "Enabled"
        },

        {
          "key": "group",
          "value": "Low"
        },
        {
          "key": "level",
          "value": null
        }
      ],
      "name": "test 3",
      "number": "128737812381723",
      "id": "kasjdashdkaskjd"
    }
  ]

Body:
You don't have to get sortedKeys and then create an object. You could directly use indexOf inside sort's compareFunction. If a.key has a lower index in orderArrcomapred b.key, the subtraction will return -1 and a will be placed ahead of b.

const data=[{"fields":[{"key":"terminal","value":null},{"key":"status","value":"Enabled"},{"key":"area","value":null},{"key":"note","value":"Some key notes"},{"key":"group","value":"Medium"},{"key":"level","value":null}],"name":"test 1","number":"123456127890","id":"yqweyqweu213"},{"fields":[{"key":"terminal","value":null},{"key":"status","value":"Disabled"},{"key":"area","value":"Delhi"},{"key":"note","value":"Some key orginal notes"},{"key":"group","value":"Medium"},{"key":"level","value":"High"}],"name":"test 2","number":"173276123612","id":"uqweyewueyyuqwe"},{"fields":[{"key":"terminal","value":1},{"key":"status","value":"Enabled"},{"key":"area","value":"Mumbai"},{"key":"note","value":"Some key orginal sample notes"},{"key":"group","value":"Low"},{"key":"level","value":null}],"name":"test 3","number":"128737812381723","id":"kasjdashdkaskjd"}]
const orderArr=["area","terminal","note","status","group","level"]

data.forEach(o =>
  o.fields.sort((a, b) => orderArr.indexOf(a.key) - orderArr.indexOf(b.key))
)

console.log(data)

If you want a new array without mutating the original arary, you could use map like this:

const data=[{"fields":[{"key":"terminal","value":null},{"key":"status","value":"Enabled"},{"key":"area","value":null},{"key":"note","value":"Some key notes"},{"key":"group","value":"Medium"},{"key":"level","value":null}],"name":"test 1","number":"123456127890","id":"yqweyqweu213"},{"fields":[{"key":"terminal","value":null},{"key":"status","value":"Disabled"},{"key":"area","value":"Delhi"},{"key":"note","value":"Some key orginal notes"},{"key":"group","value":"Medium"},{"key":"level","value":"High"}],"name":"test 2","number":"173276123612","id":"uqweyewueyyuqwe"},{"fields":[{"key":"terminal","value":1},{"key":"status","value":"Enabled"},{"key":"area","value":"Mumbai"},{"key":"note","value":"Some key orginal sample notes"},{"key":"group","value":"Low"},{"key":"level","value":null}],"name":"test 3","number":"128737812381723","id":"kasjdashdkaskjd"}]
const orderArr=["area","terminal","note","status","group","level"]

const output = data.map(o => ({
  ...o,
  fields: [...o.fields].sort((a, b) => orderArr.indexOf(a.key) - orderArr.indexOf(b.key))
}))

console.log(output)


问:
What is the default reference path for Visual Studio extensions?
I'm creating a Visual Studio Extension. This is a VSIX project.

I've added a reference to the project which I installed using NuGet.

At runtime, however, an error message is thrown. Cannot find file.... [name of dll].

What I would like to do is try and manually install this dll to the reference path that Visual Studio uses, so that it can resolve correctly.

答:
Looks like your problem is very similar to this

But also there is a solution what we are using in our extensions.
You can create your own installer and move all necessary files into your specific folder. For this behavior you need to specify full path to your main integration dll in pkgdef

```<code>"CodeBase"="C:\Program Files (x86)\CompanyName\ProductName\integration.dll"
</code>```

and vsixmanifest

```<code><Asset Type="Microsoft.VisualStudio.MefComponent" Path="C:\Program Files (x86)\CompanyName\ProductName\integration.dll" />
</code>```

files.

For VS2019 Community pkgdef and vsixmanifest should be placed here c:\Program Files (x86)\Microsoft Visual Studio\2019\Community\Common7\IDE\Extensions\

Subscribe on AppDomain.CurrentDomain.AssemblyResolve. Wait when specific assembly with specific version! required - and load it from your folder (C:\Program Files (x86)\CompanyName\ProductName).

Body:
Looks like your problem is very similar to this

But also there is a solution what we are using in our extensions.
You can create your own installer and move all necessary files into your specific folder. For this behavior you need to specify full path to your main integration dll in pkgdef

"CodeBase"="C:\Program Files (x86)\CompanyName\ProductName\integration.dll"

and vsixmanifest

<Asset Type="Microsoft.VisualStudio.MefComponent" Path="C:\Program Files (x86)\CompanyName\ProductName\integration.dll" />

files.

For VS2019 Community pkgdef and vsixmanifest should be placed here c:\Program Files (x86)\Microsoft Visual Studio\2019\Community\Common7\IDE\Extensions\

Subscribe on AppDomain.CurrentDomain.AssemblyResolve. Wait when specific assembly with specific version! required - and load it from your folder (C:\Program Files (x86)\CompanyName\ProductName).


问:
Assert called with argument of specific type
I want to check in my test if a function is called with an argument of a specific class.

```<code>class Foo:
...
</code>```

I found mock.ANY, but there I cannot pass any class. What is want is:

```<code>test_mock.assert_called_with("expected string", ANY(spec=Foo))
</code>```

答:
I solved it with a custom matcher.

```<code>class TypeMatcher:

def __init__(self, expected_type):
    self.expected_type = expected_type

def __eq__(self, other):
    return isinstance(other, self.expected_type)
</code>```

And then test it like this:

```<code>test_mock.assert_called_with("expected string", TypeMatcher(Foo))
</code>```

Body:
I want to check in my test if a function is called with an argument of a specific class.

class Foo:
...

I found mock.ANY, but there I cannot pass any class. What is want is:

test_mock.assert_called_with("expected string", ANY(spec=Foo))

Body:
I solved it with a custom matcher.

class TypeMatcher:

def __init__(self, expected_type):
    self.expected_type = expected_type

def __eq__(self, other):
    return isinstance(other, self.expected_type)

And then test it like this:

test_mock.assert_called_with("expected string", TypeMatcher(Foo))


问:
C# App database - small, miltiple-form application - forms need to exchange data via database
To give you some background, the project I am working on is a poker tournament manager. It uses two forms - the main form will display information throughout the tournament, such as players remaining, player names, stakes, payout structure, time left etc; and the other form will be used as a 'setup' form. Both of these forms are built and working, but I am struggling to get them to share data with each other.

What I want to do is load the setup form, select my options for configuring the tournament, and then clicking 'save' will assign all of my options to variables and then write these variables to a database of some kind (I'm new to DB design and I haven't used any DB objects in Visual Studio yet). The main form can then read the DB and display the relevant data. The benefits I can see of this is that the tournament setup can be saved for future use, and player stats can be accumulated over time.

What sort of database object do I need to create to store this data, and how do I open connections etc and write data to the DB?

答:
I'd probably suggest that you use LINQ to SQL. ScottGu did an excellent series on blog posts on how to build a model with this. You only really need to read the first few for a simple CRUD application.

http://weblogs.asp.net/scottgu/archive/2007/05/19/using-linq-to-sql-part-1.aspx

http://weblogs.asp.net/scottgu/archive/2007/05/29/linq-to-sql-part-2-defining-our-data-model-classes.aspx

http://weblogs.asp.net/scottgu/archive/2007/06/29/linq-to-sql-part-3-querying-our-database.aspx

http://weblogs.asp.net/scottgu/archive/2007/07/11/linq-to-sql-part-4-updating-our-database.aspx

http://weblogs.asp.net/scottgu/archive/2007/07/16/linq-to-sql-part-5-binding-ui-using-the-asp-linqdatasource-control.aspx

http://weblogs.asp.net/scottgu/archive/2007/08/16/linq-to-sql-part-6-retrieving-data-using-stored-procedures.aspx

http://weblogs.asp.net/scottgu/archive/2007/08/23/linq-to-sql-part-7-updating-our-database-using-stored-procedures.aspx

http://weblogs.asp.net/scottgu/archive/2007/08/27/linq-to-sql-part-8-executing-custom-sql-expressions.aspx

http://weblogs.asp.net/scottgu/archive/2007/09/07/linq-to-sql-part-9-using-a-custom-linq-expression-with-the-lt-asp-linqdatasource-gt-control.aspx

Reference: http://msdn.microsoft.com/en-us/library/bb425822.aspx

ContentLicense: CC BY-SA 3.0


问:
Display data json (plot.ly) from influxdb
I'm trying to get a graph of my influxdb measurements.To display graphics, I use plot.ly and python. I started in python with a sql request to get my json data from localhost:8086, but it doesn't work. I've tried some things, I'm sending you my little piece of code:

import plotly
import plotly.plotly as py
import numpy as np
import plotly.graph_objs as go
import plotly.offline as ply
import pandas as pd
from plotly.tools import FigureFactory as FF

if __name__ == "__main__":
    df = pd.read_json('http://localhost:8086/query?q=SELECT%20%22I%22%20FROM%20%22michelin%22.%22autogen%22.%22mqtt_consumer%22%20WHERE%20time%20%3E%20now()%20-%202d%20AND%20%22topic%22=%27PI1%27')
    print(df['results'])
    #df = [go.Scatter(x=df['time'], y=df['mqtt_consumer.mean_I'])]
    ply.plot(df, filename = 'time-series-simple')

```

The link with the request shows me this :

I would like a time series, with the value "I" as a function of time.
If anyone can help me, thank you for your feedback

答:
To plot the data via Plot.ly, You need to create a trace first where you define the X, Y axis data.

```<code>import plotly.plotly as py
import plotly.graph_objs as go

trace = go.Scatter(
x = ("Your X data, Must be a numpy array"),
y = ("Your Y data, Must be a numpy array"),
mode = 'markers'
)

data = [trace]
</code>```

Then you can simply,

```<code>py.plot(data, filename='basic-line')
</code>```

Body:
I'm trying to get a graph of my influxdb measurements.To display graphics, I use plot.ly and python. I started in python with a sql request to get my json data from localhost:8086, but it doesn't work. I've tried some things, I'm sending you my little piece of code:

import plotly
import plotly.plotly as py
import numpy as np
import plotly.graph_objs as go
import plotly.offline as ply
import pandas as pd
from plotly.tools import FigureFactory as FF

if __name__ == "__main__":
    df = pd.read_json('http://localhost:8086/query?q=SELECT%20%22I%22%20FROM%20%22michelin%22.%22autogen%22.%22mqtt_consumer%22%20WHERE%20time%20%3E%20now()%20-%202d%20AND%20%22topic%22=%27PI1%27')
    print(df['results'])
    #df = [go.Scatter(x=df['time'], y=df['mqtt_consumer.mean_I'])]
    ply.plot(df, filename = 'time-series-simple')

The link with the request shows me this :

I would like a time series, with the value "I" as a function of time.
If anyone can help me, thank you for your feedback

Body:
To plot the data via Plot.ly, You need to create a trace first where you define the X, Y axis data.

import plotly.plotly as py
import plotly.graph_objs as go

trace = go.Scatter(
x = ("Your X data, Must be a numpy array"),
y = ("Your Y data, Must be a numpy array"),
mode = 'markers'
)

data = [trace]

Then you can simply,

py.plot(data, filename='basic-line')


问:
How to load datagrid binding information with a button?
I want a DataGrid to be filled or loaded when the user click the button "load"

This is my Grid:

```<code>  <Grid>
     <DataGrid Name="test" ItemsSource="{Binding Items}"  AutoGenerateColumns="True" Margin="0,0,286.4,190.6" />
     <Button Content="Load" Command="{Binding cmdReset_Click}" Margin="450,0,165.4,702.6"/>
  </Grid>
</code>```

and this is my ViewModel

```<code> namespace test.ViewModel
 {

    class ViewModel : INotifyPropertyChanged
    {

        public DelegateCommand cmdReset_Click { get; }

        public ViewModel()
        {
            cmdReset_Click = new DelegateCommand(Reset_Click);
            Items = GetData();
        }

        public class Log
        {
            public int ID { get; set; }
            public string PDO { get; set; }
            public string LOCATION { get; set; }
            public string HOSTAME { get; set; }
            public int SEVERITY { get; set; }
            public DateTime TIMESTAMP { get; set; }
            public string MESSAGE { get; set; }

        }

        public List<Log> Items { get; set; } = new List<Log>();

        private List<Log> GetData()
        {
                List<Log> logs = new List<Log>();
                    logs.Add(new Log()
                    {
                        PDO = "TEST",
                        ID = "TEST",
                        //LOCATION = "TEST",
                        HOSTAME = "TEST",
                        SEVERITY = "TEST",
                        TIMESTAMP = "TEST",
                        MESSAGE = "TEST",
                    });
                }
            return logs;
        }
        private void Reset_Click()
        {
            Items = GetData();
        }
    }
}
</code>```

Right now I am getting the list info after running the program. What I need to get this info AFTER the Button is clicked

答:
```<code>public partial class WebForm1 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void btnGenerate_Click(object sender, EventArgs e)
    {
        GridView1.DataSource = GetData();
        GridView1.DataBind();
    }

    private List<Log> GetData()
    {
        List<Log> logs = new List<Log>();
        logs.Add(new Log()
        {
            PDO = "test",
            ID = 100,
            HOSTAME = "test",
            SEVERITY = 5,
            TIMESTAMP = DateTime.Now,
            MESSAGE = "number",
        });
        return logs;
    }
}

public class Log
{
    public int ID { get; set; }
    public string PDO { get; set; }
    public string LOCATION { get; set; }
    public string HOSTAME { get; set; }
    public int SEVERITY { get; set; }
    public DateTime TIMESTAMP { get; set; }
    public string MESSAGE { get; set; }
}
</code>```

Body:
I want a DataGrid to be filled or loaded when the user click the button "load"

This is my Grid:

  <Grid>
     <DataGrid Name="test" ItemsSource="{Binding Items}"  AutoGenerateColumns="True" Margin="0,0,286.4,190.6" />
     <Button Content="Load" Command="{Binding cmdReset_Click}" Margin="450,0,165.4,702.6"/>
  </Grid>

and this is my ViewModel

 namespace test.ViewModel
 {

    class ViewModel : INotifyPropertyChanged
    {

        public DelegateCommand cmdReset_Click { get; }

        public ViewModel()
        {
            cmdReset_Click = new DelegateCommand(Reset_Click);
            Items = GetData();
        }

        public class Log
        {
            public int ID { get; set; }
            public string PDO { get; set; }
            public string LOCATION { get; set; }
            public string HOSTAME { get; set; }
            public int SEVERITY { get; set; }
            public DateTime TIMESTAMP { get; set; }
            public string MESSAGE { get; set; }

        }

        public List<Log> Items { get; set; } = new List<Log>();

        private List<Log> GetData()
        {
                List<Log> logs = new List<Log>();
                    logs.Add(new Log()
                    {
                        PDO = "TEST",
                        ID = "TEST",
                        //LOCATION = "TEST",
                        HOSTAME = "TEST",
                        SEVERITY = "TEST",
                        TIMESTAMP = "TEST",
                        MESSAGE = "TEST",
                    });
                }
            return logs;
        }
        private void Reset_Click()
        {
            Items = GetData();
        }
    }
}

Right now I am getting the list info after running the program. What I need to get this info AFTER the Button is clicked


问:
Eclipse C++ project with subfolders
I am solving a lot of LeetCode problems with C++.
I work in Eclipse and want to create a file structure like:

```<code>Leetcode
        Topic1
              Problem1
                     solution.cpp
              Problem2
                     solution.cpp
              Problem3
                     solution.cpp
        Topic2
              Problem1
                     solution.cpp
              Problem2
                     solution.cpp
              Problem3
                     solution.cpp
</code>```

I want every solution.cpp file to be run independently from all other solution files...

But whenever I create a subfolder inside project and place a cpp file there the project stops to Build and can't run. For example this doesn't build or run :

Leetcode/Binary_Search/349.Intersection-of-two-arrays/349.Intersection-of-Two-Arrays.cpp
  Leetcode/Binary_Search/4.Median-of-two-sorted-arrays/4.median-of-two-sorted-arrays.cpp
  Leetcode/Array/1.Two-Sum/1.Two-Sum.cpp

(here Leetcode is Workspace, _Binary_Search_ and Array are projects, 4.Media-of-two-sorted-arrays and 1.Two-Sum are Folders and respective *.cpp files are solutions)

I understand that I am lacking the knowledge of how Eclipse project folders for C++ are organized. Can anyone help me? If you send me a link for what to read I'll appreciate it.

答:
Here is a link that explains how the file structure of eclipse works

https://courses.cs.washington.edu/courses/cse143/11wi/eclipse-tutorial/file_organization.shtml

Title: Eclipse C++ project with subfolders

Body:
I am solving a lot of LeetCode problems with C++.
I work in Eclipse and want to create a file structure like:

Leetcode
        Topic1
              Problem1
                     solution.cpp
              Problem2
                     solution.cpp
              Problem3
                     solution.cpp
        Topic2
              Problem1
                     solution.cpp
              Problem2
                     solution.cpp
              Problem3
                     solution.cpp

I want every solution.cpp file to be run independently from all other solution files...

But whenever I create a subfolder inside project and place a cpp file there the project stops to Build and can't run. For example this doesn't build or run :

Leetcode/Binary_Search/349.Intersection-of-two-arrays/349.Intersection-of-Two-Arrays.cpp
  Leetcode/Binary_Search/4.Median-of-two-sorted-arrays/4.median-of-two-sorted-arrays.cpp
  Leetcode/Array/1.Two-Sum/1.Two-Sum.cpp

(here Leetcode is Workspace, _Binary_Search_ and Array are projects, 4.Media-of-two-sorted-arrays and 1.Two-Sum are Folders and respective *.cpp files are solutions)

I understand that I am lacking the knowledge of how Eclipse project folders for C++ are organized. Can anyone help me? If you send me a link for what to read I'll appreciate it.


问:
Lua and the white spaces in an OS
After reading this post, I used [[ ]] to put commands into the system. The problem is the following: The same structure:

```<code>local Program = [["c:\Archivos de programa\Automated QA\TestComplete 8\Bin\TestComplete.exe" ]];
local testcase = [["C:\svn_test\trunk\Automation\XMM\XMM.pjs" ]];
local options = [[/r /exit /p:XMMGeneralTest /t:"Script|main|Main" ]];

local cmd = Program..testcase..options;
print(cmd);
os.execute(cmd);

local tcLog = [[ C:\svn_test\trunk\Automation\XTYLE\XTyleGeneralTest\Log\11_04_2011_12_40_06_264\*]];
local zippedFile = "11_04_2011_12_40_06_264.7z ";
local sevenZip = [["c:\Archivos de Programa\7-Zip\7z.exe" a -t7z ]];

local cmd = sevenZip..zippedFile..tcLog;
print(cmd);
os.execute(cmd);
</code>```

The same code produce different results. The first one doesn't run:

```<code>"c:\Archivos" not recognized as internal command or external,
program...
</code>```

The second one runs perfectly.

How can I resolve this?

答:
I also don't have a windows system to test with, so this is just a guess:

Try replacing this:

```<code>local Program = [["c:\Archivos de programa\Automated QA\TestComplete 8\Bin\TestComplete.exe" ]];
</code>```

with this:

```<code>local Program = [[c:\\Archivos\ de\ programa\\Automated\ QA\\TestComplete\ 8\\Bin\\TestComplete.exe ]];
</code>```

I fear that it won't work since the [[ and ]] will block the interpretation of the escapes, but that may change as it goes from one variable to another and then to the os.execute.  The other option is to use the windows version of these files without spaces, e.g.:

```<code>local Program = [[c:\Archiv~1\Automa~1\TestCo~1\Bin\TestComplete.exe ]];
</code>```

Title: Lua and the white spaces in an OS

Body:
After reading this post, I used [[ ]] to put commands into the system. The problem is the following: The same structure:

local Program = [["c:\Archivos de programa\Automated QA\TestComplete 8\Bin\TestComplete.exe" ]];
local testcase = [["C:\svn_test\trunk\Automation\XMM\XMM.pjs" ]];
local options = [[/r /exit /p:XMMGeneralTest /t:"Script|main|Main" ]];

local cmd = Program..testcase..options;
print(cmd);
os.execute(cmd);

local tcLog = [[ C:\svn_test\trunk\Automation\XTYLE\XTyleGeneralTest\Log\11_04_2011_12_40_06_264\*]];
local zippedFile = "11_04_2011_12_40_06_264.7z ";
local sevenZip = [["c:\Archivos de Programa\7-Zip\7z.exe" a -t7z ]];

local cmd = sevenZip..zippedFile..tcLog;
print(cmd);
os.execute(cmd);

The same code produce different results. The first one doesn't run:

"c:\Archivos" not recognized as internal command or external,
program...

The second one runs perfectly.

How can I resolve this?

Body:
I also don't have a windows system to test with, so this is just a guess:

Try replacing this:

local Program = [["c:\Archivos de programa\Automated QA\TestComplete 8\Bin\TestComplete.exe" ]];

with this:

local Program = [[c:\\Archivos\ de\ programa\\Automated\ QA\\TestComplete\ 8\\Bin\\TestComplete.exe ]];

I fear that it won't work since the [[ and ]] will block the interpretation of the escapes, but that may change as it goes from one variable to another and then to the os.execute.  The other option is to use the windows version of these files without spaces, e.g.:

local Program = [[c:\Archiv~1\Automa~1\TestCo~1\Bin\TestComplete.exe ]];


问:
Can I scroll a ScrollView programmatically in Android?
Is there any way to scroll a ScrollView programmatically to a certain position?

I have created dynamic TableLayout which is placed in a ScrollView. So I want that on a specific action (like clicking a Button, etc.) the particular row should scroll automatically to a top position.

Is it possible?

答:
```<code>private int totalHeight = 0;

ViewTreeObserver ScrollTr = loutMain.getViewTreeObserver();
ScrollTr.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
            loutMain.getViewTreeObserver().removeGlobalOnLayoutListener(this);
        } else {
            loutMain.getViewTreeObserver().removeOnGlobalLayoutListener(this);
        }
        TotalHeight = loutMain.getMeasuredHeight();

    }
});

scrollMain.smoothScrollTo(0, totalHeight);
</code>```


问:
Is there a way of hiding the telephone country code in Android Studio
I need to add a country code to phone numbers to dial it from Android, but I would like to display the phone numbers without the country code. I can get the dialler working using setText() for the phone number (with country code) in Java and adding Autolink in the XML.

However I can't seem to find a way of displaying the phone number without the country code i.e. when using href= you can have different text to the actual hyperlink.

So I want to display 01234 567890, but dial +441234567890.

I've tried using this HTML in a string but it doesn't work:

```<code><a href="tel:+441234567890">01234 567890</a>
</code>```

答:
You can remove first three characters of your string line:

```<code>numberString.substring(3);
</code>```

and it will return you:
01234 567890

Hope it will help you :)

Body:
I need to add a country code to phone numbers to dial it from Android, but I would like to display the phone numbers without the country code. I can get the dialler working using setText() for the phone number (with country code) in Java and adding Autolink in the XML.

However I can't seem to find a way of displaying the phone number without the country code i.e. when using <a href= you can have different text to the actual hyperlink.

So I want to display 01234 567890, but dial +441234567890.

I've tried using this HTML in a string but it doesn't work:

01234 567890

Body:
You can remove first three characters of your string line:

numberString.substring(3);

and it will return you:
01234 567890

Hope it will help you :)


问:
How to extract string from JSON object in protractor
I am not able to extract string from JSON object in protractor in webstorm. I want value of statusCode i.e :200, The code I've tried for this mentioned below...

CODE IS :

```<code>console.log('body is :' + JSON.stringify(body));

var jsonResponse = JSON.stringify(response);

console.log('---------response is: '+ jsonResponse);

var statusResponse = jsonResponse.getString("statusCode");

console.log('---- statusResponse is :'+ statusResponse.toString());
</code>```

OUTPUT IS:

```<code>body is :{"oBody":{"payLoad":{"sLoginId":"HDB_TW_DSA@softcell.com","iInstId":4019,"sFirstName":"PRIYANKA","sLastName":"MADGUNDI","sEmail":"priyanka@softcell.com","sEmpId":"HDB18458","sMobile":"8237276692","bActive":true,"aRoles":["DSA"],"aDealers":[{"id":"TW423684019","iInstId":4019,"iDlrId":"42368","sDlrName":"GODSPEED MOTORCYCLE PVT LTD","iBranchId":1278,"sBranchName":"HYDERABAD-SF","sProduct":"TW","bActive":true},{"oStatus":{"iStatus":200,"sStatus":"OK"}}
</code>```

---------response is:

```<code>{"statusCode":200,"body":{"oBody":{"payLoad":{"sLoginId":"HDB_TW_DSA@softcell.com","iInstId":4019,"sFirstName":"PRIYANKA","sLastName":"MADGUNDI","sEmail":"priyanka@softcell.com","sEmpId":"HDB18458","sMobile":"8237276692","bActive":true,"aRoles":["DSA"],"aDealers","path":"/gonogo-api/atm/login-web-v3","href":"https://ssg.serviceurl.in/login-web-v3"},"method":"POST","headers":{"Postman-Token":"7aad048f-f8ad-4765-a0b8-be3b3a485ab6","cache-control":"no-cache","Content-Type":"application/json","accept":"application/json","content-length":380}}}
</code>```

答:
So it appears what jsonResponse is giving you from the stringifying is not recognized as perfect json by json parse. So you can do the parsing yourself by finding where it says "statusCode:", taking the response string from a space beyond that for as long as statusCode could be and then some (8 characters seemed plenty to me), then taking only up to the comma. I assumed you want the code as a number, not a string, so I converted it.    </p>

```<code>var temp =jsonResponse.search('"statusCode":')+'"statusCode":'.length;
var temp2 = jsonResponse.slice(temp,temp+8);
var status = parseInt(temp2.slice(0,temp2.search(',')),10);
</code>```

Body:
I am not able to extract string from JSON object in protractor in webstorm. I want value of statusCode i.e :200, The code I've tried for this mentioned below...

CODE IS :

console.log('body is :' + JSON.stringify(body));

var jsonResponse = JSON.stringify(response);

console.log('---------response is: '+ jsonResponse);

var statusResponse = jsonResponse.getString("statusCode");

console.log('---- statusResponse is :'+ statusResponse.toString());

OUTPUT IS:

body is :{"oBody":{"payLoad":{"sLoginId":"HDB_TW_DSA@softcell.com","iInstId":4019,"sFirstName":"PRIYANKA","sLastName":"MADGUNDI","sEmail":"priyanka@softcell.com","sEmpId":"HDB18458","sMobile":"8237276692","bActive":true,"aRoles":["DSA"],"aDealers":[{"id":"TW423684019","iInstId":4019,"iDlrId":"42368","sDlrName":"GODSPEED MOTORCYCLE PVT LTD","iBranchId":1278,"sBranchName":"HYDERABAD-SF","sProduct":"TW","bActive":true},{"oStatus":{"iStatus":200,"sStatus":"OK"}}

---------response is:

{"statusCode":200,"body":{"oBody":{"payLoad":{"sLoginId":"HDB_TW_DSA@softcell.com","iInstId":4019,"sFirstName":"PRIYANKA","sLastName":"MADGUNDI","sEmail":"priyanka@softcell.com","sEmpId":"HDB18458","sMobile":"8237276692","bActive":true,"aRoles":["DSA"],"aDealers","path":"/gonogo-api/atm/login-web-v3","href":"https://ssg.serviceurl.in/login-web-v3"},"method":"POST","headers":{"Postman-Token":"7aad048f-f8ad-4765-a0b8-be3b3a485ab6","cache-control":"no-cache","Content-Type":"application/json","accept":"application/json","content-length":380}}}

Body:
So it appears what jsonResponse is giving you from the stringifying is not recognized as perfect json by json parse. So you can do the parsing yourself by finding where it says "statusCode:", taking the response string from a space beyond that for as long as statusCode could be and then some (8 characters seemed plenty to me), then taking only up to the comma. I assumed you want the code as a number, not a string, so I converted it.

var temp =jsonResponse.search('"statusCode":')+'"statusCode":'.length;
var temp2 = jsonResponse.slice(temp,temp+8);
var status = parseInt(temp2.slice(0,temp2.search(',')),10);


问:
Angular Testing Dependency Injection of MAT_DIALOG_DATA
I have an app component like this and I want to write a unit test for this.

```<code>   export class AppComponent {
        public errorCode = new BehaviorSubject<number | null>(null);
        public isLoading = new BehaviorSubject<boolean>(false);

        constructor(
            public dialogRef: MatDialogRef<NotificationDeleteDialogComponent>,
            private notificationService: NotificationService,
            @Inject(MAT_DIALOG_DATA) public data: any
        ) { }
}
</code>```

How can I do DI, I mean how can I import these constructor classes into a test file and Inject the data.

Thank you

答:
You just have to provide your constructor arguments in your TestBed, like this:

```<code>beforeEach(async(() => {
    TestBed.configureTestingModule({
        declarations: [ AppComponent ],
        providers: [
            { provide: MatDialogRef, useValue: { close: () => {} } },
            { provide: notificationService, useValue: mockedNotificationService},
            { provide: MAT_DIALOG_DATA, useValue: mockedDialogData },
        ]
    }).compileComponents();
}));

beforeEach(() => {
    fixture = TestBed.createComponent(AppComponent);
    component = fixture.componentInstance;
    matDialogRef = fixture.debugElement.injector.get(MatDialogRef);
    notificationService = fixture.debugElement.injector.get(NotificationService);

    fixture.detectChanges();
});
</code>```

Do not forget to declare mockedNotificationService and mockedDialogData with whatever is needed in the test.

Body:
I have an app component like this and I want to write a unit test for this.

   export class AppComponent {
        public errorCode = new BehaviorSubject<number | null>(null);
        public isLoading = new BehaviorSubject<boolean>(false);

        constructor(
            public dialogRef: MatDialogRef<NotificationDeleteDialogComponent>,
            private notificationService: NotificationService,
            @Inject(MAT_DIALOG_DATA) public data: any
        ) { }
}

How can I do DI, I mean how can I import these constructor classes into a test file and Inject the data.

Thank you

Body:
You just have to provide your constructor arguments in your TestBed, like this:

beforeEach(async(() => {
    TestBed.configureTestingModule({
        declarations: [ AppComponent ],
        providers: [
            { provide: MatDialogRef, useValue: { close: () => {} } },
            { provide: notificationService, useValue: mockedNotificationService},
            { provide: MAT_DIALOG_DATA, useValue: mockedDialogData },
        ]
    }).compileComponents();
}));

beforeEach(() => {
    fixture = TestBed.createComponent(AppComponent);
    component = fixture.componentInstance;
    matDialogRef = fixture.debugElement.injector.get(MatDialogRef);
    notificationService = fixture.debugElement.injector.get(NotificationService);

    fixture.detectChanges();
});

Do not forget to declare mockedNotificationService and mockedDialogData with whatever is needed in the test.


问:
Get total length of pipe per date interval
I have a table containing pipes that are installed at a location.
Installed dates are always filled in, removed dates can be NULL

```<code>Type   Installed     Removed     Length
PT2    01/01/2011    NULL        2000
PT2    01/01/2011    NULL        2000
PT1    01/01/2011    NULL        1200
PT1    01/01/2011    NULL        1200
PT1    15/02/2011    25/02/2011  1000
PT1    15/02/2011    25/02/2011  1000
</code>```

Now I need an overview of the total length per type that was installed for a given month, so the result should be for example from 01/02/2011 to 28/02/2011:

```<code> Type    From         To            Length
 PT2     01/02/2011   28/02/2011    4000
 PT1     01/02/2011   14/02/2011    2400
 PT1     15/02/2011   24/02/2011    4400 Edit: (starts on 15 not 14)
 PT1     25/02/2011   28/02/2011    2400
</code>```

EDIT: Clarification on this expected result.
In the end this will be used to see the total length of pipe at any given moment during the requested month. So if you look at the table above, during February 2 PT2 pipes were installed. They were installed in January, but are still present, so during the entire month there is a total length of 4000.

Same for PT1: From the start of February 2 PT1 pipes are installed, so 2400. However on the 15th an extra 2 PT1 pipes of length 1000 are installed so during the 15th to the 25th the total length of PT1 pipes is 4400.

These 2 pipes are removed on the 25th so 25 to end of month it's 2400 again.

I hope this makes a little more sense now.

I'm struggling with how to do this in SQL, It's for a report, and generally there are hundreds of these pipes installed in any given month.

It's for use in a Powerbuilder application, so if you know any datawindow trickery that might help feel free to share.

答:
Your sample result doesn't seem to make sense. This

```<code>Type    From         To            Length
 PT2     01/02/2011   28/02/2011    4000
 PT1     01/02/2011   14/02/2011    2400
 PT1     14/02/2011   24/02/2011    4400
 PT1     25/02/2011   28/02/2011    2400
</code>```

doesn't show how much PT1 pipe was installed for either January or February.

The following query shows the total length of pipe that was installed each month, one row per type.

```<code>select type,
       extract(year from installed) || '-' || extract(month from installed) as year_month,
       sum(length)
from pipes
group by type, year_month
order by year_month, type
</code>```

returns

```<code>PT1   2011-1   2400
PT2   2011-1   4000
PT1   2011-2   2000
</code>```

Later . . .

For the total length of pipe on any given date, I'd probably use something like this.

```<code>select p.type,
       '2011-02-28' as effective_date,
       (select sum(length)
         from pipes
         where installed <= '2011-02-28'
           and type = p.type) as installed,
       (select sum(length)
        from pipes
        where removed <= '2011-02-28'
          and type = p.type) as removed
from pipes p
group by p.type, effective_date
order by type
</code>```

That query returns

```<code>type  effective_date   installed  removed
PT1   2011-02-28       4400       2000
PT2   2011-02-28       4000
</code>```

Body:
I have a table containing pipes that are installed at a location.
Installed dates are always filled in, removed dates can be NULL

Type   Installed     Removed     Length
PT2    01/01/2011    NULL        2000
PT2    01/01/2011    NULL        2000
PT1    01/01/2011    NULL        1200
PT1    01/01/2011    NULL        1200
PT1    15/02/2011    25/02/2011  1000
PT1    15/02/2011    25/02/2011  1000

Now I need an overview of the total length per type that was installed for a given month, so the result should be for example from 01/02/2011 to 28/02/2011:

 Type    From         To            Length
 PT2     01/02/2011   28/02/2011    4000
 PT1     01/02/2011   14/02/2011    2400
 PT1     15/02/2011   24/02/2011    4400 Edit: (starts on 15 not 14)
 PT1     25/02/2011   28/02/2011    2400

EDIT: Clarification on this expected result.
In the end this will be used to see the total length of pipe at any given moment during the requested month. So if you look at the table above, during February 2 PT2 pipes were installed. They were installed in January, but are still present, so during the entire month there is a total length of 4000.

Same for PT1: From the start of February 2 PT1 pipes are installed, so 2400. However on the 15th an extra 2 PT1 pipes of length 1000 are installed so during the 15th to the 25th the total length of PT1 pipes is 4400.

These 2 pipes are removed on the 25th so 25 to end of month it's 2400 again.

I hope this makes a little more sense now.

I'm struggling with how to do this in SQL, It's for a report, and generally there are hundreds of these pipes installed in any given month.

It's for use in a Powerbuilder application, so if you know any datawindow trickery that might help feel free to share.

Body:
Your sample result doesn't seem to make sense. This

Type    From         To            Length
 PT2     01/02/2011   28/02/2011    4000
 PT1     01/02/2011   14/02/2011    2400
 PT1     14/02/2011   24/02/2011    4400
 PT1     25/02/2011   28/02/2011    2400

doesn't show how much PT1 pipe was installed for either January or February.

The following query shows the total length of pipe that was installed each month, one row per type.

select type,
       extract(year from installed) || '-' || extract(month from installed) as year_month,
       sum(length)
from pipes
group by type, year_month
order by year_month, type

returns

PT1   2011-1   2400
PT2   2011-1   4000
PT1   2011-2   2000

Later . . .

For the total length of pipe on any given date, I'd probably use something like this.

select p.type,
       '2011-02-28' as effective_date,
       (select sum(length)
         from pipes
         where installed <= '2011-02-28'
           and type = p.type) as installed,
       (select sum(length)
        from pipes
        where removed <= '2011-02-28'
          and type = p.type) as removed
from pipes p
group by p.type, effective_date
order by type

That query returns

type  effective_date   installed  removed
PT1   2011-02-28       4400       2000
PT2   2011-02-28       4000


问:
Maximum sum of sub-array using Kadane's Algorithm in Java
This is a problem statement from geeks for geeks (link : https://practice.geeksforgeeks.org/problems/kadanes-algorithm/0 )

My code is working fine as per the Compile & test option. But when I try to submit, it throws error about failure for multiple test cases.

Could anyone help me with this?

CODE:

```<code>import java.io.IOException;
import java.io.InputStreamReader;
import java.io.BufferedReader;

public class Kadane

{
public static void main(String[]args) throws IOException,NumberFormatException

{
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

    System.out.println("Enter the number of test cases");
    int T = Integer.parseInt(br.readLine());

    for(int t=0 ; t<T ; t++)
    {
        int N,a=0;
        int sum1=0,maxsum=-2147483648,kadanesum=-2147483648;

        System.out.println("Enter the size of array : ");
        N =  Integer.parseInt(br.readLine());
        int arr[] = new int[N];

        System.out.println("Enter the array elements separated by space");
        String S = new String(br.readLine());
        String elem[] = S.split(" ");

        for(String e:elem)
        {
            arr[a] = Integer.parseInt(e);
            a++;
        }

        for(int i=0 ; i<N ; i++)
        {
            for(int j=i ; j<N ; j++)
            {
                sum1 = sum1 + arr[j];
                if(maxsum<sum1)
                {
                    maxsum=sum1;

                }
            }
            if(maxsum>kadanesum)
            {
                kadanesum=maxsum;
            }
            sum1=0;
            maxsum=-2147483648;
        }

        System.out.println("\tKadane Sum = " + kadanesum);

    }
}
}
</code>```

My code link : https://ide.geeksforgeeks.org/tXNHh28A0D

My input :
5(number of test cases)

3(array size)

1 2 3(array elements)

5

1 2 3 -2 5

10

2 9 3 -10 -20 34 28 -50 30 -1

7

4 5 -10 -50 3 9 8

8

8 9 8 -25 25 1 2

My output :
Enter the number of test cases

Enter the size of array :
Enter the array elements separated by space
Kadane Sum = 6

Enter the size of array :
Enter the array elements separated by space
Kadane Sum = 9

Enter the size of array :
Enter the array elements separated by space
Kadane Sum = 62

Enter the size of array :
Enter the array elements separated by space
Kadane Sum = 20

Enter the size of array :
Enter the array elements separated by space
Kadane Sum = 28

I get the below error message when submitting my code :

Wrong Answer. !!!Wrong Answer
Possibly your code doesn't work correctly for multiple test-cases (TCs).
The first test case where your code failed:

Input:(As per website)
3
1 2 3

Its Correct output is:
6

I have used this same input in my input test cases(test case 1) and the output is same as expected.

Could anyone help me to optimize the code using StringBuffer?

答:
The output should be the sum:

```<code>System.out.println(kadanesum);
</code>```

And not the message you wrote:

```<code>System.out.println("\tKadane Sum = " + kadanesum);
</code>```

And as Rahul pointed out, you also need to remove the other messages such as:

```<code>System.out.println("Enter the array elements separated by space");
</code>```

Body:
This is a problem statement from geeks for geeks (link : https://practice.geeksforgeeks.org/problems/kadanes-algorithm/0 )

My code is working fine as per the Compile & test option. But when I try to submit, it throws error about failure for multiple test cases.

Could anyone help me with this?

CODE:

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.BufferedReader;

public class Kadane

{
public static void main(String[]args) throws IOException,NumberFormatException

{
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

    System.out.println("Enter the number of test cases");
    int T = Integer.parseInt(br.readLine());

    for(int t=0 ; t<T ; t++)
    {
        int N,a=0;
        int sum1=0,maxsum=-2147483648,kadanesum=-2147483648;

        System.out.println("Enter the size of array : ");
        N =  Integer.parseInt(br.readLine());
        int arr[] = new int[N];

        System.out.println("Enter the array elements separated by space");
        String S = new String(br.readLine());
        String elem[] = S.split(" ");

        for(String e:elem)
        {
            arr[a] = Integer.parseInt(e);
            a++;
        }

        for(int i=0 ; i<N ; i++)
        {
            for(int j=i ; j<N ; j++)
            {
                sum1 = sum1 + arr[j];
                if(maxsum<sum1)
                {
                    maxsum=sum1;

                }
            }
            if(maxsum>kadanesum)
            {
                kadanesum=maxsum;
            }
            sum1=0;
            maxsum=-2147483648;
        }

        System.out.println("\tKadane Sum = " + kadanesum);

    }
}
}

My code link : https://ide.geeksforgeeks.org/tXNHh28A0D

My input :
5(number of test cases)

3(array size)

1 2 3(array elements)

5

1 2 3 -2 5

10

2 9 3 -10 -20 34 28 -50 30 -1

7

4 5 -10 -50 3 9 8

8

8 9 8 -25 25 1 2

My output :
Enter the number of test cases

Enter the size of array :
Enter the array elements separated by space
Kadane Sum = 6

Enter the size of array :
Enter the array elements separated by space
Kadane Sum = 9

Enter the size of array :
Enter the array elements separated by space
Kadane Sum = 62

Enter the size of array :
Enter the array elements separated by space
Kadane Sum = 20

Enter the size of array :
Enter the array elements separated by space
Kadane Sum = 28

I get the below error message when submitting my code :

Wrong Answer. !!!Wrong Answer
Possibly your code doesn't work correctly for multiple test-cases (TCs).
The first test case where your code failed:

Input:(As per website)
3
1 2 3

Its Correct output is:
6

I have used this same input in my input test cases(test case 1) and the output is same as expected.

Could anyone help me to optimize the code using StringBuffer?

Body:
The output should be the sum:

System.out.println(kadanesum);

And not the message you wrote:

System.out.println("\tKadane Sum = " + kadanesum);

And as Rahul pointed out, you also need to remove the other messages such as:

System.out.println("Enter the array elements separated by space");


问:
How to prevent XSS in play framework 2?
according to https://www.owasp.org/index.php/XSS_%28Cross_Site_Scripting%29_Prevention_Cheat_Sheet#XSS_Prevention_Rules_Summary

in play framework 2 document, I only can find method @Html to escape html.
how to deal with other condition?

答:
As per Play Framework 1.2.4 docs: You can use flag

future.escapeInTemplates=true  , In application.conf setting which will help you to block cross site scripting attack.

From docs :

It is strongly recommended to enable this option. When you really need to insert unescaped HTML in your templates, you can do so using the raw() method on the string. But if the string comes from a user input, you need to make sure it is sanitized first.

When sanitizing user inputs, always prefer whitelisting (only allow a list of safe tags) to blacklisting (forbid a list of unsafe tags and allow all the rest).

Title: How to prevent XSS in play framework 2?


问:
Pandas: dynamically shifting values across columns
I have the following df:

```<code>           sales2001   sales2002   sales2003  sales2004
   200012  19.12       0.98
   200101  19.1        0.98        2.3
   200102  21          0.97        0.8
    ...
   200112  19.12       0.99        2.4
   200201              0.98        2.5
   200202              0.97        0.8        1.2
</code>```

I would like to shift the content in order to align it a timegap view, as follow:

```<code>           sales+1y   sales+2y
   200012  19.12       0.98
   200101  0.98        2.3
   200102  0.97        0.8
    ...
   200112  0.99        2.4
   200201  0.98        2.5
   200202  0.8         1.2
</code>```

basically aligning the forecasted data points to a fixed timegap to the index.
I tried with iterrows and dynamically calling the columns given the index but cannot make it work. do you guys have any suggestion?

答:
Another option is to use pd.wide_to_long and pivot:

```<code># here I assume the index name is index
new_df = pd.wide_to_long(df.reset_index(), 'sales', i='index', j='sale_end').reset_index()

# if index is datetime, then use dt.year
new_df['periods'] = new_df['sale_end'] - new_df['index']//100

# pivot
new_df.dropna().pivot(index='index',columns='periods', values='sales')
</code>```

output:

```<code>periods -1      0       1       2
idx
200012  NaN     NaN     19.12   0.98
200101  NaN     19.10   0.98    2.30
200102  NaN     21.00   0.97    0.80
200112  NaN     19.12   0.99    2.40
200201  0.98    2.50    NaN     NaN
200202  0.97    0.80    1.20    NaN
</code>```

Body:
I have the following df:

           sales2001   sales2002   sales2003  sales2004
   200012  19.12       0.98
   200101  19.1        0.98        2.3
   200102  21          0.97        0.8
    ...
   200112  19.12       0.99        2.4
   200201              0.98        2.5
   200202              0.97        0.8        1.2

I would like to shift the content in order to align it a timegap view, as follow:

           sales+1y   sales+2y
   200012  19.12       0.98
   200101  0.98        2.3
   200102  0.97        0.8
    ...
   200112  0.99        2.4
   200201  0.98        2.5
   200202  0.8         1.2

basically aligning the forecasted data points to a fixed timegap to the index.
I tried with iterrows and dynamically calling the columns given the index but cannot make it work. do you guys have any suggestion?

Body:
Another option is to use pd.wide_to_long and pivot:

# here I assume the index name is index
new_df = pd.wide_to_long(df.reset_index(), 'sales', i='index', j='sale_end').reset_index()

# if index is datetime, then use dt.year
new_df['periods'] = new_df['sale_end'] - new_df['index']//100

# pivot
new_df.dropna().pivot(index='index',columns='periods', values='sales')

output:

periods -1      0       1       2
idx
200012  NaN     NaN     19.12   0.98
200101  NaN     19.10   0.98    2.30
200102  NaN     21.00   0.97    0.80
200112  NaN     19.12   0.99    2.40
200201  0.98    2.50    NaN     NaN
200202  0.97    0.80    1.20    NaN


答:
One simpliest solution is convert index to FloatIndex in all DataFrames:

```<code>df1.index = df1.index.astype(float)
df2.index = df2.index.astype(float)
df3.index = df3.index.astype(float)
</code>```

Title: Indexing a Dataframe in steps of 0.5

Body:
I have several dataframes that I want to add. Theyre indices range from 0 to 25 in steps of 0.5. Now, when I try to add them, the indices are interpreted differently and the new added dataframe has the indices ordered from "0 to 2" its 0.5,1,1.5,10,10.5...19.5, 2....etc. So that 10 is listed lower than 2, I guess because it starts with a 1 and the dataframe sorts the indices by the first value.

I tried different ways of adding the frames:

pd.concat([df1, df2, df3...], axis=0)
df1 + df2 + df3
df1.add(df2, fill_value=0).add(df3.....)

all of them work. The only problem is the new indexing which messes up my frames.

I could of course reset the indices before adding the frames and then change the index back. But is there a more direct way?

answer to comment:

Index(['0.5', '1.0', '1.5', '2.0', '2.5', '3.0', '3.5', '4.0', '4.5', '5.0',
       '5.5', '6.0', '6.5', '7.0', '7.5', '8.0', '8.5', '9.0', '9.5', '10.0',
       '10.5', '11.0', '11.5', '12.0', '12.5', '13.0', '13.5', '14.0', '14.5',
       '15.0', '15.5', '16.0', '16.5', '17.0', '17.5', '18.0', '18.5', '19.0',
       '19.5', '20.0', '20.5', '21.0', '21.5', '22.0', '22.5', '23.0', '23.5',
       '24.0', '24.5', '25.0', '25.5', '26.0', '26.5', '27.0', '27.5', '28.0',
       '28.5'],
      dtype='object') Index(['0.5', '1.0', '1.5', '2.0', '2.5', '3.0', '3.5', '4.0', '4.5', '5.0',
       '5.5', '6.0', '6.5', '7.0', '7.5', '8.0', '8.5', '9.0', '9.5', '10.0',
       '10.5', '11.0', '11.5', '12.0', '12.5', '13.0', '13.5'],
      dtype='object') Index(['0.5', '1.0', '1.5', '2.0', '2.5', '3.0', '3.5', '4.0', '4.5', '5.0',
       '5.5', '6.0', '6.5', '7.0', '7.5', '8.0', '8.5', '9.0', '9.5', '10.0',
       '10.5', '11.0', '11.5', '12.0', '12.5', '13.0', '13.5', '14.0', '14.5',
       '15.0', '15.5', '16.0', '16.5', '17.0', '17.5', '18.0'],
      dtype='object')

Body:
One simpliest solution is convert index to FloatIndex in all DataFrames:

df1.index = df1.index.astype(float)
df2.index = df2.index.astype(float)
df3.index = df3.index.astype(float)


问:
Angular 5: Function calls are not supported in decorators
I am building a PWA from my Angular app and I am getting the following error when I run ng build --prod:

```<code>ERROR in app\app.module.ts(108,64): Error during template compile of 'AppModule'
Function calls are not supported in decorators but 'Environment' was called in 'environment'
'environment' calls 'Environment'.
</code>```

However, it makes no sense because I added export to the class as you can see here:

environment.prod.ts

```<code>import { BaseEnvironment } from './base-environment';
import { ProspectBuilderModel } from '../app/models/prospect';

export class Environment extends BaseEnvironment {
  production: boolean = true;
  prospectBuilderModel: ProspectBuilderModel = {
    buildQuote: false,
    buildAcknowledge: false,
    buildOrganizationInfo: false,
    buildFinancialInfo: false,
    buildTradeInfo: false,
    buildPermissiblePurpose: false,
    buildUserSetup: false,
    buildPackageSelection: false,
    buildPaymentOptions: false,
    buildOrderOptions: false,
    buildVerifyOrganizationInfo: false,
    buildDocusignAuthorization: false,
    buildDocusignContract: false
  };
}

export const environment = new Environment();
</code>```

base-environment.ts

```<code>import { ProspectBuilderModel } from '../app/models/prospect';

export abstract class BaseEnvironment {
  abstract production: boolean;
  abstract prospectBuilderModel: ProspectBuilderModel;
}
</code>```

app.module.ts

```<code>...
 ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule,
    MultiselectDropdownModule,
    ReactiveFormsModule,
    HttpModule,
    ToastrModule.forRoot(),
    BrowserAnimationsModule,
    NgxMyDatePickerModule.forRoot(),
    PopoverModule.forRoot(),
    ModalModule.forRoot(),
    ServiceWorkerModule.register('/ngsw-worker.js', { enabled: environment.production })
  ],
  providers: [
...
</code>```

Does anyone know what I can do to resolve this error?

答:
Had same problem, here are possible workarounds (if you don't have dynamically loaded properties):

1. As your answer, just object.

But you lose default properties and information about "to implement" properties.

2. Use static classes:

here you lose 'to implement' properties, since abstract statics are not possible, but you have the types and defaults.

```<code>// default.env.ts
export class BaseEnvironment {
  public production: boolean = true;
  public specialPropToImpl: boolean = true;
}

// your.env.ts
export class Environment extends BaseEnvironment {
  public specialPropToImpl = true;
}

export const environment = Environment;
</code>```

3. Use default properties object, interface and object assignment:

here you have the 'to implement' properties, types and defaults, but little bit ugly to implement.

```<code>// default.env.ts
export interface EnvProperties {
  production: boolean;
  specialPropToImpl: boolean;
}

export const defaultEnv = {
  production: true
};

// your.env.ts
export const environment: EnvProperties = {
  ...defaultEnv,
  specialPropToImpl: true
};
</code>```

4. Just one static variable more from environment

simple solution, you keep your subclasses, but every env file must have it. But since new environment files are created by copypaste of old one, this can work.

Depends on production value, you should change the variable value manually.

Not very flexible and maintainable solution. But simple.

```<code>// your.env.ts
export const enablePwa = true

// app.module.ts
import {environment, enablePwa} from 'env.ts'
//...
ServiceWorkerModule.register('/ngsw-worker.js', { enabled: enablePwa })
</code>```

Body:
I am building a PWA from my Angular app and I am getting the following error when I run ng build --prod:

ERROR in app\app.module.ts(108,64): Error during template compile of 'AppModule'
Function calls are not supported in decorators but 'Environment' was called in 'environment'
'environment' calls 'Environment'.

However, it makes no sense because I added export to the class as you can see here:

environment.prod.ts

import { BaseEnvironment } from './base-environment';
import { ProspectBuilderModel } from '../app/models/prospect';

export class Environment extends BaseEnvironment {
  production: boolean = true;
  prospectBuilderModel: ProspectBuilderModel = {
    buildQuote: false,
    buildAcknowledge: false,
    buildOrganizationInfo: false,
    buildFinancialInfo: false,
    buildTradeInfo: false,
    buildPermissiblePurpose: false,
    buildUserSetup: false,
    buildPackageSelection: false,
    buildPaymentOptions: false,
    buildOrderOptions: false,
    buildVerifyOrganizationInfo: false,
    buildDocusignAuthorization: false,
    buildDocusignContract: false
  };
}

export const environment = new Environment();

base-environment.ts

import { ProspectBuilderModel } from '../app/models/prospect';

export abstract class BaseEnvironment {
  abstract production: boolean;
  abstract prospectBuilderModel: ProspectBuilderModel;
}

app.module.ts

...
 ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule,
    MultiselectDropdownModule,
    ReactiveFormsModule,
    HttpModule,
    ToastrModule.forRoot(),
    BrowserAnimationsModule,
    NgxMyDatePickerModule.forRoot(),
    PopoverModule.forRoot(),
    ModalModule.forRoot(),
    ServiceWorkerModule.register('/ngsw-worker.js', { enabled: environment.production })
  ],
  providers: [
...

Does anyone know what I can do to resolve this error?

Body:
Had same problem, here are possible workarounds (if you don't have dynamically loaded properties):

1. As your answer, just object.

But you lose default properties and information about "to implement" properties.

2. Use static classes:

here you lose 'to implement' properties, since abstract statics are not possible, but you have the types and defaults.

// default.env.ts
export class BaseEnvironment {
  public production: boolean = true;
  public specialPropToImpl: boolean = true;
}

// your.env.ts
export class Environment extends BaseEnvironment {
  public specialPropToImpl = true;
}

export const environment = Environment;

3. Use default properties object, interface and object assignment:

here you have the 'to implement' properties, types and defaults, but little bit ugly to implement.

// default.env.ts
export interface EnvProperties {
  production: boolean;
  specialPropToImpl: boolean;
}

export const defaultEnv = {
  production: true
};

// your.env.ts
export const environment: EnvProperties = {
  ...defaultEnv,
  specialPropToImpl: true
};

4. Just one static variable more from environment

simple solution, you keep your subclasses, but every env file must have it. But since new environment files are created by copypaste of old one, this can work.

Depends on production value, you should change the variable value manually.

Not very flexible and maintainable solution. But simple.

// your.env.ts
export const enablePwa = true

// app.module.ts
import {environment, enablePwa} from 'env.ts'
//...
ServiceWorkerModule.register('/ngsw-worker.js', { enabled: enablePwa })


问:
How could I transform a datetime dataframe column to int64, replacing the value 2018-08-01 to 20180801?
How could I transform a datetime dataframe column to int64, replacing the value 2018-08-01 to 20180801?

```<code>  myDataFrame

  DATA_REFE COD_SGTO

0 2018-08-01        1
1 2018-08-01        1
2 2018-08-01        1
3 2018-08-01        1
4 2018-08-01        1

myDataFrame column type
DATA_REFE       datetime64[ns]
COD_SGTO                object

df['DATA_REFE'].astype(str).replace('-', '')
</code>```

The result continue the same

答:
Try this:</p>

```<code>myDataFrame['DATA_REFE'].dt.strftime('%Y%m%d').astype(int)
</code>```

Body:
How could I transform a datetime dataframe column to int64, replacing the value 2018-08-01 to 20180801?

  myDataFrame

  DATA_REFE COD_SGTO

0 2018-08-01        1
1 2018-08-01        1
2 2018-08-01        1
3 2018-08-01        1
4 2018-08-01        1

myDataFrame column type
DATA_REFE       datetime64[ns]
COD_SGTO                object

df['DATA_REFE'].astype(str).replace('-', '')

The result continue the same

Body:
Try this:

myDataFrame['DATA_REFE'].dt.strftime('%Y%m%d').astype(int)


问:
Error "Timed out waiting for the socket to be ready for a write" while connecting to server in Xcode
I am trying to connect to server for web socket connection. but I am getting the error:

"Websocket is disconnected: Optional(Starscream.WSError(type:
  Starscream.ErrorType.writeTimeoutError, message: \"Timed out waiting
  for the socket to be ready for a write\", code: 0))"

Starscream.WSError(type: Starscream.ErrorType.writeTimeoutError

How can I solve it? also
Here is my source code link:
https://www.dropbox.com/s/v348vxxjf74dsds/websocket.zip?dl=0

I tried to connect after some time again too, Once its failed but still it's giving me same error.

答:
I tried your code, it's working fine. the only change I have made is your socket server URL

before it was  ws://192.168.1.2:8080

and I have updated with "http://192.168.1.41:8080" //41 is my IP. you can use yours

just changed ws with http.


问:
Execute Task in new background thread
I know there are a million questions on this and I am trying their solutions but it does not seem to behave as I would expect.

With the following code:

```<code>await Task.Run(() => { Thread.Sleep(5000); Console.WriteLine("I'm running after Thread.Sleep"); });
Console.WriteLine("I'm running after Task.Run");
</code>```

I get the output:

```<code>[ 5 seconds elapses ]
I'm running after Thread.Sleep
I'm running after Task.Run
</code>```

Which is the same output I would get without using Task.Run

What I want is the output:

```<code>I'm running after Task.Run
[ 5 seconds elapses ]
I'm running after Thread.Sleep
</code>```

Where execution of the 'parent' thread continues and the long-running task is executed 'in the background' in a way which does not affect the 'parent' thread.

答:
As mentioned you need to remove the await. However that turns it into a fire-and-forget task which, if the above code just happens to be in say a console app's Main then your process could terminate before the task has completed.

Good:

```<code> // C# 7
 static async void Main(string[] args) // <--- note `async` signature
 {
     await Task.Run(() => { Thread.Sleep(5000); Console.WriteLine("I'm running
                 after Thread.Sleep"); });
     Console.WriteLine("I'm running after Task.Run");
 }
</code>```

Bad: - fire-and-forget task that isn't awaited

```<code> static void Main(string[] args)
 {
     Task.Run(() => { Thread.Sleep(5000); Console.WriteLine("Spider Man: I don't wan't to go!"); });  // POOF!!

     Console.WriteLine("I'm running after Task.Run");

     // sorry Spidy, you're dead
 }
</code>```

So you might not see I'm running after Thread.Sleep at all even if you have a Thread.Sleep(). (by the way you should be using Task.Delay()).  You could mitigate it with a Console.ReadKey() but that might defeat the purpose.

Fire-and-forget tasks have their uses, and can be used reasonably safely in other types of long-running apps like say WinForms but people generally don't go spawning Tasks in the process's entry point so the tasks generally run to completion without any early termination by the process.  However, it's generally a good idea to use await where you can so you don't shoot yourself in the foot.

Also, your requirements of wanting things in a certain order sort of demonstrates a misunderstanding of how async/await works.

Title: Execute Task in new background thread

Body:
I know there are a million questions on this and I am trying their solutions but it does not seem to behave as I would expect.

With the following code:

await Task.Run(() => { Thread.Sleep(5000); Console.WriteLine("I'm running after Thread.Sleep"); });
Console.WriteLine("I'm running after Task.Run");

I get the output:

[ 5 seconds elapses ]
I'm running after Thread.Sleep
I'm running after Task.Run

Which is the same output I would get without using Task.Run

What I want is the output:

I'm running after Task.Run
[ 5 seconds elapses ]
I'm running after Thread.Sleep

Where execution of the 'parent' thread continues and the long-running task is executed 'in the background' in a way which does not affect the 'parent' thread.

Body:
As mentioned you need to remove the await. However that turns it into a fire-and-forget task which, if the above code just happens to be in say a console app's Main then your process could terminate before the task has completed.

Good:

 // C# 7
 static async void Main(string[] args) // <--- note `async` signature
 {
     await Task.Run(() => { Thread.Sleep(5000); Console.WriteLine("I'm running
                 after Thread.Sleep"); });
     Console.WriteLine("I'm running after Task.Run");
 }

Bad: - fire-and-forget task that isn't awaited

 static void Main(string[] args)
 {
     Task.Run(() => { Thread.Sleep(5000); Console.WriteLine("Spider Man: I don't wan't to go!"); });  // POOF!!

     Console.WriteLine("I'm running after Task.Run");

     // sorry Spidy, you're dead
 }

So you might not see I'm running after Thread.Sleep at all even if you have a Thread.Sleep(). (by the way you should be using Task.Delay()).  You could mitigate it with a Console.ReadKey() but that might defeat the purpose.

Fire-and-forget tasks have their uses, and can be used reasonably safely in other types of long-running apps like say WinForms but people generally don't go spawning Tasks in the process's entry point so the tasks generally run to completion without any early termination by the process.  However, it's generally a good idea to use await where you can so you don't shoot yourself in the foot.

Also, your requirements of wanting things in a certain order sort of demonstrates a misunderstanding of how async/await works.


答:
Try the below code with str.replace and extra astype:

```<code>df['DATA_REFE'] = df['DATA_REFE'].astype(str).str.replace('-', '').astype(int)
</code>```

Title: How could I transform a datetime dataframe column to int64, replacing the value 2018-08-01 to 20180801?

Body:
Try the below code with str.replace and extra astype:

df['DATA_REFE'] = df['DATA_REFE'].astype(str).str.replace('-', '').astype(int)


问:
Does the linker script always determine at what addresses code is placed
I've spent most of my time developing for microcontrollers using tools and IDEs such as Atmel Studio, and abstracted from as to what goes on behind the scenes exactly.

Let's say in this case we are executing the code directly from flash which can be the case in embedded systems.

When we develop an application and flash it to the microcontroller using provided tools from the chip vendor, is it the loader / flasher that determines at what physical address in memory will be flashed?

I understand that the linker script defines memory offsets as to where the different sections such as .data and .txt should be placed, so is it actually this that ultimately determines at what address in the mcu flash everything should go?

Lets's say now that I discover a part of flash that is not used at all and I wish to put something else there (another application even), do I modify the linker script, create a new one, or how would I write to this particular location? I haven't fully grasped this yet.

答:
You asked if you should modify or create a new linker script. I would requirement that you modify the exciting linker script. I find them from time to time quite extensive. Why throw away what is already there while modifying it is only a few lines.

Some very common cases for micro controllers to change the linker script are:

Adding a bootloader in the first flash sector while the actual program starts in a higher sector.

Adding a sector dedicated to storing data generated by the application.

Using a dedicated sector for configuration parameters.

Lets use the first as an example on how to write to firmware to different flash sectors. Important to know is that for this example the bootloader and the actual application are two separate projects each with their own compilation configuration or makefile. Each project also has its own linker script. Below part of both files is listed:

The bootloader:

```<code>/* Specify the memory areas */
MEMORY
{
  FLASH (rx)      : ORIGIN = 0x08000000, LENGTH = 16K
  RAM (xrw)       : ORIGIN = 0x20000000, LENGTH = 128K
  MEMORY_B1 (rx)  : ORIGIN = 0x60000000, LENGTH = 0K
  CCMRAM (rw)     : ORIGIN = 0x10000000, LENGTH = 64K
}
</code>```

The application:

```<code>/* Specify the memory areas */
MEMORY
{
  FLASH (rx)      : ORIGIN = 0x0800C000, LENGTH = (1M - 16K)
  RAM (xrw)       : ORIGIN = 0x20000000, LENGTH = 128K
  MEMORY_B1 (rx)  : ORIGIN = 0x60000000, LENGTH = 0K
  CCMRAM (rw)     : ORIGIN = 0x10000000, LENGTH = 64K
}
</code>```

Please not the differences in the definition of the FLASH. The bootloader flash start at the default. The size allocated for the bootloader is 16K. Important to note is that the total flash size of the example chip is 1M. This is seen in the size of the flash of the application project. But we do not allow the full 1M for the application as of course we need to reduce it by the size allocated for the bootloader. You can also see it does not start at the same address. It has an offset of 0xC000 which amounts for the 16k.

Before you can run and debug the application code you have to do two more things:

Define the vector table offset of your code. This is required for the compiler and linker to know where the code is located in memory. This is where my knowledge of this part is lacking a bit so anyone who knows please elaborate.

If you would like to debug your application you also have to tell your debugger where to start. Atollic does this via a linker script. From what I remember from a few years back Atmel Studio has an option in the programming window where you can set the offset.

One final note: when you do something link this it is best to stick to the flash sectors of the chip. Often you can only delete a whole sector. Placing your next part of the code at the start of the next sector makes live easier.

The given examples are based on a linker file generated by Atollic TrueSTUDIO for STM32 for a STM32F4xx chip. Compilation is done using ARM gcc toolchain.

Body:
You asked if you should modify or create a new linker script. I would requirement that you modify the exciting linker script. I find them from time to time quite extensive. Why throw away what is already there while modifying it is only a few lines.

Some very common cases for micro controllers to change the linker script are:

Adding a bootloader in the first flash sector while the actual program starts in a higher sector.

Adding a sector dedicated to storing data generated by the application.

Using a dedicated sector for configuration parameters.

Lets use the first as an example on how to write to firmware to different flash sectors. Important to know is that for this example the bootloader and the actual application are two separate projects each with their own compilation configuration or makefile. Each project also has its own linker script. Below part of both files is listed:

The bootloader:

/* Specify the memory areas */
MEMORY
{
  FLASH (rx)      : ORIGIN = 0x08000000, LENGTH = 16K
  RAM (xrw)       : ORIGIN = 0x20000000, LENGTH = 128K
  MEMORY_B1 (rx)  : ORIGIN = 0x60000000, LENGTH = 0K
  CCMRAM (rw)     : ORIGIN = 0x10000000, LENGTH = 64K
}

The application:

/* Specify the memory areas */
MEMORY
{
  FLASH (rx)      : ORIGIN = 0x0800C000, LENGTH = (1M - 16K)
  RAM (xrw)       : ORIGIN = 0x20000000, LENGTH = 128K
  MEMORY_B1 (rx)  : ORIGIN = 0x60000000, LENGTH = 0K
  CCMRAM (rw)     : ORIGIN = 0x10000000, LENGTH = 64K
}

Please not the differences in the definition of the FLASH. The bootloader flash start at the default. The size allocated for the bootloader is 16K. Important to note is that the total flash size of the example chip is 1M. This is seen in the size of the flash of the application project. But we do not allow the full 1M for the application as of course we need to reduce it by the size allocated for the bootloader. You can also see it does not start at the same address. It has an offset of 0xC000 which amounts for the 16k.

Before you can run and debug the application code you have to do two more things:

Define the vector table offset of your code. This is required for the compiler and linker to know where the code is located in memory. This is where my knowledge of this part is lacking a bit so anyone who knows please elaborate.

If you would like to debug your application you also have to tell your debugger where to start. Atollic does this via a linker script. From what I remember from a few years back Atmel Studio has an option in the programming window where you can set the offset.

One final note: when you do something link this it is best to stick to the flash sectors of the chip. Often you can only delete a whole sector. Placing your next part of the code at the start of the next sector makes live easier.

The given examples are based on a linker file generated by Atollic TrueSTUDIO for STM32 for a STM32F4xx chip. Compilation is done using ARM gcc toolchain.


问:
How to stop flickering of Markers on mouseover and onmouseout events in react-google-maps?
I'm using React.js and react-google-maps to implement this. I'm trying to display the InfoWindow on Hovering any Marker and hiding when mouse leaves the Marker.
 Here's the link for code. (https://codesandbox.io/s/loving-microservice-88oop)</p>

答: I solved this by using pixelOffset option available as props. In the other answer, It was using lat as offset but when we zoom, it no longer persists in that position.</p>


问:
Pull huge data from MySQL
Trying to pull huge data [about 200,000 rows] from MySQL using PHP.
Getting the error: PHP Fatal error:  Allowed memory size of xxxxx bytes exhausted

I have an application which generates almost 80-90 thousand trasnactions every month. This is a growing application, so I can expect the numbers to grow rapidly.
While generating the monthly or quaterly report, I am getting the memory size error. I tried to increase the allowed memory and it worked.
But I know allowing more memory is a temprary fix and is not a good practice in long run.

I need some help in scaling this application.

In my opinion, breaking the query result into multiple manageable chunks and join them together should solve the problem.

Is there any alternative/better solution?

Does NoSQL helps here? how?

Edit:

Here is the way data is used:
The transaction table containes all transaction details along with the references to master data like user-id, place/location id, type of transacation.

The report will:

Pull the records from transaction table

Replace master references appropriately [replace user-id with name, address, etc]

Dump the data in csv/xls format

Store/download the file

Thanks

答:
Insert this line of code into your script at the top:

```<code>ini_set("memory_limit","128M"); // size based on your requirement if you need more than 128M then u can add this value in the place of 128M
</code>```

Or another option is use Mysql command line if possible:

```<code>Use yourdatabasename
source  mysqlfile
</code>```

Title: Pull huge data from MySQL

Body:
Insert this line of code into your script at the top:

ini_set("memory_limit","128M"); // size based on your requirement if you need more than 128M then u can add this value in the place of 128M

Or another option is use Mysql command line if possible:

Use yourdatabasename
source  mysqlfile


问:
Calling functions and returning values
I am a beginner in C++.I have a function which returns some parameters that i need ,to use in  the rest of my program.I am trying to access that function within another class.I am confused with the way i can do it...Can anyone please help me..?

Following is my code :

```<code> void SampleProgram :: myFunction()
   {
         string sInput;
         GetInfo  getInfo(sInput);  //creating instance of the class containing the function

            string sSw="";
       string sName="ram";
       string sList="list";

           getInfo.getRequiredInfo(sSw,sName,sList); //calling the function

    }
</code>```

How can i access the output parameters of getRequiredInfo() ..?and save it if the ouput parameters are as following :string name,int status
Please help me...

答:
You'd have to show us the declaration of getRequiredInfo(), but presumably it's something like

```<code>X result = getInfo.getRequiredInfo(sSw,sName,sList);
</code>```

We don't know what X is without seeing that declaration.

Title: Calling functions and returning values

Body:
I am a beginner in C++.I have a function which returns some parameters that i need ,to use in  the rest of my program.I am trying to access that function within another class.I am confused with the way i can do it...Can anyone please help me..?

Following is my code :

 void SampleProgram :: myFunction()
   {
         string sInput;
         GetInfo  getInfo(sInput);  //creating instance of the class containing the function

            string sSw="";
       string sName="ram";
       string sList="list";

           getInfo.getRequiredInfo(sSw,sName,sList); //calling the function

    }

How can i access the output parameters of getRequiredInfo() ..?and save it if the ouput parameters are as following :string name,int status
Please help me...

Body:
You'd have to show us the declaration of getRequiredInfo(), but presumably it's something like

X result = getInfo.getRequiredInfo(sSw,sName,sList);

We don't know what X is without seeing that declaration.


问:
Why Android Studio (3.4) created .gitignore doesn't exclude all `/.idea`?
Whenever a new Android Studio project is created (I'm using Android Studio 3.4), the .gitignore content is as below.

```<code>*.iml
.gradle
/local.properties
/.idea/caches
/.idea/libraries
/.idea/modules.xml
/.idea/workspace.xml
/.idea/navEditor.xml
/.idea/assetWizardSettings.xml
.DS_Store
/build
/captures
.externalNativeBuild
</code>```

Why isn't entire /.idea to be ignore but only the selective few? Are the remaining of any special use?

答:
Excluding all .idea-data would also exclude gradle.xml

I guess this is important for building.
But I am just guessing.

Body:
Whenever a new Android Studio project is created (I'm using Android Studio 3.4), the .gitignore content is as below.

*.iml
.gradle
/local.properties
/.idea/caches
/.idea/libraries
/.idea/modules.xml
/.idea/workspace.xml
/.idea/navEditor.xml
/.idea/assetWizardSettings.xml
.DS_Store
/build
/captures
.externalNativeBuild

Why isn't entire /.idea to be ignore but only the selective few? Are the remaining of any special use?


问:
Dynamically importing an entire module
I was wondering if there was a way to dynamically import an entire module (equivalent to "import * some_module").

After some research on other posts I saw you could dynamically do "import some_module", but not pull the entire module.

In order to clarify my question,

some_module :

```<code>SOME_VARIABLE = 1
</code>```

module a :

```<code>if(1 == 1):
    __import__("some_module");
</code>```

module b :

```<code>from module a import *
print(SOME_VARIABLE);
</code>```

running this code returns an unrecognized variable exception, I would like to prevent that.

Motiviation :

Lets say I have a global module which imports multiple other module via a function that recieves an argument.

Example :

module a :

```<code>import_modules(modules_id):
    if(modules_id == 1):
        from module_c import *
        from module_d import *
    else :
        from module_e import *
</code>```

module b :

```<code>from module a import *
import_modules(1);
</code>```

and I want to access all variables from module_c/d with explicit calling.

My actual problem :

I have an interface driver which interacts with different devices using different protocols (Each implemented via a different class), these protocols have certain similarities, for example : they both a have a CUSTOMER_STATUS dict (Which is defined in a protcol_a/b_global_def module which is imported by the specific protocol).

The problem I am encountering is that both protocols have variables with the same name, and since the interface driver needs to recognize them both I cant know which variable I am accessing from the program that is using the interface driver (Imports it).

Take in account that the program using the interface driver only knows dynamically which protocol it needs to use and I want to avoid importing the protocol global def manually inside the program (Even though I want to use its variables in the program).

答:
Extension to donkopotamus's answer

Make the module a be:

```<code>def load_module():
    globals().update(__import__("some_module").__dict__)
</code>```

Now in b

```<code>from a import *
load_module()
from a import *
print(SOME_VARIABLE)
</code>```

Title: Dynamically importing an entire module

Body:
I was wondering if there was a way to dynamically import an entire module (equivalent to "import * some_module").

After some research on other posts I saw you could dynamically do "import some_module", but not pull the entire module.

In order to clarify my question,

some_module :

SOME_VARIABLE = 1

module a :

if(1 == 1):
    __import__("some_module");

module b :

from module a import *
print(SOME_VARIABLE);

running this code returns an unrecognized variable exception, I would like to prevent that.

Motiviation :

Lets say I have a global module which imports multiple other module via a function that recieves an argument.

Example :

module a :

import_modules(modules_id):
    if(modules_id == 1):
        from module_c import *
        from module_d import *
    else :
        from module_e import *

module b :

from module a import *
import_modules(1);

and I want to access all variables from module_c/d with explicit calling.

My actual problem :

I have an interface driver which interacts with different devices using different protocols (Each implemented via a different class), these protocols have certain similarities, for example : they both a have a CUSTOMER_STATUS dict (Which is defined in a protcol_a/b_global_def module which is imported by the specific protocol).

The problem I am encountering is that both protocols have variables with the same name, and since the interface driver needs to recognize them both I cant know which variable I am accessing from the program that is using the interface driver (Imports it).

Take in account that the program using the interface driver only knows dynamically which protocol it needs to use and I want to avoid importing the protocol global def manually inside the program (Even though I want to use its variables in the program).

Body:
Extension to donkopotamus's answer

Make the module a be:

def load_module():
    globals().update(__import__("some_module").__dict__)

Now in b

from a import *
load_module()
from a import *
print(SOME_VARIABLE)


答: There are some that you generally want to check into version control (anything project-specific but not user-specific). See What to gitignore from the .idea folder? for more information. If you don't want to version control them, you can exclude the whole directory.

Title: Why Android Studio (3.4) created .gitignore doesn't exclude all `/.idea`?


问:
Get values from a number line at specific position
I have a dataframe with three columns. The first is "A" or "B" the second is a value and the third is a value (from and to). Now I want to get the values of the first column for given values of the two other columns.

I got this data frame:

```<code>a <- c('A','B','A','B')
b <- c(0,40,60,80)
c <- c(40,60,80,100)

frame <- data.frame(a,b,c)

> frame
  a  b   c
1 A  0  40
2 B 40  60
3 A 60  80
4 B 80 100
</code>```

And I want to generate this second data frame from the first one.

```<code>> frame2
   d   e
1  A  10
2  A  20
3  A  30
4  A  40
5  B  50
6  B  60
7  A  70
8  A  80
9  B  90
10 B 100
</code>```

答:
An option with tidyverse by creating a sequence between b and c and unnesting the values.

```<code>library(tidyverse)

frame %>%
  mutate(value = map2(b + 10, c, seq, by = 10)) %>%
  unnest(value) %>%
  select(-b, -c)

#   a value
#1  A    10
#2  A    20
#3  A    30
#4  A    40
#5  B    50
#6  B    60
#7  A    70
#8  A    80
#9  B    90
#10 B   100
</code>```

Body:
I have a dataframe with three columns. The first is "A" or "B" the second is a value and the third is a value (from and to). Now I want to get the values of the first column for given values of the two other columns.

I got this data frame:

a <- c('A','B','A','B')
b <- c(0,40,60,80)
c <- c(40,60,80,100)

frame <- data.frame(a,b,c)

> frame
  a  b   c
1 A  0  40
2 B 40  60
3 A 60  80
4 B 80 100

And I want to generate this second data frame from the first one.

> frame2
   d   e
1  A  10
2  A  20
3  A  30
4  A  40
5  B  50
6  B  60
7  A  70
8  A  80
9  B  90
10 B 100

Body:
An option with tidyverse by creating a sequence between b and c and unnesting the values.

library(tidyverse)

frame %>%
  mutate(value = map2(b + 10, c, seq, by = 10)) %>%
  unnest(value) %>%
  select(-b, -c)

#   a value
#1  A    10
#2  A    20
#3  A    30
#4  A    40
#5  B    50
#6  B    60
#7  A    70
#8  A    80
#9  B    90
#10 B   100


问:
How to fetch Build information in jenkins
I've build a sample project in Jenkins by cloning from the Github repo. Can I get all the Jenkins and Git build details (such as the last commit ID, Origin details, Jenkins build number, Build URL, workspace location of Jenkins, Last commit author name) in a HTML page (It should be created after jenkins build) after triggering a build in Jenkins? </p>

答:
You can get all the variables of the Jenkins pipeline by the below:-

```<code>script {
      // Prints all the variables
      sh "printenv"
}
</code>```

After this you can store all the variables inside a file and publish that file using the HTML Publisher plugin to get the result in a HTML page. You can make changes in the below code:-

publishHTML([allowMissing: false, alwaysLinkToLastBuild: false, keepAll: false, reportDir: 'fileDirectory', reportFiles: 'index.html', reportName: 'HTML Report', reportTitles: 'titleName'])

Body:
You can get all the variables of the Jenkins pipeline by the below:-

script {
      // Prints all the variables
      sh "printenv"
}

After this you can store all the variables inside a file and publish that file using the HTML Publisher plugin to get the result in a HTML page. You can make changes in the below code:-

publishHTML([allowMissing: false, alwaysLinkToLastBuild: false, keepAll: false, reportDir: 'fileDirectory', reportFiles: 'index.html', reportName: 'HTML Report', reportTitles: 'titleName'])