问:
Does not contain a static 'main' method suitable for an entry point
I began organizing my code to day into seperarate .cs files, and in order to allow the methods that work with the UI to continue to do so I would create the .cs code under the same namespace and public partial class name so the methods could be inter-operable.

My header look like this in four files, including my main core file that calls:

```<code>public shell()
{
InitializeComponent();
}
</code>```

Header area of .cs files that work with the UI (and seem to be causing this new conflict):

```<code>using System;
using System.Windows.Forms;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;
using System.Data.SqlServerCe;
using System.Diagnostics;
using System.Threading;
using System.Collections.Specialized;
using System.Net;
using System.Runtime.InteropServices;
using watin = WatiN.Core;
using WatiN.Core.Native.InternetExplorer;
using System.Web;

namespace WindowsFormsApplication1
{

    public partial class shell : Form
    {
</code>```

Now when I try to debug/preview my application (BTW this is a Windows Application within Visual Studio 2010 Express) I get this error message:

Does not contain a static 'main' method suitable for an entry point

I looked in the application properties in Application->Startup object, but it offers me no options. How can I inform the application to begin at the .cs file that has my InitializeComponent(); command?

I've looked around so far without a solution.

The properties on each .cs file are set to 'Compile'.

I do not see an App.xaml file in my Solutions explorer but I do see a app.config file.

I'm still very new and this is my first attempt at an organizing method with c# code.

答:
Had this problem in VS 2017 caused by:

static async Task Main(string[] args)

(Feature 'async main' is not available in C# 7.0. Please use language version 7.1 or greater)

Adding

<LangVersion>latest</LangVersion>

to app.csproj helped.

Body:
I began organizing my code to day into seperarate .cs files, and in order to allow the methods that work with the UI to continue to do so I would create the .cs code under the same namespace and public partial class name so the methods could be inter-operable.

My header look like this in four files, including my main core file that calls:

public shell()
{
InitializeComponent();
}

Header area of .cs files that work with the UI (and seem to be causing this new conflict):

using System;
using System.Windows.Forms;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;
using System.Data.SqlServerCe;
using System.Diagnostics;
using System.Threading;
using System.Collections.Specialized;
using System.Net;
using System.Runtime.InteropServices;
using watin = WatiN.Core;
using WatiN.Core.Native.InternetExplorer;
using System.Web;

namespace WindowsFormsApplication1
{

    public partial class shell : Form
    {

Now when I try to debug/preview my application (BTW this is a Windows Application within Visual Studio 2010 Express) I get this error message:

Does not contain a static 'main' method suitable for an entry point

I looked in the application properties in Application->Startup object, but it offers me no options. How can I inform the application to begin at the .cs file that has my InitializeComponent(); command?

I've looked around so far without a solution.

The properties on each .cs file are set to 'Compile'.

I do not see an App.xaml file in my Solutions explorer but I do see a app.config file.

I'm still very new and this is my first attempt at an organizing method with c# code.


来源: stackexchange

问:
Retrain Multiclassification ITransformer
I created a ITransformer model based on the SdcaMaximumEntropy trainer from the MulticlassClassification :

```<code>var trainingPipeline = pipeline.Append(mlContext.MulticlassClassification.Trainers.SdcaMaximumEntropy())
                    .Append(mlContext.Transforms.Conversion.MapKeyToValue("PredictedLabel"));
ITransformer trainedModel = trainingPipeline.Fit(splitTrainSet);
</code>```

Now I want to retrain it with the Fit method by applying the original model parameters :

```<code>var originalModelParameters = ((MulticlassPredictionTransformer<object>)model).Model as MaximumEntropyModelParameters;
            model = mlContext.MulticlassClassification.Trainers.SdcaMaximumEntropy().Fit(newData, originalModelParameters);
</code>```

But I get an error on the Fit method :

No overload for method 'Fit' takes 2 arguments

So I'm aware that the Fit method from the SdcaMaximumEntropy trainer doesn't have the required Fit method with 2 arguments, but I am wondering how can I retrain my multiclassification model without it ?

答:
Unfortunately, the SdcaMaximumEntrpy trainer isn't in the list of trainers that can be retrained. Perhaps you can try LbfgsMaximumEntropyMulticlassTrainer instead?

Hopefully, in the future, more trainers will be able to be retrained.

ContentLicense: CC BY-SA 4.0

Body:
I created a ITransformer model based on the SdcaMaximumEntropy trainer from the MulticlassClassification :

var trainingPipeline = pipeline.Append(mlContext.MulticlassClassification.Trainers.SdcaMaximumEntropy())
                    .Append(mlContext.Transforms.Conversion.MapKeyToValue("PredictedLabel"));
ITransformer trainedModel = trainingPipeline.Fit(splitTrainSet);

Now I want to retrain it with the Fit method by applying the original model parameters :

var originalModelParameters = ((MulticlassPredictionTransformer<object>)model).Model as MaximumEntropyModelParameters;
            model = mlContext.MulticlassClassification.Trainers.SdcaMaximumEntropy().Fit(newData, originalModelParameters);

But I get an error on the Fit method :

No overload for method 'Fit' takes 2 arguments

So I'm aware that the Fit method from the SdcaMaximumEntropy trainer doesn't have the required Fit method with 2 arguments, but I am wondering how can I retrain my multiclassification model without it ?


问:
Shape "8" looped animation with SVG <animate> only
I'm having massive headaches trying to fin the sweet-spot to achieve "8" shape animation using the combination of just <animate attributeName="cx"> and <attributeName="cy">.

I'll like to do it using that since it seems, by my metrics, that it's the most performant in terms of FPS, CPU and GPU usage.

Quick demo of the "ideal" motion path: https://codepen.io/ivancis/pen/eYmZowz

答:
I was looking into a similar thing and came across this answer. @Alexandr_TT's answer got me thinking about a more flexible way to do this, without using a graphics editor (like Inkscape etc.)

I came up with the following idea:

Use the <AnimateMotion/> for the first loop.

Fire a setInterval every X milliseconds and each time it fires to capture the centre point of the circle (from circle.getBoundingClientRect() and svg.matrixTransform())

Push these x and y values to two arrays to capture them

When the AnimateMotion ends, clear the current setInterval and push the first element also to the end of each of the arrays (to close the loop)

Remove the <AnimateMotion/> tag from the DOM

Push these arrays to the values attribute of the <animate id="cx" attributeName="cx" values="" .../> and <animate id="cy" attributeName="cy" values="" .../> tags

begin both of these animate tags with cx.beginElement() and cy.beginElement()

You could just be happy with this performance-wise, or you could copy-paste the DOM elements with their values="..." attributes and save that as your new master file, essentially achieving what @Alexandr_TT did with the graphics editor. Of course, this method I am showing is flexible if you decide to change your path etc.

Demo: https://codepen.io/Alexander9111/pen/VwLaNEN

HTML:

```<code><circle id="circle" class="circle" cx="0" cy="00" r="125">
      <animateMotion
           path="M162.9,150c6.8-0.2,12.1-5.7,12.1-12.5c0-6.9-5.6-12.5-12.5-12.5c-6.8,0-12.3,5.4-12.5,12.2v25.7 c-0.2,6.8-5.7,12.2-12.5,12.2c-6.9,0-12.5-5.6-12.5-12.5c0-6.8,5.4-12.3,12.1-12.5L162.9,150z"
           dur="4s" begin="0s"
           epeatCount="1" fill="freeze"
           calcMode="linear"
           fill="freeze">
      </animateMotion>
      <animate id="cx" attributeName="cx" values="" dur="4s" repeatCount="indefinite" begin="indefinite"/>
      <animate id="cy" attributeName="cy" values="" dur="4s" repeatCount="indefinite" begin="indefinite"/>
</circle>
</code>```

JS:

```<code>const svg = document.querySelector('svg');
const animateElem = document.querySelector('animateMotion');
const circle = document.querySelector('#circle');
const cx = document.querySelector('#cx');
const cy = document.querySelector('#cy');
let myInterval;
let valuesX = [];
let valuesY = [];

function startFunction() {
  const box = circle.getBoundingClientRect();
  var pt = svg.createSVGPoint();
  pt.x = (box.left + box.right) / 2;
  pt.y = (box.top + box.bottom) / 2;
  var svgP = pt.matrixTransform(svg.getScreenCTM().inverse());
  console.log(svgP.x,svgP.y)
  valuesX.push(svgP.x);
  valuesY.push(svgP.y);
}

function endFunction() {
  animateElem.parentNode.removeChild(animateElem);
  clearInterval(myInterval)
  valuesX.push(valuesX[0]);
  valuesY.push(valuesY[0]);
  cx.setAttribute('values', valuesX.join('; '));
  cy.setAttribute('values', valuesY.join('; '));
  circle.setAttribute('cx', 0);
  circle.setAttribute('cy', 0);
  cx.beginElement();
  cy.beginElement();
}

animateElem.addEventListener('beginEvent', () => {
  console.log('beginEvent fired');
  myInterval = setInterval(startFunction, 50);
})

animateElem.addEventListener('endEvent', () => {
  console.log('endEvent fired');
  endFunction();
})
</code>```

Body:
I was looking into a similar thing and came across this answer. @Alexandr_TT's answer got me thinking about a more flexible way to do this, without using a graphics editor (like Inkscape etc.)

I came up with the following idea:

Use the <AnimateMotion/> for the first loop.

Fire a setInterval every X milliseconds and each time it fires to capture the centre point of the circle (from circle.getBoundingClientRect() and svg.matrixTransform())

Push these x and y values to two arrays to capture them

When the AnimateMotion ends, clear the current setInterval and push the first element also to the end of each of the arrays (to close the loop)

Remove the <AnimateMotion/> tag from the DOM

Push these arrays to the values attribute of the <animate id="cx" attributeName="cx" values="" .../> and <animate id="cy" attributeName="cy" values="" .../> tags

begin both of these animate tags with cx.beginElement() and cy.beginElement()

You could just be happy with this performance-wise, or you could copy-paste the DOM elements with their values="..." attributes and save that as your new master file, essentially achieving what @Alexandr_TT did with the graphics editor. Of course, this method I am showing is flexible if you decide to change your path etc.

Demo: https://codepen.io/Alexander9111/pen/VwLaNEN

HTML:

<circle id="circle" class="circle" cx="0" cy="00" r="125">
      <animateMotion
           path="M162.9,150c6.8-0.2,12.1-5.7,12.1-12.5c0-6.9-5.6-12.5-12.5-12.5c-6.8,0-12.3,5.4-12.5,12.2v25.7 c-0.2,6.8-5.7,12.2-12.5,12.2c-6.9,0-12.5-5.6-12.5-12.5c0-6.8,5.4-12.3,12.1-12.5L162.9,150z"
           dur="4s" begin="0s"
           epeatCount="1" fill="freeze"
           calcMode="linear"
           fill="freeze">
      </animateMotion>
      <animate id="cx" attributeName="cx" values="" dur="4s" repeatCount="indefinite" begin="indefinite"/>
      <animate id="cy" attributeName="cy" values="" dur="4s" repeatCount="indefinite" begin="indefinite"/>
</circle>

JS:

const svg = document.querySelector('svg');
const animateElem = document.querySelector('animateMotion');
const circle = document.querySelector('#circle');
const cx = document.querySelector('#cx');
const cy = document.querySelector('#cy');
let myInterval;
let valuesX = [];
let valuesY = [];

function startFunction() {
  const box = circle.getBoundingClientRect();
  var pt = svg.createSVGPoint();
  pt.x = (box.left + box.right) / 2;
  pt.y = (box.top + box.bottom) / 2;
  var svgP = pt.matrixTransform(svg.getScreenCTM().inverse());
  console.log(svgP.x,svgP.y)
  valuesX.push(svgP.x);
  valuesY.push(svgP.y);
}

function endFunction() {
  animateElem.parentNode.removeChild(animateElem);
  clearInterval(myInterval)
  valuesX.push(valuesX[0]);
  valuesY.push(valuesY[0]);
  cx.setAttribute('values', valuesX.join('; '));
  cy.setAttribute('values', valuesY.join('; '));
  circle.setAttribute('cx', 0);
  circle.setAttribute('cy', 0);
  cx.beginElement();
  cy.beginElement();
}

animateElem.addEventListener('beginEvent', () => {
  console.log('beginEvent fired');
  myInterval = setInterval(startFunction, 50);
})

animateElem.addEventListener('endEvent', () => {
  console.log('endEvent fired');
  endFunction();
})


问:
How can I delete the SQLite DLL when I'm finished with it if the OS thinks it's still in use?
How can I unlock or delete a file that is in use, so that I can delete it? The file in question is used by my own application.

More specifically, my application is using the freeware Zeos Lib. When opening and saving my database the sqlite3.dll file must reside in the same directory as my application to work correctly.

I want my application to be 100% standalone, so I have added the sqlite3.dll as RC_DATA to my project, and whenever I need to use it (ie, open or save database), I extract it to the same folder as my application. Once the open or save operation has completed, I would like to delete the sqlite3.dll file, and no one would even know it was there or have to worry about missing libraries etc. (While I can appreciate that some of you may not like the idea of storing the libraries inside the application, I have my reasons for doing this: I don't want my end-users knowing what is behind the functioning of my application (SQL), and they also don't need to worry about missing dynamic link libraries.)

The problem is, I can successfully extract the sqlite3.dll and use it for my operations, but the file becomes locked by my application (until I close my application), which brings me to either:

Force unlock the sqlite3.dll file, without closing my application

Force delete the sqlite3.dll file

Unless of course there is another suggestion?

Here is a sample of extracting and using it. No direct calls need to be made such as LoadLibrary etc from my part; the Zeos Lib units must take care of this, so long as the sqlite3.dll is in the same directory as the application.

```<code>procedure ExtractResource(ResName: String; Filename: String);
var
  ResStream: TResourceStream;
begin
  ResStream:= TResourceStream.Create(HInstance, ResName, RT_RCDATA);
  try
    ResStream.Position:= 0;
    ResStream.SaveToFile(Filename);
  finally
    ResStream.Free;
  end;
end;

//Open procedure
var
  sFileName: String = ExtractFilePath(ParamStr(0)) + 'Sqlite3.dll';

if OpenDialog1.Execute then
begin
  ExtractResource('RES_SQLITE3', sFileName);
  ... //process my database
  ...
  ... // finished opening database
  if FileExists(sFileName) then
        DeleteFile(sFileName);
end;
</code>```

EDIT

I think what I am attempting to do is not very practical, it is not a good idea to this as STATUS_ACCESS_DENIED earlier commented on. I have decided it is best not to proceed with what I set out to do.

答:
There's a couple solutions available that allow you to compile the SQLite libraries into your exe, rather than using the DLL.  I think that'd be a much better approach if you really must have a single file executable.  What you are basically trying to duplicate by extracting/deleting the DLL is the functionality of an installer, and you really shouldnt.  That approach is just asking for support problems.

Also keep in mind that your app may need to run with administrator rights to be able to extract the dll and save it into the program files directory.

If you can live with a DLL being installed along with the executable, you can rename the DLL file to something else (ie, Database.dll), and make changes in the zeos code so that it points to the new DLL name.  Then the SQLite functionality would not be immediately apparent.

ContentLicense: CC BY-SA 3.0

Body:
How can I unlock or delete a file that is in use, so that I can delete it? The file in question is used by my own application.

More specifically, my application is using the freeware Zeos Lib. When opening and saving my database the sqlite3.dll file must reside in the same directory as my application to work correctly.

I want my application to be 100% standalone, so I have added the sqlite3.dll as RC_DATA to my project, and whenever I need to use it (ie, open or save database), I extract it to the same folder as my application. Once the open or save operation has completed, I would like to delete the sqlite3.dll file, and no one would even know it was there or have to worry about missing libraries etc. (While I can appreciate that some of you may not like the idea of storing the libraries inside the application, I have my reasons for doing this: I don't want my end-users knowing what is behind the functioning of my application (SQL), and they also don't need to worry about missing dynamic link libraries.)

The problem is, I can successfully extract the sqlite3.dll and use it for my operations, but the file becomes locked by my application (until I close my application), which brings me to either:

Force unlock the sqlite3.dll file, without closing my application

Force delete the sqlite3.dll file

Unless of course there is another suggestion?

Here is a sample of extracting and using it. No direct calls need to be made such as LoadLibrary etc from my part; the Zeos Lib units must take care of this, so long as the sqlite3.dll is in the same directory as the application.

procedure ExtractResource(ResName: String; Filename: String);
var
  ResStream: TResourceStream;
begin
  ResStream:= TResourceStream.Create(HInstance, ResName, RT_RCDATA);
  try
    ResStream.Position:= 0;
    ResStream.SaveToFile(Filename);
  finally
    ResStream.Free;
  end;
end;

//Open procedure
var
  sFileName: String = ExtractFilePath(ParamStr(0)) + 'Sqlite3.dll';

if OpenDialog1.Execute then
begin
  ExtractResource('RES_SQLITE3', sFileName);
  ... //process my database
  ...
  ... // finished opening database
  if FileExists(sFileName) then
        DeleteFile(sFileName);
end;

EDIT

I think what I am attempting to do is not very practical, it is not a good idea to this as STATUS_ACCESS_DENIED earlier commented on. I have decided it is best not to proceed with what I set out to do.


问:
AD password update via Powershell
Too all Powershell Experts: I need some help to figure out why this is working incorrectly. What I mean incorrectly, the accounts in CSV password get updated with a random password and email is sent to the users but i don't under why they are getting the same password, and everyaccount in the AD is addressed. See email output:

Firstuser email:

```<code>Hello Guest DefaultAccount user1, user2, user3, user4 test John Doe,
Your AD Account user1, password has been updated to e,wQlsGfBE;J'4
</code>```

Second useremail

```<code> Hello Guest DefaultAccount user1, user2, user3, user4 test John Doe,
Your AD Account jdoe, password has been updated to e,wQlsGfBE;J'4
</code>```

what I'm trying to accomplish are as follows:

List item

Import one column cvs with just "samAccountName"

reset password of the accounts listed in the csv with a random generated 20 character long password

Email the AD account associated email address with the new password. (I'm doing this because their email address if different from their AD Account), so they are able to receive their email.

Import-Module ActiveDirectory
# Import AD user objects and store in users variables
$users = Get-ADUser -Filter *  -Properties Name, EmailAddress,SamAccountName | Select SamAccountName,Name,EmailAddress

$Name = $users.Name
$SamAccountName = $users.SamAccountName
$EmailAddress = $users.EmailAddress

#Date
$date = (Get-Date -Format F)

#Generate a random password and store in newpwd
$newpwd = -join (33..126|%{[char]$_}|Get-Random -Count 20)
$newPassword = ConvertTo-SecureString -AsPlainText "$newpwd" -Force

# Import users from CSV
Import-Csv "C:\Userlist.csv" | ForEach-Object {
$samAccountName= $_."samAccountName"

        #Proceed with password reset
            Set-ADAccountPassword -Identity $samAccountName -NewPassword $newPassword -Reset
            Set-AdUser -Identity $samAccountName -ChangePasswordAtLogon $true

#Server configuration
$smtpServer =""
$SmtpPort = ""
# sending option
$from = "it-operation@example.com"
$to = $EmailAddress
$subject  ="AD Password updated - " + $date
$priority = "Normal"
$from = ""

$body = @"
Hello $name,

Your AD Account $samAccountName, password has been updated to $newpwd
"@
try {
# Send the report email
Send-MailMessage -To $to -Subject $subject -BodyAsHtml -body $body -SmtpServer $smtpServer -Port $SmtpPort -From $From -Priority $priority
}
catch{
    write-warning "error in sending. $_"
}  # End User Processing

    }```

The Account password is getting updated, but just can't send the emai

答:
Don't accept my answer. I'm just building off what @Theo did.  (I'd love an up-vote though)

```<code>Import-Module ActiveDirectory

# Import AD user objects and store in users variables
$Users = @{}
Get-ADUser -Filter *  -Properties Name,EmailAddress,SamAccountName | Select-Object SamAccountName,Name,EmailAddress |
ForEach-Object{ $Users.Add( $_.samAccountName, $_ ) }

#Date
$Date = (Get-Date -Format F)

# Generate a random password and store in newPassword
$newPassword = -join ( 33..126 | ForEach-Object{ [char]$_ }| Get-Random -Count 20 )
$newPassword = ConvertTo-SecureString -AsPlainText "$newPassword" -Force
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
# Move to the loop if you want each user's pwd to be different!!!

# Put this here so you can indent the loop easier...
$BaseBody =
@"
Hello %NAME%, <br>
Your AD Account %SAMACCOUNTNAME%, password has been updated to %NEWPASSWORD%
"@

# Server configuration & recipien configurations...:
$MailParams = @{
    $smtpServer = "YorServer.example.com" #MAKE SURE YOU CHANGE THIS
    $SmtpPort   = 25
    $from       = "it-operation@example.com"
    $To         = ""
    $subject    ="AD Password updated - " + $date
    $Body       = ""
}
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
# Removed -Priority if it's alwasy going to be normal you don't need it.

# Import users from CSV
Import-Csv "C:\Userlist.csv" |
ForEach-Object {
    $samAccountName = $_."samAccountName"

    # Proceed with password reset
    Set-ADAccountPassword -Identity $samAccountName -NewPassword $newPassword -Reset
    Set-ADUser -Identity $samAccountName -ChangePasswordAtLogon $true

    # Get the Name & Email address from the $Users Hash...:
    $EmailAddress = $Users[$samAccountName].EmailAddress
    $Name         = $Users[$samAccountName].Name

    # Reset the To & Body values
    $MailParams['To']   = $EmailAddress
    $MailParams['Body'] = $BaseBody.Replace('%NAME%', $Name).Replace('%SAMACCOUNTNAME%', $samAccountName).Replace('%NEWPASSWORD%', $newPassword)

    try { # Send the report email
        Send-MailMessage @MailParams -ErrorAction Stop
    }
    catch{
        write-warning "Error in sending : $_"
    }
} # End User Processing
</code>```

Used a hash table to store the AD user objects so you don't have to re-execute a Where{} on every loop iteration.  Depending on the number of users this could be quite a bit faster.  When relating data between 2 sources I gravitate toward a hash tables.

Moved the $Body var out of the loop.  Here strings don't like to be indented, by moving it out we don't have to interfere with the loop indentation; improving readability.  Then inside the loop we can get the actual body by doing some string replacement.

I also placed the $MailParams parameter hash outside the loop. Then inside the loop I reset the 2 keys that vary.  Nitpicking, but I'd rather not declare the hash on every loop iteration either.

$Reused the $newPassword variable rather than have the extra $newpdw variable just laying around.

Expanded the aliases, just because PSScriptAnalyzer complains about it...

Obviously this is untested!  But, I hope it's helpful...

Title: AD password update via Powershell

Body:
Too all Powershell Experts: I need some help to figure out why this is working incorrectly. What I mean incorrectly, the accounts in CSV password get updated with a random password and email is sent to the users but i don't under why they are getting the same password, and everyaccount in the AD is addressed. See email output:

Firstuser email:

Hello Guest DefaultAccount user1, user2, user3, user4 test John Doe,
Your AD Account user1, password has been updated to e,wQlsGfBE;J'4

Second useremail

 Hello Guest DefaultAccount user1, user2, user3, user4 test John Doe,
Your AD Account jdoe, password has been updated to e,wQlsGfBE;J'4

what I'm trying to accomplish are as follows:

List item

Import one column cvs with just "samAccountName"

reset password of the accounts listed in the csv with a random generated 20 character long password

Email the AD account associated email address with the new password. (I'm doing this because their email address if different from their AD Account), so they are able to receive their email.

Import-Module ActiveDirectory
# Import AD user objects and store in users variables
$users = Get-ADUser -Filter *  -Properties Name, EmailAddress,SamAccountName | Select SamAccountName,Name,EmailAddress

$Name = $users.Name
$SamAccountName = $users.SamAccountName
$EmailAddress = $users.EmailAddress

#Date
$date = (Get-Date -Format F)

#Generate a random password and store in newpwd
$newpwd = -join (33..126|%{[char]$_}|Get-Random -Count 20)
$newPassword = ConvertTo-SecureString -AsPlainText "$newpwd" -Force

# Import users from CSV
Import-Csv "C:\Userlist.csv" | ForEach-Object {
$samAccountName= $_."samAccountName"

        #Proceed with password reset
            Set-ADAccountPassword -Identity $samAccountName -NewPassword $newPassword -Reset
            Set-AdUser -Identity $samAccountName -ChangePasswordAtLogon $true

#Server configuration
$smtpServer =""
$SmtpPort = ""
# sending option
$from = "it-operation@example.com"
$to = $EmailAddress
$subject  ="AD Password updated - " + $date
$priority = "Normal"
$from = ""

$body = @"
Hello $name,

Your AD Account $samAccountName, password has been updated to $newpwd
"@
try {
# Send the report email
Send-MailMessage -To $to -Subject $subject -BodyAsHtml -body $body -SmtpServer $smtpServer -Port $SmtpPort -From $From -Priority $priority
}
catch{
    write-warning "error in sending. $_"
}  # End User Processing

    }

The Account password is getting updated, but just can't send the emai

Body:
Don't accept my answer. I'm just building off what @Theo did.  (I'd love an up-vote though)

Import-Module ActiveDirectory

# Import AD user objects and store in users variables
$Users = @{}
Get-ADUser -Filter *  -Properties Name,EmailAddress,SamAccountName | Select-Object SamAccountName,Name,EmailAddress |
ForEach-Object{ $Users.Add( $_.samAccountName, $_ ) }

#Date
$Date = (Get-Date -Format F)

# Generate a random password and store in newPassword
$newPassword = -join ( 33..126 | ForEach-Object{ [char]$_ }| Get-Random -Count 20 )
$newPassword = ConvertTo-SecureString -AsPlainText "$newPassword" -Force
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
# Move to the loop if you want each user's pwd to be different!!!

# Put this here so you can indent the loop easier...
$BaseBody =
@"
Hello %NAME%, <br>
Your AD Account %SAMACCOUNTNAME%, password has been updated to %NEWPASSWORD%
"@

# Server configuration & recipien configurations...:
$MailParams = @{
    $smtpServer = "YorServer.example.com" #MAKE SURE YOU CHANGE THIS
    $SmtpPort   = 25
    $from       = "it-operation@example.com"
    $To         = ""
    $subject    ="AD Password updated - " + $date
    $Body       = ""
}
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
# Removed -Priority if it's alwasy going to be normal you don't need it.

# Import users from CSV
Import-Csv "C:\Userlist.csv" |
ForEach-Object {
    $samAccountName = $_."samAccountName"

    # Proceed with password reset
    Set-ADAccountPassword -Identity $samAccountName -NewPassword $newPassword -Reset
    Set-ADUser -Identity $samAccountName -ChangePasswordAtLogon $true

    # Get the Name & Email address from the $Users Hash...:
    $EmailAddress = $Users[$samAccountName].EmailAddress
    $Name         = $Users[$samAccountName].Name

    # Reset the To & Body values
    $MailParams['To']   = $EmailAddress
    $MailParams['Body'] = $BaseBody.Replace('%NAME%', $Name).Replace('%SAMACCOUNTNAME%', $samAccountName).Replace('%NEWPASSWORD%', $newPassword)

    try { # Send the report email
        Send-MailMessage @MailParams -ErrorAction Stop
    }
    catch{
        write-warning "Error in sending : $_"
    }
} # End User Processing

Used a hash table to store the AD user objects so you don't have to re-execute a Where{} on every loop iteration.  Depending on the number of users this could be quite a bit faster.  When relating data between 2 sources I gravitate toward a hash tables.

Moved the $Body var out of the loop.  Here strings don't like to be indented, by moving it out we don't have to interfere with the loop indentation; improving readability.  Then inside the loop we can get the actual body by doing some string replacement.

I also placed the $MailParams parameter hash outside the loop. Then inside the loop I reset the 2 keys that vary.  Nitpicking, but I'd rather not declare the hash on every loop iteration either.

$Reused the $newPassword variable rather than have the extra $newpdw variable just laying around.

Expanded the aliases, just because PSScriptAnalyzer complains about it...

Obviously this is untested!  But, I hope it's helpful...


问:
Checking position of newly added unique_ptr to priority_queue
I am switching my design to use smart pointers and I've encountered a problem with std::priority_que

I had a method that inserts new task into queue and signalizes if new task landed at the top of it:

```<code>bool foo(SchedulerTask* task)
{
  eventList_.push(task);
  return task == eventList_.top();
}
</code>```

After wrapping SchedulerTask into unique_ptr I met problem with checking its priority in container. After moving the object into queue I was not able to use it again for compare. I have end up with caching comparator member and comparing it with the top object:

```<code>bool foo(std::unique_ptr<SchedulerTask> task)
{
  const auto prio = task->getCycle(); // my priority_queue compares objects by getCycle() value

  eventList_.push(std::move(task));

  return prio >= eventList_.top()->getCycle();;
}
</code>```

Can it be done better way?

答:
You can also check before adding the task if it will end up in front:

```<code>// Assumes eventList_ uses a stateless Comparator of type Cmp
bool foo(std::unique_ptr<SchedulerTask> task)
{
  bool greater = Cmp{}(eventList_.top(), task);

  eventList_.push(std::move(task));

  return greater;
}
</code>```

Of course this can be a wrong result in a multi-threaded context, since eventList_ can change between the check and the push. But the same can happen for a check afterwards and this has to be caught by a lock.

Body:
I am switching my design to use smart pointers and I've encountered a problem with std::priority_que

I had a method that inserts new task into queue and signalizes if new task landed at the top of it:

bool foo(SchedulerTask* task)
{
  eventList_.push(task);
  return task == eventList_.top();
}

After wrapping SchedulerTask into unique_ptr I met problem with checking its priority in container. After moving the object into queue I was not able to use it again for compare. I have end up with caching comparator member and comparing it with the top object:

bool foo(std::unique_ptr<SchedulerTask> task)
{
  const auto prio = task->getCycle(); // my priority_queue compares objects by getCycle() value

  eventList_.push(std::move(task));

  return prio >= eventList_.top()->getCycle();;
}

Can it be done better way?

Body:
You can also check before adding the task if it will end up in front:

// Assumes eventList_ uses a stateless Comparator of type Cmp
bool foo(std::unique_ptr<SchedulerTask> task)
{
  bool greater = Cmp{}(eventList_.top(), task);

  eventList_.push(std::move(task));

  return greater;
}

Of course this can be a wrong result in a multi-threaded context, since eventList_ can change between the check and the push. But the same can happen for a check afterwards and this has to be caught by a lock.


问:
Not able to get the current active /selected TabITem in DevExpress DxTabControl in WPF
I have a WPF app and I am trying to Automate it using FlaUI. I am facing a problem with the DxTabControl. I have provided Automation IDs to the DxTabControl. I am using DXTabControl.ItemHeaderTemplate to generate TabItems dynamically.
According to DevExpress Team, The DXTabControl.ItemHeaderTemplate doesnt support AutoamtionPeer so a custom implementation has been added to override its default behaviour.

Now, I am able to see the TabControl and the TabItems in the Inspect.exe.
Now , my requirement is to Access the currently selected Tabitem and find the CloseButton using the AutoamtionID mentioned in the XAML below and close it. Pasting below the line again. As there would be multiple TabItems generated, I am unable to get the Currently active/Selected TabItem .

The XAML is below

```<code><dx:DXTabControl AutomationProperties.AutomationId="ViewsParentTabControl"
        MaxWidth="4000"
        MaxHeight="4000"
        Margin="1,0,-1,0"
        Focusable="False"
        ItemsSource="{Binding OpenViews}"
        SelectedIndex="{Binding SelectedTabIndex}"
        TabContentCacheMode="CacheTabsOnSelecting">
        <dx:DXTabControl.ItemHeaderTemplate>
            <DataTemplate DataType="viewModels1:OpenViewDefinitionViewModel">
                <Grid>
                    <Grid.RowDefinitions>
                        <RowDefinition Height="*" />
                        <RowDefinition Height="Auto" />
                    </Grid.RowDefinitions>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="Auto" />
                        <ColumnDefinition Width="Auto" />
                        <ColumnDefinition Width="Auto" />
                        <ColumnDefinition Width="Auto" />
                        <ColumnDefinition Width="Auto" />
                    </Grid.ColumnDefinitions>
                    <TextBlock Name="CreatedViewName"
                        MaxWidth="100"
                        Text="{Binding Data.ViewDefinition.Name}"
                        TextTrimming="CharacterEllipsis"
                        ToolTip="{Binding DisplayName}" />
                    <TextBlock Grid.Row="0" Grid.Column="1"><Run Text=" [" /><Run Text="{Binding ItemsCount, FallbackValue=0, Mode=OneWay}" /><Run Text="]" /></TextBlock>
                    <controls2:ProgressIndicator AutomationProperties.AutomationId="ProgressCurrentView"
                        Grid.Row="0"
                        Grid.Column="3"
                        Width="14"
                        Margin="4,0,0,0"
                        VerticalAlignment="Center"
                        CircleBorder="{StaticResource ListBoxItem.Foreground}"
                        CircleFill="{StaticResource ListBoxItem.Foreground}"
                        IndicatorEnabled="{Binding IsDataLoading}" />
                    <Button AutomationProperties.AutomationId="CloseCurrentViewButton"
                        Grid.Row="0"
                        Grid.Column="2"
                        Width="10"
                        Height="10"
                        Margin="10,1,0,0"
                        Padding="0"
                        HorizontalAlignment="Right"
                        BorderThickness="0"
                        Command="{Binding DataContext.CloseItemCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=dx:DXTabControl}}"
                        CommandParameter="{Binding}"
                        Focusable="False"
                        Style="{StaticResource MwButtonStyle}"
                        ToolTip="Close">
                        <Path
                            Data="F1 M 26.9166,22.1667L 37.9999,33.25L 49.0832,22.1668L 53.8332,26.9168L 42.7499,38L 53.8332,49.0834L 49.0833,53.8334L 37.9999,42.75L 26.9166,53.8334L 22.1666,49.0833L 33.25,38L 22.1667,26.9167L 26.9166,22.1667 Z"
                            Fill="White"
                            Stretch="Fill" />
                    </Button>
                </Grid>
            </DataTemplate>
        </dx:DXTabControl.ItemHeaderTemplate>
        <dx:DXTabControl.ItemTemplate>
            <DataTemplate DataType="viewModels1:OpenViewDefinitionViewModel">
                <Grid>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="*" />
                        <ColumnDefinition Width="Auto" />
                    </Grid.ColumnDefinitions>
                    <Grid.RowDefinitions>
                        <RowDefinition Height="*" />
                        <RowDefinition Height="Auto" />
                        <RowDefinition Height="Auto" />
                        <RowDefinition Height="Auto" />
                        <RowDefinition Height="Auto" />
                    </Grid.RowDefinitions>

                    <local:VoyagesGridControl />

                    <local:VoyageValidationUserControl
                        Grid.Row="1"
                        Grid.Column="0"
                        MinHeight="100"
                        MaxHeight="300"
                        Visibility="{Binding Path=IsVoyageValidationShowing, FallbackValue=Collapsed, Converter={StaticResource BooleanToVisibilityConverter}}" />
                    <local:VoyageHistoryUserControl
                        Grid.Row="2"
                        Grid.Column="0"
                        MinHeight="300"
                        MaxHeight="300"
                        Visibility="{Binding Path=IsVoyageHistoryShowing, FallbackValue=Collapsed, Converter={StaticResource BooleanToVisibilityConverter}}" />
                    <local:VesselHistoryUserControl
                        Grid.Row="3"
                        Grid.Column="0"
                        MinHeight="300"
                        MaxHeight="300"
                        Visibility="{Binding Path=IsVesselHistoryShowing, FallbackValue=Collapsed, Converter={StaticResource BooleanToVisibilityConverter}}" />
                    <local:VoyageEvents
                        Grid.Row="0"
                        Grid.RowSpan="3"
                        Grid.Column="1"
                        VerticalAlignment="Top"
                        Visibility="{Binding Path=IsVoyageEventsShowing, FallbackValue=Collapsed, Converter={StaticResource BooleanToVisibilityConverter}}" />

                    <controls2:ProgressIndicator AutomationProperties.AutomationId="showProgressForLoadingViews"
                        Grid.Row="0"
                        Grid.RowSpan="3"
                        Grid.Column="0"
                        Width="80"
                        HorizontalAlignment="Center"
                        VerticalAlignment="Center"
                        CircleBorder="{StaticResource ListBox.BorderBrush}"
                        CircleFill="{StaticResource ListBox.BorderBrush}"
                        IndicatorEnabled="{Binding IsDataLoading}" />
                    <!--  Buttons  -->
                    <Grid Grid.Row="4" Grid.Column="0">
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="Auto" />
                            <ColumnDefinition Width="Auto" />
                            <ColumnDefinition Width="Auto" />
                            <ColumnDefinition Width="*" />
                            <ColumnDefinition Width="Auto" />
                            <ColumnDefinition Width="Auto" />
                            <ColumnDefinition Width="Auto" />
                            <ColumnDefinition Width="*" />
                            <ColumnDefinition Width="Auto" />
                            <ColumnDefinition Width="Auto" />
                            <ColumnDefinition Width="Auto" />
                            <ColumnDefinition Width="Auto" />
                        </Grid.ColumnDefinitions>
                        <StackPanel
                            Grid.Column="0"
                            VerticalAlignment="Center"
                            Orientation="Horizontal">
                            <TextBlock Style="{StaticResource MwTextBlockLabelStyle}" Text="Last Refresh:" />
                            <TextBlock
                                Margin="2,0,4,0"
                                VerticalAlignment="Center"
                                Text="{Binding LoadDate, StringFormat=G}" />
                        </StackPanel>
                        <Button AutomationProperties.AutomationId="AddNewVoyageButton"
                            Grid.Row="0"
                            Grid.Column="1"
                            Padding="0"
                            Command="{Binding AddVoyagesCommand}"
                            Focusable="False"
                            Style="{StaticResource MwButtonStyle}"
                            ToolTip="Add a new voyage to this View (ALT + A)">
                            <StackPanel Orientation="Horizontal">
                                <ContentControl Height="26" Content="{StaticResource Add}" />
                                <Label Style="{StaticResource MwLabelStyle}">_Add</Label>
                            </StackPanel>
                        </Button>

                        <Button AutomationProperties.AutomationId="refreshVoyageButton"
                            Grid.Row="0"
                            Grid.Column="2"
                            Padding="0"
                            Command="{Binding RefreshVoyagesCommand}"
                            Focusable="False"
                            Style="{StaticResource MwButtonStyle}"
                            ToolTip="Refresh the this View (modified entries are left unchanged)">
                            <StackPanel Orientation="Horizontal">
                                <ContentControl Height="26" Content="{StaticResource Refresh}" />
                                <TextBlock Style="{StaticResource MwTextBlockLabelStyle}" Text="Refresh" />
                            </StackPanel>
                        </Button>

                        <Button AutomationProperties.AutomationId="showVoyageHistroyButton"
                            Grid.Column="4"
                            Margin="2,2,2,2"
                            Padding="0"
                            VerticalAlignment="Center"
                            Command="{Binding ShowVoyageHistoryCommand}"
                            Focusable="False"
                            ToolTip="Show the selected voyage's change history"
                            Visibility="{Binding Data.ViewDefinition.IsInternalView, Converter={StaticResource MwBoolToVisibilityConverterReverse}}">
                            <StackPanel Orientation="Horizontal">
                                <ContentControl Height="26" Content="{StaticResource ShowVoyageHistory}" />
                                <TextBlock
                                    Style="{StaticResource MwTextBlockLabelStyle}"
                                    Text="Hide Voyage History"
                                    Visibility="{Binding IsVoyageHistoryShowing, Converter={StaticResource BooleanToVisibilityConverter}}" />
                                <TextBlock
                                    Style="{StaticResource MwTextBlockLabelStyle}"
                                    Text="Show Voyage History"
                                    Visibility="{Binding IsVoyageHistoryShowing, Converter={StaticResource MwBoolToVisibilityConverterReverse}}" />
                            </StackPanel>
                        </Button>

                        <Button AutomationProperties.AutomationId="showVesselHistroyButton"
                            Grid.Column="5"
                            Margin="2,2,2,2"
                            Padding="0"
                            VerticalAlignment="Center"
                            Command="{Binding ShowVesselHistoryCommand}"
                            Focusable="False"
                            ToolTip="Show the selected vessel's voyage history"
                            Visibility="{Binding Data.ViewDefinition.IsInternalView, Converter={StaticResource MwBoolToVisibilityConverterReverse}}">
                            <StackPanel Orientation="Horizontal">
                                <ContentControl Height="26" Content="{StaticResource ShowVesselHistory}" />
                                <TextBlock
                                    Style="{StaticResource MwTextBlockLabelStyle}"
                                    Text="Hide Vessel History"
                                    Visibility="{Binding IsVesselHistoryShowing, Converter={StaticResource BooleanToVisibilityConverter}}" />
                                <TextBlock
                                    Style="{StaticResource MwTextBlockLabelStyle}"
                                    Text="Show Vessel History"
                                    Visibility="{Binding IsVesselHistoryShowing, Converter={StaticResource MwBoolToVisibilityConverterReverse}}" />
                            </StackPanel>
                        </Button>

                        <Button AutomationProperties.AutomationId="showVoyageButton"
                            Grid.Column="6"
                            Margin="2,2,2,2"
                            Padding="0"
                            VerticalAlignment="Center"
                            Command="{Binding ShowVesselVisitsCommand}"
                            Focusable="False"
                            ToolTip="Show the selected voyage's events"
                            Visibility="{Binding Data.ViewDefinition.IsInternalView, Converter={StaticResource MwBoolToVisibilityConverterReverse}}">
                            <StackPanel Orientation="Horizontal">
                                <ContentControl Height="26" Content="{StaticResource Anchor}" />
                                <TextBlock
                                    Style="{StaticResource MwTextBlockLabelStyle}"
                                    Text="Hide Voyage Events"
                                    Visibility="{Binding IsVoyageEventsShowing, Converter={StaticResource BooleanToVisibilityConverter}}" />
                                <TextBlock
                                    Style="{StaticResource MwTextBlockLabelStyle}"
                                    Text="Show Voyage Events"
                                    Visibility="{Binding IsVoyageEventsShowing, Converter={StaticResource MwBoolToVisibilityConverterReverse}}" />
                            </StackPanel>
                        </Button>

                        <Border Grid.Row="0" Grid.Column="8">
                            <Border.Style>
                                <Style TargetType="Border">
                                    <Style.Triggers>
                                        <DataTrigger Binding="{Binding IsDuplicateView, Mode=TwoWay}" Value="true">
                                            <Setter Property="Background" Value="LightGreen" />
                                        </DataTrigger>
                                    </Style.Triggers>
                                </Style>
                            </Border.Style>
                            <Button AutomationProperties.AutomationId="DuplicateCheckButton"
                                Padding="0"
                                Command="{Binding DuplicateVoyagesCommand}"
                                Focusable="False"
                                Style="{StaticResource MwButtonStyle}"
                                ToolTip="Switch to duplicate Voyages (ALT + D)"
                                Visibility="{Binding Data.ViewDefinition.IsInternalView, Converter={StaticResource MwBoolToVisibilityConverterReverse}}">
                                <StackPanel Orientation="Horizontal">
                                    <ContentControl Height="26" Content="{StaticResource Duplicate}" />
                                    <AccessText Style="{StaticResource MwAccessTextLabelStyle}" Text="{Binding VoyageDuplicateText}" />
                                </StackPanel>
                            </Button>
                        </Border>

                        <Button AutomationProperties.AutomationId="PublishVoyagesButton"
                            Grid.Row="0"
                            Grid.Column="9"
                            Padding="0"
                            Command="{Binding PublishVoyagesCommand}"
                            Focusable="False"
                            Style="{StaticResource MwButtonStyle}"
                            ToolTip="Publish any modified Voyages (ALT + P)"
                            Visibility="{Binding Data.ViewDefinition.IsInternalView, Converter={StaticResource MwBoolToVisibilityConverterReverse}}">
                            <StackPanel Orientation="Horizontal">
                                <ContentControl Height="26" Content="{StaticResource Publish}" />
                                <AccessText Style="{StaticResource MwAccessTextLabelStyle}" Text="{Binding VoyagePublishText}" />
                            </StackPanel>
                        </Button>

                        <Button AutomationProperties.AutomationId="UndoSingleVoyageButton"
                            Grid.Row="0"
                            Grid.Column="10"
                            Padding="0"
                            Command="{Binding UndoSingleChangedVoyagesCommand}"
                            Focusable="False"
                            Style="{StaticResource MwButtonStyle}"
                            ToolTip="Locally Undo unpublished changes to the selected voyage"
                            Visibility="{Binding Data.ViewDefinition.IsInternalView, Converter={StaticResource MwBoolToVisibilityConverterReverse}}">
                            <StackPanel Orientation="Horizontal">
                                <ContentControl Height="26" Content="{StaticResource Undo}" />
                                <TextBlock Style="{StaticResource MwTextBlockLabelStyle}" Text="Undo Selected" />
                            </StackPanel>
                        </Button>

                        <Button AutomationProperties.AutomationId="UndoandUnpublishVoyageButton"
                            Grid.Row="0"
                            Grid.Column="11"
                            Padding="0"
                            Command="{Binding UndoChangedVoyagesCommand}"
                            Focusable="False"
                            Style="{StaticResource MwButtonStyle}"
                            ToolTip="Locally Undo any changed and unpublished voyages"
                            Visibility="{Binding Data.ViewDefinition.IsInternalView, Converter={StaticResource MwBoolToVisibilityConverterReverse}}">
                            <StackPanel Orientation="Horizontal">
                                <ContentControl Height="26" Content="{StaticResource Undo}" />
                                <TextBlock Style="{StaticResource MwTextBlockLabelStyle}" Text="Undo All" />
                            </StackPanel>
                        </Button>
                    </Grid>
                </Grid>
            </DataTemplate>
        </dx:DXTabControl.ItemTemplate>
    </dx:DXTabControl>
</code>```

My FlaUIapproach of locating the Controls is below

```<code>public IMainWindow ConfirmCreatedView()
        {
            _logger.Info("Checking the newly created View on the screen");
            //Apoorv: Need to find TabItem here
            _controlAction.Highlight(ViewsTabControl); // This highlights the TabControl- Works
            int NumberOfActiveTabs = ViewsTabControl.TabItems.Length; // This gives me no of TabItems

          TabItem SelectedTab=  ViewsTabControl.SelectedTabItem as TabItem; // Gives me Null here
            var newTab = ViewsTabControl.SelectedTabItemIndex ; // Give me -1 here

            _controlAction.Highlight(ViewsTabControl.TabItems[2]); // Works. It highlights the TabItem at position 2

            _controlAction.ClickWait<TabItem>(ViewsTabControl.TabItems[2]); // This goes and clicks the tab item

            TabItem SelectedTabs = ViewsTabControl.SelectedTabItem as TabItem;
            var check = ViewsTabControl.TabItems[2].FindAllChildren();
            // TabItem ti = ViewsTabControl.SelectedItem as TabItem;
            //_controlAction.Highlight()

                _controlAction.Highlight(CloseCurrentView); // highlights the close button atTabItem[0]
                _controlAction.Click<Button>(CloseCurrentView); // closes it

                      return this;
        }
</code>```

I am using FlaUI to Find the TabControl using AutomationID as shown below

```<code> private Tab ViewsTabControl => _uiAutomation.FindElement("ViewsParentTabControl", Automation.FindBy.Id).AsTab();
        private TabItem ViewsTabItem => _uiAutomation.FindElement("DXTabItem", Automation.FindBy.Id).AsTabItem();
</code>```

I would like to find the curently active TabItem based on the Index and then go and click the close button by automating it.

```<code>TabItem SelectedTab=  ViewsTabControl.SelectedTabItem as TabItem; // Gives me Null here
            var newTab = ViewsTabControl.SelectedTabItemIndex ; // Give me -1 here
</code>```

答:
DevEXpress don't create automation peers for controls within ItemHeaderTemplate. It will be necessary to use a custom automation peer to provide this functionality. For example, I used the following class for test purposes:

```<code>public class DXTabItemAutomationPeerEx : DXTabItemAutomationPeer, ISelectionItemProvider {
    private DXTabItem TabItem => base.Owner as DXTabItem;
    private DXTabControl TabControl => TabItem.With((DXTabItem x) => x.Owner);
    public DXTabItemAutomationPeerEx(DXTabItem ownerCore) : base(ownerCore) { }
    protected override List<AutomationPeer> GetChildrenCore() {
        List<AutomationPeer> children = base.GetChildrenCore();
        foreach (var button in LayoutTreeHelper.GetVisualChildren(Owner).OfType<Button>())
            children.Add(new ButtonAutomationPeer(button));
        return children;
    }
    bool ISelectionItemProvider.IsSelected { get {
            if (TabControl != null) {
                return TabControl.SelectedContainer == TabItem;
            }
            return false;
        }
    }
}
</code>```

Post adding this code inside my MainPage.Xaml.cs , I added a static constructor to register it

```<code>static MainWindow() {
    NavigationAutomationPeersCreator.Default.RegisterObject(typeof(DXTabItem), typeof(DXTabItemAutomationPeerEx), owner => new DXTabItemAutomationPeerEx((DXTabItem)owner));
}
</code>```

post this , these lines work as charm

```<code>TabItem CurrentTab = ViewsTabControl.SelectedTabItem as TabItem;
var Children = ViewsTabControl.FindAllChildren();
foreach (var child in Children) {
    var subChildren = child.FindAllChildren();
}
</code>```

Body:
I have a WPF app and I am trying to Automate it using FlaUI. I am facing a problem with the DxTabControl. I have provided Automation IDs to the DxTabControl. I am using DXTabControl.ItemHeaderTemplate to generate TabItems dynamically.
According to DevExpress Team, The DXTabControl.ItemHeaderTemplate doesnt support AutoamtionPeer so a custom implementation has been added to override its default behaviour.

Now, I am able to see the TabControl and the TabItems in the Inspect.exe.
Now , my requirement is to Access the currently selected Tabitem and find the CloseButton using the AutoamtionID mentioned in the XAML below and close it. Pasting below the line again. As there would be multiple TabItems generated, I am unable to get the Currently active/Selected TabItem .

The XAML is below

<dx:DXTabControl AutomationProperties.AutomationId="ViewsParentTabControl"
        MaxWidth="4000"
        MaxHeight="4000"
        Margin="1,0,-1,0"
        Focusable="False"
        ItemsSource="{Binding OpenViews}"
        SelectedIndex="{Binding SelectedTabIndex}"
        TabContentCacheMode="CacheTabsOnSelecting">
        <dx:DXTabControl.ItemHeaderTemplate>
            <DataTemplate DataType="viewModels1:OpenViewDefinitionViewModel">
                <Grid>
                    <Grid.RowDefinitions>
                        <RowDefinition Height="*" />
                        <RowDefinition Height="Auto" />
                    </Grid.RowDefinitions>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="Auto" />
                        <ColumnDefinition Width="Auto" />
                        <ColumnDefinition Width="Auto" />
                        <ColumnDefinition Width="Auto" />
                        <ColumnDefinition Width="Auto" />
                    </Grid.ColumnDefinitions>
                    <TextBlock Name="CreatedViewName"
                        MaxWidth="100"
                        Text="{Binding Data.ViewDefinition.Name}"
                        TextTrimming="CharacterEllipsis"
                        ToolTip="{Binding DisplayName}" />
                    <TextBlock Grid.Row="0" Grid.Column="1"><Run Text=" [" /><Run Text="{Binding ItemsCount, FallbackValue=0, Mode=OneWay}" /><Run Text="]" /></TextBlock>
                    <controls2:ProgressIndicator AutomationProperties.AutomationId="ProgressCurrentView"
                        Grid.Row="0"
                        Grid.Column="3"
                        Width="14"
                        Margin="4,0,0,0"
                        VerticalAlignment="Center"
                        CircleBorder="{StaticResource ListBoxItem.Foreground}"
                        CircleFill="{StaticResource ListBoxItem.Foreground}"
                        IndicatorEnabled="{Binding IsDataLoading}" />
                    <Button AutomationProperties.AutomationId="CloseCurrentViewButton"
                        Grid.Row="0"
                        Grid.Column="2"
                        Width="10"
                        Height="10"
                        Margin="10,1,0,0"
                        Padding="0"
                        HorizontalAlignment="Right"
                        BorderThickness="0"
                        Command="{Binding DataContext.CloseItemCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=dx:DXTabControl}}"
                        CommandParameter="{Binding}"
                        Focusable="False"
                        Style="{StaticResource MwButtonStyle}"
                        ToolTip="Close">
                        <Path
                            Data="F1 M 26.9166,22.1667L 37.9999,33.25L 49.0832,22.1668L 53.8332,26.9168L 42.7499,38L 53.8332,49.0834L 49.0833,53.8334L 37.9999,42.75L 26.9166,53.8334L 22.1666,49.0833L 33.25,38L 22.1667,26.9167L 26.9166,22.1667 Z"
                            Fill="White"
                            Stretch="Fill" />
                    </Button>
                </Grid>
            </DataTemplate>
        </dx:DXTabControl.ItemHeaderTemplate>
        <dx:DXTabControl.ItemTemplate>
            <DataTemplate DataType="viewModels1:OpenViewDefinitionViewModel">
                <Grid>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="*" />
                        <ColumnDefinition Width="Auto" />
                    </Grid.ColumnDefinitions>
                    <Grid.RowDefinitions>
                        <RowDefinition Height="*" />
                        <RowDefinition Height="Auto" />
                        <RowDefinition Height="Auto" />
                        <RowDefinition Height="Auto" />
                        <RowDefinition Height="Auto" />
                    </Grid.RowDefinitions>

                    <local:VoyagesGridControl />

                    <local:VoyageValidationUserControl
                        Grid.Row="1"
                        Grid.Column="0"
                        MinHeight="100"
                        MaxHeight="300"
                        Visibility="{Binding Path=IsVoyageValidationShowing, FallbackValue=Collapsed, Converter={StaticResource BooleanToVisibilityConverter}}" />
                    <local:VoyageHistoryUserControl
                        Grid.Row="2"
                        Grid.Column="0"
                        MinHeight="300"
                        MaxHeight="300"
                        Visibility="{Binding Path=IsVoyageHistoryShowing, FallbackValue=Collapsed, Converter={StaticResource BooleanToVisibilityConverter}}" />
                    <local:VesselHistoryUserControl
                        Grid.Row="3"
                        Grid.Column="0"
                        MinHeight="300"
                        MaxHeight="300"
                        Visibility="{Binding Path=IsVesselHistoryShowing, FallbackValue=Collapsed, Converter={StaticResource BooleanToVisibilityConverter}}" />
                    <local:VoyageEvents
                        Grid.Row="0"
                        Grid.RowSpan="3"
                        Grid.Column="1"
                        VerticalAlignment="Top"
                        Visibility="{Binding Path=IsVoyageEventsShowing, FallbackValue=Collapsed, Converter={StaticResource BooleanToVisibilityConverter}}" />

                    <controls2:ProgressIndicator AutomationProperties.AutomationId="showProgressForLoadingViews"
                        Grid.Row="0"
                        Grid.RowSpan="3"
                        Grid.Column="0"
                        Width="80"
                        HorizontalAlignment="Center"
                        VerticalAlignment="Center"
                        CircleBorder="{StaticResource ListBox.BorderBrush}"
                        CircleFill="{StaticResource ListBox.BorderBrush}"
                        IndicatorEnabled="{Binding IsDataLoading}" />

                    <Grid Grid.Row="4" Grid.Column="0">
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="Auto" />
                            <ColumnDefinition Width="Auto" />
                            <ColumnDefinition Width="Auto" />
                            <ColumnDefinition Width="*" />
                            <ColumnDefinition Width="Auto" />
                            <ColumnDefinition Width="Auto" />
                            <ColumnDefinition Width="Auto" />
                            <ColumnDefinition Width="*" />
                            <ColumnDefinition Width="Auto" />
                            <ColumnDefinition Width="Auto" />
                            <ColumnDefinition Width="Auto" />
                            <ColumnDefinition Width="Auto" />
                        </Grid.ColumnDefinitions>
                        <StackPanel
                            Grid.Column="0"
                            VerticalAlignment="Center"
                            Orientation="Horizontal">
                            <TextBlock Style="{StaticResource MwTextBlockLabelStyle}" Text="Last Refresh:" />
                            <TextBlock
                                Margin="2,0,4,0"
                                VerticalAlignment="Center"
                                Text="{Binding LoadDate, StringFormat=G}" />
                        </StackPanel>
                        <Button AutomationProperties.AutomationId="AddNewVoyageButton"
                            Grid.Row="0"
                            Grid.Column="1"
                            Padding="0"
                            Command="{Binding AddVoyagesCommand}"
                            Focusable="False"
                            Style="{StaticResource MwButtonStyle}"
                            ToolTip="Add a new voyage to this View (ALT + A)">
                            <StackPanel Orientation="Horizontal">
                                <ContentControl Height="26" Content="{StaticResource Add}" />
                                _Add
                            </StackPanel>
                        </Button>

                        <Button AutomationProperties.AutomationId="refreshVoyageButton"
                            Grid.Row="0"
                            Grid.Column="2"
                            Padding="0"
                            Command="{Binding RefreshVoyagesCommand}"
                            Focusable="False"
                            Style="{StaticResource MwButtonStyle}"
                            ToolTip="Refresh the this View (modified entries are left unchanged)">
                            <StackPanel Orientation="Horizontal">
                                <ContentControl Height="26" Content="{StaticResource Refresh}" />
                                <TextBlock Style="{StaticResource MwTextBlockLabelStyle}" Text="Refresh" />
                            </StackPanel>
                        </Button>

                        <Button AutomationProperties.AutomationId="showVoyageHistroyButton"
                            Grid.Column="4"
                            Margin="2,2,2,2"
                            Padding="0"
                            VerticalAlignment="Center"
                            Command="{Binding ShowVoyageHistoryCommand}"
                            Focusable="False"
                            ToolTip="Show the selected voyage's change history"
                            Visibility="{Binding Data.ViewDefinition.IsInternalView, Converter={StaticResource MwBoolToVisibilityConverterReverse}}">
                            <StackPanel Orientation="Horizontal">
                                <ContentControl Height="26" Content="{StaticResource ShowVoyageHistory}" />
                                <TextBlock
                                    Style="{StaticResource MwTextBlockLabelStyle}"
                                    Text="Hide Voyage History"
                                    Visibility="{Binding IsVoyageHistoryShowing, Converter={StaticResource BooleanToVisibilityConverter}}" />
                                <TextBlock
                                    Style="{StaticResource MwTextBlockLabelStyle}"
                                    Text="Show Voyage History"
                                    Visibility="{Binding IsVoyageHistoryShowing, Converter={StaticResource MwBoolToVisibilityConverterReverse}}" />
                            </StackPanel>
                        </Button>

                        <Button AutomationProperties.AutomationId="showVesselHistroyButton"
                            Grid.Column="5"
                            Margin="2,2,2,2"
                            Padding="0"
                            VerticalAlignment="Center"
                            Command="{Binding ShowVesselHistoryCommand}"
                            Focusable="False"
                            ToolTip="Show the selected vessel's voyage history"
                            Visibility="{Binding Data.ViewDefinition.IsInternalView, Converter={StaticResource MwBoolToVisibilityConverterReverse}}">
                            <StackPanel Orientation="Horizontal">
                                <ContentControl Height="26" Content="{StaticResource ShowVesselHistory}" />
                                <TextBlock
                                    Style="{StaticResource MwTextBlockLabelStyle}"
                                    Text="Hide Vessel History"
                                    Visibility="{Binding IsVesselHistoryShowing, Converter={StaticResource BooleanToVisibilityConverter}}" />
                                <TextBlock
                                    Style="{StaticResource MwTextBlockLabelStyle}"
                                    Text="Show Vessel History"
                                    Visibility="{Binding IsVesselHistoryShowing, Converter={StaticResource MwBoolToVisibilityConverterReverse}}" />
                            </StackPanel>
                        </Button>

                        <Button AutomationProperties.AutomationId="showVoyageButton"
                            Grid.Column="6"
                            Margin="2,2,2,2"
                            Padding="0"
                            VerticalAlignment="Center"
                            Command="{Binding ShowVesselVisitsCommand}"
                            Focusable="False"
                            ToolTip="Show the selected voyage's events"
                            Visibility="{Binding Data.ViewDefinition.IsInternalView, Converter={StaticResource MwBoolToVisibilityConverterReverse}}">
                            <StackPanel Orientation="Horizontal">
                                <ContentControl Height="26" Content="{StaticResource Anchor}" />
                                <TextBlock
                                    Style="{StaticResource MwTextBlockLabelStyle}"
                                    Text="Hide Voyage Events"
                                    Visibility="{Binding IsVoyageEventsShowing, Converter={StaticResource BooleanToVisibilityConverter}}" />
                                <TextBlock
                                    Style="{StaticResource MwTextBlockLabelStyle}"
                                    Text="Show Voyage Events"
                                    Visibility="{Binding IsVoyageEventsShowing, Converter={StaticResource MwBoolToVisibilityConverterReverse}}" />
                            </StackPanel>
                        </Button>

                        <Border Grid.Row="0" Grid.Column="8">
                            <Border.Style>

                                </Style>
                            </Border.Style>
                            <Button AutomationProperties.AutomationId="DuplicateCheckButton"
                                Padding="0"
                                Command="{Binding DuplicateVoyagesCommand}"
                                Focusable="False"
                                Style="{StaticResource MwButtonStyle}"
                                ToolTip="Switch to duplicate Voyages (ALT + D)"
                                Visibility="{Binding Data.ViewDefinition.IsInternalView, Converter={StaticResource MwBoolToVisibilityConverterReverse}}">
                                <StackPanel Orientation="Horizontal">
                                    <ContentControl Height="26" Content="{StaticResource Duplicate}" />
                                    <AccessText Style="{StaticResource MwAccessTextLabelStyle}" Text="{Binding VoyageDuplicateText}" />
                                </StackPanel>
                            </Button>
                        </Border>

                        <Button AutomationProperties.AutomationId="PublishVoyagesButton"
                            Grid.Row="0"
                            Grid.Column="9"
                            Padding="0"
                            Command="{Binding PublishVoyagesCommand}"
                            Focusable="False"
                            Style="{StaticResource MwButtonStyle}"
                            ToolTip="Publish any modified Voyages (ALT + P)"
                            Visibility="{Binding Data.ViewDefinition.IsInternalView, Converter={StaticResource MwBoolToVisibilityConverterReverse}}">
                            <StackPanel Orientation="Horizontal">
                                <ContentControl Height="26" Content="{StaticResource Publish}" />
                                <AccessText Style="{StaticResource MwAccessTextLabelStyle}" Text="{Binding VoyagePublishText}" />
                            </StackPanel>
                        </Button>

                        <Button AutomationProperties.AutomationId="UndoSingleVoyageButton"
                            Grid.Row="0"
                            Grid.Column="10"
                            Padding="0"
                            Command="{Binding UndoSingleChangedVoyagesCommand}"
                            Focusable="False"
                            Style="{StaticResource MwButtonStyle}"
                            ToolTip="Locally Undo unpublished changes to the selected voyage"
                            Visibility="{Binding Data.ViewDefinition.IsInternalView, Converter={StaticResource MwBoolToVisibilityConverterReverse}}">
                            <StackPanel Orientation="Horizontal">
                                <ContentControl Height="26" Content="{StaticResource Undo}" />
                                <TextBlock Style="{StaticResource MwTextBlockLabelStyle}" Text="Undo Selected" />
                            </StackPanel>
                        </Button>

                        <Button AutomationProperties.AutomationId="UndoandUnpublishVoyageButton"
                            Grid.Row="0"
                            Grid.Column="11"
                            Padding="0"
                            Command="{Binding UndoChangedVoyagesCommand}"
                            Focusable="False"
                            Style="{StaticResource MwButtonStyle}"
                            ToolTip="Locally Undo any changed and unpublished voyages"
                            Visibility="{Binding Data.ViewDefinition.IsInternalView, Converter={StaticResource MwBoolToVisibilityConverterReverse}}">
                            <StackPanel Orientation="Horizontal">
                                <ContentControl Height="26" Content="{StaticResource Undo}" />
                                <TextBlock Style="{StaticResource MwTextBlockLabelStyle}" Text="Undo All" />
                            </StackPanel>
                        </Button>
                    </Grid>
                </Grid>
            </DataTemplate>
        </dx:DXTabControl.ItemTemplate>
    </dx:DXTabControl>

My FlaUIapproach of locating the Controls is below

public IMainWindow ConfirmCreatedView()
        {
            _logger.Info("Checking the newly created View on the screen");
            //Apoorv: Need to find TabItem here
            _controlAction.Highlight(ViewsTabControl); // This highlights the TabControl- Works
            int NumberOfActiveTabs = ViewsTabControl.TabItems.Length; // This gives me no of TabItems

          TabItem SelectedTab=  ViewsTabControl.SelectedTabItem as TabItem; // Gives me Null here
            var newTab = ViewsTabControl.SelectedTabItemIndex ; // Give me -1 here

            _controlAction.Highlight(ViewsTabControl.TabItems[2]); // Works. It highlights the TabItem at position 2

            _controlAction.ClickWait<TabItem>(ViewsTabControl.TabItems[2]); // This goes and clicks the tab item

            TabItem SelectedTabs = ViewsTabControl.SelectedTabItem as TabItem;
            var check = ViewsTabControl.TabItems[2].FindAllChildren();
            // TabItem ti = ViewsTabControl.SelectedItem as TabItem;
            //_controlAction.Highlight()

                _controlAction.Highlight(CloseCurrentView); // highlights the close button atTabItem[0]
                _controlAction.Click<Button>(CloseCurrentView); // closes it

                      return this;
        }

I am using FlaUI to Find the TabControl using AutomationID as shown below

 private Tab ViewsTabControl => _uiAutomation.FindElement("ViewsParentTabControl", Automation.FindBy.Id).AsTab();
        private TabItem ViewsTabItem => _uiAutomation.FindElement("DXTabItem", Automation.FindBy.Id).AsTabItem();

I would like to find the curently active TabItem based on the Index and then go and click the close button by automating it.

TabItem SelectedTab=  ViewsTabControl.SelectedTabItem as TabItem; // Gives me Null here
            var newTab = ViewsTabControl.SelectedTabItemIndex ; // Give me -1 here

Body:
DevEXpress don't create automation peers for controls within ItemHeaderTemplate. It will be necessary to use a custom automation peer to provide this functionality. For example, I used the following class for test purposes:

public class DXTabItemAutomationPeerEx : DXTabItemAutomationPeer, ISelectionItemProvider {
    private DXTabItem TabItem => base.Owner as DXTabItem;
    private DXTabControl TabControl => TabItem.With((DXTabItem x) => x.Owner);
    public DXTabItemAutomationPeerEx(DXTabItem ownerCore) : base(ownerCore) { }
    protected override List<AutomationPeer> GetChildrenCore() {
        List<AutomationPeer> children = base.GetChildrenCore();
        foreach (var button in LayoutTreeHelper.GetVisualChildren(Owner).OfType<Button>())
            children.Add(new ButtonAutomationPeer(button));
        return children;
    }
    bool ISelectionItemProvider.IsSelected { get {
            if (TabControl != null) {
                return TabControl.SelectedContainer == TabItem;
            }
            return false;
        }
    }
}

Post adding this code inside my MainPage.Xaml.cs , I added a static constructor to register it

static MainWindow() {
    NavigationAutomationPeersCreator.Default.RegisterObject(typeof(DXTabItem), typeof(DXTabItemAutomationPeerEx), owner => new DXTabItemAutomationPeerEx((DXTabItem)owner));
}

post this , these lines work as charm

TabItem CurrentTab = ViewsTabControl.SelectedTabItem as TabItem;
var Children = ViewsTabControl.FindAllChildren();
foreach (var child in Children) {
    var subChildren = child.FindAllChildren();
}


问:
How do I convert a random number in to a character
I have tried to convert a random number into a character.

If I type a number into a variable it works, but if I do this int number = (int)(Math.random()*10); and then to assign it to a char and convert it char c = (char)number; when I print it, it shows nothing without errors like an invisible character.

Could you help me to do this?

答:
Just add '0' to your int.

```<code>int number = (int)(Math.random()*10);
char c = (char)number + '0';
</code>```

Since '0' is ASCII value 48, '1' is 49, etc..., any number from 0 to 9 you sum to it will result in a number whose ASCII value is between between '0' and '9'.

Body:
Just add '0' to your int.

int number = (int)(Math.random()*10);
char c = (char)number + '0';

Since '0' is ASCII value 48, '1' is 49, etc..., any number from 0 to 9 you sum to it will result in a number whose ASCII value is between between '0' and '9'.


问:
Django allauth invalid token error not showing
I'm using allauth for authentication in my Django project.

In PasswordResetFromKeyView, I can't figure out why there is not error showing when the password reset token is invalid, for whatever reason.

Instead, the token is caught as invalid but the page simply reloads without any message to the user.

allauth.account.views.PasswordResetFromKeyView

```<code>class PasswordResetFromKeyView(AjaxCapableProcessFormViewMixin, FormView):
template_name = (
    "account/password_reset_from_key." + app_settings.TEMPLATE_EXTENSION)
form_class = ResetPasswordKeyForm
success_url = reverse_lazy("account_reset_password_from_key_done")

def get_form_class(self):
    return get_form_class(app_settings.FORMS,
                          'reset_password_from_key',
                          self.form_class)

def dispatch(self, request, uidb36, key, **kwargs):
    self.request = request
    self.key = key

    if self.key == INTERNAL_RESET_URL_KEY:
        self.key = self.request.session.get(INTERNAL_RESET_SESSION_KEY, '')
        # (Ab)using forms here to be able to handle errors in XHR #890
        token_form = UserTokenForm(
            data={'uidb36': uidb36, 'key': self.key})
        if token_form.is_valid():
            self.reset_user = token_form.reset_user
            return super(PasswordResetFromKeyView, self).dispatch(request,
                                                                  uidb36,
                                                                  self.key,
                                                                  **kwargs)
    else:
        token_form = UserTokenForm(
            data={'uidb36': uidb36, 'key': self.key})
        if token_form.is_valid():
            # Store the key in the session and redirect to the
            # password reset form at a URL without the key. That
            # avoids the possibility of leaking the key in the
            # HTTP Referer header.
            self.request.session[INTERNAL_RESET_SESSION_KEY] = self.key
            redirect_url = self.request.path.replace(
                self.key, INTERNAL_RESET_URL_KEY)
            return redirect(redirect_url)

    self.reset_user = None
    response = self.render_to_response(
        self.get_context_data(token_fail=True)
    )
    return _ajax_response(self.request, response, form=token_form)

def get_context_data(self, **kwargs):
    ret = super(PasswordResetFromKeyView, self).get_context_data(**kwargs)
    ret['action_url'] = reverse(
        'account_reset_password_from_key',
        kwargs={'uidb36': self.kwargs['uidb36'],
                'key': self.kwargs['key']})
    return ret
</code>```

View

```<code>class PasswordResetConfirmView(PasswordResetFromKeyView):
form_class = PasswordResetConfirmForm
template_name = 'users/password_reset_confirm.html'

def get_success_url(self):
    return reverse('account_login')
</code>```

Template

```<code>{% load crispy_forms_tags %}

<div class="content-section">
    <form method="POST">
        {% csrf_token %}
        <fieldset class="form-group">
            <legend class="border-bottom mb-4">Confirm New Password</legend>
            {{ form|crispy }}
        </fieldset>
        <div class="form-group">
            <button class="btn btn-outline-info" type="submit">Save password</button>
        </div>
    </form>
</div>
</code>```

答:
The allauth view uses the template "account/password_reset_from_key.html". You should check that, because it contains an if/else statement to display an error if the token is invalid:

```<code><h1>{% if token_fail %}{% trans "Bad Token" %}{% else %}{% trans "Change Password" %}{% endif %}</h1>

{% if token_fail %}
    Some error message
{% else %}
    <form> ... </form>
{% endif %}
</code>```

So when you override the template, just make sure you do something in case token_fail is True.

Body:
I'm using allauth for authentication in my Django project.

In PasswordResetFromKeyView, I can't figure out why there is not error showing when the password reset token is invalid, for whatever reason.

Instead, the token is caught as invalid but the page simply reloads without any message to the user.

allauth.account.views.PasswordResetFromKeyView

class PasswordResetFromKeyView(AjaxCapableProcessFormViewMixin, FormView):
template_name = (
    "account/password_reset_from_key." + app_settings.TEMPLATE_EXTENSION)
form_class = ResetPasswordKeyForm
success_url = reverse_lazy("account_reset_password_from_key_done")

def get_form_class(self):
    return get_form_class(app_settings.FORMS,
                          'reset_password_from_key',
                          self.form_class)

def dispatch(self, request, uidb36, key, **kwargs):
    self.request = request
    self.key = key

    if self.key == INTERNAL_RESET_URL_KEY:
        self.key = self.request.session.get(INTERNAL_RESET_SESSION_KEY, '')
        # (Ab)using forms here to be able to handle errors in XHR #890
        token_form = UserTokenForm(
            data={'uidb36': uidb36, 'key': self.key})
        if token_form.is_valid():
            self.reset_user = token_form.reset_user
            return super(PasswordResetFromKeyView, self).dispatch(request,
                                                                  uidb36,
                                                                  self.key,
                                                                  **kwargs)
    else:
        token_form = UserTokenForm(
            data={'uidb36': uidb36, 'key': self.key})
        if token_form.is_valid():
            # Store the key in the session and redirect to the
            # password reset form at a URL without the key. That
            # avoids the possibility of leaking the key in the
            # HTTP Referer header.
            self.request.session[INTERNAL_RESET_SESSION_KEY] = self.key
            redirect_url = self.request.path.replace(
                self.key, INTERNAL_RESET_URL_KEY)
            return redirect(redirect_url)

    self.reset_user = None
    response = self.render_to_response(
        self.get_context_data(token_fail=True)
    )
    return _ajax_response(self.request, response, form=token_form)

def get_context_data(self, **kwargs):
    ret = super(PasswordResetFromKeyView, self).get_context_data(**kwargs)
    ret['action_url'] = reverse(
        'account_reset_password_from_key',
        kwargs={'uidb36': self.kwargs['uidb36'],
                'key': self.kwargs['key']})
    return ret

View

class PasswordResetConfirmView(PasswordResetFromKeyView):
form_class = PasswordResetConfirmForm
template_name = 'users/password_reset_confirm.html'

def get_success_url(self):
    return reverse('account_login')

Template

{% load crispy_forms_tags %}

    <form method="POST">
        {% csrf_token %}
        <fieldset class="form-group">
            <legend class="border-bottom mb-4">Confirm New Password</legend>
            {{ form|crispy }}
        </fieldset>

            <button class="btn btn-outline-info" type="submit">Save password</button>

    </form>

Body:
The allauth view uses the template "account/password_reset_from_key.html". You should check that, because it contains an if/else statement to display an error if the token is invalid:

<h1>{% if token_fail %}{% trans "Bad Token" %}{% else %}{% trans "Change Password" %}{% endif %}</h1>

{% if token_fail %}
    Some error message
{% else %}
    <form> ... </form>
{% endif %}

So when you override the template, just make sure you do something in case token_fail is True.


问:
How to replace all strings in a column in R?
I have a column of data where I am trying to remove all characters which aren't numbers
The data looks like:

```<code>Col1
Name=12_Represse, Name=12_Represse, Name=12_Represse, Name=13_Heterochrom/l, Name=13_Heterochrom/lo
Name=13_Heterochrom/lo
Name=11_Weak_Tx, Name=11_Weak_Tx, Name=11_Weak_Tx, Name=11_Weak_Tx, Name=11_Weak_Tx, Name=11_Weak_Tx
</code>```

The output I expect is:

```<code>Col1
12,12,12,13,13
13
11,11,11,11,11,11
</code>```

I've tried to adapt from other questions which look to remove specific strings.
For example trying:

test <- str_replace_all(data$col1,"#[a-z,A-Z]*","")

However this, or similar adaptations where I have tried gsub, does not seem to work. I am new to R so any guidance would help.

答:
You could try:

```<code>gsub("[A-Z]|[a-z]|[=]|\\s|_|/", "", Col1)
</code>```

So that if Col1 matches yours:

```<code>Col1 <- c("Name=12_Represse, Name=12_Represse, Name=12_Represse, Name=13_Heterochrom/l, Name=13_Heterochrom/lo",
"Name=13_Heterochrom/lo", "Name=11_Weak_Tx, Name=11_Weak_Tx, Name=11_Weak_Tx, Name=11_Weak_Tx, Name=11_Weak_Tx, Name=11_Weak_Tx "
)
</code>```

You get

```<code>gsub("[A-Z]|[a-z]|[=]|\\s|_|/", "", Col1)
#> [1] "12,12,12,13,13"    "13"                "11,11,11,11,11,11"
</code>```

Body:
I have a column of data where I am trying to remove all characters which aren't numbers
The data looks like:

Col1
Name=12_Represse, Name=12_Represse, Name=12_Represse, Name=13_Heterochrom/l, Name=13_Heterochrom/lo
Name=13_Heterochrom/lo
Name=11_Weak_Tx, Name=11_Weak_Tx, Name=11_Weak_Tx, Name=11_Weak_Tx, Name=11_Weak_Tx, Name=11_Weak_Tx

The output I expect is:

Col1
12,12,12,13,13
13
11,11,11,11,11,11

I've tried to adapt from other questions which look to remove specific strings.
For example trying:

test <- str_replace_all(data$col1,"#[a-z,A-Z]*","")

However this, or similar adaptations where I have tried gsub, does not seem to work. I am new to R so any guidance would help.

Body:
You could try:

gsub("[A-Z]|[a-z]|[=]|\\s|_|/", "", Col1)

So that if Col1 matches yours:

Col1 <- c("Name=12_Represse, Name=12_Represse, Name=12_Represse, Name=13_Heterochrom/l, Name=13_Heterochrom/lo",
"Name=13_Heterochrom/lo", "Name=11_Weak_Tx, Name=11_Weak_Tx, Name=11_Weak_Tx, Name=11_Weak_Tx, Name=11_Weak_Tx, Name=11_Weak_Tx "
)

You get

gsub("[A-Z]|[a-z]|[=]|\\s|_|/", "", Col1)
#> [1] "12,12,12,13,13"    "13"                "11,11,11,11,11,11"


问:
Auto image resize based on browser window dimensions
I have a basic web page layout with a 100% width header and a sticky footer. In between the two I have a large graphic.

I would like the graphic to resize dynamically depending on the size of the window.

I prefer not to use flash, and was wondering if there is an easy way to do this with jquery/javascript.

I'm not much of a jquery/javascript expert so I was wondering how to approach this of there is a component out there that already does it.

答:
```<code><style>
.wrapper {width:58.536585%; /*960/1640 = .58536585*/ margin:0 auto;}
.resize {width:100%; height:auto;}
</style>

<div class="wrapper">
  <img class="resize" src="image.jpg" />
</div>
</code>```

This will resize your image to match your container and keep the ratio in place. If you set the container to a percentage everything will scale.

wrapper width = 960px divided by screen width = 1640px

If you want the entire site to be responsive you have to do the math all the way down. divide the child by it's parent. Hope this helps!

ContentLicense: CC BY-SA 2.5

Body:
<style>
.wrapper {width:58.536585%; /*960/1640 = .58536585*/ margin:0 auto;}
.resize {width:100%; height:auto;}
</style>

<div class="wrapper">
  <img class="resize" src="image.jpg" />
</div>

This will resize your image to match your container and keep the ratio in place. If you set the container to a percentage everything will scale.

wrapper width = 960px divided by screen width = 1640px

If you want the entire site to be responsive you have to do the math all the way down. divide the child by it's parent. Hope this helps!


问:
PowerShell: How to set culture?
I tried to Set-Culture -CultureInfo vi-VN but Powershell was not changed to my setted Culture.

I tested by open Powershell ISE and seen my setted Culture was changed successful.

How to make Powershell changes to my setted Culture?

答:
To set cultures you are correct in that you should use

```<code>Set-Culture -CultureInfo vi-vn
</code>```

Looking at the culture list here as suggested by mklement0 you will find an entire list of codes.

edit: on testing, I can see that this works for the current user, however, as mklement0 has shown in his answer there appears to be a bug where this does in fact not work.

Title: PowerShell: How to set culture?

Body:
To set cultures you are correct in that you should use

Set-Culture -CultureInfo vi-vn

Looking at the culture list here as suggested by mklement0 you will find an entire list of codes.

edit: on testing, I can see that this works for the current user, however, as mklement0 has shown in his answer there appears to be a bug where this does in fact not work.


答:
You are using a random from 0 to 9. And when trying to convert that to an integer you can have this possible values from the ASCII table

```<code>Dec  Char
---------
  0  NUL (null)
  1  SOH (start of heading)
  2  STX (start of text)
  3  ETX (end of text)
  4  EOT (end of transmission)
  5  ENQ (enquiry)
  6  ACK (acknowledge)
  7  BEL (bell)
  8  BS  (backspace)
  9  TAB (horizontal tab)
 10  LF  (NL line feed, new line)
</code>```

So you need to check the ASCII table for the Char to use

Title: How do I convert a random number in to a character

Body:
I have tried to convert a random number into a character.

If I type a number into a variable it works, but if I do this int number = (int)(Math.random()*10); and then to assign it to a char and convert it char c = (char)number; when I print it, it shows nothing without errors like an invisible character.

Could you help me to do this?

Body:
You are using a random from 0 to 9. And when trying to convert that to an integer you can have this possible values from the ASCII table

Dec  Char
---------
  0  NUL (null)
  1  SOH (start of heading)
  2  STX (start of text)
  3  ETX (end of text)
  4  EOT (end of transmission)
  5  ENQ (enquiry)
  6  ACK (acknowledge)
  7  BEL (bell)
  8  BS  (backspace)
  9  TAB (horizontal tab)
 10  LF  (NL line feed, new line)

So you need to check the ASCII table for the Char to use


答:
It is happening because you are getting a number from 0 to 9 which corresponds to a non-printable character. Try the following code:

```<code>import java.util.Random;

public class Main {
    public static void main(String[] args) {
        int number = new Random().nextInt((126 - 33) + 1) + 33;
        char c = (char) number;
        System.out.println(c);
    }
}
</code>```

This will print some character from the ASCII range of 33 to 126.

Body:
It is happening because you are getting a number from 0 to 9 which corresponds to a non-printable character. Try the following code:

import java.util.Random;

public class Main {
    public static void main(String[] args) {
        int number = new Random().nextInt((126 - 33) + 1) + 33;
        char c = (char) number;
        System.out.println(c);
    }
}

This will print some character from the ASCII range of 33 to 126.