问:
Panorama Creation using OpenCV-Python; black frame appears when trying to stitch 2 images together because the image to be stitched gets rotated
I'm doing a project on panorama creation using python and openCV. The methodology which I'm following in order to create the panorama contains the following steps, working in pairs of images;

find the keypoints of each of the 2 images with SIFT detector

match the keypoints

find the homography matrix that transforms the second image to the wanted image, using the RANSAC algorithm

stitch the 2 images

The problem is that the method cv2.warpPerspective(imgs[1], M, shape) returns an image slightly rotated to the left (imgs[1] is the right image, M is the homography matrix and shape is the shape of the result image) which causes the stiched image not to be vertical to the horizontal axis and therefore a black frame appears on the top right corner of the stiched image. when I try to stich the next image into this first part of the panorama, that black frame is considered part of the left image and therefore it appears between the images.

Most people using this methodology to create panoramas follow exactly the structure below, but for them the result is a an image whose left and right sides are vertical and not a rotated image.

```<code>img1 = cv2.cvtColor(imgs[1], cv2.COLOR_BGR2GRAY) #right image in gray
img2 = cv2.cvtColor(imgs[0], cv2.COLOR_BGR2GRAY) #left image in gray

#create sift detector object
sift = cv2.xfeatures2d.SIFT_create()

kp1, des1 = sift.detectAndCompute(img1, None) #find keypoints and descriptor for right image
kp2, des2 = sift.detectAndCompute(img2, None) #find keypoints and descriptor for left image

#create BFMatcher object
match = cv2.BFMatcher()
#find the matches between the 2 images using BFMatcher object
matches = match.knnMatch(des1, des2, k=2)

good = []
#find and store the good matches
for m,n in matches:
    if m.distance < 0.8*n.distance:
        good.append(m)

MIN_MATCH_COUNT = 10
#if number of mathces is higher than 10
if len(good) > MIN_MATCH_COUNT:
    #reshape keypoint lists and declare the source and destination keypoints
    src_pts = np.float32([ kp1[m.queryIdx].pt for m in good ])
    dst_pts = np.float32([ kp2[m.trainIdx].pt for m in good ])

    #find the homography matrix M
    M, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC, 5.0)
    #h,w = img1.shape #heigh and width of right image
    #pts = np.float32([[0,0], [0,h-1], [w-1, h-1], [w-1,0]]).reshape(-1,1,2)
    #find the perspective transformation using the homography matrix
    #transform = cv2.perspectiveTransform(pts, M)

    #the line below is to show the overlapping region - optional
    #img2 = cv2.polylines(img2, [np.int32(transform)], True, 255, 3, cv2.LINE_AA)

    #plt.imshow(img2)
else:
    print("Not enough matches are found.")

#connect the 2 images
dst = cv2.warpPerspective(imgs[1], M, (imgs[0].shape[1] + imgs[1].shape[1], imgs[0].shape[0]))
dst[0:imgs[0].shape[0], 0:imgs[0].shape[1]] = imgs[0]

#show stiched image in RGB
plt.imshow(cv2.cvtColor(dst, cv2.COLOR_BGR2RGB))

</code>```

This is the link to my github repository for this project
https://github.com/angepl/panoramaTest.git

Body:
I'm doing a project on panorama creation using python and openCV. The methodology which I'm following in order to create the panorama contains the following steps, working in pairs of images;

find the keypoints of each of the 2 images with SIFT detector

match the keypoints

find the homography matrix that transforms the second image to the wanted image, using the RANSAC algorithm

stitch the 2 images

The problem is that the method cv2.warpPerspective(imgs[1], M, shape) returns an image slightly rotated to the left (imgs[1] is the right image, M is the homography matrix and shape is the shape of the result image) which causes the stiched image not to be vertical to the horizontal axis and therefore a black frame appears on the top right corner of the stiched image. when I try to stich the next image into this first part of the panorama, that black frame is considered part of the left image and therefore it appears between the images.

Most people using this methodology to create panoramas follow exactly the structure below, but for them the result is a an image whose left and right sides are vertical and not a rotated image.

img1 = cv2.cvtColor(imgs[1], cv2.COLOR_BGR2GRAY) #right image in gray
img2 = cv2.cvtColor(imgs[0], cv2.COLOR_BGR2GRAY) #left image in gray

#create sift detector object
sift = cv2.xfeatures2d.SIFT_create()

kp1, des1 = sift.detectAndCompute(img1, None) #find keypoints and descriptor for right image
kp2, des2 = sift.detectAndCompute(img2, None) #find keypoints and descriptor for left image

#create BFMatcher object
match = cv2.BFMatcher()
#find the matches between the 2 images using BFMatcher object
matches = match.knnMatch(des1, des2, k=2)

good = []
#find and store the good matches
for m,n in matches:
    if m.distance < 0.8*n.distance:
        good.append(m)

MIN_MATCH_COUNT = 10
#if number of mathces is higher than 10
if len(good) > MIN_MATCH_COUNT:
    #reshape keypoint lists and declare the source and destination keypoints
    src_pts = np.float32([ kp1[m.queryIdx].pt for m in good ])
    dst_pts = np.float32([ kp2[m.trainIdx].pt for m in good ])

    #find the homography matrix M
    M, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC, 5.0)
    #h,w = img1.shape #heigh and width of right image
    #pts = np.float32([[0,0], [0,h-1], [w-1, h-1], [w-1,0]]).reshape(-1,1,2)
    #find the perspective transformation using the homography matrix
    #transform = cv2.perspectiveTransform(pts, M)

    #the line below is to show the overlapping region - optional
    #img2 = cv2.polylines(img2, [np.int32(transform)], True, 255, 3, cv2.LINE_AA)

    #plt.imshow(img2)
else:
    print("Not enough matches are found.")

#connect the 2 images
dst = cv2.warpPerspective(imgs[1], M, (imgs[0].shape[1] + imgs[1].shape[1], imgs[0].shape[0]))
dst[0:imgs[0].shape[0], 0:imgs[0].shape[1]] = imgs[0]

#show stiched image in RGB
plt.imshow(cv2.cvtColor(dst, cv2.COLOR_BGR2RGB))

This is the link to my github repository for this project
https://github.com/angepl/panoramaTest.git


来源: stackexchange

问:
How to authorize request using laravel breeze?
I have installed laravel breeze with sail, and I'm trying to make axios request, like

```<code>axios.get('/api/messages');
</code>```

But I got an error

```<code>{"message":"Unauthenticated."}
</code>```

I am authorized, and can open pages like "dashboard".

I added

```<code>axios.defaults.withCredentials = true;
</code>```

to my "bootstrap.js" but it didn't help.

ContentLicense: CC BY-SA 4.0

Body:
I have installed laravel breeze with sail, and I'm trying to make axios request, like

axios.get('/api/messages');

But I got an error

{"message":"Unauthenticated."}

I am authorized, and can open pages like "dashboard".

I added

axios.defaults.withCredentials = true;

to my "bootstrap.js" but it didn't help.


问:
image will not scale to 100% of div properly?
I am trying to make the image take up the whole page for my component but cannot figure out what I am doing wrong?

this is how it currently looks and I cannot figure out how to ensure it takes up the extra whitespace marked in red too.

I tried setting the min width and height of the div it is contained in. Is it maybe I need to set the image up in the body but I was confused how to do that in react.

current page:

css:

```<code>.container {
    background-image: url("../images/img.jpg");

            background-repeat: no-repeat;
            background-size: contain;
            min-height: 100%;
            min-width: 100%;
}

.default-button {
    align-items: center;
    background-clip: padding-box;
    background-color: #fa6400;
    border: 1px solid transparent;
    border-radius: .25rem;
    box-shadow: rgba(0, 0, 0, 0.02) 0 1px 3px 0;
    box-sizing: border-box;
    color: #fff;
    cursor: pointer;
    display: inline-flex;
    font-family: "Rams Black";
    font-size: 16px;
    font-weight: 600;
    justify-content: center;
    line-height: 1.25;
    margin: 0;
    min-height: 3rem;
    padding: calc(.875rem - 1px) calc(1.5rem - 1px);
    position: relative;
    text-decoration: none;
    transition: all 250ms;
    user-select: none;
    -webkit-user-select: none;
    touch-action: manipulation;
    vertical-align: baseline;
    width: auto;
}

.default-button:hover,
.default-button:focus {
    background-color: #fb8332;
    box-shadow: rgba(0, 0, 0, 0.1) 0 4px 12px;
}

.default-button:hover {
    transform: translateY(-1px);
}

.default-button:active {
    background-color: #c85000;
    box-shadow: rgba(0, 0, 0, .06) 0 2px 4px;
    transform: translateY(0);
}

.powered-by-strava {
    display: flex;
    align-items: center;
    justify-content: center;
}

.connect-btn {
    background-color: transparent;
    padding: 0;
    border: none;
    background: none;
}
</code>```

component where image is rendered:

```<code> return (
    <div className="container">

        <button className="connect-btn" onClick={stravaAuth}><img src={connectSVG}
        alt="Connect to Strava"/></button>
        <button onClick={changeTheme}>Change mode</button>
        <div className="powered-by-strava">
          <img className="strava-img" src={poweredSVG}/>
        </div>

    </div>
  );
</code>```

Body:
I am trying to make the image take up the whole page for my component but cannot figure out what I am doing wrong?

this is how it currently looks and I cannot figure out how to ensure it takes up the extra whitespace marked in red too.

I tried setting the min width and height of the div it is contained in. Is it maybe I need to set the image up in the body but I was confused how to do that in react.

current page:

css:

.container {
    background-image: url("../images/img.jpg");

            background-repeat: no-repeat;
            background-size: contain;
            min-height: 100%;
            min-width: 100%;
}

.default-button {
    align-items: center;
    background-clip: padding-box;
    background-color: #fa6400;
    border: 1px solid transparent;
    border-radius: .25rem;
    box-shadow: rgba(0, 0, 0, 0.02) 0 1px 3px 0;
    box-sizing: border-box;
    color: #fff;
    cursor: pointer;
    display: inline-flex;
    font-family: "Rams Black";
    font-size: 16px;
    font-weight: 600;
    justify-content: center;
    line-height: 1.25;
    margin: 0;
    min-height: 3rem;
    padding: calc(.875rem - 1px) calc(1.5rem - 1px);
    position: relative;
    text-decoration: none;
    transition: all 250ms;
    user-select: none;
    -webkit-user-select: none;
    touch-action: manipulation;
    vertical-align: baseline;
    width: auto;
}

.default-button:hover,
.default-button:focus {
    background-color: #fb8332;
    box-shadow: rgba(0, 0, 0, 0.1) 0 4px 12px;
}

.default-button:hover {
    transform: translateY(-1px);
}

.default-button:active {
    background-color: #c85000;
    box-shadow: rgba(0, 0, 0, .06) 0 2px 4px;
    transform: translateY(0);
}

.powered-by-strava {
    display: flex;
    align-items: center;
    justify-content: center;
}

.connect-btn {
    background-color: transparent;
    padding: 0;
    border: none;
    background: none;
}

component where image is rendered:

 return (

        <button className="connect-btn" onClick={stravaAuth}></button>
        <button onClick={changeTheme}>Change mode</button>

  );


问:
Have to destroy and re-deploy pipeline stack after replacing Github token
I uses CDK to create and deploy pipeline(with AWS CodePipeline https://aws.amazon.com/codepipeline/), and today Source stage stopped working, complaining about insufficient permission, which turns out to be that the Github token is expired. Error:

"Could not access the GitHub repository: "pandaWebsite". The access token might be invalid or has been revoked. Edit the pipeline to reconnect with GitHub."

So I re-genereate the Github token, and updated it in AWS Secrets Manager. And click "Retry" button in pipeline, and it still failed. Eventually I have to run cdk destroy to destroy the pipeline, and run cdk deploy to re-deploy the pipeline, and then it works.

My question is, why I have to destroy and re-deploy the pipeline? I was expecting that once I updated the token in Secrets Manager, it should just work.

More context

AWS Secrets Manager is where I stored the Github token, and my CDK code fetch from it. See code here:

 // Add Source stage to fetch code from GitHub repository.
  private addSourceStage(
    pipeline: codepipeline.Pipeline,
    sourceCode: codepipeline.Artifact
  ) {
    pipeline.addStage({
      stageName: "Source",
      actions: [
        new codepipeline_actions.GitHubSourceAction({
          actionName: "Checkout",
          owner: "yangliu",
          repo: "pandaWebsite",
          branch: "main",
          // read the value from Secrets Manager
          oauthToken: CDK.SecretValue.secretsManager(
            "github-token"
          ),
          output: sourceCode,
          trigger: codepipeline_actions.GitHubTrigger.WEBHOOK,
        }),
      ],
    });
  }
```


问:
Cygwin script access to COM port denied
I get 'access denied' when using a shell script in cygwin.
Using stty > /dev/ttyS6 (for COM6).

Yet python scipts work fine, no access problem.

Have checked that I am i dialup group in cygwin.
Checked permissions on /dev/ttyS5

Can't find /etc/groups to check dialup is there.
Can't see if I am in dialup.

Title: Cygwin script access to COM port denied


问:
How to make an alert for the correct or incorrect answer in a quiz game?
I'm having trouble displaying the correct alert for a quiz game that I'm making. The correct_answer and incorrect_answers from an API are placed in an array that are displayed randomly in the game.html page. Not sure what to do to get the correct result on the page.

This is my script.js file:

```<code>window.onload = sendApiRequest

async function sendApiRequest(){
    let response = await fetch("https://opentdb.com/api.php?amount=1&category=9&difficulty=easy&type=multiple");
    console.log(response)
    let data = await response.json()
    console.log(data)
    useApiData(data)
}

function randomAnswers(array){
    let copyOfArray = Array.from(array);
      return function() {
        if (copyOfArray.length < 1) {
            copyOfArray = Array.from(array);
        }
        const index = Math.floor(Math.random() * copyOfArray.length);
        const item = copyOfArray[index];
        copyOfArray.splice(index, 1);
        return item;
    };
}

function useApiData(data){
    document.querySelector("#category").innerHTML = `Category: ${data.results[0].category}`
    document.querySelector("#difficulty").innerHTML = `Difficulty: ${data.results[0].difficulty}`
    document.querySelector("#question").innerHTML = `Question: ${data.results[0].question}`

    const chooseFromArray = randomAnswers([data.results[0].incorrect_answers[2], data.results[0].incorrect_answers[0],
    data.results[0].incorrect_answers[1], data.results[0].correct_answer]);

    document.querySelector("#answer1").innerHTML = `${chooseFromArray()}`;
    document.querySelector("#answer2").innerHTML = `${chooseFromArray()}`;
    document.querySelector("#answer3").innerHTML = `${chooseFromArray()}`;
    document.querySelector("#answer4").innerHTML = `${chooseFromArray()}`;

}

let correct_answer = document.querySelector("#answer1")
let incorrect_answers1 = document.querySelector("#answer2")
let incorrect_answers2 = document.querySelector("#answer3")
let incorrect_answers3 = document.querySelector("#answer4")

correct_answer.addEventListener("click", () => {
    alert("You got it right!")
    sendApiRequest()
})

incorrect_answers1.addEventListener("click", () => {
  alert("You got it wrong!")
  sendApiRequest()
})

incorrect_answers2.addEventListener("click", () => {
  alert("You got it wrong!")
  sendApiRequest()
})

incorrect_answers3.addEventListener("click", () => {
  alert("You got it wrong!")
  sendApiRequest()
})
</code>```

And this is my game.html file:

```<code><!DOCTYPE html>
<html>
<head>
    <title>Trivia Game</title>
    <script src="/script.js" defer></script>
</head>
    <body>
        <h2>Your Game Has Begun!</h2>
        <p id="category"></p>
        <p id="difficulty"></p>
        <p id="question"></p>
        <button id="answer1" value="A">A</button>
        <button id="answer2">B</button>
        <button id="answer3">C</button>
        <button id="answer4">D</button>
    </body>
</html>
</code>```

Any assistance or direction would be greatly appreciated. Thanks!

Body:
I'm having trouble displaying the correct alert for a quiz game that I'm making. The correct_answer and incorrect_answers from an API are placed in an array that are displayed randomly in the game.html page. Not sure what to do to get the correct result on the page.

This is my script.js file:

window.onload = sendApiRequest

async function sendApiRequest(){
    let response = await fetch("https://opentdb.com/api.php?amount=1&category=9&difficulty=easy&type=multiple");
    console.log(response)
    let data = await response.json()
    console.log(data)
    useApiData(data)
}

function randomAnswers(array){
    let copyOfArray = Array.from(array);
      return function() {
        if (copyOfArray.length < 1) {
            copyOfArray = Array.from(array);
        }
        const index = Math.floor(Math.random() * copyOfArray.length);
        const item = copyOfArray[index];
        copyOfArray.splice(index, 1);
        return item;
    };
}

function useApiData(data){
    document.querySelector("#category").innerHTML = `Category: ${data.results[0].category}`
    document.querySelector("#difficulty").innerHTML = `Difficulty: ${data.results[0].difficulty}`
    document.querySelector("#question").innerHTML = `Question: ${data.results[0].question}`

    const chooseFromArray = randomAnswers([data.results[0].incorrect_answers[2], data.results[0].incorrect_answers[0],
    data.results[0].incorrect_answers[1], data.results[0].correct_answer]);

    document.querySelector("#answer1").innerHTML = `${chooseFromArray()}`;
    document.querySelector("#answer2").innerHTML = `${chooseFromArray()}`;
    document.querySelector("#answer3").innerHTML = `${chooseFromArray()}`;
    document.querySelector("#answer4").innerHTML = `${chooseFromArray()}`;

}

let correct_answer = document.querySelector("#answer1")
let incorrect_answers1 = document.querySelector("#answer2")
let incorrect_answers2 = document.querySelector("#answer3")
let incorrect_answers3 = document.querySelector("#answer4")

correct_answer.addEventListener("click", () => {
    alert("You got it right!")
    sendApiRequest()
})

incorrect_answers1.addEventListener("click", () => {
  alert("You got it wrong!")
  sendApiRequest()
})

incorrect_answers2.addEventListener("click", () => {
  alert("You got it wrong!")
  sendApiRequest()
})

incorrect_answers3.addEventListener("click", () => {
  alert("You got it wrong!")
  sendApiRequest()
})

And this is my game.html file:

<!DOCTYPE html>

    <title>Trivia Game</title>

Your Game Has Begun!

        <button id="answer1" value="A">A</button>
        <button id="answer2">B</button>
        <button id="answer3">C</button>
        <button id="answer4">D</button>

Any assistance or direction would be greatly appreciated. Thanks!


问:
Being able to display an image from MySQL database
What I'm currently trying to do is display an image from the database in which I've saved an image into. The problem is that the image comes up blank on the home page, when it should be showing the image.

What I tried was asking for assistance and ended up with creating a controller which would display the image by doing some conversion which will be shown below

My Controller

```<code>@GetMapping("/display/image/{id}")
public ResponseEntity<byte[]> displayItemImage(@PathVariable int id) {
    Item item = itemService.findItemById(id);
    byte[] image = item.getImage();
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.IMAGE_JPEG);
    return new ResponseEntity<>(image, headers, HttpStatus.OK);
}
</code>```

The thymeleaf

```<code><div class="category-1">
    <h2>Headwear</h2>
    <div class="image-container" th:each="clothing : ${clothingItems}">
        <img th:src="@{'display/image/' + ${clothing.id}}">
    </div>

</div>
</code>```

Expected result was hoping to be like this from the database

The actual result was a blank image (Just showing an image icon with an empty white box)
It wouldn't end up showing and I was told that my server-side code is fine and it could be the way I'm saving it into the database

HTML form with thymeleaf to save the result

```<code><form class="contact-form" method="POST" th:action="@{/crafts}" th:object="${item}">

    <div class="button-group">
        <input type="radio" name="category-choice" id="choice-1" th:field="*{category}" th:value="${clothing}">
        <input type="radio" name="category-choice" id="choice-2" th:field="*{category}" th:value="${cosmetics}">
        <input type="radio" name="category-choice" id="choice-3" th:field="*{category}" th:value="${celebration}">
        <input type="radio" name="category-choice" id="choice-4" th:field="*{category}" th:value="${other}">
    </div>

    <div class="label-group">
        <label for="choice-1" class="label-1">Clothing</label>
        <label for="choice-2" class="label-2">Cosmetics</label>
        <label for="choice-3" class="label-3">Celebration</label>
        <label for="choice-4" class="label-4">Other</label>
    </div>

    <input type="file" id="fileUpload" accept="image/*" th:field="*{image}">

    <div id="description-field">
        <label for="description">Description</label>
        <textarea name="userText" id="description" cols="50" rows="10" placeholder="Describe what you have made..."
                  required th:field="*{text}"></textarea>
    </div>

    <button type="submit">Submit</button>

</form>
</code>```

Controllers used for this

```<code>@GetMapping("/crafts/new")
public String createPost(Model model){

    Item item = new Item();

    Category clothing = categoryService.findCategoryById(1);
    Category cosmetics = categoryService.findCategoryById(2);
    Category celebration = categoryService.findCategoryById(3);
    Category other = categoryService.findCategoryById(4);

    model.addAttribute("item", item);

    model.addAttribute("clothing", clothing.getId());
    model.addAttribute("cosmetics", cosmetics.getId());
    model.addAttribute("celebration", celebration.getId());
    model.addAttribute("other", other.getId());

    return "add-form";

}
</code>```
```<code>@PostMapping("/crafts")
public String saveItem(@ModelAttribute("item") Item item){
    itemService.saveItem(item);
    return "redirect:/home";
}
</code>```

And MySQL

```<code>CREATE TABLE categories(
   id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
    category VARCHAR(50) NOT NULL
);

INSERT INTO categories (category) VALUES
 ("Clothing"),
 ("Cosmetics"),
 ("Celebration"),
 ("Other");

CREATE TABLE posts(
   id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
   img BLOB NOT NULL,
   post TEXT,
    category_id INT,
    FOREIGN KEY(category_id) REFERENCES categories(id)
);

CREATE TABLE authorities(
   id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
    authority VARCHAR(50)
);

INSERT INTO authorities(authority) VALUES
   ("ROLE_USER"),
    ("ROLE_ADMIN");

CREATE TABLE users(
   username VARCHAR(100) NOT NULL PRIMARY KEY,
    password VARCHAR(255) NOT NULL,
    role_id INT,
    FOREIGN KEY(role_id) REFERENCES authorities(id)
);

INSERT INTO users(username, password, role_id) VALUES
("Admin", "password", 2);

CREATE TABLE contact(
   id INT PRIMARY KEY,
    name VARCHAR(100),
    email VARCHAR(255),
   body TEXT
);
</code>```

An image within the database would look like this below

Item class

```<code>@Entity
@Table(name = "posts")
public class Item {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private int id;

    @Column(name = "post")
    private String text;

    @Lob
    @Column(name = "img")
    private byte[] image;

    @OneToOne(cascade = {CascadeType.DETACH,
                        CascadeType.MERGE,
                        CascadeType.PERSIST,
                        CascadeType.REFRESH})
    @JoinColumn(name = "category_id")
    private Category category;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    public byte[] getImage() {
        return image;
    }

    public void setImage(byte[] image) {
        this.image = image;
    }

    public Category getCategory() {
        return category;
    }

    public void setCategory(Category category) {
        this.category = category;
    }

    @Override
    public String toString() {
        return "Item{" +
                "id=" + id +
                ", text='" + text + '\'' +
                ", image=" + Arrays.toString(image) +
                ", category=" + category +
                '}';
    }
}
</code>```

Item Repository which extends JPARepository

```<code>@Repository
public interface ItemRepository extends JpaRepository<Item, Integer> {

    @Query("FROM Item WHERE category_id = 1")
    List<Item> findAllHeadwear();

    @Query("FROM Item WHERE category_id = 2")
    List<Item> findAllCosmetics();

    @Query("FROM Item WHERE category_id = 3")
    List<Item> findAllCelebration();

    @Query("FROM Item WHERE category_id = 4")
    List<Item> findAllOther();

}
</code>```

Along with the Service which is using the repository

```<code>@Override
public void saveItem(Item item) {
    itemRepository.save(item);
}
</code>```

Body:
What I'm currently trying to do is display an image from the database in which I've saved an image into. The problem is that the image comes up blank on the home page, when it should be showing the image.

What I tried was asking for assistance and ended up with creating a controller which would display the image by doing some conversion which will be shown below

My Controller

@GetMapping("/display/image/{id}")
public ResponseEntity<byte[]> displayItemImage(@PathVariable int id) {
    Item item = itemService.findItemById(id);
    byte[] image = item.getImage();
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.IMAGE_JPEG);
    return new ResponseEntity<>(image, headers, HttpStatus.OK);
}

The thymeleaf

Headwear

Expected result was hoping to be like this from the database

The actual result was a blank image (Just showing an image icon with an empty white box)
It wouldn't end up showing and I was told that my server-side code is fine and it could be the way I'm saving it into the database

HTML form with thymeleaf to save the result

<form class="contact-form" method="POST" th:action="@{/crafts}" th:object="${item}">

        <input type="radio" name="category-choice" id="choice-1" th:field="*{category}" th:value="${clothing}">
        <input type="radio" name="category-choice" id="choice-2" th:field="*{category}" th:value="${cosmetics}">
        <input type="radio" name="category-choice" id="choice-3" th:field="*{category}" th:value="${celebration}">
        <input type="radio" name="category-choice" id="choice-4" th:field="*{category}" th:value="${other}">

        Clothing
        Cosmetics
        Celebration
        Other

    <input type="file" id="fileUpload" accept="image/*" th:field="*{image}">

        Description
        <textarea name="userText" id="description" cols="50" rows="10" placeholder="Describe what you have made..."
                  required th:field="*{text}"></textarea>

    <button type="submit">Submit</button>

</form>

Controllers used for this

@GetMapping("/crafts/new")
public String createPost(Model model){

    Item item = new Item();

    Category clothing = categoryService.findCategoryById(1);
    Category cosmetics = categoryService.findCategoryById(2);
    Category celebration = categoryService.findCategoryById(3);
    Category other = categoryService.findCategoryById(4);

    model.addAttribute("item", item);

    model.addAttribute("clothing", clothing.getId());
    model.addAttribute("cosmetics", cosmetics.getId());
    model.addAttribute("celebration", celebration.getId());
    model.addAttribute("other", other.getId());

    return "add-form";

}

@PostMapping("/crafts")
public String saveItem(@ModelAttribute("item") Item item){
    itemService.saveItem(item);
    return "redirect:/home";
}

And MySQL

CREATE TABLE categories(
   id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
    category VARCHAR(50) NOT NULL
);

INSERT INTO categories (category) VALUES
 ("Clothing"),
 ("Cosmetics"),
 ("Celebration"),
 ("Other");

CREATE TABLE posts(
   id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
   img BLOB NOT NULL,
   post TEXT,
    category_id INT,
    FOREIGN KEY(category_id) REFERENCES categories(id)
);

CREATE TABLE authorities(
   id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
    authority VARCHAR(50)
);

INSERT INTO authorities(authority) VALUES
   ("ROLE_USER"),
    ("ROLE_ADMIN");

CREATE TABLE users(
   username VARCHAR(100) NOT NULL PRIMARY KEY,
    password VARCHAR(255) NOT NULL,
    role_id INT,
    FOREIGN KEY(role_id) REFERENCES authorities(id)
);

INSERT INTO users(username, password, role_id) VALUES
("Admin", "password", 2);

CREATE TABLE contact(
   id INT PRIMARY KEY,
    name VARCHAR(100),
    email VARCHAR(255),
   body TEXT
);

An image within the database would look like this below

Item class

@Entity
@Table(name = "posts")
public class Item {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private int id;

    @Column(name = "post")
    private String text;

    @Lob
    @Column(name = "img")
    private byte[] image;

    @OneToOne(cascade = {CascadeType.DETACH,
                        CascadeType.MERGE,
                        CascadeType.PERSIST,
                        CascadeType.REFRESH})
    @JoinColumn(name = "category_id")
    private Category category;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    public byte[] getImage() {
        return image;
    }

    public void setImage(byte[] image) {
        this.image = image;
    }

    public Category getCategory() {
        return category;
    }

    public void setCategory(Category category) {
        this.category = category;
    }

    @Override
    public String toString() {
        return "Item{" +
                "id=" + id +
                ", text='" + text + '\'' +
                ", image=" + Arrays.toString(image) +
                ", category=" + category +
                '}';
    }
}

Item Repository which extends JPARepository

@Repository
public interface ItemRepository extends JpaRepository<Item, Integer> {

    @Query("FROM Item WHERE category_id = 1")
    List<Item> findAllHeadwear();

    @Query("FROM Item WHERE category_id = 2")
    List<Item> findAllCosmetics();

    @Query("FROM Item WHERE category_id = 3")
    List<Item> findAllCelebration();

    @Query("FROM Item WHERE category_id = 4")
    List<Item> findAllOther();

}

Along with the Service which is using the repository

@Override
public void saveItem(Item item) {
    itemRepository.save(item);
}


问:
Get all possible outputs from a set of inputs in python
I have a CSV file called recipes.csv:

```<code>name,alternate,time,ingredients,products,producedIn,classifiedAs
Iron Plate,False,6,30.0x Iron Ingot,20.0x Iron Plate,Constructor,Iron
Iron Rod,False,4,15.0x Iron Ingot,15.0x Iron Rod,Constructor,Iron
Wire,False,4,15.0x Copper Ingot,30.0x Wire,Constructor,Copper...
</code>```

I can't find a way to get the possible results with a set of inputs as a dictionary where the keys are the recipes and the value is the number of said recipies that can be made with the desired inputs. An example:

Input:

{'Iron Ingot':60, 'Copper Ingot':20}
```
<p><br>Desired output:</p>
<pre class="lang-py prettyprint-override"><code>[
    {'Iron Plate':2, 'Wire':1, 'Leftover':{'Copper Ingot':5}},
    {'Iron Rod':4, 'Wire':1, 'Leftover':{'Copper Ingot':5}},
    {'Iron Plate':1,'Iron Rod':2, 'Wire':1, 'Leftover':{'Copper Ingot':5}},
]
</code>```

My code:

import csv
import pandas as pd

df = pd.read_csv("recipes.csv", usecols = ['name','ingredients', 'products'])

# Original Header: ['name', 'alternate', 'time', 'ingredients', 'products', 'producedIn', 'classifiedAs']
# New Header: ['name', 'ingredients', 'products']
# Iron Plate: #139
# Iron Rod: #140
# Wire: #214

df.to_csv('recipes_new.csv')

with open('recipes_new.csv') as csvFile:
    recipes = csv.reader(csvFile)

    # Print out recipes:
    i = 0
    for row in recipes:
        print(row)
        i += 1
```

Body:
I have a CSV file called recipes.csv:

name,alternate,time,ingredients,products,producedIn,classifiedAs
Iron Plate,False,6,30.0x Iron Ingot,20.0x Iron Plate,Constructor,Iron
Iron Rod,False,4,15.0x Iron Ingot,15.0x Iron Rod,Constructor,Iron
Wire,False,4,15.0x Copper Ingot,30.0x Wire,Constructor,Copper...

I can't find a way to get the possible results with a set of inputs as a dictionary where the keys are the recipes and the value is the number of said recipies that can be made with the desired inputs. An example:

Input:

{'Iron Ingot':60, 'Copper Ingot':20}

Desired output:

[
    {'Iron Plate':2, 'Wire':1, 'Leftover':{'Copper Ingot':5}},
    {'Iron Rod':4, 'Wire':1, 'Leftover':{'Copper Ingot':5}},
    {'Iron Plate':1,'Iron Rod':2, 'Wire':1, 'Leftover':{'Copper Ingot':5}},
]

My code:

import csv
import pandas as pd

df = pd.read_csv("recipes.csv", usecols = ['name','ingredients', 'products'])

# Original Header: ['name', 'alternate', 'time', 'ingredients', 'products', 'producedIn', 'classifiedAs']
# New Header: ['name', 'ingredients', 'products']
# Iron Plate: #139
# Iron Rod: #140
# Wire: #214

df.to_csv('recipes_new.csv')

with open('recipes_new.csv') as csvFile:
    recipes = csv.reader(csvFile)

    # Print out recipes:
    i = 0
    for row in recipes:
        print(row)
        i += 1


问:
Typescript error with material react table
I'm trying to learn material-react-table and currently I'm trying to make a table actions component to be plugged in to my other tables. So, I'm trying to plug in the component into the renderRowActions prop of <MaterialReactTable />. Based on my understanding of material-react-table types like MRT_row, I'm trying to notify typescript that the data could be of User type or BoardGameHistory which are objects. However, the following is the error I'm getting. I feel like I am lacking an understanding in typescript to tackle this problem and would appreciate any help. Thanks!

```<code>Argument of type 'MRT_Row<User> | MRT_Row<BoardGameHistory>' is not assignable to parameter of type '((MRT_Row<User> | ((prevState: MRT_Row<User> | null) => MRT_Row<User> | null)) & (MRT_Row<BoardGameHistory> | ((prevState: MRT_Row<...> | null) => MRT_Row<...> | null))) | null'.
</code>```

Table Actions Component

```<code>import React from "react";
// mui
import { Tooltip, IconButton, Box } from "@mui/material";
import DeleteIcon from "@mui/icons-material/Delete";
import EditIcon from "@mui/icons-material/Edit";
// types
import { MRT_Row, MRT_TableInstance } from "material-react-table";
import { User } from "src/@types/UserTypes";
import { BoardGameHistory } from "src/@types/BoardGameTypes";

interface TableCRUDActionsProps<T extends Record<string, any>> {
  row: MRT_Row<T>;
  table: MRT_TableInstance<T>;
  // eslint-disable-next-line no-unused-vars
  handleDeleteRow: (row: MRT_Row<T>) => void;
}

export default function TableCRUDActions({
  row,
  table,
  handleDeleteRow,
}: TableCRUDActionsProps<User> | TableCRUDActionsProps<BoardGameHistory>) {
  return (
    <Box sx={{ display: "flex", gap: "1rem" }}>
      <Tooltip arrow placement="left" title="Edit">
        <IconButton onClick={() => table.setEditingRow(row)}>
          <EditIcon />
        </IconButton>
      </Tooltip>
      <Tooltip arrow placement="right" title="Delete">
        <IconButton color="error" onClick={() => handleDeleteRow(row)}>
          <DeleteIcon />
        </IconButton>
      </Tooltip>
    </Box>
  );
}
</code>```

Where I would plug this in

```<code> <MaterialReactTable
        columns={userTableColumns}
        data={data}
        enableEditing
        onEditingRowSave={handleRowEditSave}
        renderRowActions={({ row, table }) => (
          <TableCRUDActions
            row={row}
            table={table}
            handleDeleteRow={() => handleDeleteRow(row)}
          />
        )}
        renderTopToolbarCustomActions={() => (
          <PrimaryButton onClick={() => setIsDialogOpen(true)}>
            Create New User
          </PrimaryButton>
        )}
</code>```

Body:
I'm trying to learn material-react-table and currently I'm trying to make a table actions component to be plugged in to my other tables. So, I'm trying to plug in the component into the renderRowActions prop of <MaterialReactTable />. Based on my understanding of material-react-table types like MRT_row, I'm trying to notify typescript that the data could be of User type or BoardGameHistory which are objects. However, the following is the error I'm getting. I feel like I am lacking an understanding in typescript to tackle this problem and would appreciate any help. Thanks!

Argument of type 'MRT_Row<User> | MRT_Row<BoardGameHistory>' is not assignable to parameter of type '((MRT_Row<User> | ((prevState: MRT_Row<User> | null) => MRT_Row<User> | null)) & (MRT_Row<BoardGameHistory> | ((prevState: MRT_Row<...> | null) => MRT_Row<...> | null))) | null'.

Table Actions Component

import React from "react";
// mui
import { Tooltip, IconButton, Box } from "@mui/material";
import DeleteIcon from "@mui/icons-material/Delete";
import EditIcon from "@mui/icons-material/Edit";
// types
import { MRT_Row, MRT_TableInstance } from "material-react-table";
import { User } from "src/@types/UserTypes";
import { BoardGameHistory } from "src/@types/BoardGameTypes";

interface TableCRUDActionsProps<T extends Record<string, any>> {
  row: MRT_Row<T>;
  table: MRT_TableInstance<T>;
  // eslint-disable-next-line no-unused-vars
  handleDeleteRow: (row: MRT_Row<T>) => void;
}

export default function TableCRUDActions({
  row,
  table,
  handleDeleteRow,
}: TableCRUDActionsProps<User> | TableCRUDActionsProps<BoardGameHistory>) {
  return (
    <Box sx={{ display: "flex", gap: "1rem" }}>
      <Tooltip arrow placement="left" title="Edit">
        <IconButton onClick={() => table.setEditingRow(row)}>
          <EditIcon />
        </IconButton>
      </Tooltip>
      <Tooltip arrow placement="right" title="Delete">
        <IconButton color="error" onClick={() => handleDeleteRow(row)}>
          <DeleteIcon />
        </IconButton>
      </Tooltip>
    </Box>
  );
}

Where I would plug this in

 <MaterialReactTable
        columns={userTableColumns}
        data={data}
        enableEditing
        onEditingRowSave={handleRowEditSave}
        renderRowActions={({ row, table }) => (
          <TableCRUDActions
            row={row}
            table={table}
            handleDeleteRow={() => handleDeleteRow(row)}
          />
        )}
        renderTopToolbarCustomActions={() => (
          <PrimaryButton onClick={() => setIsDialogOpen(true)}>
            Create New User
          </PrimaryButton>
        )}


问:
BuildConfig is defined multiple times in Xamarin Android app
I'm working on an android application with Xamarin and I keep getting this error when I try to build.

```<code>Error       Error in obj\Debug\130\lp\0\jl\bin\classes.jar:com/getkeepsafe/relinker/BuildConfig.class:
Type com.getkeepsafe.relinker.BuildConfig is defined multiple times: obj\Debug\130\lp\0\jl\bin\classes.jar:com/getkeepsafe/relinker/BuildConfig.class, obj\Debug\130\lp\132\jl\bin\classes.jar:com/getkeepsafe/relinker/BuildConfig.class
Compilation failed
java.lang.RuntimeException: com.android.tools.r8.CompilationFailedException: Compilation failed to complete, origin: obj\Debug\130\lp\0\jl\bin\classes.jar

</code>```

I've tried looking for duplicates in packages, deleting obj and bin folders, clean+build and rebuild and many other solutions from the internet and nothing seems to solve it.

Body:
I'm working on an android application with Xamarin and I keep getting this error when I try to build.

Error       Error in obj\Debug\130\lp\0\jl\bin\classes.jar:com/getkeepsafe/relinker/BuildConfig.class:
Type com.getkeepsafe.relinker.BuildConfig is defined multiple times: obj\Debug\130\lp\0\jl\bin\classes.jar:com/getkeepsafe/relinker/BuildConfig.class, obj\Debug\130\lp\132\jl\bin\classes.jar:com/getkeepsafe/relinker/BuildConfig.class
Compilation failed
java.lang.RuntimeException: com.android.tools.r8.CompilationFailedException: Compilation failed to complete, origin: obj\Debug\130\lp\0\jl\bin\classes.jar

I've tried looking for duplicates in packages, deleting obj and bin folders, clean+build and rebuild and many other solutions from the internet and nothing seems to solve it.


问:
Change color of frame of the QGroupBox when hover on it
I have the next code where I want to change color of the frame from silver to red when hover on the frame by mouse:

```<code>#include <QApplication>
#include <QGroupBox>
#include <QLineEdit>
#include <QVBoxLayout>

int main(int argc, char* argv[])
{
    QApplication app(argc, argv);

    QWidget* mainWidget = new QWidget;
    mainWidget->resize(600, 400);

    QVBoxLayout* mainLayout = new QVBoxLayout(mainWidget);

    QLineEdit* lineEdit = new QLineEdit("initial text");
    lineEdit->setStyleSheet(
        "QLineEdit"
        "{"
        "    font-size: 14px;"
        "}"
        //
    );

    QGroupBox* groupBox = new QGroupBox("Group Box Title");
    groupBox->setStyleSheet(
        "QGroupBox {"
        "    font: bold;"
        "    font-size: 10px;"
        "    border: 1px solid silver;"
        "    border-radius: 6px;"
        "    margin-top: 12px;"
        "    margin-left: 10px;"
        "}"
        //      "QGroupBox:hover" // don't work as expected
        //      "{"
        //      "    border: 1px solid red;"
        //      "}"
        "QGroupBox:focus"
        "{"
        "    border: 1px solid red;"
        "}"
        "QGroupBox::title"
        "{"
        "    subcontrol-origin: margin;"
        "    left: 16px;"
        "    padding: 5px 8px 0px 8px;"
        "}"
        //
    );

    groupBox->setFocusProxy(lineEdit);
    groupBox->setLayout(new QVBoxLayout);
    groupBox->layout()->addWidget(lineEdit);

    mainLayout->addWidget(groupBox);

    mainWidget->setFocusPolicy(Qt::ClickFocus);
    mainWidget->show();

    return app.exec();
}
</code>```

Eventually I decided at least implement changing color of the frame when it in the focus, and focus changing by clicking.

But I want to change color by hovering.

I have tried "QGroupBox:hover{}" and "QGroupBox:enabled:hover {}" - both of them don't give diserable effect.

Can anyone tell me what am I doing wrong?

Body:
I have the next code where I want to change color of the frame from silver to red when hover on the frame by mouse:

#include <QApplication>
#include <QGroupBox>
#include <QLineEdit>
#include <QVBoxLayout>

int main(int argc, char* argv[])
{
    QApplication app(argc, argv);

    QWidget* mainWidget = new QWidget;
    mainWidget->resize(600, 400);

    QVBoxLayout* mainLayout = new QVBoxLayout(mainWidget);

    QLineEdit* lineEdit = new QLineEdit("initial text");
    lineEdit->setStyleSheet(
        "QLineEdit"
        "{"
        "    font-size: 14px;"
        "}"
        //
    );

    QGroupBox* groupBox = new QGroupBox("Group Box Title");
    groupBox->setStyleSheet(
        "QGroupBox {"
        "    font: bold;"
        "    font-size: 10px;"
        "    border: 1px solid silver;"
        "    border-radius: 6px;"
        "    margin-top: 12px;"
        "    margin-left: 10px;"
        "}"
        //      "QGroupBox:hover" // don't work as expected
        //      "{"
        //      "    border: 1px solid red;"
        //      "}"
        "QGroupBox:focus"
        "{"
        "    border: 1px solid red;"
        "}"
        "QGroupBox::title"
        "{"
        "    subcontrol-origin: margin;"
        "    left: 16px;"
        "    padding: 5px 8px 0px 8px;"
        "}"
        //
    );

    groupBox->setFocusProxy(lineEdit);
    groupBox->setLayout(new QVBoxLayout);
    groupBox->layout()->addWidget(lineEdit);

    mainLayout->addWidget(groupBox);

    mainWidget->setFocusPolicy(Qt::ClickFocus);
    mainWidget->show();

    return app.exec();
}

Eventually I decided at least implement changing color of the frame when it in the focus, and focus changing by clicking.

But I want to change color by hovering.

I have tried "QGroupBox:hover{}" and "QGroupBox:enabled:hover {}" - both of them don't give diserable effect.

Can anyone tell me what am I doing wrong?


问:
How to prevent a Lua file closing when I press enter?
I have a block of code in sublime text, and whenever I press enter on the Lua file its connected to, the file closes, so I can't enter input. The code is below.

```<code>io.write("name?")
local name = io.read()
io.write("hello " .. name)
</code>```

I expected it to print "hello " and then whatever input was entered, but the file closes instead.

Body:
I have a block of code in sublime text, and whenever I press enter on the Lua file its connected to, the file closes, so I can't enter input. The code is below.

io.write("name?")
local name = io.read()
io.write("hello " .. name)

I expected it to print "hello " and then whatever input was entered, but the file closes instead.


问:
Loop won't break
The program is stuck at the first input, also won't respond to while True

```<code>available_toppings = ["mushrooms", "olives", "pepperoni", "pineapple"]
print(f"Hello! please choose from the available toppings:\n{available_toppings[0].title()}\n{available_toppings[1].title()}\n{available_toppings[2].title()}\n{available_toppings[3].title()}\n")
requested_toppings = input("Please choose your topping:\n")

def program():
            if requested_toppings in available_toppings:
                print(f"Adding {requested_toppings}..")
            else:
                print(f"Sorry, {requested_toppings} is not available!")

while True:
    program()
    if input("Do you want to add another topping? (Y/N)\n").strip().upper().lower() == "N":
        break
print("Finished making your pizza!")
</code>```

The program should print(f"Adding{requested_toppings}..")  if the user input is a value that exists in available_toppings else print(f"Sorry, {requested_toppings} is not available!") if it's not. Then ask the user if they want to add another topping. If not (N), the loop breaks and print("Finished making your pizza!")
Instead it's stuck at the first input.

Title: Loop won't break

Body:
The program is stuck at the first input, also won't respond to while True

available_toppings = ["mushrooms", "olives", "pepperoni", "pineapple"]
print(f"Hello! please choose from the available toppings:\n{available_toppings[0].title()}\n{available_toppings[1].title()}\n{available_toppings[2].title()}\n{available_toppings[3].title()}\n")
requested_toppings = input("Please choose your topping:\n")

def program():
            if requested_toppings in available_toppings:
                print(f"Adding {requested_toppings}..")
            else:
                print(f"Sorry, {requested_toppings} is not available!")

while True:
    program()
    if input("Do you want to add another topping? (Y/N)\n").strip().upper().lower() == "N":
        break
print("Finished making your pizza!")

The program should print(f"Adding{requested_toppings}..")  if the user input is a value that exists in available_toppings else print(f"Sorry, {requested_toppings} is not available!") if it's not. Then ask the user if they want to add another topping. If not (N), the loop breaks and print("Finished making your pizza!")
Instead it's stuck at the first input.


问:
theme and face=bold in ggplot
I need to use a specific font for my ggplots, and i set in in the theme

```<code>theme_set(theme_minimal(
  base_family="Calibri",
  base_size=8
))
</code>```

however, when i try to use face=bold for my axes it does not seem to apply and shows them as regular, not bold. The minute i remove base_family, the "boldness" is back...

How can i fix this?

```<code>ggplot(data = mpg, aes(x = class)) +
  geom_bar(stat = "count")+
  theme(
    axis.title = element_text(face="bold"), #10pt bold
    axis.text= element_text(size = 9, colour = "black") #9pt
  )
</code>```

Title: theme and face=bold in ggplot

Body:
I need to use a specific font for my ggplots, and i set in in the theme

theme_set(theme_minimal(
  base_family="Calibri",
  base_size=8
))

however, when i try to use face=bold for my axes it does not seem to apply and shows them as regular, not bold. The minute i remove base_family, the "boldness" is back...

How can i fix this?

ggplot(data = mpg, aes(x = class)) +
  geom_bar(stat = "count")+
  theme(
    axis.title = element_text(face="bold"), #10pt bold
    axis.text= element_text(size = 9, colour = "black") #9pt
  )


问:
Tkinter Window won't open when launched from CMD/Terminal or Python Shell?
I've seen other questions posted along this line but I have a mainloop() function in my program which for most people seems to be the usual fix.

When attempting to launch the program from a command line prompt or terminal or just by double pressing to open it as a python shell on windows it briefly shows the command window and closes instantly. This happens on Windows 11 and Ubuntu. Unsure what is causing it see attached a photo of what is happening.

The CMD Prompt just flashes up and instantly closes with a similar occurrence on Ubuntu. There are print() functions in the script of which I see none running. I'd also like to mention that the program launches absolutely fine from Python IDLE - My personal choice of Python IDE.

I do have to add I have got a infinite loop of sorts running in my program code for which I will attach below. I've played around adding "root.update_idletasks()" and "root.update()" to the loop to no avail. I'm unsure of what other actions to take?

The Infinite Loop I have mentioned above is a defined function, being called with the "after" method "root.after(0,main_program_exec)" and then continuously run with another after method " root.after(500,main_program_exec)".

NOTE: Most of the code has been left out as this is an application I'll be using for work. - Sorry about messy code normally others don't have to read it! I also have included all modules imported in the case that one of those could be causing a issue!

CODE SNIPPIT:

```<code>from pymodbus.client import ModbusTcpClient
from pymodbus.constants import Endian
from pymodbus.payload import BinaryPayloadDecoder
from tkinter import *
import time
from PIL import ImageTk, Image
from tksheet import Sheet

def main_program_exec():
    global client, datatype
    root.update_idletasks()
    root.update()
    if program_mode.get():
        pass
    else:
        a = RegType.returnSelection()
        b = StartAdd_Entry_Widget.returnValue()
        if b <=0:
            b = 1
        if b > 9999:
            b = 9999
        c = Length_Entry_Widget.returnValue()
        if c >100:
            c = 100
        elif c < 1:
            c = 1
    try:
        main_data = client.compile_data(a,c,b,datatype) #Mode, length, starting add, mode
        update_table(main_data)
    except Exception as e:
        print(e)
        pass

    root.after(500, main_program_exec)
</code>```

....

```<code>
root.after(0, main_program_exec)
main loop()

</code>```

Body:
I've seen other questions posted along this line but I have a mainloop() function in my program which for most people seems to be the usual fix.

When attempting to launch the program from a command line prompt or terminal or just by double pressing to open it as a python shell on windows it briefly shows the command window and closes instantly. This happens on Windows 11 and Ubuntu. Unsure what is causing it see attached a photo of what is happening.

The CMD Prompt just flashes up and instantly closes with a similar occurrence on Ubuntu. There are print() functions in the script of which I see none running. I'd also like to mention that the program launches absolutely fine from Python IDLE - My personal choice of Python IDE.

I do have to add I have got a infinite loop of sorts running in my program code for which I will attach below. I've played around adding "root.update_idletasks()" and "root.update()" to the loop to no avail. I'm unsure of what other actions to take?

The Infinite Loop I have mentioned above is a defined function, being called with the "after" method "root.after(0,main_program_exec)" and then continuously run with another after method " root.after(500,main_program_exec)".

NOTE: Most of the code has been left out as this is an application I'll be using for work. - Sorry about messy code normally others don't have to read it! I also have included all modules imported in the case that one of those could be causing a issue!

CODE SNIPPIT:

from pymodbus.client import ModbusTcpClient
from pymodbus.constants import Endian
from pymodbus.payload import BinaryPayloadDecoder
from tkinter import *
import time
from PIL import ImageTk, Image
from tksheet import Sheet

def main_program_exec():
    global client, datatype
    root.update_idletasks()
    root.update()
    if program_mode.get():
        pass
    else:
        a = RegType.returnSelection()
        b = StartAdd_Entry_Widget.returnValue()
        if b <=0:
            b = 1
        if b > 9999:
            b = 9999
        c = Length_Entry_Widget.returnValue()
        if c >100:
            c = 100
        elif c < 1:
            c = 1
    try:
        main_data = client.compile_data(a,c,b,datatype) #Mode, length, starting add, mode
        update_table(main_data)
    except Exception as e:
        print(e)
        pass

    root.after(500, main_program_exec)

....

root.after(0, main_program_exec)
main loop()


问:
Why does the input box keep glitching on iOS but not on Android?
Does anyone know why the input box might be glitching only on iOS but works fine on Android? I have attached two videos for better explanation of this problem. Basically on iOS I would have to tap the input field twice for it to go into 'active' state and afterwards when I try type it zooms in so much into the screen to type. No issues like this in the browser as well.

iOS - https://streamable.com/e622tj
Android - https://streamable.com/4zvns6

```<code><div
        id='task-writer'
        onClick={() => {
          inputRef.current?.focus();
        }}
      >
        <div className='left'>
          <label>
            <input
              type='checkbox'
              defaultChecked={checked}
              onChange={() => setChecked(!checked)}
            />
            <div className='checkbox-div' />
          </label>
          <form
            className='NewTodoForm'
            id='task-form'
            onSubmit={handleSubmit}
            ref={formRef}
          >
            <input
              value={userInput.task}
              onChange={handleChange}
              id='task'
              type='text'
              name='task'
              placeholder='Add your task here...'
              autoComplete='off'
              ref={inputRef}
              // onFocus={() => {
              //   console.log('focused');
              //   setIsFocused(true);
              // }}
              // onBlur={() => {
              //   console.log('blurred');
              //   inputRef.current?.focus();
              //   setIsFocused(false);
              // }}
            />
          </form>
        </div>
</code>```

CSS Code:

```<code> #task-writer {
      display: flex;
      flex-direction: row;

      width: 100%;

      align-items: center;

      padding: 10px;
      padding-left: 20px;
      padding-right: 15px;

      border-radius: 20px;

      background-color: #f5f7fa;

      .left {
        display: flex;
        flex-direction: row;

        width: 100%;
        height: 100%;

        align-items: center;

        gap: 20px;
        padding: 10px 0;

        label {
          display: grid;
          place-items: center;
          width: 30px;
          height: 30px;
          cursor: pointer;
          input {
            display: none;
          }

        form {
          width: 100%;
          height: 100%;

          overflow: hidden;
          transform: translateX(-50px);

          transition: 0.25s ease;
          transition-property: transform;

          input {
            width: 100%;
            height: 100%;

            border: none;
            outline: none;

            font-family: 'Inter var', sans-serif;
            font-size: clamp(12px, 1.65vw, 16px);
            font-weight: 400;

            color: #000;
            background-color: transparent;
          }
        }
      }

      right-calendar-date {
        position: relative;

        display: flex;
        flex-direction: row;

        height: 40px;
        width: fit-content;
        align-items: center;

        gap: 12px;
        padding: 0px 12px;
        margin-left: 12px;

        border-radius: 10px;
        padding-right: 40px;
        cursor: pointer;

        color: #6d6d6d;
        background-color: #EAEDEE;

        opacity: 0;
        pointer-events: none;

        transition: 0.25s ease;
        transition-property: opacity;

        h4 {
          overflow: hidden;
          white-space: nowrap;

          color: #000;
        }

      }

      .date-form {
        display: grid;
      place-items: center;

      height: 30px;
      width: 80px;
      padding: 0 16px;

      border-radius: 10px;
      opacity: 0;
      cursor: pointer;

      color: #6d6d6d;
      background-color: #eaedee;

      transition: 0.25s ease;
      transition-property: background-color;

      :hover {
        background-color: #d9d9d9;
      }

      h4 {
        font-size: clamp(12px, 1.65vw, 14px);
        font-weight: 500;
      }
    }
</code>```

Body:
Does anyone know why the input box might be glitching only on iOS but works fine on Android? I have attached two videos for better explanation of this problem. Basically on iOS I would have to tap the input field twice for it to go into 'active' state and afterwards when I try type it zooms in so much into the screen to type. No issues like this in the browser as well.

iOS - https://streamable.com/e622tj
Android - https://streamable.com/4zvns6

 {
          inputRef.current?.focus();
        }}
      >

            <input
              type='checkbox'
              defaultChecked={checked}
              onChange={() => setChecked(!checked)}
            />

          <form
            className='NewTodoForm'
            id='task-form'
            onSubmit={handleSubmit}
            ref={formRef}
          >
            <input
              value={userInput.task}
              onChange={handleChange}
              id='task'
              type='text'
              name='task'
              placeholder='Add your task here...'
              autoComplete='off'
              ref={inputRef}
              // onFocus={() => {
              //   console.log('focused');
              //   setIsFocused(true);
              // }}
              // onBlur={() => {
              //   console.log('blurred');
              //   inputRef.current?.focus();
              //   setIsFocused(false);
              // }}
            />
          </form>

CSS Code:

 #task-writer {
      display: flex;
      flex-direction: row;

      width: 100%;

      align-items: center;

      padding: 10px;
      padding-left: 20px;
      padding-right: 15px;

      border-radius: 20px;

      background-color: #f5f7fa;

      .left {
        display: flex;
        flex-direction: row;

        width: 100%;
        height: 100%;

        align-items: center;

        gap: 20px;
        padding: 10px 0;

        label {
          display: grid;
          place-items: center;
          width: 30px;
          height: 30px;
          cursor: pointer;
          input {
            display: none;
          }

        form {
          width: 100%;
          height: 100%;

          overflow: hidden;
          transform: translateX(-50px);

          transition: 0.25s ease;
          transition-property: transform;

          input {
            width: 100%;
            height: 100%;

            border: none;
            outline: none;

            font-family: 'Inter var', sans-serif;
            font-size: clamp(12px, 1.65vw, 16px);
            font-weight: 400;

            color: #000;
            background-color: transparent;
          }
        }
      }

      right-calendar-date {
        position: relative;

        display: flex;
        flex-direction: row;

        height: 40px;
        width: fit-content;
        align-items: center;

        gap: 12px;
        padding: 0px 12px;
        margin-left: 12px;

        border-radius: 10px;
        padding-right: 40px;
        cursor: pointer;

        color: #6d6d6d;
        background-color: #EAEDEE;

        opacity: 0;
        pointer-events: none;

        transition: 0.25s ease;
        transition-property: opacity;

        h4 {
          overflow: hidden;
          white-space: nowrap;

          color: #000;
        }

      }

      .date-form {
        display: grid;
      place-items: center;

      height: 30px;
      width: 80px;
      padding: 0 16px;

      border-radius: 10px;
      opacity: 0;
      cursor: pointer;

      color: #6d6d6d;
      background-color: #eaedee;

      transition: 0.25s ease;
      transition-property: background-color;

      :hover {
        background-color: #d9d9d9;
      }

      h4 {
        font-size: clamp(12px, 1.65vw, 14px);
        font-weight: 500;
      }
    }


问:
Failed to run custom build command for `librocksdb-sys
Does anybody know what should I install to fulfill librocksdb-sys dependency? I was trying to solve it with apt install clang but does not solve the issue. My best guess is that it is some error connected with linking and/or versioning.

Appreciate any hints.

error: failed to run custom build command for librocksdb-sys v0.8.0+7.4.4

Caused by:   process didn't exit successfully:
/home/tomek/ssd/workspaces/substrate/target/release/build/librocksdb-sys-dcab8f317e6498cb/build-script-build
(exit status: 101)   --- stderr   thread 'main' panicked at
'"enum_(unnamed_at_rocksdb/include/rocksdb/c_h_981_1)" is not a valid
Ident',
/home/tomek/.cargo/registry/src/github.com-1ecc6299db9ec823/proc-macro2-1.0.46/src/fallback.rs:756:9
note: run with RUST_BACKTRACE=1 environment variable to display a
backtrace warning: build failed, waiting for other jobs to finish...

The error occurs on Debian.


问:
Why does my text not show up in relative position to a box background?
I have made a background with the div box, following this triangles tutorial to separate it into two navy blue triangles and one white trapezoid.

I duplicated this div and added child elements with text to go in front of this background. I used position: absolute and the text was in front, but the text was grouped up funny, with the 3 sentences all duplicated and overlapping.

I then tried separating the div-child-text elements into 3 separate classes (.Child-text-01, -02, and -03) and adjusting the top function accordingly. And tada, no longer overlapping but still duplicated.

I tried position: relative for the text, and voila, it wouldn't show up because it is behind the box.

I checked my parses, they were fine as far as I know. I reasoned maybe the box isn't calculating its children because the relative position doesn't do it, I changed the boxes to position: absolute, but it screwed the web page up pretty hard. then I checked the HTML, and fiddled around with the ending  parse, no dice, I am wondering what I am missing, I am a new coder and self-taught.

My code is below:

body {
  background-color: #1d3c6e;
}

@font-face {
  font-family: "cola-font";
  src: url("cola-font-medium.ttf");
}

body h1 {
  color: white;
  font-size: 80px;
  font-family: "cola-font";
  font-width: 10px;
}

body h2 {
  color: white;
  font-family: "cola-font";
  font-width: 10px
}

body h3 {
  color: white;
}

body h4 {
  color: white;
}

.Child-text-01 {
  color: #212b2a;
  font-size: 30px;
  font-family: "cola-font";
  position: absolute;
  top: 2750px;
  font-weight: bold;
}

.Child-text-02 {
  color: #212b2a;
  font-size: 30px;
  position: absolute;
  top: 2780px;
  font-family: "cola-font";
  font-weight: bold;
}

.Child-text-03 {
  color: #212b2a;
  font-size: 30px;
  position: absolute;
  top: 2810px;
  font-family: "cola-font";
  font-weight: bold;
}

.Child-text-04 {
  color: white;
  font-size: 100px;
  font-weight: bolder;
  font-family: "cola-font"
}

.Child-text-05 {
  color: white;
  font-size: 30px;
  font-weight: bold;
}

.box-one-red {
  background-color: #e30b0b;
  width: 1200px;
  margin: 50px;
  border: 10px solid #050000;
  position: fixed;
  bottom: -50px;
}

.box-two-white-trapeziod {
  border-bottom: 2048px solid #fff;
  border-left: 512px solid #1d3c6e;
  border-right: 512px solid #1d3c6e;
}

.box-two-navy-trapezoid {
  border-top: 2048px solid #fff;
  border-left: 512px solid #1d3c6e;
  border-right: 512px solid #1d3c6e;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>

<head>
  <link rel="stylesheet" href="HtmlbrickhouseStyle.css">
  <title> Cloth's Generic Website </title>
  <meta: charset "UTF-8">
</head>

<body>
  <header>
    <div class="box-two-white-trapeziod">
      <h1> Do You Want to see some of the stuff i made? </h1>
    </div>

    <div class="box-two-navy-trapezoid parent">
      <div class="Cliffsidetest">
        <div class="Child-text-01 child"> Number one Cliffsidetest, A TF2 map</div>
        <div class="Child-text-02 child">Number two, Various Blender Models i Made Of Various Things,</div>
        <div class="Child-text-03 child">Number three, A Mobile Game Currently In The Works</div>
      </div>
    </div></code>```

So now the three sentences, (.Child-text-01, .Child-text-02, and .Child-text-03) are supposedly stuck behind the box element.

Body:
I have made a background with the div box, following this triangles tutorial to separate it into two navy blue triangles and one white trapezoid.

I duplicated this div and added child elements with text to go in front of this background. I used position: absolute and the text was in front, but the text was grouped up funny, with the 3 sentences all duplicated and overlapping.

I then tried separating the div-child-text elements into 3 separate classes (.Child-text-01, -02, and -03) and adjusting the top function accordingly. And tada, no longer overlapping but still duplicated.

I tried position: relative for the text, and voila, it wouldn't show up because it is behind the box.

I checked my parses, they were fine as far as I know. I reasoned maybe the box isn't calculating its children because the relative position doesn't do it, I changed the boxes to position: absolute, but it screwed the web page up pretty hard. then I checked the HTML, and fiddled around with the ending  parse, no dice, I am wondering what I am missing, I am a new coder and self-taught.

My code is below:

body {
  background-color: #1d3c6e;
}

@font-face {
  font-family: "cola-font";
  src: url("cola-font-medium.ttf");
}

body h1 {
  color: white;
  font-size: 80px;
  font-family: "cola-font";
  font-width: 10px;
}

body h2 {
  color: white;
  font-family: "cola-font";
  font-width: 10px
}

body h3 {
  color: white;
}

body h4 {
  color: white;
}

.Child-text-01 {
  color: #212b2a;
  font-size: 30px;
  font-family: "cola-font";
  position: absolute;
  top: 2750px;
  font-weight: bold;
}

.Child-text-02 {
  color: #212b2a;
  font-size: 30px;
  position: absolute;
  top: 2780px;
  font-family: "cola-font";
  font-weight: bold;
}

.Child-text-03 {
  color: #212b2a;
  font-size: 30px;
  position: absolute;
  top: 2810px;
  font-family: "cola-font";
  font-weight: bold;
}

.Child-text-04 {
  color: white;
  font-size: 100px;
  font-weight: bolder;
  font-family: "cola-font"
}

.Child-text-05 {
  color: white;
  font-size: 30px;
  font-weight: bold;
}

.box-one-red {
  background-color: #e30b0b;
  width: 1200px;
  margin: 50px;
  border: 10px solid #050000;
  position: fixed;
  bottom: -50px;
}

.box-two-white-trapeziod {
  border-bottom: 2048px solid #fff;
  border-left: 512px solid #1d3c6e;
  border-right: 512px solid #1d3c6e;
}

.box-two-navy-trapezoid {
  border-top: 2048px solid #fff;
  border-left: 512px solid #1d3c6e;
  border-right: 512px solid #1d3c6e;
}

<!DOCTYPE html>

  <link rel="stylesheet" href="HtmlbrickhouseStyle.css">
  <title> Cloth's Generic Website </title>
  <meta: charset "UTF-8">

 Do You Want to see some of the stuff i made?

 Number one Cliffsidetest, A TF2 map

Number two, Various Blender Models i Made Of Various Things,

Number three, A Mobile Game Currently In The Works

So now the three sentences, (.Child-text-01, .Child-text-02, and .Child-text-03) are supposedly stuck behind the box element.


问:
ripple rpc api - username and password?
I'm playing around with Rippled RPC API ;

I'm specifically looking at the Admin Access;

https://xrpl.org/get-started-using-http-websocket-apis.html#admin-access

Admin Access
The API methods are divided into Public Methods and Admin Methods so that organizations can offer public servers for the benefit of the community. To access admin methods, or admin functionality of public methods, you must connect to the API on a port and IP address marked as admin in the server's config file.

The example config file  listens for connections on the local loopback network (127.0.0.1), with JSON-RPC (HTTP) on port 5005 and WebSocket (WS) on port 6006, and treats all connected clients as admin.

By Default in the example config it treats all connected clients as admin; is there a way to set a username and password for admin functions.

A work around I found would be to get the admin port restricted in firewall with an exception rule however is it possible to set a username and password in the config for the admin port instead?

thanks for any insight into this.

Title: ripple rpc api - username and password?


问:
PromQL - Metric to determine PersistentVolumeClaim timespent in Pending State
Beginner in PromQL. I am looking at ways to determine if PersistentVolumeClaims spent more than 15m in Pending State and need some assistance. Here is roughly the set of requirements

Kube_persistentvolume_status_phase has label phase ( 'Pending' and 'Bound') which each have 0 or 1 (with Pending label 1 means the volume is pending and 0 means its moved to bound)

I am looking at setting up the following in grafana and alertmanager

Find the number of PersistentVolumeClaims that are pending in
total

Graph the time spent in pending state in buckets (2,5,15min,etc)

Alert  if the time spent  is greater than 5min

Find avg time pvc spent in bound state for the past hour

Total number of pvc in the queue (meaning pending state)

Any help would be appreciated. I did try using avg_over_time , sum_over_time but was not able to get the exact requirement


问:
Why for loop does not work while map() works in reactjs?
I have an object employees that gets updated from user input through setEmployees() inside a function. I don't understand why for loop does not work but map() works to update the value on the webpage. I am not sure if this is react thing or useState() thing or maybe something else that I missed or did not know. Any idea? Thank you.

The employee object that gets updates from useState hook:

```<code>  const [employees, setEmployees] = useState([
    {
      id: 0,
      name: "Jason",
      role: "Engineer",
      img: 'https://images.pexels.com/photos/2598024/pexels-photo-2598024.jpeg'
    },
    {
      id: 1,
      name: "Abby",
      role: "Manager",
      img: 'https://images.pexels.com/photos/2598024/pexels-photo-2598024.jpeg'
    }
  ]);
</code>```

The case where I use for loop but it does not work:

```<code>  function updateEmployee(id, newName, newRole) {

    // Using for loop to update values
    const updatedEmployees = employees
    for (let i of updatedEmployees) {
      if (i.id == id) {
        i.name = newName
        i.role = newRole
      }
    }
    console.log(updatedEmployees)  // updatedEmployees has been successfully updated
    setEmployees(updatedEmployees) // object `employees` values have been updated but the update does not show on the webpage
  }
</code>```

The case where I use map() and it works:

```<code>  function updateEmployee(id, newName, newRole) {

    // Using map() to update values
    const updatedEmployees = employees.map((employee) => {
      if (id == employee.id) {
        return {...employee, name: newName, role: newRole}
      }
      return employee
    })

    setEmployees(updatedEmployees) // object `employees` values have been updated and also update the values shown on the webpage
  }
</code>```

Body:
I have an object employees that gets updated from user input through setEmployees() inside a function. I don't understand why for loop does not work but map() works to update the value on the webpage. I am not sure if this is react thing or useState() thing or maybe something else that I missed or did not know. Any idea? Thank you.

The employee object that gets updates from useState hook:

  const [employees, setEmployees] = useState([
    {
      id: 0,
      name: "Jason",
      role: "Engineer",
      img: 'https://images.pexels.com/photos/2598024/pexels-photo-2598024.jpeg'
    },
    {
      id: 1,
      name: "Abby",
      role: "Manager",
      img: 'https://images.pexels.com/photos/2598024/pexels-photo-2598024.jpeg'
    }
  ]);

The case where I use for loop but it does not work:

  function updateEmployee(id, newName, newRole) {

    // Using for loop to update values
    const updatedEmployees = employees
    for (let i of updatedEmployees) {
      if (i.id == id) {
        i.name = newName
        i.role = newRole
      }
    }
    console.log(updatedEmployees)  // updatedEmployees has been successfully updated
    setEmployees(updatedEmployees) // object `employees` values have been updated but the update does not show on the webpage
  }

The case where I use map() and it works:

  function updateEmployee(id, newName, newRole) {

    // Using map() to update values
    const updatedEmployees = employees.map((employee) => {
      if (id == employee.id) {
        return {...employee, name: newName, role: newRole}
      }
      return employee
    })

    setEmployees(updatedEmployees) // object `employees` values have been updated and also update the values shown on the webpage
  }


问:
Why share state store across kafka streams is considered as warning by InteractiveQueryService?
I have Kafka 3 topics: 1st with actual temperature, 2nd with with actual air pressure and 3rd with requests. Request may be for actual temperature or for actual pressure.

I need system for processing requests. Because joining could became too complex in future, my plan is create 3 Kafka streams:

one stream mapping temperature to global table "temperature"

second stream mapping pressure to global table "pressure"

third to process requests. If request if for temperature I will call interactiveQueryService.getQueryableStore("temperature",...).get(key)
and respectively same for pressure.

It works, but see warning:

Store ("temperature") could not be found in Streams context, falling back to all known Streams instances

The warning comes from https://github.com/spring-cloud/spring-cloud-stream-binder-kafka/commit/aff0dc00eff4e7740a7e67db3fa5489de684e893

Is my implementation good and warning is misleading or my plan should be modified and the warning is good?


问:
How to fix vector size discrepancy(?): lmeInfo::g_mlm function, between r_const and utils::combn(1:cor_q, 2) : n < m
Using this code block in fresh install of R,

```<code>if (!require('readr')) install.packages('readr')

data <- as.data.frame(readr::read_delim("/Users/{le me}/Desktop/{path}/Histology Data for R.csv", delim = ","))
DataGroupLabel <- "3groupAnova"
subdata <- data[3:80,1:7] # Select a single trial of data to analyze for 3-way ANOVA

colnames(subdata) <- c("Tx","XCoordinate","Channel","VarianceLabel", "VarianceCode", "BrainRegion", "CellCount") # give the data simple labels

subdata$CellCount <- as.numeric(subdata$CellCount) # convert CellCount to numeric

# Calculate intraclass correlation (ICC)
ANOVAresult <- aov(CellCount ~ XCoordinate, data = subdata)
ANOVAtable <-  summary(ANOVAresult)
names(ANOVAtable) <- "Ftable"
Atable <- as.data.frame(ANOVAtable$Ftable)
icc <- Atable[1,3]/(Atable[1,3] + Atable[2,3])
icc

# dummy code the 3 groups (sham = baseline = 0 in $CCI and 0 in $Xpro)
subdata$CCI <- 0
subdata$CCI[subdata$Tx=="CCI"]<- 1
subdata$Xpro <- 0
subdata$Xpro[subdata$Tx=="Xpro"]<- 1

subdata$CCI=as.factor(subdata$CCI)
subdata$Xpro=as.factor(subdata$Xpro)
#subdata$XCoordinate <- type_convert(subdata$XCoordinate)
head(subdata, 100) # Preview & inspect

if (!require('nlme')) install.packages('nlme') # fit multilevel model to run t-test
HCSresult <- nlme::gls(CellCount  ~ CCI + Xpro,
                       # heterogeneous variances
                       weights=varIdent(form = ~1|VarianceCode),
                       correlation = corSymm(value=numeric(0),form = ~1|XCoordinate,fixed=T),
                       data = subdata)

residual <- HCSresult$residuals #setup plots for inspection
par(mfrow=c(1,2))
h <- hist(residual, xlab="Residual")
xfit <- seq(min(residual), max(residual), length = 40)
yfit <- dnorm(xfit, mean = mean(residual), sd = sd(residual))
yfit <- yfit * diff(h$mids[1:2]) * length(residual)
lines(xfit, yfit, col = "black", lwd = 2)
qqnorm(residual, frame = FALSE)
qqline(residual)
par(mfrow=c(1,1))

summary(HCSresult)

# fit null model for comparison
NULresult <- nlme::gls(CellCount  ~ 1,
                       # heterogeneous variances
                       weights=varIdent(form = ~1|VarianceCode),
                       correlation = corSymm(value=numeric(0),form = ~1|XCoordinate,fixed=T),
                       data = subdata)

logLik(NULresult, REML=FALSE)
logLik(HCSresult, REML=FALSE)
chidiff <- -2*as.numeric(logLik(NULresult, REML=FALSE) - logLik(HCSresult, REML=FALSE))
chidiff # print delta chi-square value
qchisq(.95, df=2) # print critical value
round(pchisq(chidiff, df=2, lower.tail=FALSE), 4) # p-value

if (!require('lmeInfo')) install.packages('lmeInfo') # asymmetric conf interval for ES
ctrl <- lmeControl(opt='optim');
result <- lme(fixed = CellCount  ~ CCI + Xpro, control=ctrl,
              random = ~ 1 | XCoordinate,
              correlation = corSymm(value=numeric(0),form = ~1|XCoordinate,fixed=T),
              # heterogeneous variances
              weights=varIdent(form = ~1|VarianceCode),
              data = subdata)

#control=lmeControl(opt="optim") # Switching optimizers for occasional convergence errors

summary(result)

# extract_varcomp(result,separate_variances = TRUE)
ESresult <- lmeInfo::g_mlm(result, p_const = c(0,1,1), r_const = c(1,1,0,0,1,1,1),
                           infotype = "expected", separate_variances = TRUE)

summary(ESresult)

CI_g(ESresult, symmetric = FALSE)
</code>```

I fixed a bunch of errors in this to get it to run all the way to the final ESresult <- lmeInfo ::gmlm function call.  Unfortunately the lmeInfo module's GitHub page ( https://github.com/jepusto/lmeInfo ) doesn't seem to go into detail on how to specify the r_const = c() vector.  My advisor said to use these modules to run this analysis, but is functionally unavailable to teach me how to use them.  Specifically, how to understand the string of integers in r_const().  I think I'll need to adjust r_const for other blocks of data in this set, as many of the blocks are of unique sample sizes.

Got this error: Error in utils::combn(1:cor_q, 2) : n < m

...against the following example block of data:

```<code>CCI,2108,FITC,Ipsi Group 1,A,Cortex,12.2222222
CCI,1218,FITC,Ipsi Group 1,A,Cortex,19.4736842
CCI,2380,FITC,Ipsi Group 1,A,Cortex,15
CCI,4479,FITC,Ipsi Group 1,A,Cortex,9.47368421
CCI,949,FITC,Ipsi Group 1,A,Cortex,25.2631579
CCI,2129,FITC,Ipsi Group 1,A,Cortex,0
CCI,618,FITC,Ipsi Group 1,A,Cortex,15.5555556
CCI,5061,FITC,Ipsi Group 1,A,Cortex,28.3333333
CCI,2768,FITC,Ipsi Group 1,A,Cortex,25
CCI,2733,FITC,Ipsi Group 1,A,Cortex,31
CCI,2063,FITC,Ipsi Group 1,A,Cortex,25.5
CCI,5307,FITC,Ipsi Group 1,A,Cortex,36
CCI,1923,FITC,Ipsi Group 1,A,Cortex,16.3157895
CCI,9414,FITC,Contra Group 1,D,Cortex,1.05263158
CCI,9123,FITC,Contra Group 1,D,Cortex,4
CCI,10723,FITC,Contra Group 1,D,Cortex,5.2631579
CCI,9737,FITC,Contra Group 1,D,Cortex,6.5
CCI,7422,FITC,Contra Group 1,D,Cortex,8.42105263
CCI,9012,FITC,Contra Group 1,D,Cortex,5
CCI,8924,FITC,Contra Group 1,D,Cortex,5
CCI,9550,FITC,Contra Group 1,D,Cortex,9
CCI,8070,FITC,Contra Group 1,D,Cortex,6
CCI,8734,FITC,Contra Group 1,D,Cortex,7.5
CCI,10154,FITC,Contra Group 1,D,Cortex,9.5
CCI,10203,FITC,Contra Group 1,D,Cortex,38.5
CCI,11305,FITC,Contra Group 1,D,Cortex,24.4444444
Sham,803,FITC,Ipsi Group 2,B,Cortex,1.49342891
Sham,1937,FITC,Ipsi Group 2,B,Cortex,1.88101926
Sham,278,FITC,Ipsi Group 2,B,Cortex,1.38966092
Sham,1414,FITC,Ipsi Group 2,B,Cortex,0
Sham,2762,FITC,Ipsi Group 2,B,Cortex,2.86418056
Sham,3218,FITC,Ipsi Group 2,B,Cortex,1.06126694
Sham,157,FITC,Ipsi Group 2,B,Cortex,5.68860572
Sham,1174,FITC,Ipsi Group 2,B,Cortex,3.09463391
Sham,4481,FITC,Ipsi Group 2,B,Cortex,5.33253701
Sham,4011,FITC,Ipsi Group 2,B,Cortex,4.53607312
Sham,2784,FITC,Ipsi Group 2,B,Cortex,1.1154863
Sham,2379,FITC,Ipsi Group 2,B,Cortex,1.05037604
Sham,1417,FITC,Ipsi Group 2,B,Cortex,0
Sham,6739,FITC,Contra Group 2,E,Cortex,9.59452079
Sham,5166,FITC,Contra Group 2,E,Cortex,2.18957325
Sham,7252,FITC,Contra Group 2,E,Cortex,5.16175655
Sham,7115,FITC,Contra Group 2,E,Cortex,9.05843988
Sham,8000,FITC,Contra Group 2,E,Cortex,11.5952485
Sham,5843,FITC,Contra Group 2,E,Cortex,0
Sham,6361,FITC,Contra Group 2,E,Cortex,4.84261501
Sham,8444,FITC,Contra Group 2,E,Cortex,6.10209357
Sham,8247,FITC,Contra Group 2,E,Cortex,5.22677678
Sham,5260,FITC,Contra Group 2,E,Cortex,3.88888889
Sham,7526,FITC,Contra Group 2,E,Cortex,3.97645936
Sham,7495,FITC,Contra Group 2,E,Cortex,5.7390456
Sham,8052,FITC,Contra Group 2,E,Cortex,3.17302506
Xpro,2845,FITC,Ipsi Group 3,C,Cortex,33.6842105
Xpro,1379,FITC,Ipsi Group 3,C,Cortex,9.09090909
Xpro,1592,FITC,Ipsi Group 3,C,Cortex,21.6666667
Xpro,968,FITC,Ipsi Group 3,C,Cortex,6.25
Xpro,2982,FITC,Ipsi Group 3,C,Cortex,17.2222222
Xpro,1212,FITC,Ipsi Group 3,C,Cortex,6.31578947
Xpro,2563,FITC,Ipsi Group 3,C,Cortex,29
Xpro,4615,FITC,Ipsi Group 3,C,Cortex,30
Xpro,630,FITC,Ipsi Group 3,C,Cortex,23
Xpro,5014,FITC,Ipsi Group 3,C,Cortex,27
Xpro,1409,FITC,Ipsi Group 3,C,Cortex,16.5
Xpro,3969,FITC,Ipsi Group 3,C,Cortex,23
Xpro,3527,FITC,Ipsi Group 3,C,Cortex,15
Xpro,7253,FITC,Contra Group 3,F,Cortex,7
Xpro,7891,FITC,Contra Group 3,F,Cortex,9
Xpro,6711,FITC,Contra Group 3,F,Cortex,15.625
Xpro,7830,FITC,Contra Group 3,F,Cortex,11.1111111
Xpro,7218,FITC,Contra Group 3,F,Cortex,10.2857143
Xpro,7849,FITC,Contra Group 3,F,Cortex,4.57085395
Xpro,7303,FITC,Contra Group 3,F,Cortex,12.6019498
Xpro,6928,FITC,Contra Group 3,F,Cortex,33.8199036
Xpro,7991,FITC,Contra Group 3,F,Cortex,5.81483248
Xpro,8452,FITC,Contra Group 3,F,Cortex,1.28539661
Xpro,6717,FITC,Contra Group 3,F,Cortex,36.0048967
Xpro,7328,FITC,Contra Group 3,F,Cortex,23.0207289
Xpro,5772,FITC,Contra Group 3,F,Cortex,7
</code>```

So, I've troubleshot all the way to the end and I'm stuck here on the last lines of code.  Much appreciation to anyone for wisdom.

Body:
Using this code block in fresh install of R,

if (!require('readr')) install.packages('readr')

data <- as.data.frame(readr::read_delim("/Users/{le me}/Desktop/{path}/Histology Data for R.csv", delim = ","))
DataGroupLabel <- "3groupAnova"
subdata <- data[3:80,1:7] # Select a single trial of data to analyze for 3-way ANOVA

colnames(subdata) <- c("Tx","XCoordinate","Channel","VarianceLabel", "VarianceCode", "BrainRegion", "CellCount") # give the data simple labels

subdata$CellCount <- as.numeric(subdata$CellCount) # convert CellCount to numeric

# Calculate intraclass correlation (ICC)
ANOVAresult <- aov(CellCount ~ XCoordinate, data = subdata)
ANOVAtable <-  summary(ANOVAresult)
names(ANOVAtable) <- "Ftable"
Atable <- as.data.frame(ANOVAtable$Ftable)
icc <- Atable[1,3]/(Atable[1,3] + Atable[2,3])
icc

# dummy code the 3 groups (sham = baseline = 0 in $CCI and 0 in $Xpro)
subdata$CCI <- 0
subdata$CCI[subdata$Tx=="CCI"]<- 1
subdata$Xpro <- 0
subdata$Xpro[subdata$Tx=="Xpro"]<- 1

subdata$CCI=as.factor(subdata$CCI)
subdata$Xpro=as.factor(subdata$Xpro)
#subdata$XCoordinate <- type_convert(subdata$XCoordinate)
head(subdata, 100) # Preview & inspect

if (!require('nlme')) install.packages('nlme') # fit multilevel model to run t-test
HCSresult <- nlme::gls(CellCount  ~ CCI + Xpro,
                       # heterogeneous variances
                       weights=varIdent(form = ~1|VarianceCode),
                       correlation = corSymm(value=numeric(0),form = ~1|XCoordinate,fixed=T),
                       data = subdata)

residual <- HCSresult$residuals #setup plots for inspection
par(mfrow=c(1,2))
h <- hist(residual, xlab="Residual")
xfit <- seq(min(residual), max(residual), length = 40)
yfit <- dnorm(xfit, mean = mean(residual), sd = sd(residual))
yfit <- yfit * diff(h$mids[1:2]) * length(residual)
lines(xfit, yfit, col = "black", lwd = 2)
qqnorm(residual, frame = FALSE)
qqline(residual)
par(mfrow=c(1,1))

summary(HCSresult)

# fit null model for comparison
NULresult <- nlme::gls(CellCount  ~ 1,
                       # heterogeneous variances
                       weights=varIdent(form = ~1|VarianceCode),
                       correlation = corSymm(value=numeric(0),form = ~1|XCoordinate,fixed=T),
                       data = subdata)

logLik(NULresult, REML=FALSE)
logLik(HCSresult, REML=FALSE)
chidiff <- -2*as.numeric(logLik(NULresult, REML=FALSE) - logLik(HCSresult, REML=FALSE))
chidiff # print delta chi-square value
qchisq(.95, df=2) # print critical value
round(pchisq(chidiff, df=2, lower.tail=FALSE), 4) # p-value

if (!require('lmeInfo')) install.packages('lmeInfo') # asymmetric conf interval for ES
ctrl <- lmeControl(opt='optim');
result <- lme(fixed = CellCount  ~ CCI + Xpro, control=ctrl,
              random = ~ 1 | XCoordinate,
              correlation = corSymm(value=numeric(0),form = ~1|XCoordinate,fixed=T),
              # heterogeneous variances
              weights=varIdent(form = ~1|VarianceCode),
              data = subdata)

#control=lmeControl(opt="optim") # Switching optimizers for occasional convergence errors

summary(result)

# extract_varcomp(result,separate_variances = TRUE)
ESresult <- lmeInfo::g_mlm(result, p_const = c(0,1,1), r_const = c(1,1,0,0,1,1,1),
                           infotype = "expected", separate_variances = TRUE)

summary(ESresult)

CI_g(ESresult, symmetric = FALSE)

I fixed a bunch of errors in this to get it to run all the way to the final ESresult <- lmeInfo ::gmlm function call.  Unfortunately the lmeInfo module's GitHub page ( https://github.com/jepusto/lmeInfo ) doesn't seem to go into detail on how to specify the r_const = c() vector.  My advisor said to use these modules to run this analysis, but is functionally unavailable to teach me how to use them.  Specifically, how to understand the string of integers in r_const().  I think I'll need to adjust r_const for other blocks of data in this set, as many of the blocks are of unique sample sizes.

Got this error: Error in utils::combn(1:cor_q, 2) : n < m

...against the following example block of data:

CCI,2108,FITC,Ipsi Group 1,A,Cortex,12.2222222
CCI,1218,FITC,Ipsi Group 1,A,Cortex,19.4736842
CCI,2380,FITC,Ipsi Group 1,A,Cortex,15
CCI,4479,FITC,Ipsi Group 1,A,Cortex,9.47368421
CCI,949,FITC,Ipsi Group 1,A,Cortex,25.2631579
CCI,2129,FITC,Ipsi Group 1,A,Cortex,0
CCI,618,FITC,Ipsi Group 1,A,Cortex,15.5555556
CCI,5061,FITC,Ipsi Group 1,A,Cortex,28.3333333
CCI,2768,FITC,Ipsi Group 1,A,Cortex,25
CCI,2733,FITC,Ipsi Group 1,A,Cortex,31
CCI,2063,FITC,Ipsi Group 1,A,Cortex,25.5
CCI,5307,FITC,Ipsi Group 1,A,Cortex,36
CCI,1923,FITC,Ipsi Group 1,A,Cortex,16.3157895
CCI,9414,FITC,Contra Group 1,D,Cortex,1.05263158
CCI,9123,FITC,Contra Group 1,D,Cortex,4
CCI,10723,FITC,Contra Group 1,D,Cortex,5.2631579
CCI,9737,FITC,Contra Group 1,D,Cortex,6.5
CCI,7422,FITC,Contra Group 1,D,Cortex,8.42105263
CCI,9012,FITC,Contra Group 1,D,Cortex,5
CCI,8924,FITC,Contra Group 1,D,Cortex,5
CCI,9550,FITC,Contra Group 1,D,Cortex,9
CCI,8070,FITC,Contra Group 1,D,Cortex,6
CCI,8734,FITC,Contra Group 1,D,Cortex,7.5
CCI,10154,FITC,Contra Group 1,D,Cortex,9.5
CCI,10203,FITC,Contra Group 1,D,Cortex,38.5
CCI,11305,FITC,Contra Group 1,D,Cortex,24.4444444
Sham,803,FITC,Ipsi Group 2,B,Cortex,1.49342891
Sham,1937,FITC,Ipsi Group 2,B,Cortex,1.88101926
Sham,278,FITC,Ipsi Group 2,B,Cortex,1.38966092
Sham,1414,FITC,Ipsi Group 2,B,Cortex,0
Sham,2762,FITC,Ipsi Group 2,B,Cortex,2.86418056
Sham,3218,FITC,Ipsi Group 2,B,Cortex,1.06126694
Sham,157,FITC,Ipsi Group 2,B,Cortex,5.68860572
Sham,1174,FITC,Ipsi Group 2,B,Cortex,3.09463391
Sham,4481,FITC,Ipsi Group 2,B,Cortex,5.33253701
Sham,4011,FITC,Ipsi Group 2,B,Cortex,4.53607312
Sham,2784,FITC,Ipsi Group 2,B,Cortex,1.1154863
Sham,2379,FITC,Ipsi Group 2,B,Cortex,1.05037604
Sham,1417,FITC,Ipsi Group 2,B,Cortex,0
Sham,6739,FITC,Contra Group 2,E,Cortex,9.59452079
Sham,5166,FITC,Contra Group 2,E,Cortex,2.18957325
Sham,7252,FITC,Contra Group 2,E,Cortex,5.16175655
Sham,7115,FITC,Contra Group 2,E,Cortex,9.05843988
Sham,8000,FITC,Contra Group 2,E,Cortex,11.5952485
Sham,5843,FITC,Contra Group 2,E,Cortex,0
Sham,6361,FITC,Contra Group 2,E,Cortex,4.84261501
Sham,8444,FITC,Contra Group 2,E,Cortex,6.10209357
Sham,8247,FITC,Contra Group 2,E,Cortex,5.22677678
Sham,5260,FITC,Contra Group 2,E,Cortex,3.88888889
Sham,7526,FITC,Contra Group 2,E,Cortex,3.97645936
Sham,7495,FITC,Contra Group 2,E,Cortex,5.7390456
Sham,8052,FITC,Contra Group 2,E,Cortex,3.17302506
Xpro,2845,FITC,Ipsi Group 3,C,Cortex,33.6842105
Xpro,1379,FITC,Ipsi Group 3,C,Cortex,9.09090909
Xpro,1592,FITC,Ipsi Group 3,C,Cortex,21.6666667
Xpro,968,FITC,Ipsi Group 3,C,Cortex,6.25
Xpro,2982,FITC,Ipsi Group 3,C,Cortex,17.2222222
Xpro,1212,FITC,Ipsi Group 3,C,Cortex,6.31578947
Xpro,2563,FITC,Ipsi Group 3,C,Cortex,29
Xpro,4615,FITC,Ipsi Group 3,C,Cortex,30
Xpro,630,FITC,Ipsi Group 3,C,Cortex,23
Xpro,5014,FITC,Ipsi Group 3,C,Cortex,27
Xpro,1409,FITC,Ipsi Group 3,C,Cortex,16.5
Xpro,3969,FITC,Ipsi Group 3,C,Cortex,23
Xpro,3527,FITC,Ipsi Group 3,C,Cortex,15
Xpro,7253,FITC,Contra Group 3,F,Cortex,7
Xpro,7891,FITC,Contra Group 3,F,Cortex,9
Xpro,6711,FITC,Contra Group 3,F,Cortex,15.625
Xpro,7830,FITC,Contra Group 3,F,Cortex,11.1111111
Xpro,7218,FITC,Contra Group 3,F,Cortex,10.2857143
Xpro,7849,FITC,Contra Group 3,F,Cortex,4.57085395
Xpro,7303,FITC,Contra Group 3,F,Cortex,12.6019498
Xpro,6928,FITC,Contra Group 3,F,Cortex,33.8199036
Xpro,7991,FITC,Contra Group 3,F,Cortex,5.81483248
Xpro,8452,FITC,Contra Group 3,F,Cortex,1.28539661
Xpro,6717,FITC,Contra Group 3,F,Cortex,36.0048967
Xpro,7328,FITC,Contra Group 3,F,Cortex,23.0207289
Xpro,5772,FITC,Contra Group 3,F,Cortex,7

So, I've troubleshot all the way to the end and I'm stuck here on the last lines of code.  Much appreciation to anyone for wisdom.


问:
Add more attribute to available API request with Strava (running app)
I am using add-in API connector in Chrome to request a connection with my Strava account (a running app).
My point is to automatically update any new activity of my club members, then show up on a google_sheet link for recording and statistics.

Unfortunately available field of API request return does not have the starting time of the activity as attached image.
How can I have it as well? Many thanks.

Edit field pop-up window


问:
Substance Painter Python - Toggle ToneMapper
I'm trying to create a plugin for Painter that will simplify some of the things my team and I have to do manually. One of those things is to toggle elements in the Display Settings, like the ToneMapper Function.
Looking at the Python API documentation, it should be possible by checking the current state with and if and then setting the tone mapper to the other function.

Here's my approach so far:

```<code>def toggleToneMap():
    toneMapper = substance_painter.display.get_tone_mapping()
    new_tone_mapping = substance_painter.display.ToneMappingFunction.ACES
        if toneMapper == "ToneMappingFunction.ACES":
        new_tone_mapping = substance_painter.display.ToneMappingFunction.Linear
        print(new_tone_mapping)

    else:
        new_tone_mapping = substance_painter.display.ToneMappingFunction.ACES

    substance_painter.display.set_tone_mapping(new_tone_mapping)
</code>```

substance_painter.display.get_tone_mapping returns ' [Python] ToneMappingFunction.Linear ' in the log. So unless I'm missing something, my approach should work.  But alas, it goes straight to the else and doesn't seem to produce the nice toggle that need.

I tried replacing the "ToneMappingFunction.ACES" by ' [Python] ToneMappingFunction.Linear ', didn't help.
Also tried with just the value, like "ACES", didn't work either.
Even tried " if "ACES" in toneMapper: " as a method and I'm getting a Type error in the log

```<code>[Python] if "ACES" in toneMapper:
[Python] TypeError
[Python] :
[Python] argument of type '_substance_painter.display.ToneMappingFunction' is not iterable
</code>```

Can anyone tell me what I'm doing wrong or point me in a direction where I should be looking?

Body:
I'm trying to create a plugin for Painter that will simplify some of the things my team and I have to do manually. One of those things is to toggle elements in the Display Settings, like the ToneMapper Function.
Looking at the Python API documentation, it should be possible by checking the current state with and if and then setting the tone mapper to the other function.

Here's my approach so far:

def toggleToneMap():
    toneMapper = substance_painter.display.get_tone_mapping()
    new_tone_mapping = substance_painter.display.ToneMappingFunction.ACES
        if toneMapper == "ToneMappingFunction.ACES":
        new_tone_mapping = substance_painter.display.ToneMappingFunction.Linear
        print(new_tone_mapping)

    else:
        new_tone_mapping = substance_painter.display.ToneMappingFunction.ACES

    substance_painter.display.set_tone_mapping(new_tone_mapping)

substance_painter.display.get_tone_mapping returns ' [Python] ToneMappingFunction.Linear ' in the log. So unless I'm missing something, my approach should work.  But alas, it goes straight to the else and doesn't seem to produce the nice toggle that need.

I tried replacing the "ToneMappingFunction.ACES" by ' [Python] ToneMappingFunction.Linear ', didn't help.
Also tried with just the value, like "ACES", didn't work either.
Even tried " if "ACES" in toneMapper: " as a method and I'm getting a Type error in the log

[Python] if "ACES" in toneMapper:
[Python] TypeError
[Python] :
[Python] argument of type '_substance_painter.display.ToneMappingFunction' is not iterable

Can anyone tell me what I'm doing wrong or point me in a direction where I should be looking?