问:
why does png image not show up in JPanel in java using g.drawImage()?
so I'm trying to display a png image on a JPanel and the frame runs fine and its the size I want and everything but it doesn't display the image, I don't think its the image im using because I used the same method to display it on another project and it showed up fine. I've also tried to see if g.fillRect(); works and that doesn't show up either so is it a problem with my panel not showing up?</p>
```<code>package main;
import java.io.InputStream;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.imageio.ImageIO;
import javax.swing.JPanel;

public class GamePanel extends JPanel{

    private BufferedImage img, subImg;
    private float xDelta = 0, yDelta = 0;

    public GamePanel() {
        importImg();
        setPanelSize();
    }

    public void importImg() {
        InputStream is = getClass().getResourceAsStream("/TetrisBlocksTextureAtlas.png");
        try {
        img = ImageIO.read(is);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public void setPanelSize() {
        Dimension size = new Dimension(200, 400);
        setPreferredSize(size);
    }

     void PaintComponent(Graphics g) {
        super.paintComponent(g);

        g.fillRect(0, 0, 50, 50);
        g.drawImage(img, 0, 0, null);

    }
}

</code>```

Body:
so I'm trying to display a png image on a JPanel and the frame runs fine and its the size I want and everything but it doesn't display the image, I don't think its the image im using because I used the same method to display it on another project and it showed up fine. I've also tried to see if g.fillRect(); works and that doesn't show up either so is it a problem with my panel not showing up?

package main;
import java.io.InputStream;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.imageio.ImageIO;
import javax.swing.JPanel;

public class GamePanel extends JPanel{

    private BufferedImage img, subImg;
    private float xDelta = 0, yDelta = 0;

    public GamePanel() {
        importImg();
        setPanelSize();
    }

    public void importImg() {
        InputStream is = getClass().getResourceAsStream("/TetrisBlocksTextureAtlas.png");
        try {
        img = ImageIO.read(is);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public void setPanelSize() {
        Dimension size = new Dimension(200, 400);
        setPreferredSize(size);
    }

     void PaintComponent(Graphics g) {
        super.paintComponent(g);

        g.fillRect(0, 0, 50, 50);
        g.drawImage(img, 0, 0, null);

    }
}


来源: stackexchange

问:
Pandas text file read and convert data frame
I would like to solve the problem

input :
-----------
column1:Name
column2:Age

 raju  20
 kanu  24
------------
```
<p>The above  is <code>input.txt</code> file one need to read the file and create a pandas dataframe and than need to convert to csv I am facing issue while doing it provides me with one column and consider lines as full object help would be great.</p>
<pre class="lang-none prettyprint-override"><code>output :
Name Age
raju  20
kanu  24
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I would like to solve the problem

input :
-----------
column1:Name
column2:Age

 raju  20
 kanu  24
------------

The above  is input.txt file one need to read the file and create a pandas dataframe and than need to convert to csv I am facing issue while doing it provides me with one column and consider lines as full object help would be great.

output :
Name Age
raju  20
kanu  24


问:
Spring Boot application to read from impala db and write to postgres db
Use case - build an rest endpoint which will take list of tables as request payload and check whether those table exist in impala db, if exist then extract the table creation script from impala and run it into postgres then copy the impala data into postgres db (insert script)</p>


问:
Create React App integration with ReactJS.net
I'm trying to set up a asp.net mvc project integrating a create react app and reactjs.net. Trying to follow the tutorial here but facing this exception

```<code>ReactJS.NET has not been initialised correctly. Please ensure you have called services.AddReact() and app.UseReact() in your Startup.cs file. (ReactNotInitialisedException)
ReactNotInitialisedException at React.ReactEnvironment.get_GetCurrentOrThrow()
    No JS engines were registered. Visit https://reactjs.net/docs for more information. (ReactException)
</code>```

This is my ReactConfig file. I have tried some combinations here to not load react and set JS engines.

```<code>ReactSiteConfiguration.Configuration
              .SetLoadBabel(false)
              .SetLoadReact(false)
              .SetReactAppBuildPath("~/ClientApp/build");
JsEngineSwitcher.Current.DefaultEngineName = V8JsEngine.EngineName;
            JsEngineSwitcher.Current.EngineFactories.AddV8();
</code>```

This is my layout cshtml.

```<code><html>
<head>
    <title>Hello React</title>
    <link href="~/Content/Site.css" rel="stylesheet" type="text/css" />
</head>
<body className="">
    <div id="content"></div>
    @Html.React("Components.App", new{p1 = "value"})
</body>
</html>
</code>```

From the tutorial, instead of expose-components.js, I'm doing the same in my default index.js as this would be the default entry point for the create react app and I did not want to eject it. I do not have a startup.cs file in my MVC project instead have a Global.ascx.cs

Body:
I'm trying to set up a asp.net mvc project integrating a create react app and reactjs.net. Trying to follow the tutorial here but facing this exception

ReactJS.NET has not been initialised correctly. Please ensure you have called services.AddReact() and app.UseReact() in your Startup.cs file. (ReactNotInitialisedException)
ReactNotInitialisedException at React.ReactEnvironment.get_GetCurrentOrThrow()
    No JS engines were registered. Visit https://reactjs.net/docs for more information. (ReactException)

This is my ReactConfig file. I have tried some combinations here to not load react and set JS engines.

ReactSiteConfiguration.Configuration
              .SetLoadBabel(false)
              .SetLoadReact(false)
              .SetReactAppBuildPath("~/ClientApp/build");
JsEngineSwitcher.Current.DefaultEngineName = V8JsEngine.EngineName;
            JsEngineSwitcher.Current.EngineFactories.AddV8();

This is my layout cshtml.

    <title>Hello React</title>
    <link href="~/Content/Site.css" rel="stylesheet" type="text/css" />

    @Html.React("Components.App", new{p1 = "value"})

From the tutorial, instead of expose-components.js, I'm doing the same in my default index.js as this would be the default entry point for the create react app and I did not want to eject it. I do not have a startup.cs file in my MVC project instead have a Global.ascx.cs


问:
I need my toggle switch in the appBar to be visible
I have created a toggle switch in the appBar but its not visible because of the code.

It changes themes between light to dark when clicked

main.dart

```<code>class MyApp extends StatelessWidget {
  static const String title = "User Profile";
    const MyApp({Key? key}) : super(key: key);

    @override
    Widget build(BuildContext context) {
      final user = UserPreferences.getUser();

      return ThemeProvider(
        initTheme: user.isDarkMode ? Mythemes.darkTheme : Mythemes.lightTheme,
        child: Builder(
          builder: (context) =>
                MaterialApp(
                debugShowCheckedModeBanner: false,
                theme: ThemeModelInheritedNotifier.of(context).theme,
                title: title,
                home: const ProfilePage(),
              ),
        ),
        );
    }
}
</code>```

What do I need to change and what not to get the toggle switch visible?

themes.dart

```<code>class Mythemes {
  static const primary = Colors.blue;
  static final primaryColor = Colors.blue.shade300;

  static final darkTheme = ThemeData(
    scaffoldBackgroundColor: Colors.grey.shade900,
    primaryColorDark: primaryColor,
    dividerColor: Colors.white,
    colorScheme: const ColorScheme.dark(primary: primary).copyWith(secondary: Colors.blue),
  );
  static final lightTheme = ThemeData(
    scaffoldBackgroundColor: Colors.white,
    primaryColor: primaryColor,
    colorScheme: const ColorScheme.light(primary: primary),
    dividerColor: Colors.black,
  );
}
</code>```

Appbar widget code

```<code> AppBar buildAppBar(BuildContext context) {
  final user = UserPreferences.getUser();
  final isDarkMode = user.isDarkMode;
  final icon = isDarkMode ? CupertinoIcons.sun_max : CupertinoIcons.moon_stars;
  return AppBar(
    leading: const BackButton(
      color: Colors.blue,
    ),
    backgroundColor: Theme.of(context).scaffoldBackgroundColor,
    elevation: 0,
    actions: [
      ThemeSwitcher(
        builder: (context) => IconButton(
          color: Colors.blue,
          icon: Icon(icon),
          onPressed: () {
            final theme = isDarkMode ? Mythemes.lightTheme : Mythemes.darkTheme;
            final switcher = ThemeSwitcher.of(context);
            switcher.changeTheme(theme: theme);
            final newUser = user.copy(isDarkMode : !isDarkMode);
            UserPreferences.setUser(newUser);
          },
        ),
      ),
    ],
  );
}
</code>```

how to solve this error

Body:
I have created a toggle switch in the appBar but its not visible because of the code.

It changes themes between light to dark when clicked

main.dart

class MyApp extends StatelessWidget {
  static const String title = "User Profile";
    const MyApp({Key? key}) : super(key: key);

    @override
    Widget build(BuildContext context) {
      final user = UserPreferences.getUser();

      return ThemeProvider(
        initTheme: user.isDarkMode ? Mythemes.darkTheme : Mythemes.lightTheme,
        child: Builder(
          builder: (context) =>
                MaterialApp(
                debugShowCheckedModeBanner: false,
                theme: ThemeModelInheritedNotifier.of(context).theme,
                title: title,
                home: const ProfilePage(),
              ),
        ),
        );
    }
}

What do I need to change and what not to get the toggle switch visible?

themes.dart

class Mythemes {
  static const primary = Colors.blue;
  static final primaryColor = Colors.blue.shade300;

  static final darkTheme = ThemeData(
    scaffoldBackgroundColor: Colors.grey.shade900,
    primaryColorDark: primaryColor,
    dividerColor: Colors.white,
    colorScheme: const ColorScheme.dark(primary: primary).copyWith(secondary: Colors.blue),
  );
  static final lightTheme = ThemeData(
    scaffoldBackgroundColor: Colors.white,
    primaryColor: primaryColor,
    colorScheme: const ColorScheme.light(primary: primary),
    dividerColor: Colors.black,
  );
}

Appbar widget code

 AppBar buildAppBar(BuildContext context) {
  final user = UserPreferences.getUser();
  final isDarkMode = user.isDarkMode;
  final icon = isDarkMode ? CupertinoIcons.sun_max : CupertinoIcons.moon_stars;
  return AppBar(
    leading: const BackButton(
      color: Colors.blue,
    ),
    backgroundColor: Theme.of(context).scaffoldBackgroundColor,
    elevation: 0,
    actions: [
      ThemeSwitcher(
        builder: (context) => IconButton(
          color: Colors.blue,
          icon: Icon(icon),
          onPressed: () {
            final theme = isDarkMode ? Mythemes.lightTheme : Mythemes.darkTheme;
            final switcher = ThemeSwitcher.of(context);
            switcher.changeTheme(theme: theme);
            final newUser = user.copy(isDarkMode : !isDarkMode);
            UserPreferences.setUser(newUser);
          },
        ),
      ),
    ],
  );
}

how to solve this error


问:
How to make an or statement in a firebase realtime database
I have a realtime database in firebase and have the following query

query(ref(database, 'message/'), orderByChild('ReceiverID'), equalTo("Username"))

But I want to create the following query

query(ref(database, 'message/'), orderByChild('ReceiverID'), equalTo("Username") or orderByChild('SenderID'), equalTo("Username"))


问:
Python Pandas: Using a one column in a dataframe to search for matches in another dataframe column
I am new to Pandas and already spent a good few hours on videos and websites getting familiar with this python library. I would appreciate some help with this issue I am working on;
I am using one column from a dataframe(df1) to look up a matching entry in a column of dataframe (df2).
An entry in a cell (df1) could be 'Advanced Automation Co.' that would be the same entity in column of df2
'Advanced Automation' - missing the Co. I'd like to iterate where I start with the complete string (Advance Automation Co.' and if I do not find an exact match I use the first two words. Thank you.

I have tried slice() to pick the words I need from column in df1 but I cannot isolate the 'slice' I need as a variable to pass on to the search code.


问:
Is there any way to calculate the height of the bottom bar that Samsung adds when selecting Swipe gestures/Full screen gestures as Navigation bar?
When selecting gesture navigation in Samsung devices, a small black bar with three thin buttons is added at the bottom as an overlay. I'm taking a screenshot of the screen, and setting that screenshot as background on the next page. The screenshot doesn't seem to be considering the bottom bar, and when setting it as background, it tries to fill the entire screen, causing some stretching. Adding a bottom margin of the same height of the bottom bar, would solve the issue.

Is there any way to calculate that height?


问:
why token doesn't store in cookie on browser?
I want to save JWT token in cookies.
when I try that by postman it works but when I send it by browser in localhost it doesn't send and cookie in browser application is empty.
my code :

```<code>export const Login = async (req, res, next) => {
  try {
    const user = await User.findOne({ email: req.body.email });
    if (!user) return next(CreateError(404, "wrong username or password"));

    const decryptPass = cryptoJs.AES.decrypt(user.password, process.env.CRYPTO);
    const StPassword = decryptPass.toString(cryptoJs.enc.Utf8);

    if (req.body.password !== StPassword) return next(CreateError(401, "wrong username or password"));
    const token = jwt.sign({id : user._id , isAdmin : user.isAdmin} , process.env.JWT)

     res.cookie('access_token' , token , {
      httpOnly : true
    });
    next(CreateError(200 , 'successful login', true))
  } catch (error) {
    next(error);
  }
};
</code>```

I run both front and back on localhost.

Body:
I want to save JWT token in cookies.
when I try that by postman it works but when I send it by browser in localhost it doesn't send and cookie in browser application is empty.
my code :

export const Login = async (req, res, next) => {
  try {
    const user = await User.findOne({ email: req.body.email });
    if (!user) return next(CreateError(404, "wrong username or password"));

    const decryptPass = cryptoJs.AES.decrypt(user.password, process.env.CRYPTO);
    const StPassword = decryptPass.toString(cryptoJs.enc.Utf8);

    if (req.body.password !== StPassword) return next(CreateError(401, "wrong username or password"));
    const token = jwt.sign({id : user._id , isAdmin : user.isAdmin} , process.env.JWT)

     res.cookie('access_token' , token , {
      httpOnly : true
    });
    next(CreateError(200 , 'successful login', true))
  } catch (error) {
    next(error);
  }
};

I run both front and back on localhost.


问:
How can I set-cookie on browser of mobile device?
I know there is have question like this, although I following so many answer, I still fix my problem. On computer, the cookie work perfectly, but on mobile it does not, I tried with Safari and Google Chrome.
This is server config

async function bootstrap() {
  const app = await NestFactory.create(AppModule,{cors:{
    origin:isProduction ? process.env.CORS_PROD : process.env.CORS_DEV,
    credentials:true,
  }
});
  app.useGlobalPipes(new ValidationPipe());
  app.use(cookieParser());
  app.setGlobalPrefix('finance/api')

  await app.listen(4444);
}
bootstrap();
```
<p>And this function to set-cookie to browser . finance/api is prefix and /users/checkAuth is the route for authenticate user.</p>
<pre class="lang-js prettyprint-override"><code>async setCookie(userId: string, res: Response) {
    const refresh_token = await this.signToken(userId, 'refresh');
    res.cookie(this.config.get('COOKIE_NAME'), refresh_token, {

        httpOnly: true,
        secure: this.config.get('NODE_ENV') === 'production',
        sameSite: 'lax',
        path: 'finance/api/users/checkAuth',

    });
}
</code>```

My client has a domain like https://example.com
My server has a domain like https://example.com/finance/api

Is this cause by cross-site domain or something ?

I tried to set secure option is false, and turn off Prevent Cross-Site Tracking, I'm also set credentials is true in client.
I hope understand what problem's kind happening and How can I fix it.

Body:
I know there is have question like this, although I following so many answer, I still fix my problem. On computer, the cookie work perfectly, but on mobile it does not, I tried with Safari and Google Chrome.
This is server config

async function bootstrap() {
  const app = await NestFactory.create(AppModule,{cors:{
    origin:isProduction ? process.env.CORS_PROD : process.env.CORS_DEV,
    credentials:true,
  }
});
  app.useGlobalPipes(new ValidationPipe());
  app.use(cookieParser());
  app.setGlobalPrefix('finance/api')

  await app.listen(4444);
}
bootstrap();

And this function to set-cookie to browser . finance/api is prefix and /users/checkAuth is the route for authenticate user.

async setCookie(userId: string, res: Response) {
    const refresh_token = await this.signToken(userId, 'refresh');
    res.cookie(this.config.get('COOKIE_NAME'), refresh_token, {

        httpOnly: true,
        secure: this.config.get('NODE_ENV') === 'production',
        sameSite: 'lax',
        path: 'finance/api/users/checkAuth',

    });
}

My client has a domain like https://example.com
My server has a domain like https://example.com/finance/api

Is this cause by cross-site domain or something ?

I tried to set secure option is false, and turn off Prevent Cross-Site Tracking, I'm also set credentials is true in client.
I hope understand what problem's kind happening and How can I fix it.


问:
Can't setup persistent logging and dags for airflow running in kubernetes
I'm trying to get persistent logs as for now after DAG is completed, I get below error:

```<code>hello-world-run-a-demo-job-4b7650b6dd784429a54c3bd5e5c983e6
*** Trying to get logs (last 100 lines) from worker pod hello-world-run-a-demo-job-4b7650b6dd784429a54c3bd5e5c983e6 ***

*** Unable to fetch logs from worker pod hello-world-run-a-demo-job-4b7650b6dd784429a54c3bd5e5c983e6 ***
(404)
Reason: Not Found
</code>```

I have created storage class:

```<code>$ kubectl get sc
NAME                    PROVISIONER                RECLAIMPOLICY   VOLUMEBINDINGMODE      ALLOWVOLUMEEXPANSION   AGE
airflow-logs            kubernetes.io/azure-file   Delete          Immediate              false                  10m
</code>```

and in Valyes.yaml of Airflow I have used that SC and persistent volume claim was created when I run helm upgrade:

```<code>logs:
  persistence:
    # Enable persistent volume for storing logs
    enabled: true
    # Volume size for logs
    size: 10Gi
    # If using a custom storageClass, pass name here
    storageClassName: airflow-logs
    ## the name of an existing PVC to use
    existingClaim:
</code>```

PVC was created automatically:

```<code>$ kubectl get pvc
NAME                        STATUS   VOLUME                                     CAPACITY   ACCESS MODES   STORAGECLASS   AGE
airflow-logs                Bound    pvc-f13ea0d8-243d-41ea-8ca2-35b48b848e2f   10Gi       RWX            airflow-logs   18m
</code>```

But I still get the same 404 error when trying to get into Logs

Persistent volume.yaml:

```<code>kind: StorageClass
apiVersion: storage.k8s.io/v1
metadata:
  name: airflow-logs
provisioner: kubernetes.io/azure-file
mountOptions:
  - dir_mode=0777
  - file_mode=0777
  - uid=50000
  - gid=0
  - mfsymlinks
  - cache=strict
  - actimeo=30
parameters:
  skuName: Standard_LRS
</code>```

I've also tried just to create PV and PVC instead of just creating PV and use them explicitly with helm upgrade but it did not changed anything:

```<code>    helm upgrade --install airflow . \
      --set images.airflow.repository=my-repo \
      --set images.airflow.tag=latest \
      --set logs.persistence.enabled=true \
      --set logs.persistence.existingClaim=airflow-logs \
      --set images.airflow.pullPolicy=Always \
      --set registry.secretName=mysecretrg
</code>```

Body:
I'm trying to get persistent logs as for now after DAG is completed, I get below error:

hello-world-run-a-demo-job-4b7650b6dd784429a54c3bd5e5c983e6
*** Trying to get logs (last 100 lines) from worker pod hello-world-run-a-demo-job-4b7650b6dd784429a54c3bd5e5c983e6 ***

*** Unable to fetch logs from worker pod hello-world-run-a-demo-job-4b7650b6dd784429a54c3bd5e5c983e6 ***
(404)
Reason: Not Found

I have created storage class:

$ kubectl get sc
NAME                    PROVISIONER                RECLAIMPOLICY   VOLUMEBINDINGMODE      ALLOWVOLUMEEXPANSION   AGE
airflow-logs            kubernetes.io/azure-file   Delete          Immediate              false                  10m

and in Valyes.yaml of Airflow I have used that SC and persistent volume claim was created when I run helm upgrade:

logs:
  persistence:
    # Enable persistent volume for storing logs
    enabled: true
    # Volume size for logs
    size: 10Gi
    # If using a custom storageClass, pass name here
    storageClassName: airflow-logs
    ## the name of an existing PVC to use
    existingClaim:

PVC was created automatically:

$ kubectl get pvc
NAME                        STATUS   VOLUME                                     CAPACITY   ACCESS MODES   STORAGECLASS   AGE
airflow-logs                Bound    pvc-f13ea0d8-243d-41ea-8ca2-35b48b848e2f   10Gi       RWX            airflow-logs   18m

But I still get the same 404 error when trying to get into Logs

Persistent volume.yaml:

kind: StorageClass
apiVersion: storage.k8s.io/v1
metadata:
  name: airflow-logs
provisioner: kubernetes.io/azure-file
mountOptions:
  - dir_mode=0777
  - file_mode=0777
  - uid=50000
  - gid=0
  - mfsymlinks
  - cache=strict
  - actimeo=30
parameters:
  skuName: Standard_LRS

I've also tried just to create PV and PVC instead of just creating PV and use them explicitly with helm upgrade but it did not changed anything:

    helm upgrade --install airflow . \
      --set images.airflow.repository=my-repo \
      --set images.airflow.tag=latest \
      --set logs.persistence.enabled=true \
      --set logs.persistence.existingClaim=airflow-logs \
      --set images.airflow.pullPolicy=Always \
      --set registry.secretName=mysecretrg


问:
Keyboard navigation with list item not working properly?
I am create a dropdown component with keyboard navigation

hook

```<code>export const useKeyPress = function (targetKey: string) {
    const [keyPressed, setKeyPressed] = React.useState(false);

    function downHandler({ key }: { key: string }) {
        if (key === targetKey) {
            setKeyPressed(true);
        }
    }

    const upHandler = ({ key }: { key: string }) => {
        if (key === targetKey) {
            setKeyPressed(false);
        }
    };

    React.useEffect(() => {
        window.addEventListener("keydown", downHandler);
        window.addEventListener("keyup", upHandler);

        return () => {
            window.removeEventListener("keydown", downHandler);
            window.removeEventListener("keyup", upHandler);
        };
    });

    return keyPressed;
};
</code>```

And in my compoennt-

```<code>const downPress = useKeyPress("ArrowDown");
const upPress = useKeyPress("ArrowUp");
const enterPress = useKeyPress("Enter");
useEffect(() => {
        if (countryDataInfo.length && downPress) {
            setCursor(prevState =>
                prevState < countryDataInfo.length - 1 ? prevState + 1 : prevState
            );
        }
    }, [downPress]);
useEffect(() => {
        if (countryDataInfo.length && upPress) {
            setCursor(prevState => (prevState > 0 ? prevState - 1 : prevState));
        }
    }, [upPress]);
useEffect(() => {
        if (countryDataInfo.length && enterPress) {
            setSelected(countryDataInfo[cursor]);
        }
    }, [cursor, enterPress]);

<ul className={isDropdown ? "simple-phone-input-sri198-dropdown active" : "simple-phone-input-sri198-dropdown"} >
    {search &&
        <div className="simple-phone-input-sri198-search-container">
            <input
                placeholder={searchPlaceholder}
                {...searchProps}
                onChange={onSearchHandler}
            />
            {showSearchIcon &&
                <div className="simple-phone-input-sri198-search-icon">
                    {searchIconComponent ?? (
                        <svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 48 48"><g fill="#616161"><path d="m29.175 31.99l2.828-2.827l12.019 12.019l-2.828 2.827z" /><circle cx="20" cy="20" r="16" /></g><path fill="#37474F" d="m32.45 35.34l2.827-2.828l8.696 8.696l-2.828 2.828z" /><circle cx="20" cy="20" r="13" fill="#64B5F6" /><path fill="#BBDEFB" d="M26.9 14.2c-1.7-2-4.2-3.2-6.9-3.2s-5.2 1.2-6.9 3.2c-.4.4-.3 1.1.1 1.4c.4.4 1.1.3 1.4-.1C16 13.9 17.9 13 20 13s4 .9 5.4 2.5c.2.2.5.4.8.4c.2 0 .5-.1.6-.2c.4-.4.4-1.1.1-1.5z" /></svg>
                    )}

                </div>
            }
        </div>
    }
    {countryDataInfo.length === 0 &&
        <div className="simple-phone-input-sri198-not-found">
            {searchNotFound}
        </div>
    }
    {countryDataInfo.map((item, i) => (
        <li key={i} onClick={() => handleSelected(item)} className={i === cursor ? "active" : ""}>
            <img src={"https://cdn.jsdelivr.net/gh/siamahnaf198/country-flags@main/img/" + item.countryCode + ".svg"} alt={item.country} width="20px" />
            <span className="simple-phone-input-sri198-dropdown-text">{item.country}</span>
            <span className="simple-phone-input-sri198-dropdown-country-code">{item.callingCode}</span>
        </li>
    ))}
</ul>
</code>```

But works perfectly. But problem is when I press on down key then whole window being scrolled. But I want to scroll only list element on keypress. Is it possible do only scroll ul tag area and select the list by keydown and keyup with enter press. Please help me. Actually it is a dropdown menu. Ul will open when a button clicked.

It is live url- https://test-eight-omega-89.vercel.app/

Body:
I am create a dropdown component with keyboard navigation

hook

export const useKeyPress = function (targetKey: string) {
    const [keyPressed, setKeyPressed] = React.useState(false);

    function downHandler({ key }: { key: string }) {
        if (key === targetKey) {
            setKeyPressed(true);
        }
    }

    const upHandler = ({ key }: { key: string }) => {
        if (key === targetKey) {
            setKeyPressed(false);
        }
    };

    React.useEffect(() => {
        window.addEventListener("keydown", downHandler);
        window.addEventListener("keyup", upHandler);

        return () => {
            window.removeEventListener("keydown", downHandler);
            window.removeEventListener("keyup", upHandler);
        };
    });

    return keyPressed;
};

And in my compoennt-

const downPress = useKeyPress("ArrowDown");
const upPress = useKeyPress("ArrowUp");
const enterPress = useKeyPress("Enter");
useEffect(() => {
        if (countryDataInfo.length && downPress) {
            setCursor(prevState =>
                prevState < countryDataInfo.length - 1 ? prevState + 1 : prevState
            );
        }
    }, [downPress]);
useEffect(() => {
        if (countryDataInfo.length && upPress) {
            setCursor(prevState => (prevState > 0 ? prevState - 1 : prevState));
        }
    }, [upPress]);
useEffect(() => {
        if (countryDataInfo.length && enterPress) {
            setSelected(countryDataInfo[cursor]);
        }
    }, [cursor, enterPress]);

    {search &&

            <input
                placeholder={searchPlaceholder}
                {...searchProps}
                onChange={onSearchHandler}
            />
            {showSearchIcon &&

                    {searchIconComponent ?? (
                        <svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 48 48"><g fill="#616161"><path d="m29.175 31.99l2.828-2.827l12.019 12.019l-2.828 2.827z" /><circle cx="20" cy="20" r="16" /></g><path fill="#37474F" d="m32.45 35.34l2.827-2.828l8.696 8.696l-2.828 2.828z" /><circle cx="20" cy="20" r="13" fill="#64B5F6" /><path fill="#BBDEFB" d="M26.9 14.2c-1.7-2-4.2-3.2-6.9-3.2s-5.2 1.2-6.9 3.2c-.4.4-.3 1.1.1 1.4c.4.4 1.1.3 1.4-.1C16 13.9 17.9 13 20 13s4 .9 5.4 2.5c.2.2.5.4.8.4c.2 0 .5-.1.6-.2c.4-.4.4-1.1.1-1.5z" /></svg>
                    )}

            }

    }
    {countryDataInfo.length === 0 &&

            {searchNotFound}

    }
    {countryDataInfo.map((item, i) => (

 handleSelected(item)} className={i === cursor ? "active" : ""}>

            {item.country}
            {item.callingCode}

    ))}

But works perfectly. But problem is when I press on down key then whole window being scrolled. But I want to scroll only list element on keypress. Is it possible do only scroll ul tag area and select the list by keydown and keyup with enter press. Please help me. Actually it is a dropdown menu. Ul will open when a button clicked.

It is live url- https://test-eight-omega-89.vercel.app/


问:
How to create a tensorflow-Federated float-point tensor, placed at `tff.CLIENTS`?
I am using the function

```<code>federated_mean(value, weight=None)
</code>```

The documentation of this function says:

```<code>weight: An optional weight, a TFF federated integer or floating-point tensor
      value, also placed at `tff.CLIENTS`.
</code>```

My question is: how do I create a tensorflow-Federated float-point tensor, placed at tff.CLIENTS?

For example, my weights are [0.8, 0.2] for two clients' federated learning.

Thank you!

I have no clue on how to do this. I am new with tensorflow-federated.

Body:
I am using the function

federated_mean(value, weight=None)

The documentation of this function says:

weight: An optional weight, a TFF federated integer or floating-point tensor
      value, also placed at `tff.CLIENTS`.

My question is: how do I create a tensorflow-Federated float-point tensor, placed at tff.CLIENTS?

For example, my weights are [0.8, 0.2] for two clients' federated learning.

Thank you!

I have no clue on how to do this. I am new with tensorflow-federated.


问:
Apache Camel retry delivery attempt log issue
When retrying SQLException with max attempts of 3, i was logging the attempts and used below parameters for the same.

......
.maximumRedeliveries(3)
.redeliveryDelay(1000)
.asyncDelayedRedelivery()
.logRetryAttempted(true)
.log(LoggingLevel.ERROR, "retry attempts exhausted")
.end();

The delivery attempts in the log are not in ascending order of the retry attempt made. Ex. "On delivery attempt: 3" was coming before "On delivery attempt: 2". Any thoughts on the issue please?

Camel Version : 3.4.0

I was expecting the delivery attempts in the log to be in ascending order of attempt made.


问:
how to insert new record in a relational table using prisma
I have issue with creating a record to the module room
it works when I tried to insert a new element in the user table but with the room it didn't work
here's an image for more infoenter image description here

```<code>root@70cfe0072344:/usr/src/api# yarn prisma migrate dev
yarn run v1.22.19
$ /usr/src/api/node_modules/.bin/prisma migrate dev
Environment variables loaded from .env
Prisma schema loaded from prisma/schema.prisma
Datasource "db": PostgreSQL database "trandandan", schema "public" at "postgres:5432"

Already in sync, no schema change or pending migration was found.

✔ Generated Prisma Client (4.7.1 | library) to ./node_modules/@prisma/client in 99ms

Done in 3.36s.
root@70cfe0072344:/usr/src/api# yarn prisma generate
yarn run v1.22.19
$ /usr/src/api/node_modules/.bin/prisma generate
Environment variables loaded from .env
Prisma schema loaded from prisma/schema.prisma

✔ Generated Prisma Client (4.7.1 | library) to ./node_modules/@prisma/client in 90ms
You can now start using Prisma Client in your code. Reference: https://pris.ly/d/client
```
import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient()
```
Done in 1.64s.
root@70cfe0072344:/usr/src/api#
</code>```

I tried to run the command yarn prisma migrate dev and yarn prisma generate in both the container and host but it didn't work
Here is my docker-compose file for reference :

```<code>
version: '3.7'

services:
  api:
    container_name: api
    build:
      context: ./api
      target: development
    volumes:
      - ./api:/usr/src/api
      - /usr/src/api/node_modules
    ports:
      - ${SERVER_PORT}:${SERVER_PORT}
      - 5555:5555 # for prisma studio
      - 9229:9229 # for debugging
    command: yarn start:dev
    networks:
      - webnet
    depends_on:
      - postgres
  postgres:
    container_name: postgres
    image: postgres:14
    networks:
      - webnet
    environment:
      POSTGRES_DB: ${DB_DATABASE_NAME}
      POSTGRES_USER: ${DB_USERNAME}
      POSTGRES_PASSWORD: ${DB_PASSWORD}
      PG_DATA: /var/lib/postgresql/data
    ports:
      - 5432:5432
    volumes:
      - pgdata:/var/lib/postgresql/data
networks:
  webnet:
volumes:
  pgdata:

</code>```

Body:
I have issue with creating a record to the module room
it works when I tried to insert a new element in the user table but with the room it didn't work
here's an image for more infoenter image description here

root@70cfe0072344:/usr/src/api# yarn prisma migrate dev
yarn run v1.22.19
$ /usr/src/api/node_modules/.bin/prisma migrate dev
Environment variables loaded from .env
Prisma schema loaded from prisma/schema.prisma
Datasource "db": PostgreSQL database "trandandan", schema "public" at "postgres:5432"

Already in sync, no schema change or pending migration was found.

✔ Generated Prisma Client (4.7.1 | library) to ./node_modules/@prisma/client in 99ms

Done in 3.36s.
root@70cfe0072344:/usr/src/api# yarn prisma generate
yarn run v1.22.19
$ /usr/src/api/node_modules/.bin/prisma generate
Environment variables loaded from .env
Prisma schema loaded from prisma/schema.prisma

✔ Generated Prisma Client (4.7.1 | library) to ./node_modules/@prisma/client in 90ms
You can now start using Prisma Client in your code. Reference: https://pris.ly/d/client
```
import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient()
```
Done in 1.64s.
root@70cfe0072344:/usr/src/api#

I tried to run the command yarn prisma migrate dev and yarn prisma generate in both the container and host but it didn't work
Here is my docker-compose file for reference :

version: '3.7'

services:
  api:
    container_name: api
    build:
      context: ./api
      target: development
    volumes:
      - ./api:/usr/src/api
      - /usr/src/api/node_modules
    ports:
      - ${SERVER_PORT}:${SERVER_PORT}
      - 5555:5555 # for prisma studio
      - 9229:9229 # for debugging
    command: yarn start:dev
    networks:
      - webnet
    depends_on:
      - postgres
  postgres:
    container_name: postgres
    image: postgres:14
    networks:
      - webnet
    environment:
      POSTGRES_DB: ${DB_DATABASE_NAME}
      POSTGRES_USER: ${DB_USERNAME}
      POSTGRES_PASSWORD: ${DB_PASSWORD}
      PG_DATA: /var/lib/postgresql/data
    ports:
      - 5432:5432
    volumes:
      - pgdata:/var/lib/postgresql/data
networks:
  webnet:
volumes:
  pgdata:


问:
scala/databricks/pyspark: how to parse/format a string based on a pattern?
how to parse/format a string based on a pattern which is similar in SQL server with scala or pyspark?

Example,

val string = abcdefg

val pattern= XX-XXX-XX

Then format_string= ab-cde-fg

if val pattern = X-XX-XXXX

Then format_string = a-bc-defg is another example.

I tried substring and others.

Here is my raw initial code:

```<code>val pattern="XX-XX-XXXX"

val item="abcdefgh"

var lenplus = pattern.indexOf("-")

var fitem=item.substring(0,lenplus)

val result = pattern.split("-")

    for ( a <-result )
    {
      val len= a.length()
      // Displays output
        //println(len)

        var sitem= item.substring(lenplus,lenplus + len)

        lenplus = len + lenplus

        fitem=fitem + "-" + sitem

        //println(lenplus)
      println(fitem)
    }
</code>```

But I received below err message. This is the output and err message

ab-cd

ab-cd-ef

StringIndexOutOfBoundsException: String index out of range: 10

Body:
how to parse/format a string based on a pattern which is similar in SQL server with scala or pyspark?

Example,

val string = abcdefg

val pattern= XX-XXX-XX

Then format_string= ab-cde-fg

if val pattern = X-XX-XXXX

Then format_string = a-bc-defg is another example.

I tried substring and others.

Here is my raw initial code:

val pattern="XX-XX-XXXX"

val item="abcdefgh"

var lenplus = pattern.indexOf("-")

var fitem=item.substring(0,lenplus)

val result = pattern.split("-")

    for ( a <-result )
    {
      val len= a.length()
      // Displays output
        //println(len)

        var sitem= item.substring(lenplus,lenplus + len)

        lenplus = len + lenplus

        fitem=fitem + "-" + sitem

        //println(lenplus)
      println(fitem)
    }

But I received below err message. This is the output and err message

ab-cd

ab-cd-ef

StringIndexOutOfBoundsException: String index out of range: 10


问:
ThreadPoolExecutor or multi-processing for Pandas DataFrame
Asuume there will be a mega size dataframe, which has > 1M columns. Based on the following toy dataframe.

```<code>import pandas as pd
import numpy as np
from concurrent.futures import *
import multiprocessing
num_processes = multiprocessing.cpu_count()
print(f'num_precesses: {num_processes}')

def ReplaceItem(old_item, input_list, new_item = 'ham'):
    output = []
    for item in input_list:
        if item == old_item:
            output.append(new_item)
        else:
            output.append(item)
    return output

food = pd.DataFrame({'customer':range(1,4),
                     'original':[['egg', 'berry', 'pork', 'tea'],
                                 ['chicken', 'beef', 'water', 'soda'],
                                 ['fish', 'chicken', 'pork', 'coffee']]})

replace_items = {'list1':'egg', 'list2':'chicken', 'list3':'fish'}

food

num_precesses: 10

customer    original
0   1   [egg, berry, pork, tea]
1   2   [chicken, beef, water, soda]
2   3   [fish, chicken, pork, coffee]
</code>```

The goal is to create a new dataframe which have update columns that replace items on the replace_items list with a NEW item 'ham'. The final table should be like below

```<code>change_items, item_dict = [], dict()

for i in range(len(replace_items.values())):
    change_items.append((list(replace_items.keys())[i],
                         food['original'].apply(lambda x: ReplaceItem(list(replace_items.values())[i], x))))
    item_dict.update(change_items)
    new_df = pd.DataFrame(item_dict)
    update_df = pd.concat([food, new_df], axis = 1)

update_df
    customer    original                list1                           list2   list3
0   1   [egg, berry, pork, tea]         [ham, berry, pork, tea]         [egg, berry, pork, tea]     [egg, berry, pork, tea]
1   2   [chicken, beef, water, soda]    [chicken, beef, water, soda]    [ham, beef, water, soda]    [chicken, beef, water, soda]
2   3   [fish, chicken, pork, coffee]   [fish, chicken, pork, coffee]   [fish, ham, pork, coffee]   [ham, chicken, pork, coffee]
</code>```

I try to use multi-threading or multi-processing to speed up the whole process but don't know how to implement it correctly. Here, each new column indicates any of rows that have been replaced by a new item. Any suggestions? many thanks in advance

Body:
Asuume there will be a mega size dataframe, which has > 1M columns. Based on the following toy dataframe.

import pandas as pd
import numpy as np
from concurrent.futures import *
import multiprocessing
num_processes = multiprocessing.cpu_count()
print(f'num_precesses: {num_processes}')

def ReplaceItem(old_item, input_list, new_item = 'ham'):
    output = []
    for item in input_list:
        if item == old_item:
            output.append(new_item)
        else:
            output.append(item)
    return output

food = pd.DataFrame({'customer':range(1,4),
                     'original':[['egg', 'berry', 'pork', 'tea'],
                                 ['chicken', 'beef', 'water', 'soda'],
                                 ['fish', 'chicken', 'pork', 'coffee']]})

replace_items = {'list1':'egg', 'list2':'chicken', 'list3':'fish'}

food

num_precesses: 10

customer    original
0   1   [egg, berry, pork, tea]
1   2   [chicken, beef, water, soda]
2   3   [fish, chicken, pork, coffee]

The goal is to create a new dataframe which have update columns that replace items on the replace_items list with a NEW item 'ham'. The final table should be like below

change_items, item_dict = [], dict()

for i in range(len(replace_items.values())):
    change_items.append((list(replace_items.keys())[i],
                         food['original'].apply(lambda x: ReplaceItem(list(replace_items.values())[i], x))))
    item_dict.update(change_items)
    new_df = pd.DataFrame(item_dict)
    update_df = pd.concat([food, new_df], axis = 1)

update_df
    customer    original                list1                           list2   list3
0   1   [egg, berry, pork, tea]         [ham, berry, pork, tea]         [egg, berry, pork, tea]     [egg, berry, pork, tea]
1   2   [chicken, beef, water, soda]    [chicken, beef, water, soda]    [ham, beef, water, soda]    [chicken, beef, water, soda]
2   3   [fish, chicken, pork, coffee]   [fish, chicken, pork, coffee]   [fish, ham, pork, coffee]   [ham, chicken, pork, coffee]

I try to use multi-threading or multi-processing to speed up the whole process but don't know how to implement it correctly. Here, each new column indicates any of rows that have been replaced by a new item. Any suggestions? many thanks in advance


问:
Python Kafka Producer connection error despite consumer being able to connect
I am trying to create a producer:

```<code>        producer = KafkaProducer(bootstrap_servers=SERVER, security_protocol="PLAINTEXT") # this line does not have issue. From my experiments, if it cannot connect to broker, it will throw error NoBrokersAvailable

        producer.send("g", "test")
</code>```

error:

```<code>decoding-server  | [E 221216 16:23:01 conn:418] Connect attempt to <BrokerConnection node_id=1 host=localhost:29092 <connecting> [IPv4 ('127.0.0.1', 29092)]> returned error 111. Disconnecting.
decoding-server  | [I 221216 16:23:01 conn:919] <BrokerConnection node_id=1 host=localhost:29092 <connecting> [IPv4 ('127.0.0.1', 29092)]>: Closing connection. KafkaConnectionError: 111 ECONNREFUSED
decoding-server  | [W 221216 16:23:01 client_async:331] Node 1 connection failed -- refreshing metadata
decoding-server  | [I 221216 16:23:02 conn:380] <BrokerConnection node_id=1 host=localhost:29092 <connecting> [IPv6 ('::1', 29092, 0, 0)]>: connecting to localhost:29092 [('::1', 29092, 0, 0) IPv6]
decoding-server  | [E 221216 16:23:02 conn:418] Connect attempt to <BrokerConnection node_id=1 host=localhost:29092 <connecting> [IPv6 ('::1', 29092, 0, 0)]> returned error 99. Disconnecting.
decoding-server  | [I 221216 16:23:02 conn:919] <BrokerConnection node_id=1 host=localhost:29092 <connecting> [IPv6 ('::1', 29092, 0, 0)]>: Closing connection. KafkaConnectionError: 99 EADDRNOTAVAIL
decoding-server  | [W 221216 16:23:02 client_async:331] Node 1 connection failed -- refreshing metadata
decoding-server  | [I 221216 16:23:03 conn:380] <BrokerConnection node_id=1 host=localhost:29092 <connecting> [IPv4 ('127.0.0.1', 29092)]>: connecting to localhost:29092 [('127.0.0.1', 29092) IPv4]
decoding-server  | [E 221216 16:23:03 conn:418] Connect attempt to <BrokerConnection node_id=1 host=localhost:29092 <connecting> [IPv4 ('127.0.0.1', 29092)]> returned error 111. Disconnecting.
decoding-server  | [I 221216 16:23:03 conn:919] <BrokerConnection node_id=1 host=localhost:29092 <connecting> [IPv4 ('127.0.0.1', 29092)]>: Closing connection. KafkaConnectionError: 111 ECONNREFUSED
decoding-server  | [W 221216 16:23:03 client_async:331] Node 1 connection failed -- refreshing metadata

</code>```

However, I do not think it's not able to connect, because the following code works:

```<code>            consumer = KafkaConsumer(
                "g",
                group_id="g",
                bootstrap_servers=SERVER,
            )
</code>```

I am running the containers locally using docker-compose.
docker-compose:

```<code>zookeeper:
        image: confluentinc/cp-zookeeper:latest
        environment:
            ZOOKEEPER_CLIENT_PORT: 2181
            ZOOKEEPER_TICK_TIME: 2000
        ports:
            - 22181:2181

    kafka:
        image: confluentinc/cp-kafka:5.3.1
        depends_on:
            - zookeeper
        ports:
            - 29092:29092
        environment:
            KAFKA_BROKER_ID: 1
            KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181
            KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka:9092,PLAINTEXT_HOST://localhost:29092
            KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: PLAINTEXT:PLAINTEXT,PLAINTEXT_HOST:PLAINTEXT
            KAFKA_INTER_BROKER_LISTENER_NAME: PLAINTEXT
            KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1

</code>```

Body:
I am trying to create a producer:

        producer = KafkaProducer(bootstrap_servers=SERVER, security_protocol="PLAINTEXT") # this line does not have issue. From my experiments, if it cannot connect to broker, it will throw error NoBrokersAvailable

        producer.send("g", "test")

error:

decoding-server  | [E 221216 16:23:01 conn:418] Connect attempt to <BrokerConnection node_id=1 host=localhost:29092 <connecting> [IPv4 ('127.0.0.1', 29092)]> returned error 111. Disconnecting.
decoding-server  | [I 221216 16:23:01 conn:919] <BrokerConnection node_id=1 host=localhost:29092 <connecting> [IPv4 ('127.0.0.1', 29092)]>: Closing connection. KafkaConnectionError: 111 ECONNREFUSED
decoding-server  | [W 221216 16:23:01 client_async:331] Node 1 connection failed -- refreshing metadata
decoding-server  | [I 221216 16:23:02 conn:380] <BrokerConnection node_id=1 host=localhost:29092 <connecting> [IPv6 ('::1', 29092, 0, 0)]>: connecting to localhost:29092 [('::1', 29092, 0, 0) IPv6]
decoding-server  | [E 221216 16:23:02 conn:418] Connect attempt to <BrokerConnection node_id=1 host=localhost:29092 <connecting> [IPv6 ('::1', 29092, 0, 0)]> returned error 99. Disconnecting.
decoding-server  | [I 221216 16:23:02 conn:919] <BrokerConnection node_id=1 host=localhost:29092 <connecting> [IPv6 ('::1', 29092, 0, 0)]>: Closing connection. KafkaConnectionError: 99 EADDRNOTAVAIL
decoding-server  | [W 221216 16:23:02 client_async:331] Node 1 connection failed -- refreshing metadata
decoding-server  | [I 221216 16:23:03 conn:380] <BrokerConnection node_id=1 host=localhost:29092 <connecting> [IPv4 ('127.0.0.1', 29092)]>: connecting to localhost:29092 [('127.0.0.1', 29092) IPv4]
decoding-server  | [E 221216 16:23:03 conn:418] Connect attempt to <BrokerConnection node_id=1 host=localhost:29092 <connecting> [IPv4 ('127.0.0.1', 29092)]> returned error 111. Disconnecting.
decoding-server  | [I 221216 16:23:03 conn:919] <BrokerConnection node_id=1 host=localhost:29092 <connecting> [IPv4 ('127.0.0.1', 29092)]>: Closing connection. KafkaConnectionError: 111 ECONNREFUSED
decoding-server  | [W 221216 16:23:03 client_async:331] Node 1 connection failed -- refreshing metadata

However, I do not think it's not able to connect, because the following code works:

            consumer = KafkaConsumer(
                "g",
                group_id="g",
                bootstrap_servers=SERVER,
            )

I am running the containers locally using docker-compose.
docker-compose:

zookeeper:
        image: confluentinc/cp-zookeeper:latest
        environment:
            ZOOKEEPER_CLIENT_PORT: 2181
            ZOOKEEPER_TICK_TIME: 2000
        ports:
            - 22181:2181

    kafka:
        image: confluentinc/cp-kafka:5.3.1
        depends_on:
            - zookeeper
        ports:
            - 29092:29092
        environment:
            KAFKA_BROKER_ID: 1
            KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181
            KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka:9092,PLAINTEXT_HOST://localhost:29092
            KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: PLAINTEXT:PLAINTEXT,PLAINTEXT_HOST:PLAINTEXT
            KAFKA_INTER_BROKER_LISTENER_NAME: PLAINTEXT
            KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1


问:
Plotly Dash - Python - Issue with callback function
Please bare with my limited experience in programming. At least, I will elaborate.

My task is to create a Dropdown for a number of launch sites, and then plot the success rate in a pie chart. The user can also select a range of payloads with a RangeSlider, that will be used to create a scatter plot.

This is how the result should look like:
enter image description here

Here is the code:

from dash import Dash, dcc, html, Input, Output
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go

URL = 'https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBM-DS0321EN-SkillsNetwork/datasets/spacex_launch_geo.csv'

df_spacex = pd.read_csv(URL)
df_spacex.head()

```<code># dropdown menu to choose from the various sites:
app = Dash(__name__)

app.layout = html.Div(children = [
    html.Div([
        html.H1('SpaceX Launch Records Dashboard',
                style = {'textAlign': 'center',
                         'color': 'black',
                         'font-size': 24}
               ),
        html.Label('Dropdown:',
                  style = {'color': 'black',
                          'font-size': 18}
                  ),
        dcc.Dropdown(id = 'site-dropdown',
                     options = [{'label': 'All Sites',    'value': 'ALL'},
                                {'label': 'CCAFS SCL-40', 'value': 'CCAFS SLC-40'},
                                {'label': 'CCAFS LC-40',  'value': 'CCAFS LC-40'},
                                {'label': 'VAFB SLC-4E',  'value': 'VAFB SLC-4E'},
                                {'label': 'KSC LC-39A',   'value': 'KSC LC-39A'}],
                                value = 'ALL',
                                placeholder = 'Select a site',
                                searchable = True,
                                style = {'width': '80%', 'height': '3px',
                                        'textAlign': 'left', 'font-size': '16px'}
                    ),
            ]),
    html.Div([
        html.Br(),
        html.Br(),
        dcc.Graph(id = 'success-pie-chart'),
        html.Br(),
        html.Label('Payload range slider (kg):',
                   style = {'color': 'black',
                           'font-size': 18}
                  ),
        dcc.RangeSlider(id = 'payload-slider',
                        min = df_spacex['Payload Mass (kg)'].min(),
                        max = df_spacex['Payload Mass (kg)'].max(),
                        step = 1000,
                        marks = {0: '0',
                                100: '100'},
                        value = [2000, 8000]
                       ),
        html.Br(),
        dcc.Graph(id = 'success-payload-scatter-chart')
            ])
                                    ])
</code>```
```<code># function decorator to specify function input and output
@app.callback(Output('success-pie-chart', 'figure'),
              Output('success-payload-scatter-chart', 'figure'),
              Input('site-dropdown', 'value'),
              Input('payload-slider', 'value'))

def get_pie_chart(entered_site, payload):
    if entered_site == 'ALL':
        fig = px.pie(df_spacex, values = 'class', names = 'Launch Site',
                     title = 'Successful Launch Distribution by Site')
    else:
        # choose the rows that have the same launch site as the one entered
        df_filtered = df_spacex.loc[df_spacex['Launch Site'] == entered_site]

        fig = px.pie(df_filtered, names = 'class',
                     title = 'Launch Distribution for ' + entered_site)
    return fig

def get_scatter_chart(entered_site, payload):
    # expand equals True to return a data frame
    # with seperated strings in different columns
    df_split = df_spacex['Booster Version'].str.split(' ', expand = True)

    # save the modified data frame
    df_mod = df_spacex.drop(columns = ['Booster Version'], inplace = False)
    df_mod['Booster Version'] = df_split[1]
    print(payload)
    # based on the input payload range choose the corresponding rows
    df_mod = df_mod.loc[(df_mod['Payload Mass (kg)'] >= payload[0]) & (df_mod['Payload Mass (kg)'] <= payload[1])]

    if entered_site == 'ALL':
        fig = px.scatter(df_mod,
                         x = 'Payload Mass (kg)',
                         y = 'class',
                         color = 'Booster Version',
                         hover_data = ['Booster Version'])
    else:
        df_filtered = df_mod.loc[df_mod['Launch Site'] == entered_site]

        fig = px.scatter(df_filtered,
                         x = 'Payload Mass (kg)',
                         y = 'class',
                         color = 'Booster Version',
                         hover_data = ['Booster Version'])
    return fig

if __name__ == '__main__':
    app.run_server(debug = True, use_reloader = False)
</code>```

Finally, the error that I get is the following:

```<code>dash._grouping.SchemaTypeValidationError: Schema: [<Output `success-pie-chart.figure`>, <Output `success-payload-scatter-chart.figure`>]
                Path: ()
                Expected type: (<class 'tuple'>, <class 'list'>)
                Received value of type <class 'plotly.graph_objs._figure.Figure'>:
</code>```

I really appreciate your time guys.

Please let me know if I can provide any more info or help clarify.

I've tested the functions that take the user's input and produce the pie and scatter charts outside Dash, and they worked fine. So, the error is arising from Dash.

Body:
Please bare with my limited experience in programming. At least, I will elaborate.

My task is to create a Dropdown for a number of launch sites, and then plot the success rate in a pie chart. The user can also select a range of payloads with a RangeSlider, that will be used to create a scatter plot.

This is how the result should look like:
enter image description here

Here is the code:

from dash import Dash, dcc, html, Input, Output
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go

URL = 'https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBM-DS0321EN-SkillsNetwork/datasets/spacex_launch_geo.csv'

df_spacex = pd.read_csv(URL)
df_spacex.head()

# dropdown menu to choose from the various sites:
app = Dash(__name__)

app.layout = html.Div(children = [
    html.Div([
        html.H1('SpaceX Launch Records Dashboard',
                style = {'textAlign': 'center',
                         'color': 'black',
                         'font-size': 24}
               ),
        html.Label('Dropdown:',
                  style = {'color': 'black',
                          'font-size': 18}
                  ),
        dcc.Dropdown(id = 'site-dropdown',
                     options = [{'label': 'All Sites',    'value': 'ALL'},
                                {'label': 'CCAFS SCL-40', 'value': 'CCAFS SLC-40'},
                                {'label': 'CCAFS LC-40',  'value': 'CCAFS LC-40'},
                                {'label': 'VAFB SLC-4E',  'value': 'VAFB SLC-4E'},
                                {'label': 'KSC LC-39A',   'value': 'KSC LC-39A'}],
                                value = 'ALL',
                                placeholder = 'Select a site',
                                searchable = True,
                                style = {'width': '80%', 'height': '3px',
                                        'textAlign': 'left', 'font-size': '16px'}
                    ),
            ]),
    html.Div([
        html.Br(),
        html.Br(),
        dcc.Graph(id = 'success-pie-chart'),
        html.Br(),
        html.Label('Payload range slider (kg):',
                   style = {'color': 'black',
                           'font-size': 18}
                  ),
        dcc.RangeSlider(id = 'payload-slider',
                        min = df_spacex['Payload Mass (kg)'].min(),
                        max = df_spacex['Payload Mass (kg)'].max(),
                        step = 1000,
                        marks = {0: '0',
                                100: '100'},
                        value = [2000, 8000]
                       ),
        html.Br(),
        dcc.Graph(id = 'success-payload-scatter-chart')
            ])
                                    ])

# function decorator to specify function input and output
@app.callback(Output('success-pie-chart', 'figure'),
              Output('success-payload-scatter-chart', 'figure'),
              Input('site-dropdown', 'value'),
              Input('payload-slider', 'value'))

def get_pie_chart(entered_site, payload):
    if entered_site == 'ALL':
        fig = px.pie(df_spacex, values = 'class', names = 'Launch Site',
                     title = 'Successful Launch Distribution by Site')
    else:
        # choose the rows that have the same launch site as the one entered
        df_filtered = df_spacex.loc[df_spacex['Launch Site'] == entered_site]

        fig = px.pie(df_filtered, names = 'class',
                     title = 'Launch Distribution for ' + entered_site)
    return fig

def get_scatter_chart(entered_site, payload):
    # expand equals True to return a data frame
    # with seperated strings in different columns
    df_split = df_spacex['Booster Version'].str.split(' ', expand = True)

    # save the modified data frame
    df_mod = df_spacex.drop(columns = ['Booster Version'], inplace = False)
    df_mod['Booster Version'] = df_split[1]
    print(payload)
    # based on the input payload range choose the corresponding rows
    df_mod = df_mod.loc[(df_mod['Payload Mass (kg)'] >= payload[0]) & (df_mod['Payload Mass (kg)'] <= payload[1])]

    if entered_site == 'ALL':
        fig = px.scatter(df_mod,
                         x = 'Payload Mass (kg)',
                         y = 'class',
                         color = 'Booster Version',
                         hover_data = ['Booster Version'])
    else:
        df_filtered = df_mod.loc[df_mod['Launch Site'] == entered_site]

        fig = px.scatter(df_filtered,
                         x = 'Payload Mass (kg)',
                         y = 'class',
                         color = 'Booster Version',
                         hover_data = ['Booster Version'])
    return fig

if __name__ == '__main__':
    app.run_server(debug = True, use_reloader = False)

Finally, the error that I get is the following:

dash._grouping.SchemaTypeValidationError: Schema: [<Output `success-pie-chart.figure`>, <Output `success-payload-scatter-chart.figure`>]
                Path: ()
                Expected type: (<class 'tuple'>, <class 'list'>)
                Received value of type <class 'plotly.graph_objs._figure.Figure'>:

I really appreciate your time guys.

Please let me know if I can provide any more info or help clarify.

I've tested the functions that take the user's input and produce the pie and scatter charts outside Dash, and they worked fine. So, the error is arising from Dash.


问:
DKIM fail using mailcow
I'm using Mailcow,
I can send email but it goes to spam folder in Gmail,
check header it says "DKIM fail".
spf and DMARC are passed.

I just copied dkim record from mailcow UI and pasted it into domain's DNS.

this is the DNS setings

```<code>DKIM._DOMAINKEY TXT  3600 v=DKIM1;k=rsa;t=s;s=email;p=MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAtltohTp1WvnqRlFkGbaG9Urchi6jnvAQTBRxiehh6ZcslrBdU9KfXVMFDckasKyeHP0tVZSTTWRAiroiTWfKLk7trq3DBsy+Wc8EAz6yMEVLwyCJhh1wtgC/khHjdxzrvQrxbbJIYnz79bKTMUp4/Cr6BJ7eRBnjxWuwJtDmbuGZaxLl5biPvgbUmXqQWGvncSIUrytmLvd2XzLETXDBueIezB0vjZxfFH65znYOs4J+y6hd+EryWjGlM1Gy4Y8uwaKJhVCwdrOGCQjRYeZW3OA1NDCyYxlkPi5mSK/WGIVZBwTdAKwrV5NP2HyNZ5HCZIC8VzcSKAJ3VYHeTsaesQIDAQAB
</code>```

this is the header

DKIM FAILED

```<code>
DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=jpyy.ml; s=dkim;
    t=1671204384; h=from:subject:date:message-id:to:mime-version:content-type;
    bh=RenstW80cSPLXw/2g0G4x1MNFKyZVMXFRE1oZh7R63c=;
    b=FKL9WJIT6f2xgTQnGPgg6i2SaXyjbWtxTFnQAwcfceqPWKYtzrPJkebLmj8ZHDXGv3+7J5
    +XiRjtQOqF5q0KHhNy06fmx1j66n6Z//zTpWhVdVAqjwTeelqfPu2tewt8tZgpvN5Bqpvm
    9+jBJ0iw0Hd+IS/H6uy7TgRPVQzqJ9+bZW99SxDt5QJxTOxW1wsbmEv/4V8P47vARyQCd0
    adPenQewmS8f0BoJwS30pnwVjiHO3ZSe/huBSrlsvWbjjM6b5E+cIfUckBX5dNtiylmcNx
    YACE9Q/QYd/SmvyZnAxFDAFUkCeuKLMxFGKeBBxN6iecyThjVMajspgp1N6z4w==
Signed-by: mail@jjyy.ml
Expected-Body-Hash: RenstW80cSPLXw/2g0G4x1MNFKyZVMXFRE1oZh7R63c=
Public-Key: v=DKIM1;k=rsa;t=s;s=email;p=MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArZGc4NCdvFe5WSXASt7bcsI0E5XrO97yaokMB65cLOi6RDfS4+N9Jt3MlFMKCEJTAa/BT6fHEDJpEOngI9U3Oz8SiTLvzFLz/quguLGZhNYVL1N7yHrMBEP4xsmD1zeoxF573ioIBHeil/27RCQitvco1xUAC5houoA0V3PuayS411Qmgqiinr93gBiaRvKnpGs82pbkQa9N5QDHwDzyTszMemSbEbC4CfBFu7SOlf8ziSVfS/F1VTY/rBa30uSQ8YDz4NbaecykbU4W/QwdHDA9kljUKrCbhA7nOds+l1l+fLl+mtgpu/dAMR9RJ4arNvRmAPv8IojV35Kdg+MH/wIDAQAB;

DKIM-Result: fail (bad signature)
</code>```

I've been struggling with this for 2 days.
any help would be appreciated thank you.

Title: DKIM fail using mailcow

Body:
I'm using Mailcow,
I can send email but it goes to spam folder in Gmail,
check header it says "DKIM fail".
spf and DMARC are passed.

I just copied dkim record from mailcow UI and pasted it into domain's DNS.

this is the DNS setings

DKIM._DOMAINKEY TXT  3600 v=DKIM1;k=rsa;t=s;s=email;p=MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAtltohTp1WvnqRlFkGbaG9Urchi6jnvAQTBRxiehh6ZcslrBdU9KfXVMFDckasKyeHP0tVZSTTWRAiroiTWfKLk7trq3DBsy+Wc8EAz6yMEVLwyCJhh1wtgC/khHjdxzrvQrxbbJIYnz79bKTMUp4/Cr6BJ7eRBnjxWuwJtDmbuGZaxLl5biPvgbUmXqQWGvncSIUrytmLvd2XzLETXDBueIezB0vjZxfFH65znYOs4J+y6hd+EryWjGlM1Gy4Y8uwaKJhVCwdrOGCQjRYeZW3OA1NDCyYxlkPi5mSK/WGIVZBwTdAKwrV5NP2HyNZ5HCZIC8VzcSKAJ3VYHeTsaesQIDAQAB

this is the header

DKIM FAILED

DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=jpyy.ml; s=dkim;
    t=1671204384; h=from:subject:date:message-id:to:mime-version:content-type;
    bh=RenstW80cSPLXw/2g0G4x1MNFKyZVMXFRE1oZh7R63c=;
    b=FKL9WJIT6f2xgTQnGPgg6i2SaXyjbWtxTFnQAwcfceqPWKYtzrPJkebLmj8ZHDXGv3+7J5
    +XiRjtQOqF5q0KHhNy06fmx1j66n6Z//zTpWhVdVAqjwTeelqfPu2tewt8tZgpvN5Bqpvm
    9+jBJ0iw0Hd+IS/H6uy7TgRPVQzqJ9+bZW99SxDt5QJxTOxW1wsbmEv/4V8P47vARyQCd0
    adPenQewmS8f0BoJwS30pnwVjiHO3ZSe/huBSrlsvWbjjM6b5E+cIfUckBX5dNtiylmcNx
    YACE9Q/QYd/SmvyZnAxFDAFUkCeuKLMxFGKeBBxN6iecyThjVMajspgp1N6z4w==
Signed-by: mail@jjyy.ml
Expected-Body-Hash: RenstW80cSPLXw/2g0G4x1MNFKyZVMXFRE1oZh7R63c=
Public-Key: v=DKIM1;k=rsa;t=s;s=email;p=MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArZGc4NCdvFe5WSXASt7bcsI0E5XrO97yaokMB65cLOi6RDfS4+N9Jt3MlFMKCEJTAa/BT6fHEDJpEOngI9U3Oz8SiTLvzFLz/quguLGZhNYVL1N7yHrMBEP4xsmD1zeoxF573ioIBHeil/27RCQitvco1xUAC5houoA0V3PuayS411Qmgqiinr93gBiaRvKnpGs82pbkQa9N5QDHwDzyTszMemSbEbC4CfBFu7SOlf8ziSVfS/F1VTY/rBa30uSQ8YDz4NbaecykbU4W/QwdHDA9kljUKrCbhA7nOds+l1l+fLl+mtgpu/dAMR9RJ4arNvRmAPv8IojV35Kdg+MH/wIDAQAB;

DKIM-Result: fail (bad signature)

I've been struggling with this for 2 days.
any help would be appreciated thank you.


问:
How to dismandle the existing admin login page from the Spring mvc project
Need to remove the Admin login page from the existing Spring mvc project without code scan issues

Tried with jsp changes and controller method changes but it will create scan issues


问:
Script PHP who calls another script PHP
I beg your pardon if some part of the code is written in italian, but I'm trying to make a script for my work, and I want to split two scripts, where in the main script there is a call to another script with the require function.

The main script is the following:

```<code>\<?php
require('c:/include_connessione/ldbproxy.inc.php');

    //define('DB2SERVER' , 'udbsrv0e:50004');
    define('DB2SERVER' , '192.168.8.128:50004');
    define('DB' , 'WAREHSOA');
    define('DBUSR' , 'db2itsoa');
    define('DBPWD' , 'db2itsoa');

    $styleSpieg="style='font-family:arial;font-size: 10pt;text-align: left;'";

    function TRACE($str)
    {
        $fp=fopen('c:/Manutenzione/confronti_itcam/confronti_itcam.log', 'a');
        if($fp)
        {
            fprintf($fp, date('Y-m-d H:i:s') . ' ' . $str . "\n");
            fclose($fp);
        }
    }

    TRACE("START");

    $conn = new ldbproxy();

    if(! $conn->connect_db2(DB2SERVER, DB, DBUSR, DBPWD))
    {
        TRACE('cannot connect to ' . DB2SERVER . ': ' . $conn->errorMsg);
        die();
    }

    $confronti_DataPower=require("confronti_itcam_DataPower.php");

    $conn->close();

    $subject = "Confronto eventi SOA del ".date('d-m-Y',strtotime("-1 days"));
    $spiegazione = "<td $styleSpieg align=left >
                        <b>I dati che seguono hanno lo scopo di confrontare gli eventi dell'applicativo ITCAmfSOA che vengono scritti dall'agent di monitoraggio sulle tabelle del DB2 WAREHSOA, in particolare:<br>
                           - confronto tra eventi di request sulla tabella Services_Inventory_610 (di seguito SI) e la tabella Services_Inventory_ReqID_610 (di seguito SI_ReqID)<br>
                           - confronto tra eventi di fault sulla tabella Services_Inventory_610 (SI) e la tabella Fault_Log_Table_610 (di seguito FLT) </b>
                    </td>";

    $header =  'From:tivoli@inps.it' . "\r\n";
    $header .= "X-Mailer: \n";
    $header .= "MIME-Version: 1.0\n";
    $header .= "Content-Type: text/html; charset=\"iso-8859-1\"\n";
    $header .= "Content-Transfer-Encoding: 7bit\n\n";

    $out = "<html>
            <body>
                <table>
                    <tr>
                            $spiegazione
                    </tr>
                    <tr>
                    </tr>
                    <tr>
                    </tr>
                    <tr>
                        <td>
                            $confronti_DataPower
                        </td>
                    </tr>
                    <tr>
                    </tr>
                </table>
            </body>
        </html>";

    $header="";
    $header = "From: Tivoli <tivoli@inps.it>\n";
    $header .= "MIME-Version: 1.0\n";
    $header .= "Content-Type: text/html; charset=\"iso-8859-1\"\n";
    $header .= "Content-Transfer-Encoding: 7bit\n\n";

    $to= 'f.gatta@man-con.com';

    $res=mail($to,$subject,$out,$header);

    ($res)?TRACE("Mail inviata con successo"):TRACE("Errore invio mail");

    TRACE("END");

?\>
</code>```

The called script (titled "confronti_itcam_DataPower.php") in the require function has the following code:

```<code>
\<?php

    $data=array();
    $temp=array("Request_SI"=>0,"Request_ReqID"=>0,"Fault_SI"=>0,"Fault_FLT"=>0,);

    function Executequery($q,$type)
    {
        global $data;
        global $conn;
        global $temp;
        $resultset=$conn->query($q);
        if(!$resultset)
        {
            TRACE("Errore esecuzione query $type :" . $conn->errorMsg);
            die();
        }

        while($row_object=$conn->fetch($resultset))
        {
            (!isset($data[$row_object['Server']]))?$data[$row_object['Server']]=$temp:'';
            $data[$row_object['Server']][$type]=(($row_object['value']!="")?$row_object['value']:'');
        }
    }

    //COSTRUZIONE TABELLA PER AMBIENTE DATAPOWER

    function create_table()
    {
        global $data;
        $keys=array_keys($data);

        $styleTB="style='font-family:arial;background-color:#1a0da8;margin:3px 0pt 15px;font-size: 9pt;width: 100%;text-align: center;'";
        $styleTHfirst="style='color:#f7fafa;background-color:#1a0da8;border:1px solid #FFF;padding:4px;font-size:18px;font-weight:bold;'";
        $styleTHsecond="style='background-color:#d5eded;border:1px solid #FFF;padding:4px;font-size:15px;font-weight:bold;font-style:italic;'";
        $styleTD="style='color:#3D3D3D;padding:4px;background-color:#FFF;vertical-align:top;'";

        $rowTable="";

        foreach($keys as $key)
        {
            $_Request_SI=$data[$key]['Request_SI'];
            $_Request_ReqID=$data[$key]['Request_ReqID'];
            $scostRequest=$_Request_SI-$_Request_ReqID;

            //$scostRequestPerc=(($_Request_SI==0 && $_Request_ReqID==0)?"Nessuno":(($_Request_SI==0)?"100 %":number_format((($scostRequest/$_Request_SI)*100),2)." %"));

            $_Fault_SI=$data[$key]['Fault_SI'];
            $_Fault_FLT=$data[$key]['Fault_FLT'];
            $scostFault=$_Fault_SI-$_Fault_FLT;

            //$scostFaultPerc=(($_Fault_FLT==0 && $_Fault_SI==0)?"Nessuno":(($_Fault_SI==0)?"100 %":number_format((($scostFault/$_Fault_SI)*100),2)." %"));

            $rowTable.="<tr>
                                <td $styleTD align=center >
                                    <b>$key</b>
                                </td>
                                <td $styleTD align=center >
                                    $_Request_SI
                                </td>
                                <td $styleTD align=center >
                                    $_Request_ReqID
                                </td>
                                <td $styleTD align=center>
                                    $scostRequest
                                </td>
                                <td $styleTD align=center >
                                    $_Fault_SI
                                </td>
                                <td $styleTD align=center >
                                    $_Fault_FLT
                                </td>
                                <td $styleTD align=center >
                                    $scostFault
                                </td>
                            </tr>";
        }

        $table_confronti="<table $styleTB id='table_confronti' style='width:100%'>
                            <thead>
                                <th $styleTHfirst colspan=7  align=center >
                                Ambiente DataPower
                                </th>
                            </thead>
                            <tbody>
                                <tr>
                                    <td $styleTHsecond align=center>
                                        Server
                                    </td>
                                    <td $styleTHsecond align=center >
                                        Request su SI
                                    </td>
                                    <td $styleTHsecond align=center >
                                        Request su SI_ReqID
                                    </td>
                                    <td $styleTHsecond align=center >
                                         Δ request
                                    <td $styleTHsecond align=center>
                                        Fault su SI
                                    </td>
                                    <td $styleTHsecond align=center >
                                        Fault su FLT
                                    </td>
                                    <td $styleTHsecond align=center >
                                        Δ fault
                                    </td>
                                </tr>
                                $rowTable
                            </tbody>
                        </table>";

        $tb="   <center>
                    <table style='width:100%'>
                        <tr>
                            <td>
                                <div >".$table_confronti."</div>
                            </td>
                        </tr>
                    </table>
                </center>";

        return  $tb;
    }

    $yesterday_inf_sol= "1".substr(date('Ymd',strtotime("-2 days")),2)."230000000";
    $yesterday_sup_sol= "1".substr(date('Ymd',strtotime("-1 days")),2)."230000000";
    $yesterday_inf_leg= "1".substr(date('Ymd',strtotime("-2 days")),2)."220000000";
    $yesterday_sup_leg= "1".substr(date('Ymd',strtotime("-1 days")),2)."220000000";

    $query_SI_request='select
                                    upper(substr("Origin_Node",13,17)) as "Server",
                                    sum("Request_Count") as "value"
                                from
                                    "Services_Inventory_610"
                                where
                                    upper(substr("Local_Hostname_U",1,9))=\'CUSTMON03\' and "Service_Type"=1 and
                                    CASE
                                       WHEN "TMZDIFF"=\'-3600\' THEN  ("Interval_Begin_Time">=\''.$yesterday_inf_sol.'\' and "Interval_Begin_Time"<\''.$yesterday_sup_sol.'\')
                                       WHEN "TMZDIFF"=\'-7200\' THEN  ("Interval_Begin_Time">=\''.$yesterday_inf_leg.'\' and "Interval_Begin_Time"<\''.$yesterday_sup_leg.'\')
                                    END
                                    group by upper(substr("Origin_Node",13,17))';

    $query_ReqID='select
                                upper(substr("Origin_Node",13,17)) as "Server",
                                sum("Request_Count") as "value"
                            from
                                "Services_Inventory_ReqID_610"
                            where
                                upper(substr("Local_Hostname_U",1,9))=\'CUSTMON03\' and
                                CASE
                                       WHEN "TMZDIFF"=\'-3600\' THEN  ("Interval_Begin_Time">=\''.$yesterday_inf_sol.'\' and "Interval_Begin_Time"<\''.$yesterday_sup_sol.'\')
                                       WHEN "TMZDIFF"=\'-7200\' THEN  ("Interval_Begin_Time">=\''.$yesterday_inf_leg.'\' and "Interval_Begin_Time"<\''.$yesterday_sup_leg.'\')
                                END
                                group by upper(substr("Origin_Node",13,17))';

    $query_SI_fault='select
                                sum("Fault_Count") as "value",
                                upper(substr("Origin_Node",13,17)) as "Server"
                               from
                                "Services_Inventory_610"
                            where upper(substr("Local_Hostname_U",1,9))=\'CUSTMON03\' and
                                CASE
                                       WHEN "TMZDIFF"=\'-3600\' THEN  ("Interval_Begin_Time">=\''.$yesterday_inf_sol.'\' and "Interval_Begin_Time"<\''.$yesterday_sup_sol.'\')
                                       WHEN "TMZDIFF"=\'-7200\' THEN  ("Interval_Begin_Time">=\''.$yesterday_inf_leg.'\' and "Interval_Begin_Time"<\''.$yesterday_sup_leg.'\')
                                END
                            group by upper(substr("Origin_Node",13,17)) ';

    $query_FLT='select
                                count(*) as "value",
                                upper(substr("Origin_Node",13,17)) as "Server"
                            from
                                "Fault_Log_Table_610"
                            where upper(substr("Hostname_U",1,9))=\'CUSTMON03\' and
                                CASE
                                       WHEN "TMZDIFF"=\'-3600\' THEN  ("Message_Time">=\''.$yesterday_inf_sol.'\' and "Message_Time"<\''.$yesterday_sup_sol.'\')
                                       WHEN "TMZDIFF"=\'-7200\' THEN  ("Message_Time">=\''.$yesterday_inf_leg.'\' and "Message_Time"<\''.$yesterday_sup_leg.'\')
                                END
                            group by upper(substr("Origin_Node",13,17)) ';

    Executequery($query_SI_request,'Request_SI');
    Executequery($query_ReqID,'Request_ReqID');

    Executequery($query_SI_fault,'Fault_SI');
    Executequery($query_FLT,'Fault_FLT');

    $result=create_table();

?\>
</code>```

What I got when all the code was in one script is a table with data after the variable $spiegazione, now after the splitting I get "1" in place of the table after $spiegazione.

Where am I wrong?

Title: Script PHP who calls another script PHP

Body:
I beg your pardon if some part of the code is written in italian, but I'm trying to make a script for my work, and I want to split two scripts, where in the main script there is a call to another script with the require function.

The main script is the following:

\<?php
require('c:/include_connessione/ldbproxy.inc.php');

    //define('DB2SERVER' , 'udbsrv0e:50004');
    define('DB2SERVER' , '192.168.8.128:50004');
    define('DB' , 'WAREHSOA');
    define('DBUSR' , 'db2itsoa');
    define('DBPWD' , 'db2itsoa');

    $styleSpieg="style='font-family:arial;font-size: 10pt;text-align: left;'";

    function TRACE($str)
    {
        $fp=fopen('c:/Manutenzione/confronti_itcam/confronti_itcam.log', 'a');
        if($fp)
        {
            fprintf($fp, date('Y-m-d H:i:s') . ' ' . $str . "\n");
            fclose($fp);
        }
    }

    TRACE("START");

    $conn = new ldbproxy();

    if(! $conn->connect_db2(DB2SERVER, DB, DBUSR, DBPWD))
    {
        TRACE('cannot connect to ' . DB2SERVER . ': ' . $conn->errorMsg);
        die();
    }

    $confronti_DataPower=require("confronti_itcam_DataPower.php");

    $conn->close();

    $subject = "Confronto eventi SOA del ".date('d-m-Y',strtotime("-1 days"));
    $spiegazione = "
                        I dati che seguono hanno lo scopo di confrontare gli eventi dell'applicativo ITCAmfSOA che vengono scritti dall'agent di monitoraggio sulle tabelle del DB2 WAREHSOA, in particolare:

                           - confronto tra eventi di request sulla tabella Services_Inventory_610 (di seguito SI) e la tabella Services_Inventory_ReqID_610 (di seguito SI_ReqID)

                           - confronto tra eventi di fault sulla tabella Services_Inventory_610 (SI) e la tabella Fault_Log_Table_610 (di seguito FLT)
                    	";

    $header =  'From:tivoli@inps.it' . "\r\n";
    $header .= "X-Mailer: \n";
    $header .= "MIME-Version: 1.0\n";
    $header .= "Content-Type: text/html; charset=\"iso-8859-1\"\n";
    $header .= "Content-Transfer-Encoding: 7bit\n\n";

    $out = "

                            $spiegazione

                            $confronti_DataPower

        ";

    $header="";
    $header = "From: Tivoli <tivoli@inps.it>\n";
    $header .= "MIME-Version: 1.0\n";
    $header .= "Content-Type: text/html; charset=\"iso-8859-1\"\n";
    $header .= "Content-Transfer-Encoding: 7bit\n\n";

    $to= 'f.gatta@man-con.com';

    $res=mail($to,$subject,$out,$header);

    ($res)?TRACE("Mail inviata con successo"):TRACE("Errore invio mail");

    TRACE("END");

?\>

The called script (titled "confronti_itcam_DataPower.php") in the require function has the following code:

\<?php

    $data=array();
    $temp=array("Request_SI"=>0,"Request_ReqID"=>0,"Fault_SI"=>0,"Fault_FLT"=>0,);

    function Executequery($q,$type)
    {
        global $data;
        global $conn;
        global $temp;
        $resultset=$conn->query($q);
        if(!$resultset)
        {
            TRACE("Errore esecuzione query $type :" . $conn->errorMsg);
            die();
        }

        while($row_object=$conn->fetch($resultset))
        {
            (!isset($data[$row_object['Server']]))?$data[$row_object['Server']]=$temp:'';
            $data[$row_object['Server']][$type]=(($row_object['value']!="")?$row_object['value']:'');
        }
    }

    //COSTRUZIONE TABELLA PER AMBIENTE DATAPOWER

    function create_table()
    {
        global $data;
        $keys=array_keys($data);

        $styleTB="style='font-family:arial;background-color:#1a0da8;margin:3px 0pt 15px;font-size: 9pt;width: 100%;text-align: center;'";
        $styleTHfirst="style='color:#f7fafa;background-color:#1a0da8;border:1px solid #FFF;padding:4px;font-size:18px;font-weight:bold;'";
        $styleTHsecond="style='background-color:#d5eded;border:1px solid #FFF;padding:4px;font-size:15px;font-weight:bold;font-style:italic;'";
        $styleTD="style='color:#3D3D3D;padding:4px;background-color:#FFF;vertical-align:top;'";

        $rowTable="";

        foreach($keys as $key)
        {
            $_Request_SI=$data[$key]['Request_SI'];
            $_Request_ReqID=$data[$key]['Request_ReqID'];
            $scostRequest=$_Request_SI-$_Request_ReqID;

            //$scostRequestPerc=(($_Request_SI==0 && $_Request_ReqID==0)?"Nessuno":(($_Request_SI==0)?"100 %":number_format((($scostRequest/$_Request_SI)*100),2)." %"));

            $_Fault_SI=$data[$key]['Fault_SI'];
            $_Fault_FLT=$data[$key]['Fault_FLT'];
            $scostFault=$_Fault_SI-$_Fault_FLT;

            //$scostFaultPerc=(($_Fault_FLT==0 && $_Fault_SI==0)?"Nessuno":(($_Fault_SI==0)?"100 %":number_format((($scostFault/$_Fault_SI)*100),2)." %"));

            $rowTable.="

                                    $key

                                    $_Request_SI

                                    $_Request_ReqID

                                    $scostRequest

                                    $_Fault_SI

                                    $_Fault_FLT

                                    $scostFault

";
        }

        $table_confronti="

                                Ambiente DataPower

                                        Server

                                        Request su SI

                                        Request su SI_ReqID

                                         Δ request

                                        Fault su SI

                                        Fault su FLT

                                        Δ fault

                                $rowTable

";

        $tb="

".$table_confronti."

                ";

        return  $tb;
    }

    $yesterday_inf_sol= "1".substr(date('Ymd',strtotime("-2 days")),2)."230000000";
    $yesterday_sup_sol= "1".substr(date('Ymd',strtotime("-1 days")),2)."230000000";
    $yesterday_inf_leg= "1".substr(date('Ymd',strtotime("-2 days")),2)."220000000";
    $yesterday_sup_leg= "1".substr(date('Ymd',strtotime("-1 days")),2)."220000000";

    $query_SI_request='select
                                    upper(substr("Origin_Node",13,17)) as "Server",
                                    sum("Request_Count") as "value"
                                from
                                    "Services_Inventory_610"
                                where
                                    upper(substr("Local_Hostname_U",1,9))=\'CUSTMON03\' and "Service_Type"=1 and
                                    CASE
                                       WHEN "TMZDIFF"=\'-3600\' THEN  ("Interval_Begin_Time">=\''.$yesterday_inf_sol.'\' and "Interval_Begin_Time"<\''.$yesterday_sup_sol.'\')
                                       WHEN "TMZDIFF"=\'-7200\' THEN  ("Interval_Begin_Time">=\''.$yesterday_inf_leg.'\' and "Interval_Begin_Time"<\''.$yesterday_sup_leg.'\')
                                    END
                                    group by upper(substr("Origin_Node",13,17))';

    $query_ReqID='select
                                upper(substr("Origin_Node",13,17)) as "Server",
                                sum("Request_Count") as "value"
                            from
                                "Services_Inventory_ReqID_610"
                            where
                                upper(substr("Local_Hostname_U",1,9))=\'CUSTMON03\' and
                                CASE
                                       WHEN "TMZDIFF"=\'-3600\' THEN  ("Interval_Begin_Time">=\''.$yesterday_inf_sol.'\' and "Interval_Begin_Time"<\''.$yesterday_sup_sol.'\')
                                       WHEN "TMZDIFF"=\'-7200\' THEN  ("Interval_Begin_Time">=\''.$yesterday_inf_leg.'\' and "Interval_Begin_Time"<\''.$yesterday_sup_leg.'\')
                                END
                                group by upper(substr("Origin_Node",13,17))';

    $query_SI_fault='select
                                sum("Fault_Count") as "value",
                                upper(substr("Origin_Node",13,17)) as "Server"
                               from
                                "Services_Inventory_610"
                            where upper(substr("Local_Hostname_U",1,9))=\'CUSTMON03\' and
                                CASE
                                       WHEN "TMZDIFF"=\'-3600\' THEN  ("Interval_Begin_Time">=\''.$yesterday_inf_sol.'\' and "Interval_Begin_Time"<\''.$yesterday_sup_sol.'\')
                                       WHEN "TMZDIFF"=\'-7200\' THEN  ("Interval_Begin_Time">=\''.$yesterday_inf_leg.'\' and "Interval_Begin_Time"<\''.$yesterday_sup_leg.'\')
                                END
                            group by upper(substr("Origin_Node",13,17)) ';

    $query_FLT='select
                                count(*) as "value",
                                upper(substr("Origin_Node",13,17)) as "Server"
                            from
                                "Fault_Log_Table_610"
                            where upper(substr("Hostname_U",1,9))=\'CUSTMON03\' and
                                CASE
                                       WHEN "TMZDIFF"=\'-3600\' THEN  ("Message_Time">=\''.$yesterday_inf_sol.'\' and "Message_Time"<\''.$yesterday_sup_sol.'\')
                                       WHEN "TMZDIFF"=\'-7200\' THEN  ("Message_Time">=\''.$yesterday_inf_leg.'\' and "Message_Time"<\''.$yesterday_sup_leg.'\')
                                END
                            group by upper(substr("Origin_Node",13,17)) ';

    Executequery($query_SI_request,'Request_SI');
    Executequery($query_ReqID,'Request_ReqID');

    Executequery($query_SI_fault,'Fault_SI');
    Executequery($query_FLT,'Fault_FLT');

    $result=create_table();

?\>

What I got when all the code was in one script is a table with data after the variable $spiegazione, now after the splitting I get "1" in place of the table after $spiegazione.

Where am I wrong?


问:
Expo, usePreventScreenCapture how can i use preventCapture in modal? (React native)
I wanted to prevent screen shots in my app, similar to how Netflix uses PreventScreenCapture. I found the Expo package 'expo-screen-capture' and tried using the usePreventScreenCapture hook, but it only works for the current screen. This is a problem because I have a modal in my app, and it is not considered part of the current screen. Is there a way I can prevent screen shots from being taken of the entire app, even when the modal is displayed? I tried declaring the usePreventScreenCapture hook in the main component (which is at the top of the routes), but it doesn't seem to work for the modal.

*: I try declare inside the modal component too


问:
PostgreSQL query and convert a column with Ruby serialized YAML to JSON
I am connecting to a PostgreSQL database, which connected to an old Rails app. It has a table versions  and it has a column with Ruby serialized YAML. From Postico, I would like to do a SELECT query but convert a column with Ruby serialized YAML to JSON.

I tried looking around and found this gist but did not return as expected.

YAML column

```<code>--- !ruby/object:BillingInfo
gateway_identifier: blah
organisation: blah
billing_email: blah
reference: blah
phone: blah
country: blah
vat: blah
subscription: blah
</code>```

expected query result

```<code>{
  "--- !ruby/object":"BillingInfo",
  "gateway_identifier": "blah ",
  "organisation": "blah",
  "billing_email": "blah",
  "reference": "blah",
  "phone": "blah",
  "country": "blah",
  "vat": "blah",
  "subscription": "blah"
}
</code>```

updates:
I tried the suggested from the comment by Gerard

```<code>SELECT jsonb_pretty(jsonb_build_object('YAML', data)) FROM versions;
</code>```

but this returned

```<code>{
    "YAML": "--- !ruby/object:BillingInfo\ngateway_identifier: blah \norganisation: blah\nbilling_email: blah\nreference: blah\nphone: blah\ncountry: blah\nvat: blah\nsubscription: blah"
}
</code>```

Body:
I am connecting to a PostgreSQL database, which connected to an old Rails app. It has a table versions  and it has a column with Ruby serialized YAML. From Postico, I would like to do a SELECT query but convert a column with Ruby serialized YAML to JSON.

I tried looking around and found this gist but did not return as expected.

YAML column

--- !ruby/object:BillingInfo
gateway_identifier: blah
organisation: blah
billing_email: blah
reference: blah
phone: blah
country: blah
vat: blah
subscription: blah

expected query result

{
  "--- !ruby/object":"BillingInfo",
  "gateway_identifier": "blah ",
  "organisation": "blah",
  "billing_email": "blah",
  "reference": "blah",
  "phone": "blah",
  "country": "blah",
  "vat": "blah",
  "subscription": "blah"
}

updates:
I tried the suggested from the comment by Gerard

SELECT jsonb_pretty(jsonb_build_object('YAML', data)) FROM versions;

but this returned

{
    "YAML": "--- !ruby/object:BillingInfo\ngateway_identifier: blah \norganisation: blah\nbilling_email: blah\nreference: blah\nphone: blah\ncountry: blah\nvat: blah\nsubscription: blah"
}


问:
How to revalidate a user in nuxt
In my nuxt project, i get a token from the backend that identifies the user. I tie this token to a vuex prop and save it in localstorage, so the user doesnt have to re authenticate when the page is refreshed.

To revalidate the user only when the page is actually refreshed, i wrote a beforemount function in the highest level, which is the default layout

```<code>beforeMount() {
    const token = localStorage.getItem('user-token')
    console.log(token)

    if (token) {
      this.$axios.defaults.headers.common.Authorization = token
      this.$store.dispatch('auth/setToken', token)
    }
  }
</code>```

In the next step, the router on protected pages should check if the authstate is true, which is only true if the vuex localstorage prop is set. Since i only need that on certain pages, i wrote a router middleware thats only loaded on these pages

```<code>export default function (context) {
  if (!context.store.getters['auth/isAuthenticated']) {
    return context.redirect('/auth?login')
  }
}
</code>```

Problem is, the middleware runs before the beforeMount according to the docu, which creates the problem that the middleware checks for a token which is set later and kicks the user out.

Since the only thing that comes before router middleware is global middleware, my plan was to write the reauth as global middleware. But somehow, the middleware is also called on every router change, not only before the site is created aka page refresh. This would execute the function way too often.

The goal is to set the token before the route validate based on the token, only on page refresh, since the rest is taken care of by vuex.

Title: How to revalidate a user in nuxt

Body:
In my nuxt project, i get a token from the backend that identifies the user. I tie this token to a vuex prop and save it in localstorage, so the user doesnt have to re authenticate when the page is refreshed.

To revalidate the user only when the page is actually refreshed, i wrote a beforemount function in the highest level, which is the default layout

beforeMount() {
    const token = localStorage.getItem('user-token')
    console.log(token)

    if (token) {
      this.$axios.defaults.headers.common.Authorization = token
      this.$store.dispatch('auth/setToken', token)
    }
  }

In the next step, the router on protected pages should check if the authstate is true, which is only true if the vuex localstorage prop is set. Since i only need that on certain pages, i wrote a router middleware thats only loaded on these pages

export default function (context) {
  if (!context.store.getters['auth/isAuthenticated']) {
    return context.redirect('/auth?login')
  }
}

Problem is, the middleware runs before the beforeMount according to the docu, which creates the problem that the middleware checks for a token which is set later and kicks the user out.

Since the only thing that comes before router middleware is global middleware, my plan was to write the reauth as global middleware. But somehow, the middleware is also called on every router change, not only before the site is created aka page refresh. This would execute the function way too often.

The goal is to set the token before the route validate based on the token, only on page refresh, since the rest is taken care of by vuex.


问:
Is there a way to open several connections through script on Anydesk?
I'm trying to make a script where I could do the following:

Open an Anydesk connection

Put the ID and password

Close the connection

Repeat 1, 2 and 3 but with different IDs.

The idea of this is because I have a lot of computers where I have to configure several IDs with its respective password. So I'd like to save time and not doing manually.

This is what I tried:

```<code>@echo off
for /f "delims=" %%i in ('"C:\Program Files (x86)\AnyDesk\AnyDesk.exe" --get-status') do set STATUS=%%i
echo <password> | "C:\Program Files (x86)\AnyDesk\AnyDesk.exe" <ID/Alias> --with-password
echo <password> | "C:\Program Files (x86)\AnyDesk\AnyDesk.exe" <ID/Alias> --with-password
pause
</code>```

The first connections works, but it doesn't go throught the next connection, and I also don't know how to close the current one throught the script.

I'd gladly appreciate any help.

Body:
I'm trying to make a script where I could do the following:

Open an Anydesk connection

Put the ID and password

Close the connection

Repeat 1, 2 and 3 but with different IDs.

The idea of this is because I have a lot of computers where I have to configure several IDs with its respective password. So I'd like to save time and not doing manually.

This is what I tried:

@echo off
for /f "delims=" %%i in ('"C:\Program Files (x86)\AnyDesk\AnyDesk.exe" --get-status') do set STATUS=%%i
echo <password> | "C:\Program Files (x86)\AnyDesk\AnyDesk.exe" <ID/Alias> --with-password
echo <password> | "C:\Program Files (x86)\AnyDesk\AnyDesk.exe" <ID/Alias> --with-password
pause

The first connections works, but it doesn't go throught the next connection, and I also don't know how to close the current one throught the script.

I'd gladly appreciate any help.


问:
How to expect error 'element click intercepted' in Javascript?
I am writing a test on Webdriverio. I want to click on an element and I know I will get a 'element click intercepted' error because I can't click on it.

How should I write expect(...) for my test? I want to write that I know what error I want to see.

My code is:

```<code>await settingsDateViewObjets.setDate('Tomorrow')
</code>```

This function opens the calendar and sets the date there. My test is to check that I can't click on a future date.

I tried to write something like that:

```<code>expect(await settingsDateViewObjets.setDate('Tomorrow')).toHaveValue('element click intercepted')
</code>```

and this

```<code>expect(await settingsDateViewObjets.setDate('Tomorrow')).toThrowError('element click intercepted');
</code>```

but this is not correctly. Thank you for helping.

Body:
I am writing a test on Webdriverio. I want to click on an element and I know I will get a 'element click intercepted' error because I can't click on it.

How should I write expect(...) for my test? I want to write that I know what error I want to see.

My code is:

await settingsDateViewObjets.setDate('Tomorrow')

This function opens the calendar and sets the date there. My test is to check that I can't click on a future date.

I tried to write something like that:

expect(await settingsDateViewObjets.setDate('Tomorrow')).toHaveValue('element click intercepted')

and this

expect(await settingsDateViewObjets.setDate('Tomorrow')).toThrowError('element click intercepted');

but this is not correctly. Thank you for helping.


问:
calculate the execution time in 2 different devices
I want to measure the delay of a system which works in 2 different python scripts in different devices ie one in the local pc and other in the virtual machine.

In simple words, i need to measure the delay when the script in virtual machine start and when its gets the feedback from the local pc .

I tried with the time module where i can find the start and end time and subtracting them gives the duration of the process.
Since different devices have different time references. It would not give an accurate answer.
I want to know if there is any way to find the delay in 2 different devices.

Hoping to get some ideas on how to do it.


问:
Android. How to access pdf document from android test?
I have create PdfViewer with compose. Now I need to write android tests for my component. My PdfViewer retrieves uri.
The problem is that in the test I need to somehow get uri on a pdf document. Is it possible to do this?
And if there is no pdf document on the device, then my test will fail. How are these cases handled? Please help me.</p>