问:
How to fix 'Minified React Error - Hydration failed because the initial UI does not match what was rendered on the server ' - Vue/Vite
I am using a VueJS/Vite template from this repo: https://github.com/Digitalmvps/ShopifyVue/issues/new

And for the life of me I cannot figure out why I am getting this error.

Where could it be happening? I've tried removing all HTML from index/app.vue but nothing works?

Any ideas? Could it be one of the dependencies?

package.json

{
  "name": "vue-typescript-template",
  "private": true,
  "version": "0.0.0",
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "preview": "vite preview",
    "debug": "node --inspect-brk server/index.js",
    "serve:dev": "npm run build && cross-env NODE_ENV=development nodemon server/index.js --watch ./server",
    "prepare": "husky install",
    "preserve": "npm run build",
    "serve": "npm run build && cross-env NODE_ENV=production node server/index.js",
    "start": "npm run serve",
    "test": "vitest --reporter=verbose"
  },
  "dependencies": {
    "@originjs/vite-plugin-require-context": "^1.0.9",
    "@shopify/app-bridge-utils": "^3.1.2",
    "@shopify/shopify-api": "^3.0.0",
    "axios": "^0.27.2",
    "compression": "^1.7.4",
    "cookie-parser": "^1.4.6",
    "cross-env": "^7.0.3",
    "dotenv": "^16.0.0",
    "express": "^4.18.1",
    "graphql": "^16.5.0",
    "sass": "^1.53.0",
    "serve-static": "^1.14.1",
    "vite-plugin-dynamic-import": "^0.1.1",
    "vue": "^3.2.37",
    "vue-class-component": "^8.0.0-0",
    "vue-meta": "^3.0.0-alpha.7",
    "vue-router": "^4.0.0-0",
    "vue3-runtime-template": "^1.0.1",
    "vuex": "^4.0.0-0"
  },
  "devDependencies": {
    "@vitejs/plugin-vue": "^3.0.0",
    "autoprefixer": "^10.4.7",
    "husky": "^7.0.4",
    "nodemon": "^2.0.16",
    "postcss": "^8.4.14",
    "supertest": "^6.2.3",
    "tailwindcss": "^3.1.6",
    "typescript": "^4.6.4",
    "vite": "^3.0.0",
    "vitest": "^0.10.5",
    "vue-tsc": "^0.38.4"
  }
}

```


来源: stackexchange

问:
How to find Organisation URN in Linkedin API?
I am running a page in Linkedin. I can able to find urn:li:person:XXXXXX using API. And I want to know how to find urn:li:organisation:YYYY ? Please help me.

Thanks.

ContentLicense: CC BY-SA 4.0


问:
Not able to dismiss "open application" confirmation window Dialog using Puppeteer
I am creating small node.js script to open Zoom meeting in browser using Puppeteer.

I am able to open but not able to dismiss confirmation dialog to open meeting in browser as I dont want to open Desktop Zoom app.

How can I get rid of this confirmation dialog box?

```<code>import puppeteer from 'puppeteer';

(async () => {
    const browser = await puppeteer.launch({ headless: false });
    const page = await browser.newPage();
    page.on('dialog', async dialog => {
        console.log('alok', dialog.message());
        await dialog.dismiss();
        await browser.close();
    });
    await page.goto('https://us04web.zoom.us/j/74468563733?pwd=tdvfpLvoL_ktFwO-5reV36kjicgBBx.1');

    // await browser.close();
})();
</code>```

Body:
I am creating small node.js script to open Zoom meeting in browser using Puppeteer.

I am able to open but not able to dismiss confirmation dialog to open meeting in browser as I dont want to open Desktop Zoom app.

How can I get rid of this confirmation dialog box?

import puppeteer from 'puppeteer';

(async () => {
    const browser = await puppeteer.launch({ headless: false });
    const page = await browser.newPage();
    page.on('dialog', async dialog => {
        console.log('alok', dialog.message());
        await dialog.dismiss();
        await browser.close();
    });
    await page.goto('https://us04web.zoom.us/j/74468563733?pwd=tdvfpLvoL_ktFwO-5reV36kjicgBBx.1');

    // await browser.close();
})();


问:
How can I add 1 in the beginning of a numpy array?
I have a numpy array X = [[3 4 5 6] [6 5 3 3] [9 8 5 2]]

I would like to add 1 in each array like so:

X = [[1 3 4 5 6] [1 6 5 3 3] [1 9 8 5 2]]

I wanted to do it using np.ones() and np.hstack()

This is what I tried to do

```<code>X = [[3 4 5 6] [6 5 3 3] [9 8 5 2]]
ones = np.ones(len(X))
X = np.hstack((ones, X))
</code>```

Body:
I have a numpy array X = [[3 4 5 6] [6 5 3 3] [9 8 5 2]]

I would like to add 1 in each array like so:

X = [[1 3 4 5 6] [1 6 5 3 3] [1 9 8 5 2]]

I wanted to do it using np.ones() and np.hstack()

This is what I tried to do

X = [[3 4 5 6] [6 5 3 3] [9 8 5 2]]
ones = np.ones(len(X))
X = np.hstack((ones, X))


问:
CHUNKING an audio signal with python
when i chunk an audio file (Sine wave in this case) the sound changes!

i want to stream out an audio signal (a sine wave). first of all i tried streaming the whole original Signal

```<code>import numpy as np
import pyaudio as py
from scipy.io.wavfile import read

fs, y = read('Sinus_440Hz.wav')

p = py.PyAudio()

stream = p.open(format=p.get_format_from_width(y.dtype.itemsize),
                      channels=1,
                      rate=fs,
                      output=True,
                      frames_per_buffer=1024)

stream.write(y)              #Output 1 to 1 Original Sound  (WORKS FINE)

stream.stop_stream()
stream.close()
py.terminate()

</code>```

this works fine and i hear the original sine wave without any artefacts or modifications.

i need to treat the data in Chunks and then stream it out. i did it this way

```<code>import numpy as np
import pyaudio as py
from scipy.io.wavfile import read

fs, y = read('Sinus_440Hz.wav')

totalSamps = len(y)
sample = 128
seg = 0

p = py.PyAudio()

stream = p.open(format=p.get_format_from_width(y.dtype.itemsize),
                      channels=1,
                      rate=fs,
                      output=True,
                      frames_per_buffer=1024)

while True:
     inds = 1 + np.mod((np.arange(sample) + sample * seg), totalSamps) # Chunks of 128
     Output = y[inds]
     stream.write(Output)    # Signal is not the same and have a lot of artefacts!!
     seg = seg + 1

stream.stop_stream()
stream.close()
py.terminate()

</code>```

i didnt alter the signal yet and the sound of the sine wave has already changed

Why am i getting this signal changed although i didnt modifie anything yet? im just splitting it in Chunks
and stream it out.

Thanks in advance!

Title: CHUNKING an audio signal with python

Body:
when i chunk an audio file (Sine wave in this case) the sound changes!

i want to stream out an audio signal (a sine wave). first of all i tried streaming the whole original Signal

import numpy as np
import pyaudio as py
from scipy.io.wavfile import read

fs, y = read('Sinus_440Hz.wav')

p = py.PyAudio()

stream = p.open(format=p.get_format_from_width(y.dtype.itemsize),
                      channels=1,
                      rate=fs,
                      output=True,
                      frames_per_buffer=1024)

stream.write(y)              #Output 1 to 1 Original Sound  (WORKS FINE)

stream.stop_stream()
stream.close()
py.terminate()

this works fine and i hear the original sine wave without any artefacts or modifications.

i need to treat the data in Chunks and then stream it out. i did it this way

import numpy as np
import pyaudio as py
from scipy.io.wavfile import read

fs, y = read('Sinus_440Hz.wav')

totalSamps = len(y)
sample = 128
seg = 0

p = py.PyAudio()

stream = p.open(format=p.get_format_from_width(y.dtype.itemsize),
                      channels=1,
                      rate=fs,
                      output=True,
                      frames_per_buffer=1024)

while True:
     inds = 1 + np.mod((np.arange(sample) + sample * seg), totalSamps) # Chunks of 128
     Output = y[inds]
     stream.write(Output)    # Signal is not the same and have a lot of artefacts!!
     seg = seg + 1

stream.stop_stream()
stream.close()
py.terminate()

i didnt alter the signal yet and the sound of the sine wave has already changed

Why am i getting this signal changed although i didnt modifie anything yet? im just splitting it in Chunks
and stream it out.

Thanks in advance!


问:
Zoom deep linking from the web or browser
We are developing a browser-based web application. That application enables the user to populate a profile, including having a “call me”, “message me” and “schedule a meeting” buttons.

We have integrated with MS Teams, so that if the person is connected with their Microsoft account, then their “call me” button opens MS Teams application and starts a call with that user. Message me opens a chat with that user, and schedule a meeting opens Outlook calendar with that user’s Microsoft email pre-populated in the “To” field. We have achieved that by using the following MS Teams deep links:

Call: https://teams.microsoft.com/l/call/0/0?users=<user1>,<user2>

Chat: https://teams.microsoft.com/l/chat/0/0?users=<user1>,<user2>,...&topicName=<chat name>&message=<precanned text>

Schedule a meeting: https://teams.microsoft.com/l/meeting/new?subject=<meeting subject>&startTime=<date>&endTime=<date>&content=<content>&attendees=<user1>,<user2>,<user3>,...

Now we want to implement a Zoom integration. However, I couldn’t find Zoom deep links that would directly open a chat/call/calendar with a given contact. I am happy with the fact that the zoommtg protocol opens Zoom application all right, but what do I pass to that protocol to make the above happen?


问:
Not able to access deployment from external network kubernetes
I am new to Kubernetes and have a limited understanding of the Kubernetes networking part.
problem context:

Minikube installed on VM (RHEL 8) [minikube start --driver=docker]

under minikube node have a deployment with the service (type: nodePort) with port mapping as 8008:30000
(refer to screenshot)

so now the confusion is I am able to access the application (in deployment) using curl < node-ip>:< node-port> inside the VM (x.y.z.w), but while trying to access from my external network, using URL as x.y.z.w:30000, I am not able to, what am I missing here?

or do I need to use ingress (with Nginx) here?


问:
Form groups using block random assignment on two covariates
I often have groups of people who differ in their nationality and their status. They have to work in groups, and I would like to use block random assignment to create groups of a maximum of 5 individuals. Each group should have at least one person who is "foreign" and one who is "female". I have found the library randomizr which is supposedly able to do block random assignments, but my code does not work as intended.

An example dataset would be:

```<code>structure(list(Student = c("Susan", "Ciara", "Carl",
"Paula", "Emil", "Tammy", "Logan", "Anna", "Victor",
"Felix", "Federica", "Jesus", "Jens", "Samira", "Berit", "Yi",
"Lea", "Gordon", "Boris", "Silvester", "Celine", "Thomas", "Eduardo",
"RoY", "Marlene", "Amelie", "Claudius", "Herbert", "Cynthia", "Melanie",
"Leander", "Leona", "Tobias", "Leander", "Peter",
"Lilly", "Roxy", "Joachim"), Nationality = structure(c(2L, 2L,
1L, 1L, 2L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 1L,
1L, 1L, 2L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 2L, 2L, 1L,
1L, 1L, 2L, 2L), levels = c("Non-foreign", "Foreign"), class = "factor"),
    Gender = structure(c(1L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L,
    2L, 1L, 2L, 2L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 1L, 2L, 2L, 2L,
    1L, 1L, 2L, 2L, 1L, 1L, 2L, 1L, 2L, 2L, 2L, 1L, 1L, 2L), levels = c("female",
    "male"), class = "factor")), class = "data.frame", row.names = c(NA,
-38L))
</code>```

UPDATE: I have carefully read the vignette for the randomzir package again. I found that it is possible to create blocks with more than 1 covariate. I am now looking to see if i can assign these blocks to the students to get block random groups. I need to test if the code below works as intended.

```<code>blocks <- with(data, paste(Nationality, Gender, sep = "_"))
Z <- block_ra(blocks = blocks, num_arms = 6)
table(data$Student, Z)
</code>```

Body:
I often have groups of people who differ in their nationality and their status. They have to work in groups, and I would like to use block random assignment to create groups of a maximum of 5 individuals. Each group should have at least one person who is "foreign" and one who is "female". I have found the library randomizr which is supposedly able to do block random assignments, but my code does not work as intended.

An example dataset would be:

structure(list(Student = c("Susan", "Ciara", "Carl",
"Paula", "Emil", "Tammy", "Logan", "Anna", "Victor",
"Felix", "Federica", "Jesus", "Jens", "Samira", "Berit", "Yi",
"Lea", "Gordon", "Boris", "Silvester", "Celine", "Thomas", "Eduardo",
"RoY", "Marlene", "Amelie", "Claudius", "Herbert", "Cynthia", "Melanie",
"Leander", "Leona", "Tobias", "Leander", "Peter",
"Lilly", "Roxy", "Joachim"), Nationality = structure(c(2L, 2L,
1L, 1L, 2L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 1L,
1L, 1L, 2L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 2L, 2L, 1L,
1L, 1L, 2L, 2L), levels = c("Non-foreign", "Foreign"), class = "factor"),
    Gender = structure(c(1L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L,
    2L, 1L, 2L, 2L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 1L, 2L, 2L, 2L,
    1L, 1L, 2L, 2L, 1L, 1L, 2L, 1L, 2L, 2L, 2L, 1L, 1L, 2L), levels = c("female",
    "male"), class = "factor")), class = "data.frame", row.names = c(NA,
-38L))

UPDATE: I have carefully read the vignette for the randomzir package again. I found that it is possible to create blocks with more than 1 covariate. I am now looking to see if i can assign these blocks to the students to get block random groups. I need to test if the code below works as intended.

blocks <- with(data, paste(Nationality, Gender, sep = "_"))
Z <- block_ra(blocks = blocks, num_arms = 6)
table(data$Student, Z)


问:
Unable to upgrade tflite-support.task to latest version
While trying to perform object detection on raspberry pi I need tflite-support.task library which is present in version greater than 0.4 but I am unable to upgrade it.
 ERROR: Could not find a version that satisfies the requirement tflite-support==0.4 (from versions: 0.1.0a0.dev3, 0.1.0a0.dev4, 0.1.0a0.dev5, 0.1.0a0, 0.1.0a1) ERROR: No matching distribution found for tflite-support==0.4

I tried upgrading it using pip but it was of no help. I am currently having python3.9.2 and raspberry pi OS version 11.


问:
R & Lubridate: how to set time zone when importing csv file
I'm trying to import a csv file as an R dataframe where one of the columns is a string representing a date-time. I can't get the time zone component to set correctly.

This code works when I don't explicitly set the time zone:

```<code>example2 <- read_csv("NAME, TRNSCO, ID, DPMNEM, DATE, PEAK
                 BEC,EGSI,1062,SERP,10/12/2022 18:00,6.464
                 BEC,EGSI,1072,SPTR,10/30/2022 22:00,67.456
                 BEC,EGSI,1152,DYNE,10/24/2022 12:00,4.606
                 CLA,ELI,3023,FRMR,10/12/2022 17:00,6.352
                 CLA,ELI,3043,SHON,10/19/2022 8:00,2.296
                 CLA,ELI,3063,BERN,10/20/2022 7:00,5.232",
            col_types = cols_only(
              NAME = col_character(),
              ID =  col_character(),
              DPMNEM = col_character(),
              DATE = col_datetime(format = "%m/%d/%Y %H:%M"),
              PEAK = col_double()))
</code>```

And this code works:

```<code>parse_datetime("10/12/2022 18:00", format = "%m/%d/%Y %H:%M",
           locale = locale(tz = "US/Central"))
</code>```

But fails when I try to put it all together:

```<code>example3 <- read_csv("NAME, TRNSCO, ID, DPMNEM, DATE, PEAK
                 BEC,EGSI,1062,SERP,10/12/2022 18:00,6.464
                  BEC,EGSI,1072,SPTR,10/30/2022 22:00,67.456
                 BEC,EGSI,1152,DYNE,10/24/2022 12:00,4.606
                 CLA,ELI,3023,FRMR,10/12/2022 17:00,6.352
                 CLA,ELI,3043,SHON,10/19/2022 8:00,2.296
                 CLA,ELI,3063,BERN,10/20/2022 7:00,5.232",
                 col_types = cols_only(
                   NAME = col_character(),
                   ID =  col_character(),
                   DPMNEM = col_character(),
                   DATE = col_datetime(format = "%m/%d/%Y %H:%M", locale = locale(tz = "US/Central")),
                   PEAK = col_double()))
</code>```

I get this error message:

Error in col_datetime(format = "%m/%d/%Y %H:%M", locale = locale(tz = "US/Central")) :
unused argument (locale = locale(tz = "US/Central"))

I've tried variations of the tz parameter with no luck, e.g.:

```<code>DATE = col_datetime(format = "%m/%d/%Y %H:%M", tz = "US/Central"),
</code>```

Also, how can I extract the tz component from datetime datetime column?

Thanks for the help.

Body:
I'm trying to import a csv file as an R dataframe where one of the columns is a string representing a date-time. I can't get the time zone component to set correctly.

This code works when I don't explicitly set the time zone:

example2 <- read_csv("NAME, TRNSCO, ID, DPMNEM, DATE, PEAK
                 BEC,EGSI,1062,SERP,10/12/2022 18:00,6.464
                 BEC,EGSI,1072,SPTR,10/30/2022 22:00,67.456
                 BEC,EGSI,1152,DYNE,10/24/2022 12:00,4.606
                 CLA,ELI,3023,FRMR,10/12/2022 17:00,6.352
                 CLA,ELI,3043,SHON,10/19/2022 8:00,2.296
                 CLA,ELI,3063,BERN,10/20/2022 7:00,5.232",
            col_types = cols_only(
              NAME = col_character(),
              ID =  col_character(),
              DPMNEM = col_character(),
              DATE = col_datetime(format = "%m/%d/%Y %H:%M"),
              PEAK = col_double()))

And this code works:

parse_datetime("10/12/2022 18:00", format = "%m/%d/%Y %H:%M",
           locale = locale(tz = "US/Central"))

But fails when I try to put it all together:

example3 <- read_csv("NAME, TRNSCO, ID, DPMNEM, DATE, PEAK
                 BEC,EGSI,1062,SERP,10/12/2022 18:00,6.464
                  BEC,EGSI,1072,SPTR,10/30/2022 22:00,67.456
                 BEC,EGSI,1152,DYNE,10/24/2022 12:00,4.606
                 CLA,ELI,3023,FRMR,10/12/2022 17:00,6.352
                 CLA,ELI,3043,SHON,10/19/2022 8:00,2.296
                 CLA,ELI,3063,BERN,10/20/2022 7:00,5.232",
                 col_types = cols_only(
                   NAME = col_character(),
                   ID =  col_character(),
                   DPMNEM = col_character(),
                   DATE = col_datetime(format = "%m/%d/%Y %H:%M", locale = locale(tz = "US/Central")),
                   PEAK = col_double()))

I get this error message:

Error in col_datetime(format = "%m/%d/%Y %H:%M", locale = locale(tz = "US/Central")) :
unused argument (locale = locale(tz = "US/Central"))

I've tried variations of the tz parameter with no luck, e.g.:

DATE = col_datetime(format = "%m/%d/%Y %H:%M", tz = "US/Central"),

Also, how can I extract the tz component from datetime datetime column?

Thanks for the help.


问:
Python package importing module works in pytest script but not other script
I'm learning how to make a python package and having trouble importing modules from a relative path. I know there are at least two dozen excellent questions/answers on this on SO, and I've spent over an hour going through them to no avail.

Below is an MRE. I'm trying to run the example1.py file and getting the errors as shown. What is confusing to me is that my pytest runs fine, and I have the same imports in example1.py, so I don't understand why it works in pytest but not another script.

Folder structure:

```<code>D:.
└───package
    ├───examples
    │       example1.py
    │
    ├───package
    │   │   module1.py
    │   │   __init__.py
    │   │
    │   └───__pycache__
    │           ...
    │
    └───tests
        │   test_module1.py
        │   __init__.py
        │
        └───__pycache__
                ...
</code>```

module1.py:

```<code>def squared(x):
    return x**2
</code>```

test_module1.py:

```<code>import numpy as np
import pytest

from package.module1 import *

def test_squared():
    x = 4
    expected = 16
    computed = squared(x)
    msg = "fail"
    np.testing.assert_allclose(expected, computed, rtol=2e-2, err_msg=msg)
</code>```

example1.py:

```<code>from package.module1 import *

ans = squared(7)
print(ans)
</code>```

Things I've tried:

I'm on Windows but using Git Bash as a bash terminal. Here is my setup:

```<code>alias py='C:/Users/name/anaconda3/envs/myenv/python.exe'
. C:/Users/name/anaconda3/etc/profile.d/conda.sh
conda activate myenv
</code>```

I can confirm that python works with py -c "print('hello world')", which prints as expected.

Where pwd is the . root as shown above, py package/examples/example1.py returns:

```<code>Traceback (most recent call last):
  File "package/examples/example1.py", line 1, in <module>
    from package.module1 import *
ModuleNotFoundError: No module named 'package'
</code>```

However, running pytest . from the terminal works perfectly and returns:

```<code>============================= test session starts =============================
platform win32 -- Python 3.8.3, pytest-7.2.0, pluggy-1.0.0
rootdir: D:\Documents\_mydocs\Work FDHI
collected 1 item

package\tests\test_module1.py .                                          [100%]

============================== 1 passed in 0.21s ==============================
</code>```

How can I resolve the filepath issue and run example1.py? Why does the same import structure work for the pytest script but not the other script?

Other things I've tried that don't work:

adding __init__.py to "examples" folder ch

changing line 1 in "example1.py" to from .package import module1, which returns ImportError: attempted relative import with no known parent package

Body:
I'm learning how to make a python package and having trouble importing modules from a relative path. I know there are at least two dozen excellent questions/answers on this on SO, and I've spent over an hour going through them to no avail.

Below is an MRE. I'm trying to run the example1.py file and getting the errors as shown. What is confusing to me is that my pytest runs fine, and I have the same imports in example1.py, so I don't understand why it works in pytest but not another script.

Folder structure:

D:.
└───package
    ├───examples
    │       example1.py
    │
    ├───package
    │   │   module1.py
    │   │   __init__.py
    │   │
    │   └───__pycache__
    │           ...
    │
    └───tests
        │   test_module1.py
        │   __init__.py
        │
        └───__pycache__
                ...

module1.py:

def squared(x):
    return x**2

test_module1.py:

import numpy as np
import pytest

from package.module1 import *

def test_squared():
    x = 4
    expected = 16
    computed = squared(x)
    msg = "fail"
    np.testing.assert_allclose(expected, computed, rtol=2e-2, err_msg=msg)

example1.py:

from package.module1 import *

ans = squared(7)
print(ans)

Things I've tried:

I'm on Windows but using Git Bash as a bash terminal. Here is my setup:

alias py='C:/Users/name/anaconda3/envs/myenv/python.exe'
. C:/Users/name/anaconda3/etc/profile.d/conda.sh
conda activate myenv

I can confirm that python works with py -c "print('hello world')", which prints as expected.

Where pwd is the . root as shown above, py package/examples/example1.py returns:

Traceback (most recent call last):
  File "package/examples/example1.py", line 1, in <module>
    from package.module1 import *
ModuleNotFoundError: No module named 'package'

However, running pytest . from the terminal works perfectly and returns:

============================= test session starts =============================
platform win32 -- Python 3.8.3, pytest-7.2.0, pluggy-1.0.0
rootdir: D:\Documents\_mydocs\Work FDHI
collected 1 item

package\tests\test_module1.py .                                          [100%]

============================== 1 passed in 0.21s ==============================

How can I resolve the filepath issue and run example1.py? Why does the same import structure work for the pytest script but not the other script?

Other things I've tried that don't work:

adding __init__.py to "examples" folder ch

changing line 1 in "example1.py" to from .package import module1, which returns ImportError: attempted relative import with no known parent package


问:
how to get only name of specific user from AdminID which has a child of User-ID and which also have different childs that contain name using flutter?
In this image i created and store data on database.

demo data base for better understanding

First i get admin id from login user and i get user id from controller through which a user is created by admin and that contain random id and store user name on data base.

```<code>String idss = DateTime.now().millisecondsSinceEpoch.toString();

  void dbs() {
    final user = FirebaseAuth.instance.currentUser;
    String? numb;
    numb = user?.phoneNumber;
    final dbRefrence = FirebaseDatabase.instance.ref(numb);
    dbRefrence.child(numberss).child(idss).set({
      'name': namess,
      'title': titleController.text.toString(),
      'amount': amoutController.text.toString(),
      'date': DateFormat.yMMMMd().format(dateTime),
      'time': timeOfDay.format(context).toString(),
    }).then((value) {
      TostMessage().tostMessage("Record Added");
    }).onError((FirebaseException error, stackTrace) {
      TostMessage().tostMessage(error.message);
    });
  }

</code>```

But i don't know to fetch only user name from this type of structure.
I know i can fetch data from structure like adminID which has a child userID and hase a user name and other data.
i am fetching data by

```<code>final user = FirebaseAuth.instance.currentUser;
var dbShowRefrence;
String? num;

@override
void initState() {
  super.initState();
  num = user?.phoneNumber;
  dbShowRefrence = FirebaseDatabase.instance.ref(num!).child("name");
}
</code>```

in body

```<code>FirebaseAnimatedList(
  query: dbShowRefrence,
  itemBuilder: (context, snapshot, animation, index) {
    return Card(
      child: ListTile(
        onTap: () {
          Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) => AddAll(
                id,
                customerNameController.text.toString(),
                customerNumberController.text.toString(),
              ),
            ),
          );
        },
        title: Text(snapshot.value.toString()),
        leading: const CircleAvatar(
          child: Icon(Icons.person),
        ),
      ),
    );
  }),
</code>```

Actual data base

data displayed on my mobile.

I don't know to get only name.

Can anyone help me to fetch only name from data base?

Body:
In this image i created and store data on database.

demo data base for better understanding

First i get admin id from login user and i get user id from controller through which a user is created by admin and that contain random id and store user name on data base.

String idss = DateTime.now().millisecondsSinceEpoch.toString();

  void dbs() {
    final user = FirebaseAuth.instance.currentUser;
    String? numb;
    numb = user?.phoneNumber;
    final dbRefrence = FirebaseDatabase.instance.ref(numb);
    dbRefrence.child(numberss).child(idss).set({
      'name': namess,
      'title': titleController.text.toString(),
      'amount': amoutController.text.toString(),
      'date': DateFormat.yMMMMd().format(dateTime),
      'time': timeOfDay.format(context).toString(),
    }).then((value) {
      TostMessage().tostMessage("Record Added");
    }).onError((FirebaseException error, stackTrace) {
      TostMessage().tostMessage(error.message);
    });
  }

But i don't know to fetch only user name from this type of structure.
I know i can fetch data from structure like adminID which has a child userID and hase a user name and other data.
i am fetching data by

final user = FirebaseAuth.instance.currentUser;
var dbShowRefrence;
String? num;

@override
void initState() {
  super.initState();
  num = user?.phoneNumber;
  dbShowRefrence = FirebaseDatabase.instance.ref(num!).child("name");
}

in body

FirebaseAnimatedList(
  query: dbShowRefrence,
  itemBuilder: (context, snapshot, animation, index) {
    return Card(
      child: ListTile(
        onTap: () {
          Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) => AddAll(
                id,
                customerNameController.text.toString(),
                customerNumberController.text.toString(),
              ),
            ),
          );
        },
        title: Text(snapshot.value.toString()),
        leading: const CircleAvatar(
          child: Icon(Icons.person),
        ),
      ),
    );
  }),

Actual data base

data displayed on my mobile.

I don't know to get only name.

Can anyone help me to fetch only name from data base?


问:
How to recreate a nested Eloquent Collection in Laravel 9?
I would like to re-use a Laravel 9 Blade template that I built to display the results of an Eloquent query. But this time I want to fill it with data from an API, so I need to re-create the structure of the Collection to match the Blade template.

Possible solutions:

1. Manually recreate the Collection with the same structure:

```<code>$author1 = ["name" => "John Smith"];
$author2 = ["name" => "Larry White"];
$authors = Collect([$author1, $author2]);
$library1 = ["title" => "City library", "authors" => $authors];
$libraries = Collect([$library1]);

return view('library', compact('libraries'));
</code>```

2. Recreate the Collection using existing model and its relationships:

```<code>$author1 = new Author;
$author1->name = "John Smith";
$author2 = new Author;
$author2->name = "Larry White";
$library1 = new Library;
$library1->title = "City library";
$library1->authors->push($author1);
$library1->authors->push($author2);
$libraries = [$library1];

return view('library', compact('libraries'));
</code>```

Both options don't work and throw error: "name" is not defined on $author->name

library.blade.php:

```<code>@forelse ($libraries as $library)
    <h1>{{ $library->title }}</h1>

    <ul>
    @forelse ($library->authors as $author)
        <li>{{ $author->name}}</li>
    @endforelse
    </ul>

@endforelse
</code>```

Body:
I would like to re-use a Laravel 9 Blade template that I built to display the results of an Eloquent query. But this time I want to fill it with data from an API, so I need to re-create the structure of the Collection to match the Blade template.

Possible solutions:

1. Manually recreate the Collection with the same structure:

$author1 = ["name" => "John Smith"];
$author2 = ["name" => "Larry White"];
$authors = Collect([$author1, $author2]);
$library1 = ["title" => "City library", "authors" => $authors];
$libraries = Collect([$library1]);

return view('library', compact('libraries'));

2. Recreate the Collection using existing model and its relationships:

$author1 = new Author;
$author1->name = "John Smith";
$author2 = new Author;
$author2->name = "Larry White";
$library1 = new Library;
$library1->title = "City library";
$library1->authors->push($author1);
$library1->authors->push($author2);
$libraries = [$library1];

return view('library', compact('libraries'));

Both options don't work and throw error: "name" is not defined on $author->name

library.blade.php:

@forelse ($libraries as $library)

{{ $library->title }}

    @forelse ($library->authors as $author)

{{ $author->name}}

    @endforelse

@endforelse


问:
Clicking the login button always loads the page in new tab - Spring Security
I'm building a website with Spring Security and when I click on the login button on my custom login page, a new tab ALWAYS opens where the user is redirected to Homepage.

I want the login button to redirect to the home page in the same tab.

What I've tried:

Checking if I have set target='_blank' on the form or the button. - No, nowhere!

Manually setting target=_self

Opening from 3 different browsers

It started out of the blue without me seemingly changing any configs or the login page itself.

I guess it could be something non code-related but I can't figure it out.


问:
Linkedin Add to Profile button is not working if not logged in
If user is not loggedin, addtoprofile is directing to a blank page instead of loginpage. Is this the intended behaviour?

[Sample link](https://www.linkedin.com/profile/add?startTask=CERTIFICATION_NAME&name=Test%20Certificate&organizationName=LinkedIn&issueYear
=2018&issueMonth=2&expirationYear=2020&expirationMonth=5&certUrl=https%3A%2F%2Fdocs.
microsoft.com%2Fen-us%2Flearn%2Fcertifications%2Fd365-functional-consultant-sales&certId=1234)

Addtoprofile Documentation


问:
Unable to create a blob in a container
Scenario: unable to deploy a blob within a container tha is created in a storage account, read in as a data source. Obscure error is produced in GitHub actions workflow.

Error:

```<code>Error: creating Blob "xrdpdeploy.sh" (Container "morpheus-tinkering-csecontainer" / Account "***"): opening: open # update available packages

[ERROR] provider.terraform-provider-azurerm_v3.35.0_x5: Response contains error diagnostic: @caller=github.com/hashicorp/terraform-plugin-go@v0.14.1/tfprotov5/internal/diag/diagnostics.go:55 @module=sdk.proto diagnostic_detail= diagnostic_severity=ERROR tf_proto_version=5.3 diagnostic_summary="creating Blob "xrdpdeploy.sh" (Container "morpheus-tinkering-csecontainer" / Account "***"): opening: open # update available packages
</code>```

Hi folks, given the above scenario I am stuck with; do you have any suggestions to help me upload the blob object correct. The terraform config is shown below:

```<code>resource "azurerm_storage_container" "cse_container" {
    name = "${local.naming_prefix}csecontainer"
    storage_account_name = data.azurerm_storage_account.storage_account.name
    container_access_type = "blob"
}

#-------------------------------------------------------------

# storage container blob script used to run as a custom script extension
resource "azurerm_storage_blob" "cse_blob" {
    name = "xrdpdeploy.sh"
    storage_account_name = data.azurerm_storage_account.storage_account.name
    storage_container_name = azurerm_storage_container.cse_container.name
    type = "Block"
    access_tier = "Hot"
    # absolute path to file on local system
    source = file("${path.module}/cse-script/xrdpdeploy.sh")
    #explicit dependency on storage container to be deployed first prior to uploading blobk blob
    depends_on = [
      azurerm_storage_container.cse_container
    ]
}

#-------------------------------------------------------------

data "azurerm_storage_account" "storage_account" {
  name = "morpheuszcit10394"
  resource_group_name = "zimcanit-morpheus-tinkering-rg"
}

#-------------------------------------------------------------

</code>```

I'm using Azure Terraform provider version 3.35.0.

What I've done; ensured the container is being created correctly; explicitly set access tier and  even tried dropping Azure provider version to 3.30.0.

Thanks in advance!

Title: Unable to create a blob in a container

Body:
Scenario: unable to deploy a blob within a container tha is created in a storage account, read in as a data source. Obscure error is produced in GitHub actions workflow.

Error:

Error: creating Blob "xrdpdeploy.sh" (Container "morpheus-tinkering-csecontainer" / Account "***"): opening: open # update available packages

[ERROR] provider.terraform-provider-azurerm_v3.35.0_x5: Response contains error diagnostic: @caller=github.com/hashicorp/terraform-plugin-go@v0.14.1/tfprotov5/internal/diag/diagnostics.go:55 @module=sdk.proto diagnostic_detail= diagnostic_severity=ERROR tf_proto_version=5.3 diagnostic_summary="creating Blob "xrdpdeploy.sh" (Container "morpheus-tinkering-csecontainer" / Account "***"): opening: open # update available packages

Hi folks, given the above scenario I am stuck with; do you have any suggestions to help me upload the blob object correct. The terraform config is shown below:

resource "azurerm_storage_container" "cse_container" {
    name = "${local.naming_prefix}csecontainer"
    storage_account_name = data.azurerm_storage_account.storage_account.name
    container_access_type = "blob"
}

#-------------------------------------------------------------

# storage container blob script used to run as a custom script extension
resource "azurerm_storage_blob" "cse_blob" {
    name = "xrdpdeploy.sh"
    storage_account_name = data.azurerm_storage_account.storage_account.name
    storage_container_name = azurerm_storage_container.cse_container.name
    type = "Block"
    access_tier = "Hot"
    # absolute path to file on local system
    source = file("${path.module}/cse-script/xrdpdeploy.sh")
    #explicit dependency on storage container to be deployed first prior to uploading blobk blob
    depends_on = [
      azurerm_storage_container.cse_container
    ]
}

#-------------------------------------------------------------

data "azurerm_storage_account" "storage_account" {
  name = "morpheuszcit10394"
  resource_group_name = "zimcanit-morpheus-tinkering-rg"
}

#-------------------------------------------------------------

I'm using Azure Terraform provider version 3.35.0.

What I've done; ensured the container is being created correctly; explicitly set access tier and  even tried dropping Azure provider version to 3.30.0.

Thanks in advance!


问:
count work order history for each location with filters
I have a work orders history table that has the following columns. I need to count the number of Need Spares (wo_status=2) work orders that have been Closed (wo_status=4) for each location between a particular date span.

work_order_num
equipment_name
location
wo_status
created_at

55261
Endoscopy
15
5
2022-11-02 09:39:05

55261
Endoscopy
15
3
2022-11-02 09:39:05

55261
Endoscopy
15
4
2022-11-02 09:39:05

55262
Endoscopy
15
5
2022-11-02 09:39:05

55262
Endoscopy
15
3
2022-11-02 09:39:05

55262
Endoscopy
15
2
2022-11-02 09:39:05

55262
Endoscopy
15
2
2022-11-02 09:39:05

55262
Endoscopy
15
4
2022-11-02 09:39:05

55263
Baby Warmer
37
5
2022-11-08 09:39:05

55263
Baby Warmer
37
3
2022-11-08 09:39:05

55263
Baby Warmer
37
4
2022-11-08 09:39:05

55264
Baby Warmer
37
5
2022-11-08 09:39:05

55264
Baby Warmer
37
3
2022-11-08 09:39:05

55264
Baby Warmer
37
2
2022-11-08 09:39:05

55264
Baby Warmer
37
2
2022-11-08 09:39:05

55264
Baby Warmer
37
4
2022-11-08 09:39:05

More Details

Work order number 55261 and 55263 should not be considered as they have been Closed without going into Need Spares status.

Work order number 55262 and 55264 have two rows of wo_status=2 so, it should count only 1 row in each work order. For some reason, there are work orders in my table that have multiple rows with the same work order status.

What I have done so far is

```<code>SELECT d.name district_name,
sum(case when w.`wo_status`='2' then 1 ELSE 0 END) AS need_spares,
sum(case when w.`wo_status`='4' then 1 ELSE 0 END) AS closed
FROM `work_orders_history` w
LEFT JOIN berc_locations l ON w.location=l.ID
LEFT JOIN berc_cities c ON l.city_id=c.ID
LEFT JOIN berc_districts d ON c.district_id=d.ID
WHERE (w.`created_at` BETWEEN '2022-09-19 00:00:00' AND '2022-11-30 00:00:00')
AND w.`wo_status` IN(2,4)
GROUP BY d.`name`
ORDER BY closed DESC
</code>```

The above query is returning me data in the format like this

district_name
need_spares
closed

Mianwali
4
15

Sargodha
17
22

Rawalpindi
19
82

Lahore
17
29

The query is considering work orders like 55261 and 55263 due to which closed count is exceeding from the total number of need spares, and also it is counting all multiple rows (where wo_status=2) instead of treating them as 1 entity. Can someone please help me in fixing this query. Thanks in advance

EDITS

My Expected output

district_name
need_spares
closed

Mianwali
4
3

Sargodha
17
17

Rawalpindi
19
12

Lahore
14
9

The number of Closed work orders should not exceed the Need Spares work orders count if the above-mentioned conditions are considered correctly.

Body:
I have a work orders history table that has the following columns. I need to count the number of Need Spares (wo_status=2) work orders that have been Closed (wo_status=4) for each location between a particular date span.

work_order_num
equipment_name
location
wo_status
created_at

55261
Endoscopy
15
5
2022-11-02 09:39:05

55261
Endoscopy
15
3
2022-11-02 09:39:05

55261
Endoscopy
15
4
2022-11-02 09:39:05

55262
Endoscopy
15
5
2022-11-02 09:39:05

55262
Endoscopy
15
3
2022-11-02 09:39:05

55262
Endoscopy
15
2
2022-11-02 09:39:05

55262
Endoscopy
15
2
2022-11-02 09:39:05

55262
Endoscopy
15
4
2022-11-02 09:39:05

55263
Baby Warmer
37
5
2022-11-08 09:39:05

55263
Baby Warmer
37
3
2022-11-08 09:39:05

55263
Baby Warmer
37
4
2022-11-08 09:39:05

55264
Baby Warmer
37
5
2022-11-08 09:39:05

55264
Baby Warmer
37
3
2022-11-08 09:39:05

55264
Baby Warmer
37
2
2022-11-08 09:39:05

55264
Baby Warmer
37
2
2022-11-08 09:39:05

55264
Baby Warmer
37
4
2022-11-08 09:39:05

More Details

Work order number 55261 and 55263 should not be considered as they have been Closed without going into Need Spares status.

Work order number 55262 and 55264 have two rows of wo_status=2 so, it should count only 1 row in each work order. For some reason, there are work orders in my table that have multiple rows with the same work order status.

What I have done so far is

SELECT d.name district_name,
sum(case when w.`wo_status`='2' then 1 ELSE 0 END) AS need_spares,
sum(case when w.`wo_status`='4' then 1 ELSE 0 END) AS closed
FROM `work_orders_history` w
LEFT JOIN berc_locations l ON w.location=l.ID
LEFT JOIN berc_cities c ON l.city_id=c.ID
LEFT JOIN berc_districts d ON c.district_id=d.ID
WHERE (w.`created_at` BETWEEN '2022-09-19 00:00:00' AND '2022-11-30 00:00:00')
AND w.`wo_status` IN(2,4)
GROUP BY d.`name`
ORDER BY closed DESC

The above query is returning me data in the format like this

district_name
need_spares
closed

Mianwali
4
15

Sargodha
17
22

Rawalpindi
19
82

Lahore
17
29

The query is considering work orders like 55261 and 55263 due to which closed count is exceeding from the total number of need spares, and also it is counting all multiple rows (where wo_status=2) instead of treating them as 1 entity. Can someone please help me in fixing this query. Thanks in advance

EDITS

My Expected output

district_name
need_spares
closed

Mianwali
4
3

Sargodha
17
17

Rawalpindi
19
12

Lahore
14
9

The number of Closed work orders should not exceed the Need Spares work orders count if the above-mentioned conditions are considered correctly.


问:
Rest assured - Create Json file with expected return from an API called internally in test
I'm using rest assured to develop test integrations, inside these there are calls to other microservices.
There are test scenarios where I really wouldn't want to call these microservices and for those cases I would like to simulate the return in a file with the expected json.
Is there any way to do this?</p>


问:
My question is related ajax request. I am new to ajax . So i want to know taht how to pass data in ajax dynamically?
```<code>Below code is of my ajax request where i pass return_id in data which is not dynamic. So how can i pass return id dynamically?
$ ->
  $('#manualShipment').click ->
    $.ajax
      type: 'POST'
      datatype: 'json'
      data:
        return_id: 274588
      url: '/returns/create_shipment_manually'
      success: (data) ->
    $('#manualShipment').disabled = true;
    $('.tracking_detail').show()

</code>```

I tried to take id from view of rails but it won't work. So what would be correct way to pass data dynamically in ajax post request

Body:
Below code is of my ajax request where i pass return_id in data which is not dynamic. So how can i pass return id dynamically?
$ ->
  $('#manualShipment').click ->
    $.ajax
      type: 'POST'
      datatype: 'json'
      data:
        return_id: 274588
      url: '/returns/create_shipment_manually'
      success: (data) ->
    $('#manualShipment').disabled = true;
    $('.tracking_detail').show()

I tried to take id from view of rails but it won't work. So what would be correct way to pass data dynamically in ajax post request


问:
Redirect to app after being connected to a bluetooth from setting page
So, I have created a normal Bluetooth app and I did faced many troubles for trying to connect to a device (Only Bluetooth headphone)from the app programmatically. That's why I thought that I would lead the user to the Bluetooth setting page using intent and it all works till now. Now I am trying to know if it is possible for me to redirect the user to app after he connects with a Bluetooth device from the Bluetooth setting page ?

The code is in JAVA

Anyone please help me with the connection problem I am facing. The app only connects to Bluetooth headphone and nothing else. If anyone has a working code for the connection in Bluetooth it would be a great favor


问:
Inherited classes don't appear in SQL Server?
I'm using ASP.NET Core 6 and Entity Framework.

I have 4 classes (meat, dairy, breads and notdiaryOrMeat) that all inherit from class Food.

In the SQL class all the dbsets for the inherited classes but only class Food appears in SQL Server.

Why can't I see the different classes in SQL Server?


问:
Request timeout on Cloud Run limits grpc stream time
I am having bidirectional grpc stream on a server which is deployed on Cloud Run (Server written in Go). Time of stream is limited by Request Timeout which can not be longer than 1 hour. Grpc stream suppose to be use for long time connections. Workaround for that is to reconnect on a client side but it requires some additional implementations on a client and server side to provide continuous operations. Is there a little bit more "elegant" way to handle long time continous grpc streams via Cloud Run ?</p>


问:
Facing issue while getting the parent object property in nested object using class validator
I have a two class DTO one is Order & one is product and is there any way to access the Order class  fields in the Product class?

```<code>export class Order {

  @Expose({ name: 'orderId' })
  order_id: number;

  @Expose({ name: 'products' })
  @IsArray({ message: 'products must be an array' })
  @ValidateNested()
  @Type(() => Products)
  products: Products[];

}

export class Products {

  @Expose({ name: 'quantity' })
  quantity: number;

  @Expose({ name: 'sku' })
  sku: string;

}
</code>```

I am able to access the current object but not able to access the Order class fields in the nested Products

Body:
I have a two class DTO one is Order & one is product and is there any way to access the Order class  fields in the Product class?

export class Order {

  @Expose({ name: 'orderId' })
  order_id: number;

  @Expose({ name: 'products' })
  @IsArray({ message: 'products must be an array' })
  @ValidateNested()
  @Type(() => Products)
  products: Products[];

}

export class Products {

  @Expose({ name: 'quantity' })
  quantity: number;

  @Expose({ name: 'sku' })
  sku: string;

}

I am able to access the current object but not able to access the Order class fields in the nested Products


问:
TKinter Widget creation... Issue with arrangement of widgets
I was trying to create some nested widgets within file widget however exit is appearing above open. I tried changing the index but still the problems persists any idea how to fix this?

```<code>#!/usr/bin/python3

import tkinter as tk
import tkinter.ttk as ttk
from tkinter import messagebox
import sys

class GuiBaseClass():
  def __init__(self,root):
      # create widgets

      self.root=root
      root.title('GUIBASECLASS V0.1')
      root.option_add('*tearOff', False)
      self.menu=dict()
      self.menubar = tk.Menu(root)
      #File
      menu_file = tk.Menu(self.menubar)
      self.menubar.add_cascade(menu=menu_file,label='File',underline=0)
      menu_file.add_separator()
      menu_file.add_command(label='Exit', command=self.Exit,underline=0)
      #Edit
      menu_edit = tk.Menu(self.menubar)
      self.menubar.add_cascade(menu=menu_edit,label='Edit',underline=0)
      #Help
      menu_help = tk.Menu(self.menubar)
      menu_help.add_command(label='About', command=self.About, underline=0)
      self.menubar.add_cascade(menu=menu_help,label ='Help',underline=0)

      #config
      root.config(menu=self.menubar)
      self.menu['menubar'] = self.menubar
      self.menu['File']    = menu_file
      self.menu['Edit']    = menu_edit
      self.menu['Help']    = menu_help
      self.frame = ttk.Frame(root)
      self.frame.pack(fill='both',expand=True)

  # public functions
  def mainLoop(self):
      self.root.mainloop()
  def getFrame(self):
      return(self.frame)
  def getMenu(self,entry):
      if entry in self.menu:
        return (self.menu[entry])
      else:
        # we create a new one
        last = self.menu['menubar'].index('end')
        self.menu[entry]= tk.Menu(self.menubar)
        self.menu['menubar'].insert_cascade(
          last, menu=self.menu[entry],label=entry)
        return(self.menu[entry])
  # private functions
  def Exit(self,ask=True):
      res = tk.messagebox.askyesno(title='Are you sure',message='Really quit the application')
      if res:
        sys.exit(0)
      pass

  def About(self):
    print('print GUIBASECLASS V0.1')

if __name__ == '__main__':
    root=tk.Tk()
    bapp = GuiBaseClass(root)
    # example for using the BaseClass in other applications
    mnu=bapp.getMenu('Edit')
    mnu.add_command(label='Copy',command=lambda: print('Copy'))
    # example for using getFrame
    frm=bapp.getFrame()
    btn=ttk.Button(frm,text="Button X",command=lambda: sys.exit(0))
    btn.pack()
    bapp.mainLoop()

#!/usr/bin/python3

import tkinter as tk
import tkinter.ttk as ttk
from tkinter import filedialog
from tkinter import messagebox
from GuiBaseClass import GuiBaseClass
import os , sys

class PumlEditor(GuiBaseClass):
    def __init__(self, root):
        super().__init__(root)

        # Create the File menu and add a "Open..." option
        mnu_file = self.getMenu('File')
        mnu_file.add_command(0, label='Open...', underline=0, command=self.fileOpen)

        mnu_file.add_separator()

        # Create the main text area
        frame = self.getFrame()
        #insert tk.Text
        self.text = tk.Text(frame, wrap='word', undo=True)
        self.text.insert('end', 'Hello start writing, please...')
        self.text.delete('1.0','end')
        self.text.pack(fill='both', expand=True)

    def fileOpen(self, filename=''):
        # Open a file dialog to select a file to open
        if filename == "":
            filename = filedialog.askopenfilename()

        if filename != "":
            self.text.delete('1.0','end')
            file = open(filename,'r')
            for line in file:
                self.text.insert('end',line)

if __name__ == '__main__':
    root = tk.Tk()
    root.geometry("300x200")
    pedit = PumlEditor(root)
    # Create the PumlEditor instance and start the main loop
    root.title("PumlEditor 2022")
    if len(sys.argv)>1:
        if os.path.exits(sys.arg[1]):
            pedit.fileOpen(sys.argv[1])
    pedit.mainLoop()

</code>```

Open to appear before exit in files widget

Body:
I was trying to create some nested widgets within file widget however exit is appearing above open. I tried changing the index but still the problems persists any idea how to fix this?

#!/usr/bin/python3

import tkinter as tk
import tkinter.ttk as ttk
from tkinter import messagebox
import sys

class GuiBaseClass():
  def __init__(self,root):
      # create widgets

      self.root=root
      root.title('GUIBASECLASS V0.1')
      root.option_add('*tearOff', False)
      self.menu=dict()
      self.menubar = tk.Menu(root)
      #File
      menu_file = tk.Menu(self.menubar)
      self.menubar.add_cascade(menu=menu_file,label='File',underline=0)
      menu_file.add_separator()
      menu_file.add_command(label='Exit', command=self.Exit,underline=0)
      #Edit
      menu_edit = tk.Menu(self.menubar)
      self.menubar.add_cascade(menu=menu_edit,label='Edit',underline=0)
      #Help
      menu_help = tk.Menu(self.menubar)
      menu_help.add_command(label='About', command=self.About, underline=0)
      self.menubar.add_cascade(menu=menu_help,label ='Help',underline=0)

      #config
      root.config(menu=self.menubar)
      self.menu['menubar'] = self.menubar
      self.menu['File']    = menu_file
      self.menu['Edit']    = menu_edit
      self.menu['Help']    = menu_help
      self.frame = ttk.Frame(root)
      self.frame.pack(fill='both',expand=True)

  # public functions
  def mainLoop(self):
      self.root.mainloop()
  def getFrame(self):
      return(self.frame)
  def getMenu(self,entry):
      if entry in self.menu:
        return (self.menu[entry])
      else:
        # we create a new one
        last = self.menu['menubar'].index('end')
        self.menu[entry]= tk.Menu(self.menubar)
        self.menu['menubar'].insert_cascade(
          last, menu=self.menu[entry],label=entry)
        return(self.menu[entry])
  # private functions
  def Exit(self,ask=True):
      res = tk.messagebox.askyesno(title='Are you sure',message='Really quit the application')
      if res:
        sys.exit(0)
      pass

  def About(self):
    print('print GUIBASECLASS V0.1')

if __name__ == '__main__':
    root=tk.Tk()
    bapp = GuiBaseClass(root)
    # example for using the BaseClass in other applications
    mnu=bapp.getMenu('Edit')
    mnu.add_command(label='Copy',command=lambda: print('Copy'))
    # example for using getFrame
    frm=bapp.getFrame()
    btn=ttk.Button(frm,text="Button X",command=lambda: sys.exit(0))
    btn.pack()
    bapp.mainLoop()

#!/usr/bin/python3

import tkinter as tk
import tkinter.ttk as ttk
from tkinter import filedialog
from tkinter import messagebox
from GuiBaseClass import GuiBaseClass
import os , sys

class PumlEditor(GuiBaseClass):
    def __init__(self, root):
        super().__init__(root)

        # Create the File menu and add a "Open..." option
        mnu_file = self.getMenu('File')
        mnu_file.add_command(0, label='Open...', underline=0, command=self.fileOpen)

        mnu_file.add_separator()

        # Create the main text area
        frame = self.getFrame()
        #insert tk.Text
        self.text = tk.Text(frame, wrap='word', undo=True)
        self.text.insert('end', 'Hello start writing, please...')
        self.text.delete('1.0','end')
        self.text.pack(fill='both', expand=True)

    def fileOpen(self, filename=''):
        # Open a file dialog to select a file to open
        if filename == "":
            filename = filedialog.askopenfilename()

        if filename != "":
            self.text.delete('1.0','end')
            file = open(filename,'r')
            for line in file:
                self.text.insert('end',line)

if __name__ == '__main__':
    root = tk.Tk()
    root.geometry("300x200")
    pedit = PumlEditor(root)
    # Create the PumlEditor instance and start the main loop
    root.title("PumlEditor 2022")
    if len(sys.argv)>1:
        if os.path.exits(sys.arg[1]):
            pedit.fileOpen(sys.argv[1])
    pedit.mainLoop()

Open to appear before exit in files widget


问:
Copy PowerPoint file with Python pptx
I'm trying to make a Python code to copy a PowerPoint file. I have the file test.pptx which contains pictures (can be totally ignored) and text, with different slides (title, tittle and content, etc). I need to copy the text from this file, and create a new .pptx file containing the text in the same format.

I already have a code to extract the text from the file, but I have no clue in what to do next. Any ideas? Thank you.

This is the code to read the text from the file

import collections.abc
from pptx import Presentation

prs = Presentation('test.pptx')

text_runs = []

for slide in prs.slides:
    for shape in slide.shapes:
        if not shape.has_text_frame:
            continue
        for paragraph in shape.text_frame.paragraphs:
            for run in paragraph.runs:
                text_runs.append(run.text)
```

Title: Copy PowerPoint file with Python pptx


问:
How to make a "colspan" in a table in pysimplegui
im traying to make a todolist with pysimplegui, but i dont know how to make the equivalent of a some text	 in pysimplegui


问:
Poor speed up when running code in parallel using MPI and openMP
I have the following code:

int main(int argc, char **argv)
{
    int n_runs = 100; // Number of runs
    int seed = 1;
    int arraySize = 400;
    /////////////////////////////////////////////////////////////////////

    // initialise the random number generator using a fixed seed for reproducibility
    srand(seed);

    MPI_Init(nullptr, nullptr);

    int rank, n_procs;
    MPI_Comm_size(MPI_COMM_WORLD, &n_procs);
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);

    // Initialise the probability step and results vectors.
    // We have 21 probabilities between 0 and 1 (inclusive).
    double prob_step = 0.05;
    std::vector<double> avg_steps_over_p(21,0);
    std::vector<double> trans_avg_steps_over_p(21,0);
    std::vector<int> min_steps_over_p(21,0);
    std::vector<int> trans_min_steps_over_p(21,0);
    std::vector<int> max_steps_over_p(21,0);
    std::vector<int> trans_max_steps_over_p(21,0);
    std::vector<double> prob_reached_end(21,0);
    std::vector<double> trans_prob_reached_end(21,0);

    // Loop over probabilities and compute the number of steps before the model burns out,
    // averaged over n_runs.
    for (int i = rank; i < 21; i+=n_procs)
    {
        double prob = i*prob_step;

        int min_steps = std::numeric_limits<int>::max();
        int max_steps = 0;

        for (int i_run = 0; i_run < n_runs; ++i_run)
        {
            Results result = forest_fire(arraySize, prob);

            avg_steps_over_p[i] += result.stepCount;

            if (result.fireReachedEnd) ++prob_reached_end[i];
            if (result.stepCount < min_steps) min_steps = result.stepCount;
            if (result.stepCount > max_steps) max_steps = result.stepCount;
        }

        avg_steps_over_p[i] /= n_runs;
        min_steps_over_p[i] = min_steps;
        max_steps_over_p[i] = max_steps;
        prob_reached_end[i] = 1.0*prob_reached_end[i] / n_runs;
    }

    // Worker processes communicate their results to the master process.
    if (rank > 0)
    {
        MPI_Send(&avg_steps_over_p[0], 21, MPI_DOUBLE, 0, rank, MPI_COMM_WORLD);
        MPI_Send(&min_steps_over_p[0], 21, MPI_INT, 0, rank, MPI_COMM_WORLD);
        MPI_Send(&max_steps_over_p[0], 21, MPI_INT, 0, rank, MPI_COMM_WORLD);
        MPI_Send(&prob_reached_end[0], 21, MPI_DOUBLE, 0, rank, MPI_COMM_WORLD);
    } else
    {
        for (int i = 1; i < n_procs; ++i)
        {
            MPI_Status status;
            MPI_Recv(&trans_avg_steps_over_p[0], 21, MPI_DOUBLE, i, i, MPI_COMM_WORLD, &status);
            for (int j = i; j < 21; j += n_procs) {
                 avg_steps_over_p[j] = trans_avg_steps_over_p[j];
            }
            MPI_Recv(&trans_min_steps_over_p[0], 21, MPI_INT, i, i, MPI_COMM_WORLD, &status);
            for (int j = i; j < 21; j += n_procs) {
                 min_steps_over_p[j] = trans_min_steps_over_p[j];
            }

            MPI_Recv(&trans_max_steps_over_p[0], 21, MPI_INT, i, i, MPI_COMM_WORLD, &status);
            for (int j = i; j < 21; j += n_procs) {
                 max_steps_over_p[j] = trans_max_steps_over_p[j];
            }

            MPI_Recv(&trans_prob_reached_end[0], 21, MPI_DOUBLE, i, i, MPI_COMM_WORLD, &status);
            for (int j = i; j < 21; j += n_procs) {
                 prob_reached_end[j] = trans_prob_reached_end[j];
            }
        }

        // Master process outputs the final result.
        std::cout << "Probability, Avg. Steps, Min. Steps, Max Steps" << std::endl;
        for (int i = 0; i < 21; ++i)
        {
            double prob = i * prob_step;
            std::cout << prob << "," << avg_steps_over_p[i]
                      << "," << min_steps_over_p[i] << ","
                      << max_steps_over_p[i] << ","
                      << prob_reached_end[i] << std::endl;
        }
    }

    MPI_Finalize();
    return 0;
}
```

I have tried the following parameters:
Speed-up ratios

I'm new to parallelisation and HPC so forgive me if I'm wrong, but I was expecting an improvement of greater than 3 when increasing the tasks per node and CPUs per task. I haven't yet tried all the possibilities but I believe the behaviour here is odd, especially when keeping CPUs per task at 1 and increasing tasks per node from 2->3->4. I know it's not as simple a case as greater core usage = greater speed up, but from what I've gathered these should speed-up.

Is there a possible inefficiency in my code that is leading to this, or is this expected behaviour? My full code is here, which includes the openMP parallelisation: https://www.codedump.xyz/cpp/Y5Rr68L8Mncmx1Sd.

Body:
I have the following code:

int main(int argc, char **argv)
{
    int n_runs = 100; // Number of runs
    int seed = 1;
    int arraySize = 400;
    /////////////////////////////////////////////////////////////////////

    // initialise the random number generator using a fixed seed for reproducibility
    srand(seed);

    MPI_Init(nullptr, nullptr);

    int rank, n_procs;
    MPI_Comm_size(MPI_COMM_WORLD, &n_procs);
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);

    // Initialise the probability step and results vectors.
    // We have 21 probabilities between 0 and 1 (inclusive).
    double prob_step = 0.05;
    std::vector<double> avg_steps_over_p(21,0);
    std::vector<double> trans_avg_steps_over_p(21,0);
    std::vector<int> min_steps_over_p(21,0);
    std::vector<int> trans_min_steps_over_p(21,0);
    std::vector<int> max_steps_over_p(21,0);
    std::vector<int> trans_max_steps_over_p(21,0);
    std::vector<double> prob_reached_end(21,0);
    std::vector<double> trans_prob_reached_end(21,0);

    // Loop over probabilities and compute the number of steps before the model burns out,
    // averaged over n_runs.
    for (int i = rank; i < 21; i+=n_procs)
    {
        double prob = i*prob_step;

        int min_steps = std::numeric_limits<int>::max();
        int max_steps = 0;

        for (int i_run = 0; i_run < n_runs; ++i_run)
        {
            Results result = forest_fire(arraySize, prob);

            avg_steps_over_p[i] += result.stepCount;

            if (result.fireReachedEnd) ++prob_reached_end[i];
            if (result.stepCount < min_steps) min_steps = result.stepCount;
            if (result.stepCount > max_steps) max_steps = result.stepCount;
        }

        avg_steps_over_p[i] /= n_runs;
        min_steps_over_p[i] = min_steps;
        max_steps_over_p[i] = max_steps;
        prob_reached_end[i] = 1.0*prob_reached_end[i] / n_runs;
    }

    // Worker processes communicate their results to the master process.
    if (rank > 0)
    {
        MPI_Send(&avg_steps_over_p[0], 21, MPI_DOUBLE, 0, rank, MPI_COMM_WORLD);
        MPI_Send(&min_steps_over_p[0], 21, MPI_INT, 0, rank, MPI_COMM_WORLD);
        MPI_Send(&max_steps_over_p[0], 21, MPI_INT, 0, rank, MPI_COMM_WORLD);
        MPI_Send(&prob_reached_end[0], 21, MPI_DOUBLE, 0, rank, MPI_COMM_WORLD);
    } else
    {
        for (int i = 1; i < n_procs; ++i)
        {
            MPI_Status status;
            MPI_Recv(&trans_avg_steps_over_p[0], 21, MPI_DOUBLE, i, i, MPI_COMM_WORLD, &status);
            for (int j = i; j < 21; j += n_procs) {
                 avg_steps_over_p[j] = trans_avg_steps_over_p[j];
            }
            MPI_Recv(&trans_min_steps_over_p[0], 21, MPI_INT, i, i, MPI_COMM_WORLD, &status);
            for (int j = i; j < 21; j += n_procs) {
                 min_steps_over_p[j] = trans_min_steps_over_p[j];
            }

            MPI_Recv(&trans_max_steps_over_p[0], 21, MPI_INT, i, i, MPI_COMM_WORLD, &status);
            for (int j = i; j < 21; j += n_procs) {
                 max_steps_over_p[j] = trans_max_steps_over_p[j];
            }

            MPI_Recv(&trans_prob_reached_end[0], 21, MPI_DOUBLE, i, i, MPI_COMM_WORLD, &status);
            for (int j = i; j < 21; j += n_procs) {
                 prob_reached_end[j] = trans_prob_reached_end[j];
            }
        }

        // Master process outputs the final result.
        std::cout << "Probability, Avg. Steps, Min. Steps, Max Steps" << std::endl;
        for (int i = 0; i < 21; ++i)
        {
            double prob = i * prob_step;
            std::cout << prob << "," << avg_steps_over_p[i]
                      << "," << min_steps_over_p[i] << ","
                      << max_steps_over_p[i] << ","
                      << prob_reached_end[i] << std::endl;
        }
    }

    MPI_Finalize();
    return 0;
}

I have tried the following parameters:
Speed-up ratios

I'm new to parallelisation and HPC so forgive me if I'm wrong, but I was expecting an improvement of greater than 3 when increasing the tasks per node and CPUs per task. I haven't yet tried all the possibilities but I believe the behaviour here is odd, especially when keeping CPUs per task at 1 and increasing tasks per node from 2->3->4. I know it's not as simple a case as greater core usage = greater speed up, but from what I've gathered these should speed-up.

Is there a possible inefficiency in my code that is leading to this, or is this expected behaviour? My full code is here, which includes the openMP parallelisation: https://www.codedump.xyz/cpp/Y5Rr68L8Mncmx1Sd.


问:
I pip installed the arcgis library, but the reverse geocoding function is not working
```<code>from geopy.geocoders import ArcGIS
from arcgis.geocoding import reverse_geocode

arcgis = ArcGIS()

results = reverse_geocode(location={"x": 103.876722, "y": 1.3330736})
print(results)
</code>```

When I run this script in python, I get the following error.

```<code>Traceback (most recent call last):
  File "C:\Users\18102\RentScraping\newMarketRequests.py", line 22, in <module>
    results = reverse_geocode(location={"x": 103.876722, "y": 1.3330736})
  File "C:\Users\18102\AppData\Roaming\Python\Python310\site-packages\arcgis\geocoding\_functions.py", line 1457, in reverse_geocode
    geocoder = arcgis.env.active_gis._tools.geocoders[0]
AttributeError: 'NoneType' object has no attribute '_tools'
</code>```

I pip installed the arcgis library, which I have used before for geocoding on a different project, but the reverse geocoding isn't working. I saw some documentation that had a few variations on how to provide the location parameter. I also tried reverse_geocode([103.876722, 1.3330736]) and got the same result. I think there might be something that got updated and the documentation I'm referencing is out of date. Any advice?

Body:
from geopy.geocoders import ArcGIS
from arcgis.geocoding import reverse_geocode

arcgis = ArcGIS()

results = reverse_geocode(location={"x": 103.876722, "y": 1.3330736})
print(results)

When I run this script in python, I get the following error.

Traceback (most recent call last):
  File "C:\Users\18102\RentScraping\newMarketRequests.py", line 22, in <module>
    results = reverse_geocode(location={"x": 103.876722, "y": 1.3330736})
  File "C:\Users\18102\AppData\Roaming\Python\Python310\site-packages\arcgis\geocoding\_functions.py", line 1457, in reverse_geocode
    geocoder = arcgis.env.active_gis._tools.geocoders[0]
AttributeError: 'NoneType' object has no attribute '_tools'

I pip installed the arcgis library, which I have used before for geocoding on a different project, but the reverse geocoding isn't working. I saw some documentation that had a few variations on how to provide the location parameter. I also tried reverse_geocode([103.876722, 1.3330736]) and got the same result. I think there might be something that got updated and the documentation I'm referencing is out of date. Any advice?


问:
Error writing lock file: Permission denied
After connecting my NAS drive with the mount command in the nashome directory,
the following error occurs, when trying to edit or create any file in the mounted directory tree:
[ Error writing lock file ./.index.html.swp: Permission denied ]
Error Message when trying to edit the index.html file

I also tried editing the files as a root, however the same error occurs.

The permissions in the parent directory of the file are as follows:
permissions to the index.html file

Is there anyone who can explain what is happening?

I already tried deleting the nashome directory and unmounting the NAS drive and then remounting it again.
However, with no effect.


问:
TypeError: undefined is not an object (evaluating 'this.props = props')
im trying to implement task function that would allow me to display different task just by reading them from TASK_DATA.js but i got an "TypeError: undefined is not an object (evaluating 'this.props = props')" and i got kind of mixed up and i dont know where to start to get out of that. Probably there is easy way out but i need someone else advice to clear my thoughts out.

```<code>const TASK_DATA = [
 {
    id: 't1',
    title: 'Application Setup',
    content: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi vel gravida orci. Proin odio ex, elementum eu malesuada sit amet, congue eget dui. Suspendisse sem ligula, pharetra non aliquam non, tincidunt rutrum nunc. Suspendisse faucibus, diam et facilisis pellentesque, ligula justo posuere tellus, vitae viverra nunc erat ut quam. Praesent semper elit suscipit blandit iaculis. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer in consequat nulla, sit amet semper augue. Donec cursus efficitur nibh, vel cursus velit faucibus et. Morbi sit amet augue tellus. Vivamus sapien justo, ullamcorper aliquet lectus a, interdum facilisis nulla. Suspendisse lobortis pulvinar mauris, pulvinar tempus dolor. Aliquam commodo gravida arcu, dictum gravida neque sagittis vel',
    status: 'done'
 },
 {
    id: 't2',
    title: 'Administrator Panel',
    content: 'Fusce tincidunt libero eget orci facilisis vulputate. In varius pretium scelerisque. Vestibulum leo arcu, dictum nec feugiat non, sagittis sit amet neque. Ut vulputate sem leo, eu placerat dolor ultricies at. Mauris et massa diam. Ut quis pulvinar dolor, vestibulum aliquet est. Fusce ut cursus lacus. Vestibulum accumsan gravida ornare. Maecenas mollis mattis elit, sed porttitor erat consectetur sit amet.',
    status: 'done'
 },
 {
    id: 't3',
    title: 'Connect Admin with Frontend',
    content: 'Etiam malesuada tincidunt semper. Nunc dolor nulla, luctus id tempus ut, dignissim quis diam. Aliquam placerat ex at sapien pellentesque bibendum. Nam eget metus id mauris dapibus pharetra eu quis odio. Aliquam facilisis bibendum neque, feugiat consequat libero ultricies et. Ut tristique justo lobortis finibus gravida. Etiam sed arcu in augue efficitur maximus vitae sit amet tellus.',
    status: 'current'
 },
 {
    id: 't4',
    title: 'Book review status',
    content: 'At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga.',
    status: 'lock'
 }
];

export default TASK_DATA;
</code>```

App.js

```<code>class App extends Component() {
  constructor(props) {
    super(props)
  }

  render(props) {
    props.tasks.map(task => <Task
      key={task.id}
      id={task.id}
      title={task.title}
      content={task.content}
      status={task.status}
      />)
    return (
      <div>
        <div>Menu
          <p>nerds.family</p>
          <p>img kółeczko</p>
        </div>

        <Bar/>
        <hr className="sep"></hr>
        <Router>
          <Window/>
          <Routes>
            <Route path="/" element={<Content/>}/>
            <Route path="/task-1" element={<Task />}/>
            <Route path="/task-2"></Route>
            <Route path="/task-3"></Route>
            <Route path="/task-4"></Route>
          </Routes>
        </Router>
        <Footer/>
      </div>

    );
  }
}
export default App;
</code>```

Task.js

```<code>    return (
        <div className="container">
            <div className="taskText">
                <p>{props.content}</p>
            </div>
            <div className="taskCrit">
                <h1>Acceptance Criteria</h1>
                <input type="checkbox"/>
            </div>
        </div>
        );
}

export default Task;
</code>```

Window.js

```<code>import React from 'react';
import { Link} from 'react-router-dom';

import CheckIcon from '@mui/icons-material/Check';
import ArrowForwardIcon from '@mui/icons-material/ArrowForward';
import LockIcon from '@mui/icons-material/Lock';

function Window () {

        return (

            <div className="window">
                <div className="header">
                    YOUR TASKS
                </div>
                <hr></hr>
                <div className="tasksList">
                    <ul>
                        <li><Link to='/task-1'><CheckIcon className={this.task1.status}/>{this.task1.title}</Link></li>
                        <li><Link to='/task-2'><CheckIcon className={this.task2.status}/>{this.task2.title}</Link></li>
                        <li className="curr"><Link to='/task-3'><ArrowForwardIcon className={this.task3.status}/>{this.task3.title}</Link></li>
                        <li><Link to='/task-4'><LockIcon className={this.task4.status}/>{this.task4.title}</Link></li>
                    </ul>
                </div>
            </div>
        );

}

export default Window;
</code>```

Body:
im trying to implement task function that would allow me to display different task just by reading them from TASK_DATA.js but i got an "TypeError: undefined is not an object (evaluating 'this.props = props')" and i got kind of mixed up and i dont know where to start to get out of that. Probably there is easy way out but i need someone else advice to clear my thoughts out.

const TASK_DATA = [
 {
    id: 't1',
    title: 'Application Setup',
    content: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi vel gravida orci. Proin odio ex, elementum eu malesuada sit amet, congue eget dui. Suspendisse sem ligula, pharetra non aliquam non, tincidunt rutrum nunc. Suspendisse faucibus, diam et facilisis pellentesque, ligula justo posuere tellus, vitae viverra nunc erat ut quam. Praesent semper elit suscipit blandit iaculis. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer in consequat nulla, sit amet semper augue. Donec cursus efficitur nibh, vel cursus velit faucibus et. Morbi sit amet augue tellus. Vivamus sapien justo, ullamcorper aliquet lectus a, interdum facilisis nulla. Suspendisse lobortis pulvinar mauris, pulvinar tempus dolor. Aliquam commodo gravida arcu, dictum gravida neque sagittis vel',
    status: 'done'
 },
 {
    id: 't2',
    title: 'Administrator Panel',
    content: 'Fusce tincidunt libero eget orci facilisis vulputate. In varius pretium scelerisque. Vestibulum leo arcu, dictum nec feugiat non, sagittis sit amet neque. Ut vulputate sem leo, eu placerat dolor ultricies at. Mauris et massa diam. Ut quis pulvinar dolor, vestibulum aliquet est. Fusce ut cursus lacus. Vestibulum accumsan gravida ornare. Maecenas mollis mattis elit, sed porttitor erat consectetur sit amet.',
    status: 'done'
 },
 {
    id: 't3',
    title: 'Connect Admin with Frontend',
    content: 'Etiam malesuada tincidunt semper. Nunc dolor nulla, luctus id tempus ut, dignissim quis diam. Aliquam placerat ex at sapien pellentesque bibendum. Nam eget metus id mauris dapibus pharetra eu quis odio. Aliquam facilisis bibendum neque, feugiat consequat libero ultricies et. Ut tristique justo lobortis finibus gravida. Etiam sed arcu in augue efficitur maximus vitae sit amet tellus.',
    status: 'current'
 },
 {
    id: 't4',
    title: 'Book review status',
    content: 'At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga.',
    status: 'lock'
 }
];

export default TASK_DATA;

App.js

class App extends Component() {
  constructor(props) {
    super(props)
  }

  render(props) {
    props.tasks.map(task => <Task
      key={task.id}
      id={task.id}
      title={task.title}
      content={task.content}
      status={task.status}
      />)
    return (

Menu

nerds.family

img kółeczko

        <Bar/>

        <Router>
          <Window/>
          <Routes>
            <Route path="/" element={<Content/>}/>
            <Route path="/task-1" element={<Task />}/>
            <Route path="/task-2"></Route>
            <Route path="/task-3"></Route>
            <Route path="/task-4"></Route>
          </Routes>
        </Router>

    );
  }
}
export default App;

Task.js

    return (

{props.content}

Acceptance Criteria

                <input type="checkbox"/>

        );
}

export default Task;

Window.js

import React from 'react';
import { Link} from 'react-router-dom';

import CheckIcon from '@mui/icons-material/Check';
import ArrowForwardIcon from '@mui/icons-material/ArrowForward';
import LockIcon from '@mui/icons-material/Lock';

function Window () {

        return (

                    YOUR TASKS

<Link to='/task-1'><CheckIcon className={this.task1.status}/>{this.task1.title}</Link>

<Link to='/task-2'><CheckIcon className={this.task2.status}/>{this.task2.title}</Link>

<Link to='/task-3'><ArrowForwardIcon className={this.task3.status}/>{this.task3.title}</Link>

<Link to='/task-4'><LockIcon className={this.task4.status}/>{this.task4.title}</Link>

        );

}

export default Window;


问:
TypeScript, define interface types in useGet custom hook
Coding this custom hook useGet, i would like to define the IStatus interface. For example loading status is clearly boolean, error: I tryed with Error or AxiosError types but i have an alert in VSCode (Type 'unknown' is not assignable to type 'Error | null'). data: an empty Array ?. Thanks in advance.

useGet.ts (custom hook)

import { useEffect, useState } from 'react'
import axios from 'axios'

export const useGet = (url: string) => {
  interface IStatus {
    loading: boolean;
    error: null | any;
    data: null | []
  }

  const [status, setStatus] = useState<IStatus>({
    loading: true,
    error: null,
    data: null
  });

  useEffect(() => {
    getData();
  }, []);

  const getData = async () => {
    try {
      const res = await axios(url);
      setStatus({
        loading: false,
        error: null,
        data: res.data
      });
    } catch (error) {
      setStatus({
        loading: false,
        error: error,
        data: null
      });
      console.error(error);
    }
  }

  return [status.data, status.loading, status.error]
}```
</div>
</div>
</p>
<blockquote>
<p>Component.tsx (consuming custom hook)</p>
</blockquote>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import { useGet } from '../hooks/useGet';

const UseGetComponent = () => {
  interface IUser {
    id: number;
    name: string;
    email: string;
  }

  interface IPost {
    id: number;
    userId: number;
    title: string;
  }

  const [dataUsers, loadingUsers, errorUsers] = useGet('https://jsonplaceholder.typicode.com/users')
  const [dataPosts, loadingPosts, errorPosts] = useGet('https://jsonplaceholder.typicode.com/posts')
  return (
    <>
      <h1>Custom hooks</h1>
      {loadingUsers && <div>Loading...</div>}
      {errorUsers && <div>Error: {errorUsers.message}</div>}
      {dataUsers && (
        <div >
          <ul>
            {dataUsers.map((user: IUser) => (
              <li key={user.id}>
              {user.name} - {user.email}
              {loadingPosts && <div>Loading...</div>}
              {errorPosts && <div>Error: {errorPosts.message}</div>}
              {dataPosts && (
                <ul>
                  {dataPosts
                    .filter((post: IPost) => post.userId === user.id)
                    .map((post: IPost) => (
                      <li key={post.id}>{post.title}</li>
                    ))}
                </ul>
              )}
              </li>
            ))}
          </ul>
        </div>
      )}
    </>
  )
}

export default UseGetComponent</code>```

Body:
Coding this custom hook useGet, i would like to define the IStatus interface. For example loading status is clearly boolean, error: I tryed with Error or AxiosError types but i have an alert in VSCode (Type 'unknown' is not assignable to type 'Error | null'). data: an empty Array ?. Thanks in advance.

useGet.ts (custom hook)

import { useEffect, useState } from 'react'
import axios from 'axios'

export const useGet = (url: string) => {
  interface IStatus {
    loading: boolean;
    error: null | any;
    data: null | []
  }

  const [status, setStatus] = useState<IStatus>({
    loading: true,
    error: null,
    data: null
  });

  useEffect(() => {
    getData();
  }, []);

  const getData = async () => {
    try {
      const res = await axios(url);
      setStatus({
        loading: false,
        error: null,
        data: res.data
      });
    } catch (error) {
      setStatus({
        loading: false,
        error: error,
        data: null
      });
      console.error(error);
    }
  }

  return [status.data, status.loading, status.error]
}

Component.tsx (consuming custom hook)

import { useGet } from '../hooks/useGet';

const UseGetComponent = () => {
  interface IUser {
    id: number;
    name: string;
    email: string;
  }

  interface IPost {
    id: number;
    userId: number;
    title: string;
  }

  const [dataUsers, loadingUsers, errorUsers] = useGet('https://jsonplaceholder.typicode.com/users')
  const [dataPosts, loadingPosts, errorPosts] = useGet('https://jsonplaceholder.typicode.com/posts')
  return (
    <>

Custom hooks

      {loadingUsers &&
Loading...
}
      {errorUsers &&
Error: {errorUsers.message}
}
      {dataUsers && (

            {dataUsers.map((user: IUser) => (

              {user.name} - {user.email}
              {loadingPosts &&
Loading...
}
              {errorPosts &&
Error: {errorPosts.message}
}
              {dataPosts && (

                  {dataPosts
                    .filter((post: IPost) => post.userId === user.id)
                    .map((post: IPost) => (

{post.title}

                    ))}

              )}

            ))}

      )}
    </>
  )
}

export default UseGetComponent


问:
Can MBED CLI 2 build a multiple directory project or do I need CMAKE?
I am trying to make the transtition from MBED Studio to VSCode.

I have succesfully compiled and debugged the Blinky example.
I now want to create a large project with many subdirectories.
When I create a new library, and include it’s header in the main.cpp, and try building using MBED CLI2 I get:

```<code>myLibrary.hpp: No such file or directory.
Compilation terminated.
</code>```

Perhaps I have misunderstood the functionality of MBED CLI2, but I thought that it could behave like MBED Studio and could build a project, afterwhich convert it to a CMAKE-build.

So the question is, do I need cmake?

Thanks in advance,
Will

Body:
I am trying to make the transtition from MBED Studio to VSCode.

I have succesfully compiled and debugged the Blinky example.
I now want to create a large project with many subdirectories.
When I create a new library, and include it’s header in the main.cpp, and try building using MBED CLI2 I get:

myLibrary.hpp: No such file or directory.
Compilation terminated.

Perhaps I have misunderstood the functionality of MBED CLI2, but I thought that it could behave like MBED Studio and could build a project, afterwhich convert it to a CMAKE-build.

So the question is, do I need cmake?

Thanks in advance,
Will


问:
Determine Position (lan-long) on turning radius from a point to another point

Lat-lon position A and B are known, the turning radius r also known.

I need help to create a function to calculate position 'P' for any turning "progress" (0.0 - 1.0) between position A and B

progress 0.0 = A

progress 1.0 = B

progress x = P

LatLon getTurnInterpolation(LatLon A, LatLon B, double r, double progress){
}
```

since there are two possible option for position C, we can just assume the turning is always anti-clockwise from A to B, also the position is in spherical space (WGS84 lat-lon) or all distance are great circle distance

Body:
Lat-lon position A and B are known, the turning radius r also known.

I need help to create a function to calculate position 'P' for any turning "progress" (0.0 - 1.0) between position A and B

progress 0.0 = A

progress 1.0 = B

progress x = P

LatLon getTurnInterpolation(LatLon A, LatLon B, double r, double progress){
}

since there are two possible option for position C, we can just assume the turning is always anti-clockwise from A to B, also the position is in spherical space (WGS84 lat-lon) or all distance are great circle distance


问:
I have generated ECDSA signature with nodeJS crypto library. How to verify it with openssl command
I have generated ECDSA-with-sha256 signature in node using following script:

const crypto = require('node:crypto')

const keys = {
    "pubKey": "LS0tLS1CRUdJTiBQVUJMSUMgS0VZLS0tLS0KTUU0d0VBWUhLb1pJemowQ0FRWUZLNEVFQUNFRE9nQUViVCtFVHUzV21BNjc3b1ZVcDZ3Q1E4eU5ocFZIMWtBQQo4V3F2T0hxR3JqaFVoUzdUcUNGRHBGNStGbklrWUpjSWpwcTJtNmJkcHpNPQotLS0tLUVORCBQVUJMSUMgS0VZLS0tLS0K",
    "privKey": "LS0tLS1CRUdJTiBQUklWQVRFIEtFWS0tLS0tCk1IZ0NBUUF3RUFZSEtvWkl6ajBDQVFZRks0RUVBQ0VFWVRCZkFnRUJCQnhCK01iaS96am90bWJQL1NJTjh1L1kKUitIa0p2cXF5OXdaNTZZaG9Ud0RPZ0FFYlQrRVR1M1dtQTY3N29WVXA2d0NROHlOaHBWSDFrQUE4V3F2T0hxRwpyamhVaFM3VHFDRkRwRjUrRm5Ja1lKY0lqcHEybTZiZHB6TT0KLS0tLS1FTkQgUFJJVkFURSBLRVktLS0tLQo="
}

const message = "Some data"

const privateKey = Buffer.from(keys.privKey, 'base64')
const publicKey = Buffer.from(keys.pubKey, 'base64')

const sign = crypto.createSign('sha256')
sign.write(message)
sign.end()

const signed = sign.sign(privateKey, 'base64')
console.log(signed)
```
<p>As an output I get for example this signature: <code>MD0CHDNm8dc0uUTBQmBMjlF7t7+QqofLJJzXfA4TIjsCHQDH6br8YJxaa7xB15hLRpWT0ewKBZnhf3UYtx3C</code></p>
<p>I am trying to verify it using openssl command:</p>
<pre class="lang-bash prettyprint-override"><code>#!/bin/zsh

PUBLIC_KEY="LS0tLS1CRUdJTiBQVUJMSUMgS0VZLS0tLS0KTUU0d0VBWUhLb1pJemowQ0FRWUZLNEVFQUNFRE9nQUViVCtFVHUzV21BNjc3b1ZVcDZ3Q1E4eU5ocFZIMWtBQQo4V3F2T0hxR3JqaFVoUzdUcUNGRHBGNStGbklrWUpjSWpwcTJtNmJkcHpNPQotLS0tLUVORCBQVUJMSUMgS0VZLS0tLS0K"
MESSAGE="Some data"
SIGNATURE="MD0CHDNm8dc0uUTBQmBMjlF7t7+QqofLJJzXfA4TIjsCHQDH6br8YJxaa7xB15hLRpWT0ewKBZnhf3UYtx3C"

openssl dgst \
  -sha256 \
  -verify <(base64 -d <(echo $PUBLIC_KEY)) \
  -signature <(base64 -d <(echo $SIGNATURE)) \
  <(echo $MESSAGE)
</code>```

I am getting an Verification Failure output.

What am I doing wrong here? Am I missing some transformation or parameter?

Body:
I have generated ECDSA-with-sha256 signature in node using following script:

const crypto = require('node:crypto')

const keys = {
    "pubKey": "LS0tLS1CRUdJTiBQVUJMSUMgS0VZLS0tLS0KTUU0d0VBWUhLb1pJemowQ0FRWUZLNEVFQUNFRE9nQUViVCtFVHUzV21BNjc3b1ZVcDZ3Q1E4eU5ocFZIMWtBQQo4V3F2T0hxR3JqaFVoUzdUcUNGRHBGNStGbklrWUpjSWpwcTJtNmJkcHpNPQotLS0tLUVORCBQVUJMSUMgS0VZLS0tLS0K",
    "privKey": "LS0tLS1CRUdJTiBQUklWQVRFIEtFWS0tLS0tCk1IZ0NBUUF3RUFZSEtvWkl6ajBDQVFZRks0RUVBQ0VFWVRCZkFnRUJCQnhCK01iaS96am90bWJQL1NJTjh1L1kKUitIa0p2cXF5OXdaNTZZaG9Ud0RPZ0FFYlQrRVR1M1dtQTY3N29WVXA2d0NROHlOaHBWSDFrQUE4V3F2T0hxRwpyamhVaFM3VHFDRkRwRjUrRm5Ja1lKY0lqcHEybTZiZHB6TT0KLS0tLS1FTkQgUFJJVkFURSBLRVktLS0tLQo="
}

const message = "Some data"

const privateKey = Buffer.from(keys.privKey, 'base64')
const publicKey = Buffer.from(keys.pubKey, 'base64')

const sign = crypto.createSign('sha256')
sign.write(message)
sign.end()

const signed = sign.sign(privateKey, 'base64')
console.log(signed)

As an output I get for example this signature: MD0CHDNm8dc0uUTBQmBMjlF7t7+QqofLJJzXfA4TIjsCHQDH6br8YJxaa7xB15hLRpWT0ewKBZnhf3UYtx3C

I am trying to verify it using openssl command:

#!/bin/zsh

PUBLIC_KEY="LS0tLS1CRUdJTiBQVUJMSUMgS0VZLS0tLS0KTUU0d0VBWUhLb1pJemowQ0FRWUZLNEVFQUNFRE9nQUViVCtFVHUzV21BNjc3b1ZVcDZ3Q1E4eU5ocFZIMWtBQQo4V3F2T0hxR3JqaFVoUzdUcUNGRHBGNStGbklrWUpjSWpwcTJtNmJkcHpNPQotLS0tLUVORCBQVUJMSUMgS0VZLS0tLS0K"
MESSAGE="Some data"
SIGNATURE="MD0CHDNm8dc0uUTBQmBMjlF7t7+QqofLJJzXfA4TIjsCHQDH6br8YJxaa7xB15hLRpWT0ewKBZnhf3UYtx3C"

openssl dgst \
  -sha256 \
  -verify <(base64 -d <(echo $PUBLIC_KEY)) \
  -signature <(base64 -d <(echo $SIGNATURE)) \
  <(echo $MESSAGE)

I am getting an Verification Failure output.

What am I doing wrong here? Am I missing some transformation or parameter?


问:
MTL file along with OBJ file for displaying 3D models in p5.js
I followed the example from p5.js Reference
It contains an example of how to load an OBJ file in JavaScript with p5.js:

```<code>//draw a spinning teapot
let teapot;

function preload() {
  // Load model with normalise parameter set to true
  teapot = loadModel('assets/teapot.obj', true);
}

function setup() {
  createCanvas(100, 100, WEBGL);
  describe('Vertically rotating 3-d teapot with red, green and blue gradient.');
}

function draw() {
  background(200);
  scale(0.4); // Scaled to make model fit into canvas
  rotateX(frameCount * 0.01);
  rotateY(frameCount * 0.01);
  normalMaterial(); // For effect
  model(teapot);
}
</code>```

Is there a way to load an MTL file which contains the material and texture information to replace the normalMaterial() function?

The texture() function doesn't work right for 3D objects.

Body:
I followed the example from p5.js Reference
It contains an example of how to load an OBJ file in JavaScript with p5.js:

//draw a spinning teapot
let teapot;

function preload() {
  // Load model with normalise parameter set to true
  teapot = loadModel('assets/teapot.obj', true);
}

function setup() {
  createCanvas(100, 100, WEBGL);
  describe('Vertically rotating 3-d teapot with red, green and blue gradient.');
}

function draw() {
  background(200);
  scale(0.4); // Scaled to make model fit into canvas
  rotateX(frameCount * 0.01);
  rotateY(frameCount * 0.01);
  normalMaterial(); // For effect
  model(teapot);
}

Is there a way to load an MTL file which contains the material and texture information to replace the normalMaterial() function?

The texture() function doesn't work right for 3D objects.


问:
When I deploy my next js app on cPanel, style is not working, style was written in sass
I have deployed my next js app on to cPanel, everything is ok, but it shows just html, scss files are not working. How can I fix it?

I have searched on google but could not find proper answer. I have no idea what to do. Has anyone encountered this problem?


问:
req.isAuthenticated() is false, after successful login
I have a simple login by nickname:

```<code>async login(
      _: any,
      args: UserFindArgs,
      { req, res }: Context
    ): Promise<User | null> {
      const user = await prisma.user.findUnique({
        where: { nickname: args.nickname },
      });
      console.log(req.user);
      req.logIn(user, (err: any) => {
        if (err) {
          return null;
        }
      });
      console.log(req.user);
      return user;
    },
</code>```

after login console returns user, which is fine: console.log

but when I try to get that user in query:

```<code>    async me(
      _: any,
      args: UserFindArgs,
      { req, res }: Context
    ): Promise<String> {
      console.log(req.user); // req.isauthenticated() is also false
      return "req";
    },
</code>```

it's returning undefined

index.ts:

```<code>(async () => {
  const app = express();

  passport.serializeUser(function (user: any, done) {
    done(null, user.id);
  });
  passport.deserializeUser(async function (id: number, done) {
    const user = await prisma.user.findUnique({
      where: { id },
    });
    if (!user) {
      return done("cannot find user");
    }

    done(null, { id: user.id, username: user.nickname });
  });

  app.set("trust proxy", 1);
  app.use(
    session({
      name: "mnbmnbmbn",
      secret: "somesecret",
      resave: false,
      saveUninitialized: true,
      cookie: {
        maxAge: 1000 * 60 * 60 * 24 * 7,
        sameSite: "lax",
        secure: false,
      },
    })
  );
  app.use(passport.initialize());
  app.use(passport.session());
  app.use(bodyParser.urlencoded({ extended: false }));

  const httpServer = createServer(app);

  const schema = makeExecutableSchema({ typeDefs, resolvers });

  const apolloServer = new ApolloServer({
    schema,
    plugins: [
      ApolloServerPluginDrainHttpServer({ httpServer }),
      {
        serverWillStart: async () => ({
          //drainServer: async () => await serverCleanup.dispose(),
        }),
      },
      ApolloServerPluginLandingPageLocalDefault({ embed: true }),
    ],
    context: ({ req, res }) => ({ req, res }),
  });

  await apolloServer.start();

  apolloServer.applyMiddleware({
    app,
    cors: {
      origin: "http://138.68.66.201:5000",
    },
  });

  httpServer.listen(port, () => console.log(`started, http://localhost:4000`));
})();
</code>```

What's the problem?

Body:
I have a simple login by nickname:

async login(
      _: any,
      args: UserFindArgs,
      { req, res }: Context
    ): Promise<User | null> {
      const user = await prisma.user.findUnique({
        where: { nickname: args.nickname },
      });
      console.log(req.user);
      req.logIn(user, (err: any) => {
        if (err) {
          return null;
        }
      });
      console.log(req.user);
      return user;
    },

after login console returns user, which is fine: console.log

but when I try to get that user in query:

    async me(
      _: any,
      args: UserFindArgs,
      { req, res }: Context
    ): Promise<String> {
      console.log(req.user); // req.isauthenticated() is also false
      return "req";
    },

it's returning undefined

index.ts:

(async () => {
  const app = express();

  passport.serializeUser(function (user: any, done) {
    done(null, user.id);
  });
  passport.deserializeUser(async function (id: number, done) {
    const user = await prisma.user.findUnique({
      where: { id },
    });
    if (!user) {
      return done("cannot find user");
    }

    done(null, { id: user.id, username: user.nickname });
  });

  app.set("trust proxy", 1);
  app.use(
    session({
      name: "mnbmnbmbn",
      secret: "somesecret",
      resave: false,
      saveUninitialized: true,
      cookie: {
        maxAge: 1000 * 60 * 60 * 24 * 7,
        sameSite: "lax",
        secure: false,
      },
    })
  );
  app.use(passport.initialize());
  app.use(passport.session());
  app.use(bodyParser.urlencoded({ extended: false }));

  const httpServer = createServer(app);

  const schema = makeExecutableSchema({ typeDefs, resolvers });

  const apolloServer = new ApolloServer({
    schema,
    plugins: [
      ApolloServerPluginDrainHttpServer({ httpServer }),
      {
        serverWillStart: async () => ({
          //drainServer: async () => await serverCleanup.dispose(),
        }),
      },
      ApolloServerPluginLandingPageLocalDefault({ embed: true }),
    ],
    context: ({ req, res }) => ({ req, res }),
  });

  await apolloServer.start();

  apolloServer.applyMiddleware({
    app,
    cors: {
      origin: "http://138.68.66.201:5000",
    },
  });

  httpServer.listen(port, () => console.log(`started, http://localhost:4000`));
})();

What's the problem?