问:
Catch the value returning from Django in HTML/JavaScript
I have created a django API, which is returning a json object. And then I have a separate web application from which I am calling the django API. Now I want to store/catch the returned Json object in my HTML/Javascript.

Here's the code I am using

HTML Code

```<code><div >
    <form acton="http://xx.xxx.xx.xxx:xxxx/export" method="POST">
        <label class="optinLabel">Project Name</label>
        <input type="text" placeholder="confirm your project name"/>
        <label class="optionLabel">Downlaod</label>
        <input  type="submit" value="Json" style="color:red" />
    </form>
</div>
</code>```

Django views.py

```<code>def export(request):
    if request.method == "POST":
        projectname = request.POST.get('projectname')
        folderpath = "/home/data"
        finalpath = os.path.join(folderpath,projectname)
        json_result = ann_json(finalpath)

    return JsonResponse({"response":json_result})
</code>```

Here the view.py returning the Json, how will catch that in my HTML Code?
Any help will be appreciated.

答:
you can use javascript to store your data in a variable or use localStorage to cache the data, and to get the data from your API I recommend to use fetch API.

```<code>fetch('http://xx.xxx.xx.xxx:xxxx/export')
        .then((response) => return response.json())
        .then((data) => {
                localStorage.setItem('data', data)
        })

</code>```

but as far as I'm concerned using API is mostly used for web applications, not just regular website

Body:
I have created a django API, which is returning a json object. And then I have a separate web application from which I am calling the django API. Now I want to store/catch the returned Json object in my HTML/Javascript.

Here's the code I am using

HTML Code

    <form acton="http://xx.xxx.xx.xxx:xxxx/export" method="POST">
        Project Name
        <input type="text" placeholder="confirm your project name"/>
        Downlaod
        <input  type="submit" value="Json" style="color:red" />
    </form>

Django views.py

def export(request):
    if request.method == "POST":
        projectname = request.POST.get('projectname')
        folderpath = "/home/data"
        finalpath = os.path.join(folderpath,projectname)
        json_result = ann_json(finalpath)

    return JsonResponse({"response":json_result})

Here the view.py returning the Json, how will catch that in my HTML Code?
Any help will be appreciated.

Body:
you can use javascript to store your data in a variable or use localStorage to cache the data, and to get the data from your API I recommend to use fetch API.

fetch('http://xx.xxx.xx.xxx:xxxx/export')
        .then((response) => return response.json())
        .then((data) => {
                localStorage.setItem('data', data)
        })

but as far as I'm concerned using API is mostly used for web applications, not just regular website


来源: stackexchange

问:
python installation fails with File "setup.py", line 1023, SyntaxError: invalid syntax
I am trying to install python3.8.1 on a RHEL 7 server. It is an offline installation.
The python folder is untared and stored in a folder in the server.
After redirecting myself into the folder where the setup.py file is located. I run

master1 Python-3.8.1]$ sudo python setup.py install-sh

```<code>  File "setup.py", line 1023
    libraries=[panel_library, *curses_libs]))
                              ^
SyntaxError: invalid syntax
</code>```

I cant find a solution. Appreciate help

答:
You are trying to install python with source code zipped in tgz. So, you will need to compile it and then install it.

Once you unzip, refer readme.rst file.

Build Instructions

On Unix, Linux, BSD, macOS, and Cygwin::

```<code>./configure
make
make test
sudo make install
</code>```

This will install Python as python3.

I think you are using command to install packages offline using setup.py, that won't work for python fresh installation

ContentLicense: CC BY-SA 4.0

Body:
I am trying to install python3.8.1 on a RHEL 7 server. It is an offline installation.
The python folder is untared and stored in a folder in the server.
After redirecting myself into the folder where the setup.py file is located. I run

master1 Python-3.8.1]$ sudo python setup.py install-sh

  File "setup.py", line 1023
    libraries=[panel_library, *curses_libs]))
                              ^
SyntaxError: invalid syntax

I cant find a solution. Appreciate help

Body:
You are trying to install python with source code zipped in tgz. So, you will need to compile it and then install it.

Once you unzip, refer readme.rst file.

Build Instructions

On Unix, Linux, BSD, macOS, and Cygwin::

./configure
make
make test
sudo make install

This will install Python as python3.

I think you are using command to install packages offline using setup.py, that won't work for python fresh installation


问:
I'm not able to upload ipa file to apple store. Any suggestions?
I've uploaded non-Xcode builds with xcrun altool --upload-app -f path-to-build.ipa -u your-account@apple.com. It won't show any progress, but you can see the network traffic in Activity Monitor. It finishes with No errors uploading 'path-to-build.ipa'.</p>

答: While we are using xcrun commands to upload app, it will not show any progress and if you are getting this "No errors uploading 'path-to-build.ipa'.", it means your iPad is uploaded successfully, so please check your developer account for the application you will see uploaded builds.</p>


问:
How use image in api get by axios request in html tags in ReactJS?
I use axios to get data from the api, now I need to display the image in the td tag in HTML, the text response are working fine but the image is not displaying.

my request code is:

```<code>componentDidMount(){

      var headers = {
        "Content-Type":"application/json",
        "AccessToken":localStorage.TOKEN,
      }

      axios.get(window.$_APIurl+"myProviders/5e463d53e7179a2f011c4104", {headers: headers})
        .then((response) => {
          console.log(response.data[0].provider.image);
          const doctor = response.data[0].provider.image;
        if(response.data.length > 0)   this.setState({"listOfProviders": response.data});
      })
  }
</code>```

My html to use is:

```<code>  {this.state.listOfProviders.length > 0 ?
                      <tbody>
                        {this.state.listOfProviders.map((providerData,indx)=>
                          <tr>
                            <td className="font-weight-medium"> <img className="logo" src={doctor} alt="pam-logo" /> {providerData.provider.firstName} {providerData.provider.lastName} </td>
                            <td>{providerData.provider.email}</td>
                            <td>{providerData.provider.phoneNumber}</td>
                            <td>{(providerData.provider.specialities)}</td>
                            <td > {providerData.provider.qbid}</td>
                            <td> Mountain view,Ave </td>
                            <td><Icon icon={editIcon} width="20px"/>  <Icon icon={deleteIcon} width="20px"/></td>

                        </tr>
                        )}
                      </tbody>
</code>```

I need image in src tag.

答: I guess doctor vairable scoping problem. As you are declaring this  const doctor = response.data[0].provider.image; in componentDidMount but you are accessing from another place. </p>

Body:
I use axios to get data from the api, now I need to display the image in the td tag in HTML, the text response are working fine but the image is not displaying.

my request code is:

componentDidMount(){

      var headers = {
        "Content-Type":"application/json",
        "AccessToken":localStorage.TOKEN,
      }

      axios.get(window.$_APIurl+"myProviders/5e463d53e7179a2f011c4104", {headers: headers})
        .then((response) => {
          console.log(response.data[0].provider.image);
          const doctor = response.data[0].provider.image;
        if(response.data.length > 0)   this.setState({"listOfProviders": response.data});
      })
  }

My html to use is:

  {this.state.listOfProviders.length > 0 ?

                        {this.state.listOfProviders.map((providerData,indx)=>

                              {providerData.provider.firstName} {providerData.provider.lastName}
                            {providerData.provider.email}
                            {providerData.provider.phoneNumber}
                            {(providerData.provider.specialities)}
                             {providerData.provider.qbid}
                             Mountain view,Ave
                            <Icon icon={editIcon} width="20px"/>  <Icon icon={deleteIcon} width="20px"/>

                        )}

I need image in src tag.


问:
Run Powershell script to show a form without Powershell screen at the back
I have a powershell script that can be run locally on a Workstation or remotely using PSEXEC tool, that shows a dialog box to console user that the PC is going to be rebooted in X amount of time and timer. The dialog box cannot be closed, only be minimized (this is as per code). However when I run it, it also shows Powershell screen at the back of dialog box and closing it also closes the form.

I tried Powershell switches [-NoLogo], [-NonInteractive], [-WindowStyle Hidden], it doesn't work.

This is the custom-restart script:

```<code>Function Create-GetSchedTime {
Param(
$SchedTime
)
      $script:StartTime = (Get-Date).AddSeconds($TotalTime)
      $RestartDate = ((get-date).AddSeconds($TotalTime)).AddMinutes(-5)
      $RDate = (Get-Date $RestartDate -f 'dd.MM.yyyy') -replace "\.","/"      # 16/03/2016
      $RTime = Get-Date $RestartDate -f 'HH:mm'                                    # 09:31
      #&schtasks /delete /tn "Post Maintenance Restart" /f
      #&schtasks /create /sc once /tn "Post Maintenance Restart" /tr "'C:\Windows\system32\cmd.exe' /c shutdown -r -f -t 300" /SD $RDate /ST $RTime /f
}
[System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") | Out-Null
[System.Reflection.Assembly]::LoadWithPartialName( "Microsoft.VisualBasic") | Out-Null
$Title = "Computer Reboot Notification"
$Message = "Your computer will automatically restart in :"
$Button1Text = "Restart now"
$Button2Text = "Postpone for 1 hour"
$Button3Text = "Postpone for 4 hours"
$Form = $null
$Button1 = $null
$Button2 = $null
$Label = $null
$TextBox = $null
$Result = $null
$timerUpdate = New-Object 'System.Windows.Forms.Timer'
#$TotalTime = 14400 #in seconds
$TotalTime = 60 #in seconds
Create-GetSchedTime -SchedTime $TotalTime
$timerUpdate_Tick={
      # Define countdown timer
      [TimeSpan]$span = $script:StartTime - (Get-Date)
      # Update the display
      $hours = "{0:00}" -f $span.Hours
      $mins = "{0:00}" -f $span.Minutes
    $secs = "{0:00}" -f $span.Seconds
    $labelTime.Text = "{0}:{1}:{2}" -f $hours, $mins, $secs
      $timerUpdate.Start()
      if ($span.TotalSeconds -le 0)
      {
            $timerUpdate.Stop()
            &schtasks /delete /tn "Post Maintenance Restart" /f
            shutdown -r -f /t 0
      }
}
$Form_StoreValues_Closing=
      {
            #Store the control values
      }

$Form_Cleanup_FormClosed=
      {
            #Remove all event handlers from the controls
            try
            {
                  $Form.remove_Load($Form_Load)
                  $timerUpdate.remove_Tick($timerUpdate_Tick)
                  #$Form.remove_Load($Form_StateCorrection_Load)
                  $Form.remove_Closing($Form_StoreValues_Closing)
                  $Form.remove_FormClosed($Form_Cleanup_FormClosed)
            }
            catch [Exception]
            { }
      }

# Form
$Form = New-Object -TypeName System.Windows.Forms.Form
$Form.Text = $Title
$Form.Size = New-Object -TypeName System.Drawing.Size(407,205)
$Form.StartPosition = "CenterScreen"
$Form.Topmost = $true
$Form.KeyPreview = $true
$Form.ShowInTaskbar = $Formalse
$Form.FormBorderStyle = "FixedDialog"
$Form.MaximizeBox = $Formalse
$Form.MinimizeBox = $true
$Icon = [system.drawing.icon]::ExtractAssociatedIcon("c:\Windows\System32\UserAccountControlSettings.exe")
$Form.Icon = $Icon

# Button One (Reboot/Shutdown Now)
$Button1 = New-Object -TypeName System.Windows.Forms.Button
$Button1.Size = New-Object -TypeName System.Drawing.Size(90,25)
$Button1.Location = New-Object -TypeName System.Drawing.Size(10,135)
$Button1.Text = $Button1Text
$Button1.Font = 'Tahoma, 10pt'
$Button1.Add_Click({
      &schtasks /delete /tn "Post Maintenance Restart" /f
      shutdown -r -f /t 0
      $Form.Close()
})
$Form.Controls.Add($Button1)
# Button Two (Postpone for 1 Hour)
$Button2 = New-Object -TypeName System.Windows.Forms.Button
$Button2.Size = New-Object -TypeName System.Drawing.Size(133,25)
$Button2.Location = New-Object -TypeName System.Drawing.Size(105,135)
$Button2.Text = $Button2Text
$Button2.Font = 'Tahoma, 10pt'
$Button2.Add_Click({
      $Button2.Enabled = $False
      $timerUpdate.Stop()
      #$TotalTime = 3600
      $TotalTime = 30
      Create-GetSchedTime -SchedTime $TotalTime
      $timerUpdate.add_Tick($timerUpdate_Tick)
      $timerUpdate.Start()
})
$Form.Controls.Add($Button2)

# Button Three (Postpone for 4 Hours)
$Button3 = New-Object -TypeName System.Windows.Forms.Button
$Button3.Size = New-Object -TypeName System.Drawing.Size(140,25)
$Button3.Location = New-Object -TypeName System.Drawing.Size(243,135)
$Button3.Text = $Button3Text
$Button3.Font = 'Tahoma, 10pt'
$Button3.Add_Click({
      $Button2.Enabled = $False
      $timerUpdate.Stop()
      $TotalTime = 14400
      Create-GetSchedTime -SchedTime $TotalTime
      $timerUpdate.add_Tick($timerUpdate_Tick)
      $timerUpdate.Start()
})
$Form.Controls.Add($Button3)
$Button3.Enabled = $False

# Label
$Label = New-Object -TypeName System.Windows.Forms.Label
$Label.Size = New-Object -TypeName System.Drawing.Size(330,25)
$Label.Location = New-Object -TypeName System.Drawing.Size(10,15)
$Label.Text = $Message
$label.Font = 'Tahoma, 10pt'
$Form.Controls.Add($Label)

# Label2
$Label2 = New-Object -TypeName System.Windows.Forms.Label
$Label2.Size = New-Object -TypeName System.Drawing.Size(355,30)
$Label2.Location = New-Object -TypeName System.Drawing.Size(10,100)
$Label2.Text = $Message2
$label2.Font = 'Tahoma, 10pt'
$Form.Controls.Add($Label2)

# labelTime
$labelTime = New-Object 'System.Windows.Forms.Label'
$labelTime.AutoSize = $True
$labelTime.Font = 'Arial, 26pt, style=Bold'
$labelTime.Location = '120, 60'
$labelTime.Name = 'labelTime'
$labelTime.Size = '43, 15'
$labelTime.TextAlign = 'MiddleCenter'
$labelTime.ForeColor = "Red"
$Form.Controls.Add($labelTime)

#Start the timer
$timerUpdate.add_Tick($timerUpdate_Tick)
$timerUpdate.Start()
# Show
$Form.Add_Shown({$Form.Activate()})
#Clean up the control events
$Form.add_FormClosed($Form_Cleanup_FormClosed)
#Store the control values when form is closing
#$Form.add_Closing($Form_StoreValues_Closing)
$Form.Add_Closing({$_.cancel = $true})
#Show the Form
$Form.ShowDialog() | Out-Null
#$Form.Focused
#return $Form.ShowDialog()

#$Form.Add_Closing({$_.cancel = $false})
#Show the Form
#return $Form.ShowDialog()
</code>```

答:
Eventually I found out the issue. I was putting "-WindowStyle Hidden" at the end of command, not after Powershell. So this didn't work.

```<code>Powershell -File CustomRestart.ps1 -WindowStyle Hidden
</code>```

This worked, also with PSEXEC.

```<code>Powershell -WindowStyle Hidden -File CustomRestart.ps1
</code>```

Now I added a YES/No confirmation dialog box after user clicks on "Restart Now" button, if clicks Yes, it will reboot, if no, then nothing, just confirmation box disappears. If you look at the $Button1.Add_Click event, there is the code.

Problem is: when I run it on Pwershell ISE, its doing fine (confirmation box shows-up and works), but when running from Command or Run menu, it won't show confirmation box, and thus no effect after clicking "Restart Now" button.

Here is the complete code:

```<code>Function Create-GetSchedTime {
Param(
$SchedTime
)
      $script:StartTime = (Get-Date).AddSeconds($TotalTime)
      $RestartDate = ((get-date).AddSeconds($TotalTime)).AddMinutes(-5)
      $RDate = (Get-Date $RestartDate -f 'dd.MM.yyyy') -replace "\.","/"      # 16/03/2016
      $RTime = Get-Date $RestartDate -f 'HH:mm'                                    # 09:31
      #&schtasks /delete /tn "Post Maintenance Restart" /f
      #&schtasks /create /sc once /tn "Post Maintenance Restart" /tr "'C:\Windows\system32\cmd.exe' /c shutdown -r -f -t 300" /SD $RDate /ST $RTime /f
}
[System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") | Out-Null
[System.Reflection.Assembly]::LoadWithPartialName( "Microsoft.VisualBasic") | Out-Null
$Title = "Computer Reboot Notification"
#$Message = "Your computer will automatically restart in :"
$Message = "Your computer has been updated with latest software and requires a reboot. Please save your work and click ""Restart now"" to reboot it now.`nYour computer will automatically reboot in :"
$Button1Text = "Restart now"
$Button2Text = "Postpone for 1 hour"
$Button3Text = "Postpone for 4 hours"
$Form = $null
$Button1 = $null
$Button2 = $null
$Label = $null
$TextBox = $null
$Result = $null
$timerUpdate = New-Object 'System.Windows.Forms.Timer'
$TotalTime = 14400 #in seconds
#$TotalTime = 60 #in seconds
Create-GetSchedTime -SchedTime $TotalTime
$timerUpdate_Tick={
      # Define countdown timer
      [TimeSpan]$span = $script:StartTime - (Get-Date)
      # Update the display
      $hours = "{0:00}" -f $span.Hours
      $mins = "{0:00}" -f $span.Minutes
    $secs = "{0:00}" -f $span.Seconds
    $labelTime.Text = "{0}:{1}:{2}" -f $hours, $mins, $secs
      $timerUpdate.Start()
      if ($span.TotalSeconds -le 0)
      {
            $timerUpdate.Stop()
            #&schtasks /delete /tn "Post Maintenance Restart" /f
            shutdown -r -f /t 0
      }
}
$Form_StoreValues_Closing=
      {
            #Store the control values
      }

$Form_Cleanup_FormClosed=
      {
            #Remove all event handlers from the controls
            try
            {
                  $Form.remove_Load($Form_Load)
                  $timerUpdate.remove_Tick($timerUpdate_Tick)
                  #$Form.remove_Load($Form_StateCorrection_Load)
                  $Form.remove_Closing($Form_StoreValues_Closing)
                  $Form.remove_FormClosed($Form_Cleanup_FormClosed)
            }
            catch [Exception]
            { }
      }

# Form
$Form = New-Object -TypeName System.Windows.Forms.Form
$Form.Text = $Title
$Form.Size = New-Object -TypeName System.Drawing.Size(407,205)
$Form.StartPosition = "CenterScreen"
$Form.Topmost = $true
$Form.KeyPreview = $true
$Form.ShowInTaskbar = $Formalse
$Form.FormBorderStyle = "FixedDialog"
$Form.MaximizeBox = $Formalse
$Form.MinimizeBox = $true
$Icon = [system.drawing.icon]::ExtractAssociatedIcon("c:\Windows\System32\UserAccountControlSettings.exe")
$Form.Icon = $Icon

# Button One (Reboot/Shutdown Now)
$Button1 = New-Object -TypeName System.Windows.Forms.Button
$Button1.Size = New-Object -TypeName System.Drawing.Size(90,25)
#$Button1.Location = New-Object -TypeName System.Drawing.Size(10,135)
$Button1.Location = New-Object -TypeName System.Drawing.Size(10,145)
$Button1.Text = $Button1Text
$Button1.Font = 'Tahoma, 10pt'
$Button1.Add_Click({

    $msgBoxInput =  [System.Windows.MessageBox]::Show('Are you sure you want to reboot now?','Computer Reboot Confirmation','YesNo','Warning')
    switch  ($msgBoxInput) {
        'Yes' {
            shutdown -r -f /t 0
            $Form.Close()
              }

        'No' {
          ## Do something
            }
                            }

})
$Form.Controls.Add($Button1)
# Button Two (Postpone for 1 Hour)
$Button2 = New-Object -TypeName System.Windows.Forms.Button
$Button2.Size = New-Object -TypeName System.Drawing.Size(133,25)
#$Button2.Location = New-Object -TypeName System.Drawing.Size(105,135)
$Button2.Location = New-Object -TypeName System.Drawing.Size(105,145)
$Button2.Text = $Button2Text
$Button2.Font = 'Tahoma, 10pt'
$Button2.Add_Click({
      $Button2.Enabled = $False
      $timerUpdate.Stop()
      $TotalTime = 3600
      #$TotalTime = 30
      Create-GetSchedTime -SchedTime $TotalTime
      $timerUpdate.add_Tick($timerUpdate_Tick)
      $timerUpdate.Start()
})
$Form.Controls.Add($Button2)

# Button Three (Postpone for 4 Hours)
$Button3 = New-Object -TypeName System.Windows.Forms.Button
$Button3.Size = New-Object -TypeName System.Drawing.Size(140,25)
#$Button3.Location = New-Object -TypeName System.Drawing.Size(243,135)
$Button3.Location = New-Object -TypeName System.Drawing.Size(243,145)
$Button3.Text = $Button3Text
$Button3.Font = 'Tahoma, 10pt'
$Button3.Add_Click({
      $Button2.Enabled = $False
      $timerUpdate.Stop()
      $TotalTime = 14400
      Create-GetSchedTime -SchedTime $TotalTime
      $timerUpdate.add_Tick($timerUpdate_Tick)
      $timerUpdate.Start()
})
$Form.Controls.Add($Button3)
$Button3.Enabled = $False

# Label
$Label = New-Object -TypeName System.Windows.Forms.Label
$Label.Size = New-Object -TypeName System.Drawing.Size(380,65)
$Label.Location = New-Object -TypeName System.Drawing.Size(10,15)
$Label.Text = $Message
$label.Font = 'Tahoma, 10pt'
$Form.Controls.Add($Label)

# Label2
#$Label2 = New-Object -TypeName System.Windows.Forms.Label
#$Label2.Size = New-Object -TypeName System.Drawing.Size(355,30)
#$Label2.Location = New-Object -TypeName System.Drawing.Size(10,100)
#$Label2.Text = $Message2
#$label2.Font = 'Tahoma, 10pt'
#$Form.Controls.Add($Label2)

# labelTime
$labelTime = New-Object 'System.Windows.Forms.Label'
$labelTime.AutoSize = $True
$labelTime.Font = 'Arial, 26pt, style=Bold'
#$labelTime.Location = '120, 60'
$labelTime.Location = '120, 90'
$labelTime.Name = 'labelTime'
$labelTime.Size = '43, 15'
$labelTime.TextAlign = 'MiddleCenter'
$labelTime.ForeColor = "Red"
$Form.Controls.Add($labelTime)

#Start the timer
$timerUpdate.add_Tick($timerUpdate_Tick)
$timerUpdate.Start()
# Show
$Form.Add_Shown({$Form.Activate()})
#Clean up the control events
$Form.add_FormClosed($Form_Cleanup_FormClosed)
#Store the control values when form is closing
#$Form.add_Closing($Form_StoreValues_Closing)
$Form.Add_Closing({$_.cancel = $true})
#Show the Form
$Form.ShowDialog() | Out-Null
#$Form.Focused
#return $Form.ShowDialog()

#$Form.Add_Closing({$_.cancel = $false})
#Show the Form
#return $Form.ShowDialog()
</code>```

Body:
I have a powershell script that can be run locally on a Workstation or remotely using PSEXEC tool, that shows a dialog box to console user that the PC is going to be rebooted in X amount of time and timer. The dialog box cannot be closed, only be minimized (this is as per code). However when I run it, it also shows Powershell screen at the back of dialog box and closing it also closes the form.

I tried Powershell switches [-NoLogo], [-NonInteractive], [-WindowStyle Hidden], it doesn't work.

This is the custom-restart script:

Function Create-GetSchedTime {
Param(
$SchedTime
)
      $script:StartTime = (Get-Date).AddSeconds($TotalTime)
      $RestartDate = ((get-date).AddSeconds($TotalTime)).AddMinutes(-5)
      $RDate = (Get-Date $RestartDate -f 'dd.MM.yyyy') -replace "\.","/"      # 16/03/2016
      $RTime = Get-Date $RestartDate -f 'HH:mm'                                    # 09:31
      #&schtasks /delete /tn "Post Maintenance Restart" /f
      #&schtasks /create /sc once /tn "Post Maintenance Restart" /tr "'C:\Windows\system32\cmd.exe' /c shutdown -r -f -t 300" /SD $RDate /ST $RTime /f
}
[System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") | Out-Null
[System.Reflection.Assembly]::LoadWithPartialName( "Microsoft.VisualBasic") | Out-Null
$Title = "Computer Reboot Notification"
$Message = "Your computer will automatically restart in :"
$Button1Text = "Restart now"
$Button2Text = "Postpone for 1 hour"
$Button3Text = "Postpone for 4 hours"
$Form = $null
$Button1 = $null
$Button2 = $null
$Label = $null
$TextBox = $null
$Result = $null
$timerUpdate = New-Object 'System.Windows.Forms.Timer'
#$TotalTime = 14400 #in seconds
$TotalTime = 60 #in seconds
Create-GetSchedTime -SchedTime $TotalTime
$timerUpdate_Tick={
      # Define countdown timer
      [TimeSpan]$span = $script:StartTime - (Get-Date)
      # Update the display
      $hours = "{0:00}" -f $span.Hours
      $mins = "{0:00}" -f $span.Minutes
    $secs = "{0:00}" -f $span.Seconds
    $labelTime.Text = "{0}:{1}:{2}" -f $hours, $mins, $secs
      $timerUpdate.Start()
      if ($span.TotalSeconds -le 0)
      {
            $timerUpdate.Stop()
            &schtasks /delete /tn "Post Maintenance Restart" /f
            shutdown -r -f /t 0
      }
}
$Form_StoreValues_Closing=
      {
            #Store the control values
      }

$Form_Cleanup_FormClosed=
      {
            #Remove all event handlers from the controls
            try
            {
                  $Form.remove_Load($Form_Load)
                  $timerUpdate.remove_Tick($timerUpdate_Tick)
                  #$Form.remove_Load($Form_StateCorrection_Load)
                  $Form.remove_Closing($Form_StoreValues_Closing)
                  $Form.remove_FormClosed($Form_Cleanup_FormClosed)
            }
            catch [Exception]
            { }
      }

# Form
$Form = New-Object -TypeName System.Windows.Forms.Form
$Form.Text = $Title
$Form.Size = New-Object -TypeName System.Drawing.Size(407,205)
$Form.StartPosition = "CenterScreen"
$Form.Topmost = $true
$Form.KeyPreview = $true
$Form.ShowInTaskbar = $Formalse
$Form.FormBorderStyle = "FixedDialog"
$Form.MaximizeBox = $Formalse
$Form.MinimizeBox = $true
$Icon = [system.drawing.icon]::ExtractAssociatedIcon("c:\Windows\System32\UserAccountControlSettings.exe")
$Form.Icon = $Icon

# Button One (Reboot/Shutdown Now)
$Button1 = New-Object -TypeName System.Windows.Forms.Button
$Button1.Size = New-Object -TypeName System.Drawing.Size(90,25)
$Button1.Location = New-Object -TypeName System.Drawing.Size(10,135)
$Button1.Text = $Button1Text
$Button1.Font = 'Tahoma, 10pt'
$Button1.Add_Click({
      &schtasks /delete /tn "Post Maintenance Restart" /f
      shutdown -r -f /t 0
      $Form.Close()
})
$Form.Controls.Add($Button1)
# Button Two (Postpone for 1 Hour)
$Button2 = New-Object -TypeName System.Windows.Forms.Button
$Button2.Size = New-Object -TypeName System.Drawing.Size(133,25)
$Button2.Location = New-Object -TypeName System.Drawing.Size(105,135)
$Button2.Text = $Button2Text
$Button2.Font = 'Tahoma, 10pt'
$Button2.Add_Click({
      $Button2.Enabled = $False
      $timerUpdate.Stop()
      #$TotalTime = 3600
      $TotalTime = 30
      Create-GetSchedTime -SchedTime $TotalTime
      $timerUpdate.add_Tick($timerUpdate_Tick)
      $timerUpdate.Start()
})
$Form.Controls.Add($Button2)

# Button Three (Postpone for 4 Hours)
$Button3 = New-Object -TypeName System.Windows.Forms.Button
$Button3.Size = New-Object -TypeName System.Drawing.Size(140,25)
$Button3.Location = New-Object -TypeName System.Drawing.Size(243,135)
$Button3.Text = $Button3Text
$Button3.Font = 'Tahoma, 10pt'
$Button3.Add_Click({
      $Button2.Enabled = $False
      $timerUpdate.Stop()
      $TotalTime = 14400
      Create-GetSchedTime -SchedTime $TotalTime
      $timerUpdate.add_Tick($timerUpdate_Tick)
      $timerUpdate.Start()
})
$Form.Controls.Add($Button3)
$Button3.Enabled = $False

# Label
$Label = New-Object -TypeName System.Windows.Forms.Label
$Label.Size = New-Object -TypeName System.Drawing.Size(330,25)
$Label.Location = New-Object -TypeName System.Drawing.Size(10,15)
$Label.Text = $Message
$label.Font = 'Tahoma, 10pt'
$Form.Controls.Add($Label)

# Label2
$Label2 = New-Object -TypeName System.Windows.Forms.Label
$Label2.Size = New-Object -TypeName System.Drawing.Size(355,30)
$Label2.Location = New-Object -TypeName System.Drawing.Size(10,100)
$Label2.Text = $Message2
$label2.Font = 'Tahoma, 10pt'
$Form.Controls.Add($Label2)

# labelTime
$labelTime = New-Object 'System.Windows.Forms.Label'
$labelTime.AutoSize = $True
$labelTime.Font = 'Arial, 26pt, style=Bold'
$labelTime.Location = '120, 60'
$labelTime.Name = 'labelTime'
$labelTime.Size = '43, 15'
$labelTime.TextAlign = 'MiddleCenter'
$labelTime.ForeColor = "Red"
$Form.Controls.Add($labelTime)

#Start the timer
$timerUpdate.add_Tick($timerUpdate_Tick)
$timerUpdate.Start()
# Show
$Form.Add_Shown({$Form.Activate()})
#Clean up the control events
$Form.add_FormClosed($Form_Cleanup_FormClosed)
#Store the control values when form is closing
#$Form.add_Closing($Form_StoreValues_Closing)
$Form.Add_Closing({$_.cancel = $true})
#Show the Form
$Form.ShowDialog() | Out-Null
#$Form.Focused
#return $Form.ShowDialog()

#$Form.Add_Closing({$_.cancel = $false})
#Show the Form
#return $Form.ShowDialog()

Body:
Eventually I found out the issue. I was putting "-WindowStyle Hidden" at the end of command, not after Powershell. So this didn't work.

Powershell -File CustomRestart.ps1 -WindowStyle Hidden

This worked, also with PSEXEC.

Powershell -WindowStyle Hidden -File CustomRestart.ps1

Now I added a YES/No confirmation dialog box after user clicks on "Restart Now" button, if clicks Yes, it will reboot, if no, then nothing, just confirmation box disappears. If you look at the $Button1.Add_Click event, there is the code.

Problem is: when I run it on Pwershell ISE, its doing fine (confirmation box shows-up and works), but when running from Command or Run menu, it won't show confirmation box, and thus no effect after clicking "Restart Now" button.

Here is the complete code:

Function Create-GetSchedTime {
Param(
$SchedTime
)
      $script:StartTime = (Get-Date).AddSeconds($TotalTime)
      $RestartDate = ((get-date).AddSeconds($TotalTime)).AddMinutes(-5)
      $RDate = (Get-Date $RestartDate -f 'dd.MM.yyyy') -replace "\.","/"      # 16/03/2016
      $RTime = Get-Date $RestartDate -f 'HH:mm'                                    # 09:31
      #&schtasks /delete /tn "Post Maintenance Restart" /f
      #&schtasks /create /sc once /tn "Post Maintenance Restart" /tr "'C:\Windows\system32\cmd.exe' /c shutdown -r -f -t 300" /SD $RDate /ST $RTime /f
}
[System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") | Out-Null
[System.Reflection.Assembly]::LoadWithPartialName( "Microsoft.VisualBasic") | Out-Null
$Title = "Computer Reboot Notification"
#$Message = "Your computer will automatically restart in :"
$Message = "Your computer has been updated with latest software and requires a reboot. Please save your work and click ""Restart now"" to reboot it now.`nYour computer will automatically reboot in :"
$Button1Text = "Restart now"
$Button2Text = "Postpone for 1 hour"
$Button3Text = "Postpone for 4 hours"
$Form = $null
$Button1 = $null
$Button2 = $null
$Label = $null
$TextBox = $null
$Result = $null
$timerUpdate = New-Object 'System.Windows.Forms.Timer'
$TotalTime = 14400 #in seconds
#$TotalTime = 60 #in seconds
Create-GetSchedTime -SchedTime $TotalTime
$timerUpdate_Tick={
      # Define countdown timer
      [TimeSpan]$span = $script:StartTime - (Get-Date)
      # Update the display
      $hours = "{0:00}" -f $span.Hours
      $mins = "{0:00}" -f $span.Minutes
    $secs = "{0:00}" -f $span.Seconds
    $labelTime.Text = "{0}:{1}:{2}" -f $hours, $mins, $secs
      $timerUpdate.Start()
      if ($span.TotalSeconds -le 0)
      {
            $timerUpdate.Stop()
            #&schtasks /delete /tn "Post Maintenance Restart" /f
            shutdown -r -f /t 0
      }
}
$Form_StoreValues_Closing=
      {
            #Store the control values
      }

$Form_Cleanup_FormClosed=
      {
            #Remove all event handlers from the controls
            try
            {
                  $Form.remove_Load($Form_Load)
                  $timerUpdate.remove_Tick($timerUpdate_Tick)
                  #$Form.remove_Load($Form_StateCorrection_Load)
                  $Form.remove_Closing($Form_StoreValues_Closing)
                  $Form.remove_FormClosed($Form_Cleanup_FormClosed)
            }
            catch [Exception]
            { }
      }

# Form
$Form = New-Object -TypeName System.Windows.Forms.Form
$Form.Text = $Title
$Form.Size = New-Object -TypeName System.Drawing.Size(407,205)
$Form.StartPosition = "CenterScreen"
$Form.Topmost = $true
$Form.KeyPreview = $true
$Form.ShowInTaskbar = $Formalse
$Form.FormBorderStyle = "FixedDialog"
$Form.MaximizeBox = $Formalse
$Form.MinimizeBox = $true
$Icon = [system.drawing.icon]::ExtractAssociatedIcon("c:\Windows\System32\UserAccountControlSettings.exe")
$Form.Icon = $Icon

# Button One (Reboot/Shutdown Now)
$Button1 = New-Object -TypeName System.Windows.Forms.Button
$Button1.Size = New-Object -TypeName System.Drawing.Size(90,25)
#$Button1.Location = New-Object -TypeName System.Drawing.Size(10,135)
$Button1.Location = New-Object -TypeName System.Drawing.Size(10,145)
$Button1.Text = $Button1Text
$Button1.Font = 'Tahoma, 10pt'
$Button1.Add_Click({

    $msgBoxInput =  [System.Windows.MessageBox]::Show('Are you sure you want to reboot now?','Computer Reboot Confirmation','YesNo','Warning')
    switch  ($msgBoxInput) {
        'Yes' {
            shutdown -r -f /t 0
            $Form.Close()
              }

        'No' {
          ## Do something
            }
                            }

})
$Form.Controls.Add($Button1)
# Button Two (Postpone for 1 Hour)
$Button2 = New-Object -TypeName System.Windows.Forms.Button
$Button2.Size = New-Object -TypeName System.Drawing.Size(133,25)
#$Button2.Location = New-Object -TypeName System.Drawing.Size(105,135)
$Button2.Location = New-Object -TypeName System.Drawing.Size(105,145)
$Button2.Text = $Button2Text
$Button2.Font = 'Tahoma, 10pt'
$Button2.Add_Click({
      $Button2.Enabled = $False
      $timerUpdate.Stop()
      $TotalTime = 3600
      #$TotalTime = 30
      Create-GetSchedTime -SchedTime $TotalTime
      $timerUpdate.add_Tick($timerUpdate_Tick)
      $timerUpdate.Start()
})
$Form.Controls.Add($Button2)

# Button Three (Postpone for 4 Hours)
$Button3 = New-Object -TypeName System.Windows.Forms.Button
$Button3.Size = New-Object -TypeName System.Drawing.Size(140,25)
#$Button3.Location = New-Object -TypeName System.Drawing.Size(243,135)
$Button3.Location = New-Object -TypeName System.Drawing.Size(243,145)
$Button3.Text = $Button3Text
$Button3.Font = 'Tahoma, 10pt'
$Button3.Add_Click({
      $Button2.Enabled = $False
      $timerUpdate.Stop()
      $TotalTime = 14400
      Create-GetSchedTime -SchedTime $TotalTime
      $timerUpdate.add_Tick($timerUpdate_Tick)
      $timerUpdate.Start()
})
$Form.Controls.Add($Button3)
$Button3.Enabled = $False

# Label
$Label = New-Object -TypeName System.Windows.Forms.Label
$Label.Size = New-Object -TypeName System.Drawing.Size(380,65)
$Label.Location = New-Object -TypeName System.Drawing.Size(10,15)
$Label.Text = $Message
$label.Font = 'Tahoma, 10pt'
$Form.Controls.Add($Label)

# Label2
#$Label2 = New-Object -TypeName System.Windows.Forms.Label
#$Label2.Size = New-Object -TypeName System.Drawing.Size(355,30)
#$Label2.Location = New-Object -TypeName System.Drawing.Size(10,100)
#$Label2.Text = $Message2
#$label2.Font = 'Tahoma, 10pt'
#$Form.Controls.Add($Label2)

# labelTime
$labelTime = New-Object 'System.Windows.Forms.Label'
$labelTime.AutoSize = $True
$labelTime.Font = 'Arial, 26pt, style=Bold'
#$labelTime.Location = '120, 60'
$labelTime.Location = '120, 90'
$labelTime.Name = 'labelTime'
$labelTime.Size = '43, 15'
$labelTime.TextAlign = 'MiddleCenter'
$labelTime.ForeColor = "Red"
$Form.Controls.Add($labelTime)

#Start the timer
$timerUpdate.add_Tick($timerUpdate_Tick)
$timerUpdate.Start()
# Show
$Form.Add_Shown({$Form.Activate()})
#Clean up the control events
$Form.add_FormClosed($Form_Cleanup_FormClosed)
#Store the control values when form is closing
#$Form.add_Closing($Form_StoreValues_Closing)
$Form.Add_Closing({$_.cancel = $true})
#Show the Form
$Form.ShowDialog() | Out-Null
#$Form.Focused
#return $Form.ShowDialog()

#$Form.Add_Closing({$_.cancel = $false})
#Show the Form
#return $Form.ShowDialog()


问:
Regex for a phone number where a phone number exclusively contains numbers in the range of 5 to 15 digits
My regex:/[0-9]{5,15}/ that satisfies a number e.g. 8801778620485 which is fine.
But it also satisfies a number i.e 8801778620485|123456|987123456 (Three parts are a single phone number). I don't want this kind of phone number to be accepted. I want exclusively numbers without any special characters like (|, ?, *, -) these no special characters are allowed, only numbers are allowed.

答:
number.match(/^\d{5,15}$/);

This should work \d for [0-9], and start and end of the expression specified so that a a string like 123456|12345678 doesn't result in a partial match.


问:
Renaming columns in a system versioned table Visual Studio SQL Project
I'm looking to have Visual Studio's SQL Schema Compare generate the delta SQL to update a production database, including a column rename on a table with system versioning on (temporal table).

Using refactoring within Visual Studio SQL Project will indeed create an entry in the refactorlog file, and will generate the correct sp_rename SQL for that renamed field.  However, the associated history table doesn't get the field renamed - it does a drop and add, which will not work well once there is actual data in the table. Plus it also makes it so the tables get out of sync with each other.

Maybe I could modify the refactorlog XML to indicate it is a field with a history table attached?  the XML below shows the Elementtype is "SqlSimpleColumn".  Are there any other options I could explore?

System: Visual Studio Community 2017
SQL server: Azure SQL Database V12

```<code>  <Operation Name="Rename Refactor" Key="48b6ef58-988b-48bf-9606-4048b0c51bf2" ChangeDateTime="04/03/2017 21:19:32">
    <Property Name="ElementName" Value="[dbo].[xyz2].[newafterreset]" />
    <Property Name="ElementType" Value="SqlSimpleColumn" />
    <Property Name="ParentElementName" Value="[dbo].[xyz2]" />
    <Property Name="ParentElementType" Value="SqlTable" />
    <Property Name="NewName" Value="[updateafterreset]" />
  </Operation>
</code>```

答:
Yes, you can set the system versioning off before making changes to the table.
ALTER TABLE [dbo].[TABLE_NAME] SET ( SYSTEM_VERSIONING = OFF  )
GO

This will allow you to make changes to the table.
BEWARE: A word of caution  - when you execute a sp_rename to rename a column, on a system versioned (temporal) table it breaks the version history for that entity

ContentLicense: CC BY-SA 3.0

Body:
I'm looking to have Visual Studio's SQL Schema Compare generate the delta SQL to update a production database, including a column rename on a table with system versioning on (temporal table).

Using refactoring within Visual Studio SQL Project will indeed create an entry in the refactorlog file, and will generate the correct sp_rename SQL for that renamed field.  However, the associated history table doesn't get the field renamed - it does a drop and add, which will not work well once there is actual data in the table. Plus it also makes it so the tables get out of sync with each other.

Maybe I could modify the refactorlog XML to indicate it is a field with a history table attached?  the XML below shows the Elementtype is "SqlSimpleColumn".  Are there any other options I could explore?

System: Visual Studio Community 2017
SQL server: Azure SQL Database V12

  <Operation Name="Rename Refactor" Key="48b6ef58-988b-48bf-9606-4048b0c51bf2" ChangeDateTime="04/03/2017 21:19:32">
    <Property Name="ElementName" Value="[dbo].[xyz2].[newafterreset]" />
    <Property Name="ElementType" Value="SqlSimpleColumn" />
    <Property Name="ParentElementName" Value="[dbo].[xyz2]" />
    <Property Name="ParentElementType" Value="SqlTable" />
    <Property Name="NewName" Value="[updateafterreset]" />
  </Operation>


问:
Limiting Application permission scopes to specific Site Collection(s)
I need an Access Token to make calls into a SharePoint site using Application scopes (Client Credentials).

Is there a way to limit the scope of application permissions? I am currently unable to receive Admin Concent for my application as this would allow access to every SharePoint Site in their Tenant.

答:
If we grant the application Sites.Manage.All permission, we will be able to manage all the sites. We can not limit the application scope to specific Site Collection(s).

The application permissions are for all the site collections.


问:
Posting array of JSON objects to MVC3 action method via jQuery ajax
Does the model binder not suport arrays of JSON objects? The code below works when sending a single JSON domain object as part of the ajax post. However, when sending an array of JSON domain objects, the action parameter is null.

```<code>     var domains = [{
                        DomainName: 'testt1',
                        Price: '19.99',
                        Available: true
                    }, {
                        DomainName: 'testt2',
                        Price: '15.99',
                        Available: false
                    }];

                $.ajax({
                    type: 'POST',
                    url: Url.BasketAddDomain,
                    dataType: "json",
                    data: domains,
                    success: function (basketHtml) {

                    },
                    error: function (a, b, c) {
                        alert('A problem ocurred');
                    }
            });
</code>```

This is the action method:

```<code>public ActionResult AddDomain(IEnumerable<DomainBasketItemModel> domain)
{
    ...
</code>```

Any ideas if it is possible to do this?

EDIT

@Milimetric

Your solution works! However, this is my fault, but the code I demonstrated isn't the real code of my problem, I was trying to show equivalent code that is easier to understand.

I am actually creating an array, then interating some DOM elements and pushing a JSON object onto the array, then posting this array as the data...

```<code>var domains = [];

                $(this).parents('table').find('input:checked').each(function () {
                    var domain = {
                        DomainName: $(this).parent().parent().find('.name').html(),
                        Price: $(this).parent().parent().find('.price span').html(),
                        Available: $(this).parent().parent().find('.available').html() == "Available"
                    }

                    domains.push(domain);
                });

                $.ajax({
                    type: 'POST',
                    url: Url.BasketAddDomain,
                    dataType: "json",
                    data: { domain: domains },
                    success: function (basketHtml) {

                    },
                    error: function (a, b, c) {
                        alert('A problem ocurred');
                    }
                });
</code>```

答:
I had a similar problem. To solve it, I took a slightly different approach. Instead of a JSON object, I used arrays of hidden form variables. As long as the variable names matched up, model binding worked like a charm.

```<code>function AddDomainBasket(domainName, price, available) {

    if ( typeof AddDomainBasket.counter == 'undefined' ) {
        AddDomainBasket.counter = 0;
    }

    $("#some_form").append('<input type="hidden" name="[' + AddDomainBasket.counter + '].DomainName" value="' + domainName_index + '" />');
    $("#some_form").append('<input type="hidden" name="[' + AddDomainBasket.counter + '].Price" value="' + price + '" />');
    $("#some_form").append('<input type="hidden" name="[' + AddDomainBasket.counter + '].Available" value="' + available + '" />');

    ++AddDomainBasket.counter;
}
</code>```

And then submit the serlialized form

```<code>$(this).parents('table').find('input:checked').each(function () {
    AddDomainBasket($(this).parent().parent().find('.name').html(),
                    $(this).parent().parent().find('.price span').html(),
                    $(this).parent().parent().find('.available').html() ==   "Available");
                }
            });

$.ajax({
    type: 'POST',
    url: Url.BasketAddDomain,
    data: $('#some_form').serialize(),
    success: function (basketHtml) {
        },
        error: function (a, b, c) {
            alert('A problem ocurred');
    }
});
</code>```

Body:
Does the model binder not suport arrays of JSON objects? The code below works when sending a single JSON domain object as part of the ajax post. However, when sending an array of JSON domain objects, the action parameter is null.

     var domains = [{
                        DomainName: 'testt1',
                        Price: '19.99',
                        Available: true
                    }, {
                        DomainName: 'testt2',
                        Price: '15.99',
                        Available: false
                    }];

                $.ajax({
                    type: 'POST',
                    url: Url.BasketAddDomain,
                    dataType: "json",
                    data: domains,
                    success: function (basketHtml) {

                    },
                    error: function (a, b, c) {
                        alert('A problem ocurred');
                    }
            });

This is the action method:

public ActionResult AddDomain(IEnumerable<DomainBasketItemModel> domain)
{
    ...

Any ideas if it is possible to do this?

EDIT

@Milimetric

Your solution works! However, this is my fault, but the code I demonstrated isn't the real code of my problem, I was trying to show equivalent code that is easier to understand.

I am actually creating an array, then interating some DOM elements and pushing a JSON object onto the array, then posting this array as the data...

var domains = [];

                $(this).parents('table').find('input:checked').each(function () {
                    var domain = {
                        DomainName: $(this).parent().parent().find('.name').html(),
                        Price: $(this).parent().parent().find('.price span').html(),
                        Available: $(this).parent().parent().find('.available').html() == "Available"
                    }

                    domains.push(domain);
                });

                $.ajax({
                    type: 'POST',
                    url: Url.BasketAddDomain,
                    dataType: "json",
                    data: { domain: domains },
                    success: function (basketHtml) {

                    },
                    error: function (a, b, c) {
                        alert('A problem ocurred');
                    }
                });

Body:
I had a similar problem. To solve it, I took a slightly different approach. Instead of a JSON object, I used arrays of hidden form variables. As long as the variable names matched up, model binding worked like a charm.

function AddDomainBasket(domainName, price, available) {

    if ( typeof AddDomainBasket.counter == 'undefined' ) {
        AddDomainBasket.counter = 0;
    }

    $("#some_form").append('<input type="hidden" name="[' + AddDomainBasket.counter + '].DomainName" value="' + domainName_index + '" />');
    $("#some_form").append('<input type="hidden" name="[' + AddDomainBasket.counter + '].Price" value="' + price + '" />');
    $("#some_form").append('<input type="hidden" name="[' + AddDomainBasket.counter + '].Available" value="' + available + '" />');

    ++AddDomainBasket.counter;
}

And then submit the serlialized form

$(this).parents('table').find('input:checked').each(function () {
    AddDomainBasket($(this).parent().parent().find('.name').html(),
                    $(this).parent().parent().find('.price span').html(),
                    $(this).parent().parent().find('.available').html() ==   "Available");
                }
            });

$.ajax({
    type: 'POST',
    url: Url.BasketAddDomain,
    data: $('#some_form').serialize(),
    success: function (basketHtml) {
        },
        error: function (a, b, c) {
            alert('A problem ocurred');
    }
});


问:
Hashing string values results in different outputs on Linux vs Windows in C++
I am trying to hash single std::string and std::vector<std::string> values. I am following the examples from cppreference and boost. When the code is compiled and run on Windows vs Linux, I get different results.

The header file for MyHasher.h is as follows.

```<code>class MyHasher {
 private:
  MyHasher() = delete;
 public:
  static std::size_t hash(std::vector<std::string> ids);
  static std::size_t hash(std::string s);
  static void hashCombine(std::size_t &seed, std::size_t value);
};
</code>```

The CPP file MyHasher.cpp is as follows.

```<code>std::size_t MyHasher::hash(std::vector<std::string> ids) {
  std::size_t seed = 0;
  for (auto id : ids) {
    std::size_t h = std::hash<std::string>{}(id);
    hashCombine(seed, h);
  }
  return seed;
}
std::size_t MyHasher::hash(std::string s) {
  std::size_t seed = 0;
  std::size_t h = std::hash<std::string>{}(s);
  hashCombine(seed, h);
  return seed;
}
void MyHasher::hashCombine(std::size_t &seed, std::size_t value) {
  seed ^= value + 0x9e3779b9 + (seed<<6) + (seed>>2);
}
</code>```

A sample program then runs as follows.

```<code>int main() {
  std::cout << std::to_string(MyHasher::hash("0")) << " | 0" << std::endl;
  std::cout << std::to_string(MyHasher::hash(std::vector<std::string>{"0"})) << " | 0" << std::endl;
  std::cout << std::to_string(MyHasher::hash(std::vector<std::string>{"0", "1"})) << " | 0 1" << std::endl;
  return 0;
}
</code>```

On Linux (g++ 7.4.0), the output is as follows.

```
2297668036269395695 | 0
2297668036269395695 | 0
10545066640295778616 | 0 1
```

On Windows (Visual Studio Community 2019, MSVC-14.0), the output is as follows.

```
12638135526163551848 | 0
12638135526163551848 | 0
1964774108746342951 | 0 1
```

Any ideas on this discrepancy?

What I really want is a way to always produce an unique hash output that is dependent on the input, but cross-platform and fixed width. The width is not important, per say, but as long as it is the same width regardless of the input(s).

答:
In the doc. of std::hash, it is explicitly mentioned that:

The actual hash functions are implementation-dependent

…

Hash functions are only required to produce the same result for the same input within a single execution of a program;

I'm a bit uncertain about a hash function which always returns identical hashs for identical input. I googled a bit but failed to find something which I would dare to present.

Assuming that the std library of MS VC++ and g++ may be different implementations, it cannot be expected to produce identical hashs for identical input.

Reading the second part of cite carefully, you even cannot expect that the same program results in identical hashs for identical input in distinct processes (e.g. when started, exited, and started again).

Cryptographic hash functions might be a solution:

it is deterministic, meaning that the same message always results in the same hash

it is quick to compute the hash value for any given message

it is infeasible to generate a message that yields a given hash value

it is infeasible to find two different messages with the same hash value
  a small change to a message should change the hash value so extensively that the new hash value appears uncorrelated with the old hash value (avalanche effect)

Checksums are related to hash functions. For a checksum, it must be required to result in identical output for identical input (to be reliable).

So, a checksum implementation based on a hash function should match the requirement of OP as well.

The accepted answer to SSE: Which hashing algorithm shoud I use for a safe file checksum? recommends SHA256 or SHA512.

This remembered me that I recently heard that git uses a variation of SHA-1 but git may use SHA256 as well as well which appears to me as similar use case to what (I assume) OP might have.

Body:
I am trying to hash single std::string and std::vector<std::string> values. I am following the examples from cppreference and boost. When the code is compiled and run on Windows vs Linux, I get different results.

The header file for MyHasher.h is as follows.

class MyHasher {
 private:
  MyHasher() = delete;
 public:
  static std::size_t hash(std::vector<std::string> ids);
  static std::size_t hash(std::string s);
  static void hashCombine(std::size_t &seed, std::size_t value);
};

The CPP file MyHasher.cpp is as follows.

std::size_t MyHasher::hash(std::vector<std::string> ids) {
  std::size_t seed = 0;
  for (auto id : ids) {
    std::size_t h = std::hash<std::string>{}(id);
    hashCombine(seed, h);
  }
  return seed;
}
std::size_t MyHasher::hash(std::string s) {
  std::size_t seed = 0;
  std::size_t h = std::hash<std::string>{}(s);
  hashCombine(seed, h);
  return seed;
}
void MyHasher::hashCombine(std::size_t &seed, std::size_t value) {
  seed ^= value + 0x9e3779b9 + (seed<<6) + (seed>>2);
}

A sample program then runs as follows.

int main() {
  std::cout << std::to_string(MyHasher::hash("0")) << " | 0" << std::endl;
  std::cout << std::to_string(MyHasher::hash(std::vector<std::string>{"0"})) << " | 0" << std::endl;
  std::cout << std::to_string(MyHasher::hash(std::vector<std::string>{"0", "1"})) << " | 0 1" << std::endl;
  return 0;
}

On Linux (g++ 7.4.0), the output is as follows.

2297668036269395695 | 0
2297668036269395695 | 0
10545066640295778616 | 0 1

On Windows (Visual Studio Community 2019, MSVC-14.0), the output is as follows.

12638135526163551848 | 0
12638135526163551848 | 0
1964774108746342951 | 0 1

Any ideas on this discrepancy?

What I really want is a way to always produce an unique hash output that is dependent on the input, but cross-platform and fixed width. The width is not important, per say, but as long as it is the same width regardless of the input(s).


问:
Kafka Topic And Offset
I have a question,Suppose there is a TOPIC T1 and there are two Consumer C1 and C2 belongs to two different groups and current offset is 0.We know that Kafka maintains the Offset for consumer.So if C1 consume the message and Offset becomes 1 then what will happen if C2 consume the message will it start from 1 offset or it will start consume the message from 0 offset?. Means how offset will be maintains for two different consumer Group?.

Thanks

答:
If you have two Kafka consumers with different Group Id they will read partitions without any interference between each other. Meaning both consumers will read the exact same set of messages independently. If you have four Kafka consumers with different Group Id they will all read all partitions etc.

As to answer your question, C1 will read from offset 0 and C2 will read from offset 0 also, as they belongs to two different groups.

Title: Kafka Topic And Offset


问:
How to create an interface for object and array of objects in Angular 8 and type script?
I'm trying to create an interface for Object, objects, and array of objects.

Sample interface

```<code>export interface ErateColumn {
  categories:{
    [key:string]:column[]
  }
}

interface column {
  label:string
  value:string
}
</code>```

Sample API response like this

```<code>{
"categories": {
    "Basic Information": [
        { label: "Applicant Type", value: "ApplicantType" },
        { label: "Organization Name", value: "OrganizationName" },
    ],
    "FRN Lineitem": [
        { label: "Monthly_Cost", value: "Monthly_Cost" },
        ],
    "FRN status": [
        { label: "Purpose Type", value: "PurposeType" },

    ]
}
}
</code>```

答:
May be this approach can help someone

You can convert JSON to typescript's class or interface, Using online tool json2ts or if you are using vs code (Visual Studio)  use this extension QuickType - Paste JSON as Code

Note: Your JSON should be a valid JSON otherwise you will get errors

Body:
I'm trying to create an interface for Object, objects, and array of objects.

Sample interface

export interface ErateColumn {
  categories:{
    [key:string]:column[]
  }
}

interface column {
  label:string
  value:string
}

Sample API response like this

{
"categories": {
    "Basic Information": [
        { label: "Applicant Type", value: "ApplicantType" },
        { label: "Organization Name", value: "OrganizationName" },
    ],
    "FRN Lineitem": [
        { label: "Monthly_Cost", value: "Monthly_Cost" },
        ],
    "FRN status": [
        { label: "Purpose Type", value: "PurposeType" },

    ]
}
}


问:
Web Request Encoding Problem
Hi i'm getting encoding problems with the code below any ideas?

```<code>string url = "http://www.google.com/ig/api?weather=istanbul,TR&hl=tr";
        HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
        using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
        {
            StreamReader reader = new StreamReader(response.GetResponseStream());
            string retVal = reader.ReadToEnd();
            Response.Write(retVal);
        }
</code>```

My Screenshoot is like that;

Thanks for your help!

答:
Google is notorious for checking the useragent HTTP header. Because you're not setting it its encoding everything as ISO-8859-9. The simple solution is to manually set the UserAgent property of the HttpWebRequest. Set it to anything you want, below is a Firefox string (and an extra Using block):

```<code>        string url = "http://www.google.com/ig/api?weather=istanbul,TR&hl=tr";
        HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
        request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; rv:2.0.1) Gecko/20100101 Firefox/4.0.1";
        using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
        {
            using (StreamReader reader = new StreamReader(response.GetResponseStream()))
            {
                string retVal = reader.ReadToEnd();
                Console.WriteLine(retVal);
            }
        }
</code>```

Title: Web Request Encoding Problem

Body:
Hi i'm getting encoding problems with the code below any ideas?

string url = "http://www.google.com/ig/api?weather=istanbul,TR&hl=tr";
        HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
        using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
        {
            StreamReader reader = new StreamReader(response.GetResponseStream());
            string retVal = reader.ReadToEnd();
            Response.Write(retVal);
        }

My Screenshoot is like that;

Thanks for your help!

Body:
Google is notorious for checking the useragent HTTP header. Because you're not setting it its encoding everything as ISO-8859-9. The simple solution is to manually set the UserAgent property of the HttpWebRequest. Set it to anything you want, below is a Firefox string (and an extra Using block):

        string url = "http://www.google.com/ig/api?weather=istanbul,TR&hl=tr";
        HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
        request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; rv:2.0.1) Gecko/20100101 Firefox/4.0.1";
        using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
        {
            using (StreamReader reader = new StreamReader(response.GetResponseStream()))
            {
                string retVal = reader.ReadToEnd();
                Console.WriteLine(retVal);
            }
        }


问:
Finding symmetric difference of two lists of objects
Consider two lists (or other appropriate data structures) of the objects of type:

```<code>class Object
{
    public string clause;

    public string preamble;
    public string description;
}
</code>```

I need to build a list of these objects that are NOT perfect matches (preamble and description exactly the same in both). For example, if there is a record in list A whose preamble matches that of one in list B, but their description do not match, it should be included. If their description match, they should not be included (that would be part of their intersection).

I have been going round in circles trying to find a solution, including implementing nested foreach loops. Is there a symmetric difference function for List, or any other appropriate data structure, that can compare objects by comparing their members like this?

For context, one of the lists represents records from an Excel spreadsheet obtained with Epplus library, and the other list represents issues from Jira API.

答: There is no convenient built-in solution for that, probably because object in .NET is not data. However, there are some projects useful for your problem, like Compare .NET Objects, which can compare object by using reflection and can be configured to list all differences between two objects.</p>

Body:
Consider two lists (or other appropriate data structures) of the objects of type:

class Object
{
    public string clause;

    public string preamble;
    public string description;
}

I need to build a list of these objects that are NOT perfect matches (preamble and description exactly the same in both). For example, if there is a record in list A whose preamble matches that of one in list B, but their description do not match, it should be included. If their description match, they should not be included (that would be part of their intersection).

I have been going round in circles trying to find a solution, including implementing nested foreach loops. Is there a symmetric difference function for List, or any other appropriate data structure, that can compare objects by comparing their members like this?

For context, one of the lists represents records from an Excel spreadsheet obtained with Epplus library, and the other list represents issues from Jira API.


问:
Cannot execute command with SSH.NET on Cisco WLC
Trying to use SSH.NET to connect to the Cisco wireless controller and add a mac address to it. When I debug my code I am getting a true on the IsConnected property of the client, but when I log onto the controller itself and do a "Show loginsession", I am not seeing the supposed connection being listed.

Also, when I get to var result = client.RunCommand(comman.ToString()).Result; the code just hangs with no response at all. Have left for several minutes and does not timeout or return any sort of error.

Picture of PuTTY session when executing above line

It does not matter what we use for "login as".

```<code>public WebAPIEndPoint Put(WebAPIEndPoint console)
{
    var auth = new PasswordAuthenticationMethod("UserName", "Password");
    var connectionInfo = new ConnectionInfo(hostIP, 22, "UserName", auth);

    using (var client = new SshClient(connectionInfo))
    {
        client.Connect();

        var command =
            client.CreateCommand("config macfilter add 00:17:ab:ea:d4:aa 5 0 Testing1234");

        var result = client.RunCommand(comman.ToString()).Result;

        Console.WriteLine(result);

        client.Disconnect();

        return console;
    }
}

</code>```

When running plink user@host config macfilter add 00:17:ab:ea:d4:aa 5 0 Testing1234, I get:

FATAL ERROR: Server refused to start a shell/command.

答:
Your server does not seem to support SSH "exec" channel. So you cannot use CreateCommand/RunCommand.

You have to use a "shell" channel (SshClient.CreateShell or SshClient.CreateShellStream). This is normally not recommended for a command automation. Even more so with SSH.NET, which does not even allow your to turn off a pseudo terminal for the "shell" channel. This brings lots of nasty side effects, particularly with "smart" shells on Linux. But with devices likes yours, it might be bearable and the only solution anyway.

```<code>ShellStream shellStream = client.CreateShellStream(string.Empty, 0, 0, 0, 0, 0);
shellStream.Write("username\n");
shellStream.Write("password\n");
shellStream.Write("config macfilter add 00:17:ab:ea:d4:aa 5 0 Testing1234\n");
</code>```

Body:
Trying to use SSH.NET to connect to the Cisco wireless controller and add a mac address to it. When I debug my code I am getting a true on the IsConnected property of the client, but when I log onto the controller itself and do a "Show loginsession", I am not seeing the supposed connection being listed.

Also, when I get to var result = client.RunCommand(comman.ToString()).Result; the code just hangs with no response at all. Have left for several minutes and does not timeout or return any sort of error.

Picture of PuTTY session when executing above line

It does not matter what we use for "login as".

public WebAPIEndPoint Put(WebAPIEndPoint console)
{
    var auth = new PasswordAuthenticationMethod("UserName", "Password");
    var connectionInfo = new ConnectionInfo(hostIP, 22, "UserName", auth);

    using (var client = new SshClient(connectionInfo))
    {
        client.Connect();

        var command =
            client.CreateCommand("config macfilter add 00:17:ab:ea:d4:aa 5 0 Testing1234");

        var result = client.RunCommand(comman.ToString()).Result;

        Console.WriteLine(result);

        client.Disconnect();

        return console;
    }
}

When running plink user@host config macfilter add 00:17:ab:ea:d4:aa 5 0 Testing1234, I get:

FATAL ERROR: Server refused to start a shell/command.

Body:
Your server does not seem to support SSH "exec" channel. So you cannot use CreateCommand/RunCommand.

You have to use a "shell" channel (SshClient.CreateShell or SshClient.CreateShellStream). This is normally not recommended for a command automation. Even more so with SSH.NET, which does not even allow your to turn off a pseudo terminal for the "shell" channel. This brings lots of nasty side effects, particularly with "smart" shells on Linux. But with devices likes yours, it might be bearable and the only solution anyway.

ShellStream shellStream = client.CreateShellStream(string.Empty, 0, 0, 0, 0, 0);
shellStream.Write("username\n");
shellStream.Write("password\n");
shellStream.Write("config macfilter add 00:17:ab:ea:d4:aa 5 0 Testing1234\n");


问:
undefined and null
```<code>undefined === null => false
undefined == null => true
</code>```

I have thought about the reason of undefined == null and found out only one case:

```<code>if(document.getElementById() == null) ....
</code>```

Is there any other reason to make (undefined === null) == false ?

Is there any other examples of use === - operation in javascript?

答:
Is there any other reason to make (undefined === null) == false ?

They are not equal so the Strict Equality Comparison Algorithm considers them to be false.

Is there any other examples of use === - operation in javascript?

The === gives the most predictable result. I only use == when I have a specific purpose for type coercion. (See Abstract Equality Comparison Algorithm.)

Title: undefined and null

Body:
undefined === null => false
undefined == null => true

I have thought about the reason of undefined == null and found out only one case:

if(document.getElementById() == null) ....

Is there any other reason to make (undefined === null) == false ?

Is there any other examples of use === - operation in javascript?


问:
How to solve "Unsupported platform for inotify@1.4.2"
```<code>**npm ERR!** code EBADPLATFORM
**npm ERR!** notsup Unsupported platform for inotify@1.4.2: wanted {"os":"linux","arch":"any"} (current: {"os":"darwin","arch":"x64"})

**npm ERR!** notsup Valid OS:    linux
**npm ERR!** notsup Valid Arch:  any
**npm ERR!** notsup Actual OS:   darwin
**npm ERR!** notsup Actual Arch: x64
</code>```

答:
Below command worked for me.

```<code>sudo npm -g uninstall dev --save
</code>```

More details on uninstalling npm package can be found here : How to uninstall npm modules in node js?

Body:
Below command worked for me.

sudo npm -g uninstall dev --save

More details on uninstalling npm package can be found here : How to uninstall npm modules in node js?


问:
How to use DISTINCT ON in ARRAY_AGG()?
I have the following query:

```<code>SELECT array_agg(DISTINCT p.id) AS price_ids,
       array_agg(p.name)        AS price_names
FROM items
         LEFT JOIN prices p on p.item_id = id
         LEFT JOIN third_table t3 on third_table.item_id = id
WHERE id = 1;
</code>```

When I LEFT JOIN the third_table all my prices are duplicated.

I'm using DISTINCT inside ARRAY_AGG() to get the ids without dups, but I want the names without dups aswell.

If I use array_agg(DISTINCT p.name) AS price_names, it will return distinct values based on the name, not the id.

I want to do something similar to array_agg(DISTINCT ON (p.id) p.name) AS price_names, but it is invalid.

How can I use DISTINCT ON inside ARRAY_AGG()?

答:
Aggregate first, then join:

```<code>SELECT p.price_ids,
       p.price_names,
       t3.*
FROM items
  LEFT JOIN (
     SELECT pr.item_id,
            array_agg(pr.id)    AS price_ids,
            array_agg(pr.name)  AS price_names
     FROM prices pr
     GROUP BY pr.item_id
  ) p on p.item_id = items.id
  LEFT JOIN third_table t3 on third_table.item_id = id
WHERE items.id = 1;
</code>```

Using a lateral join might be faster if you only pick a single item:

```<code>SELECT p.price_ids,
       p.price_names,
       t3.*
FROM items
  LEFT JOIN LATERAL (
     SELECT array_agg(pr.id)    AS price_ids,
            array_agg(pr.name)  AS price_names
     FROM prices pr
     WHERE pr.item_id = items.id
  ) p on true
  LEFT JOIN third_table t3 on third_table.item_id = id
WHERE items.id = 1;
</code>```

Title: How to use DISTINCT ON in ARRAY_AGG()?

Body:
I have the following query:

SELECT array_agg(DISTINCT p.id) AS price_ids,
       array_agg(p.name)        AS price_names
FROM items
         LEFT JOIN prices p on p.item_id = id
         LEFT JOIN third_table t3 on third_table.item_id = id
WHERE id = 1;

When I LEFT JOIN the third_table all my prices are duplicated.

I'm using DISTINCT inside ARRAY_AGG() to get the ids without dups, but I want the names without dups aswell.

If I use array_agg(DISTINCT p.name) AS price_names, it will return distinct values based on the name, not the id.

I want to do something similar to array_agg(DISTINCT ON (p.id) p.name) AS price_names, but it is invalid.

How can I use DISTINCT ON inside ARRAY_AGG()?

Body:
Aggregate first, then join:

SELECT p.price_ids,
       p.price_names,
       t3.*
FROM items
  LEFT JOIN (
     SELECT pr.item_id,
            array_agg(pr.id)    AS price_ids,
            array_agg(pr.name)  AS price_names
     FROM prices pr
     GROUP BY pr.item_id
  ) p on p.item_id = items.id
  LEFT JOIN third_table t3 on third_table.item_id = id
WHERE items.id = 1;

Using a lateral join might be faster if you only pick a single item:

SELECT p.price_ids,
       p.price_names,
       t3.*
FROM items
  LEFT JOIN LATERAL (
     SELECT array_agg(pr.id)    AS price_ids,
            array_agg(pr.name)  AS price_names
     FROM prices pr
     WHERE pr.item_id = items.id
  ) p on true
  LEFT JOIN third_table t3 on third_table.item_id = id
WHERE items.id = 1;


问:
ggplot geom_histogram with different colors
I want to create histogram with ggplot2 package in R and add vertical lines to show the mean-sd and mean+sd.

I am using below codes

```<code>iris %>%
  ggplot(aes(Sepal.Length)) + geom_histogram() + theme_bw() +
  geom_vline(xintercept = mean(iris$Sepal.Length) - sd(iris$Sepal.Length), linetype = "dashed") +
  geom_vline(xintercept = mean(iris$Sepal.Length), linetype = "solid") +
  geom_vline(xintercept = mean(iris$Sepal.Length) + sd(iris$Sepal.Length), linetype = "dashed")
</code>```

It works perfectly. Is there any way to add different color for each group?

For example, scores that are below mean - sd with orange color and score that are above mean + sd with red color.

Thank you in advanced.

答:
Your code is OK, just you have to add fill=Species within aes like

```<code>iris %>%
  ggplot(aes(Sepal.Length, fill=Species)) + geom_histogram() + theme_bw() +
  geom_vline(xintercept = mean(iris$Sepal.Length) - sd(iris$Sepal.Length), linetype = "dashed") +
  geom_vline(xintercept = mean(iris$Sepal.Length), linetype = "solid") +
  geom_vline(xintercept = mean(iris$Sepal.Length) + sd(iris$Sepal.Length), linetype = "dashed")
</code>```

Is this what you want?

Update

```<code>iris$value<-cut(iris$Sepal.Length, c(min(iris$Sepal.Length)-1, mean(iris$Sepal.Length) - sd(iris$Sepal.Length), mean(iris$Sepal.Length) + sd(iris$Sepal.Length), max(iris$Sepal.Length)),
              labels = c("< Mean - SD","Mean",">  Mean + SD"))

iris %>%
  ggplot(aes(Sepal.Length, fill=value)) + geom_histogram() + theme_bw() +
  geom_vline(xintercept = mean(iris$Sepal.Length) - sd(iris$Sepal.Length), linetype = "dashed") +
  geom_vline(xintercept = mean(iris$Sepal.Length), linetype = "solid") +
  geom_vline(xintercept = mean(iris$Sepal.Length) + sd(iris$Sepal.Length), linetype = "dashed")
</code>```

Body:
I want to create histogram with ggplot2 package in R and add vertical lines to show the mean-sd and mean+sd.

I am using below codes

iris %>%
  ggplot(aes(Sepal.Length)) + geom_histogram() + theme_bw() +
  geom_vline(xintercept = mean(iris$Sepal.Length) - sd(iris$Sepal.Length), linetype = "dashed") +
  geom_vline(xintercept = mean(iris$Sepal.Length), linetype = "solid") +
  geom_vline(xintercept = mean(iris$Sepal.Length) + sd(iris$Sepal.Length), linetype = "dashed")

It works perfectly. Is there any way to add different color for each group?

For example, scores that are below mean - sd with orange color and score that are above mean + sd with red color.

Thank you in advanced.

Body:
Your code is OK, just you have to add fill=Species within aes like

iris %>%
  ggplot(aes(Sepal.Length, fill=Species)) + geom_histogram() + theme_bw() +
  geom_vline(xintercept = mean(iris$Sepal.Length) - sd(iris$Sepal.Length), linetype = "dashed") +
  geom_vline(xintercept = mean(iris$Sepal.Length), linetype = "solid") +
  geom_vline(xintercept = mean(iris$Sepal.Length) + sd(iris$Sepal.Length), linetype = "dashed")

Is this what you want?

Update

iris$value<-cut(iris$Sepal.Length, c(min(iris$Sepal.Length)-1, mean(iris$Sepal.Length) - sd(iris$Sepal.Length), mean(iris$Sepal.Length) + sd(iris$Sepal.Length), max(iris$Sepal.Length)),
              labels = c("< Mean - SD","Mean",">  Mean + SD"))

iris %>%
  ggplot(aes(Sepal.Length, fill=value)) + geom_histogram() + theme_bw() +
  geom_vline(xintercept = mean(iris$Sepal.Length) - sd(iris$Sepal.Length), linetype = "dashed") +
  geom_vline(xintercept = mean(iris$Sepal.Length), linetype = "solid") +
  geom_vline(xintercept = mean(iris$Sepal.Length) + sd(iris$Sepal.Length), linetype = "dashed")


问:
Move in doubly linked list Ramda.js
When I started using a doubly linked list, it became more difficult to manage prev_id & next_id.

```<code>const dll = [
  {id: '14', prev_id: null, next_id: '41'}, // <- source
  {id: '41', prev_id: '14', next_id: '22'},
  {id: '22', prev_id: '41', next_id: '45'},
  {id: '45', prev_id: '22', next_id: null}, // <- destination
]
</code>```

For example, I want to move object 14 to the end, so the array should become:

```<code>const dll_result = [
  {id: '41', prev_id: null, next_id: '22'},
  {id: '22', prev_id: '41', next_id: '45'},
  {id: '45', prev_id: '22', next_id: '14'},
  {id: '14', prev_id: '45', next_id: null},
]
</code>```

The hardest thing what I need to do to change the prev_id & next_id of the objects?

My attempt:

.as-console-wrapper { max-height: 100% !important; top: 0; }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script type="text/javascript" charset="utf8" src="//cdn.jsdelivr.net/npm/ramda@0.27.0/dist/ramda.min.js"></script>
<script>
  const {move} = R

  const dll = [
    {id: '14', prev_id: null, next_id: '41'}, //<- source
    {id: '41', prev_id: '14', next_id: '22'}, //<- destination
    {id: '22', prev_id: '41', next_id: '45'},
    {id: '45', prev_id: '22', next_id: null},
  ]

  const fromId = '14'
  const toId = '41'

  const fromItem = dll.find(item => item.id === fromId)
  const toItem = dll.find(item => item.id === toId)

  const updated = dll.map(item => {
    if (item.id === fromId) {
      return {...item, prev_id: toId, next_id: toItem.next_id}
    } else if (item.prev_id === fromId) {
      return {...item, prev_id: fromItem.prev_id}
    } else if (item.id === toItem.next_id) {
      return {...item, prev_id: fromId}
    } else if (item.id === toId) {
      return {...item, next_id: fromId}
    } else {
      return item
    }
  })

  console.log(JSON.stringify(move(0, 1, updated), null, 2))
</script></code>```

答:
I'd do something like this,
hope it helps...

Moving an item in a double-linked list is not ideal since then you need to shift all the links...

const move = (id, toIndex, list) => {
  const fromIndex = R.findIndex(
    R.whereEq({ id }),
    list,
  );

  return R.move(fromIndex, toIndex, list);
};

// R.nth would cause cyclic dbl-list
const pickId = (i, list) => R.propOr(null, 'id', list[i]);

const shiftLinks = (item, i, list) => R.mergeRight(item, {
  prev: pickId(R.dec(i), list),
  next: pickId(R.inc(i), list),
});

const moveById = R.pipe(
  move,
  R.addIndex(R.map)(shiftLinks),
);

// ==
const data = [
  {id: 'first', prev: null, next: 'second'},
  {id: 'second', prev: 'first', next: 'third'},
  {id: 'third', prev: 'second', next: 'fourth'},
  {id: 'fourth', prev: 'third', next: null},
];
console.log(
  // id: 'second', toIndex: 3, data: data
  moveById('second', 3, data),
);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.0/ramda.js" integrity="sha256-buL0byPvI/XRDFscnSc/e0q+sLA65O9y+rbF+0O/4FE=" crossorigin="anonymous"></script></code>```

Title: Move in doubly linked list Ramda.js

Body:
When I started using a doubly linked list, it became more difficult to manage prev_id & next_id.

const dll = [
  {id: '14', prev_id: null, next_id: '41'}, // <- source
  {id: '41', prev_id: '14', next_id: '22'},
  {id: '22', prev_id: '41', next_id: '45'},
  {id: '45', prev_id: '22', next_id: null}, // <- destination
]

For example, I want to move object 14 to the end, so the array should become:

const dll_result = [
  {id: '41', prev_id: null, next_id: '22'},
  {id: '22', prev_id: '41', next_id: '45'},
  {id: '45', prev_id: '22', next_id: '14'},
  {id: '14', prev_id: '45', next_id: null},
]

The hardest thing what I need to do to change the prev_id & next_id of the objects?

My attempt:

.as-console-wrapper { max-height: 100% !important; top: 0; }

Body:
I'd do something like this,
hope it helps...

Moving an item in a double-linked list is not ideal since then you need to shift all the links...

const move = (id, toIndex, list) => {
  const fromIndex = R.findIndex(
    R.whereEq({ id }),
    list,
  );

  return R.move(fromIndex, toIndex, list);
};

// R.nth would cause cyclic dbl-list
const pickId = (i, list) => R.propOr(null, 'id', list[i]);

const shiftLinks = (item, i, list) => R.mergeRight(item, {
  prev: pickId(R.dec(i), list),
  next: pickId(R.inc(i), list),
});

const moveById = R.pipe(
  move,
  R.addIndex(R.map)(shiftLinks),
);

// ==
const data = [
  {id: 'first', prev: null, next: 'second'},
  {id: 'second', prev: 'first', next: 'third'},
  {id: 'third', prev: 'second', next: 'fourth'},
  {id: 'fourth', prev: 'third', next: null},
];
console.log(
  // id: 'second', toIndex: 3, data: data
  moveById('second', 3, data),
);

<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.0/ramda.js" integrity="sha256-buL0byPvI/XRDFscnSc/e0q+sLA65O9y+rbF+0O/4FE=" crossorigin="anonymous"></script>


答:
=== is strict equal.

Undefined and null are not the same thing.

== uses type coercion.

null and undefined coerce to each other.

Title: undefined and null


问:
Cannot get the value of the position sensor in webots::PositionSensor object
I am trying to get the position of a PositionSensor using Webots. I am using the e-puck robot and my code is below

```<code>#include <webots/Robot.hpp>
#include <webots/Motor.hpp>
#include <iostream>

#define TIME_STEP 64
#define MAX_SPEED 6.28

// All the webots classes are defined in the "webots" namespace
using namespace webots;

int main(int argc, char **argv)
{
  Robot *robot = new Robot();

  Motor *leftMotor = robot->getMotor("left wheel motor");
  Motor *rightMotor = robot->getMotor("right wheel motor");
  PositionSensor *leftSensor = robot->getPositionSensor("left wheel sensor");

  leftMotor->setPosition(INFINITY);
  rightMotor->setPosition(INFINITY);

  leftMotor->setVelocity(MAX_SPEED);
  rightMotor->setVelocity(MAX_SPEED);

  while (robot->step(TIME_STEP) != -1)
  {
    std::cout << leftSensor->getValue() << std::endl;
  };

  delete robot;
  return 0;
}
</code>```

When I attempt top build this code I get the following error:

```<code>TestController.cpp: In function ‘int main(int, char**)’:
TestController.cpp:38:28: error: invalid use of incomplete type ‘class webots::PositionSensor’
     std::cout << leftSensor->getValue() << std::endl;
                            ^~
In file included from TestController.cpp:1:0:
/usr/local/webots/include/controller/cpp/webots/Robot.hpp:42:9: note: forward declaration of ‘class webots::PositionSensor’
   class PositionSensor;
         ^~~~~~~~~~~~~~
</code>```

I cannot understand why trying to get the value which should return a double in the print statement. Thank you

The header for the PositionSensor class is below

```<code>// Copyright 1996-2020 Cyberbotics Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#ifndef POSITION_SENSOR_HPP
#define POSITION_SENSOR_HPP

#include <webots/Device.hpp>

namespace webots {
  class Brake;
  class Motor;

  class PositionSensor : public Device {
  public:
    typedef enum { ROTATIONAL = 0, LINEAR } Type;

    explicit PositionSensor(const std::string &name) :
      Device(name),
      brake(NULL),
      motor(NULL) {}  // Use Robot::getPositionSensor() instead
    virtual ~PositionSensor() {}
    virtual void enable(int samplingPeriod);  // milliseconds
    virtual void disable();
    int getSamplingPeriod() const;
    double getValue() const;  // rad or meters
    Type getType() const;

    Brake *getBrake();
    Motor *getMotor();

    // internal functions
    int getBrakeTag() const;
    int getMotorTag() const;

    enum {  // kept for backward compatibility R2018b
      ANGULAR = 0
    };

  private:
    Brake *brake;
    Motor *motor;
  };
}  // namespace webots

#endif  // POSITION_SENSOR_HPP

</code>```

答:
There are several issues in your code:

You are not adding the position sensors include: #include <webots/PositionSensor.hpp

You need to enable the sensor: leftSensor->enable(TIME_STEP);

Here is how your code should look like:

```<code>#include <webots/Robot.hpp>
#include <webots/Motor.hpp>
#include <webots/PositionSensor.hpp
#include <iostream>

#define TIME_STEP 64
#define MAX_SPEED 6.28

// All the webots classes are defined in the "webots" namespace
using namespace webots;

int main(int argc, char **argv)
{
  Robot *robot = new Robot();

  Motor *leftMotor = robot->getMotor("left wheel motor");
  Motor *rightMotor = robot->getMotor("right wheel motor");
  PositionSensor *leftSensor = robot->getPositionSensor("left wheel sensor");

  leftSensor->enable(TIME_STEP);

  leftMotor->setPosition(INFINITY);
  rightMotor->setPosition(INFINITY);

  leftMotor->setVelocity(MAX_SPEED);
  rightMotor->setVelocity(MAX_SPEED);

  while (robot->step(TIME_STEP) != -1)
  {
    std::cout << leftSensor->getValue() << std::endl;
  };

  delete robot;
  return 0;
}
</code>```

I would strongly recommend following the tutorial about robot programming: in Webots: https://cyberbotics.com/doc/guide/tutorial-4-more-about-controllers?tab-language=c++

Body:
I am trying to get the position of a PositionSensor using Webots. I am using the e-puck robot and my code is below

#include <webots/Robot.hpp>
#include <webots/Motor.hpp>
#include <iostream>

#define TIME_STEP 64
#define MAX_SPEED 6.28

// All the webots classes are defined in the "webots" namespace
using namespace webots;

int main(int argc, char **argv)
{
  Robot *robot = new Robot();

  Motor *leftMotor = robot->getMotor("left wheel motor");
  Motor *rightMotor = robot->getMotor("right wheel motor");
  PositionSensor *leftSensor = robot->getPositionSensor("left wheel sensor");

  leftMotor->setPosition(INFINITY);
  rightMotor->setPosition(INFINITY);

  leftMotor->setVelocity(MAX_SPEED);
  rightMotor->setVelocity(MAX_SPEED);

  while (robot->step(TIME_STEP) != -1)
  {
    std::cout << leftSensor->getValue() << std::endl;
  };

  delete robot;
  return 0;
}

When I attempt top build this code I get the following error:

TestController.cpp: In function ‘int main(int, char**)’:
TestController.cpp:38:28: error: invalid use of incomplete type ‘class webots::PositionSensor’
     std::cout << leftSensor->getValue() << std::endl;
                            ^~
In file included from TestController.cpp:1:0:
/usr/local/webots/include/controller/cpp/webots/Robot.hpp:42:9: note: forward declaration of ‘class webots::PositionSensor’
   class PositionSensor;
         ^~~~~~~~~~~~~~

I cannot understand why trying to get the value which should return a double in the print statement. Thank you

The header for the PositionSensor class is below

// Copyright 1996-2020 Cyberbotics Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#ifndef POSITION_SENSOR_HPP
#define POSITION_SENSOR_HPP

#include <webots/Device.hpp>

namespace webots {
  class Brake;
  class Motor;

  class PositionSensor : public Device {
  public:
    typedef enum { ROTATIONAL = 0, LINEAR } Type;

    explicit PositionSensor(const std::string &name) :
      Device(name),
      brake(NULL),
      motor(NULL) {}  // Use Robot::getPositionSensor() instead
    virtual ~PositionSensor() {}
    virtual void enable(int samplingPeriod);  // milliseconds
    virtual void disable();
    int getSamplingPeriod() const;
    double getValue() const;  // rad or meters
    Type getType() const;

    Brake *getBrake();
    Motor *getMotor();

    // internal functions
    int getBrakeTag() const;
    int getMotorTag() const;

    enum {  // kept for backward compatibility R2018b
      ANGULAR = 0
    };

  private:
    Brake *brake;
    Motor *motor;
  };
}  // namespace webots

#endif  // POSITION_SENSOR_HPP

Body:
There are several issues in your code:

You are not adding the position sensors include: #include <webots/PositionSensor.hpp

You need to enable the sensor: leftSensor->enable(TIME_STEP);

Here is how your code should look like:

#include <webots/Robot.hpp>
#include <webots/Motor.hpp>
#include <webots/PositionSensor.hpp
#include <iostream>

#define TIME_STEP 64
#define MAX_SPEED 6.28

// All the webots classes are defined in the "webots" namespace
using namespace webots;

int main(int argc, char **argv)
{
  Robot *robot = new Robot();

  Motor *leftMotor = robot->getMotor("left wheel motor");
  Motor *rightMotor = robot->getMotor("right wheel motor");
  PositionSensor *leftSensor = robot->getPositionSensor("left wheel sensor");

  leftSensor->enable(TIME_STEP);

  leftMotor->setPosition(INFINITY);
  rightMotor->setPosition(INFINITY);

  leftMotor->setVelocity(MAX_SPEED);
  rightMotor->setVelocity(MAX_SPEED);

  while (robot->step(TIME_STEP) != -1)
  {
    std::cout << leftSensor->getValue() << std::endl;
  };

  delete robot;
  return 0;
}

I would strongly recommend following the tutorial about robot programming: in Webots: https://cyberbotics.com/doc/guide/tutorial-4-more-about-controllers?tab-language=c++