答:
The issue with your code is that .map expects you to return a value to be stored in the resulting array, whereas you are not returning anything.

You can keep an array of all the ids of searchAndChangeFor. This will be computed only once so it will be efficient, and will be easier to compare with the officer.id in the .map.

const officers = [
  { id: 20, name: 'Captain Piett' },
  { id: 24, name: 'General Veers' },
  { id: 56, name: 'Admiral Ozzel' },
  { id: 88, name: 'Commander Jerjerrod' }
];

const searchAndChangeFor = [
  { id: 56, name: 'Admiral Ozzel' },
];

const allIDsToChange = searchAndChangeFor.map(el => el.id);
const newOfficers = officers.map((item) => allIDsToChange.includes(item.id) ? { ...item,
  name: 'Change name for 56'
} : item);

console.log(newOfficers);```

Title: Search element in array based on another array and change property


来源: stackexchange

问:
How to update excel cell via SQL by a coordinate?
Is it possible to update an excel file using this SQL query?

```<code>UPDATE [My Sheet] SET B40='17'
</code>```

The B40 is the coordinate of that excel file.
Due to the structure of the existing excel file, I cannot use a table column to update. I only have to use coordinates.

When I run this I get this exception below:

```<code>No value given for one or more required parameters.
</code>```

And my connection string is:

```<code>@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName +";Extended Properties='Excel 12.0;HDR=NO;ReadOnly=False;'"
</code>```

There is also a question here but I'm still getting the same error

答:
Thank you very much for Aditya on the comments that helped me realize I was thinking this a bit wrong.

First, my conn string is now:

```<code>@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties='Excel 12.0;HDR=NO;ReadOnly=False;'"
</code>```

And second, the query is now like:

```<code>UPDATE [My Sheet$B40:B40] SET F1=17
</code>```

I always thought F1 should be THE coordinate I want to update and that's why I failed.

ContentLicense: CC BY-SA 4.0

Body:
Is it possible to update an excel file using this SQL query?

UPDATE [My Sheet] SET B40='17'

The B40 is the coordinate of that excel file.
Due to the structure of the existing excel file, I cannot use a table column to update. I only have to use coordinates.

When I run this I get this exception below:

No value given for one or more required parameters.

And my connection string is:

@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName +";Extended Properties='Excel 12.0;HDR=NO;ReadOnly=False;'"

There is also a question here but I'm still getting the same error

Body:
Thank you very much for Aditya on the comments that helped me realize I was thinking this a bit wrong.

First, my conn string is now:

@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties='Excel 12.0;HDR=NO;ReadOnly=False;'"

And second, the query is now like:

UPDATE [My Sheet$B40:B40] SET F1=17

I always thought F1 should be THE coordinate I want to update and that's why I failed.


问:
Subscribing multiple handlers to DOM Events with jQuery
I am attempting to subscribe events by the CSS class.  I have two handlers, defined as follows:

```<code>$(document).ready(function() {
    $('.refresh-cart').click(
        function(e) {
            alert('refreshing');
        });

    $('form.ajax').submit(
        function(e) {
            e.preventDefault();
            $.post(
                this.action,
                $(this).serialize(),
                function(data, textStatus, jqXHR) { alert('post'); },
                'text');
        }
    );
});
</code>```

When these handlers overlap, I am not getting the expected functionality.

This code works correctly, by alerting 'post' and submitting an ajax request.

```<code> <form action="page.html" method="post" class="ajax">
     <input type="text" name="Sample" value="SampleValue" />
     <input type="submit" />
 </form>
</code>```

This code works correctly, by alerting 'refreshing'

```<code>  <div class="refresh-cart">Refresh Widget</div>
</code>```

However, when these overlap (such as in the following example), only the 'refresh-cart' subscriber fires.

```<code> <form action="page.html" method="post" class="ajax">
     <input type="text" name="Sample" value="SampleValue" />
     <input type="submit" class="refresh-cart" />
 </form>
</code>```

What am I doing wrong and how can I make both handlers fire?

答:
Have you tried submitting the form from the click handler?</p>

```<code>$(document).ready(function() {
    $('form.ajax').submit(
        function(e) {
            e.preventDefault();
            $.post(
                this.action,
                $(this).serialize(),
                function(data, textStatus, jqXHR) { alert('post'); },
                'text'
            );
    });

    $('.refresh-cart').click(
        function(e) {
            alert('refreshing');
            $('form.ajax').submit();
            return false;
     });
});
</code>```

Body:
I am attempting to subscribe events by the CSS class.  I have two handlers, defined as follows:

$(document).ready(function() {
    $('.refresh-cart').click(
        function(e) {
            alert('refreshing');
        });

    $('form.ajax').submit(
        function(e) {
            e.preventDefault();
            $.post(
                this.action,
                $(this).serialize(),
                function(data, textStatus, jqXHR) { alert('post'); },
                'text');
        }
    );
});

When these handlers overlap, I am not getting the expected functionality.

This code works correctly, by alerting 'post' and submitting an ajax request.

 <form action="page.html" method="post" class="ajax">
     <input type="text" name="Sample" value="SampleValue" />
     <input type="submit" />
 </form>

This code works correctly, by alerting 'refreshing'

Refresh Widget

However, when these overlap (such as in the following example), only the 'refresh-cart' subscriber fires.

 <form action="page.html" method="post" class="ajax">
     <input type="text" name="Sample" value="SampleValue" />
     <input type="submit" class="refresh-cart" />
 </form>

What am I doing wrong and how can I make both handlers fire?

Body:
Have you tried submitting the form from the click handler?

$(document).ready(function() {
    $('form.ajax').submit(
        function(e) {
            e.preventDefault();
            $.post(
                this.action,
                $(this).serialize(),
                function(data, textStatus, jqXHR) { alert('post'); },
                'text'
            );
    });

    $('.refresh-cart').click(
        function(e) {
            alert('refreshing');
            $('form.ajax').submit();
            return false;
     });
});

ContentLicense: CC BY-SA 3.0


问:
alternative for Not Like Operator in SQL
I want to exclude user accounts which ends with '_test' in table1.
I use

```<code>select * from table1 Not Like '%_test'.
</code>```

But this query doesn't work as expected.

答:
In your query, there is not WHERE keyword and the column name on which you want to check the 'like' condition.</p>

```<code>SELECT * FROM Table1 WHERE
[AccountColumn] NOT LIKE '%[_]test'
</code>```

Body:
I want to exclude user accounts which ends with '_test' in table1.
I use

select * from table1 Not Like '%_test'.

But this query doesn't work as expected.

Body:
In your query, there is not WHERE keyword and the column name on which you want to check the 'like' condition.

SELECT * FROM Table1 WHERE
[AccountColumn] NOT LIKE '%[_]test'


问:
The Microsoft Office Access database engine cannot open or write to the file
I am getting this below exception

"The Microsoft Office Access database engine cannot open or write to
  the file ''. It is already opened exclusively by another user, or you
  need permission to view and write its data." at  Econ.Open();

```<code>public partial class LBMIS1New : System.Web.UI.Page
{
    OleDbConnection Econ;
    SqlConnection con;

    string constr, Query, sqlconn;
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    private void ExcelConn(string FilePath)
    {

        constr = string.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0 Xml;HDR=YES;""", FilePath);
        Econ = new OleDbConnection(constr);

    }
    private void connection()
    {
        sqlconn = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
        con = new SqlConnection(sqlconn);

    }

    private void InsertExcelRecords(string FilePath)
    {
        ExcelConn(FilePath);

        Query = string.Format("Select [Name],[City],[Address],[Designation] FROM [{0}]", "Sheet1$");
        OleDbCommand Ecom = new OleDbCommand(Query, Econ);
        Econ.Open();

        DataSet ds = new DataSet();
        OleDbDataAdapter oda = new OleDbDataAdapter(Query, Econ);
        Econ.Close();
        oda.Fill(ds);
        DataTable Exceldt = ds.Tables[0];
        connection();
        //creating object of SqlBulkCopy
        SqlBulkCopy objbulk = new SqlBulkCopy(con);
        //assigning Destination table name
        objbulk.DestinationTableName = "Employee";
        //Mapping Table column
        objbulk.ColumnMappings.Add("Name", "Name");
        objbulk.ColumnMappings.Add("City", "City");
        objbulk.ColumnMappings.Add("Address", "Address");
        objbulk.ColumnMappings.Add("Designation", "Designation");
        //inserting Datatable Records to DataBase
        con.Open();
        objbulk.WriteToServer(Exceldt);
        con.Close();

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        string CurrentFilePath = Path.GetFullPath(FileUpload1.PostedFile.FileName);
        InsertExcelRecords(CurrentFilePath);
    }
}
</code>```

答: You can work with a copy of your file...</p>

Body:
I am getting this below exception

"The Microsoft Office Access database engine cannot open or write to
  the file ''. It is already opened exclusively by another user, or you
  need permission to view and write its data." at  Econ.Open();

public partial class LBMIS1New : System.Web.UI.Page
{
    OleDbConnection Econ;
    SqlConnection con;

    string constr, Query, sqlconn;
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    private void ExcelConn(string FilePath)
    {

        constr = string.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0 Xml;HDR=YES;""", FilePath);
        Econ = new OleDbConnection(constr);

    }
    private void connection()
    {
        sqlconn = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
        con = new SqlConnection(sqlconn);

    }

    private void InsertExcelRecords(string FilePath)
    {
        ExcelConn(FilePath);

        Query = string.Format("Select [Name],[City],[Address],[Designation] FROM [{0}]", "Sheet1$");
        OleDbCommand Ecom = new OleDbCommand(Query, Econ);
        Econ.Open();

        DataSet ds = new DataSet();
        OleDbDataAdapter oda = new OleDbDataAdapter(Query, Econ);
        Econ.Close();
        oda.Fill(ds);
        DataTable Exceldt = ds.Tables[0];
        connection();
        //creating object of SqlBulkCopy
        SqlBulkCopy objbulk = new SqlBulkCopy(con);
        //assigning Destination table name
        objbulk.DestinationTableName = "Employee";
        //Mapping Table column
        objbulk.ColumnMappings.Add("Name", "Name");
        objbulk.ColumnMappings.Add("City", "City");
        objbulk.ColumnMappings.Add("Address", "Address");
        objbulk.ColumnMappings.Add("Designation", "Designation");
        //inserting Datatable Records to DataBase
        con.Open();
        objbulk.WriteToServer(Exceldt);
        con.Close();

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        string CurrentFilePath = Path.GetFullPath(FileUpload1.PostedFile.FileName);
        InsertExcelRecords(CurrentFilePath);
    }
}


问:
Ember Data: Pushing the data to the store will not replace the changedAttributes of the record?
I am using Ember Data and I have a model say my-model. I am having a realtime notification server to update my application if there is any change for a record. When I am editing an attribute of my-model from UI, the model has some changedAttributes and when the real time notification comes, I am fetching the record from the server and pushing it to the store using store.push(store.normalize('my-model', data)).

Now, In the store the model still has my changedAttributes and it is not replaced. So I believe, the Ember Store will not replace the entire record and will replace only the clean attributes of the record when I do a store.push. I just want to confirm the behaviour. Can someone confirm if my understanding about this is right?

答:
I've written a small Ember Twiddle to test that behavior: https://ember-twiddle.com/a8eb87a1c7e5019214320d81af05aca5?openFiles=templates.application.hbs%2C As it shows ember-data does not reset dirty attributes if the record is pushed again into the store - at least not for the tested version 3.4.2, which is a little bit outdated.

I wasn't able to find any tests in ember-data repository that covers your use case but I'm also not that familiar with Ember Data's source code. So you might want to open an issue there or ask on Ember Community Discord or Ember Discussion Forum if this is expected behavior.

To be honest I guess there should be a straight-forward solution to your problem as realtime notification (e.g. through WebSocket) is a common use case.


问:
Convert HEX to ASCII, data from GPS tracker
I have just bought a GPS Tracker, it can send SMS to cellphone just fine. It also supports reporting to a server via GPRS.

I have setup the device to contact my own server on port 8123, it's a FreeBSD server and i have checked that i recieve packets on that port.

I successfully have setup a listener server written in PHP, and i can receive data from the device. But how do i convert the partial HEX data to something usefull (ASCII)?

Example data string:

```$$^@T^@E Y'^WÿU210104.000,A,5534.4079,N,01146.2510,E,0.00,,170411,,*10|1.0|72|0000á```

Unfortunately i don't know how i can copy-paste the HEX parts

Now how do i get the ID part out? I have tried echo hexdec(mb_substr($data, 4, 7));

The data is following this protocol

From the document:

```
Command format of GPRS packets are as follows:

From server to tracker:
@@\r\n

From tracker to server:
$$\r\n

Note:
Do NOT input ‘’ when writing a command.
All multi-byte data complies with the following sequence: High byte prior to low byte.
The size of a GPRS packet (including data) is about 100 bytes

Item        Specification
@@          2 bytes. It means the header of packet from server to tracker.
            It is in ASCII code (Hex code: 0x40)

$$          2 bytes. It is the header of packet from tracker to server.
            It is in ASCII code (Hex code: 0x24)

L           2 bytes. It means the length of the whole packet including
            the header and ending character and it is in hex code

ID          7 bytes, ID must be digit and not over 14 digits, the unused byte
            will be stuffed by ‘f’ or ‘0xff’. It is in the format of hex code.
            For example, if ID is 13612345678, then it will be shown as
            follows: 0x13, 0x61, 0x23, 0x45, 0x67, 0x8f, 0xff.
            If all 7 bytes are 0xff, it is a broadcasting command. ID is in hex code

command     2 bytes. The command code is in hex code. Please refer to the
            command list below.

data        Min 0 byte and max 100 bytes. See Annex 1 for description of ‘data’.

checksum    2 bytes. It indicates CRC-CCITT (default is 0xffff) checksum of
            all data (not including CRC itself and the ending character).
            It is in hex code.
            For example: 24 24 00 11 13 61 23 45 67 8f ff 50 00 05 d8 0d 0a
            0x05d8 = CRC-CCITT (24 24 00 11 13 61 23 45 67 8f ff 50 00)

\r\n        2 bytes. It is the ending character and in hex code
            (0x0d,0x0a in hex code)
```

Update

With the answer from Anomie, i was able to piece this together

```<code>$arr = unpack('H4length/H14id/H4cmd/H4crc/H4end', mb_substr($data, 2, 11) . mb_substr($data, -4));

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

This will out put something like

```
array(5) {
  ["length"]=>
  string(4) "0054"
  ["id"]=>
  string(14) "004512345678ff"
  ["cmd"]=>
  string(4) "9955"
  ["crc"]=>
  string(4) "c97e"
  ["end"]=>
  string(4) "0d0a"
}
```

答:
You need to know the format of the messages you are going to receive from the device. You can get this info from the manufacturer. Then, depending on that, you have to create a proper listener in the server side.

I've been working with several devices like that and normally you have to create a process in the server listening to the port with a Socket (or similar). You may have an authentication process also to differentiate between devices (you can have more than one). After that, you simply get the data from the device, you parse it and you store it. Depending on the device you can also send requests or configurations.

Hope this helps

OwnerDisplayName: Phliplip

Body:
I have just bought a GPS Tracker, it can send SMS to cellphone just fine. It also supports reporting to a server via GPRS.

I have setup the device to contact my own server on port 8123, it's a FreeBSD server and i have checked that i recieve packets on that port.

I successfully have setup a listener server written in PHP, and i can receive data from the device. But how do i convert the partial HEX data to something usefull (ASCII)?

Example data string:

$$^@T^@E Y'^WÿU210104.000,A,5534.4079,N,01146.2510,E,0.00,,170411,,*10|1.0|72|0000á

Unfortunately i don't know how i can copy-paste the HEX parts

Now how do i get the ID part out? I have tried echo hexdec(mb_substr($data, 4, 7));

The data is following this protocol

From the document:

Command format of GPRS packets are as follows:

From server to tracker:
@@\r\n

From tracker to server:
$$\r\n

Note:
Do NOT input ‘’ when writing a command.
All multi-byte data complies with the following sequence: High byte prior to low byte.
The size of a GPRS packet (including data) is about 100 bytes

Item        Specification
@@          2 bytes. It means the header of packet from server to tracker.
            It is in ASCII code (Hex code: 0x40)

$$          2 bytes. It is the header of packet from tracker to server.
            It is in ASCII code (Hex code: 0x24)

L           2 bytes. It means the length of the whole packet including
            the header and ending character and it is in hex code

ID          7 bytes, ID must be digit and not over 14 digits, the unused byte
            will be stuffed by ‘f’ or ‘0xff’. It is in the format of hex code.
            For example, if ID is 13612345678, then it will be shown as
            follows: 0x13, 0x61, 0x23, 0x45, 0x67, 0x8f, 0xff.
            If all 7 bytes are 0xff, it is a broadcasting command. ID is in hex code

command     2 bytes. The command code is in hex code. Please refer to the
            command list below.

data        Min 0 byte and max 100 bytes. See Annex 1 for description of ‘data’.

checksum    2 bytes. It indicates CRC-CCITT (default is 0xffff) checksum of
            all data (not including CRC itself and the ending character).
            It is in hex code.
            For example: 24 24 00 11 13 61 23 45 67 8f ff 50 00 05 d8 0d 0a
            0x05d8 = CRC-CCITT (24 24 00 11 13 61 23 45 67 8f ff 50 00)

\r\n        2 bytes. It is the ending character and in hex code
            (0x0d,0x0a in hex code)

Update

With the answer from Anomie, i was able to piece this together

$arr = unpack('H4length/H14id/H4cmd/H4crc/H4end', mb_substr($data, 2, 11) . mb_substr($data, -4));

var_dump($arr);

This will out put something like

array(5) {
  ["length"]=>
  string(4) "0054"
  ["id"]=>
  string(14) "004512345678ff"
  ["cmd"]=>
  string(4) "9955"
  ["crc"]=>
  string(4) "c97e"
  ["end"]=>
  string(4) "0d0a"
}


问:
laravel scopes with relation and conditions
i have this laravel scope code

```<code>public function apply(Builder $builder, Model $model)
{
    $builder->whereDoesntHave('getPermissionData');
}
</code>```

everything working fine till now what i need is to wright conditions
like this

```<code>public function apply(Builder $builder, Model $model)
{
    /*
        if($builder->whereHas('getPermissionData'))
        {
            check the relation
            and do some code here
        }
    */
    $builder->whereDoesntHave('getPermissionData');
}
</code>```

is that possible or not

答:
You need to create two different conditions in or with each others. You also should wrap this condition in a where clause so next conditions won't be in or aswell

```<code>public function apply(Builder $builder, Model $model) {
    $builder->where(function ($query) {
         $query->whereDoesntHave('getPermissionData')
               ->orWhereHas('getPermissionData', function ($permissionQuery) {
                   // Apply your condition to the relation query
               });
    });
}
</code>```

Body:
i have this laravel scope code

public function apply(Builder $builder, Model $model)
{
    $builder->whereDoesntHave('getPermissionData');
}

everything working fine till now what i need is to wright conditions
like this

public function apply(Builder $builder, Model $model)
{
    /*
        if($builder->whereHas('getPermissionData'))
        {
            check the relation
            and do some code here
        }
    */
    $builder->whereDoesntHave('getPermissionData');
}

is that possible or not

Body:
You need to create two different conditions in or with each others. You also should wrap this condition in a where clause so next conditions won't be in or aswell

public function apply(Builder $builder, Model $model) {
    $builder->where(function ($query) {
         $query->whereDoesntHave('getPermissionData')
               ->orWhereHas('getPermissionData', function ($permissionQuery) {
                   // Apply your condition to the relation query
               });
    });
}


问:
How to make a list from string values (dates in a cell separated by delimeter)
I have a table shown like this (there is only one column where all dates are written in one cell, separated by a delimiter). How to make a list of dates out of those values and calculate MAX and MIN value in a particular row?

```<code>values
1. 01. 2019;5. 07. 2016;3. 05. 2014;1. 04. 2019;7. 04. 2016
2. 01. 2019;6. 07. 2016;2. 01. 2019;3. 01. 2019;8. 04. 2016
3. 01. 2019;7. 07. 2016;4. 01. 2019;9. 07. 2016
8. 07. 2016;8. 07. 2016;9. 07. 2016;4. 01. 2019;10. 04. 2016
5. 01. 2019;3. 04. 2019;8. 04. 2016;11. 04. 2016
6. 01. 2019;2. 04. 2019;6. 01. 2019;6. 07. 2016
</code>```

I tried to do List.Max([values]), but this doesn't work.

答:
You can Transform each record of your single column to a list of dates, then add columns for the Min and Max values:

```<code>let
    Source = YourTable
    #"Listed Dates" = Table.TransformColumns(Source, {{"Column1", each List.Transform(Text.Split(_,";"), each Date.FromText(_))}}),
    #"Added Min" = Table.AddColumn(#"Listed Dates", "Min Date", each List.Min([Column1]), type date),
    #"Added Max" = Table.AddColumn(#"Added Min", "Max Date", each List.Max([Column1]), type date)
in
    #"Added Max"
</code>```

See https://pwrbi.com/so_56333087/ for worked example

Body:
I have a table shown like this (there is only one column where all dates are written in one cell, separated by a delimiter). How to make a list of dates out of those values and calculate MAX and MIN value in a particular row?

values
1. 01. 2019;5. 07. 2016;3. 05. 2014;1. 04. 2019;7. 04. 2016
2. 01. 2019;6. 07. 2016;2. 01. 2019;3. 01. 2019;8. 04. 2016
3. 01. 2019;7. 07. 2016;4. 01. 2019;9. 07. 2016
8. 07. 2016;8. 07. 2016;9. 07. 2016;4. 01. 2019;10. 04. 2016
5. 01. 2019;3. 04. 2019;8. 04. 2016;11. 04. 2016
6. 01. 2019;2. 04. 2019;6. 01. 2019;6. 07. 2016

I tried to do List.Max([values]), but this doesn't work.

Body:
You can Transform each record of your single column to a list of dates, then add columns for the Min and Max values:

let
    Source = YourTable
    #"Listed Dates" = Table.TransformColumns(Source, {{"Column1", each List.Transform(Text.Split(_,";"), each Date.FromText(_))}}),
    #"Added Min" = Table.AddColumn(#"Listed Dates", "Min Date", each List.Min([Column1]), type date),
    #"Added Max" = Table.AddColumn(#"Added Min", "Max Date", each List.Max([Column1]), type date)
in
    #"Added Max"

See https://pwrbi.com/so_56333087/ for worked example


问:
UWP ListView/GridView DragItems results to Catastrophic Failure
We are developing an UWP App that needs the ability to drag items from one GridView to another.
While testing this functionality we encountered multiple catastrophic failures 0x80000FFFF.

After almost 2 days of research we were not able to find a solution for our problem.
We found out that these failures happen, when there's an ItemTemplate set for the GridView the item is dragged from.

Even trying out the official drag-drop sample provided by Microsoft “XamlDragAndDrop”,(https://github.com/Microsoft/Windows-universal-samples/tree/master/Samples/XamlDragAndDrop), when you drag the items in Scenario1 from the source ListView to the target ListView (~30-50) times, you will encounter the failure as well.

Has someone else encountered this problem before? We would be super grateful for any advice!

Our developing machines run Windows 10 Enterprise, Version 1803, OS build 17134.285.

Opened an issue on the official GitHub repo.
https://github.com/Microsoft/Windows-universal-samples/issues/977

I recorded a small video of the sample crashing.
https://1drv.ms/v/s!AiZ-jksNqbXLi9kZPPfSeGmQr_YeHg

We managed the get the native trace here.

When running in release mode its crashing earlier, and also when the redraw function is turned on in the display heatmap section.

答:
According to the Raymond Chen this is a plataform specific problem which was solved in the Windows 10 May 2019 update.

So the solution is: update your version of the windows to the latest.
Find out here how you can update it.

Windows 10 May 2019 (What's new)

Windows 10 May 2019 changelog


问:
How to structure a React App with several functional areas on different ports?
A web application that we are building must have 3 different "areas" accessible on 3 different ports, for example:

localhost:9001 - for Admins

localhost:9002 - for Customers

localhost:9003 - for Non-Registered users

The back-end is built on Hapi/Node and exposes many API endpoints to be consumed by the UI. The front-end must now be built in React - the three areas should share common UI elements, but being on different ports each of them may have unique UI features.

How would you go about structuring the front-end code (React) of the application in this scenario?

Until now, I would use create-react-app and build an app that in practice has only 1 port - and use authentication/authorization to limit certain functionalities. Now, with three different functional areas, should there be 3 separate create-react-apps, one for each area, living in the same root project? Would the shared UI elements be inside a separate "Shared" module and then the 3 different apps would import the components from there?

All advice on how to structure a React App to work with (at least) 3 different ports / areas is much appreciated.

答:
I am aware that the response might be too late for the question at this point in time.

But, if you really want to explore more on your question. You can check out Lerna tool.


问:
Spring CrudRepository method findAll() returns an empty list
So, my problem is in the title - crudrepository method findAll() returns a null list. I've overriden Crud's method because it returned an iterable instead of a list.

I've tried using the JpaRepository instead of CrudRepository (I didn't override the findAll() method then), but got the same result.

My code:

Event.java

```<code>@Data
@Entity
@NoArgsConstructor
public class Event{

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable=false)
    private String name;

    @Column(nullable=false)
    private LocalDateTime time;

    @ManyToOne
    @JoinColumn
    private City city;

}
</code>```

City.java

```<code>@Data
@Entity
@NoArgsConstructor
public class City {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable=false)
    private Long code;

    @Column(nullable=false)
    private String name;

        @OneToMany(mappedBy = "city", cascade = CascadeType.ALL)
        private Set<Event> events;
    }

CityRepository.java

    @Repository
    public interface CityRepository extends CrudRepository<City, Long> {

    @Override
    List<City> findAll();
}
</code>```

EventsController.java

```<code>@Controller
@RequestMapping
public class EventsController {

    @Autowired
    static CityRepository cityRepository;

    public static List<Event> eventList = new ArrayList<>();

    @RequestMapping
    public String eventEntry(Model model) {

        model.addAttribute("event", new Event());
        model.addAttribute("cities", cityRepository.findAll());

        return "eventEntry";
    }
}
</code>```

eventEntry.html

```<code><!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
  xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Event entry</title>
</head>
<body>

    <h3>New event</h3>

    <form method="POST" th:object="${event}">

        <div class="form-group">
            <label for="city">City: </label>
            <select th:field="*{city}">
                <option value="" >Choose a city</option>
                <option th:each="city : ${cities}" th:value="${city}" th:text="${city}"></option>
            </select>
            <span class="validation-error" th:if="${#fields.hasErrors('city')}" th:errors="*{city}">City Error</span>
        </div>

        <div class="form-group">
            <label for="name">Name: </label>
            <input type="text" th:field="*{name}" />
            <span class="validation-error" th:if="${#fields.hasErrors('name')}" th:errors="*{name}">Name Error</span>
        </div>

        <div class="form-group">
            <label for="time">Time: </label>
            <input type="datetime-local" th:field="*{time}" />
            <span class="validation-error" th:if="${#fields.hasErrors('time')}" th:errors="*{time}">Time Error</span>
        </div>

        <div class="form-group">
            <input type="submit" th:value="Save">
        </div>

    </form>
</body>
</code>```

I am using an embedded H2 database with a data.sql file used to fill data into the database (I don't have the schema.sql file since tables are created using annotations).
When viewing the H2 database console and using the SELECT * FROM CITY I'm getting the list of the cities.

I am getting a NullPointerException on this line from the EventController class: model.addAttribute("cities", cityRepository.findAll());
Can someone explain why?

答: removed the static declaration in front of the repository, it works fine now

Body:
So, my problem is in the title - crudrepository method findAll() returns a null list. I've overriden Crud's method because it returned an iterable instead of a list.

I've tried using the JpaRepository instead of CrudRepository (I didn't override the findAll() method then), but got the same result.

My code:

Event.java

@Data
@Entity
@NoArgsConstructor
public class Event{

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable=false)
    private String name;

    @Column(nullable=false)
    private LocalDateTime time;

    @ManyToOne
    @JoinColumn
    private City city;

}

City.java

@Data
@Entity
@NoArgsConstructor
public class City {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable=false)
    private Long code;

    @Column(nullable=false)
    private String name;

        @OneToMany(mappedBy = "city", cascade = CascadeType.ALL)
        private Set<Event> events;
    }

CityRepository.java

    @Repository
    public interface CityRepository extends CrudRepository<City, Long> {

    @Override
    List<City> findAll();
}

EventsController.java

@Controller
@RequestMapping
public class EventsController {

    @Autowired
    static CityRepository cityRepository;

    public static List<Event> eventList = new ArrayList<>();

    @RequestMapping
    public String eventEntry(Model model) {

        model.addAttribute("event", new Event());
        model.addAttribute("cities", cityRepository.findAll());

        return "eventEntry";
    }
}

eventEntry.html

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Event entry</title>

New event

    <form method="POST" th:object="${event}">

            City:
            <select th:field="*{city}">
                <option value="" >Choose a city</option>
                <option th:each="city : ${cities}" th:value="${city}" th:text="${city}"></option>
            </select>
            City Error

            Name:
            <input type="text" th:field="*{name}" />
            Name Error

            Time:
            <input type="datetime-local" th:field="*{time}" />
            Time Error

            <input type="submit" th:value="Save">

    </form>

I am using an embedded H2 database with a data.sql file used to fill data into the database (I don't have the schema.sql file since tables are created using annotations).
When viewing the H2 database console and using the SELECT * FROM CITY I'm getting the list of the cities.

I am getting a NullPointerException on this line from the EventController class: model.addAttribute("cities", cityRepository.findAll());
Can someone explain why?


问:
Django i cannot add button in modal for each field with ajax
I m trying to put a button in my table but i cannot succeed

i receive an error
"Reverse for 'editare-agenda' with keyword arguments '{'pk': '+field.id+'}' not found. 1 pattern(s) tried: ['dashboard/editare\-agenda/(?P[0-9]+)$']"

if i put an number  instead +field.id+ is working . if i test alert(field.id) i receive the id. is something wrong writing {% url 'dasboard:editare-agenda' pk=field.id %} but i cannot find the solution.

this is my urls.py:

path('editare-agenda/<"int":pk>', editare_agenda, name="editare-agenda"),

** "int" = int  -> i cannot write int in url path because he disappear

```<code> $.ajax({
    data: values,
    method:"POST",
    url: destinatie,
    contenttType: 'application/json',
    success: function(data){
        var content ="";
        $.each(data.agenda, function(i, field){
            content += '<tr class="text-center">';
            content += '<td>'+field.denumire_unitate+'</td>';
            content += '<td>'+field.sectia+'</td>';
            content += '<td>'+field.telefon+'</td>';
            content += '<td>'+field.pers_contact+'</td>';
            content += '<td>'+field.adresa+'</td>';
            content += '<td><a href="{% url "dashboard:editare-agenda" pk='+field.id+'%}"><button type="button" class="btn btn-sm" style="border-radius: 5px;margin: 1px;"><i class="fas fa-edit fa-lg" style="color: blue"></i></button></a></td>';
            content += '</tr>';
    });
    $('#tabela_agenda').html(content);
}
</code>```

});

答:
You can change your url entry

```<code>path('editare-agenda/', editare_agenda, name="editare-agenda"),
</code>```

and in template

```<code>content += '<td><a href="{% url "dashboard:editare-agenda" %}?id='+field.id+'"><button type="button" tclass="btn btn-sm" style="border-radius: 5px;margin: 1px;"><i class="fas fa-edit fa-lg" style="color: blue"></i></button></a></td>';
</code>```

and in view

def editare_agenda(request):
    field_id = request.GET.get('id', None)
     # Now you can use field id as pk
    .....
```

Body:
I m trying to put a button in my table but i cannot succeed

i receive an error
"Reverse for 'editare-agenda' with keyword arguments '{'pk': '+field.id+'}' not found. 1 pattern(s) tried: ['dashboard/editare\-agenda/(?P[0-9]+)$']"

if i put an number  instead +field.id+ is working . if i test alert(field.id) i receive the id. is something wrong writing {% url 'dasboard:editare-agenda' pk=field.id %} but i cannot find the solution.

this is my urls.py:

path('editare-agenda/<"int":pk>', editare_agenda, name="editare-agenda"),

** "int" = int  -> i cannot write int in url path because he disappear

 $.ajax({
    data: values,
    method:"POST",
    url: destinatie,
    contenttType: 'application/json',
    success: function(data){
        var content ="";
        $.each(data.agenda, function(i, field){
            content += '
';
            content += ''+field.denumire_unitate+'	';
            content += ''+field.sectia+'	';
            content += ''+field.telefon+'	';
            content += ''+field.pers_contact+'	';
            content += ''+field.adresa+'	';
            content += '<button type="button" class="btn btn-sm" style="border-radius: 5px;margin: 1px;"></button>	';
            content += '
';
    });
    $('#tabela_agenda').html(content);
}

});

Body:
You can change your url entry

path('editare-agenda/', editare_agenda, name="editare-agenda"),

and in template

content += '<td><a href="{% url "dashboard:editare-agenda" %}?id='+field.id+'"><button type="button" tclass="btn btn-sm" style="border-radius: 5px;margin: 1px;"><i class="fas fa-edit fa-lg" style="color: blue"></i></button></a></td>';

and in view

def editare_agenda(request):
    field_id = request.GET.get('id', None)
     # Now you can use field id as pk
    .....


问:
How can I add an Double_Click Event Handler to a DataTable?
I work with VisualStudio19, C# and WPF. I have a method to copy the selected Datarow from Table one, to Table two with a button_click, but now I want to copy the row when I double click it. I will use the same method as button_click for that so I need only an Eventhandler which start my method on doubleclick

The Tables:

```<code>       public MainWindow()
    {
        InitializeComponent();

        //First Table for all values
        tableAllVar.Columns.Add("Parameter", typeof(string));
        tableAllVar.Columns.Add("Adresse", typeof(string));
        tableAllVar.Columns.Add("Groesse", typeof(string));
        dgTable1.ItemsSource = tableAllVar.DefaultView;

        //second Table for selected values
        tableSelectedVar.Columns.Add("Parameter", typeof(string));
        tableSelectedVar.Columns.Add("Adresse", typeof(string));
        tableSelectedVar.Columns.Add("Groesse", typeof(string));
        dgTable2.ItemsSource = tableSelectedVar.DefaultView;
    }
</code>```

The two Tables left ist the table I want to copy the row and right is the aimtable for the row.

My method to copy the selected Datarow with a Button

```<code>        private void ButtonAddVar_Click(object sender, RoutedEventArgs e)
    {
        string[] daten = new string[3];
        if (dgTable1.SelectedItem != null)
        {
            DataRowView datarow = (DataRowView)dgTable1.SelectedItem;
            daten[0] = (string)datarow.Row.ItemArray[0];
            daten[1] = (string)datarow.Row.ItemArray[1];
            daten[2] = (string)datarow.Row.ItemArray[2];
            bool rowExists = ContainDataRowInDataTable(tableSelectedVar, datarow.Row);
            if (rowExists == false)
            {
                tableSelectedVar.Rows.Add(daten[0], daten[1], daten[2]);
                //anzahl++;
            }
            else
            {
                MessageBox.Show("Die Variable ist bereits Teil der Variablenüberwachung", null, MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        else
            MessageBox.Show("Bitte eine Variable aus der linken Liste mit der Maus auswählen",null,MessageBoxButton.OK,MessageBoxImage.Information);
    }
</code>```

And here the way i create my Datagrid in the xaml

```<code><DataGrid Name="dgTable1"  HorizontalAlignment="Left" Height="180" Margin="5,30,0,0" VerticalAlignment="Top" Width="150" AutoGenerateColumns="False" FontSize="6" ColumnHeaderHeight="15" IsReadOnly="True"  >
            <DataGrid.Columns>
                <DataGridTextColumn Header="Parameter" Binding="{Binding Path=Parameter}"  Width="auto" />
                <DataGridTextColumn Header="Adresse" Binding="{Binding Path=Adresse}" Width="auto"/>
                <DataGridTextColumn Header="Größe" Binding="{Binding Path=Größe}" Width="auto"/>
            </DataGrid.Columns>
        </DataGrid>
</code>```

I saw that the DataGrid has an Eventhandler for Double_Click but i don't know how i can use them for the DataTable?
When i can't use them for Table how can i make a new Eventhandler for that event?

答:
As you know DataGrid has a Double_Click  Eventhandler
for copy one row you can use selected row property.</p>

```<code> private void dgTable1_MouseDoubleClick(object sender, MouseButtonEventArgs e)
 {
 string[] daten = new string[3];
 if (dgTable1.SelectedItem != null)
 {
 DataRowView datarow = (DataRowView)dgTable1.SelectedItem;
 daten[0] = (string)datarow.Row.ItemArray[0];
 daten[1] = (string)datarow.Row.ItemArray[1];
 daten[2] = (string)datarow.Row.ItemArray[2];
 }
 else
 MessageBox.Show("please select again");
 }
</code>```

Body:
I work with VisualStudio19, C# and WPF. I have a method to copy the selected Datarow from Table one, to Table two with a button_click, but now I want to copy the row when I double click it. I will use the same method as button_click for that so I need only an Eventhandler which start my method on doubleclick

The Tables:

       public MainWindow()
    {
        InitializeComponent();

        //First Table for all values
        tableAllVar.Columns.Add("Parameter", typeof(string));
        tableAllVar.Columns.Add("Adresse", typeof(string));
        tableAllVar.Columns.Add("Groesse", typeof(string));
        dgTable1.ItemsSource = tableAllVar.DefaultView;

        //second Table for selected values
        tableSelectedVar.Columns.Add("Parameter", typeof(string));
        tableSelectedVar.Columns.Add("Adresse", typeof(string));
        tableSelectedVar.Columns.Add("Groesse", typeof(string));
        dgTable2.ItemsSource = tableSelectedVar.DefaultView;
    }

The two Tables left ist the table I want to copy the row and right is the aimtable for the row.

My method to copy the selected Datarow with a Button

        private void ButtonAddVar_Click(object sender, RoutedEventArgs e)
    {
        string[] daten = new string[3];
        if (dgTable1.SelectedItem != null)
        {
            DataRowView datarow = (DataRowView)dgTable1.SelectedItem;
            daten[0] = (string)datarow.Row.ItemArray[0];
            daten[1] = (string)datarow.Row.ItemArray[1];
            daten[2] = (string)datarow.Row.ItemArray[2];
            bool rowExists = ContainDataRowInDataTable(tableSelectedVar, datarow.Row);
            if (rowExists == false)
            {
                tableSelectedVar.Rows.Add(daten[0], daten[1], daten[2]);
                //anzahl++;
            }
            else
            {
                MessageBox.Show("Die Variable ist bereits Teil der Variablenüberwachung", null, MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        else
            MessageBox.Show("Bitte eine Variable aus der linken Liste mit der Maus auswählen",null,MessageBoxButton.OK,MessageBoxImage.Information);
    }

And here the way i create my Datagrid in the xaml

<DataGrid Name="dgTable1"  HorizontalAlignment="Left" Height="180" Margin="5,30,0,0" VerticalAlignment="Top" Width="150" AutoGenerateColumns="False" FontSize="6" ColumnHeaderHeight="15" IsReadOnly="True"  >
            <DataGrid.Columns>
                <DataGridTextColumn Header="Parameter" Binding="{Binding Path=Parameter}"  Width="auto" />
                <DataGridTextColumn Header="Adresse" Binding="{Binding Path=Adresse}" Width="auto"/>
                <DataGridTextColumn Header="Größe" Binding="{Binding Path=Größe}" Width="auto"/>
            </DataGrid.Columns>
        </DataGrid>

I saw that the DataGrid has an Eventhandler for Double_Click but i don't know how i can use them for the DataTable?
When i can't use them for Table how can i make a new Eventhandler for that event?

Body:
As you know DataGrid has a Double_Click  Eventhandler
for copy one row you can use selected row property.

 private void dgTable1_MouseDoubleClick(object sender, MouseButtonEventArgs e)
 {
 string[] daten = new string[3];
 if (dgTable1.SelectedItem != null)
 {
 DataRowView datarow = (DataRowView)dgTable1.SelectedItem;
 daten[0] = (string)datarow.Row.ItemArray[0];
 daten[1] = (string)datarow.Row.ItemArray[1];
 daten[2] = (string)datarow.Row.ItemArray[2];
 }
 else
 MessageBox.Show("please select again");
 }


问:
Matching of cells in excel
It Sum of columns is storing in one cell and if I want the same answer to be printed in another cell, what is the formula to get this?</p>

答:
Let's say your sum is stored in B1 and you want same in C1 then you can do

=B1

inside C1 cell

Title: Matching of cells in excel


问:
QMessageBox position on QMessageBox.warning call
From current window I am trying to create a simple confirmation dialog using QMessageBox.

My code is:

```<code>res = QMessageBox.question(QMessageBox(currentWindow), "Question",  "Are you sure?", QMessageBox.Yes | QMessageBox.No)

</code>```

The problem is that the confirmation dialog appears in absolutely random place on the screen and not on top of the parent window. I observe this behavior on MacOS 10.12. And it is also the case for QMessageBox.warning, QMessageBox.critical, and other static methods.

Is there any way to set the position of modal dialog to be relative to its parent?

答:
The first parameter of QMessageBox::question() is the parent which will be used by the dialog box. A QDialog is centered (and modal) on its parent.

By doing QMessageBox.question(QMessageBox(currentWindow), you pass a new instance of QMessageBox which is not displayed.

Pass currentWindow instead:

```<code>res = QMessageBox.question(currentWindow, "Question", "Are you sure?", QMessageBox.Yes | QMessageBox.No)
</code>```

But, you need to be sure that currentWindow is displayed and not None.

Body:
From current window I am trying to create a simple confirmation dialog using QMessageBox.

My code is:

res = QMessageBox.question(QMessageBox(currentWindow), "Question",  "Are you sure?", QMessageBox.Yes | QMessageBox.No)

The problem is that the confirmation dialog appears in absolutely random place on the screen and not on top of the parent window. I observe this behavior on MacOS 10.12. And it is also the case for QMessageBox.warning, QMessageBox.critical, and other static methods.

Is there any way to set the position of modal dialog to be relative to its parent?

Body:
The first parameter of QMessageBox::question() is the parent which will be used by the dialog box. A QDialog is centered (and modal) on its parent.

By doing QMessageBox.question(QMessageBox(currentWindow), you pass a new instance of QMessageBox which is not displayed.

Pass currentWindow instead:

res = QMessageBox.question(currentWindow, "Question", "Are you sure?", QMessageBox.Yes | QMessageBox.No)

But, you need to be sure that currentWindow is displayed and not None.


问:
Removing attributes from oracle json object
Use case:
Application requires a subset of attributes, based on business rules

Example:
Some students do not require to enter in home address

Database : Oracle

Proposed implementation:
Build json object containing all possible attribute named pairs, then selectively remove specific named pairs

Issue:
Hoped to use native oracle function to remove the specified named pair.
e.g json_object.remove_attribute('home_address');
However Oracle do not appear to provide any such method.

Workaround : Convert json_object to VARCHAR2 string, and then use combination of INSTR and REPLACE to remove named pair.

Illustrative code:

```<code>DECLARE
  CURSOR cur_student_json (p_s_ref IN VARCHAR2) IS
  SELECT  JSON_OBJECT(
       ,'s_surname'                     value s.s_surname
       ,'s_forename_1'                  value s.s_forename_1
       ,'s_home_address_1'              value s.s_home_address_1
  RETURNING VARCHAR2 ) student_json
    FROM   students  s
   WHERE  s.s_ref = p_s_ref;

BEGIN
  FOR x IN cur_student_json (p_s_ref) LOOP
    vs_student_json:=x.student_json;
    EXIT;
  END LOOP;

  -- Determine student type
  vs_student_type:=get_student_type(p_s_ref);

  -- Collect list of elements not required, based on student type
  FOR x IN cur_json_inorout(vs_student_type) LOOP
     -- Remove element from the json
     vs_student_json:=json_remove(vs_student_json,x.attribute);
  END LOOP;
END;
/
</code>```

Question:
There must be an elegant method to achieve requirement

答:
Classify under RTFM. Needs Oracle 12.2</p>

```<code>DECLARE

  -- Declare an object of type JSON_OBJECT_T
  l_obj JSON_OBJECT_T;

  -- Declare cursor to build json object
  CURSOR cur_student_json (p_s_ref IN VARCHAR2) IS
  SELECT  JSON_OBJECT(
      ,'s_surname'                     value s.s_surname
      ,'s_forename_1'                  value s.s_forename_1
      ,'s_home_address_1'              value s.s_home_address_1
    ) student_json
    FROM   students  s
   WHERE  s.s_ref = p_s_ref;

BEGIN

  -- Initialise object
  l_obj := JSON_OBJECT_T();

  -- Populate the object
  FOR x IN cur_student_json (p_s_ref) LOOP
    l_obj:=JSON_OBJECT_T.parse(x.student_json);
    EXIT;
  END LOOP;

  -- Determine student type
  vs_student_type:=get_student_type(p_s_ref);

  -- Collect list of elements not required, based on student type
  FOR x IN cur_json_inorout(vs_student_type) LOOP
    -- Remove element from the json
    l_obj.remove(x.attribute);
  END LOOP;

  -- Display modified object
  dbms_output.put_line(l_obj.stringify);
END;
/
</code>```

Body:
Use case:
Application requires a subset of attributes, based on business rules

Example:
Some students do not require to enter in home address

Database : Oracle

Proposed implementation:
Build json object containing all possible attribute named pairs, then selectively remove specific named pairs

Issue:
Hoped to use native oracle function to remove the specified named pair.
e.g json_object.remove_attribute('home_address');
However Oracle do not appear to provide any such method.

Workaround : Convert json_object to VARCHAR2 string, and then use combination of INSTR and REPLACE to remove named pair.

Illustrative code:

DECLARE
  CURSOR cur_student_json (p_s_ref IN VARCHAR2) IS
  SELECT  JSON_OBJECT(
       ,'s_surname'                     value s.s_surname
       ,'s_forename_1'                  value s.s_forename_1
       ,'s_home_address_1'              value s.s_home_address_1
  RETURNING VARCHAR2 ) student_json
    FROM   students  s
   WHERE  s.s_ref = p_s_ref;

BEGIN
  FOR x IN cur_student_json (p_s_ref) LOOP
    vs_student_json:=x.student_json;
    EXIT;
  END LOOP;

  -- Determine student type
  vs_student_type:=get_student_type(p_s_ref);

  -- Collect list of elements not required, based on student type
  FOR x IN cur_json_inorout(vs_student_type) LOOP
     -- Remove element from the json
     vs_student_json:=json_remove(vs_student_json,x.attribute);
  END LOOP;
END;
/

Question:
There must be an elegant method to achieve requirement

Body:
Classify under RTFM. Needs Oracle 12.2

DECLARE

  -- Declare an object of type JSON_OBJECT_T
  l_obj JSON_OBJECT_T;

  -- Declare cursor to build json object
  CURSOR cur_student_json (p_s_ref IN VARCHAR2) IS
  SELECT  JSON_OBJECT(
      ,'s_surname'                     value s.s_surname
      ,'s_forename_1'                  value s.s_forename_1
      ,'s_home_address_1'              value s.s_home_address_1
    ) student_json
    FROM   students  s
   WHERE  s.s_ref = p_s_ref;

BEGIN

  -- Initialise object
  l_obj := JSON_OBJECT_T();

  -- Populate the object
  FOR x IN cur_student_json (p_s_ref) LOOP
    l_obj:=JSON_OBJECT_T.parse(x.student_json);
    EXIT;
  END LOOP;

  -- Determine student type
  vs_student_type:=get_student_type(p_s_ref);

  -- Collect list of elements not required, based on student type
  FOR x IN cur_json_inorout(vs_student_type) LOOP
    -- Remove element from the json
    l_obj.remove(x.attribute);
  END LOOP;

  -- Display modified object
  dbms_output.put_line(l_obj.stringify);
END;
/


问:
Replace a parameter in an expression with a constant
I have an expression of type Expression<Func<TElement, TElement, bool>> and a constant of type TElement. I need an expression of type Expression<Func<TElement, bool>> with one of the parameters replaced by the constant. In other words, I need the body to the following method:

```<code>public static Expression<Func<TElement, bool>> ReplaceParameter<TElement>
(
    Expression<Func<TElement, TElement, bool>> inputExpression,
    TElement element
)
{
    ...
}
</code>```

If I call ReplaceParameter((i1, i2) => i1 > i2, 5), I expect the result to be i => i > 5.

I was thinking, it might be able to recursively deconstruct and then reconstruct the input expression and replace all occurrences of the second parameter with a constant expression. Since there are so many different kind of expressions, I'm unsure on how to do that, though.

答:
ExpressionVisitor is your friend:

static void Main()
{
    Expression<Func<int, int, bool>> before = (x, y) => x * 2 == y + 1;
    var after = ReplaceParameter(before, 3);
    Console.WriteLine(after);
}
public static Expression<Func<TElement, bool>> ReplaceParameter<TElement>
(
    Expression<Func<TElement, TElement, bool>> inputExpression,
    TElement element
)
{
    var replacer = new Replacer(inputExpression.Parameters[0],
        Expression.Constant(element, typeof(TElement)));
    var body = replacer.Visit(inputExpression.Body);
    return Expression.Lambda<Func<TElement, bool>>(body,
        inputExpression.Parameters[1]);
}
class Replacer : ExpressionVisitor
{
    private readonly Expression _from, _to;
    public Replacer(Expression from, Expression to)
    {
        _from = from;
        _to = to;
    }
    public override Expression Visit(Expression node)
        => node == _from ? _to : base.Visit(node);
}
```

<p>Note that this does not automatically collapse pure constant expressions, i.e. the code shown results in:</p>

<pre class="lang-cs prettyprint-override"><code>y => ((3 * 2) == (y + 1))
</code>```

You could however, if you wanted, try looking for BinaryExpression that only has ConstantExpression as inputs, and evaluate the node directly, again inside Replacer.

Body:
I have an expression of type Expression<Func<TElement, TElement, bool>> and a constant of type TElement. I need an expression of type Expression<Func<TElement, bool>> with one of the parameters replaced by the constant. In other words, I need the body to the following method:

public static Expression<Func<TElement, bool>> ReplaceParameter<TElement>
(
    Expression<Func<TElement, TElement, bool>> inputExpression,
    TElement element
)
{
    ...
}

If I call ReplaceParameter((i1, i2) => i1 > i2, 5), I expect the result to be i => i > 5.

I was thinking, it might be able to recursively deconstruct and then reconstruct the input expression and replace all occurrences of the second parameter with a constant expression. Since there are so many different kind of expressions, I'm unsure on how to do that, though.

Body:
ExpressionVisitor is your friend:

static void Main()
{
    Expression<Func<int, int, bool>> before = (x, y) => x * 2 == y + 1;
    var after = ReplaceParameter(before, 3);
    Console.WriteLine(after);
}
public static Expression<Func<TElement, bool>> ReplaceParameter<TElement>
(
    Expression<Func<TElement, TElement, bool>> inputExpression,
    TElement element
)
{
    var replacer = new Replacer(inputExpression.Parameters[0],
        Expression.Constant(element, typeof(TElement)));
    var body = replacer.Visit(inputExpression.Body);
    return Expression.Lambda<Func<TElement, bool>>(body,
        inputExpression.Parameters[1]);
}
class Replacer : ExpressionVisitor
{
    private readonly Expression _from, _to;
    public Replacer(Expression from, Expression to)
    {
        _from = from;
        _to = to;
    }
    public override Expression Visit(Expression node)
        => node == _from ? _to : base.Visit(node);
}

Note that this does not automatically collapse pure constant expressions, i.e. the code shown results in:

y => ((3 * 2) == (y + 1))

You could however, if you wanted, try looking for BinaryExpression that only has ConstantExpression as inputs, and evaluate the node directly, again inside Replacer.


问:
How to merge 2 list of objects into 1 with a comparison expression in Automapper
I need to merge 2 lists of objects into 1 taking some properties from objects in list 1 and some properties from the objects in list 2 using a comparison expression using Automapper

I've tried Automapper.Collection (https://github.com/AutoMapper/AutoMapper.Collection) nuget but the default actions are:

If ID's match will map 1 to 2

If 2 exists and 1 doesn't add to the collection

If 1 exists and 2 doesn't remove from the collection

but I only want to map if there is a match, if not I want to ignore the record

public class Class1
        {
            public string Id { get; set; }
            public string Code { get; set; }
        }

        public class Class2
        {
            public string Id { get; set; }
            public string Description { get; set; }
        }

        public class Class3
        {
            public string NewId { get; set; }
            public string NewCode { get; set; }
            public string NewDescription { get; set; }
        }

var configuration = new MapperConfiguration(cfg =>
            {
                cfg.CreateMap<Class1, Class3>()
                    .ForMember(dest => dest.NewId, opt => opt.MapFrom(src => src.Id))
                    .ForMember(dest => dest.NewCode, opt => opt.MapFrom(src => src.Code))
                    ;
                cfg.CreateMap<Class2, Class3>()
                    .ForMember(dest => dest.NewDescription, opt => opt.MapFrom(src => src.Description))
                    ;
            });
            var mapper = configuration.CreateMapper();

            var class1List = new List<Class1>
            {
                new Class1 {Id = "1", Code = "code1"},
                new Class1 { Id = "2", Code = "code2" },
                new Class1 {Id = "3", Code = "code3"}
            };

            var class2List = new List<Class2>
            {
                new Class2 {Id = "2", Description = "desc2"}
            };

 var class3List = mapper.Map<List<Class3>>(class1List);
            mapper.Map(class2List, class3List);
```

I want that "class3List" at the end contains 3 elements, the element with id "2" must have both code and description.

答:
Automapper might not be the right tool for the task.
Instead of Automapper, you may use a simple LINQ Join statement:</p>

```<code>var class3List = class1List.Join(class2List, o => o.Id, i => i.Id, (o, i) => new Class3 { NewId = o.Id, NewCode = o.Code, NewDescription = i.Description }).ToList();
</code>```

Body:
I need to merge 2 lists of objects into 1 taking some properties from objects in list 1 and some properties from the objects in list 2 using a comparison expression using Automapper

I've tried Automapper.Collection (https://github.com/AutoMapper/AutoMapper.Collection) nuget but the default actions are:

If ID's match will map 1 to 2

If 2 exists and 1 doesn't add to the collection

If 1 exists and 2 doesn't remove from the collection

but I only want to map if there is a match, if not I want to ignore the record

public class Class1
        {
            public string Id { get; set; }
            public string Code { get; set; }
        }

        public class Class2
        {
            public string Id { get; set; }
            public string Description { get; set; }
        }

        public class Class3
        {
            public string NewId { get; set; }
            public string NewCode { get; set; }
            public string NewDescription { get; set; }
        }

var configuration = new MapperConfiguration(cfg =>
            {
                cfg.CreateMap<Class1, Class3>()
                    .ForMember(dest => dest.NewId, opt => opt.MapFrom(src => src.Id))
                    .ForMember(dest => dest.NewCode, opt => opt.MapFrom(src => src.Code))
                    ;
                cfg.CreateMap<Class2, Class3>()
                    .ForMember(dest => dest.NewDescription, opt => opt.MapFrom(src => src.Description))
                    ;
            });
            var mapper = configuration.CreateMapper();

            var class1List = new List<Class1>
            {
                new Class1 {Id = "1", Code = "code1"},
                new Class1 { Id = "2", Code = "code2" },
                new Class1 {Id = "3", Code = "code3"}
            };

            var class2List = new List<Class2>
            {
                new Class2 {Id = "2", Description = "desc2"}
            };

 var class3List = mapper.Map<List<Class3>>(class1List);
            mapper.Map(class2List, class3List);

I want that "class3List" at the end contains 3 elements, the element with id "2" must have both code and description.

Body:
Automapper might not be the right tool for the task.
Instead of Automapper, you may use a simple LINQ Join statement:

var class3List = class1List.Join(class2List, o => o.Id, i => i.Id, (o, i) => new Class3 { NewId = o.Id, NewCode = o.Code, NewDescription = i.Description }).ToList();


问:
Change id of multiple dynamic fields
I have a form with dynamic fields but I would like the additional fields to have a different ID.

My code works pretty well but as it is a simple copy of HTML code, there is no reference of any ID. I am a totally beginner in Javascript, and I don't know how to achieve that.

$(".addMore").click(function() {
  if ($('body').find('.field').length <= 10) {
    var fieldHTML = '
' + $(".fieldCopy").html() + '
';
    $('body').find('.field:last').after(fieldHTML);
  }
});

// Remove
$("body").on("click", ".remove", function() {
  $(this).parents(".field").remove();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post" action="">
  <div class="form-group field">
    <div class="input-group">
      <input id="name" type="text" name="name[]" class="form-control" />
      <input id="email" type="text" name="email[]" class="form-control" />
      <div class="input-group-addon">
        Add
      </div>
    </div>
  </div>
  <input type="submit" name="submit" class="btn btn-primary" value="Submit" />
</form>

<!-- copy of input fields group -->
<div class="form-group fieldCopy" style="display: none;">
  <div class="input-group">
    <input id="name" type="text" name="name[]" class="form-control" />
    <input id="email" type="text" name="email[]" class="form-control" />
    <div class="input-group-addon">
      Remove
    </div>
  </div>
</div></code>```

答:
You can set it like this:</p>

```<code>var i = 0;
    $(".addMore").click(function() {
      if ($('body').find('.field').length <= 10) {
        var fieldHTML = '<div class="form-group field">' + $(".fieldCopy").html() + '</div>';
        $('body').find('.field:last').after(fieldHTML);
           $('body').find('.field:last').attr("id",i);
        i++
      }
    });
</code>```

Title: Change id of multiple dynamic fields

Body:
I have a form with dynamic fields but I would like the additional fields to have a different ID.

My code works pretty well but as it is a simple copy of HTML code, there is no reference of any ID. I am a totally beginner in Javascript, and I don't know how to achieve that.

$(".addMore").click(function() {
  if ($('body').find('.field').length <= 10) {
    var fieldHTML = '
' + $(".fieldCopy").html() + '
';
    $('body').find('.field:last').after(fieldHTML);
  }
});

// Remove
$("body").on("click", ".remove", function() {
  $(this).parents(".field").remove();
});

<form method="post" action="">

      <input id="name" type="text" name="name[]" class="form-control" />
      <input id="email" type="text" name="email[]" class="form-control" />

        Add

  <input type="submit" name="submit" class="btn btn-primary" value="Submit" />
</form>

    <input id="name" type="text" name="name[]" class="form-control" />
    <input id="email" type="text" name="email[]" class="form-control" />

      Remove

Body:
You can set it like this:

var i = 0;
    $(".addMore").click(function() {
      if ($('body').find('.field').length <= 10) {
        var fieldHTML = '<div class="form-group field">' + $(".fieldCopy").html() + '</div>';
        $('body').find('.field:last').after(fieldHTML);
           $('body').find('.field:last').attr("id",i);
        i++
      }
    });


问:
extract values from list with the help of another list with condition in python
Extract items from the list with comes in between another list items

```<code>a = [4,8]
b = [1,2,3,4,5,6,7,8,9,0]
</code>```

I want to extract values from b list which comes in between 4 and 8 values of list a ?

Result should be

```<code>b = [5,6,7]
</code>```

答:
You can use inbuilt filter() method.

a = [4, 8]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]

# If you aren't sure that items in a is in correct order then use min max
c = list(filter(lambda x: min(a) < x < max(a), b))
```

<p>Or use list comprehension:</p>

<pre class="lang-py prettyprint-override"><code>c = [x for x in b if min(a) < x < max(a)]
</code>```

Body:
Extract items from the list with comes in between another list items

a = [4,8]
b = [1,2,3,4,5,6,7,8,9,0]

I want to extract values from b list which comes in between 4 and 8 values of list a ?

Result should be

b = [5,6,7]

Body:
You can use inbuilt filter() method.

a = [4, 8]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]

# If you aren't sure that items in a is in correct order then use min max
c = list(filter(lambda x: min(a) < x < max(a), b))

Or use list comprehension:

c = [x for x in b if min(a) < x < max(a)]


问:
Scatter Plot with Mirrored X-Axis
I am using RGraph version 5.00, trying to make a scatter plot that looks like this,

https://i.stack.imgur.com/lsPB8.png

This is my best effort, thus far,

https://i.stack.imgur.com/LKIYH.png

How can I move the Y-Axis from the left-hand side to the center of the plot?

I've tried setting the 'xaxisScaleMin' option to 'mirror', but that doesn't work. Here is my code,

```<code>            new RGraph.SVG.Scatter({
            id: 'chart-container',
            data: [],
            options: {
                backgroundGridHlinesCount: 10,
                backgroundGridVlinesCount: 10,
                colors: ['cyan', 'magenta', '#cc0', 'black', 'red', 'green', 'blue', 'brown'],
                linewidth: 3,
                gutterLeft: 50,
                gutterBottom: 50,
                xaxisLinewidth: 1.5,
                xaxisScale: true,
                xaxisScaleMax: 125,
                xaxisScaleMin: -125,
                yaxisLabelsCount: 10,
                yaxisLinewidth: 1.5,
                yaxisScale: true,
                yaxisScaleMax: 125,
                yaxisScaleMin: -125,
                title: 'solid ink colors'
            }
        }).draw();
</code>```

2019-05-29:
Looking at the source, RGraph.svg.common.core.js, there is no way to place the Y-axis at the origin, as with the X-axis. Placing the Y-axis on the origin, when it is in the range of the graph, seems like a proper default behavior, or should at least be a simple option. I will try changing the source.

答:
One of the examples in the download does just this:

```<code>demos/scatter-negative-x-axis.html
</code>```

The trick is to add a large left margin and then use the drawing API X axis to add the extra axis (the left-hand-side X axis).

(incidentally - the lines that are shown on the chart are just trigonometry curves - sin/cos/tan)

You can get the RGraph download here:

https://www.rgraph.net/download.html#stable

Title: Scatter Plot with Mirrored X-Axis

Body:
I am using RGraph version 5.00, trying to make a scatter plot that looks like this,

https://i.stack.imgur.com/lsPB8.png

This is my best effort, thus far,

https://i.stack.imgur.com/LKIYH.png

How can I move the Y-Axis from the left-hand side to the center of the plot?

I've tried setting the 'xaxisScaleMin' option to 'mirror', but that doesn't work. Here is my code,

            new RGraph.SVG.Scatter({
            id: 'chart-container',
            data: [],
            options: {
                backgroundGridHlinesCount: 10,
                backgroundGridVlinesCount: 10,
                colors: ['cyan', 'magenta', '#cc0', 'black', 'red', 'green', 'blue', 'brown'],
                linewidth: 3,
                gutterLeft: 50,
                gutterBottom: 50,
                xaxisLinewidth: 1.5,
                xaxisScale: true,
                xaxisScaleMax: 125,
                xaxisScaleMin: -125,
                yaxisLabelsCount: 10,
                yaxisLinewidth: 1.5,
                yaxisScale: true,
                yaxisScaleMax: 125,
                yaxisScaleMin: -125,
                title: 'solid ink colors'
            }
        }).draw();

2019-05-29:
Looking at the source, RGraph.svg.common.core.js, there is no way to place the Y-axis at the origin, as with the X-axis. Placing the Y-axis on the origin, when it is in the range of the graph, seems like a proper default behavior, or should at least be a simple option. I will try changing the source.

Body:
One of the examples in the download does just this:

demos/scatter-negative-x-axis.html

The trick is to add a large left margin and then use the drawing API X axis to add the extra axis (the left-hand-side X axis).

(incidentally - the lines that are shown on the chart are just trigonometry curves - sin/cos/tan)

You can get the RGraph download here:

https://www.rgraph.net/download.html#stable


问:
What is the most impressive Lisp application?
I know that this is subjective and all, but still, can you provide some list of serious applications that were written in Lisp (perhaps along with what Lisp it is)?</p>

答:
Lisp Machines were used by NASA to check Space Shuttle starts. From a Symbolics press release from 1990:

"Recently the National Aeronautical and Space Administration (NASA) used Symbolics'
high-definition technology to analyze HDTV video images of the
Discovery launch in real-time.  This high-definition system enabled
NASA engineers to get an instant replay of critical launch systems.
The engineers were able to enhance and enlarge high-resolution images
of the lift-off in order to analyze the condition of and spot
potential problems with space shuttle tiles."

They used a bunch of Lisp Machines with special image processing boards.

OwnerDisplayName: Bartosz Radaczyński

LastEditorDisplayName: starblue

OwnerDisplayName: foo

ContentLicense: CC BY-SA 2.5


问:
how to install Google Cloud Tools for visual studio ion Visual Studio 2019 Community?
I am trying to install Google Cloud Tools for Visual Studio 2019 through Online Extension, it does not show up in the search results

I tried installing the extension manually, still can't install it, I have multiple version of Visual Studio installed one of which is VS 2015, which is not supported. So I am getting this error

```<code>28-05-2019 09:51:15 - VSIXInstaller.NoApplicableSKUsException: This extension is not installable on any currently installed products.
   at VSIXInstaller.ExtensionService.GetInstallableData(String vsixPath, String extensionPackParentName, Boolean isRepairSupported, IStateData stateData, IEnumerable`1& skuData)
   at VSIXInstaller.ExtensionPackService.IsExtensionPack(IStateData stateData, Boolean isRepairSupported)
   at VSIXInstaller.ExtensionPackService.ExpandExtensionPackToInstall(IStateData stateData, Boolean isRepairSupported)
   at VSIXInstaller.App.Initialize(Boolean isRepairSupported)
   at VSIXInstaller.App.Initialize()
   at System.Threading.Tasks.Task`1.InnerInvoke()
   at System.Threading.Tasks.Task.Execute()
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.VisualStudio.Telemetry.WindowsErrorReporting.WatsonReport.GetClrWatsonExceptionInfo(Exception exceptionObject)
</code>```

According to the documentation prerequisite is VS2017, is it only available for VS 2017?

答:
Based on searching the Visual Studio marketplace (https://marketplace.visualstudio.com/publishers/GoogleCloudTools) it appears this extension is only available for 2017.

Maybe there is an update in development, but you'll need a way to contact to authors to confirm this.

While some extensions can be loaded into 2019 by unzipping the VSIX file, modifying the manifest and re-zipping, there is no guarantee this will work at all (let alone not lead to crashes or other more subtle errors).

The 2017 version pages does link to https://github.com/GoogleCloudPlatform/google-cloud-visualstudio and that shows an open source licence, so maybe you could make changes yourself and push a PR?

Body:
I am trying to install Google Cloud Tools for Visual Studio 2019 through Online Extension, it does not show up in the search results

I tried installing the extension manually, still can't install it, I have multiple version of Visual Studio installed one of which is VS 2015, which is not supported. So I am getting this error

28-05-2019 09:51:15 - VSIXInstaller.NoApplicableSKUsException: This extension is not installable on any currently installed products.
   at VSIXInstaller.ExtensionService.GetInstallableData(String vsixPath, String extensionPackParentName, Boolean isRepairSupported, IStateData stateData, IEnumerable`1& skuData)
   at VSIXInstaller.ExtensionPackService.IsExtensionPack(IStateData stateData, Boolean isRepairSupported)
   at VSIXInstaller.ExtensionPackService.ExpandExtensionPackToInstall(IStateData stateData, Boolean isRepairSupported)
   at VSIXInstaller.App.Initialize(Boolean isRepairSupported)
   at VSIXInstaller.App.Initialize()
   at System.Threading.Tasks.Task`1.InnerInvoke()
   at System.Threading.Tasks.Task.Execute()
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.VisualStudio.Telemetry.WindowsErrorReporting.WatsonReport.GetClrWatsonExceptionInfo(Exception exceptionObject)

According to the documentation prerequisite is VS2017, is it only available for VS 2017?


问:
How to prevent LastPass (chrome extension) from auto-filling input field
I want to prevent LastPass from filling out an input field on my site. I'm using AngularJS and HTML5, and the extension is autofilling the following input field. This field is a search field inside my page; it's not a login page.

```<code><input id="search-publishers-box" type="text" placeholder="Search Publishers" data-ng-model="publishersSearchQuery.name" class="search-field-text" autocomplete="off"/>
</code>```

What can I do to prevent LastPass from doing its autofill? I've tried to change the placeholder, the model, adding autocomplete="off", and changed the id of the input field.

None have worked at all for me.

答:
For me, the previous answer from @nawlbergs helped to solve the issue. The data-lpignore="true" isn't helping anymore (probably they've updated their logic as this solution is no more present in their FAQs as well).

LastPass seems to only work with the inputs with type="text" and type="password" to fill the passwords (these are the only input types one can configure in the form fields in LastPass entries). Whenever you're using some other type that's valid (unlike @nawlbergs suggested) but isn't a "text".

That said, the type="search" helps, as well as the rest of the possible valid type values. It's just that the type="search" has the same text-like behaviour and can be used freely anywhere:
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/search

Body:
I want to prevent LastPass from filling out an input field on my site. I'm using AngularJS and HTML5, and the extension is autofilling the following input field. This field is a search field inside my page; it's not a login page.

<input id="search-publishers-box" type="text" placeholder="Search Publishers" data-ng-model="publishersSearchQuery.name" class="search-field-text" autocomplete="off"/>

What can I do to prevent LastPass from doing its autofill? I've tried to change the placeholder, the model, adding autocomplete="off", and changed the id of the input field.

None have worked at all for me.


问:
ARM7 ViSUAL Emulator and Keil uVision4
There are two questions about  ARM7 ViSUAL EMulator and Keil uVision4.

Run this on the ARM7 ViSUAL Emulator and explain what it does.

Consider how the variables Value1, Value2, Value3 and Result have been declared. Explain why this would not compile using Keil uVision4.

I have run the code but I still don't understand what it does.

```<code> Main
  LDR r1, =Value1
  LDR R2, =Value2
  LDR r1,[r1]
  LDR r2,[r2]
Return
  ANDS R3, R1,R2
  BNE SEND
  BEQ NEXT
  END
SEND
  LDR r4, =Result
  LDR r4,[r4]
  STR r3, [r4]
  END
NEXT
   MOV R1, R2
   LDR R2, =Value3
   LDR R2, [r2]
   B       Return
   END
 Value1 DCD &0202
 Value2 DCD  &0101
 Value3 DCD &0001
 Result DCD  &FFFFFFF0
</code>```

答:
The memory allocations (DCD) are done in the same area as the code declaration. Which means that it probably will be used as if AREA PROGRAM, CODE, READONLY was set and as such keil won't assemble it. It also means that if it was assembled the data locations will be READONLY. A proper declaration of variables would be preceded by AREA section name>, DATA, READWRITE

```<code> Main
  LDR R1, =Value1 -- load Value1 inside R1
  LDR R2, =Value2 -- load Value2 inside R2
  LDR R1,[R1]  -- load indirect the address pointed to by the value of R1 to R1 -- (I have reservations about the functionality of this code)
  LDR R2,[R2]  -- load indirect the address pointed to by the value of R2 to R2 -- (I have reservations about the functionality of this code)
Return
  ANDS R3, R1,R2 -- R3 = R1 AND R2
  BNE SEND -- branch if not equal to SEND label
  BEQ NEXT -- branch to NEXT if equal
  END
SEND
  LDR R4, =Result -- load Result to R4
  LDR R4,[R4]  -- load indirect the address pointed to by the value of R4 to R4 -- (I have reservations about the functionality of this code)
  STR R3, [R4] -- store indirect to address pointed to by the value of R4 with the value of R3
  END
NEXT
   MOV R1, R2  -- copy R2 to R1
   LDR R2, =Value3  -- load Value3 to R2
   LDR R2, [R2] -- load indirect the address pointed to by the value of R2 to R2 -- (I have reservations about the functionality of this code)
   B       Return -- unconditional branch to Return label
   END
 Value1 DCD &0202  -- word allocation with hex value of
 Value2 DCD &0101  -- word allocation with hex value of
 Value3 DCD &0001  -- word allocation with hex value of
 Result DCD &FFFFFFF0 -- word allocation with hex value of
</code>```

This code tries to save the fact that r2 and r1 are equal or an infinite loop will occur because of the static nature of the values saved inside Value<1-3>

Title: ARM7 ViSUAL Emulator and Keil uVision4

Body:
There are two questions about  ARM7 ViSUAL EMulator and Keil uVision4.

Run this on the ARM7 ViSUAL Emulator and explain what it does.

Consider how the variables Value1, Value2, Value3 and Result have been declared. Explain why this would not compile using Keil uVision4.

I have run the code but I still don't understand what it does.

 Main
  LDR r1, =Value1
  LDR R2, =Value2
  LDR r1,[r1]
  LDR r2,[r2]
Return
  ANDS R3, R1,R2
  BNE SEND
  BEQ NEXT
  END
SEND
  LDR r4, =Result
  LDR r4,[r4]
  STR r3, [r4]
  END
NEXT
   MOV R1, R2
   LDR R2, =Value3
   LDR R2, [r2]
   B       Return
   END
 Value1 DCD &0202
 Value2 DCD  &0101
 Value3 DCD &0001
 Result DCD  &FFFFFFF0

Body:
The memory allocations (DCD) are done in the same area as the code declaration. Which means that it probably will be used as if AREA PROGRAM, CODE, READONLY was set and as such keil won't assemble it. It also means that if it was assembled the data locations will be READONLY. A proper declaration of variables would be preceded by AREA <a section name>, DATA, READWRITE

 Main
  LDR R1, =Value1 -- load Value1 inside R1
  LDR R2, =Value2 -- load Value2 inside R2
  LDR R1,[R1]  -- load indirect the address pointed to by the value of R1 to R1 -- (I have reservations about the functionality of this code)
  LDR R2,[R2]  -- load indirect the address pointed to by the value of R2 to R2 -- (I have reservations about the functionality of this code)
Return
  ANDS R3, R1,R2 -- R3 = R1 AND R2
  BNE SEND -- branch if not equal to SEND label
  BEQ NEXT -- branch to NEXT if equal
  END
SEND
  LDR R4, =Result -- load Result to R4
  LDR R4,[R4]  -- load indirect the address pointed to by the value of R4 to R4 -- (I have reservations about the functionality of this code)
  STR R3, [R4] -- store indirect to address pointed to by the value of R4 with the value of R3
  END
NEXT
   MOV R1, R2  -- copy R2 to R1
   LDR R2, =Value3  -- load Value3 to R2
   LDR R2, [R2] -- load indirect the address pointed to by the value of R2 to R2 -- (I have reservations about the functionality of this code)
   B       Return -- unconditional branch to Return label
   END
 Value1 DCD &0202  -- word allocation with hex value of
 Value2 DCD &0101  -- word allocation with hex value of
 Value3 DCD &0001  -- word allocation with hex value of
 Result DCD &FFFFFFF0 -- word allocation with hex value of

This code tries to save the fact that r2 and r1 are equal or an infinite loop will occur because of the static nature of the values saved inside Value<1-3>


问:
Search element in array based on another array and change property
I have two array of objects like this:

```<code>const officers: any[] = [
  { id: 20, name: 'Captain Piett' },
  { id: 24, name: 'General Veers' },
  { id: 56, name: 'Admiral Ozzel' },
  { id: 88, name: 'Commander Jerjerrod' }
];

const searchAndChangeFor: any[] = [
  { id: 56, name: 'New Name', additionalData: 1 },
];
</code>```

I want to find elements from searchAndChangeFor in officers and modify content. Usually If I have one element I do this:

```<code>officers.map((item) => {
    // I want to modify id: 56 and update officers here.
    item.id === 56 ? { ...item, name: 'Change name for 56' } : item
});
</code>```

But I need to search by array not single element so I've tried this but not succeeded:

```<code>officers.map((item) => {
   searchAndChangeFor.find((item2) => {
       item.id === item2.id? { ...item, name: 'Change name for 56' } : item
   });
});
</code>```

Expected Output:

```<code>  { id: 20, name: 'Captain Piett' },
  { id: 24, name: 'General Veers' },
  { id: 56, name: 'New Name', additionalData: 1 },
  { id: 88, name: 'Commander Jerjerrod' }
</code>```

It goes crazy with array. How can I find elements in officers based on searchAndChangeFor and change its name? I also want to keep all other existing items in officers.

答:
find is expecting a boolean response, when it receives true it returns the item that true was returned for, you are attempting to mutate the item directly in the find callback body. This isn't what you need to do, you want to just change the value where the id exists in your searchAndChangeFor for array.

```<code>const ids = searchAndChangeFor.map((rel) => rel.id);
const changed = officers.map((item) => ids.includes(item.id) ?
    {{ Item mutation logic here }} :
    item);
</code>```

Body:
I have two array of objects like this:

const officers: any[] = [
  { id: 20, name: 'Captain Piett' },
  { id: 24, name: 'General Veers' },
  { id: 56, name: 'Admiral Ozzel' },
  { id: 88, name: 'Commander Jerjerrod' }
];

const searchAndChangeFor: any[] = [
  { id: 56, name: 'New Name', additionalData: 1 },
];

I want to find elements from searchAndChangeFor in officers and modify content. Usually If I have one element I do this:

officers.map((item) => {
    // I want to modify id: 56 and update officers here.
    item.id === 56 ? { ...item, name: 'Change name for 56' } : item
});

But I need to search by array not single element so I've tried this but not succeeded:

officers.map((item) => {
   searchAndChangeFor.find((item2) => {
       item.id === item2.id? { ...item, name: 'Change name for 56' } : item
   });
});

Expected Output:

  { id: 20, name: 'Captain Piett' },
  { id: 24, name: 'General Veers' },
  { id: 56, name: 'New Name', additionalData: 1 },
  { id: 88, name: 'Commander Jerjerrod' }

It goes crazy with array. How can I find elements in officers based on searchAndChangeFor and change its name? I also want to keep all other existing items in officers.

Body:
find is expecting a boolean response, when it receives true it returns the item that true was returned for, you are attempting to mutate the item directly in the find callback body. This isn't what you need to do, you want to just change the value where the id exists in your searchAndChangeFor for array.

const ids = searchAndChangeFor.map((rel) => rel.id);
const changed = officers.map((item) => ids.includes(item.id) ?
    {{ Item mutation logic here }} :
    item);


问:
How to Get in between button tag text value in IFormCollection?
I have a search form on view that displays check boxes as a list which may be selected multi, on each item check, value comes in between button tags.

In Controller Action IFormCollection provides various key value but not that button which tags contain results, it always returns null

```<code><button type="button" data-toggle="dropdown" name="State" data-placeholder="---" class="dropdown-toggle js-select-checkboxes-btn">---</button>
                                        <div class="dropdown-menu js-dropdown-menu js-select-checkboxes">
                                            <ul>
                                                <li>
                                                    <input id="checkbox_type_1" type="checkbox" name="checkbox_type_1" class="in-checkbox">
                                                    <label for="checkbox_type_1" data-toggle="tooltip" data-placement="left" title="Tooltip on top" class="in-label">Punjab</label>
                                                </li>
                                                <li>
                                                    <input id="checkbox_type_2" type="checkbox" name="checkbox_type_2" class="in-checkbox">
                                                    <label for="checkbox_type_2" data-toggle="tooltip" data-placement="top" title="Tooltip on top" class="in-label">Sindh</label>
                                                </li>
                                                <li>
                                                    <input id="checkbox_type_3" type="checkbox" name="checkbox_type_3" class="in-checkbox">
                                                    <label for="checkbox_type_3" data-toggle="tooltip" data-placement="bottom" title="Tooltip on top" class="in-label">Balochistan</label>
                                                </li>
                                                <li>
                                                    <input id="checkbox_type_4" type="checkbox" name="checkbox_type_4" class="in-checkbox">
                                                    <label for="checkbox_type_4" data-toggle="tooltip" data-placement="bottom" title="Tooltip on top" class="in-label">Khaybar Pakhtonkhwa</label>
                                                </li>
                                                <li>
                                                    <input id="checkbox_type_5" type="checkbox" name="checkbox_type_5" class="in-checkbox">
                                                    <label for="checkbox_type_5" data-toggle="tooltip" data-placement="bottom" title="Tooltip on top" class="in-label">Azad Kashmir</label>
                                                </li>
                                                <li>
                                                    <input id="checkbox_type_6" type="checkbox" name="checkbox_type_6" class="in-checkbox">
                                                    <label for="checkbox_type_6" data-toggle="tooltip" data-placement="bottom" title="Tooltip on top" class="in-label">Gilgit Baltistan</label>
                                                </li>
                                            </ul>
                                            <!-- end of block .dropdown-menu-->
                                        </div>
</code>```

In Page Source:

```<code><button type="button" data-toggle="dropdown" data-placeholder="---" class="dropdown-toggle js-select-checkboxes-btn" aria-expanded="true">Punjab, Sindh, Balochistan</button>
</code>```

In Controller Action Result:

```<code>public IActionResult SearchPerson(IFormCollection formCollection)
    {
        string txtState = formCollection["State"]; << Null}
</code>```

I Expect the output as string i.e. in between tags

答:
You could not get the text value of <button> in IFormCollection.

For a workaround, you could add a hidden input in the form and pass the selected values to it when you click.Then you could get the value of the input in IFormCollection when you submit.

```<code><input type="hidden" id="States" name="States" />
<button type="button" data-toggle="dropdown" data-placeholder="---" class="dropdown-toggle js-select-checkboxes-btn" aria-expanded="true">---</button>
</code>```

JS code:

```<code>@section Scripts{
<script>
    $(document).ready(function () {
        $(".dropdown-menu input[type=checkbox]").each(function () {
            $(this).change(function () {
                var line = "";
                $(".dropdown-menu input[type=checkbox]").each(function () {
                    if ($(this).is(":checked")) {
                        line += $("+ label", this).text() + ",";
                    }
                });
                $("#States").val(line);
                $("button.dropdown-toggle").text(line);
            });
        });
    });
</script>
</code>```

Controller:

```<code>[HttpPost]
public IActionResult SearchPerson(IFormCollection formCollection)
{
   string txtState = formCollection["States"];
</code>```

Body:
I have a search form on view that displays check boxes as a list which may be selected multi, on each item check, value comes in between button tags.

In Controller Action IFormCollection provides various key value but not that button which tags contain results, it always returns null

<button type="button" data-toggle="dropdown" name="State" data-placeholder="---" class="dropdown-toggle js-select-checkboxes-btn">---</button>

                                                    <input id="checkbox_type_1" type="checkbox" name="checkbox_type_1" class="in-checkbox">
                                                    Punjab

                                                    <input id="checkbox_type_2" type="checkbox" name="checkbox_type_2" class="in-checkbox">
                                                    Sindh

                                                    <input id="checkbox_type_3" type="checkbox" name="checkbox_type_3" class="in-checkbox">
                                                    Balochistan

                                                    <input id="checkbox_type_4" type="checkbox" name="checkbox_type_4" class="in-checkbox">
                                                    Khaybar Pakhtonkhwa

                                                    <input id="checkbox_type_5" type="checkbox" name="checkbox_type_5" class="in-checkbox">
                                                    Azad Kashmir

                                                    <input id="checkbox_type_6" type="checkbox" name="checkbox_type_6" class="in-checkbox">
                                                    Gilgit Baltistan

In Page Source:

<button type="button" data-toggle="dropdown" data-placeholder="---" class="dropdown-toggle js-select-checkboxes-btn" aria-expanded="true">Punjab, Sindh, Balochistan</button>

In Controller Action Result:

public IActionResult SearchPerson(IFormCollection formCollection)
    {
        string txtState = formCollection["State"]; << Null}

I Expect the output as string i.e. in between tags

Body:
You could not get the text value of <button> in IFormCollection.

For a workaround, you could add a hidden input in the form and pass the selected values to it when you click.Then you could get the value of the input in IFormCollection when you submit.

<input type="hidden" id="States" name="States" />
<button type="button" data-toggle="dropdown" data-placeholder="---" class="dropdown-toggle js-select-checkboxes-btn" aria-expanded="true">---</button>

JS code:

@section Scripts{
<script>
    $(document).ready(function () {
        $(".dropdown-menu input[type=checkbox]").each(function () {
            $(this).change(function () {
                var line = "";
                $(".dropdown-menu input[type=checkbox]").each(function () {
                    if ($(this).is(":checked")) {
                        line += $("+ label", this).text() + ",";
                    }
                });
                $("#States").val(line);
                $("button.dropdown-toggle").text(line);
            });
        });
    });
</script>

Controller:

[HttpPost]
public IActionResult SearchPerson(IFormCollection formCollection)
{
   string txtState = formCollection["States"];


问:
How to iterate over a JavaScript object?
I have an object in JavaScript:

```<code>{
    abc: '...',
    bca: '...',
    zzz: '...',
    xxx: '...',
    ccc: '...',
    // ...
}
</code>```

I want to use a for loop to get its properties. And I want to iterate it in parts (not all object properties at once).

With a simple array I can do it with a standard for loop:

```<code>for (i = 0; i < 100; i++) { ... } // first part
for (i = 100; i < 300; i++) { ... } // second
for (i = 300; i < arr.length; i++) { ... } // last
</code>```

But how to do it with objects?

答:
Yes. You can loop through an object using for loop. Here is an example

var myObj = {
    abc: 'ABC',
    bca: 'BCA',
    zzz: 'ZZZ',
    xxx: 'XXX',
    ccc: 'CCC',
}

var k = Object.keys (myObj);
for (var i = 0; i < k.length; i++) {
    console.log (k[i] + ": " + myObj[k[i]]);
}```

NOTE: the example mentioned above will only work in IE9+. See Objec.keys browser support here.

Body:
I have an object in JavaScript:

{
    abc: '...',
    bca: '...',
    zzz: '...',
    xxx: '...',
    ccc: '...',
    // ...
}

I want to use a for loop to get its properties. And I want to iterate it in parts (not all object properties at once).

With a simple array I can do it with a standard for loop:

for (i = 0; i < 100; i++) { ... } // first part
for (i = 100; i < 300; i++) { ... } // second
for (i = 300; i < arr.length; i++) { ... } // last

But how to do it with objects?

Body:
Yes. You can loop through an object using for loop. Here is an example

var myObj = {
    abc: 'ABC',
    bca: 'BCA',
    zzz: 'ZZZ',
    xxx: 'XXX',
    ccc: 'CCC',
}

var k = Object.keys (myObj);
for (var i = 0; i < k.length; i++) {
    console.log (k[i] + ": " + myObj[k[i]]);
}

NOTE: the example mentioned above will only work in IE9+. See Objec.keys browser support here.