问:
Why does this simple SSI not render the include?
I'm trying to add ssi to a more complex project without success. I've whittled it down to the simplest possible and it still does not work. I'm obviously missing something very simple, but what?

OS: Windows 10 Pro, build 19045.2251

Server:

```<code>Server version: Apache/2.4.46 (Win64)
Apache Lounge VS16 Server built:   Oct  2 2020 11:45:39
</code>```

relevant http.conf lines not commented out:

```<code>LoadModule include_module modules/mod_include.so
LoadModule mime_module modules/mod_mime.so
</code>```

http.conf contains:

```<code>...
<Directory "c:/Apache24/htdocs">
...
    Options +Includes
    AddType text/html .shtml
    AddOutputFilter INCLUDES .shtml
...
</code>```

C:\Apache24\htdocs contents:

```<code>index.html
bogus.shtml
</code>```

index.html:

```<code><html><body>
<!--#include file="bogus.shtml"  -->
<h1>It works!</h1></body></html>
</code>```

bogus.shtml:

```<code><h4>Nothing to see here</h4>
</code>```

Yet http://localhost renders only It works!

Body:
I'm trying to add ssi to a more complex project without success. I've whittled it down to the simplest possible and it still does not work. I'm obviously missing something very simple, but what?

OS: Windows 10 Pro, build 19045.2251

Server:

Server version: Apache/2.4.46 (Win64)
Apache Lounge VS16 Server built:   Oct  2 2020 11:45:39

relevant http.conf lines not commented out:

LoadModule include_module modules/mod_include.so
LoadModule mime_module modules/mod_mime.so

http.conf contains:

...
<Directory "c:/Apache24/htdocs">
...
    Options +Includes
    AddType text/html .shtml
    AddOutputFilter INCLUDES .shtml
...

C:\Apache24\htdocs contents:

index.html
bogus.shtml

index.html:

It works!

bogus.shtml:

Nothing to see here

Yet http://localhost renders only It works!


来源: stackexchange

问:
how can i generate a program that guess a word and apply by a button?
i made a button in an html document, that suppose to chose one word from a 20 words i defiend in a what supposed to be a nice guessing program that include a search bar  which the user of the program guess one of the words at the search bar (from the 20 i defiend) and the program picks one word randomly and shows that after the user made his guess.

i did the button and search bar but when the user write a word and press the button to get the word that picked by the program nothing happens .

i guess that the problem is at the script  i wrote.

```<code> let teams = ["atalanta", "Bologna", "Cremonese", "Empoli", "Fiorentina",
"Verona", "Inter", "Juventus", "Lazio", "Lecce", "Milan", "Monza",
 "Napoli", "Roma", "Salernitana", "Sampdoria", "Sassuolo", "Spezia",
  "Torino", "Udinese"];

  let secretTeam = teams[Math.floor(Math.random() * 20)];
  console.log(secretTeam);

document.querySelector('.search').addEventListener('.click' , function() {
const guess = teams(document.querySelector('.guess').value);

    if(guess === secretTeam) {
        document.querySelector('.messege').textContent = (secretTeam),'you right!';
        document.querySelector('body').style.backgroundColor = '#4ceb34';}

   else{
        document.querySelector('.messege').textContent = (secretTeam),'wrong answer';
        document.querySelector('body').style.backgroundColor = '#f71505';
   }

})
</code>```

this is my script

ContentLicense: CC BY-SA 4.0

Body:
i made a button in an html document, that suppose to chose one word from a 20 words i defiend in a what supposed to be a nice guessing program that include a search bar  which the user of the program guess one of the words at the search bar (from the 20 i defiend) and the program picks one word randomly and shows that after the user made his guess.

i did the button and search bar but when the user write a word and press the button to get the word that picked by the program nothing happens .

i guess that the problem is at the script  i wrote.

 let teams = ["atalanta", "Bologna", "Cremonese", "Empoli", "Fiorentina",
"Verona", "Inter", "Juventus", "Lazio", "Lecce", "Milan", "Monza",
 "Napoli", "Roma", "Salernitana", "Sampdoria", "Sassuolo", "Spezia",
  "Torino", "Udinese"];

  let secretTeam = teams[Math.floor(Math.random() * 20)];
  console.log(secretTeam);

document.querySelector('.search').addEventListener('.click' , function() {
const guess = teams(document.querySelector('.guess').value);

    if(guess === secretTeam) {
        document.querySelector('.messege').textContent = (secretTeam),'you right!';
        document.querySelector('body').style.backgroundColor = '#4ceb34';}

   else{
        document.querySelector('.messege').textContent = (secretTeam),'wrong answer';
        document.querySelector('body').style.backgroundColor = '#f71505';
   }

})

this is my script


问:
Get Google OAuth2 token without browser?
I am writing a service that will access a Google Nest Thermostat, and need a Google Oauth2 token in order to do so.  All of the documentation I can find references a browser-driven login to identify, authenticate, and then store a token as a cookie.

All of my OAuth experience has involved receiving a secret and/or API key, and then using that against a token service to get a security token.  I then use that token for subsequent API endpoints.  All of the Google docs / samples tell me I have to get my "headless" service to log in via browser and get a token via a redirect, the same way I'd log in to any other service using my Google credentials.  Is there a way to do this without a live browser session, i.e. just a Google endpoint that I trigger with my secret data, to get a token to use with the Google Smart Home APIs?


问:
Is it possible to dynamically position a "tooltip" (div) such that it does not go outside the window using only CSS?
I have code that makes popups (I recommended to do this by an accessibility consultant) based on focus using only CSS and tag attributes.  It works great until the focused element is too near the right side or bottom of the window, and then I need specific markup to flip the tooltip to the other side of (or above) the focused element.

I'd like to have generic CSS that "just works" without knowing the placement of the focused element ahead of time (this is for a responsive layout that reflows for different window sizes)

I know I can solve this with Javascript, and there is already a question talking about that (Display a div on mouse enter, cannot be seen if mouse position is in the right-most) but I'd really like to do it using only CSS.

Fiddle:  https://jsfiddle.net/e6g39Lvb/

HTML:

```<code><div id="wrapper">
<p>
<input type="text" /> Place cursor here and hit "tab" key to move focus
</p>
<a href="#" title="this is just an example link that does nothing">example link 1</a>
<div class="rightside">
<a href="#" title="this is just an example link that does nothing">example link 2</a>
<br />
<a class="corrected" href="#" title="this only works if I already know it's on the right edge of the screen">example link 3</a>
</div>
</div>
</code>```

CSS

```<code>#wrapper{
  margin: 1em;
}
.rightside{
  text-align: right;
}
*:not(:hover):focus{
  position:relative;
  border: 1px solid red;
}
*[title]:not(:hover):focus:after { /* show tooltip on focus but user default for hover */
    text-align: left;
    border: 1px solid #fc0;
    padding: 3px 6px;
    color: black;
    background: #fffea1;
    content: attr(title) !important;
    position: absolute;
    width: auto;
    min-width: 5em;
    max-width: 15em;
    transform: translate(0.5em,-30%);
}
.corrected[title]:not(:hover):focus:after {
      transform: translate(-100%,-30%);
      left: -0.5em;
}
</code>```

Just to be clear:  I know to achieve this with JS, I'm looking for a CSS only answer (if it's possible)

Body:
I have code that makes popups (I recommended to do this by an accessibility consultant) based on focus using only CSS and tag attributes.  It works great until the focused element is too near the right side or bottom of the window, and then I need specific markup to flip the tooltip to the other side of (or above) the focused element.

I'd like to have generic CSS that "just works" without knowing the placement of the focused element ahead of time (this is for a responsive layout that reflows for different window sizes)

I know I can solve this with Javascript, and there is already a question talking about that (Display a div on mouse enter, cannot be seen if mouse position is in the right-most) but I'd really like to do it using only CSS.

Fiddle:  https://jsfiddle.net/e6g39Lvb/

HTML:

<input type="text" /> Place cursor here and hit "tab" key to move focus

example link 1

example link 2

example link 3

CSS

#wrapper{
  margin: 1em;
}
.rightside{
  text-align: right;
}
*:not(:hover):focus{
  position:relative;
  border: 1px solid red;
}
*[title]:not(:hover):focus:after { /* show tooltip on focus but user default for hover */
    text-align: left;
    border: 1px solid #fc0;
    padding: 3px 6px;
    color: black;
    background: #fffea1;
    content: attr(title) !important;
    position: absolute;
    width: auto;
    min-width: 5em;
    max-width: 15em;
    transform: translate(0.5em,-30%);
}
.corrected[title]:not(:hover):focus:after {
      transform: translate(-100%,-30%);
      left: -0.5em;
}

Just to be clear:  I know to achieve this with JS, I'm looking for a CSS only answer (if it's possible)


问:
Vue js and Laravel problem with computed properties can't save data in database
Iam beginner in vue js and i need help.I'm working on invoice application and i want when select customer to auto fill data properties and i'm using computed properties to get data which i need.
I succeed to save only once in database and then it gives me error in laravelI see in vue devtool that computed properties remain the same like first time and they don't change except when i click on component in vuetools and they will be saved again.This is my data form:

```<code>form: {
    customer_id: null,
    project_id: null,
    invoice_date: this.invoice_data.invoice_date,
    due_date: null,
    invoice_number: this.invoice_data.invoice_number,
    item_id: null,
    billing_address: null,
    billing_city: null,
    billing_state: null,
    billing_zip_code: null,
    billing_country_id : null,
    shipping_country_id: null,
    shipping_address: null,
    shipping_city: null,
    shipping_state: null,
    shipping_zip_code: null,
    items_test: null,

},
</code>```

This is my computed property how i find data when i select customer:

```<code>customer_object: function() {
    return this.customers.find(customer => customer.id === this.form.customer_id) ?? ""

},

</code>```

These are my props:

```<code>props: {
    customers: Object,
    users: Object,
    countries: Object,
    currencies:Object,
    items:Object,
    payment_modes: Object,
    invoice_data: Object,
    // invoice_items:Object,
    products:Object,
    // projects:Object,
    // customers_projects: Object,
    // filters: Object,
    // groups: Object,
    errors: Object,
},
</code>```

This is another computed how i try to put values in form when i select customer:

```<code>formCount: function () {

   return [
        this.form.billing_address = this.customer_object.address,
        this.form.billing_city = this.customer_object.city,
        this.form.billing_state = this.customer_object.state,
        this.form.billing_zip_code = this.customer_object.zip_code,
        this.form.billing_country_id = this.customer_object.country_id,
        this.form.shipping_city = this.customer_object.shipping_city,
        this.form.shipping_state = this.customer_object.shipping_state,
        this.form.shipping_address = this.customer_object.shipping_address,
        this.form.shipping_zip_code = this.customer_object.shipping_zip_code,
        this.form.shipping_country_id = this.customer_object.shipping_country_id,
        ]
},
</code>```

Body:
Iam beginner in vue js and i need help.I'm working on invoice application and i want when select customer to auto fill data properties and i'm using computed properties to get data which i need.
I succeed to save only once in database and then it gives me error in laravelI see in vue devtool that computed properties remain the same like first time and they don't change except when i click on component in vuetools and they will be saved again.This is my data form:

form: {
    customer_id: null,
    project_id: null,
    invoice_date: this.invoice_data.invoice_date,
    due_date: null,
    invoice_number: this.invoice_data.invoice_number,
    item_id: null,
    billing_address: null,
    billing_city: null,
    billing_state: null,
    billing_zip_code: null,
    billing_country_id : null,
    shipping_country_id: null,
    shipping_address: null,
    shipping_city: null,
    shipping_state: null,
    shipping_zip_code: null,
    items_test: null,

},

This is my computed property how i find data when i select customer:

customer_object: function() {
    return this.customers.find(customer => customer.id === this.form.customer_id) ?? ""

},

These are my props:

props: {
    customers: Object,
    users: Object,
    countries: Object,
    currencies:Object,
    items:Object,
    payment_modes: Object,
    invoice_data: Object,
    // invoice_items:Object,
    products:Object,
    // projects:Object,
    // customers_projects: Object,
    // filters: Object,
    // groups: Object,
    errors: Object,
},

This is another computed how i try to put values in form when i select customer:

formCount: function () {

   return [
        this.form.billing_address = this.customer_object.address,
        this.form.billing_city = this.customer_object.city,
        this.form.billing_state = this.customer_object.state,
        this.form.billing_zip_code = this.customer_object.zip_code,
        this.form.billing_country_id = this.customer_object.country_id,
        this.form.shipping_city = this.customer_object.shipping_city,
        this.form.shipping_state = this.customer_object.shipping_state,
        this.form.shipping_address = this.customer_object.shipping_address,
        this.form.shipping_zip_code = this.customer_object.shipping_zip_code,
        this.form.shipping_country_id = this.customer_object.shipping_country_id,
        ]
},


问:
How can I use my model for a single picture?
I trained a machine and I got the model now.
This is my code:( It works fine but i wanna use it for a single picture.)

```<code>import numpy as np
import pandas as pd
import os
import cv2
import matplotlib.pyplot as plt
from tqdm import tqdm
from random import shuffle
from keras.utils  import to_categorical
import pickle
def load_rand():
    X=[]
    dir_path='D:/dataset/train'
    for sub_dir in tqdm(os.listdir(dir_path)):
        print(sub_dir)
        path_main=os.path.join(dir_path,sub_dir)
        i=0
        for img_name in os.listdir(path_main):
            if i>=6:
                break
            img=cv2.imread(os.path.join(path_main,img_name))
            img=cv2.resize(img,(100,100))
            img=cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
            X.append(img)
            i+=1
    return X
X=load_rand()
X=np.array(X)
X.shape
def show_subpot(X,title=False,Y=None):
    if X.shape[0]==36:
        f, ax= plt.subplots(6,6, figsize=(40,60))
        list_fruits=['rottenoranges', 'rottenapples', 'freshbanana', 'freshoranges', 'rottenbanana', 'freshapples']
        for i,img in enumerate(X):
            ax[i//6][i%6].imshow(img, aspect='auto')
            if title==False:
                ax[i//6][i%6].set_title(list_fruits[i//6])
            elif title and Y is not None:
                ax[i//6][i%6].set_title(Y[i])
        plt.show()
    else:
        print('Cannot plot')
show_subpot(X)
del X
def load_rottenvsfresh():
    quality=['fresh', 'rotten']
    X,Y=[],[]
    z=[]
    for cata in tqdm(os.listdir('D:/dataset/train')):
        if quality[0] in cata:
            path_main=os.path.join('D:/dataset/train',cata)
            for img_name in os.listdir(path_main):
                img=cv2.imread(os.path.join(path_main,img_name))
                img=cv2.resize(img,(100,100))
                img=cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
                z.append([img,0])
        else:
            path_main=os.path.join('D:/dataset/train',cata)
            for img_name in os.listdir(path_main):
                img=cv2.imread(os.path.join(path_main,img_name))
                img=cv2.resize(img,(100,100))
                img=cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
                z.append([img,1])
    print('Shuffling your data.....')
    shuffle(z)
    for images, labels in tqdm(z):
        X.append(images);Y.append(labels)
    return X,Y
X,Y=load_rottenvsfresh()
Y=np.array(Y)
X=np.array(X)
y_ser=pd.Series(Y)
y_ser.value_counts()
def load_rottenvsfresh_valset():
    quality=['fresh', 'rotten']
    X,Y=[],[]
    z=[]
    for cata in tqdm(os.listdir('D:/dataset/test')):
        if quality[0] in cata:
            path_main=os.path.join('D:/dataset/test',cata)
            for img_name in os.listdir(path_main):
                img=cv2.imread(os.path.join(path_main,img_name))
                img=cv2.resize(img,(100,100))
                img=cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
                z.append([img,0])
        else:
            path_main=os.path.join('D:/dataset/test',cata)
            for img_name in os.listdir(path_main):
                img=cv2.imread(os.path.join(path_main,img_name))
                img=cv2.resize(img,(100,100))
                img=cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
                z.append([img,1])
    print('Shuffling your data.....')
    shuffle(z)
    for images, labels in tqdm(z):
        X.append(images);Y.append(labels)
    return X,Y
X_val,Y_val=load_rottenvsfresh_valset()
Y_val=np.array(Y_val)
X_val=np.array(X_val)
y_ser=pd.Series(Y_val)
y_ser.value_counts()
import keras
from keras.layers import Dense,Dropout, Conv2D,MaxPooling2D , Activation, Flatten, BatchNormalization, SeparableConv2D
from keras.models import Sequential
X=X/255.0
X_val=X_val/255.0
model.evaluate(X_val,Y_val)
model=load_model('D:/dataset/rottenvsfresh.h5')
from keras.models import Model, load_model
new_model=load_model('D:/dataset/rotten.h5')
new_model.evaluate(X_val,Y_val)
plt.imshow(X_val[0])
model.predict(X_val[0].reshape(1,100,100,3))
show_subpot(X_val[-36*11:-36*10])
#model.predict(X_val[-36*11:-36*10])
y_pred =model.predict(X_val[-36*11:-36*10])
np.round(y_pred).astype(int)
</code>```

I trained the model to classify rotten fruit from the fresh one. I do not have enough experince in machine learning and this is my first project. I could do this in general but now I wanna try the model for single pictures as input. ( I copy pasted the codes from jupiter cells.)
I tried a lot to use the model for a single picture as input but it dosen't work.

This is how I tried: (But it gives wrong output.)

```<code># Load the image you want to classify
img_path = "C:/Users/d/Desktop/hjbjkh/lo.jpg"
img = load_image(img_path)

# Preprocess the image and prepare it for classification
img = np.array([img])  # Add a batch dimension

# Print a summary of the model's architecture
model.summary()

# Use the classification model to predict the class of the image
predictions = model.predict(img)

# Get the predicted class
predicted_class = np.argmax(predictions)

# If desired, display the image and the predicted class
print("Predicted class:", predicted_class)
plt.imshow(img[0])
</code>```

Edited part from what i get from comments:

```<code># Import PyTorch
import torch

# Load the image you want to classify
img_path = "C:/Users/d/Desktop/hjbjkh/ad.jpg"
img = cv2.imread(img_path)

# Resize the image to the desired dimensions
img = cv2.resize(img, (100, 100))

# Convert the image from BGR color space to RGB color space
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

# Convert the image from a NumPy array to a PyTorch tensor
img = torch.from_numpy(img)

# Add a batch dimension to the image
img = img.unsqueeze(0)

# Convert the image from a PyTorch tensor to a NumPy array
img = img.numpy()

# Use the classification model to predict the class of the image
predictions = model.predict(img)

# Get the predicted class
predicted_class = np.argmax(predictions)

# If desired, display the image and the predicted class
print("Predicted class:", predicted_class)
plt.imshow(img[0])
</code>```

Body:
I trained a machine and I got the model now.
This is my code:( It works fine but i wanna use it for a single picture.)

import numpy as np
import pandas as pd
import os
import cv2
import matplotlib.pyplot as plt
from tqdm import tqdm
from random import shuffle
from keras.utils  import to_categorical
import pickle
def load_rand():
    X=[]
    dir_path='D:/dataset/train'
    for sub_dir in tqdm(os.listdir(dir_path)):
        print(sub_dir)
        path_main=os.path.join(dir_path,sub_dir)
        i=0
        for img_name in os.listdir(path_main):
            if i>=6:
                break
            img=cv2.imread(os.path.join(path_main,img_name))
            img=cv2.resize(img,(100,100))
            img=cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
            X.append(img)
            i+=1
    return X
X=load_rand()
X=np.array(X)
X.shape
def show_subpot(X,title=False,Y=None):
    if X.shape[0]==36:
        f, ax= plt.subplots(6,6, figsize=(40,60))
        list_fruits=['rottenoranges', 'rottenapples', 'freshbanana', 'freshoranges', 'rottenbanana', 'freshapples']
        for i,img in enumerate(X):
            ax[i//6][i%6].imshow(img, aspect='auto')
            if title==False:
                ax[i//6][i%6].set_title(list_fruits[i//6])
            elif title and Y is not None:
                ax[i//6][i%6].set_title(Y[i])
        plt.show()
    else:
        print('Cannot plot')
show_subpot(X)
del X
def load_rottenvsfresh():
    quality=['fresh', 'rotten']
    X,Y=[],[]
    z=[]
    for cata in tqdm(os.listdir('D:/dataset/train')):
        if quality[0] in cata:
            path_main=os.path.join('D:/dataset/train',cata)
            for img_name in os.listdir(path_main):
                img=cv2.imread(os.path.join(path_main,img_name))
                img=cv2.resize(img,(100,100))
                img=cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
                z.append([img,0])
        else:
            path_main=os.path.join('D:/dataset/train',cata)
            for img_name in os.listdir(path_main):
                img=cv2.imread(os.path.join(path_main,img_name))
                img=cv2.resize(img,(100,100))
                img=cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
                z.append([img,1])
    print('Shuffling your data.....')
    shuffle(z)
    for images, labels in tqdm(z):
        X.append(images);Y.append(labels)
    return X,Y
X,Y=load_rottenvsfresh()
Y=np.array(Y)
X=np.array(X)
y_ser=pd.Series(Y)
y_ser.value_counts()
def load_rottenvsfresh_valset():
    quality=['fresh', 'rotten']
    X,Y=[],[]
    z=[]
    for cata in tqdm(os.listdir('D:/dataset/test')):
        if quality[0] in cata:
            path_main=os.path.join('D:/dataset/test',cata)
            for img_name in os.listdir(path_main):
                img=cv2.imread(os.path.join(path_main,img_name))
                img=cv2.resize(img,(100,100))
                img=cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
                z.append([img,0])
        else:
            path_main=os.path.join('D:/dataset/test',cata)
            for img_name in os.listdir(path_main):
                img=cv2.imread(os.path.join(path_main,img_name))
                img=cv2.resize(img,(100,100))
                img=cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
                z.append([img,1])
    print('Shuffling your data.....')
    shuffle(z)
    for images, labels in tqdm(z):
        X.append(images);Y.append(labels)
    return X,Y
X_val,Y_val=load_rottenvsfresh_valset()
Y_val=np.array(Y_val)
X_val=np.array(X_val)
y_ser=pd.Series(Y_val)
y_ser.value_counts()
import keras
from keras.layers import Dense,Dropout, Conv2D,MaxPooling2D , Activation, Flatten, BatchNormalization, SeparableConv2D
from keras.models import Sequential
X=X/255.0
X_val=X_val/255.0
model.evaluate(X_val,Y_val)
model=load_model('D:/dataset/rottenvsfresh.h5')
from keras.models import Model, load_model
new_model=load_model('D:/dataset/rotten.h5')
new_model.evaluate(X_val,Y_val)
plt.imshow(X_val[0])
model.predict(X_val[0].reshape(1,100,100,3))
show_subpot(X_val[-36*11:-36*10])
#model.predict(X_val[-36*11:-36*10])
y_pred =model.predict(X_val[-36*11:-36*10])
np.round(y_pred).astype(int)

I trained the model to classify rotten fruit from the fresh one. I do not have enough experince in machine learning and this is my first project. I could do this in general but now I wanna try the model for single pictures as input. ( I copy pasted the codes from jupiter cells.)
I tried a lot to use the model for a single picture as input but it dosen't work.

This is how I tried: (But it gives wrong output.)

# Load the image you want to classify
img_path = "C:/Users/d/Desktop/hjbjkh/lo.jpg"
img = load_image(img_path)

# Preprocess the image and prepare it for classification
img = np.array([img])  # Add a batch dimension

# Print a summary of the model's architecture
model.summary()

# Use the classification model to predict the class of the image
predictions = model.predict(img)

# Get the predicted class
predicted_class = np.argmax(predictions)

# If desired, display the image and the predicted class
print("Predicted class:", predicted_class)
plt.imshow(img[0])

Edited part from what i get from comments:

# Import PyTorch
import torch

# Load the image you want to classify
img_path = "C:/Users/d/Desktop/hjbjkh/ad.jpg"
img = cv2.imread(img_path)

# Resize the image to the desired dimensions
img = cv2.resize(img, (100, 100))

# Convert the image from BGR color space to RGB color space
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

# Convert the image from a NumPy array to a PyTorch tensor
img = torch.from_numpy(img)

# Add a batch dimension to the image
img = img.unsqueeze(0)

# Convert the image from a PyTorch tensor to a NumPy array
img = img.numpy()

# Use the classification model to predict the class of the image
predictions = model.predict(img)

# Get the predicted class
predicted_class = np.argmax(predictions)

# If desired, display the image and the predicted class
print("Predicted class:", predicted_class)
plt.imshow(img[0])


问:
How to add an array of markers using Lat/Lng - google maps api
Would someone be able to explain what I need to do to add an array of markers using javascript. I understand that basics of displaying the map and adding a marker or even multiple markers but they have to be hard coded in. I want to display a list of markers from an API.

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>

test

```


问:
Open Access data
I wanted to know if it is possible to find open access Lidar and Photogrammetry data for the same area. I came across OpenTopography where thee are plenty of Lidar or Photogrammetry data, but is it possible to search for both sources of data for one place?

Title: Open Access data


问:
Why mac terminal screen gives me different characters then pyserial?
I'm trying transfer a .jpeg image from one device to another using serial communication. If I use mac built-in screen command in terminal

```<code>screen /dev/cu.usbserial-6 115200
</code>```

I get correct .jpg image starting with the right header

```<code>ÿØÿàJFIF
</code>```

But if I use pyserial, I get

```<code>Ã¿Ã˜Ã¿Ã JFIF
</code>```

Python receiving code:

```<code>import serial

ser = serial.Serial('/dev/cu.usbserial-5', 115200)

while True:
    s = ser.read(1)

    try:
        print(s.decode('charmap'), end='')

    except:
        pass
</code>```

I believe it has something to do with encoding but I'm not sure what. All the non-exteded ascii values are the same in screen and pyserial.

If I convert "ÿØÿàJFIF" on website https://www.rapidtables.com/convert/number/ascii-to-hex.html, in ASCII encoding, it gives me correct start values for .jpeg

FF D8 FF E0 4A 46 49 46

but if I do it in UTF-8, it gives me

C3 BF C3 98 C3 BF C3 A0 4A 46 49 46

which has the same start as the value from pyserial in ASCII

Ã¿Ã˜Ã¿Ã JFIF
C3 BF C3 98 C3 BF C3 20 10 4A 46 49 46

I'm not sure what exactly is wrong.

Thank you

Body:
I'm trying transfer a .jpeg image from one device to another using serial communication. If I use mac built-in screen command in terminal

screen /dev/cu.usbserial-6 115200

I get correct .jpg image starting with the right header

ÿØÿàJFIF

But if I use pyserial, I get

Ã¿Ã˜Ã¿Ã JFIF

Python receiving code:

import serial

ser = serial.Serial('/dev/cu.usbserial-5', 115200)

while True:
    s = ser.read(1)

    try:
        print(s.decode('charmap'), end='')

    except:
        pass

I believe it has something to do with encoding but I'm not sure what. All the non-exteded ascii values are the same in screen and pyserial.

If I convert "ÿØÿàJFIF" on website https://www.rapidtables.com/convert/number/ascii-to-hex.html, in ASCII encoding, it gives me correct start values for .jpeg

FF D8 FF E0 4A 46 49 46

but if I do it in UTF-8, it gives me

C3 BF C3 98 C3 BF C3 A0 4A 46 49 46

which has the same start as the value from pyserial in ASCII

Ã¿Ã˜Ã¿Ã JFIF
C3 BF C3 98 C3 BF C3 20 10 4A 46 49 46

I'm not sure what exactly is wrong.

Thank you


问:
React Outside Hook not reacting to outside Click
I am finishing up a project where I want to use a small dropdown menu when I click on my settings icon. The problem is that for some reason it is not recognized when I click outside of that dropdown menu. I used a hook that worked in the same project with a different dropdown menu, but now it doesn't. Maybe because it is in a modal? I really don't know.

Here is the Repo of this Project: https://github.com/Clytax/fem-kanban

The Hook (I modified it a bit by excluding the elipsis icon so it doesnt reopen when Click on it to close it.)

```<code>import React from "react";
export const useOutsideClick = (callback, exclude) => {
  const ref = React.useRef();

  React.useEffect(() => {
    const handleClick = (e) => {
      if (
        ref.current &&
        !ref.current.contains(e.target) &&
        !exclude.current.contains(e.target)
      ) {
        callback();
      }
    };

    document.addEventListener("click", handleClick);

    return () => {
      document.removeEventListener("click", handleClick);
    };
  }, [callback, exclude]);

  return ref;
};

</code>```

The Modal:

```<code>import React, { useRef, useState, useEffect } from "react";
import "./taskModal.scss";
import { ReactComponent as Elipsis } from "../../../assets/Icons/icon-vertical-ellipsis.svg";
import { ReactComponent as Close } from "../../../assets/Icons/icon-chevron-up.svg";
import { ReactComponent as Open } from "../../../assets/Icons/icon-chevron-down.svg";
import { useSelector, useDispatch } from "react-redux";
import modalSlice, {
  closeViewTaskModal,
  openEditTaskModal,
  closeAllModals,
  openDeleteTaskModal,
} from "../../../features/global/modalSlice";
import Backdrop from "../Backdrop/Backdrop";
import Subtask from "../../Task/Subtask";

import "../../Extra/DropdownSettings.scss";

import { useOutsideClick } from "../../../hooks/useOutsideClick";

import { motion } from "framer-motion";
import DropdownStatus from "../../Extra/DropdownStatus";
import DropdownSettings from "../../Extra/DropdownSettings";
import DropdownSettingsTask from "../../Extra/DropdownSettingsTask";

const ViewTaskModal = ({ handleClose }) => {
  const [openSettings, setOpenSettings] = useState(false);
  const dispatch = useDispatch();
  const task = useSelector((state) => state.modal.viewTaskModal.task);
  const handleCloseSettings = () => {
    console.log("hi");
    setOpenSettings(false);
  };

  const modal = useSelector((state) => state.modal);
  const viewTaskModal = useSelector((state) => state.modal.viewTaskModal);
  const elipsisRef = useRef(null);
  const wrapperRef = useOutsideClick(handleCloseSettings, elipsisRef);

  const getFinishedSubTasks = () => {
    let finishedSubTasks = 0;
    task.subTasks.forEach((subtask) => {
      if (subtask.isDone) {
        finishedSubTasks++;
      }
    });
    return finishedSubTasks;
  };

  const closeModal = () => {
    dispatch(closeViewTaskModal());
  };
  return (
    <Backdrop onClick={closeModal} mobile={false}>
      <motion.div
        onClick={(e) => {
          e.stopPropagation();
        }}
        onMouseDown={(e) => {
          e.stopPropagation();
        }}
        className="view-task"
      >
        <div className="view-task__header | flex">
          <h2 className="view-task__header__title">{task.name}</h2>
          <div className="view-tastk__settings">
            <div
              className="view-task__header__icon"
              style={{ cursor: "pointer" }}
              ref={elipsisRef}
              onClick={() => {
                setOpenSettings(!openSettings);
              }}
            >
              <Elipsis />
            </div>
            {openSettings && (
              <div className="dropdown-settings__task" ref={wrapperRef}>
                <div
                  className="dropdown-settings__item"
                  onClick={() => {
                    dispatch(closeAllModals());
                    dispatch(openEditTaskModal(task));
                  }}
                >
                  Edit Task
                </div>
                <div
                  className="dropdown-settings__item"
                  onClick={() => {
                    dispatch(closeAllModals());
                    dispatch(openDeleteTaskModal(task));
                  }}
                >
                  Delete Task
                </div>
              </div>
            )}
          </div>
        </div>
        <p className="view-task__description">{task.description}</p>

        <div className="view-task__subtasks">
          <p>
            Subtasks ({getFinishedSubTasks()} of {task.subTasks.length})
          </p>
          <div className="view-task__subtasks__list">
            {task.subTasks.map((subtask, index) => (
              <Subtask
                subtaskID={subtask.id}
                boardID={task.boardID}
                taskID={task.id}
                columnID={task.columnID}
                key={index}
              />
            ))}
          </div>
        </div>
        <div className="view-task__status">
          <p>Current Status</p>
          <DropdownStatus click={handleCloseSettings} task={task} />
        </div>
      </motion.div>
    </Backdrop>
  );
};

export default ViewTaskModal;

</code>```

Body:
I am finishing up a project where I want to use a small dropdown menu when I click on my settings icon. The problem is that for some reason it is not recognized when I click outside of that dropdown menu. I used a hook that worked in the same project with a different dropdown menu, but now it doesn't. Maybe because it is in a modal? I really don't know.

Here is the Repo of this Project: https://github.com/Clytax/fem-kanban

The Hook (I modified it a bit by excluding the elipsis icon so it doesnt reopen when Click on it to close it.)

import React from "react";
export const useOutsideClick = (callback, exclude) => {
  const ref = React.useRef();

  React.useEffect(() => {
    const handleClick = (e) => {
      if (
        ref.current &&
        !ref.current.contains(e.target) &&
        !exclude.current.contains(e.target)
      ) {
        callback();
      }
    };

    document.addEventListener("click", handleClick);

    return () => {
      document.removeEventListener("click", handleClick);
    };
  }, [callback, exclude]);

  return ref;
};

The Modal:

import React, { useRef, useState, useEffect } from "react";
import "./taskModal.scss";
import { ReactComponent as Elipsis } from "../../../assets/Icons/icon-vertical-ellipsis.svg";
import { ReactComponent as Close } from "../../../assets/Icons/icon-chevron-up.svg";
import { ReactComponent as Open } from "../../../assets/Icons/icon-chevron-down.svg";
import { useSelector, useDispatch } from "react-redux";
import modalSlice, {
  closeViewTaskModal,
  openEditTaskModal,
  closeAllModals,
  openDeleteTaskModal,
} from "../../../features/global/modalSlice";
import Backdrop from "../Backdrop/Backdrop";
import Subtask from "../../Task/Subtask";

import "../../Extra/DropdownSettings.scss";

import { useOutsideClick } from "../../../hooks/useOutsideClick";

import { motion } from "framer-motion";
import DropdownStatus from "../../Extra/DropdownStatus";
import DropdownSettings from "../../Extra/DropdownSettings";
import DropdownSettingsTask from "../../Extra/DropdownSettingsTask";

const ViewTaskModal = ({ handleClose }) => {
  const [openSettings, setOpenSettings] = useState(false);
  const dispatch = useDispatch();
  const task = useSelector((state) => state.modal.viewTaskModal.task);
  const handleCloseSettings = () => {
    console.log("hi");
    setOpenSettings(false);
  };

  const modal = useSelector((state) => state.modal);
  const viewTaskModal = useSelector((state) => state.modal.viewTaskModal);
  const elipsisRef = useRef(null);
  const wrapperRef = useOutsideClick(handleCloseSettings, elipsisRef);

  const getFinishedSubTasks = () => {
    let finishedSubTasks = 0;
    task.subTasks.forEach((subtask) => {
      if (subtask.isDone) {
        finishedSubTasks++;
      }
    });
    return finishedSubTasks;
  };

  const closeModal = () => {
    dispatch(closeViewTaskModal());
  };
  return (
    <Backdrop onClick={closeModal} mobile={false}>
      <motion.div
        onClick={(e) => {
          e.stopPropagation();
        }}
        onMouseDown={(e) => {
          e.stopPropagation();
        }}
        className="view-task"
      >

{task.name}

 {
                setOpenSettings(!openSettings);
              }}
            >
              <Elipsis />

            {openSettings && (

 {
                    dispatch(closeAllModals());
                    dispatch(openEditTaskModal(task));
                  }}
                >
                  Edit Task

 {
                    dispatch(closeAllModals());
                    dispatch(openDeleteTaskModal(task));
                  }}
                >
                  Delete Task

            )}

{task.description}

            Subtasks ({getFinishedSubTasks()} of {task.subTasks.length})

            {task.subTasks.map((subtask, index) => (
              <Subtask
                subtaskID={subtask.id}
                boardID={task.boardID}
                taskID={task.id}
                columnID={task.columnID}
                key={index}
              />
            ))}

Current Status

          <DropdownStatus click={handleCloseSettings} task={task} />

      </motion.div>
    </Backdrop>
  );
};

export default ViewTaskModal;


问:
Nested repo calls Spring Mono
I am getting started with Spring Flux

When i try to make a call to the repo based on the repsonse of first call. The call to the repository is not made.

Looking up DocParts in a repo by docpartId and just building a new Docpart and writing over existing for now for test.
(Code for db handling in repo is removed for simplicity as the return values are the same as in this example)

The newly created docParts get flatMapped and should be upserted into the database but the upsert call is never made as I have debugged it and also cosnole logged from it.

First call to repo is made but second call is never made

IE it gets to

```<code>return docPartRepo.getDocPartById(docPartId)
        .map(docPart-> DocPart.builder())
            .build())
        .flatMap(docPart -> docPartRepo.upsert(docPartId, docPart) // This upsert is never called
        .doOnSuccess(xx -> LOGGER.info("Updated docRepo with docPart")));
</code>```

Repo Code example

```<code>public Mono<DocPart> getDocPartById(Long docPartId) {

   return Mono.just(DocPart.builder().
      .build())

}
</code>```
```<code>public Mono<Void> upsert(Long id, DocPart) {
   System.out.println("In Upsert")
   //Make db call
   return Mono.empty();
}
</code>```

If I test the code to just call upsert it is made OK but the doSuccess is not called

```<code>final Mono<DocPart> docPart = docPartRepo.getDocPartById(docPartId)
        .map(docPart-> DocPart.builder())
            .build())

final DocPart docPart = docPart.block();
docPartRepo.upsert(docPartId, docPart)
    .doOnSuccess(xxx -> System.out.println("Updated db")); // Now the upsert is made but not doOnSuccess
</code>```

Not sure if it is connected to calling the same repo nested or if anybody can give som inputto what might be hindering the call to upsert in flatmap not to be made

Title: Nested repo calls Spring Mono

Body:
I am getting started with Spring Flux

When i try to make a call to the repo based on the repsonse of first call. The call to the repository is not made.

Looking up DocParts in a repo by docpartId and just building a new Docpart and writing over existing for now for test.
(Code for db handling in repo is removed for simplicity as the return values are the same as in this example)

The newly created docParts get flatMapped and should be upserted into the database but the upsert call is never made as I have debugged it and also cosnole logged from it.

First call to repo is made but second call is never made

IE it gets to

return docPartRepo.getDocPartById(docPartId)
        .map(docPart-> DocPart.builder())
            .build())
        .flatMap(docPart -> docPartRepo.upsert(docPartId, docPart) // This upsert is never called
        .doOnSuccess(xx -> LOGGER.info("Updated docRepo with docPart")));

Repo Code example

public Mono<DocPart> getDocPartById(Long docPartId) {

   return Mono.just(DocPart.builder().
      .build())

}

public Mono<Void> upsert(Long id, DocPart) {
   System.out.println("In Upsert")
   //Make db call
   return Mono.empty();
}

If I test the code to just call upsert it is made OK but the doSuccess is not called

final Mono<DocPart> docPart = docPartRepo.getDocPartById(docPartId)
        .map(docPart-> DocPart.builder())
            .build())

final DocPart docPart = docPart.block();
docPartRepo.upsert(docPartId, docPart)
    .doOnSuccess(xxx -> System.out.println("Updated db")); // Now the upsert is made but not doOnSuccess

Not sure if it is connected to calling the same repo nested or if anybody can give som inputto what might be hindering the call to upsert in flatmap not to be made


问:
MsAccess updating leave table
Trying to get a code in msacess to generate the following result.

On the form the user applied for leave like this-

Username: name1

Leave start date 15 Dec

Leave end date 17 Dec

Leave 3 days

On the 'leavetable' it should show like this-

Username   leavestart     leaveend

Name1        15 Dec        15 Dec

Name1        16 Dec        16 Dec

Name1        17 Dec        17 Dec

Is this possible via code? Please advise.

Thank you

I tried using Insert Into but constantly failing.

Title: MsAccess updating leave table


问:
Method as to grouping columns by a unique value in a pandas dataframe WITHOUT changing their data-types. PANDAS GROUPBY
I am struggling to find a method which will group by data frame by unique values.

If I type in

```<code>products = q3_df.groupby(['product_id']).agg(['unique']).reset_index()
</code>```

This will return a multi-index column. The data types have changed so I cannot run the sort function.

```<code>products.sort_values(by=[('Price x Quantity', 'unique')], ascending = False)
</code>```

This returns an error because the values have all changed to tuples.

If I try:

```<code>products.q3_df.groupby(['product_id']).nunique().reset_index()
</code>```

This will change the values of Price x Quantity to an integer and count the number of unique values which is not what I want.

I want to groupby unique product_id and then sort by Price x Quantity to get the top 10 highest selling products, without changing the values of the Price x Quantity column.

Body:
I am struggling to find a method which will group by data frame by unique values.

If I type in

products = q3_df.groupby(['product_id']).agg(['unique']).reset_index()

This will return a multi-index column. The data types have changed so I cannot run the sort function.

products.sort_values(by=[('Price x Quantity', 'unique')], ascending = False)

This returns an error because the values have all changed to tuples.

If I try:

products.q3_df.groupby(['product_id']).nunique().reset_index()

This will change the values of Price x Quantity to an integer and count the number of unique values which is not what I want.

I want to groupby unique product_id and then sort by Price x Quantity to get the top 10 highest selling products, without changing the values of the Price x Quantity column.


问:
XSLT odd behivior with a xsl:template
can someone explain to me this strange output i got here.

Title: XSLT odd behivior with a xsl:template


问:
Distance between two lines in 3d
I'm writing a program for university on python. I have to find the shortest distance between two lines in 3d given by two points (A B and C D) and find the points on both of these lines with the shortest distance between them. I'm bad at math so I can't understand how to find the points, only managed to find the formula of the minimal distance between two lines.

tried to write program, but it finds only point of intersection between lines and doesn't work correctly

#line 1
A = [1, 3, 1]
B = [0, -1, 2]

#line 2
C = [0, -2, 3]
D = [1, 0, 2]

def line_intersection(a, b, c, d):
    v1 = [a_i - b_i for a_i, b_i in zip(B, A)]
    v2 = [a_i - b_i for a_i, b_i in zip(D, C)]
    if (-v1[0] * v2[1] + v1[1] * v2[0]) == 0:
        t = ((c[1]-a[1]) * (-v2[2]) + (v2[1]) * (c[2]-a[2]))/(-v1[1] * v2[2] + v1[2] * v2[1])
    else:
        t = ((c[0]-a[0]) * (-v2[1]) + (v2[0]) * (c[1]-a[1]))/(-v1[0] * v2[1] + v1[1] * v2[0])

    x = a[0] + t * v1[0]
    y = a[1] + t * v1[1]
    z = a[2] + t * v1[2]
    return x, y, z
```

Title: Distance between two lines in 3d


问:
How to assign array to JSONB variable in postgres script
I want to adjust a JSONB column by adding a new array prop in an existing record, but I struggle with getting this updated record.

Something like this:

```<code>DO $$
DECLARE
  mt table1%ROWTYPE;
  arr TEXT[];
BEGIN
    FOR mt IN
        SELECT * FROM table1
    LOOP
        arr := ARRAY(SELECT col1 FROM table2 WHERE id_ext=mt.id);

        raise notice 'arr=%', arr;   -- nice array printed here

        mt.column.arr_prop=arr;   -- !!!!! This does not work

        UPDATE table1 SET column=mt.column WHERE id=mt.id;

    END LOOP;
END $$;
</code>```

Body:
I want to adjust a JSONB column by adding a new array prop in an existing record, but I struggle with getting this updated record.

Something like this:

DO $$
DECLARE
  mt table1%ROWTYPE;
  arr TEXT[];
BEGIN
    FOR mt IN
        SELECT * FROM table1
    LOOP
        arr := ARRAY(SELECT col1 FROM table2 WHERE id_ext=mt.id);

        raise notice 'arr=%', arr;   -- nice array printed here

        mt.column.arr_prop=arr;   -- !!!!! This does not work

        UPDATE table1 SET column=mt.column WHERE id=mt.id;

    END LOOP;
END $$;


问:
Can't Check Children Element's Class Name using If statement In JavaScript
Want to check child element class exist or not using if statement.

want to check a global variable's children[0] class. if it has the specific one. just want to remove that child.
Here's my code. On the printCourse function its showing liParent.children[0] as Undefined;

```<code>const courseAddBtn = document.getElementById("button-addon1");
        courseAddBtn.addEventListener("click", printCourse);
        const typedInput = document.getElementById("courseText");
        const liParent = document.getElementById("courseList");

        function printCourse (e){
            if(liParent.children[0].className == "emptyMsg"){
              liParent.children[0].remove();
            }
            const courseCurrentBtn = e.currentTarget;
            const courseCurrentInput = courseCurrentBtn.previousElementSibling;
            const newLi = document.createElement("li");
            newLi.innerHTML = `
                        <h5 class="courseName flex-grow-1"> ${courseCurrentInput.value} </h5>
                        <button type="button" class="btn btn-outline-warning mx-2" onclick="editChapter(this)">Edit</button>
                        <button type="button" class="btn btn-outline-danger" onclick="removeChapter(this)">Remove</button>
            `;
            newLi.className = "listName list-group-item d-flex flex-direction-column justify-content-even";
            liParent.appendChild(newLi);
        }

        function editChapter(e){
            const editableInput = e.previousElementSibling;
            typedInput.textContent = editableInput.textContent;
            e.parentElement.remove();
        }

        function removeChapter (e){
            e.parentElement.remove();
            if(liParent.children.length<=0){
                const emptyH5 = document.createElement("h5");
                emptyH5.textContent = "No Input! Please Input Your Data";
                liParent.appendChild(emptyH5);
                emptyH5.className = "emptyMsg text-center";
            }
        }
</code>```

Body:
Want to check child element class exist or not using if statement.

want to check a global variable's children[0] class. if it has the specific one. just want to remove that child.
Here's my code. On the printCourse function its showing liParent.children[0] as Undefined;

const courseAddBtn = document.getElementById("button-addon1");
        courseAddBtn.addEventListener("click", printCourse);
        const typedInput = document.getElementById("courseText");
        const liParent = document.getElementById("courseList");

        function printCourse (e){
            if(liParent.children[0].className == "emptyMsg"){
              liParent.children[0].remove();
            }
            const courseCurrentBtn = e.currentTarget;
            const courseCurrentInput = courseCurrentBtn.previousElementSibling;
            const newLi = document.createElement("li");
            newLi.innerHTML = `

 ${courseCurrentInput.value}

                        <button type="button" class="btn btn-outline-warning mx-2" onclick="editChapter(this)">Edit</button>
                        <button type="button" class="btn btn-outline-danger" onclick="removeChapter(this)">Remove</button>
            `;
            newLi.className = "listName list-group-item d-flex flex-direction-column justify-content-even";
            liParent.appendChild(newLi);
        }

        function editChapter(e){
            const editableInput = e.previousElementSibling;
            typedInput.textContent = editableInput.textContent;
            e.parentElement.remove();
        }

        function removeChapter (e){
            e.parentElement.remove();
            if(liParent.children.length<=0){
                const emptyH5 = document.createElement("h5");
                emptyH5.textContent = "No Input! Please Input Your Data";
                liParent.appendChild(emptyH5);
                emptyH5.className = "emptyMsg text-center";
            }
        }


问:
Publishing grails 5 plugin to private repository
I want to upgrade an old plugin that is written in grails 2. But am having difficulties in setting up a new grails 5 plugin and it's build.gradle file. Seemingly nowhere it's documented how to publish a plugin to your own repository.

I created an empty grails 5.2.4 plugin project with this command

```<code>grails create-plugin newPluginProject --profile=plugin
</code>```

this is the following build.gradle file that I have tried (part of it anyways)

```<code>apply plugin:"eclipse"
apply plugin:"idea"
apply plugin: "org.grails.grails-plugin"
apply plugin: 'maven-publish'
apply plugin: "io.github.gradle-nexus.publish-plugin"

repositories {
    maven {
        url "http://company-nexus.com:8081/nexus/repository/maven-public/"
        allowInsecureProtocol = true
        credentials {
            username "my-name"
            password "my-password"
        }
    }
    maven {
        name "internal-releases"
        url "http://company-nexus.com:8081/nexus/repository/maven-releases/"
        allowInsecureProtocol = true
        credentials {
            username "my-name"
            password "my-password"
        }
    }
    maven {
        name "internal-snapshots"
        url "http://company-nexus.com:8081/nexus/repository/maven-snapshots/"
        allowInsecureProtocol = true
        credentials {
            username "my-name"
            password "my-password"
        }
    }
    maven { url "https://repo.grails.org/grails/core" }
}

publishing {
    repositories {
        maven {
            url = "http://company-nexus:8081/nexus/repository/maven-releases/"
            username = 'my-name'
            password = 'my-password'
        }
    }
}
</code>```

I did try to follow this guide and modify it for our use, but it seems that no combination of settings is working.

I looked at the documentation found at gradle nexus publish plugin. But it seems that grails completely ignores those settings

Grails seemingly doesn't support publishing plugins to your internal repository? Because the commands in grails documentation and even from documents found online don't work

What am I doing wrong?

I even tried this example from gradle nexus plugin and it is not even trying to connect to our repositories.

```<code>plugins {
    id "java-library"
    id "maven-publish"
    id "io.github.gradle-nexus.publish-plugin" version "«version»"
}

publishing {
    publications {
        mavenJava(MavenPublication) {
            from(components.java)
        }
    }
}

nexusPublishing {
    repositories {
        myNexus {
            nexusUrl = uri("https://your-server.com/staging")
            snapshotRepositoryUrl = uri("https://your-server.com/snapshots")
            username = "your-username" // defaults to project.properties["myNexusUsername"]
            password = "your-password" // defaults to project.properties["myNexusPassword"]
        }
    }
}
</code>```

Body:
I want to upgrade an old plugin that is written in grails 2. But am having difficulties in setting up a new grails 5 plugin and it's build.gradle file. Seemingly nowhere it's documented how to publish a plugin to your own repository.

I created an empty grails 5.2.4 plugin project with this command

grails create-plugin newPluginProject --profile=plugin

this is the following build.gradle file that I have tried (part of it anyways)

apply plugin:"eclipse"
apply plugin:"idea"
apply plugin: "org.grails.grails-plugin"
apply plugin: 'maven-publish'
apply plugin: "io.github.gradle-nexus.publish-plugin"

repositories {
    maven {
        url "http://company-nexus.com:8081/nexus/repository/maven-public/"
        allowInsecureProtocol = true
        credentials {
            username "my-name"
            password "my-password"
        }
    }
    maven {
        name "internal-releases"
        url "http://company-nexus.com:8081/nexus/repository/maven-releases/"
        allowInsecureProtocol = true
        credentials {
            username "my-name"
            password "my-password"
        }
    }
    maven {
        name "internal-snapshots"
        url "http://company-nexus.com:8081/nexus/repository/maven-snapshots/"
        allowInsecureProtocol = true
        credentials {
            username "my-name"
            password "my-password"
        }
    }
    maven { url "https://repo.grails.org/grails/core" }
}

publishing {
    repositories {
        maven {
            url = "http://company-nexus:8081/nexus/repository/maven-releases/"
            username = 'my-name'
            password = 'my-password'
        }
    }
}

I did try to follow this guide and modify it for our use, but it seems that no combination of settings is working.

I looked at the documentation found at gradle nexus publish plugin. But it seems that grails completely ignores those settings

Grails seemingly doesn't support publishing plugins to your internal repository? Because the commands in grails documentation and even from documents found online don't work

What am I doing wrong?

I even tried this example from gradle nexus plugin and it is not even trying to connect to our repositories.

plugins {
    id "java-library"
    id "maven-publish"
    id "io.github.gradle-nexus.publish-plugin" version "«version»"
}

publishing {
    publications {
        mavenJava(MavenPublication) {
            from(components.java)
        }
    }
}

nexusPublishing {
    repositories {
        myNexus {
            nexusUrl = uri("https://your-server.com/staging")
            snapshotRepositoryUrl = uri("https://your-server.com/snapshots")
            username = "your-username" // defaults to project.properties["myNexusUsername"]
            password = "your-password" // defaults to project.properties["myNexusPassword"]
        }
    }
}


问:
Generating 3D image using stack of 2D images
I'm trying to generate a 3D images using stack of 2D grayscale images in python. I currently have the images, mask, and mask output. I tried creating an ndarray by adding an axis to my images but this didn't seems to work.

This is what I wrote:

```<code># load images
images_gray = []

#x, y= images[0].shape
#z= len(frames)
#threeD= np.ndarray([x,y,z]) #3D
threeD=[]

for i in range(len(images)):

    frame= cv2.imread(path+'/images/' + str(i))

    #convert to grayscale then save
    images_gray.append(rgb2gray(frame))

    #create a polygon
    coordinates=coord[i]
    coordinates = [[y,x] for [x,y] in coordinates] #change order for polygon2mask
    polygon = np.array(coordinates)
    #create a mask
    mask= polygon2mask(images_gray[i].shape, polygon)

    #apply mask
    result=ma.masked_array(images_gray[i],  np.invert(mask))
    temp=result[... ,np.newaxis]
    threeD.append(temp)

</code>```

The resulted output shape for threeD is (#of frames, image hight, image width, 1). I don't know where the 1 come from, and I also expected the order to be (x, y, z) = (image hight, image width, #of frames). The output is wrong and I wasn't able to view it using plt as I got type error saying invalid shape.

For the z, I thought about setting a value of 0.1 that would represent the thickness, not sure how to set that up.

I'm also not sure if my approach is correct or not; do I have to create a points clouds instead? mesh? any suggestions?

Body:
I'm trying to generate a 3D images using stack of 2D grayscale images in python. I currently have the images, mask, and mask output. I tried creating an ndarray by adding an axis to my images but this didn't seems to work.

This is what I wrote:

# load images
images_gray = []

#x, y= images[0].shape
#z= len(frames)
#threeD= np.ndarray([x,y,z]) #3D
threeD=[]

for i in range(len(images)):

    frame= cv2.imread(path+'/images/' + str(i))

    #convert to grayscale then save
    images_gray.append(rgb2gray(frame))

    #create a polygon
    coordinates=coord[i]
    coordinates = [[y,x] for [x,y] in coordinates] #change order for polygon2mask
    polygon = np.array(coordinates)
    #create a mask
    mask= polygon2mask(images_gray[i].shape, polygon)

    #apply mask
    result=ma.masked_array(images_gray[i],  np.invert(mask))
    temp=result[... ,np.newaxis]
    threeD.append(temp)

The resulted output shape for threeD is (#of frames, image hight, image width, 1). I don't know where the 1 come from, and I also expected the order to be (x, y, z) = (image hight, image width, #of frames). The output is wrong and I wasn't able to view it using plt as I got type error saying invalid shape.

For the z, I thought about setting a value of 0.1 that would represent the thickness, not sure how to set that up.

I'm also not sure if my approach is correct or not; do I have to create a points clouds instead? mesh? any suggestions?


问:
How to use GetStorage to store a Set
I am using get_storage to store List, and it works fine, but I wonder if it is possible to use the same way with Set, since Set has few advantages over List,

This is the method that I am using to write and read with List:

```<code>var box = GetStorage();

List<int> listInt = [1, 2, 3];

// Write
box.write('listInt', listInt);
// Read
List<int> a = box.read('listInt')?.cast<int>() ?? [];
List<int> readList = a.toList();

</code>```

And here is Set, please help me if it is possible

Set<int> setInt = {1, 2, 3};

Title: How to use GetStorage to store a Set

Body:
I am using get_storage to store List, and it works fine, but I wonder if it is possible to use the same way with Set, since Set has few advantages over List,

This is the method that I am using to write and read with List:

var box = GetStorage();

List<int> listInt = [1, 2, 3];

// Write
box.write('listInt', listInt);
// Read
List<int> a = box.read('listInt')?.cast<int>() ?? [];
List<int> readList = a.toList();

And here is Set, please help me if it is possible

Set<int> setInt = {1, 2, 3};


问:
Treat git submodule like directory and track changes in outer Repository
I have a git repo with a gitlab remote.
Inside of that repo I have a submodule folder connected to github.
How can I make the outer repo treat the submodule like it was just another folder inside of it?

Right now when i make changes in the inner repo I don't see specific changes in the outer repo when running git status, allI see is that there have been new commits or there is modified content. This seems like the normal submodules behavior.
On gitlab, it is not possible to see the files in the submodule since they are in the private github repo. This is my biggest issue since I need others to see the content of that submodule on gitlab.
Submodules might not be the way to go here but how can I make the inner folder and all files in there visible in the outer repo while staying connected to both remotes?

I saw that in order to integrate a different git repo into another, submodules are suggested but it seems like there is no way to treat a submodule like a normal folder.

I saw this but I don't want to remove the connection to the private github repo.


问:
How to find method declarations in LibTooling?
I'm writing a program in LibTooling to print information of all functions, including methods in classes. But it seems VisitFunctionDecl() only detects functions outside a class. I also tried VisiCXXMethodDecl(),

```<code>bool VisiCXXMethodDecl(CXXMethodDecl *node) {
    string return_type = node->getReturnType().getAsString();
    string function_name = node->getNameInfo().getAsString();
    cout << "function name: " << function_name << endl;
    cout << "return type: " << return_type << endl;
    cout << "has body: " << node->hasBody() << endl;
 }
</code>```

but still failed to detect them. Can anyone tell me what's the correct way to detect methods defined in classes?

Body:
I'm writing a program in LibTooling to print information of all functions, including methods in classes. But it seems VisitFunctionDecl() only detects functions outside a class. I also tried VisiCXXMethodDecl(),

bool VisiCXXMethodDecl(CXXMethodDecl *node) {
    string return_type = node->getReturnType().getAsString();
    string function_name = node->getNameInfo().getAsString();
    cout << "function name: " << function_name << endl;
    cout << "return type: " << return_type << endl;
    cout << "has body: " << node->hasBody() << endl;
 }

but still failed to detect them. Can anyone tell me what's the correct way to detect methods defined in classes?


问:
Unity HDRP + RayTracing. Skybox reflection overlaps other object reflections
I'm using Unity HDRP with enabled raytracing to simulate realistic reflections. Everything works well except skybox reflections. For some reason skybox reflections overlaps every other reflections even if reflected skybox placed behind reflected object. You can see an exaple in the screenshot. The mountains(which are skybox) reflection overlap the wall refelction. How can I fix it?


问:
Qt: How to make a grid for a worm game that has x amount of tiles
So this is the code that I have made in c++.

`

```<code>#include "mainwindow.hh"
#include "gameboard.hh"
#include "ui_mainwindow.h"
#include <iostream>

int SQUARE_SIDE_SIZE =30;

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)

{
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::MakeBoard(int x_len, int y_len, int SeedNumber){
    QGridLayout* grid =ui->gridLayout;

    for (int x=0; x_len>x;x++){
        for (int y=0; y_len>y;y++){
            QMainWindow* newSquare = new MainWindow(this);

            newSquare->setFixedHeight(SQUARE_SIDE_SIZE);
            newSquare->setFixedWidth(SQUARE_SIDE_SIZE);
            grid->addWidget(newSquare, x+1, y+1);

        }
    }
}

void MainWindow::on_PlayButton_clicked()
{

    QString spin = ui->spinBox->text();
    int SeedNumber = spin.toInt();

    QString Y_len = ui->spinBox->text();
    int y_len = Y_len.toInt();

    QString X_len = ui->spinBox->text();
    int x_len = X_len.toInt();

    MainWindow::MakeBoard(x_len,y_len,SeedNumber);

}

</code>```

`

I would need to make some sort of a grid with this that has every other square of the grid a different colour. I have no idea how to make the grid it-self. Currently when i run this program it gives me this:enter image description here

Body:
So this is the code that I have made in c++.

`

#include "mainwindow.hh"
#include "gameboard.hh"
#include "ui_mainwindow.h"
#include <iostream>

int SQUARE_SIDE_SIZE =30;

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)

{
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::MakeBoard(int x_len, int y_len, int SeedNumber){
    QGridLayout* grid =ui->gridLayout;

    for (int x=0; x_len>x;x++){
        for (int y=0; y_len>y;y++){
            QMainWindow* newSquare = new MainWindow(this);

            newSquare->setFixedHeight(SQUARE_SIDE_SIZE);
            newSquare->setFixedWidth(SQUARE_SIDE_SIZE);
            grid->addWidget(newSquare, x+1, y+1);

        }
    }
}

void MainWindow::on_PlayButton_clicked()
{

    QString spin = ui->spinBox->text();
    int SeedNumber = spin.toInt();

    QString Y_len = ui->spinBox->text();
    int y_len = Y_len.toInt();

    QString X_len = ui->spinBox->text();
    int x_len = X_len.toInt();

    MainWindow::MakeBoard(x_len,y_len,SeedNumber);

}

`

I would need to make some sort of a grid with this that has every other square of the grid a different colour. I have no idea how to make the grid it-self. Currently when i run this program it gives me this:enter image description here


问:
Remove None value and append to the new list while filtering db.query in SqlAlchemy
I have a filter that looks for the correct order_id, order_status from a table named Work and returns a list of order_id and document_location if the filter has the correct values and the query looks like this:

```<code>loc_list = db.query(Work.order_id, Work.document_location).filter(Work.order_id == order_id, Work.status == "Finished").order_by(desc(Work.last_update)).limit(1).one_or_none()
new_location.append(loc_list)
</code>```

It looks for the right order_id and status in the Work table and if Work.status != "Finished" then it appends None value to the new_location list as there is no order_id or document_location is found and the filtered list looks like this:

```<code>[None, None, None, None, None, ('Order_id12fb', 'order_12.pdf'),('Order_id13fb', 'order_13.pdf'), ('Order_id14fb', 'order_14.pdf'), ('Order_id15fb', 'order_15.pdf'), ('Order_id16fb', 'order_16.pdf'), None, None]
</code>```

When I run my next logic using new_location list where I loop through the new_location list and return every single order_id and document_location:

```<code>for result in new_location:
    order_items = (result.document_location, result.order_id)
return order_items
</code>```

it returns an error saying:

```<code>TypeError: argument of type 'NoneType' is not iterable
</code>```

I am looking for a way to remove the None values within the db.query filter and append only order_id or document_location by ignoring None. Is there a way in sqlalchemy to handle this?

Body:
I have a filter that looks for the correct order_id, order_status from a table named Work and returns a list of order_id and document_location if the filter has the correct values and the query looks like this:

loc_list = db.query(Work.order_id, Work.document_location).filter(Work.order_id == order_id, Work.status == "Finished").order_by(desc(Work.last_update)).limit(1).one_or_none()
new_location.append(loc_list)

It looks for the right order_id and status in the Work table and if Work.status != "Finished" then it appends None value to the new_location list as there is no order_id or document_location is found and the filtered list looks like this:

[None, None, None, None, None, ('Order_id12fb', 'order_12.pdf'),('Order_id13fb', 'order_13.pdf'), ('Order_id14fb', 'order_14.pdf'), ('Order_id15fb', 'order_15.pdf'), ('Order_id16fb', 'order_16.pdf'), None, None]

When I run my next logic using new_location list where I loop through the new_location list and return every single order_id and document_location:

for result in new_location:
    order_items = (result.document_location, result.order_id)
return order_items

it returns an error saying:

TypeError: argument of type 'NoneType' is not iterable

I am looking for a way to remove the None values within the db.query filter and append only order_id or document_location by ignoring None. Is there a way in sqlalchemy to handle this?


问:
Cannot coerce class '"rpart"' to a Data frame
I'm doing some testing and practicing, tried to knit the code in case there were any typos or something but face that issue. Have not been able to solve it. Any help is appreciated.

```<code>```{r message=FALSE, warning=FALSE}
library(knitr)
library(dplyr)
library(tidyverse)
library(rpart)
library(rpart.plot)

setwd("~/R stuff/directorio activo/Asignatura 3/data")

TABLON_ENTRENAMIENTO <- read.csv("~/R stuff/directorio
activo/Asignatura 3/TABLON_ENTRENAMIENTO.csv", sep=";")

TABLON_VALIDACION <- read.csv("~/R stuff/directorio activo/Asignatura 3/TABLON_VALIDACION.csv", sep=";")

arbol1 <- rpart(TARGET~., TABLON_ENTRENAMIENTO) # line of error

View(arbol1)
rpart.plot(arbol1)

prediccion1 = predict(arbol1,newdata=TABLON_VALIDACION,type="vector")

head(prediccion1, n=20)
plot(prediccion1, main="Predicción1", xlab="Target", ylab="Var")
plot(TABLON_VALIDACION$TARGET, main="Validacón", xlab="Target", ylab="Var")
```
</code>```

"Error in as.data.frame.default (x): cannot coerce class '"rpart"' to a data frame. Calls:  ... -> view -> as.data.frame -> as.data.frame.default"

It is importsnt to note that the error come only while trying to knit the code, the console displays de rpart.plot just fine.

Body:
I'm doing some testing and practicing, tried to knit the code in case there were any typos or something but face that issue. Have not been able to solve it. Any help is appreciated.

```{r message=FALSE, warning=FALSE}
library(knitr)
library(dplyr)
library(tidyverse)
library(rpart)
library(rpart.plot)

setwd("~/R stuff/directorio activo/Asignatura 3/data")

TABLON_ENTRENAMIENTO <- read.csv("~/R stuff/directorio
activo/Asignatura 3/TABLON_ENTRENAMIENTO.csv", sep=";")

TABLON_VALIDACION <- read.csv("~/R stuff/directorio activo/Asignatura 3/TABLON_VALIDACION.csv", sep=";")

arbol1 <- rpart(TARGET~., TABLON_ENTRENAMIENTO) # line of error

View(arbol1)
rpart.plot(arbol1)

prediccion1 = predict(arbol1,newdata=TABLON_VALIDACION,type="vector")

head(prediccion1, n=20)
plot(prediccion1, main="Predicción1", xlab="Target", ylab="Var")
plot(TABLON_VALIDACION$TARGET, main="Validacón", xlab="Target", ylab="Var")
```

"Error in as.data.frame.default (x): cannot coerce class '"rpart"' to a data frame. Calls:  ... -> view -> as.data.frame -> as.data.frame.default"

It is importsnt to note that the error come only while trying to knit the code, the console displays de rpart.plot just fine.


问:
How to set schema location for @ManyToMany Entity Collection with JPA
I want to create 2 tables in my PostgreSQL database while using the Spring-boot JPA.

```<code>@Entity
@Table(schema = "test")
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Role {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
}
</code>```

And my User class

```<code>@Entity
@Table(schema = "test")
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {

    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String username;
    private String password;
    private String group_id;
    private String email;
    @ManyToMany(fetch = FetchType.EAGER)
    private Collection<Role> roles = new ArrayList<>();
}
</code>```

The 2 tables above are created in test schema but the user_roles is trying to be created without any schema selected and I get the error

Caused by: org.postgresql.util.PSQLException: ERROR: no schema has been selected to create in

So my question is: How to assign the schema to the user_roles table that JPA is trying to create

Body:
I want to create 2 tables in my PostgreSQL database while using the Spring-boot JPA.

@Entity
@Table(schema = "test")
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Role {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
}

And my User class

@Entity
@Table(schema = "test")
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {

    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String username;
    private String password;
    private String group_id;
    private String email;
    @ManyToMany(fetch = FetchType.EAGER)
    private Collection<Role> roles = new ArrayList<>();
}

The 2 tables above are created in test schema but the user_roles is trying to be created without any schema selected and I get the error

Caused by: org.postgresql.util.PSQLException: ERROR: no schema has been selected to create in

So my question is: How to assign the schema to the user_roles table that JPA is trying to create


问:
Crop images in python - TypeError: 'NoneType' object is not subscriptable
I'm writing an script for cropping png images and I get the result, but I also ran into the error "TypeError: 'NoneType' object is not subscriptable"

```<code>import os
import cv2

path = "/content/image/"
dest_path = "/content/cropped/"

for f in os.listdir(path):
    image = cv2.imread(os.path.join(path, f))
    imgcropped = image[150:400, 250:600]
    cv2.imwrite(os.path.join(dest_path, f), imgcropped)
</code>```

Here is my error:

```<code>---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-49-ea6eac11778b> in <module>
      7 for f in os.listdir(path):
      8     image = cv2.imread(os.path.join(path, f))
----> 9     imgcropped = image[150:400, 250:600]
     10     cv2.imwrite(os.path.join(dest_path, f), imgcropped)

TypeError: 'NoneType' object is not subscriptable
</code>```

enter image description here

Body:
I'm writing an script for cropping png images and I get the result, but I also ran into the error "TypeError: 'NoneType' object is not subscriptable"

import os
import cv2

path = "/content/image/"
dest_path = "/content/cropped/"

for f in os.listdir(path):
    image = cv2.imread(os.path.join(path, f))
    imgcropped = image[150:400, 250:600]
    cv2.imwrite(os.path.join(dest_path, f), imgcropped)

Here is my error:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-49-ea6eac11778b> in <module>
      7 for f in os.listdir(path):
      8     image = cv2.imread(os.path.join(path, f))
----> 9     imgcropped = image[150:400, 250:600]
     10     cv2.imwrite(os.path.join(dest_path, f), imgcropped)

TypeError: 'NoneType' object is not subscriptable

enter image description here


问:
How can I make the button revert to its previous state before converting it to text?
```<code>//The problem
 val btntext1=btn1.text.toString()
if (btntext1==rightAnswer){
    //I want to change the background of the button as per the condition
}
</code>```
<p>//rightAnswer This is a method containing the correct answer</p>
```<code>//I want to do this process
val btntext1=btn1.text.toString()
if (btntext1==rightAnswer){

    btntext1.setBackgroundColor(Color.RED)

//Of course this is wrong

}
</code>```

Body:
//The problem
 val btntext1=btn1.text.toString()
if (btntext1==rightAnswer){
    //I want to change the background of the button as per the condition
}

//rightAnswer This is a method containing the correct answer

//I want to do this process
val btntext1=btn1.text.toString()
if (btntext1==rightAnswer){

    btntext1.setBackgroundColor(Color.RED)

//Of course this is wrong

}


问:
Can't install dbt-snowflake; "No module named 'cmake'"
(Context: Barely a novice at Terminal, know some SQL, don't know Python)

I'm taking a course on dbt, have my own Snowflake set up, and I'm trying to install dbt-snowflake on Mac. Attempting to run:

pip install dbt-snowflake

This fails, and it returns:

`

```<code> Traceback (most recent call last):
              File "/Users/xxxx/course/venv/bin/cmake", line 5, in <module>
                from cmake import cmake
            ModuleNotFoundError: No module named 'cmake'
            error: command '/Users/xxxx/course/venv/bin/cmake' failed with exit code 1
            [end of output]

        note: This error originates from a subprocess, and is likely not a problem with pip.
        ERROR: Failed building wheel for pyarrow
      Failed to build pyarrow
      ERROR: Could not build wheels for pyarrow, which is required to install pyproject.toml-based projects
</code>```

`

I once successfully changed Python version in virtual environment to 3.9 to see whether that was the problem (but I can't replicate how I changed it), that didn't solve the problem, and currently it's back to 3.11.

Have installed multiple versions of snowflake (3.7, 3.9, 3.11). I don't really understand how this works in context of everything.

I have tried deleting and recreating virtual environments (under same name, venv)

uninstalled and reinstalled cmake (pip install --upgrade cmake); this is version 3.25.0

I don't understand how I can have cmake installed and be told there is no module named 'cmake'.

Is there a particular version of Python I should be running, and if so, how do I reliably change that in virtual environments and different directories?

EDIT TO ADDRESS A COMMENT: I installed Python versions via terminal brew install python@3.9

Body:
(Context: Barely a novice at Terminal, know some SQL, don't know Python)

I'm taking a course on dbt, have my own Snowflake set up, and I'm trying to install dbt-snowflake on Mac. Attempting to run:

pip install dbt-snowflake

This fails, and it returns:

`

 Traceback (most recent call last):
              File "/Users/xxxx/course/venv/bin/cmake", line 5, in <module>
                from cmake import cmake
            ModuleNotFoundError: No module named 'cmake'
            error: command '/Users/xxxx/course/venv/bin/cmake' failed with exit code 1
            [end of output]

        note: This error originates from a subprocess, and is likely not a problem with pip.
        ERROR: Failed building wheel for pyarrow
      Failed to build pyarrow
      ERROR: Could not build wheels for pyarrow, which is required to install pyproject.toml-based projects

`

I once successfully changed Python version in virtual environment to 3.9 to see whether that was the problem (but I can't replicate how I changed it), that didn't solve the problem, and currently it's back to 3.11.

Have installed multiple versions of snowflake (3.7, 3.9, 3.11). I don't really understand how this works in context of everything.

I have tried deleting and recreating virtual environments (under same name, venv)

uninstalled and reinstalled cmake (pip install --upgrade cmake); this is version 3.25.0

I don't understand how I can have cmake installed and be told there is no module named 'cmake'.

Is there a particular version of Python I should be running, and if so, how do I reliably change that in virtual environments and different directories?

EDIT TO ADDRESS A COMMENT: I installed Python versions via terminal brew install python@3.9


问:
how to import my own package on github action
I have a project organized like below:

```<code>code/
|-- init.py
|-- global_code/
|   |-- all_process.py
|-- africa/
|   |-- egypt/
|   |  |-- egypt_workflow.py

</code>```

I want to run egypt_workflow in all_process (above just a sample, actual there are many countries code)

so I simple added init.py in my 'code' folder
and write

```<code>import code.africa.egypt.egypt_workflow as ew
</code>```

and it works

however, when i try to run it on github action on ubuntu enviorment, it failed

```<code>ModuleNotFoundError: No module named 'code.africa'; 'code' is not a package
</code>```

I dont know why it happened, so i search online and tried below methods but all failed:

```<code>import sys
sys.path.append('.') # i also tried '..','./','../'
</code>```

got same error

```<code>import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))
</code>```

still same error

```<code>from pathlib import Path
import sys
path_root = Path(__file__).parents[2]
sys.path.append(str(path_root))
print(sys.path)
</code>```

still same error, but i found the print result contains below path:

```<code>/home/runner/work/***/***/code/global_code
</code>```

so i was wondering if the problem was here?

anyway, i also tried change

```<code>import code.africa.egypt.egypt_workflow as ew
</code>```

to

```<code>import .code.africa.egypt.egypt_workflow as ew
</code>```

and i got different error

```<code>ImportError: attempted relative import with no known parent package
</code>```

so I was wondering if someone could point me to the correct direction?

or maybe i should change my organize way?

Thanks:)

P.S.

I used to use

```<code>
sys.path.append('./code/africa/')
import egypt.egypt_workflow as ee
ee.main()
sys.path.append('./code/asian/')
import japan.japan_workflow as j
j.main()
</code>```

it worked, but as you can see, for each country i have to write one, because many countries not in same continent. So, i want to change to a more elegant way:P

Another P.S.
below is my action code for your reference

```<code>name: all_action
on:
  schedule:
    - cron: 0 22 * * *
  workflow_dispatch:
jobs:
  all_process:
    runs-on: ubuntu-latest
    steps:
      - name: check code
        uses: actions/checkout@v3
      - name: set up Python 3.10
        uses: actions/setup-Python@v4
        with:
          python-version: 3.10
      - name: install requirements
        run: |
          pip install openpyxl
          pip install -r requirements.txt
      - name: run code
        run: python ./code/global_code/all_process.py
      - name: commit and push
        run: |
          git config user.name "${GITHUB_ACTOR}"
          git config user.email "${GITHUB_ACTOR}@users.noreply.github.com"
          git add -A
          git commit -m "updated"
          git push
</code>```

Body:
I have a project organized like below:

code/
|-- init.py
|-- global_code/
|   |-- all_process.py
|-- africa/
|   |-- egypt/
|   |  |-- egypt_workflow.py

I want to run egypt_workflow in all_process (above just a sample, actual there are many countries code)

so I simple added init.py in my 'code' folder
and write

import code.africa.egypt.egypt_workflow as ew

and it works

however, when i try to run it on github action on ubuntu enviorment, it failed

ModuleNotFoundError: No module named 'code.africa'; 'code' is not a package

I dont know why it happened, so i search online and tried below methods but all failed:

import sys
sys.path.append('.') # i also tried '..','./','../'

got same error

import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))

still same error

from pathlib import Path
import sys
path_root = Path(__file__).parents[2]
sys.path.append(str(path_root))
print(sys.path)

still same error, but i found the print result contains below path:

/home/runner/work/***/***/code/global_code

so i was wondering if the problem was here?

anyway, i also tried change

import code.africa.egypt.egypt_workflow as ew

to

import .code.africa.egypt.egypt_workflow as ew

and i got different error

ImportError: attempted relative import with no known parent package

so I was wondering if someone could point me to the correct direction?

or maybe i should change my organize way?

Thanks:)

P.S.

I used to use

sys.path.append('./code/africa/')
import egypt.egypt_workflow as ee
ee.main()
sys.path.append('./code/asian/')
import japan.japan_workflow as j
j.main()

it worked, but as you can see, for each country i have to write one, because many countries not in same continent. So, i want to change to a more elegant way:P

Another P.S.
below is my action code for your reference

name: all_action
on:
  schedule:
    - cron: 0 22 * * *
  workflow_dispatch:
jobs:
  all_process:
    runs-on: ubuntu-latest
    steps:
      - name: check code
        uses: actions/checkout@v3
      - name: set up Python 3.10
        uses: actions/setup-Python@v4
        with:
          python-version: 3.10
      - name: install requirements
        run: |
          pip install openpyxl
          pip install -r requirements.txt
      - name: run code
        run: python ./code/global_code/all_process.py
      - name: commit and push
        run: |
          git config user.name "${GITHUB_ACTOR}"
          git config user.email "${GITHUB_ACTOR}@users.noreply.github.com"
          git add -A
          git commit -m "updated"
          git push


问:
PySpark Glue Job Fails with "So space on device" even after configuring Shuffle Manager to S3
I have a PySpark code in Glue which fails with error "No space left on device". I understand it happens when shuffle operations do not have enough space. I found out about Glue Shuffle Manager where you can leverage S3 for storing shuffle data. I configured it still I am running into the same error. I am using Glue 3.0 and Spark 3.1. I believe Shuffle manager is now supported with Glue 3.0 as well.

https://docs.amazonaws.cn/en_us/glue/latest/dg/monitor-spark-shuffle-manager.html
https://docs.aws.amazon.com/glue/latest/dg/cloud-shuffle-storage-plugin.html


问:
Pytube download error: urlopen error EOF occurred in violation of protocol (_ssl.c:997)
I am trying to download a video from youtube with the python pytube library, I am working in docker with python:3.10-slim, the same error occurs with the standard version of python.

This is my code.

`

```<code>import logging
import pytube
import sys

logging.basicConfig(
  level=logging.INFO,
  format="%(asctime)s [%(levelname)s] %(message)s",
  handlers=[
    logging.StreamHandler(sys.stdout)
  ]
)

logging.info("Downloading the video from YouTube...")
youtubeVideo = pytube.YouTube(sys.argv[1])

logging.info("Get only the audio from the video")
audio = youtubeVideo.streams.filter(only_audio=True).first()
out_file = audio.download(output_path='./audio/')
</code>```

`

This is the error.

```<code>err: Error: urllib.error.URLError: <urlopen error EOF occurred in violation of protocol (_ssl.c:997)>
    at PythonShell.parseError (/automated-clock-in/node_modules/python-shell/index.js:295:21)
    at terminateIfNeeded (/automated-clock-in/node_modules/python-shell/index.js:190:32)
    at ChildProcess.<anonymous> (/automated-clock-in/node_modules/python-shell/index.js:182:13)
    at ChildProcess.emit (node:events:513:28)
    at ChildProcess._handle.onexit (node:internal/child_process:291:12)
    ----- Python Traceback -----
    File "/usr/local/lib/python3.10/urllib/request.py", line 1348, in do_open
      h.request(req.get_method(), req.selector, req.data, headers,
    File "/usr/local/lib/python3.10/http/client.py", line 1282, in request
      self._send_request(method, url, body, headers, encode_chunked)
    File "/usr/local/lib/python3.10/http/client.py", line 1328, in _send_request
      self.endheaders(body, encode_chunked=encode_chunked)
    File "/usr/local/lib/python3.10/http/client.py", line 1277, in endheaders
      self._send_output(message_body, encode_chunked=encode_chunked)
    File "/usr/local/lib/python3.10/http/client.py", line 1037, in _send_output
      self.send(msg)
    File "/usr/local/lib/python3.10/http/client.py", line 975, in send
      self.connect()
    File "/usr/local/lib/python3.10/http/client.py", line 1454, in connect
      self.sock = self._context.wrap_socket(self.sock,
    File "/usr/local/lib/python3.10/ssl.py", line 513, in wrap_socket
      return self.sslsocket_class._create(
    File "/usr/local/lib/python3.10/ssl.py", line 1071, in _create
      self.do_handshake()
    File "/usr/local/lib/python3.10/ssl.py", line 1342, in do_handshake
      self._sslobj.do_handshake()
  ssl.SSLEOFError: EOF occurred in violation of protocol (_ssl.c:997)
</code>```

I understand that the problem is with the ssl certificates as the request is being made from inside the container. Can anyone help me to fix this problem? Thanks

Body:
I am trying to download a video from youtube with the python pytube library, I am working in docker with python:3.10-slim, the same error occurs with the standard version of python.

This is my code.

`

import logging
import pytube
import sys

logging.basicConfig(
  level=logging.INFO,
  format="%(asctime)s [%(levelname)s] %(message)s",
  handlers=[
    logging.StreamHandler(sys.stdout)
  ]
)

logging.info("Downloading the video from YouTube...")
youtubeVideo = pytube.YouTube(sys.argv[1])

logging.info("Get only the audio from the video")
audio = youtubeVideo.streams.filter(only_audio=True).first()
out_file = audio.download(output_path='./audio/')

`

This is the error.

err: Error: urllib.error.URLError: <urlopen error EOF occurred in violation of protocol (_ssl.c:997)>
    at PythonShell.parseError (/automated-clock-in/node_modules/python-shell/index.js:295:21)
    at terminateIfNeeded (/automated-clock-in/node_modules/python-shell/index.js:190:32)
    at ChildProcess.<anonymous> (/automated-clock-in/node_modules/python-shell/index.js:182:13)
    at ChildProcess.emit (node:events:513:28)
    at ChildProcess._handle.onexit (node:internal/child_process:291:12)
    ----- Python Traceback -----
    File "/usr/local/lib/python3.10/urllib/request.py", line 1348, in do_open
      h.request(req.get_method(), req.selector, req.data, headers,
    File "/usr/local/lib/python3.10/http/client.py", line 1282, in request
      self._send_request(method, url, body, headers, encode_chunked)
    File "/usr/local/lib/python3.10/http/client.py", line 1328, in _send_request
      self.endheaders(body, encode_chunked=encode_chunked)
    File "/usr/local/lib/python3.10/http/client.py", line 1277, in endheaders
      self._send_output(message_body, encode_chunked=encode_chunked)
    File "/usr/local/lib/python3.10/http/client.py", line 1037, in _send_output
      self.send(msg)
    File "/usr/local/lib/python3.10/http/client.py", line 975, in send
      self.connect()
    File "/usr/local/lib/python3.10/http/client.py", line 1454, in connect
      self.sock = self._context.wrap_socket(self.sock,
    File "/usr/local/lib/python3.10/ssl.py", line 513, in wrap_socket
      return self.sslsocket_class._create(
    File "/usr/local/lib/python3.10/ssl.py", line 1071, in _create
      self.do_handshake()
    File "/usr/local/lib/python3.10/ssl.py", line 1342, in do_handshake
      self._sslobj.do_handshake()
  ssl.SSLEOFError: EOF occurred in violation of protocol (_ssl.c:997)

I understand that the problem is with the ssl certificates as the request is being made from inside the container. Can anyone help me to fix this problem? Thanks


问:
MongoDB : RUN A PART PF CODE NOT ALL OF CODE
I use mongoDB in vs code and 3t studio , when i put a block and run it , i need to remove it to run i other block , so i lose the precedent  , i want to have all of code in one terminal and run just a part like delimiter in (sql)

this is my code:

```<code>db.Sportifs.findOne();
db.Gymnases.find();

db.Sportifs.find(
{Age: {$gt: 20, $lt: 30}},
{_id: 0, IdSportif: 1, Nom: 1, Prenom: 1}
)

db.Gymnases.find(
{$and: [
    {Ville: {$in : ["STAINS", "SARCELLES"]}},
    {Surface: {$gt: 400}}
    ]}
)

db.Sportifs.find(
{"Sports.Jouer": "Hand ball"},
{_id: 0, IdSportif: 1, Nom: 1}
)
</code>```

Body:
I use mongoDB in vs code and 3t studio , when i put a block and run it , i need to remove it to run i other block , so i lose the precedent  , i want to have all of code in one terminal and run just a part like delimiter in (sql)

this is my code:

db.Sportifs.findOne();
db.Gymnases.find();

db.Sportifs.find(
{Age: {$gt: 20, $lt: 30}},
{_id: 0, IdSportif: 1, Nom: 1, Prenom: 1}
)

db.Gymnases.find(
{$and: [
    {Ville: {$in : ["STAINS", "SARCELLES"]}},
    {Surface: {$gt: 400}}
    ]}
)

db.Sportifs.find(
{"Sports.Jouer": "Hand ball"},
{_id: 0, IdSportif: 1, Nom: 1}
)


问:
CMake how to find linked absolute path for *.lib files
I have a CMake project which is runnable, with part of the code

```<code>target_link_libraries(exec PRIVATE d3d11.lib dwmapi.lib d3dcompiler.lib)
</code>```

How do I know which *.lib (from where) is used?
Is it possible to print the path?

Thanks

Try to find the path to CMake link library, specifically *.lib files.

Body:
I have a CMake project which is runnable, with part of the code

target_link_libraries(exec PRIVATE d3d11.lib dwmapi.lib d3dcompiler.lib)

How do I know which *.lib (from where) is used?
Is it possible to print the path?

Thanks

Try to find the path to CMake link library, specifically *.lib files.


问:
How to wait for all async tasks to finish before moving to next iteration of forEach function?
I am trying to create a NodeJS script that takes JSON data on vehicle makes and models and creates SVG charts, then converts them into PNG images.

I have nested forEach functions where I take each make, process the chart creation for each model before moving to the next iteration of make.

The problem is my script goes through the iterations without finishing processing of all the models, which creates timeouts.

How can I change the following code so that all PNG images for each make get processed and finished before moving to the next make?

```<code>const { convertFile } = require('convert-svg-to-png');

const makesJSONs = ['Acura', 'BMW', 'Cadillac'];

makesJSONs.forEach((make) => {

    make.forEach((model)=> {

        // do stuff to create chart

        const run = async ()=>{

            // I Want to....

            // 1. Render SVG and save to file
            const svgStr = await chart.renderToSVGString();
            chart.dispose();

            fs.writeFileSync(`charts/${model}.svg`, svgStr, (err) => {
                if (err) throw err;
                console.log(`${model}.svg file has saved`);
            });

            // 2. Convert SVG to PNG and save to file
            const inputFilePath = `charts/${model}.svg`;
            const outputFilePath = await convertFile(inputFilePath, {scale: 2, background: '#F7F7ED'});
            console.log(outputFilePath);
        }

        run();

    })

})

</code>```

Body:
I am trying to create a NodeJS script that takes JSON data on vehicle makes and models and creates SVG charts, then converts them into PNG images.

I have nested forEach functions where I take each make, process the chart creation for each model before moving to the next iteration of make.

The problem is my script goes through the iterations without finishing processing of all the models, which creates timeouts.

How can I change the following code so that all PNG images for each make get processed and finished before moving to the next make?

const { convertFile } = require('convert-svg-to-png');

const makesJSONs = ['Acura', 'BMW', 'Cadillac'];

makesJSONs.forEach((make) => {

    make.forEach((model)=> {

        // do stuff to create chart

        const run = async ()=>{

            // I Want to....

            // 1. Render SVG and save to file
            const svgStr = await chart.renderToSVGString();
            chart.dispose();

            fs.writeFileSync(`charts/${model}.svg`, svgStr, (err) => {
                if (err) throw err;
                console.log(`${model}.svg file has saved`);
            });

            // 2. Convert SVG to PNG and save to file
            const inputFilePath = `charts/${model}.svg`;
            const outputFilePath = await convertFile(inputFilePath, {scale: 2, background: '#F7F7ED'});
            console.log(outputFilePath);
        }

        run();

    })

})