问:
Force CakePHP plugin to use its own layout
I have written a CakePHP plugin https://github.com/anuj9196/CakePHP-App-Installer

The plugin is using default.ctp layout from plugin_path/src/template/layout/default.ctp

When there is some other theme used in the host application. Like in my case I have setup one in AppController's beforeRender()

```<code>$this->viewBuilder()->setTheme('DashboardTemplate');
</code>```

DashboardTemplate is in application's /plugin/ directory.

Now, when I access my plugin's URL using example.com/installer/install

The template loads on top of DashboardTemplate theme.

How can I disable them in plugin's AppController?

The AppController inside plugin directory contains

```<code><?php
namespace Installer\Controller;

use App\Controller\AppController as BaseController;

class AppController extends BaseController
{
    // nothing here
}
</code>```

答:
Remove the theme by using beforeRender() in your plugin's AppController.

```<code><?php
namespace Installer\Controller;

use App\Controller\AppController as BaseController;

class AppController extends BaseController
{
    /**
     * @param \Cake\Event\Event $event The beforeRender event.
     * @return \Cake\Http\Response|null|void
     */
    public function beforeRender(Event $event)
    {
         try {
             return parent::beforeRender($event);
         } finally {
             $this->viewBuilder()->setTheme(null);
         }
    }
}
</code>```

Body:
I have written a CakePHP plugin https://github.com/anuj9196/CakePHP-App-Installer

The plugin is using default.ctp layout from plugin_path/src/template/layout/default.ctp

When there is some other theme used in the host application. Like in my case I have setup one in AppController's beforeRender()

$this->viewBuilder()->setTheme('DashboardTemplate');

DashboardTemplate is in application's /plugin/ directory.

Now, when I access my plugin's URL using example.com/installer/install

The template loads on top of DashboardTemplate theme.

How can I disable them in plugin's AppController?

The AppController inside plugin directory contains

<?php
namespace Installer\Controller;

use App\Controller\AppController as BaseController;

class AppController extends BaseController
{
    // nothing here
}

Body:
Remove the theme by using beforeRender() in your plugin's AppController.

<?php
namespace Installer\Controller;

use App\Controller\AppController as BaseController;

class AppController extends BaseController
{
    /**
     * @param \Cake\Event\Event $event The beforeRender event.
     * @return \Cake\Http\Response|null|void
     */
    public function beforeRender(Event $event)
    {
         try {
             return parent::beforeRender($event);
         } finally {
             $this->viewBuilder()->setTheme(null);
         }
    }
}


来源: stackexchange

问:
why input type=date is different width to input type=text?
Within the same container input text with display: block stretches to fill available space as expected but if I change type to 'date' it becomes shorter. Why?

HTML:

```<code>  <div class="panel">
    <div class="input-group">
      <label for="text1">text1</label>
      <input id="text1" type="text"/>
    </div>
    <div class="input-group">
      <label for="date">date</label>
      <input id="date" type="date" />
    </div>
    <div class="input-group">
      <label for="text2">text2</label>
      <input id="text2" type="text" />
    </div>
  </div>
</code>```

CSS:

```<code>.panel {
    display: flex;
    flex-wrap: wrap;
}

.input-group {
    flex-grow: 1;
    text-align: left;
}

label, input {
  display: block;
}
</code>```

Result: text1 and text2 are the same size but date is shorter.

https://jsfiddle.net/e0v13ns3/

答:
An input of type text has a size attribute which defaults to 20, and give it an initial width.

An input of type date doesn't, its width is set using CSS, hence their initial width differs.

Note, these preset width's can differ between browsers as well.

Here is a sample where the first input has a size of 10

  <input id="text1" type="text" size="10" />

  <input id="date" type="date" />

  <input id="text2" type="text" />

```

ContentLicense: CC BY-SA 3.0

Body:
Within the same container input text with display: block stretches to fill available space as expected but if I change type to 'date' it becomes shorter. Why?

HTML:

      text1
      <input id="text1" type="text"/>

      date
      <input id="date" type="date" />

      text2
      <input id="text2" type="text" />

CSS:

.panel {
    display: flex;
    flex-wrap: wrap;
}

.input-group {
    flex-grow: 1;
    text-align: left;
}

label, input {
  display: block;
}

Result: text1 and text2 are the same size but date is shorter.

https://jsfiddle.net/e0v13ns3/

Body:
An input of type text has a size attribute which defaults to 20, and give it an initial width.

An input of type date doesn't, its width is set using CSS, hence their initial width differs.

Note, these preset width's can differ between browsers as well.

Here is a sample where the first input has a size of 10

<div>
  <input id="text1" type="text" size="10" />
</div>
<div>
  <input id="date" type="date" />
</div>
<div>
  <input id="text2" type="text" />
</div>


问:
How to input function so it can be graphed correctly
Currently I am trying to graph the sin(x) function and a function named myPolys which is the taylor polynomial of sin(x) as it is equal to

```<code>myPolys =
Table[Table[(-1)^((j - 1)/2) x^j/Factorial[j], {j, 1, h, 2}], {h, 1,
      19, 2}];
</code>```

How can I use manipulate to graph both functions so that each part of myPolys is graphed

My graphing code so far:

```<code>Manipulate[Plot[{Sin[x], myPolys[[n]]}, {x, -10, 10},
PlotRange -> {-5, 5}], {n, 1, Length[myPolys], 1}];
</code>```

currently for each iteration of n, myPolys is graphed as separate
x and then x & -(x^3)/3! and then x & -(x^3)/3! & x^5/5! (all are plotted separate o the same graph )

The graph I'm trying to achieve is that for n=1 sin(x) should be plotted and x from myPoly should be plotted, for n=2 it continues and graphs x-(x^3/3!) (instead of plotting, for n=2, x and -x^3/3! seperately) and so on and so forth until n reaches 10.

My graph at the moment:

The graph I'm hoping for:

答:
I suppose you know there is the built in Series you can use..

```<code>Manipulate[m = n;
 Show[{
   Plot[Sin[x], {x, -10, 10}, PlotRange -> {-5, 5},
    PlotStyle -> {Thick, Red}],
   Plot[Evaluate[
     Accumulate[List @@ Normal@Series[Sin[x], {x, 0, m}]]], {x, -10, 10}]}],
    {{n, 3}, 3, 25, 2}]
</code>```

Body:
Currently I am trying to graph the sin(x) function and a function named myPolys which is the taylor polynomial of sin(x) as it is equal to

myPolys =
Table[Table[(-1)^((j - 1)/2) x^j/Factorial[j], {j, 1, h, 2}], {h, 1,
      19, 2}];

How can I use manipulate to graph both functions so that each part of myPolys is graphed

My graphing code so far:

Manipulate[Plot[{Sin[x], myPolys[[n]]}, {x, -10, 10},
PlotRange -> {-5, 5}], {n, 1, Length[myPolys], 1}];

currently for each iteration of n, myPolys is graphed as separate
x and then x & -(x^3)/3! and then x & -(x^3)/3! & x^5/5! (all are plotted separate o the same graph )

The graph I'm trying to achieve is that for n=1 sin(x) should be plotted and x from myPoly should be plotted, for n=2 it continues and graphs x-(x^3/3!) (instead of plotting, for n=2, x and -x^3/3! seperately) and so on and so forth until n reaches 10.

My graph at the moment:

The graph I'm hoping for:

Body:
I suppose you know there is the built in Series you can use..

Manipulate[m = n;
 Show[{
   Plot[Sin[x], {x, -10, 10}, PlotRange -> {-5, 5},
    PlotStyle -> {Thick, Red}],
   Plot[Evaluate[
     Accumulate[List @@ Normal@Series[Sin[x], {x, 0, m}]]], {x, -10, 10}]}],
    {{n, 3}, 3, 25, 2}]


问:
MySql, can anyone suggest how to improve my query / index?
Can anyone suggest how I can improve my query, its used for a site map and theres 80000 pages, hence the limit.

Heres my query

```<code>SELECT PageName
FROM pads
WHERE RemoveMeDate = '2001-01-01 00:00:00'
ORDER BY PadID DESC
LIMIT 20000 , 30000
</code>```

Heres my EXPLAIN

Heres the indexes I have already

答: Optimal index for this query would probably be a combination index on columns RemoveMeDate, PadID, and PageName.

ContentLicense: CC BY-SA 2.5

Body:
Can anyone suggest how I can improve my query, its used for a site map and theres 80000 pages, hence the limit.

Heres my query

SELECT PageName
FROM pads
WHERE RemoveMeDate = '2001-01-01 00:00:00'
ORDER BY PadID DESC
LIMIT 20000 , 30000

Heres my EXPLAIN

Heres the indexes I have already


问:
Case Select syntax is creating a Loop I do not want
I have written a syntax which includes case select and a msgbox. I want the syntax to find the first active cell in the spreadsheet and move it to A1 or A2 based on some predetermined questions and answers, but the commands are not working optimally. can somene help me out?

I want the messagebox to pop up intuitively based on the answers provided to previous questions, but there seems to be a mishap in terms of the message box ending up in a loop.

I have attached the code underneath.

```<code>Public Sub SurvAnalysis()

    Dim InpSh As Worksheet
    Dim fCell As Range
    Dim msg1 As String, msg2 As String
    Dim Ans1 As Variant, Ans2 As Variant

    Set InpSh = ThisWorkbook.Worksheets("Input")

    msg1 = "Are these headers included in the Data, and is the data in the correct format? { Dob ∏ StartDate ∏ End Date }"
    Ans1 = MsgBox(msg1, vbYesNoCancel, " Data type")

    Select Case Ans1
        Case vbYes
            On Error Resume Next
            Set fCell = InpSh.Cells.Find(What:="*", _
                                        After:=InpSh.Cells(Rows.Count, Columns.Count), _
                                        LookAt:=xlPart, _
                                        LookIn:=xlFormulas, _
                                        SearchOrder:=xlByRows, _
                                        SearchDirection:=xlNext, _
                                        MatchCase:=False)
            On Error GoTo 0
            If fCell Is Nothing Then
                MsgBox "All cells are blank."
            Else
                fCell.CurrentRegion.Cut Destination:=InpSh.Range("A1")
            End If
            GoTo Quit:

        Case vbCancel
            MsgBox ("Get your data sorted out")
            GoTo Quit:

        Case vbNo
            GoTo Option2:
    End Select

Quit:
Option2:

    msg2 = "Are the data in the correct manner and do you wish for us to include the headers on your behalf?"
    Ans = MsgBox(msg2, vbYesNo, "Sort Data")

    Select Case Ans
        Case vbYes
            Set fCell = InpSh.Cells.Find(What:="*", _
                                        After:=InpSh.Cells(Rows.Count, Columns.Count), _
                                        LookAt:=xlPart, _
                                        LookIn:=xlFormulas, _
                                        SearchOrder:=xlByRows, _
                                        SearchDirection:=xlNext, _
                                        MatchCase:=False)
            If fCell Is Nothing Then
                MsgBox "All cells are blank."
            Else
                fCell.CurrentRegion.Cut Destination:=InpSh.Range("A2")
                InpSh.Range("A1").Value = " Dob"
                InpSh.Range("B1").Value = " StartDate"
                InpSh.Range("C1").Value = " End Date"
            End If
        Case vbNo
            MsgBox ("Get your data sorted out")
            GoTo Quit:
    End Select
End Sub
</code>```

答: Your goto ending statement Quit: should be at the very end. In your code when it goes to Quit: it will continue on and process all the code lines below it.  Also just as a general rule of thumb and this may be opinion but usually you can always right code without having to use any goto statement.  They cause more issues than what it's worth.  See if you can write your logic without any goto statements and you'll be set for life.

Body:
I have written a syntax which includes case select and a msgbox. I want the syntax to find the first active cell in the spreadsheet and move it to A1 or A2 based on some predetermined questions and answers, but the commands are not working optimally. can somene help me out?

I want the messagebox to pop up intuitively based on the answers provided to previous questions, but there seems to be a mishap in terms of the message box ending up in a loop.

I have attached the code underneath.

Public Sub SurvAnalysis()

    Dim InpSh As Worksheet
    Dim fCell As Range
    Dim msg1 As String, msg2 As String
    Dim Ans1 As Variant, Ans2 As Variant

    Set InpSh = ThisWorkbook.Worksheets("Input")

    msg1 = "Are these headers included in the Data, and is the data in the correct format? { Dob ∏ StartDate ∏ End Date }"
    Ans1 = MsgBox(msg1, vbYesNoCancel, " Data type")

    Select Case Ans1
        Case vbYes
            On Error Resume Next
            Set fCell = InpSh.Cells.Find(What:="*", _
                                        After:=InpSh.Cells(Rows.Count, Columns.Count), _
                                        LookAt:=xlPart, _
                                        LookIn:=xlFormulas, _
                                        SearchOrder:=xlByRows, _
                                        SearchDirection:=xlNext, _
                                        MatchCase:=False)
            On Error GoTo 0
            If fCell Is Nothing Then
                MsgBox "All cells are blank."
            Else
                fCell.CurrentRegion.Cut Destination:=InpSh.Range("A1")
            End If
            GoTo Quit:

        Case vbCancel
            MsgBox ("Get your data sorted out")
            GoTo Quit:

        Case vbNo
            GoTo Option2:
    End Select

Quit:
Option2:

    msg2 = "Are the data in the correct manner and do you wish for us to include the headers on your behalf?"
    Ans = MsgBox(msg2, vbYesNo, "Sort Data")

    Select Case Ans
        Case vbYes
            Set fCell = InpSh.Cells.Find(What:="*", _
                                        After:=InpSh.Cells(Rows.Count, Columns.Count), _
                                        LookAt:=xlPart, _
                                        LookIn:=xlFormulas, _
                                        SearchOrder:=xlByRows, _
                                        SearchDirection:=xlNext, _
                                        MatchCase:=False)
            If fCell Is Nothing Then
                MsgBox "All cells are blank."
            Else
                fCell.CurrentRegion.Cut Destination:=InpSh.Range("A2")
                InpSh.Range("A1").Value = " Dob"
                InpSh.Range("B1").Value = " StartDate"
                InpSh.Range("C1").Value = " End Date"
            End If
        Case vbNo
            MsgBox ("Get your data sorted out")
            GoTo Quit:
    End Select
End Sub


问:
Convert generic IList into an array of a subtype
(please don't ask why I'm doing this - I'm interfacing with some legacy code)

I have an IList<Animal> and I want to convert it to an array of a sub-type of Animal (e.g. Leopard), but the sub-type is not known at compile time - it's passed in as a parameter.

[edit: it's guaranteed the list will only contain leopards]

I have found a way that works:

var myArray = (object[])new ArrayList(animals.ToList()).ToArray(animalType)

the caller will then cast myArray to Leopard[] for instance.

is there a better solution?

答:
Is this what you mean?</p>

```<code>public class Animal
{
    public string Name { get; set; }
}

public class Leopard : Animal
{
}

class Program
{
    static void Main(string[] args)
    {
        var animals = new List<Animal>
        {
            new Leopard { Name = "Bob" },
            new Leopard { Name = "Jeff" },
            new Leopard { Name = "Bill" },
            new Leopard { Name = "Dave" }
        };

        Leopard[] leopardArray = new Leopard[animals.Count];
        animals.CopyTo(leopardArray, 0);

        Console.Write(leopardArray.Count());
    }
}
</code>```

Body:
Is this what you mean?

public class Animal
{
    public string Name { get; set; }
}

public class Leopard : Animal
{
}

class Program
{
    static void Main(string[] args)
    {
        var animals = new List<Animal>
        {
            new Leopard { Name = "Bob" },
            new Leopard { Name = "Jeff" },
            new Leopard { Name = "Bill" },
            new Leopard { Name = "Dave" }
        };

        Leopard[] leopardArray = new Leopard[animals.Count];
        animals.CopyTo(leopardArray, 0);

        Console.Write(leopardArray.Count());
    }
}


问:
Observable type with two http.get calls in Angular 2
In my ng2 service, i have a method that has 2 http.get calls.
The function looks something like this:

```<code>getInfo(userId: number): any {

    this.http
       .get(apiUrl, options)
       .map(response => response.json())
       .subscribe(example => {
           this.example.FirstName = example.FirstName;
           this.example.LastName = example.LastName;

           this.http
               .get(`/api/${userId}`)
               .map(response => response.json())
               .subscribe(example => {
                   this.example.Street = example.Street;
                   this.example.City = example.City;

                   return this.example;
               });
       });
 }
</code>```

The only problem is that, in my component, i can't subscribe to this function, because it's not of type Observable<Example>.

If I replace the type any for the function with Observable<Example> I get :

A function whose declared type is neither 'void' nor 'any' must return a value

But I do return a value, after the response.

How can I do this without having two separate functions?

Yes, i did checked this answer: https://stackoverflow.com/a/36712707/3264998

答:
My solution using rxjs/Rx flatMap :</p>

```<code>import {Observable} from 'rxjs/Rx';

ngOnInit() {
  const usersId = ['USR001', 'USR003'];
  this.doRequest(usersId);
}

doRequest(queryArr, previousObservable = null) {
        if (queryArr.length) {
            const url = 'api/' + queryArr.shift();
            let observable = null;
            if (previousObservable) {
                observable = previousObservable.flatMap(() => {
                    return this.http.get(url);
                });
            } else {
                observable = this.http.get(url);
            }
            return this.doRequest(queryArr, observable);
        } else {
            return previousObservable;
        }
    }
</code>```

Body:
In my ng2 service, i have a method that has 2 http.get calls.
The function looks something like this:

getInfo(userId: number): any {

    this.http
       .get(apiUrl, options)
       .map(response => response.json())
       .subscribe(example => {
           this.example.FirstName = example.FirstName;
           this.example.LastName = example.LastName;

           this.http
               .get(`/api/${userId}`)
               .map(response => response.json())
               .subscribe(example => {
                   this.example.Street = example.Street;
                   this.example.City = example.City;

                   return this.example;
               });
       });
 }

The only problem is that, in my component, i can't subscribe to this function, because it's not of type Observable<Example>.

If I replace the type any for the function with Observable<Example> I get :

A function whose declared type is neither 'void' nor 'any' must return a value

But I do return a value, after the response.

How can I do this without having two separate functions?

Yes, i did checked this answer: https://stackoverflow.com/a/36712707/3264998

Body:
My solution using rxjs/Rx flatMap :

import {Observable} from 'rxjs/Rx';

ngOnInit() {
  const usersId = ['USR001', 'USR003'];
  this.doRequest(usersId);
}

doRequest(queryArr, previousObservable = null) {
        if (queryArr.length) {
            const url = 'api/' + queryArr.shift();
            let observable = null;
            if (previousObservable) {
                observable = previousObservable.flatMap(() => {
                    return this.http.get(url);
                });
            } else {
                observable = this.http.get(url);
            }
            return this.doRequest(queryArr, observable);
        } else {
            return previousObservable;
        }
    }


问:
Detect multiple keys on single keypress event in jQuery
Is it at all possible to combine a mixture of keypress' to fire a single event?

```<code>$(document).keyup(function(e){
    if (e.keyCode == 68 && e.keyCode == 69 && e.keyCode == 86) {
        alert('oh hai');
    }
});
</code>```

I've tried it in Chrome but the event doesn't fire.

Call me crazy but I am writing a Chrome extension and want to push D+E+V keys together to force it into a hidden developer mode.

答:
Use this code to have an event triggered by multiple key presses + Timeout after 100ms to prevent mistypes.
In this example : if A,Z,E are pressed within a time period of 100ms, the event will be triggered.</p>

```<code>var map = {65:false,90:false,69:false}; //Modify keyCodes here
$(document).keydown(function(e){
    console.log(e.keyCode);
    map[e.keyCode] = e.keyCode in map ? true : map[e.keyCode] || false;
    var result = Object.keys(map).filter(function(key){
        return map[key];
    }).length === Object.keys(map).length ? true : false;
    if(result){
        //Your event here
        Object.keys(map).forEach(function(key){
            map[key] = false;
        });
    }
    setTimeout(function(){
        map[e.keyCode] = false;
    },100);
});
</code>```

Body:
Is it at all possible to combine a mixture of keypress' to fire a single event?

$(document).keyup(function(e){
    if (e.keyCode == 68 && e.keyCode == 69 && e.keyCode == 86) {
        alert('oh hai');
    }
});

I've tried it in Chrome but the event doesn't fire.

Call me crazy but I am writing a Chrome extension and want to push D+E+V keys together to force it into a hidden developer mode.

Body:
Use this code to have an event triggered by multiple key presses + Timeout after 100ms to prevent mistypes.
In this example : if A,Z,E are pressed within a time period of 100ms, the event will be triggered.

var map = {65:false,90:false,69:false}; //Modify keyCodes here
$(document).keydown(function(e){
    console.log(e.keyCode);
    map[e.keyCode] = e.keyCode in map ? true : map[e.keyCode] || false;
    var result = Object.keys(map).filter(function(key){
        return map[key];
    }).length === Object.keys(map).length ? true : false;
    if(result){
        //Your event here
        Object.keys(map).forEach(function(key){
            map[key] = false;
        });
    }
    setTimeout(function(){
        map[e.keyCode] = false;
    },100);
});


问:
DynamoDB Sort and select top 20 records
I wanted to get records like top 10 or 20 basically some configurable number which are sorted based on a date field stored as ISO-8601 format uuuu-MM-dd after applying some filters.

```<code>@DynamoDBTable(tableName = "Data")
@NoArgsConstructor
@ToString
public class Data {

    private LocalDate date;
    @Setter
    private Long number;
    @Setter
    private STATUS status;

    @DynamoDBHashKey
    @DynamoDBTypeConverted(converter = LocalDateConverter.class)
    public LocalDate getDate() {
        return date;
    }

    @DynamoDBTypeConverted(converter = LocalDateConverter.class)
    public void setDate(LocalDate date) {
        this.date = date;
    }

    @DynamoDBIndexHashKey(globalSecondaryIndexName = "idx_Data_number")
    public Long getCompetitionId() {
        return number;
    }

    @DynamoDBTypeConvertedEnum
    @DynamoDBIndexHashKey(globalSecondaryIndexName = "idx_Data_status")
    public STATUS getStatus() {
        return status;
    }
}
</code>```

I need to get say 20 records sorted based on date field after filtering based on number and multiple status. I was using ScanRequest to basically filter the records. Now I want to limit the results and get top records based on the date.

```<code>@AllArgsConstructor
public class DataRepositoryImpl implements DataRepository {
 private final DynamoDBMapper dynamoDBMapper;
 private final AmazonDynamoDB amazonDynamoDB;

 @Override
 public List<Data> findAll(Long number, List<String> status) {
    Condition numberCondition = new Condition()
            .withComparisonOperator(ComparisonOperator.EQ)
            .withAttributeValueList(new AttributeValue().withN(String.valueOf(number)));

    List<AttributeValue> attributeValues = newArrayList();
    status.forEach(s -> attributeValues.add(new AttributeValue().withS(s)));
    Condition statusCondition = new Condition()
            .withComparisonOperator(ComparisonOperator.IN)
            .withAttributeValueList(attributeValues);

    Map<String, Condition> conditions = newHashMap();
    conditions.put("number", numberCondition);
    conditions.put("status", statusCondition);

    ScanRequest scanRequest = new ScanRequest()
            .withTableName("Data")
            .withScanFilter(conditions)
            .withConditionalOperator(ConditionalOperator.AND);

    ScanResult scanResult = amazonDynamoDB.scan(scanRequest);
    return dynamoDBMapper.marshallIntoObjects(Data.class, scanResult.getItems());
    }
}
</code>```

答:
You can set the Limit in your scan. ScanRequest#setLimit

The maximum number of items to evaluate (not necessarily the number of
  matching items). If DynamoDB processes the number of items up to the
  limit while processing the results, it stops the operation and returns
  the matching values up to that point, and a key in LastEvaluatedKey to
  apply in a subsequent operation, so that you can pick up where you
  left off.

But I doubt dynamodb provide sort on any key in scan.

You can create Local Index, and that will help you to retrieve with limit as well as sorted.

Title: DynamoDB Sort and select top 20 records

Body:
I wanted to get records like top 10 or 20 basically some configurable number which are sorted based on a date field stored as ISO-8601 format uuuu-MM-dd after applying some filters.

@DynamoDBTable(tableName = "Data")
@NoArgsConstructor
@ToString
public class Data {

    private LocalDate date;
    @Setter
    private Long number;
    @Setter
    private STATUS status;

    @DynamoDBHashKey
    @DynamoDBTypeConverted(converter = LocalDateConverter.class)
    public LocalDate getDate() {
        return date;
    }

    @DynamoDBTypeConverted(converter = LocalDateConverter.class)
    public void setDate(LocalDate date) {
        this.date = date;
    }

    @DynamoDBIndexHashKey(globalSecondaryIndexName = "idx_Data_number")
    public Long getCompetitionId() {
        return number;
    }

    @DynamoDBTypeConvertedEnum
    @DynamoDBIndexHashKey(globalSecondaryIndexName = "idx_Data_status")
    public STATUS getStatus() {
        return status;
    }
}

I need to get say 20 records sorted based on date field after filtering based on number and multiple status. I was using ScanRequest to basically filter the records. Now I want to limit the results and get top records based on the date.

@AllArgsConstructor
public class DataRepositoryImpl implements DataRepository {
 private final DynamoDBMapper dynamoDBMapper;
 private final AmazonDynamoDB amazonDynamoDB;

 @Override
 public List<Data> findAll(Long number, List<String> status) {
    Condition numberCondition = new Condition()
            .withComparisonOperator(ComparisonOperator.EQ)
            .withAttributeValueList(new AttributeValue().withN(String.valueOf(number)));

    List<AttributeValue> attributeValues = newArrayList();
    status.forEach(s -> attributeValues.add(new AttributeValue().withS(s)));
    Condition statusCondition = new Condition()
            .withComparisonOperator(ComparisonOperator.IN)
            .withAttributeValueList(attributeValues);

    Map<String, Condition> conditions = newHashMap();
    conditions.put("number", numberCondition);
    conditions.put("status", statusCondition);

    ScanRequest scanRequest = new ScanRequest()
            .withTableName("Data")
            .withScanFilter(conditions)
            .withConditionalOperator(ConditionalOperator.AND);

    ScanResult scanResult = amazonDynamoDB.scan(scanRequest);
    return dynamoDBMapper.marshallIntoObjects(Data.class, scanResult.getItems());
    }
}


问:
MySQL Query with multiple AND statements seems to be ignoring one
I'm trying to run a query on a MySQL database, but I found that it seems to be ignoring the 'status' item.

```<code>SELECT * FROM  `posts`
WHERE
      `tags` LIKE '%gda%'
   OR `tags` LIKE '%contests%'
   OR `tags` LIKE '%merch%'
  AND `newsID` != '2134'
  AND `status` > '1'
ORDER BY  `postDate` DESC  LIMIT 5
</code>```

In that example, it's still pulling items even if 'status' is set to 0. What am I doing wrong?

答:
Usually mixing ORs and ANDs is not a smart practice, since you'll get different results based on the execution order and the operator precedence, e.g, true or true and false, can be evaluated as (true or true) and false - yielding false or as true or (true and false) - yielding true.

Use parentheses to separate the ORs and the ANDs, and the execution order will be explicit, like this:

```<code>SELECT * FROM  `posts`
WHERE (`tags` LIKE '%gda%' OR `tags` LIKE '%contests%' OR `tags` LIKE '%merch%')
  AND `newsID` != '2134'
  AND `status` > '1'
ORDER BY  `postDate` DESC  LIMIT 5
</code>```

Body:
I'm trying to run a query on a MySQL database, but I found that it seems to be ignoring the 'status' item.

SELECT * FROM  `posts`
WHERE
      `tags` LIKE '%gda%'
   OR `tags` LIKE '%contests%'
   OR `tags` LIKE '%merch%'
  AND `newsID` != '2134'
  AND `status` > '1'
ORDER BY  `postDate` DESC  LIMIT 5

In that example, it's still pulling items even if 'status' is set to 0. What am I doing wrong?

Body:
Usually mixing ORs and ANDs is not a smart practice, since you'll get different results based on the execution order and the operator precedence, e.g, true or true and false, can be evaluated as (true or true) and false - yielding false or as true or (true and false) - yielding true.

Use parentheses to separate the ORs and the ANDs, and the execution order will be explicit, like this:

SELECT * FROM  `posts`
WHERE (`tags` LIKE '%gda%' OR `tags` LIKE '%contests%' OR `tags` LIKE '%merch%')
  AND `newsID` != '2134'
  AND `status` > '1'
ORDER BY  `postDate` DESC  LIMIT 5


问:
Receiving the key value pair as input parameter
I am trying to receive the below key value pair as the input parameter to my Web API

```<code>json=%7B%0A%22MouseSampleBarcode%22%20%3A%20%22MOS81%22%0A%7D%0A
</code>```

where the right of the string is the URL encoded JSON which looks like

```<code>{
"MouseSampleBarcode" : "MOS81"
}
</code>```

How can I parse this and store them in to the Model class

```<code> [HttpPost]
 public async Task<IHttpActionResult> Get([FromBody] CoreBarCodeDTO.RootObject coreBarCode)
 {
  string Bar_Code = coreBarCode.MouseSampleBarcode.ToString();
</code>```

where the CoreBarCodeDTO looks like below

```<code>public class CoreBarCodeDTO
{
    public class RootObject
    {
        public string MouseSampleBarcode { get; set; }
    }
 }
</code>```

答:
As @Lokki mentioned in his comment. The GET verb does not have a body, you need to change that to POST or PUT (depending if you are creating/searching or updating), so your code would look like this:</p>

```<code>[HttpPost("/")]
public async Task<IHttpActionResult> Get([FromBody] CoreBarCodeDTO.RootObject coreBarCode)
{
   string Bar_Code = coreBarCode.MouseSampleBarcode.ToString();
</code>```

Body:
I am trying to receive the below key value pair as the input parameter to my Web API

json=%7B%0A%22MouseSampleBarcode%22%20%3A%20%22MOS81%22%0A%7D%0A

where the right of the string is the URL encoded JSON which looks like

{
"MouseSampleBarcode" : "MOS81"
}

How can I parse this and store them in to the Model class

 [HttpPost]
 public async Task<IHttpActionResult> Get([FromBody] CoreBarCodeDTO.RootObject coreBarCode)
 {
  string Bar_Code = coreBarCode.MouseSampleBarcode.ToString();

where the CoreBarCodeDTO looks like below

public class CoreBarCodeDTO
{
    public class RootObject
    {
        public string MouseSampleBarcode { get; set; }
    }
 }

Body:
As @Lokki mentioned in his comment. The GET verb does not have a body, you need to change that to POST or PUT (depending if you are creating/searching or updating), so your code would look like this:

[HttpPost("/")]
public async Task<IHttpActionResult> Get([FromBody] CoreBarCodeDTO.RootObject coreBarCode)
{
   string Bar_Code = coreBarCode.MouseSampleBarcode.ToString();


问:
Oracle SQL - Count XML nodes in a clob type column
I was trying to write an optimized SQL query to count a specific XML node in clob type column, for now I'm using a REGEXP_COUNT to browse through all rows and all XMLs, but this is terribly slow.

Like this:

```<code>SELECT sum(REGEXP_COUNT(clobtype_column_withXMLs, '/Node_Closing_tag', 1)) as 'Node_number' FROM MY_TABLE;
</code>```

This works, but with hundreds of millions of tags it takes literally ages.

I want to bypass the XML structure and shorten the count time. I have found some things, but most of them involve changing the column type to xml and use xquery and other DML functions.

In my case I can't modify the table, I only need the number, how many times the specified node occurs in the column.

My table structure:

not an XML Table, various column types and a CLOB type column, in which every row contains a different sized XML (hundreds of millions of characters).
The XML has pretty complex structure, the one node I'm searching for is in the middle:

```<code>1/2/3/4/5/I'm_searching_for_this/contains_multiple_nodes
</code>```

Is there any fast way to count nodes in a structure like this, without modifying anything in the table? With fast I mean, count 500 million nodes in a couple of hours maximum. (text search takes 24h+)

答:
You don't have to change the column type in the table to be able to use XML queries, you can convert on the fly with XMLQuery or XMLTable.

One option is to use XMLTable to extract all of the relevant nodes, and count how many you get back:

```<code>select count(*)
from your_table
cross join xmltable(
  '//targetNodeName'
  passing xmltype(clobtype_column_withXMLs)
  columns dummy varchar2(1) path '@dummy'
);
</code>```

The XMLTable produces one row for each matching node. As you are only counting them, and not using the contents of that node, I've used a dummy column name and contents, picking an attribute name that probably doesn't exist - if it might, change that to something else. The dummy value will therefore be null, but count(*) will count them anyway.

How that performs will have to be tested of course... it may well be even worse than using regular expressions. It would allow you to search for self-closed tags though, which might not matter to you based on what you're currently doing.

You could also adapt this to counts the nodes in each CLOB/XML value from your original table if that was useful; if it has an ID column for instance:

```<code>select t.id, count(*)
from your_table t
cross join xmltable(
  '//targetNodeName'
  passing xmltype(clobtype_column_withXMLs)
  columns dummy varchar2(1) path '@dummy'
)
group by t.id;
</code>```

Body:
I was trying to write an optimized SQL query to count a specific XML node in clob type column, for now I'm using a REGEXP_COUNT to browse through all rows and all XMLs, but this is terribly slow.

Like this:

SELECT sum(REGEXP_COUNT(clobtype_column_withXMLs, '/Node_Closing_tag', 1)) as 'Node_number' FROM MY_TABLE;

This works, but with hundreds of millions of tags it takes literally ages.

I want to bypass the XML structure and shorten the count time. I have found some things, but most of them involve changing the column type to xml and use xquery and other DML functions.

In my case I can't modify the table, I only need the number, how many times the specified node occurs in the column.

My table structure:

not an XML Table, various column types and a CLOB type column, in which every row contains a different sized XML (hundreds of millions of characters).
The XML has pretty complex structure, the one node I'm searching for is in the middle:

1/2/3/4/5/I'm_searching_for_this/contains_multiple_nodes

Is there any fast way to count nodes in a structure like this, without modifying anything in the table? With fast I mean, count 500 million nodes in a couple of hours maximum. (text search takes 24h+)

Body:
You don't have to change the column type in the table to be able to use XML queries, you can convert on the fly with XMLQuery or XMLTable.

One option is to use XMLTable to extract all of the relevant nodes, and count how many you get back:

select count(*)
from your_table
cross join xmltable(
  '//targetNodeName'
  passing xmltype(clobtype_column_withXMLs)
  columns dummy varchar2(1) path '@dummy'
);

The XMLTable produces one row for each matching node. As you are only counting them, and not using the contents of that node, I've used a dummy column name and contents, picking an attribute name that probably doesn't exist - if it might, change that to something else. The dummy value will therefore be null, but count(*) will count them anyway.

How that performs will have to be tested of course... it may well be even worse than using regular expressions. It would allow you to search for self-closed tags though, which might not matter to you based on what you're currently doing.

You could also adapt this to counts the nodes in each CLOB/XML value from your original table if that was useful; if it has an ID column for instance:

select t.id, count(*)
from your_table t
cross join xmltable(
  '//targetNodeName'
  passing xmltype(clobtype_column_withXMLs)
  columns dummy varchar2(1) path '@dummy'
)
group by t.id;


问:
confused addition operator logic
Why does the variable counter keep increasing when it re-initializes itself back to 0 in the self-invoking function?

```<code> var add = (function () {
     var counter = 0;
     return function () {
        return counter += 1;
     }
 })();

 add();
 add();
 add();

 // the counter is still 3 when this line of code exists
 // var counter = 0;
</code>```

So when add() function gets invoked, a function runs first with initializing counter = 0 and returning another function that returns the incremental value of counter. Why is this the case when there's var counter = 0; ?

source: https://www.w3schools.com/js/js_function_closures.asp

edit: November 16th, 2017

Okay so it makes a lot more sense now from both of the answers given on this page. For extra clarification, I will add my own reasoning to give it a better visualization of why this happens.

```<code> //first call of add()
 (function(){ // a self-invoking function
    var counter = 0; // executes once with the self-invoking function
    return function() { return counter += 1; } //explained below
 });

 //since the self-invoke function ran already, add() will begin to run the returned function:
 add = function() { return counter += 1; };
 add(); ----> counter += 1; -----> add.counter = 1;
 //counter acts like this.counter, so it's a part of add()
 //counter is now at 1

 //second call of add();
 //add has now officially been **transformed** to the new function:
 add = function() {
    return counter += 1;
 };
 //while add.counter still **exists** and remains in the self-invoke
 //function. Do we call this **limbo variable** ? Don't know.
 //add.counter is at 2

 //third call of add();
 function() {
   return counter += 1;
 }
 //add.counter is at 3!
</code>```

答:
Because the variable add contains the result of the self invoking function. So the value of add is this:

```<code>function () {
    return counter += 1;
}
</code>```

The counter variable is only initialized before this function is set to the add variable.

Title: confused addition operator logic

Body:
Why does the variable counter keep increasing when it re-initializes itself back to 0 in the self-invoking function?

 var add = (function () {
     var counter = 0;
     return function () {
        return counter += 1;
     }
 })();

 add();
 add();
 add();

 // the counter is still 3 when this line of code exists
 // var counter = 0;

So when add() function gets invoked, a function runs first with initializing counter = 0 and returning another function that returns the incremental value of counter. Why is this the case when there's var counter = 0; ?

source: https://www.w3schools.com/js/js_function_closures.asp

edit: November 16th, 2017

Okay so it makes a lot more sense now from both of the answers given on this page. For extra clarification, I will add my own reasoning to give it a better visualization of why this happens.

 //first call of add()
 (function(){ // a self-invoking function
    var counter = 0; // executes once with the self-invoking function
    return function() { return counter += 1; } //explained below
 });

 //since the self-invoke function ran already, add() will begin to run the returned function:
 add = function() { return counter += 1; };
 add(); ----> counter += 1; -----> add.counter = 1;
 //counter acts like this.counter, so it's a part of add()
 //counter is now at 1

 //second call of add();
 //add has now officially been **transformed** to the new function:
 add = function() {
    return counter += 1;
 };
 //while add.counter still **exists** and remains in the self-invoke
 //function. Do we call this **limbo variable** ? Don't know.
 //add.counter is at 2

 //third call of add();
 function() {
   return counter += 1;
 }
 //add.counter is at 3!

Body:
Because the variable add contains the result of the self invoking function. So the value of add is this:

function () {
    return counter += 1;
}

The counter variable is only initialized before this function is set to the add variable.


问:
jQuery File Upload by bluimp, how to replace instead of renaming
First of all the jQuery plugin can be found here:

https://github.com/blueimp/jQuery-File-Upload

I'm using the PHP-version of the script and I'm trying to replace images that has the same name instead of renaming them.

I think I've found the functions that do the renaming, but the edits I tried do not work.

```<code>  protected function upcount_name_callback($matches) {
        $index = isset($matches[1]) ? intval($matches[1]) + 1 : 1;
        $ext = isset($matches[2]) ? $matches[2] : '';
        return ' ('.$index.')'.$ext;
    }

    protected function upcount_name($name) {
        return preg_replace_callback(
            '/(?:(?: \(([\d]+)\))?(\.[^.]+))?$/',
            array($this, 'upcount_name_callback'),
            $name,
            1
        );
    }
</code>```

Any suggestions? I've searched for this all over the place but to no avail.

Link to the php class that does the upload:
https://github.com/blueimp/jQuery-File-Upload/blob/master/server/php/upload.class.php

Any suggestions?

Edit:

I've tried to just return null on these functions, but that just hangs the script, probably because it doesn't know what to do if the filename is the same.

答:
you can also use overwrite as an option like this:

```<code>$options = array(
  'overwrite' => $overwrite
);
$upload_handler = new UploadHandler($options);
</code>```

in UploadHandler.php :
add the default parameter

```<code>    function __construct($options = null,...){
            ...
            'overwrite' => false,
            ...
    }
</code>```

then replace get_file_name() function by

```<code>    protected function get_file_name($file_path, $name, $size, $type, $error,
            $index, $content_range) {
        $name = $this->trim_file_name($file_path, $name, $size, $type, $error,
            $index, $content_range);
        if($this->options['overwrite'])
            return $name;
        else
            return $this->get_unique_filename(
                $file_path,
                $this->fix_file_extension($file_path, $name, $size, $type, $error,
                    $index, $content_range),
                $size,
                $type,
                $error,
                $index,
                $content_range
            );
    }
</code>```

regards

Body:
First of all the jQuery plugin can be found here:

https://github.com/blueimp/jQuery-File-Upload

I'm using the PHP-version of the script and I'm trying to replace images that has the same name instead of renaming them.

I think I've found the functions that do the renaming, but the edits I tried do not work.

  protected function upcount_name_callback($matches) {
        $index = isset($matches[1]) ? intval($matches[1]) + 1 : 1;
        $ext = isset($matches[2]) ? $matches[2] : '';
        return ' ('.$index.')'.$ext;
    }

    protected function upcount_name($name) {
        return preg_replace_callback(
            '/(?:(?: \(([\d]+)\))?(\.[^.]+))?$/',
            array($this, 'upcount_name_callback'),
            $name,
            1
        );
    }

Any suggestions? I've searched for this all over the place but to no avail.

Link to the php class that does the upload:
https://github.com/blueimp/jQuery-File-Upload/blob/master/server/php/upload.class.php

Any suggestions?

Edit:

I've tried to just return null on these functions, but that just hangs the script, probably because it doesn't know what to do if the filename is the same.

Body:
you can also use overwrite as an option like this:

$options = array(
  'overwrite' => $overwrite
);
$upload_handler = new UploadHandler($options);

in UploadHandler.php :
add the default parameter

    function __construct($options = null,...){
            ...
            'overwrite' => false,
            ...
    }

then replace get_file_name() function by

    protected function get_file_name($file_path, $name, $size, $type, $error,
            $index, $content_range) {
        $name = $this->trim_file_name($file_path, $name, $size, $type, $error,
            $index, $content_range);
        if($this->options['overwrite'])
            return $name;
        else
            return $this->get_unique_filename(
                $file_path,
                $this->fix_file_extension($file_path, $name, $size, $type, $error,
                    $index, $content_range),
                $size,
                $type,
                $error,
                $index,
                $content_range
            );
    }

regards


答:
Try to use brackets to emphasize your logical sentences. Such as:

```<code>SELECT *
  FROM  `posts`
 WHERE  (`tags` LIKE  '%gda%' OR  `tags` LIKE  '%contests%' OR  `tags` LIKE  '%merch%')
   AND  `newsID` !=  '2134'
   AND `status` > '1'
ORDER BY  `postDate` DESC  LIMIT 5
</code>```

Otherwise, your logic gets lost. Also using brackets makes easier to read your SQL sentences.

Title: MySQL Query with multiple AND statements seems to be ignoring one

Body:
Try to use brackets to emphasize your logical sentences. Such as:

SELECT *
  FROM  `posts`
 WHERE  (`tags` LIKE  '%gda%' OR  `tags` LIKE  '%contests%' OR  `tags` LIKE  '%merch%')
   AND  `newsID` !=  '2134'
   AND `status` > '1'
ORDER BY  `postDate` DESC  LIMIT 5

Otherwise, your logic gets lost. Also using brackets makes easier to read your SQL sentences.


问:
Should I use redundancy or a simple query on a large dataset with Firebase Cloud Firestore database?
I have a collection, itemsCollection, which contains a very large amount of small itemDocs.  Each itemDoc has a subcollection, statistics.  Each itemDoc also has a field "owner" which indicates which user owns the itemDoc.

```<code>itemsCollection
    itemDoc1
        statistics
    itemDoc2
        statistics
    itemDoc3
        statistics
    itemDoc4
        statistics
    ...
</code>```

I also have a collection, usersCollection, which contains basic user info.

```<code>usersCollection
    user1
    user2
    user3
    ...
</code>```

Since each itemDoc belongs to a specific user, it's necessary to display to each user which itemDocs they own.  I have been using the query:

```<code>db.collection("itemsCollection").where("owner", "==", "user1")
</code>```

I am wondering if this will scale effectively, i.e. whenever itemsCollection gets to be millions of records? If not, is the best solution to duplicate each itemDoc and its statistics subcollection as a subcollection in the user document, or should I be doing something else?

答:
As Alex Dufter, the product manager from Firebase, explained in one of days at Firebase Dev Summit 2017 that Firestore was inspired in many ways by the feed-back that they had on the Firebase Realtime Database over the years. They faced two types of issues:

Data modelling and querying. Firebase Realtime Database cannot query over multiple properties because it ussaly involves duplication data or cliend-side filtering, which we all already know that is some kind of messy.

Realtime Database does not scale automatically.

With this new product, they say that you can now build an app and grow it to planetary scale without changing a single line of code. Cloud Firestore is also a NoSQL database that was build specifically for mobile and web app development. It's flexible to build all kinds of apps and scalable to grow to any size.

So because the new database was build knowing this iusses, duplication data is not nedeed anymore. So you will not have to worry about using that line of code, even if your data will grow to millions of records, it will scale automatically. But one thing you need to remember, if you will use multiple conditions, don't forget to use the indexes by simply adding them in the Firebase console. Here are two simple examples from the offical documentation:

```<code>citiesRef.whereEqualTo("state", "CO").whereEqualTo("name", "Denver");
citiesRef.whereEqualTo("state", "CA").whereLessThan("population", 1000000);
</code>```

Body:
I have a collection, itemsCollection, which contains a very large amount of small itemDocs.  Each itemDoc has a subcollection, statistics.  Each itemDoc also has a field "owner" which indicates which user owns the itemDoc.

itemsCollection
    itemDoc1
        statistics
    itemDoc2
        statistics
    itemDoc3
        statistics
    itemDoc4
        statistics
    ...

I also have a collection, usersCollection, which contains basic user info.

usersCollection
    user1
    user2
    user3
    ...

Since each itemDoc belongs to a specific user, it's necessary to display to each user which itemDocs they own.  I have been using the query:

db.collection("itemsCollection").where("owner", "==", "user1")

I am wondering if this will scale effectively, i.e. whenever itemsCollection gets to be millions of records? If not, is the best solution to duplicate each itemDoc and its statistics subcollection as a subcollection in the user document, or should I be doing something else?

Body:
As Alex Dufter, the product manager from Firebase, explained in one of days at Firebase Dev Summit 2017 that Firestore was inspired in many ways by the feed-back that they had on the Firebase Realtime Database over the years. They faced two types of issues:

Data modelling and querying. Firebase Realtime Database cannot query over multiple properties because it ussaly involves duplication data or cliend-side filtering, which we all already know that is some kind of messy.

Realtime Database does not scale automatically.

With this new product, they say that you can now build an app and grow it to planetary scale without changing a single line of code. Cloud Firestore is also a NoSQL database that was build specifically for mobile and web app development. It's flexible to build all kinds of apps and scalable to grow to any size.

So because the new database was build knowing this iusses, duplication data is not nedeed anymore. So you will not have to worry about using that line of code, even if your data will grow to millions of records, it will scale automatically. But one thing you need to remember, if you will use multiple conditions, don't forget to use the indexes by simply adding them in the Firebase console. Here are two simple examples from the offical documentation:

citiesRef.whereEqualTo("state", "CO").whereEqualTo("name", "Denver");
citiesRef.whereEqualTo("state", "CA").whereLessThan("population", 1000000);


问:
SSRS PMT Function producing #ERROR
I am hoping someone can help me here. I am using the PMT function to calculate mortgage payments in SSRS. I am using the following Formula

```<code>=IIF(Note = "Present",-PMT(Rate/12,Term,Balance,0,DueDate.EndOfPeriod),Nothing))
</code>```

The formula works perfectly when Note = Present.  However on all other loans it is producing #ERROR. I don't understand why this is happening.

Is there some other error handling that needs to be done to simply leave the cell blank if the note is not present?

答:
What is Nothing in your code?</p>

```<code>=IF(Note = "Present",-PMT(Rate/12,Term,Balance,0,DueDate.EndOfPeriod),0))
</code>```

Title: SSRS PMT Function producing #ERROR

Body:
I am hoping someone can help me here. I am using the PMT function to calculate mortgage payments in SSRS. I am using the following Formula

=IIF(Note = "Present",-PMT(Rate/12,Term,Balance,0,DueDate.EndOfPeriod),Nothing))

The formula works perfectly when Note = Present.  However on all other loans it is producing #ERROR. I don't understand why this is happening.

Is there some other error handling that needs to be done to simply leave the cell blank if the note is not present?

Body:
What is Nothing in your code?

=IF(Note = "Present",-PMT(Rate/12,Term,Balance,0,DueDate.EndOfPeriod),0))


问:
pymongo update/insert a dict in a document
I want to insert a dict into a document as the value for a field (say v) if this document does not exist;

```<code>db.table.update_one({'k': some_unique_key},
                    {'$set': {'v': {name: 'some_name'},
                    upsert=True)
</code>```

Also if the document exists, I want to update the document by updating the dict of the same field (v), i.e. adding one name: value pair to v, I am wondering how to do that.

e.g. the original document is like,

```<code>{'k': some_key, 'v': {'name_a': 'name_a_val'}}
</code>```

adding one more key:value pair name_b:name_b_val to v is like

```<code>{'k': some_key, 'v': {'name_a': 'name_a_val', 'name_b': 'name_b_val'}}
</code>```

UPDATE

this is the solution I came up with

```<code>if not db.table.find_one({'k': some_unique_key}):
    db.table.insert_one({'k': some_unique_key, 'v': {'name_a': 'name_a_val'})
else:
    v_val_dict = db.table.find_one({'k': some_unique_key})['v']

    vat_cache.update_one({'k': some_unique_key},
                     {'$set': {'v': v_val_dict.update({'name_b': 'name_b_val'})}})
</code>```

I am wondering if there is a better way to do this.

答:
you have to use the dot notation. This will update the nested field named name_a or will create it inside v if it doesn't exist.

```<code>coll.update_one({'k': 'some_key'},
                {'$set': { 'v.name_a': 'name_a_val'}}, upsert=True)
</code>```

Body:
I want to insert a dict into a document as the value for a field (say v) if this document does not exist;

db.table.update_one({'k': some_unique_key},
                    {'$set': {'v': {name: 'some_name'},
                    upsert=True)

Also if the document exists, I want to update the document by updating the dict of the same field (v), i.e. adding one name: value pair to v, I am wondering how to do that.

e.g. the original document is like,

{'k': some_key, 'v': {'name_a': 'name_a_val'}}

adding one more key:value pair name_b:name_b_val to v is like

{'k': some_key, 'v': {'name_a': 'name_a_val', 'name_b': 'name_b_val'}}

UPDATE

this is the solution I came up with

if not db.table.find_one({'k': some_unique_key}):
    db.table.insert_one({'k': some_unique_key, 'v': {'name_a': 'name_a_val'})
else:
    v_val_dict = db.table.find_one({'k': some_unique_key})['v']

    vat_cache.update_one({'k': some_unique_key},
                     {'$set': {'v': v_val_dict.update({'name_b': 'name_b_val'})}})

I am wondering if there is a better way to do this.

Body:
you have to use the dot notation. This will update the nested field named name_a or will create it inside v if it doesn't exist.

coll.update_one({'k': 'some_key'},
                {'$set': { 'v.name_a': 'name_a_val'}}, upsert=True)


问:
How to ensure maximum compatibility/portability of my code?
With newer versions of MATLAB newer features have been introduced such as the string class that allows creating string arrays and the possibility to define strings using double quotes "" (see answer), among other features.

This is great news because this kind of features make life easier. However, this also brings a problem to the table.

I share code with colleagues frequently and they may not necessarily have the latest version of MATLAB installed. If they run my code written using the newer syntax it will crash in their machines.

What techniques/measures can I put in practice to ensure maximum compatibility/portability of my code?

This post suggests refraining from using the newer features, but then what's in it for me by using the newest version if I have to force myself to use the older syntax?

Is using the older syntax and checking for the MATLAB version the only options I have?

答:
It largely depends on what you mean by sharing "code with colleagues frequently"

If you are writing code and they are simply using it as you have provided, then all they have to do is have the latest MATLAB Runtime. Which is free. You can then use whatever version you want.

If you and and your colleagues are all contributing code then you definitely need to agree on what version to use.


问:
Circumventing Retrofit's "baseUrl must end in /"
I use Retrofit 2.3.0 to interact with OAI-PMH endpoints.

I now happen to interact with an endpoint which is picky about whether its base URL ends with a slash or not:

Without slash:

http://www.relacionesinternacionales.info/ojs/oai.html?verb=Identify works as intended.

With slash:

http://www.relacionesinternacionales.info/ojs/oai.html/?verb=Identify causes a redirect to a 404 page.

Now the problem is that Retrofit 2.3.0 demands base URLs to end with a slash.

Providing the Retrofit builder with the no-ending-slash base URL makes Retrofit complain.

Providing the Retrofit builder with the ending-with-a-slash base URL causes Retrofit to build an incorrect URL, causing the 404 error.

How can I circumvent this limitation?

答:
As a workaround, I use Java Reflection to manipulate the Retrofit object's baseUrl field.

First, the code checks if the provided baseUrl ends with a slash. If so, nothing particular has to happen.

In case the provided baseUrl does not end with a slash, first the retrofit object is created with a trailing slash to baseUrl, then later this baseUrl object is replaced with the original non-slash-ending baseUrl:

```<code>String baseUrl = "..."; // can end with slash or not

Retrofit retrofit = new Retrofit.Builder()
        .baseUrl( baseUrl.endsWith("/") ? baseUrl : baseUrl + "/" )
        .addConverterFactory(ScalarsConverterFactory.create())
        .build();

// workaround for https://stackoverflow.com/q/47331753/923560
if ( ! baseUrl.endsWith("/") ) {
    try {
        Field baseUrlField = retrofit.getClass().getDeclaredField("baseUrl");
        baseUrlField.setAccessible(true);
        HttpUrl newHttpUrl = HttpUrl.parse(baseUrl);
        baseUrlField.set(retrofit, newHttpUrl);
        baseUrlField.setAccessible(false);
    }
    catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
        LOG.error("Exception while manipulating baseUrl=" + baseUrl + " to not end with a slash", e);
        throw new RuntimeException(e);
    }
}

service = retrofit.create(OaiPmhService.class);
// ...
</code>```

Body:
As a workaround, I use Java Reflection to manipulate the Retrofit object's baseUrl field.

First, the code checks if the provided baseUrl ends with a slash. If so, nothing particular has to happen.

In case the provided baseUrl does not end with a slash, first the retrofit object is created with a trailing slash to baseUrl, then later this baseUrl object is replaced with the original non-slash-ending baseUrl:

String baseUrl = "..."; // can end with slash or not

Retrofit retrofit = new Retrofit.Builder()
        .baseUrl( baseUrl.endsWith("/") ? baseUrl : baseUrl + "/" )
        .addConverterFactory(ScalarsConverterFactory.create())
        .build();

// workaround for https://stackoverflow.com/q/47331753/923560
if ( ! baseUrl.endsWith("/") ) {
    try {
        Field baseUrlField = retrofit.getClass().getDeclaredField("baseUrl");
        baseUrlField.setAccessible(true);
        HttpUrl newHttpUrl = HttpUrl.parse(baseUrl);
        baseUrlField.set(retrofit, newHttpUrl);
        baseUrlField.setAccessible(false);
    }
    catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
        LOG.error("Exception while manipulating baseUrl=" + baseUrl + " to not end with a slash", e);
        throw new RuntimeException(e);
    }
}

service = retrofit.create(OaiPmhService.class);
// ...


问:
java ee - authenticate users using servlets
I just started learning java, and have not worked with java ee. I need to authenticate users using servlets. Advise, please, sample code and technical literature. Thank you!</p>

答:
create a html form that accept username / password.

post these data to a servlet.

in doPost() read these data from request check them against database.

set some parameter in session that will show your system that this user is authenticated and logged in.

Also See

Document

A Simple step by step example + tutorial


问:
Measure the execution time of a function call in Perl
Is it possible to execute staff only if the previous function is not over yet and the time is over
Something like:</p>

```<code>my $timeout = 10; # seconds
sub get_entities {
    # do staff ...
}
get_entities();

if (time == $timeout and get_entities is not over yet) {
    # do staff...
}
</code>```

答:
Have you tried this?

```<code>my $start = time;
get_entities();
my $duration = time - $start;
</code>```

Or were you looking for something more sophisticated?

Body:
Is it possible to execute staff only if the previous function is not over yet and the time is over
Something like:

my $timeout = 10; # seconds
sub get_entities {
    # do staff ...
}
get_entities();

if (time == $timeout and get_entities is not over yet) {
    # do staff...
}

Body:
Have you tried this?

my $start = time;
get_entities();
my $duration = time - $start;

Or were you looking for something more sophisticated?


问:
Help with mercurial repo problem
I have a repo in a condition I don't understand.  2 weeks ago, I tagged a release to mark a particular point I may have needed to go back to.  Later, I decided to branch, and have also been pulling in changes from another repo (the repo that I originally cloned).

The original rev that is of interest is 52:

```<code>changeset:   52:5044a88ba2a9
date:        Mon Jan 10 18:09:30 2011 -0500
</code>```

A few commits later, I branched into "MultiPartition"  (I should have done this immediately, but I didn't anticipate needing it).

After some more work, I pull changes from the sister repo (all the changes do not conflict with my work in the branch, so it's safe).

Here's what I see now:

```<code>$ hg branches
MultiPartition                75:9fd803c56505
default                       72:3939850a77e2 (inactive)
</code>```

Where I'm working in MultiPartition, and default is the tip from the sister repo.

If I look at the heads:

```<code>$ hg heads
changeset:   75:9fd803c56505
branch:      MultiPartition
tag:         tip
date:        Tue Jan 18 18:32:38 2011 -0500

changeset:   72:3939850a77e2
parent:      69:997a5b43216d
date:        Tue Jan 18 13:26:48 2011 -0500

changeset:   54:4ad1d36a79aa
date:        Thu Jan 13 19:14:57 2011 -0500
</code>```

there's rev 54 hanging out there, which I didn't (knowingly) mean to leave behind.

Here's where it gets strange:  The changeset 52 isn't in my current MultiPartition tip (though it was actually in the source on my disk, as I expected).  I've attached a graphlog of the changesets at the bottom.

If I use the hgcontains extension, I see:

```<code>$ hg headscontaining 52
changeset:   75:9fd803c56505
branch:      MultiPartition
tag:         tip
date:        Tue Jan 18 18:32:38 2011 -0500
</code>```

which tells me that the contents of rev 52 (which has new files I want in the current branch) should be in the tip of this branch. However, an hg update -C MultiPartition removes the new files from the directory I want them in.

If I use hgtk log and filter by the directory of interest, I see the 52 changeset which adds the files, but no newer changesets have any files removed from this directory.

The only thing that makes me wonder is this:  Changeset 71 was the merge from the original repo.  In that repo, those new files don't exist.  The log for that changset is:

```<code>| o  changeset:   71:ba4c67a24185
|/|  branch:      MultiPartition
| |  parent:      70:2dcbf69c325d
| |  parent:      69:997a5b43216d
| |  date:        Mon Jan 17 17:55:10 2011 -0500
</code>```

Here's my core question:

If parent 70: has what I expected, but parent 69: didn't, how is that resolved?

How can I check for other omissions?  Is there a way to see this sort of behavior?

I want to not have multiple heads, but I can't seem to "merge" them.  Technically, they are already merged (I think).  How should I clean this up?

Sorry if this is complex, but I don't know how else to ask the question except for giving a ton of info.

Full graphlog:

```<code>o  changeset:   75:9fd803c56505
|  branch:      MultiPartition
|  tag:         tip
|  date:        Tue Jan 18 18:32:38 2011 -0500
|
o    changeset:   74:be7df4e2579c
|\   branch:      MultiPartition
| |  parent:      73:3e7ac80ab37a
| |  parent:      72:3939850a77e2
| |  date:        Tue Jan 18 18:31:24 2011 -0500
| |
| o  changeset:   73:3e7ac80ab37a
| |  branch:      MultiPartition
| |  parent:      71:ba4c67a24185
| |  date:        Tue Jan 18 18:28:51 2011 -0500
| |
o |  changeset:   72:3939850a77e2
| |  parent:      69:997a5b43216d
| |  date:        Tue Jan 18 13:26:48 2011 -0500
| |
| o  changeset:   71:ba4c67a24185
|/|  branch:      MultiPartition
| |  parent:      70:2dcbf69c325d
| |  parent:      69:997a5b43216d
| |  date:        Mon Jan 17 17:55:10 2011 -0500
| |
| o  changeset:   70:2dcbf69c325d
| |  branch:      MultiPartition
| |  parent:      66:79272b7e7c01
| |  date:        Mon Jan 17 17:42:04 2011 -0500
| |
o |  changeset:   69:997a5b43216d
| |  date:        Mon Jan 17 12:00:09 2011 -0500
| |
o |  changeset:   68:b39f8a7af0c5
| |  date:        Sun Jan 16 20:23:43 2011 -0500
| |
o |  changeset:   67:63d3b40427e0
| |  parent:      58:29029a74e351
| |  date:        Sun Jan 16 18:07:49 2011 -0500
| |
| o  changeset:   66:79272b7e7c01
| |  branch:      MultiPartition
| |  date:        Mon Jan 17 09:43:32 2011 -0500
| |
| o  changeset:   65:b33eb978d647
| |  branch:      MultiPartition
| |  date:        Mon Jan 17 09:39:54 2011 -0500
| |
| o  changeset:   64:1fdafb6d0e84
| |  branch:      MultiPartition
| |  date:        Sun Jan 16 17:48:09 2011 -0500
| |
| o  changeset:   63:74942ab5113d
| |  branch:      MultiPartition
| |  date:        Sun Jan 16 17:46:15 2011 -0500
| |
| o  changeset:   62:2cd5a6d9d120
| |  branch:      MultiPartition
| |  date:        Sun Jan 16 01:55:23 2011 -0500
| |
| o  changeset:   61:acc73e7a35fc
|/|  branch:      MultiPartition
| |  parent:      60:c10e217081f0
| |  parent:      58:29029a74e351
| |  date:        Sun Jan 16 01:53:01 2011 -0500
| |
| o  changeset:   60:c10e217081f0
| |  branch:      MultiPartition
| |  date:        Sun Jan 16 01:45:16 2011 -0500
| |
| o  changeset:   59:2709b82b3ac0
| |  branch:      MultiPartition
| |  parent:      54:4ad1d36a79aa
| |  date:        Sun Jan 16 01:42:34 2011 -0500
| |
o |  changeset:   58:29029a74e351
| |  date:        Sun Jan 16 01:36:44 2011 -0500
| |
o |  changeset:   57:48840b75e37b
| |  date:        Fri Jan 14 11:04:06 2011 -0500
| |
o |  changeset:   56:dab5f0d40be9
| |  date:        Thu Jan 13 15:51:11 2011 -0500
| |
o |  changeset:   55:214ac45834fd
| |  parent:      51:7d0a1da31199
| |  date:        Wed Jan 12 16:49:00 2011 -0500
| |
| @  changeset:   54:4ad1d36a79aa
| |  date:        Thu Jan 13 19:14:57 2011 -0500
| |
| o  changeset:   53:8f06d69177d6
| |  date:        Thu Jan 13 14:02:42 2011 -0500
| |
| o  changeset:   52:5044a88ba2a9
|    date:        Mon Jan 10 18:09:30 2011 -0500
|
o
</code>```

答:
1: If parent 70: has what I expected, but parent 69: didn't, how is that resolved?

I guess the files got removed in either the 61 or 71 merge. You can check this in hgtk with the "diff to second parent" option.

3: I want to not have multiple heads, but I can't seem to "merge" them. Technically, they are already merged (I think). How should I clean this up?

On your default branch are two anonymous heads (54 and 72, where 72 is the tip of default), and they will stay open as long as the MultiPartition branch is not merged back into default. Depite being later merged in the MultiPartition branch, they are still heads of the default branch, because mercurial does not consider a follow-up branch as a new head of a branch. The reason for this treatment is that you typically want the latest revision the a branch when you hg update branch.

You can get rid of the two default heads when you merge MultiPartition back into default. When you are done with MultiPartition you can also close this branch with hg ci --close-branch (technically you cant remove the MultiPartition head, but when it is closed hg heads wont consider it as active head).

Title: Help with mercurial repo problem

Body:
I have a repo in a condition I don't understand.  2 weeks ago, I tagged a release to mark a particular point I may have needed to go back to.  Later, I decided to branch, and have also been pulling in changes from another repo (the repo that I originally cloned).

The original rev that is of interest is 52:

changeset:   52:5044a88ba2a9
date:        Mon Jan 10 18:09:30 2011 -0500

A few commits later, I branched into "MultiPartition"  (I should have done this immediately, but I didn't anticipate needing it).

After some more work, I pull changes from the sister repo (all the changes do not conflict with my work in the branch, so it's safe).

Here's what I see now:

$ hg branches
MultiPartition                75:9fd803c56505
default                       72:3939850a77e2 (inactive)

Where I'm working in MultiPartition, and default is the tip from the sister repo.

If I look at the heads:

$ hg heads
changeset:   75:9fd803c56505
branch:      MultiPartition
tag:         tip
date:        Tue Jan 18 18:32:38 2011 -0500

changeset:   72:3939850a77e2
parent:      69:997a5b43216d
date:        Tue Jan 18 13:26:48 2011 -0500

changeset:   54:4ad1d36a79aa
date:        Thu Jan 13 19:14:57 2011 -0500

there's rev 54 hanging out there, which I didn't (knowingly) mean to leave behind.

Here's where it gets strange:  The changeset 52 isn't in my current MultiPartition tip (though it was actually in the source on my disk, as I expected).  I've attached a graphlog of the changesets at the bottom.

If I use the hgcontains extension, I see:

$ hg headscontaining 52
changeset:   75:9fd803c56505
branch:      MultiPartition
tag:         tip
date:        Tue Jan 18 18:32:38 2011 -0500

which tells me that the contents of rev 52 (which has new files I want in the current branch) should be in the tip of this branch. However, an hg update -C MultiPartition removes the new files from the directory I want them in.

If I use hgtk log and filter by the directory of interest, I see the 52 changeset which adds the files, but no newer changesets have any files removed from this directory.

The only thing that makes me wonder is this:  Changeset 71 was the merge from the original repo.  In that repo, those new files don't exist.  The log for that changset is:

| o  changeset:   71:ba4c67a24185
|/|  branch:      MultiPartition
| |  parent:      70:2dcbf69c325d
| |  parent:      69:997a5b43216d
| |  date:        Mon Jan 17 17:55:10 2011 -0500

Here's my core question:

If parent 70: has what I expected, but parent 69: didn't, how is that resolved?

How can I check for other omissions?  Is there a way to see this sort of behavior?

I want to not have multiple heads, but I can't seem to "merge" them.  Technically, they are already merged (I think).  How should I clean this up?

Sorry if this is complex, but I don't know how else to ask the question except for giving a ton of info.

Full graphlog:

o  changeset:   75:9fd803c56505
|  branch:      MultiPartition
|  tag:         tip
|  date:        Tue Jan 18 18:32:38 2011 -0500
|
o    changeset:   74:be7df4e2579c
|\   branch:      MultiPartition
| |  parent:      73:3e7ac80ab37a
| |  parent:      72:3939850a77e2
| |  date:        Tue Jan 18 18:31:24 2011 -0500
| |
| o  changeset:   73:3e7ac80ab37a
| |  branch:      MultiPartition
| |  parent:      71:ba4c67a24185
| |  date:        Tue Jan 18 18:28:51 2011 -0500
| |
o |  changeset:   72:3939850a77e2
| |  parent:      69:997a5b43216d
| |  date:        Tue Jan 18 13:26:48 2011 -0500
| |
| o  changeset:   71:ba4c67a24185
|/|  branch:      MultiPartition
| |  parent:      70:2dcbf69c325d
| |  parent:      69:997a5b43216d
| |  date:        Mon Jan 17 17:55:10 2011 -0500
| |
| o  changeset:   70:2dcbf69c325d
| |  branch:      MultiPartition
| |  parent:      66:79272b7e7c01
| |  date:        Mon Jan 17 17:42:04 2011 -0500
| |
o |  changeset:   69:997a5b43216d
| |  date:        Mon Jan 17 12:00:09 2011 -0500
| |
o |  changeset:   68:b39f8a7af0c5
| |  date:        Sun Jan 16 20:23:43 2011 -0500
| |
o |  changeset:   67:63d3b40427e0
| |  parent:      58:29029a74e351
| |  date:        Sun Jan 16 18:07:49 2011 -0500
| |
| o  changeset:   66:79272b7e7c01
| |  branch:      MultiPartition
| |  date:        Mon Jan 17 09:43:32 2011 -0500
| |
| o  changeset:   65:b33eb978d647
| |  branch:      MultiPartition
| |  date:        Mon Jan 17 09:39:54 2011 -0500
| |
| o  changeset:   64:1fdafb6d0e84
| |  branch:      MultiPartition
| |  date:        Sun Jan 16 17:48:09 2011 -0500
| |
| o  changeset:   63:74942ab5113d
| |  branch:      MultiPartition
| |  date:        Sun Jan 16 17:46:15 2011 -0500
| |
| o  changeset:   62:2cd5a6d9d120
| |  branch:      MultiPartition
| |  date:        Sun Jan 16 01:55:23 2011 -0500
| |
| o  changeset:   61:acc73e7a35fc
|/|  branch:      MultiPartition
| |  parent:      60:c10e217081f0
| |  parent:      58:29029a74e351
| |  date:        Sun Jan 16 01:53:01 2011 -0500
| |
| o  changeset:   60:c10e217081f0
| |  branch:      MultiPartition
| |  date:        Sun Jan 16 01:45:16 2011 -0500
| |
| o  changeset:   59:2709b82b3ac0
| |  branch:      MultiPartition
| |  parent:      54:4ad1d36a79aa
| |  date:        Sun Jan 16 01:42:34 2011 -0500
| |
o |  changeset:   58:29029a74e351
| |  date:        Sun Jan 16 01:36:44 2011 -0500
| |
o |  changeset:   57:48840b75e37b
| |  date:        Fri Jan 14 11:04:06 2011 -0500
| |
o |  changeset:   56:dab5f0d40be9
| |  date:        Thu Jan 13 15:51:11 2011 -0500
| |
o |  changeset:   55:214ac45834fd
| |  parent:      51:7d0a1da31199
| |  date:        Wed Jan 12 16:49:00 2011 -0500
| |
| @  changeset:   54:4ad1d36a79aa
| |  date:        Thu Jan 13 19:14:57 2011 -0500
| |
| o  changeset:   53:8f06d69177d6
| |  date:        Thu Jan 13 14:02:42 2011 -0500
| |
| o  changeset:   52:5044a88ba2a9
|    date:        Mon Jan 10 18:09:30 2011 -0500
|
o


问:
Updating the structure of dynamic nested object
I have a nested object with the dynamic depth. I need to slightly alter it's structure.

For example I have an object like this :

```<code>let root = {
    data:{
      id:"5df6608a-59f0-42ac-9c2e-fb2a53df9008",
      name:"Product"
    },
    children:[
      {
         data:{
           id:"b527b1f5-4fd5-4f11-b4f1-6deeb33473d8",
           name:"productId"
         },
         children:[
           {
             data:{
               id:"7045051e-b97e-4836-9048-e93d72c75751",
               name:"rating"
             },
             children:[
               {
                  data:{
                    id:"88025b92-4309-4864-9c40-d4effd33a38b",
                    name:"ratingId"
                  },
                  children:[

                  ]
               }
             ]
           }
         ]
      }
    ]
  }
</code>```

The root object contains an object called data and an array of children which in turn has the same structure as the root object i need to remove the data object and move the id and name values which is inside the data object to the same level as children array as shown below.

```<code>let root = {
   id:"5df6608a-59f0-42ac-9c2e-fb2a53df9008",
   name:"Product",
   children:[
      {
         id:"b527b1f5-4fd5-4f11-b4f1-6deeb33473d8",
         name:"productId",
         children:[
           {
            id:"7045051e-b97e-4836-9048-e93d72c75751",
            name:"rating",
            children:[
               {
                  id:"88025b92-4309-4864-9c40-d4effd33a38b",
                  name:"ratingId",
                  children:[

                  ]
               }
             ]
           }
         ]
      }
    ]
}
</code>```

How can i do it using javascript?

So for i have written a method using which i can traverse the object up to depth of two levels but the object's depth is dynamic.

Below is the code that i have written in reactjs.

```<code>formateTreeChlidren(treeData){
    let rootObject = {
        name: treeData.data.name,
        id: treeData.data.id,
        children: []
    }
    let tempArray= [];
    treeData.children.map( child => {
        let childrenArray = [];
        if(child.children.length > 0){
            child.children.map( subChild => {
                let subChildObject= {
                    name: subChild.data.name,
                    id: subChild.data.id,
                    children:subChild.children
                }
                childrenArray.push(subChildObject);
            });
        }
        let childObject= {
            name: child.data.name,
            id: child.data.id,
            children:childrenArray
        }
        tempArray.push(childObject);
    });
    rootObject["children"] = tempArray;
}
</code>```

答:
Declare an interface for each node type

```<code>const OldNode = ( id , name , ...children ) =>
  ( { data : { id , name }
    , children : children
    }
  )

const NewNode = ( id , name , ...children ) =>
  ( { id
    , name
    , children
    }
  )
</code>```

Then make a function to convert between the two

```<code>const old2new = ( { data : { id = 0 , name = '' } , children = [] } )  =>
  NewNode ( id
          , name
          , children .map ( old2new )
          )
</code>```

Some dataset

```<code>const data0 =
  [ OldNode ( 1
            , 'a'
            , OldNode ( 2 , 'b' )
            , OldNode ( 3 , 'c' )
            )
  , OldNode ( 4
            , 'd'
            , OldNode ( 5 , 'e' )
            , OldNode ( 6 , 'f' )
            )
  ]

console.log (data0)
// [ { data: { id : 1
//           , name : 'a'
//           }
//   , children : [ { data : { id : 2
//                           , name : 'b'
//                           }
//                  , children : []
//                  }
//                , { data : { id : 3
//                           , name : 'c'
//                           }
//                   , children : []
//                  }
//                ]
//   }
// , { data : { id : 4
//            , name : 'd'
//            }
//   , children : [ { data : { id : 5
//                           , name : 'e'
//                           }
//                  , children : []
//                  }
//                , { data : { id : 6
//                           , name : 'f'
//                           }
//                  , children : []
//                  }
//                ]
//   }
// ]
</code>```

Transform using Array.prototype.map

```<code>const data1 =
  data0 .map ( old2new )

console.log (data1)
// [ { id : 1
//   , name : 'a'
//   , children : [ { id : 2
//                  , name : 'b'
//                  , children : []
//                  }
//                , { id : 3
//                  , name : 'c'
//                  , children : []
//                  }
//                ]
//   }
// , { id : 4
//   , name : 'd'
//   , children : [ { id : 5
//                  , name : 'e'
//                  , children : []
//                  }
//                , { id : 6
//                  , name : 'f'
//                  , children : []
//                  }
//                ]
//   }
// ]
</code>```

Code demo

const OldNode = ( id , name , ...children ) =>
  ( { data : { id , name }
    , children : children
    }
  )

const NewNode = ( id , name , ...children ) =>
  ( { id
    , name
    , children
    }
  )

const old2new = ( { data : { id = 0 , name = '' } , children = [] } )  =>
  NewNode ( id
          , name
          , children .map ( old2new )
          )

const data0 =
  [ OldNode ( 1
            , 'a'
            , OldNode ( 2 , 'b' )
            , OldNode ( 3 , 'c' )
            )
  , OldNode ( 4
            , 'd'
            , OldNode ( 5 , 'e' )
            , OldNode ( 6 , 'f' )
            )
  ]

const data1 =
  data0 .map ( old2new )

console.log (data1)
// [ { id : 1
//   , name : 'a'
//   , children : [ { id : 2
//                 , name : 'b'
//                 , children : []
//                 }
//               , { id : 3
//                 , name : 'c'
//                 , children : []
//                 }
//               ]
//   }
// , { id : 4
//   , name : 'd'
//   , children : [ { id : 5
//                 , name : 'e'
//                 , children : []
//                 }
//               , { id : 6
//                 , name : 'f'
//                 , children : []
//                 }
//               ]
//   }
// ]```

Body:
I have a nested object with the dynamic depth. I need to slightly alter it's structure.

For example I have an object like this :

let root = {
    data:{
      id:"5df6608a-59f0-42ac-9c2e-fb2a53df9008",
      name:"Product"
    },
    children:[
      {
         data:{
           id:"b527b1f5-4fd5-4f11-b4f1-6deeb33473d8",
           name:"productId"
         },
         children:[
           {
             data:{
               id:"7045051e-b97e-4836-9048-e93d72c75751",
               name:"rating"
             },
             children:[
               {
                  data:{
                    id:"88025b92-4309-4864-9c40-d4effd33a38b",
                    name:"ratingId"
                  },
                  children:[

                  ]
               }
             ]
           }
         ]
      }
    ]
  }

The root object contains an object called data and an array of children which in turn has the same structure as the root object i need to remove the data object and move the id and name values which is inside the data object to the same level as children array as shown below.

let root = {
   id:"5df6608a-59f0-42ac-9c2e-fb2a53df9008",
   name:"Product",
   children:[
      {
         id:"b527b1f5-4fd5-4f11-b4f1-6deeb33473d8",
         name:"productId",
         children:[
           {
            id:"7045051e-b97e-4836-9048-e93d72c75751",
            name:"rating",
            children:[
               {
                  id:"88025b92-4309-4864-9c40-d4effd33a38b",
                  name:"ratingId",
                  children:[

                  ]
               }
             ]
           }
         ]
      }
    ]
}

How can i do it using javascript?

So for i have written a method using which i can traverse the object up to depth of two levels but the object's depth is dynamic.

Below is the code that i have written in reactjs.

formateTreeChlidren(treeData){
    let rootObject = {
        name: treeData.data.name,
        id: treeData.data.id,
        children: []
    }
    let tempArray= [];
    treeData.children.map( child => {
        let childrenArray = [];
        if(child.children.length > 0){
            child.children.map( subChild => {
                let subChildObject= {
                    name: subChild.data.name,
                    id: subChild.data.id,
                    children:subChild.children
                }
                childrenArray.push(subChildObject);
            });
        }
        let childObject= {
            name: child.data.name,
            id: child.data.id,
            children:childrenArray
        }
        tempArray.push(childObject);
    });
    rootObject["children"] = tempArray;
}

Body:
Declare an interface for each node type

const OldNode = ( id , name , ...children ) =>
  ( { data : { id , name }
    , children : children
    }
  )

const NewNode = ( id , name , ...children ) =>
  ( { id
    , name
    , children
    }
  )

Then make a function to convert between the two

const old2new = ( { data : { id = 0 , name = '' } , children = [] } )  =>
  NewNode ( id
          , name
          , children .map ( old2new )
          )

Some dataset

const data0 =
  [ OldNode ( 1
            , 'a'
            , OldNode ( 2 , 'b' )
            , OldNode ( 3 , 'c' )
            )
  , OldNode ( 4
            , 'd'
            , OldNode ( 5 , 'e' )
            , OldNode ( 6 , 'f' )
            )
  ]

console.log (data0)
// [ { data: { id : 1
//           , name : 'a'
//           }
//   , children : [ { data : { id : 2
//                           , name : 'b'
//                           }
//                  , children : []
//                  }
//                , { data : { id : 3
//                           , name : 'c'
//                           }
//                   , children : []
//                  }
//                ]
//   }
// , { data : { id : 4
//            , name : 'd'
//            }
//   , children : [ { data : { id : 5
//                           , name : 'e'
//                           }
//                  , children : []
//                  }
//                , { data : { id : 6
//                           , name : 'f'
//                           }
//                  , children : []
//                  }
//                ]
//   }
// ]

Transform using Array.prototype.map

const data1 =
  data0 .map ( old2new )

console.log (data1)
// [ { id : 1
//   , name : 'a'
//   , children : [ { id : 2
//                  , name : 'b'
//                  , children : []
//                  }
//                , { id : 3
//                  , name : 'c'
//                  , children : []
//                  }
//                ]
//   }
// , { id : 4
//   , name : 'd'
//   , children : [ { id : 5
//                  , name : 'e'
//                  , children : []
//                  }
//                , { id : 6
//                  , name : 'f'
//                  , children : []
//                  }
//                ]
//   }
// ]

Code demo

const OldNode = ( id , name , ...children ) =>
  ( { data : { id , name }
    , children : children
    }
  )

const NewNode = ( id , name , ...children ) =>
  ( { id
    , name
    , children
    }
  )

const old2new = ( { data : { id = 0 , name = '' } , children = [] } )  =>
  NewNode ( id
          , name
          , children .map ( old2new )
          )

const data0 =
  [ OldNode ( 1
            , 'a'
            , OldNode ( 2 , 'b' )
            , OldNode ( 3 , 'c' )
            )
  , OldNode ( 4
            , 'd'
            , OldNode ( 5 , 'e' )
            , OldNode ( 6 , 'f' )
            )
  ]

const data1 =
  data0 .map ( old2new )

console.log (data1)
// [ { id : 1
//   , name : 'a'
//   , children : [ { id : 2
//                 , name : 'b'
//                 , children : []
//                 }
//               , { id : 3
//                 , name : 'c'
//                 , children : []
//                 }
//               ]
//   }
// , { id : 4
//   , name : 'd'
//   , children : [ { id : 5
//                 , name : 'e'
//                 , children : []
//                 }
//               , { id : 6
//                 , name : 'f'
//                 , children : []
//                 }
//               ]
//   }
// ]


问:
How to add an object to file every time i run my program in java
I Have 3 objects of Person type and i write them to my file Person.person and than i read them one by one but when i run my program again i get the same 3 objets written as when i run it for the firts time.How to add those 3 objects to  my file again and again every time i run my program.I want from it to be the same 3 objects or some other objects but they need to be added to the end of my file.

And how to get that data when i want to read that file?

```<code> package pisanjeUFajl;

 import java.io.BufferedInputStream;
 import java.io.BufferedOutputStream;
 import java.io.EOFException;
 import java.io.File;
 import java.io.FileInputStream;
 import java.io.FileOutputStream;
 import java.io.IOException;
 import java.io.ObjectInputStream;
 import java.io.ObjectOutputStream;
 import java.util.List;

 public class Serilizacija {
 public static void main(String[] args) throws IOException,
 ClassNotFoundException {

    Person person = new Person("Jovan", "Dukic");
    Person person2 = new Person("Stanko", "Maca");
    Person person3 = new Person("Tole", "Lopove");

    File file = new File("C:\\Users\\Jovan\\Desktop\\Person.person");
    if (!(file.exists())) {
        file.createNewFile();
    }

    ObjectOutputStream outputStream = null;

    outputStream = new ObjectOutputStream(new BufferedOutputStream(new
    FileOutputStream(file)));

    outputStream.writeObject(person);
    outputStream.reset();
    outputStream.writeObject(person2);
    outputStream.reset();
    outputStream.writeObject(person3);
    outputStream.reset();

    outputStream.close();

    ObjectInputStream inputStream = null;

    inputStream = new ObjectInputStream(new BufferedInputStream(new
    FileInputStream(file)));
    int count = 0;
    Person object = null;
</code>```

I added more objects to my file but when i wanted to read them i got and error:
Exception in thread "main" java.io.StreamCorruptedException:
 invalid typecode:AC

```<code>at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
at pisanjeUFajl.Serilizacija.main(Serilizacija.java:46)
</code>```

It read just the first 3 objects which were added the first to my file.

```<code>    try {
        while (true) {
            object = (Person) inputStream.readObject();
            count++;
            System.out.println(object);

        }
    } catch (EOFException error) {
        System.out.println("\nEnd of file reacher - objects read = " +
    count);
    }

    inputStream.close();
}
</code>```

}

答:
Use the Constructor of FileOutputStream that accepts a boolean as a parameter.
If its set to true, everything written to file through this Stream is appended to the existing content. Constructor looks like this:</p>

```<code>    FileOutputStream(File file, boolean append)
</code>```

Body:
I Have 3 objects of Person type and i write them to my file Person.person and than i read them one by one but when i run my program again i get the same 3 objets written as when i run it for the firts time.How to add those 3 objects to  my file again and again every time i run my program.I want from it to be the same 3 objects or some other objects but they need to be added to the end of my file.

And how to get that data when i want to read that file?

 package pisanjeUFajl;

 import java.io.BufferedInputStream;
 import java.io.BufferedOutputStream;
 import java.io.EOFException;
 import java.io.File;
 import java.io.FileInputStream;
 import java.io.FileOutputStream;
 import java.io.IOException;
 import java.io.ObjectInputStream;
 import java.io.ObjectOutputStream;
 import java.util.List;

 public class Serilizacija {
 public static void main(String[] args) throws IOException,
 ClassNotFoundException {

    Person person = new Person("Jovan", "Dukic");
    Person person2 = new Person("Stanko", "Maca");
    Person person3 = new Person("Tole", "Lopove");

    File file = new File("C:\\Users\\Jovan\\Desktop\\Person.person");
    if (!(file.exists())) {
        file.createNewFile();
    }

    ObjectOutputStream outputStream = null;

    outputStream = new ObjectOutputStream(new BufferedOutputStream(new
    FileOutputStream(file)));

    outputStream.writeObject(person);
    outputStream.reset();
    outputStream.writeObject(person2);
    outputStream.reset();
    outputStream.writeObject(person3);
    outputStream.reset();

    outputStream.close();

    ObjectInputStream inputStream = null;

    inputStream = new ObjectInputStream(new BufferedInputStream(new
    FileInputStream(file)));
    int count = 0;
    Person object = null;

I added more objects to my file but when i wanted to read them i got and error:
Exception in thread "main" java.io.StreamCorruptedException:
 invalid typecode:AC

at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
at pisanjeUFajl.Serilizacija.main(Serilizacija.java:46)

It read just the first 3 objects which were added the first to my file.

    try {
        while (true) {
            object = (Person) inputStream.readObject();
            count++;
            System.out.println(object);

        }
    } catch (EOFException error) {
        System.out.println("\nEnd of file reacher - objects read = " +
    count);
    }

    inputStream.close();
}

}

Body:
Use the Constructor of FileOutputStream that accepts a boolean as a parameter.
If its set to true, everything written to file through this Stream is appended to the existing content. Constructor looks like this:

    FileOutputStream(File file, boolean append)


问:
link between two columns when generating random data
I have a spreadsheet of words in German and English.

For example:

```<code>          A          B           C          D
1     Hallo         Hello                  random word
2     Blau          Blue
3     Hund          Dog
4     Blumen        Flowers
5     Auto          Car
</code>```

And in a random cell (say in cell D1) I can generate a random german word from column A using:

```<code>=INDEX($A:$A|RANDBETWEEN(1|COUNTA($A:$A))|1)
</code>```

Now in E1, I want to print the appropriate english word. So when we press F9 and generate a new random word, I always get the correction translation.

Any suggestions on how to make this link?

答:
In cell E1 you can do this:

```<code>= INDEX($B:$B,MATCH(D1,$A:$A,0))
</code>```

Although it is recommended to reduce the full-column arrays down to the end of your data. (e.g. if you have 100 rows of data, change to $A$1:$A$100)

Body:
I have a spreadsheet of words in German and English.

For example:

          A          B           C          D
1     Hallo         Hello                  random word
2     Blau          Blue
3     Hund          Dog
4     Blumen        Flowers
5     Auto          Car

And in a random cell (say in cell D1) I can generate a random german word from column A using:

=INDEX($A:$A|RANDBETWEEN(1|COUNTA($A:$A))|1)

Now in E1, I want to print the appropriate english word. So when we press F9 and generate a new random word, I always get the correction translation.

Any suggestions on how to make this link?

Body:
In cell E1 you can do this:

= INDEX($B:$B,MATCH(D1,$A:$A,0))

Although it is recommended to reduce the full-column arrays down to the end of your data. (e.g. if you have 100 rows of data, change to $A$1:$A$100)