问:
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

答:
When you do $Name = $users.Name, the $Name variable gets an array containing ALL usernames in the CSV.

Remove that line and instead set the variable inside your ForEach-Object loop:

```<code># Import users from CSV
$UserList = Import-Csv "C:\Userlist.csv" | ForEach-Object {
    $samAccountName= $_.samAccountName
    $name = $_.Name
    # then the rest of your code
}
</code>```

Note:

SmtpPort takes an integer, not a string

From cannot be an empty string

P.S. Try to do some proper code indentation, so it is much easier to see where a code block (like ForEach-Object) starts and ends)

Your code revised:

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

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

# Import users from CSV
Import-Csv "C:\Userlist.csv" | ForEach-Object {
    # read this from the CSV
    $samAccountName= $_.samAccountName
    # get the user object from the $users array
    $user = $users | Where-Object { $_.SamAccountName -eq $samAccountName }
    $name = $user.Name
    $emailAddress = $user.EmailAddress

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

    $body = @"
Hello $name, <br>
Your AD Account $samAccountName, password has been updated to $newpwd
"@

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

    #Server configuration
    $mailParams = @{
        SmtpServer = "YourSMTPServer"
        Port = 25  # <-- an integer value
        # sending option
        From = "it-operation@example.com"
        To = $user.EmailAddress
        Subject  ="AD Password updated - " + $date
        Priority = "Normal"
        Body = $body
        BodyAsHtml = $true
    }
    try {
    # Send the report email
    Send-MailMessage @mailParams -ErrorAction Stop
    }
    catch{
        write-warning "error in sending. $_"
    }  # End User Processing
}
</code>```

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:
When you do $Name = $users.Name, the $Name variable gets an array containing ALL usernames in the CSV.

Remove that line and instead set the variable inside your ForEach-Object loop:

# Import users from CSV
$UserList = Import-Csv "C:\Userlist.csv" | ForEach-Object {
    $samAccountName= $_.samAccountName
    $name = $_.Name
    # then the rest of your code
}

Note:

SmtpPort takes an integer, not a string

From cannot be an empty string

P.S. Try to do some proper code indentation, so it is much easier to see where a code block (like ForEach-Object) starts and ends)

Your code revised:

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

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

# Import users from CSV
Import-Csv "C:\Userlist.csv" | ForEach-Object {
    # read this from the CSV
    $samAccountName= $_.samAccountName
    # get the user object from the $users array
    $user = $users | Where-Object { $_.SamAccountName -eq $samAccountName }
    $name = $user.Name
    $emailAddress = $user.EmailAddress

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

    $body = @"
Hello $name, <br>
Your AD Account $samAccountName, password has been updated to $newpwd
"@

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

    #Server configuration
    $mailParams = @{
        SmtpServer = "YourSMTPServer"
        Port = 25  # <-- an integer value
        # sending option
        From = "it-operation@example.com"
        To = $user.EmailAddress
        Subject  ="AD Password updated - " + $date
        Priority = "Normal"
        Body = $body
        BodyAsHtml = $true
    }
    try {
    # Send the report email
    Send-MailMessage @mailParams -ErrorAction Stop
    }
    catch{
        write-warning "error in sending. $_"
    }  # End User Processing
}


来源: stackexchange

问:
Automatically mount an EBS volume upon starting an Amazon EC2 Linux instance
I have an EBS volume (e.g. /dev/sdf) that has been attached to an EC2 instance (which boots from a different EBS volume), and I have mounted the volume (through mount /dev/sdf /data). When I stop and start again the instance, the volume is still attached but no longer mounted, and I have to manually mount it again.

Is there a way to make the volume /dev/sdf automatically mounted to /data upon starting the instance?

答:
Make an entry to /etc/fstab

Entry would be like:

```<code>/dev/sdf    /data   ext3    defaults    1 1
</code>```

This will automatically mount the volume during reboot.

ContentLicense: CC BY-SA 3.0

Body:
Make an entry to /etc/fstab

Entry would be like:

/dev/sdf    /data   ext3    defaults    1 1

This will automatically mount the volume during reboot.


问:
Easiest way to increment a data point in Firebase?
I'm having trouble incrementing a piece of data in Firebase.

```<code>Firebase {
    clickedCounter: 0
}
</code>```

This is my code:

```<code>@IBAction func plus(sender: UIButton) {
        FIRDatabase.database().reference().child("clickedCounter").observeEventType(.Value) { (snap: FIRDataSnapshot) in
            let value = FIRDatabase.database().reference().child("clickedCounter") as? NSNumber
            let increment = ((value?.intValue)! + ((1 as? NSNumber)?.intValue)!) as? NSNumber
            FIRDatabase.database().reference().child("clickedCounter").setValue()
            self.clickLabel.text = snap.value?.description as String!
        }
    }
</code>```

I also tried:

```<code>@IBAction func plus(sender: UIButton) {
        FIRDatabase.database().reference().child("clickedCounter").observeEventType(.Value) { (snap: FIRDataSnapshot) in
            FIRDatabase.database().reference().child("clickedCounter").setValue((snap.value?.description)! + 1)
            self.clickedLabel.text = snap.value?.description as! String!
        }
    }
</code>```

For my first my warnings are:

Cast from Int32 to NSNumber always fails

Conditional cast from NSNumber to NSNumber always succeeds

Cast from FIRDatabaseReference to NSNumber always fails

After I ran it, I got the error on let increment.... : Thread 1: EXC_BAD_INSTRUCTION

For my second the error is:

Binary operator + cannot be applied to operands of the type String and Int

I'm confused as to how my snap.value?.description is a String when I thought I defined it in Firebase as an Int.

Why do I get a warning when something always succeeds?

Is there a better way to do this?

Thanks!

答:
If the database has persistence turned OFF, follow @Jay's answer.

But if your database has persistence turned ON, the usual way to increment with observeSingleEventOfType won't work at all - it will increment based on old value and will mess everything in the end.

Luckily, thanks to the findings made by Natural Lam described in his article here, there is still a way to reliably increment in case of persistence turned on. The trick is in forcing Firebase to sync data by a combination of keepSynced and a write operation. Here's an example how it works for me:

```<code>func increaseUnreadChatsFor(chatId: String) {
    let chatRef = self.ref.child("chats/\(chatId)")
    chatRef.keepSynced(true)
    chatRef.child("dummy").setValue("dummy") { _, _ in
        chatRef.child("dummy").removeValue()
        chatRef.keepSynced(false)
        chatRef.child("unread").observeSingleEvent(of: .value, with: { snapshot in
             if !snapshot.exists() { // no unread record yet, creating one
                chatRef.child("unread").setValue(1)
             } else if let unread = snapshot.value as? Int { // record already exists, incrementing it
                chatRef.child("unread").setValue(unread + 1)
             }
         })
    }
}
</code>```

Of course it is not guaranteed to work in offline.

Another alternative would be to configure same database once again, but this time with persistence turned OFF and do the increment using that firebase instance (which will obviously work only in online). How to do this you can read in my answer here.

Body:
I'm having trouble incrementing a piece of data in Firebase.

Firebase {
    clickedCounter: 0
}

This is my code:

@IBAction func plus(sender: UIButton) {
        FIRDatabase.database().reference().child("clickedCounter").observeEventType(.Value) { (snap: FIRDataSnapshot) in
            let value = FIRDatabase.database().reference().child("clickedCounter") as? NSNumber
            let increment = ((value?.intValue)! + ((1 as? NSNumber)?.intValue)!) as? NSNumber
            FIRDatabase.database().reference().child("clickedCounter").setValue()
            self.clickLabel.text = snap.value?.description as String!
        }
    }

I also tried:

@IBAction func plus(sender: UIButton) {
        FIRDatabase.database().reference().child("clickedCounter").observeEventType(.Value) { (snap: FIRDataSnapshot) in
            FIRDatabase.database().reference().child("clickedCounter").setValue((snap.value?.description)! + 1)
            self.clickedLabel.text = snap.value?.description as! String!
        }
    }

For my first my warnings are:

Cast from Int32 to NSNumber always fails

Conditional cast from NSNumber to NSNumber always succeeds

Cast from FIRDatabaseReference to NSNumber always fails

After I ran it, I got the error on let increment.... : Thread 1: EXC_BAD_INSTRUCTION

For my second the error is:

Binary operator + cannot be applied to operands of the type String and Int

I'm confused as to how my snap.value?.description is a String when I thought I defined it in Firebase as an Int.

Why do I get a warning when something always succeeds?

Is there a better way to do this?

Thanks!

Body:
If the database has persistence turned OFF, follow @Jay's answer.

But if your database has persistence turned ON, the usual way to increment with observeSingleEventOfType won't work at all - it will increment based on old value and will mess everything in the end.

Luckily, thanks to the findings made by Natural Lam described in his article here, there is still a way to reliably increment in case of persistence turned on. The trick is in forcing Firebase to sync data by a combination of keepSynced and a write operation. Here's an example how it works for me:

func increaseUnreadChatsFor(chatId: String) {
    let chatRef = self.ref.child("chats/\(chatId)")
    chatRef.keepSynced(true)
    chatRef.child("dummy").setValue("dummy") { _, _ in
        chatRef.child("dummy").removeValue()
        chatRef.keepSynced(false)
        chatRef.child("unread").observeSingleEvent(of: .value, with: { snapshot in
             if !snapshot.exists() { // no unread record yet, creating one
                chatRef.child("unread").setValue(1)
             } else if let unread = snapshot.value as? Int { // record already exists, incrementing it
                chatRef.child("unread").setValue(unread + 1)
             }
         })
    }
}

Of course it is not guaranteed to work in offline.

Another alternative would be to configure same database once again, but this time with persistence turned OFF and do the increment using that firebase instance (which will obviously work only in online). How to do this you can read in my answer here.

ContentLicense: CC BY-SA 4.0


问:
Translate scratch script to HTML and javascript
I am wondering if there already exists a translator to export a scratch project to HTML and javascript or to export a project so it can be played on a tablet.</p>

答: Yes, you can use Scratch HTMLifier by SheepTester, which generates a HTML file that runs the project. It uses the official Scratch VM so everything should work the same as in Scratch. Note that variables and ask prompts will look different.</p>


问:
Rename rownames
I would like to rename row names by removing common part of a row name

```<code>          a b  c
CDA_Part  1 4  4
CDZ_Part  3 4  4
CDX_Part  1 4  4

</code>```

result

```<code>     a b  c
CDA  1 4  4
CDZ  3 4  4
CDX  1 4  4
</code>```

答:
1.Create a minimal reproducible example:

```<code>df <- data.frame(a = 1:3, b = 4:6)
rownames(df) <- c("CDA_Part", "CDZ_Part", "CDX_Part")

df
</code>```

Returns:

```<code>         a b
CDA_Part 1 4
CDZ_Part 2 5
CDX_Part 3 6
</code>```

2.Suggested solution using base Rs gsub:

```<code>rownames(df) <- gsub("_Part", "", rownames(df), fixed=TRUE)

df
</code>```

Returns:

```<code>    a b
CDA 1 4
CDZ 2 5
CDX 3 6
</code>```

Explanation:

gsub uses regex to identify and replace parts of strings. The three first arguments are:

pattern the pattern to be replaced - i.e. "_Part"

replacement the string to be used as replacement - i.e. the empty string ""

x the string we want to replace something in - i.e. the rownames

An additional argument (not in the first 3):

fixed indicating if pattern is meant to be a regular expression or "just" an ordinary string - i.e. just a string

Title: Rename rownames

Body:
I would like to rename row names by removing common part of a row name

          a b  c
CDA_Part  1 4  4
CDZ_Part  3 4  4
CDX_Part  1 4  4

result

     a b  c
CDA  1 4  4
CDZ  3 4  4
CDX  1 4  4

Body:
1.Create a minimal reproducible example:

df <- data.frame(a = 1:3, b = 4:6)
rownames(df) <- c("CDA_Part", "CDZ_Part", "CDX_Part")

df

Returns:

         a b
CDA_Part 1 4
CDZ_Part 2 5
CDX_Part 3 6

2.Suggested solution using base Rs gsub:

rownames(df) <- gsub("_Part", "", rownames(df), fixed=TRUE)

df

Returns:

    a b
CDA 1 4
CDZ 2 5
CDX 3 6

Explanation:

gsub uses regex to identify and replace parts of strings. The three first arguments are:

pattern the pattern to be replaced - i.e. "_Part"

replacement the string to be used as replacement - i.e. the empty string ""

x the string we want to replace something in - i.e. the rownames

An additional argument (not in the first 3):

fixed indicating if pattern is meant to be a regular expression or "just" an ordinary string - i.e. just a string


问:
How to add the option "AllowDiskUse: true" in Mongodb requests with Api Platform?
The project uses Api Platform with mongodb.
I have a Player document with an sort on lastName. With 5000 players it works.
When I test with 200,000 players, I have an error:

Sort exceeded memory limit of 104857600 bytes, but did not opt in to
  external sorting. Aborting operation. Pass allowDiskUse:true to opt
  in.

I need to add "allowDiskUse: true" in the options of the request.

I tried adding it directly into the ApiPlatform code to test and it works! (but I can not add it to the library).

My question is: How to add the option "allowDiskUse: true" in the mongodb query with Api Platform?

```<code>/**
 * @ODM\Document(repositoryClass="App\Repository\PlayerRepository")
 * @ApiResource(
 *     attributes={"orders"={"lastName"= "ASC"}},
 *     collectionOperations={"get", "post"},
 *     itemOperations={"get", "put"},
 *
 *     normalizationContext={"groups"={"player"}},
 *     denormalizationContext={"groups"={"player"}}
 *     )
 */
class Player
{
    /**
     * @ODM\Id
     * @Groups({"player"})
     */
    private $id;

    /**
     * @ODM\Field(type="string")
     * @Groups({"player"})
     */
    private $optaId;

    /**
     * @ODM\Field(type="string")
     * @Groups({"player"})
     */
    private $firstName;

    /**
     * @ODM\Field(type="string")
     * @Groups({"player"})
     */
    private $lastName;
</code>```

答:
You can do it by adding</p>

```<code>* @ApiResource(attributes={
*     "doctrine_mongodb"={
*       "execute_options"={
*         "allowDiskUse"=true
*       }
*     }
* })
</code>```

Body:
The project uses Api Platform with mongodb.
I have a Player document with an sort on lastName. With 5000 players it works.
When I test with 200,000 players, I have an error:

Sort exceeded memory limit of 104857600 bytes, but did not opt in to
  external sorting. Aborting operation. Pass allowDiskUse:true to opt
  in.

I need to add "allowDiskUse: true" in the options of the request.

I tried adding it directly into the ApiPlatform code to test and it works! (but I can not add it to the library).

My question is: How to add the option "allowDiskUse: true" in the mongodb query with Api Platform?

/**
 * @ODM\Document(repositoryClass="App\Repository\PlayerRepository")
 * @ApiResource(
 *     attributes={"orders"={"lastName"= "ASC"}},
 *     collectionOperations={"get", "post"},
 *     itemOperations={"get", "put"},
 *
 *     normalizationContext={"groups"={"player"}},
 *     denormalizationContext={"groups"={"player"}}
 *     )
 */
class Player
{
    /**
     * @ODM\Id
     * @Groups({"player"})
     */
    private $id;

    /**
     * @ODM\Field(type="string")
     * @Groups({"player"})
     */
    private $optaId;

    /**
     * @ODM\Field(type="string")
     * @Groups({"player"})
     */
    private $firstName;

    /**
     * @ODM\Field(type="string")
     * @Groups({"player"})
     */
    private $lastName;

Body:
You can do it by adding

* @ApiResource(attributes={
*     "doctrine_mongodb"={
*       "execute_options"={
*         "allowDiskUse"=true
*       }
*     }
* })


答:
Using PIL, you can create an image using an array:

```<code>from PIL import Image
import numpy as np
img = Image.fromarray(np.array(pix).astype(np.uint8))
</code>```

Now, you may look at the image:

```<code>img.show()
</code>```

Good thing is, from now on, you can benefit from all of PIL's toolcase for image processing (resize, thumbnail, filters, ...).

Title: How to convert pixels stored in a list into an image with python?

Body:
pix = [
    [[90, 94, 6], [126, 108, 24], [180, 116, 42], [166, 116, 46], [72, 94, 31]],
    [[101, 96, 14], [190, 165, 84], [202, 134, 63], [170, 115, 50], [40, 50, 0]],
    [[145, 125, 53], [150, 112, 40], [148, 73, 6], [156, 90, 31], [25, 11, 1]],
    [[133, 124, 57], [165, 142, 75], [195, 142, 77], [169, 120, 62], [82, 74, 28]],
    [[73, 105, 40], [56, 77, 10], [138, 135, 67], [97, 95, 34], [45, 69, 21]],
]

I have a bunch of pixels stored in the list and now I want to convert it to an image. How can I turn that list into an image? Thank you

Body:
Using PIL, you can create an image using an array:

from PIL import Image
import numpy as np
img = Image.fromarray(np.array(pix).astype(np.uint8))

Now, you may look at the image:

img.show()

Good thing is, from now on, you can benefit from all of PIL's toolcase for image processing (resize, thumbnail, filters, ...).


问:
How to let JVM know about custom marker interface in java
Is that possible to write our own marker interface in java. I am writing a code like

```<code>public interface MyMarker {

}
</code>```

Is that a marker interface?

If it is possible then how can I let JVM know that this interface is my own created marker interface?

答:
Yes, that's a marker interface. You would test whether an object "implemented" it as simply as:

```<code>if (x instanceof MyMarker)
</code>```

For a particular class (instead of object) you'd want

```<code>if (MyMarker.isAssignableFrom(otherClass))
</code>```

You should consider using annotations instead of marker interfaces though. They're not always direct replacements, but in many cases they're used for the same goals, and annotations are (IMO) cleaner.

Body:
Is that possible to write our own marker interface in java. I am writing a code like

public interface MyMarker {

}

Is that a marker interface?

If it is possible then how can I let JVM know that this interface is my own created marker interface?

Body:
Yes, that's a marker interface. You would test whether an object "implemented" it as simply as:

if (x instanceof MyMarker)

For a particular class (instead of object) you'd want

if (MyMarker.isAssignableFrom(otherClass))

You should consider using annotations instead of marker interfaces though. They're not always direct replacements, but in many cases they're used for the same goals, and annotations are (IMO) cleaner.


问:
JQuery Easing and WebPack
I have a button that have to hide a frameset and show the following one

This a part of my HTML

```<code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-easing/1.3/jquery.easing.min.js"></script>
<script src="./js/scripts-bundled.js"></script>
</code>```

This is where the easing function is called

```<code>import $ from "jquery";

class FormController {
  // variables declararations and some code not useful now...

  buttonClicked(evt) {

    this.current_object.animate(
      { opacity: 0 },
      {
        step: function(now, mx) {
        //as the opacity of current_fs reduces to 0 - stored in "now"
        //1. scale current_fs down to 80%
        scale = 1 - (1 - now) * 0.2;
        //2. bring next_fs from the right(50%)
        left = now * 50 + "%";
        //3. increase opacity of next_fs to 1 as it moves in
        opacity = 1 - now;
        this.current_object.css({
          transform: "scale(" + scale + ")",
          position: "absolute"
        });
        this.next_object.css({ left: left, opacity: opacity });
      },
      duration: 800,
      complete: function() {
        this.current_object.hide();
        this.animating = false;
      },
      //this comes from the custom easing plugin
      easing: "easeInOutBack"
    }
  );
}
</code>```

If I run this code and I click on the button I receive this error
Uncaught TypeError: jQuery.easing[this.easing] is not a function

I believe that, for some reason, the easing plugin is not loaded properly.

Is there a way to require it inside the code via Webpack?

Thanks

答:
I had the same error with jquery.easing and then fix it via Webpack this way:

Add these dependencies to package.json

```<code>"dependencies": {
    "jquery": "3.4.1",
    "jquery.easing": "^1.4.1",
    "popper.js": "^1.16"
}
</code>```

npm run install to install dependencies and import it in your main.js file:

```<code>try {
    window.Popper = require('popper.js').default;
    window.jQuery = window.$ = require('jquery');
    require('jquery.easing'); // dat works :3
} catch (e) {}
</code>```

Then run webpack script (like npm run dev) to make a build for the application.
That's works fine for me.

Title: JQuery Easing and WebPack

Body:
I have a button that have to hide a frameset and show the following one

This a part of my HTML

This is where the easing function is called

import $ from "jquery";

class FormController {
  // variables declararations and some code not useful now...

  buttonClicked(evt) {

    this.current_object.animate(
      { opacity: 0 },
      {
        step: function(now, mx) {
        //as the opacity of current_fs reduces to 0 - stored in "now"
        //1. scale current_fs down to 80%
        scale = 1 - (1 - now) * 0.2;
        //2. bring next_fs from the right(50%)
        left = now * 50 + "%";
        //3. increase opacity of next_fs to 1 as it moves in
        opacity = 1 - now;
        this.current_object.css({
          transform: "scale(" + scale + ")",
          position: "absolute"
        });
        this.next_object.css({ left: left, opacity: opacity });
      },
      duration: 800,
      complete: function() {
        this.current_object.hide();
        this.animating = false;
      },
      //this comes from the custom easing plugin
      easing: "easeInOutBack"
    }
  );
}

If I run this code and I click on the button I receive this error
Uncaught TypeError: jQuery.easing[this.easing] is not a function

I believe that, for some reason, the easing plugin is not loaded properly.

Is there a way to require it inside the code via Webpack?

Thanks

Body:
I had the same error with jquery.easing and then fix it via Webpack this way:

Add these dependencies to package.json

"dependencies": {
    "jquery": "3.4.1",
    "jquery.easing": "^1.4.1",
    "popper.js": "^1.16"
}

npm run install to install dependencies and import it in your main.js file:

try {
    window.Popper = require('popper.js').default;
    window.jQuery = window.$ = require('jquery');
    require('jquery.easing'); // dat works :3
} catch (e) {}

Then run webpack script (like npm run dev) to make a build for the application.
That's works fine for me.


问:
Form Recognizer invalid model status
We tried Form Recognizer custom training, with these steps (API 2.0)

https://pnagarjuna.wordpress.com/2020/01/07/azure-form-recognizer-service-custom-model-training-steps/

The Training modell is success (201), but after Check Custom Model Status we got this error

```<code>{  "modelInfo": {    "modelId": "f17bd306-3c6a-4067-8ef1-5f2e6ced79e1",    "status": "invalid",    "createdDateTime": "2020-02-05T17:24:30Z",    "lastUpdatedDateTime": "2020-02-05T17:24:31Z"  },  "trainResult": {    "trainingDocuments": [],    "errors": [{      "code": "2014",      "message": "No valid blobs found in the specified Azure blob container. Please conform to the document format/size/page/dimensions requirements."    }]  }}
We also check
</code>```

https://learn.microsoft.com/en-us/azure/cognitive-services/form-recognizer/overview#custom-model
and everything is okay.

How can go further?

Thank you!

Gabor

答:
The question has been resolved.

It's not an service issue definitely.

First of all, my prefix shouldn't contain '/' symbol at the beginning.
Another important point is the prefix is case sensitive.
In my case I've uploaded file with "USMF/VendorInvoices/Vendor - 1001/" prefix but requested model training with "usmf/VendorInvoices/Vendor - 1001/". So, this led to the error message - No valid blobs found in the specified Azure blob container. Please conform to the document format/size/page/dimensions requirements.

Title: Form Recognizer invalid model status

Body:
We tried Form Recognizer custom training, with these steps (API 2.0)

https://pnagarjuna.wordpress.com/2020/01/07/azure-form-recognizer-service-custom-model-training-steps/

The Training modell is success (201), but after Check Custom Model Status we got this error

{  "modelInfo": {    "modelId": "f17bd306-3c6a-4067-8ef1-5f2e6ced79e1",    "status": "invalid",    "createdDateTime": "2020-02-05T17:24:30Z",    "lastUpdatedDateTime": "2020-02-05T17:24:31Z"  },  "trainResult": {    "trainingDocuments": [],    "errors": [{      "code": "2014",      "message": "No valid blobs found in the specified Azure blob container. Please conform to the document format/size/page/dimensions requirements."    }]  }}
We also check

https://learn.microsoft.com/en-us/azure/cognitive-services/form-recognizer/overview#custom-model
and everything is okay.

How can go further?

Thank you!

Gabor


问:
Unable to compare the given input of lat and long with generated co-ordinates
In the below prg I'm able to generate lat and long of given max and min co-ordinates. But I'm unable to compare the given input of lat and long with generated co-ordinates and display whether the co-ordinates are inside or outside. It would be great help if someone rectifies the problem
The generated co-ordinates are in this order:

Lat
12.941312
12.941313
12.941314
12.941315
12.941316
12.941317
12.941318
12.941319
12.94132
12.941321

Long 77.565712
77.565713
77.565714
77.565715
77.565716
77.565717
77.565718
77.565719
77.56572
77.565721

```<code>import numpy as np
a=np.arange(12.941312, 12.941389, 0.000001)
b=np.arange(77.565712, 77.565789, 0.000001)
Lat=float(input("ENter the lat:"))
Long=float(input("ENter the long:"))
for lat,long in zip(a,b):

    s=float("{:.6f}".format(lat))
    #print(s)

    t=float("{:.6f}".format(long))
    #print(t)
    if Lat==s and Long==t:
        print("Inside")
else:
    print("Outside")
</code>```

答:
You must compare the coordinates independently:</p>

```<code>import numpy as np
a = np.arange(12.941312, 12.941389, 0.000001)
a_float = [float("{:.6f}".format(lat)) for lat in a]
b = np.arange(77.565712, 77.565813, 0.000001)
b_float = [float("{:.6f}".format(long)) for long in b]
Lat = float(input("ENter the lat:"))
Long = float(input("ENter the long:"))
if Lat in a_float and Long in b_float:
    print("Inside")
else:
    print("Outside")
</code>```

Body:
In the below prg I'm able to generate lat and long of given max and min co-ordinates. But I'm unable to compare the given input of lat and long with generated co-ordinates and display whether the co-ordinates are inside or outside. It would be great help if someone rectifies the problem
The generated co-ordinates are in this order:

Lat
12.941312
12.941313
12.941314
12.941315
12.941316
12.941317
12.941318
12.941319
12.94132
12.941321

Long 77.565712
77.565713
77.565714
77.565715
77.565716
77.565717
77.565718
77.565719
77.56572
77.565721

import numpy as np
a=np.arange(12.941312, 12.941389, 0.000001)
b=np.arange(77.565712, 77.565789, 0.000001)
Lat=float(input("ENter the lat:"))
Long=float(input("ENter the long:"))
for lat,long in zip(a,b):

    s=float("{:.6f}".format(lat))
    #print(s)

    t=float("{:.6f}".format(long))
    #print(t)
    if Lat==s and Long==t:
        print("Inside")
else:
    print("Outside")

Body:
You must compare the coordinates independently:

import numpy as np
a = np.arange(12.941312, 12.941389, 0.000001)
a_float = [float("{:.6f}".format(lat)) for lat in a]
b = np.arange(77.565712, 77.565813, 0.000001)
b_float = [float("{:.6f}".format(long)) for long in b]
Lat = float(input("ENter the lat:"))
Long = float(input("ENter the long:"))
if Lat in a_float and Long in b_float:
    print("Inside")
else:
    print("Outside")


答:
Below is for BigQuery Standard SQL

```<code>#standardSQL
SELECT * EXCEPT(flag),
  COUNTIF(flag) OVER(ORDER BY User, Time) New_Column
FROM (
  SELECT *,
    (User, Property) != LAG((User, Property)) OVER(ORDER BY User, Time) flag
  FROM `project.dataset.table`
)
</code>```

You can test, play with above using dummy data from your question as in example below

```<code>#standardSQL
WITH `project.dataset.table` AS (
  SELECT 'u1' User, DATE '2020-02-01' Time, 'p1' Property UNION ALL
  SELECT 'u1', '2020-02-02', 'p1' UNION ALL
  SELECT 'u1', '2020-02-03', 'p2' UNION ALL
  SELECT 'u1', '2020-02-04', 'p2' UNION ALL
  SELECT 'u2', '2020-02-01', 'p2' UNION ALL
  SELECT 'u2', '2020-02-02', 'p2' UNION ALL
  SELECT 'u2', '2020-02-04', 'p1' UNION ALL
  SELECT 'u2', '2020-02-05', 'p1'
)
SELECT * EXCEPT(flag),
  COUNTIF(flag) OVER(ORDER BY User, Time) New_Column
FROM (
  SELECT *,
    (User, Property) != LAG((User, Property)) OVER(ORDER BY User, Time) flag
  FROM `project.dataset.table`
)
-- ORDER BY User, Time
</code>```

with output

```<code>Row User    Time        Property    New_Column
1   u1      2020-02-01  p1          0
2   u1      2020-02-02  p1          0
3   u1      2020-02-03  p2          1
4   u1      2020-02-04  p2          1
5   u2      2020-02-01  p2          2
6   u2      2020-02-02  p2          2
7   u2      2020-02-04  p1          3
8   u2      2020-02-05  p1          3
</code>```

Title: How to compare previous and current rows in Google Bigquery?

Body:
My sample table scenario is as follows:

+-------------------------------+
| User | Time        | Property |
|------|-------------|----------|
| u1   | 2020-02-01  |    p1    |
| u1   | 2020-02-02  |    p1    |
| u1   | 2020-02-03  |    p2    |
| u1   | 2020-02-04  |    p2    |
| u2   | 2020-02-01  |    p2    |
| u2   | 2020-02-02  |    p2    |
| u2   | 2020-02-04  |    p1    |
| u2   | 2020-02-05  |    p1    |
+-------------------------------+

The data is ordered by User and Time columns.

I want to add a column as follows

+--------------------------------------------+
| User | Time        | Property | New_Column |
|------|-------------|----------|------------|
| u1   | 2020-02-01  |    p1    |  1         |
| u1   | 2020-02-02  |    p1    |  1         |
| u1   | 2020-02-03  |    p2    |  2         |
| u1   | 2020-02-04  |    p2    |  2         |
| u2   | 2020-02-01  |    p2    |  3         |
| u2   | 2020-02-02  |    p2    |  3         |
| u2   | 2020-02-04  |    p1    |  4         |
| u2   | 2020-02-05  |    p1    |  4         |
+--------------------------------------------+

The value in the New_Column is unique for a sequence of continuous rows until the User or the Property changes.

Edit 1:

I am trying to build a logic that makes use of the previous property in time for a user.

select
  *
, lag(property,1) over (partition by User order by Time) as Prev_Property
from table
order by User, Time

Next I added a column Row_Number
This gives me

+------------------------------------------------------------+
| User | Time        | Property | Prev_Property | Row_Number |
|------|-------------|----------|---------------|------------|
| u1   | 2020-02-01  |    p1    |  Null         | 1          |
| u1   | 2020-02-02  |    p1    |  p1           | 2          |
| u1   | 2020-02-03  |    p2    |  p1           | 3          |
| u1   | 2020-02-04  |    p2    |  p2           | 4          |
| u2   | 2020-02-01  |    p2    |  Null         | 5          |
| u2   | 2020-02-02  |    p2    |  p2           | 6          |
| u2   | 2020-02-04  |    p1    |  p2           | 7          |
| u2   | 2020-02-05  |    p1    |  p1           | 8          |
+------------------------------------------------------------+

I tried to build a logic as follows

CASE
  WHEN Prev_Property is not null
  THEN Row_Number
  WHEN Property <> Prev_Property
  THEN Row_Number
  WHEN Property = Prev_Property
  THEN   -- a logic that gives me the Row_Number of the Prev_Property

I am still trying to build the final few conditions in my query. This is my attempt so far.

I don't need the values in New_Column to be in order. I only want them to be unique and satisfying the grouping criteria.

Body:
Below is for BigQuery Standard SQL

#standardSQL
SELECT * EXCEPT(flag),
  COUNTIF(flag) OVER(ORDER BY User, Time) New_Column
FROM (
  SELECT *,
    (User, Property) != LAG((User, Property)) OVER(ORDER BY User, Time) flag
  FROM `project.dataset.table`
)

You can test, play with above using dummy data from your question as in example below

#standardSQL
WITH `project.dataset.table` AS (
  SELECT 'u1' User, DATE '2020-02-01' Time, 'p1' Property UNION ALL
  SELECT 'u1', '2020-02-02', 'p1' UNION ALL
  SELECT 'u1', '2020-02-03', 'p2' UNION ALL
  SELECT 'u1', '2020-02-04', 'p2' UNION ALL
  SELECT 'u2', '2020-02-01', 'p2' UNION ALL
  SELECT 'u2', '2020-02-02', 'p2' UNION ALL
  SELECT 'u2', '2020-02-04', 'p1' UNION ALL
  SELECT 'u2', '2020-02-05', 'p1'
)
SELECT * EXCEPT(flag),
  COUNTIF(flag) OVER(ORDER BY User, Time) New_Column
FROM (
  SELECT *,
    (User, Property) != LAG((User, Property)) OVER(ORDER BY User, Time) flag
  FROM `project.dataset.table`
)
-- ORDER BY User, Time

with output

Row User    Time        Property    New_Column
1   u1      2020-02-01  p1          0
2   u1      2020-02-02  p1          0
3   u1      2020-02-03  p2          1
4   u1      2020-02-04  p2          1
5   u2      2020-02-01  p2          2
6   u2      2020-02-02  p2          2
7   u2      2020-02-04  p1          3
8   u2      2020-02-05  p1          3


问:
How can I extract in excel certain strings that begin with a word from a row that contains multiple strings delimited by commas?
I have the following row in excel: ['milk', 'milk with honey','bread','milk with bread','butter','milk with butter']
I want to be able to extract all the strings that begin with the word "milk" either on separate columns or in the same column.
The extract should look like: milk, milk with honey, milk with bread, milk with butter.</p>

答:
For the sake of simplicity, I will assume that your initial string looks like this:

milk,milk with honey,bread,milk with bread,butter,milk with butter

...and that it's stored in cell A1 of a worksheet named Sheet1.

The first thing I would do to make my life easier, would be to use Text to Columns and define comma as the delimiter. This would split your initial string into as many cells as it needs, the first one being stored in A1.

Then, to find which of the individual strings start with the word milk and combine them to one new string named output, I would do the following:

```<code>Option Explicit

Sub milk()
Dim output As String
Dim inputRng As Range, cell As Range
Dim sht As Worksheet
Set sht = ThisWorkbook.Worksheets("Sheet1")
output = ""
With sht
    Set inputRng = .Range(.Range("A1"), .Cells(1, .Columns.Count).End(xlToLeft))
End With
For Each cell In inputRng.Cells
    If InStr(1, cell.Value, "milk") = 1 Then
        output = output & cell.Value & ", "
    End If
Next cell
MsgBox output
End Sub
</code>```

Body:
For the sake of simplicity, I will assume that your initial string looks like this:

milk,milk with honey,bread,milk with bread,butter,milk with butter

...and that it's stored in cell A1 of a worksheet named Sheet1.

The first thing I would do to make my life easier, would be to use Text to Columns and define comma as the delimiter. This would split your initial string into as many cells as it needs, the first one being stored in A1.

Then, to find which of the individual strings start with the word milk and combine them to one new string named output, I would do the following:

Option Explicit

Sub milk()
Dim output As String
Dim inputRng As Range, cell As Range
Dim sht As Worksheet
Set sht = ThisWorkbook.Worksheets("Sheet1")
output = ""
With sht
    Set inputRng = .Range(.Range("A1"), .Cells(1, .Columns.Count).End(xlToLeft))
End With
For Each cell In inputRng.Cells
    If InStr(1, cell.Value, "milk") = 1 Then
        output = output & cell.Value & ", "
    End If
Next cell
MsgBox output
End Sub


问:
Why is there timing problem while to fork child processes
When I took a look at the reference of 'Launching-Jobs' in gnu.org, I didn't get this part.

The shell should also call setpgid to put each of its child processes into the new process group. This is because there is a potential timing problem: each child process must be put in the process group before it begins executing a new program, and the shell depends on having all the child processes in the group before it continues executing. If both the child processes and the shell call setpgid, this ensures that the right things happen no matter which process gets to it first.

There is two method on the link page, launch_job () and launch_process ().
They both call the setpgid in order to prevent the timing problem.

But I didn't get why is there such a problem.

I guess new program means result of execvp (p->argv[0], p->argv); in launch_process(). And before run execvp, setpgid (pid, pgid); is always executed, without same function on launch_job ().

So again, why is there such a problem? (why we have to call setpgid (); on launch_job () either?)

答:
The problem is that the shell wants the process to be in the right process group. If the shell doesn't call setpgid() on its child process, there is a window of time during which the child process is not part of the process group, while the shell execution continues. (By calling setpgid() the shell can guarantee that the child process is part of the process group after that call).

There is another problem, which is that the child process may execute the new program (via exec) before its process group id has been properly set (i.e. before the parent calls setpgid()). That is why the child process should also call setpgid() (before calling exec()).

The description is admittedly pretty bad. There isn't just one problem being solved here; it's really two separate problems. One - the parent (i.e. the shell) wants to have the child process in the right process group. Two - the new program should begin execution only once its process has already been put into the right process group.


问:
How to create events for a visitor that is already an intercom user?
We use both intercom web library and intercom-java sdk to send events as some events can be sent from client side, but some need to be sent from server side. Here is how we send server side events:

When the visitor triggers some action, say a failed login attempt, we grab visitorId from web library window.Intercom("getVisitorId") and send it to the server

On the server side, we first try to find the visitor Visitor.findByUserID(visitorId), if it returns NotFoundException, then we try to find the lead Contact.findByUserID(visitorId), if it returns NotFoundException, then we try to find currently logged in user from server session(I know, old technology), if no logged in user found, we can't create the event because we don't know who the user is. If any of the steps above succeeds, we can create the event with the returned user's userId

The flow above usually works, however it doesn't work when the visitor has already logged in, and remains in the same intercom session while the server session is cleared out - say we restarted the server after the visitor logged in. In this case, the visitorId doesn't represent any visitor/lead anymore, and the user is no longer logged in to be found in the server session. So we don't know how to identify the user on the server side to send the event.

This is not a problem for client side events. So my question is, is there a way to workaround this on the intercom-java sdk side?

答:
I workaround it by doing the following on intercom web library loaded:

If window.intercomSettings.user_id is not null, don't do nothing else, otherwise proceed to next step

Make a call with window.Intercom("getVisitorId") to check if current visitor exists or not

If visitor exists, don't do anything else, otherwise reload intercom by calling:

```<code>window.Intercom("shutdown");
window.Intercom("boot", window.intercomSettings)
</code>```

This will make sure intercom session in sync with server session, and any non logged in user to be treated as visitor.

Body:
I workaround it by doing the following on intercom web library loaded:

If window.intercomSettings.user_id is not null, don't do nothing else, otherwise proceed to next step

Make a call with window.Intercom("getVisitorId") to check if current visitor exists or not

If visitor exists, don't do anything else, otherwise reload intercom by calling:

window.Intercom("shutdown");
window.Intercom("boot", window.intercomSettings)

This will make sure intercom session in sync with server session, and any non logged in user to be treated as visitor.


问:
Laravel - How to Customize Ellipsis with a button
I have a web application project using Laravel-5.8. In the project, I applied HTML text editor.

Controller

```<code>public function create()
{
    return view('organization.announcements.create');
}

public function store(StoreAnnouncementRequest $request)
{
    try {
        $announcement = new OrgAnnouncement();
        $announcement->title                    = $request->title;
        $announcement->description              = $request->description;

        $announcement->save();

            Session::flash('success', 'Announcement is created successfully');
            return redirect()->route('organization.announcements.index');
    } catch (Exception $exception) {
            Session::flash('danger', 'Announcement creation failed!');
            return redirect()->route('organization.announcements.index');
    }
}
</code>```

View

                        #

                        Announcement Title

                        Description

                @foreach($announcements as $key => $announcement)

                            {{$key+1}}

                            {{$announcement->title ?? '' }}

                            {{str_limit($announcement->description, $limit = 20, $end = ' ...')}}

                            @can('announcement_show')
                                id) }}">
                                    {{ trans('global.view') }}

                            @endcan
                            @can('announcement_edit')
                                $announcement->id]) }}">
                                    {{ trans('global.edit') }}

                            @endcan
                            @can('announcement_delete')
                                id }}" data-original-title="Close">
                                    {{ trans('global.delete') }}

                            @endcan

id }}" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">

Delete Announcement

                                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                  ×
                                </button>

                                <form action="{{route('organization.announcements.destroy',$announcement->id)}}" method="post">
                                    {{ csrf_field() }}

Are you sure you want to delete this Announcement?

{{ $announcement->title }}

                                </form>

                                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                                <button type="submit" class="btn btn-danger">Delete</button>

                @endforeach

```

The field description is the text editor. On the view blade, I truncated the field description to 20 characters and ... will be displayed as shown in my field.

However, what I want to achieve is that I want to replace the ... with a button that will have view more. Then it is clicked, it will show the full content in a modal form of redirect to another page.

How do I achieve this?

Thank you

答:
You may use</p>

```<code><td>
    {{str_limit($announcement->description, $limit = 20, $end = ' ...')}}
    @if(strlen($announcement->description) > 20)
      <a href="{{ route('organization.announcements.show', $announcement->id) }}"> Show more </a>
    @endif

</td>
</code>```

Body:
I have a web application project using Laravel-5.8. In the project, I applied HTML text editor.

Controller

public function create()
{
    return view('organization.announcements.create');
}

public function store(StoreAnnouncementRequest $request)
{
    try {
        $announcement = new OrgAnnouncement();
        $announcement->title                    = $request->title;
        $announcement->description              = $request->description;

        $announcement->save();

            Session::flash('success', 'Announcement is created successfully');
            return redirect()->route('organization.announcements.index');
    } catch (Exception $exception) {
            Session::flash('danger', 'Announcement creation failed!');
            return redirect()->route('organization.announcements.index');
    }
}

View

                        #

                        Announcement Title

                        Description

                @foreach($announcements as $key => $announcement)

                            {{$key+1}}

                            {{$announcement->title ?? '' }}

                            {{str_limit($announcement->description, $limit = 20, $end = ' ...')}}

                            @can('announcement_show')
                                id) }}">
                                    {{ trans('global.view') }}

                            @endcan
                            @can('announcement_edit')
                                $announcement->id]) }}">
                                    {{ trans('global.edit') }}

                            @endcan
                            @can('announcement_delete')
                                id }}" data-original-title="Close">
                                    {{ trans('global.delete') }}

                            @endcan

id }}" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">

Delete Announcement

                                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                  ×
                                </button>

                                <form action="{{route('organization.announcements.destroy',$announcement->id)}}" method="post">
                                    {{ csrf_field() }}

Are you sure you want to delete this Announcement?

{{ $announcement->title }}

                                </form>

                                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                                <button type="submit" class="btn btn-danger">Delete</button>

                @endforeach

The field description is the text editor. On the view blade, I truncated the field description to 20 characters and ... will be displayed as shown in my field.

However, what I want to achieve is that I want to replace the ... with a button that will have view more. Then it is clicked, it will show the full content in a modal form of redirect to another page.

How do I achieve this?

Thank you

Body:
You may use

<td>
    {{str_limit($announcement->description, $limit = 20, $end = ' ...')}}
    @if(strlen($announcement->description) > 20)
      <a href="{{ route('organization.announcements.show', $announcement->id) }}"> Show more </a>
    @endif

</td>


问:
Stop PyYaml from converting a yaml item to list
I am trying to load the following yaml:

yaml_string = """
key:
- [HELLO]
- another string
- another
"""
yaml.safe_load(yaml_string) # returns {"key": [["HELLLO"], "another_string", "another"}
```

<p>and the result is a list containing the HELLO string. I wan to load this a string value that is </p>

<pre class="lang-py prettyprint-override"><code>type(yaml.save_load(yaml_string).get("key")[0])
<class 'str'>
</code>```

Since yaml describes some sort of commnads that are formatted this way, it is necessary to be read as strings and not as sequences. Basically I want to be able to read strings that start and end with brackets. As explained to the comment underneath, unfortunatelly it is not possible to add " since the yaml files were created by a Java app using Jackson which didn't have a problem turning yaml into an object and treating entries that start and end with brackets as strings.  The files are to many for users to start adding quotes.

Is this possible?

EDIT: Added a more complete example

答:
surround [HELLO] with quotes:

```<code>import yaml

yaml_string = """
key:
- "[HELLO]"
- another string
- another
"""

print(yaml.safe_load(yaml_string))
</code>```

outputs

```<code>{'key': ['[HELLO]', 'another string', 'another']}
</code>```

Body:
I am trying to load the following yaml:

yaml_string = """
key:
- [HELLO]
- another string
- another
"""
yaml.safe_load(yaml_string) # returns {"key": [["HELLLO"], "another_string", "another"}

and the result is a list containing the HELLO string. I wan to load this a string value that is

type(yaml.save_load(yaml_string).get("key")[0])
<class 'str'>

Since yaml describes some sort of commnads that are formatted this way, it is necessary to be read as strings and not as sequences. Basically I want to be able to read strings that start and end with brackets. As explained to the comment underneath, unfortunatelly it is not possible to add " since the yaml files were created by a Java app using Jackson which didn't have a problem turning yaml into an object and treating entries that start and end with brackets as strings.  The files are to many for users to start adding quotes.

Is this possible?

EDIT: Added a more complete example

Body:
surround [HELLO] with quotes:

import yaml

yaml_string = """
key:
- "[HELLO]"
- another string
- another
"""

print(yaml.safe_load(yaml_string))

outputs

{'key': ['[HELLO]', 'another string', 'another']}


问:
Angular how to display data from user which contain an array
I'm working on RecipesApp (Asp.Net MVC + Angular as a View)

I have User which contain ICollection of Recipes

What i'm trying to do is:

Display all recipes from User.

Smth like that *ngFor let user of user.recipes

{{user.recipes}}

What i've already tried
My user class:

```<code>export interface User {
    id: number;
    username: string;
    knownAs: string;
    age: number;
    gender: string;
    created: Date;
    lastActive: Date;
    photoUrl: string;
    city: string;
    country: string;
    introduction?: string;
    userPhotos?: UserPhoto[];
    recipes?: Recipe[];
}
</code>```

MyComponent

```<code>export class MemberDetailComponent implements OnInit {
  user: User;
  recipes: Recipe[];

  constructor(private userService: UserService, private alertify: AlertifyService, private route: ActivatedRoute) { }

  ngOnInit() {
    this.route.data.subscribe(data => {
      this.user.recipes = data.user;
    });
  }
</code>```

html

```<code><div class="container">
    {{user.username}}
    <br>
    <hr>
    <p class="text-center">User Recipes: </p>

    <!-- <div *ngFor="let user of user" class="col-lg-3 col-md-3 col-sm-6">
      </div> -->
    </div>
</code>```

@EDIT

My resolver:

```<code>import {Injectable} from '@angular/core';
import { User } from '../_models/user';
import { Resolve, Router, ActivatedRouteSnapshot } from '@angular/router';
import { UserService } from '../_services/user.service';
import { Observable, of } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { AlertifyService } from '../_services/alertify.service';

@Injectable()
export class MemberDetailResolver implements Resolve<User> {

    constructor(private userService: UserService, private router: Router, private alertify: AlertifyService) {

    }

    resolve(route: ActivatedRouteSnapshot): Observable<User> {
        return this.userService.getUser(route.params.id).pipe(
            catchError(error => {
                this.alertify.error('Problem retrieving data');
                this.router.navigate(['/members']);
                return of(null);
            })
        );

    }
}
</code>```

Recipe class

```<code>export interface Recipe {
    id: number;
    name: string;
    ingredients: string;
    preparationTime: number;
    dateAdded: Date;
    photoUrl: string;
    description?: string;
    recipePhotos?: RecipePhoto[];
}
</code>```

答:
try this in you .html:

in your ts you need to do this:

```<code>ngOnInit() {
    this.route.data.subscribe(data => {
      this.user= data.user; //here change
    });
  }
</code>```

and in your html (I suppose recipes class has a property name)

```<code>     <div  *ngFor="let recipe of user.recipes" >
      <p>{{recipe.name}}</p>
     </div>
</code>```

Body:
I'm working on RecipesApp (Asp.Net MVC + Angular as a View)

I have User which contain ICollection of Recipes

What i'm trying to do is:

Display all recipes from User.

Smth like that *ngFor let user of user.recipes

{{user.recipes}}

What i've already tried
My user class:

export interface User {
    id: number;
    username: string;
    knownAs: string;
    age: number;
    gender: string;
    created: Date;
    lastActive: Date;
    photoUrl: string;
    city: string;
    country: string;
    introduction?: string;
    userPhotos?: UserPhoto[];
    recipes?: Recipe[];
}

MyComponent

export class MemberDetailComponent implements OnInit {
  user: User;
  recipes: Recipe[];

  constructor(private userService: UserService, private alertify: AlertifyService, private route: ActivatedRoute) { }

  ngOnInit() {
    this.route.data.subscribe(data => {
      this.user.recipes = data.user;
    });
  }

html

    {{user.username}}

User Recipes:

@EDIT

My resolver:

import {Injectable} from '@angular/core';
import { User } from '../_models/user';
import { Resolve, Router, ActivatedRouteSnapshot } from '@angular/router';
import { UserService } from '../_services/user.service';
import { Observable, of } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { AlertifyService } from '../_services/alertify.service';

@Injectable()
export class MemberDetailResolver implements Resolve<User> {

    constructor(private userService: UserService, private router: Router, private alertify: AlertifyService) {

    }

    resolve(route: ActivatedRouteSnapshot): Observable<User> {
        return this.userService.getUser(route.params.id).pipe(
            catchError(error => {
                this.alertify.error('Problem retrieving data');
                this.router.navigate(['/members']);
                return of(null);
            })
        );

    }
}

Recipe class

export interface Recipe {
    id: number;
    name: string;
    ingredients: string;
    preparationTime: number;
    dateAdded: Date;
    photoUrl: string;
    description?: string;
    recipePhotos?: RecipePhoto[];
}

Body:
try this in you .html:

in your ts you need to do this:

ngOnInit() {
    this.route.data.subscribe(data => {
      this.user= data.user; //here change
    });
  }

and in your html (I suppose recipes class has a property name)

     <div  *ngFor="let recipe of user.recipes" >
      <p>{{recipe.name}}</p>
     </div>


问:
Why must a variable be declared in a for loop initialization?

int v = 0;

for (v; v<2; v++) {
    ...

}
```

Why is this not allowed in Java?

Why do we have to declare variable v in the for loop initialization?
I know it's not a statement if I do it like that but why doesn't Java allow the above?

答:
int w =0;

int v;

for(v;v<2;v++){

}
 you have declared v prior the loop but you again used without any initialization.

if you use w which is already declared and initialized prior then there will be no issues.like below code,

for(;w<2;w++){

}

Body:
int v = 0;

for (v; v<2; v++) {
    ...

}

Why is this not allowed in Java?

Why do we have to declare variable v in the for loop initialization?
I know it's not a statement if I do it like that but why doesn't Java allow the above?


问:
Python saving file to Wrong path
My intention for the code bellow is to save a file inside a folder. But the file is beeing saved on the folder before the correct one.

How can i modify it so it saves the file to correct folder?

    #Make Selenium check the chatroom name
    chatroom = driver.find_element_by_class_name('_19vo_').text

    #Create a variable of a folder path with chatroom name
    chat_path = 'D:\Drive\Outros\Python\data_save\chats\ ' + chatroom

    #Verify if folder already exists, if not, create it
    Path(chat_path).mkdir(parents=True, exist_ok=True)

    #Save a df.csv to the chatroom folder
    df.to_csv(chat_path +chatroom+' in'+ timestr +' .csv', index=None, header=True, encoding='utf-8-sig')```

答:
You are missing a directory separator:

```<code>df.to_csv(chat_path + '/' +chatroom+' in'+ timestr +' .csv', index=None, header=True, encoding='utf-8-sig')
</code>```

The best practice is to use os.path.join:

```<code>import os
chat_filename = '%s in%s.csv' % (chatroom, timestr)
df.to_csv(os.path.join(chat_path, chat_filename), index=None, header=True, encoding='utf-8-sig')
</code>```

Title: Python saving file to Wrong path

Body:
You are missing a directory separator:

df.to_csv(chat_path + '/' +chatroom+' in'+ timestr +' .csv', index=None, header=True, encoding='utf-8-sig')

The best practice is to use os.path.join:

import os
chat_filename = '%s in%s.csv' % (chatroom, timestr)
df.to_csv(os.path.join(chat_path, chat_filename), index=None, header=True, encoding='utf-8-sig')


问:
Passing variable arguments conditionally
In one of my iPhone application, I need to send the variable arguments to the action sheet conditionally. i.e

```<code>if(condition1)
    otherButtonTitles = @"Button1", @"Button2", nil
else
    otherButtonTitles = @"Button3", @"Button4", nil

UIActionSheet *mediaActionsSheet = [[UIActionSheet alloc] initWithTitle: nil
                                                             delegate: self
                                                    cancelButtonTitle: @"Cancel"
                                               destructiveButtonTitle: nil
                                                    otherButtonTitles: otherButtonTitles];
</code>```

What is the syntax to do this? How should the data type for otherButtonTitles be defined?

答:
You can't. (Well, it's not impossible, but you don't want to do that.)

Just use

```<code>UIActionSheet *mediaActionsSheet=nil;
if(condition){
         mediaActionsSheet=[[UIActionSheet alloc] initWithTitle: nil
                                                         delegate: self
                                                cancelButtonTitle: @"Cancel"
                                           destructiveButtonTitle: nil
                                                otherButtonTitles: @"button1",@"button2",nil];
}else{
         mediaActionsSheet=[[UIActionSheet alloc] initWithTitle: nil
                                                         delegate: self
                                                cancelButtonTitle: @"Cancel"
                                           destructiveButtonTitle: nil
                                                otherButtonTitles: @"button2",@"button3",nil];
}
</code>```

If you really want to construct a variable to hold variable number of arguments, start from this Wikipedia article. But you don't really want to do that. I promise.

Body:
In one of my iPhone application, I need to send the variable arguments to the action sheet conditionally. i.e

if(condition1)
    otherButtonTitles = @"Button1", @"Button2", nil
else
    otherButtonTitles = @"Button3", @"Button4", nil

UIActionSheet *mediaActionsSheet = [[UIActionSheet alloc] initWithTitle: nil
                                                             delegate: self
                                                    cancelButtonTitle: @"Cancel"
                                               destructiveButtonTitle: nil
                                                    otherButtonTitles: otherButtonTitles];

What is the syntax to do this? How should the data type for otherButtonTitles be defined?

Body:
You can't. (Well, it's not impossible, but you don't want to do that.)

Just use

UIActionSheet *mediaActionsSheet=nil;
if(condition){
         mediaActionsSheet=[[UIActionSheet alloc] initWithTitle: nil
                                                         delegate: self
                                                cancelButtonTitle: @"Cancel"
                                           destructiveButtonTitle: nil
                                                otherButtonTitles: @"button1",@"button2",nil];
}else{
         mediaActionsSheet=[[UIActionSheet alloc] initWithTitle: nil
                                                         delegate: self
                                                cancelButtonTitle: @"Cancel"
                                           destructiveButtonTitle: nil
                                                otherButtonTitles: @"button2",@"button3",nil];
}

If you really want to construct a variable to hold variable number of arguments, start from this Wikipedia article. But you don't really want to do that. I promise.


问:
XHProf profiling - How to get hierarchical profile?
I can see high CPU usage when I hit search URL of my Drupal application. I have enabled XHProf module and UProfiler extension on PHP5.6 to find the culprit function.

But the report I am getting is giving me only the first level of functions which takes cpu time.

But, there is no hyperlink on the function names to click on it and drill down. Any suggestions on what else can be done to drill down?

Basically it shows only flat profile, how do I get Hierarchical profile view?

答: This is fully possible with the native GUI that comes with Xhprof, you just have to make the xhprof_html directory reachable from your document root.


问:
OnChange for Storing Value of Selected Drop Down Option
I have a Material UI dropdown menu. I will make a search later on the basis of the selected option from the drop down menu. How exactly could I use onChange() to store the option selected?

For now, I am trying to print the stored value (criteria) using typography at the end but instead of showing the selected value, I get a black page.

```<code>export default class userSearchPage extends Component<{}, { searchItem: string, criteria: string }>{

  constructor(props: Readonly<{}>) {
    super(props);
    this.state = {
      searchItem: '',
      criteria: '',
    };
    this.handleDropDownChange = this.handleDropDownChange.bind(this);
  }

  handleDropDownChange(selected: any) {
    this.setState({
        criteria: selected
    });
  }

  render() {
    return (
      <div>
        <PermanentDrawerLeft></PermanentDrawerLeft>
        <div className='main-content'>
          <MuiThemeProvider>
            <DropDownMenu onChange = {this.handleDropDownChange}>
              <MenuItem style={{ fontSize: "20px" }} primaryText="Search By" />
              <MenuItem value={1} style={{ fontSize: "20px" }} primaryText="First Name" />
              <MenuItem value={2} style={{ fontSize: "20px" }} primaryText="Last Name" />
              <MenuItem value={3} style={{ fontSize: "20px" }} primaryText="Phone Number" />
              <MenuItem value={4} style={{ fontSize: "20px" }} primaryText="Email" />
            </DropDownMenu>
          </MuiThemeProvider>
          <Typography>{this.state.criteria}</Typography>
          <br></br><br></br>
          <SearchBar
            onChange={e => this.setState({ searchItem: e })}
            value = {this.state.searchItem}
            onRequestSearch={() => console.log('onRequestSearch')}
            style={{
              margin: '0 auto',
              maxWidth: 800
            }}
          />
           <Typography>{this.state.criteria}</Typography>
        </div>
      </div>
    );
  }
}
</code>```

How could I fix this?

Note: This is typescript

Added

```<code>export default class userSearchPage extends Component<{}, { searchItem: string, criteria: any}>{

  constructor(props: Readonly<{}>) {
    super(props);
    this.state = {
      searchItem: '',
      criteria: null,
    };
    this.handleDropDownChange = this.handleDropDownChange.bind(this);
  }

  handleDropDownChange(event: any) {
    console.log(event.target.value);
    this.setState({
      criteria: event.target.value
    });
  }

  render() {
    return (
      <div>
        <PermanentDrawerLeft></PermanentDrawerLeft>
        <div className='main-content'>
        <InputLabel id="demo-simple-select-label">Search By</InputLabel>
          <Select
            value={this.state.criteria}
            onChange={this.handleDropDownChange}
            displayEmpty
          >
            <MenuItem disabled value="  ">
              <em>Search By</em>
            </MenuItem>
            <MenuItem value={1}>First Name</MenuItem>
            <MenuItem value={2}>Last Name</MenuItem>
            <MenuItem value={3}>Phone Number</MenuItem>
            <MenuItem value={4}>Email</MenuItem>
          </Select>
        </div>
      </div>
    );
  }
}
</code>```

答: You could use the onChange event to do something when the user is selecting an option. If you want information, you could look at this article: https://www.w3schools.com/jsref/event_onchange.asp</p>

Body:
I have a Material UI dropdown menu. I will make a search later on the basis of the selected option from the drop down menu. How exactly could I use onChange() to store the option selected?

For now, I am trying to print the stored value (criteria) using typography at the end but instead of showing the selected value, I get a black page.

export default class userSearchPage extends Component<{}, { searchItem: string, criteria: string }>{

  constructor(props: Readonly<{}>) {
    super(props);
    this.state = {
      searchItem: '',
      criteria: '',
    };
    this.handleDropDownChange = this.handleDropDownChange.bind(this);
  }

  handleDropDownChange(selected: any) {
    this.setState({
        criteria: selected
    });
  }

  render() {
    return (

        <PermanentDrawerLeft></PermanentDrawerLeft>

          <MuiThemeProvider>
            <DropDownMenu onChange = {this.handleDropDownChange}>
              <MenuItem style={{ fontSize: "20px" }} primaryText="Search By" />
              <MenuItem value={1} style={{ fontSize: "20px" }} primaryText="First Name" />
              <MenuItem value={2} style={{ fontSize: "20px" }} primaryText="Last Name" />
              <MenuItem value={3} style={{ fontSize: "20px" }} primaryText="Phone Number" />
              <MenuItem value={4} style={{ fontSize: "20px" }} primaryText="Email" />
            </DropDownMenu>
          </MuiThemeProvider>
          <Typography>{this.state.criteria}</Typography>

          <SearchBar
            onChange={e => this.setState({ searchItem: e })}
            value = {this.state.searchItem}
            onRequestSearch={() => console.log('onRequestSearch')}
            style={{
              margin: '0 auto',
              maxWidth: 800
            }}
          />
           <Typography>{this.state.criteria}</Typography>

    );
  }
}

How could I fix this?

Note: This is typescript

Added

export default class userSearchPage extends Component<{}, { searchItem: string, criteria: any}>{

  constructor(props: Readonly<{}>) {
    super(props);
    this.state = {
      searchItem: '',
      criteria: null,
    };
    this.handleDropDownChange = this.handleDropDownChange.bind(this);
  }

  handleDropDownChange(event: any) {
    console.log(event.target.value);
    this.setState({
      criteria: event.target.value
    });
  }

  render() {
    return (

        <PermanentDrawerLeft></PermanentDrawerLeft>

        <InputLabel id="demo-simple-select-label">Search By</InputLabel>
          <Select
            value={this.state.criteria}
            onChange={this.handleDropDownChange}
            displayEmpty
          >
            <MenuItem disabled value="  ">
              Search By
            </MenuItem>
            <MenuItem value={1}>First Name</MenuItem>
            <MenuItem value={2}>Last Name</MenuItem>
            <MenuItem value={3}>Phone Number</MenuItem>
            <MenuItem value={4}>Email</MenuItem>
          </Select>

    );
  }
}


答:
If you want the string "HELLO" as a result, then remove the [...] around it in the YAML:

```<code>yaml_string = """
key:
- HELLO
"""
print(yaml.safe_load(yaml_string))
# {'key': ['HELLO']}
</code>```

If you want the string "[HELLO]" (instead of a list containing the string "HELLO"), then add quotes in the YAML:

```<code>yaml_string = """
key:
- "[HELLO]"
"""
print(yaml.safe_load(yaml_string))
# {'key': ['[HELLO]']}
</code>```

Title: Stop PyYaml from converting a yaml item to list

Body:
If you want the string "HELLO" as a result, then remove the [...] around it in the YAML:

yaml_string = """
key:
- HELLO
"""
print(yaml.safe_load(yaml_string))
# {'key': ['HELLO']}

If you want the string "[HELLO]" (instead of a list containing the string "HELLO"), then add quotes in the YAML:

yaml_string = """
key:
- "[HELLO]"
"""
print(yaml.safe_load(yaml_string))
# {'key': ['[HELLO]']}


问:
Python module "logging" double output
I want to use the logging module, but I'm having some trouble because it is outputting twice. I've read a lot of posts with people having the same issue and log.propagate = False or `log.handlers.pop()´ fixed it for them. This doesn't work for me.

I have a file called logger.py that looks like this:

```<code>import logging

def __init__():
    log = logging.getLogger("output")
    filelog = logging.FileHandler("output.log")
    formatlog = logging.Formatter("%(asctime)s %(levelname)s %(message)s")
    filelog.setFormatter(formatlog)
    log.addHandler(filelog)
    log.setLevel(logging.INFO)

    return log
</code>```

So that I from multiple files can write:

```<code>import logger
log = logger.__init__()
</code>```

But this is giving me issues. So I've seen several solutions, but I don't know how to incorporate it in multiple scripts without defining the logger in all of them.

答:
You have to be very carefully by adding new handler to your logger with:

```<code>log.addHandler(...)
</code>```

If you add more than one handler to your logger, you will get more than one outputs. Be aware that this is only truth for logger which are running in the same thread. If you are running a class which is derived from Thread, then it is the same thread. But if you are running a class which is derived from Process, then it is another thread. To ensure that you only have one handler for your logger according to this thread, you should use the following code (this is an example for SocketHandler):

```<code>logger_root = logging.getLogger()
if not logger_root.hasHandlers():
    socket_handler = logging.handlers.SocketHandler('localhost', logging.handlers.DEFAULT_TCP_LOGGING_PORT)
    logger_root.addHandler(socket_handler)
</code>```

Title: Python module "logging" double output

Body:
I want to use the logging module, but I'm having some trouble because it is outputting twice. I've read a lot of posts with people having the same issue and log.propagate = False or `log.handlers.pop()´ fixed it for them. This doesn't work for me.

I have a file called logger.py that looks like this:

import logging

def __init__():
    log = logging.getLogger("output")
    filelog = logging.FileHandler("output.log")
    formatlog = logging.Formatter("%(asctime)s %(levelname)s %(message)s")
    filelog.setFormatter(formatlog)
    log.addHandler(filelog)
    log.setLevel(logging.INFO)

    return log

So that I from multiple files can write:

import logger
log = logger.__init__()

But this is giving me issues. So I've seen several solutions, but I don't know how to incorporate it in multiple scripts without defining the logger in all of them.

Body:
You have to be very carefully by adding new handler to your logger with:

log.addHandler(...)

If you add more than one handler to your logger, you will get more than one outputs. Be aware that this is only truth for logger which are running in the same thread. If you are running a class which is derived from Thread, then it is the same thread. But if you are running a class which is derived from Process, then it is another thread. To ensure that you only have one handler for your logger according to this thread, you should use the following code (this is an example for SocketHandler):

logger_root = logging.getLogger()
if not logger_root.hasHandlers():
    socket_handler = logging.handlers.SocketHandler('localhost', logging.handlers.DEFAULT_TCP_LOGGING_PORT)
    logger_root.addHandler(socket_handler)


问:
Detecting length of overlap between two strings
```<code>int overlap(const char *s1, const char *s2){
    int i = 0;
    while (s1[i] && s2[i] && s1[i] == s2[i])
        i++;
    return i;
}
</code>```

This returns the length of the substring overlap between the two strings it takes as input. However, if the two strings are:

```<code>abcdefg
1234efg
</code>```

it returns an overlap of 0 because it can only read overlaps that start at the beginning of the strings, can someone modify or help me to make it so that it can read overlaps no mantter where they are in the strings?

答:
i think the codes will be like this:</p>

```<code>int overlap(const char *s1, const char *s2){
    int i = 0, n = 0;
    while (s1[i] && s2[i]) {
        if (s1[i++] == s2[i++]) n++;
    }
    return n;
}
</code>```

Body:
int overlap(const char *s1, const char *s2){
    int i = 0;
    while (s1[i] && s2[i] && s1[i] == s2[i])
        i++;
    return i;
}

This returns the length of the substring overlap between the two strings it takes as input. However, if the two strings are:

abcdefg
1234efg

it returns an overlap of 0 because it can only read overlaps that start at the beginning of the strings, can someone modify or help me to make it so that it can read overlaps no mantter where they are in the strings?

Body:
i think the codes will be like this:

int overlap(const char *s1, const char *s2){
    int i = 0, n = 0;
    while (s1[i] && s2[i]) {
        if (s1[i++] == s2[i++]) n++;
    }
    return n;
}


问:
How to set up a key press detection that toggles the state of the boolean variable
How to set up a key press detection that toggles the state of the boolean variable paused where paused is an attribute of my GCTester class with an initial state of false?

```<code>// GCTester demonstrates how we can override the GameCore class
// to create our own 'game'. We usually need to implement at
// least 'draw' and 'update' (not including any local event handling)
// to begin the process. You should also write your own 'init'
// method that will initialise event handlers etc. By default GameCore
// will handle the 'Escape' key to quit the game but you should
// override this with your own event handler.

public class GCTester extends GameCore {

    private Animation anim;
    private Sprite rock;
    long total;         // Total time elapsed
    boolean paused;

    // The obligatory main method that creates
    // an instance of our GCTester class and
    // starts it running
    public static void main(String[] args) {
        GCTester gct = new GCTester();
        gct.init();
        // Start in windowed mode with a 800x600 screen
        gct.run(false, 800, 600);
    }

    // Initialise the class, e.g. set up variables
    // animations, register event handlers
    public void init() {
        total = 0;
        Image player = loadImage("images/rock.png");
        anim = new Animation();
        anim.addFrame(player, 20);

        rock = new Sprite(anim);

        rock.setX(100);
        rock.setY(100);
        rock.setVelocityX(0.1f);
        rock.setVelocityY(0.1f);
        rock.show();
    }

    // Draw the current frame
    public void draw(Graphics2D g) {
        // A simple demo - note that this is not
        // very efficient since we fill the screen
        // on every frame.
        g.setColor(Color.black);
        g.fillRect(0, 0, 800, 600);
        g.setColor(Color.yellow);
        g.drawString("Time Expired:" + total, 30, 50);

        rock.draw(g);
    }

    // Update any sprites and check for collisions
    public void update(long elapsed) {
        if (paused) return;
        total += elapsed;
        if (total > 60000) stop();
        rock.update(elapsed);
    }

    public void keyPressed(KeyEvent e) {
        int keyCode = e.getKeyCode();
        if (keyCode == KeyEvent.VK_ESCAPE)
            stop(); // Call GameCore stop method to stop the game loop
        else {
            if (keyCode == KeyEvent.VK_S) rock.stop();
            if (keyCode == KeyEvent.VK_G) rock.setVelocityX(0.1f);

            e.consume();
        }
    }
}
</code>```

答:
You should use a window component to show your app on screen. Suppose it's a JFrame (or it can be a JDialog). Create a JComponent that will 'listen' to key actions, add it to your jFrame, or any other upper window component you use:

```<code>JComponent controlComp = new JComponent() {};
controlComp.setBounds(0, 0, 800, 600); // your bounds
controlComp.setFocusTraversalKeysEnabled(false);
jFrame.add(controlComp);

ActionListener keyEscListener = new ActionListener() {
    public void actionPerformed(ActionEvent actionEvent) {
        paused = !paused;
        // your logic for Escape
    }
};

// tie KeyStroke and keyboard action to the controlComp
KeyStroke keyEsc = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0, false);
controlComp.registerKeyboardAction(keyEscListener, keyEsc, JComponent.WHEN_FOCUSED);

</code>```

This method requires creating separate Listener and KeyStroke object for each key you want to listen

Body:
How to set up a key press detection that toggles the state of the boolean variable paused where paused is an attribute of my GCTester class with an initial state of false?

// GCTester demonstrates how we can override the GameCore class
// to create our own 'game'. We usually need to implement at
// least 'draw' and 'update' (not including any local event handling)
// to begin the process. You should also write your own 'init'
// method that will initialise event handlers etc. By default GameCore
// will handle the 'Escape' key to quit the game but you should
// override this with your own event handler.

public class GCTester extends GameCore {

    private Animation anim;
    private Sprite rock;
    long total;         // Total time elapsed
    boolean paused;

    // The obligatory main method that creates
    // an instance of our GCTester class and
    // starts it running
    public static void main(String[] args) {
        GCTester gct = new GCTester();
        gct.init();
        // Start in windowed mode with a 800x600 screen
        gct.run(false, 800, 600);
    }

    // Initialise the class, e.g. set up variables
    // animations, register event handlers
    public void init() {
        total = 0;
        Image player = loadImage("images/rock.png");
        anim = new Animation();
        anim.addFrame(player, 20);

        rock = new Sprite(anim);

        rock.setX(100);
        rock.setY(100);
        rock.setVelocityX(0.1f);
        rock.setVelocityY(0.1f);
        rock.show();
    }

    // Draw the current frame
    public void draw(Graphics2D g) {
        // A simple demo - note that this is not
        // very efficient since we fill the screen
        // on every frame.
        g.setColor(Color.black);
        g.fillRect(0, 0, 800, 600);
        g.setColor(Color.yellow);
        g.drawString("Time Expired:" + total, 30, 50);

        rock.draw(g);
    }

    // Update any sprites and check for collisions
    public void update(long elapsed) {
        if (paused) return;
        total += elapsed;
        if (total > 60000) stop();
        rock.update(elapsed);
    }

    public void keyPressed(KeyEvent e) {
        int keyCode = e.getKeyCode();
        if (keyCode == KeyEvent.VK_ESCAPE)
            stop(); // Call GameCore stop method to stop the game loop
        else {
            if (keyCode == KeyEvent.VK_S) rock.stop();
            if (keyCode == KeyEvent.VK_G) rock.setVelocityX(0.1f);

            e.consume();
        }
    }
}

Body:
You should use a window component to show your app on screen. Suppose it's a JFrame (or it can be a JDialog). Create a JComponent that will 'listen' to key actions, add it to your jFrame, or any other upper window component you use:

JComponent controlComp = new JComponent() {};
controlComp.setBounds(0, 0, 800, 600); // your bounds
controlComp.setFocusTraversalKeysEnabled(false);
jFrame.add(controlComp);

ActionListener keyEscListener = new ActionListener() {
    public void actionPerformed(ActionEvent actionEvent) {
        paused = !paused;
        // your logic for Escape
    }
};

// tie KeyStroke and keyboard action to the controlComp
KeyStroke keyEsc = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0, false);
controlComp.registerKeyboardAction(keyEscListener, keyEsc, JComponent.WHEN_FOCUSED);

This method requires creating separate Listener and KeyStroke object for each key you want to listen


问:
Dropzone ProcessQueue event does not hit server after first upload
I have a dropzone upload on my website which handles file uploads. It works perfectly on the first upload. However, when attempting to upload a file (or the same file) a second time by clicking the 'btn_Upload' button again, nothing happens. I believe the issue lies with the 'processQueue()' function as the code reaches this point but the breakpoint serverside is never hit a second time.

The success, error and complete events are also never reached again after the initial upload.

If anyone more knowledgeable with Dropzone could give me a hint as to where I can find a solution to this issue or if someone has encountered a similar problem before, I would appreciate some guidance.

```<code>$(document).ready(function () {
    $("#ContentPlaceHolder1_dZUpload").dropzone({
        url: "handlers/Upload.ashx",
        dictDefaultMessage: "Click or Drag and Drop to Upload a File",
        previewTemplate: document.getElementById("dropzoneTemplate").innerHTML,
        timeout: 10000,
        autoProcessQueue: false,
        init: function () {
            let upload = this;

            // Restrict to 1 file uploaded
            upload.on("addedfile", function () {
                if (upload.files[1] != null) {
                    upload.removeFile(upload.files[0]);
                }
            });
            // If validation passes, process queue and add insurance
            $("#btn_Upload").on("click", function (e) {
                e.preventDefault();
                upload.processQueue();
            });
        },
        success: function (file, response) {
            console.log("Upload Attempt Success - Insurance added");
        },
        error: function (file, xhr, formData) {
            console.log("Upload Attempt Error - " + formData.status + " " + formData.statusText);
        },
        complete: function (file, response) {
            console.log("Upload Attempt Finished");
        }
    });
});
</code>```

答:
I feel like an idiot now. I literally found the solution a few minutes later.

```<code>complete: function (file, response) {
   file.status = "queued";
   console.log("Insurance Upload Attempt Finished");
}
</code>```

It turns out that dropzone marks files when they have been handled to avoid handling them twice. Therefore, I simply changes the status back to 'queued' and this ensured dropzone would upload them when the button was pushed again.

Solution found here:
Using Dropzone to upload twice with asp.net

Body:
I have a dropzone upload on my website which handles file uploads. It works perfectly on the first upload. However, when attempting to upload a file (or the same file) a second time by clicking the 'btn_Upload' button again, nothing happens. I believe the issue lies with the 'processQueue()' function as the code reaches this point but the breakpoint serverside is never hit a second time.

The success, error and complete events are also never reached again after the initial upload.

If anyone more knowledgeable with Dropzone could give me a hint as to where I can find a solution to this issue or if someone has encountered a similar problem before, I would appreciate some guidance.

$(document).ready(function () {
    $("#ContentPlaceHolder1_dZUpload").dropzone({
        url: "handlers/Upload.ashx",
        dictDefaultMessage: "Click or Drag and Drop to Upload a File",
        previewTemplate: document.getElementById("dropzoneTemplate").innerHTML,
        timeout: 10000,
        autoProcessQueue: false,
        init: function () {
            let upload = this;

            // Restrict to 1 file uploaded
            upload.on("addedfile", function () {
                if (upload.files[1] != null) {
                    upload.removeFile(upload.files[0]);
                }
            });
            // If validation passes, process queue and add insurance
            $("#btn_Upload").on("click", function (e) {
                e.preventDefault();
                upload.processQueue();
            });
        },
        success: function (file, response) {
            console.log("Upload Attempt Success - Insurance added");
        },
        error: function (file, xhr, formData) {
            console.log("Upload Attempt Error - " + formData.status + " " + formData.statusText);
        },
        complete: function (file, response) {
            console.log("Upload Attempt Finished");
        }
    });
});

Body:
I feel like an idiot now. I literally found the solution a few minutes later.

complete: function (file, response) {
   file.status = "queued";
   console.log("Insurance Upload Attempt Finished");
}

It turns out that dropzone marks files when they have been handled to avoid handling them twice. Therefore, I simply changes the status back to 'queued' and this ensured dropzone would upload them when the button was pushed again.

Solution found here:
Using Dropzone to upload twice with asp.net


问:
How to use 2 mixins in State in Flutter?
I have a state class

```<code>class ListScreenState extends State<ListScreen>...
</code>```

And I want to use AutomaticKeepAliveClientMixin (to prevent the TabBar that holds these screens from disposing of) and TickerProviderStateMixin because I have the animation controller that requires it. But when I put both mixins in this class there's an error:

```<code>error: Type parameters could not be inferred for the mixin 'TickerProviderStateMixin' because the base class implements the mixin's supertype constraint 'State<T>' in multiple conflicting ways (mixin_inference_inconsistent_matching_classes at [myapp] lib/trips/ListScreen.dart:21)
</code>```

I couldn't really find a good explanation of how to use mixins in one class. Any help is appreciated.

Here's the full code:

```<code>import 'package:flutter/widgets.dart';

class ListScreen extends StatefulWidget {

  @override
  State<StatefulWidget> createState() {
    return ListScreenState();
  }
}

 class ListScreenState extends State<ListScreen>
    with AutomaticKeepAliveClientMixin, TickerProviderStateMixin {

  AnimationController controller;

  @override
  void initState() {
    super.initState();

    controller = AnimationController(
        duration: const Duration(milliseconds: 250), vsync: this);

  }

  @override
  bool get wantKeepAlive => true;
}
</code>```

Dart specifically complains about adding TickerProviderStateMixin. If I remove AutomaticKeepAliveClientMixin, then it doesn't complain anymore.

答: For anyone coming here using SingleTickerProviderStateMixin, simply remove the Single from the name.

Body:
I have a state class

class ListScreenState extends State<ListScreen>...

And I want to use AutomaticKeepAliveClientMixin (to prevent the TabBar that holds these screens from disposing of) and TickerProviderStateMixin because I have the animation controller that requires it. But when I put both mixins in this class there's an error:

error: Type parameters could not be inferred for the mixin 'TickerProviderStateMixin' because the base class implements the mixin's supertype constraint 'State<T>' in multiple conflicting ways (mixin_inference_inconsistent_matching_classes at [myapp] lib/trips/ListScreen.dart:21)

I couldn't really find a good explanation of how to use mixins in one class. Any help is appreciated.

Here's the full code:

import 'package:flutter/widgets.dart';

class ListScreen extends StatefulWidget {

  @override
  State<StatefulWidget> createState() {
    return ListScreenState();
  }
}

 class ListScreenState extends State<ListScreen>
    with AutomaticKeepAliveClientMixin, TickerProviderStateMixin {

  AnimationController controller;

  @override
  void initState() {
    super.initState();

    controller = AnimationController(
        duration: const Duration(milliseconds: 250), vsync: this);

  }

  @override
  bool get wantKeepAlive => true;
}

Dart specifically complains about adding TickerProviderStateMixin. If I remove AutomaticKeepAliveClientMixin, then it doesn't complain anymore.