问:
next-auth JWT with custom backend access token never update till the client make hard refresh
I use CredentialsProvider to auth users with the Django backend
take the Credentials in authorize Callback

 async authorize(credentials, req) {
        try {
          const respo = await axios.post(
            "http://127.0.0.1:8000/auth/jwt/create/",
            {
             // hard coded for testing
              phone_number: "123456789",
              password: "123456",
            }
          );

          const { access, refresh } = respo.data;

          const respo1 = await axios.get(
            "http://127.0.0.1:8000/auth/users/me/",
            {
              headers: { Authorization: "JWT " + access },
            }
          );

          return { ...respo1.data, refresh: refresh, access: access };
        } catch (e) {
          return false;
        }
},
```
<p>request Django to create access, refresh token, and user info
then check for access token expire in JWT Callback</p>
<pre class="lang-js prettyprint-override"><code>    async jwt({ token, user, account, profile, isNewUser }) {
      if (user) {
        token.accessToken = user.access;
        token.refreshToken = user.refresh;

        return token;
      }

      if (isJwtExpired(token.accessToken)) {
        const [newAccessToken, newRefreshToken] = await refreshToken(
          token.refreshToken
        );

        if (newAccessToken) {
          token = {
            ...token,
            accessToken: newAccessToken,
            iat: Math.floor(Date.now() / 1000),
            exp: Math.floor(Date.now() / 1000 + 2 * 60 * 60),
          };

          return token;
        }
        setAxiosAuthToken(null);
        return {
          ...token,
          exp: 0,
          error: "RefreshAccessTokenError",
        };
      }

      // token valid
      return token;
    },
</code>```

session callback call setAxiosAuthToken to add Jwt in every Axios request

async session({ session, user, token }) {
      session.accessToken = token.accessToken;
      session.error = token.error;
      setAxiosAuthToken(session.accessToken);
      return session;
    }
},
```
<p>the problem is when the access token is refreshed setAxiosAuthToken never gets an update
and still request the old access token</p>
<p>I tried using <code>getSession()</code> in Axios <code>interceptors.response</code> but <code>getSession()</code> always <code>returns null</code> even in <code>interceptors.request</code>
also tried requesting session URL in Axios interceptors but respond with <code>{}</code></p>
<p>Then I found an article for someone explaining the problem and offering a solution which is to use <code>useSwr</code> to keep the session up to date by pinging the session URL in interval</p>
<pre class="lang-js prettyprint-override"><code>  const { data, error } = useSwr(sessionUrl, fetchSession, {
    revalidateOnFocus: true,
    revalidateOnMount: true,
    revalidateOnReconnect: true,
  });

  useEffect(() => {
    const intervalId = setInterval(
      () => mutate(sessionUrl),
      (refreshInterval || 20) * 1000
    );

    return () => clearInterval(intervalId);
  }, []);

  return {
    session: data,
    loading: typeof data === "undefined" && typeof error === "undefined",
  };
}

</code>```

HOc for require auth views

export function withAuth(refreshInterval) {
  return function (Component) {
    return function (props) {
      const { session, loading } = useAuth(refreshInterval);

      if (typeof window !== undefined && loading) {
        return null;
      }

      if (
        (!loading && !session) ||
        session?.error === "RefreshAccessTokenError"
      ) {
        return (
          <>
            <button onClick={() => signIn()}>Sign in</button>
          </>
        );
      }
      return <Component session={session} {...props} />;
    };
  };
}
```

but the problem remains, session is updated with the latest access Token but Axios never gets updated till the next hard refresh

Body:
I use CredentialsProvider to auth users with the Django backend
take the Credentials in authorize Callback

 async authorize(credentials, req) {
        try {
          const respo = await axios.post(
            "http://127.0.0.1:8000/auth/jwt/create/",
            {
             // hard coded for testing
              phone_number: "123456789",
              password: "123456",
            }
          );

          const { access, refresh } = respo.data;

          const respo1 = await axios.get(
            "http://127.0.0.1:8000/auth/users/me/",
            {
              headers: { Authorization: "JWT " + access },
            }
          );

          return { ...respo1.data, refresh: refresh, access: access };
        } catch (e) {
          return false;
        }
},

request Django to create access, refresh token, and user info
then check for access token expire in JWT Callback

    async jwt({ token, user, account, profile, isNewUser }) {
      if (user) {
        token.accessToken = user.access;
        token.refreshToken = user.refresh;

        return token;
      }

      if (isJwtExpired(token.accessToken)) {
        const [newAccessToken, newRefreshToken] = await refreshToken(
          token.refreshToken
        );

        if (newAccessToken) {
          token = {
            ...token,
            accessToken: newAccessToken,
            iat: Math.floor(Date.now() / 1000),
            exp: Math.floor(Date.now() / 1000 + 2 * 60 * 60),
          };

          return token;
        }
        setAxiosAuthToken(null);
        return {
          ...token,
          exp: 0,
          error: "RefreshAccessTokenError",
        };
      }

      // token valid
      return token;
    },

session callback call setAxiosAuthToken to add Jwt in every Axios request

async session({ session, user, token }) {
      session.accessToken = token.accessToken;
      session.error = token.error;
      setAxiosAuthToken(session.accessToken);
      return session;
    }
},

the problem is when the access token is refreshed setAxiosAuthToken never gets an update
and still request the old access token

I tried using getSession() in Axios interceptors.response but getSession() always returns null even in interceptors.request
also tried requesting session URL in Axios interceptors but respond with {}

Then I found an article for someone explaining the problem and offering a solution which is to use useSwr to keep the session up to date by pinging the session URL in interval

  const { data, error } = useSwr(sessionUrl, fetchSession, {
    revalidateOnFocus: true,
    revalidateOnMount: true,
    revalidateOnReconnect: true,
  });

  useEffect(() => {
    const intervalId = setInterval(
      () => mutate(sessionUrl),
      (refreshInterval || 20) * 1000
    );

    return () => clearInterval(intervalId);
  }, []);

  return {
    session: data,
    loading: typeof data === "undefined" && typeof error === "undefined",
  };
}

HOc for require auth views

export function withAuth(refreshInterval) {
  return function (Component) {
    return function (props) {
      const { session, loading } = useAuth(refreshInterval);

      if (typeof window !== undefined && loading) {
        return null;
      }

      if (
        (!loading && !session) ||
        session?.error === "RefreshAccessTokenError"
      ) {
        return (
          <>
            <button onClick={() => signIn()}>Sign in</button>
          </>
        );
      }
      return <Component session={session} {...props} />;
    };
  };
}

but the problem remains, session is updated with the latest access Token but Axios never gets updated till the next hard refresh


来源: stackexchange

问:
Hi I am new to rust And I tried to setup a matrix rust server... and it always throws me a issue in error.rs

error[E0599]: no method named `map_err` found for type parameter `Self` in the current scope
  --> src\server\error.rs:40:24
   |
34 | pub trait ResultExt<T>: Sized {
   | ----------------------------- method `map_err` not found for this type parameter
...
40 |         let res = self.map_err(|_| MatrixError::internal_err());
   |                        ^^^^^^^ method not found in `Self`
   |
   = help: items from traits can only be used if the type parameter is bounded by the trait
help: the following traits define an item `map_err`, perhaps you need to add another supertrait for one of them:
   |
34 | pub trait ResultExt<T>: Sized + ServiceFactory {
   |                               ++++++++++++++++
34 | pub trait ResultExt<T>: Sized + TryFutureExt {
   |                               ++++++++++++++
34 | pub trait ResultExt<T>: Sized + TryStreamExt {
   |                               ++++++++++++++
34 | pub trait ResultExt<T>: Sized + actix_service::Service {
   |                               ++++++++++++++++++++++++

For more information about this error, try `rustc --explain E0599`.
warning: `maelstrom` (bin "maelstrom") generated 12 warnings
error: could not compile `maelstrom` due to previous error; 12 warnings emitted
```
<p>It runs into an error where it says that <code>self.map_err</code> is not defined</p>
<p>I tried to completely delete the <code>error.rs</code> out of the code (it didn't work)</p>
<p>here is the code to mess around with
(oh and yes the matrix server uses actix web)</p>
```use actix_web::{http::StatusCode, Error, HttpResponse};

#[derive(Clone, Debug, serde::Serialize)]
pub struct MatrixError {
    #[serde(skip)]
    pub status: StatusCode,
    pub errcode: ErrorCode,
    pub error: String,
}

impl MatrixError {
    pub fn new(status: StatusCode, errcode: ErrorCode, error: &str) -> Self {
        MatrixError {
            status,
            errcode,
            error: error.to_string(),
        }
    }

    pub fn internal_err() -> Self {
        Self::new(
            StatusCode::INTERNAL_SERVER_ERROR,
            ErrorCode::UNKNOWN,
            "Internal server error.",
        )
    }
}
impl From<MatrixError> for Error {
    fn from(e: MatrixError) -> Self {
        HttpResponse::build(e.status).json(e).into()
    }
}

pub trait ResultExt<T>: Sized {
    fn with_codes(self, status: StatusCode, code: ErrorCode) -> Result<T, MatrixError>;
    fn unknown(self) -> Result<T, MatrixError> {
        #[cfg(debug_assertions)] // don't leak ISE info in release mode
        let res = self.with_codes(StatusCode::INTERNAL_SERVER_ERROR, ErrorCode::UNKNOWN);
        #[cfg(not(debug_assertions))]
        let res = self.map_err(|_| MatrixError::internal_err());
        res
    }
}

impl<T, E> ResultExt<T> for Result<T, E>
where
    E: std::fmt::Display,
{
    fn with_codes(self, status: StatusCode, code: ErrorCode) -> Result<T, MatrixError> {
        self.map_err(|e| MatrixError {
            status,
            errcode: code,
            error: format!("{}", e),
        })
    }
}
```

ContentLicense: CC BY-SA 4.0

Body:
error[E0599]: no method named `map_err` found for type parameter `Self` in the current scope
  --> src\server\error.rs:40:24
   |
34 | pub trait ResultExt<T>: Sized {
   | ----------------------------- method `map_err` not found for this type parameter
...
40 |         let res = self.map_err(|_| MatrixError::internal_err());
   |                        ^^^^^^^ method not found in `Self`
   |
   = help: items from traits can only be used if the type parameter is bounded by the trait
help: the following traits define an item `map_err`, perhaps you need to add another supertrait for one of them:
   |
34 | pub trait ResultExt<T>: Sized + ServiceFactory {
   |                               ++++++++++++++++
34 | pub trait ResultExt<T>: Sized + TryFutureExt {
   |                               ++++++++++++++
34 | pub trait ResultExt<T>: Sized + TryStreamExt {
   |                               ++++++++++++++
34 | pub trait ResultExt<T>: Sized + actix_service::Service {
   |                               ++++++++++++++++++++++++

For more information about this error, try `rustc --explain E0599`.
warning: `maelstrom` (bin "maelstrom") generated 12 warnings
error: could not compile `maelstrom` due to previous error; 12 warnings emitted

It runs into an error where it says that self.map_err is not defined

I tried to completely delete the error.rs out of the code (it didn't work)

here is the code to mess around with
(oh and yes the matrix server uses actix web)

use actix_web::{http::StatusCode, Error, HttpResponse};

#[derive(Clone, Debug, serde::Serialize)]
pub struct MatrixError {
    #[serde(skip)]
    pub status: StatusCode,
    pub errcode: ErrorCode,
    pub error: String,
}

impl MatrixError {
    pub fn new(status: StatusCode, errcode: ErrorCode, error: &str) -> Self {
        MatrixError {
            status,
            errcode,
            error: error.to_string(),
        }
    }

    pub fn internal_err() -> Self {
        Self::new(
            StatusCode::INTERNAL_SERVER_ERROR,
            ErrorCode::UNKNOWN,
            "Internal server error.",
        )
    }
}
impl From<MatrixError> for Error {
    fn from(e: MatrixError) -> Self {
        HttpResponse::build(e.status).json(e).into()
    }
}

pub trait ResultExt<T>: Sized {
    fn with_codes(self, status: StatusCode, code: ErrorCode) -> Result<T, MatrixError>;
    fn unknown(self) -> Result<T, MatrixError> {
        #[cfg(debug_assertions)] // don't leak ISE info in release mode
        let res = self.with_codes(StatusCode::INTERNAL_SERVER_ERROR, ErrorCode::UNKNOWN);
        #[cfg(not(debug_assertions))]
        let res = self.map_err(|_| MatrixError::internal_err());
        res
    }
}

impl<T, E> ResultExt<T> for Result<T, E>
where
    E: std::fmt::Display,
{
    fn with_codes(self, status: StatusCode, code: ErrorCode) -> Result<T, MatrixError> {
        self.map_err(|e| MatrixError {
            status,
            errcode: code,
            error: format!("{}", e),
        })
    }
}


问:
Error using pixi.js v7.x.x within create-react-app v5: webpack + @babel/plugin-transform-parameters error
I'm trying to use pixi.js in my react app created using create-react-app, however, am getting a webpack/babel error on npm start.

Versions

```<code>create-react-app v5.0.1
pixi.js v7.0.4
</code>```

Code

```<code>import React, { useRef, useEffect } from "react";
import { Application } from "pixi.js";

function MyComponent() {
  const ref = useRef(null);

  useEffect(() => {
    // On first render create our application
    const app = new Application({
      width: 800,
      height: 600,
      backgroundColor: 0x5BBA6F,
    });

    // Add app to DOM
    ref.current.appendChild(app.view);
    // Start the PixiJS app
    app.start();

    return () => {
      // On unload completely destroy the application and all of it's children
      app.destroy(true, true);
    };
  }, []);

  return <div ref={ref} />;
}
</code>```

I run npm install, all fine. I then run npm start and I get the following error:

```<code>ERROR in ./node_modules/@pixi/core/lib/textures/resources/ImageBitmapResource.mjs

SyntaxError: ./node_modules/@pixi/core/lib/textures/resources/ImageBitmapResource.mjs: When using '@babel/plugin-transform-parameters', it's not possible to compile \`super()\` in an arrow function with default or rest parameters without compiling classes.
Please add '@babel/plugin-transform-classes' to your Babel configuration.
6 |   constructor(source, options) {
7 |     var \__super = (...args) =\> {
\\>  8 |       super(...args);
|       ^^^^^^^^^^^^^^
9 |     };
10 |     options = options || {};
11 |     if (typeof source === "string") {
.
.
.
webpack compiled with 1 error
</code>```

I've tried installing the @babel/plugin-transform-classes to babel config following these steps. Error persists.

Down-grading to pixi.js version 6.5.8 resolves the error, just hoping to find a solution that allows me to use 7.x.x

Cheers!

Body:
I'm trying to use pixi.js in my react app created using create-react-app, however, am getting a webpack/babel error on npm start.

Versions

create-react-app v5.0.1
pixi.js v7.0.4

Code

import React, { useRef, useEffect } from "react";
import { Application } from "pixi.js";

function MyComponent() {
  const ref = useRef(null);

  useEffect(() => {
    // On first render create our application
    const app = new Application({
      width: 800,
      height: 600,
      backgroundColor: 0x5BBA6F,
    });

    // Add app to DOM
    ref.current.appendChild(app.view);
    // Start the PixiJS app
    app.start();

    return () => {
      // On unload completely destroy the application and all of it's children
      app.destroy(true, true);
    };
  }, []);

  return
;
}

I run npm install, all fine. I then run npm start and I get the following error:

ERROR in ./node_modules/@pixi/core/lib/textures/resources/ImageBitmapResource.mjs

SyntaxError: ./node_modules/@pixi/core/lib/textures/resources/ImageBitmapResource.mjs: When using '@babel/plugin-transform-parameters', it's not possible to compile \`super()\` in an arrow function with default or rest parameters without compiling classes.
Please add '@babel/plugin-transform-classes' to your Babel configuration.
6 |   constructor(source, options) {
7 |     var \__super = (...args) =\> {
\\>  8 |       super(...args);
|       ^^^^^^^^^^^^^^
9 |     };
10 |     options = options || {};
11 |     if (typeof source === "string") {
.
.
.
webpack compiled with 1 error

I've tried installing the @babel/plugin-transform-classes to babel config following these steps. Error persists.

Down-grading to pixi.js version 6.5.8 resolves the error, just hoping to find a solution that allows me to use 7.x.x

Cheers!


问:
What is this 'stdin' argument in subprocess?
```<code>from subprocess import *
run(args='cat', stdin='testfile.txt')
</code>```

What does stdin do in the subprocess module in python ?

Body:
from subprocess import *
run(args='cat', stdin='testfile.txt')

What does stdin do in the subprocess module in python ?


问:
How to list data from MYSQL in HTML
I want to list the data registered in my table over mysql database on html using Go. How can I achieve this. I am able to list on the terminal console, but unfortunately I could not do it with html.

```<code>package main

import (
    "database/sql"
    "fmt"
    _ "github.com/go-sql-driver/mysql"
    "html/template"
    "log"
    "net/http"
)

func add_user(isimsoyisim string, telefon string, eposta string) bool {

    db, err := sql.Open("mysql", "root:PASSWORD@tcp(127.0.0.1:3306)/deneme1")
    if err != nil {
        panic(err)
    }
    add, err := db.Query("INSERT INTO telefondefter (isimsoyisim,telefon,eposta) VALUES (?,?,?)", (isimsoyisim), (telefon), (eposta))
    if err != nil {
        panic(err)
    }

    fmt.Println(add)
    defer db.Close()
    return true
}

func kayitekle1(w http.ResponseWriter, r *http.Request) {
    var tmplt = template.Must(template.ParseFiles("html/index.html"))
    tmplt.Execute(w, nil)
}

func kayitekle(w http.ResponseWriter, r *http.Request) {
    r.ParseForm()
    var isimsoyisim = r.Form["isimsoyisim"]
    var telefon = r.Form["telefon"]
    var eposta = r.Form["eposta"]
    fmt.Println(isimsoyisim, telefon, eposta)
    if add_user(isimsoyisim[0], telefon[0], eposta[0]) {
        var tmplt = template.Must(template.ParseFiles("html/index3.html"))
        tmplt.Execute(w, nil)
    } else {
        var tmplt = template.Must(template.ParseFiles("html/error.html"))
        tmplt.Execute(w, nil)
    }
}

func kayitlist(w http.ResponseWriter, r *http.Request) {
    var tmplt = template.Must(template.ParseFiles("html/index2.html"))
    rows, err := db.Query("SELECT * FROM telefondefter")
    if err != nil {
        log.Println(err)
        panic(err)
        return
    }
    var id int
    var isimsoyisim string
    var telefon string
    var eposta string
    var ps []PersonData

    for rows.Next() {
        err = rows.Scan(&id, &isimsoyisim, &telefon, &eposta)
        if err != nil {
            log.Println(err)
            panic(err)
            return
        }
        ps = append(ps, PersonData{id: id, isimsoyisim: isimsoyisim, telefon: telefon, eposta: eposta})
    }
    tmplt.Execute(w, nil)
}

func main() {
    http.Handle("/scss/", http.StripPrefix("/scss/", http.FileServer(http.Dir("scss"))))
    http.Handle("/src/", http.StripPrefix("/src/", http.FileServer(http.Dir("src"))))
    http.Handle("/rtl/", http.StripPrefix("/rtl/", http.FileServer(http.Dir("rtl"))))
    http.Handle("/html/", http.StripPrefix("/html/", http.FileServer(http.Dir("html"))))
    http.Handle("/layouts/", http.StripPrefix("/layouts/", http.FileServer(http.Dir("layouts"))))
    http.Handle("/tmp/", http.StripPrefix("/tmp/", http.FileServer(http.Dir("tmp"))))

    fmt.Println("Server Başlatılıyor")

    http.HandleFunc("/", kayitekle1)
    http.HandleFunc("/kayitekle", kayitekle)
    http.HandleFunc("/kayitlist", kayitlist)
    http.ListenAndServe(":8999", nil)

}
</code>```

HTML (INDEX2)

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, shrink-to-fit=no">
    <title>Golang Defter Uygulaması </title>
    <link rel="icon" type="image/x-icon" href="../src/assets/img/favicon.ico"/>
    <link href="../layouts/modern-light-menu/css/light/loader.css" rel="stylesheet" type="text/css" />
    <link href="../layouts/modern-light-menu/css/dark/loader.css" rel="stylesheet" type="text/css" />
    <script src="../layouts/modern-light-menu/loader.js"></script>
    <!-- BEGIN GLOBAL MANDATORY STYLES -->
    <link href="https://fonts.googleapis.com/css?family=Nunito:400,600,700" rel="stylesheet">
    <link href="../src/bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
    <link href="../layouts/modern-light-menu/css/light/plugins.css" rel="stylesheet" type="text/css" />
    <link href="../layouts/modern-light-menu/css/dark/plugins.css" rel="stylesheet" type="text/css" />
    <!-- END GLOBAL MANDATORY STYLES -->

    <!--  BEGIN CUSTOM STYLE FILE  -->
    <link href="../src/assets/css/light/scrollspyNav.css" rel="stylesheet" type="text/css" />
    <link href="../src/assets/css/dark/scrollspyNav.css" rel="stylesheet" type="text/css" />
    <!--  END CUSTOM STYLE FILE  -->
</head>
<body class="layout-boxed" data-bs-spy="scroll" data-bs-target="#navSection" data-bs-offset="100">

    <!-- BEGIN LOADER -->
    <div id="load_screen"> <div class="loader"> <div class="loader-content">
        <div class="spinner-grow align-self-center"></div>
    </div></div></div>
    <!--  END LOADER -->

    <!--  BEGIN NAVBAR  -->

    <!--  END NAVBAR  -->

    <!--  BEGIN MAIN CONTAINER  -->
    <div class="main-container " id="container">

        <div class="overlay"></div>
        <div class="cs-overlay"></div>
        <div class="search-overlay"></div>

        <!--  BEGIN SIDEBAR  -->
        <div class="sidebar-wrapper sidebar-theme">

              <nav id="sidebar">

                <div class="navbar-nav theme-brand flex-row  text-center">
                    <div class="nav-logo">
                        <div class="nav-item theme-logo">
                            <a href="./index.html">
                                <img src="../src/assets/img/logo.svg" class="navbar-logo" alt="logo">
                            </a>
                        </div>
                        <div class="nav-item theme-text">
                            <a href="./index.html" class="nav-link"> ERMAT </a>
                        </div>
                    </div>
                    <div class="nav-item sidebar-toggle">
                        <div class="btn-toggle sidebarCollapse">
                            <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-chevrons-left"><polyline points="11 17 6 12 11 7"></polyline><polyline points="18 17 13 12 18 7"></polyline></svg>
                        </div>
                    </div>
                </div>

                <div class="shadow-bottom"></div>
                <ul class="list-unstyled menu-categories" id="accordionExample">
                    <li class="menu active">

                            <div>
                                <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-chevron-right"><polyline points="9 18 15 12 9 6"></polyline></svg>
                            </div>

                        <ul class="collapse submenu list-unstyled show" id="dashboard" data-bs-parent="#accordionExample">
                            <li class="active">
                                <a href="./index.html"> Kayıt Ekleme </a>
                            </li>
                            <li>
                                <a href="./index2.html"> Kayıtları Listele </a>
                            </li>
                        </ul>
                    </li>
                </ul>

            </nav>

        </div>
        <!--  END SIDEBAR  -->

        <!--  BEGIN CONTENT AREA  -->
        <div id="content" class="main-content">
            <div class="container">

                <div class="container">

                    <!-- BREADCRUMB -->

                    <!-- /BREADCRUMB -->

                    <div class="row layout-top-spacing">

                        <div id="basic" class="col-lg-12 layout-spacing">
                            <div class="statbox widget box box-shadow">
                                <div class="widget-header">
                                    <div class="row">
                                        <div class="col-xl-12 col-md-12 col-sm-12 col-12">
                                            <h4>Telefon Defter Kayit Listesi</h4>
                                        </div>
                                    </div>
                                </div>
                                <div class="widget-content widget-content-area">

                                    <div class="row">
                                        <div class="col-lg-6 col-12 ">
                                            <form name="kayitekle" action="/kayitekle" method="post">
                                                <div class="form-group">
                                                    <!DOCTYPE html>
<html lang="en" >
<head>
  <meta charset="UTF-8">
  <title>Ermat Kayit List</title>
  <link rel="stylesheet" href="/dist/">

</head>
<body>
<!-- partial:index.partial.html -->
<center><p>
<table>
  <thead>
    <tr>
      <th scope="col">ID</th>
      <th scope="col">AdSoyad</th>
      <th scope="col">Telefon</th>
      <th scope="col">Eposta</th>

  </thead>
  <tbody>
    <tr>
      <td>{{.id}}</td>
      <td>{{.isimsoyisim}}</td>
      <td>{{.telefon}}</td>
      <td>{{.eposta}}</td>
    <tr>

  </tbody>
</table>
  </p></center>
<!-- partial -->

</body>
</html>

                                                </div>
                                            </form>
                                        </div>
                                    </div>

                                </div>
                            </div>
                        </div>

            <!--  BEGIN FOOTER  -->
            <div class="footer-wrapper">
                <div class="footer-section f-section-1">
                    <p class="">Copyright © <span class="dynamic-year">2022</span> <a target="_blank" href="https://designreset.com/cork-admin/">Ermat</a>, All rights reserved.</p>
                </div>
                <div class="footer-section f-section-2">
                    <p class="">Coded with Deniz Korkmazer<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-heart"><path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"></path></svg></p>
                </div>
            </div>
            <!--  END FOOTER  -->

        </div>
        <!--  END CONTENT AREA  -->
    </div>
    <!-- END MAIN CONTAINER -->

    <!-- BEGIN GLOBAL MANDATORY SCRIPTS -->
    <script src="../src/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script src="../src/plugins/src/perfect-scrollbar/perfect-scrollbar.min.js"></script>
    <script src="../src/plugins/src/mousetrap/mousetrap.min.js"></script>
    <script src="../src/plugins/src/waves/waves.min.js"></script>
    <script src="../layouts/modern-light-menu/app.js"></script>
    <script src="../src/plugins/src/highlight/highlight.pack.js"></script>
    <!-- END GLOBAL MANDATORY SCRIPTS -->
    <script src="../src/assets/js/scrollspyNav.js"></script>
  </body>
</html>
</code>```

Title: How to list data from MYSQL in HTML

Body:
I want to list the data registered in my table over mysql database on html using Go. How can I achieve this. I am able to list on the terminal console, but unfortunately I could not do it with html.

package main

import (
    "database/sql"
    "fmt"
    _ "github.com/go-sql-driver/mysql"
    "html/template"
    "log"
    "net/http"
)

func add_user(isimsoyisim string, telefon string, eposta string) bool {

    db, err := sql.Open("mysql", "root:PASSWORD@tcp(127.0.0.1:3306)/deneme1")
    if err != nil {
        panic(err)
    }
    add, err := db.Query("INSERT INTO telefondefter (isimsoyisim,telefon,eposta) VALUES (?,?,?)", (isimsoyisim), (telefon), (eposta))
    if err != nil {
        panic(err)
    }

    fmt.Println(add)
    defer db.Close()
    return true
}

func kayitekle1(w http.ResponseWriter, r *http.Request) {
    var tmplt = template.Must(template.ParseFiles("html/index.html"))
    tmplt.Execute(w, nil)
}

func kayitekle(w http.ResponseWriter, r *http.Request) {
    r.ParseForm()
    var isimsoyisim = r.Form["isimsoyisim"]
    var telefon = r.Form["telefon"]
    var eposta = r.Form["eposta"]
    fmt.Println(isimsoyisim, telefon, eposta)
    if add_user(isimsoyisim[0], telefon[0], eposta[0]) {
        var tmplt = template.Must(template.ParseFiles("html/index3.html"))
        tmplt.Execute(w, nil)
    } else {
        var tmplt = template.Must(template.ParseFiles("html/error.html"))
        tmplt.Execute(w, nil)
    }
}

func kayitlist(w http.ResponseWriter, r *http.Request) {
    var tmplt = template.Must(template.ParseFiles("html/index2.html"))
    rows, err := db.Query("SELECT * FROM telefondefter")
    if err != nil {
        log.Println(err)
        panic(err)
        return
    }
    var id int
    var isimsoyisim string
    var telefon string
    var eposta string
    var ps []PersonData

    for rows.Next() {
        err = rows.Scan(&id, &isimsoyisim, &telefon, &eposta)
        if err != nil {
            log.Println(err)
            panic(err)
            return
        }
        ps = append(ps, PersonData{id: id, isimsoyisim: isimsoyisim, telefon: telefon, eposta: eposta})
    }
    tmplt.Execute(w, nil)
}

func main() {
    http.Handle("/scss/", http.StripPrefix("/scss/", http.FileServer(http.Dir("scss"))))
    http.Handle("/src/", http.StripPrefix("/src/", http.FileServer(http.Dir("src"))))
    http.Handle("/rtl/", http.StripPrefix("/rtl/", http.FileServer(http.Dir("rtl"))))
    http.Handle("/html/", http.StripPrefix("/html/", http.FileServer(http.Dir("html"))))
    http.Handle("/layouts/", http.StripPrefix("/layouts/", http.FileServer(http.Dir("layouts"))))
    http.Handle("/tmp/", http.StripPrefix("/tmp/", http.FileServer(http.Dir("tmp"))))

    fmt.Println("Server Başlatılıyor")

    http.HandleFunc("/", kayitekle1)
    http.HandleFunc("/kayitekle", kayitekle)
    http.HandleFunc("/kayitlist", kayitlist)
    http.ListenAndServe(":8999", nil)

}

HTML (INDEX2)

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, shrink-to-fit=no">
    <title>Golang Defter Uygulaması </title>
    <link rel="icon" type="image/x-icon" href="../src/assets/img/favicon.ico"/>
    <link href="../layouts/modern-light-menu/css/light/loader.css" rel="stylesheet" type="text/css" />
    <link href="../layouts/modern-light-menu/css/dark/loader.css" rel="stylesheet" type="text/css" />

    <link href="https://fonts.googleapis.com/css?family=Nunito:400,600,700" rel="stylesheet">
    <link href="../src/bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
    <link href="../layouts/modern-light-menu/css/light/plugins.css" rel="stylesheet" type="text/css" />
    <link href="../layouts/modern-light-menu/css/dark/plugins.css" rel="stylesheet" type="text/css" />

    <link href="../src/assets/css/light/scrollspyNav.css" rel="stylesheet" type="text/css" />
    <link href="../src/assets/css/dark/scrollspyNav.css" rel="stylesheet" type="text/css" />

                             ERMAT

                            <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-chevrons-left"><polyline points="11 17 6 12 11 7"></polyline><polyline points="18 17 13 12 18 7"></polyline></svg>

                                <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-chevron-right"><polyline points="9 18 15 12 9 6"></polyline></svg>

                                 Kayıt Ekleme

                                 Kayıtları Listele

Telefon Defter Kayit Listesi

                                            <form name="kayitekle" action="/kayitekle" method="post">

                                                    <!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Ermat Kayit List</title>
  <link rel="stylesheet" href="/dist/">

      ID
      AdSoyad
      Telefon
      Eposta

      {{.id}}
      {{.isimsoyisim}}
      {{.telefon}}
      {{.eposta}}

                                            </form>

Copyright © 2022 Ermat, All rights reserved.

Coded with Deniz Korkmazer<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-heart"><path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"></path></svg>


问:
The log driver for mail is adding some extra characters in the log file
I update the Laravel version to 9. Everything is working fine after the upgrade.

I am using the Log driver for mail as I am developing on my local system but the mail content inserts in my laravel.log file append some extra content so it is difficult to open the URL.
The next line is converted into = and I don't know what is this --443HnvBP--.

This extra append string makes the verification link invalid (i.e 404 page).

MAIL_MAILER=log

Here is the example (User verification email).

Text version:

```<code>Thanks for crea=
ting an account with InstaWP.

Verify your email account by clicking on=
 below button

Verify Email Address: http://localhost:8000/email/verify=
/3/744ff86c600429114e8bcbfcf2c38d23b227ad74?expires=3D1670592804&signature=
=3D55417e62485ca154af312bd48703c3e1849379ef7a0a0398d2378a4ae2638b04

Re=
gards,
InstaWP Team
</code>```

HTML version (I didn't provide the entire content but you get the idea):

Verify Email Address
=

=

--443HnvBP--
```

However, these mail content are working fine with all mail clients but the real issue is with the local development.
Generally, when I was on Laravel 8, after sending a mail, I opened the laravel.log file and click on the link which directly redirect me to the web browser.

but now I have to manually correct the URL first which is a very cumbersome job.

Here are the details of the packages.

Laravel Version: 9.43.0

PHP Version: 8.1.11

Database Driver & Version: Server version: 8.0.25 - MySQL

Body:
I update the Laravel version to 9. Everything is working fine after the upgrade.

I am using the Log driver for mail as I am developing on my local system but the mail content inserts in my laravel.log file append some extra content so it is difficult to open the URL.
The next line is converted into = and I don't know what is this --443HnvBP--.

This extra append string makes the verification link invalid (i.e 404 page).

MAIL_MAILER=log

Here is the example (User verification email).

Text version:

Thanks for crea=
ting an account with InstaWP.

Verify your email account by clicking on=
 below button

Verify Email Address: http://localhost:8000/email/verify=
/3/744ff86c600429114e8bcbfcf2c38d23b227ad74?expires=3D1670592804&signature=
=3D55417e62485ca154af312bd48703c3e1849379ef7a0a0398d2378a4ae2638b04

Re=
gards,
InstaWP Team

HTML version (I didn't provide the entire content but you get the idea):

<a href=3D"http://localhost:8000/email/verify/3/744ff86c6=
00429114e8bcbfcf2c38d23b227ad74?expires=3D1670592804&signature=3D55417e=
62485ca154af312bd48703c3e1849379ef7a0a0398d2378a4ae2638b04" class=3D"button=
 button-primary" target=3D"_blank" rel=3D"noopener" style=3D"box-sizing: bo=
rder-box; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Robot=
o, Helvetica, Arial, sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Se=
goe UI Symbol'; position: relative; -webkit-text-size-adjust: none; border-=
radius: 4px; color: #fff; display: inline-block; overflow: hidden; text-dec=
oration: none; background-color: #2d3748; border-bottom: 8px solid #2d3748;=
 border-left: 18px solid #2d3748; border-right: 18px solid #2d3748; border-=
top: 8px solid #2d3748;">Verify Email Address
=

=

--443HnvBP--

However, these mail content are working fine with all mail clients but the real issue is with the local development.
Generally, when I was on Laravel 8, after sending a mail, I opened the laravel.log file and click on the link which directly redirect me to the web browser.

but now I have to manually correct the URL first which is a very cumbersome job.

Here are the details of the packages.

Laravel Version: 9.43.0

PHP Version: 8.1.11

Database Driver & Version: Server version: 8.0.25 - MySQL


问:
Converting json objects to csv using Twitter API in Python (adding username and description)
I want to collect tweets with the Twitter API (Academic Access) and I just want to add the username, name and the description to the csv and it just doesn't work. I could really need some help, thank you in advance!

This is the code:

```<code>def create_url(keyword, start_date, end_date, max_results = 10):

search_url = "https://api.twitter.com/2/tweets/search/all" #Change to the endpoint you want to collect data from

#change params based on the endpoint you are using
query_params = {'query': keyword,
                'start_time': start_date,
                'end_time': end_date,
                'max_results': max_results,
                'expansions': 'author_id,in_reply_to_user_id,geo.place_id',
                'tweet.fields': 'id,text,author_id,in_reply_to_user_id,geo,conversation_id,created_at,lang,public_metrics,referenced_tweets,reply_settings,source',
                'user.fields': 'id,name,username,created_at,description,public_metrics,verified',
                'place.fields': 'full_name,id,country,country_code,geo,name,place_type',
                'next_token': {}}
return (search_url, query_params)

def connect_to_endpoint(url, headers, params, next_token = None):
params['next_token'] = next_token   #params object received from create_url function
response = requests.request("GET", url, headers = headers, params = params)
print("Endpoint Response Code: " + str(response.status_code))
if response.status_code != 200:
    raise Exception(response.status_code, response.text)
return response.json()

def append_to_csv(json_response, fileName):

#A counter variable
counter = 0

#Open OR create the target CSV file
csvFile = open(fileName, "a", newline="", encoding='utf-8')
csvWriter = csv.writer(csvFile)

#Loop through each tweet
for tweet in json_response['data']:

    # Create a variable for each since some of the keys might not exist for some tweets

    # 1. Author ID
    author_id = tweet['author_id']

    # 2. Author Username
    username = tweet['username']

    # 3. Author name
    name = tweet['name']

    # 4. Author Description
    description = tweet['description']

    # 5. Time created
    created_at = dateutil.parser.parse(tweet['created_at'])

    # 6. Tweet text
    text = tweet['text']

    # 7. Geolocation
    if ('geo' in tweet):
        geo = tweet['geo']['place_id']
    else:
        geo = " "

    # 8. Tweet ID
    tweet_id = tweet['id']

    # 9. Language
    lang = tweet['lang']

    # 10. Tweet metrics
    retweet_count = tweet['public_metrics']['retweet_count']
    reply_count = tweet['public_metrics']['reply_count']
    like_count = tweet['public_metrics']['like_count']
    quote_count = tweet['public_metrics']['quote_count']

    # 11. source
    source = tweet['source']

    # Assemble all data in a list
    res = [author_id, username, name, description, created_at, text, geo, tweet_id, lang, like_count, quote_count, reply_count, retweet_count, source]

    # Append the result to the CSV file
    csvWriter.writerow(res)
    counter += 1

# When done, close the CSV file
csvFile.close()
</code>```

The Problem is in section append_to_csv, as I get a KeyError for username, name and description. Do you have an idea what I have to change in #2, 3, and 4 to be able to add these columns to my csv? Thank you so much in advance!

Body:
I want to collect tweets with the Twitter API (Academic Access) and I just want to add the username, name and the description to the csv and it just doesn't work. I could really need some help, thank you in advance!

This is the code:

def create_url(keyword, start_date, end_date, max_results = 10):

search_url = "https://api.twitter.com/2/tweets/search/all" #Change to the endpoint you want to collect data from

#change params based on the endpoint you are using
query_params = {'query': keyword,
                'start_time': start_date,
                'end_time': end_date,
                'max_results': max_results,
                'expansions': 'author_id,in_reply_to_user_id,geo.place_id',
                'tweet.fields': 'id,text,author_id,in_reply_to_user_id,geo,conversation_id,created_at,lang,public_metrics,referenced_tweets,reply_settings,source',
                'user.fields': 'id,name,username,created_at,description,public_metrics,verified',
                'place.fields': 'full_name,id,country,country_code,geo,name,place_type',
                'next_token': {}}
return (search_url, query_params)

def connect_to_endpoint(url, headers, params, next_token = None):
params['next_token'] = next_token   #params object received from create_url function
response = requests.request("GET", url, headers = headers, params = params)
print("Endpoint Response Code: " + str(response.status_code))
if response.status_code != 200:
    raise Exception(response.status_code, response.text)
return response.json()

def append_to_csv(json_response, fileName):

#A counter variable
counter = 0

#Open OR create the target CSV file
csvFile = open(fileName, "a", newline="", encoding='utf-8')
csvWriter = csv.writer(csvFile)

#Loop through each tweet
for tweet in json_response['data']:

    # Create a variable for each since some of the keys might not exist for some tweets

    # 1. Author ID
    author_id = tweet['author_id']

    # 2. Author Username
    username = tweet['username']

    # 3. Author name
    name = tweet['name']

    # 4. Author Description
    description = tweet['description']

    # 5. Time created
    created_at = dateutil.parser.parse(tweet['created_at'])

    # 6. Tweet text
    text = tweet['text']

    # 7. Geolocation
    if ('geo' in tweet):
        geo = tweet['geo']['place_id']
    else:
        geo = " "

    # 8. Tweet ID
    tweet_id = tweet['id']

    # 9. Language
    lang = tweet['lang']

    # 10. Tweet metrics
    retweet_count = tweet['public_metrics']['retweet_count']
    reply_count = tweet['public_metrics']['reply_count']
    like_count = tweet['public_metrics']['like_count']
    quote_count = tweet['public_metrics']['quote_count']

    # 11. source
    source = tweet['source']

    # Assemble all data in a list
    res = [author_id, username, name, description, created_at, text, geo, tweet_id, lang, like_count, quote_count, reply_count, retweet_count, source]

    # Append the result to the CSV file
    csvWriter.writerow(res)
    counter += 1

# When done, close the CSV file
csvFile.close()

The Problem is in section append_to_csv, as I get a KeyError for username, name and description. Do you have an idea what I have to change in #2, 3, and 4 to be able to add these columns to my csv? Thank you so much in advance!


问:
Generating Subtitles of a Youtube video when CC is not available
How to get subtitles of a youtube video when CC is not available (using python). Is there any library to make it possible?

I tried using youtube_transcript_api for YT videos that have CC. I want it for videos that do not have CC and I don't want to download the video for getting mp4 to text. I want it directly.


问:
react-slick sets its own "dir" attribute
I use react-slick library and it turns out that it sets its own "dir" attribute. I set the direction for the whole app in the main container, but react-slick overrides it for itself. Is there any option to fix this?</p>
```<code><div dir="rtl" className={appClassName}>
   <div slick-slider slick-initialized dir="ltr">
      // some code
   </div>
</div>
</code>```

Body:
I use react-slick library and it turns out that it sets its own "dir" attribute. I set the direction for the whole app in the main container, but react-slick overrides it for itself. Is there any option to fix this?

      // some code


问:
Removing form buttons from a phpbb forum reply editor via user.js (aka tampermonkey) script
I'd like to remove or disable a couple of buttons from the reply editor of a phpbb forum I'm a member of, because the bbcodes they insert are too tempting but for some reason reserved for "more mortals".

Removing is probably the easiest solution; I have already identified what code to remove to achieve this:

```<code></button>
    <button type="button" class="button button-secondary bbcode-anchor" name="addbbcode24" value="anchor" onclick="bbstyle(24)" title="Anchor: [anchor]Name of the anchor[/anchor]">
    anchor
</button>
    <button type="button" class="button button-secondary bbcode-goto" name="addbbcode26" value="goto" onclick="bbstyle(26)" title="Goto: [goto=Anchor Name]Link tekst[/goto]">
    goto
</button>
</code>```

In the old days I would do this via a filter in Privoxy but nowadays that requires setting up its https_inspection, which I'd prefer to avoid.

I think it should be possible to do this via an in-browser userscript, e.g. via Tampermonkey. I found a promising JS function on here (https://stackoverflow.com/a/50537862/1460868) but have little idea for now how to deploy it (I have no knowledge of Javascript):

the function uses node.textContent.replace(); does it take simple expression (if so, how to pass a multi-line pattern?) or a regexp (and if so, what flavour)?

some guidelines/pointers as to how to put this function in a user.js/tampermonkey script would be appreciated.

Thanks in advance!

Body:
I'd like to remove or disable a couple of buttons from the reply editor of a phpbb forum I'm a member of, because the bbcodes they insert are too tempting but for some reason reserved for "more mortals".

Removing is probably the easiest solution; I have already identified what code to remove to achieve this:

</button>
    <button type="button" class="button button-secondary bbcode-anchor" name="addbbcode24" value="anchor" onclick="bbstyle(24)" title="Anchor: [anchor]Name of the anchor[/anchor]">
    anchor
</button>
    <button type="button" class="button button-secondary bbcode-goto" name="addbbcode26" value="goto" onclick="bbstyle(26)" title="Goto: [goto=Anchor Name]Link tekst[/goto]">
    goto
</button>

In the old days I would do this via a filter in Privoxy but nowadays that requires setting up its https_inspection, which I'd prefer to avoid.

I think it should be possible to do this via an in-browser userscript, e.g. via Tampermonkey. I found a promising JS function on here (https://stackoverflow.com/a/50537862/1460868) but have little idea for now how to deploy it (I have no knowledge of Javascript):

the function uses node.textContent.replace(); does it take simple expression (if so, how to pass a multi-line pattern?) or a regexp (and if so, what flavour)?

some guidelines/pointers as to how to put this function in a user.js/tampermonkey script would be appreciated.

Thanks in advance!


问:
Hi everyone.. Please I have been trying to run scripts on powershell administrator
When I inputted "Get-ExecutionPolicy" it showed me AllSigned in. then i want to enable running of scripts by inputting the cmdlet "Get-ExecutionPolicy unrestricted" then it displaenter image description hereyed the error in this image. Please how can I solve it

I tried using the "Get-ExecutionPolicy unrestricted" cmdlet and it allow me to enable Scripts running on my powershellenter image description here


问:
Trying to run some c# code in my PowerShell script
I'm looking for a way to use the following C# code in my PowerShell script:

```<code>[DllImport("shell32.dll", SetLastError=true)]
static extern void SetCurrentProcessExplicitAppUserModelID( [MarshalAs(UnmanagedType.LPWStr)] string AppID);
SetCurrentProcessExplicitAppUserModelID("MyAUMID");
</code>```

My Windows application starts another application, which is basically PowerShell script compiled with PS1 to Exe. I'm trying to see if I can have both exe files grouped on the taskbar by giving them the same AUMID. Does anybody know how to run this C# code in my PowerShell script? I think I need to use something like:

```<code>$loadLibrary = @'
[DllImport("shell32.dll", SetLastError=true)]
static extern void SetCurrentProcessExplicitAppUserModelID( [MarshalAs( UnmanagedType.LPWStr )] string AppID );
'@
</code>```

But I don't know how to use the SetCurrentProcessExplicitAppUserModelID() properly.
Thanks for any help in advance!

Kind regards, Eric

Body:
I'm looking for a way to use the following C# code in my PowerShell script:

[DllImport("shell32.dll", SetLastError=true)]
static extern void SetCurrentProcessExplicitAppUserModelID( [MarshalAs(UnmanagedType.LPWStr)] string AppID);
SetCurrentProcessExplicitAppUserModelID("MyAUMID");

My Windows application starts another application, which is basically PowerShell script compiled with PS1 to Exe. I'm trying to see if I can have both exe files grouped on the taskbar by giving them the same AUMID. Does anybody know how to run this C# code in my PowerShell script? I think I need to use something like:

$loadLibrary = @'
[DllImport("shell32.dll", SetLastError=true)]
static extern void SetCurrentProcessExplicitAppUserModelID( [MarshalAs( UnmanagedType.LPWStr )] string AppID );
'@

But I don't know how to use the SetCurrentProcessExplicitAppUserModelID() properly.
Thanks for any help in advance!

Kind regards, Eric


问:
How to solve django.core.paginator.EmptyPage error?
I'm trying to filter and paginate objects in a template. I created a views and I have 3 objects. I want to list 1 object in a page. When I do it it shows the page numbers (should be 3 pages) when I click next it gives me the error:

raise EmptyPage(_('That page contains no results')) django.core.paginator.EmptyPage:
That page contains no results

How can I solve that?

views

```<code>class EntitySelect(FormView):
    template_name = 'sgm/entity_select.html'
    form_class = EntitySelectForm

    def get_context_data(self):
        self.context = super().get_context_data(**self.kwargs)
        process_type = ProcessType.objects.get(id=self.kwargs['process_type'])
        entity = process_type.consolidate_on
        rows = getattr(entities, entity).objects.all()
        paginator = Paginator(rows, 10)
        page_number = self.request.GET.get('page')
        if page_number == None:
            page_number = 1
        page_obj = paginator.page(int(page_number))
        rows = getattr(entities, entity).objects.all()
        if entity == 'Merchant':
            tableFilter = MerchantFilter(self.request.GET, queryset=rows)
        else:
            tableFilter = CustomerFilter(self.request.GET, queryset=rows)

        rows_2 = tableFilter.qs
        paginator = Paginator(rows_2, 2)
        page_number = self.request.GET.get('page')
        if page_number == None:
            page_number = 1
        page_obj = paginator.page(int(page_number))
        self.context['entity_type'] = entity
        self.context['columns'] = [field.name for field in getattr(entities, entity)._meta.local_fields if
                                   field.name != 'entity_ptr']
        self.context['tableFilter'] = tableFilter
        self.context['columns'] = [field.name for field in getattr(entities, entity)._meta.local_fields if field.name != 'entity_ptr']
        self.context['rows'] = page_obj
        self.context['process_type'] = process_type
</code>```

template

```<code> <table class="table table-striped table-condensed table-hover">
        <thead>
          <th> Select </th>
          {% for column in columns %}
            <th> {{ column|title|pretty_title }}</th>
          {% endfor %}
        </thead>
        {% for row in rows %}
          <tr onclick="checked(`{{ row.id }}`)">
            <td>
              <input type="radio" id="{{ row.id }}" name="entity" value="{{ row.identifier }}" required>
            </td>
            <label for="{{ row.identifier }}">
              {% for column in columns %}
                <td> {% if row|get_obj_attr:column %}{{ row|get_obj_attr:column }}{% else %} {% endif %}</td>
              {% endfor %}
            </label>
          </tr>
        {% endfor %}
      </table>
    <div class="col-4 offset-4">
            <nav aria-label="...">
                <ul class="pagination">

                    {% if rows.has_previous %}
                        <li class="page-item">
                            <a href="?page={{ rows.previous_page_number }}" class="page-link">Previous</a>
                        </li>
                        <li>
                            <a class="page-link" href="?page={{ rows.previous_page_number }}">
                                {{ rows.previous_page_number }}
                            </a>
                        </li>
                    {% else %}
                        <li class="page-item disabled">
                            <span class="page-link">Previous</span>
                        </li>
                    {% endif %}

                    <li class="page-item active">
                        <span class="page-link">{{ rows.number }}</span>
                    </li>

                    {% if rows.has_next %}
                        <li class="page-item">
                            <a class="page-link" href="?page={{ rows.next_page_number }}">
                                {{ rows.next_page_number }}
                            </a>
                        </li>
                        <li class="page-item ">
                            <a class="page-link" href="?page={{ rows.next_page_number }}">Next</a>
                        </li>
                    {% else %}
                        <li class="page-item disabled">
                            <span class="page-link">Next</span>
                        </li>
                    {% endif %}

                </ul>
            </nav>
        </div>
</code>```

Body:
I'm trying to filter and paginate objects in a template. I created a views and I have 3 objects. I want to list 1 object in a page. When I do it it shows the page numbers (should be 3 pages) when I click next it gives me the error:

raise EmptyPage(_('That page contains no results')) django.core.paginator.EmptyPage:
That page contains no results

How can I solve that?

views

class EntitySelect(FormView):
    template_name = 'sgm/entity_select.html'
    form_class = EntitySelectForm

    def get_context_data(self):
        self.context = super().get_context_data(**self.kwargs)
        process_type = ProcessType.objects.get(id=self.kwargs['process_type'])
        entity = process_type.consolidate_on
        rows = getattr(entities, entity).objects.all()
        paginator = Paginator(rows, 10)
        page_number = self.request.GET.get('page')
        if page_number == None:
            page_number = 1
        page_obj = paginator.page(int(page_number))
        rows = getattr(entities, entity).objects.all()
        if entity == 'Merchant':
            tableFilter = MerchantFilter(self.request.GET, queryset=rows)
        else:
            tableFilter = CustomerFilter(self.request.GET, queryset=rows)

        rows_2 = tableFilter.qs
        paginator = Paginator(rows_2, 2)
        page_number = self.request.GET.get('page')
        if page_number == None:
            page_number = 1
        page_obj = paginator.page(int(page_number))
        self.context['entity_type'] = entity
        self.context['columns'] = [field.name for field in getattr(entities, entity)._meta.local_fields if
                                   field.name != 'entity_ptr']
        self.context['tableFilter'] = tableFilter
        self.context['columns'] = [field.name for field in getattr(entities, entity)._meta.local_fields if field.name != 'entity_ptr']
        self.context['rows'] = page_obj
        self.context['process_type'] = process_type

template

           Select
          {% for column in columns %}
             {{ column|title|pretty_title }}
          {% endfor %}

        {% for row in rows %}
          <tr onclick="checked(`{{ row.id }}`)">

              <input type="radio" id="{{ row.id }}" name="entity" value="{{ row.identifier }}" required>

              {% for column in columns %}
                 {% if row|get_obj_attr:column %}{{ row|get_obj_attr:column }}{% else %} {% endif %}
              {% endfor %}

        {% endfor %}

                    {% if rows.has_previous %}

                            Previous

                                {{ rows.previous_page_number }}

                    {% else %}

                            Previous

                    {% endif %}

                        {{ rows.number }}

                    {% if rows.has_next %}

                                {{ rows.next_page_number }}

                            Next

                    {% else %}

                            Next

                    {% endif %}


问:
setMediaAspectRatio(MediaAspectRatio.PORTRAIT) is not working Google ad manager
I need to load a Portrait Full-screen native ad.

I have set the nativeAdOptions like these

val nativeAdOptions = NativeAdOptions.Builder().setMediaAspectRatio(MediaAspectRatio.PORTRAIT).build()

and load the ad like this

```<code>AdLoader.Builder(context, adUnitId).withNativeAdOptions(nativeAdOptions)
</code>```

Even I set the MediaAspectRatio to MediaAspectRatio.PORTRAIT.
I am getting landscape ads.

Is there any issue with Google Ad Manager SDK or Do I need to specify any extra AdOptions?

Body:
I need to load a Portrait Full-screen native ad.

I have set the nativeAdOptions like these

val nativeAdOptions = NativeAdOptions.Builder().setMediaAspectRatio(MediaAspectRatio.PORTRAIT).build()

and load the ad like this

AdLoader.Builder(context, adUnitId).withNativeAdOptions(nativeAdOptions)

Even I set the MediaAspectRatio to MediaAspectRatio.PORTRAIT.
I am getting landscape ads.

Is there any issue with Google Ad Manager SDK or Do I need to specify any extra AdOptions?


问:
Way to pivot multiple rows into columns in Tableau using Custom SQL?
I am using a snowflake data source for tableau and unfortunately the generated results show like this

Agent
Manager
Row
Question
Answer

Bob
Cindy
1
Breakfast?
yes

Bob
Cindy
2
Lunch?
no

Bob
Cindy
3
Dinner?
maybe

Jim
Debby
1
Breakfast?
yes

Jim
Debby
2
Lunch?
no

Jim
Debby
3
Dinner?
maybe

and I'm trying to get it to look like this

Agent
Manager
Question1
question2
question3
answer1
answer2
answer3

Bob
Cindy
Breakfast?
Lunch?
Dinner?
yes
no
maybe

Jim
Debby
Breakfast?
Lunch?
Dinner?
yes
no
maybe

The pivot options aren't available because it's coming from snowflake, and I only seem to find results that show how to convert columns to rows using SQL, but nothing showing how to do rows to columns in Tableau from a snowflake connection.  There seems to be certain things you can't use in the tableau sql that you can do in snowflake so I'm just at a loss at this point.

The snowflake data is also unavailable to do queries on so I'm stuck only able to fix it through Tableau. Any suggestions on how to do this? or if it's doable? Thanks in advance.


问:
How to avoid "linear" glitches generated using lightkurve package to obtain Light Curves (by cuts over FFI of TESS)?
I'm trying to obtain Light Curves (LCs) making cuts over Full Frame Images (FFIs) of TESS, but sometimes I obtain different types of glitches (Figure 1) when I obtain the cuts (TPF-like objects). I need to avoid/eliminate automatically these glitches because I will obtain LCs automatically and I can't eliminate these glitches one by one manually.

Figure 1: Types of glitches ("random", "empty" and "linear". I need to find a way to eliminate the linear ones.)

I can avoid the first two types that I'm showing in the image (For the first one, I use an IF to select TPFs with a mask with one or more pixels. For the second one, I use an IF too to select TPFs where the central pixel have a flux diferent to zero). But the way to eliminate the linear glitches is not trivial for me.


问:
how to make a NavLink activeClassName change background color when clicked
i am trying to make a  nav bar when a  navlink is clicked i want  the activelink to change background-color
i have used  NavLink but it is not woeking for some reasome pls help

```<code>export class side extends Component {
  render() {

    return (
      <div className="l-navbar " id="nav-bar">

        <nav className="nav">

          <NavLink
            activeClassName="active3"
            className="porpssidebar"
            exact={true}
            to="/"
          >
            <div>
              <a href="#" className="nav_logo">
                <img className="slogo" src={forur} />
                <i className="fas fa-angry"></i>{" "}
              </a>
            </div>
          </NavLink>

          <NavLink activeClassName="active3" exact={true} to="/orders">
            <div>
              {" "}
              <a href="#" className="nav_logo">
                <Orders />
                <i className="fas fa-angry"></i>{" "}
              </a>
            </div>
          </NavLink>
          <NavLink to="/customers" activeClassName="active3">
            <div>
              {" "}
              <a href="#" className="nav_logo">
                <Package />
                <i className="fas fa-angry"></i>{" "}
              </a>
            </div>
          </NavLink>

      </div>
    );
  }
}

export default side;
</code>```

in app.css i have a class called active3 for changing color

```<code>.active3 {
  background: black;
}

</code>```

Body:
i am trying to make a  nav bar when a  navlink is clicked i want  the activelink to change background-color
i have used  NavLink but it is not woeking for some reasome pls help

export class side extends Component {
  render() {

    return (

          <NavLink
            activeClassName="active3"
            className="porpssidebar"
            exact={true}
            to="/"
          >

                {" "}

          </NavLink>

          <NavLink activeClassName="active3" exact={true} to="/orders">

              {" "}

                <Orders />
                {" "}

          </NavLink>
          <NavLink to="/customers" activeClassName="active3">

              {" "}

                <Package />
                {" "}

          </NavLink>

    );
  }
}

export default side;

in app.css i have a class called active3 for changing color

.active3 {
  background: black;
}


问:
asp.net core populate environment variables from appsettings.json
I have a solution layed out as follows -

Class library

Azure Function

.net Core Web App

The class library is shared between the function and web app and obtains configuration values by calling Environment.GetEnvironmentVariable(). This works great for the Azure function, I can specify the values in local.settings.json for development and in Configuration -> application settings in the azure portal.

In the web app I am building the configuration like so -

```<code>builder.Configuration
        .SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
        .AddJsonFile($"appsettings.json", true, true)
        .AddEnvironmentVariables();
</code>```

Then I am injecting IConfiguration config into the controller's constructor but I would like the functionality to work the same as the Azure Function, so that in the class library, Environment.GetEnvironmentVariable() will return the values from appsettings.json in the web app .

Question - how can I get the web app to populate environment variables in the same way Azure Functions do?

Body:
I have a solution layed out as follows -

Class library

Azure Function

.net Core Web App

The class library is shared between the function and web app and obtains configuration values by calling Environment.GetEnvironmentVariable(). This works great for the Azure function, I can specify the values in local.settings.json for development and in Configuration -> application settings in the azure portal.

In the web app I am building the configuration like so -

builder.Configuration
        .SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
        .AddJsonFile($"appsettings.json", true, true)
        .AddEnvironmentVariables();

Then I am injecting IConfiguration config into the controller's constructor but I would like the functionality to work the same as the Azure Function, so that in the class library, Environment.GetEnvironmentVariable() will return the values from appsettings.json in the web app .

Question - how can I get the web app to populate environment variables in the same way Azure Functions do?


问:
Unexpected ragged shape from tf.gather
```<code>x = tf.gather(tf.ragged.constant([[0],[2,3,4],[3,4]]), tf.constant([[0,1,2],[1,2,1]]))
tf.shape(x)
</code>```

has shape
<DynamicRaggedShape lengths=[2, (3, 3), (1, 3, 2, 3, 2, 3)] num_row_partitions=2>
however I expect
<DynamicRaggedShape lengths=[2, 3, (1, 3, 2, 3, 2, 3)] num_row_partitions=2>

I tried to reshape it, but is there a better solution by giving more informtion to tf.gather?

Title: Unexpected ragged shape from tf.gather

Body:
x = tf.gather(tf.ragged.constant([[0],[2,3,4],[3,4]]), tf.constant([[0,1,2],[1,2,1]]))
tf.shape(x)

has shape
<DynamicRaggedShape lengths=[2, (3, 3), (1, 3, 2, 3, 2, 3)] num_row_partitions=2>
however I expect
<DynamicRaggedShape lengths=[2, 3, (1, 3, 2, 3, 2, 3)] num_row_partitions=2>

I tried to reshape it, but is there a better solution by giving more informtion to tf.gather?


问:
Laragon - access wordpress folder inside laravel app
I have a Laravel app and I want to install WordPress inside that app. So, the folder structure will be like this:

```<code>my-laravel-app
   - app
   - bootstrap
   - blog      <--- This is the WordPress folder
       - wp-admin
       - wp-content
       - wp-includes
       ...
   - config
   - database
   ...
</code>```

I can access my laravel app using this link in laragon:

```<code>https://my-laravel-app.test
</code>```

But, when I access the blog folder, it causes 404 NOT FOUND

```<code>https://my-laravel-app.test/blog
</code>```

Here's the my-laravel-app/.htaccess file

```<code><IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews -Indexes
    </IfModule>

    RewriteEngine On

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} (.+)/$
    RewriteRule ^ %1 [L,R=301]

    # Send Requests To Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
</IfModule>
</code>```

Here's the my-laravel-app/blog/.htaccess file

```<code># BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /my-laravel-app/blog/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /my-laravel-app/blog/index.php [L]
</IfModule>
# END WordPress
</code>```

What configuration should I do to make this link https://my-laravel-app.test/blog work?

Body:
I have a Laravel app and I want to install WordPress inside that app. So, the folder structure will be like this:

my-laravel-app
   - app
   - bootstrap
   - blog      <--- This is the WordPress folder
       - wp-admin
       - wp-content
       - wp-includes
       ...
   - config
   - database
   ...

I can access my laravel app using this link in laragon:

https://my-laravel-app.test

But, when I access the blog folder, it causes 404 NOT FOUND

https://my-laravel-app.test/blog

Here's the my-laravel-app/.htaccess file

<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews -Indexes
    </IfModule>

    RewriteEngine On

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} (.+)/$
    RewriteRule ^ %1 [L,R=301]

    # Send Requests To Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
</IfModule>

Here's the my-laravel-app/blog/.htaccess file

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /my-laravel-app/blog/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /my-laravel-app/blog/index.php [L]
</IfModule>
# END WordPress

What configuration should I do to make this link https://my-laravel-app.test/blog work?


问:
Laravell, artisan error Class "App\Console\Kernel" does not exist
I have install fresh version of laravel and put inside my script, after that I want to run migrations but there is an error from artisan that class Kernel does not exist when oryginal file in /app/console/Kernel.php exist

error:

```<code>php artisan

PHP Fatal error:  Uncaught ReflectionException: Class "App\Console\Kernel" does not exist in /home/john/domains/mydomain.com/vendor/laravel/framework/src/Illuminate/Container/Container.php:875
Stack trace:
#0 /home/john/domains/mydomain.com/vendor/laravel/framework/src/Illuminate/Container/Container.php(875): ReflectionClass->__construct()
(...)
#8 /home/john/domains/mydomain.com/vendor/laravel/framework/src/Illuminate/Foundation/Application.php(845): Illuminate\Container\Container->make()
#9 /home/john/domains/mydomain.com/artisan(33): Illuminate\Foundation\Application->make()
#10 {main}

Next Illuminate\Contracts\Container\BindingResolutionException: Target class [App\Console\Kernel] does not exist. in /home/john/domains/mydomain.com/vendor/laravel/framework/src/Illuminate/Container/Container.php:877
Stack trace:
#0 /home/john/domains/mydomain.com/vendor/laravel/framework/src/Illuminate/Container/Container.php(756): Illuminate\Container\Container->build()
(...)
#8 /home/john/domains/mydomain.com/artisan(33): Illuminate\Foundation\Application->make()
#9 {main}
  thrown in /home/john/domains/mydomain.com/vendor/laravel/framework/src/Illuminate/Container/Container.php on line 877

</code>```

I have check if Kernel file exist, trying to remove vendor folder and composer install but problem still exist

Body:
I have install fresh version of laravel and put inside my script, after that I want to run migrations but there is an error from artisan that class Kernel does not exist when oryginal file in /app/console/Kernel.php exist

error:

php artisan

PHP Fatal error:  Uncaught ReflectionException: Class "App\Console\Kernel" does not exist in /home/john/domains/mydomain.com/vendor/laravel/framework/src/Illuminate/Container/Container.php:875
Stack trace:
#0 /home/john/domains/mydomain.com/vendor/laravel/framework/src/Illuminate/Container/Container.php(875): ReflectionClass->__construct()
(...)
#8 /home/john/domains/mydomain.com/vendor/laravel/framework/src/Illuminate/Foundation/Application.php(845): Illuminate\Container\Container->make()
#9 /home/john/domains/mydomain.com/artisan(33): Illuminate\Foundation\Application->make()
#10 {main}

Next Illuminate\Contracts\Container\BindingResolutionException: Target class [App\Console\Kernel] does not exist. in /home/john/domains/mydomain.com/vendor/laravel/framework/src/Illuminate/Container/Container.php:877
Stack trace:
#0 /home/john/domains/mydomain.com/vendor/laravel/framework/src/Illuminate/Container/Container.php(756): Illuminate\Container\Container->build()
(...)
#8 /home/john/domains/mydomain.com/artisan(33): Illuminate\Foundation\Application->make()
#9 {main}
  thrown in /home/john/domains/mydomain.com/vendor/laravel/framework/src/Illuminate/Container/Container.php on line 877

I have check if Kernel file exist, trying to remove vendor folder and composer install but problem still exist


问:
How can I facet wrap for specific categorical values of multiple variables in Shiny?
as part of my research, I'm designing a Shiny app that allows visualization of a big pile of data. However, right now I'm working on the base of the app. For my app, I want the user to facet wrap just for specific categorical values of a variable. I'm working on a meta-analysis so I'm sure the number of categorical values will increase. Therefore, it would be much easier to look at a few values instead of all of them. Anyways, this is how my data looks like:

```<code>ABXID | ANIMALID | TIME | TLD | DV | DOSEMGKG | SPECIES | SUBSPECIES | AGE | PLATFORM | MUTATION
</code>```

I know there's a lot of data, but it's all useful. So, for example the platform variable has different values, three to be exact: Duobody, Hexabody and Bispecific. I want the user to choose what type of antibody platform they want to be displayed and even more than just 1. Not only will I be doing this for PLATFORM, but also for the other variables, allowing the user to really see what they want. My Shiny app looks like this:

Note: I have only written the conditionPanels for PLATFORM and MUTATION, because I think it would be easy to see if it would work and if anyone could help me.

```<code>ui <- fluidPage(

    tabsetPanel(tabPanel("Tab 1",

        titlePanel("Shiny App: Concentration vs Time Graphs"),

         sidebarLayout(
            mainPanel("Concentration vs Time graphs", plotOutput(outputId = "plot")),
            sidebarPanel(helpText("This app is developed to visualize pharmacokinetic data of different antibodies..."),
            selectInput(
                inputId = "study",
                label = "Include study:",
                choices = c("GLP Toxicity" = "ME1044-011", "Dose Range Finding", "Single Dose", "Repeat Dose"),
                selected = "ME1044-011",
                multiple = T
            ),
            selectInput(
                inputId = "x",
                label = "X-axis:",
                choices = c("Time" = "TIME", "TLD"),
                selected = "Time"
            ),
            selectInput(
                inputId = 'column',
                label = "Columns for:",
                choices = c("Dose mg/kg" = "DOSEMGKG", "Species" = "SPECIES", "Antibody" = "ABXID", "Subspecies" = "SUBSPECIES", "Age" = "AGE", "Animal ID" = "ANIMALID"),
                selected = "DOSEMGKG"
            ),
            selectInput(
                inputId = 'row',
                label = "Rows for:",
                choices = c("Dose mg/kg" = "DOSEMGKG", "Species" = "SPECIES", "Antibody" = "ABXID", "Subspecies" = "SUBSPECIES", "Age" = "AGE",  "Animal ID" = "ANIMALID", "Platform" = "PLATFORM"),
                selected = "ABXID"
            ),
            conditionalPanel(
                condition = "input.row == 'PLATFORM'",
                selectInput(
                    inputId = 'platform',
                    label = "Choose platform(s)",
                    choices = c("Hexabody", "Duobody", "Bispecific"), multiple = T
                 )
            ),
            conditionalPanel(
                conditoin = "input.row == 'Mutation'",
                selectInput(
                    inputId = 'mutation',
                    label = "Choose mutation(s):",
                    choices = c('M1', "M2", "M3"), multiple = T
                )
            ),
            selectInput(
                inputId = "group",
                label = "Group by:",
                choices = c("Dose mg/kg" = "DOSEMGKG", "Species" = "SPECIES", "Antibody" = "ABXID", "Subspecies" = "SUBSPECIES", "Age" = "AGE",  "Animal ID" = "ANIMALID"),
                selected = "ANIMALID"
            ),
            sliderInput(
                inputId = 'trange',
                label = "Time range:",
                min = 0,
                max = 1704,
                value = c(0, 1704 )
            )
                    ))

    )),

    tabsetPanel(tabPanel("Tab 2",

        titlePanel("Tab 2"),

            sidebarLayout(
                mainPanel("Plot #2", plotOutput(outputId = "plot2")),
                    sidebarPanel(helpText("Whatever text..."),
                        selectInput(
                        inputId = 't',
                        label = "Example",
                        choices = c("#1", "#2", "#3"),
                        selected = "#1"
                        )
                             )
                         )))
)

</code>```

This is the server:

```<code>server <- function(input, output, session){

    output$plot <- renderPlot({
        ggplot(data = df, aes_string(x = input$x, y = "DV", col = input$group)) + xlab("Time") + ylab("Concentration (ug/mL)") +
            geom_point() + facet_grid(get(input$row) ~ get(input$column)) + scale_x_continuous(limits = input$trange) +
            scale_color_viridis(discrete = T) + theme_bw() })

}

shinyApp(ui = ui, server = server)

</code>```

Anyways, I really hope someone can help me with this question, as I'm fairly new to Shiny and still am learning things. So with the conditionPanel, a selectInput will appear if the user clicks on the variable, allowing them to choose what value they want to be displayed. That's how I want them to use the app. I hope the helpful readers get my question!

I have tried facet_wrap(), but that is showing me all the values of course. I'm not familiar with other options. Anyways, I hope I can just facet_wrap() for specific values of a variable that the user has chosen, even if it's more than 1.

Body:
as part of my research, I'm designing a Shiny app that allows visualization of a big pile of data. However, right now I'm working on the base of the app. For my app, I want the user to facet wrap just for specific categorical values of a variable. I'm working on a meta-analysis so I'm sure the number of categorical values will increase. Therefore, it would be much easier to look at a few values instead of all of them. Anyways, this is how my data looks like:

ABXID | ANIMALID | TIME | TLD | DV | DOSEMGKG | SPECIES | SUBSPECIES | AGE | PLATFORM | MUTATION

I know there's a lot of data, but it's all useful. So, for example the platform variable has different values, three to be exact: Duobody, Hexabody and Bispecific. I want the user to choose what type of antibody platform they want to be displayed and even more than just 1. Not only will I be doing this for PLATFORM, but also for the other variables, allowing the user to really see what they want. My Shiny app looks like this:

Note: I have only written the conditionPanels for PLATFORM and MUTATION, because I think it would be easy to see if it would work and if anyone could help me.

ui <- fluidPage(

    tabsetPanel(tabPanel("Tab 1",

        titlePanel("Shiny App: Concentration vs Time Graphs"),

         sidebarLayout(
            mainPanel("Concentration vs Time graphs", plotOutput(outputId = "plot")),
            sidebarPanel(helpText("This app is developed to visualize pharmacokinetic data of different antibodies..."),
            selectInput(
                inputId = "study",
                label = "Include study:",
                choices = c("GLP Toxicity" = "ME1044-011", "Dose Range Finding", "Single Dose", "Repeat Dose"),
                selected = "ME1044-011",
                multiple = T
            ),
            selectInput(
                inputId = "x",
                label = "X-axis:",
                choices = c("Time" = "TIME", "TLD"),
                selected = "Time"
            ),
            selectInput(
                inputId = 'column',
                label = "Columns for:",
                choices = c("Dose mg/kg" = "DOSEMGKG", "Species" = "SPECIES", "Antibody" = "ABXID", "Subspecies" = "SUBSPECIES", "Age" = "AGE", "Animal ID" = "ANIMALID"),
                selected = "DOSEMGKG"
            ),
            selectInput(
                inputId = 'row',
                label = "Rows for:",
                choices = c("Dose mg/kg" = "DOSEMGKG", "Species" = "SPECIES", "Antibody" = "ABXID", "Subspecies" = "SUBSPECIES", "Age" = "AGE",  "Animal ID" = "ANIMALID", "Platform" = "PLATFORM"),
                selected = "ABXID"
            ),
            conditionalPanel(
                condition = "input.row == 'PLATFORM'",
                selectInput(
                    inputId = 'platform',
                    label = "Choose platform(s)",
                    choices = c("Hexabody", "Duobody", "Bispecific"), multiple = T
                 )
            ),
            conditionalPanel(
                conditoin = "input.row == 'Mutation'",
                selectInput(
                    inputId = 'mutation',
                    label = "Choose mutation(s):",
                    choices = c('M1', "M2", "M3"), multiple = T
                )
            ),
            selectInput(
                inputId = "group",
                label = "Group by:",
                choices = c("Dose mg/kg" = "DOSEMGKG", "Species" = "SPECIES", "Antibody" = "ABXID", "Subspecies" = "SUBSPECIES", "Age" = "AGE",  "Animal ID" = "ANIMALID"),
                selected = "ANIMALID"
            ),
            sliderInput(
                inputId = 'trange',
                label = "Time range:",
                min = 0,
                max = 1704,
                value = c(0, 1704 )
            )
                    ))

    )),

    tabsetPanel(tabPanel("Tab 2",

        titlePanel("Tab 2"),

            sidebarLayout(
                mainPanel("Plot #2", plotOutput(outputId = "plot2")),
                    sidebarPanel(helpText("Whatever text..."),
                        selectInput(
                        inputId = 't',
                        label = "Example",
                        choices = c("#1", "#2", "#3"),
                        selected = "#1"
                        )
                             )
                         )))
)

This is the server:

server <- function(input, output, session){

    output$plot <- renderPlot({
        ggplot(data = df, aes_string(x = input$x, y = "DV", col = input$group)) + xlab("Time") + ylab("Concentration (ug/mL)") +
            geom_point() + facet_grid(get(input$row) ~ get(input$column)) + scale_x_continuous(limits = input$trange) +
            scale_color_viridis(discrete = T) + theme_bw() })

}

shinyApp(ui = ui, server = server)

Anyways, I really hope someone can help me with this question, as I'm fairly new to Shiny and still am learning things. So with the conditionPanel, a selectInput will appear if the user clicks on the variable, allowing them to choose what value they want to be displayed. That's how I want them to use the app. I hope the helpful readers get my question!

I have tried facet_wrap(), but that is showing me all the values of course. I'm not familiar with other options. Anyways, I hope I can just facet_wrap() for specific values of a variable that the user has chosen, even if it's more than 1.


问:
Migrate a go repository from Bitbucket to Gitlab
I have a go repository and several dependency repositories I recently moved from BitBucket to GitLab. The latest version works as the dependencies have been updated, but the older versions are still pointing to bitbucket where the repo no longer exists. Is there anyway for me to fix the git history to point to the new location other than updating every commit? I would like to save the history because there are several major releases.</p>


问:
How to get the first element of a python list with a [start:stop:-1] slice?
I have a list like this:

list = ['a', 'b', 'c']

I want the first element only, by using a list slicer that counts down.
That is:

list[start:stop:-1]

What do I set as start and stop to return exactly ['a']?

My first intuition would be list[0:-1:-1], but this returns an empty list.


问:
Making GAN work for both Cifar10 and Mnist datasets
I'm building a Cyclic GAN based GAN that needs to work for both Mnist and Cifar10 datasets. With Cifar10 it runs smoothly, but with Mnist it gives this error:

RuntimeError: Given groups=1, weight of size [56, 1, 7, 7], expected input[1, 3, 30, 30] to have 1 channels, but got 3 channels instead

The complete code is here: https://gist.github.com/lucasseadi/bbe265ade7cdc1c5ed481fd837037fc2

Here are the layers for the Generator:

```<code>model = [
    nn.ReflectionPad2d(channels),
    nn.Conv2d(channels, out_features, 7),
    nn.InstanceNorm2d(out_features),
    nn.ReLU(inplace=True)
]
in_features = out_features

for _ in range(2):
    out_features *= 2
    model += [
        nn.Conv2d(in_features, out_features, 3, stride=2, padding=1),
        nn.InstanceNorm2d(out_features),
        nn.ReLU(inplace=True)
    ]
    in_features = out_features

for _ in range(num_residual_block):
    model += [ResidualBlock(out_features, channels)]

for _ in range(2):
    out_features = out_features // 2
    model += [
        nn.Upsample(scale_factor=2),
        nn.Conv2d(in_features, out_features, 3, stride=1, padding=1),
        nn.InstanceNorm2d(out_features),
        nn.ReLU(inplace=True)
    ]
    in_features = out_features

model += [
    nn.ReflectionPad2d(channels),
    nn.Conv2d(out_features, channels, 7),
    nn.Tanh()
]
self.model = nn.Sequential(*model)
</code>```

And here are the layers for the Discriminator:

```<code>def discriminator_block(in_filters, out_filters, normalize=True):
    layers = [nn.Conv2d(in_filters, out_filters, 4, stride=2, padding=1)]
    if normalize:
        layers.append(nn.InstanceNorm2d(out_filters))
    layers.append(nn.LeakyReLU(0.2, inplace=True))
    return layers
</code>```
```<code>self.model = nn.Sequential(
    *discriminator_block(self.channels, 2 * self.height, normalize=False),
    *discriminator_block(2 * self.height, 3 * self.height),
    *discriminator_block(3 * self.height, 4 * self.height),
    *discriminator_block(4 * self.height, 5 * self.height),
    nn.ZeroPad2d((1, 0, 1, 0)),
    nn.Conv2d(5 * self.height, 1, 4, padding=1)
)
</code>```

I've tried to generalize the code to work for both datasets and I tried adjusting the nn.Conv2d layers but no success.

Body:
I'm building a Cyclic GAN based GAN that needs to work for both Mnist and Cifar10 datasets. With Cifar10 it runs smoothly, but with Mnist it gives this error:

RuntimeError: Given groups=1, weight of size [56, 1, 7, 7], expected input[1, 3, 30, 30] to have 1 channels, but got 3 channels instead

The complete code is here: https://gist.github.com/lucasseadi/bbe265ade7cdc1c5ed481fd837037fc2

Here are the layers for the Generator:

model = [
    nn.ReflectionPad2d(channels),
    nn.Conv2d(channels, out_features, 7),
    nn.InstanceNorm2d(out_features),
    nn.ReLU(inplace=True)
]
in_features = out_features

for _ in range(2):
    out_features *= 2
    model += [
        nn.Conv2d(in_features, out_features, 3, stride=2, padding=1),
        nn.InstanceNorm2d(out_features),
        nn.ReLU(inplace=True)
    ]
    in_features = out_features

for _ in range(num_residual_block):
    model += [ResidualBlock(out_features, channels)]

for _ in range(2):
    out_features = out_features // 2
    model += [
        nn.Upsample(scale_factor=2),
        nn.Conv2d(in_features, out_features, 3, stride=1, padding=1),
        nn.InstanceNorm2d(out_features),
        nn.ReLU(inplace=True)
    ]
    in_features = out_features

model += [
    nn.ReflectionPad2d(channels),
    nn.Conv2d(out_features, channels, 7),
    nn.Tanh()
]
self.model = nn.Sequential(*model)

And here are the layers for the Discriminator:

def discriminator_block(in_filters, out_filters, normalize=True):
    layers = [nn.Conv2d(in_filters, out_filters, 4, stride=2, padding=1)]
    if normalize:
        layers.append(nn.InstanceNorm2d(out_filters))
    layers.append(nn.LeakyReLU(0.2, inplace=True))
    return layers

self.model = nn.Sequential(
    *discriminator_block(self.channels, 2 * self.height, normalize=False),
    *discriminator_block(2 * self.height, 3 * self.height),
    *discriminator_block(3 * self.height, 4 * self.height),
    *discriminator_block(4 * self.height, 5 * self.height),
    nn.ZeroPad2d((1, 0, 1, 0)),
    nn.Conv2d(5 * self.height, 1, 4, padding=1)
)

I've tried to generalize the code to work for both datasets and I tried adjusting the nn.Conv2d layers but no success.


问:
selenium not sending keys but manages to click on the search bar?
i manage to find the search bar (click it) but fail to send any keys i tried everything from different elements to even using javascript but it always fails to send any keys

i tired every element i could find even tried javascript but it all failed

summery of the search bar code -

```<code>driver.find_element(By.XPATH, '(//div)[125]').click()
time.sleep(2)
driver.find_element(By.XPATH, '(//div)[125]').clear()
time.sleep(2)
driver.find_element(By.XPATH, "(//span)[125]").send_keys("abc")
time.sleep(1)
driver.find_element(By.XPATH, '(//div)[125]').send_keys(Keys.ENTER)

---
copy past of html code for the search bar
<div class="sc-bdVaJa hjHTBy sDash_fullwidth-select" style="--gap:8px; --template: initial;"><div class="ant-select sc-htoDjs iOndSp ant-select-single ant-select-show-arrow ant-select-open ant-select-show-search"><div class="ant-select-selector"><span class="ant-select-selection-search"><input type="search" autocomplete="off" class="ant-select-selection-search-input" role="combobox" aria-haspopup="listbox" aria-owns="rc_select_1_list" aria-autocomplete="list" aria-controls="rc_select_1_list" aria-activedescendant="rc_select_1_list_0" value="" id="rc_select_1" aria-expanded="true"></span><span class="ant-select-selection-placeholder">Search from Lahore</span></div><span class="ant-select-arrow" unselectable="on" aria-hidden="true" style="user-select: none;"><span role="img" class="anticon"><svg stroke="currentColor" fill="currentColor" stroke-width="0" viewBox="0 0 24 24" height="1.2em" width="1.2em" xmlns="http://www.w3.org/2000/svg"><path fill="none" d="M0 0h24v24H0z"></path><path d="M7.41 15.41L12 10.83l4.59 4.58L18 14l-6-6-6 6z"></path></svg></span></span></div></div>

<div class="ant-select sc-htoDjs iOndSp ant-select-single ant-select-show-arrow ant-select-open ant-select-show-search"><div class="ant-select-selector"><span class="ant-select-selection-search"><input type="search" autocomplete="off" class="ant-select-selection-search-input" role="combobox" aria-haspopup="listbox" aria-owns="rc_select_1_list" aria-autocomplete="list" aria-controls="rc_select_1_list" aria-activedescendant="rc_select_1_list_0" value="" id="rc_select_1" aria-expanded="true"></span><span class="ant-select-selection-placeholder">Search from Lahore</span></div><span class="ant-select-arrow" unselectable="on" aria-hidden="true" style="user-select: none;"><span role="img" class="anticon"><svg stroke="currentColor" fill="currentColor" stroke-width="0" viewBox="0 0 24 24" height="1.2em" width="1.2em" xmlns="http://www.w3.org/2000/svg"><path fill="none" d="M0 0h24v24H0z"></path><path d="M7.41 15.41L12 10.83l4.59 4.58L18 14l-6-6-6 6z"></path></svg></span></span></div>

<div class="ant-select-selector"><span class="ant-select-selection-search"><input type="search" autocomplete="off" class="ant-select-selection-search-input" role="combobox" aria-haspopup="listbox" aria-owns="rc_select_1_list" aria-autocomplete="list" aria-controls="rc_select_1_list" aria-activedescendant="rc_select_1_list_0" value="" id="rc_select_1" aria-expanded="true"></span><span class="ant-select-selection-placeholder">Search from Lahore</span></div>

::before

<span class="ant-select-selection-search"><input type="search" autocomplete="off" class="ant-select-selection-search-input" role="combobox" aria-haspopup="listbox" aria-owns="rc_select_1_list" aria-autocomplete="list" aria-controls="rc_select_1_list" aria-activedescendant="rc_select_1_list_0" value="" id="rc_select_1" aria-expanded="true"></span>

<input type="search" autocomplete="off" class="ant-select-selection-search-input" role="combobox" aria-haspopup="listbox" aria-owns="rc_select_1_list" aria-autocomplete="list" aria-controls="rc_select_1_list" aria-activedescendant="rc_select_1_list_0" value="" id="rc_select_1" aria-expanded="true">

<span class="ant-select-selection-search"><input type="search" autocomplete="off" class="ant-select-selection-search-input" role="combobox" aria-haspopup="listbox" aria-owns="rc_select_1_list" aria-autocomplete="list" aria-controls="rc_select_1_list" aria-activedescendant="rc_select_1_list_0" value="" id="rc_select_1" aria-expanded="true"></span>

<span class="ant-select-selection-placeholder">Search from Lahore</span>

::after
</span>
</code>```

Body:
i manage to find the search bar (click it) but fail to send any keys i tried everything from different elements to even using javascript but it always fails to send any keys

i tired every element i could find even tried javascript but it all failed

summery of the search bar code -

driver.find_element(By.XPATH, '(//div)[125]').click()
time.sleep(2)
driver.find_element(By.XPATH, '(//div)[125]').clear()
time.sleep(2)
driver.find_element(By.XPATH, "(//span)[125]").send_keys("abc")
time.sleep(1)
driver.find_element(By.XPATH, '(//div)[125]').send_keys(Keys.ENTER)

---
copy past of html code for the search bar

<input type="search" autocomplete="off" class="ant-select-selection-search-input" role="combobox" aria-haspopup="listbox" aria-owns="rc_select_1_list" aria-autocomplete="list" aria-controls="rc_select_1_list" aria-activedescendant="rc_select_1_list_0" value="" id="rc_select_1" aria-expanded="true">Search from Lahore
<svg stroke="currentColor" fill="currentColor" stroke-width="0" viewBox="0 0 24 24" height="1.2em" width="1.2em" xmlns="http://www.w3.org/2000/svg"><path fill="none" d="M0 0h24v24H0z"></path><path d="M7.41 15.41L12 10.83l4.59 4.58L18 14l-6-6-6 6z"></path></svg>

<input type="search" autocomplete="off" class="ant-select-selection-search-input" role="combobox" aria-haspopup="listbox" aria-owns="rc_select_1_list" aria-autocomplete="list" aria-controls="rc_select_1_list" aria-activedescendant="rc_select_1_list_0" value="" id="rc_select_1" aria-expanded="true">Search from Lahore
<svg stroke="currentColor" fill="currentColor" stroke-width="0" viewBox="0 0 24 24" height="1.2em" width="1.2em" xmlns="http://www.w3.org/2000/svg"><path fill="none" d="M0 0h24v24H0z"></path><path d="M7.41 15.41L12 10.83l4.59 4.58L18 14l-6-6-6 6z"></path></svg>

<input type="search" autocomplete="off" class="ant-select-selection-search-input" role="combobox" aria-haspopup="listbox" aria-owns="rc_select_1_list" aria-autocomplete="list" aria-controls="rc_select_1_list" aria-activedescendant="rc_select_1_list_0" value="" id="rc_select_1" aria-expanded="true">Search from Lahore

::before

<input type="search" autocomplete="off" class="ant-select-selection-search-input" role="combobox" aria-haspopup="listbox" aria-owns="rc_select_1_list" aria-autocomplete="list" aria-controls="rc_select_1_list" aria-activedescendant="rc_select_1_list_0" value="" id="rc_select_1" aria-expanded="true">

<input type="search" autocomplete="off" class="ant-select-selection-search-input" role="combobox" aria-haspopup="listbox" aria-owns="rc_select_1_list" aria-autocomplete="list" aria-controls="rc_select_1_list" aria-activedescendant="rc_select_1_list_0" value="" id="rc_select_1" aria-expanded="true">

<input type="search" autocomplete="off" class="ant-select-selection-search-input" role="combobox" aria-haspopup="listbox" aria-owns="rc_select_1_list" aria-autocomplete="list" aria-controls="rc_select_1_list" aria-activedescendant="rc_select_1_list_0" value="" id="rc_select_1" aria-expanded="true">

Search from Lahore

::after