问:
Animating a filled rectangle with CoreAnimation
I am trying to animate a filled rectangle using CoreAnimation. When adding the animation to the CAShapeLayer, the animation is added, however, the animation looks strange.

I have attached gif:

I have created a small example:

```<code>import Foundation
import UIKit

class TestView : UIView
{
    private var progressLayer = CAShapeLayer()

    override init(frame: CGRect)
    {
        super.init(frame: frame)

        self.commonInit()
    }

    required init?(coder: NSCoder)
    {
        super.init(coder: coder)

        self.commonInit()
    }

    override func layoutSubviews()
    {
        super.layoutSubviews()

        self.commonInit()
    }

    fileprivate func commonInit()
    {
        self.progressLayer.removeFromSuperlayer()

        let barWidth: CGFloat = self.frame.width * 0.33

        let path = UIBezierPath(roundedRect: CGRect(x: self.bounds.width / 2 - barWidth / 2.0, y: self.bounds.height - 1.0, width: barWidth, height: 1.0), byRoundingCorners: [.topLeft, .topRight], cornerRadii: CGSize(width: 6.0, height: 6.0))
        self.progressLayer.path = path.cgPath
        self.progressLayer.fillColor = UIColor.systemBlue.cgColor
        self.progressLayer.strokeColor = UIColor.clear.cgColor

        Swift.print(self.progressLayer.position)
        self.progressLayer.position = CGPoint(x: -barWidth / 2.0, y: 0.0)

        self.layer.addSublayer(self.progressLayer)
    }

    func animate()
    {
        let barWidth: CGFloat = self.frame.width * 0.33

        let from = UIBezierPath(roundedRect: CGRect(x: self.bounds.width / 2 - barWidth / 2.0, y: self.bounds.height - 1.0, width: barWidth, height: 1.0), byRoundingCorners: [.topLeft, .topRight], cornerRadii: CGSize(width: 6.0, height: 6.0))
        let to = UIBezierPath(roundedRect: CGRect(x: self.bounds.width / 2 - barWidth / 2.0, y: 0.0, width: barWidth, height: self.bounds.height), byRoundingCorners: [.topLeft, .topRight], cornerRadii: CGSize(width: 6.0, height: 6.0))

        // This works fine.
//        let from = UIBezierPath(rect: CGRect(x: self.bounds.width / 2 - barWidth / 2.0, y: self.bounds.height - 1.0, width: barWidth, height: 1.0))
//        let to = UIBezierPath(rect: CGRect(x: self.bounds.width / 2 - barWidth / 2.0, y: 0.0, width: barWidth, height: self.bounds.height))

        let animation = CABasicAnimation(keyPath: "path")
        animation.fromValue = from.cgPath
        animation.toValue = to.cgPath
        animation.duration = 0.8
        animation.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
        animation.fillMode = .forwards
        animation.isRemovedOnCompletion = false

        self.progressLayer.add(animation, forKey: "path")
    }
}
</code>```

When removing the rounded corners, everything works fine. How can I fix the animation so it only animates in one dimension (from bottom to top)?

答:
You can use auto layout to do this:
declare your UIViews and your button under controller class:

```<code>let grayView = UIView()
let blueView = UIView()
let button = UIButton(type: .system)
</code>```

in viewDidLoad set attributes and cal the function for constraints:

```<code>button.backgroundColor = .red
    button.setTitle("Up", for: .normal)
    button.setTitleColor(.white, for: .normal)
    button.titleLabel?.font = .systemFont(ofSize: 16, weight: .semibold)
    button.addTarget(self, action: #selector(handleUp), for: .touchUpInside)
    button.translatesAutoresizingMaskIntoConstraints = false

    grayView.backgroundColor = .gray
    grayView.translatesAutoresizingMaskIntoConstraints = false

    blueView.backgroundColor = .blue
    blueView.translatesAutoresizingMaskIntoConstraints = false

    setupConstraints()
</code>```

now below viewDidLoad set variables for animation:

```<code>var normalHeight: NSLayoutConstraint?
var newHeight: NSLayoutConstraint?
</code>```

after that write function to set constraints:

```<code>fileprivate func setupConstraints() {

    view.addSubview(grayView)
    grayView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 50).isActive = true
    grayView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 50).isActive = true
    grayView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -50).isActive = true
    grayView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -50).isActive = true

    grayView.addSubview(blueView)
    blueView.bottomAnchor.constraint(equalTo: grayView.bottomAnchor, constant: 0).isActive = true
    blueView.trailingAnchor.constraint(equalTo: grayView.trailingAnchor, constant: -40).isActive = true
    blueView.leadingAnchor.constraint(equalTo: grayView.leadingAnchor, constant: 40).isActive = true
    normalHeight = blueView.heightAnchor.constraint(equalToConstant: 10)
    normalHeight?.isActive = true

    newHeight = blueView.topAnchor.constraint(equalTo: grayView.topAnchor)

    view.addSubview(button)
    button.topAnchor.constraint(equalTo: grayView.bottomAnchor, constant: 10).isActive = true
    button.leadingAnchor.constraint(equalTo: grayView.leadingAnchor).isActive = true
    button.trailingAnchor.constraint(equalTo: grayView.trailingAnchor).isActive = true
    button.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor).isActive = true
}
</code>```

last step write function to call animation and set corner radius:

```<code>@objc fileprivate func handleUp() {
    UIView.animate(withDuration: 0.5, delay: 0, options: .curveEaseOut, animations: {
        self.normalHeight?.isActive = false
        self.newHeight?.isActive = true
        self.blueView.layer.cornerRadius = 14
        self.blueView.layer.maskedCorners = [.layerMaxXMinYCorner, .layerMinXMinYCorner]
        self.view.layoutIfNeeded()
    }, completion: nil)
}
</code>```

this is the result:

Body:
I am trying to animate a filled rectangle using CoreAnimation. When adding the animation to the CAShapeLayer, the animation is added, however, the animation looks strange.

I have attached gif:

I have created a small example:

import Foundation
import UIKit

class TestView : UIView
{
    private var progressLayer = CAShapeLayer()

    override init(frame: CGRect)
    {
        super.init(frame: frame)

        self.commonInit()
    }

    required init?(coder: NSCoder)
    {
        super.init(coder: coder)

        self.commonInit()
    }

    override func layoutSubviews()
    {
        super.layoutSubviews()

        self.commonInit()
    }

    fileprivate func commonInit()
    {
        self.progressLayer.removeFromSuperlayer()

        let barWidth: CGFloat = self.frame.width * 0.33

        let path = UIBezierPath(roundedRect: CGRect(x: self.bounds.width / 2 - barWidth / 2.0, y: self.bounds.height - 1.0, width: barWidth, height: 1.0), byRoundingCorners: [.topLeft, .topRight], cornerRadii: CGSize(width: 6.0, height: 6.0))
        self.progressLayer.path = path.cgPath
        self.progressLayer.fillColor = UIColor.systemBlue.cgColor
        self.progressLayer.strokeColor = UIColor.clear.cgColor

        Swift.print(self.progressLayer.position)
        self.progressLayer.position = CGPoint(x: -barWidth / 2.0, y: 0.0)

        self.layer.addSublayer(self.progressLayer)
    }

    func animate()
    {
        let barWidth: CGFloat = self.frame.width * 0.33

        let from = UIBezierPath(roundedRect: CGRect(x: self.bounds.width / 2 - barWidth / 2.0, y: self.bounds.height - 1.0, width: barWidth, height: 1.0), byRoundingCorners: [.topLeft, .topRight], cornerRadii: CGSize(width: 6.0, height: 6.0))
        let to = UIBezierPath(roundedRect: CGRect(x: self.bounds.width / 2 - barWidth / 2.0, y: 0.0, width: barWidth, height: self.bounds.height), byRoundingCorners: [.topLeft, .topRight], cornerRadii: CGSize(width: 6.0, height: 6.0))

        // This works fine.
//        let from = UIBezierPath(rect: CGRect(x: self.bounds.width / 2 - barWidth / 2.0, y: self.bounds.height - 1.0, width: barWidth, height: 1.0))
//        let to = UIBezierPath(rect: CGRect(x: self.bounds.width / 2 - barWidth / 2.0, y: 0.0, width: barWidth, height: self.bounds.height))

        let animation = CABasicAnimation(keyPath: "path")
        animation.fromValue = from.cgPath
        animation.toValue = to.cgPath
        animation.duration = 0.8
        animation.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
        animation.fillMode = .forwards
        animation.isRemovedOnCompletion = false

        self.progressLayer.add(animation, forKey: "path")
    }
}

When removing the rounded corners, everything works fine. How can I fix the animation so it only animates in one dimension (from bottom to top)?

Body:
You can use auto layout to do this:
declare your UIViews and your button under controller class:

let grayView = UIView()
let blueView = UIView()
let button = UIButton(type: .system)

in viewDidLoad set attributes and cal the function for constraints:

button.backgroundColor = .red
    button.setTitle("Up", for: .normal)
    button.setTitleColor(.white, for: .normal)
    button.titleLabel?.font = .systemFont(ofSize: 16, weight: .semibold)
    button.addTarget(self, action: #selector(handleUp), for: .touchUpInside)
    button.translatesAutoresizingMaskIntoConstraints = false

    grayView.backgroundColor = .gray
    grayView.translatesAutoresizingMaskIntoConstraints = false

    blueView.backgroundColor = .blue
    blueView.translatesAutoresizingMaskIntoConstraints = false

    setupConstraints()

now below viewDidLoad set variables for animation:

var normalHeight: NSLayoutConstraint?
var newHeight: NSLayoutConstraint?

after that write function to set constraints:

fileprivate func setupConstraints() {

    view.addSubview(grayView)
    grayView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 50).isActive = true
    grayView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 50).isActive = true
    grayView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -50).isActive = true
    grayView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -50).isActive = true

    grayView.addSubview(blueView)
    blueView.bottomAnchor.constraint(equalTo: grayView.bottomAnchor, constant: 0).isActive = true
    blueView.trailingAnchor.constraint(equalTo: grayView.trailingAnchor, constant: -40).isActive = true
    blueView.leadingAnchor.constraint(equalTo: grayView.leadingAnchor, constant: 40).isActive = true
    normalHeight = blueView.heightAnchor.constraint(equalToConstant: 10)
    normalHeight?.isActive = true

    newHeight = blueView.topAnchor.constraint(equalTo: grayView.topAnchor)

    view.addSubview(button)
    button.topAnchor.constraint(equalTo: grayView.bottomAnchor, constant: 10).isActive = true
    button.leadingAnchor.constraint(equalTo: grayView.leadingAnchor).isActive = true
    button.trailingAnchor.constraint(equalTo: grayView.trailingAnchor).isActive = true
    button.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor).isActive = true
}

last step write function to call animation and set corner radius:

@objc fileprivate func handleUp() {
    UIView.animate(withDuration: 0.5, delay: 0, options: .curveEaseOut, animations: {
        self.normalHeight?.isActive = false
        self.newHeight?.isActive = true
        self.blueView.layer.cornerRadius = 14
        self.blueView.layer.maskedCorners = [.layerMaxXMinYCorner, .layerMinXMinYCorner]
        self.view.layoutIfNeeded()
    }, completion: nil)
}

this is the result:


来源: stackexchange

问:
LinkedIn share button on webpage
I have a design below which I am trying to replicate on a webpage:

Right now I am able to get this in the following code (also in this fiddle):

```<code><div style="display:inline-block;vertical-align:top">
    <a href="https://twitter.com/share" class="twitter-share-button" data-url="http://www.awardwinnersonly.com" data-text="Czech out the books, movies, and music that won major awards" data-via="BClayShannon">Tweet</a>
    <script>
        ! function(d, s, id) {
            var js, fjs = d.getElementsByTagName(s)[0],
                p = /^http:/.test(d.location) ? 'http' : 'https';
            if (!d.getElementById(id)) {
                js = d.createElement(s);
                js.id = id;
                js.src = p + '://platform.twitter.com/widgets.js';
                fjs.parentNode.insertBefore(js, fjs);
            }
        }(document, 'script', 'twitter-wjs');
    </script>
</div>
<div style="display:inline-block;vertical-align:top" class="fb-like" data-href="http://www.awardwinnersonly.com" data-send="false" data-width="450" data-show-faces="false" data-font="segoe ui">
</div>
<iframe src="https://www.facebook.com/plugins/share_button.php?href=https%3A%2F%2Fdevelopers.facebook.com%2Fdocs%2Fplugins%2F&layout=button&size=small&mobile_iframe=true&width=59&height=20&appId" width="59" height="20" style="border:none;overflow:hidden" scrolling="no" frameborder="0" allowTransparency="true"></iframe>
<script src="https://apis.google.com/js/platform.js" async defer></script>
<g:plus action="share" href="https://www.example.com"></g:plus>
</code>```

but not the LinkedIn button. I tried placing it in directly from the their code generator but for some reason it doesn't work.

The code generated is the following:

```<code><script src="//platform.linkedin.com/in.js" type="text/javascript"> lang: en_US</script>
<script type="IN/Share"></script>
</code>```

I am wondering, am I using the right code as highlighted above for LinkedId button to show up?

答:
To simplify what the actual answer was from the given fiddle of the user...

```<code><script src="//platform.linkedin.com/in.js" type="text/javascript"> lang: en_US</script>
<script type="IN/Share"></script>
</code>```

However, all this does is produce a button that links to...

```<code>https://www.linkedin.com/sharing/share-offsite/?url={url}
</code>```

Source: Official Microsoft LinkedIn Sharing Documentation.

I find it easier to simply use a href ...> link to solve this problem with an  tag.  That sounds easier than importing an entire JavaScript library.

ContentLicense: CC BY-SA 3.0

Title: LinkedIn share button on webpage

Body:
I have a design below which I am trying to replicate on a webpage:

Right now I am able to get this in the following code (also in this fiddle):

    Tweet

<g:plus action="share" href="https://www.example.com"></g:plus>

but not the LinkedIn button. I tried placing it in directly from the their code generator but for some reason it doesn't work.

The code generated is the following:

I am wondering, am I using the right code as highlighted above for LinkedId button to show up?

Body:
To simplify what the actual answer was from the given fiddle of the user...

<script src="//platform.linkedin.com/in.js" type="text/javascript"> lang: en_US</script>
<script type="IN/Share"></script>

However, all this does is produce a button that links to...

https://www.linkedin.com/sharing/share-offsite/?url={url}

Source: Official Microsoft LinkedIn Sharing Documentation.

I find it easier to simply use a <a href ...> link to solve this problem with an <img ...> tag.  That sounds easier than importing an entire JavaScript library.

ContentLicense: CC BY-SA 4.0


问:
How to clear jQuery validation error messages?
I am using the jQuery validation plugin for client side validation.
Function editUser() is called on click of 'Edit User' button, which displays error messages.

But I want to clear error messages on my form, when I click on 'Clear' button, that calls a separate function clearUser().

```<code>function clearUser() {
    // Need to clear previous errors here
}

function editUser(){
    var validator = $("#editUserForm").validate({
        rules: {
            userName: "required"
        },
        errorElement: "span",
        messages: {
            userName: errorMessages.E2
        }
    });

    if(validator.form()){
        // Form submission code
    }
}
</code>```

答:
Write own code because everyone uses a different class name. I am resetting jQuery validation by this code.</p>

```<code>$('.error').remove();
        $('.is-invalid').removeClass('is-invalid');
</code>```

Body:
I am using the jQuery validation plugin for client side validation.
Function editUser() is called on click of 'Edit User' button, which displays error messages.

But I want to clear error messages on my form, when I click on 'Clear' button, that calls a separate function clearUser().

function clearUser() {
    // Need to clear previous errors here
}

function editUser(){
    var validator = $("#editUserForm").validate({
        rules: {
            userName: "required"
        },
        errorElement: "span",
        messages: {
            userName: errorMessages.E2
        }
    });

    if(validator.form()){
        // Form submission code
    }
}

Body:
Write own code because everyone uses a different class name. I am resetting jQuery validation by this code.

$('.error').remove();
        $('.is-invalid').removeClass('is-invalid');


问:
Problem with list-style-type: none; in FireFox
For example, in that html code I add list-style-type: none; in external test.css. When FireFox loads that page, the dots (list-style-type without none) could be seen for about a second. Only inline css works

```<code><!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <link href="test.css" rel="stylesheet" type="text/css" />
    </head>
    <body>
        <div>TODO write content</div>
        <ul id="categories">
            <li><a>Test1</a></li>
            <li><a>Test2</a></li>
            <li><a>Test3</a></li>
        </ul>
    </body>
</html>
</code>```

ScreenShot

答:
use this css to remove the dots:

```<code>ul
{
    list-style:none;
}
</code>```

Here is the working demo

Body:
For example, in that html code I add list-style-type: none; in external test.css. When FireFox loads that page, the dots (list-style-type without none) could be seen for about a second. Only inline css works

<!DOCTYPE html>

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <link href="test.css" rel="stylesheet" type="text/css" />

TODO write content

Test1

Test2

Test3

ScreenShot

Body:
use this css to remove the dots:

ul
{
    list-style:none;
}

Here is the working demo


问:
How to use mouse in Assembly?
I need to write an assembly code that if you click a particular icon on a screen, a sound is activated.(For example: piano)
How to do it?

I'm using a Assembly 86 and dosbox 0.74-3 If that helps.

This is the code that creates the piano (5 white rectangles)
I need that when the mouse clicks on one of the rectangles, it will make a sound.

I know how to make a sound, I just need the sound to be heard when the icons are clicked.
The remarks are in Hebrew because it is my native language

```<code>IDEAL
MODEL small
STACK 100h
DATASEG
; --------------------------
color db 12
Player_CoordinateIn_X dw 5
Player_CoordinateIn_Y dw 10
Player_CoordinateIn_X1 dw 40
Player_CoordinateIn_X2 dw 75
Player_CoordinateIn_X3 dw 110
Player_CoordinateIn_X4 dw 145
Player_CoordinateIn_X5 dw 180
Player_CoordinateIn_X6 dw 215
Player_CoordinateIn_X7 dw 250

include "iconbox.asm"

; --------------------------
CODESEG
; ---------------------------------------

proc printIcon
 push offset iconbox ;שם האייקון
 push 25d ;Width
 push 150d ;Height
 push 15D ;Color
 push [Player_CoordinateIn_X] ; x location
 push [Player_CoordinateIn_Y] ;y location
 call drawIcon
 ret
endp printIcon

proc drawIcon
;פרוצדורה מקבלת מיקום ותמונה
;פרוצדורה מדפיסה תמונה במיקום המבוקש
iconOffset EQU [BP+14] ;מספר האייקון
iconWidth EQU [BP+12] ;רוחב האייקון
iconHeight EQU [BP+10] ;גובה האייקון
iconColor EQU [BP+8] ;צבע האייקון
iconX EQU [BP+6] ;מיקום ציר X
iconY EQU [BP+4] ;מיקום ציר Y

 add [bp],10
 push bp
 mov bp,sp
 ;PushAll
 mov si,0
 mov di,0
 mov bx,iconOffset
 mov dx,iconY
bigLoop:
 cmp [byte ptr bx],0
 je afterPixel
 MOV AX,iconColor
 MOV AH,0Ch
 MOV CX,iconX
 ADD CX,SI
 INT 10H
afterPixel:
 inc bx
 inc si
 cmp si,iconWidth
 jne bigLoop
 mov si,0
 inc dx
 inc di
 cmp di,iconHeight
 jne bigLoop
 ;PopAll
 pop bp
 ret 12
endp drawIcon

proc open_grafic
    mov ax,13h
    int 10h
    ret
endp open_grafic
;------------------------------------
proc printIcon2
 push offset iconbox ;שם האייקון
 push 25d ;Width
 push 150d ;Height
 push 15D ;Color
 push [Player_CoordinateIn_X1] ; x location
 push [Player_CoordinateIn_Y] ;y location
 call drawIcon
 ret
endp printIcon2
;--------------------------------------
proc printIcon1
 push offset iconbox ;שם האייקון
 push 25d ;Width
 push 150d ;Height
 push 15D ;Color
 push [Player_CoordinateIn_X2] ; x location
 push [Player_CoordinateIn_Y] ;y location
 call drawIcon
 ret
endp printIcon1
;--------------------------------------
proc printIcon3
 push offset iconbox ;שם האייקון
 push 25d ;Width
 push 150d ;Height
 push 15D ;Color
 push [Player_CoordinateIn_X3] ; x location
 push [Player_CoordinateIn_Y] ;y location
 call drawIcon
 ret
endp printIcon3
;--------------------------------------
proc printIcon4
 push offset iconbox ;שם האייקון
 push 25d ;Width
 push 150d ;Height
 push 15D ;Color
 push [Player_CoordinateIn_X4] ; x location
 push [Player_CoordinateIn_Y] ;y location
 call drawIcon
 ret
endp printIcon4
;--------------------------------------
proc printIcon5
 push offset iconbox ;שם האייקון
 push 25d ;Width
 push 150d ;Height
 push 15D ;Color
 push [Player_CoordinateIn_X5] ; x location
 push [Player_CoordinateIn_Y] ;y location
 call drawIcon
 ret
endp printIcon5
;--------------------------------------
proc printIcon6
 push offset iconbox ;שם האייקון
 push 25d ;Width
 push 150d ;Height
 push 15D ;Color
 push [Player_CoordinateIn_X6] ; x location
 push [Player_CoordinateIn_Y] ;y location
 call drawIcon
 ret
endp printIcon6
;--------------------------------------
proc printIcon7
 push offset iconbox ;שם האייקון
 push 25d ;Width
 push 150d ;Height
 push 15D ;Color
 push [Player_CoordinateIn_X7] ; x location
 push [Player_CoordinateIn_Y] ;y location
 call drawIcon
 ret
endp printIcon7
;--------------------------------------
start:
    mov ax, @data
    mov ds, ax
; -------------------------
call open_grafic
call printIcon
call printIcon1
call printIcon2
call printIcon3
call printIcon4
call printIcon5
call printIcon6
call printIcon7
    ; --------------------------
    mov ax,0h
int 33h
; Show mouse
mov ax,1h
int 33h
; Loop until mouse click
MouseLP :
mov ax,3h
int 33h
cmp bx, 01h ; check left mouse click
jne MouseLP
; Print dot near mouse location
shr cx,1 ; adjust cx to range 0-319, to fit screen
sub dx, 1 ; move one pixel, so the pixel will not be hidden by mouse
mov bh,0h
mov al,[color]
mov ah,0Ch
int 10h
; Press any key to continue
mov ah,00h
 int 16h
; Text mode
mov ax,3h
int 10h

exit:

end start
</code>```

答:
Your code already waits for a left button click:

```<code>MouseLP:
    mov     ax, 0003h   ; MOUSE.GetMousePosition
    int     33h         ; -> BX CX DX
    test    bx, 1       ; Is left button down?
    jz      MouseLP     ; No
    shr     cx, 1       ; Adjust cx to range 0-319, to fit screen
</code>```

Once the click arrives you start comparing the coordinates that you got in CX (X) and DX (Y) with the coordinates of the rectangle that interests you:

All of your rectangles have the same width (25) and height (150).

Next snippet will check if the mouse was clicked while above your first rectangle, whose upperleft corner is at (Player_CoordinateIn_X1, Player_CoordinateIn_Y).

```<code>    mov     ax, [Player_CoordinateIn_X1]  ; UpperLeftCornerX
    cmp     cx, ax
    jb      Outside
    add     ax, 25-1                      ; LowerRightCornerX
    cmp     cx, ax
    ja      Outside
    mov     ax, [Player_CoordinateIn_Y]   ; UpperLeftCornerY
    cmp     dx, ax
    jb      Outside
    add     ax, 150-1                     ; LowerRightCornerY
    cmp     dx, ax
    ja      Outside
Inside:
    ... Make the corresponding sound!
Outside:
    ... Go check for another mouse click!
</code>```

```<code>proc drawIcon
 add [bp],10
 push bp
 mov bp,sp
</code>```

Your drawIcon proc starts with this strange instruction add [bp],10. What's it supposed to do?

Title: How to use mouse in Assembly?

Body:
I need to write an assembly code that if you click a particular icon on a screen, a sound is activated.(For example: piano)
How to do it?

I'm using a Assembly 86 and dosbox 0.74-3 If that helps.

This is the code that creates the piano (5 white rectangles)
I need that when the mouse clicks on one of the rectangles, it will make a sound.

I know how to make a sound, I just need the sound to be heard when the icons are clicked.
The remarks are in Hebrew because it is my native language

IDEAL
MODEL small
STACK 100h
DATASEG
; --------------------------
color db 12
Player_CoordinateIn_X dw 5
Player_CoordinateIn_Y dw 10
Player_CoordinateIn_X1 dw 40
Player_CoordinateIn_X2 dw 75
Player_CoordinateIn_X3 dw 110
Player_CoordinateIn_X4 dw 145
Player_CoordinateIn_X5 dw 180
Player_CoordinateIn_X6 dw 215
Player_CoordinateIn_X7 dw 250

include "iconbox.asm"

; --------------------------
CODESEG
; ---------------------------------------

proc printIcon
 push offset iconbox ;שם האייקון
 push 25d ;Width
 push 150d ;Height
 push 15D ;Color
 push [Player_CoordinateIn_X] ; x location
 push [Player_CoordinateIn_Y] ;y location
 call drawIcon
 ret
endp printIcon

proc drawIcon
;פרוצדורה מקבלת מיקום ותמונה
;פרוצדורה מדפיסה תמונה במיקום המבוקש
iconOffset EQU [BP+14] ;מספר האייקון
iconWidth EQU [BP+12] ;רוחב האייקון
iconHeight EQU [BP+10] ;גובה האייקון
iconColor EQU [BP+8] ;צבע האייקון
iconX EQU [BP+6] ;מיקום ציר X
iconY EQU [BP+4] ;מיקום ציר Y

 add [bp],10
 push bp
 mov bp,sp
 ;PushAll
 mov si,0
 mov di,0
 mov bx,iconOffset
 mov dx,iconY
bigLoop:
 cmp [byte ptr bx],0
 je afterPixel
 MOV AX,iconColor
 MOV AH,0Ch
 MOV CX,iconX
 ADD CX,SI
 INT 10H
afterPixel:
 inc bx
 inc si
 cmp si,iconWidth
 jne bigLoop
 mov si,0
 inc dx
 inc di
 cmp di,iconHeight
 jne bigLoop
 ;PopAll
 pop bp
 ret 12
endp drawIcon

proc open_grafic
    mov ax,13h
    int 10h
    ret
endp open_grafic
;------------------------------------
proc printIcon2
 push offset iconbox ;שם האייקון
 push 25d ;Width
 push 150d ;Height
 push 15D ;Color
 push [Player_CoordinateIn_X1] ; x location
 push [Player_CoordinateIn_Y] ;y location
 call drawIcon
 ret
endp printIcon2
;--------------------------------------
proc printIcon1
 push offset iconbox ;שם האייקון
 push 25d ;Width
 push 150d ;Height
 push 15D ;Color
 push [Player_CoordinateIn_X2] ; x location
 push [Player_CoordinateIn_Y] ;y location
 call drawIcon
 ret
endp printIcon1
;--------------------------------------
proc printIcon3
 push offset iconbox ;שם האייקון
 push 25d ;Width
 push 150d ;Height
 push 15D ;Color
 push [Player_CoordinateIn_X3] ; x location
 push [Player_CoordinateIn_Y] ;y location
 call drawIcon
 ret
endp printIcon3
;--------------------------------------
proc printIcon4
 push offset iconbox ;שם האייקון
 push 25d ;Width
 push 150d ;Height
 push 15D ;Color
 push [Player_CoordinateIn_X4] ; x location
 push [Player_CoordinateIn_Y] ;y location
 call drawIcon
 ret
endp printIcon4
;--------------------------------------
proc printIcon5
 push offset iconbox ;שם האייקון
 push 25d ;Width
 push 150d ;Height
 push 15D ;Color
 push [Player_CoordinateIn_X5] ; x location
 push [Player_CoordinateIn_Y] ;y location
 call drawIcon
 ret
endp printIcon5
;--------------------------------------
proc printIcon6
 push offset iconbox ;שם האייקון
 push 25d ;Width
 push 150d ;Height
 push 15D ;Color
 push [Player_CoordinateIn_X6] ; x location
 push [Player_CoordinateIn_Y] ;y location
 call drawIcon
 ret
endp printIcon6
;--------------------------------------
proc printIcon7
 push offset iconbox ;שם האייקון
 push 25d ;Width
 push 150d ;Height
 push 15D ;Color
 push [Player_CoordinateIn_X7] ; x location
 push [Player_CoordinateIn_Y] ;y location
 call drawIcon
 ret
endp printIcon7
;--------------------------------------
start:
    mov ax, @data
    mov ds, ax
; -------------------------
call open_grafic
call printIcon
call printIcon1
call printIcon2
call printIcon3
call printIcon4
call printIcon5
call printIcon6
call printIcon7
    ; --------------------------
    mov ax,0h
int 33h
; Show mouse
mov ax,1h
int 33h
; Loop until mouse click
MouseLP :
mov ax,3h
int 33h
cmp bx, 01h ; check left mouse click
jne MouseLP
; Print dot near mouse location
shr cx,1 ; adjust cx to range 0-319, to fit screen
sub dx, 1 ; move one pixel, so the pixel will not be hidden by mouse
mov bh,0h
mov al,[color]
mov ah,0Ch
int 10h
; Press any key to continue
mov ah,00h
 int 16h
; Text mode
mov ax,3h
int 10h

exit:

end start

Body:
Your code already waits for a left button click:

MouseLP:
    mov     ax, 0003h   ; MOUSE.GetMousePosition
    int     33h         ; -> BX CX DX
    test    bx, 1       ; Is left button down?
    jz      MouseLP     ; No
    shr     cx, 1       ; Adjust cx to range 0-319, to fit screen

Once the click arrives you start comparing the coordinates that you got in CX (X) and DX (Y) with the coordinates of the rectangle that interests you:

All of your rectangles have the same width (25) and height (150).

Next snippet will check if the mouse was clicked while above your first rectangle, whose upperleft corner is at (Player_CoordinateIn_X1, Player_CoordinateIn_Y).

    mov     ax, [Player_CoordinateIn_X1]  ; UpperLeftCornerX
    cmp     cx, ax
    jb      Outside
    add     ax, 25-1                      ; LowerRightCornerX
    cmp     cx, ax
    ja      Outside
    mov     ax, [Player_CoordinateIn_Y]   ; UpperLeftCornerY
    cmp     dx, ax
    jb      Outside
    add     ax, 150-1                     ; LowerRightCornerY
    cmp     dx, ax
    ja      Outside
Inside:
    ... Make the corresponding sound!
Outside:
    ... Go check for another mouse click!

proc drawIcon
 add [bp],10
 push bp
 mov bp,sp

Your drawIcon proc starts with this strange instruction add [bp],10. What's it supposed to do?


问:
How to call one async function inside another async function in flutter
I have two future functions one for verifying OTP with API and another for setting a password using the API.

When the OTP verification is successful the set password API must be called. How can I do that?

My code is:

```<code>    () async {

var status = await registrationService.verifyOtp(registrationData.mobileNumber,otpController.text);
                                if(status == 'approved'){
                                  print('success');
                                      () async {
                                    var passwordStatus = await registrationService.setPassword(registrationData.name, registrationData.number, passController.text);
                                    if(passwordStatus == 'approved'){
                                      print('approved');
                                      Navigator.pushNamed(context, StudMainPage.id);
                                    }
                                    else{
                                      WidgetsBinding.instance.addPostFrameCallback((timeStamp) => _showNewVersionAvailableDialog(context));
                                    }
                                  };
                                 }

    }
</code>```

It shows error or the function is not being called. What should I do now?
Thanks in advance.

答:
Create a second async function for

```<code>Future<PasswordStatus> getPasswordStatus() async {
await registrationService.setPassword(registrationData.name, registrationData.number, passController.text);
}
</code>```

and call that function as;

```<code>if(status == 'approved'){
   var passwordStatus = await getPasswordStatus();
}
</code>```

then just use the passwordStatus value.

Body:
I have two future functions one for verifying OTP with API and another for setting a password using the API.

When the OTP verification is successful the set password API must be called. How can I do that?

My code is:

    () async {

var status = await registrationService.verifyOtp(registrationData.mobileNumber,otpController.text);
                                if(status == 'approved'){
                                  print('success');
                                      () async {
                                    var passwordStatus = await registrationService.setPassword(registrationData.name, registrationData.number, passController.text);
                                    if(passwordStatus == 'approved'){
                                      print('approved');
                                      Navigator.pushNamed(context, StudMainPage.id);
                                    }
                                    else{
                                      WidgetsBinding.instance.addPostFrameCallback((timeStamp) => _showNewVersionAvailableDialog(context));
                                    }
                                  };
                                 }

    }

It shows error or the function is not being called. What should I do now?
Thanks in advance.

Body:
Create a second async function for

Future<PasswordStatus> getPasswordStatus() async {
await registrationService.setPassword(registrationData.name, registrationData.number, passController.text);
}

and call that function as;

if(status == 'approved'){
   var passwordStatus = await getPasswordStatus();
}

then just use the passwordStatus value.


问:
pandas histogram: plot histogram for each column as subplot of a big figure
I am using the following code, trying to plot the histogram of every column of a my pandas data frame df_in as subplot of a big figure.

```<code>%matplotlib notebook
from itertools import combinations
import matplotlib.pyplot as plt

fig, axes = plt.subplots(len(df_in.columns) // 3, 3, figsize=(12, 48))
for x in df_in.columns:
    df_in.hist(column = x, bins = 100)

fig.tight_layout()
</code>```

However, the histogram didn't show in the subplot. Any one knows what I missed? Thanks!

答:
```<code>import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline

fig, axis = plt.subplots(2,3,figsize=(8, 8))
df_in.hist(ax=axis)
</code>```

The above will plot a 2*3 (total 6 histogram for your dataframe). Adjust the rows and columns as per your arrangement requirements(# of columns)

My TA @Benjamin once told me , dataframe means do not have to use for loop.

Body:
I am using the following code, trying to plot the histogram of every column of a my pandas data frame df_in as subplot of a big figure.

%matplotlib notebook
from itertools import combinations
import matplotlib.pyplot as plt

fig, axes = plt.subplots(len(df_in.columns) // 3, 3, figsize=(12, 48))
for x in df_in.columns:
    df_in.hist(column = x, bins = 100)

fig.tight_layout()

However, the histogram didn't show in the subplot. Any one knows what I missed? Thanks!

Body:
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline

fig, axis = plt.subplots(2,3,figsize=(8, 8))
df_in.hist(ax=axis)

The above will plot a 2*3 (total 6 histogram for your dataframe). Adjust the rows and columns as per your arrangement requirements(# of columns)

My TA @Benjamin once told me , dataframe means do not have to use for loop.


问:
progress-bar changes color based on the value
I have a progress_profile field where I enter values from 1 to 100 in mysql,

```<code>$progress = $row['progress_profile'];
</code>```

in the bootstrap-bar code I put this code

```<code><p class="bioheading">Profile Completed Progess</p>
<div class="progress">

<div class="progress-bar" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="width: <?php echo $progress; ?>%;"><?php echo $progress . '% Profile Completed'; ?>
</div>
</div>
</code>```

I would like based on the values entered in progress_profile,
change the color of the bar

example"

from 1 to 49 red color

from 50 to 90 blue color

from 91 to 100 green color

Thank you

答:
```<code><?php
$progress = $row['progress_profile'];
$color = '';
if ($progress > 90) {
    $color = 'green';
}else if($progress >= 50){
    $color = 'blue';
}else{
    $color = 'red';
}
?>
</code>```

Add this snippet before the progress bar!.

In your code for progress bar set the style background-color of div with $color as shown..

Hence your code should be...

```<code><p class="bioheading">Profile Completed Progess</p>
<div class="progress">

<div class="progress-bar" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="width: <?php echo $progress; ?>%;background-color: <?php echo $color; ?>"><?php echo $progress . '% Profile Completed'; ?>
</div>
</div>
</code>```

One Suggestion For You:

Instead of manually setting colors you should implement it this way,
by using bootstrap standard colors!

Changes:

Snippet:

```<code><?php
$progress = $row['progress_profile'];
$color = 'bg-';
if ($progress > 90) {
    $color .= 'success';
}else if($progress >= 50){
    $color .= 'primary';
}else{
    $color .= 'danger';
}

?>
</code>```

progress bar code:

```<code><p class="bioheading">Profile Completed Progess</p>
    <div class="progress ">

    <div class="progress-bar <?php echo $color ?>" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="width: <?php echo $progress; ?>%;"><?php echo $progress . '% Profile Completed'; ?>
    </div>
    </div>
</body>
</code>```

Note: you can add the snippet inline, but add it after the $progress['progress_profile'].

Body:
I have a progress_profile field where I enter values from 1 to 100 in mysql,

$progress = $row['progress_profile'];

in the bootstrap-bar code I put this code

Profile Completed Progess

<div class="progress-bar" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="width: <?php echo $progress; ?>%;"><?php echo $progress . '% Profile Completed'; ?>

I would like based on the values entered in progress_profile,
change the color of the bar

example"

from 1 to 49 red color

from 50 to 90 blue color

from 91 to 100 green color

Thank you

Body:
<?php
$progress = $row['progress_profile'];
$color = '';
if ($progress > 90) {
    $color = 'green';
}else if($progress >= 50){
    $color = 'blue';
}else{
    $color = 'red';
}
?>

Add this snippet before the progress bar!.

In your code for progress bar set the style background-color of div with $color as shown..

Hence your code should be...

<p class="bioheading">Profile Completed Progess</p>
<div class="progress">

<div class="progress-bar" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="width: <?php echo $progress; ?>%;background-color: <?php echo $color; ?>"><?php echo $progress . '% Profile Completed'; ?>
</div>
</div>

One Suggestion For You:

Instead of manually setting colors you should implement it this way,
by using bootstrap standard colors!

Changes:

Snippet:

<?php
$progress = $row['progress_profile'];
$color = 'bg-';
if ($progress > 90) {
    $color .= 'success';
}else if($progress >= 50){
    $color .= 'primary';
}else{
    $color .= 'danger';
}

?>

progress bar code:

<p class="bioheading">Profile Completed Progess</p>
    <div class="progress ">

    <div class="progress-bar <?php echo $color ?>" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="width: <?php echo $progress; ?>%;"><?php echo $progress . '% Profile Completed'; ?>
    </div>
    </div>
</body>

Note: you can add the snippet inline, but add it after the $progress['progress_profile'].


问:
Reducer: getting information about value changes at the store
I don't understand how to get an updated value from the reducer store. For example, I have a React component. In this component after some actions, for example, after a few clicks on a button, I call the action from my reducer actions script like this.props.PostSomethingToServer(). Then the action sends some data to the node express server. The server makes some changes with data and then sends a response to the client store reducer. How can I get the updated data from the reducer store? I need to call another function in this React component with updated values.
By the way, I use  mapStateToProps and export default connect() in the React component. As I know, mapStateToProps and export default connect() help to get data from the store before render(). But I still don't understand how to get updated data from the store after some actions.
A couple of code:
React component:

```<code>ChangeArrayData(){
let something = [];
// filling this array and modifying values
//then I call the action
this.props.postSomethingToServer(something);//something will be changed by server logic and will be returned with updated data by a response.
//then I wanna export the data to .excel, for example
this.ExportToExcel(); // here I have to get updated data from the reducer, but I don't have any information about changes in the reducer.
}
</code>```

Reducer action:

```<code>export const postSomethingToServer= rankedElements => dispatch => {
    axios
      .post("/api/postData", elements)
      .then(response => {
        dispatch({
          type: POST_SOMETHING_SUCCESSFUL,
          status : "success",
          payload:  response.data
        });
//... etc.
</code>```

Reducer:

```<code>const initialState = {
    something: {},
    status: "",
    error : ""
};

export default function(state = initialState, action) {
  switch (action.type) {
    case POST_SOMETHING:
      return {
        ...state,
        status: action.status,
      }
    case POST_SOMETHING_SUCCESSFUL:
      return {
        ...state,
        status: action.status,
        something: action.payload
      }
    case GET_ERRORS:
      return {
        ...state,
        status: action.status,
        error: action.error
      }
    default:
      return state;
  }
}
</code>```

答:
You Should assign reducer state values to some local state like following:

```<code>`const mapStateToProps = state => ({
 contacts: state.data
 });
 export default connect(mapStateToProps, { actions })
 (withStyles(contactStyle)(Contact));`
</code>```

Here 'contacts' is a local state name we are using in the class and 'data' is a state name that we return from reducer after updating a state.

You can access the updated data using componentWillReceiveProps method like,

```<code> `componentWillReceiveProps(nextProps) {
    if(nextProps.contacts !== undefined) {
       //Handle updated states here
     }
  }`
</code>```

Body:
I don't understand how to get an updated value from the reducer store. For example, I have a React component. In this component after some actions, for example, after a few clicks on a button, I call the action from my reducer actions script like this.props.PostSomethingToServer(). Then the action sends some data to the node express server. The server makes some changes with data and then sends a response to the client store reducer. How can I get the updated data from the reducer store? I need to call another function in this React component with updated values.
By the way, I use  mapStateToProps and export default connect() in the React component. As I know, mapStateToProps and export default connect() help to get data from the store before render(). But I still don't understand how to get updated data from the store after some actions.
A couple of code:
React component:

ChangeArrayData(){
let something = [];
// filling this array and modifying values
//then I call the action
this.props.postSomethingToServer(something);//something will be changed by server logic and will be returned with updated data by a response.
//then I wanna export the data to .excel, for example
this.ExportToExcel(); // here I have to get updated data from the reducer, but I don't have any information about changes in the reducer.
}

Reducer action:

export const postSomethingToServer= rankedElements => dispatch => {
    axios
      .post("/api/postData", elements)
      .then(response => {
        dispatch({
          type: POST_SOMETHING_SUCCESSFUL,
          status : "success",
          payload:  response.data
        });
//... etc.

Reducer:

const initialState = {
    something: {},
    status: "",
    error : ""
};

export default function(state = initialState, action) {
  switch (action.type) {
    case POST_SOMETHING:
      return {
        ...state,
        status: action.status,
      }
    case POST_SOMETHING_SUCCESSFUL:
      return {
        ...state,
        status: action.status,
        something: action.payload
      }
    case GET_ERRORS:
      return {
        ...state,
        status: action.status,
        error: action.error
      }
    default:
      return state;
  }
}

Body:
You Should assign reducer state values to some local state like following:

`const mapStateToProps = state => ({
 contacts: state.data
 });
 export default connect(mapStateToProps, { actions })
 (withStyles(contactStyle)(Contact));`

Here 'contacts' is a local state name we are using in the class and 'data' is a state name that we return from reducer after updating a state.

You can access the updated data using componentWillReceiveProps method like,

 `componentWillReceiveProps(nextProps) {
    if(nextProps.contacts !== undefined) {
       //Handle updated states here
     }
  }`


问:
Gtk.CssProvider not working in Gtk3 Python3?
I am trying to set style in a python 3 with Gtk3 from gi.repository in Fedora 32, but it just does nothing.

I used to do this in Gtk2 and python2 with

```<code>settings = gtk.settings_get_for_screen(gdk.screen_get_default())
gtk.rc_parse_string(...)
gtk.rc_reset_styles(settings)
</code>```

This worked fine.

Now, in Python 3 with Gtk3 from gi.repository I tried this, just to make the background red.

```<code>import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk as gtk
from gi.repository import Gdk as gdk
....

class Ave:
    ...
    def __init__(self):
        css_provider = gtk.CssProvider()
        css_provider.load_from_data(b'GtkWindow { background-color: #ff0000; }')
        screen = gdk.Screen.get_default()
        gtk.StyleContext.add_provider_for_screen(screen, css_provider, gtk.STYLE_PROVIDER_PRIORITY_USER)
        ...

Ave()
gtk.main()
</code>```

I also tried with css_provider.load_from_path('./ave_style.css') without success (the program even complains if ave_style.css has errors, so it is loaded. I even tried with gtk.STYLE_PROVIDER_PRIORITY_APPLICATION.

Yet, nothing happens. The program completely ignores the CSS styles.

答:
Unless you're using GTK < 3.20, that snippet of CSS is not valid.

If you want to match a GtkWindow, you must use the window selector, as the documentation describes.

You also want to use Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION for style introduced by your application, either programmatically or by custom resources; the USER priority is for user-provided CSS files.

Body:
I am trying to set style in a python 3 with Gtk3 from gi.repository in Fedora 32, but it just does nothing.

I used to do this in Gtk2 and python2 with

settings = gtk.settings_get_for_screen(gdk.screen_get_default())
gtk.rc_parse_string(...)
gtk.rc_reset_styles(settings)

This worked fine.

Now, in Python 3 with Gtk3 from gi.repository I tried this, just to make the background red.

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk as gtk
from gi.repository import Gdk as gdk
....

class Ave:
    ...
    def __init__(self):
        css_provider = gtk.CssProvider()
        css_provider.load_from_data(b'GtkWindow { background-color: #ff0000; }')
        screen = gdk.Screen.get_default()
        gtk.StyleContext.add_provider_for_screen(screen, css_provider, gtk.STYLE_PROVIDER_PRIORITY_USER)
        ...

Ave()
gtk.main()

I also tried with css_provider.load_from_path('./ave_style.css') without success (the program even complains if ave_style.css has errors, so it is loaded. I even tried with gtk.STYLE_PROVIDER_PRIORITY_APPLICATION.

Yet, nothing happens. The program completely ignores the CSS styles.


问:
Issue in decoding in node js
I have a requirement where I need to encode data in "iso-8859-1" and then convert back it to readable string in node js.

In .Net env:

```<code>string encodedData = "VABpAG0AZQAgAHMAZQByAGUAaQBzAA==";
Encoding encoding = Encoding.GetEncoding("iso-8859-1"); // encoding in "iso-8859-1"
byte[] = decodedbuff = convert.FromBase64String(encodedData);   // getting buffer
result = encoding.GetString(decodedbuff);    //decoding
</code>```

result = timesereis

In a similar way, I need to encode and decode in node js

In Node js(using iconvlite)

```<code>const data = "VABpAG0AZQAgAHMAZQByAGUAaQBzAA=="
const buffer = iconvlite.encode(data,'iso-8859-1');
const result = buffer.toString('utf8');
</code>```

Here in result, I am getting  "VABpAG0AZQAgAHMAZQByAGUAaQBzAA=="   instead of decoded result

答:
By using the following code you get your desired result</p>

```<code>let buffer = new Buffer(data, 'base64');
let result = buff.toString('utf-8');

console.log("result: "+text)
</code>```

Title: Issue in decoding in node js

Body:
I have a requirement where I need to encode data in "iso-8859-1" and then convert back it to readable string in node js.

In .Net env:

string encodedData = "VABpAG0AZQAgAHMAZQByAGUAaQBzAA==";
Encoding encoding = Encoding.GetEncoding("iso-8859-1"); // encoding in "iso-8859-1"
byte[] = decodedbuff = convert.FromBase64String(encodedData);   // getting buffer
result = encoding.GetString(decodedbuff);    //decoding

result = timesereis

In a similar way, I need to encode and decode in node js

In Node js(using iconvlite)

const data = "VABpAG0AZQAgAHMAZQByAGUAaQBzAA=="
const buffer = iconvlite.encode(data,'iso-8859-1');
const result = buffer.toString('utf8');

Here in result, I am getting  "VABpAG0AZQAgAHMAZQByAGUAaQBzAA=="   instead of decoded result

Body:
By using the following code you get your desired result

let buffer = new Buffer(data, 'base64');
let result = buff.toString('utf-8');

console.log("result: "+text)


问:
error C2248: 'CObject::CObject' : cannot access private member declared in class 'CObject'
I will specify the reason for my error.
Please rectify my error:

CODE

```<code>   private:
   CStringArray m_strMnemonicArray;

   public:
   CStringArray getMnemonicSet();
   CStringArray CParserDlg::getMnemonicSet()
   {
      return m_strMnemonicArray;
   }
</code>```

答:
I have automated several tasks into a function shown below:

```<code>    CStringArray CParserDlg::getMnemonicSet();
</code>```

return the CStringArray by reference, not value.

```<code>   CStringArray& CParserDlg::getMnemonicSet();
</code>```

Not only would this get rid of the compiler error, it is also a rule of thumb in C++ to pass objects such as CStringArray by either (const) reference, or if not, by pointer.

The reason is that passing by value incurs a temporary copy of the object. If not aware of it, passing objects by value will yield undesirable results, both in execution time and in wrong results (i.e. expecting the passed in object to have changed within the function).

The underlying reason for the error is that CObject is not copyable, but you are passing a CStringArray (which is derived from CObject) by value. Passing by value means that the compiler will attempt to make a temporary copy of the object. Since CObject has no available copy constructor, the compiler gives you the error.

But to add, I would much prefer this than CStringArray:

```<code>  #include <vector>
  std::vector<CString> CStringVector;
</code>```

Then you wouldn't have gotten the compiler error, since vector is copyable (but you would get the problem of the execution time and possible erroneous results I mentioned earlier).

Body:
I will specify the reason for my error.
Please rectify my error:

CODE

   private:
   CStringArray m_strMnemonicArray;

   public:
   CStringArray getMnemonicSet();
   CStringArray CParserDlg::getMnemonicSet()
   {
      return m_strMnemonicArray;
   }

Body:
I have automated several tasks into a function shown below:

    CStringArray CParserDlg::getMnemonicSet();

return the CStringArray by reference, not value.

   CStringArray& CParserDlg::getMnemonicSet();

Not only would this get rid of the compiler error, it is also a rule of thumb in C++ to pass objects such as CStringArray by either (const) reference, or if not, by pointer.

The reason is that passing by value incurs a temporary copy of the object. If not aware of it, passing objects by value will yield undesirable results, both in execution time and in wrong results (i.e. expecting the passed in object to have changed within the function).

The underlying reason for the error is that CObject is not copyable, but you are passing a CStringArray (which is derived from CObject) by value. Passing by value means that the compiler will attempt to make a temporary copy of the object. Since CObject has no available copy constructor, the compiler gives you the error.

But to add, I would much prefer this than CStringArray:

  #include <vector>
  std::vector<CString> CStringVector;

Then you wouldn't have gotten the compiler error, since vector is copyable (but you would get the problem of the execution time and possible erroneous results I mentioned earlier).


问:
Kafka s3 sink connector - many jsons in one json
I'm having an issue with the s3 sink connector. I set my flush-size to 3 (for tests) and my s3 is receiving properly the json file. But when I open the json, I don't have a list of jsons, I only have one after other. Is there any way to get "properly" the jsons in a list when they are sent to my bucket? I want to try a "good way" to solve that, else I'll fix this in a lambda function (but I wouldn't like to do it...)

What I have:

```<code>{"before":null,"after":{"id":10230,"nome":"John","idade":30,"cidade":"São Paulo","estado":"SP","sexo":"M"}
{"before":null,"after":{"id":10231,"nome":"Alan","idade":30,"cidade":"São Paulo","estado":"SP","sexo":"M"}
{"before":null,"after":{"id":10232,"nome":"Rodrigo","idade":30,"cidade":"São Paulo","estado":"SP","sexo":"M"}
</code>```

What I want

```<code>[{"before":null,"after":{"id":10230,"nome":"John","idade":30,"cidade":"São Paulo","estado":"SP","sexo":"M"},
{"before":null,"after":{"id":10231,"nome":"Alan","idade":30,"cidade":"São Paulo","estado":"SP","sexo":"M"},
{"before":null,"after":{"id":10232,"nome":"Rodrigo","idade":30,"cidade":"São Paulo","estado":"SP","sexo":"M"}]
</code>```

答: Not clear how you expect to read these files other than manually, but most analytical tools that read S3 buckets (Hive, Athena, Spark, Presto, etc), all expect JSONLines

Body:
I'm having an issue with the s3 sink connector. I set my flush-size to 3 (for tests) and my s3 is receiving properly the json file. But when I open the json, I don't have a list of jsons, I only have one after other. Is there any way to get "properly" the jsons in a list when they are sent to my bucket? I want to try a "good way" to solve that, else I'll fix this in a lambda function (but I wouldn't like to do it...)

What I have:

{"before":null,"after":{"id":10230,"nome":"John","idade":30,"cidade":"São Paulo","estado":"SP","sexo":"M"}
{"before":null,"after":{"id":10231,"nome":"Alan","idade":30,"cidade":"São Paulo","estado":"SP","sexo":"M"}
{"before":null,"after":{"id":10232,"nome":"Rodrigo","idade":30,"cidade":"São Paulo","estado":"SP","sexo":"M"}

What I want

[{"before":null,"after":{"id":10230,"nome":"John","idade":30,"cidade":"São Paulo","estado":"SP","sexo":"M"},
{"before":null,"after":{"id":10231,"nome":"Alan","idade":30,"cidade":"São Paulo","estado":"SP","sexo":"M"},
{"before":null,"after":{"id":10232,"nome":"Rodrigo","idade":30,"cidade":"São Paulo","estado":"SP","sexo":"M"}]


问:
Killing abandoned process on Heroku
I killed an IRB prompt in a not-so-graceful manner (started with heroku run irb), and now I've got a zombie process which I can't seem to kill:

```<code>Process       State               Command
------------  ------------------  ------------------------------
run.3         up for 2h           irb -r ./init.rb
web.1         up for 0s           thin -p $PORT -e $RACK_ENV -R $HER..
</code>```

I've tried:

heroku restart

heroku ps:scale run=0

heroku ps:restart run.3

Anyone know how I can force quit it?

答:
If anyone else is struggling with killing using something like:

```<code>heroku run ps:stop run.789
</code>```

Killing by id worked for me:

```<code>heroku ps:kill 61ff0687-eaf4-4299-9c65-f0b22af7ec67
</code>```

I got the id using the platform api list dynos - https://devcenter.heroku.com/articles/platform-api-reference#dyno-list

Worked for a detached one-off that was abandoned.

Title: Killing abandoned process on Heroku

Body:
I killed an IRB prompt in a not-so-graceful manner (started with heroku run irb), and now I've got a zombie process which I can't seem to kill:

Process       State               Command
------------  ------------------  ------------------------------
run.3         up for 2h           irb -r ./init.rb
web.1         up for 0s           thin -p $PORT -e $RACK_ENV -R $HER..

I've tried:

heroku restart

heroku ps:scale run=0

heroku ps:restart run.3

Anyone know how I can force quit it?

Body:
If anyone else is struggling with killing using something like:

heroku run ps:stop run.789

Killing by id worked for me:

heroku ps:kill 61ff0687-eaf4-4299-9c65-f0b22af7ec67

I got the id using the platform api list dynos - https://devcenter.heroku.com/articles/platform-api-reference#dyno-list

Worked for a detached one-off that was abandoned.


问:
I want to chain the"standard" output stream (System.out) to PrintWriter stream. But I can not. Why?
I wanted replaced:

```<code>System.out.println("It works properly");
</code>```

by:

```<code>PrintWriter myPrintWriter = new PrintWriter(System.out);
myPrintWriter.print("This text is not displayed on my screen");
</code>```

Unfortunately this second options does not work and I do not why. I am learning Java from scratch and I am trying to understand some basics problems, concepts so... please, help. And sorry for my English ;)

答:
The stream is not flushed automatically. Use myPrintWriter.flush() to get the result on the console.

Demo:

```<code>import java.io.PrintWriter;

class Main {
    public static void main(String[] args) {
        PrintWriter myPrintWriter = new PrintWriter(System.out);
        myPrintWriter.print("This text is not displayed on my screen");
        myPrintWriter.flush();
    }
}
</code>```

Output:

```<code>This text is not displayed on my screen
</code>```

Body:
I wanted replaced:

System.out.println("It works properly");

by:

PrintWriter myPrintWriter = new PrintWriter(System.out);
myPrintWriter.print("This text is not displayed on my screen");

Unfortunately this second options does not work and I do not why. I am learning Java from scratch and I am trying to understand some basics problems, concepts so... please, help. And sorry for my English ;)

Body:
The stream is not flushed automatically. Use myPrintWriter.flush() to get the result on the console.

Demo:

import java.io.PrintWriter;

class Main {
    public static void main(String[] args) {
        PrintWriter myPrintWriter = new PrintWriter(System.out);
        myPrintWriter.print("This text is not displayed on my screen");
        myPrintWriter.flush();
    }
}

Output:

This text is not displayed on my screen


问:
Convert date issue in c#
I have dateformat issue where I need to convert the date from DB to different formats according to the login

Like I have 3 different format

DD/MM/YY,MM/DD/YY,DD/MMM/YY
I tried to convert using the following methods but no luck.

```<code>DateTime.TryParseExact(drtemp["StartDate"].ToString(),dateFormat,null,
   System.Globalization.DateTimeStyles.None,out startDate);
orderDate =DateTime.ParseExact(drtemp["StartDate"].ToString(), dateFormat, null);
</code>```

Any help is highly apprenticed
Thanks,
Magz

答:
Or You could do this: </p>

```<code>String.Format(dateFormat, (DateTime)drtemp["StartDate"])
</code>```

Title: Convert date issue in c#

Body:
I have dateformat issue where I need to convert the date from DB to different formats according to the login

Like I have 3 different format

DD/MM/YY,MM/DD/YY,DD/MMM/YY
I tried to convert using the following methods but no luck.

DateTime.TryParseExact(drtemp["StartDate"].ToString(),dateFormat,null,
   System.Globalization.DateTimeStyles.None,out startDate);
orderDate =DateTime.ParseExact(drtemp["StartDate"].ToString(), dateFormat, null);

Any help is highly apprenticed
Thanks,
Magz

Body:
Or You could do this:

String.Format(dateFormat, (DateTime)drtemp["StartDate"])


问:
Loading from json into HTML/JavaScript
so I am doing a small project in which I need to put some data about products into a json file, and then load that data into the JavaScript section of the html code. The problem is that I keep getting errors like Microsoft Visual Code is telling me that the object I am trying to load is underfined.
Here is my JSON file:

```<code>{
"Data" :
[
{"Name": "Widget", "Price": 25.00, "Quantity": 5 },
{"Name": "Thing", "Price": 15.00, "Quantity": 5 },
{"Name": "Doodad", "Price": 5.00, "Quantity": 10 }
]
</code>```

}

And here is my code from the HTML page.

```<code><form id="form1">
What product do you wish to search for? <input name="name" type="text" size="20">
</form>
<button onclick="outputprodus()">Submit
</button>
<script type="text/javascript" src="Vlad.json"></script>

<script>
    var userdata = JSON.parse(Data);
    var produs1_nume = userdata[0].Name;
    var produs1_pret = userdata[0].Price;
    var produs1_cantitate = userdata[0].Quantity;

    function outputprodus(){
    var x, y;
    x=document.getElementById("form1");
    y=x.elements["name"].value;
    document.write(y+" este produsul cautat.");
    document.write("<br>");
    document.write(produs1_nume+" costa "+produs1_pret+" pentru "+produs1_cantitate+" bucati");
    }
</script>
</code>```

Am I loading the data wrong, or making some mistake afterwards?

答:
You were loading json as script.
Here is how to load a file from network.

Codepen: https://codepen.io/kishin-karra/pen/ExVqzRw?editors=1010

```<code>var userdata = null;
var produs1_nume = null;
var produs1_pret = null;
var produs1_cantitate = null;

fetch('https://s3.ap-south-1.amazonaws.com/com.instadl.test-assets-123/Vlad.json').then(res => {
    res.json().then((data) => {
        userdata = data.Data;
        produs1_nume = userdata[0].Name;
        produs1_pret = userdata[0].Price;
        produs1_cantitate = userdata[0].Quantity;
    })
})

function outputprodus() {
    var x, y;
    x = document.getElementById("form1");
    y = x.elements["name"].value;
    document.write(y + " este produsul cautat.");
    document.write("<br>");
    document.write(produs1_nume + " costa " + produs1_pret + " pentru " + produs1_cantitate + " bucati");
}
</code>```

Title: Loading from json into HTML/JavaScript

Body:
so I am doing a small project in which I need to put some data about products into a json file, and then load that data into the JavaScript section of the html code. The problem is that I keep getting errors like Microsoft Visual Code is telling me that the object I am trying to load is underfined.
Here is my JSON file:

{
"Data" :
[
{"Name": "Widget", "Price": 25.00, "Quantity": 5 },
{"Name": "Thing", "Price": 15.00, "Quantity": 5 },
{"Name": "Doodad", "Price": 5.00, "Quantity": 10 }
]

}

And here is my code from the HTML page.

<form id="form1">
What product do you wish to search for? <input name="name" type="text" size="20">
</form>
<button onclick="outputprodus()">Submit
</button>

Am I loading the data wrong, or making some mistake afterwards?

Body:
You were loading json as script.
Here is how to load a file from network.

Codepen: https://codepen.io/kishin-karra/pen/ExVqzRw?editors=1010

var userdata = null;
var produs1_nume = null;
var produs1_pret = null;
var produs1_cantitate = null;

fetch('https://s3.ap-south-1.amazonaws.com/com.instadl.test-assets-123/Vlad.json').then(res => {
    res.json().then((data) => {
        userdata = data.Data;
        produs1_nume = userdata[0].Name;
        produs1_pret = userdata[0].Price;
        produs1_cantitate = userdata[0].Quantity;
    })
})

function outputprodus() {
    var x, y;
    x = document.getElementById("form1");
    y = x.elements["name"].value;
    document.write(y + " este produsul cautat.");
    document.write("<br>");
    document.write(produs1_nume + " costa " + produs1_pret + " pentru " + produs1_cantitate + " bucati");
}


问:
What will be the SQL oracle query for finding out the maximum experience from hire date?
Have to find the most experienced employee.

```<code>select empno, ename,
from emp
where max(months_between(SYSDATE,hiredate))
</code>```

My software is giving errors on sysdate, so could anyone please verify if this is correct.

答:
Use NOT EXISTS:

```<code>select e.empno, e.ename
from emp e
where not exists (select 1 from emp where hiredate < e.hiredate)
</code>```

or:

```<code>select empno, ename
from emp
where hiredate = (select min(hiredate) from emp)
</code>```

or modify the WHERE clause of your query like this:

```<code>select empno, ename
from emp
where months_between(SYSDATE, hiredate) = (
  select max(months_between(SYSDATE, hiredate))
  from emp
)
</code>```

Body:
Have to find the most experienced employee.

select empno, ename,
from emp
where max(months_between(SYSDATE,hiredate))

My software is giving errors on sysdate, so could anyone please verify if this is correct.

Body:
Use NOT EXISTS:

select e.empno, e.ename
from emp e
where not exists (select 1 from emp where hiredate < e.hiredate)

or:

select empno, ename
from emp
where hiredate = (select min(hiredate) from emp)

or modify the WHERE clause of your query like this:

select empno, ename
from emp
where months_between(SYSDATE, hiredate) = (
  select max(months_between(SYSDATE, hiredate))
  from emp
)


问:
How can I call arguments and return the outputs from a Google cloud hosted function?
I want to write a python function that allows me to scrape a website given a url, that will interface with a flutter mobile application. I have written the very basic code on python, but now I have no clue whatsoever on how to integrate it Google Cloud. Would really appreciate some walkthrough help.

My code model is as follows:

```<code>import timeago
import pytz
from bs4 import BeautifulSoup
from time import mktime
from datetime import datetime

def Parser(url):
     ......# URL PARSING
     ......
     ......
     return domain_name, page_title, clean_txt, timestamp
url = '******************'
file = Parser(url)
print (file[0], file [1], file [2], file [3])
</code>```

I have tried looking at many examples online, and most of them use flask. I do not understand what flask is used for to be honest, and how to use it for Google Cloud Functions (or any cloud functions for that matter). As far as I understand, I should put my requirements.txt file as follows:

```<code>timeago
pytz
mktime
bs4
datetime
</code>```

If so, then how should I define my imports (i.e. the from bs4 import BeautifulSoup, etc) statements?

Also, how can I call these functions to my flutter app code? I have the url for the cloud function, but don't know what to do with it. I tried going through the official documentation, but most of it is just "Hello World" code that is barely of any use to understand (for me), due to the lack of any input or output arguments.

Thanks and cheers

答:
To address some of your queries:

I do not understand what flask is used for to be honest, and how to use it for Google Cloud Functions (or any cloud functions for that matter)

There are a few methods to trigger a Cloud Function, one of the more common ones is using HTTP Triggers.

For HTTP Triggers, Flask is needed to wrap around your actual function/business logic with a RESTful endpoint, so that your function can be invoked via an HTTP request (The latter action should be performed by your flutter code). Some of this is actually handled by Cloud Functions, and you mainly need to specify a wrapper method taking in a flask.Request object (essentially the payload of the above-mentioned HTTP request) as an argument to invoke your main business logic/function, wherein the flask.Request object will be the point where your arguments (e.g. url) are provided.  You will then need to provide this wrapper method when deploying the cloud function (see below).

If so, then how should I define my imports (i.e. the from bs4 import BeautifulSoup, etc) statements?

The import statements work as usual as per your code snippet.

how can I call these functions to my flutter app code?

You will need to fire an HTTP request from your flutter app code to the URL of the cloud function.

To put things into context:

In your example above, you can wrap it around an entry point method with a flask.Request object like this:

```<code>import timeago
import pytz
from bs4 import BeautifulSoup
from time import mktime
from datetime import datetime
from flask import escape

def Parser(url):
     ......# URL PARSING
     ......
     ......
     return domain_name, page_title, clean_txt, timestamp

def invoke_parser(request):
    request_json = request.get_json(silent=True)
    file = Parser(escape(request_json['url']))
    print (file[0], file [1], file [2], file [3])
</code>```

How your function has changed is that url has to be passed in the HTTP request body instead when invoking the function.

So, to deploy the function, use the command:

```<code>gcloud functions deploy [CLOUD FUNCTION NAME] \
--entry-point invoke_parser \
--runtime python37 \
--trigger-http
</code>```

The --entry-point argument will be the wrapper method to be invoked (I have used invoke_parser as the wrapper method in my example).

To invoke it, fire an HTTP request (this is where the url argument to your Parser function can be provided) e.g.:

```<code>curl -X POST \
"https://YOUR_REGION-YOUR_PROJECT_ID.cloudfunctions.net/FUNCTION_NAME" \
-H "Content-Type:application/json" \
--data '{"url":"******************"}'
</code>```

In your flutter code, you will need to fire an HTTP request equivalent to the above curl command

Body:
I want to write a python function that allows me to scrape a website given a url, that will interface with a flutter mobile application. I have written the very basic code on python, but now I have no clue whatsoever on how to integrate it Google Cloud. Would really appreciate some walkthrough help.

My code model is as follows:

import timeago
import pytz
from bs4 import BeautifulSoup
from time import mktime
from datetime import datetime

def Parser(url):
     ......# URL PARSING
     ......
     ......
     return domain_name, page_title, clean_txt, timestamp
url = '******************'
file = Parser(url)
print (file[0], file [1], file [2], file [3])

I have tried looking at many examples online, and most of them use flask. I do not understand what flask is used for to be honest, and how to use it for Google Cloud Functions (or any cloud functions for that matter). As far as I understand, I should put my requirements.txt file as follows:

timeago
pytz
mktime
bs4
datetime

If so, then how should I define my imports (i.e. the from bs4 import BeautifulSoup, etc) statements?

Also, how can I call these functions to my flutter app code? I have the url for the cloud function, but don't know what to do with it. I tried going through the official documentation, but most of it is just "Hello World" code that is barely of any use to understand (for me), due to the lack of any input or output arguments.

Thanks and cheers

Body:
To address some of your queries:

I do not understand what flask is used for to be honest, and how to use it for Google Cloud Functions (or any cloud functions for that matter)

There are a few methods to trigger a Cloud Function, one of the more common ones is using HTTP Triggers.

For HTTP Triggers, Flask is needed to wrap around your actual function/business logic with a RESTful endpoint, so that your function can be invoked via an HTTP request (The latter action should be performed by your flutter code). Some of this is actually handled by Cloud Functions, and you mainly need to specify a wrapper method taking in a flask.Request object (essentially the payload of the above-mentioned HTTP request) as an argument to invoke your main business logic/function, wherein the flask.Request object will be the point where your arguments (e.g. url) are provided.  You will then need to provide this wrapper method when deploying the cloud function (see below).

If so, then how should I define my imports (i.e. the from bs4 import BeautifulSoup, etc) statements?

The import statements work as usual as per your code snippet.

how can I call these functions to my flutter app code?

You will need to fire an HTTP request from your flutter app code to the URL of the cloud function.

To put things into context:

In your example above, you can wrap it around an entry point method with a flask.Request object like this:

import timeago
import pytz
from bs4 import BeautifulSoup
from time import mktime
from datetime import datetime
from flask import escape

def Parser(url):
     ......# URL PARSING
     ......
     ......
     return domain_name, page_title, clean_txt, timestamp

def invoke_parser(request):
    request_json = request.get_json(silent=True)
    file = Parser(escape(request_json['url']))
    print (file[0], file [1], file [2], file [3])

How your function has changed is that url has to be passed in the HTTP request body instead when invoking the function.

So, to deploy the function, use the command:

gcloud functions deploy [CLOUD FUNCTION NAME] \
--entry-point invoke_parser \
--runtime python37 \
--trigger-http

The --entry-point argument will be the wrapper method to be invoked (I have used invoke_parser as the wrapper method in my example).

To invoke it, fire an HTTP request (this is where the url argument to your Parser function can be provided) e.g.:

curl -X POST \
"https://YOUR_REGION-YOUR_PROJECT_ID.cloudfunctions.net/FUNCTION_NAME" \
-H "Content-Type:application/json" \
--data '{"url":"******************"}'

In your flutter code, you will need to fire an HTTP request equivalent to the above curl command


问:
Git diff against a stash
How can I see the changes un-stashing will make to the current working tree? I would like to know what changes will be made before applying them!</p>

答:
Depending on what you want to compare the stash with (local working tree / parent commit / head commit), there are actually several commands available, amongst which the good old git diff, and the more specific git stash show:

Compare stash with ↓
git diff
git stash show

Local working tree
git diff stash@{0}
git stash show -l

Parent commit
git diff stash@{0}^ stash@{0}
git stash show -p

HEAD commit
git diff stash@{0} HEAD
/

While git stash show looks more user friendly on first sight, git diff is actually more powerful in that it allows specifying filenames for a more focused diff. I've personally set up aliases for all of these commands in my zsh git plugin.

Title: Git diff against a stash


问:
How to apply styles and css and bootstrap cdn in window.print() when using vuejs?
I want get Print  From my component in Vuejs.

Also I want apply my css and bootsrap in window.print()

I use window.print() in mounted Like this :

```<code>       export default {
             mounted() {
                  window.print();

               }
          }
</code>```

But CSS and Bootstrap have not been applied to the print screen.

Can you tell me how to fix it?

UPDATE:
I use adminlte Template.It may be a problem

答:
Hi you can have two ways to achieve this

```<code>PrintScreen(el)
{
    let printWindow = window.open('', 'PRINT', 'height=600,width=800');

    printWindow.document.write('<html><head><title>' + document.title  + '</title>');
    printWindow.document.write('</head><body >');
    printWindow.document.write('<h1>' + document.title  + '</h1>');
    printWindow.document.write(document.getElementById(el).innerHTML);
    printWindow.document.write('</body></html>');

    printWindow.document.close(); // IE >= 10
    printWindow.focus(); //  IE >= 10*/

    printWindow.print();
    printWindow.close();

    return true;
}
</code>```

Or

You can use a wrapper to do this stuff
Npm Link

```<code>npm install vue-html-to-paper
</code>```

Body:
I want get Print  From my component in Vuejs.

Also I want apply my css and bootsrap in window.print()

I use window.print() in mounted Like this :

       export default {
             mounted() {
                  window.print();

               }
          }

But CSS and Bootstrap have not been applied to the print screen.

Can you tell me how to fix it?

UPDATE:
I use adminlte Template.It may be a problem

Body:
Hi you can have two ways to achieve this

PrintScreen(el)
{
    let printWindow = window.open('', 'PRINT', 'height=600,width=800');

    printWindow.document.write('<html><head><title>' + document.title  + '</title>');
    printWindow.document.write('</head><body >');
    printWindow.document.write('<h1>' + document.title  + '</h1>');
    printWindow.document.write(document.getElementById(el).innerHTML);
    printWindow.document.write('</body></html>');

    printWindow.document.close(); // IE >= 10
    printWindow.focus(); //  IE >= 10*/

    printWindow.print();
    printWindow.close();

    return true;
}

Or

You can use a wrapper to do this stuff
Npm Link

npm install vue-html-to-paper


问:
unable to post minute, hour works
i'm stuck here and would appreciate some guidance, not just the answer, but how I could trouble shoot by placing "traps" to see where it's going wrong.
The main problem is I can't get "minute" to be posted, the mysql update puts nothing for minute.  "Hour" works.

 I had a var_dump($_POST) in there to see what's being posted , for minute nothing is being posted and I don't know why since I'm doing similar method for minute as for hour, and hour works.
Please help.

```<code><?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require_once "db.php";

if(isset($_POST["submit"]) && $_POST["submit"]!="") {
// var_dump($_POST);
$usersCount = count($_POST["hour"]);
for($i=0;$i<$usersCount;$i++) {
mysqli_query($conn, "UPDATE events set hour='" . $_POST["hour"][$i] . "', minute='" . $_POST["minute"][$i] . "'   WHERE event='" . $_POST["event"][$i] . "'");
}
// header("Location:golist.php");
}
?>
<html>
<head>
<title>Edit events</title>
<link rel="stylesheet" type="text/css" href="styles.css" />
</head>
<body>
<form name="frmUser" method="post" action="">
<div style="width:500px;">
<table border="0" cellpadding="10" cellspacing="0" width="500" align="center">
<tr class="tableheader">
<td>Edit Event</td>
</tr>
<?php
$rowCount = count($_POST["myevents"]);
// var_dump($_POST);
for($i=0;$i<$rowCount;$i++) {
$result = mysqli_query($conn, "SELECT * FROM events  WHERE event='" . $_POST["myevents"][$i] . "'");
$row[$i]= mysqli_fetch_array($result);
// $CompanyID=$row["id"];
?>
<tr>
 <td>
  <table border="0" cellpadding="10" cellspacing="0" width="500" align="center" class="tblSaveForm">
   <tr>
    <td><label>Hour</label></td>
    <td><input type="hidden"  class="txtField" name="event[]"  value="<?php echo $row[$i]['event']; ?>">
    <form><select name="hour[]">
    <option><?php echo $row[$i]['hour']; ?></option>
    <option value="00">00</option>
    <option value="01">01</option>
    <option value="02">02</option>
    </select>
    </form>
    </td>
   </tr>

   <tr>
    <td><label for="minute">Minute</label></td>
    <td><input type="hidden"  class="txtField" name="event[]"  value="<?php echo  $row[$i]['event']; ?>">
    <form><select name="minute[]">
    <option><?php echo $row[$i]['minute']; ?></option>
    <option value="15">15</option>
    <option value="30">30</option>
    <option value="45">45</option>
    </select>
    </form>
    </td>
   </tr>

</table>
</td>
</tr>
<?php
}
?>
<tr>
<td colspan="2"><input type="submit" name="submit" value="Submit" class="btnSubmit"></td>
</tr>
</table>
</div>
</form>
</body></html>
</code>```

答:
You have hours and minutes and your button in separate forms. Move your form statement before the table starts and remove the 2nd one and the closing form tags.

To address the vulnerability Dharman mentions you'll also want to use prepared statements.

```<code>ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require_once "db.php";

if(isset($_POST["submit"]) && $_POST["submit"]!="") {
    // var_dump($_POST);
    $usersCount = count($_POST["hour"]);
    $stmt = $mysqli->prepare('UPDATE events SET hour = ? , minute= ?');
    for($i=0;$i<$usersCount;$i++) {
        $stmt->bind_param("ss",$_POST["hour"][$i],$_POST["minute"][$i]);
        $stmt->execute();
    }
    // header("Location:golist.php");
}
?>

<form name="frmUser" method="post" action="">
<div style="width:500px;">
<table border="0" cellpadding="10" cellspacing="0" width="500" align="center">
<tr class="tableheader">
<td>Edit Event</td>
</tr>
<?php
$rowCount = count($_POST["myevents"]);
// var_dump($_POST);
$stmt = $mysqli->prepare('SELECT * FROM events  WHERE event= ?');
for($i=0;$i<$rowCount;$i++) {
    $stmt->bind_param("s",$_POST["myevents"][$i]);
    $stmt->execute();
    $row[$i] = $stmt->get_result()->fetch_array();
// $CompanyID=$row["id"];
?>
<tr>
 <td>
  <table border="0" cellpadding="10" cellspacing="0" width="500" align="center" class="tblSaveForm">
   <tr>
    <td><label>Hour</label></td>
    <td><input type="hidden"  class="txtField" name="event[]"  value="<?php echo $row[$i]['event']; ?>">
    <select name="hour[]">
    <option><?php echo $row[$i]['hour']; ?></option>
    <option value="00">00</option>
    <option value="01">01</option>
    <option value="02">02</option>
    </select>
    </td>
   </tr>

   <tr>
    <td><label for="minute">Minute</label></td>
    <td><input type="hidden"  class="txtField" name="event[]"  value="<?php echo  $row[$i]['event']; ?>">
    <select name="minute[]">
    <option><?php echo $row[$i]['minute']; ?></option>
    <option value="15">15</option>
    <option value="30">30</option>
    <option value="45">45</option>
    </select>
    </td>
   </tr>

</table>
</td>
</tr>
<?php
}
?>
<tr>
<td colspan="2"><input type="submit" name="submit" value="Submit" class="btnSubmit"></td>
</tr>
</table>
</div>
</form>
</body></html>
</code>```

Title: unable to post minute, hour works

Body:
i'm stuck here and would appreciate some guidance, not just the answer, but how I could trouble shoot by placing "traps" to see where it's going wrong.
The main problem is I can't get "minute" to be posted, the mysql update puts nothing for minute.  "Hour" works.

 I had a var_dump($_POST) in there to see what's being posted , for minute nothing is being posted and I don't know why since I'm doing similar method for minute as for hour, and hour works.
Please help.

<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require_once "db.php";

if(isset($_POST["submit"]) && $_POST["submit"]!="") {
// var_dump($_POST);
$usersCount = count($_POST["hour"]);
for($i=0;$i<$usersCount;$i++) {
mysqli_query($conn, "UPDATE events set hour='" . $_POST["hour"][$i] . "', minute='" . $_POST["minute"][$i] . "'   WHERE event='" . $_POST["event"][$i] . "'");
}
// header("Location:golist.php");
}
?>

<title>Edit events</title>
<link rel="stylesheet" type="text/css" href="styles.css" />

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

Edit Event

<?php
$rowCount = count($_POST["myevents"]);
// var_dump($_POST);
for($i=0;$i<$rowCount;$i++) {
$result = mysqli_query($conn, "SELECT * FROM events  WHERE event='" . $_POST["myevents"][$i] . "'");
$row[$i]= mysqli_fetch_array($result);
// $CompanyID=$row["id"];
?>

    Hour
    <input type="hidden"  class="txtField" name="event[]"  value="<?php echo $row[$i]['event']; ?>">
    <form><select name="hour[]">
    <option><?php echo $row[$i]['hour']; ?></option>
    <option value="00">00</option>
    <option value="01">01</option>
    <option value="02">02</option>
    </select>
    </form>

    Minute
    <input type="hidden"  class="txtField" name="event[]"  value="<?php echo  $row[$i]['event']; ?>">
    <form><select name="minute[]">
    <option><?php echo $row[$i]['minute']; ?></option>
    <option value="15">15</option>
    <option value="30">30</option>
    <option value="45">45</option>
    </select>
    </form>

<?php
}
?>

<input type="submit" name="submit" value="Submit" class="btnSubmit">

</form>

Body:
You have hours and minutes and your button in separate forms. Move your form statement before the table starts and remove the 2nd one and the closing form tags.

To address the vulnerability Dharman mentions you'll also want to use prepared statements.

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require_once "db.php";

if(isset($_POST["submit"]) && $_POST["submit"]!="") {
    // var_dump($_POST);
    $usersCount = count($_POST["hour"]);
    $stmt = $mysqli->prepare('UPDATE events SET hour = ? , minute= ?');
    for($i=0;$i<$usersCount;$i++) {
        $stmt->bind_param("ss",$_POST["hour"][$i],$_POST["minute"][$i]);
        $stmt->execute();
    }
    // header("Location:golist.php");
}
?>

<form name="frmUser" method="post" action="">
<div style="width:500px;">
<table border="0" cellpadding="10" cellspacing="0" width="500" align="center">
<tr class="tableheader">
<td>Edit Event</td>
</tr>
<?php
$rowCount = count($_POST["myevents"]);
// var_dump($_POST);
$stmt = $mysqli->prepare('SELECT * FROM events  WHERE event= ?');
for($i=0;$i<$rowCount;$i++) {
    $stmt->bind_param("s",$_POST["myevents"][$i]);
    $stmt->execute();
    $row[$i] = $stmt->get_result()->fetch_array();
// $CompanyID=$row["id"];
?>
<tr>
 <td>
  <table border="0" cellpadding="10" cellspacing="0" width="500" align="center" class="tblSaveForm">
   <tr>
    <td><label>Hour</label></td>
    <td><input type="hidden"  class="txtField" name="event[]"  value="<?php echo $row[$i]['event']; ?>">
    <select name="hour[]">
    <option><?php echo $row[$i]['hour']; ?></option>
    <option value="00">00</option>
    <option value="01">01</option>
    <option value="02">02</option>
    </select>
    </td>
   </tr>

   <tr>
    <td><label for="minute">Minute</label></td>
    <td><input type="hidden"  class="txtField" name="event[]"  value="<?php echo  $row[$i]['event']; ?>">
    <select name="minute[]">
    <option><?php echo $row[$i]['minute']; ?></option>
    <option value="15">15</option>
    <option value="30">30</option>
    <option value="45">45</option>
    </select>
    </td>
   </tr>

</table>
</td>
</tr>
<?php
}
?>
<tr>
<td colspan="2"><input type="submit" name="submit" value="Submit" class="btnSubmit"></td>
</tr>
</table>
</div>
</form>
</body></html>


问:
How to end an incoming call programmatically on Android 8.0 Oreo
Up to Android 7.1 it was possible to end an incoming call by using the ITelephony.endCall() method and giving your app the permissions android.permission.CALL_PHONE and android.permission.READ_PHONE_STATE.

When doing the same on Android 8.0 Oreo (API 26), i get this error

12-09 18:11:25.195 16833-16833/li.doerf.leavemealone
  E/TelephonyServiceCallHangup: Missing permission MODIFY_PHONE_STATE,
  cannot hangup call

Since MODIFY_PHONE_STATE is a protected permission, my app cannot get it. Is there a way to programmatically end an incoming call on Android 8.0+?

答:
Add these permissions:

```<code><uses-permission android:name="android.permission.ANSWER_PHONE_CALLS" />
<uses-permission android:name="android.permission.READ_CALL_LOG"/>
</code>```

Also ask for runtime permission for ANSWER_PHONE_CALLS and READ_CALL_LOG permissions (as they are Dangerous Permissions).

For android oreo and below:

Create package com.android.internal.telephony in your project, and put this in a file called "ITelephony.aidl":

```<code>package com.android.internal.telephony;
interface ITelephony {
    boolean endCall();
}
</code>```

For above android oreo:

TelecomManager class provides direct method to end call(provided in code).

After above steps add method provided below: (Before this make sure to initialize TelecomManager and TelephonyManager).

```<code>@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
    telecomManager = (TelecomManager) getSystemService(Context.TELECOM_SERVICE);
}

private boolean declinePhone() {
    if (telecomManager.isInCall()) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            if (telecomManager != null) {
                boolean success = telecomManager.endCall();
                return success;
            }
        } else {
            try {
                Class classTelephony = Class.forName(telephonyManager.getClass().getName());
                Method methodGetITelephony = classTelephony.getDeclaredMethod("getITelephony");
                methodGetITelephony.setAccessible(true);
                ITelephony telephonyService = (ITelephony) methodGetITelephony.invoke(telephonyManager);
                if (telephonyService != null) {
                    return telephonyService.endCall();
                }
            } catch (Exception e) {
                e.printStackTrace();
                Log.d("LOG", "Cant disconnect call");
                return false;
            }
        }
    }
    return false;
}
</code>```

Body:
Add these permissions:

<uses-permission android:name="android.permission.ANSWER_PHONE_CALLS" />
<uses-permission android:name="android.permission.READ_CALL_LOG"/>

Also ask for runtime permission for ANSWER_PHONE_CALLS and READ_CALL_LOG permissions (as they are Dangerous Permissions).

For android oreo and below:

Create package com.android.internal.telephony in your project, and put this in a file called "ITelephony.aidl":

package com.android.internal.telephony;
interface ITelephony {
    boolean endCall();
}

For above android oreo:

TelecomManager class provides direct method to end call(provided in code).

After above steps add method provided below: (Before this make sure to initialize TelecomManager and TelephonyManager).

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
    telecomManager = (TelecomManager) getSystemService(Context.TELECOM_SERVICE);
}

private boolean declinePhone() {
    if (telecomManager.isInCall()) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            if (telecomManager != null) {
                boolean success = telecomManager.endCall();
                return success;
            }
        } else {
            try {
                Class classTelephony = Class.forName(telephonyManager.getClass().getName());
                Method methodGetITelephony = classTelephony.getDeclaredMethod("getITelephony");
                methodGetITelephony.setAccessible(true);
                ITelephony telephonyService = (ITelephony) methodGetITelephony.invoke(telephonyManager);
                if (telephonyService != null) {
                    return telephonyService.endCall();
                }
            } catch (Exception e) {
                e.printStackTrace();
                Log.d("LOG", "Cant disconnect call");
                return false;
            }
        }
    }
    return false;
}


问:
Nested if or switch case statement
From the point of view of optimizing the code run time, is there a thumb rule for where to use "nested if" statement and when to use "switch case" statements ?</p>

答: I don't believe it will make any difference for a decision structure that could be implemented using either method. It's highly likely that your compiler would produce the same instructions in the executable.</p>

Title: Nested if or switch case statement


问:
Download File Using Alamofire 4.0 (Swift 3)
In older version of Alamofire. This is how I download file

```<code>    let destinationPath = Alamofire.Request.suggestedDownloadDestination( directory: .documentDirectory, domain: .userDomainMask);

    Alamofire.download(.GET, urlString, destination: destinationPath)
        .progress { bytesRead, totalBytesRead, totalBytesExpectedToRead in
//                print(totalBytesRead)
        }
        .response { request, response, _, error in

            let downloadedFilePath = destinationPath(URL(string: "")!, response!);

            NSUserDefaultsHelper.saveURL(downloadedFilePath, key: urlString);

            completion(downloadedFilePath, true);
    }
</code>```

But now in the new version, my code is completely unusable and there is no similar function in the Alamofire library.

Any ideas please?

答:
For the latest versions this is how it should look like:</p>

```<code>let destination: DownloadRequest.Destination = { _, _ in
        let documentsURL = FileManager.default.urls(for: .picturesDirectory, in: .userDomainMask)[0]
            let fileURL = documentsURL.appendingPathComponent("image.png")

            return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
    }

    AF.download("https://httpbin.org/image/png", to: destination).response { response in
        debugPrint(response)

        if response.error == nil, let imagePath = response.fileURL?.path {
            let image = UIImage(contentsOfFile: imagePath)
        }
    }
</code>```

Body:
In older version of Alamofire. This is how I download file

    let destinationPath = Alamofire.Request.suggestedDownloadDestination( directory: .documentDirectory, domain: .userDomainMask);

    Alamofire.download(.GET, urlString, destination: destinationPath)
        .progress { bytesRead, totalBytesRead, totalBytesExpectedToRead in
//                print(totalBytesRead)
        }
        .response { request, response, _, error in

            let downloadedFilePath = destinationPath(URL(string: "")!, response!);

            NSUserDefaultsHelper.saveURL(downloadedFilePath, key: urlString);

            completion(downloadedFilePath, true);
    }

But now in the new version, my code is completely unusable and there is no similar function in the Alamofire library.

Any ideas please?

Body:
For the latest versions this is how it should look like:

let destination: DownloadRequest.Destination = { _, _ in
        let documentsURL = FileManager.default.urls(for: .picturesDirectory, in: .userDomainMask)[0]
            let fileURL = documentsURL.appendingPathComponent("image.png")

            return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
    }

    AF.download("https://httpbin.org/image/png", to: destination).response { response in
        debugPrint(response)

        if response.error == nil, let imagePath = response.fileURL?.path {
            let image = UIImage(contentsOfFile: imagePath)
        }
    }


问:
Spring Security: what do authorizeRequests(), anyRequest() and authenticated() do?
In the below code what do the different chained methods do?

```<code>protected void configure(HttpSecurity http ) throws Exception {

    http.authorizeRequests()
        .antMatchers(PUBLIC_URL).permitAll()
        .anyRequest().authenticated();

}
</code>```

NOTE: PUBLIC_URL is an array of strings containing public URLs.

答: It means that all requests must be authenticated except those matching PUBLIC_URL

Body:
In the below code what do the different chained methods do?

protected void configure(HttpSecurity http ) throws Exception {

    http.authorizeRequests()
        .antMatchers(PUBLIC_URL).permitAll()
        .anyRequest().authenticated();

}

NOTE: PUBLIC_URL is an array of strings containing public URLs.


问:
Viewing Inline images in Mutt mail on macos/OSX
Is there any way to see inline images in mutt pager view in terminal?
I've tried w3m but it requires w3m-img which seems not for macos/osx.
Can anyone suggest if it's possible to integrate imgcat(avaiable in iterm2) in mailcap?
Please suggest complete steps/any solution for displaying images in terminal for mutt mail agent.
Thanks a lot in advance.

答:
Unfortunately it's not possible to use imgcat to show images directly in built-in pager using mailcap and autoview at least from my findings.

Try following line in Your mailcap file

```<code>image/*; (clear && imgcat %s && read -N 1); needsterminal
</code>```

Then hit v to show attachments, select any image attachment and press <enter>.
To get back to mutt, just press any key.

Body:
Unfortunately it's not possible to use imgcat to show images directly in built-in pager using mailcap and autoview at least from my findings.

Try following line in Your mailcap file

image/*; (clear && imgcat %s && read -N 1); needsterminal

Then hit v to show attachments, select any image attachment and press <enter>.
To get back to mutt, just press any key.