问:
How to apply Gradient to UIView in iOS 10 on a real device
I have this extension to add a Gradient to a View in Swift:

```<code>extension UIView {
    func addGradientWithColor(colorTop: UIColor, colorButton: UIColor){
        let gradient = CAGradientLayer()
        gradient.frame = self.bounds
        gradient.colors = [colorTop.cgColor, colorButton.cgColor]

        self.layer.insertSublayer(gradient, at: 0)
    }
}
</code>```

Then, I use it like that in my UIViewController:

```<code>override func viewDidLoad(){
    self.view.addGradientWithColor(colorTop: UIColor.red, colorButton: UIColor.clear)
    super.viewDidLoad()
}
</code>```

I run the simulator and it works great. But when I want use my app on a real device, the Gradient does not work.

PD: I tried many ways to do a Gradient but nothing worked on a real device.

答:
This code for Gradient with transparent background in Swift 5. [transparent|white mix]</p>

```<code>    let gradientLayer:CAGradientLayer = CAGradientLayer()
    gradientLayer.colors = [UIColor.white.withAlphaComponent(0.0).cgColor, UIColor.white.cgColor]
    gradientLayer.startPoint = CGPoint(x: 0.5, y: 0.0)
    gradientLayer.endPoint = CGPoint(x: 0.5, y: 1.0)
    gradientLayer.frame.size = self.gradientView.frame.size

    self.gradientView.layer.addSublayer(gradientLayer)
</code>```

Body:
I have this extension to add a Gradient to a View in Swift:

extension UIView {
    func addGradientWithColor(colorTop: UIColor, colorButton: UIColor){
        let gradient = CAGradientLayer()
        gradient.frame = self.bounds
        gradient.colors = [colorTop.cgColor, colorButton.cgColor]

        self.layer.insertSublayer(gradient, at: 0)
    }
}

Then, I use it like that in my UIViewController:

override func viewDidLoad(){
    self.view.addGradientWithColor(colorTop: UIColor.red, colorButton: UIColor.clear)
    super.viewDidLoad()
}

I run the simulator and it works great. But when I want use my app on a real device, the Gradient does not work.

PD: I tried many ways to do a Gradient but nothing worked on a real device.

Body:
This code for Gradient with transparent background in Swift 5. [transparent|white mix]

    let gradientLayer:CAGradientLayer = CAGradientLayer()
    gradientLayer.colors = [UIColor.white.withAlphaComponent(0.0).cgColor, UIColor.white.cgColor]
    gradientLayer.startPoint = CGPoint(x: 0.5, y: 0.0)
    gradientLayer.endPoint = CGPoint(x: 0.5, y: 1.0)
    gradientLayer.frame.size = self.gradientView.frame.size

    self.gradientView.layer.addSublayer(gradientLayer)


来源: stackexchange

问:
Skip http interceptors for all GET requests
I had a http interceptor service which will hit a toast message on success and failure and it is working fine.

But i want to skip this toasts to get all requests , cos everytime when i open a page it was showing the success toast.

I want to display only when user makes a request manually

import { Jsonp } from '@angular/http';
import { HttpInterceptor, HttpHandler, HttpRequest, HttpEvent, HttpResponse, HttpErrorResponse } from '@angular/common/http';
import { Injectable } from "@angular/core"
import { Observable } from "rxjs";
import { tap, catchError } from "rxjs/operators";
import { ToastrService } from 'ngx-toastr';
import { of } from 'rxjs/observable/of';

@Injectable()

export class AppHttpInterceptor implements HttpInterceptor {
    constructor(public toasterService: ToastrService) { }
    intercept(
        req: HttpRequest<any>,
        next: HttpHandler
    ): Observable<HttpEvent<any>> {
        return next.handle(req).pipe(
            tap(evt => {
                if (evt instanceof HttpResponse && evt.body && evt.body.success) {
                    // this.toasterService.success(evt.body.success.message, evt.body.success.title);
                    this.displayToast(evt.body)
                }
            }),
            catchError((err: any) => {
                if (err instanceof HttpErrorResponse) {
                    try {
                        // this.toasterService.error(err.error.message, err.error.title);
                        this.displayToast(err.error)
                    } catch (e) {
                        // this.toasterService.error('An error occurred', '');
                        this.displayToast(err.error)
                    }
                    //log error
                }
                return of(err);
            }));

    }

    displayToast(response) {
        let message = response.message;

        if (response.code == 200) {
            this.toasterService.success('success');
        } else if (response.code == 201) {
            this.toasterService.success(message, 'Created');
        } else if (response.code == 400) {
            this.toasterService.error(message, 'Bad Request');
        } else if (response.code == 401) {
            this.toasterService.warning(message, 'Unauthorized');
        } else if (response.code == 403) {
            this.toasterService.warning(message, 'Forbidden');
        } else if (response.code == 404) {
            this.toasterService.warning(message, 'Not Found');
        } else if (response.code == 409) {
            this.toasterService.error(message);
        } else if (response.code == 411) {
            this.toasterService.info(message, 'No Records');
        } else if (response.code == 500) {
            this.toasterService.error(message, 'Internal Server Error');
        } else if (response.code == 503) {
            this.toasterService.error(message, 'Service Unavailable');
        }
    }

}```

答:
You can detect the request method by req.method

Try this:

```<code>requestMethod = req.method

if(requestMethod != "GET" {
  this.displayToast(err.error)
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
You can detect the request method by req.method

Try this:

requestMethod = req.method

if(requestMethod != "GET" {
  this.displayToast(err.error)
}


问:
React's stopPropagation does not work for parent event handlers
I tried solutions provided on the internet but no luck. Here is the codepen link. This is how the code looks like:

```<code>//JSX:
    <div className="drawer-component" onClick={this.closeDrawer}>
      <div className="drawer-opener">
        <button onClick={this.toggleDrawer}>Toggle</button>
      </div>
      {this.state.isOpen && <div class="drawer">Hello I am a drawer. Cliking on me should not close myself.</div>}
    </div>

// Event Handlers:

toggleDrawer(e) {
  e.stopPropagation();
  this.setState((state, props) => {
      return {isOpen: !state.isOpen};
  })
}

closeDrawer(e) {
  e.stopPropagation();
  this.setState((state, props) => {
      return {isOpen: false};
  })
}
</code>```

No idea what I am doing wrong, any help would be appreciated.

答:
The behaviour matches the code written.
You have your text in a div(class='drawer') without any click handler, so the click handler of the parent (div class='drawer-component') gets executed, and in this case it is setting your state variable isOpen to false and closing your drawer. The e.stopPropagation() in this does not affect anything since that div does not have any further parent with a click handler to which the event might get propagated.

If what you intended was to have your text clickable without closing your drawer, add a click handler for the div (with class='drawer') which just prevents propagation.

    closeDrawer(e) {
      // e.stopPropagation();  This isn't required as there's nowhere further the event can get propagated
      this.setState((state, props) => {
          return {isOpen: false};
      })
    }

   // Prevent click handler of parent being called and closing the drawer
   preventClosingOnTextClick(e) {
      e.stopPropagation();
    }

    render() {
      return (

            <button onClick={this.toggleDrawer}>Toggle</button>

          {
           this.state.isOpen &&

 // This prevents the closing
                 Hello I am a drawer. Cliking on me should not close myself.

          }

      );
    }
  };

);
```

Body:
I tried solutions provided on the internet but no luck. Here is the codepen link. This is how the code looks like:

//JSX:

        <button onClick={this.toggleDrawer}>Toggle</button>

      {this.state.isOpen &&
Hello I am a drawer. Cliking on me should not close myself.
}

// Event Handlers:

toggleDrawer(e) {
  e.stopPropagation();
  this.setState((state, props) => {
      return {isOpen: !state.isOpen};
  })
}

closeDrawer(e) {
  e.stopPropagation();
  this.setState((state, props) => {
      return {isOpen: false};
  })
}

No idea what I am doing wrong, any help would be appreciated.

Body:
The behaviour matches the code written.
You have your text in a div(class='drawer') without any click handler, so the click handler of the parent (div class='drawer-component') gets executed, and in this case it is setting your state variable isOpen to false and closing your drawer. The e.stopPropagation() in this does not affect anything since that div does not have any further parent with a click handler to which the event might get propagated.

If what you intended was to have your text clickable without closing your drawer, add a click handler for the div (with class='drawer') which just prevents propagation.

    closeDrawer(e) {
      // e.stopPropagation();  This isn't required as there's nowhere further the event can get propagated
      this.setState((state, props) => {
          return {isOpen: false};
      })
    }

   // Prevent click handler of parent being called and closing the drawer
   preventClosingOnTextClick(e) {
      e.stopPropagation();
    }

    render() {
      return (
        <div className="drawer-component" onClick={this.closeDrawer}>
          <div className="drawer-opener">
            <button onClick={this.toggleDrawer}>Toggle</button>
          </div>
          {
           this.state.isOpen &&
             <div class="drawer"
              onClick={this.preventClosingOnTextClick}> // This prevents the closing
                 Hello I am a drawer. Cliking on me should not close myself.
             </div>
          }
        </div>
      );
    }
  };

);


问:
Storing word documents
I'm working on job site (using asp.net 3.5) in which a user can upload one or more resumes.
Database is sql server 2005.
Whats the recommendation regarding storage of these documents?
Shall i store it as a blob in the database or just store the path in database and keep the document in the physical folder?
Can someone please mention the pros and cons of each wrt performance and scalability?

Thanks!

答:
I'm in charge of some applications that manage many TB of images.  I think this application is similar in that it's storing files relatively large to typical database rows.  We've found that storing file paths in the database to be best.

There are a couple of issues:

database storage is usually more expensive than file system storage.

you can accelerate/distribute file system access with standard off the shelf products.

things like web servers, etc, need no special coding or processing to access images in the file system.

OwnerDisplayName: Patrick

ContentLicense: CC BY-SA 2.5

Title: Storing word documents

OwnerDisplayName: Mark Harrison


问:
Error Unable to read data from transport connection. Connection reset by peer. Xamarin
When I pause my application and then resume after a while, I get this error message:

System.IO.IOException: Unable to read data from the transport connection.
  Connection reset by peer ---> system.net.sockets.....

I've assigned a class which defines all my objects inside my activity example:

```<code>public class Connection: Activity
{
    protected SqlConnection con;
    protected string MyIp;

    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);

        var prefs = Application.Context.GetSharedPreferences("Preferences", FileCreationMode.Private);
        MyIp = prefs.GetString("IpAdress", null);

        con = new SqlConnection("Data Source = " + MyIp + "; Initial Catalog = WiOrder; user id = admin; password = 1234;Connection Timeout=5");

    }
}
</code>```

Here is how I call this class inside activity:

```<code>public class Main : Connection
{
    protected override void OnCreate(Bundle savedInstanceState)
    {

        base.OnCreate(savedInstanceState);
       //Rest of my code
       con.Open();
       SqlCommand cmd = new SqlCommand (//query,con);
       //.........

    }
}
</code>```

答:
I faced the same issue and I was getting this exception (sometimes) when trying to connect to the server.

Unable to read data from the transport connection: Connection reset by
peer.

After many searches, I found this answer

Quote from the answer

This error usually means that the target machine is running, but the
service that you're trying to connect to is not available. (Either it
stopped, crashed, or is busy with another request.)

In English: The connection to the machine (remote host/server/PC that
the service runs at) was made but since the service was not available
on that machine, the machine didn't know what to do with the request.

So, you should check your network connection

For more information,

Take a look at the similar questions here and here

IOException

Body:
When I pause my application and then resume after a while, I get this error message:

System.IO.IOException: Unable to read data from the transport connection.
  Connection reset by peer ---> system.net.sockets.....

I've assigned a class which defines all my objects inside my activity example:

public class Connection: Activity
{
    protected SqlConnection con;
    protected string MyIp;

    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);

        var prefs = Application.Context.GetSharedPreferences("Preferences", FileCreationMode.Private);
        MyIp = prefs.GetString("IpAdress", null);

        con = new SqlConnection("Data Source = " + MyIp + "; Initial Catalog = WiOrder; user id = admin; password = 1234;Connection Timeout=5");

    }
}

Here is how I call this class inside activity:

public class Main : Connection
{
    protected override void OnCreate(Bundle savedInstanceState)
    {

        base.OnCreate(savedInstanceState);
       //Rest of my code
       con.Open();
       SqlCommand cmd = new SqlCommand (//query,con);
       //.........

    }
}


问:
How to add two panels and resize them when frame change sizes?
I have three classes. GameFrame extends JFrame, GamePanel & InfoPanel extend JPanel.
I am looking for the best solution how to add those two panels to frame like on the picture:

The initial size of GamePanel must be (800x800). I would like that when changing the size of the window, both panels also change the size to fit the window. How to do it?

答: Sounds like you need to set the layout of GameFrame to Border Layout and add InfoPanel to the NORTH of GameFrame and GamePanel to the CENTER. BorderLayout will automatically resize its components to match the size of the JFrame.


问:
SVG does not scale correctly in Chrome
I have a SVG (simplified for the Question) with the max-height: 100%;. I don't know the width of the element (calculated on runtime). I want it to have a aspect ration of 1:1, (In Illustrator it was a square) and in Firefox it works. But in Chrome it is about 4:3.

Images: (First is in Firefox, second Chrome)
https://imgur.com/a/qzTcpr4

JSFiddle:
https://jsfiddle.net/rs1bp420/

.container {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  height: 45%;
  width: 80%;
}

svg {
  max-height: 100%;
  width: auto;
  border-radius: 50%;
  box-shadow: 0 0 0 2px #fff, 0 0 0 5px #13ee37;
}

.cls-1 {
  fill: #13ee37;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
<svg id="Layer_1" data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1000 974">
  <title>Vector
  </title>
  <path
        class="cls-1"
        d="M853.92,142.13c-194.92-189.7-515.2-189.32-709,0-193.59,189.07-192.73,499.79,0,688.67,193.37,189.5,513.88,191.67,709.05,2.07C1048.62,643.73,1048.76,331.62,853.92,142.13Z"
        transform="translate(0)"
        >
  </path>
</svg>
</div></code>```

I want the SVG to be a square in Chrome, because of the border (or the box-shadow in my case)

答:
This is a quirk in how inline-replaced elements should get resized. You are in a very special and unclear case where the ratio is known and thus the rule should be

If 'height' and 'width' both have computed values of 'auto' and the element has an intrinsic ratio but no intrinsic height or width, then the used value of 'width' is undefined in CSS 2.2. However, it is suggested that, if the containing block's width does not itself depend on the replaced element's width, then the used value of 'width' is calculated from the constraint equation used for block-level, non-replaced elements in normal flow.

But then, here we are not in "normal flow" because your container element has its position set to absolute.

In your case, you can replicate FF behavior in Chrome by assigning the width and height attributes of you <svg> so that they are not unknown at parsing anymore and don't default to 300 x 150px in Chrome.

.container {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  height: 45%;
  width: 80%;
}

svg {
  max-height: 100%;
  width: auto;
  border-radius: 50%;
  box-shadow: 0 0 0 2px #fff, 0 0 0 5px #13ee37;
}

.cls-1 {
  fill: #13ee37;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
<svg id="Layer_1" data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1000 974" width="100%" height="100%">
  <title>Vector
  </title>
  <path
    class="cls-1"
    d="M853.92,142.13c-194.92-189.7-515.2-189.32-709,0-193.59,189.07-192.73,499.79,0,688.67,193.37,189.5,513.88,191.67,709.05,2.07C1048.62,643.73,1048.76,331.62,853.92,142.13Z"
    transform="translate(0)"
    >
  </path>
</svg>
</div></code>```

Title: SVG does not scale correctly in Chrome

Body:
I have a SVG (simplified for the Question) with the max-height: 100%;. I don't know the width of the element (calculated on runtime). I want it to have a aspect ration of 1:1, (In Illustrator it was a square) and in Firefox it works. But in Chrome it is about 4:3.

Images: (First is in Firefox, second Chrome)
https://imgur.com/a/qzTcpr4

JSFiddle:
https://jsfiddle.net/rs1bp420/

.container {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  height: 45%;
  width: 80%;
}

svg {
  max-height: 100%;
  width: auto;
  border-radius: 50%;
  box-shadow: 0 0 0 2px #fff, 0 0 0 5px #13ee37;
}

.cls-1 {
  fill: #13ee37;
}

<svg id="Layer_1" data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1000 974">
  <title>Vector
  </title>
  <path
        class="cls-1"
        d="M853.92,142.13c-194.92-189.7-515.2-189.32-709,0-193.59,189.07-192.73,499.79,0,688.67,193.37,189.5,513.88,191.67,709.05,2.07C1048.62,643.73,1048.76,331.62,853.92,142.13Z"
        transform="translate(0)"
        >
  </path>
</svg>

I want the SVG to be a square in Chrome, because of the border (or the box-shadow in my case)

Body:
This is a quirk in how inline-replaced elements should get resized. You are in a very special and unclear case where the ratio is known and thus the rule should be

If 'height' and 'width' both have computed values of 'auto' and the element has an intrinsic ratio but no intrinsic height or width, then the used value of 'width' is undefined in CSS 2.2. However, it is suggested that, if the containing block's width does not itself depend on the replaced element's width, then the used value of 'width' is calculated from the constraint equation used for block-level, non-replaced elements in normal flow.

But then, here we are not in "normal flow" because your container element has its position set to absolute.

In your case, you can replicate FF behavior in Chrome by assigning the width and height attributes of you <svg> so that they are not unknown at parsing anymore and don't default to 300 x 150px in Chrome.

.container {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  height: 45%;
  width: 80%;
}

svg {
  max-height: 100%;
  width: auto;
  border-radius: 50%;
  box-shadow: 0 0 0 2px #fff, 0 0 0 5px #13ee37;
}

.cls-1 {
  fill: #13ee37;
}

<div class="container">
<svg id="Layer_1" data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1000 974" width="100%" height="100%">
  <title>Vector
  </title>
  <path
    class="cls-1"
    d="M853.92,142.13c-194.92-189.7-515.2-189.32-709,0-193.59,189.07-192.73,499.79,0,688.67,193.37,189.5,513.88,191.67,709.05,2.07C1048.62,643.73,1048.76,331.62,853.92,142.13Z"
    transform="translate(0)"
    >
  </path>
</svg>
</div>


问:
Convert HTML to NSAttributedString in iOS
I am using a instance of UIWebView to process some text and color it correctly, it gives the result as HTML but rather than displaying it in the UIWebView I want to display it using Core Text with a NSAttributedString.

I am able to create and draw the NSAttributedString but I am unsure how I can convert and map the HTML into the attributed string.

I understand that under Mac OS X NSAttributedString has a initWithHTML: method but this was a Mac only addition and is not available for iOS.

I also know that there is a similar question to this but it had no answers, I though I would try again and see whether anyone has created a way to do this and if so, if they could share it.

答:
honoring font family, dynamic font I've concocted this abomination:

```<code>extension NSAttributedString
{
    convenience fileprivate init?(html: String, font: UIFont? = Font.dynamic(style: .subheadline))
    {
        guard let data = html.data(using: String.Encoding.utf8, allowLossyConversion: true) else {
        var totalString = html
        /*
         https://stackoverflow.com/questions/32660748/how-to-use-apples-new-san-francisco-font-on-a-webpage
            .AppleSystemUIFont I get in font.familyName does not work
         while -apple-system does:
         */
        var ffamily = "-apple-system"
        if let font = font {
            let lLDBsucks = font.familyName
            if !lLDBsucks.hasPrefix(".appleSystem") {
                ffamily = font.familyName
            }
            totalString = "<style>\nhtml * {font-family: \(ffamily) !important;}\n            </style>\n" + html
        }
        guard let data = totalString.data(using: String.Encoding.utf8, allowLossyConversion: true) else {
            return nil
        }
        assert(Thread.isMainThread)
        guard let attributedText = try?  NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue], documentAttributes: nil) else {
            return nil
        }
        let mutable = NSMutableAttributedString(attributedString: attributedText)
        if let font = font {
        do {
            var found = false
            mutable.beginEditing()
            mutable.enumerateAttribute(NSAttributedString.Key.font, in: NSMakeRange(0, attributedText.length), options: NSAttributedString.EnumerationOptions(rawValue: 0)) { (value, range, stop) in
                    if let oldFont = value as? UIFont {
                        let newsize = oldFont.pointSize * 15 * Font.scaleHeruistic / 12
                        let newFont = oldFont.withSize(newsize)
                        mutable.addAttribute(NSAttributedString.Key.font, value: newFont, range: range)
                        found = true
                    }
                }
                if !found {
                    // No font was found - do something else?
                }

            mutable.endEditing()

//            mutable.addAttribute(.font, value: font, range: NSRange(location: 0, length: mutable.length))
        }
        self.init(attributedString: mutable)
    }

}
</code>```

alternatively you can use the versions this was derived from and set
font on UILabel after setting attributedString

this will clobber the size and boldness encapsulated in the attributestring though

kudos for reading through all the answers up to here.
You are a very patient man woman or child.

Body:
honoring font family, dynamic font I've concocted this abomination:

extension NSAttributedString
{
    convenience fileprivate init?(html: String, font: UIFont? = Font.dynamic(style: .subheadline))
    {
        guard let data = html.data(using: String.Encoding.utf8, allowLossyConversion: true) else {
        var totalString = html
        /*
         https://stackoverflow.com/questions/32660748/how-to-use-apples-new-san-francisco-font-on-a-webpage
            .AppleSystemUIFont I get in font.familyName does not work
         while -apple-system does:
         */
        var ffamily = "-apple-system"
        if let font = font {
            let lLDBsucks = font.familyName
            if !lLDBsucks.hasPrefix(".appleSystem") {
                ffamily = font.familyName
            }
            totalString = "<style>\nhtml * {font-family: \(ffamily) !important;}\n            </style>\n" + html
        }
        guard let data = totalString.data(using: String.Encoding.utf8, allowLossyConversion: true) else {
            return nil
        }
        assert(Thread.isMainThread)
        guard let attributedText = try?  NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue], documentAttributes: nil) else {
            return nil
        }
        let mutable = NSMutableAttributedString(attributedString: attributedText)
        if let font = font {
        do {
            var found = false
            mutable.beginEditing()
            mutable.enumerateAttribute(NSAttributedString.Key.font, in: NSMakeRange(0, attributedText.length), options: NSAttributedString.EnumerationOptions(rawValue: 0)) { (value, range, stop) in
                    if let oldFont = value as? UIFont {
                        let newsize = oldFont.pointSize * 15 * Font.scaleHeruistic / 12
                        let newFont = oldFont.withSize(newsize)
                        mutable.addAttribute(NSAttributedString.Key.font, value: newFont, range: range)
                        found = true
                    }
                }
                if !found {
                    // No font was found - do something else?
                }

            mutable.endEditing()

//            mutable.addAttribute(.font, value: font, range: NSRange(location: 0, length: mutable.length))
        }
        self.init(attributedString: mutable)
    }

}

alternatively you can use the versions this was derived from and set
font on UILabel after setting attributedString

this will clobber the size and boldness encapsulated in the attributestring though

kudos for reading through all the answers up to here.
You are a very patient man woman or child.


问:
Making a scrollable div that encompasses the entire height of the PDF
I am embedding a PDF into my webpage.  I'm doing some tom-foolery to hide the status bar (including the download buttons and page numbers) so I can control them externally (I want to be able to force a different download when they try to download the document).  If it makes any difference (such as a solution that will only work/won't work given a framework), I'm using React.

I can set the active page of the PDF using a URL, but after the load of that page I can't get the scroll position of the document to update the page number.

I think a solution for this is to contain the embedded PDF in a div that I can personally control.  To do this, I want the embedded object to have a height that is the sum of the vertical height of all of the pages of the PDF combined, and then encase that in a div with a set height.  I can, from there, monitor the scroll position of the document to determine the current page.

```<code><div class='encasing-div'>
    <div class='toolbar'/>
    <object data='some.pdf' type='application/pdf'>
        <embed src='some.pdf' type='application/pdf' wmode='opaque'/>
    </object>
</div>
</code>```

I can't get the embedded PDF to be the full height of the document.  I know the number of pages in the document on page load, but I don't know how/if I can use that to adjust the height properly.

How does one go about making the embedded object the height of the entire PDF, thus eliminating the scroll from the embedded object and allowing an external scroll to be used?

Edit:  Here's a picture attemping to explain what I'm looking for.  In the second part of the picture, the stuff outside of the div would be hidden but scrollable to.

答:
You can use iframe instead of object & embed</p>

```<code><!DOCTYPE html>
<html style="height:100%">
<body style="height:100%">

<h2>HTML Iframes</h2>
<p>You can use the height and width attributes to specify the size of the iframe:</p>
<div style="height:100%">
        <iframe src="some.pdf" height="100%" width="100%""></iframe>
</div>

</body>
</html>
</code>```

Body:
I am embedding a PDF into my webpage.  I'm doing some tom-foolery to hide the status bar (including the download buttons and page numbers) so I can control them externally (I want to be able to force a different download when they try to download the document).  If it makes any difference (such as a solution that will only work/won't work given a framework), I'm using React.

I can set the active page of the PDF using a URL, but after the load of that page I can't get the scroll position of the document to update the page number.

I think a solution for this is to contain the embedded PDF in a div that I can personally control.  To do this, I want the embedded object to have a height that is the sum of the vertical height of all of the pages of the PDF combined, and then encase that in a div with a set height.  I can, from there, monitor the scroll position of the document to determine the current page.

    <object data='some.pdf' type='application/pdf'>
        <embed src='some.pdf' type='application/pdf' wmode='opaque'/>
    </object>

I can't get the embedded PDF to be the full height of the document.  I know the number of pages in the document on page load, but I don't know how/if I can use that to adjust the height properly.

How does one go about making the embedded object the height of the entire PDF, thus eliminating the scroll from the embedded object and allowing an external scroll to be used?

Edit:  Here's a picture attemping to explain what I'm looking for.  In the second part of the picture, the stuff outside of the div would be hidden but scrollable to.

Body:
You can use iframe instead of object & embed

<!DOCTYPE html>
<html style="height:100%">
<body style="height:100%">

<h2>HTML Iframes</h2>
<p>You can use the height and width attributes to specify the size of the iframe:</p>
<div style="height:100%">
        <iframe src="some.pdf" height="100%" width="100%""></iframe>
</div>

</body>
</html>


问:
Which OpenGL version is most stable and currently used?
I've been thinking of making an additional wrapper for my project to use OpenGL rather then Allegro. I was not sure which OpenGL version to go for since I know that some computers cannot run recent versions such as v4.4. Also, I need a version which compiles no problem in Linux, Windows, Mac.</p>

答:
You'll want to look at what kinds of graphics cards will be available on your target systems and bear some details in mind:

OpenGL up to 1.5 can be completely emulated in software in real time on most systems. You don't necessarily need hardware support for good performance.

OpenGL 1.4 has universal support. Virtually all hardware supports it.

Mac OS X only supports up to OpenGL 2.0 and OpenGL 2.1, depending on OS version and hardware. Systems using GMA950 have only OGL1.4 support. Mac OS X Lion 10.7 supports OpenGL 3.2 Core profile on supported hardware.

On Linux, it's not unusual for users to specifically prefer open source drivers over the alternative "binary blobs," so bear in mind that the version of Mesa that most people have supports only up to about OpenGL 2.1 compatibility. Upcoming versions have support for OpenGL 3.x. Closed-source "binary blobs" will generally support the highest OpenGL version for the hardware, including up to OpenGL 4.2 Core.

When considering what hardware is available to your users, the Steam hardware Survey may help. Note that most users have DirectX 9-compatible hardware, which is roughly feature-equivalent to OpenGL 2.0. Wikipedia's OpenGL article also specifies what hardware came with initial support for which versions.

If you use a library like GLEW or GLEE or any toolkit that depends on them or offers similar functionality (like SFML, or even Allegro since 4.3), then you'll not need to concern yourself with whether your code will compile. These toolkits will take care of the details of enabling extensions and providing all of the symbols you need.

Given all of this, I'd suggest targeting OpenGL 2.1 to get the widest audience possible with the best feature support.

ContentLicense: CC BY-SA 3.0


问:
Find issues that were ever assigned to me
I am trying to create a filter to search for all issues that were ever assigned to me, even after the assignee is changed. I cant find the appropriate search parameters for this. Is it even possible in jira?</p>

答:
Click the eyeglass icon on the left pane

Click on "Advanced search for issues"

In the top right, click on "Advanced Search" to open the JQL textbox

Enter the query:

```<code>assignee = currentUser() OR assignee was currentUser()
</code>```

If you'll use this repeatedly, click save and name the search. Then you'll see it on the left bar under Starred...

Body:
Click the eyeglass icon on the left pane

Click on "Advanced search for issues"

In the top right, click on "Advanced Search" to open the JQL textbox

Enter the query:

assignee = currentUser() OR assignee was currentUser()

If you'll use this repeatedly, click save and name the search. Then you'll see it on the left bar under Starred...


问:
Only one expression can be specified in the select list w
I am having problem in part of my code anyway to do this
Only one expression can be specified in the select list when the subquery is not introduced with EXISTS. The update part is working but how to use insert into to calculate if  a condition is not meant it will insert.  </p>

```<code>IF
    /* CHECKLIST TO UPDATE*/
    (NOT EXISTS
        (SELECT *
        FROM    ENERGY.D_ENERGY_REFERENCE D_ENERGY_REFERENCE
                ,ENERGY.D_CHECK_LIST D_CHECK_LIST
        WHERE   D_ENERGY_REFERENCE.ID = D_CHECK_LIST.ID
        AND     D_ENERGY_REFERENCE.REFERENCE = 19051

        )
)

BEGIN

INSERT INTO DB.D_ENERGY_REFERENCE(ID, REFERENCE_NO, REFERENCE,VALUE_INTEGER)
(SELECT ID,
                (SELECT  ISNULL(MAX(REFERENCE_NO), 0) + 1 FROM DB.D_ENERGY_REFERENCE),
                19051,  (SELECT D_CHECK_LIST.ID,
      CASE
        WHEN CAST(COUNT(CASE WHEN D_CHECK_LIST.EVALUATION  NOT IN (0,1) THEN EVALUATION ELSE NULL END) AS FLOAT) = 0 THEN NULL
        ELSE
        (
          CAST(COUNT(CASE WHEN D_CHECK_LIST.EVALUATION  IN (2, 3, 50001, 50003, 50004, 50005, 50006, 50020, 50027, 50028) THEN EVALUATION ELSE NULL END) AS FLOAT)
            /
            CAST(COUNT(CASE WHEN D_CHECK_LIST.EVALUATION  NOT IN (0,1) THEN EVALUATION ELSE NULL END) AS FLOAT)
        ) * 100

    END  FROM DB.D_CHECK_LIST

     GROUP BY D_CHECK_LIST.ID)

FROM DB.D_ENERGY_REFERENCE D_ENERGY_REFERENCE
WHERE  D_ENERGY_REFERENCE.ID = ID AND D_ENERGY_REFERENCE.REFERENCE = 19051
GROUP BY D_ENERGY_REFERENCE.ID
)

END
</code>```

答:
Can you please check this following part in the sub query of your script-

```<code>.......
19051,
(
    SELECT
    D_CHECK_LIST.ID, -- This is the column 1
    CASE
        WHEN -- Here you are generating column 2 in the sub query
        ......
)
</code>```

Here you are selecting 2 column - one is "D_CHECK_LIST.ID" and other one is generation through CASE WHEN statement. I think you should SELECT any 1 column from those 2 column. If both are required, you can use separate Sub query for that.

The ERROR code "Only one expression can be specified in the select list when the subquery is not introduced with EXISTS" is self explanatory that you can not implement a Sub Query with more than 1 column selected unless the Sub Query is using inside EXISTS method.

Body:
I am having problem in part of my code anyway to do this
Only one expression can be specified in the select list when the subquery is not introduced with EXISTS. The update part is working but how to use insert into to calculate if  a condition is not meant it will insert.

IF
    /* CHECKLIST TO UPDATE*/
    (NOT EXISTS
        (SELECT *
        FROM    ENERGY.D_ENERGY_REFERENCE D_ENERGY_REFERENCE
                ,ENERGY.D_CHECK_LIST D_CHECK_LIST
        WHERE   D_ENERGY_REFERENCE.ID = D_CHECK_LIST.ID
        AND     D_ENERGY_REFERENCE.REFERENCE = 19051

        )
)

BEGIN

INSERT INTO DB.D_ENERGY_REFERENCE(ID, REFERENCE_NO, REFERENCE,VALUE_INTEGER)
(SELECT ID,
                (SELECT  ISNULL(MAX(REFERENCE_NO), 0) + 1 FROM DB.D_ENERGY_REFERENCE),
                19051,  (SELECT D_CHECK_LIST.ID,
      CASE
        WHEN CAST(COUNT(CASE WHEN D_CHECK_LIST.EVALUATION  NOT IN (0,1) THEN EVALUATION ELSE NULL END) AS FLOAT) = 0 THEN NULL
        ELSE
        (
          CAST(COUNT(CASE WHEN D_CHECK_LIST.EVALUATION  IN (2, 3, 50001, 50003, 50004, 50005, 50006, 50020, 50027, 50028) THEN EVALUATION ELSE NULL END) AS FLOAT)
            /
            CAST(COUNT(CASE WHEN D_CHECK_LIST.EVALUATION  NOT IN (0,1) THEN EVALUATION ELSE NULL END) AS FLOAT)
        ) * 100

    END  FROM DB.D_CHECK_LIST

     GROUP BY D_CHECK_LIST.ID)

FROM DB.D_ENERGY_REFERENCE D_ENERGY_REFERENCE
WHERE  D_ENERGY_REFERENCE.ID = ID AND D_ENERGY_REFERENCE.REFERENCE = 19051
GROUP BY D_ENERGY_REFERENCE.ID
)

END

Body:
Can you please check this following part in the sub query of your script-

.......
19051,
(
    SELECT
    D_CHECK_LIST.ID, -- This is the column 1
    CASE
        WHEN -- Here you are generating column 2 in the sub query
        ......
)

Here you are selecting 2 column - one is "D_CHECK_LIST.ID" and other one is generation through CASE WHEN statement. I think you should SELECT any 1 column from those 2 column. If both are required, you can use separate Sub query for that.

The ERROR code "Only one expression can be specified in the select list when the subquery is not introduced with EXISTS" is self explanatory that you can not implement a Sub Query with more than 1 column selected unless the Sub Query is using inside EXISTS method.


问:
How to ensure referential integrity which relies on a value
Suppose I have a table Level1:

```<code>Id int PK
Deleted bit
</code>```

and another table Level2:

```<code>Id
Level1id
</code>```

I can add a FK to Level2 to match the Level1id with Level1.Id
That works fine.

However, what If I want to ensure that records INSERTed in Level2 only match records in Level1 where the Deleted bit = 0 ? How do I do that?

I'm guessing that I might have to write a Trigger, but am hoping there's a more elegant solution...

答:
I don't think it's very elegant, but doable.

```<code>create table Level1(
    Id int not null Primary key,
    Deleted bit not null,
constraint u1 unique (Id, Deleted)
);

create table Level2(
    Id int ,
    Level1id int,
    level1Deleted bit default(1) check (level1Deleted=1),
constraint fk1 foreign key (Level1id, level1Deleted) references Level1(Id, Deleted)
);
</code>```

Use it with a big care, one will have problems updating level1.

Body:
Suppose I have a table Level1:

Id int PK
Deleted bit

and another table Level2:

Id
Level1id

I can add a FK to Level2 to match the Level1id with Level1.Id
That works fine.

However, what If I want to ensure that records INSERTed in Level2 only match records in Level1 where the Deleted bit = 0 ? How do I do that?

I'm guessing that I might have to write a Trigger, but am hoping there's a more elegant solution...

Body:
I don't think it's very elegant, but doable.

create table Level1(
    Id int not null Primary key,
    Deleted bit not null,
constraint u1 unique (Id, Deleted)
);

create table Level2(
    Id int ,
    Level1id int,
    level1Deleted bit default(1) check (level1Deleted=1),
constraint fk1 foreign key (Level1id, level1Deleted) references Level1(Id, Deleted)
);

Use it with a big care, one will have problems updating level1.


问:
MySQL correct statement for "update all rows where column > number"?
I have a table called 'images' with a few rows of image names and a value for their position (order which they will appear on site).

```<code>id      name       position
1       dog.png    3
2       cat.png    1
3       snake.png  2
</code>```

What im trying to do is decrement all position column values if they are above a specific value.

For example, if 'cat' is to be deleted, i want to find all rows with a position higher (would be snake and dog) and decrement their position values by 1. I need an SQL statement for

"update all 'position' columns where 'position' > 'value'"

I know i need to get the 'position' of the image to be deleted, and set this to 'value' before updating the rest of the rows with higher position columns. But, I'm not sure how to create the SQL statement for the rest of:

"update all 'position' columns where 'position' > 'value'"

I'm not sure whether i would need one or two queries for it.

答:
You can use the following simple UPDATE:

```<code>UPDATE images SET position = position - 1 WHERE position > 1
</code>```

You can also use the following to UPDATE the images and DELETE the specific image:

```<code>-- first update the other images
UPDATE images t1, (SELECT * FROM images WHERE id = 2) t2 SET t1.position = t1.position - 1 WHERE t1.position > t2.position

-- now you can delete the image
DELETE FROM images WHERE id = 2
</code>```

demo on dbfiddle.uk

Inspired by Tim Biegeleisen's solution you can use the following UPDATE to close the gaps after deleting one or more images. In this case you have to use MySQL 8.0 or later (for ROW_NUMBER):

```<code>UPDATE images t1,
  (SELECT id, ROW_NUMBER() OVER (ORDER BY position) rn FROM images) t2
SET t1.position = t2.rn
WHERE t1.id = t2.id
</code>```

In this case you can also delete multiple images like this:

```<code>DELETE FROM images WHERE id IN (1, 2)
</code>```

demo on dbfiddle.uk

Body:
I have a table called 'images' with a few rows of image names and a value for their position (order which they will appear on site).

id      name       position
1       dog.png    3
2       cat.png    1
3       snake.png  2

What im trying to do is decrement all position column values if they are above a specific value.

For example, if 'cat' is to be deleted, i want to find all rows with a position higher (would be snake and dog) and decrement their position values by 1. I need an SQL statement for

"update all 'position' columns where 'position' > 'value'"

I know i need to get the 'position' of the image to be deleted, and set this to 'value' before updating the rest of the rows with higher position columns. But, I'm not sure how to create the SQL statement for the rest of:

"update all 'position' columns where 'position' > 'value'"

I'm not sure whether i would need one or two queries for it.

Body:
You can use the following simple UPDATE:

UPDATE images SET position = position - 1 WHERE position > 1

You can also use the following to UPDATE the images and DELETE the specific image:

-- first update the other images
UPDATE images t1, (SELECT * FROM images WHERE id = 2) t2 SET t1.position = t1.position - 1 WHERE t1.position > t2.position

-- now you can delete the image
DELETE FROM images WHERE id = 2

demo on dbfiddle.uk

Inspired by Tim Biegeleisen's solution you can use the following UPDATE to close the gaps after deleting one or more images. In this case you have to use MySQL 8.0 or later (for ROW_NUMBER):

UPDATE images t1,
  (SELECT id, ROW_NUMBER() OVER (ORDER BY position) rn FROM images) t2
SET t1.position = t2.rn
WHERE t1.id = t2.id

In this case you can also delete multiple images like this:

DELETE FROM images WHERE id IN (1, 2)

demo on dbfiddle.uk


问:
Gulp: error in console, assert.js:90 throw new assert.AssertionError
I get such an error in console:
$ gulp

```<code>assert.js:90
  throw new assert.AssertionError({
  ^
AssertionError: Task function must be specified

at Gulp.set [as _setTask] (C:\Users\user\Projects\New project\node_modules\undertaker\lib\set-task.js:10:3)

at Gulp.task (C:\Users\user\Projects\New project\node_modules\undertaker\lib\task.js:13:8)

at Object.<anonymous> (C:\Users\user\Projects\New project\gulpfile.js:44:6)
at Module._compile (module.js:541:32)
at Object.Module._extensions..js (module.js:550:10)
at Module.load (module.js:458:32)
at tryModuleLoad (module.js:417:12)
at Function.Module._load (module.js:409:3)
at Module.require (module.js:468:17)
at require (internal/module.js:20:19)
</code>```

Here is my gulpfile:

```<code>var gulp = require('gulp');
var build = require('gulp-build');
var sass = require('gulp-sass');
var sourcemaps = require('gulp-sourcemaps');
var browser_sync = require('browser-sync');
var gulps = require("gulp-series");

//gulp-build
gulp.task('build', function() {
    gulp.src('scripts/*.js')
        .pipe(build({
            GA_ID: '123456'
        }))
        .pipe(gulp.dest('dist'))
});

//gulp-sass
gulp.task('sass', function() {
    return gulp.src('scss/**/*.scss')
        .pipe(sourcemaps.init())
        .pipe(sass({
            errLogToConsole: true,
            outputStyle: 'expanded'
        }).on('error', sass.logError))
        .pipe(sourcemaps.write('./maps'))
        .pipe(gulp.dest('css'));
});

//gulp-browser-sync
gulp.task('browser_sync', function() {
    var files = [
        '*.html',
        'css/*.css'
    ];
    browser_sync.init(files, {
        server: {
            baseDir: './'
        }
    });
});

//gulp-watch
gulp.task('watch', ['sass'], function() {
    gulp.watch('scss/**/*.scss', ['sass']);
});

//gulp-series
gulps.registerTasks({
    "test1": (function(done) {
        setTimeout(function() {
            console.log("test1 is done");
            done();
        }, 1000);
    }),
    "test2": (function() {
        console.log("test2 is done");
    })
});

gulps.registerSeries("default", ["test1", "test2"]);

// gulp.task('default', ['watch', 'browser_sync'], function() {});
</code>```

I'm just a beginner, have you any idea what I've done wrong?

答:
Also an important thing to notice, if you get the

"AssertionError: Task never defined: two"

Probably it's because the tasks should be in sequence, so first task one task two and then the task with the

gulp.series('one', 'two')

Body:
I get such an error in console:
$ gulp

assert.js:90
  throw new assert.AssertionError({
  ^
AssertionError: Task function must be specified

at Gulp.set [as _setTask] (C:\Users\user\Projects\New project\node_modules\undertaker\lib\set-task.js:10:3)

at Gulp.task (C:\Users\user\Projects\New project\node_modules\undertaker\lib\task.js:13:8)

at Object.<anonymous> (C:\Users\user\Projects\New project\gulpfile.js:44:6)
at Module._compile (module.js:541:32)
at Object.Module._extensions..js (module.js:550:10)
at Module.load (module.js:458:32)
at tryModuleLoad (module.js:417:12)
at Function.Module._load (module.js:409:3)
at Module.require (module.js:468:17)
at require (internal/module.js:20:19)

Here is my gulpfile:

var gulp = require('gulp');
var build = require('gulp-build');
var sass = require('gulp-sass');
var sourcemaps = require('gulp-sourcemaps');
var browser_sync = require('browser-sync');
var gulps = require("gulp-series");

//gulp-build
gulp.task('build', function() {
    gulp.src('scripts/*.js')
        .pipe(build({
            GA_ID: '123456'
        }))
        .pipe(gulp.dest('dist'))
});

//gulp-sass
gulp.task('sass', function() {
    return gulp.src('scss/**/*.scss')
        .pipe(sourcemaps.init())
        .pipe(sass({
            errLogToConsole: true,
            outputStyle: 'expanded'
        }).on('error', sass.logError))
        .pipe(sourcemaps.write('./maps'))
        .pipe(gulp.dest('css'));
});

//gulp-browser-sync
gulp.task('browser_sync', function() {
    var files = [
        '*.html',
        'css/*.css'
    ];
    browser_sync.init(files, {
        server: {
            baseDir: './'
        }
    });
});

//gulp-watch
gulp.task('watch', ['sass'], function() {
    gulp.watch('scss/**/*.scss', ['sass']);
});

//gulp-series
gulps.registerTasks({
    "test1": (function(done) {
        setTimeout(function() {
            console.log("test1 is done");
            done();
        }, 1000);
    }),
    "test2": (function() {
        console.log("test2 is done");
    })
});

gulps.registerSeries("default", ["test1", "test2"]);

// gulp.task('default', ['watch', 'browser_sync'], function() {});

I'm just a beginner, have you any idea what I've done wrong?


问:
Read data from memory
I have an API to read data:

ROM_READ_PAGE(BLOCK_NO, PAGE_NO, *READ_BUFFER);

The Page size is 2048 and you can ONLY read WHOLE page at a time.

I know it is just about using C, but my system doesn't run using either of the methods I tried.

For example:

```<code>char *readPtr;
char readBuff[128]; //(Can not use 2048 due to stack overflow)

readPtr = readBuff;

ROM_READ_PAGE(BLOCK_NO, PAGE_NO, readPtr); // SMX doesn't like this and shows some exception
</code>```

Any other idea or if I am missing something important.

答:
Don't use the stack.
If you compiler uses the stack for auto variables, you can either change the way your compiler deals with auto variables (unlikely) or use some other kind of variable.

Usually, compilers put static storage variables in a different area than auto variables. You may want to try that.

Or, try dynamic memory allocation.

Title: Read data from memory

Body:
I have an API to read data:

ROM_READ_PAGE(BLOCK_NO, PAGE_NO, *READ_BUFFER);

The Page size is 2048 and you can ONLY read WHOLE page at a time.

I know it is just about using C, but my system doesn't run using either of the methods I tried.

For example:

char *readPtr;
char readBuff[128]; //(Can not use 2048 due to stack overflow)

readPtr = readBuff;

ROM_READ_PAGE(BLOCK_NO, PAGE_NO, readPtr); // SMX doesn't like this and shows some exception

Any other idea or if I am missing something important.


问:
how to use pandas.assign with lambda and if condition
can anyone please tell me what's the problem in the line code above

```<code>out_inf=q25-1.5*iqr
out_sup=q75+1.5*iqr

df=df.assign(label=1 if ((df'std']<out_inf) is True) | ((df['std']>out_sup) is True) else 0)
</code>```

my new column have only 0 which is not correct
normally i gotta have them both because I've tried this with a simple for{ if else } but it took too long to be executed.

答:
Try a better approach:

```<code>df['label']=((df['std']<out_inf)|(df['std']>out_sup)).astype(int)
</code>```

Or for any other if,else conditions use np.where()

```<code>m=(df['std']<out_inf)|(df['std']>out_sup)
df['label']=np.where(m,1,0)
</code>```

Conditions like (df['std']<out_inf) will return a boolean output already, so we are avoiding any further comparison.

Body:
can anyone please tell me what's the problem in the line code above

out_inf=q25-1.5*iqr
out_sup=q75+1.5*iqr

df=df.assign(label=1 if ((df'std']<out_inf) is True) | ((df['std']>out_sup) is True) else 0)

my new column have only 0 which is not correct
normally i gotta have them both because I've tried this with a simple for{ if else } but it took too long to be executed.

Body:
Try a better approach:

df['label']=((df['std']<out_inf)|(df['std']>out_sup)).astype(int)

Or for any other if,else conditions use np.where()

m=(df['std']<out_inf)|(df['std']>out_sup)
df['label']=np.where(m,1,0)

Conditions like (df['std']<out_inf) will return a boolean output already, so we are avoiding any further comparison.


问:
How to add a comment to a page using ajax
I am trying to allow the user to make a comment in an article but somehow, so that my page is not reloaded, I have to use ajax and I don't have much knowledge about it. This is how my comment section looks like:

```<code><div class="usrcmmnt_list">
      @foreach($comments as $comment)
      <div class="usrcmmnt flex_box">
        <div class="usrcmmnt_pic">
          <img src="{{ $comment->user['profile_image'] }}">
        </div>
        <div class="usrcmmnt_area">
          <p class="usrcmmnt_name">{{ $comment->user['name'] }}</p>
          <div class="usrcmmnt_box">
            <p class="usrcmmnt_text">{{$comment['content']}}</p>
            <p class="usrcmmnt_time"><img src="{{ url('/img/icon_time.png') }}">{{ date("m/d H:m", strtotime($comment->created_at)) }}</p>
          </div>
        </div>
      </div>
      @endforeach
    </div>
    <div class="comment_write">
      <textarea placeholder="Write a comment" name="comment" id="comment" maxLength="255"></textarea>
      <p class="usrcmmnt_text" id="textarea_warning"></p>
      <span class="alert"></span>
      <button class="btn btn_orange btn_m_2" id="saveComment" type="submit">Post comment</button>
    </div>
</div>
</code>```

In my script part, I have this one but it only copies the existing comments. This is just for my testing:

```<code>$('.comment_write button').on('click', function(e){
  e.preventDefault();
  var tmp = document.createElement('div');
  $(tmp).load('myurl', function(data){
    // usrcmmnt_list
    var tmp2 = document.createElement('div');
    $(tmp2).html(data);
    var list = $(tmp2).find('.usrcmmnt_list');

    $(".usrcmmnt_list").append(list);
  });
});
</code>```

How can I attain my goal using ajax?

答:
You must try something like this.

```<code>$(document).on('click', '#saveComment', function(){
    if($('#comment').val()==''){
        alert('Please write a Comment First!');
    }
    else{
        var comment = $('#comment').val();
        $.ajax({
            type: 'POST',
            url: '<your url goes here>',
            data: {"comment": comment},
            success: function(){
               // update comment listing.
            },
        });
    }

});
</code>```

However here is the complete tutorial you can follow. https://www.sourcecodester.com/tutorials/php/11819/laravel-comment-post-using-ajax.html

Body:
I am trying to allow the user to make a comment in an article but somehow, so that my page is not reloaded, I have to use ajax and I don't have much knowledge about it. This is how my comment section looks like:

      @foreach($comments as $comment)

          user['profile_image'] }}">

{{ $comment->user['name'] }}

{{$comment['content']}}

{{ date("m/d H:m", strtotime($comment->created_at)) }}

      @endforeach

      <textarea placeholder="Write a comment" name="comment" id="comment" maxLength="255"></textarea>

      <button class="btn btn_orange btn_m_2" id="saveComment" type="submit">Post comment</button>

In my script part, I have this one but it only copies the existing comments. This is just for my testing:

$('.comment_write button').on('click', function(e){
  e.preventDefault();
  var tmp = document.createElement('div');
  $(tmp).load('myurl', function(data){
    // usrcmmnt_list
    var tmp2 = document.createElement('div');
    $(tmp2).html(data);
    var list = $(tmp2).find('.usrcmmnt_list');

    $(".usrcmmnt_list").append(list);
  });
});

How can I attain my goal using ajax?

Body:
You must try something like this.

$(document).on('click', '#saveComment', function(){
    if($('#comment').val()==''){
        alert('Please write a Comment First!');
    }
    else{
        var comment = $('#comment').val();
        $.ajax({
            type: 'POST',
            url: '<your url goes here>',
            data: {"comment": comment},
            success: function(){
               // update comment listing.
            },
        });
    }

});

However here is the complete tutorial you can follow. https://www.sourcecodester.com/tutorials/php/11819/laravel-comment-post-using-ajax.html


问:
What is a coroutine?
What is a coroutine? How are they related to concurrency?</p>

答:
From Python Coroutine:

Execution of Python coroutines can be suspended and resumed at many
  points (see coroutine). Inside the body of a coroutine function, await
  and async identifiers become reserved keywords; await expressions,
  async for and async with can only be used in coroutine function
  bodies.

From Coroutines (C++20)

A coroutine is a function that can suspend execution to be resumed
  later. Coroutines are stackless: they suspend execution by returning
  to the caller. This allows for sequential code that executes
  asynchronously (e.g. to handle non-blocking I/O without explicit
  callbacks), and also supports algorithms on lazy-computed infinite
  sequences and other uses.

Compare with other's answer:

In my opinion, the resumed later part is a core difference, just like @Twinkle's.

Although many fields of the document are still work in progress, however, this part is similar to most answer, except @Nan Xiao 's

Coroutines, on the other hand, are collaborative: at any given time, a
  program with coroutines is running only one of its coroutines, and
  this running coroutine suspends its execution only when it explicitly
  requests to be suspended.

Since it's quoted from Program in Lua, maybe it's language related(not familiar with Lua currently), not all document mentioned the only one part.

The relation with concurrent:

There is an "Execution" part of the Coroutines (C++20).Too long to quote here.

Besides the detail, there are several states.

```<code>When a coroutine begins execution
When a coroutine reaches a suspension point
When a coroutine reaches the co_return statement
If the coroutine ends with an uncaught exception
When the coroutine state is destroyed either because it terminated via co_return or uncaught exception, or because it was destroyed via its handle
</code>```

as the comment from @Adam Arold under @user217714's answer. It's concurrency.

But it's different from multithreading.
from std::thread

Threads allow multiple functions to execute concurrently.
  Threads begin execution immediately upon construction of the
  associated thread object (pending any OS scheduling delays), starting
  at the top-level function provided as a constructor argument. The
  return value of the top-level function is ignored and if it terminates
  by throwing an exception, std::terminate is called. The top-level
  function may communicate its return value or an exception to the
  caller via std::promise or by modifying shared variables (which may
  require synchronization, see std::mutex and std::atomic)

Since it's concurrency, it works like multithreading especially when waiting is unavoidable(from the OS perspective), that's also why it's confusing.

OwnerDisplayName: rajKumar

Title: What is a coroutine?

LastEditorDisplayName: Rich B

Body:
From Python Coroutine:

Execution of Python coroutines can be suspended and resumed at many
  points (see coroutine). Inside the body of a coroutine function, await
  and async identifiers become reserved keywords; await expressions,
  async for and async with can only be used in coroutine function
  bodies.

From Coroutines (C++20)

A coroutine is a function that can suspend execution to be resumed
  later. Coroutines are stackless: they suspend execution by returning
  to the caller. This allows for sequential code that executes
  asynchronously (e.g. to handle non-blocking I/O without explicit
  callbacks), and also supports algorithms on lazy-computed infinite
  sequences and other uses.

Compare with other's answer:

In my opinion, the resumed later part is a core difference, just like @Twinkle's.

Although many fields of the document are still work in progress, however, this part is similar to most answer, except @Nan Xiao 's

Coroutines, on the other hand, are collaborative: at any given time, a
  program with coroutines is running only one of its coroutines, and
  this running coroutine suspends its execution only when it explicitly
  requests to be suspended.

Since it's quoted from Program in Lua, maybe it's language related(not familiar with Lua currently), not all document mentioned the only one part.

The relation with concurrent:

There is an "Execution" part of the Coroutines (C++20).Too long to quote here.

Besides the detail, there are several states.

When a coroutine begins execution
When a coroutine reaches a suspension point
When a coroutine reaches the co_return statement
If the coroutine ends with an uncaught exception
When the coroutine state is destroyed either because it terminated via co_return or uncaught exception, or because it was destroyed via its handle

as the comment from @Adam Arold under @user217714's answer. It's concurrency.

But it's different from multithreading.
from std::thread

Threads allow multiple functions to execute concurrently.
  Threads begin execution immediately upon construction of the
  associated thread object (pending any OS scheduling delays), starting
  at the top-level function provided as a constructor argument. The
  return value of the top-level function is ignored and if it terminates
  by throwing an exception, std::terminate is called. The top-level
  function may communicate its return value or an exception to the
  caller via std::promise or by modifying shared variables (which may
  require synchronization, see std::mutex and std::atomic)

Since it's concurrency, it works like multithreading especially when waiting is unavoidable(from the OS perspective), that's also why it's confusing.


问:
listview in android
I have a list view in which I show data. When I click on a row of the list view, I want to display data for that row from web services. How do I do that?</p>

答:
```<code>ListView lv = getListView();
lv.setTextFilterEnabled(true);

lv.setOnItemClickListener(new OnItemClickListener() {
  public void onItemClick(AdapterView<?> parent, View view,
      int position, long id) {
    // When clicked, show a toast with the TextView text
    Toast.makeText(getApplicationContext(), ((TextView) view).getText(),
        Toast.LENGTH_SHORT).show();
  }
});
</code>```

Title: listview in android


问:
Print multiple row outputs in csv file
Suppose

```<code>A='First'
B='Random'
C='Degree'
D='Largest'

A='Second'
B='Odd'
C='Inclined'
D='Maximum'

A='Third'
B='Even'
C='Steep'
D='Smallest'

A='Fourth'
B='Prime'
C='Gradient'
D='Minimum'

c = ['Group', 'Number', 'Angle', 'Max value']

df = pd.DataFrame([[A, B, C, D]], columns=c)
print (df)

#to csv
df.to_csv('Output.csv', encoding='utf-8', index=False)

</code>```

Actual Output:

It is showing only the last output, instead of each and every value. Like this if there are N values, the csv  must store all the N values one below each other

```<code>Group  Number Angle    Max Value
Fourth Prime  Gradient Minimum
</code>```

Expected Output:

答:
You are overwriting your A B C D variables each time you re-define them. You should add them to a nested list or use a loop:

```<code>data = [
    ['First', 'Random', 'Degree', 'Largest'],
    ['Second', 'Odd', 'Inclined', 'Maximum'],
    ['Third', 'Even', 'Steep', 'Smallest'],
    ['Fourth', 'Prime', 'Gradient', 'Minimum']
]

df = pd.DataFrame(data, columns=c)
</code>```

Or....

```<code>A = ['First', 'Random', 'Degree', 'Largest']
B = ['Second', 'Odd', 'Inclined', 'Maximum']
C = ['Third', 'Even', 'Steep', 'Smallest']
D = ['Fourth', 'Prime', 'Gradient', 'Minimum']

df = pd.DataFrame([A, B, C, D], columns=c]
</code>```

Title: Print multiple row outputs in csv file

Body:
Suppose

A='First'
B='Random'
C='Degree'
D='Largest'

A='Second'
B='Odd'
C='Inclined'
D='Maximum'

A='Third'
B='Even'
C='Steep'
D='Smallest'

A='Fourth'
B='Prime'
C='Gradient'
D='Minimum'

c = ['Group', 'Number', 'Angle', 'Max value']

df = pd.DataFrame([[A, B, C, D]], columns=c)
print (df)

#to csv
df.to_csv('Output.csv', encoding='utf-8', index=False)

Actual Output:

It is showing only the last output, instead of each and every value. Like this if there are N values, the csv  must store all the N values one below each other

Group  Number Angle    Max Value
Fourth Prime  Gradient Minimum

Expected Output:

Body:
You are overwriting your A B C D variables each time you re-define them. You should add them to a nested list or use a loop:

data = [
    ['First', 'Random', 'Degree', 'Largest'],
    ['Second', 'Odd', 'Inclined', 'Maximum'],
    ['Third', 'Even', 'Steep', 'Smallest'],
    ['Fourth', 'Prime', 'Gradient', 'Minimum']
]

df = pd.DataFrame(data, columns=c)

Or....

A = ['First', 'Random', 'Degree', 'Largest']
B = ['Second', 'Odd', 'Inclined', 'Maximum']
C = ['Third', 'Even', 'Steep', 'Smallest']
D = ['Fourth', 'Prime', 'Gradient', 'Minimum']

df = pd.DataFrame([A, B, C, D], columns=c]


问:
increase swagger requestTimeout
is there anyway that can help me increase the timeout of the swagger request that i issue to my RestAPI using " Try it out" of swagger ?

i roamed the internet and disn't find something usefull, and i tried to add things to my yml conf files, but i didn't know what to write

i expected to find something like this maybe :

```<code>swagger.timeout=5000
</code>```

i have a spring boot application using swagger in order to test my webservices in a restController. i have a treatement that takes about 30 seconds, the thing that makes swagger throw a 500 timeout error for me.

thanks !

答:
solved by adding this to ZUUL's (API Gateway) </p>

```<code>ribbon:
ReadTimeout: 120000
ConnectTimeout: 120000
</code>```

Title: increase swagger requestTimeout

Body:
is there anyway that can help me increase the timeout of the swagger request that i issue to my RestAPI using " Try it out" of swagger ?

i roamed the internet and disn't find something usefull, and i tried to add things to my yml conf files, but i didn't know what to write

i expected to find something like this maybe :

swagger.timeout=5000

i have a spring boot application using swagger in order to test my webservices in a restController. i have a treatement that takes about 30 seconds, the thing that makes swagger throw a 500 timeout error for me.

thanks !

Body:
solved by adding this to ZUUL's (API Gateway)

ribbon:
ReadTimeout: 120000
ConnectTimeout: 120000


问:
SQL Select all columns from two or more Unrelated tables
```<code>Table A
    A1 A2
1   1   2
2   2   2
3   1   3

Table B
  A1  A2
1  3   3
2  1   4
3  4   1
4  5   0

Expected Result
Table C
   A1   A2
1  1    2
2  2    2
3  1    3
4  3    3
5  1    4
6  4    1
7  5    0
</code>```

答:
use union all</p>

```<code>select a1,a2 from tbalea
union all
select a1,a2 from tbleb
</code>```

Body:
use union all

select a1,a2 from tbalea
union all
select a1,a2 from tbleb


问:
How can I create a "personality-test" using Rails?
This is both a request for existing open-source modules, as well as the "architecture".  The data-gathering part (asking questions) looks like can be done using surveyor or wizard gems.

The part I need help on is...how do you "weight" or "score" the answers to come up with the "personality"?  For example, Myers-Briggs type tests ask multiple questions and then describe one of 16 personalities.

I want to limit my outcomes to four, but I'm not sure how.  The standard "If you scored 10-16, you're a rockstar; if you scored 5-9, go home" I don't think quite works this same way?

This is more of a "design" question, so if there's a better place I can ask it, let me know, but it feels that people may know programmatically how in rails to do this kind of simplified expert-system.

答:
You have four personality types, and each user's test creates a rank for each of these types.  (e.g. By the end of the test, the user will have a score of 50 for Type-A, a score for 86 for Type-B, a score of 34 for Type-C, and a score of 60 for Type-D)  The user is designated by whichever personality type has the highest score.  (e.g. Type-B)

Each question in the personality test is multiple choice.  Every answer contributes a certain amount to one or more of the personality types.  (e.g. On question 1, an answer of "D" will contribute 5 points to Type-A, 3 points to Type-B, and 0 points to Type-C and Type-D.)

Each answer for each question would have a 4-digit value attribute, indicating how the math on your back end should be carried out.  For instance:

```<code><input type="radio" name="question_one" value="5400" />
<input type="radio" name="question_one" value="3211" />
<input type="radio" name="question_one" value="5608" />
<input type="radio" name="question_one" value="9006" />
</code>```

Here's how you might handle the back end in Ruby on Rails.  First, you have a User object named @user, which has four fields, type_a, type_b, type_c, type_d, indicating how well the User aligns with each of the four personality types.  In your User model, include a method like this:

```<code>def process_answer(value)
  self.type_a += value[0].chr.to_i
  self.type_b += value[1].chr.to_i
  self.type_c += value[2].chr.to_i
  self.type_d += value[3].chr.to_i
</code>```

In your controller, pass the form data to your User instance:

```<code>  @user.process_answer(params[:question_one])
</code>```

If the user selects the second option for question_one (corresponding to a value of "3211"), then his personality profile will increase 3 pts for type-A, 2 pts for type-B, 1 pt for type-C, and 1 pt for type-D.

Body:
You have four personality types, and each user's test creates a rank for each of these types.  (e.g. By the end of the test, the user will have a score of 50 for Type-A, a score for 86 for Type-B, a score of 34 for Type-C, and a score of 60 for Type-D)  The user is designated by whichever personality type has the highest score.  (e.g. Type-B)

Each question in the personality test is multiple choice.  Every answer contributes a certain amount to one or more of the personality types.  (e.g. On question 1, an answer of "D" will contribute 5 points to Type-A, 3 points to Type-B, and 0 points to Type-C and Type-D.)

Each answer for each question would have a 4-digit value attribute, indicating how the math on your back end should be carried out.  For instance:

<input type="radio" name="question_one" value="5400" />
<input type="radio" name="question_one" value="3211" />
<input type="radio" name="question_one" value="5608" />
<input type="radio" name="question_one" value="9006" />

Here's how you might handle the back end in Ruby on Rails.  First, you have a User object named @user, which has four fields, type_a, type_b, type_c, type_d, indicating how well the User aligns with each of the four personality types.  In your User model, include a method like this:

def process_answer(value)
  self.type_a += value[0].chr.to_i
  self.type_b += value[1].chr.to_i
  self.type_c += value[2].chr.to_i
  self.type_d += value[3].chr.to_i

In your controller, pass the form data to your User instance:

  @user.process_answer(params[:question_one])

If the user selects the second option for question_one (corresponding to a value of "3211"), then his personality profile will increase 3 pts for type-A, 2 pts for type-B, 1 pt for type-C, and 1 pt for type-D.


Title: How to transpose row values (time series) into column values in PySpark?

Body:
I have a Spark DataFrame whose row values I would like to transform into a single column. It is time data (columns = hours). (Example see below).

The DataFrame looks like this so far:

>>> newdf.show(2)
+----------+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+------+------+------+------+------+------+------+------+------+------+-------+------+------+------+
|Date      |temp0|temp1|temp2|temp3|temp4|temp5|temp6|temp7|temp8|temp9|temp10|temp11|temp12|temp13|temp14|temp15|temp16|temp17|temp18|temp19|temp20 |temp21|temp22|temp23|
+----------+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+------+------+------+------+------+------+------+------+------+------+-------+------+------+------+
|2012-01-07|25   |29   |15   |null |null |null |4    |39   |128  |65   |3     |3     |7     |1     |4     |1     |4     |3     |4     |6     |1      |3     |1     |2     |
|2012-01-08|16   |15   |8    |null |null |null |4    |39   |128  |65   |3     |3     |7     |1     |4     |1     |4     |3     |4     |6     |1      |3     |1     |2     |
+----------+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+------+------+------+------+------+------+------+------+------+------+-------+------+------+------+

Target DataFrame should look like this:

+---------------------+-------------+
| Date                | temperature |
+---------------------+-------------+
| 2012-01-07 00:00:00 | 25          |
| 2012-01-07 01:00:00 | 29          |
| 2012-01-07 02:00:00 | 15          |
| 2012-01-07 03:00:00 | null        |
| ....                | ....        |
| 2012-01-08 00:00:00 | 16          |
| 2012-01-08 01:00:00 | 15          |
+---------------------+-------------+

Is this possible with PySpark? I've already tested the pivot function, but it couldn't give me the structure I wanted. Each line should correspond to one hour.

What other possibilities of transposing are there?

Body:
Step 1: Creating the dataframe,

import pyspark.sql.functions as F

df = sql.createDataFrame([
('2012-01-07',25   ,29   ,15   ,7 ,7 ,7 ,4    ,39   ,128  ,65   ,3     ,3     ,7     ,1     ,4     ,1     ,4     ,3     ,4     ,6     ,1      ,3     ,1     ,2     ),\
('2012-01-08',16   ,15   ,8    ,7 ,7 ,7 ,4    ,39   ,128  ,65   ,3     ,3     ,7     ,1     ,4     ,1     ,4     ,3     ,4     ,6     ,1      ,3     ,1     ,2     ),\
],[
'Date','temp0','temp1','temp2','temp3','temp4','temp5','temp6','temp7','temp8','temp9','temp10','temp11','temp12','temp13','temp14','temp15','temp16','temp17','temp18','temp19','temp20' ,'temp21','temp22','temp23'
])

Step 2: Explode the columns and merge to create timestamp

def _combine(x,y):
    d = str(x) + ' {}:00:00'.format(y)
    return d

combine = F.udf(lambda x,y: _combine(x,y))

cols, dtypes = zip(*((c, t) for (c, t) in df.dtypes if c not in ['Date']))

kvs = F.explode(F.array([
      F.struct(F.lit(c).alias("key"), F.col(c).alias("val")) for c in cols])).alias("kvs")

df = df.select(['Date'] + [kvs])\
       .select(['Date'] + ["kvs.key", F.col("kvs.val").alias('temperature')])\
       .withColumn('key', F.regexp_replace('key', 'temp', ''))\
       .withColumn('Date', combine('Date','key').cast('timestamp'))\
       .drop('key')
df.show()

This gives output as,

+-------------------+-----------+
|               Date|temperature|
+-------------------+-----------+
|2012-01-07 00:00:00|         25|
|2012-01-07 01:00:00|         29|
|2012-01-07 02:00:00|         15|
|2012-01-07 03:00:00|          7|
|2012-01-07 04:00:00|          7|
|2012-01-07 05:00:00|          7|
|2012-01-07 06:00:00|          4|
|2012-01-07 07:00:00|         39|
|2012-01-07 08:00:00|        128|
|2012-01-07 09:00:00|         65|
|2012-01-07 10:00:00|          3|
|2012-01-07 11:00:00|          3|
|2012-01-07 12:00:00|          7|
|2012-01-07 13:00:00|          1|
|2012-01-07 14:00:00|          4|
|2012-01-07 15:00:00|          1|
|2012-01-07 16:00:00|          4|
|2012-01-07 17:00:00|          3|
|2012-01-07 18:00:00|          4|
|2012-01-07 19:00:00|          6|
|2012-01-07 20:00:00|          1|
|2012-01-07 21:00:00|          3|
|2012-01-07 22:00:00|          1|
|2012-01-07 23:00:00|          2|
|2012-01-08 00:00:00|         16|
|2012-01-08 01:00:00|         15|
|2012-01-08 02:00:00|          8|
|2012-01-08 03:00:00|          7|
|2012-01-08 04:00:00|          7|
|2012-01-08 05:00:00|          7|
|2012-01-08 06:00:00|          4|
|2012-01-08 07:00:00|         39|
|2012-01-08 08:00:00|        128|
|2012-01-08 09:00:00|         65|
|2012-01-08 10:00:00|          3|
|2012-01-08 11:00:00|          3|
|2012-01-08 12:00:00|          7|
|2012-01-08 13:00:00|          1|
|2012-01-08 14:00:00|          4|
|2012-01-08 15:00:00|          1|
|2012-01-08 16:00:00|          4|
|2012-01-08 17:00:00|          3|
|2012-01-08 18:00:00|          4|
|2012-01-08 19:00:00|          6|
|2012-01-08 20:00:00|          1|
|2012-01-08 21:00:00|          3|
|2012-01-08 22:00:00|          1|
|2012-01-08 23:00:00|          2|
+-------------------+-----------+

EDIT: In case of two columns,

cols_1, dtypes = zip(*((c, t) for (c, t) in df.dtypes if 'temp' in c))
cols_2, dtypes = zip(*((c, t) for (c, t) in df.dtypes if 'wind' in c))

kvs = F.explode(F.array([
      F.struct(F.lit(c1).alias("key1"), F.col(c1).alias("val1"), F.lit(c2).alias("key2"), F.col(c2).alias("val2"))\
                         for c1,c2 in zip(cols_1,cols_2)\
                        ] )).alias("kvs")
df = df.select(['Date'] + [kvs]).select(['Date'] + ["kvs.key1", F.col("kvs.val1").alias('temperature'),
                                                    "kvs.key2", F.col("kvs.val2").alias("wind")])


问:
Select column name per row for max value in PySpark
I have a dataframe like this, shown only two columns however there are many columns in original dataframe

```<code>data = [(("ID1", 3, 5)), (("ID2", 4, 12)), (("ID3", 8, 3))]
df = spark.createDataFrame(data, ["ID", "colA", "colB"])
df.show()

+---+----+----+
| ID|colA|colB|
+---+----+----+
|ID1|   3|   5|
|ID2|   4|  12|
|ID3|   8|   3|
+---+----+----+
</code>```

I want to extract the name of the column per row, which has the max value. Hence the expected output is like this

```<code>+---+----+----+-------+
| ID|colA|colB|Max_col|
+---+----+----+-------+
|ID1|   3|   5|   colB|
|ID2|   4|  12|   colB|
|ID3|   8|   3|   colA|
+---+----+----+-------+
</code>```

In case of tie, where colA and colB have same value, choose the first column.

How can I achieve this in pyspark

答:
Extending what Suresh has done.... returning appropriate the column name</p>

```<code>from pyspark.sql import functions as f
from pyspark.sql.types import IntegerType, StringType

import numpy as np

data = [(("ID1", 3, 5,78)), (("ID2", 4, 12,45)), (("ID3", 68, 3,67))]
df = spark.createDataFrame(data, ["ID", "colA", "colB","colC"])
df.show()

cols = df.columns
maxcol = f.udf(lambda row: cols[row.index(max(row)) +1], StringType())

maxDF = df.withColumn("Max_col", maxcol(f.struct([df[x] for x in df.columns[1:]])))
maxDF.show(truncate=False)

+---+----+----+----+------+
|ID |colA|colB|colC|Max_col|
+---+----+----+----+------+
|ID1|3   |5   |78  |colC  |
|ID2|4   |12  |45  |colC  |
|ID3|68  |3   |67  |colA  |
+---+----+----+----+------+
</code>```

Body:
I have a dataframe like this, shown only two columns however there are many columns in original dataframe

data = [(("ID1", 3, 5)), (("ID2", 4, 12)), (("ID3", 8, 3))]
df = spark.createDataFrame(data, ["ID", "colA", "colB"])
df.show()

+---+----+----+
| ID|colA|colB|
+---+----+----+
|ID1|   3|   5|
|ID2|   4|  12|
|ID3|   8|   3|
+---+----+----+

I want to extract the name of the column per row, which has the max value. Hence the expected output is like this

+---+----+----+-------+
| ID|colA|colB|Max_col|
+---+----+----+-------+
|ID1|   3|   5|   colB|
|ID2|   4|  12|   colB|
|ID3|   8|   3|   colA|
+---+----+----+-------+

In case of tie, where colA and colB have same value, choose the first column.

How can I achieve this in pyspark

Body:
Extending what Suresh has done.... returning appropriate the column name

from pyspark.sql import functions as f
from pyspark.sql.types import IntegerType, StringType

import numpy as np

data = [(("ID1", 3, 5,78)), (("ID2", 4, 12,45)), (("ID3", 68, 3,67))]
df = spark.createDataFrame(data, ["ID", "colA", "colB","colC"])
df.show()

cols = df.columns
maxcol = f.udf(lambda row: cols[row.index(max(row)) +1], StringType())

maxDF = df.withColumn("Max_col", maxcol(f.struct([df[x] for x in df.columns[1:]])))
maxDF.show(truncate=False)

+---+----+----+----+------+
|ID |colA|colB|colC|Max_col|
+---+----+----+----+------+
|ID1|3   |5   |78  |colC  |
|ID2|4   |12  |45  |colC  |
|ID3|68  |3   |67  |colA  |
+---+----+----+----+------+


答:
I'm actually going to recommend against doing the update after deleting records.  Instead, just use ROW_NUMBER to generate the effective position of each record, e.g.

```<code>SELECT
    id,
    name,
    ROW_NUMBER() OVER (ORDER BY position) position
FROM yourTable;
</code>```

Deleting rows will not change the relative order which exists between all records in the table.

If you are not using MySQL 8+, then you can easily enough simulate row number using user variables.

Title: MySQL correct statement for "update all rows where column > number"?

Body:
I have a table called 'images' with a few rows of image names and a value for their position (order which they will appear on site).

id      name       position
1       dog.png    3
2       cat.png    1
3       snake.png  2

What im trying to do is decrement all position column values if they are above a specific value.

For example, if 'cat' is to be deleted, i want to find all rows with a position higher (would be snake and dog) and decrement their position values by 1. I need an SQL statement for

"update all 'position' columns where 'position' > 'value'"

I know i need to get the 'position' of the image to be deleted, and set this to 'value' before updating the rest of the rows with higher position columns. But, I'm not sure how to create the SQL statement for the rest of:

"update all 'position' columns where 'position' > 'value'"

I'm not sure whether i would need one or two queries for it.

Body:
I'm actually going to recommend against doing the update after deleting records.  Instead, just use ROW_NUMBER to generate the effective position of each record, e.g.

SELECT
    id,
    name,
    ROW_NUMBER() OVER (ORDER BY position) position
FROM yourTable;

Deleting rows will not change the relative order which exists between all records in the table.

If you are not using MySQL 8+, then you can easily enough simulate row number using user variables.


问:
Copy DataFrame with NaN values in Column
I have a DataFrame that looks like the example below.

# define DataFrame for reproducability

df = pd.DataFrame({'date': ['2019-05-06', '2019-05-07', '2019-05-07', '2019-05-09', '2019-05-10', '2019-05-11'],
                   'Identifier': [1, 1, 1, 1, 1, 1],
                   'B': [2.4, 3.9, 3.9, 4.3, 2.5, 3.14],
                   'C': [0.214, 0.985, 0.985, 0.839, 0.555, 0.159],
                   'Name': [np.nan, "CD", "AD", np.nan, np.nan, np.nan]})

print(df)

    date        Identifier  B       C       Name
0   2019-05-06  1           2.40    0.214   NaN
1   2019-05-07  1           3.90    0.985   CD
2   2019-05-07  1           3.90    0.985   AD
3   2019-05-09  1           4.30    0.839   NaN
4   2019-05-10  1           2.50    0.555   NaN
5   2019-05-11  1           3.14    0.159   NaN
```

<p>What can be seen is that, for a given identifier, there <em>can</em> be more than one name. However, the name is only appended to the DataFrame once at a single date. What I need is to basically forward <strong>and backward</strong> fill the names at every date. Currently, I have a solution that works, but that is extremely slow for the full dataframe that I am working on. The code is shown below</p>

<pre class="lang-py prettyprint-override"><code>final_df = pd.DataFrame()

for i in df.Identifier.unique():
    # select the current identifier
    identifier_df = df.loc[df.Identifier == i]
    # allow a given identifier to have different names
    for n in df.Name.unique():
        if pd.isna(n):
            continue
        else:
            intermediate = identifier_df.copy()
            intermediate.loc[:,"Name"] = np.repeat(n, len(intermediate))
            final_df = final_df.append(intermediate)

final_df = final_df.drop_duplicates()
</code>```

Note that the loop through identifiers is required for my full DataFrame. In this instance, however, it seems rather pointless. This code, nevertheless, results in the following DataFrame (which is how I would like the output to be):

print(final_df)

    date        Identifier  B       C       Name
0   2019-05-06  1           2.40    0.214   CD
1   2019-05-07  1           3.90    0.985   CD
3   2019-05-09  1           4.30    0.839   CD
4   2019-05-10  1           2.50    0.555   CD
5   2019-05-11  1           3.14    0.159   CD
0   2019-05-06  1           2.40    0.214   AD
1   2019-05-07  1           3.90    0.985   AD
3   2019-05-09  1           4.30    0.839   AD
4   2019-05-10  1           2.50    0.555   AD
5   2019-05-11  1           3.14    0.159   AD
```

Is there any way to perform this operation with a groupby, or is there any other way to make it faster?

Thanks!

答:
One way to speed up this code by a significant amount is by appending the intermediate DataFrames to a list first, and concatenate the list of DataFrames in one final step using pd.concat().

This would make the code look as follows:

```<code>final_df = []

for i in df.Identifier.unique():
    # select the current identifier
    identifier_df = df.loc[df.Identifier == i]
    # allow a given identifier to have different names
    for n in df.Name.unique():
        if pd.isna(n):
            continue
        else:
            intermediate = identifier_df.copy()
            intermediate.loc[:,"Name"] = np.repeat(n, len(intermediate))
            final_df.append(intermediate)

final_df = pd.concat(final_df).drop_duplicates()
</code>```

This simple solution made me decrease execution time by a significant margin. Hopefully it helps someone else as well.

Body:
I have a DataFrame that looks like the example below.

# define DataFrame for reproducability

df = pd.DataFrame({'date': ['2019-05-06', '2019-05-07', '2019-05-07', '2019-05-09', '2019-05-10', '2019-05-11'],
                   'Identifier': [1, 1, 1, 1, 1, 1],
                   'B': [2.4, 3.9, 3.9, 4.3, 2.5, 3.14],
                   'C': [0.214, 0.985, 0.985, 0.839, 0.555, 0.159],
                   'Name': [np.nan, "CD", "AD", np.nan, np.nan, np.nan]})

print(df)

    date        Identifier  B       C       Name
0   2019-05-06  1           2.40    0.214   NaN
1   2019-05-07  1           3.90    0.985   CD
2   2019-05-07  1           3.90    0.985   AD
3   2019-05-09  1           4.30    0.839   NaN
4   2019-05-10  1           2.50    0.555   NaN
5   2019-05-11  1           3.14    0.159   NaN

What can be seen is that, for a given identifier, there can be more than one name. However, the name is only appended to the DataFrame once at a single date. What I need is to basically forward and backward fill the names at every date. Currently, I have a solution that works, but that is extremely slow for the full dataframe that I am working on. The code is shown below

final_df = pd.DataFrame()

for i in df.Identifier.unique():
    # select the current identifier
    identifier_df = df.loc[df.Identifier == i]
    # allow a given identifier to have different names
    for n in df.Name.unique():
        if pd.isna(n):
            continue
        else:
            intermediate = identifier_df.copy()
            intermediate.loc[:,"Name"] = np.repeat(n, len(intermediate))
            final_df = final_df.append(intermediate)

final_df = final_df.drop_duplicates()

Note that the loop through identifiers is required for my full DataFrame. In this instance, however, it seems rather pointless. This code, nevertheless, results in the following DataFrame (which is how I would like the output to be):

print(final_df)

    date        Identifier  B       C       Name
0   2019-05-06  1           2.40    0.214   CD
1   2019-05-07  1           3.90    0.985   CD
3   2019-05-09  1           4.30    0.839   CD
4   2019-05-10  1           2.50    0.555   CD
5   2019-05-11  1           3.14    0.159   CD
0   2019-05-06  1           2.40    0.214   AD
1   2019-05-07  1           3.90    0.985   AD
3   2019-05-09  1           4.30    0.839   AD
4   2019-05-10  1           2.50    0.555   AD
5   2019-05-11  1           3.14    0.159   AD

Is there any way to perform this operation with a groupby, or is there any other way to make it faster?

Thanks!

Body:
One way to speed up this code by a significant amount is by appending the intermediate DataFrames to a list first, and concatenate the list of DataFrames in one final step using pd.concat().

This would make the code look as follows:

final_df = []

for i in df.Identifier.unique():
    # select the current identifier
    identifier_df = df.loc[df.Identifier == i]
    # allow a given identifier to have different names
    for n in df.Name.unique():
        if pd.isna(n):
            continue
        else:
            intermediate = identifier_df.copy()
            intermediate.loc[:,"Name"] = np.repeat(n, len(intermediate))
            final_df.append(intermediate)

final_df = pd.concat(final_df).drop_duplicates()

This simple solution made me decrease execution time by a significant margin. Hopefully it helps someone else as well.


问:
OpenLayers: How to refresh map after changing the vector layer
In OpenLayers, I have a cluster strategy to limit how many features/points the user sees on the map. When the user is fully zoomed in however, I want to turn off the clustering strategy so that all features are shown. To do this I am catching the zoom event like this:

```<code>map.events.register("zoomend", this, function (e) {
    if (map.getZoom() === this.mapMaxZoom) {
        // Don't cluster at this level. No matter what.
        this.vector.strategies[0].threshold = 1000;
        console.log("setting the clustering strategy to 1000");
    }
});
</code>```

This kinda works, but I don't see the new clustering applied - I have to zoom back out again to see the clustering change to a threshold of 1000 (and thus show all features). I need some way to force openlayers to refresh. I've tried calling map.redraw() but that doesn't help. Any ideas?

答:
In OL3 refresh it by calling layer's source refresh() method

layer.getSource().refresh()

Body:
In OpenLayers, I have a cluster strategy to limit how many features/points the user sees on the map. When the user is fully zoomed in however, I want to turn off the clustering strategy so that all features are shown. To do this I am catching the zoom event like this:

map.events.register("zoomend", this, function (e) {
    if (map.getZoom() === this.mapMaxZoom) {
        // Don't cluster at this level. No matter what.
        this.vector.strategies[0].threshold = 1000;
        console.log("setting the clustering strategy to 1000");
    }
});

This kinda works, but I don't see the new clustering applied - I have to zoom back out again to see the clustering change to a threshold of 1000 (and thus show all features). I need some way to force openlayers to refresh. I've tried calling map.redraw() but that doesn't help. Any ideas?


问:
Django rest api DRF - ViewSet hide a field from get but include for put
I have a field that I need to hide from a get put it needs to be there for a put in a Viewset, how would I achieve this?

my serialiser is as the below, the field stores data as JSON so I need to load it as JSON to perform a get. but having the original field (routing_data) there on a get will cause a 500 error, so I need to hide it from get. but when I'm using a put, it will be this field I put into.

Thanks

serializers.py

```<code>class MonitoringSerializerRoutingTable(serializers.ModelSerializer):
    hostname = serializers.ReadOnlyField(source='device.hostname', )
    site_id = serializers.ReadOnlyField(source='device.site_id', )
    rt = serializers.SerializerMethodField(source='routing_data',)
    use = serializers.ReadOnlyField(source='device_use.use', )

    def get_rt(self, instance):
        try:
            return json.loads(instance.routing_data)
        except:
            return instance.routing_data

    class Meta:
        model = DeviceData
        fields = ('id','site_id','device_id','hostname','use', 'timestamp', 'rt','routing_data')
</code>```

views.py

```<code>class MonitoringRoutingTableUpload(viewsets.ModelViewSet):
    queryset = DeviceData.objects.select_related('device','device_use').order_by('monitoring_order')
    serializer_class = MonitoringSerializerRoutingTable
    permission_classes = (IsAdminUser,)
    filter_class = DeviceData
    filter_backends = (filters.SearchFilter,)
    search_fields = ('device__hostname','device_use__use')
</code>```

EDIT
the update serialiser doesn't seem to be updating the data

```<code>class MonitoringRoutingTableUpload(viewsets.ModelViewSet):
    queryset = DeviceData.objects.select_related('device','device_use').order_by('monitoring_order')
    permission_classes = (IsAdminUser,)
    filter_class = DeviceData
    filter_backends = (filters.SearchFilter,)
    search_fields = ('device__hostname','device_use__use')
    def get_serializer_class(self):
        serializers = {
            create: MonitoringCreateSerializer,
            update: MonitoringCreateSerializer,
            list: MonitoringSerializerRoutingTable,
            retrieve: MonitoringSerializerRoutingTable,
        }
        return serializers.get(self.action)
</code>```

serialiezr.py

```<code>class MonitoringSerializerRoutingTable(serializers.ModelSerializer):
    hostname = serializers.ReadOnlyField(source='device.hostname', )
    site_id = serializers.ReadOnlyField(source='device.site_id', )
    rt = serializers.SerializerMethodField(source='routing_data',)
    use = serializers.ReadOnlyField(source='device_use.use', )

    def get_rt(self, instance):
        try:
            return json.loads(instance.routing_data)
        except:
            return instance.routing_data

    class Meta:
        model = DeviceData
        fields = ('id','site_id','device_id','hostname','use', 'timestamp', 'rt')

class MonitoringCreateSerializer(serializers.ModelSerializer):

    class Meta:
        model = DeviceData
        fields = ('id','site_id','device_id','routing_data')
</code>```

PUT request

```<code>URL: http://10.66.193.200:8100/api/rt_upload/9/
data: {"routing_data": "[{'subnet': '10.10.0.0/16', 'age': '6w3d', 'next_hop': '10.20.0.0/16'}, {'subnet': '10.30.0.0/16', 'age': '6w3d', 'next_hop': '10.40.0.0/16'}, {'subnet': '10.50.0.0/16', 'age': '6w3d'...}]"}
</code>```

response from postman:

```<code>{
    "id": 9,
    "site_id": 118,
    "device_id": 460,
    "hostname": "EDGE",
    "use": "Remote Site Connectivity",
    "timestamp": "2019-05-31T10:12:58.300252",
    "rt": ""
}
</code>```

答:
In this case, you can use a different serializer for get and for put/post. Create a new serializer with the fields you need, then drop the serializer_class attribute and override the get_serializer_class  in the view. Something like this:

```<code>class MonitoringRoutingTableUpload(viewsets.ModelViewSet):
    ...
    def get_serializer_class(self):
        serializers = {
            create: MonitoringCreateSerializer,
            update: MonitoringCreateSerializer,
            list: MonitoringSerializerRoutingTable,
            retrieve: MonitoringSerializerRoutingTable,
        }
        return serializers.get(self.action)
</code>```

Body:
I have a field that I need to hide from a get put it needs to be there for a put in a Viewset, how would I achieve this?

my serialiser is as the below, the field stores data as JSON so I need to load it as JSON to perform a get. but having the original field (routing_data) there on a get will cause a 500 error, so I need to hide it from get. but when I'm using a put, it will be this field I put into.

Thanks

serializers.py

class MonitoringSerializerRoutingTable(serializers.ModelSerializer):
    hostname = serializers.ReadOnlyField(source='device.hostname', )
    site_id = serializers.ReadOnlyField(source='device.site_id', )
    rt = serializers.SerializerMethodField(source='routing_data',)
    use = serializers.ReadOnlyField(source='device_use.use', )

    def get_rt(self, instance):
        try:
            return json.loads(instance.routing_data)
        except:
            return instance.routing_data

    class Meta:
        model = DeviceData
        fields = ('id','site_id','device_id','hostname','use', 'timestamp', 'rt','routing_data')

views.py

class MonitoringRoutingTableUpload(viewsets.ModelViewSet):
    queryset = DeviceData.objects.select_related('device','device_use').order_by('monitoring_order')
    serializer_class = MonitoringSerializerRoutingTable
    permission_classes = (IsAdminUser,)
    filter_class = DeviceData
    filter_backends = (filters.SearchFilter,)
    search_fields = ('device__hostname','device_use__use')

EDIT
the update serialiser doesn't seem to be updating the data

class MonitoringRoutingTableUpload(viewsets.ModelViewSet):
    queryset = DeviceData.objects.select_related('device','device_use').order_by('monitoring_order')
    permission_classes = (IsAdminUser,)
    filter_class = DeviceData
    filter_backends = (filters.SearchFilter,)
    search_fields = ('device__hostname','device_use__use')
    def get_serializer_class(self):
        serializers = {
            create: MonitoringCreateSerializer,
            update: MonitoringCreateSerializer,
            list: MonitoringSerializerRoutingTable,
            retrieve: MonitoringSerializerRoutingTable,
        }
        return serializers.get(self.action)

serialiezr.py

class MonitoringSerializerRoutingTable(serializers.ModelSerializer):
    hostname = serializers.ReadOnlyField(source='device.hostname', )
    site_id = serializers.ReadOnlyField(source='device.site_id', )
    rt = serializers.SerializerMethodField(source='routing_data',)
    use = serializers.ReadOnlyField(source='device_use.use', )

    def get_rt(self, instance):
        try:
            return json.loads(instance.routing_data)
        except:
            return instance.routing_data

    class Meta:
        model = DeviceData
        fields = ('id','site_id','device_id','hostname','use', 'timestamp', 'rt')

class MonitoringCreateSerializer(serializers.ModelSerializer):

    class Meta:
        model = DeviceData
        fields = ('id','site_id','device_id','routing_data')

PUT request

URL: http://10.66.193.200:8100/api/rt_upload/9/
data: {"routing_data": "[{'subnet': '10.10.0.0/16', 'age': '6w3d', 'next_hop': '10.20.0.0/16'}, {'subnet': '10.30.0.0/16', 'age': '6w3d', 'next_hop': '10.40.0.0/16'}, {'subnet': '10.50.0.0/16', 'age': '6w3d'...}]"}

response from postman:

{
    "id": 9,
    "site_id": 118,
    "device_id": 460,
    "hostname": "EDGE",
    "use": "Remote Site Connectivity",
    "timestamp": "2019-05-31T10:12:58.300252",
    "rt": ""
}

Body:
In this case, you can use a different serializer for get and for put/post. Create a new serializer with the fields you need, then drop the serializer_class attribute and override the get_serializer_class  in the view. Something like this:

class MonitoringRoutingTableUpload(viewsets.ModelViewSet):
    ...
    def get_serializer_class(self):
        serializers = {
            create: MonitoringCreateSerializer,
            update: MonitoringCreateSerializer,
            list: MonitoringSerializerRoutingTable,
            retrieve: MonitoringSerializerRoutingTable,
        }
        return serializers.get(self.action)