问:
"await" in Widget build FLUTTER
I've been stuck for several hours with a problem on flutter. If you can help me that would be really nice.

I need to put "await" in my Widget build(BuildContext context){} but it's impossible to put "async".
How to do ?

When i test void _myAsyncMethod()async{} :

答:
What you want to do is not optimal but you can create a method and put your await variable in there:

```<code> late final FirebaseUser _user;
  void _myAsyncMethod()async{
    _user = await auth.currentUser;
  }

  @override
  Widget build(BuildContext context) {
    _myAsyncMethod();
    return Scaffold(appBar: AppBar(), body: Container());
  }
</code>```

Title: "await" in Widget build FLUTTER

Body:
What you want to do is not optimal but you can create a method and put your await variable in there:

 late final FirebaseUser _user;
  void _myAsyncMethod()async{
    _user = await auth.currentUser;
  }

  @override
  Widget build(BuildContext context) {
    _myAsyncMethod();
    return Scaffold(appBar: AppBar(), body: Container());
  }


来源: stackexchange

问:
How to subscribe to EventKit changes in SwiftUI?
I am trying to understand how to subscribe to EventKit calendar event updates within SwiftIU.

The EventKit documentation shows how to do this in Swift (https://developer.apple.com/documentation/eventkit/updating_with_notifications).

It says to subscribe to calendar update notifications by writing:

NotificationCenter.default.addObserver(self, selector: Selector("storeChanged:"), name: .EKEventStoreChanged, object: eventStore)

It also appears that the storeChanged function needs do be tagged with @objc based on xcode warnings. However, when I do the below within a SwiftUI app, I get the error @objc can only be used with members of classes, @objc protocols, and concrete extensions of classes

```<code>import SwiftUI
import EventKit

struct ContentView: View {
    let eventStore = EKEventStore()

    var body: some View {
        Text("Hello, world!")
            .padding()
            .onAppear{
                NotificationCenter.default.addObserver(self, selector: Selector("observeEvents"), name: .EKEventStoreChanged, object: eventStore)
            }
    }

    @objc func observeEvents() {
        print("called with updated events")
    }
}
</code>```

Am I doing something wrong? What would be the way to subscribe to calendar event updates within the EventStore in SwiftUI?

答:
You have a couple of options. One is to use an ObservableObject that can have @objc functions and declare it as the delegate for the notifications:

```<code>struct ContentView: View {
    @StateObject private var eventDelegate = EventDelegate()

    var body: some View {
        Text("Hello, world!")
            .padding()
    }
}

class EventDelegate: ObservableObject {
    let eventStore = EKEventStore()

    init() {
        NotificationCenter.default.addObserver(self, selector: #selector(observeEvents), name: .EKEventStoreChanged, object: eventStore)
        //remember to clean up your observers later
    }

    @objc func observeEvents() {
        print("called with updated events")
    }
}
</code>```

A second option would be to use NotificationCenter's publisher inside your View. Note this example is incomplete, as it's unclear what actions you want to take with the notification, but it's a template to get you started:

```<code>struct ContentView: View {
    @State private var eventStore = EKEventStore() //normally wouldn't use @State for a reference type like this, but it seems pointless to recreate it
    @State private var pub : NotificationCenter.Publisher?

    var body: some View {
        Text("Hello, world!")
            .padding()
            .onAppear {
                pub = NotificationCenter.default.publisher(for: .EKEventStoreChanged, object: eventStore)
                //use sink or assign here
            }
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to understand how to subscribe to EventKit calendar event updates within SwiftIU.

The EventKit documentation shows how to do this in Swift (https://developer.apple.com/documentation/eventkit/updating_with_notifications).

It says to subscribe to calendar update notifications by writing:

NotificationCenter.default.addObserver(self, selector: Selector("storeChanged:"), name: .EKEventStoreChanged, object: eventStore)

It also appears that the storeChanged function needs do be tagged with @objc based on xcode warnings. However, when I do the below within a SwiftUI app, I get the error @objc can only be used with members of classes, @objc protocols, and concrete extensions of classes

import SwiftUI
import EventKit

struct ContentView: View {
    let eventStore = EKEventStore()

    var body: some View {
        Text("Hello, world!")
            .padding()
            .onAppear{
                NotificationCenter.default.addObserver(self, selector: Selector("observeEvents"), name: .EKEventStoreChanged, object: eventStore)
            }
    }

    @objc func observeEvents() {
        print("called with updated events")
    }
}

Am I doing something wrong? What would be the way to subscribe to calendar event updates within the EventStore in SwiftUI?

Body:
You have a couple of options. One is to use an ObservableObject that can have @objc functions and declare it as the delegate for the notifications:

struct ContentView: View {
    @StateObject private var eventDelegate = EventDelegate()

    var body: some View {
        Text("Hello, world!")
            .padding()
    }
}

class EventDelegate: ObservableObject {
    let eventStore = EKEventStore()

    init() {
        NotificationCenter.default.addObserver(self, selector: #selector(observeEvents), name: .EKEventStoreChanged, object: eventStore)
        //remember to clean up your observers later
    }

    @objc func observeEvents() {
        print("called with updated events")
    }
}

A second option would be to use NotificationCenter's publisher inside your View. Note this example is incomplete, as it's unclear what actions you want to take with the notification, but it's a template to get you started:

struct ContentView: View {
    @State private var eventStore = EKEventStore() //normally wouldn't use @State for a reference type like this, but it seems pointless to recreate it
    @State private var pub : NotificationCenter.Publisher?

    var body: some View {
        Text("Hello, world!")
            .padding()
            .onAppear {
                pub = NotificationCenter.default.publisher(for: .EKEventStoreChanged, object: eventStore)
                //use sink or assign here
            }
    }
}


问:
is there any free barcode reader sdk for Windows Phone 7?
I am developing windows mobile application to scan a product barcode by using in built camera. Can you tell me something about barcode reader sdk which are supporting windows mobile 7?</p>

答:
There is always this library (zxing):

http://silverlightzxing.codeplex.com/

It does a pretty decent job, and is able to read a number of different barcodes/qrcodes/and so on.

I updated the link to the silverlight version.

You can see the documentation here:
http://silverlightzxing.codeplex.com/documentation

It's fairly easy to implement, as he's given everything you need for WP7.

ContentLicense: CC BY-SA 3.0


问:
How to dynamically add new columns with the datatypes to the existing Delta table and update the new columns with values
Scenario:

df1 ---> Col1,Col2,Col3 -- which  are the columns in the  delta table

df2 ---> Col1,Col2,Col3,Col4,Col5 -- which are the columns in the latest refresh table

How to get the new columns (in the above Col4,Col5) with datatypes dynamically.

How to alter the existing Delta table to include the  new    columns (in the above Col4,Col5) dynamically and update the new  column values

Thanks for your help.

答:
You don't need to perform explicit ALTER TABLE if you have Delta table - you just need to use built-in capabilities for schema evolution (blog post) - just add the mergeSchema option with value true, and Delta will take care for updating schema.  For example, if I have initial table with two fields: i1 & i2:

df1 = spark.createDataFrame([[1,2]], schema="i1 int, i2 int")
df1.write.format("delta").mode("overwrite").saveAsTable("test")
```
<p>then I can update it even if I have more columns:</p>
<pre class="lang-py prettyprint-override"><code>df2 = spark.createDataFrame([[1,2, '1']], schema="i1 int, i2 int, v string")
df2.write.format("delta").mode("append") \
  .option("mergeSchema", "true").saveAsTable("test")
</code>```

You can find more information about schema evolution & enforcement in the following blog post and this webinar.

Body:
You don't need to perform explicit ALTER TABLE if you have Delta table - you just need to use built-in capabilities for schema evolution (blog post) - just add the mergeSchema option with value true, and Delta will take care for updating schema.  For example, if I have initial table with two fields: i1 & i2:

df1 = spark.createDataFrame([[1,2]], schema="i1 int, i2 int")
df1.write.format("delta").mode("overwrite").saveAsTable("test")

then I can update it even if I have more columns:

df2 = spark.createDataFrame([[1,2, '1']], schema="i1 int, i2 int, v string")
df2.write.format("delta").mode("append") \
  .option("mergeSchema", "true").saveAsTable("test")

You can find more information about schema evolution & enforcement in the following blog post and this webinar.


问:
How to format a Double into Currency - Swift 3
I'm new to Swift programming and I've been creating a simple tip calculator app in Xcode 8.2, I have my calculations set up within my IBAction below. But when I actually run my app and input an amount to calculate (such as 23.45), it comes up with more than 2 decimal places. How do I format it to .currency in this case?

```<code>@IBAction func calculateButtonTapped(_ sender: Any) {

    var tipPercentage: Double {

        if tipAmountSegmentedControl.selectedSegmentIndex == 0 {
            return 0.05
        } else if tipAmountSegmentedControl.selectedSegmentIndex == 1 {
            return 0.10
        } else {
            return 0.2
        }
    }

    let billAmount: Double? = Double(userInputTextField.text!)

    if let billAmount = billAmount {
        let tipAmount = billAmount * tipPercentage
        let totalBillAmount = billAmount + tipAmount

        tipAmountLabel.text = "Tip Amount: $\(tipAmount)"
        totalBillAmountLabel.text = "Total Bill Amount: $\(totalBillAmount)"
    }
}
</code>```

答:
As of Swift 5.5, you can do this with the help of .formatted:

import Foundation

let amount = 12345678.9
print(amount.formatted(.currency(code: "USD")))
// prints: $12,345,678.90
```
<p>This should support most common currency code, such as "EUR", "GBP", or "CNY".</p>
<p>Similarly, you can append locale to <code>.currency</code>:</p>
```print(amount.formatted(
    .currency(code:"EUR").locale(Locale(identifier: "fr-FR"))
))
// prints: 12 345 678,90 €
```

Body:
I'm new to Swift programming and I've been creating a simple tip calculator app in Xcode 8.2, I have my calculations set up within my IBAction below. But when I actually run my app and input an amount to calculate (such as 23.45), it comes up with more than 2 decimal places. How do I format it to .currency in this case?

@IBAction func calculateButtonTapped(_ sender: Any) {

    var tipPercentage: Double {

        if tipAmountSegmentedControl.selectedSegmentIndex == 0 {
            return 0.05
        } else if tipAmountSegmentedControl.selectedSegmentIndex == 1 {
            return 0.10
        } else {
            return 0.2
        }
    }

    let billAmount: Double? = Double(userInputTextField.text!)

    if let billAmount = billAmount {
        let tipAmount = billAmount * tipPercentage
        let totalBillAmount = billAmount + tipAmount

        tipAmountLabel.text = "Tip Amount: $\(tipAmount)"
        totalBillAmountLabel.text = "Total Bill Amount: $\(totalBillAmount)"
    }
}

Body:
As of Swift 5.5, you can do this with the help of .formatted:

import Foundation

let amount = 12345678.9
print(amount.formatted(.currency(code: "USD")))
// prints: $12,345,678.90

This should support most common currency code, such as "EUR", "GBP", or "CNY".

Similarly, you can append locale to .currency:

print(amount.formatted(
    .currency(code:"EUR").locale(Locale(identifier: "fr-FR"))
))
// prints: 12 345 678,90 €


问:
enable button after actual input entered
How  to enabled button, when the actual amount entered

lets say i have 100 minimum and 200 maximum

i want when user enters amount below 100 error comes actual amount needed and button reamins dsiabled

when user enters more than 200 do the same echo error

user has to enter 100 and above but not exceed maximum

```<code> <form method="post">
<input type="text" id="Textfield">
<button type="submit" class="disabledButton" disabled>Submit</button>
<p id="error"></p>
</form>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$('#Textfield').keyup(function(){
     var textBox = $('#Textfield').val();
     if((textBox >= 100) || (textBox <= 200) ){
       $('.disabledButton').prop("disabled", false);
     } else {
     $('#error').text('actual amount needed');
        return false;
    }
});
</script>
</code>```

答:
If you are using html 5, you don't need JavaScript. The best way to do this is to set this field to a number, like

```<code><input type="number" min="100" max="200" placeholder="value in 100-200" id="Textfield" />
</code>```

By setting min and max values, the form will not submit if the value in this field is not in that range

Body:
How  to enabled button, when the actual amount entered

lets say i have 100 minimum and 200 maximum

i want when user enters amount below 100 error comes actual amount needed and button reamins dsiabled

when user enters more than 200 do the same echo error

user has to enter 100 and above but not exceed maximum

 <form method="post">
<input type="text" id="Textfield">
<button type="submit" class="disabledButton" disabled>Submit</button>

</form>

Body:
If you are using html 5, you don't need JavaScript. The best way to do this is to set this field to a number, like

<input type="number" min="100" max="200" placeholder="value in 100-200" id="Textfield" />

By setting min and max values, the form will not submit if the value in this field is not in that range


问:
How Can I Improve My Pygame Text Function?
I want to improve this text function I use hopefully using a dictionary to store values but I don't know how.

The code:

def text(text, x, y, size, color):
    # the font for the text
    font = pygame.font.Font(None, size)
    # the text itself
    txt = font.render(text, 0, color)
    # draw the text
    screen.blit(txt, (x, y))
```

答:
You need to specify what font you will use "font_name.ttf"

```<code>font_type = 'font_name.ttf'

def draw_text(text, color, size, x, y):
    font = pygame.font.Font(font_type, size)
    text = font.render(text, False, color)
    text_rect = text.get_rect(center=(x, y))
    screen.blit(text, text_rect)
</code>```

I hope it will help you, Adam

Body:
You need to specify what font you will use "font_name.ttf"

font_type = 'font_name.ttf'

def draw_text(text, color, size, x, y):
    font = pygame.font.Font(font_type, size)
    text = font.render(text, False, color)
    text_rect = text.get_rect(center=(x, y))
    screen.blit(text, text_rect)

I hope it will help you, Adam


问:
Skipping registering GPU devices error for Cuda version 11.2
I just downloaded cuda 11.3 version and installed cudnn 8.1, added path to both bin and libnvvp. after that i installed tensorflow 2.7(according to tensorflow requirement) but after i run this code to check cuda its giving error

```<code>import tensorflow as tf
tf.test.is_gpu_available(
    cuda_only=False, min_cuda_compute_capability=None
)
</code>```

its giving error:

```<code>
WARNING:tensorflow:From C:/Users/Moiz/PycharmProjects/pythonProject/main.py:2: is_gpu_available (from tensorflow.python.framework.test_util) is deprecated and will be removed in a future version.
Instructions for updating:
Use `tf.config.list_physical_devices('GPU')` instead.
2022-02-13 22:04:16.993299: I tensorflow/core/platform/cpu_feature_guard.cc:151] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN) to use the following CPU instructions in performance-critical operations:  AVX AVX2
To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.
2022-02-13 22:04:17.938394: W tensorflow/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'cusolver64_11.dll'; dlerror: cusolver64_11.dll not found
2022-02-13 22:04:17.941517: W tensorflow/core/common_runtime/gpu/gpu_device.cc:1850] Cannot dlopen some GPU libraries. Please make sure the missing libraries mentioned above are installed properly if you would like to use GPU. Follow the guide at https://www.tensorflow.org/install/gpu for how to download and setup the required libraries for your platform.
Skipping registering GPU devices...
</code>```

答:
hey dude this is was the same error that I got too so I checked it and turns out that some PC dont have the avx for this Try running this command on your terminal or cmd
pip install tensorflow-gpu it will reduce the errors which includes gpu which is most on ur case and then it is easy to remove the others

Body:
I just downloaded cuda 11.3 version and installed cudnn 8.1, added path to both bin and libnvvp. after that i installed tensorflow 2.7(according to tensorflow requirement) but after i run this code to check cuda its giving error

import tensorflow as tf
tf.test.is_gpu_available(
    cuda_only=False, min_cuda_compute_capability=None
)

its giving error:

WARNING:tensorflow:From C:/Users/Moiz/PycharmProjects/pythonProject/main.py:2: is_gpu_available (from tensorflow.python.framework.test_util) is deprecated and will be removed in a future version.
Instructions for updating:
Use `tf.config.list_physical_devices('GPU')` instead.
2022-02-13 22:04:16.993299: I tensorflow/core/platform/cpu_feature_guard.cc:151] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN) to use the following CPU instructions in performance-critical operations:  AVX AVX2
To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.
2022-02-13 22:04:17.938394: W tensorflow/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'cusolver64_11.dll'; dlerror: cusolver64_11.dll not found
2022-02-13 22:04:17.941517: W tensorflow/core/common_runtime/gpu/gpu_device.cc:1850] Cannot dlopen some GPU libraries. Please make sure the missing libraries mentioned above are installed properly if you would like to use GPU. Follow the guide at https://www.tensorflow.org/install/gpu for how to download and setup the required libraries for your platform.
Skipping registering GPU devices...


问:
How to decode a video (memory file / byte string) and step through it frame by frame in python?
I am using python to do some basic image processing, and want to extend it to process a video frame by frame.

I get the video as a blob from a server - .webm encoded - and have it in python as a byte string (b'\x1aE\xdf\xa3\xa3B\x86\x81\x01B\xf7\x81\x01B\xf2\x81\x04B\xf3\x81\x08B\x82\x88matroskaB\x87\x81\x04B\x85\x81\x02\x18S\x80g\x01\xff\xff\xff\xff\xff\xff\xff\x15I\xa9f\x99*\xd7\xb1\x83\x0fB@M\x80\x86ChromeWA\x86Chrome\x16T\xaek\xad\xae\xab\xd7\x81\x01s\xc5\x87\x04\xe8\xfc\x16\t^\x8c\x83\x81\x01\x86\x8fV_MPEG4/ISO/AVC\xe0\x88\xb0\x82\x02\x80\xba\x82\x01\xe0\x1fC\xb6u\x01\xff\xff\xff\xff\xff\xff ...).

I know that there is cv.VideoCapture, which can do almost what I need. The problem is that I would have to first write the file to disk, and then load it again. It seems much cleaner to wrap the string, e.g., into an IOStream, and feed it to some function that does the decoding.

Is there a clean way to do this in python, or is writing to disk and loading it again the way to go?

答:
Two years after Rotem wrote his answer there is now a cleaner / easier way to do this using ImageIO.

Note: Assuming ffmpeg is in your path, you can generate a test video to try this example using: ffmpeg -f lavfi -i testsrc=duration=10:size=1280x720:rate=30 testsrc.webm

import imageio.v3 as iio
from pathlib import Path

webm_bytes = Path("testsrc.webm").read_bytes()

# read all frames from the bytes string
frames = iio.imread(webm_bytes, index=None, format_hint=".webm")
frames.shape
# Output:
#    (300, 720, 1280, 3)

for frame in iio.imiter(webm_bytes, format_hint=".webm"):
    print(frame.shape)

# Output:
#    (720, 1280, 3)
#    (720, 1280, 3)
#    (720, 1280, 3)
#    ...

```
<p>To use this you'll need the ffmpeg backend (which implements a solution similar to what Rotem proposed): <code>pip install imageio[ffmpeg]</code></p>
<hr />
<p>In response to Rotem's comment a bit of explanation:</p>
<p>The above snippet uses <code>imageio==2.16.0</code>. The v3 API is an upcoming user-facing API that streamlines reading and writing. The API is available since <code>imageio==2.10.0</code>, however, you will have to use <code>import imageio as iio</code> and use <code>iio.v3.imiter</code> and <code>iio.v3.imread</code> on versions older than 2.16.0.</p>
<p>The ability to read video bytes has existed forever (>5 years and counting) but has (as I am just now realizing) never been documented directly ... so I will add a PR for that soon™ :)</p>
<p>On older versions (tested on v2.9.0) of ImageIO (v2 API) you can still read video byte strings; however, this is slightly more verbose:</p>
<pre class="lang-py prettyprint-override"><code>import imageio as iio
import numpy as np
from pathlib import Path

webm_bytes = Path("testsrc.webm").read_bytes()

# read all frames from the bytes string
frames = np.stack(iio.mimread(webm_bytes, format="FFMPEG", memtest=False))

# iterate over frames one by one
reader = iio.get_reader(webm_bytes, format="FFMPEG")
for frame in reader:
    print(frame.shape)
reader.close()
</code>```

Body:
Two years after Rotem wrote his answer there is now a cleaner / easier way to do this using ImageIO.

Note: Assuming ffmpeg is in your path, you can generate a test video to try this example using: ffmpeg -f lavfi -i testsrc=duration=10:size=1280x720:rate=30 testsrc.webm

import imageio.v3 as iio
from pathlib import Path

webm_bytes = Path("testsrc.webm").read_bytes()

# read all frames from the bytes string
frames = iio.imread(webm_bytes, index=None, format_hint=".webm")
frames.shape
# Output:
#    (300, 720, 1280, 3)

for frame in iio.imiter(webm_bytes, format_hint=".webm"):
    print(frame.shape)

# Output:
#    (720, 1280, 3)
#    (720, 1280, 3)
#    (720, 1280, 3)
#    ...

To use this you'll need the ffmpeg backend (which implements a solution similar to what Rotem proposed): pip install imageio[ffmpeg]

In response to Rotem's comment a bit of explanation:

The above snippet uses imageio==2.16.0. The v3 API is an upcoming user-facing API that streamlines reading and writing. The API is available since imageio==2.10.0, however, you will have to use import imageio as iio and use iio.v3.imiter and iio.v3.imread on versions older than 2.16.0.

The ability to read video bytes has existed forever (>5 years and counting) but has (as I am just now realizing) never been documented directly ... so I will add a PR for that soon™ :)

On older versions (tested on v2.9.0) of ImageIO (v2 API) you can still read video byte strings; however, this is slightly more verbose:

import imageio as iio
import numpy as np
from pathlib import Path

webm_bytes = Path("testsrc.webm").read_bytes()

# read all frames from the bytes string
frames = np.stack(iio.mimread(webm_bytes, format="FFMPEG", memtest=False))

# iterate over frames one by one
reader = iio.get_reader(webm_bytes, format="FFMPEG")
for frame in reader:
    print(frame.shape)
reader.close()


问:
How to make multiple Svelte windows in Electron?
For my electron app, I would like to open another Svelte-window (or load different windows/components depending on the startup variables).

So let's say I used this tutorial to set up a basic structure, with my App.svelte looking like this:

<button on:click={openLauncher}>Open Launcher</button>
```
<p>As you can see, I added an IPC function to open a new window. The corresponding <code>index.js</code>:</p>
<pre class="lang-js prettyprint-override"><code>const { app, BrowserWindow, ipcMain } = require("electron");
const { join } = require("path");

app.on("ready", () => {
    const mainWindow = new BrowserWindow({
        webPreferences: {
            preload: join(__dirname, "./preload.js"),
        }
    });
    mainWindow.loadFile(join(__dirname, "../public/index.html"));
});

ipcMain.on("openLauncher", (event, args) => {
    const launcher = new BrowserWindow({
        webPreferences: {
            preload: join(__dirname, "./preload.js"),
        }
    });
    launcher.loadFile(join(__dirname, "../public/launcher.html"));
});
</code>```

preload.js:

const { contextBridge, ipcRenderer } = require("electron");

const API = {
    openWindow: (obj) => ipcRenderer.send("openLauncher", obj),
}

contextBridge.exposeInMainWorld("api", API);
```
<p>This does work and opens a new window with the <code>launcher.html</code>, but I can't figure out how to get the Svelte components working in that new file.</p>
<p>One idea I had was modifying <code>main.js</code> file so that the body component changes, like so:</p>
<pre class="lang-js prettyprint-override"><code>import App from './App.svelte';
import LauncherApp from './LauncherApp.svelte';

const bodyID = document.getElementsByTagName('body')[0].id;

const app = {};
if (bodyID == "index") {
    app = new App({
        target: document.body,
    });
}
else if (bodyID == "launcher") {
    app = new LauncherApp({
        target: document.body,
    });
}
export default app;
</code>```

This works for the main window (i.e. if I switch the IDs, it loads the correct component at startup) but since it doesn't load any Svelte whe opening the new window, this doesn't work.

So I would really appreciate any ideas on how to get Svelte to load for new/different windows/html-files! And if there is a way to do this with SvelteKit, even better!

Thank you in advance!

答:
The obvious quick fix I see is using an #if block on bodyID in App.svelte containing two components, MainApp (content of App.svelte) and LauncherApp, and then simply changing bodyID depending on in which mode you are.

When using sveltekit I think it would make sense to treat LauncherApp as a separate route (I believe this is the only way to have "separated" pages with sveltekit, though I am not 100%). So when opening a new window you navigate the new instance of your application to the LauncherApp route. If you don't want the same base layout as in the main app, you can add a __layout.reset.svelte file.

I don't know why your solution didn't work, it was quite elegant.

Body:
For my electron app, I would like to open another Svelte-window (or load different windows/components depending on the startup variables).

So let's say I used this tutorial to set up a basic structure, with my App.svelte looking like this:

<button on:click={openLauncher}>Open Launcher</button>

As you can see, I added an IPC function to open a new window. The corresponding index.js:

const { app, BrowserWindow, ipcMain } = require("electron");
const { join } = require("path");

app.on("ready", () => {
    const mainWindow = new BrowserWindow({
        webPreferences: {
            preload: join(__dirname, "./preload.js"),
        }
    });
    mainWindow.loadFile(join(__dirname, "../public/index.html"));
});

ipcMain.on("openLauncher", (event, args) => {
    const launcher = new BrowserWindow({
        webPreferences: {
            preload: join(__dirname, "./preload.js"),
        }
    });
    launcher.loadFile(join(__dirname, "../public/launcher.html"));
});

preload.js:

const { contextBridge, ipcRenderer } = require("electron");

const API = {
    openWindow: (obj) => ipcRenderer.send("openLauncher", obj),
}

contextBridge.exposeInMainWorld("api", API);

This does work and opens a new window with the launcher.html, but I can't figure out how to get the Svelte components working in that new file.

One idea I had was modifying main.js file so that the body component changes, like so:

import App from './App.svelte';
import LauncherApp from './LauncherApp.svelte';

const bodyID = document.getElementsByTagName('body')[0].id;

const app = {};
if (bodyID == "index") {
    app = new App({
        target: document.body,
    });
}
else if (bodyID == "launcher") {
    app = new LauncherApp({
        target: document.body,
    });
}
export default app;

This works for the main window (i.e. if I switch the IDs, it loads the correct component at startup) but since it doesn't load any Svelte whe opening the new window, this doesn't work.

So I would really appreciate any ideas on how to get Svelte to load for new/different windows/html-files! And if there is a way to do this with SvelteKit, even better!

Thank you in advance!


问:
Python SAX parser says XML file is not well-formed
I stripped some tags that I thought were unnecessary from an XML file. Now when I try to parse it, my SAX parser throws an error and says my file is not well-formed. However, I know every start tag has an end tag. The file's opening tag has a link to an XML schema. Could this be causing the trouble? If so, then how do I fix it?

Edit: I think I've found the problem. My character data contains "&lt" and "&gt" characters, presumably from html tags. After being parsed, these are converted to "<" and ">" characters, which seems to bother the SAX parser. Is there any way to prevent this from happening?

答:
I would second recommendation to try to parse it using another XML parser. That should give an indication as to whether it's the document that's wrong, or parser.

Also, the actual error message might be useful. One fairly common problem for example is that the xml declaration (if one is used, it's optional) must be the very first thing -- not even whitespace is allowed before it.

OwnerDisplayName: Jacob Lyles

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Jacob Lyles

OwnerDisplayName: StaxMan


问:
I'm getting an error that says my random_number variable doesn't exist. Any advice on what I should do to create it?
I'm working on homework and I need to take random observations from a data set. I am trying to create the random data set based on my teacher's coding instructions but I keep getting an error saying my random_number variable does not exist. I have posted an image of my code. Do I need to create the variable or make a proc sort for it?
Code

Here are the error logs:

434  proc print data= random_sample (obs=100);
435      var id country year random_number pr cl;
ERROR: Variable RANDOM_NUMBER not found.
436  run;

NOTE: The SAS System stopped processing this step because of errors.
NOTE: PROCEDURE PRINT used (Total process time):
real time           0.00 seconds
cpu time            0.00 seconds

答: In your photograph of code the data step that looks like it is trying to create a list of random numbers will fail because it does not have an END for the DO loop. (unless you have it at the end of some line that is out of frame from the camera.)</p>


问:
ENV_VARS "undefined" when deploying Next JS app through Gitlab CI/CD to a Kubernetes cluster:
I stick to this problem quite long now:

I have a standard NextJS app, which uses environment variables (for client side NEXT_PUBLIC_MY_VAR as well for server side ones MY_OTHER_VAR).

I use the Gitlab CI-CD AutoDevOps with an tiny custom .gitlab-ci.yml-file (see below).

I have a successful connection to my Kubernetes cluster with Gitlab, and my NextJS app is getting also deployed successfully. (Gitlab/K8s cache cleaned, too)

The only thing where I struggle is to get the process.env.ENV_VARS running.
Whatever I tried they are undefined.

I deployed my app manually into the cluster, and mounted a configMap to my deployment ( so a .env.local-file is present at /app/.env.local
ONLY THEN the ENV_VARS are set correctly.

So how to set the ENV_VARS when deploying my NextJS app via Gitlab Auto DevOps?

I've tried so far:

setting ENV_VARS in Gitlab -> Settings -> CI/CD -> Variables

I added an ARG in my Dockerfile which should pick up the Gitlab CI vars when building the Docker image:

```<code>FROM node:alpine AS deps
RUN apk add --no-cache libc6-compat
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
# ...
# ..

# docker build --build-arg API_URL=http://myApiEndpoint
ARG API_URL
ENV API_URL=$API_URL
RUN npm run build

FROM node:alpine AS runner
WORKDIR /app

ENV NODE_ENV production

# COPY --from=builder /app/next.config.js ./ # TRIED WITH AND WITHOUT
COPY --from=builder /app/public ./public
COPY --from=builder /app/.next ./.next
COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app/package.json ./package.json

RUN addgroup -g 1001 -S nodejs
RUN adduser -S nextjs -u 1001
RUN chown -R nextjs:nodejs /app/.next

USER nextjs

EXPOSE 5000

CMD ["npm", "run", "start"]
</code>```

I have also added the ENV_VARS also in my next.config.js

module.exports = withSvgr({
    serverRuntimeConfig: {},
    publicRuntimeConfig: {
        NEXT_PUBLIC_API_URL: process.env.NEXT_PUBLIC_API_URL,
        API_URL: process.env.API_URL,
    },
});

```
<ul>
<li>I also added a custom <code>.gitlab-ci.yml</code> file (complete file here):</li>
</ul>
<p>yaml
include:
- template: Auto-DevOps.gitlab-ci.yml</p>
```# added vars for build
build:
  stage: build
  variables:
    API_URL: $API_URL
```
<p>This is the error message in my POD</p>
```> metashop-frontend.react@1.8.0 start
> next start -p 5000
ready - started server on 0.0.0.0:5000, url: http://localhost:5000
ApiURL alias: undefined #### <<<----
API_URL: undefined      #### <<<----
TypeError: Only absolute URLs are supported
    at getNodeRequestOptions (/app/node_modules/node-fetch/lib/index.js:1305:9)
    at /app/node_modules/node-fetch/lib/index.js:1410:19
    at new Promise (<anonymous>)
    at fetch (/app/node_modules/node-fetch/lib/index.js:1407:9)
    at Object.getItems (/app/.next/server/pages/_app.js:1194:12)
    at getServerSideProps (/app/.next/server/pages/index.js:2952:55)
    at renderToHTML (/app/node_modules/next/dist/next-server/server/render.js:40:221)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async /app/node_modules/next/dist/next-server/server/next-server.js:109:97
    at async /app/node_modules/next/dist/next-server/server/next-server.js:102:142
```
<p>And is the code that the error refers to:</p>
<pre class="lang-js prettyprint-override"><code>const ApiUrl = process.env.API_URL;

console.log("ApiURL alias:", ApiUrl);
console.log("API_URL:", process.env.API_URL);
console.log("NEXT_PUBLIC_API_URL:", process.env.NEXT_PUBLIC_API_URL);
return fetch(`${ApiUrl}/items.json?${qs.stringify(options)}`).then(
    (response) => response.json()
);
</code>```

and for completeness (but mostly useless) the tail of the failing job (which seems the normal error when K8s not responding):

```<code>Error: release production failed, and has been uninstalled due to atomic being set: timed out waiting for the condition
Uploading artifacts for failed job
00:01
Uploading artifacts...
WARNING: environment_url.txt: no matching files
WARNING: tiller.log: no matching files
ERROR: No files to upload
Cleaning up file based variables
00:01
ERROR: Job failed: exit code 1
</code>```

is .env.local the only way to use NextJS ENV_VARS in Kubernetes?

Do I have to customize the Gilab AutoDevOps for this particular (and common) app deployment?

Thank you in advance, any help would be appreciated

答:
If you stick on Auto Devops on GITLAB then YOU HAVE TO set this Gitlab ENV Variable AUTO_DEVOPS_BUILD_IMAGE_EXTRA_ARGS and set it to

--build-arg=NEXT_PUBLIC_API_URL=http://your.domain.com/api

In your Dockerfile you can assign it via

```<code>    ARG NEXT_PUBLIC_API_URL
    ENV NEXT_PUBLIC_API_URL=$NEXT_PUBLIC_API_URL
</code>```

More information here:

https://docs.gitlab.com/ee/topics/autodevops/customize.html#passing-arguments-to-docker-build

Body:
I stick to this problem quite long now:

I have a standard NextJS app, which uses environment variables (for client side NEXT_PUBLIC_MY_VAR as well for server side ones MY_OTHER_VAR).

I use the Gitlab CI-CD AutoDevOps with an tiny custom .gitlab-ci.yml-file (see below).

I have a successful connection to my Kubernetes cluster with Gitlab, and my NextJS app is getting also deployed successfully. (Gitlab/K8s cache cleaned, too)

The only thing where I struggle is to get the process.env.ENV_VARS running.
Whatever I tried they are undefined.

I deployed my app manually into the cluster, and mounted a configMap to my deployment ( so a .env.local-file is present at /app/.env.local
ONLY THEN the ENV_VARS are set correctly.

So how to set the ENV_VARS when deploying my NextJS app via Gitlab Auto DevOps?

I've tried so far:

setting ENV_VARS in Gitlab -> Settings -> CI/CD -> Variables

I added an ARG in my Dockerfile which should pick up the Gitlab CI vars when building the Docker image:

FROM node:alpine AS deps
RUN apk add --no-cache libc6-compat
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
# ...
# ..

# docker build --build-arg API_URL=http://myApiEndpoint
ARG API_URL
ENV API_URL=$API_URL
RUN npm run build

FROM node:alpine AS runner
WORKDIR /app

ENV NODE_ENV production

# COPY --from=builder /app/next.config.js ./ # TRIED WITH AND WITHOUT
COPY --from=builder /app/public ./public
COPY --from=builder /app/.next ./.next
COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app/package.json ./package.json

RUN addgroup -g 1001 -S nodejs
RUN adduser -S nextjs -u 1001
RUN chown -R nextjs:nodejs /app/.next

USER nextjs

EXPOSE 5000

CMD ["npm", "run", "start"]

I have also added the ENV_VARS also in my next.config.js

module.exports = withSvgr({
    serverRuntimeConfig: {},
    publicRuntimeConfig: {
        NEXT_PUBLIC_API_URL: process.env.NEXT_PUBLIC_API_URL,
        API_URL: process.env.API_URL,
    },
});

I also added a custom .gitlab-ci.yml file (complete file here):

yaml
include:
- template: Auto-DevOps.gitlab-ci.yml

# added vars for build
build:
  stage: build
  variables:
    API_URL: $API_URL

This is the error message in my POD

> metashop-frontend.react@1.8.0 start
> next start -p 5000
ready - started server on 0.0.0.0:5000, url: http://localhost:5000
ApiURL alias: undefined #### <<<----
API_URL: undefined      #### <<<----
TypeError: Only absolute URLs are supported
    at getNodeRequestOptions (/app/node_modules/node-fetch/lib/index.js:1305:9)
    at /app/node_modules/node-fetch/lib/index.js:1410:19
    at new Promise (<anonymous>)
    at fetch (/app/node_modules/node-fetch/lib/index.js:1407:9)
    at Object.getItems (/app/.next/server/pages/_app.js:1194:12)
    at getServerSideProps (/app/.next/server/pages/index.js:2952:55)
    at renderToHTML (/app/node_modules/next/dist/next-server/server/render.js:40:221)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async /app/node_modules/next/dist/next-server/server/next-server.js:109:97
    at async /app/node_modules/next/dist/next-server/server/next-server.js:102:142

And is the code that the error refers to:

const ApiUrl = process.env.API_URL;

console.log("ApiURL alias:", ApiUrl);
console.log("API_URL:", process.env.API_URL);
console.log("NEXT_PUBLIC_API_URL:", process.env.NEXT_PUBLIC_API_URL);
return fetch(`${ApiUrl}/items.json?${qs.stringify(options)}`).then(
    (response) => response.json()
);

and for completeness (but mostly useless) the tail of the failing job (which seems the normal error when K8s not responding):

Error: release production failed, and has been uninstalled due to atomic being set: timed out waiting for the condition
Uploading artifacts for failed job
00:01
Uploading artifacts...
WARNING: environment_url.txt: no matching files
WARNING: tiller.log: no matching files
ERROR: No files to upload
Cleaning up file based variables
00:01
ERROR: Job failed: exit code 1

is .env.local the only way to use NextJS ENV_VARS in Kubernetes?

Do I have to customize the Gilab AutoDevOps for this particular (and common) app deployment?

Thank you in advance, any help would be appreciated

Body:
If you stick on Auto Devops on GITLAB then YOU HAVE TO set this Gitlab ENV Variable AUTO_DEVOPS_BUILD_IMAGE_EXTRA_ARGS and set it to

--build-arg=NEXT_PUBLIC_API_URL=http://your.domain.com/api

In your Dockerfile you can assign it via

    ARG NEXT_PUBLIC_API_URL
    ENV NEXT_PUBLIC_API_URL=$NEXT_PUBLIC_API_URL

More information here:

https://docs.gitlab.com/ee/topics/autodevops/customize.html#passing-arguments-to-docker-build


问:
Is it possible to use an array value as a switch case value?
I am trying to create a working Java code. I created an encryption function that takes any symbol in a string and replaces it with a value from an array.

The problem is very simple. Decryption function must take any value written in an array and use it to decrypt. The code describes it better than I do.

```<code>   case "1" -> output += n_encryptions[0];
// Then in decrypt():
   case n_encryptions[0] -> output += "1";
// Sadly, this creates an error
</code>```

My goal is to make an easily changeable encryption and decryption system, since I am planning to change these values in the future.

I need a way to use an array value (n_encryptions[0] in the example) as a case parameter.

Edit: I guess an if statement is the best option. Thanks!

答:
I'm just suggesting a way of solving the problem. You can use a Map<Character, Character> for encryption and another for decryption. You can adapt the following program to your needs.

```<code>import java.util.HashMap;
import java.util.Map;

public class Test {
    public static void main (String[] args) {
        Map<Character, Character> encryptionMap = new HashMap<>();
        encryptionMap.put('a', '-');
        encryptionMap.put('b', '+');
        encryptionMap.put('-', '1');
        encryptionMap.put('+', '3');

        String plainText = "a+b-a";
        String encryptedText = "";
        for (int i = 0; i < plainText.length(); i++) {
            char ch = plainText.charAt(i);
            encryptedText += encryptionMap.get(ch);
        }
        System.out.println("Plain Text: " + plainText);
        System.out.println("Encrypted Text: " + encryptedText);

        Map<Character, Character> decryptionMap = new HashMap<>();
        decryptionMap.put('-', 'a');
        decryptionMap.put('+', 'b');
        decryptionMap.put('1', '-');
        decryptionMap.put('3', '+');

        String decryptedText = "";
        for (int i = 0; i < encryptedText.length(); i++) {
            char ch = encryptedText.charAt(i);
            decryptedText += decryptionMap.get(ch);
        }
        System.out.println("Decrypted Text: " + decryptedText);
    }
}
</code>```

Body:
I am trying to create a working Java code. I created an encryption function that takes any symbol in a string and replaces it with a value from an array.

The problem is very simple. Decryption function must take any value written in an array and use it to decrypt. The code describes it better than I do.

   case "1" -> output += n_encryptions[0];
// Then in decrypt():
   case n_encryptions[0] -> output += "1";
// Sadly, this creates an error

My goal is to make an easily changeable encryption and decryption system, since I am planning to change these values in the future.

I need a way to use an array value (n_encryptions[0] in the example) as a case parameter.

Edit: I guess an if statement is the best option. Thanks!

Body:
I'm just suggesting a way of solving the problem. You can use a Map<Character, Character> for encryption and another for decryption. You can adapt the following program to your needs.

import java.util.HashMap;
import java.util.Map;

public class Test {
    public static void main (String[] args) {
        Map<Character, Character> encryptionMap = new HashMap<>();
        encryptionMap.put('a', '-');
        encryptionMap.put('b', '+');
        encryptionMap.put('-', '1');
        encryptionMap.put('+', '3');

        String plainText = "a+b-a";
        String encryptedText = "";
        for (int i = 0; i < plainText.length(); i++) {
            char ch = plainText.charAt(i);
            encryptedText += encryptionMap.get(ch);
        }
        System.out.println("Plain Text: " + plainText);
        System.out.println("Encrypted Text: " + encryptedText);

        Map<Character, Character> decryptionMap = new HashMap<>();
        decryptionMap.put('-', 'a');
        decryptionMap.put('+', 'b');
        decryptionMap.put('1', '-');
        decryptionMap.put('3', '+');

        String decryptedText = "";
        for (int i = 0; i < encryptedText.length(); i++) {
            char ch = encryptedText.charAt(i);
            decryptedText += decryptionMap.get(ch);
        }
        System.out.println("Decrypted Text: " + decryptedText);
    }
}


问:
Changing button style after interaction using Discord.js v13
I'm trying to make a rock paper scissors game using buttons, however, I'm new to 13v and this is my first time using buttons, I wanted to make it where when the user clicks the button of their choice, that button turns green aka its style turns into "SUCCESS" but it's not updating on the Discord API, seems like styles aren't Read-only so, does anyone have any idea why is this happening?

My code:

const db = require('quick.db')
const { MessageEmbed, MessageButton, MessageActionRow } = require('discord.js')
const { BOT_PREFIX } = require('../config')
const commandName = 'rockpaperscissor'

module.exports = client => {
    client.on('messageCreate', async message => {
        if (message.author.bot) return
        if (!message.content.startsWith(BOT_PREFIX)) return

        const command = message.content.split(' ')
        const args = message.content.substring(1).split(' ')

        if (command.toString().toLowerCase().replace(BOT_PREFIX, '').startsWith(commandName) || command.toString().toLowerCase().replace(BOT_PREFIX, '').startsWith('rps')) {
            const buttonRow1 = new MessageActionRow().addComponents(
                new MessageButton()
                .setCustomId('rock-RPS')
                .setLabel('ROCK')
                .setStyle('SECONDARY')
                .setDisabled(false),
                new MessageButton()
                .setCustomId('paper-RPS')
                .setLabel('PAPER')
                .setStyle('SECONDARY')
                .setDisabled(false),
                new MessageButton()
                .setCustomId('scissors-RPS')
                .setLabel('SCISSORS')
                .setStyle('SECONDARY')
                .setDisabled(false)
            )

            const filter = (interaction) => {
                if (!interaction.isButton) return
                if (interaction.customId.includes('-RPS'))
                if (interaction.user.id === message.author.id) return true;
                interaction.reply({ content: 'This game isn\'t for you.' })
            }

            const collector = message.channel.createMessageComponentCollector({
                filter,
                max: 1,
            })

            message.reply({ content: 'Testing!', components: [buttonRow1] })

            const choices = ['Rock', 'Paper', 'Scissors']
            let botChoice = choices[Math.floor(Math.random() * choices.length)];

            let userBalance =  parseInt(await db.fetch(`${message.author.id}.balance`))
            if (userBalance == null) await db.set(`${message.author.id}.balance`, 0)
            function randomNumber(min, max) {
                return Math.floor(Math.random() * (max - min+1)+min);
            }
            let reward1 = randomNumber(153, 535)
            let reward2 = randomNumber(553, 1460)

            collector.on('end', async (buttonInteraction) => {
                const interaction = buttonInteraction.first();
                const success = new MessageButton(buttonInteraction.component).setStyle("SUCCESS");
                await interaction.deferReply({
                    ephemeral: false
                })
                interaction.reply('Please wait...')
                if (interaction.customId == 'rock-RPS') {
                    interaction.update({ components: [new MessageActionRow().addComponents(
                        new MessageButton()
                        .setCustomId('rock-RPS')
                        .setLabel('ROCK')
                        .setStyle('SUCCESS')
                        .setDisabled(true),
                        new MessageButton()
                        .setCustomId('paper-RPS')
                        .setLabel('PAPER')
                        .setStyle('SECONDARY')
                        .setDisabled(true),
                        new MessageButton()
                        .setCustomId('scissors-RPS')
                        .setLabel('SCISSORS')
                        .setStyle('SECONDARY')
                        .setDisabled(true))]
                    })
                } else if (interaction.customId == 'paper-RPS') {
                    interaction.update({ components: [new MessageActionRow().addComponents(
                        new MessageButton()
                        .setCustomId('rock-RPS')
                        .setLabel('ROCK')
                        .setStyle('SECONDARY')
                        .setDisabled(true),
                        new MessageButton()
                        .setCustomId('paper-RPS')
                        .setLabel('PAPER')
                        .setStyle('SUCCESS')
                        .setDisabled(true),
                        new MessageButton()
                        .setCustomId('scissors-RPS')
                        .setLabel('SCISSORS')
                        .setStyle('SECONDARY')
                        .setDisabled(true))]
                    })
                } else if (interaction.customId == 'scissors-RPS') {
                    interaction.update({ components: [new MessageActionRow().addComponents(
                        new MessageButton()
                        .setCustomId('rock-RPS')
                        .setLabel('ROCK')
                        .setStyle('SECONDARY')
                        .setDisabled(true),
                        new MessageButton()
                        .setCustomId('paper-RPS')
                        .setLabel('PAPER')
                        .setStyle('SECONDARY')
                        .setDisabled(true),
                        new MessageButton()
                        .setCustomId('scissors-RPS')
                        .setLabel('SCISSORS')
                        .setStyle('SUCCESS')
                        .setDisabled(true))]
                    })
                }
                if (interaction.customId == 'rock-RPS') {
                    if (botChoice == 'Rock') {
                        interaction.editReply({ content: `I chose Rock too, so it's a tie!\nYou got \`$${reward1}\` as a small reward.`})
                        await db.set(`${interaction.user.id}.balance`, userBalance + reward1)
                    } else if (botChoice == 'Paper') {
                        interaction.editReply({ content: `I chose Paper, so I win!`})
                    } else if (botChoice == 'Scissors') {
                        interaction.editReply({ content: `I chose Scissors, so you win!\nYou got \`$${reward2}\` as an award!`})
                        await db.set(`${interaction.user.id}.balance`, userBalance + reward2)
                    }
                } else if (interaction.customId == 'paper-RPS') {
                    if (botChoice == 'Rock') {
                        interaction.editReply({ content: `I chose Rock, so you win!\nYou got \`$${reward2}\` as an award!`})
                        await db.set(`${interaction.user.id}.balance`, userBalance + reward2)
                    } else if (botChoice == 'Paper') {
                        interaction.editReply({ content: `I chose Paper too, so it's a tie!\nYou got \`$${reward1}\` as a small reward.`})
                        await db.set(`${interaction.user.id}.balance`, userBalance + reward1)
                    } else if (botChoice == 'Scissors') {
                        interaction.editReply({ content: `I chose Scissors, so I win!`})
                    }
                } else if (interaction.customId == 'scissors-RPS') {
                    if (botChoice == 'Rock') {
                        interaction.editReply({ content: `I chose Rock, so I win!`})
                    } else if (botChoice == 'Paper') {
                        interaction.editReply({ content: `I chose Paper, so you win!\nYou got \`$${reward2}\` as an award!`})
                        await db.set(`${interaction.user.id}.balance`, userBalance + reward2)
                    } else if (botChoice == 'Scissors') {
                        interaction.editReply({ content: `I chose Scissors too, so it's a tie!\nYou got \`$${reward1}\` as a small reward.`})
                        await db.set(`${interaction.user.id}.balance`, userBalance + reward1)
                    }
                }
            })
        }
    })
}
```

答:
I updated my answer to be a working correction of your original question. I have the db lines commented out for obvious reasons. You will just need to copy the new code in bot selections for PAPER and SCISSORS.

```<code>client.on('messageCreate', async message => {
    if (message.content === "!rps") {
        const buttonRow1 = new MessageActionRow().addComponents(
            new MessageButton()
                .setCustomId('rock-RPS')
                .setLabel('ROCK')
                .setStyle('SECONDARY')
                .setDisabled(false),
            new MessageButton()
                .setCustomId('paper-RPS')
                .setLabel('PAPER')
                .setStyle('SECONDARY')
                .setDisabled(false),
            new MessageButton()
                .setCustomId('scissors-RPS')
                .setLabel('SCISSORS')
                .setStyle('SECONDARY')
                .setDisabled(false)
        )

        const filter = (interaction) => {
            if (!interaction.isButton) return
            if (interaction.customId.includes('-RPS'))
            if (interaction.user.id === message.author.id) return true;

            interaction.reply({ content: 'This game isn\'t for you.' })
        }

        const collector = message.channel.createMessageComponentCollector({
            filter,
            max: 1,
        })

        // ******** CHANGE THIS LINE FROM .reply TO .send; ADD await to all sends/replies ********
        await message.channel.send({ embeds: [new MessageEmbed().setTitle('Let\'s Play!')], components: [buttonRow1] })

        const choices = ['Rock', 'Paper', 'Scissors']

        let botChoice = choices[Math.floor(Math.random() * choices.length)];

        // let userBalance =  parseInt(await db.fetch(`${message.author.id}.balance`))

        // if (userBalance == null) await db.set(`${message.author.id}.balance`, 0)

        function randomNumber(min, max) {
            return Math.floor(Math.random() * (max - min+1)+min);
        }

        let reward1 = randomNumber(153, 535)
        let reward2 = randomNumber(553, 1460)

        collector.on('end', async (buttonInteraction) => {
            const interaction = buttonInteraction.first();
            const success = new MessageButton(buttonInteraction.component).setStyle("SUCCESS");

            if (interaction.customId == 'rock-RPS') {
                await interaction.update({ components: [new MessageActionRow().addComponents(
                    new MessageButton()
                        .setCustomId('rock-RPS')
                        .setLabel('ROCK')
                        .setStyle('SUCCESS')
                        .setDisabled(true),
                    new MessageButton()
                        .setCustomId('paper-RPS')
                        .setLabel('PAPER')
                        .setStyle('SECONDARY')
                        .setDisabled(true),
                    new MessageButton()
                        .setCustomId('scissors-RPS')
                        .setLabel('SCISSORS')
                        .setStyle('SECONDARY')
                        .setDisabled(true))]
                })
            } else if (interaction.customId == 'paper-RPS') {
                await interaction.update({ components: [new MessageActionRow().addComponents(
                    new MessageButton()
                        .setCustomId('rock-RPS')
                        .setLabel('ROCK')
                        .setStyle('SECONDARY')
                        .setDisabled(true),
                    new MessageButton()
                        .setCustomId('paper-RPS')
                        .setLabel('PAPER')
                        .setStyle('SUCCESS')
                        .setDisabled(true),
                    new MessageButton()
                        .setCustomId('scissors-RPS')
                        .setLabel('SCISSORS')
                        .setStyle('SECONDARY')
                        .setDisabled(true))]
                })
            } else if (interaction.customId == 'scissors-RPS') {
                await interaction.update({ components: [new MessageActionRow().addComponents(
                    new MessageButton()
                        .setCustomId('rock-RPS')
                        .setLabel('ROCK')
                        .setStyle('SECONDARY')
                        .setDisabled(true),
                    new MessageButton()
                        .setCustomId('paper-RPS')
                        .setLabel('PAPER')
                        .setStyle('SECONDARY')
                        .setDisabled(true),
                    new MessageButton()
                        .setCustomId('scissors-RPS')
                        .setLabel('SCISSORS')
                        .setStyle('SUCCESS')
                        .setDisabled(true))]
                })
            }

            if (interaction.customId == 'rock-RPS') {
                if (botChoice == 'Rock') {
                    // ******** ADDED INDIVIDUAL STATES; DO FOR PAPER AND SCISSORS; THIS CAN BE GREATLY IMPROVED BUT IT GETS YOU GOING ********
                    const tie = new MessageActionRow().addComponents(
                        new MessageButton()
                            .setCustomId('rock-RPS')
                            .setLabel('ROCK')
                            .setStyle('PRIMARY')
                            .setDisabled(true));

                    await interaction.editReply({ content: `I chose Rock too, so it's a tie!\nYou got \`$${reward1}\` as a small reward.`, components: [tie]})

                    // await db.set(`${interaction.user.id}.balance`, userBalance + reward1)
                } else if (botChoice == 'Paper') {
                    const lose = new MessageActionRow().addComponents(
                        new MessageButton()
                            .setCustomId('rock-RPS')
                            .setLabel('ROCK')
                            .setStyle('DANGER')
                            .setDisabled(true));

                    await interaction.editReply({ content: `I chose Paper, so I win!`, components: [lose]})
                } else if (botChoice == 'Scissors') {
                    const win = new MessageActionRow().addComponents(
                        new MessageButton()
                            .setCustomId('rock-RPS')
                            .setLabel('ROCK')
                            .setStyle('SUCCESS')
                            .setDisabled(true));

                    await interaction.editReply({ content: `I chose Scissors, so you win!\nYou got \`$${reward2}\` as an award!`, components: [win]})

                    // await db.set(`${interaction.user.id}.balance`, userBalance + reward2)
                }
            } else if (interaction.customId == 'paper-RPS') {
                if (botChoice == 'Rock') {
                    await interaction.editReply({ content: `I chose Rock, so you win!\nYou got \`$${reward2}\` as an award!`})

                    // await db.set(`${interaction.user.id}.balance`, userBalance + reward2)
                } else if (botChoice == 'Paper') {
                    await interaction.editReply({ content: `I chose Paper too, so it's a tie!\nYou got \`$${reward1}\` as a small reward.`})

                    // await db.set(`${interaction.user.id}.balance`, userBalance + reward1)
                } else if (botChoice == 'Scissors') {
                    await interaction.editReply({ content: `I chose Scissors, so I win!`})
                }
            } else if (interaction.customId == 'scissors-RPS') {
                if (botChoice == 'Rock') {
                    await interaction.editReply({ content: `I chose Rock, so I win!`})
                } else if (botChoice == 'Paper') {
                    await interaction.editReply({ content: `I chose Paper, so you win!\nYou got \`$${reward2}\` as an award!`})

                    // await db.set(`${interaction.user.id}.balance`, userBalance + reward2)
                } else if (botChoice == 'Scissors') {
                    await interaction.editReply({ content: `I chose Scissors too, so it's a tie!\nYou got \`$${reward1}\` as a small reward.`})

                    // await db.set(`${interaction.user.id}.balance`, userBalance + reward1)
                }
            }
        })
                // }
            // })
        // }
    }
});
</code>```

Body:
I updated my answer to be a working correction of your original question. I have the db lines commented out for obvious reasons. You will just need to copy the new code in bot selections for PAPER and SCISSORS.

client.on('messageCreate', async message => {
    if (message.content === "!rps") {
        const buttonRow1 = new MessageActionRow().addComponents(
            new MessageButton()
                .setCustomId('rock-RPS')
                .setLabel('ROCK')
                .setStyle('SECONDARY')
                .setDisabled(false),
            new MessageButton()
                .setCustomId('paper-RPS')
                .setLabel('PAPER')
                .setStyle('SECONDARY')
                .setDisabled(false),
            new MessageButton()
                .setCustomId('scissors-RPS')
                .setLabel('SCISSORS')
                .setStyle('SECONDARY')
                .setDisabled(false)
        )

        const filter = (interaction) => {
            if (!interaction.isButton) return
            if (interaction.customId.includes('-RPS'))
            if (interaction.user.id === message.author.id) return true;

            interaction.reply({ content: 'This game isn\'t for you.' })
        }

        const collector = message.channel.createMessageComponentCollector({
            filter,
            max: 1,
        })

        // ******** CHANGE THIS LINE FROM .reply TO .send; ADD await to all sends/replies ********
        await message.channel.send({ embeds: [new MessageEmbed().setTitle('Let\'s Play!')], components: [buttonRow1] })

        const choices = ['Rock', 'Paper', 'Scissors']

        let botChoice = choices[Math.floor(Math.random() * choices.length)];

        // let userBalance =  parseInt(await db.fetch(`${message.author.id}.balance`))

        // if (userBalance == null) await db.set(`${message.author.id}.balance`, 0)

        function randomNumber(min, max) {
            return Math.floor(Math.random() * (max - min+1)+min);
        }

        let reward1 = randomNumber(153, 535)
        let reward2 = randomNumber(553, 1460)

        collector.on('end', async (buttonInteraction) => {
            const interaction = buttonInteraction.first();
            const success = new MessageButton(buttonInteraction.component).setStyle("SUCCESS");

            if (interaction.customId == 'rock-RPS') {
                await interaction.update({ components: [new MessageActionRow().addComponents(
                    new MessageButton()
                        .setCustomId('rock-RPS')
                        .setLabel('ROCK')
                        .setStyle('SUCCESS')
                        .setDisabled(true),
                    new MessageButton()
                        .setCustomId('paper-RPS')
                        .setLabel('PAPER')
                        .setStyle('SECONDARY')
                        .setDisabled(true),
                    new MessageButton()
                        .setCustomId('scissors-RPS')
                        .setLabel('SCISSORS')
                        .setStyle('SECONDARY')
                        .setDisabled(true))]
                })
            } else if (interaction.customId == 'paper-RPS') {
                await interaction.update({ components: [new MessageActionRow().addComponents(
                    new MessageButton()
                        .setCustomId('rock-RPS')
                        .setLabel('ROCK')
                        .setStyle('SECONDARY')
                        .setDisabled(true),
                    new MessageButton()
                        .setCustomId('paper-RPS')
                        .setLabel('PAPER')
                        .setStyle('SUCCESS')
                        .setDisabled(true),
                    new MessageButton()
                        .setCustomId('scissors-RPS')
                        .setLabel('SCISSORS')
                        .setStyle('SECONDARY')
                        .setDisabled(true))]
                })
            } else if (interaction.customId == 'scissors-RPS') {
                await interaction.update({ components: [new MessageActionRow().addComponents(
                    new MessageButton()
                        .setCustomId('rock-RPS')
                        .setLabel('ROCK')
                        .setStyle('SECONDARY')
                        .setDisabled(true),
                    new MessageButton()
                        .setCustomId('paper-RPS')
                        .setLabel('PAPER')
                        .setStyle('SECONDARY')
                        .setDisabled(true),
                    new MessageButton()
                        .setCustomId('scissors-RPS')
                        .setLabel('SCISSORS')
                        .setStyle('SUCCESS')
                        .setDisabled(true))]
                })
            }

            if (interaction.customId == 'rock-RPS') {
                if (botChoice == 'Rock') {
                    // ******** ADDED INDIVIDUAL STATES; DO FOR PAPER AND SCISSORS; THIS CAN BE GREATLY IMPROVED BUT IT GETS YOU GOING ********
                    const tie = new MessageActionRow().addComponents(
                        new MessageButton()
                            .setCustomId('rock-RPS')
                            .setLabel('ROCK')
                            .setStyle('PRIMARY')
                            .setDisabled(true));

                    await interaction.editReply({ content: `I chose Rock too, so it's a tie!\nYou got \`$${reward1}\` as a small reward.`, components: [tie]})

                    // await db.set(`${interaction.user.id}.balance`, userBalance + reward1)
                } else if (botChoice == 'Paper') {
                    const lose = new MessageActionRow().addComponents(
                        new MessageButton()
                            .setCustomId('rock-RPS')
                            .setLabel('ROCK')
                            .setStyle('DANGER')
                            .setDisabled(true));

                    await interaction.editReply({ content: `I chose Paper, so I win!`, components: [lose]})
                } else if (botChoice == 'Scissors') {
                    const win = new MessageActionRow().addComponents(
                        new MessageButton()
                            .setCustomId('rock-RPS')
                            .setLabel('ROCK')
                            .setStyle('SUCCESS')
                            .setDisabled(true));

                    await interaction.editReply({ content: `I chose Scissors, so you win!\nYou got \`$${reward2}\` as an award!`, components: [win]})

                    // await db.set(`${interaction.user.id}.balance`, userBalance + reward2)
                }
            } else if (interaction.customId == 'paper-RPS') {
                if (botChoice == 'Rock') {
                    await interaction.editReply({ content: `I chose Rock, so you win!\nYou got \`$${reward2}\` as an award!`})

                    // await db.set(`${interaction.user.id}.balance`, userBalance + reward2)
                } else if (botChoice == 'Paper') {
                    await interaction.editReply({ content: `I chose Paper too, so it's a tie!\nYou got \`$${reward1}\` as a small reward.`})

                    // await db.set(`${interaction.user.id}.balance`, userBalance + reward1)
                } else if (botChoice == 'Scissors') {
                    await interaction.editReply({ content: `I chose Scissors, so I win!`})
                }
            } else if (interaction.customId == 'scissors-RPS') {
                if (botChoice == 'Rock') {
                    await interaction.editReply({ content: `I chose Rock, so I win!`})
                } else if (botChoice == 'Paper') {
                    await interaction.editReply({ content: `I chose Paper, so you win!\nYou got \`$${reward2}\` as an award!`})

                    // await db.set(`${interaction.user.id}.balance`, userBalance + reward2)
                } else if (botChoice == 'Scissors') {
                    await interaction.editReply({ content: `I chose Scissors too, so it's a tie!\nYou got \`$${reward1}\` as a small reward.`})

                    // await db.set(`${interaction.user.id}.balance`, userBalance + reward1)
                }
            }
        })
                // }
            // })
        // }
    }
});


问:
Cannot connect to Metro (Running React Native App in Expo)
I am a beginner who just learn React Native.

I am facing an issues in running my React Native Application from Android Studio Emulator by using Expo. My android emulator keep disconnecting and it prompting an error message saying that "Cannot connect to Metro".

Here is the screenshot from Android Emulator for the error message. May I ask how to solve this issue?

Error message from Android Emulator

Thank you.

答:
Workaround for this is to install adb tools via brew and then connect it to metro via adb reverse tcp:8081 tcp:8081 in a second terminal. When the answer is 8081 you are connected...
If somebody has a solution to finally resolve this I would also be happy to not use this all the time.


问:
multi level drop down menu with css
i want to add multi level dropdown to that w3schools menu.
https://www.w3schools.com/howto/howto_js_responsive_navbar_dropdown.asp
it looks like
original w3schools menu
i tried to make it multi level as you can see.
multi level drop down photo 1
multi level drop down photo 2

My problem is as you can see in the photos; multi level does not close when you are another level. can you fix that ?

```<code>
 <div class="topnav" id="myTopnav">
   <a href="#home" class="active">Home</a>
   <a href="#news">News</a>
   <a href="#contact">Contact</a>
   <div class="dropdown">
     <button class="dropbtn">Dropdown
       <i class="fa fa-caret-down"></i>
     </button>
     <div class="dropdown-content">
       <a href="#">Link 1</a>
       <a href="#">Link 2</a>
       <a href="#">Link 3</a>
     </div>
   </div>
   <a href="#about">About</a>
   <a href="javascript:void(0);" style="font-size:15px;" class="icon" onclick="myFunction()">☰</a>
 </div>

 `/* Add a black background color to the top navigation */
 .topnav {
   background-color: #333;
   overflow: hidden;
 }

 /* Style the links inside the navigation bar */
 .topnav a {
   float: left;
   display: block;
   color: #f2f2f2;
   text-align: center;
   padding: 14px 16px;
   text-decoration: none;
   font-size: 17px;
 }

 /* Add an active class to highlight the current page */
 .active {
   background-color: #04AA6D;
   color: white;
 }

 /* Hide the link that should open and close the topnav on small screens */
 .topnav .icon {
   display: none;
 }

 /* Dropdown container - needed to position the dropdown content */
 .dropdown {
   float: left;
   overflow: hidden;
 }

 /* Style the dropdown button to fit inside the topnav */
 .dropdown .dropbtn {
   font-size: 17px;
   border: none;
   outline: none;
   color: white;
   padding: 14px 16px;
   background-color: inherit;
   font-family: inherit;
   margin: 0;
 }

 /* Style the dropdown content (hidden by default) */
 .dropdown-content {
   display: none;
   position: absolute;
   background-color: #f9f9f9;
   min-width: 160px;
   box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
   z-index: 1;
 }

 /* Style the links inside the dropdown */
 .dropdown-content a {
   float: none;
   color: black;
   padding: 12px 16px;
   text-decoration: none;
   display: block;
   text-align: left;
 }

 /* Add a dark background on topnav links and the dropdown button on hover */
 .topnav a:hover, .dropdown:hover .dropbtn {
   background-color: #555;
   color: white;
 }

 /* Add a grey background to dropdown links on hover */
 .dropdown-content a:hover {
   background-color: #ddd;
   color: black;
 }

 /* Show the dropdown menu when the user moves the mouse over the dropdown button */
 .dropdown:hover .dropdown-content {
   display: block;
 }

 /* When the screen is less than 600 pixels wide, hide all links, except for the first one ("Home"). Show the link that contains should open and close the topnav (.icon) */
 @media screen and (max-width: 600px) {
   .topnav a:not(:first-child), .dropdown .dropbtn {
     display: none;
   }
   .topnav a.icon {
     float: right;
     display: block;
   }
 }

 /* The "responsive" class is added to the topnav with JavaScript when the user clicks on the icon. This class makes the topnav look good on small screens (display the links vertically instead of horizontally) */
 @media screen and (max-width: 600px) {
   .topnav.responsive {position: relative;}
   .topnav.responsive a.icon {
     position: absolute;
     right: 0;
     top: 0;
   }
   .topnav.responsive a {
     float: none;
     display: block;
     text-align: left;
   }
   .topnav.responsive .dropdown {float: none;}
   .topnav.responsive .dropdown-content {position: relative;}
   .topnav.responsive .dropdown .dropbtn {
     display: block;
     width: 100%;
     text-align: left;
   }
 }

</code>```

i changed it like this;

```<code>.topnav {
overflow: hidden;
background-color: #333;
}

.topnav a {
float: left;
display: block;
color: #f2f2f2;
text-align: center;
padding: 14px 16px;
text-decoration: none;
font-size: 17px;
}

.active {
background-color: #04AA6D;
color: white;
}

.topnav .icon {
display: none;
}

.dropdown {
float: left;
overflow: hidden;
}

.dropdown .dropbtn {
font-size: 17px;
border: none;
outline: none;
color: white;
padding: 14px 16px;
background-color: inherit;
font-family: inherit;
margin: 0;
}

.dropdown-content {
display: none;
position: absolute;
background-color: #f9f9f9;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
z-index: 1;
}
.dropdown-submenu {
display: none;
position: absolute;
background-color: #f9f9f9;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
z-index: 1;
top: 0;
left: 100%
}

.dropdown-content a {
float: none;
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
text-align: left;
}

.topnav a:hover, .dropdown:hover .dropbtn {
background-color: #555;
color: white;
}

.dropdown-content a:hover {
background-color: #ddd;
color: black;
}

.dropdown:hover .dropdown-content {
display: block;
}
.dropdown-content:hover .dropdown-submenu {
display: block;
}
@media screen and (max-width: 600px) {
.topnav a:not(:first-child), .dropdown .dropbtn {
 display: none;
}
.topnav a.icon {
 float: right;
 display: block;
}
}

@media screen and (max-width: 600px) {
.topnav.responsive {position: relative;}
.topnav.responsive .icon {
 position: absolute;
 right: 0;
 top: 0;
}
.topnav.responsive a {
 float: none;
 display: block;
 text-align: left;
}
.topnav.responsive .dropdown {float: none;}
.topnav.responsive .dropdown-content {position: relative;}
.topnav.responsive .dropdown .dropbtn {
 display: block;
 width: 100%;
 text-align: left;
}
}

 <div class="topnav" id="myTopnav">
<a href="#home" class="active">Home</a>
<a href="#news">News</a>
<a href="#contact">Contact</a>
<div class="dropdown">
 <button class="dropbtn">Dropdown
   <i class="fa fa-caret-down"></i>
 </button>
 <div class="dropdown-content">
   <a href="#">Link 1</a>
       <div class="dropdown-submenu">

   <a href="#">Link 2</a></div>
   <a href="#">Link 3</a>
 </div>
</div>
<a href="#about">About</a>
<a href="javascript:void(0);" style="font-size:15px;" class="icon" onclick="myFunction()">☰</a>
</div>

</code>```

答: your issue seems to be with the .dropdown-content:hover .dropdown-submenu  { display: block; } part, when you're hovering over 'Link 3', you're still hovering over .dropdown-content

Title: multi level drop down menu with css

Body:
i want to add multi level dropdown to that w3schools menu.
https://www.w3schools.com/howto/howto_js_responsive_navbar_dropdown.asp
it looks like
original w3schools menu
i tried to make it multi level as you can see.
multi level drop down photo 1
multi level drop down photo 2

My problem is as you can see in the photos; multi level does not close when you are another level. can you fix that ?

   Home
   News
   Contact

     <button class="dropbtn">Dropdown

     </button>

       Link 1
       Link 2
       Link 3

   About
   ☰

 `/* Add a black background color to the top navigation */
 .topnav {
   background-color: #333;
   overflow: hidden;
 }

 /* Style the links inside the navigation bar */
 .topnav a {
   float: left;
   display: block;
   color: #f2f2f2;
   text-align: center;
   padding: 14px 16px;
   text-decoration: none;
   font-size: 17px;
 }

 /* Add an active class to highlight the current page */
 .active {
   background-color: #04AA6D;
   color: white;
 }

 /* Hide the link that should open and close the topnav on small screens */
 .topnav .icon {
   display: none;
 }

 /* Dropdown container - needed to position the dropdown content */
 .dropdown {
   float: left;
   overflow: hidden;
 }

 /* Style the dropdown button to fit inside the topnav */
 .dropdown .dropbtn {
   font-size: 17px;
   border: none;
   outline: none;
   color: white;
   padding: 14px 16px;
   background-color: inherit;
   font-family: inherit;
   margin: 0;
 }

 /* Style the dropdown content (hidden by default) */
 .dropdown-content {
   display: none;
   position: absolute;
   background-color: #f9f9f9;
   min-width: 160px;
   box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
   z-index: 1;
 }

 /* Style the links inside the dropdown */
 .dropdown-content a {
   float: none;
   color: black;
   padding: 12px 16px;
   text-decoration: none;
   display: block;
   text-align: left;
 }

 /* Add a dark background on topnav links and the dropdown button on hover */
 .topnav a:hover, .dropdown:hover .dropbtn {
   background-color: #555;
   color: white;
 }

 /* Add a grey background to dropdown links on hover */
 .dropdown-content a:hover {
   background-color: #ddd;
   color: black;
 }

 /* Show the dropdown menu when the user moves the mouse over the dropdown button */
 .dropdown:hover .dropdown-content {
   display: block;
 }

 /* When the screen is less than 600 pixels wide, hide all links, except for the first one ("Home"). Show the link that contains should open and close the topnav (.icon) */
 @media screen and (max-width: 600px) {
   .topnav a:not(:first-child), .dropdown .dropbtn {
     display: none;
   }
   .topnav a.icon {
     float: right;
     display: block;
   }
 }

 /* The "responsive" class is added to the topnav with JavaScript when the user clicks on the icon. This class makes the topnav look good on small screens (display the links vertically instead of horizontally) */
 @media screen and (max-width: 600px) {
   .topnav.responsive {position: relative;}
   .topnav.responsive a.icon {
     position: absolute;
     right: 0;
     top: 0;
   }
   .topnav.responsive a {
     float: none;
     display: block;
     text-align: left;
   }
   .topnav.responsive .dropdown {float: none;}
   .topnav.responsive .dropdown-content {position: relative;}
   .topnav.responsive .dropdown .dropbtn {
     display: block;
     width: 100%;
     text-align: left;
   }
 }

i changed it like this;

.topnav {
overflow: hidden;
background-color: #333;
}

.topnav a {
float: left;
display: block;
color: #f2f2f2;
text-align: center;
padding: 14px 16px;
text-decoration: none;
font-size: 17px;
}

.active {
background-color: #04AA6D;
color: white;
}

.topnav .icon {
display: none;
}

.dropdown {
float: left;
overflow: hidden;
}

.dropdown .dropbtn {
font-size: 17px;
border: none;
outline: none;
color: white;
padding: 14px 16px;
background-color: inherit;
font-family: inherit;
margin: 0;
}

.dropdown-content {
display: none;
position: absolute;
background-color: #f9f9f9;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
z-index: 1;
}
.dropdown-submenu {
display: none;
position: absolute;
background-color: #f9f9f9;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
z-index: 1;
top: 0;
left: 100%
}

.dropdown-content a {
float: none;
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
text-align: left;
}

.topnav a:hover, .dropdown:hover .dropbtn {
background-color: #555;
color: white;
}

.dropdown-content a:hover {
background-color: #ddd;
color: black;
}

.dropdown:hover .dropdown-content {
display: block;
}
.dropdown-content:hover .dropdown-submenu {
display: block;
}
@media screen and (max-width: 600px) {
.topnav a:not(:first-child), .dropdown .dropbtn {
 display: none;
}
.topnav a.icon {
 float: right;
 display: block;
}
}

@media screen and (max-width: 600px) {
.topnav.responsive {position: relative;}
.topnav.responsive .icon {
 position: absolute;
 right: 0;
 top: 0;
}
.topnav.responsive a {
 float: none;
 display: block;
 text-align: left;
}
.topnav.responsive .dropdown {float: none;}
.topnav.responsive .dropdown-content {position: relative;}
.topnav.responsive .dropdown .dropbtn {
 display: block;
 width: 100%;
 text-align: left;
}
}

Home
News
Contact

 <button class="dropbtn">Dropdown

 </button>

   Link 1

   Link 2

   Link 3

About
☰


问:
which tools we use for implementing Sybil attack simulation in VANEt
I want to know which and how many simulation tools we need to implement a Sybil attack in VANET. I read some where SUMO alone is enough but most of people recommend to use combination of SUMO, Omnet++ and Veins. What will be the instructions and data flow here?</p>

答:
In Sybil attack, an intruder tries to acquire a number of legible nodeIds, which appear and function as a set of distinct nodes.

Sumo alone may not suffice for the purpose of simulating Sybil attack as it can only generate node movements. The properties of the nodes can be customised using veins that's available as a project in omnet++ framework.

Try learning by following the steps given on veins.car2x.org about using veins. TraciDemo11p is a sample application available inside veins project.

Happy learning


问:
is "

is not correct because "text/javascript" is not a valid MIME type and he states "application/javascript" is a valid MIME type.

I only care about serving HTML5 as the doctype.

Where are the MIME types for

答:
I think Brandon is (at least) partially wrong.  The latest editor's draft of HTML5 (15 Aug 2011) says:

The type attribute gives the language of the script or format of the
  data. If the attribute is present, its value must be a valid MIME
  type. The charset parameter must not be specified. The default, which
  is used if the attribute is absent, is "text/javascript".

So if you do not include a type attribute, the default value is "text/javascript".  If that is the default value, it must be a valid MIME type.

What are the other valid MIME types?  The spec doesn't seem to give an example list, but it does specify the required format when it says:

A string is a valid MIME type if it matches the media-type rule
  defined in section 3.7 "Media Types" of RFC 2616

Which you can have the joy of reading here:

http://www.ietf.org/rfc/rfc2616.txt

Edit:  Quentin is right:  For HTML5, there's no need to include a type attribute, assuming you're using Javascript.

Title: is "<script type='text/javascript'>" incorrect?

Body:
On aminutewithbrendan, brendan eich makes an off hand comment implying that serving scripts as

is not correct because "text/javascript" is not a valid MIME type and he states "application/javascript" is a valid MIME type.

I only care about serving HTML5 as the doctype.

Where are the MIME types for


问:
Is there any way to run the following code to get the historical data of the stock
I want to automatically get data from the NSE site link of which I have mentioned in my code. The issue I am facing is that the Get Data button on the website is not working with the code and the browser gets stuck without displaying any data thereafter. Moreover, I have written a panda code to get the data on the webpage after filling in all the information but that is also not working.

from selenium import webdriver
import time
import pandas as pd
a=input("Symbol\n")
web=webdriver.Chrome()
web.get('https://www1.nseindia.com/products/content/equities/equities/eq_security.htm')
time.sleep(5)
Data=web.find_element_by_xpath('//*[@id="dataType"]/option[1]')
Data.click()
Symbol=web.find_element_by_xpath('//*[@id="symbol"]')
Symbol.send_keys(a)
Month=web.find_element_by_xpath('//*[@id="dateRange"]/option[8]')
Month.click()
time.sleep(2)
Go=web.find_element_by_xpath('//*[@id="get"]')
Go.click()
df=pd.read_html('https://www1.nseindia.com/products/content/equities/equities/eq_security.htm')
print(df[0])
```

答:
This works fine for me by using java script executor</p>
```<code>from selenium import webdriver
import time, warnings

a=input("Symbol: ")

warnings.filterwarnings("ignore", category=DeprecationWarning)
options = webdriver.ChromeOptions()
options.add_experimental_option("excludeSwitches", ["enable-logging"])

driver = webdriver.Chrome(options=options)
driver.get('https://www1.nseindia.com/products/content/equities/equities/eq_security.htm')

time.sleep(5)

Data = driver.find_element_by_xpath('//*[@id="dataType"]/option[1]')
Data.click()

Symbol = driver.find_element_by_xpath('//*[@id="symbol"]')
Symbol.send_keys(a)

Month = driver.find_element_by_xpath('//*[@id="dateRange"]/option[8]')
Month.click()

time.sleep(2)

driver.execute_script("javascript:document.getElementById('submitMe').click()")
#driver.execute_script("javascript:submitData();") ## this one also works
</code>```

Body:
This works fine for me by using java script executor

from selenium import webdriver
import time, warnings

a=input("Symbol: ")

warnings.filterwarnings("ignore", category=DeprecationWarning)
options = webdriver.ChromeOptions()
options.add_experimental_option("excludeSwitches", ["enable-logging"])

driver = webdriver.Chrome(options=options)
driver.get('https://www1.nseindia.com/products/content/equities/equities/eq_security.htm')

time.sleep(5)

Data = driver.find_element_by_xpath('//*[@id="dataType"]/option[1]')
Data.click()

Symbol = driver.find_element_by_xpath('//*[@id="symbol"]')
Symbol.send_keys(a)

Month = driver.find_element_by_xpath('//*[@id="dateRange"]/option[8]')
Month.click()

time.sleep(2)

driver.execute_script("javascript:document.getElementById('submitMe').click()")
#driver.execute_script("javascript:submitData();") ## this one also works


问:
Python if...in.. statement. Check for vowel in word
I'm trying to check if the user input contains a vowel or not. However, I've only found how to check for one vowel at a time, but  not all.

```<code>vowel = ("a")

word = input("type a word: ")

if vowel in word:
 print (f"There is the vowel {vowel} in your word")
else:
 print ("There is no vowel in your word")
</code>```

This seems to work but I get a error if I try to make the vowel variable into a list. ["a","e","i","o","u"]

any ideas how to check for e i o u at the same time?

答:
If you do not need to know which vowels are present, you can use any as follows.

```<code>vowels = ("a", "e", "i", "o", "u")

word = input("type a word: ")

if any(v in word for v in vowels):
    print("There is at least one vowel in your word.")
else:
    print("There is no vowel in your word.")
</code>```

Body:
I'm trying to check if the user input contains a vowel or not. However, I've only found how to check for one vowel at a time, but  not all.

vowel = ("a")

word = input("type a word: ")

if vowel in word:
 print (f"There is the vowel {vowel} in your word")
else:
 print ("There is no vowel in your word")

This seems to work but I get a error if I try to make the vowel variable into a list. ["a","e","i","o","u"]

any ideas how to check for e i o u at the same time?

Body:
If you do not need to know which vowels are present, you can use any as follows.

vowels = ("a", "e", "i", "o", "u")

word = input("type a word: ")

if any(v in word for v in vowels):
    print("There is at least one vowel in your word.")
else:
    print("There is no vowel in your word.")


问:
Why does an h1 tag inside a body tag pushes the body tag down, resulting in a scrollbar showing up?
Why in this snipped the scrollbar shows up?

I see that body is 100% tall as indicated by CSS, but it is not positioned at the top of the page. Instead, the margin from the h1 tag is pushing body down by that amount, resulting in the scrollbar because the body does not fit in the page.

html, body {
  margin: 0;
  padding: 0;
  height: 100%;
}

.root {
  height: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class='root'>
<h1>Test</h1>
</div></code>```

My question is.. if the margin is in the h1 tag and h1 is inside body, why does body get pushed down and the scrollbar shows up?

答:
You have a couple of options:

set margin on h1 to 0

set overflow to hidden on body

remove height:100% from body and html

The snippet below does all three but any 1 will work

html, body {
  margin: 0;
  padding: 0;
  overflow:hidden;
 }

.root {
  height: 100%;
}

h1{margin:0;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class='root'>
<h1>Test</h1>
</div></code>```

Body:
Why in this snipped the scrollbar shows up?

I see that body is 100% tall as indicated by CSS, but it is not positioned at the top of the page. Instead, the margin from the h1 tag is pushing body down by that amount, resulting in the scrollbar because the body does not fit in the page.

html, body {
  margin: 0;
  padding: 0;
  height: 100%;
}

.root {
  height: 100%;
}

Test

My question is.. if the margin is in the h1 tag and h1 is inside body, why does body get pushed down and the scrollbar shows up?

Body:
You have a couple of options:

set margin on h1 to 0

set overflow to hidden on body

remove height:100% from body and html

The snippet below does all three but any 1 will work

html, body {
  margin: 0;
  padding: 0;
  overflow:hidden;
 }

.root {
  height: 100%;
}

h1{margin:0;}

<div class='root'>
<h1>Test</h1>
</div>


问:
How can I pass my Facebook access token that I got in JS SDK to my PHP script?
I have a functional facebook application that use the JS SDK. I can use the JS SDK to get my users facebook ID and access token, and it seem to work fine. However, my JS script need to call some server side PHP code via JQuery AJAX, in order to make some server side related operations... but i still need an access to my user's access token on the PHP code as well.
On the official facebook documentation of the PHP SDK, i saw the following:

The Facebook SDK for PHP can work in conjunction with the Facebook SDK for Javascript to provide seamless session management across both the client and server-sides of an app.

To enable this functionality, ensure that when you embed and initialize the JS SDK, you set both the status and the cookie parameters of the object passed to FB.init() to true.

I followed the exact instructions as written above, but it looks like my PHP code fails to get the user's facebook ID and access token after I initialize my facebook PHP object.

What do I miss? i don't understand it, because by what the documentation say, my user's access token should be passed automatically to the PHP SDK using a cookie.

Should it be done in some other way?

Thanks!

答:
You can still pass the access token obtained from js-SDK to PHP along with your ajax request and use it with the PHP.</p>
```<code><script>
  // This is called with the results from from FB.getLoginStatus().
  function statusChangeCallback(response) {
    console.log(response);

    if (response.status === 'connected') {
      // Logged into your app and Facebook.
     // testAPI();
      var accessToken = response.authResponse.accessToken;
        console.log(accessToken);

       //ajax call to PHP **************************************************************
       //*******************************************************************************
       $.get("/ajaxpage.php?token="+accessToken+"&uid="+response.authResponse.userID,"",function(data){
           // on reply from the server
       });

    } else if (response.status === 'not_authorized') {
      // The person is logged into Facebook, but not your app.

    } else {
      // The person is not logged into Facebook.
    }
  }

  // This function is called when someone finishes with the Login
  // Button.  See the onlogin handler attached to it in the sample
  // code below.
  function checkLoginState() {
    FB.getLoginStatus(function(response) {
      statusChangeCallback(response);
    });
  }

  window.fbAsyncInit = function() {
    FB.init({
      appId: '..................',
      cookie: true, // enable cookies to allow the server to access the session
      xfbml: true, // parse social plugins on this page
      version: 'v2.2' // use version 2.2
    });

    FB.getLoginStatus(function(response) {
      statusChangeCallback(response);
    });

  };

  // Load the SDK asynchronously
  (function(d, s, id) {
    var js, fjs = d.getElementsByTagName(s)[0];
    if (d.getElementById(id)) return;
    js = d.createElement(s);
    js.id = id;
    js.src = "//connect.facebook.net/en_US/sdk.js";
    fjs.parentNode.insertBefore(js, fjs);
  }(document, 'script', 'facebook-jssdk'));

 <fb:login-button scope="public_profile,email" onlogin="checkLoginState();">
 </fb:login-button>
</code>```

Body:
You can still pass the access token obtained from js-SDK to PHP along with your ajax request and use it with the PHP.

<script>
  // This is called with the results from from FB.getLoginStatus().
  function statusChangeCallback(response) {
    console.log(response);

    if (response.status === 'connected') {
      // Logged into your app and Facebook.
     // testAPI();
      var accessToken = response.authResponse.accessToken;
        console.log(accessToken);

       //ajax call to PHP **************************************************************
       //*******************************************************************************
       $.get("/ajaxpage.php?token="+accessToken+"&uid="+response.authResponse.userID,"",function(data){
           // on reply from the server
       });

    } else if (response.status === 'not_authorized') {
      // The person is logged into Facebook, but not your app.

    } else {
      // The person is not logged into Facebook.
    }
  }

  // This function is called when someone finishes with the Login
  // Button.  See the onlogin handler attached to it in the sample
  // code below.
  function checkLoginState() {
    FB.getLoginStatus(function(response) {
      statusChangeCallback(response);
    });
  }

  window.fbAsyncInit = function() {
    FB.init({
      appId: '..................',
      cookie: true, // enable cookies to allow the server to access the session
      xfbml: true, // parse social plugins on this page
      version: 'v2.2' // use version 2.2
    });

    FB.getLoginStatus(function(response) {
      statusChangeCallback(response);
    });

  };

  // Load the SDK asynchronously
  (function(d, s, id) {
    var js, fjs = d.getElementsByTagName(s)[0];
    if (d.getElementById(id)) return;
    js = d.createElement(s);
    js.id = id;
    js.src = "//connect.facebook.net/en_US/sdk.js";
    fjs.parentNode.insertBefore(js, fjs);
  }(document, 'script', 'facebook-jssdk'));

 <fb:login-button scope="public_profile,email" onlogin="checkLoginState();">
 </fb:login-button>