问:
import Error: 'chrome_remote_interface' could not be resolved in Selenium Python project
i am trying to use the package >>https://github.com/cyrus-and/chrome-remote-interface

in my selenium python code project

I have cloned this GitHub repo to my project
but still showing an error message for the from chrome_remote_interface import Client
saying >>

Import "chrome_remote_interface" could not be resolvedPylancereportMissingImports

and my script code also located in >>"C:\Users\loai\Documents\GitHub\chatGPt\main"

```<code>import time
import sys
sys.path.append(r"C:\Users\loai\Documents\GitHub\chatGPt\chrome-remote-interface-master")
from selenium import webdriver
from selenium.webdriver.common.by import By
from chrome_remote_interface import Client
</code>```

any one can help me how to fix this issue that I am facing with importing the chrome_remote_interface?

Body:
i am trying to use the package >>https://github.com/cyrus-and/chrome-remote-interface

in my selenium python code project

I have cloned this GitHub repo to my project
but still showing an error message for the from chrome_remote_interface import Client
saying >>

Import "chrome_remote_interface" could not be resolvedPylancereportMissingImports

and my script code also located in >>"C:\Users\loai\Documents\GitHub\chatGPt\main"

import time
import sys
sys.path.append(r"C:\Users\loai\Documents\GitHub\chatGPt\chrome-remote-interface-master")
from selenium import webdriver
from selenium.webdriver.common.by import By
from chrome_remote_interface import Client

any one can help me how to fix this issue that I am facing with importing the chrome_remote_interface?


来源: stackexchange

问:
Merge in Snowflake- Not matched then Update
Source table:

```<code>ID  EventDate   Updated_at
1001    2022-01-01  2022-03-15
1002    2022-01-02  2022-03-18
1003    2022-03-01  2022-03-15
1004    2022-03-10  2022-03-20
</code>```

Target table:

```<code>ID  EventDate   Updated_at  Active_flag
1001    2022-01-01  2022-01-01  p
1002    2022-01-02  2022-01-02  p
1003    2022-03-01  2022-03-01  p
1004    2022-03-10  2022-03-10  p
1005    2022-03-18  2022-03-18  p
</code>```

I need to update the the target table active_flag as 'Y' for 1001,1002,1003 and 1004  and for ID 1005 Active Flag should be N.

Basically the requirement is if the ID's are matching with target then active flag is Y else N

Final result should be

```<code>ID  EventDate   Updated_at  Active_flag
1001    2022-01-01  2023-01-12  Y
1002    2022-01-02  2023-01-12  Y
1003    2022-03-01  2023-03-12  Y
1004    2022-03-10  2023-03-12  Y
1005    2022-03-18  2023-03-12  N
</code>```
```<code>merge into trg_table d
using (
  select *
  from  src_table
) u
  on d.ID = u.ID
when matched then update set d.Active_flag ='Y'
when not matched then insert  (d.Active_flag) values ('N');
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Source table:

ID  EventDate   Updated_at
1001    2022-01-01  2022-03-15
1002    2022-01-02  2022-03-18
1003    2022-03-01  2022-03-15
1004    2022-03-10  2022-03-20

Target table:

ID  EventDate   Updated_at  Active_flag
1001    2022-01-01  2022-01-01  p
1002    2022-01-02  2022-01-02  p
1003    2022-03-01  2022-03-01  p
1004    2022-03-10  2022-03-10  p
1005    2022-03-18  2022-03-18  p

I need to update the the target table active_flag as 'Y' for 1001,1002,1003 and 1004  and for ID 1005 Active Flag should be N.

Basically the requirement is if the ID's are matching with target then active flag is Y else N

Final result should be

ID  EventDate   Updated_at  Active_flag
1001    2022-01-01  2023-01-12  Y
1002    2022-01-02  2023-01-12  Y
1003    2022-03-01  2023-03-12  Y
1004    2022-03-10  2023-03-12  Y
1005    2022-03-18  2023-03-12  N

merge into trg_table d
using (
  select *
  from  src_table
) u
  on d.ID = u.ID
when matched then update set d.Active_flag ='Y'
when not matched then insert  (d.Active_flag) values ('N');


问:
"Error: Can't open display" with ubuntu bash and Xming
I failed to open Xdisplay from ubuntu bash (opened in command prompt from Win11).

Setup:

Launch XLaunch with all default options

In command prompt, enter bash (Ubuntu)

Maybe relevant configs: In "/etc/ssh/sshd_config", X11Forwarding yes and X11UseLocalhost yes. In "/etc/ssh/ssh_config", ForwardX11 yes and ForwardX11Trusted yes.

Opening xeyes straight from Xming works just fine.

DISPLAY=172.17.112.1:0.0; xeyes will hang for a couple of minutes and then gives Error: Can't open display:. Any other DISPLAY I've tried (such as 127.0.0.1:0.0, localhost:0.0) instantly gives the error message. Similarly, gvim or matplotlib from python scripts fail as well.

Ideally after this is resolved, I can use Xdisplay from ssh sessions (opened from bash) as well. Any help is appreciated.


问:
Getting data from output
I have npm called ngx-snake. I would like to collect data about points. In documentation has been written

```<code>#### Outputs

Name  | Description
--- | ---
foodEaten | Called whenever our sweet snake gained some weight ;)
gameOver | :( collision! snake didn't make it (remember about reset button)
</code>```

so in my component.html I write

```<code>    <div class="container-user">
      <ngx-snake (foodEaten)="showResult($event)"></ngx-snake>
    </div>
</code>```

and in component.html

```<code>  showResult(points: any): void {
    console.log(points++);
  }
</code>```

But in fact there is no information about points. It shows another game-grid. I tried also change  to
 but it also not work.

Title: Getting data from output

Body:
I have npm called ngx-snake. I would like to collect data about points. In documentation has been written

#### Outputs

Name  | Description
--- | ---
foodEaten | Called whenever our sweet snake gained some weight ;)
gameOver | :( collision! snake didn't make it (remember about reset button)

so in my component.html I write

      <ngx-snake (foodEaten)="showResult($event)"></ngx-snake>

and in component.html

  showResult(points: any): void {
    console.log(points++);
  }

But in fact there is no information about points. It shows another game-grid. I tried also change  to
 but it also not work.


问:
How to architect cloud containerized services to provide the same interface
I am trying to develop some cloud applications for a club at school. I have several different services which need to stream data to a data application which will handle it. Some of these services need calls back after the data is done processing to do something. Each service is containerized. This is essentially an IoT problem with multiple nodes producing data to the cloud to be handled, and then instructions coming back to that node to do something. Due to differences in hardware, some of these services are written in different programming languages. I would like all of these services to provide the same API to the data application so that receiving data from each individual service does not need to hardcoded.

My first thought was to just have the names of all of the API functions to coincide. These feels awkward to me and I would like there to be more architectural structure behind it. In programming terms, each of these services or IoT device would be considered a subclass that overloads specific methods in a Data Source parent class. I would then like to configure my data application with only one interface, the Data Source interface, rather than a specific interface for every service. If there is no formal way to provide the same interface for these different components, would it be best to just provide a separate API for each one and make all the of the names the same?

Thanks.


问:
Under a Continuous Deployment process to publish a Maven package of a Clojure project, should the script execute "lein install" or "lein uberjar"?
I built a Continuous Deployment workflow via GitHub Actions for this Clojure project. It is a fork from a public repository.

The goal was to publish a Maven package on the GitHub Registry every time project.clj file gets tweaked (usually it is tweaked for version bumps).

It works. See the workflow running smoothly. And the package has been successfully published.

As shown on the cd.yml file, before the Deployment part on the script, there is a lein install execution on the script.

A co-worker suggested that instead of lein install the command lein uberjar should be the one being used.

According to the official documentation:

```<code>lein uberjar # package the project and dependencies as standalone jar
</code>```

And lein install on the other hand:

```<code>Install jar and pom to the local repository; typically ~/.m2.
</code>```

1 - Under this Maven package publishing effort context, which command should be used lein uberjar or lein install? Why?

2 - Is there any disadvantage to using lein install instead of lein uberjar? It the only downside an "overkill aspect"?

3 - Also, even if lein uberjar is the most appropriate way on GitHub Actions, if the cd.yml is being used as hard-coded documentation for other developers to replicate things locally (if needed), wouldn't it be better to have maximum reproducibility? And, hence, wouldn't lein install be the appropriate approach instead of lein uberjar?

Body:
I built a Continuous Deployment workflow via GitHub Actions for this Clojure project. It is a fork from a public repository.

The goal was to publish a Maven package on the GitHub Registry every time project.clj file gets tweaked (usually it is tweaked for version bumps).

It works. See the workflow running smoothly. And the package has been successfully published.

As shown on the cd.yml file, before the Deployment part on the script, there is a lein install execution on the script.

A co-worker suggested that instead of lein install the command lein uberjar should be the one being used.

According to the official documentation:

lein uberjar # package the project and dependencies as standalone jar

And lein install on the other hand:

Install jar and pom to the local repository; typically ~/.m2.

1 - Under this Maven package publishing effort context, which command should be used lein uberjar or lein install? Why?

2 - Is there any disadvantage to using lein install instead of lein uberjar? It the only downside an "overkill aspect"?

3 - Also, even if lein uberjar is the most appropriate way on GitHub Actions, if the cd.yml is being used as hard-coded documentation for other developers to replicate things locally (if needed), wouldn't it be better to have maximum reproducibility? And, hence, wouldn't lein install be the appropriate approach instead of lein uberjar?


问:
Postgres view column value based on criteria of another column
I would like to create a view, in the view I want a generated column created based on a like value
table-a
name, region, status

region will have values as such, A1, A2, B2, B3, D5-1, D5-2, D2-3
The new column, class, will be a 1 or 2, depending on if the region contains a '-' 1 if there is no dash or 2 if there is dash
Thanks

I have not tried anything because I am not sure how to do it.


问:
chrome extension: how to invoke an api call from outside any content scripts?
I'm making a chrome extension that invokes a content script called main.js. The main.js injects a content script content.js into a current web pages DOM . There are basically some buttons that get inserted onto any web page that you visit and content.js has the function that call an API to get data.

The thing is, when the html button is pressed and makes an API call using the javascript fetch method (I included this method in my content.js file), the origin of the request comes from whatever web page you visit and press the button on. I want to get the API request origin to show as chrome-extension://xxx, and this worked as a test when I put the api call in background.js, for example. So I'm trying to think where I can put the API call function or how to call it so it's not being called as origin from the webpage.

Is there a way that I could "message" some backend component to invoke a function from so the API call to fetch data happens outside of the DOM?


问:
AWS lambda with JSON input
I'm trying to convert InputStream to JSON and parse it to POJO object. But there pojo is always an empty object. Do you see any issue with my method? I'm using AWS lambda with function URL. Is there a better way to create a REST API in AWS lambda?</p>
```<code>public class MyHandler implements RequestStreamHandler {

private final Gson gson = new Gson();

@Override
public void handleRequest(InputStream inputStream, OutputStream outputStream, Context context) throws IOException {

    // reading json input
    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
    Request request = gson.fromJson(reader, Request.class);

    // getting logger
    LambdaLogger logger = context.getLogger();

    // logging input
    logger.log(request.toString());

    Response response = new Response(999);

    // creating response
    OutputStreamWriter writer = new OutputStreamWriter(outputStream, StandardCharsets.UTF_8);
    writer.write(gson.toJson(response));
    writer.close();
   }
}

public class Request {
private String name;

public String getName() {
    return name;
}

public Request() {
}

public void setName(String name) {
    this.name = name;
}

@Override
public String toString() {
    return "Request{" +
            "name='" + name + '\'' +
            '}';
   }
 }
</code>```

Title: AWS lambda with JSON input

Body:
I'm trying to convert InputStream to JSON and parse it to POJO object. But there pojo is always an empty object. Do you see any issue with my method? I'm using AWS lambda with function URL. Is there a better way to create a REST API in AWS lambda?

public class MyHandler implements RequestStreamHandler {

private final Gson gson = new Gson();

@Override
public void handleRequest(InputStream inputStream, OutputStream outputStream, Context context) throws IOException {

    // reading json input
    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
    Request request = gson.fromJson(reader, Request.class);

    // getting logger
    LambdaLogger logger = context.getLogger();

    // logging input
    logger.log(request.toString());

    Response response = new Response(999);

    // creating response
    OutputStreamWriter writer = new OutputStreamWriter(outputStream, StandardCharsets.UTF_8);
    writer.write(gson.toJson(response));
    writer.close();
   }
}

public class Request {
private String name;

public String getName() {
    return name;
}

public Request() {
}

public void setName(String name) {
    this.name = name;
}

@Override
public String toString() {
    return "Request{" +
            "name='" + name + '\'' +
            '}';
   }
 }


问:
js map not converting value when map is initialized after node.js filesystem reference
FIXED but i dont know how i did it

im trying to change the content of a
 element so that it is set equal to the return value from a function.
the inner.HTML is supposed to change to the press of a button.

```<code>   <p class="input-text" id="pressed"> </p> //paragraph to change
   <button class="short-button" onclick ="addShort();changeTextMorse();">⚫</button>

const morseAlphabet = {
    '.-': 'a', '-...': 'b', '-.-.': 'c', '-..': 'd', '.': 'e',
    '..-.': 'f', '--.': 'g', '....': 'h', '..': 'i', '.---': 'j',
    '-.-': 'k', '.-..': 'l', '--': 'm', '-.': 'n', '': 'o',
    '.--.': 'p', '--.-': 'q', '.-.': 'r', '...': 's', '-': 't',
    '..-': 'u', '...-': 'v', '.--': 'w', '-..-': 'x', '-.--': 'y',
    '--..': 'z', '.----': '1', '..---': '2', '...--': '3',
    '....-': '4', '.....': '5', '-....': '6', '--...': '7',
    '---..': '8', '----.': '9', '-----': '0', '.-.-.-': '.',
    '--..--': ',', '..--..': '?', '-..-.': '/', '.--.-.': '@'
};
    function changeTextMorse()
{
       document.querySelector("#pressed").innerHTML = decode(morseText);
}
function decode(word)
{
    console.log("decode function gets called");
    newWord = morseAlphabet[word];
    console.log(newWord);
    morseText = "";
    return newWord
}
</code>```

so turns out that the problem was the dictionary that i was using to convert morse code into text. previously it was below the variable

```<code>var fs = require("fs"); //function from node.js
</code>```

i moved the variable to be positioned after the map and for some reason it worked. if someone knows why that variable is stopping my code id be very interested to know.
Thanks!

Body:
FIXED but i dont know how i did it

im trying to change the content of a
 element so that it is set equal to the return value from a function.
the inner.HTML is supposed to change to the press of a button.

 //paragraph to change
   <button class="short-button" onclick ="addShort();changeTextMorse();">⚫</button>

const morseAlphabet = {
    '.-': 'a', '-...': 'b', '-.-.': 'c', '-..': 'd', '.': 'e',
    '..-.': 'f', '--.': 'g', '....': 'h', '..': 'i', '.---': 'j',
    '-.-': 'k', '.-..': 'l', '--': 'm', '-.': 'n', '': 'o',
    '.--.': 'p', '--.-': 'q', '.-.': 'r', '...': 's', '-': 't',
    '..-': 'u', '...-': 'v', '.--': 'w', '-..-': 'x', '-.--': 'y',
    '--..': 'z', '.----': '1', '..---': '2', '...--': '3',
    '....-': '4', '.....': '5', '-....': '6', '--...': '7',
    '---..': '8', '----.': '9', '-----': '0', '.-.-.-': '.',
    '--..--': ',', '..--..': '?', '-..-.': '/', '.--.-.': '@'
};
    function changeTextMorse()
{
       document.querySelector("#pressed").innerHTML = decode(morseText);
}
function decode(word)
{
    console.log("decode function gets called");
    newWord = morseAlphabet[word];
    console.log(newWord);
    morseText = "";
    return newWord
}

so turns out that the problem was the dictionary that i was using to convert morse code into text. previously it was below the variable

var fs = require("fs"); //function from node.js

i moved the variable to be positioned after the map and for some reason it worked. if someone knows why that variable is stopping my code id be very interested to know.
Thanks!


问:
What is the best outlier detector for data that has a mistype in imputing by user?
I am trying to analyze and make a model based on World Bank data. In my dataset I has some columns with mistype in numbers. The actual problem consist in mistyping one digit in a big number, and the actual number is 10 times smaller than original.

In this image there is scatter plot of Population in Afghanistan from (2000 to 2015).
The real population of Afhanistan in 2015 was 33 millions (source: Wikipedia).

The person who entered the data made mistakes in entering the data, sometimes not adding a digit to the number, for example instead of 36043432, he entered only 3604343, and respectively the number is 10 times smaller than the initial one, as a result it creates enormous disturbances in dataset.

I tried to make my own algorithm to detect bottom outliers using z-score.

```<code># Outlier Detector based on deviation from std.

# Take the natural logarithm of the data
data_Afganistan['log_pop'] =
np.log(data_Afganistan['Population'])

# Create a new column for Z-Scores
data_Afganistan['z_score'] = np.abs(data_Afganistan['log_pop'] -
data_Afganistan['log_pop'].mean()) /
data_Afganistan['log_pop'].std()

# Identify outliers
outliers = data_Afganistan[data_Afganistan['z_score'] > 1.2]

# Ploting data
plt.scatter(data_Afganistan['Year'].astype(int),
data_Afganistan['Population'], color=['blue' if year not in
outliers['Year'].values else 'red' for year in
data_Afganistan['Year']])
</code>```

But results aren't so good.
There is result

Algorithm incorrectly detected outliers (red dotes).
There is need to detect all dotes that are at the bottom

**How to detect bottom dotes ? **

Body:
I am trying to analyze and make a model based on World Bank data. In my dataset I has some columns with mistype in numbers. The actual problem consist in mistyping one digit in a big number, and the actual number is 10 times smaller than original.

In this image there is scatter plot of Population in Afghanistan from (2000 to 2015).
The real population of Afhanistan in 2015 was 33 millions (source: Wikipedia).

The person who entered the data made mistakes in entering the data, sometimes not adding a digit to the number, for example instead of 36043432, he entered only 3604343, and respectively the number is 10 times smaller than the initial one, as a result it creates enormous disturbances in dataset.

I tried to make my own algorithm to detect bottom outliers using z-score.

# Outlier Detector based on deviation from std.

# Take the natural logarithm of the data
data_Afganistan['log_pop'] =
np.log(data_Afganistan['Population'])

# Create a new column for Z-Scores
data_Afganistan['z_score'] = np.abs(data_Afganistan['log_pop'] -
data_Afganistan['log_pop'].mean()) /
data_Afganistan['log_pop'].std()

# Identify outliers
outliers = data_Afganistan[data_Afganistan['z_score'] > 1.2]

# Ploting data
plt.scatter(data_Afganistan['Year'].astype(int),
data_Afganistan['Population'], color=['blue' if year not in
outliers['Year'].values else 'red' for year in
data_Afganistan['Year']])

But results aren't so good.
There is result

Algorithm incorrectly detected outliers (red dotes).
There is need to detect all dotes that are at the bottom

**How to detect bottom dotes ? **


问:
How to prevent my hamburger icon disappearing from screen when changing the screen width?
So, I am currently building a website with HTML, CSS, and VanillaJS and the hamburger icon for the mobile menu does not work, because although I set it to a fixed position, when I am checking the responsivity of the screen on different device screen widths by decreasing the width itself the icon slips away and it just moves towards the left side of the page.

Is there any way to prevent this from happening?

//PICTURES
First, the hamicon can be seen
But as I start decreasing the width of the screen it disappears

//HERE IS MY HTML CODE

```<code>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <link rel="stylesheet" href="gallery.css">
    <title>Eckert Művek Galéria</title>
</head>
<body>
    <div class="floating-btn show-btn" aria-label="up button" role="button">
        <img src="assets/svg_files/chevron-up-solid.svg" alt="up img" />
    </div>
    <header>
        <nav>

            <div class="logo">
                <img class="header-logo" src="assets/icons/114533_321471.png" alt="">

            </div>

            <ul id="desktop-menu">
                <li class="nav-item"><a href="home.html">Főoldal</a></li>
                <li class="nav-item"><a href="aboutus.html">Rólunk</a></li>
                <li class="nav-item"><a href="services.html">Szolgáltatások</a></li>
                <li class="nav-item"><a href="whyus.html">Miért mi?</a></li>
                <li class="nav-item"><a href="gallery.html">Galéria</a></li>
                <li class="nav-item"><a href="contacts.html">Kapcsolatok</a></li>
            </ul>
            <!--HAMBURGER ICON-->
            <div class="header-right-gap">
                <button class="hamburger" aria-label="hamburger button">
              <div class="line line-1"></div>
              <div class="line line-2"></div>
              <div class="line line-3"></div>
                </button>
            </div>

        </nav>
         <!--MOBILE MENU-->
         <div class="mobile-menu">
            <ul class="m-menu">
                <li ><a href="home.html">Főoldal</a></li>
                <li ><a href="aboutus.html">Rólunk</a></li>
                <li ><a href="services.html">Szolgáltatások</a></li>
                <li ><a href="whyus.html">Miért mi?</a></li>
                <li ><a href="gallery.html:">Galéria</a></li>
                <li ><a href="contacts.html">Kapcsolat</a></li>
            </ul>

        </div>
    </header>
    <main class="carousel-container">
        <div class="carousel-images">
            <img src="assets\images\pavebrick\buckgrey.jpg" alt="img-1">
            <img src="assets\images\pavebrick\colorful.jpg" alt="img-2">
            <img src="assets\images\pavebrick\greybigplace.jpg" alt="img-3">
            <img src="assets\images\pavebrick\colbig.jpg" alt="img-4">
            <img src="assets\images\pavebrick\wheelgrey.jpg" alt="img-5">
            <img src="assets\images\pavebrick\yardrock.jpg" alt="img-6">

        </div>
        <div class= "btn-container">
            <div class="btn btn-left">
                <img src="assets/svg_files/arrow-left-solid.svg" alt="left-arrow">
            </div>
            <div class="btn btn-right">
                <img src="assets/svg_files/arrow-right-solid.svg" alt="right-arrow">
            </div>
        </div>
    </main>
    <footer>
        <div class="footer-container">

            <div class="footer-top">
                <nav>
                    <ul>
                        <li><a href="home.html">Főoldal</a></li>
                        <li><a href="aboutus.html">Rólunk</a></li>
                        <li><a href="services.html">Szolgáltatások</a></li>
                        <li><a href="whyus.html">Miért mi?</a></li>
                        <li><a href="gallery.html">Galéria</a></li>
                        <li><a href="contacts.html">Kapcsolatok</a></li>
                    </ul>
                </nav>
            <div class="text-container">
                <h4>Ttitle-1</h4>
                <p>Lorem ipsum dolor sit amet consectetur adipisicing elit.
                     Dicta modi laborum quibusdam quis natus debitis qui dolor
                     voluptatibus ab sit, cum saepe enim unde doloribus veniam
                     numquam perspiciatis optio impedit.</p>
            </div>
            <div class="text-container">
                <h4>Ttitle-1</h4>
                <p>Lorem ipsum dolor sit amet consectetur adipisicing elit.
                     Dicta modi laborum quibusdam quis natus debitis qui dolor
                     voluptatibus ab sit, cum saepe enim unde doloribus veniam
                     numquam perspiciatis optio impedit.</p>
            </div>

                </nav>
            </div>

            <!--Social media icons-->
            <div class="social-media-icons">
                <div class="sm-container" id="insta">
                    <div class="sm-icon">
                        <a href="images/instagram-logo.svg" class="fa fa-instagram"></a>

                    </div>
                </div>
                <div class="sm-container" id="github">
                    <div class="sm-icon">
                        <a href="images/github-logo.svg" class="fa fa-github"></a>

                    </div>
                </div>
                <div class="sm-container" id="facebook">
                    <div class="sm-icon">
                        <a href="images/facebook-logo.svg" class="fa fa-facebook"></a>

                    </div>
                </div>
              <div class="sm-container" id="linkedin">
                <div class="sm-icon">
                    <a href="images/linkedin-logo.svg" class="fa fa-linkedin"></a>

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

            <!--Social media icons-->

            <div class="footer-bottom">
                <p>© Eckert Művek Kft. Minden jog fenntartva.</p>
            </div>
        </div>
    </footer>

    <script src="gallery.js"></script>
</body>
</html>
</code>```

//AND HERE IS MY CSS CODE

```<code>/CSS RESET/

*, *::after, *::before { box-sizing: border-box; margin: 0; padding: 0; }

:root { --font-size: 18px; --bg-color-flt-btn: yellow; }

body { width: 100%; height: 100%; }

.floating-btn { position: fixed; bottom: 3.5vh; right: 0; width: 50px; height: 50px; z-index: 100; background-color: var(--bg-color-flt-btn); border-radius: 50%; padding: 10px; box-shadow: 0 0 5px hsla(0, 0%, 0%, hsla(0,0%,0%,0.5)); cursor: pointer; margin-right: 1rem; border: 1px solid #000; }

.show-btn { display: block; }

a { text-decoration: none; color: inherit; }

/HEADER STYLE/

header { width: 100%; height: 120px; background-color: black; color: white; display: flex; align-items: center; position: fixed; top: 0; left: 0; z-index: 10; }

/Srcollbar/

::-webkit-scrollbar{ width: 15px; background: #000; }

::-webkit-scrollbar-thumb { background: yellow; border-radius: 10px; border: 1px solid black; }

::-webkit-scrollbar-thumb:active { background: orangered; }

nav, .footer-container { width: min(90%, 1200px); display: flex; margin-inline: auto; position: relative;

}

nav { justify-content: space-between; /display: flex; flex-direction: flex-end; font-size: 30px;/

}

.nav-item a { color: var(--clr-nav-item-main); list-style: none; text-transform: uppercase; font-size: 20px; font-weight: bold; height: 100%; text-decoration: none; position: relative; margin: .5em .8em; padding: 10px;

}

/újonnan adtam hozzá 2023.01.12./ /nav a { position: relative; z-index: 1; justify-content: space-evenly; height: 100%; }/

nav ul { display: flex; gap: 1rem; width: 100%; justify-content: center; margin-top: 3.5rem;

/*margin-top: 2rem;*/

}

nav ul li { text-transform: uppercase; list-style: none;

}

.nav-item a::before, .nav-item a::after { content: ''; height: 14px; width: 14px; position: absolute; transition: all .35s ease; opacity: 0; }

nav a::before { content: ''; right: 0; top: 0; border-top: 3px solid #ffed4b; border-right: 3px solid #fdcd3b; transform: translate(-100%, 50%); /-100%, 50%/ }

.nav-item a:after { content: ''; left: 0; bottom: 0; border-bottom: 3px solid #fdcd3b; border-left: 3px solid #ffed4b; transform: translate(100%, -50%);  /100%, -50%/ }

.nav-item a:hover:before, .nav-item a:hover:after{ transform: translate(0,0); opacity: 1; }

nav ul li a:hover { color: yellow; }

/Logo/

.logo img { position: absolute; width: 150px; height: 90px; margin-top: -2rem; margin-left: 70rem; left: 0; top: 0; }

/CAROUSEL SSTYLE/ /ha négy képünk van akkor ez 200 vw lesz/

.carousel-container { position: relative; width: 100%; height: 100vh; overflow: hidden;

}
</code>```

`

```<code>/*transform: translateX(-200vw);*/
</code>```
```<code>.carousel-images { transition: all 0.8s ease; width: 600vw; /700-zal és 800-zal is működik/ display: flex; height: 100%;
}

.carousel-images img { width: 100vw; height: 100%; object-fit: cover; }

.btn-container { position: absolute; display: flex; width: 100px; justify-content: space-between; bottom: 10vh; left: calc(50% - 75px); }

.btn { width: 40px; height: 40px; border: 2px solid #000; background-color: #fff; padding: 10px; border-radius: 10px;

}

.btn:hover { cursor: pointer; }

.btn img { width: 100%; height: 100%; }

/FOOTER STYLE/

footer { width: 100%; background-color: #000; padding-block: 4rem; color: white; }

.footer-container { flex-direction: column;

}

.footer-container nav ul { flex-direction: column; }

.footer-top { width: 100%; display: grid; grid-template-columns: repeat(3, 1fr); gap: 1rem;

}

.footer-bottom { margin-top: 3rem; text-align: center;

}

/SOCIAL MEDIA ICONS/

.social-media-icons { width: 100%; display: flex; justify-content: center; align-items: center; flex-direction: row;

}

.sm-container { display: flex; justify-content: center; flex-direction: row; gap: 2rem; padding:1rem; border: 1px black; }

.fa { border-radius: 50%; }

.fa-instagram { background: #125688; color: white; padding: 1rem;

}

.fa-github { background: white; color: black; padding: 1rem;

}

.fa-facebook { background: #4267B2; color: white; padding: 1rem; }

.fa-linkedin { background: #3B5998; color: white; padding: 1rem; }

/MOBILE MENU/ .mobile-menu { display: none; }

.mobile-menu { display: flex; width: 100%; /.line a szülő tehát 40px a width/ height: calc(100vh - 80px); align-items: center; justify-content: center; position: absolute; top: 80px; left: 0; background-color: black; transform: translate(-100%); transition: all 0.4s ease; z-index: 100; }

.mobile-menu-on { display: flex; /**/ transform: translate(0); }

.m-menu { display: flex; flex-direction: column; gap: 2rem; text-align: center; font-size: 1.4rem; list-style: none; }

/hamburger icon/

.hamburger { display: none; position: fixed; width: 50px; height: 50px; border: none; background-color: transparent; margin-left: -60rem; margin-top: -2rem;

/* margin-left: -4rem; margin-top: -1.5rem;*/

}

.hamburger:hover { border: 6px solid; border-color: yellow; width: 43px; /margin-left: 4px; transform: scale(1.2);/ } .hamburger:hover .line.line-1 { /display: none;/ transform: rotate(45deg) translateY(7.5px); background-color: yellow;
</code>```
```<code>}

.hamburger:hover .line.line-2 {
  display: none;

}

.hamburger:hover .line.line-3 {
  /*display: none;*/
  transform: rotate(-45deg) translateY(-7.5px);
  background-color: yellow;

}

.line {
transition: all .4s ease;
width: 40px;
height: 5px;
background-color: white;
margin-block: 5px;
border-radius: 10px;
}
</code>```
```<code>/RESPONSIVE VERSION/
@media (max-width: 1200px) {

.hamburger { display: block; }

#desktop-menu { display: none; }

}

@media (max-width: 900px) {
</code>```
```<code>footer nav ul {
flex-direction: column;

}
</code>```
```<code>footer nav ul li a { font-size: 15px; padding: 15px; } }

@media (max-width: 750px) { .footer-container { display: flex; flex-wrap: wrap; }

footer nav ul li a { font-size: 10px; padding: 15px; }

.text-container p { font-size: 10px; } }

@media (max-width: 600px) {

}
</code>```

//AND MY JS CODE

```<code>
// MOBILE MENU

const header = document.querySelector('header')
const btn = document.querySelector('.hamburger')
const menu = document.querySelector('.mobile-menu')
const line1 = document.querySelector('.line-1')
const line2 = document.querySelector('.line-2')
const line3 = document.querySelector('.line-3')
/*let navUl = docuemnt.querySelector('ul')*/

// FLOATING BUTTON
const floatingBtn = document.querySelector('.floating-btn');

window.addEventListener('scroll', ()=> {
  if (document.documentElement.scrollTop > 400) {
    floatingBtn.classList.add('show-btn')

  } else {
    floatingBtn.classList.remove('show-btn')
  }

})

floatingBtn.addEventListener('click', () => {
 document.documentElement.scrollTop = 0

})

//SCROLLING EFFECT

window.addEventListener('scroll', () => {
  if (document.documentElement.scrollTop > 100) {
    header.style.display = 'none'

  } else {
    header.style.display = 'block'
    // navUl.style.marginTop = '32px'
  }
})

btn.addEventListener('click', () => {
  menu.classList.toggle('mobile-menu-on')
  line1.classList.toggle('line-1-on')
  line2.classList.toggle('line-2-on')
  line3.classList.toggle('line-3-on')
})

//CAROUSEL

const btnLeft = document.querySelector('.btn-left');
const btnRight = document.querySelector('.btn-right');
const images = document.querySelector('.carousel-images');

let index = 0; // első kép
// képek mozgásának automatizálása (slide effect)
setInterval(()=> {

    //slide(1) vagy függvényt teesszük csak be az alsó 5 sor helyett
    if (index === 5) {
        index = 0;
    } else {
        index++
    }
    images.style.transform = `translateX(-${100*index}vw)`
}, 5000)

console.log('.carousel-images')

const slide = (direction) => {
    if (direction === 'left') {
        if (index === 0) {
            index = 5;
        } else {
            index--
        }

    } else if (direction === 'right') {
        if (index === 5) {
            index = 0;
        } else {
            index++
        }

    }
    images.style.transform = `translateX(-${100*index}vw)`

}

btnLeft.addEventListener('click', () => {
    //slide('left') vagy -1
    if (index === 0) {
        index = 5;
    } else {
        index--
    }
    images.style.transform = `translateX(-${100*index}vw)`
})
// ha az index 2 (4. elem) de az nincs, akkor ugrik vissza az első képre
btnRight.addEventListener('click', () => {
    //slide('right') 1
   if (index === 5) {
    index = 0;
} else {
    index++
}
images.style.transform = `translateX(-${100*index}vw)`
})

document.querySelector('#contact-form').addEventListener('submit', (e) => {
  e.preventDefault();
  e.target.elements.name.value = '';
  e.target.elements.email.value = '';
  e.target.elements.message.value = '';
});
</code>```

Well, originally the hamicon was placed on the right side of the header. Since I have changed it, this kind of problem has arisen somewhy. I am still a beginner, but it is not the first time I am doing this, but still, I was unable to detect the source of the problem.

If somebody could give me some hints I would appreciate it!

Thank you very much in advance!

Body:
So, I am currently building a website with HTML, CSS, and VanillaJS and the hamburger icon for the mobile menu does not work, because although I set it to a fixed position, when I am checking the responsivity of the screen on different device screen widths by decreasing the width itself the icon slips away and it just moves towards the left side of the page.

Is there any way to prevent this from happening?

//PICTURES
First, the hamicon can be seen
But as I start decreasing the width of the screen it disappears

//HERE IS MY HTML CODE

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <link rel="stylesheet" href="gallery.css">
    <title>Eckert Művek Galéria</title>

Főoldal

Rólunk

Szolgáltatások

Miért mi?

Galéria

Kapcsolatok

                <button class="hamburger" aria-label="hamburger button">

                </button>

Főoldal

Rólunk

Szolgáltatások

Miért mi?

Galéria

Kapcsolat

Főoldal

Rólunk

Szolgáltatások

Miért mi?

Galéria

Kapcsolatok

Ttitle-1

Lorem ipsum dolor sit amet consectetur adipisicing elit.
                     Dicta modi laborum quibusdam quis natus debitis qui dolor
                     voluptatibus ab sit, cum saepe enim unde doloribus veniam
                     numquam perspiciatis optio impedit.

Ttitle-1

Lorem ipsum dolor sit amet consectetur adipisicing elit.
                     Dicta modi laborum quibusdam quis natus debitis qui dolor
                     voluptatibus ab sit, cum saepe enim unde doloribus veniam
                     numquam perspiciatis optio impedit.

© Eckert Művek Kft. Minden jog fenntartva.

//AND HERE IS MY CSS CODE

/CSS RESET/

*, *::after, *::before { box-sizing: border-box; margin: 0; padding: 0; }

:root { --font-size: 18px; --bg-color-flt-btn: yellow; }

body { width: 100%; height: 100%; }

.floating-btn { position: fixed; bottom: 3.5vh; right: 0; width: 50px; height: 50px; z-index: 100; background-color: var(--bg-color-flt-btn); border-radius: 50%; padding: 10px; box-shadow: 0 0 5px hsla(0, 0%, 0%, hsla(0,0%,0%,0.5)); cursor: pointer; margin-right: 1rem; border: 1px solid #000; }

.show-btn { display: block; }

a { text-decoration: none; color: inherit; }

/HEADER STYLE/

header { width: 100%; height: 120px; background-color: black; color: white; display: flex; align-items: center; position: fixed; top: 0; left: 0; z-index: 10; }

/Srcollbar/

::-webkit-scrollbar{ width: 15px; background: #000; }

::-webkit-scrollbar-thumb { background: yellow; border-radius: 10px; border: 1px solid black; }

::-webkit-scrollbar-thumb:active { background: orangered; }

nav, .footer-container { width: min(90%, 1200px); display: flex; margin-inline: auto; position: relative;

}

nav { justify-content: space-between; /display: flex; flex-direction: flex-end; font-size: 30px;/

}

.nav-item a { color: var(--clr-nav-item-main); list-style: none; text-transform: uppercase; font-size: 20px; font-weight: bold; height: 100%; text-decoration: none; position: relative; margin: .5em .8em; padding: 10px;

}

/újonnan adtam hozzá 2023.01.12./ /nav a { position: relative; z-index: 1; justify-content: space-evenly; height: 100%; }/

nav ul { display: flex; gap: 1rem; width: 100%; justify-content: center; margin-top: 3.5rem;

/*margin-top: 2rem;*/

}

nav ul li { text-transform: uppercase; list-style: none;

}

.nav-item a::before, .nav-item a::after { content: ''; height: 14px; width: 14px; position: absolute; transition: all .35s ease; opacity: 0; }

nav a::before { content: ''; right: 0; top: 0; border-top: 3px solid #ffed4b; border-right: 3px solid #fdcd3b; transform: translate(-100%, 50%); /-100%, 50%/ }

.nav-item a:after { content: ''; left: 0; bottom: 0; border-bottom: 3px solid #fdcd3b; border-left: 3px solid #ffed4b; transform: translate(100%, -50%);  /100%, -50%/ }

.nav-item a:hover:before, .nav-item a:hover:after{ transform: translate(0,0); opacity: 1; }

nav ul li a:hover { color: yellow; }

/Logo/

.logo img { position: absolute; width: 150px; height: 90px; margin-top: -2rem; margin-left: 70rem; left: 0; top: 0; }

/CAROUSEL SSTYLE/ /ha négy képünk van akkor ez 200 vw lesz/

.carousel-container { position: relative; width: 100%; height: 100vh; overflow: hidden;

}

`

/*transform: translateX(-200vw);*/

.carousel-images { transition: all 0.8s ease; width: 600vw; /700-zal és 800-zal is működik/ display: flex; height: 100%;
}

.carousel-images img { width: 100vw; height: 100%; object-fit: cover; }

.btn-container { position: absolute; display: flex; width: 100px; justify-content: space-between; bottom: 10vh; left: calc(50% - 75px); }

.btn { width: 40px; height: 40px; border: 2px solid #000; background-color: #fff; padding: 10px; border-radius: 10px;

}

.btn:hover { cursor: pointer; }

.btn img { width: 100%; height: 100%; }

/FOOTER STYLE/

footer { width: 100%; background-color: #000; padding-block: 4rem; color: white; }

.footer-container { flex-direction: column;

}

.footer-container nav ul { flex-direction: column; }

.footer-top { width: 100%; display: grid; grid-template-columns: repeat(3, 1fr); gap: 1rem;

}

.footer-bottom { margin-top: 3rem; text-align: center;

}

/SOCIAL MEDIA ICONS/

.social-media-icons { width: 100%; display: flex; justify-content: center; align-items: center; flex-direction: row;

}

.sm-container { display: flex; justify-content: center; flex-direction: row; gap: 2rem; padding:1rem; border: 1px black; }

.fa { border-radius: 50%; }

.fa-instagram { background: #125688; color: white; padding: 1rem;

}

.fa-github { background: white; color: black; padding: 1rem;

}

.fa-facebook { background: #4267B2; color: white; padding: 1rem; }

.fa-linkedin { background: #3B5998; color: white; padding: 1rem; }

/MOBILE MENU/ .mobile-menu { display: none; }

.mobile-menu { display: flex; width: 100%; /.line a szülő tehát 40px a width/ height: calc(100vh - 80px); align-items: center; justify-content: center; position: absolute; top: 80px; left: 0; background-color: black; transform: translate(-100%); transition: all 0.4s ease; z-index: 100; }

.mobile-menu-on { display: flex; /**/ transform: translate(0); }

.m-menu { display: flex; flex-direction: column; gap: 2rem; text-align: center; font-size: 1.4rem; list-style: none; }

/hamburger icon/

.hamburger { display: none; position: fixed; width: 50px; height: 50px; border: none; background-color: transparent; margin-left: -60rem; margin-top: -2rem;

/* margin-left: -4rem; margin-top: -1.5rem;*/

}

.hamburger:hover { border: 6px solid; border-color: yellow; width: 43px; /margin-left: 4px; transform: scale(1.2);/ } .hamburger:hover .line.line-1 { /display: none;/ transform: rotate(45deg) translateY(7.5px); background-color: yellow;

}

.hamburger:hover .line.line-2 {
  display: none;

}

.hamburger:hover .line.line-3 {
  /*display: none;*/
  transform: rotate(-45deg) translateY(-7.5px);
  background-color: yellow;

}

.line {
transition: all .4s ease;
width: 40px;
height: 5px;
background-color: white;
margin-block: 5px;
border-radius: 10px;
}

/RESPONSIVE VERSION/
@media (max-width: 1200px) {

.hamburger { display: block; }

#desktop-menu { display: none; }

}

@media (max-width: 900px) {

footer nav ul {
flex-direction: column;

}

footer nav ul li a { font-size: 15px; padding: 15px; } }

@media (max-width: 750px) { .footer-container { display: flex; flex-wrap: wrap; }

footer nav ul li a { font-size: 10px; padding: 15px; }

.text-container p { font-size: 10px; } }

@media (max-width: 600px) {

}

//AND MY JS CODE

// MOBILE MENU

const header = document.querySelector('header')
const btn = document.querySelector('.hamburger')
const menu = document.querySelector('.mobile-menu')
const line1 = document.querySelector('.line-1')
const line2 = document.querySelector('.line-2')
const line3 = document.querySelector('.line-3')
/*let navUl = docuemnt.querySelector('ul')*/

// FLOATING BUTTON
const floatingBtn = document.querySelector('.floating-btn');

window.addEventListener('scroll', ()=> {
  if (document.documentElement.scrollTop > 400) {
    floatingBtn.classList.add('show-btn')

  } else {
    floatingBtn.classList.remove('show-btn')
  }

})

floatingBtn.addEventListener('click', () => {
 document.documentElement.scrollTop = 0

})

//SCROLLING EFFECT

window.addEventListener('scroll', () => {
  if (document.documentElement.scrollTop > 100) {
    header.style.display = 'none'

  } else {
    header.style.display = 'block'
    // navUl.style.marginTop = '32px'
  }
})

btn.addEventListener('click', () => {
  menu.classList.toggle('mobile-menu-on')
  line1.classList.toggle('line-1-on')
  line2.classList.toggle('line-2-on')
  line3.classList.toggle('line-3-on')
})

//CAROUSEL

const btnLeft = document.querySelector('.btn-left');
const btnRight = document.querySelector('.btn-right');
const images = document.querySelector('.carousel-images');

let index = 0; // első kép
// képek mozgásának automatizálása (slide effect)
setInterval(()=> {

    //slide(1) vagy függvényt teesszük csak be az alsó 5 sor helyett
    if (index === 5) {
        index = 0;
    } else {
        index++
    }
    images.style.transform = `translateX(-${100*index}vw)`
}, 5000)

console.log('.carousel-images')

const slide = (direction) => {
    if (direction === 'left') {
        if (index === 0) {
            index = 5;
        } else {
            index--
        }

    } else if (direction === 'right') {
        if (index === 5) {
            index = 0;
        } else {
            index++
        }

    }
    images.style.transform = `translateX(-${100*index}vw)`

}

btnLeft.addEventListener('click', () => {
    //slide('left') vagy -1
    if (index === 0) {
        index = 5;
    } else {
        index--
    }
    images.style.transform = `translateX(-${100*index}vw)`
})
// ha az index 2 (4. elem) de az nincs, akkor ugrik vissza az első képre
btnRight.addEventListener('click', () => {
    //slide('right') 1
   if (index === 5) {
    index = 0;
} else {
    index++
}
images.style.transform = `translateX(-${100*index}vw)`
})

document.querySelector('#contact-form').addEventListener('submit', (e) => {
  e.preventDefault();
  e.target.elements.name.value = '';
  e.target.elements.email.value = '';
  e.target.elements.message.value = '';
});

Well, originally the hamicon was placed on the right side of the header. Since I have changed it, this kind of problem has arisen somewhy. I am still a beginner, but it is not the first time I am doing this, but still, I was unable to detect the source of the problem.

If somebody could give me some hints I would appreciate it!

Thank you very much in advance!


问:
Java new ArrayList clone inefficient
I'm getting the value of an ArrayList inside an ArrayList containing integers from a HashMap. However, I need a new copy of this data; otherwise, I will be changing data inside of the HashMap, as it returns a reference.

To overcome this, I'm creating a new instance of the ArrayList Object for each inner ArrayList. Is there a better, more efficient way to achieve this result (potentially with a different data structure?), as it is taking a very long time to complete with a large amount of data.

```<code>// Example of how I am copying the data currently

ArrayList<ArrayList<Integer>> calcRes = memo.get(n - i);
ArrayList<ArrayList<Integer>> calc = new ArrayList<>();

for (ArrayList<Integer> item : calcRes) {
    calc.add(new ArrayList<>(item));
}
</code>```

For a bit of context of why and how I am using this, I'm solving a problem to find all the possibilities to make stairs with N blocks.
Stairs have to descend each column by at least one. For example the stairs with six blocks would return [[5, 1], [4, 2], [3, 2, 1]]. However, for larger values N, such as 200, this takes much longer so I'm trying to cache the results inside the memo. I call the function the code above is in recursively to find more solutions. However, I don't want to change the object stored in the memo. This is because I add the previous item to the start. For example, with [3, 3] (which doesn't count as a solution), I would look at the 3 on the right and call the function I'm in again, which would give me [[2, 1]]. Then I would need to add on the 3 on the left of the original to add up to 6 blocks. This is why I am creating a new instance of the ArrayList; otherwise, the memo would be changed.

Title: Java new ArrayList clone inefficient

Body:
I'm getting the value of an ArrayList inside an ArrayList containing integers from a HashMap. However, I need a new copy of this data; otherwise, I will be changing data inside of the HashMap, as it returns a reference.

To overcome this, I'm creating a new instance of the ArrayList Object for each inner ArrayList. Is there a better, more efficient way to achieve this result (potentially with a different data structure?), as it is taking a very long time to complete with a large amount of data.

// Example of how I am copying the data currently

ArrayList<ArrayList<Integer>> calcRes = memo.get(n - i);
ArrayList<ArrayList<Integer>> calc = new ArrayList<>();

for (ArrayList<Integer> item : calcRes) {
    calc.add(new ArrayList<>(item));
}

For a bit of context of why and how I am using this, I'm solving a problem to find all the possibilities to make stairs with N blocks.
Stairs have to descend each column by at least one. For example the stairs with six blocks would return [[5, 1], [4, 2], [3, 2, 1]]. However, for larger values N, such as 200, this takes much longer so I'm trying to cache the results inside the memo. I call the function the code above is in recursively to find more solutions. However, I don't want to change the object stored in the memo. This is because I add the previous item to the start. For example, with [3, 3] (which doesn't count as a solution), I would look at the 3 on the right and call the function I'm in again, which would give me [[2, 1]]. Then I would need to add on the 3 on the left of the original to add up to 6 blocks. This is why I am creating a new instance of the ArrayList; otherwise, the memo would be changed.


问:
Not geeting response of ajax call from Laravel 9 function
I am trying to get the value of product price from pricing table. For this reason I want user to select the product and in the next field of price the value of product-price will be automatically taken from pricing database table based on product_id passed via ajax from controller.

enter image description here

My route code

```<code>public function getPrices(Request $request){$price = \DB::table('pricings')//->select('product_price')->where('product_id',$request->product_id)->get();//dd($request->product_id);if (!empty($price)){return response()->json($price) ;}
</code>```
```<code>}
</code>```

Above is function in controller to fetch the value of product-price based on 'product_id'.

```<code>$(document).ready(function() {$('#productID').on('change', function () {//alert('something changed');var productId = this.value;$('#productPrice').html('');//alert(productId);$.ajax({type: 'get',url: '{{ route("getPrices") }}',data : {product_id:productId},
</code>```
```<code>        success: function (response) {
            //$('#productPrice').val(res);
            alert(response);
            },
        dataType : "text",
            error:function (response){
            alert('Error'+response);
            }
    });
    //alert(productId);
});
</code>```
```<code>} );
</code>```

my ajax code to set the value of price after selecting product.

```<code><th scope="row">1</th><td class="col-sm-3"><div class="form-group row"><div class="col-sm-12"><select class="form-select" name="product_id" id="productID" aria-label="Default select example"><option value="" disabled>Select Product</option>@foreach($product as $products)<option data-tokens="{{ $products->product_name }}" value="{{ $products->id }}" >{{ $products->product_name}} | {{ $products->product_code }} | {{ $products->product_size }} </option>@endforeach</select></div></div></td><td class="col-sm-3"><input type="text" name="price" id="productPrice" class="form-control" placeholder="price" disabled/></td>
</code>```

My select and text fields on which I am performing this operation.

enter image description here

enter image description here

As I am not getting any value in response when I try to print it on alert.

I just want to have a response from laravel function. If anyone can highlight what is wrong. That would be really helpful.

Body:
I am trying to get the value of product price from pricing table. For this reason I want user to select the product and in the next field of price the value of product-price will be automatically taken from pricing database table based on product_id passed via ajax from controller.

enter image description here

My route code

public function getPrices(Request $request){$price = \DB::table('pricings')//->select('product_price')->where('product_id',$request->product_id)->get();//dd($request->product_id);if (!empty($price)){return response()->json($price) ;}

}

Above is function in controller to fetch the value of product-price based on 'product_id'.

$(document).ready(function() {$('#productID').on('change', function () {//alert('something changed');var productId = this.value;$('#productPrice').html('');//alert(productId);$.ajax({type: 'get',url: '{{ route("getPrices") }}',data : {product_id:productId},

        success: function (response) {
            //$('#productPrice').val(res);
            alert(response);
            },
        dataType : "text",
            error:function (response){
            alert('Error'+response);
            }
    });
    //alert(productId);
});

} );

my ajax code to set the value of price after selecting product.

1

<select class="form-select" name="product_id" id="productID" aria-label="Default select example"><option value="" disabled>Select Product</option>@foreach($product as $products)<option data-tokens="{{ $products->product_name }}" value="{{ $products->id }}" >{{ $products->product_name}} | {{ $products->product_code }} | {{ $products->product_size }} </option>@endforeach</select>

	<input type="text" name="price" id="productPrice" class="form-control" placeholder="price" disabled/>

My select and text fields on which I am performing this operation.

enter image description here

enter image description here

As I am not getting any value in response when I try to print it on alert.

I just want to have a response from laravel function. If anyone can highlight what is wrong. That would be really helpful.


问:
Blocking emails from outside organization domain that use specific name of person
Every month we have scammers creating gmail accounts with employee names and trying to phish data.

I have tried to create a MailFlow rule that says if the email is sent from outside the organization and has a display name or last name that matches one of our employee’s names then delete the email. This rule isn’t working currently. Is there a better way to achieve this?


问:
Where is this SignIn test with Jest, Typescript, ts-jest and @testing-library/react going wrong?
I am looking to create a test for a login page. The workflow should be as  follows:

- Enter email in textbox, click Continue button.

- Button greys out and a "Processing..." loading Spinner appears

- Enter password in textbox, click Sign in button

SignIn.tsx

```<code>import { useState} from 'react'
import { Stack, TextField, PrimaryButton, Spinner, DefaultButton, Dropdown, IDropdownOption } from '@fluentui/react';
import { useFormik } from "formik";
import * as yup from 'yup';
import { CredsI, OrganizationI, TokenI } from '../Lib/Interfaces/signin.interface';
import { JwtManager, sourceToken } from '../Classes/tokensManager';
import { RocklandCall } from '../Utils/apiUtils';
import ApiResponseMessage from '../Components/ApiResponseMessage';
import { ResponseTypeEnum } from '../Lib/Enum/responseTypeEnum';
import { signInTokenStyles, signInTextStyles } from '../componentStyling';
import { NotificationManager } from '../Classes/NotificationManager';
import { NotificationDismissEnum } from '../Lib/Enum/NotificationDismissEnum';
import { useMutation, useQuery } from 'react-query';

interface SignInProps {
    onSuccess: () => void;
};

/*
 * Login panel styling + layout JSX
 * API call using axios
 */
function SignIn(props: SignInProps) {

    //React boilerplate to keep track of errors
    const [loginWaiting, setLoginWaiting] = useState(false);
    const [organizationWaiting, setOrganizationWaiting] = useState(false);
    const [email, setEmail] = useState("");
    const [organizations, setOrganizations] = useState<OrganizationI>({names: []});
    const [selectedOrganization, setSelectedOrganization] = useState({key: 0, text: ""});
    const [messageBar, setMessageBar] = useState({
        show: false,
        type: ResponseTypeEnum.NONE,
        message: ""
    });
    const [showFirstAuthentication, setShowFirstAuthentication] = useState(true)
    const [showOrganization, setShowOrganization] = useState(false)

    const closeErrorMsg = () =>  setMessageBar({...messageBar, show: false});

    // Formik to manage email validation
    const emailValidationSchema = yup.object({
        email: yup.string().email('Enter a valid email').required('Email is required')
    });

    const emailFormik = useFormik({
        initialValues: { email: "" },
        validationSchema: emailValidationSchema,
        onSubmit: (values) => origanization(values.email)
    });

    const origanization = (email: string) => {
        setEmail(email);
        ApiOrganizations()
    }
    // Formik to manage password validation
    const loginValidationSchema = yup.object({
        password: yup.string().required('Password is required')
    });

    const loginFormik = useFormik({
        initialValues: { password: "" },
        validationSchema: loginValidationSchema,
        onSubmit: (values) => apiLogin(email, values.password)
    });

    const formikEmailError = (_: string) => emailFormik.errors.email ? emailFormik.errors.email : '';
    const formikPasswordError = (_: string) => loginFormik.errors.password ? loginFormik.errors.password: '';

    const onBackButton = () => {
        setEmail("")
        setShowFirstAuthentication(true)
    }

    const getDropdownOptions = () => organizations.names.map((o, index) => {
        return {
            key: index,
            text: o
        } as IDropdownOption});

    /*
     * Functions for the buttons
     * developer credentials:
     *      username: jp@rocklandscientific.com
     *      password: access.$1729Rop
     */

    const onSuccessLogin = (data: TokenI) => {
        let token = data.token;
        let expiry = data.tokenExpiry;
        JwtManager.setToken(token, expiry);
        if (data.message !== "") {
            NotificationManager.setMessage(data.message, ResponseTypeEnum.WARNING, NotificationDismissEnum.NONE);
        }

        //error in unlikely case of token being null (no token so can't log to api unfortunately but we need a UI message)
        if (token==null) {
            setMessageBar({
                show: true,
                type: ResponseTypeEnum.ERROR,
                message: "Login failed"
            })
        } else {
            //the login was successful, so do whatever parent component wants us to do (such as redirect to dashboard)
            props.onSuccess();
        }
        setLoginWaiting(false)
    }

    const onError = (error: any, setLoading: any) => {
        let message = error.response?.data?.message ?? "";
        setMessageBar({
            show: true,
            type: ResponseTypeEnum.ERROR,
            message: message
        })
        setLoading(false)
    }

    const getSinginToken = async(creds: CredsI) => {
        return await RocklandCall.signInReturnToken(creds)
    }
    const {mutate: apiLoginQuery} = useMutation(getSinginToken,{
        onSuccess: (data) => {
            onSuccessLogin(data)
        },
        onError: (error) => {
            onError(error, setLoginWaiting)
        }
    });

    const apiLogin = async (username: string, password: string) => {

        setLoginWaiting(true);
        let creds: CredsI = { username: username, password: password, organizationName: selectedOrganization.text, sourceToken: sourceToken};

        apiLoginQuery(creds) //mutate
    }

    const onSuccessOrganizationQuery  = (data: OrganizationI) => {

        setOrganizations(data);
        if (data.names.length > 0) setSelectedOrganization({key: 0, text: data.names[0]});
        if (data.names.length > 1) setShowOrganization(true)
        setOrganizationWaiting(false);
        setShowFirstAuthentication(false)
    }

    const organizationQuery = async(email: string) => {
        return await RocklandCall.organizations(email)
    }

    const {refetch: organizationAPI, status} = useQuery(['organinzation', email], () => organizationQuery(email), {
        onSuccess: (data) => {
            onSuccessOrganizationQuery (data)
        },
        onError: (error) => {
            onError(error, setOrganizationWaiting)
        },
        refetchOnWindowFocus: false,
        cacheTime: 0,
        enabled: false
    })

    const ApiOrganizations =  () => {
        setOrganizationWaiting(true);
        organizationAPI() //refetch alias name
    }

    return (
        <div className="Sign-in-panel">
            <Stack tokens={signInTokenStyles()} style={{marginLeft: 10, marginRight: 10}} >
                <Stack.Item align="start" >
                    <h2>Welcome to AIRDROP</h2>
                </Stack.Item>
                {messageBar.show &&
                <ApiResponseMessage
                message={messageBar.message}
                type={ResponseTypeEnum.ERROR}
                close={closeErrorMsg} />}

                {showFirstAuthentication && // The following is the first step of authentication
                    <form onSubmit={emailFormik.handleSubmit}>
                        <Stack tokens={signInTokenStyles()}>
                            <Stack.Item align="start" >
                                <TextField label="Email" id="email" name="email"
                                    disabled={email !== ""}
                                    required styles={signInTextStyles()} onGetErrorMessage={formikEmailError}
                                    value={emailFormik.values.email} onChange={emailFormik.handleChange} validateOnFocusOut
                                />
                            </Stack.Item>
                            <Stack.Item align="start" >
                                <Stack className="Submit-button" horizontal tokens={signInTokenStyles()}>
                                    <PrimaryButton type="submit" disabled={organizationWaiting} >Continue</PrimaryButton>
                                    { organizationWaiting && <Spinner label="Processing..." ariaLive="assertive" labelPosition="left"/> }
                                </Stack>
                            </Stack.Item>
                        </Stack>
                    </form>
                ||
                <form onSubmit={loginFormik.handleSubmit}>
                    {showOrganization && <Dropdown
                        placeholder="Select organization"
                        label="Organization"
                        options={getDropdownOptions()}
                        selectedKey = {selectedOrganization.key}
                        id="type"
                        onChange={(event, option) => setSelectedOrganization({key: option?.key as number ?? 0, text: option?.text ?? ""})}/>
                    }
                    <Stack.Item align="start" >
                        <TextField label="Password" id="password" name="password"
                            type="password" required styles={signInTextStyles()} onGetErrorMessage={formikPasswordError}
                            value={loginFormik.values.password} onChange={loginFormik.handleChange} validateOnFocusOut
                        />
                    </Stack.Item>
                    <Stack horizontal tokens={signInTokenStyles} >
                        <Stack.Item className="Submit-button" >
                            <Stack horizontal gap={10}>
                                <DefaultButton onClick={onBackButton} disabled={loginWaiting} >Back</DefaultButton>
                                <PrimaryButton type="submit" disabled={loginWaiting} >Sign in</PrimaryButton>
                                { loginWaiting && <Spinner label="Signing you in..." ariaLive="assertive" labelPosition="left"/> }
                            </Stack>
                        </Stack.Item>
                    </Stack>
                </form>
            }
            </Stack>
        </div>
    );
}
export default SignIn;
</code>```

SignIn.test.tsx

```<code>import { QueryClient, QueryClientProvider } from 'react-query';
import SignIn from '../SignIn';
import { setupServer } from 'msw/node'
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import "@testing-library/jest-dom"
import { rest } from 'msw';

// set up server to mock API login requests
let server = setupServer();
beforeAll(() => server.listen())
afterEach(() => server.resetHandlers())
afterAll(() => server.close())

const queryClient = new QueryClient();
const onSubmit = jest.fn();

beforeEach(() => {
    onSubmit.mockClear();
    render(
        <QueryClientProvider client={queryClient}>
            <SignIn onSuccess={onSubmit} />
        </QueryClientProvider>
    );
})

describe('SignIn Domain', () => {
    test('Successful login', async () => {

        server.use(
            rest.post('https://localhost:5001/api/Auth/Login', (_, res, ctx) => {
                return res(ctx.json({ token: 'myToken' }));
            }),
        );

        await waitFor(() => {
            fireEvent.change(getEmail(), {
                target: {
                    value: ""
                }
            })
        });

        // click the button
        await waitFor(() => {
            fireEvent.click(screen.getByText('Continue'));
        });

        const processing = await screen.getByText('Processing...');

        // await waitFor(() => {
        //     expect(onSubmit).toHaveBeenCalledTimes(1);
        // });
        // await waitFor(() => {
        //     expect(processing).not.toBeIntheDocument()
        // })

    //    const password = await screen.getByRole('textbox', {
    //     name: /password/i
    //    });

        await waitFor(() => {
            fireEvent.change(getPassword(), {
                target: {
                    value: "dummyPassword"
                }
            })
        })

        // click the sign in button
        await waitFor(() => {
            fireEvent.click(screen.getByText('Sign in'));
        });

        await waitFor(() => expect(onSubmit).toHaveBeenCalled());
    })
})

function getEmail() {
    return screen.getByRole('textbox', {
        name: /email/i
    })
}

function getPassword() {
    return screen.getByRole('textbox', {
        name: /password/i
    });
}
</code>```

1st attempt:

In a synchronous manner, I tried to:

- get the email and fill it in (successfully)

- click the continue button (successfully)

- get the password and fill it in (unsuccessful)

error:

TestingLibraryElementError: Unable to find an accessible element with the role "textbox" and name `/password/i`

2nd attempt:

Since the re-render isn't instant, I decided to confirm that the "Processing..." Spinner appears, and then wait until it disappears. (unsuccessful)

```<code>const processing = await screen.getByText('Processing...');
[..]
await waitFor(() => {
    expect(processing).not.toBeIntheDocument()
})
</code>```

error:

TypeError: The "options.agent" property must be one of Agent-like Object, undefined, or false. Received an instance of Object

TypeError: expect(...).not.toBeIntheDocument is not a function

In case this is needed:

tsconfig.json

```<code>{
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx",
    "types": ["node", "jest", "@testing-library/jest-dom"]
  },
  "include": [
    "src"
  ]
}
</code>```

package.json

```<code>{
  "name": "airdrop-app",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@fluentui/react": "^8.104.5",
    "@fluentui/react-icons": "^1.1.145",
    "@fluentui/react-icons-mdl2": "^1.3.29",
    "@testing-library/jest-dom": "^5.16.5",
    "@testing-library/react": "^11.2.7",
    "@testing-library/user-event": "^12.8.3",
    "@types/d3": "^6.7.5",
    "@types/file-saver": "^2.0.5",
    "@types/filesaver": "^0.0.30",
    "@types/geojson": "^7946.0.10",
    "@types/mapbox-gl": "^2.7.10",
    "@types/node": "^12.20.55",
    "@types/react": "^17.0.52",
    "@types/react-dom": "^17.0.18",
    "@types/react-motion": "0.0.29",
    "@types/react-router-dom": "^5.3.3",
    "axios": "^0.21.4",
    "d3": "^6.7.0",
    "d3-hexbin": "^0.2.2",
    "d3-svg-legend": "^2.25.6",
    "enzyme": "^3.11.0",
    "file-saver": "^2.0.5",
    "fluent": "^0.13.0",
    "formik": "^2.2.9",
    "mapbox-gl": "^2.12.0",
    "msw": "^0.28.2",
    "react": "^17.0.2",
    "react-cookie": "^4.1.1",
    "react-dom": "^17.0.2",
    "react-map-gl": "^6.1.21",
    "react-motion": "^0.5.2",
    "react-query": "^3.39.2",
    "react-rnd": "^10.4.1",
    "react-router-dom": "^5.3.4",
    "react-scripts": "5.0.1",
    "sprintf-js": "^1.1.2",
    "typescript": "^4.9.4",
    "web-vitals": "^1.1.2",
    "yup": "^0.32.11"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "jest",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "@types/d3-hexbin": "^0.2.3",
    "@types/enzyme": "^3.10.12",
    "@types/enzyme-adapter-react-16": "^1.0.6",
    "@types/sprintf-js": "^1.1.2",
    "enzyme-adapter-react-15": "^1.4.4",
    "enzyme-adapter-react-16": "^1.15.7",
    "jest": "^29.3.1",
    "jest-environment-jsdom": "^29.3.1",
    "ts-jest": "^29.0.3"
  }
}
</code>```

jest.config.js

```<code>/** @type {import('ts-jest').JestConfigWithTsJest} */

module.exports = {
  verbose: false,
  preset: 'ts-jest',
  testEnvironment: 'jsdom',
  testEnvironmentOptions: {
    url: 'http://localhost/3000'
  }
};
</code>```

Looking forward to discussing any possible solutions.

Thank you.

Body:
I am looking to create a test for a login page. The workflow should be as  follows:

- Enter email in textbox, click Continue button.

- Button greys out and a "Processing..." loading Spinner appears

- Enter password in textbox, click Sign in button

SignIn.tsx

import { useState} from 'react'
import { Stack, TextField, PrimaryButton, Spinner, DefaultButton, Dropdown, IDropdownOption } from '@fluentui/react';
import { useFormik } from "formik";
import * as yup from 'yup';
import { CredsI, OrganizationI, TokenI } from '../Lib/Interfaces/signin.interface';
import { JwtManager, sourceToken } from '../Classes/tokensManager';
import { RocklandCall } from '../Utils/apiUtils';
import ApiResponseMessage from '../Components/ApiResponseMessage';
import { ResponseTypeEnum } from '../Lib/Enum/responseTypeEnum';
import { signInTokenStyles, signInTextStyles } from '../componentStyling';
import { NotificationManager } from '../Classes/NotificationManager';
import { NotificationDismissEnum } from '../Lib/Enum/NotificationDismissEnum';
import { useMutation, useQuery } from 'react-query';

interface SignInProps {
    onSuccess: () => void;
};

/*
 * Login panel styling + layout JSX
 * API call using axios
 */
function SignIn(props: SignInProps) {

    //React boilerplate to keep track of errors
    const [loginWaiting, setLoginWaiting] = useState(false);
    const [organizationWaiting, setOrganizationWaiting] = useState(false);
    const [email, setEmail] = useState("");
    const [organizations, setOrganizations] = useState<OrganizationI>({names: []});
    const [selectedOrganization, setSelectedOrganization] = useState({key: 0, text: ""});
    const [messageBar, setMessageBar] = useState({
        show: false,
        type: ResponseTypeEnum.NONE,
        message: ""
    });
    const [showFirstAuthentication, setShowFirstAuthentication] = useState(true)
    const [showOrganization, setShowOrganization] = useState(false)

    const closeErrorMsg = () =>  setMessageBar({...messageBar, show: false});

    // Formik to manage email validation
    const emailValidationSchema = yup.object({
        email: yup.string().email('Enter a valid email').required('Email is required')
    });

    const emailFormik = useFormik({
        initialValues: { email: "" },
        validationSchema: emailValidationSchema,
        onSubmit: (values) => origanization(values.email)
    });

    const origanization = (email: string) => {
        setEmail(email);
        ApiOrganizations()
    }
    // Formik to manage password validation
    const loginValidationSchema = yup.object({
        password: yup.string().required('Password is required')
    });

    const loginFormik = useFormik({
        initialValues: { password: "" },
        validationSchema: loginValidationSchema,
        onSubmit: (values) => apiLogin(email, values.password)
    });

    const formikEmailError = (_: string) => emailFormik.errors.email ? emailFormik.errors.email : '';
    const formikPasswordError = (_: string) => loginFormik.errors.password ? loginFormik.errors.password: '';

    const onBackButton = () => {
        setEmail("")
        setShowFirstAuthentication(true)
    }

    const getDropdownOptions = () => organizations.names.map((o, index) => {
        return {
            key: index,
            text: o
        } as IDropdownOption});

    /*
     * Functions for the buttons
     * developer credentials:
     *      username: jp@rocklandscientific.com
     *      password: access.$1729Rop
     */

    const onSuccessLogin = (data: TokenI) => {
        let token = data.token;
        let expiry = data.tokenExpiry;
        JwtManager.setToken(token, expiry);
        if (data.message !== "") {
            NotificationManager.setMessage(data.message, ResponseTypeEnum.WARNING, NotificationDismissEnum.NONE);
        }

        //error in unlikely case of token being null (no token so can't log to api unfortunately but we need a UI message)
        if (token==null) {
            setMessageBar({
                show: true,
                type: ResponseTypeEnum.ERROR,
                message: "Login failed"
            })
        } else {
            //the login was successful, so do whatever parent component wants us to do (such as redirect to dashboard)
            props.onSuccess();
        }
        setLoginWaiting(false)
    }

    const onError = (error: any, setLoading: any) => {
        let message = error.response?.data?.message ?? "";
        setMessageBar({
            show: true,
            type: ResponseTypeEnum.ERROR,
            message: message
        })
        setLoading(false)
    }

    const getSinginToken = async(creds: CredsI) => {
        return await RocklandCall.signInReturnToken(creds)
    }
    const {mutate: apiLoginQuery} = useMutation(getSinginToken,{
        onSuccess: (data) => {
            onSuccessLogin(data)
        },
        onError: (error) => {
            onError(error, setLoginWaiting)
        }
    });

    const apiLogin = async (username: string, password: string) => {

        setLoginWaiting(true);
        let creds: CredsI = { username: username, password: password, organizationName: selectedOrganization.text, sourceToken: sourceToken};

        apiLoginQuery(creds) //mutate
    }

    const onSuccessOrganizationQuery  = (data: OrganizationI) => {

        setOrganizations(data);
        if (data.names.length > 0) setSelectedOrganization({key: 0, text: data.names[0]});
        if (data.names.length > 1) setShowOrganization(true)
        setOrganizationWaiting(false);
        setShowFirstAuthentication(false)
    }

    const organizationQuery = async(email: string) => {
        return await RocklandCall.organizations(email)
    }

    const {refetch: organizationAPI, status} = useQuery(['organinzation', email], () => organizationQuery(email), {
        onSuccess: (data) => {
            onSuccessOrganizationQuery (data)
        },
        onError: (error) => {
            onError(error, setOrganizationWaiting)
        },
        refetchOnWindowFocus: false,
        cacheTime: 0,
        enabled: false
    })

    const ApiOrganizations =  () => {
        setOrganizationWaiting(true);
        organizationAPI() //refetch alias name
    }

    return (

            <Stack tokens={signInTokenStyles()} style={{marginLeft: 10, marginRight: 10}} >
                <Stack.Item align="start" >

Welcome to AIRDROP

                </Stack.Item>
                {messageBar.show &&
                <ApiResponseMessage
                message={messageBar.message}
                type={ResponseTypeEnum.ERROR}
                close={closeErrorMsg} />}

                {showFirstAuthentication && // The following is the first step of authentication
                    <form onSubmit={emailFormik.handleSubmit}>
                        <Stack tokens={signInTokenStyles()}>
                            <Stack.Item align="start" >
                                <TextField label="Email" id="email" name="email"
                                    disabled={email !== ""}
                                    required styles={signInTextStyles()} onGetErrorMessage={formikEmailError}
                                    value={emailFormik.values.email} onChange={emailFormik.handleChange} validateOnFocusOut
                                />
                            </Stack.Item>
                            <Stack.Item align="start" >
                                <Stack className="Submit-button" horizontal tokens={signInTokenStyles()}>
                                    <PrimaryButton type="submit" disabled={organizationWaiting} >Continue</PrimaryButton>
                                    { organizationWaiting && <Spinner label="Processing..." ariaLive="assertive" labelPosition="left"/> }
                                </Stack>
                            </Stack.Item>
                        </Stack>
                    </form>
                ||
                <form onSubmit={loginFormik.handleSubmit}>
                    {showOrganization && <Dropdown
                        placeholder="Select organization"
                        label="Organization"
                        options={getDropdownOptions()}
                        selectedKey = {selectedOrganization.key}
                        id="type"
                        onChange={(event, option) => setSelectedOrganization({key: option?.key as number ?? 0, text: option?.text ?? ""})}/>
                    }
                    <Stack.Item align="start" >
                        <TextField label="Password" id="password" name="password"
                            type="password" required styles={signInTextStyles()} onGetErrorMessage={formikPasswordError}
                            value={loginFormik.values.password} onChange={loginFormik.handleChange} validateOnFocusOut
                        />
                    </Stack.Item>
                    <Stack horizontal tokens={signInTokenStyles} >
                        <Stack.Item className="Submit-button" >
                            <Stack horizontal gap={10}>
                                <DefaultButton onClick={onBackButton} disabled={loginWaiting} >Back</DefaultButton>
                                <PrimaryButton type="submit" disabled={loginWaiting} >Sign in</PrimaryButton>
                                { loginWaiting && <Spinner label="Signing you in..." ariaLive="assertive" labelPosition="left"/> }
                            </Stack>
                        </Stack.Item>
                    </Stack>
                </form>
            }
            </Stack>

    );
}
export default SignIn;

SignIn.test.tsx

import { QueryClient, QueryClientProvider } from 'react-query';
import SignIn from '../SignIn';
import { setupServer } from 'msw/node'
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import "@testing-library/jest-dom"
import { rest } from 'msw';

// set up server to mock API login requests
let server = setupServer();
beforeAll(() => server.listen())
afterEach(() => server.resetHandlers())
afterAll(() => server.close())

const queryClient = new QueryClient();
const onSubmit = jest.fn();

beforeEach(() => {
    onSubmit.mockClear();
    render(
        <QueryClientProvider client={queryClient}>
            <SignIn onSuccess={onSubmit} />
        </QueryClientProvider>
    );
})

describe('SignIn Domain', () => {
    test('Successful login', async () => {

        server.use(
            rest.post('https://localhost:5001/api/Auth/Login', (_, res, ctx) => {
                return res(ctx.json({ token: 'myToken' }));
            }),
        );

        await waitFor(() => {
            fireEvent.change(getEmail(), {
                target: {
                    value: ""
                }
            })
        });

        // click the button
        await waitFor(() => {
            fireEvent.click(screen.getByText('Continue'));
        });

        const processing = await screen.getByText('Processing...');

        // await waitFor(() => {
        //     expect(onSubmit).toHaveBeenCalledTimes(1);
        // });
        // await waitFor(() => {
        //     expect(processing).not.toBeIntheDocument()
        // })

    //    const password = await screen.getByRole('textbox', {
    //     name: /password/i
    //    });

        await waitFor(() => {
            fireEvent.change(getPassword(), {
                target: {
                    value: "dummyPassword"
                }
            })
        })

        // click the sign in button
        await waitFor(() => {
            fireEvent.click(screen.getByText('Sign in'));
        });

        await waitFor(() => expect(onSubmit).toHaveBeenCalled());
    })
})

function getEmail() {
    return screen.getByRole('textbox', {
        name: /email/i
    })
}

function getPassword() {
    return screen.getByRole('textbox', {
        name: /password/i
    });
}

1st attempt:

In a synchronous manner, I tried to:

- get the email and fill it in (successfully)

- click the continue button (successfully)

- get the password and fill it in (unsuccessful)

error:

TestingLibraryElementError: Unable to find an accessible element with the role "textbox" and name `/password/i`

2nd attempt:

Since the re-render isn't instant, I decided to confirm that the "Processing..." Spinner appears, and then wait until it disappears. (unsuccessful)

const processing = await screen.getByText('Processing...');
[..]
await waitFor(() => {
    expect(processing).not.toBeIntheDocument()
})

error:

TypeError: The "options.agent" property must be one of Agent-like Object, undefined, or false. Received an instance of Object

TypeError: expect(...).not.toBeIntheDocument is not a function

In case this is needed:

tsconfig.json

{
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx",
    "types": ["node", "jest", "@testing-library/jest-dom"]
  },
  "include": [
    "src"
  ]
}

package.json

{
  "name": "airdrop-app",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@fluentui/react": "^8.104.5",
    "@fluentui/react-icons": "^1.1.145",
    "@fluentui/react-icons-mdl2": "^1.3.29",
    "@testing-library/jest-dom": "^5.16.5",
    "@testing-library/react": "^11.2.7",
    "@testing-library/user-event": "^12.8.3",
    "@types/d3": "^6.7.5",
    "@types/file-saver": "^2.0.5",
    "@types/filesaver": "^0.0.30",
    "@types/geojson": "^7946.0.10",
    "@types/mapbox-gl": "^2.7.10",
    "@types/node": "^12.20.55",
    "@types/react": "^17.0.52",
    "@types/react-dom": "^17.0.18",
    "@types/react-motion": "0.0.29",
    "@types/react-router-dom": "^5.3.3",
    "axios": "^0.21.4",
    "d3": "^6.7.0",
    "d3-hexbin": "^0.2.2",
    "d3-svg-legend": "^2.25.6",
    "enzyme": "^3.11.0",
    "file-saver": "^2.0.5",
    "fluent": "^0.13.0",
    "formik": "^2.2.9",
    "mapbox-gl": "^2.12.0",
    "msw": "^0.28.2",
    "react": "^17.0.2",
    "react-cookie": "^4.1.1",
    "react-dom": "^17.0.2",
    "react-map-gl": "^6.1.21",
    "react-motion": "^0.5.2",
    "react-query": "^3.39.2",
    "react-rnd": "^10.4.1",
    "react-router-dom": "^5.3.4",
    "react-scripts": "5.0.1",
    "sprintf-js": "^1.1.2",
    "typescript": "^4.9.4",
    "web-vitals": "^1.1.2",
    "yup": "^0.32.11"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "jest",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "@types/d3-hexbin": "^0.2.3",
    "@types/enzyme": "^3.10.12",
    "@types/enzyme-adapter-react-16": "^1.0.6",
    "@types/sprintf-js": "^1.1.2",
    "enzyme-adapter-react-15": "^1.4.4",
    "enzyme-adapter-react-16": "^1.15.7",
    "jest": "^29.3.1",
    "jest-environment-jsdom": "^29.3.1",
    "ts-jest": "^29.0.3"
  }
}

jest.config.js

/** @type {import('ts-jest').JestConfigWithTsJest} */

module.exports = {
  verbose: false,
  preset: 'ts-jest',
  testEnvironment: 'jsdom',
  testEnvironmentOptions: {
    url: 'http://localhost/3000'
  }
};

Looking forward to discussing any possible solutions.

Thank you.


问:
Split and copy Excel table according to PowerPoint slide height
currently I am using a predefined solution where a large table that is too big for a slide is split into 20 rows, the header is deleted and then all 20 rows as well as the header are copied on a new PowerPoint slide until the entire table is split (this is done in Excel).

The important part of the code looks like this:

```<code>Set wb = Workbooks("Planning.xlsm")
Set ws = wb.Sheets("LastYear")
Set wss = wb.Worksheets.Add
Set PowerPointApp = GetObject(class:="PowerPoint.Application")
Set myPresentation = PowerPointApp.ActivePresentation

Do While i <= LastRow
    j = Application.Min(i + 20, LastRow)
    Union(rngH, ws.Range("A" & i, ws.Range("M" & j))).Copy
    wss.Range("A1").PasteSpecial Paste:=xlPasteColumnWidths
    wss.Range("A1").PasteSpecial Paste:=xlPasteValues
    wss.Range("A1").PasteSpecial Paste:=xlPasteAllUsingSourceTheme

    Set sld = myPresentation.Slides.Add(myPresentation.Slides.Count + 1, ppLayoutBlank)
    wss.Range("A1:M" & j - i + 2).Copy

    sld.Shapes.PasteSpecial DataType:=ppPasteHTML, Link:=msoFalse

    'Here title of the table & format is added
    Set Header = sld.Shapes.AddShape(msoShapeRectangle, 0, 0, 960, 40)
    With Header
        .Fill.ForeColor.RGB = RGB(0, 32, 91)
        .Line.Visible = False
    End With
Loop
</code>```

Afterwards I activate a macro in PowerPoint, which formats the table to the correct size, so that the entire space can be used except for the title.

The problem is that the rows can have different heights and therefore sometimes a table is too short or too long, so that a manual rework has to be done. Is it possible to split and copy the table based on the PowerPoint slide height and the summation of the row heights (something like, add rows until row height sum equals slide sum)? I have already tried a few things myself but I am not getting anywhere.

Thanks a lot for your help/hints!

Body:
currently I am using a predefined solution where a large table that is too big for a slide is split into 20 rows, the header is deleted and then all 20 rows as well as the header are copied on a new PowerPoint slide until the entire table is split (this is done in Excel).

The important part of the code looks like this:

Set wb = Workbooks("Planning.xlsm")
Set ws = wb.Sheets("LastYear")
Set wss = wb.Worksheets.Add
Set PowerPointApp = GetObject(class:="PowerPoint.Application")
Set myPresentation = PowerPointApp.ActivePresentation

Do While i <= LastRow
    j = Application.Min(i + 20, LastRow)
    Union(rngH, ws.Range("A" & i, ws.Range("M" & j))).Copy
    wss.Range("A1").PasteSpecial Paste:=xlPasteColumnWidths
    wss.Range("A1").PasteSpecial Paste:=xlPasteValues
    wss.Range("A1").PasteSpecial Paste:=xlPasteAllUsingSourceTheme

    Set sld = myPresentation.Slides.Add(myPresentation.Slides.Count + 1, ppLayoutBlank)
    wss.Range("A1:M" & j - i + 2).Copy

    sld.Shapes.PasteSpecial DataType:=ppPasteHTML, Link:=msoFalse

    'Here title of the table & format is added
    Set Header = sld.Shapes.AddShape(msoShapeRectangle, 0, 0, 960, 40)
    With Header
        .Fill.ForeColor.RGB = RGB(0, 32, 91)
        .Line.Visible = False
    End With
Loop

Afterwards I activate a macro in PowerPoint, which formats the table to the correct size, so that the entire space can be used except for the title.

The problem is that the rows can have different heights and therefore sometimes a table is too short or too long, so that a manual rework has to be done. Is it possible to split and copy the table based on the PowerPoint slide height and the summation of the row heights (something like, add rows until row height sum equals slide sum)? I have already tried a few things myself but I am not getting anywhere.

Thanks a lot for your help/hints!


问:
jsPDF-autotables table has head in the end of the page and the full content is at the another page
so as you saw at the title, basically im making a pdf but there sometimes that the table has no space at the page and it automatically creates another page with the table.
But it leaves the head of the table at the end of the page, here's a screenshot:

Here is the code of the table:

```<code>  autoTable(doc, {

  startY: tableHeight + 5,
  theme: 'plain',
  styles: {
    lineColor: [0, 0, 0],
    lineWidth: 0.25,
  },
  head: [['Redespacho', 'Tipo frete', 'Valor frete']],
  body: [
    [
      values.redispatch! || 'N/A',
      values.redispatchShippingType! || 'N/A',
      values.redispatchShippingPrice! || 'N/A',
    ],
  ],
  didDrawPage: (data: any) => {
    tableHeight = (data as any).cursor.y
  },
  willDrawCell: function (data) {
    if (data.section === 'head' && data.pageCount !== data.pageNumber) {
      return false
    }
  },
})
</code>```

If you guys could help, I'll be so thankfull.

I've tried JsPDF repeating first row on every new page, but erased all the heads

Body:
so as you saw at the title, basically im making a pdf but there sometimes that the table has no space at the page and it automatically creates another page with the table.
But it leaves the head of the table at the end of the page, here's a screenshot:

Here is the code of the table:

  autoTable(doc, {

  startY: tableHeight + 5,
  theme: 'plain',
  styles: {
    lineColor: [0, 0, 0],
    lineWidth: 0.25,
  },
  head: [['Redespacho', 'Tipo frete', 'Valor frete']],
  body: [
    [
      values.redispatch! || 'N/A',
      values.redispatchShippingType! || 'N/A',
      values.redispatchShippingPrice! || 'N/A',
    ],
  ],
  didDrawPage: (data: any) => {
    tableHeight = (data as any).cursor.y
  },
  willDrawCell: function (data) {
    if (data.section === 'head' && data.pageCount !== data.pageNumber) {
      return false
    }
  },
})

If you guys could help, I'll be so thankfull.

I've tried JsPDF repeating first row on every new page, but erased all the heads


问:
InfluxDB Cloud: Threshold Check based on a String value
I might be a bit newbie with InfluxDB Cloud but I cant find (or look correctly) a hint for my issue.

My dataset is made of one field "status" which can be "connected" or "disconnected" (value as a string).

I want to set a check on this field:

OK if status="connected"

WARN if status="disconnected" for less than 1 minute

CRIT if status="disconnected" for pore than 1 minute

Note that I know how to set a check for a numeric value, and that I want to avoid to change my data source (not in my hands to have status=0 or1)


问:
Unable to create an RSS Feed with out it being base64 encoded by my API Gateway
I wrote an RSS feed in Python using Django, using these instructions https://docs.djangoproject.com/en/4.1/ref/contrib/syndication/

It worked great locally. I can see my RSS feed with no issues on localhost:8000/latest/feeds

But when I deploy it the output looks like this:
PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz4KPHJzcyB2ZXJzaW9uPSIyLjAiIHhtbG5zOmF0b209Imh0dHA6Ly93d3cudzMub3JnLzIwMDUvQXRvbSI+PGNoYW5uZWw+PHRpdGxlPkZlZGVyYWwgUmVnaXN0ZXIgZG9jdW1lbnRzIFJTUyBGZWVkPC90aXRsZT48bGluaz5odHRwczovL3I3dmYzOXY2bDQuZXhlY3V0ZS1hcGkudXMtZWFzdC0xLmFtYXpvbmF3cy5jb20vbGF0ZXN0L2ZlZWQ8L2xpbms+PGRlc2NyaXB0aW9uPkRpc3BsYXlzIHRoZSBsYXRlc3QgZmVkZXJhbCByZWdpc3RlciBkb2N1bWVudHM8L2Rlc2NyaXB0aW9uPjxhdG9tOmxpbmsgaHJlZj0iaHR0cHM6Ly9yN3ZmMzl2Nmw0LmV4ZWN1dGUtYXBpLnVzLWVhc3QtMS5hbWF6b25hd3MuY29tL2RldjY0Ny9sYXRlc3QvZmVlZC8iIHJlbD0ic2VsZiI+PC9hdG9tOmxpbms+PGxhbmd1YWdlPmVuLXVzPC9sYW5ndWFnZT48bGFzdEJ1aWxkRGF...

Its base64 encoded but I do not understand why. Looking at the content type through the dev tool network tab it says that its
content-type: application/rss+xml; charset=utf-8

Some reason the apigateway on the server thinks its binary and encodes it? I tried everything I could and can not get this issue resolved.


问:
ST_CONTAINS returns false when point inside multipolygon
I have one point in 4326 and one multipolygon in non-standart srid. I use st_contains function but it returns false. Here is my point and my multipolygon showed in qgis:
multipolygon (orange) and point (green)

Here is my postgres query:

```<code>select st_contains(geom_of_multipolygon, st_transform(geom_of_point, srid_of_multipolygon));
</code>```

My postgis version is 3.2 and it supports st_contains for multigeometry.

Body:
I have one point in 4326 and one multipolygon in non-standart srid. I use st_contains function but it returns false. Here is my point and my multipolygon showed in qgis:
multipolygon (orange) and point (green)

Here is my postgres query:

select st_contains(geom_of_multipolygon, st_transform(geom_of_point, srid_of_multipolygon));

My postgis version is 3.2 and it supports st_contains for multigeometry.


问:
nth-check: Not able to fix vulnerability introducted through rails/webpacker
There is a vulnerability related to nth-check that I am trying to fix.
https://www.cve.org/CVERecord?id=CVE-2021-3803

It is coming from @rails/webpacker. Tried removing entry optimize-css-assets-webpack-plugin@^5.0.8 from yarn.lock and running yarn install again but no luck. It still installs 5.0.8 version.

yarn upgrade adds new entry in package.json for latest version of optimize-css-assets-webpack-plugin but looking at https://www.npmjs.com/package/@rails/webpacker?activeTab=dependencies rails/webpacker is consuming latest version of optimize-css-assets-webpack-plugin so I am not sure why its not picking up latest version.