问:
Handling hardware back button in Ionic3 Vs Ionic4
Please find the below code for the Android hardware back button action in ionic3. As Ionic4 uses angular routing for navigation how the pop event will take place for the back button? If we want to pop to the last page we can use the following code this.navCtrl.goBack('/products');.
But how we can use it for the android hardware back button action in ionic4?

Ionic3 hardware back button action

this.platform.registerBackButtonAction(() => {
    let activePortal = this.ionicApp._loadingPortal.getActive() ||
        this.ionicApp._modalPortal.getActive() ||
        this.ionicApp._toastPortal.getActive() ||
        this.ionicApp._overlayPortal.getActive();
    if (activePortal) {
        activePortal.dismiss();
    } else {
        if (this.nav.canGoBack()) {
            ***this.nav.pop();***
        } else {
            if (this.nav.getActive().name === 'LoginPage') {
                this.platform.exitApp();
            } else {
                this.generic.showAlert("Exit", "Do you want to exit the app?", this.onYesHandler, this.onNoHandler, "backPress");
            }
        }
    }
});
```

答:
This is my working code on the Ionic 5 Project.
using Cordova/PhoneGap

import {Component} from '@angular/core';
import {ToastService} from './_services/toast.service';

@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html',
  styleUrls: ['app.component.scss']
})
export class AppComponent {
  constructor(private toastCtrl: ToastService) {
    this.backButton();
  }
  backButton() {
      const that = this;
      let lastTimeBackPress = 0;
      const timePeriodToExit = 2000;
      function onBackKeyDown(e) {
          e.preventDefault();
          e.stopPropagation();
          if (new Date().getTime() - lastTimeBackPress < timePeriodToExit) {
              navigator.app.exitApp();
          } else {
              that.presentToast();
              lastTimeBackPress = new Date().getTime();
          }
      }
      document.addEventListener('backbutton', onBackKeyDown, false);
  }
  presentToast() {
    const toast = this.toastCtrl.create({
      message: "Press again to exit",
      duration: 3000,
      position: "middle"
    });
  toast.present();
  }
}```


来源: stackexchange

ContentLicense: CC BY-SA 4.0

Title: Why is my svg crisp when imported, but blurry as a cursor?

Body:
I was trying to use the following svg image as a cursor for my document:

<svg height="128" width="128" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 144 135.92"><defs></defs><g id="Layer_2" data-name="Layer 2"><g id="Layer_1-2" data-name="Layer 1"><path class="cls-1" d="M72,135.92,52.25,103c-.54-.91-.59-7.11.32-8.23l1-1.16,8.06,1.18V78.2H42.18l1.17,7.53-.81.93c-1.47,1.69-7.86.93-8.27.75L0,68,34,48.6c.6-.29,6.9-.9,8.34.48l1,1-1.18,7.61H61.63V41.1l-8.1,1.21-1-1.17c-.91-1.11-.86-7.32-.33-8.21L72,0,91.75,32.91c.5.85.68,7-.3,8.23l-1,1.17-8-1.19V57.7h19.36L100.61,50l1.08-1c1.41-1.27,7.62-.73,8-.54L144,68,110,87.3c-.65.3-6.95,1-8.42-.54l-.91-1,1.17-7.55H82.37V94.8l8.12-1.19,1,1.16c1,1.22.8,7.38.31,8.21Zm-14.82-35L72,125.58l14.82-24.7c0-.36,0-.85,0-1.35L77.05,101V73h31l-1.45,9.37H108L133.24,68l-25.3-14.4h-1.38L108,63H77.14V35l9.67,1.44c0-.51,0-1,0-1.36L72,10.34,57.18,35c0,.36,0,.85,0,1.36L67,34.92V63H36l1.45-9.4H36L10.76,68l25.3,14.37h1.38L36,72.88H66.91v28.06L57.2,99.52C57.19,100,57.18,100.52,57.18,100.89Z"/></g></g></svg>
<svg height="16" width="16" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 144 135.92"><defs></defs><g id="Layer_2" data-name="Layer 2"><g id="Layer_1-2" data-name="Layer 1"><path class="cls-1" d="M72,135.92,52.25,103c-.54-.91-.59-7.11.32-8.23l1-1.16,8.06,1.18V78.2H42.18l1.17,7.53-.81.93c-1.47,1.69-7.86.93-8.27.75L0,68,34,48.6c.6-.29,6.9-.9,8.34.48l1,1-1.18,7.61H61.63V41.1l-8.1,1.21-1-1.17c-.91-1.11-.86-7.32-.33-8.21L72,0,91.75,32.91c.5.85.68,7-.3,8.23l-1,1.17-8-1.19V57.7h19.36L100.61,50l1.08-1c1.41-1.27,7.62-.73,8-.54L144,68,110,87.3c-.65.3-6.95,1-8.42-.54l-.91-1,1.17-7.55H82.37V94.8l8.12-1.19,1,1.16c1,1.22.8,7.38.31,8.21Zm-14.82-35L72,125.58l14.82-24.7c0-.36,0-.85,0-1.35L77.05,101V73h31l-1.45,9.37H108L133.24,68l-25.3-14.4h-1.38L108,63H77.14V35l9.67,1.44c0-.51,0-1,0-1.36L72,10.34,57.18,35c0,.36,0,.85,0,1.36L67,34.92V63H36l1.45-9.4H36L10.76,68l25.3,14.37h1.38L36,72.88H66.91v28.06L57.2,99.52C57.19,100,57.18,100.52,57.18,100.89Z"/></g></g></svg>

html {
    cursor: url(cursor/move.svg), auto;
}

But it doesn't matter if I change its size to something big (128px) or small, and it doesn't matter if I'm on Chrome, Firefox, or Safari, it is still somewhat pixelated. It is crisp and clean when I import it into the HTML document, but blurry and pixelated when I use it as a cursor. What am I doing wrong?

Body:
I've just updated cursor to look like the following, I don't know if that helps:

html {
  width: 50vw;
  height: 50vh;
  background: gold;

  cursor: url("data:image/svg+xml,%3Csvg version='1.1' id='Layer_1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' x='0px' y='0px' width='128px' height='128px' viewBox='0 0 512 512' style='enable-background:new 0 0 512 512;' xml:space='preserve'%3E %3Cpath d='M72,135.92,52.25,103c-.54-.91-.59-7.11.32-8.23l1-1.16,8.06,1.18V78.2H42.18l1.17,7.53-.81.93c-1.47,1.69-7.86.93-8.27.75L0,68,34,48.6c.6-.29,6.9-.9,8.34.48l1,1-1.18,7.61H61.63V41.1l-8.1,1.21-1-1.17c-.91-1.11-.86-7.32-.33-8.21L72,0,91.75,32.91c.5.85.68,7-.3,8.23l-1,1.17-8-1.19V57.7h19.36L100.61,50l1.08-1c1.41-1.27,7.62-.73,8-.54L144,68,110,87.3c-.65.3-6.95,1-8.42-.54l-.91-1,1.17-7.55H82.37V94.8l8.12-1.19,1,1.16c1,1.22.8,7.38.31,8.21Zm-14.82-35L72,125.58l14.82-24.7c0-.36,0-.85,0-1.35L77.05,101V73h31l-1.45,9.37H108L133.24,68l-25.3-14.4h-1.38L108,63H77.14V35l9.67,1.44c0-.51,0-1,0-1.36L72,10.34,57.18,35c0,.36,0,.85,0,1.36L67,34.92V63H36l1.45-9.4H36L10.76,68l25.3,14.37h1.38L36,72.88H66.91v28.06L57.2,99.52C57.19,100,57.18,100.52,57.18,100.89Z'/%3E %3C/svg%3E"), pointer;
}


问:
CSS class not applying style
In regard to the first CSS rule, it works when i use the 'p' tag by itself. When I apply the 'article' class with or without the 'p' tag, it doesn't work. Why is that? Also the 'hr' tag with the class of 'one' works (which means CSS file is working). This seems so basic. I don't understand why it isn't working. Any ideas?

HTML

```<code><p class=article>{{ post.body|truncatewords:30|linebreaks }}</p>
</code>```

-- Also tried this

```<code><p class="article">{{ post.body|truncatewords:30|linebreaks }}</p>
</code>```

external CSS file

```<code>p.article {
    color:red;
}

hr.one {
    border:none;
    height: 2px;
    background: #cec4c4;
}
</code>```

HTML Output

```<code><div>

        <h1 class=display-4><a href="/blog/2020/5/28/gdddsasddsg/">gdddsasddsg</a></h1>

        <h6><span class="font-italic font-weight-normal">By: </span>gdorman619  <span
                class="font-italic font-weight-normal">Published Date: </span> May 28, 2020, 12:24 p.m.</h6>

        <p class="article"><p>sdadfsdsfdsfa</p></p>

        <hr class="one">

    </div>
</code>```

答:
Your code looks mostly good. To add a class attribute, you must specify the name of the class with quotes, like this:

```<code><p class="article"> Your code here</p>
</code>```

Hope this helps

Title: CSS class not applying style

Body:
In regard to the first CSS rule, it works when i use the 'p' tag by itself. When I apply the 'article' class with or without the 'p' tag, it doesn't work. Why is that? Also the 'hr' tag with the class of 'one' works (which means CSS file is working). This seems so basic. I don't understand why it isn't working. Any ideas?

HTML

{{ post.body|truncatewords:30|linebreaks }}

-- Also tried this

{{ post.body|truncatewords:30|linebreaks }}

external CSS file

p.article {
    color:red;
}

hr.one {
    border:none;
    height: 2px;
    background: #cec4c4;
}

HTML Output

gdddsasddsg

By: gdorman619  Published Date:  May 28, 2020, 12:24 p.m.

sdadfsdsfdsfa

Body:
Your code looks mostly good. To add a class attribute, you must specify the name of the class with quotes, like this:

<p class="article"> Your code here</p>

Hope this helps


问:
Bootstrap 4 and html : button toggle and modals
I tried to make a login button which opens up a modal for login details. When I click on the button it is referred to that point where I want it to be. But nothing opens up. A similar problem is with another button that has to open up another modal.

My 2nd problem in about the navbar toggling action is not working. there is no response from the button when I click on the toggle button.

below is my code - :

CODE FOR NAV BAR BUTTON -

```<code><!DOCTYPE html>
<html lang="en">

<head>
    <!-- Required meta tags always come first -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta http-equiv="x-ua-compatible" content="ie=edge">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="node_modules/bootstrap/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="node_modules/font-awesome/css/font-awesome.min.css">
    <link rel="stylesheet" href="node_modules/bootstrap-social/bootstrap-social.css">
    <link rel="stylesheet" href="css/styles.css">

    <title>Ristorante Con Fusion</title>
</head>

<body>

    <nav class="navbar navbar-dark navbar-expand-md fixed-top">
        <div class="container">
            <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#Navbar">
                <span class="navbar-toggler-icon "></span>
            </button>
            <a class="navbar-brand" href="#"><img src="img/logo.png" height="30" width="41"></a>
            <div class="collapse navbar-collapse" id="Navbar">
                <ul class="navbar-nav mr-auto">
                    <li class="nav-item active"><a class="nav-link" href="#"><span class="fa fa-home fa-lg"></span>
                            Home</a></li>
                    <li class="nav-item"><a class="nav-link" href="./aboutus.html"><span
                                class="fa fa-info fa-lg"></span> About</a></li>
                    <li class="nav-item"><a class="nav-link" href="#"><span class="fa fa-list fa-lg"></span> Menu</a>
                    </li>
                    <li class="nav-item"><a class="nav-link" href="contactus.html"><span
                                class="fa fa-address-card fa-lg"></span> Contact</a></li>
                </ul>
                <span class="navbar-text">
                    <a data-toggle="modal" href="#loginModal">
                        <span class="fa fa-sign-in"></span> Login
                    </a>
                </span>
            </div>
        </div>
    </nav>

-------------------------------------------------
-------------------------------------------------
CODE FOR LOGIN MODAL -
  <div id="loginModal" class="modal fade" role="dialog">
        <div class="modal-dialog-centered modal-lg" role="content">
            <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title">Login</h4>
                    <button type="button" class="close" data-dismiss="modal">
                        ×
                    </button>
                </div>
                <div class="modal-body">
                    <form>
                        <div class="form-row">
                            <div class="form-group col-sm-4">
                                <label class="sr-only" for="exampleInputEmail3">Email address</label>
                                <input type="email" class="form-control form-control-sm mr-1" id="exampleInputEmail3"
                                    placeholder="Enter email">
                            </div>
                            <div class="form-group col-sm-4">
                                <label class="sr-only" for="exampleInputPassword3">Password</label>
                                <input type="password" class="form-control form-control-sm mr-1"
                                    id="exampleInputPassword3" placeholder="Password">
                            </div>
                            <div class="col-sm-auto">
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox">
                                    <label class="form-check-label"> Remember me
                                    </label>
                                </div>
                            </div>
                        </div>
                        <div class="form-row">
                            <button type="button" class="btn btn-secondary btn-sm ml-auto"
                                data-dismiss="modal">Cancel</button>
                            <button type="submit" class="btn btn-primary btn-sm ml-1">Sign in</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>enter code here
    </div>
</body>

      ' <!-- jQuery first, then Popper.js, then Bootstrap JS. -->
     <script src="node_modules/jquery/dist/jquery.slim.min.js">
                            </script>
    <script src="node_modules/popper.js/dist/umd/popper.min.js">
      </script>
  <script src="node_modules/bootstrap/dist/js/bootstrap.min.js">
     </script>
     <script>'$'(document).on('.data-api')</script>
    <script>'
</code>```

答:
.navbar-toggler {bordeR:2px solid red !important;}
body{min-height: 500px;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<!DOCTYPE html>
<html lang="en">

<head>
    <!-- Required meta tags always come first -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta http-equiv="x-ua-compatible" content="ie=edge">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="node_modules/bootstrap/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="node_modules/font-awesome/css/font-awesome.min.css">
    <link rel="stylesheet" href="node_modules/bootstrap-social/bootstrap-social.css">
    <link rel="stylesheet" href="css/styles.css">

    <title>Ristorante Con Fusion</title>
</head>

<body>

    <nav class="navbar  navbar-expand-md">
        <div class="container">
            <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#Navbar">
                <span class="navbar-toggler-icon "></span>
            </button>
            <img src="img/logo.png" height="30" width="41">
            <div class="collapse navbar-collapse" id="Navbar">
                <ul class="navbar-nav mr-auto">
                    <li class="nav-item active"><span class="fa fa-home fa-lg"></span>
                            Home</li>
                    <li class="nav-item"><span
                                class="fa fa-info fa-lg"></span> About</li>
                    <li class="nav-item"><span class="fa fa-list fa-lg"></span> Menu
                    </li>
                    <li class="nav-item"><span
                                class="fa fa-address-card fa-lg"></span> Contact</li>
                </ul>
                <span class="navbar-text">

                        <span class="fa fa-sign-in"></span> Login

                </span>
            </div>
        </div>
    </nav>

  <div id="loginModal" class="modal" role="dialog">
        <div class="modal-dialog-centered modal-lg" role="content">
            <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title">Login</h4>
                    <button type="button" class="close" data-dismiss="modal">
                        ×
                    </button>
                </div>
                <div class="modal-body">
                    <form>
                        <div class="form-row">
                            <div class="form-group col-sm-4">
                                <label class="sr-only" for="exampleInputEmail3">Email address</label>
                                <input type="email" class="form-control form-control-sm mr-1" id="exampleInputEmail3"
                                    placeholder="Enter email">
                            </div>
                            <div class="form-group col-sm-4">
                                <label class="sr-only" for="exampleInputPassword3">Password</label>
                                <input type="password" class="form-control form-control-sm mr-1"
                                    id="exampleInputPassword3" placeholder="Password">
                            </div>
                            <div class="col-sm-auto">
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox">
                                    <label class="form-check-label"> Remember me
                                    </label>
                                </div>
                            </div>
                        </div>
                        <div class="form-row">
                            <button type="button" class="btn btn-secondary btn-sm ml-auto" data-dismiss="modal">Cancel</button>
                            <button type="submit" class="btn btn-primary btn-sm ml-1">Sign in</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</body></code>```

There is no Bootstrap JS and jQuery Added, so without it, modal will not work

do not pass href on login button, instead use data-target="#loginModal"

remove FADE class from modal,

I have removed many other classes from your code just for demo purpose, like fixed top on nav, yuou have have those as per your requirements

Body:
I tried to make a login button which opens up a modal for login details. When I click on the button it is referred to that point where I want it to be. But nothing opens up. A similar problem is with another button that has to open up another modal.

My 2nd problem in about the navbar toggling action is not working. there is no response from the button when I click on the toggle button.

below is my code - :

CODE FOR NAV BAR BUTTON -

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta http-equiv="x-ua-compatible" content="ie=edge">

    <link rel="stylesheet" href="node_modules/bootstrap/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="node_modules/font-awesome/css/font-awesome.min.css">
    <link rel="stylesheet" href="node_modules/bootstrap-social/bootstrap-social.css">
    <link rel="stylesheet" href="css/styles.css">

    <title>Ristorante Con Fusion</title>

            <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#Navbar">

            </button>

                            Home

 About

 Menu

 Contact

                         Login

-------------------------------------------------
-------------------------------------------------
CODE FOR LOGIN MODAL -

Login

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

                    <form>

                                Email address
                                <input type="email" class="form-control form-control-sm mr-1" id="exampleInputEmail3"
                                    placeholder="Enter email">

                                Password
                                <input type="password" class="form-control form-control-sm mr-1"
                                    id="exampleInputPassword3" placeholder="Password">

                                    <input class="form-check-input" type="checkbox">
                                     Remember me

                            <button type="button" class="btn btn-secondary btn-sm ml-auto"
                                data-dismiss="modal">Cancel</button>
                            <button type="submit" class="btn btn-primary btn-sm ml-1">Sign in</button>

                    </form>

enter code here

      '

Body:
.navbar-toggler {bordeR:2px solid red !important;}
body{min-height: 500px;}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<!DOCTYPE html>
<html lang="en">

<head>
    <!-- Required meta tags always come first -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta http-equiv="x-ua-compatible" content="ie=edge">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="node_modules/bootstrap/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="node_modules/font-awesome/css/font-awesome.min.css">
    <link rel="stylesheet" href="node_modules/bootstrap-social/bootstrap-social.css">
    <link rel="stylesheet" href="css/styles.css">

    <title>Ristorante Con Fusion</title>
</head>

<body>

    <nav class="navbar  navbar-expand-md">
        <div class="container">
            <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#Navbar">
                <span class="navbar-toggler-icon "></span>
            </button>
            <a class="navbar-brand" href="#"><img src="img/logo.png" height="30" width="41"></a>
            <div class="collapse navbar-collapse" id="Navbar">
                <ul class="navbar-nav mr-auto">
                    <li class="nav-item active"><a class="nav-link" href="#"><span class="fa fa-home fa-lg"></span>
                            Home</a></li>
                    <li class="nav-item"><a class="nav-link" href="./aboutus.html"><span
                                class="fa fa-info fa-lg"></span> About</a></li>
                    <li class="nav-item"><a class="nav-link" href="#"><span class="fa fa-list fa-lg"></span> Menu</a>
                    </li>
                    <li class="nav-item"><a class="nav-link" href="contactus.html"><span
                                class="fa fa-address-card fa-lg"></span> Contact</a></li>
                </ul>
                <span class="navbar-text">
                    <a data-toggle="modal" data-target="#loginModal">
                        <span class="fa fa-sign-in"></span> Login
                    </a>
                </span>
            </div>
        </div>
    </nav>

  <div id="loginModal" class="modal" role="dialog">
        <div class="modal-dialog-centered modal-lg" role="content">
            <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title">Login</h4>
                    <button type="button" class="close" data-dismiss="modal">
                        &times;
                    </button>
                </div>
                <div class="modal-body">
                    <form>
                        <div class="form-row">
                            <div class="form-group col-sm-4">
                                <label class="sr-only" for="exampleInputEmail3">Email address</label>
                                <input type="email" class="form-control form-control-sm mr-1" id="exampleInputEmail3"
                                    placeholder="Enter email">
                            </div>
                            <div class="form-group col-sm-4">
                                <label class="sr-only" for="exampleInputPassword3">Password</label>
                                <input type="password" class="form-control form-control-sm mr-1"
                                    id="exampleInputPassword3" placeholder="Password">
                            </div>
                            <div class="col-sm-auto">
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox">
                                    <label class="form-check-label"> Remember me
                                    </label>
                                </div>
                            </div>
                        </div>
                        <div class="form-row">
                            <button type="button" class="btn btn-secondary btn-sm ml-auto" data-dismiss="modal">Cancel</button>
                            <button type="submit" class="btn btn-primary btn-sm ml-1">Sign in</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</body>

There is no Bootstrap JS and jQuery Added, so without it, modal will not work

do not pass href on login button, instead use data-target="#loginModal"

remove FADE class from modal,

I have removed many other classes from your code just for demo purpose, like fixed top on nav, yuou have have those as per your requirements


问:
Image does not convert to Bitmap
I am currently experiencing an issue where an image cannot be converted to Bitmap.

This is the code in question:

```<code>private void btnPicture_Click(object sender, EventArgs e)
        {
            OpenFileDialog opFile = new OpenFileDialog();
            opFile.Title = "Choose a picture!";
            opFile.Filter = "jpg files (*.jpg)|*.jpg|All files (*.*)|*.*";

            string appPath = Path.GetDirectoryName(Application.ExecutablePath);
            if (Directory.Exists(appPath) == false)
            {
                Directory.CreateDirectory(appPath);
            }

            if (opFile.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    Character.imageName = opFile.SafeFileName;
                    Stream stream = opFile.OpenFile(); //<------ This is the line in question
                    Bitmap toResize = new Bitmap(stream);

                    Image characterImage = ResizeImage(toResize, 200, 306);

                    imgCharacter.Image = characterImage;
                    characterImage.Save("Images/" + Character.imageName);
                }
                catch (Exception exp)
                {
                    MessageBox.Show("Please select a picture, exception code: " + exp.Message);
                }
            }
            else
            {
                opFile.Dispose();
            }
        }
</code>```

Now basically this code works with every single image that I have tried, except 1. A single picture that my friends tried to upload will crash with the following error: Parameter is not valid.

What I have tried:

First, the friend sent me the image in question. I downloaded it and faced the same problem.

Then I had the friend send me other images that worked on his machine, these still worked.

Next, I opened the image in question in Paint, "saved as" the picture to any folder, then it worked. In the process, I received a warning that saving the image this way may result in transparency loss.

To check if transparency was the problem I had downloaded a "transparent" picture off the internet to check if that is the problem - the picture would load correctly.

Lastly, I had searched for the exact same picture on the internet and tried to download it exactly the same way my friend did, I did not get the error.

To make sure the image was not corrupted I asked the friend to download it once again and sent to me - the error would still occur.

I ran the debugger line by line to pinpoint the exact line of code that crashes. I have no idea what could be the cause there.

Link to the image: https://cdn.discordapp.com/attachments/413040202307731466/713873776143499294/babar1.jpg

I tried to find help online but could not find anything relevant so here I am, if there is anything particularly special to this picture (or a group of pictures) that I do not know about, please forgive, I am not a graphics designer in any way, shape or form.

Have a nice day.

答:
I looked at the image you provided named "barbar1.jpg" in a hex editor and can see RIFF WEBPVP8 markers at the beginning. This means the image is not a JPG file it is a WEBP file.

https://en.wikipedia.org/wiki/WebP

The error you are getting is when initializing the new Bitmap from a stream. Bitmap class only supports BMP, GIF, EXIF, JPG, PNG and TIFF.

Microsoft Paint supports WEBP which is why you are able to open it and view it. Microsoft and other image viewers ignore the file extension and parse the image based on the format of the file data itself. This is why you are able to rename the file to PNG, JPG, BMP, etc and it will still be readable by Paint.

Title: Image does not convert to Bitmap

Body:
I am currently experiencing an issue where an image cannot be converted to Bitmap.

This is the code in question:

private void btnPicture_Click(object sender, EventArgs e)
        {
            OpenFileDialog opFile = new OpenFileDialog();
            opFile.Title = "Choose a picture!";
            opFile.Filter = "jpg files (*.jpg)|*.jpg|All files (*.*)|*.*";

            string appPath = Path.GetDirectoryName(Application.ExecutablePath);
            if (Directory.Exists(appPath) == false)
            {
                Directory.CreateDirectory(appPath);
            }

            if (opFile.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    Character.imageName = opFile.SafeFileName;
                    Stream stream = opFile.OpenFile(); //<------ This is the line in question
                    Bitmap toResize = new Bitmap(stream);

                    Image characterImage = ResizeImage(toResize, 200, 306);

                    imgCharacter.Image = characterImage;
                    characterImage.Save("Images/" + Character.imageName);
                }
                catch (Exception exp)
                {
                    MessageBox.Show("Please select a picture, exception code: " + exp.Message);
                }
            }
            else
            {
                opFile.Dispose();
            }
        }

Now basically this code works with every single image that I have tried, except 1. A single picture that my friends tried to upload will crash with the following error: Parameter is not valid.

What I have tried:

First, the friend sent me the image in question. I downloaded it and faced the same problem.

Then I had the friend send me other images that worked on his machine, these still worked.

Next, I opened the image in question in Paint, "saved as" the picture to any folder, then it worked. In the process, I received a warning that saving the image this way may result in transparency loss.

To check if transparency was the problem I had downloaded a "transparent" picture off the internet to check if that is the problem - the picture would load correctly.

Lastly, I had searched for the exact same picture on the internet and tried to download it exactly the same way my friend did, I did not get the error.

To make sure the image was not corrupted I asked the friend to download it once again and sent to me - the error would still occur.

I ran the debugger line by line to pinpoint the exact line of code that crashes. I have no idea what could be the cause there.

Link to the image: https://cdn.discordapp.com/attachments/413040202307731466/713873776143499294/babar1.jpg

I tried to find help online but could not find anything relevant so here I am, if there is anything particularly special to this picture (or a group of pictures) that I do not know about, please forgive, I am not a graphics designer in any way, shape or form.

Have a nice day.


问:
make boxplot with columns from 2 dataframes [python seaborn]
I want to make a boxplot like this:

My data looks like this. It's separated into a control and an intervention dataframe.

```<code>control_df
   # of Days
0         10
1         12
2         30
</code>```

```<code>intervention_df
   # of Days
0          2
1          1
2          2

</code>```

Unfortunately, I'm not able to easily put it into sns.boxplot. Any advice on how to format it to graph appreciated.

MVE below:

import pandas as pd

# This is how my actual data is coming in
data_control = {'# of Days':[10,12,30]}
data_intervention = {'# of Days':[2,1,2]}

control_df = pd.DataFrame(data_control)
intervention_df = pd.DataFrame(data_intervention)

# This is me manually making it better for a boxplot
boxplot_data = {'Type':['control','control','control','intervention','intervention','intervention'],
                '# of Days':[10,12,30,2,1,2]}

import seaborn as sns

sns.boxplot(x='Type',y='# of Days',data=boxplot_data)
```

答:
IIUC, you can use pd.concat with keys parameter and droplevel:

```<code>sns.boxplot(data=pd.concat([control_df, intervention_df],
                           axis=1,
                           keys=['Control', 'Intervention']).droplevel(1, axis=1))
</code>```

Output:

Body:
I want to make a boxplot like this:

My data looks like this. It's separated into a control and an intervention dataframe.

control_df
   # of Days
0         10
1         12
2         30

intervention_df
   # of Days
0          2
1          1
2          2

Unfortunately, I'm not able to easily put it into sns.boxplot. Any advice on how to format it to graph appreciated.

MVE below:

import pandas as pd

# This is how my actual data is coming in
data_control = {'# of Days':[10,12,30]}
data_intervention = {'# of Days':[2,1,2]}

control_df = pd.DataFrame(data_control)
intervention_df = pd.DataFrame(data_intervention)

# This is me manually making it better for a boxplot
boxplot_data = {'Type':['control','control','control','intervention','intervention','intervention'],
                '# of Days':[10,12,30,2,1,2]}

import seaborn as sns

sns.boxplot(x='Type',y='# of Days',data=boxplot_data)

Body:
IIUC, you can use pd.concat with keys parameter and droplevel:

sns.boxplot(data=pd.concat([control_df, intervention_df],
                           axis=1,
                           keys=['Control', 'Intervention']).droplevel(1, axis=1))

Output:


问:
How to return elements of array matching criteria in MongoDB
I'm new to mongodb and I'm still trying to wrap my head around queries so forgive me if my question is too simple or have been answered elsewhere.

I have a collection like the one below

```<code>[
{"_id":1,
"data" :[{"a":1,"b":2},{"a":1,"b":3},{"a":2,"b":3},{"a":4,"b":1}]
},
{"_id":2,
"data" :[{"a":3,"b":2},{"a":2,"b":4},{"a":5,"b":3},{"a":7,"b":1}]
}
]
</code>```

How can I write a query that looks inside the data array of the first document and returns all elements where "a" is equal to one.

Something like this is the expected output:

```<code>[{"a":1,"b":2},{"a":1,"b":3}]
</code>```

This is my current attempt

```<code>db.myCollection.find({_id:1},{data: {$elemMatch: {a : 1}}})
</code>```

But this gives me

```<code>{"_id": 1, "data":
[{"a":1,"b":2},{"a":1,"b":3}]
}
</code>```

I don't need or want anything other than the results in "data".

Can someone give me a hand?

I'd also appreciate any pointers for sifting through an array in a document for elements matching more general conditions on a single document (ie for the example above finding the documents where a+b < 5, a > b, a>1 and b>2, a >3 or b<1, etc.)

Edit: I'm using mongodb version 4.2.6

答:
You have almost everything, you just forget the projection at end:</p>

```<code>db.myCollection.find({_id:1},{data: {$elemMatch: {a : 1}}}, {_id: 0, data: 1})
</code>```

Body:
I'm new to mongodb and I'm still trying to wrap my head around queries so forgive me if my question is too simple or have been answered elsewhere.

I have a collection like the one below

[
{"_id":1,
"data" :[{"a":1,"b":2},{"a":1,"b":3},{"a":2,"b":3},{"a":4,"b":1}]
},
{"_id":2,
"data" :[{"a":3,"b":2},{"a":2,"b":4},{"a":5,"b":3},{"a":7,"b":1}]
}
]

How can I write a query that looks inside the data array of the first document and returns all elements where "a" is equal to one.

Something like this is the expected output:

[{"a":1,"b":2},{"a":1,"b":3}]

This is my current attempt

db.myCollection.find({_id:1},{data: {$elemMatch: {a : 1}}})

But this gives me

{"_id": 1, "data":
[{"a":1,"b":2},{"a":1,"b":3}]
}

I don't need or want anything other than the results in "data".

Can someone give me a hand?

I'd also appreciate any pointers for sifting through an array in a document for elements matching more general conditions on a single document (ie for the example above finding the documents where a+b < 5, a > b, a>1 and b>2, a >3 or b<1, etc.)

Edit: I'm using mongodb version 4.2.6

Body:
You have almost everything, you just forget the projection at end:

db.myCollection.find({_id:1},{data: {$elemMatch: {a : 1}}}, {_id: 0, data: 1})


问:
Define what method to call based on value of Optional
Is it possible, to somehow alter the code below, so in case of no status value provided to return all the PaymentLog objects stored in the database instead of only the ones with status equal with 404? Basically, I would like if the status variable has not been provided to call another method in the service layer logService.getAllPaymentLogs()

```<code>@GetMapping(Endpoints.LOGS.PAYMENT_LOGS)
public Page<PaymentLog> getPaymentLog(@RequestParam Optional<Integer> status) {
    return logService.getPaymentLogStatus(status.orElse(404), PageRequest.of(0, 10));
}
</code>```

These are the getPaymentLogStatus() and getAllPaymentLogs

```<code>@Override
public Page<PaymentLog> getPaymentLog(Pageable pageable) {
    return paymentLogRepository.getAllBy(pageable);
}
</code>```

And

```<code>@Override
public Page<PaymentLog> getPaymentLog(int status, Pageable pageable) {
    return paymentLogRepository.getAllByStatus(status, pageable);
}
</code>```

答:
@123 answered the question in the commenting session:</p>

```<code>status.map(s -> getPaymentLog(s, page)).orElseGet(() -> getPaymentLog(page))
</code>```

Body:
Is it possible, to somehow alter the code below, so in case of no status value provided to return all the PaymentLog objects stored in the database instead of only the ones with status equal with 404? Basically, I would like if the status variable has not been provided to call another method in the service layer logService.getAllPaymentLogs()

@GetMapping(Endpoints.LOGS.PAYMENT_LOGS)
public Page<PaymentLog> getPaymentLog(@RequestParam Optional<Integer> status) {
    return logService.getPaymentLogStatus(status.orElse(404), PageRequest.of(0, 10));
}

These are the getPaymentLogStatus() and getAllPaymentLogs

@Override
public Page<PaymentLog> getPaymentLog(Pageable pageable) {
    return paymentLogRepository.getAllBy(pageable);
}

And

@Override
public Page<PaymentLog> getPaymentLog(int status, Pageable pageable) {
    return paymentLogRepository.getAllByStatus(status, pageable);
}

Body:
@123 answered the question in the commenting session:

status.map(s -> getPaymentLog(s, page)).orElseGet(() -> getPaymentLog(page))


问:
Best Way to Modify Another Programmer's Navigation
"Change an item in the navigation? Sure I can do that in 15 minutes."

So I am trying to update the navigation on a site that I inherited only to find out that the previous programmer was a college student and was using this site as a project of some sort.  Needless to say there are zero comments and the code calls function after function and I just can't follow the logic.

I am looking for a roundabout way to update the navigation. I tried using Dreamweaver to search through all of the files in the site and look for any files that contain the name of the page or the url (hoping to find some sort of included file). There was none. I did file text files that control the main navigation but none for the subnavigation.

There is no database.

If it helps here is the site. http://bit.ly/jbs639

And if you want to look at the interesting text file that is parsed to create the main navigation you can find it here: http://bit.ly/m3erna

答:
Hmmm.... Interesting indeed. You have my sympathy.

One thing that I would look at... The file that gets parsed for the main navigation appears to be a simple delimited file. Sure, the delimiter is a rather unusual +++, but that choice means it avoids conflict with things like commas that might be desirable in the link text. It looks as if the last element indicates what type of resource is being accessed (file or directory, although I don't know what - if any - effect that has on the final output). It also appears that there are similar text files (in the framework/cfg/nav/ folder... which should probably not be generally accessible BTW) for the sub-menus. (E.g. the file stores.txt appears to contain the additional navigation items associated with the stores sub-navigation).

You don't mention which sub-menu you're trying to change. I suspect it is the "About TTO" one, which I can't find an entry for... but I'd look to see if there are any similar navigation text files in the /content/about/ folder.

Good Luck!

ContentLicense: CC BY-SA 3.0


问:
How to Activate an open application window using the Process Identifier with .VBS or .BAT
My code is simple, I just want to do this:

```<code>    Set iShell = WScript.CreateObject("WScript.Shell")

    xRepeat:

    ' ** Activate a specify Internet Explorer 11 Window already open (by PID)
    iShell.SendKeys "{TAB}"
    iShell.SendKeys "{CTRL + C}"
    iShell.SendKeys "{TAB} {TAB} {TAB} {TAB}"
    iShell.SendKeys "{CTRL+ V}"
    iShell.SendKeys "{TAB} {TAB} {TAB} {TAB}"
    iShell.SendKeys "{CTRL + V}"

    ' ** Activate a program already open (by PID)
    iShell.SendKeys "{TAB} {TAB} {TAB} {TAB}"
    iShell.SendKeys "{CTRL + C}"

    ' ** Activate a specify Internet Explorer 11 Window already open (by PID)
    iShell.SendKeys "{TAB} {TAB} {TAB} {TAB}"
    iShell.SendKeys "{CTRL + V}"

    If msgbox("Repeat process?", vbYesNo) = vbYes Then
       GoTo xRepeat
    End if
</code>```

I have some programs opened, and I dont want stay using "SendKeys {ALT + TAB}"

I work in a computer with extremely blocked access and basically my job is fill forms with the same answers all day, so I want fill automatically.

How so the computer that I use has no access to anything, I wish a solution that doesn't need to install anything.

I can use only notepad(.VBS or .BAT). Aah, I Can use VBA too, so the 'automation' above can be in .bat .vbs or in excell.vba as well. I know a lot of VBA, but only to do things into Excel

Ps: I can only get PID by notepad.bat "tasklist; @pause"

Thank you!

答:
I found a (large) solution. My next goal is dont use {TAB}, I wanna learn how to get to the specific form and put a value. Like: Document.GetElementByName("username").Value = "ALEXAN"

But my problem is how to set an already opened Internet Explorer as an Object so then use .Document.GetElementByName

```<code>Dim ws

Set ws = CreateObject("WScript.Shell")

If MsgBox("Finalizado?", vbYesNo + vbQuestion, "") = vbYes Then
    ws.AppActivate "Tratar Protocolos - Internet Explorer"
    ws.SendKeys "{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}"
    ws.SendKeys "^{c}"
        WScript.Sleep 200
    ws.SendKeys "{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}"
        WScript.Sleep 200
    ws.SendKeys "~"
        WScript.Sleep 200
    ws.SendKeys "FINALIZADO"
        WScript.Sleep 200
    ws.SendKeys "~"
        WScript.Sleep 200
    ws.SendKeys "{TAB}"
    ws.SendKeys "~"
        WScript.Sleep 200
    ws.SendKeys "SOLICITAÇAO ATENDIDA"
        WScript.Sleep 200
    ws.SendKeys "~"
        WScript.Sleep 200
    ws.SendKeys "{TAB}"
    ws.SendKeys "^{v}"
        WScript.Sleep 200
    ws.SendKeys "Finalizado"
        WScript.Sleep 200
    ws.SendKeys "~"
        WScript.Sleep 200
    ws.SendKeys "{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}"
        WScript.Sleep 200
    ws.SendKeys "^{c}"
        WScript.Sleep 200
    ws.SendKeys "{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}"
        WScript.Sleep 200
    ws.SendKeys "^{v}"
        WScript.Sleep 200
    ws.AppActivate "Siebel eCommunications Produção - Meio de Acesso - \\Remote"
        MsgBox "Copie o CNPJ depoiso dê OK!"
        WScript.Sleep 200
    ws.AppActivate "Tratar Protocolos - Internet Explorer"
        WScript.Sleep 300
    ws.SendKeys "+{TAB}"
    ws.SendKeys "{TAB}{TAB}"
        WScript.Sleep 300
    ws.SendKeys "^{v}"
        WScript.Sleep 200
    ws.SendKeys "{TAB}{TAB}{TAB}{TAB}{TAB}"
        WScript.Sleep 300
    ws.SendKeys "Protocolo perfilado com sucesso!"
        WScript.Sleep 300
    ws.SendKeys "^{a}"

ElseIf MsgBox("Pendente?", vbYesNo + vbQuestion, "") = vbYes Then
    ws.AppActivate "Tratar Protocolos - Internet Explorer"
    ws.SendKeys "{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}"
    ws.SendKeys "^{c}"
        WScript.Sleep 200
    ws.SendKeys "{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}"
        WScript.Sleep 200
    ws.SendKeys "~"
        WScript.Sleep 200
    ws.SendKeys "PENDENTE"
        WScript.Sleep 200
    ws.SendKeys "~"
        WScript.Sleep 200
    ws.SendKeys "{TAB}"
    ws.SendKeys "~"
        WScript.Sleep 200
    ws.SendKeys "STATUS SUSPENSO"
        WScript.Sleep 200
    ws.SendKeys "~"
        WScript.Sleep 200
    ws.SendKeys "{TAB}"
    ws.SendKeys "0"
    ws.SendKeys "{TAB}"
        WScript.Sleep 200
    ws.SendKeys "^{v}"
    ws.SendKeys "{TAB}{TAB}{TAB}{TAB}"
    ws.SendKeys "^{v}"
        WScript.Sleep 200
    ws.SendKeys "{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}"
        WScript.Sleep 200
    ws.SendKeys "^{c}"
        WScript.Sleep 200
    ws.SendKeys "{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}"
        WScript.Sleep 200
    ws.SendKeys "^{v}"
        WScript.Sleep 200
    ws.AppActivate "Siebel eCommunications Produção - Meio de Acesso - \\Remote"
        MsgBox "Copie o CNPJ depoiso dê OK!"
        WScript.Sleep 200
    ws.AppActivate "Tratar Protocolos - Internet Explorer"
        WScript.Sleep 200
    ws.SendKeys "+{TAB}"
    ws.SendKeys "{TAB}{TAB}"
        WScript.Sleep 200
    ws.SendKeys "^{v}"
        WScript.Sleep 200
    ws.SendKeys "{TAB}{TAB}{TAB}{TAB}{TAB}"
        WScript.Sleep 200
    ws.SendKeys "Protocolo perfilado com sucesso!"
        WScript.Sleep 200
    ws.SendKeys "^{a}"
End If
WScript.Quit
</code>```

Body:
My code is simple, I just want to do this:

    Set iShell = WScript.CreateObject("WScript.Shell")

    xRepeat:

    ' ** Activate a specify Internet Explorer 11 Window already open (by PID)
    iShell.SendKeys "{TAB}"
    iShell.SendKeys "{CTRL + C}"
    iShell.SendKeys "{TAB} {TAB} {TAB} {TAB}"
    iShell.SendKeys "{CTRL+ V}"
    iShell.SendKeys "{TAB} {TAB} {TAB} {TAB}"
    iShell.SendKeys "{CTRL + V}"

    ' ** Activate a program already open (by PID)
    iShell.SendKeys "{TAB} {TAB} {TAB} {TAB}"
    iShell.SendKeys "{CTRL + C}"

    ' ** Activate a specify Internet Explorer 11 Window already open (by PID)
    iShell.SendKeys "{TAB} {TAB} {TAB} {TAB}"
    iShell.SendKeys "{CTRL + V}"

    If msgbox("Repeat process?", vbYesNo) = vbYes Then
       GoTo xRepeat
    End if

I have some programs opened, and I dont want stay using "SendKeys {ALT + TAB}"

I work in a computer with extremely blocked access and basically my job is fill forms with the same answers all day, so I want fill automatically.

How so the computer that I use has no access to anything, I wish a solution that doesn't need to install anything.

I can use only notepad(.VBS or .BAT). Aah, I Can use VBA too, so the 'automation' above can be in .bat .vbs or in excell.vba as well. I know a lot of VBA, but only to do things into Excel

Ps: I can only get PID by notepad.bat "tasklist; @pause"

Thank you!

Body:
I found a (large) solution. My next goal is dont use {TAB}, I wanna learn how to get to the specific form and put a value. Like: Document.GetElementByName("username").Value = "ALEXAN"

But my problem is how to set an already opened Internet Explorer as an Object so then use .Document.GetElementByName

Dim ws

Set ws = CreateObject("WScript.Shell")

If MsgBox("Finalizado?", vbYesNo + vbQuestion, "") = vbYes Then
    ws.AppActivate "Tratar Protocolos - Internet Explorer"
    ws.SendKeys "{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}"
    ws.SendKeys "^{c}"
        WScript.Sleep 200
    ws.SendKeys "{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}"
        WScript.Sleep 200
    ws.SendKeys "~"
        WScript.Sleep 200
    ws.SendKeys "FINALIZADO"
        WScript.Sleep 200
    ws.SendKeys "~"
        WScript.Sleep 200
    ws.SendKeys "{TAB}"
    ws.SendKeys "~"
        WScript.Sleep 200
    ws.SendKeys "SOLICITAÇAO ATENDIDA"
        WScript.Sleep 200
    ws.SendKeys "~"
        WScript.Sleep 200
    ws.SendKeys "{TAB}"
    ws.SendKeys "^{v}"
        WScript.Sleep 200
    ws.SendKeys "Finalizado"
        WScript.Sleep 200
    ws.SendKeys "~"
        WScript.Sleep 200
    ws.SendKeys "{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}"
        WScript.Sleep 200
    ws.SendKeys "^{c}"
        WScript.Sleep 200
    ws.SendKeys "{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}"
        WScript.Sleep 200
    ws.SendKeys "^{v}"
        WScript.Sleep 200
    ws.AppActivate "Siebel eCommunications Produção - Meio de Acesso - \\Remote"
        MsgBox "Copie o CNPJ depoiso dê OK!"
        WScript.Sleep 200
    ws.AppActivate "Tratar Protocolos - Internet Explorer"
        WScript.Sleep 300
    ws.SendKeys "+{TAB}"
    ws.SendKeys "{TAB}{TAB}"
        WScript.Sleep 300
    ws.SendKeys "^{v}"
        WScript.Sleep 200
    ws.SendKeys "{TAB}{TAB}{TAB}{TAB}{TAB}"
        WScript.Sleep 300
    ws.SendKeys "Protocolo perfilado com sucesso!"
        WScript.Sleep 300
    ws.SendKeys "^{a}"

ElseIf MsgBox("Pendente?", vbYesNo + vbQuestion, "") = vbYes Then
    ws.AppActivate "Tratar Protocolos - Internet Explorer"
    ws.SendKeys "{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}"
    ws.SendKeys "^{c}"
        WScript.Sleep 200
    ws.SendKeys "{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}"
        WScript.Sleep 200
    ws.SendKeys "~"
        WScript.Sleep 200
    ws.SendKeys "PENDENTE"
        WScript.Sleep 200
    ws.SendKeys "~"
        WScript.Sleep 200
    ws.SendKeys "{TAB}"
    ws.SendKeys "~"
        WScript.Sleep 200
    ws.SendKeys "STATUS SUSPENSO"
        WScript.Sleep 200
    ws.SendKeys "~"
        WScript.Sleep 200
    ws.SendKeys "{TAB}"
    ws.SendKeys "0"
    ws.SendKeys "{TAB}"
        WScript.Sleep 200
    ws.SendKeys "^{v}"
    ws.SendKeys "{TAB}{TAB}{TAB}{TAB}"
    ws.SendKeys "^{v}"
        WScript.Sleep 200
    ws.SendKeys "{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}"
        WScript.Sleep 200
    ws.SendKeys "^{c}"
        WScript.Sleep 200
    ws.SendKeys "{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}"
        WScript.Sleep 200
    ws.SendKeys "^{v}"
        WScript.Sleep 200
    ws.AppActivate "Siebel eCommunications Produção - Meio de Acesso - \\Remote"
        MsgBox "Copie o CNPJ depoiso dê OK!"
        WScript.Sleep 200
    ws.AppActivate "Tratar Protocolos - Internet Explorer"
        WScript.Sleep 200
    ws.SendKeys "+{TAB}"
    ws.SendKeys "{TAB}{TAB}"
        WScript.Sleep 200
    ws.SendKeys "^{v}"
        WScript.Sleep 200
    ws.SendKeys "{TAB}{TAB}{TAB}{TAB}{TAB}"
        WScript.Sleep 200
    ws.SendKeys "Protocolo perfilado com sucesso!"
        WScript.Sleep 200
    ws.SendKeys "^{a}"
End If
WScript.Quit


问:
How to improve performance for imbalanced dataset using SVM
I am trying to classify data at the token-level using scikit-learn.  I already have a train and test split.
The data is in the following \t seperated format:

```<code>-----------------
token       label
-----------------
way          6
to           6
reduce       6
the          6
amount       6
of           6
traffic      6
   ....
public       2
transport    5
is           5
a            5
key          5
factor       5
to           5
minimize     5
   ....
</code>```

The data is distributes as follows:

```<code>                              Training Data                    Test Data
# Total:                        119490                          29699
# Class 0:                      52631                           13490
# Class 1:                      35116                           8625
# Class 2:                      17968                           4161
# Class 3:                      8658                            2088
# Class 4:                      3002                            800
# Class 5:                      1201                            302
# Class 6:                      592                             153
</code>```

I'm trying SVM and  the F1-score is pretty bad.

The code is:

```<code>import pandas as pd
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.pipeline import Pipeline
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.linear_model import SGDClassifier
from sklearn.metrics import accuracy_score, f1_score
from sklearn.model_selection import KFold

if __name__ == '__main__':
    # reading Files
    train_df = pd.read_csv(TRAINING_DATA_PATH, names=['token', 'label'], sep='\t')
    test_df = pd.read_csv(TEST_DATA_PATH, names=['token', 'label'], sep='\t')

    # getting training and testing data
    train_X = train_df['token'].astype('U')
    test_X = test_df['token'].astype('U')
    train_y = train_df['label']
    test_y = test_df['label']

    # Linear SVM
    sgd = Pipeline([('vect', CountVectorizer()),
                    ('tfidf', TfidfTransformer()),
                    ('clf',   SGDClassifier(loss='hinge', penalty='l2', alpha=1e-3, max_iter=100, tol=None)
                   ])
    f1_list = []
    acc_list = []
    cv = KFold(n_splits=5)
    for train_index, test_index in cv.split(train_X):
        X_train, X_val = train_X[train_index], train_X[test_index]
        y_train, y_val = train_y[train_index], train_y[test_index]
        sgd.fit(X_train, y_train)
        predicted = sgd.predict(X_val)
        f1 = f1_score(y_val, predicted, average='macro')
        acc = accuracy_score(y_val, predicted)
        f1_list.append(f1)
        acc_list.append(acc)
    print(f1_list)
    print(acc_list)
    sgd_pred = sgd.predict(test_X)
    print('SVM accuracy: %s' % accuracy_score(sgd_pred, test_y))
    print('SVM F1-macro: %s' % f1_score(sgd_pred, test_y, average='macro'))
    print('SVM F1-weighted: %s' % f1_score(sgd_pred, test_y, average='weighted'))
</code>```

The results for the Linear SVM is as follows:

```<code>SVM accuracy: 0.49493248930940437
SVM F1-macro: 0.2677988484198396
</code>```

How do I improve the performace?

答:
There are several measures you can consider to improve your predictive performance:

Use the class_weight parameter to penalize errors on minority classes heavier

```<code>sgd = Pipeline([('vect', CountVectorizer()),
              ('tfidf', TfidfTransformer()),
              ('clf',   SGDClassifier(loss='hinge',
                                      penalty='l2',
                                      class_weight='balanced', # add this
                                      alpha=1e-3,
                                      max_iter=100,
                                      tol=None)
           ])
</code>```

Resample your data before training with the imblearn library, e.g.

```<code>from imblearn.oversampling import SMOTE

# getting training and testing data
train_X = train_df['token'].astype('U')
test_X = test_df['token'].astype('U')
train_y = train_df['label']
test_y = test_df['label']

sm = SMOTE(random_state=42)
train_X_res, train_y_res = sm.fit_resample(train_X, train_y)
</code>```

Try another classifier, e.g. Logistic Regression

```<code>sgd = Pipeline([('vect', CountVectorizer()),
              ('tfidf', TfidfTransformer()),
              ('clf',   SGDClassifier(loss='log', # change here
                                      penalty='l2',
                                      alpha=1e-3,
                                      max_iter=100,
                                      tol=None)
</code>```

You can try these things all separately or in combination. But especially the first two are the classic measures to deal with imbalanced data sets.

Body:
I am trying to classify data at the token-level using scikit-learn.  I already have a train and test split.
The data is in the following \t seperated format:

-----------------
token       label
-----------------
way          6
to           6
reduce       6
the          6
amount       6
of           6
traffic      6
   ....
public       2
transport    5
is           5
a            5
key          5
factor       5
to           5
minimize     5
   ....

The data is distributes as follows:

                              Training Data                    Test Data
# Total:                        119490                          29699
# Class 0:                      52631                           13490
# Class 1:                      35116                           8625
# Class 2:                      17968                           4161
# Class 3:                      8658                            2088
# Class 4:                      3002                            800
# Class 5:                      1201                            302
# Class 6:                      592                             153

I'm trying SVM and  the F1-score is pretty bad.

The code is:

import pandas as pd
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.pipeline import Pipeline
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.linear_model import SGDClassifier
from sklearn.metrics import accuracy_score, f1_score
from sklearn.model_selection import KFold

if __name__ == '__main__':
    # reading Files
    train_df = pd.read_csv(TRAINING_DATA_PATH, names=['token', 'label'], sep='\t')
    test_df = pd.read_csv(TEST_DATA_PATH, names=['token', 'label'], sep='\t')

    # getting training and testing data
    train_X = train_df['token'].astype('U')
    test_X = test_df['token'].astype('U')
    train_y = train_df['label']
    test_y = test_df['label']

    # Linear SVM
    sgd = Pipeline([('vect', CountVectorizer()),
                    ('tfidf', TfidfTransformer()),
                    ('clf',   SGDClassifier(loss='hinge', penalty='l2', alpha=1e-3, max_iter=100, tol=None)
                   ])
    f1_list = []
    acc_list = []
    cv = KFold(n_splits=5)
    for train_index, test_index in cv.split(train_X):
        X_train, X_val = train_X[train_index], train_X[test_index]
        y_train, y_val = train_y[train_index], train_y[test_index]
        sgd.fit(X_train, y_train)
        predicted = sgd.predict(X_val)
        f1 = f1_score(y_val, predicted, average='macro')
        acc = accuracy_score(y_val, predicted)
        f1_list.append(f1)
        acc_list.append(acc)
    print(f1_list)
    print(acc_list)
    sgd_pred = sgd.predict(test_X)
    print('SVM accuracy: %s' % accuracy_score(sgd_pred, test_y))
    print('SVM F1-macro: %s' % f1_score(sgd_pred, test_y, average='macro'))
    print('SVM F1-weighted: %s' % f1_score(sgd_pred, test_y, average='weighted'))

The results for the Linear SVM is as follows:

SVM accuracy: 0.49493248930940437
SVM F1-macro: 0.2677988484198396

How do I improve the performace?

Body:
There are several measures you can consider to improve your predictive performance:

Use the class_weight parameter to penalize errors on minority classes heavier

sgd = Pipeline([('vect', CountVectorizer()),
              ('tfidf', TfidfTransformer()),
              ('clf',   SGDClassifier(loss='hinge',
                                      penalty='l2',
                                      class_weight='balanced', # add this
                                      alpha=1e-3,
                                      max_iter=100,
                                      tol=None)
           ])

Resample your data before training with the imblearn library, e.g.

from imblearn.oversampling import SMOTE

# getting training and testing data
train_X = train_df['token'].astype('U')
test_X = test_df['token'].astype('U')
train_y = train_df['label']
test_y = test_df['label']

sm = SMOTE(random_state=42)
train_X_res, train_y_res = sm.fit_resample(train_X, train_y)

Try another classifier, e.g. Logistic Regression

sgd = Pipeline([('vect', CountVectorizer()),
              ('tfidf', TfidfTransformer()),
              ('clf',   SGDClassifier(loss='log', # change here
                                      penalty='l2',
                                      alpha=1e-3,
                                      max_iter=100,
                                      tol=None)

You can try these things all separately or in combination. But especially the first two are the classic measures to deal with imbalanced data sets.


问:
Trying to access items from an API gives errors
So I am trying to return a float value from an API, it is located in:
products => product_name => sell/buy_summary => pricePerUnit

and can be found in this API:
https://api.hypixel.net/skyblock/bazaar?key=73ac0a44-4c41-4933-a9ee-b4095be2b6d2

When I am returning it to my HTML I get the error "TypeError: list indices must be integers or slices, not str", I've googled around a bit and also saw the other thread here on Stackoverflow but didn't get it to work. I have another way to grab values that works completely fine, but the issue is that I NEED to save these values into a variable, to run a script through it to calculate profit/margins.

Here is my current code:

```<code>@app.route('/bflipper', methods=['POST', 'GET'])
def bFlipper():
    f = requests.get(
        'https://api.hypixel.net/skyblock/bazaar?key=73ac0a44-4c41-4933-a9ee-b4095be2b6d2').json()
    product_name = []
    product_sellPrice = []
    product_buyPrice = []
    for x in productNames:
        product_name.append(f["products"][x]["product_id"])
        product_buyPrice.append(
            f["products"][x]["buy_summary"]["pricePerUnit"])
        product_sellPrice.append(
            f["products"][x]["sell_summary"]["pricePerUnit"])
    if request.method == 'POST':
        userInput = request.form['coins']
        return render_template("flipper.html", userInput=userInput, product_name=product_name, product_buyPrice=product_buyPrice, product_sellPrice=product_sellPrice)
    else:
        return render_template("flipper.html", product_name=product_name, product_buyPrice=product_buyPrice, product_sellPrice=product_sellPrice)
</code>```

This script works for arrays though, so I need to get all "pricePerUnit"s from the API, every single product (190+) and store that in the array, this is the reason why I would like to be able to store the "pricePerUnit" first in variables (sellPrice & buyPrice), and then append that to two different arrays so I can run my script through it!

OBS: I am going to need the 'pricePerUnit' for both 'sell_summary' and 'buy_summary' from each product!

Thanks

答:
Since buySummary and sellSummary are arrays, you need to use an array index to get the price from the first element.

```<code>for x in productNames:
    if x in f["products"]:
        product_name.append(f["products"][x]["product_id"])
        if len(f["products"][x]["buy_summary"]) > 0:
            product_buyPrice.append(
                f["products"][x]["buy_summary"][0]["pricePerUnit"])
        if len(f["products"][x]["sell_summary"]) > 0:
            product_sellPrice.append(
                f["products"][x]["sell_summary"][0]["pricePerUnit"])
</code>```

Body:
So I am trying to return a float value from an API, it is located in:
products => product_name => sell/buy_summary => pricePerUnit

and can be found in this API:
https://api.hypixel.net/skyblock/bazaar?key=73ac0a44-4c41-4933-a9ee-b4095be2b6d2

When I am returning it to my HTML I get the error "TypeError: list indices must be integers or slices, not str", I've googled around a bit and also saw the other thread here on Stackoverflow but didn't get it to work. I have another way to grab values that works completely fine, but the issue is that I NEED to save these values into a variable, to run a script through it to calculate profit/margins.

Here is my current code:

@app.route('/bflipper', methods=['POST', 'GET'])
def bFlipper():
    f = requests.get(
        'https://api.hypixel.net/skyblock/bazaar?key=73ac0a44-4c41-4933-a9ee-b4095be2b6d2').json()
    product_name = []
    product_sellPrice = []
    product_buyPrice = []
    for x in productNames:
        product_name.append(f["products"][x]["product_id"])
        product_buyPrice.append(
            f["products"][x]["buy_summary"]["pricePerUnit"])
        product_sellPrice.append(
            f["products"][x]["sell_summary"]["pricePerUnit"])
    if request.method == 'POST':
        userInput = request.form['coins']
        return render_template("flipper.html", userInput=userInput, product_name=product_name, product_buyPrice=product_buyPrice, product_sellPrice=product_sellPrice)
    else:
        return render_template("flipper.html", product_name=product_name, product_buyPrice=product_buyPrice, product_sellPrice=product_sellPrice)

This script works for arrays though, so I need to get all "pricePerUnit"s from the API, every single product (190+) and store that in the array, this is the reason why I would like to be able to store the "pricePerUnit" first in variables (sellPrice & buyPrice), and then append that to two different arrays so I can run my script through it!

OBS: I am going to need the 'pricePerUnit' for both 'sell_summary' and 'buy_summary' from each product!

Thanks

Body:
Since buySummary and sellSummary are arrays, you need to use an array index to get the price from the first element.

for x in productNames:
    if x in f["products"]:
        product_name.append(f["products"][x]["product_id"])
        if len(f["products"][x]["buy_summary"]) > 0:
            product_buyPrice.append(
                f["products"][x]["buy_summary"][0]["pricePerUnit"])
        if len(f["products"][x]["sell_summary"]) > 0:
            product_sellPrice.append(
                f["products"][x]["sell_summary"][0]["pricePerUnit"])


问:
AndroidViewModel has no zero argument constructor
I am trying to create an instance of my AndroidViewModel in MainActivity. When I do this I get the following error has no zero argument constructor

Here is my RecipeViewModel

```<code>package com.example.kookrecepten;

import android.app.Application;

import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;

import java.util.List;

public class RecipeViewModel extends AndroidViewModel {
    private RecipeRepository recipeRepository;
    private LiveData<List<Recipe>> allRecipes;

    public RecipeViewModel(Application application) {
        super(application);
        recipeRepository = new RecipeRepository(application);
        allRecipes = recipeRepository.getAllRecipes();
    }

    public void insert(Recipe recipe) {
        recipeRepository.insert(recipe);
    }

    public void update(Recipe recipe) {
        recipeRepository.update(recipe);
    }

    public void delete(Recipe recipe) {
        recipeRepository.delete(recipe);
    }

    public void deleteAll() {
        recipeRepository.deleteAllRecipes();
    }

    public LiveData<List<Recipe>> getAllRecipes() {
        return allRecipes;
    }
}
</code>```

Now correct me if I'm wrong but AndroidViewModel needs the Application context in the constructor and ViewModel doesn't. So I have no idea why android asks for a zero arguments constructor.

Here is my Main activity where I ask for an instance.

```<code>package com.example.kookrecepten;

import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import com.example.kookrecepten.databinding.ActivityMainBinding;

import java.util.List;

public class MainActivity extends AppCompatActivity {
    private ActivityMainBinding binding;
    private RecipeViewModel recipeViewModel;

    protected void onCreate (Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        binding = ActivityMainBinding.inflate(getLayoutInflater());
        View view = binding.getRoot();
        setContentView(view);

        //Get an instance of the RecipeViewModel.
        recipeViewModel = new ViewModelProvider(this).get(RecipeViewModel.class);
        recipeViewModel.getAllRecipes().observe(this, new Observer<List<Recipe>>() {
            @Override
            public void onChanged(List<Recipe> recipes) {
                //Update recycle view

                Toast.makeText(MainActivity.this, "triggered", Toast.LENGTH_SHORT).show();
            }
        });
    }
}

</code>```

And this are my implementations.

```<code>def lifecycle_version = "2.2.0"
def room_version = "2.2.5"

//LifeCycle Components
    // ViewModel
    implementation "androidx.lifecycle:lifecycle-viewmodel:$lifecycle_version"
    // LiveData
    implementation "androidx.lifecycle:lifecycle-livedata:$lifecycle_version"
    // Annotation processor
    implementation "androidx.lifecycle:lifecycle-common-java8:$lifecycle_version"

    //Room Components
    implementation "androidx.room:room-runtime:$room_version"
    annotationProcessor "androidx.room:room-compiler:$room_version"
</code>```

答: I had a look to Android Source code. If your activity was extending the class Activity, instead of AppCompatActivity you wouldn't have seen this issue.  The class Activity provides an implementation for the interface HasDefaultViewModelProviderFactory which provides a correct factory for classes extending AndroidViewModel. Unfortunately, AppCompatActivity still doesn't implement that interface, and then, no correct factory is available. So, either you provide the factory as you did, or you might implement by yourself the interface HasDefaultViewModelProviderFactory.

Body:
I am trying to create an instance of my AndroidViewModel in MainActivity. When I do this I get the following error has no zero argument constructor

Here is my RecipeViewModel

package com.example.kookrecepten;

import android.app.Application;

import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;

import java.util.List;

public class RecipeViewModel extends AndroidViewModel {
    private RecipeRepository recipeRepository;
    private LiveData<List<Recipe>> allRecipes;

    public RecipeViewModel(Application application) {
        super(application);
        recipeRepository = new RecipeRepository(application);
        allRecipes = recipeRepository.getAllRecipes();
    }

    public void insert(Recipe recipe) {
        recipeRepository.insert(recipe);
    }

    public void update(Recipe recipe) {
        recipeRepository.update(recipe);
    }

    public void delete(Recipe recipe) {
        recipeRepository.delete(recipe);
    }

    public void deleteAll() {
        recipeRepository.deleteAllRecipes();
    }

    public LiveData<List<Recipe>> getAllRecipes() {
        return allRecipes;
    }
}

Now correct me if I'm wrong but AndroidViewModel needs the Application context in the constructor and ViewModel doesn't. So I have no idea why android asks for a zero arguments constructor.

Here is my Main activity where I ask for an instance.

package com.example.kookrecepten;

import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import com.example.kookrecepten.databinding.ActivityMainBinding;

import java.util.List;

public class MainActivity extends AppCompatActivity {
    private ActivityMainBinding binding;
    private RecipeViewModel recipeViewModel;

    protected void onCreate (Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        binding = ActivityMainBinding.inflate(getLayoutInflater());
        View view = binding.getRoot();
        setContentView(view);

        //Get an instance of the RecipeViewModel.
        recipeViewModel = new ViewModelProvider(this).get(RecipeViewModel.class);
        recipeViewModel.getAllRecipes().observe(this, new Observer<List<Recipe>>() {
            @Override
            public void onChanged(List<Recipe> recipes) {
                //Update recycle view

                Toast.makeText(MainActivity.this, "triggered", Toast.LENGTH_SHORT).show();
            }
        });
    }
}

And this are my implementations.

def lifecycle_version = "2.2.0"
def room_version = "2.2.5"

//LifeCycle Components
    // ViewModel
    implementation "androidx.lifecycle:lifecycle-viewmodel:$lifecycle_version"
    // LiveData
    implementation "androidx.lifecycle:lifecycle-livedata:$lifecycle_version"
    // Annotation processor
    implementation "androidx.lifecycle:lifecycle-common-java8:$lifecycle_version"

    //Room Components
    implementation "androidx.room:room-runtime:$room_version"
    annotationProcessor "androidx.room:room-compiler:$room_version"


问:
Get all first element of tuples from list of lists of tuples in Python
```<code>Input:
orders = [[('Fries', 9)], [('Burger', 6), ('Milkshake', 2), ('Cola', 2)], [('Cola', 2), ('Nuggets', 3), ('Onion Rings', 5)], [('Fries', 9)], [('Big Burger', 7), ('Nuggets', 3)]]

Expected Output:
orders = [['Fries'], ['Burger', 'Milkshare', 'Cola'], ['Cola', 'Nuggets', 'Onion Rings'], ['Fries'], ['Big Burger', 'Nuggets']]
</code>```

My attempt:

```<code> for i, order in enumerate(orders):
        for j,item in enumerate(order):
            orders[i][j] = item[0]
</code>```

Works ok. But are there any more intuitive/one-liner/faster/cooler way to do this?

答:
You can isolate the keys by zipping up each order and returning the first index of each zip result.

The following gives you a list of tuples:

```<code>orders2 = [list(zip(*order))[0] for order in orders]
</code>```

If you need a list of lists, use this:

```<code>orders2 = [list(a) for a in [list(zip(*order))[0] for order in orders]]
</code>```

Code Example

```<code>orders = [[('Fries', 9)], [('Burger', 6), ('Milkshake', 2), ('Cola', 2)], [('Cola', 2), ('Nuggets', 3), ('Onion Rings', 5)], [('Fries', 9)], [('Big Burger', 7), ('Nuggets', 3)]]

# For a list of tuples
orders2 = [list(zip(*order))[0] for order in orders]
print(*orders2) # ('Fries',) ('Burger', 'Milkshake', 'Cola') ('Cola', 'Nuggets', 'Onion Rings') ('Fries',) ('Big Burger', 'Nuggets')

# If you need a list of lists
orders2 = [list(a) for a in [list(zip(*order))[0] for order in orders]]
print(*orders2) # ['Fries'] ['Burger', 'Milkshake', 'Cola'] ['Cola', 'Nuggets', 'Onion Rings'] ['Fries'] ['Big Burger', 'Nuggets']

</code>```

Live Code -> https://onlinegdb.com/SklIG1q6iU

Body:
Input:
orders = [[('Fries', 9)], [('Burger', 6), ('Milkshake', 2), ('Cola', 2)], [('Cola', 2), ('Nuggets', 3), ('Onion Rings', 5)], [('Fries', 9)], [('Big Burger', 7), ('Nuggets', 3)]]

Expected Output:
orders = [['Fries'], ['Burger', 'Milkshare', 'Cola'], ['Cola', 'Nuggets', 'Onion Rings'], ['Fries'], ['Big Burger', 'Nuggets']]

My attempt:

 for i, order in enumerate(orders):
        for j,item in enumerate(order):
            orders[i][j] = item[0]

Works ok. But are there any more intuitive/one-liner/faster/cooler way to do this?

Body:
You can isolate the keys by zipping up each order and returning the first index of each zip result.

The following gives you a list of tuples:

orders2 = [list(zip(*order))[0] for order in orders]

If you need a list of lists, use this:

orders2 = [list(a) for a in [list(zip(*order))[0] for order in orders]]

Code Example

orders = [[('Fries', 9)], [('Burger', 6), ('Milkshake', 2), ('Cola', 2)], [('Cola', 2), ('Nuggets', 3), ('Onion Rings', 5)], [('Fries', 9)], [('Big Burger', 7), ('Nuggets', 3)]]

# For a list of tuples
orders2 = [list(zip(*order))[0] for order in orders]
print(*orders2) # ('Fries',) ('Burger', 'Milkshake', 'Cola') ('Cola', 'Nuggets', 'Onion Rings') ('Fries',) ('Big Burger', 'Nuggets')

# If you need a list of lists
orders2 = [list(a) for a in [list(zip(*order))[0] for order in orders]]
print(*orders2) # ['Fries'] ['Burger', 'Milkshake', 'Cola'] ['Cola', 'Nuggets', 'Onion Rings'] ['Fries'] ['Big Burger', 'Nuggets']

Live Code -> https://onlinegdb.com/SklIG1q6iU