问:
Why aren't text and images being displayed in NavigationView?
I have a NavigationView that is supposed to display an image and some text in a ScrollView however the screen is just blank.

Here is the code:

```<code>
NavigationView {

            ZStack {
                Color("HomeBG3")
                    .ignoresSafeArea()

                ScrollView(.vertical, showsIndicators: false) {

                    ForEach(MarketplaceModel.business_details_array) { items in

                        VStack {

                            GeometryReader { geo in
                                Image("ProductDefaultImage")
                                    .resizable()
                                    .scaledToFit()
                                    .frame(width: geo.size.width * 1, height: 300)
                            }
                            Text("Test")
                        }
                    }

                }

            }
        }

        .navigationTitle(businessData.title)
        .navigationBarTitleDisplayMode(.inline)
        .onAppear(perform: {

            let defaults = UserDefaults.standard
            let stringOne = defaults.string(forKey: "key")!

            self.MarketplaceModel.fetchBusinessDetails(id: business_id, key: stringOne)

        })

</code>```

Any ideas on why the image and text are not appearing?

EDIT:
What's causing the image and text to overlap? When I remove the ZStack, they still overlap.

Body:
I have a NavigationView that is supposed to display an image and some text in a ScrollView however the screen is just blank.

Here is the code:

NavigationView {

            ZStack {
                Color("HomeBG3")
                    .ignoresSafeArea()

                ScrollView(.vertical, showsIndicators: false) {

                    ForEach(MarketplaceModel.business_details_array) { items in

                        VStack {

                            GeometryReader { geo in
                                Image("ProductDefaultImage")
                                    .resizable()
                                    .scaledToFit()
                                    .frame(width: geo.size.width * 1, height: 300)
                            }
                            Text("Test")
                        }
                    }

                }

            }
        }

        .navigationTitle(businessData.title)
        .navigationBarTitleDisplayMode(.inline)
        .onAppear(perform: {

            let defaults = UserDefaults.standard
            let stringOne = defaults.string(forKey: "key")!

            self.MarketplaceModel.fetchBusinessDetails(id: business_id, key: stringOne)

        })

Any ideas on why the image and text are not appearing?

EDIT:
What's causing the image and text to overlap? When I remove the ZStack, they still overlap.


来源: stackexchange

问:
peewee assign str to CharField raises incompatible type error
There are many places where one wants to assign a str to CharField. But that raises below type error.

```<code>Cannot assign member "uri" for type "MyTable"
  Expression of type "str" cannot be assigned to member "uri" of class "MyTable"
    "str" is incompatible with "CharField" Pylance(reportGeneralTypeIssues)
</code>```

Well, we can suppress it by adding # type: ignore hint, but what is the proper way ( or type safe way for the type checker) to assign a string to CharField?

I was hoping for something like CharField.valueOf("str") available in the framework, but then its an overkill and adds to the execution time!

The case is same with other types too, for example assigning True/False to a BooleanField .

ContentLicense: CC BY-SA 4.0

Body:
There are many places where one wants to assign a str to CharField. But that raises below type error.

Cannot assign member "uri" for type "MyTable"
  Expression of type "str" cannot be assigned to member "uri" of class "MyTable"
    "str" is incompatible with "CharField" Pylance(reportGeneralTypeIssues)

Well, we can suppress it by adding # type: ignore hint, but what is the proper way ( or type safe way for the type checker) to assign a string to CharField?

I was hoping for something like CharField.valueOf("str") available in the framework, but then its an overkill and adds to the execution time!

The case is same with other types too, for example assigning True/False to a BooleanField .


问:
Using read_csv on Jupyter Notebook
I have problem importing an Excel file into Jupyter Notebook.

I used this code to import it:

import pandas as pd

df = pd.read_csv(r'C:\Users\Student\Documents\transaction.csv')
df
```

Yes, the code run and the file is imported, but it's not a perfect table. Data is shifted on the left side, and rows don't match along with columns.

Title: Using read_csv on Jupyter Notebook

Body:
I have problem importing an Excel file into Jupyter Notebook.

I used this code to import it:

import pandas as pd

df = pd.read_csv(r'C:\Users\Student\Documents\transaction.csv')
df

Yes, the code run and the file is imported, but it's not a perfect table. Data is shifted on the left side, and rows don't match along with columns.


问:
Isotope images don't load as they should
I'm aware this problem has come by more often, but I have tried everything and i'm still unable to fix it. I have an isotope grid with filter, everything works except for the first time loading the page. The images at the underside of the page overlap each other, but the first images are correctly displayed.
I have tried I think every sort of solution I could find but somehow nothing works. It has something to do with imagesloaded but no clue where the mistake is.

```<code>  <div id="content">

    <div class="box">
      <a href="link.html">
        <div class="container">
          <img src="work/previews/image1.jpg" class="image width2">
          <div class="overlay">
            <div class="text">TITLE</div>
          </div>
        </div>
      </a>
    </div>

    <div class="box">
      <a href="LINK2.html">
        <div class="container">
          <img src="work/previews/IMAGE2.jpg" class="image width5">
          <div class="overlay">
            <div class="text">TITLE2</div>
          </div>
        </div>
      </a>
    </div>
</code>```

and my  javascript is this:

```

I took the filter javascript out, that works fine. It doesn't change if I do .box instead of #content. .container also doesn't do anything.
Could someone help me out?
:)

Body:
I'm aware this problem has come by more often, but I have tried everything and i'm still unable to fix it. I have an isotope grid with filter, everything works except for the first time loading the page. The images at the underside of the page overlap each other, but the first images are correctly displayed.
I have tried I think every sort of solution I could find but somehow nothing works. It has something to do with imagesloaded but no clue where the mistake is.

TITLE

TITLE2

and my  javascript is this:

I took the filter javascript out, that works fine. It doesn't change if I do .box instead of #content. .container also doesn't do anything.
Could someone help me out?
:)


问:
Calculating MSD
trying to calculate mean squared displacement (MSD) with 3D coordinate data.

I have this code running and outputting a value for n time lags but have no way to confirm if the numbers are actually MSD values. x_values, y_values, and z_values are all np.array, thanks!

```<code>for t_diff in range(1, tau_val + 1):
            r = np.sqrt(x_values ** 2 + y_values ** 2 + z_values ** 2)
            diff = np.diff(r, n=t_diff)
            diff_sq = diff ** 2
            vals.append(np.mean(diff_sq))
            y_val_msd_slope.append(t_diff)
</code>```

Title: Calculating MSD

Body:
trying to calculate mean squared displacement (MSD) with 3D coordinate data.

I have this code running and outputting a value for n time lags but have no way to confirm if the numbers are actually MSD values. x_values, y_values, and z_values are all np.array, thanks!

for t_diff in range(1, tau_val + 1):
            r = np.sqrt(x_values ** 2 + y_values ** 2 + z_values ** 2)
            diff = np.diff(r, n=t_diff)
            diff_sq = diff ** 2
            vals.append(np.mean(diff_sq))
            y_val_msd_slope.append(t_diff)


问:
Visual-Studio/XCode Interface Builder, C Sharp App not relaunching its window
I hope someone can help me.

I am currently learning C# and have written my first app for macbooks (we use them at work).

I wrote the app in visual studio and XCode interface builder.

Almost everything works except for one thing.
When I close the app, with the red cross (top left), the app window closes, but the app continues to run in the dock.

Unfortunately, when I click on the app in the dock, nothing happens. I  have to close the app in the dock and then restart it so that it runs normal again.

Is this because I built the app in debug?
Or is there any way to fix this?

I can't build the app as a release at the moment unfortunately because then a signing error comes up while starting the app (code signature invalid).

Thank you very much.

Edit1: I've realized that programs for macbooks dont really close.
Closing the program with red cross (top left), closes the program window but the program still runs, every other program on my mac is doing that.
But if you click at them in the dock the program windows reappears, the window of my program is not reappearing. Only after really closing the program and reopening it the program window of my app launches again.
So there is still a problem.

Edit2: The signing fails because i need an apple developer account.

Edit3: I've build a release build and signed it successfully.
Sadly even in the release build this problems exits.

Edit4: I use an Apple M1 Pro and Visual Studio for Mac 17.4.1 and XCode 14.1.

I've solved the issue by adding:

```<code>public override bool ApplicationShouldTerminateAfterLastWindowClosed(NSApplication sender)    {
      return true;
}
</code>```

into AppDelegate.cs. Now my app is closing after i press the red cross, i prefer this a lot more than letting the app run in the dock.

You can also use:

```<code>public override bool ApplicationShouldHandleReopen(NSApplication sender, bool hasVisibleWindows)
    {
        if (!hasVisibleWindows)
        {
            var sb = NSStoryboard.FromName("Main", null);//Main.storyboard
            var controller = sb.InstantiateControllerWithIdentifier("MainWindow") as NSWindowController;// "MainWindow" is the Storyboard ID in WindowController of Main.storyboard.
            controller.Window.MakeKeyAndOrderFront(this);//You can change this window(controller.Window) if you have another window in your project
        }
        return true;
    }
</code>```

to let the app run in the dock and the window reappear after closing it.

Body:
I hope someone can help me.

I am currently learning C# and have written my first app for macbooks (we use them at work).

I wrote the app in visual studio and XCode interface builder.

Almost everything works except for one thing.
When I close the app, with the red cross (top left), the app window closes, but the app continues to run in the dock.

Unfortunately, when I click on the app in the dock, nothing happens. I  have to close the app in the dock and then restart it so that it runs normal again.

Is this because I built the app in debug?
Or is there any way to fix this?

I can't build the app as a release at the moment unfortunately because then a signing error comes up while starting the app (code signature invalid).

Thank you very much.

Edit1: I've realized that programs for macbooks dont really close.
Closing the program with red cross (top left), closes the program window but the program still runs, every other program on my mac is doing that.
But if you click at them in the dock the program windows reappears, the window of my program is not reappearing. Only after really closing the program and reopening it the program window of my app launches again.
So there is still a problem.

Edit2: The signing fails because i need an apple developer account.

Edit3: I've build a release build and signed it successfully.
Sadly even in the release build this problems exits.

Edit4: I use an Apple M1 Pro and Visual Studio for Mac 17.4.1 and XCode 14.1.

I've solved the issue by adding:

public override bool ApplicationShouldTerminateAfterLastWindowClosed(NSApplication sender)    {
      return true;
}

into AppDelegate.cs. Now my app is closing after i press the red cross, i prefer this a lot more than letting the app run in the dock.

You can also use:

public override bool ApplicationShouldHandleReopen(NSApplication sender, bool hasVisibleWindows)
    {
        if (!hasVisibleWindows)
        {
            var sb = NSStoryboard.FromName("Main", null);//Main.storyboard
            var controller = sb.InstantiateControllerWithIdentifier("MainWindow") as NSWindowController;// "MainWindow" is the Storyboard ID in WindowController of Main.storyboard.
            controller.Window.MakeKeyAndOrderFront(this);//You can change this window(controller.Window) if you have another window in your project
        }
        return true;
    }

to let the app run in the dock and the window reappear after closing it.


问:
Spring ConditionalOnWebApplication auto configuration setting
I am creating a spring application which is not a spring web application, but when loading Spring ApplicationContextConfiguration , noticing that the @ConditionalOnWebApplication is being loaded those configs too and eventually calling my spring config loading to fail due to that.

In what cases, does spring know that the app is a web application and when to call ConditionalOnWebApplication

I was looking at my spring dependencies and my project settings


问:
Remove object inheritance SQLAlchemy (polymorphic identity)

Problem

Currently we have a system that has several models that inherit from one model (Quote) through a polymorphic identity, even though they do not necessarily have a lot in common. This can cause issues and confusion when trying to write code (especially when it comes to objects having similarly named attributes that should not be used).

Our postgresql database setup also reflects this where we have tables inheriting from the quotes table meaning they only define columns that are new for that model. This can make debugging unnecessarily hard and confusing. Especially since only a couple of the columns from the parent are necessary to be inherited.

This has led us to the decision to decouple some of these models from the Quote model to improve the flexibility and readability of our code.

Hypothesis

As far as I can think of solutions there is only one. For one of the inheriting models (let's say Bid) create a new model that does not inherit from Quote. This new Bid model (let's say NewBid for now) will have all of the required attributes including any ones that were originally inherited from the Quote model.

We will then have to replace all usages of Bid with NewBid and create a migration that copies all data from the bids table to the new_bids table.

Steps to take would be:

Add new model, create migration for new model -> deploy

Create data migration copying all information from bids to new_bids. In this same PR replace all usage of Bid with NewBid to prevent new data from being entered into the bids table. -> deploy

Make sure everything works and then remove the bids table and Bid model (not cascading deletes to references they might have in the DB).

Rename the NewBid and new_bids table to Bid and bids respectively.

Obviously I would like to avoid running these steps since they feel dangerous and highly susceptible to errors. In case anything goes wrong doing a revert might be hard to accomplish and it may be easy to make a mistake in such a big PR. However, I can't think of another way of accomplishing this.

What have I tried

So far not much has been tried except for a few trivial tries to see if we can easily fix this (i.e. just removing polymorphic_identity from the Quote and Bid models).

Trying to research on how to get rid of this has not proven useful, since most results talk about deletion with polymorphic identities or relations between them. Not how to actually get rid of polymorphic identities all together and just end up with separate tables (without data loss). If I missed that question/answer my apologies.

I could find no answer to this in the docs of SQLAlchemy. Nor could I find anything about this in PostgreSQL docs, which I would not expect since the real problem lies in SQLAlchemy here I think.

Question

How to get rid of inheritance in SQLAlchemy for polymorphic identities, along with inherited tables in postgreSQL, without a loss of data?

Minimal code example

```<code>class Quote(Base):
    class Type(ValuesMixin):
        QUOTE = "quote"
        BID = "bid"

    __tablename__ = "quotes"
    __mapper_args__ = {
        "polymorphic_on": "type",
        "polymorphic_identity": Type.QUOTE,
    }

    type = Column(String, nullable=False, default=Type.QUOTE)
    ...

class Bid(Quote):
    __tablename__ = "bids"
    __mapper_args__ = {
        "polymorphic_identity": Quote.Type.BID,
    }
    ...
</code>```

Body:
Problem

Currently we have a system that has several models that inherit from one model (Quote) through a polymorphic identity, even though they do not necessarily have a lot in common. This can cause issues and confusion when trying to write code (especially when it comes to objects having similarly named attributes that should not be used).

Our postgresql database setup also reflects this where we have tables inheriting from the quotes table meaning they only define columns that are new for that model. This can make debugging unnecessarily hard and confusing. Especially since only a couple of the columns from the parent are necessary to be inherited.

This has led us to the decision to decouple some of these models from the Quote model to improve the flexibility and readability of our code.

Hypothesis

As far as I can think of solutions there is only one. For one of the inheriting models (let's say Bid) create a new model that does not inherit from Quote. This new Bid model (let's say NewBid for now) will have all of the required attributes including any ones that were originally inherited from the Quote model.

We will then have to replace all usages of Bid with NewBid and create a migration that copies all data from the bids table to the new_bids table.

Steps to take would be:

Add new model, create migration for new model -> deploy

Create data migration copying all information from bids to new_bids. In this same PR replace all usage of Bid with NewBid to prevent new data from being entered into the bids table. -> deploy

Make sure everything works and then remove the bids table and Bid model (not cascading deletes to references they might have in the DB).

Rename the NewBid and new_bids table to Bid and bids respectively.

Obviously I would like to avoid running these steps since they feel dangerous and highly susceptible to errors. In case anything goes wrong doing a revert might be hard to accomplish and it may be easy to make a mistake in such a big PR. However, I can't think of another way of accomplishing this.

What have I tried

So far not much has been tried except for a few trivial tries to see if we can easily fix this (i.e. just removing polymorphic_identity from the Quote and Bid models).

Trying to research on how to get rid of this has not proven useful, since most results talk about deletion with polymorphic identities or relations between them. Not how to actually get rid of polymorphic identities all together and just end up with separate tables (without data loss). If I missed that question/answer my apologies.

I could find no answer to this in the docs of SQLAlchemy. Nor could I find anything about this in PostgreSQL docs, which I would not expect since the real problem lies in SQLAlchemy here I think.

Question

How to get rid of inheritance in SQLAlchemy for polymorphic identities, along with inherited tables in postgreSQL, without a loss of data?

Minimal code example

class Quote(Base):
    class Type(ValuesMixin):
        QUOTE = "quote"
        BID = "bid"

    __tablename__ = "quotes"
    __mapper_args__ = {
        "polymorphic_on": "type",
        "polymorphic_identity": Type.QUOTE,
    }

    type = Column(String, nullable=False, default=Type.QUOTE)
    ...

class Bid(Quote):
    __tablename__ = "bids"
    __mapper_args__ = {
        "polymorphic_identity": Quote.Type.BID,
    }
    ...


问:
How can I get untouched status change when click enter in a inputbox
Here is simple input box in a reactive form:
Html:

```<code><form [formGroup]="form" (ngSubmit)="onSubmit()">
  <input type="text" formControlName="box" (keyup.enter)="dosomething()">
  <button>Submit</button>
</form>
</code>```

TS:

```<code>  dosomething() {
    this.cd.detectChanges(); // private *cd*: ChangeDetectorRef
    console.log(this.form.untouched);
  }
  onSubmit() {
    console.log('from submit: ', this.form.untouched);
  }
</code>```

input something in the input box

-> click enter, I got: true;

-> click the submit button, I got: false

In this case, cz the input box has already been touched, so, we should expect the false.

How can I get the false when clicking enter in the input box?

enter link description here

Body:
Here is simple input box in a reactive form:
Html:

<form [formGroup]="form" (ngSubmit)="onSubmit()">
  <input type="text" formControlName="box" (keyup.enter)="dosomething()">
  <button>Submit</button>
</form>

TS:

  dosomething() {
    this.cd.detectChanges(); // private *cd*: ChangeDetectorRef
    console.log(this.form.untouched);
  }
  onSubmit() {
    console.log('from submit: ', this.form.untouched);
  }

input something in the input box

-> click enter, I got: true;

-> click the submit button, I got: false

In this case, cz the input box has already been touched, so, we should expect the false.

How can I get the false when clicking enter in the input box?

enter link description here


问:
Export to excel in django not working quite as i hoped it would
I am a django beginner, Trying to export an excel writer to excel in a django front end app using the results of  function1 in function2 which contains the code to export/download the file but i can't seem to get it to work. It works when i include the export to excel code in function1 in my views.py (its a project with quite some sensitive data hence why i wont be sharing the actual code here). Each function has a button that run it to provide the required output but This doesnt work, i appreciate any help on this

```<code>def function1(request):
   #post method request with filters from the frontend

   #use filters to read in the data
    df = read_sql("query with filters")

   #created a writer
    output = BytesIO()
    writer = pd.ExcelWriter(output, engine='xlsxwriter')

   #called functions that send output to writer sheets, see example below
    check_for_duplicates(df,writer)
   #create context to render some sample output on the frontend

  return render(request, 'home.html', context)

def function2(request):

    function1(request) # gets me the results i want to export to excel

    writer.save()
    output.seek(0)

    response = StreamingHttpResponse(output, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    response['Content-Disposition'] = f'attachment; filename=customers_{lebook}.xlsx'

  return response

</code>```

I tried to put the code that appears in function2 in function1 and it worked but in the button (validate) that calls function1 yet i want it to run under the function2 button. I want to be able to export the results in function1 using the button (export to excel) that calls function2

my interface with the mentioned buttons

Body:
I am a django beginner, Trying to export an excel writer to excel in a django front end app using the results of  function1 in function2 which contains the code to export/download the file but i can't seem to get it to work. It works when i include the export to excel code in function1 in my views.py (its a project with quite some sensitive data hence why i wont be sharing the actual code here). Each function has a button that run it to provide the required output but This doesnt work, i appreciate any help on this

def function1(request):
   #post method request with filters from the frontend

   #use filters to read in the data
    df = read_sql("query with filters")

   #created a writer
    output = BytesIO()
    writer = pd.ExcelWriter(output, engine='xlsxwriter')

   #called functions that send output to writer sheets, see example below
    check_for_duplicates(df,writer)
   #create context to render some sample output on the frontend

  return render(request, 'home.html', context)

def function2(request):

    function1(request) # gets me the results i want to export to excel

    writer.save()
    output.seek(0)

    response = StreamingHttpResponse(output, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    response['Content-Disposition'] = f'attachment; filename=customers_{lebook}.xlsx'

  return response

I tried to put the code that appears in function2 in function1 and it worked but in the button (validate) that calls function1 yet i want it to run under the function2 button. I want to be able to export the results in function1 using the button (export to excel) that calls function2

my interface with the mentioned buttons


问:
I cannot get parallel computing working in Python (joblib)
import time
from joblib import Parallel, delayed

```<code>def fun(i):
    return i**2

start = time.time()
for i in list(range(0,10000000,1)):
    print(fun(i))
end = time.time()
print(end - start)

start = time.time()

Parallel(n_jobs=48,prefer="threads")(delayed(fun)(i) for i in list(range(0,10000000,1)))
end = time.time()
print(end - start)
</code>```

I am trying to use joblib to perform some computations in parallel. The 1st part of the code which is a traditional non-parallel for loop takes 37 seconds. The parallelized version runs for 6+ minutes without any ouput. What am I doing wrong?

Body:
import time
from joblib import Parallel, delayed

def fun(i):
    return i**2

start = time.time()
for i in list(range(0,10000000,1)):
    print(fun(i))
end = time.time()
print(end - start)

start = time.time()

Parallel(n_jobs=48,prefer="threads")(delayed(fun)(i) for i in list(range(0,10000000,1)))
end = time.time()
print(end - start)

I am trying to use joblib to perform some computations in parallel. The 1st part of the code which is a traditional non-parallel for loop takes 37 seconds. The parallelized version runs for 6+ minutes without any ouput. What am I doing wrong?


问:
AWS CDK cognito with profile picture in S3 bucket
I want to create autohrization with aws-cognito.
I am using CDKv2, and try to achieve the following workflow:

User registers with cogninto, the request contains a profile picture. This profile-picture should be uploaded to a s3 bucket, if the registration was successfully.

I have read and tried a lot (e.g. using a lambda to achieve that), but somehow it did not worked as I would expect it.

What I want:
1.) Register using cognito (in later point using the js-sdk in a frontend as counterpart)

2.) While registering I want to add a profile picture, which gets stored in an S3 bucket. The best would be, that the profilePicture field would then be the link to the item in the s3-bucket (or something else, if there is a better way)

I tried to solve this by a preSignup lambda which is a trigger on the user pool:

def handler(event, context):
    profile_picture = event['request']['userAttributes']['picture']

    file_type = profile_picture.filename.split('.')[-1].lower()

    content_type = {
        'png': 'image/png',
        'jpeg': 'image/jpeg',
    }[file_type]

    s3 = boto3.client('s3')
    s3.upload_fileobj(
        profile_picture,
        'my-bucket',
        f'profile-pictures/{event["userName"]}',
        ExtraArgs={'ContentType': content_type}
    )

    return event

```

But I think I surely do something wrong. I dont know how I really can send a picture (e.g. as base64 or something else) to cognito (e.g. with aws cognito-idp sign-up) to store it in the bucket inside of the lambda.

I am quite new to aws-cdk and would appreciate any help!

Body:
I want to create autohrization with aws-cognito.
I am using CDKv2, and try to achieve the following workflow:

User registers with cogninto, the request contains a profile picture. This profile-picture should be uploaded to a s3 bucket, if the registration was successfully.

I have read and tried a lot (e.g. using a lambda to achieve that), but somehow it did not worked as I would expect it.

What I want:
1.) Register using cognito (in later point using the js-sdk in a frontend as counterpart)

2.) While registering I want to add a profile picture, which gets stored in an S3 bucket. The best would be, that the profilePicture field would then be the link to the item in the s3-bucket (or something else, if there is a better way)

I tried to solve this by a preSignup lambda which is a trigger on the user pool:

def handler(event, context):
    profile_picture = event['request']['userAttributes']['picture']

    file_type = profile_picture.filename.split('.')[-1].lower()

    content_type = {
        'png': 'image/png',
        'jpeg': 'image/jpeg',
    }[file_type]

    s3 = boto3.client('s3')
    s3.upload_fileobj(
        profile_picture,
        'my-bucket',
        f'profile-pictures/{event["userName"]}',
        ExtraArgs={'ContentType': content_type}
    )

    return event

But I think I surely do something wrong. I dont know how I really can send a picture (e.g. as base64 or something else) to cognito (e.g. with aws cognito-idp sign-up) to store it in the bucket inside of the lambda.

I am quite new to aws-cdk and would appreciate any help!


问:
Editing a JSON file with Schema validation
I am doing a college project and I can't seem to figure out why my edit broke. I am reading a json file from database. We need to also have schema validation for when we are editing data to make sure the input is valid. It was working before, I added the validation and I am not sure if its my validation causing the error or something else as it is not throwing any errors. Below is my code.

```<code>import React, {Component} from "react"
import Form from "react-bootstrap/Form"
import {Redirect, Link} from "react-router-dom"
import axios from "axios"

import LinkInClass from "../components/LinkInClass"

import {SERVER_HOST} from "../config/global_constants"

export default class EditLandmark extends Component
{
    constructor(props)
    {
        super(props)

        this.state = {
            name:``,
            // type:``,
            url:``,
            telephone:``,
            addressRegion:``,
            addressLocality:``,
            latitude:``,
            longitude:``,
            tags:``,
            redirectToDisplayAllLandmarks:false
        }
    }

    componentDidMount()
    {
        this.inputToFocus.focus()

        axios.get(`${SERVER_HOST}/landmarks/${this.props.match.params.id}`)
        .then(res =>
        {
            if(res.data)
            {
                if (res.data.errorMessage)
                {
                    console.log(res.data.errorMessage)
                }
                else
                {
                    this.setState({
                   name: res.data.name,
                //    type: res.data.type,
                   url: res.data.url,
                   telephone: res.data.telephone,
                   addressRegion: res.data.address.addressRegion,
                   addressLocality: res.data.address.addressLocality,
                   latitude: res.data.geo.latitude,
                   longitude: res.data.geo.longitude,
                   tags: res.data.tags
                    })
                }
            }
            else
            {
                console.log(`Record not found`)
            }
        })
    }

    handleChange = (e) =>
    {
        this.setState({[e.target.name]: e.target.value})
    }

    handleSubmit = (e) =>
    {
        e.preventDefault()
        this.setState({ wasSubmittedAtLeastOnce: true });

        const formInputsState = this.validate();

        if (Object.keys(formInputsState).every(index => formInputsState[index]))
        { const landmarkObject = {

            name: this.state.name,
            // type: this.state.type,
            url: this.state.url,
            telephone: this.state.telephone,
            addressRegion: this.state.addressRegion,
            addressLocality: this.state.addressLocality,
            latitude: this.state.latitude,
            longitude: this.state.longitude,
            tags: this.state.tags
        }

        axios.put(`${SERVER_HOST}/landmarks/${this.props.match.params.id}`, landmarkObject)
        .then(res =>
        {
            if(res.data)
            {
                if (res.data.errorMessage)
                {
                    console.log(res.data.errorMessage)
                }
                else
                {
                    console.log(`Record updated`)
                    this.setState({redirectToDisplayAllLandmarks:true})
                }
            }
            else
            {
                console.log(`Record not updated`)
            }
        })
    }
}

validateName()
{
    const pattern = /^[a-zA-Z]+ [a-zA-Z]+$/;
    return pattern.test(String(this.state.name))

}

// validateType()
//     {
//         const pattern = /^[A-Za-z]+$/;
//         return pattern.test(String(this.state.type))
//     }

validateUrl()
{
    const pattern = /^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/;
    return pattern.test(String(this.state.url))
}

validateTelephone()
{
    const pattern = /^[\+]?[(]?[0-9]{[2-9]{1}\d{2}}[)]?[-\s\.]?[0-9]{3}[-\s\.]?[0-9]{4,6}$/;
    return pattern.test(String(this.state.telephone))
}

validateAddressRegion()
{
    const pattern = /^[A-Za-z]+$/;
    return pattern.test(String(this.state.addressRegion))
}

validateAddressLocality()
{
    const pattern = /^[a-zA-Z]+ [a-zA-Z]+$/;
    return pattern.test(String(this.state.addressLocality))
}

validateLatitude()
{
    const latitude = parseInt(this.state.latitude)
    return (latitude >= -90 && latitude <= 90)
}

validateLongitude()
{
    const longitude = parseInt(this.state.longitude)
    return (longitude >= -180 && longitude <= 180)
}

validateTags()
{
    const pattern = /^[a-zA-Z]+ [a-zA-Z]+$/;
    return pattern.test(String(this.state.tags))
}

validate()
{

    return {
        name: this.validateName(),
        // type: this.validateType(),
        url: this.validateUrl(),
        telephone: this.validateTelephone(),
        addressRegion: this.validateAddressRegion(),
        addressLocality: this.validateAddressLocality(),
        latitude: this.validateLatitude(),
        longitude: this.validateLongitude(),
        tags: this.validateTags()
    };
}

render()
{

    let errorMessage = "";
    if(this.state.wasSubmittedAtLeastOnce)
    {
        errorMessage = <div className="error">Landmark Details are incorrect<br/></div>;
    }

    return (
        <div className="form-container">

            {this.state.redirectToDisplayAllLandmarks ? <Redirect to="/DisplayAllLandmarks"/> : null}

            <Form>

                {errorMessage}

                <Form.Group controlId="name"><Form.Label>Name</Form.Label>
                 <Form.Control ref = {(input) =>  { this.inputToFocus = input }} type="text" name="name" value={this.state.name}
                onChange={this.handleChange} />
                </Form.Group>

                {/* <Form.Group controlId="type">
                        <Form.Label>Type</Form.Label>
                        <Form.Control type="text" name="type" value={this.state.type} onChange={this.handleChange} />
                    </Form.Group> */}

                <Form.Group controlId="url">
                    <Form.Label>Url</Form.Label>
                    <Form.Control type="text" name="url" value={this.state.url} onChange={this.handleChange} />
                </Form.Group>

                <Form.Group controlId="telephone">
                    <Form.Label>Telephone</Form.Label>
                    <Form.Control type="text" name="telephone" value={this.state.telephone} onChange={this.handleChange} />
                </Form.Group>

                <Form.Group controlId="addressRegion">
                    <Form.Label>AddressRegion</Form.Label>
                    <Form.Control type="text" name="addressRegion" value={this.state.addressRegion} onChange={this.handleChange} />
                </Form.Group>

                <Form.Group controlId="addressLocality">
                    <Form.Label>AddressLocality</Form.Label>
                    <Form.Control type="text" name="addressLocality" value={this.state.addressLocality} onChange={this.handleChange} />
                </Form.Group>

                <Form.Group controlId="latitude">
                    <Form.Label>Latitude</Form.Label>
                    <Form.Control type="text" name="latitude" value={this.state.latitude} onChange={this.handleChange} />
                </Form.Group>

                <Form.Group controlId="longitude">
                    <Form.Label>Longitude</Form.Label>
                    <Form.Control type="text" name="longitude" value={this.state.longitude} onChange={this.handleChange} />
                </Form.Group>

                <Form.Group controlId="tags">
                    <Form.Label>Tags</Form.Label>
                    <Form.Control type="text" name="tags" value={this.state.tags} onChange={this.handleChange} />
                </Form.Group>

                <LinkInClass value="Add" className="add-button" onClick={this.handleSubmit}/>

                <Link className="cancel-button" to={"/DisplayAllLandmarks"}>Cancel</Link>
            </Form>
        </div>
    )
}
}

</code>```

I have tried using different validation but nothing seems to be working here is a example of the json

```<code>"name": "Skryne Church",
    "url": "https://www.skryneandrathfeighparish.ie/",
    "geo": {
        "@type": "GeoCoordinates",
        "longitude": -6.5631088,
        "latitude": 53.5859852
    },
    "telephone": "+3530469025152",
    "address": {
        "@type": "PostalAddress",
        "addressLocality": "Dublin",
        "addressRegion": "Dublin",
        "addressCountry": "Republic of Ireland"
    },
    "image": {
        "@type": "ImageObject",
        "caption": "Fáilte Ireland Logo",
        "url": "https://failtecdn.azureedge.net/failteireland/F%C3%A1ilte_Ireland_Logo_OpenDataAPI.jpg"
    },
    "tags": ["Activity", "Church Abbey", "Monastery", "Attraction", "Churches", "Abbeys and Monastery"]
}
</code>```

Body:
I am doing a college project and I can't seem to figure out why my edit broke. I am reading a json file from database. We need to also have schema validation for when we are editing data to make sure the input is valid. It was working before, I added the validation and I am not sure if its my validation causing the error or something else as it is not throwing any errors. Below is my code.

import React, {Component} from "react"
import Form from "react-bootstrap/Form"
import {Redirect, Link} from "react-router-dom"
import axios from "axios"

import LinkInClass from "../components/LinkInClass"

import {SERVER_HOST} from "../config/global_constants"

export default class EditLandmark extends Component
{
    constructor(props)
    {
        super(props)

        this.state = {
            name:``,
            // type:``,
            url:``,
            telephone:``,
            addressRegion:``,
            addressLocality:``,
            latitude:``,
            longitude:``,
            tags:``,
            redirectToDisplayAllLandmarks:false
        }
    }

    componentDidMount()
    {
        this.inputToFocus.focus()

        axios.get(`${SERVER_HOST}/landmarks/${this.props.match.params.id}`)
        .then(res =>
        {
            if(res.data)
            {
                if (res.data.errorMessage)
                {
                    console.log(res.data.errorMessage)
                }
                else
                {
                    this.setState({
                   name: res.data.name,
                //    type: res.data.type,
                   url: res.data.url,
                   telephone: res.data.telephone,
                   addressRegion: res.data.address.addressRegion,
                   addressLocality: res.data.address.addressLocality,
                   latitude: res.data.geo.latitude,
                   longitude: res.data.geo.longitude,
                   tags: res.data.tags
                    })
                }
            }
            else
            {
                console.log(`Record not found`)
            }
        })
    }

    handleChange = (e) =>
    {
        this.setState({[e.target.name]: e.target.value})
    }

    handleSubmit = (e) =>
    {
        e.preventDefault()
        this.setState({ wasSubmittedAtLeastOnce: true });

        const formInputsState = this.validate();

        if (Object.keys(formInputsState).every(index => formInputsState[index]))
        { const landmarkObject = {

            name: this.state.name,
            // type: this.state.type,
            url: this.state.url,
            telephone: this.state.telephone,
            addressRegion: this.state.addressRegion,
            addressLocality: this.state.addressLocality,
            latitude: this.state.latitude,
            longitude: this.state.longitude,
            tags: this.state.tags
        }

        axios.put(`${SERVER_HOST}/landmarks/${this.props.match.params.id}`, landmarkObject)
        .then(res =>
        {
            if(res.data)
            {
                if (res.data.errorMessage)
                {
                    console.log(res.data.errorMessage)
                }
                else
                {
                    console.log(`Record updated`)
                    this.setState({redirectToDisplayAllLandmarks:true})
                }
            }
            else
            {
                console.log(`Record not updated`)
            }
        })
    }
}

validateName()
{
    const pattern = /^[a-zA-Z]+ [a-zA-Z]+$/;
    return pattern.test(String(this.state.name))

}

// validateType()
//     {
//         const pattern = /^[A-Za-z]+$/;
//         return pattern.test(String(this.state.type))
//     }

validateUrl()
{
    const pattern = /^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/;
    return pattern.test(String(this.state.url))
}

validateTelephone()
{
    const pattern = /^[\+]?[(]?[0-9]{[2-9]{1}\d{2}}[)]?[-\s\.]?[0-9]{3}[-\s\.]?[0-9]{4,6}$/;
    return pattern.test(String(this.state.telephone))
}

validateAddressRegion()
{
    const pattern = /^[A-Za-z]+$/;
    return pattern.test(String(this.state.addressRegion))
}

validateAddressLocality()
{
    const pattern = /^[a-zA-Z]+ [a-zA-Z]+$/;
    return pattern.test(String(this.state.addressLocality))
}

validateLatitude()
{
    const latitude = parseInt(this.state.latitude)
    return (latitude >= -90 && latitude <= 90)
}

validateLongitude()
{
    const longitude = parseInt(this.state.longitude)
    return (longitude >= -180 && longitude <= 180)
}

validateTags()
{
    const pattern = /^[a-zA-Z]+ [a-zA-Z]+$/;
    return pattern.test(String(this.state.tags))
}

validate()
{

    return {
        name: this.validateName(),
        // type: this.validateType(),
        url: this.validateUrl(),
        telephone: this.validateTelephone(),
        addressRegion: this.validateAddressRegion(),
        addressLocality: this.validateAddressLocality(),
        latitude: this.validateLatitude(),
        longitude: this.validateLongitude(),
        tags: this.validateTags()
    };
}

render()
{

    let errorMessage = "";
    if(this.state.wasSubmittedAtLeastOnce)
    {
        errorMessage =
Landmark Details are incorrect

;
    }

    return (

            {this.state.redirectToDisplayAllLandmarks ? <Redirect to="/DisplayAllLandmarks"/> : null}

            <Form>

                {errorMessage}

                <Form.Group controlId="name"><Form.Label>Name</Form.Label>
                 <Form.Control ref = {(input) =>  { this.inputToFocus = input }} type="text" name="name" value={this.state.name}
                onChange={this.handleChange} />
                </Form.Group>

                {/* <Form.Group controlId="type">
                        <Form.Label>Type</Form.Label>
                        <Form.Control type="text" name="type" value={this.state.type} onChange={this.handleChange} />
                    </Form.Group> */}

                <Form.Group controlId="url">
                    <Form.Label>Url</Form.Label>
                    <Form.Control type="text" name="url" value={this.state.url} onChange={this.handleChange} />
                </Form.Group>

                <Form.Group controlId="telephone">
                    <Form.Label>Telephone</Form.Label>
                    <Form.Control type="text" name="telephone" value={this.state.telephone} onChange={this.handleChange} />
                </Form.Group>

                <Form.Group controlId="addressRegion">
                    <Form.Label>AddressRegion</Form.Label>
                    <Form.Control type="text" name="addressRegion" value={this.state.addressRegion} onChange={this.handleChange} />
                </Form.Group>

                <Form.Group controlId="addressLocality">
                    <Form.Label>AddressLocality</Form.Label>
                    <Form.Control type="text" name="addressLocality" value={this.state.addressLocality} onChange={this.handleChange} />
                </Form.Group>

                <Form.Group controlId="latitude">
                    <Form.Label>Latitude</Form.Label>
                    <Form.Control type="text" name="latitude" value={this.state.latitude} onChange={this.handleChange} />
                </Form.Group>

                <Form.Group controlId="longitude">
                    <Form.Label>Longitude</Form.Label>
                    <Form.Control type="text" name="longitude" value={this.state.longitude} onChange={this.handleChange} />
                </Form.Group>

                <Form.Group controlId="tags">
                    <Form.Label>Tags</Form.Label>
                    <Form.Control type="text" name="tags" value={this.state.tags} onChange={this.handleChange} />
                </Form.Group>

                <LinkInClass value="Add" className="add-button" onClick={this.handleSubmit}/>

                <Link className="cancel-button" to={"/DisplayAllLandmarks"}>Cancel</Link>
            </Form>

    )
}
}

I have tried using different validation but nothing seems to be working here is a example of the json

"name": "Skryne Church",
    "url": "https://www.skryneandrathfeighparish.ie/",
    "geo": {
        "@type": "GeoCoordinates",
        "longitude": -6.5631088,
        "latitude": 53.5859852
    },
    "telephone": "+3530469025152",
    "address": {
        "@type": "PostalAddress",
        "addressLocality": "Dublin",
        "addressRegion": "Dublin",
        "addressCountry": "Republic of Ireland"
    },
    "image": {
        "@type": "ImageObject",
        "caption": "Fáilte Ireland Logo",
        "url": "https://failtecdn.azureedge.net/failteireland/F%C3%A1ilte_Ireland_Logo_OpenDataAPI.jpg"
    },
    "tags": ["Activity", "Church Abbey", "Monastery", "Attraction", "Churches", "Abbeys and Monastery"]
}


问:
Hypothesis testing for two sample t tests
I have below data frame df.

City
Income

NY
1237

NY
6352

Boston
6487

NJ
6547

Boston
7564

NY
9363

Boston
3262

NY
9473

NJ
6234

Boston
5242

NJ
7483

NY
9273

I need to check the null hypothesis: mean(Income) of NY >= mean(Income) of NJ with  α = 0.05. I get a result from below code, but I am unsure about the accuracy. Numbers look weired.

```<code>NY_Income = df$Income[df$City=="NY"]
NJ_Income = df$Income[df$City=="NJ"]
mu_NY = mean(NY_Income)
mu_NJ = mean(NJ_Income)
t.test(NY_Income,NJ_Income,mu=mu_NY,alternative="less")
</code>```

Body:
I have below data frame df.

City
Income

NY
1237

NY
6352

Boston
6487

NJ
6547

Boston
7564

NY
9363

Boston
3262

NY
9473

NJ
6234

Boston
5242

NJ
7483

NY
9273

I need to check the null hypothesis: mean(Income) of NY >= mean(Income) of NJ with  α = 0.05. I get a result from below code, but I am unsure about the accuracy. Numbers look weired.

NY_Income = df$Income[df$City=="NY"]
NJ_Income = df$Income[df$City=="NJ"]
mu_NY = mean(NY_Income)
mu_NJ = mean(NJ_Income)
t.test(NY_Income,NJ_Income,mu=mu_NY,alternative="less")


问:
How can I customize css formatting rules in html file (
```
<p>I know that I can config like this, but is does not work for <code><style></code> tag in html file:</p>
<pre class="lang-json prettyprint-override"><code>{
  // format
  "editor.formatOnSave": true,
  "editor.formatOnPaste": true,
  // html
  "[html]": {
    "editor.defaultFormatter": "vscode.html-language-features"
  },
  // css
  "[css]": {
    "editor.defaultFormatter": "vscode.css-language-features"
  },
  "css.format.newlineBetweenSelectors": false,
  "css.format.spaceAroundSelectorSeparator": true,
}
</code>```

Title: How can I customize css formatting rules in html file (<style> tag) by VS Code's built-in css formatter?

Body:
How can I customize css formatting rules in html file (

I know that I can config like this, but is does not work for


问:
Java 2d map from x and y coordinates?
I amlooking for a simple way to create a 2d map from x and y coordinates. The program should read a text file with distance measures separated with a comma in (360 measures for every degree), convert these into coordinates, and then create a map, where the dots are connected so it looks more like a map:) Also, a center point would be great, to know from where the measurements were taken.

The calculation is not the problem, however, I don't really know how to convert it into a map...

P.S The output should be something like in the picture
map

Due to lack of knowledge, I was not really able to try many things :/

Title: Java 2d map from x and y coordinates?


问:
When I generate the lighthouse report, it shows like this (I have given the error Screenshot below)

I tried in WIFI and mobile data, both are same.
Why is it showing like this?


问:
After Chef Infra Server Upgrade cannot upload modified cookbooks
After upgrading to 15.3.2 (from 14.9.23) for the Chef Server, whenever I tried to upload a modified cookbook I get:

```<code>WARN: Server returned error 503 for https://CHEFSERVERFQDN/organizations/ORGNAME/sandboxes/dcc451a10a8005662e6469d978b1571f, retrying 1/5 in 3s
</code>```

This will continue for 5 total attempts, finally ending with :

```<code>INFO: HTTP Request Returned 503 Service Unavailable: Committed incomplete sandbox: [<<"2f342b4b219866ba4272b7aa768caa28">>]
ERROR: Service temporarily unavailable
Response: Committed incomplete sandbox: [<<"2f342b4b219866ba4272b7aa768caa28">>]
</code>```

After a bunch of looking around I finally found the chef-server-ctl test command, and I got some errors out of it, but it does not direct me to anything to resolve these issues. The main one appears to be #7 Sanboxes API at least in relation to my upload issue.

All the nodes are pulling just fine, it doesn't matter what the edit in the file is either, I deleted my local copy, pulled it down from the server, and just removed a blank line, and this will happen when I try to upload it.

```<code>Failures:

  1) Cookbook Artifacts API endpoint API v0 behaves like deletes cookbook artifacts DELETE /cookbook_artifacts/<name>/<version> for existing cookbooks when deleting existent version of an existing cookbook should cleanup unused checksum data in s3/bookshelf
     Failure/Error: raise "bad response code #{response.code} in response: #{response}"

     RuntimeError:
       bad response code 503 in response: {"error":["Committed incomplete sandbox: [<<\"fb0d05a2ecd93dbd9f727c54ec1e08ac\">>]"]}
     Shared Example Group: "deletes cookbook artifacts" called from ./spec/api/cookbook_artifacts/delete_spec.rb:196
     # ./lib/pedant/rspec/common.rb:429:in `ensure_2xx'
     # ./lib/pedant/rspec/cookbook_util.rb:65:in `commit_sandbox'
     # ./lib/pedant/rspec/cookbook_util.rb:74:in `upload_files_to_sandbox'
     # ./lib/pedant/rspec/cookbook_util.rb:287:in `make_cookbook_artifact_with_recipes'
     # ./spec/api/cookbook_artifacts/delete_spec.rb:109:in `block (6 levels) in <top (required)>'

  2) Cookbook Artifacts API endpoint API v2 behaves like deletes cookbook artifacts DELETE /cookbook_artifacts/<name>/<version> for existing cookbooks when deleting existent version of an existing cookbook should cleanup unused checksum data in s3/bookshelf
     Failure/Error: raise "bad response code #{response.code} in response: #{response}"

     RuntimeError:
       bad response code 503 in response: {"error":["Committed incomplete sandbox: [<<\"fb0d05a2ecd93dbd9f727c54ec1e08ac\">>]"]}
     Shared Example Group: "deletes cookbook artifacts" called from ./spec/api/cookbook_artifacts/delete_spec.rb:200
     # ./lib/pedant/rspec/common.rb:429:in `ensure_2xx'
     # ./lib/pedant/rspec/cookbook_util.rb:65:in `commit_sandbox'
     # ./lib/pedant/rspec/cookbook_util.rb:74:in `upload_files_to_sandbox'
     # ./lib/pedant/rspec/cookbook_util.rb:287:in `make_cookbook_artifact_with_recipes'
     # ./spec/api/cookbook_artifacts/delete_spec.rb:109:in `block (6 levels) in <top (required)>'

  3) Cookbooks API endpoint API v0 behaves like deletes cookbooks DELETE /cookbooks/<name>/<version> for existing cookbooks when deleting existent version of an existing cookbook should cleanup unused checksum data in s3/bookshelf
     Failure/Error: raise "bad response code #{response.code} in response: #{response}"

     RuntimeError:
       bad response code 503 in response: {"error":["Committed incomplete sandbox: [<<\"81b28a0dc350a9cabaa562df8909ef57\">>]"]}
     Shared Example Group: "deletes cookbooks" called from ./spec/api/cookbooks/delete_spec.rb:173
     # ./lib/pedant/rspec/common.rb:429:in `ensure_2xx'
     # ./lib/pedant/rspec/cookbook_util.rb:65:in `commit_sandbox'
     # ./lib/pedant/rspec/cookbook_util.rb:74:in `upload_files_to_sandbox'
     # ./lib/pedant/rspec/cookbook_util.rb:575:in `save_dummy_cookbook_with_recipes'
     # ./lib/pedant/rspec/cookbook_util.rb:594:in `block (2 levels) in setup_cookbooks'
     # ./lib/pedant/rspec/cookbook_util.rb:593:in `each'
     # ./lib/pedant/rspec/cookbook_util.rb:593:in `block in setup_cookbooks'
     # ./lib/pedant/rspec/cookbook_util.rb:592:in `each'
     # ./lib/pedant/rspec/cookbook_util.rb:592:in `setup_cookbooks'
     # ./spec/api/cookbooks/delete_spec.rb:109:in `block (6 levels) in <top (required)>'

  4) Cookbooks API endpoint API v2 behaves like deletes cookbooks DELETE /cookbooks/<name>/<version> for existing cookbooks when deleting existent version of an existing cookbook should cleanup unused checksum data in s3/bookshelf
     Failure/Error: raise "bad response code #{response.code} in response: #{response}"

     RuntimeError:
       bad response code 503 in response: {"error":["Committed incomplete sandbox: [<<\"e672634a55b23e7bcf41a16d9b734742\">>]"]}
     Shared Example Group: "deletes cookbooks" called from ./spec/api/cookbooks/delete_spec.rb:177
     # ./lib/pedant/rspec/common.rb:429:in `ensure_2xx'
     # ./lib/pedant/rspec/cookbook_util.rb:65:in `commit_sandbox'
     # ./lib/pedant/rspec/cookbook_util.rb:74:in `upload_files_to_sandbox'
     # ./lib/pedant/rspec/cookbook_util.rb:575:in `save_dummy_cookbook_with_recipes'
     # ./lib/pedant/rspec/cookbook_util.rb:594:in `block (2 levels) in setup_cookbooks'
     # ./lib/pedant/rspec/cookbook_util.rb:593:in `each'
     # ./lib/pedant/rspec/cookbook_util.rb:593:in `block in setup_cookbooks'
     # ./lib/pedant/rspec/cookbook_util.rb:592:in `each'
     # ./lib/pedant/rspec/cookbook_util.rb:592:in `setup_cookbooks'
     # ./spec/api/cookbooks/delete_spec.rb:109:in `block (6 levels) in <top (required)>'

  5) /environments/ENVIRONMENT/recipes API endpoint with multiple versions of multiple cookbooks with no environment constraints when fetching recipes from a non-default environment should respond with 200 OK and recipes from the latest version of all cookbooks within the environment
     Failure/Error: raise "bad response code #{response.code} in response: #{response}"

     RuntimeError:
       bad response code 503 in response: {"error":["Committed incomplete sandbox: [<<\"6a57e27fe1a7a056804e458262377512\">>]"]}
     # ./lib/pedant/rspec/common.rb:429:in `ensure_2xx'
     # ./lib/pedant/rspec/cookbook_util.rb:65:in `commit_sandbox'
     # ./lib/pedant/rspec/cookbook_util.rb:74:in `upload_files_to_sandbox'
     # ./lib/pedant/rspec/cookbook_util.rb:575:in `save_dummy_cookbook_with_recipes'
     # ./lib/pedant/rspec/cookbook_util.rb:594:in `block (2 levels) in setup_cookbooks'
     # ./lib/pedant/rspec/cookbook_util.rb:593:in `each'
     # ./lib/pedant/rspec/cookbook_util.rb:593:in `block in setup_cookbooks'
     # ./lib/pedant/rspec/cookbook_util.rb:592:in `each'
     # ./lib/pedant/rspec/cookbook_util.rb:592:in `setup_cookbooks'
     # ./spec/api/environments/recipes_spec.rb:98:in `block (3 levels) in <top (required)>'

  6) /environments/ENVIRONMENT/recipes API endpoint with multiple versions of multiple cookbooks with no environment constraints when fetching recipes from _default environment should respond with 200 OK and recipes from the latest version of all cookbooks within the environment
     Failure/Error: raise "bad response code #{response.code} in response: #{response}"

     RuntimeError:
       bad response code 503 in response: {"error":["Committed incomplete sandbox: [<<\"6a57e27fe1a7a056804e458262377512\">>]"]}
     # ./lib/pedant/rspec/common.rb:429:in `ensure_2xx'
     # ./lib/pedant/rspec/cookbook_util.rb:65:in `commit_sandbox'
     # ./lib/pedant/rspec/cookbook_util.rb:74:in `upload_files_to_sandbox'
     # ./lib/pedant/rspec/cookbook_util.rb:575:in `save_dummy_cookbook_with_recipes'
     # ./lib/pedant/rspec/cookbook_util.rb:594:in `block (2 levels) in setup_cookbooks'
     # ./lib/pedant/rspec/cookbook_util.rb:593:in `each'
     # ./lib/pedant/rspec/cookbook_util.rb:593:in `block in setup_cookbooks'
     # ./lib/pedant/rspec/cookbook_util.rb:592:in `each'
     # ./lib/pedant/rspec/cookbook_util.rb:592:in `setup_cookbooks'
     # ./spec/api/environments/recipes_spec.rb:98:in `block (3 levels) in <top (required)>'

  7) Sandboxes API Endpoint Sandboxes Endpoint, PUT when committing a sandbox after uploading files should respond with 200 OK
     Failure/Error: response.should look_like expected_response

       Response should have HTTP status code 200 ('OK'), but it was actually 503 ('Service Unavailable')
         Reponse Body: {"error":["Committed incomplete sandbox: [<<\"1c5c1bca569237b5fbb880471f0444c2\">>,\n <<\"e35dd7f89565f12762c2012dffb6716a\">>]"]}
     # ./spec/api/sandboxes/complete_endpoint_spec.rb:247:in `block (4 levels) in <top (required)>'

  8) /_stats API endpoint returns prometheus output ?format=text
     Failure/Error: expect(names.uniq).to match_array(PROMETHEUS_RESPONSE_TYPE_MAP.keys)

       expected collection contained:  ["chef_index_batch_completed_latency_ms_bucket", "chef_index_batch_completed_latency_ms_count", "chef... "pg_stat_tidx_blks_read", "pg_stat_toast_blks_hit", "pg_stat_toast_blks_read", "pg_stat_tup_fetch"]
       actual collection contained:    ["chef_index_batch_completed_latency_ms_bucket", "chef_index_batch_completed_latency_ms_count", "chef... "pg_stat_tidx_blks_read", "pg_stat_toast_blks_hit", "pg_stat_toast_blks_read", "pg_stat_tup_fetch"]
       the extra elements were:        ["chef_index_http_req_failure_total"]
     # ./spec/api/stats_spec.rb:218:in `block (2 levels) in <top (required)>'

</code>```

I'd rather not revert the server back to pre-update, but I'm really banging my head here trying to figure out where the issue is and what would resolve it.

I have not been able to try many fixes as I am not finding anything really dedicated to the presented issues. I have attempted doing chef-server-ctrl reconfigure, and status, made sure the org shows up properly, made sure it wasn't some how stuck in a maintenance mode. I've also tried to dig into the specific Chef logs, and I can see some of the same errors in there on some of the logs, but I expect this is what the test option is bringing up as well.

Body:
After upgrading to 15.3.2 (from 14.9.23) for the Chef Server, whenever I tried to upload a modified cookbook I get:

WARN: Server returned error 503 for https://CHEFSERVERFQDN/organizations/ORGNAME/sandboxes/dcc451a10a8005662e6469d978b1571f, retrying 1/5 in 3s

This will continue for 5 total attempts, finally ending with :

INFO: HTTP Request Returned 503 Service Unavailable: Committed incomplete sandbox: [<<"2f342b4b219866ba4272b7aa768caa28">>]
ERROR: Service temporarily unavailable
Response: Committed incomplete sandbox: [<<"2f342b4b219866ba4272b7aa768caa28">>]

After a bunch of looking around I finally found the chef-server-ctl test command, and I got some errors out of it, but it does not direct me to anything to resolve these issues. The main one appears to be #7 Sanboxes API at least in relation to my upload issue.

All the nodes are pulling just fine, it doesn't matter what the edit in the file is either, I deleted my local copy, pulled it down from the server, and just removed a blank line, and this will happen when I try to upload it.

Failures:

  1) Cookbook Artifacts API endpoint API v0 behaves like deletes cookbook artifacts DELETE /cookbook_artifacts/<name>/<version> for existing cookbooks when deleting existent version of an existing cookbook should cleanup unused checksum data in s3/bookshelf
     Failure/Error: raise "bad response code #{response.code} in response: #{response}"

     RuntimeError:
       bad response code 503 in response: {"error":["Committed incomplete sandbox: [<<\"fb0d05a2ecd93dbd9f727c54ec1e08ac\">>]"]}
     Shared Example Group: "deletes cookbook artifacts" called from ./spec/api/cookbook_artifacts/delete_spec.rb:196
     # ./lib/pedant/rspec/common.rb:429:in `ensure_2xx'
     # ./lib/pedant/rspec/cookbook_util.rb:65:in `commit_sandbox'
     # ./lib/pedant/rspec/cookbook_util.rb:74:in `upload_files_to_sandbox'
     # ./lib/pedant/rspec/cookbook_util.rb:287:in `make_cookbook_artifact_with_recipes'
     # ./spec/api/cookbook_artifacts/delete_spec.rb:109:in `block (6 levels) in <top (required)>'

  2) Cookbook Artifacts API endpoint API v2 behaves like deletes cookbook artifacts DELETE /cookbook_artifacts/<name>/<version> for existing cookbooks when deleting existent version of an existing cookbook should cleanup unused checksum data in s3/bookshelf
     Failure/Error: raise "bad response code #{response.code} in response: #{response}"

     RuntimeError:
       bad response code 503 in response: {"error":["Committed incomplete sandbox: [<<\"fb0d05a2ecd93dbd9f727c54ec1e08ac\">>]"]}
     Shared Example Group: "deletes cookbook artifacts" called from ./spec/api/cookbook_artifacts/delete_spec.rb:200
     # ./lib/pedant/rspec/common.rb:429:in `ensure_2xx'
     # ./lib/pedant/rspec/cookbook_util.rb:65:in `commit_sandbox'
     # ./lib/pedant/rspec/cookbook_util.rb:74:in `upload_files_to_sandbox'
     # ./lib/pedant/rspec/cookbook_util.rb:287:in `make_cookbook_artifact_with_recipes'
     # ./spec/api/cookbook_artifacts/delete_spec.rb:109:in `block (6 levels) in <top (required)>'

  3) Cookbooks API endpoint API v0 behaves like deletes cookbooks DELETE /cookbooks/<name>/<version> for existing cookbooks when deleting existent version of an existing cookbook should cleanup unused checksum data in s3/bookshelf
     Failure/Error: raise "bad response code #{response.code} in response: #{response}"

     RuntimeError:
       bad response code 503 in response: {"error":["Committed incomplete sandbox: [<<\"81b28a0dc350a9cabaa562df8909ef57\">>]"]}
     Shared Example Group: "deletes cookbooks" called from ./spec/api/cookbooks/delete_spec.rb:173
     # ./lib/pedant/rspec/common.rb:429:in `ensure_2xx'
     # ./lib/pedant/rspec/cookbook_util.rb:65:in `commit_sandbox'
     # ./lib/pedant/rspec/cookbook_util.rb:74:in `upload_files_to_sandbox'
     # ./lib/pedant/rspec/cookbook_util.rb:575:in `save_dummy_cookbook_with_recipes'
     # ./lib/pedant/rspec/cookbook_util.rb:594:in `block (2 levels) in setup_cookbooks'
     # ./lib/pedant/rspec/cookbook_util.rb:593:in `each'
     # ./lib/pedant/rspec/cookbook_util.rb:593:in `block in setup_cookbooks'
     # ./lib/pedant/rspec/cookbook_util.rb:592:in `each'
     # ./lib/pedant/rspec/cookbook_util.rb:592:in `setup_cookbooks'
     # ./spec/api/cookbooks/delete_spec.rb:109:in `block (6 levels) in <top (required)>'

  4) Cookbooks API endpoint API v2 behaves like deletes cookbooks DELETE /cookbooks/<name>/<version> for existing cookbooks when deleting existent version of an existing cookbook should cleanup unused checksum data in s3/bookshelf
     Failure/Error: raise "bad response code #{response.code} in response: #{response}"

     RuntimeError:
       bad response code 503 in response: {"error":["Committed incomplete sandbox: [<<\"e672634a55b23e7bcf41a16d9b734742\">>]"]}
     Shared Example Group: "deletes cookbooks" called from ./spec/api/cookbooks/delete_spec.rb:177
     # ./lib/pedant/rspec/common.rb:429:in `ensure_2xx'
     # ./lib/pedant/rspec/cookbook_util.rb:65:in `commit_sandbox'
     # ./lib/pedant/rspec/cookbook_util.rb:74:in `upload_files_to_sandbox'
     # ./lib/pedant/rspec/cookbook_util.rb:575:in `save_dummy_cookbook_with_recipes'
     # ./lib/pedant/rspec/cookbook_util.rb:594:in `block (2 levels) in setup_cookbooks'
     # ./lib/pedant/rspec/cookbook_util.rb:593:in `each'
     # ./lib/pedant/rspec/cookbook_util.rb:593:in `block in setup_cookbooks'
     # ./lib/pedant/rspec/cookbook_util.rb:592:in `each'
     # ./lib/pedant/rspec/cookbook_util.rb:592:in `setup_cookbooks'
     # ./spec/api/cookbooks/delete_spec.rb:109:in `block (6 levels) in <top (required)>'

  5) /environments/ENVIRONMENT/recipes API endpoint with multiple versions of multiple cookbooks with no environment constraints when fetching recipes from a non-default environment should respond with 200 OK and recipes from the latest version of all cookbooks within the environment
     Failure/Error: raise "bad response code #{response.code} in response: #{response}"

     RuntimeError:
       bad response code 503 in response: {"error":["Committed incomplete sandbox: [<<\"6a57e27fe1a7a056804e458262377512\">>]"]}
     # ./lib/pedant/rspec/common.rb:429:in `ensure_2xx'
     # ./lib/pedant/rspec/cookbook_util.rb:65:in `commit_sandbox'
     # ./lib/pedant/rspec/cookbook_util.rb:74:in `upload_files_to_sandbox'
     # ./lib/pedant/rspec/cookbook_util.rb:575:in `save_dummy_cookbook_with_recipes'
     # ./lib/pedant/rspec/cookbook_util.rb:594:in `block (2 levels) in setup_cookbooks'
     # ./lib/pedant/rspec/cookbook_util.rb:593:in `each'
     # ./lib/pedant/rspec/cookbook_util.rb:593:in `block in setup_cookbooks'
     # ./lib/pedant/rspec/cookbook_util.rb:592:in `each'
     # ./lib/pedant/rspec/cookbook_util.rb:592:in `setup_cookbooks'
     # ./spec/api/environments/recipes_spec.rb:98:in `block (3 levels) in <top (required)>'

  6) /environments/ENVIRONMENT/recipes API endpoint with multiple versions of multiple cookbooks with no environment constraints when fetching recipes from _default environment should respond with 200 OK and recipes from the latest version of all cookbooks within the environment
     Failure/Error: raise "bad response code #{response.code} in response: #{response}"

     RuntimeError:
       bad response code 503 in response: {"error":["Committed incomplete sandbox: [<<\"6a57e27fe1a7a056804e458262377512\">>]"]}
     # ./lib/pedant/rspec/common.rb:429:in `ensure_2xx'
     # ./lib/pedant/rspec/cookbook_util.rb:65:in `commit_sandbox'
     # ./lib/pedant/rspec/cookbook_util.rb:74:in `upload_files_to_sandbox'
     # ./lib/pedant/rspec/cookbook_util.rb:575:in `save_dummy_cookbook_with_recipes'
     # ./lib/pedant/rspec/cookbook_util.rb:594:in `block (2 levels) in setup_cookbooks'
     # ./lib/pedant/rspec/cookbook_util.rb:593:in `each'
     # ./lib/pedant/rspec/cookbook_util.rb:593:in `block in setup_cookbooks'
     # ./lib/pedant/rspec/cookbook_util.rb:592:in `each'
     # ./lib/pedant/rspec/cookbook_util.rb:592:in `setup_cookbooks'
     # ./spec/api/environments/recipes_spec.rb:98:in `block (3 levels) in <top (required)>'

  7) Sandboxes API Endpoint Sandboxes Endpoint, PUT when committing a sandbox after uploading files should respond with 200 OK
     Failure/Error: response.should look_like expected_response

       Response should have HTTP status code 200 ('OK'), but it was actually 503 ('Service Unavailable')
         Reponse Body: {"error":["Committed incomplete sandbox: [<<\"1c5c1bca569237b5fbb880471f0444c2\">>,\n <<\"e35dd7f89565f12762c2012dffb6716a\">>]"]}
     # ./spec/api/sandboxes/complete_endpoint_spec.rb:247:in `block (4 levels) in <top (required)>'

  8) /_stats API endpoint returns prometheus output ?format=text
     Failure/Error: expect(names.uniq).to match_array(PROMETHEUS_RESPONSE_TYPE_MAP.keys)

       expected collection contained:  ["chef_index_batch_completed_latency_ms_bucket", "chef_index_batch_completed_latency_ms_count", "chef... "pg_stat_tidx_blks_read", "pg_stat_toast_blks_hit", "pg_stat_toast_blks_read", "pg_stat_tup_fetch"]
       actual collection contained:    ["chef_index_batch_completed_latency_ms_bucket", "chef_index_batch_completed_latency_ms_count", "chef... "pg_stat_tidx_blks_read", "pg_stat_toast_blks_hit", "pg_stat_toast_blks_read", "pg_stat_tup_fetch"]
       the extra elements were:        ["chef_index_http_req_failure_total"]
     # ./spec/api/stats_spec.rb:218:in `block (2 levels) in <top (required)>'

I'd rather not revert the server back to pre-update, but I'm really banging my head here trying to figure out where the issue is and what would resolve it.

I have not been able to try many fixes as I am not finding anything really dedicated to the presented issues. I have attempted doing chef-server-ctrl reconfigure, and status, made sure the org shows up properly, made sure it wasn't some how stuck in a maintenance mode. I've also tried to dig into the specific Chef logs, and I can see some of the same errors in there on some of the logs, but I expect this is what the test option is bringing up as well.


问:
container network "multi home" dns resoulution
I try to create a simple docker-compose.yml file.

The problem is a container that depends on another container, but needs also access to the local network the host is connected to.

When i do docker compose up with the following *.yml the "connector" container can not resolve "backend" and results in a "EAI_AGAIN" error:

```<code>connector  | Error: getaddrinfo EAI_AGAIN backend
connector  |     at GetAddrInfoReqWrap.onlookup [as oncomplete] (node:dns:109:26) {
connector  |   errno: -3001,
connector  |   code: 'EAI_AGAIN',
connector  |   syscall: 'getaddrinfo',
connector  |   hostname: 'backend'
connector  | }
</code>```

docker-compose.yml

version: "2"
services:
  nginx:
    image: "nginx:1.23.2-alpine"
    container_name: nginx
    hostname: nginx
    volumes:
      - "./project.conf:/etc/nginx/conf.d/project.conf"
    ports:
      - "80:80"
      - "443:443"
    depends_on:
      - backend
      - frontend
  database:
    image: mongo
    container_name: database
    hostname: database
    ports:
      - "27017:27017"
  backend:
    image: "project/backend:latest"
    container_name: backend
    hostname: backend
    environment:
      - NODE_ENV=production
      - DATABASE_HOST=database
    ports:
      - "8080:8080"
    depends_on:
      - database
    tty: true
  frontend:
    image: "project/frontend:latest"
    container_name: frontend
    hostname: frontend
    ports:
      - "3000:80"
    depends_on:
      - backend
  connector:
    image: "project/connector:latest"
    container_name: connector
    hostname: connector
    environment:
      - NODE_ENV=production
      - BACKEND_HOST=backend
    depends_on:
      - backend
    #    net: host
    network_mode: "host"
    tty: true
```

What would be the correct way to allow the connector access to the local Network where docker is running and and allow it to resolve "backend" so that it can speak with the backend container?

Backend & connector container are node.js images.

EDIT:
The connector container needs to be receive UDP multicast packets, and talk to a HTTP API in the backend container. To not deal with IP Addresses, i want to use the container names.

Which works when all container are on the same network, but not when the connector is set to "host", but which is needed to receive multicast packets.

Body:
I try to create a simple docker-compose.yml file.

The problem is a container that depends on another container, but needs also access to the local network the host is connected to.

When i do docker compose up with the following *.yml the "connector" container can not resolve "backend" and results in a "EAI_AGAIN" error:

connector  | Error: getaddrinfo EAI_AGAIN backend
connector  |     at GetAddrInfoReqWrap.onlookup [as oncomplete] (node:dns:109:26) {
connector  |   errno: -3001,
connector  |   code: 'EAI_AGAIN',
connector  |   syscall: 'getaddrinfo',
connector  |   hostname: 'backend'
connector  | }

docker-compose.yml

version: "2"
services:
  nginx:
    image: "nginx:1.23.2-alpine"
    container_name: nginx
    hostname: nginx
    volumes:
      - "./project.conf:/etc/nginx/conf.d/project.conf"
    ports:
      - "80:80"
      - "443:443"
    depends_on:
      - backend
      - frontend
  database:
    image: mongo
    container_name: database
    hostname: database
    ports:
      - "27017:27017"
  backend:
    image: "project/backend:latest"
    container_name: backend
    hostname: backend
    environment:
      - NODE_ENV=production
      - DATABASE_HOST=database
    ports:
      - "8080:8080"
    depends_on:
      - database
    tty: true
  frontend:
    image: "project/frontend:latest"
    container_name: frontend
    hostname: frontend
    ports:
      - "3000:80"
    depends_on:
      - backend
  connector:
    image: "project/connector:latest"
    container_name: connector
    hostname: connector
    environment:
      - NODE_ENV=production
      - BACKEND_HOST=backend
    depends_on:
      - backend
    #    net: host
    network_mode: "host"
    tty: true

What would be the correct way to allow the connector access to the local Network where docker is running and and allow it to resolve "backend" so that it can speak with the backend container?

Backend & connector container are node.js images.

EDIT:
The connector container needs to be receive UDP multicast packets, and talk to a HTTP API in the backend container. To not deal with IP Addresses, i want to use the container names.

Which works when all container are on the same network, but not when the connector is set to "host", but which is needed to receive multicast packets.


问:
Is there a way to tell when an PHAsset was added to a collection in PhotoKit?
I'm using PHAsset.fetchAssets to retrieve some assets from a PhotoKit collection. I need to be able to tell when an asset was added to a collection. I realize assets have a creationDate and modificationDate, but those refer to when the item was created. For example, if I copy a photo taken on device A to device B, the creationDate on device B will reflect when the photo was taken. I need to know when it was copied to the device.

I remember there being a way to retrieve "hidden" fields from PHAsset by using value(forKeyPath: <#T##String#>) or something along those lines, but I can't find the source anymore.


问:
Error in inflating ( dataBinding ) fragment when toggling light dark theme
here is my activity main codeactivity main code
here is my fragment home code fragment home code
here is my xml
main xml
home xml

could you help me fix this problem


问:
Material UI Select - How does the component know what label to render when value changes from outside
I was poking around the select component of Material UI and there's a specific functionality about it that boggles me.

The element does not render its children in the browser, its just the button. However, when the value is changed from outside ( emulated with a setTimeout at the bottom of the file), it somehow figures out what text value it should display in the button.

The select component is not passed an array of all of the options, along with a key, as props, which would help it figure out what text it should render, so how does it figure it out?

Does it render its children within one browser frame ( so that it is not visible ), read the right value from the element, then hide them again?

The relevant code is at the bottom of the demo

https://stackblitz.com/edit/react-xzjhpf?file=demo.tsx


问:
SendGrid - Whitelist Environments
Currently we're using sendgrid in our production, dev and test environments.

Is it possible to have sendgrid only allow emails to be sent to users on a whitelist?

The use case is we have real user email addresses in our dev env and we dont want to accidently have them receive emails. Is it possible to block everything except our dev email addresses?

Title: SendGrid - Whitelist Environments


问:
Writing a mixin in sass for easy use in media
I would like to write such a mixin so that you can conditionally pass an array consisting of a property and its value. I will give an example to make it clearer, it is obviously incorrect due to poor knowledge of sass. Is it possible to implement with the tools that sass provides?

```<code>
@mixin myMedia($args) {
  $sizes: (
  xxl: 1920px,
  xl: 1440px
);
  @for $i from 1 through $args {

    @media(max-width: $sizes[$i])
      $args[$i] @content
    }

}

@include myMedia(
   {font-size: 16p; line-height: 16px;},
   {font-size: 14p; line-height: 14px;}
)

</code>```

I tried for , each , functions , but didn't come up with anything like what I described above

Body:
I would like to write such a mixin so that you can conditionally pass an array consisting of a property and its value. I will give an example to make it clearer, it is obviously incorrect due to poor knowledge of sass. Is it possible to implement with the tools that sass provides?

@mixin myMedia($args) {
  $sizes: (
  xxl: 1920px,
  xl: 1440px
);
  @for $i from 1 through $args {

    @media(max-width: $sizes[$i])
      $args[$i] @content
    }

}

@include myMedia(
   {font-size: 16p; line-height: 16px;},
   {font-size: 14p; line-height: 14px;}
)

I tried for , each , functions , but didn't come up with anything like what I described above


问:
Weird behavior of git switch/checkout if index has same content as target commit
Let's create a small local repository:

git init
echo foo > foo
git add foo
git commit -m foo
git branch bar
echo foo >> foo
git commit -a -m 'another foo'
```
<p>If we do this now, we replace our file <code>foo</code> in our <em>index</em> as well as in our <em>working copy</em> with the one from the branch <code>bar</code>:</p>
<pre class="lang-bash prettyprint-override"><code>git restore --source bar --staged --worktree foo
</code>```

and now we switch to bar:

git switch bar
```
<h1>Expectation</h1>
<p>git should refuse the <code>switch</code> due to a dirty repository</p>
<h1>Actual behavior</h1>
<p>git does the switch and acts like nothing ever happened:</p>
<pre class="lang-bash prettyprint-override"><code>git status
</code>```

```<code>On branch bar
nothing to commit, working tree clean
</code>```

Even weirder, if we instead just restore to the index:

git restore --source bar --staged foo
```
<p>and switch then:</p>
<pre class="lang-bash prettyprint-override"><code>git switch bar
</code>```

It will again just do it, but this time with uncommitted changes to foo?

git status
```
<blockquote>
```On branch bar
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git restore <file>..." to discard changes in working directory)
        modified:   foo
```
</blockquote>
<h1>Questions</h1>
<ul>
<li>Why does git perform the switch?</li>
<li>Why doesn't it refuse to switch because of a dirty repository?</li>
<li>What is happening behind the scenes?</li>
<li>Where is this behavior documented?</li>
</ul>
<p>FYI, the same happens with <code>git checkout</code>.</p>
<hr />
<p>All I could find in the documentation is this sentence:</p>
<blockquote>
<p>The operation is aborted however if the operation leads to loss of local changes, [...]</p>
</blockquote>
<p>But that doesn't really explain it, since if I do this instead of the <code>restore</code> above:</p>
<pre class="lang-bash prettyprint-override"><code>echo foo >> foo
git add foo
git switch bar
</code>```

```<code>error: Your local changes to the following files would be overwritten by checkout:
        foo
Please commit your changes or stash them before you switch branches.
Aborting
</code>```

git won't do the switch because of a dirty repository (as expected), even though it theoretically could without losing local changes by only updating the index and not the working directory, as it seemingly does when the index already has the desired content for the switch.

Why is there an exception when the index has the same content as the target branch?

Body:
Let's create a small local repository:

git init
echo foo > foo
git add foo
git commit -m foo
git branch bar
echo foo >> foo
git commit -a -m 'another foo'

If we do this now, we replace our file foo in our index as well as in our working copy with the one from the branch bar:

git restore --source bar --staged --worktree foo

and now we switch to bar:

git switch bar

Expectation

git should refuse the switch due to a dirty repository

Actual behavior

git does the switch and acts like nothing ever happened:

git status

On branch bar
nothing to commit, working tree clean

Even weirder, if we instead just restore to the index:

git restore --source bar --staged foo

and switch then:

git switch bar

It will again just do it, but this time with uncommitted changes to foo?

git status

On branch bar
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git restore <file>..." to discard changes in working directory)
        modified:   foo

Questions

Why does git perform the switch?

Why doesn't it refuse to switch because of a dirty repository?

What is happening behind the scenes?

Where is this behavior documented?

FYI, the same happens with git checkout.

All I could find in the documentation is this sentence:

The operation is aborted however if the operation leads to loss of local changes, [...]

But that doesn't really explain it, since if I do this instead of the restore above:

echo foo >> foo
git add foo
git switch bar

error: Your local changes to the following files would be overwritten by checkout:
        foo
Please commit your changes or stash them before you switch branches.
Aborting

git won't do the switch because of a dirty repository (as expected), even though it theoretically could without losing local changes by only updating the index and not the working directory, as it seemingly does when the index already has the desired content for the switch.

Why is there an exception when the index has the same content as the target branch?


问:
Keyword Compare VBA What am I missing?
I'm trying to compare keywords from sheet 1 to sheet 2 and return keywords that do not have a match. I'm at a loss as to what my problem is here.

```<code>Sub CompareKeywords()

    Dim keyword As Variant
    Dim matchFound As Boolean

    'Loop through each keyword in sheet 1
    For Each keyword In Sheets("Sheet1").Range("A:A")

        'Search for the keyword in sheet 2
        matchFound = False
        For Each cell In Sheets("Sheet2").Range("A:A")
            If keyword = cell.value Then
                matchFound = True
                Exit For
            End If
        Next cell

        'If the keyword was not found in sheet 2, add it to the list of keywords without matches
        If Not matchFound Then
            Dim lastUsedCell As Range
            Set lastUsedCell = Sheets("Sheet1").Cells(Sheets("Sheet1").Rows.Count, "B").End(xlDown)
            lastUsedCell.Offset(1, 0).value = keyword
        End If

    Next keyword

    End Sub
</code>```

I'm getting a runtime error 1004
Application Defined or Object Defined error

What am I missing?

Title: Keyword Compare VBA What am I missing?

Body:
I'm trying to compare keywords from sheet 1 to sheet 2 and return keywords that do not have a match. I'm at a loss as to what my problem is here.

Sub CompareKeywords()

    Dim keyword As Variant
    Dim matchFound As Boolean

    'Loop through each keyword in sheet 1
    For Each keyword In Sheets("Sheet1").Range("A:A")

        'Search for the keyword in sheet 2
        matchFound = False
        For Each cell In Sheets("Sheet2").Range("A:A")
            If keyword = cell.value Then
                matchFound = True
                Exit For
            End If
        Next cell

        'If the keyword was not found in sheet 2, add it to the list of keywords without matches
        If Not matchFound Then
            Dim lastUsedCell As Range
            Set lastUsedCell = Sheets("Sheet1").Cells(Sheets("Sheet1").Rows.Count, "B").End(xlDown)
            lastUsedCell.Offset(1, 0).value = keyword
        End If

    Next keyword

    End Sub

I'm getting a runtime error 1004
Application Defined or Object Defined error

What am I missing?


问:
Docker sphinxdoc/sphinx does not find built-in sphinx extension (path not set...)
I created a software documentation using restructuredText and sphinx, which shall be uploaded to a gitlab repository and connected to readthedocs.

Locally I can create the html documentation. However, when I upload it to a gitlab repository, and create a CI with a sphinxdoc/sphinx docker container, it does not find the build-in extensions (I use todo and ifconfig). The reason is that locally I use

```<code>import sys
sys.path.append(os.path.abspath('/home/scheider/.local/lib/python3.8/site-packages/sphinx/ext'))
</code>```

in my conf.py in order to include the extensions, but I don't know what to use for the gitlab CI.

Sorry, if it is a stupid questions, but my knowledge about docker is very(!) limited.
Thanks in advance for any help
Ingo

I used the sphinxdoc/sphinx docker also locally and got the same error. Since I cannot work with the docker container interactively, I don't know how to get the respective path (and it seems that my google skills are minor as well...)

Body:
I created a software documentation using restructuredText and sphinx, which shall be uploaded to a gitlab repository and connected to readthedocs.

Locally I can create the html documentation. However, when I upload it to a gitlab repository, and create a CI with a sphinxdoc/sphinx docker container, it does not find the build-in extensions (I use todo and ifconfig). The reason is that locally I use

import sys
sys.path.append(os.path.abspath('/home/scheider/.local/lib/python3.8/site-packages/sphinx/ext'))

in my conf.py in order to include the extensions, but I don't know what to use for the gitlab CI.

Sorry, if it is a stupid questions, but my knowledge about docker is very(!) limited.
Thanks in advance for any help
Ingo

I used the sphinxdoc/sphinx docker also locally and got the same error. Since I cannot work with the docker container interactively, I don't know how to get the respective path (and it seems that my google skills are minor as well...)


问:
How to print xPatch text in puppeteer
I'm a new user of puppeter to the point of understanding the basics, but I'm having trouble capturing an element with Xpath and saving that value in a .txt file

the first error that returns me is that the puppeteer could not find the xPath:
#Weird error TimeoutError: Waiting for selector /html/body/div/div[2]/div/div[3]/form/div[2]/div[2]/div/div[1]/div/ul /li failed: Waiting failed: 30000ms exceeded,

in my code, it detects an HTML element on the page saying SUCCESS OR FAIL, I'm stuck on this, I can't capture that element and save it with my code :(

The logic is the following. access my website, register, then the website redirects to a new link, after that it displays the success message on the screen.
I don't know if this is the best way to be saving and capturing this element.
if someone can review my codes and point out the error I appreciate it

`

```<code>  // RODANDO O CHROME E FAZENDO REQUISIÇAO AO SITE
  try {

    const page = (await browser.pages())[0];
    await page.setUserAgent('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.88 Safari/537.36')
    await page.setDefaultNavigationTimeout(0);
            function timer(ms){
                return new Promise(res => setTimeout(res, ms));
            }

      const response = await page.goto(`https://juntos.redevida.com.br/faca-parte/cartao-de-credito`, {
      });
      await timer(600);

      //ACEITAR COOKIES
      const a1= await page.waitForXPath(`/html/body/div[5]/div[2]`);
      await a1.click();

      //INSERIR VALOR
      const a2= await page.waitForXPath(`/html/body/section/div[2]/div/div[10]/div[3]/form/div[1]/div[2]/input`);
      await a2.click();
      await a2.type(`${valor}`)

      //MENSAL ou ANUAL
      const donate= await page.waitForXPath(`/html/body/section/div[2]/div/div[10]/div[3]/form/div[1]/ul/li[1]`);
      await donate.click();

      //INSERIR DADOS NA PAGINA
      const name= await page.waitForXPath(`/html/body/section/div[2]/div/div[10]/div[3]/form/div[2]/div[2]/input`);
      await name.click();
      await name.type(`${nome}`,)

      const mail= await page.waitForXPath(`/html/body/section/div[2]/div/div[10]/div[3]/form/div[2]/div[4]/input`);
      await mail.click();
      await mail.type(`${email}`,{delay: 100})

      const code= await page.waitForXPath(`/html/body/section/div[2]/div/div[10]/div[3]/form/div[2]/div[5]/div[2]/input`);
      await code.click();
      await code.type(`${cpf}`,{delay: 100})

      const fone= await page.waitForXPath(`/html/body/section/div[2]/div/div[10]/div[3]/form/div[2]/div[6]/div[2]/input`);
      await fone.click();
      await fone.type(`${telefone}`,)

      const zip= await page.waitForXPath(`/html/body/section/div[2]/div/div[10]/div[3]/form/div[2]/div[7]/div[2]/input`);
      await zip.click();
      await zip.type(`${cep}`,{delay: 100})

      const num= await page.waitForXPath(`/html/body/section/div[2]/div/div[10]/div[3]/form/div[2]/div[8]/div[2]/input`);
      await num.click();
      await num.type(`${casa}`)

      const nasc= await page.waitForXPath(`/html/body/section/div[2]/div/div[10]/div[3]/form/div[2]/div[14]/div[2]/input`);
      await nasc.click();
      await nasc.type(`${nascimento}`,{delay: 100})

      //CHECKBOX
      const a3= await page.waitForXPath(`/html/body/section/div[2]/div/div[10]/div[3]/form/div[2]/div[15]/input`);
      await a3.click();
      //AVANÇAR
      const a4= await page.waitForXPath(`/html/body/section/div[2]/div/div[10]/div[3]/form/div[2]/div[16]/input`);
      await a4.click();

      await page.waitForNavigation()

      //DADOS DA CC
      await page.waitForTimeout(18000);
      await page.keyboard.press('Tab');
      await page.keyboard.press('Tab');
      await page.keyboard.press('Tab');
      await page.keyboard.type(cc);
      await page.keyboard.press('Tab');
      await page.keyboard.type(nome);
      await page.keyboard.press('Tab');
      await page.keyboard.type(data);
      await page.keyboard.press('Tab');
      await page.keyboard.type(cvv);
      await page.keyboard.press('Tab');
      await page.keyboard.press('Tab');
      await page.keyboard.press('Enter');

      //PAGAMENTO NAO APROVADO
      await new Promise(r => setTimeout(r, 8000));
      let resultado = await page.evaluate(() => document.body.innerHTML)
      if(resultado.includes('negado')) {
      count++
      signale.error(`Testadas: [${count}] ==> ${cc}|${data}|${cvv} ${pagamento}- Live`)
      fs.appendFile('aprovada.txt', `${cc}|${data}|${cvv} ${pagamento} - Live\n`, function (err){});
      await browser.close();
      if (lista.length !== 0) init(lista.shift())
        return;
      }else{
      count++
      signale.error(`Testadas: [${count}] ==> ${cc}|${data}|${cvv} ${pagamento}- Die`)
      fs.appendFile('reprovada.txt', `${cc}|${data}|${cvv} ${pagamento} - Die\n`, function (err){});
      await browser.close();
      if (lista.length !== 0) init(lista.shift())
        return;
      }

} catch (e) {
console.error(`#Erro estranho ${e}`)
if (lista.length !== 0) init(lista.shift())
await browser.close();
}

}
</code>```

`

Title: How to print xPatch text in puppeteer

Body:
I'm a new user of puppeter to the point of understanding the basics, but I'm having trouble capturing an element with Xpath and saving that value in a .txt file

the first error that returns me is that the puppeteer could not find the xPath:
#Weird error TimeoutError: Waiting for selector /html/body/div/div[2]/div/div[3]/form/div[2]/div[2]/div/div[1]/div/ul /li failed: Waiting failed: 30000ms exceeded,

in my code, it detects an HTML element on the page saying SUCCESS OR FAIL, I'm stuck on this, I can't capture that element and save it with my code :(

The logic is the following. access my website, register, then the website redirects to a new link, after that it displays the success message on the screen.
I don't know if this is the best way to be saving and capturing this element.
if someone can review my codes and point out the error I appreciate it

`

  // RODANDO O CHROME E FAZENDO REQUISIÇAO AO SITE
  try {

    const page = (await browser.pages())[0];
    await page.setUserAgent('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.88 Safari/537.36')
    await page.setDefaultNavigationTimeout(0);
            function timer(ms){
                return new Promise(res => setTimeout(res, ms));
            }

      const response = await page.goto(`https://juntos.redevida.com.br/faca-parte/cartao-de-credito`, {
      });
      await timer(600);

      //ACEITAR COOKIES
      const a1= await page.waitForXPath(`/html/body/div[5]/div[2]`);
      await a1.click();

      //INSERIR VALOR
      const a2= await page.waitForXPath(`/html/body/section/div[2]/div/div[10]/div[3]/form/div[1]/div[2]/input`);
      await a2.click();
      await a2.type(`${valor}`)

      //MENSAL ou ANUAL
      const donate= await page.waitForXPath(`/html/body/section/div[2]/div/div[10]/div[3]/form/div[1]/ul/li[1]`);
      await donate.click();

      //INSERIR DADOS NA PAGINA
      const name= await page.waitForXPath(`/html/body/section/div[2]/div/div[10]/div[3]/form/div[2]/div[2]/input`);
      await name.click();
      await name.type(`${nome}`,)

      const mail= await page.waitForXPath(`/html/body/section/div[2]/div/div[10]/div[3]/form/div[2]/div[4]/input`);
      await mail.click();
      await mail.type(`${email}`,{delay: 100})

      const code= await page.waitForXPath(`/html/body/section/div[2]/div/div[10]/div[3]/form/div[2]/div[5]/div[2]/input`);
      await code.click();
      await code.type(`${cpf}`,{delay: 100})

      const fone= await page.waitForXPath(`/html/body/section/div[2]/div/div[10]/div[3]/form/div[2]/div[6]/div[2]/input`);
      await fone.click();
      await fone.type(`${telefone}`,)

      const zip= await page.waitForXPath(`/html/body/section/div[2]/div/div[10]/div[3]/form/div[2]/div[7]/div[2]/input`);
      await zip.click();
      await zip.type(`${cep}`,{delay: 100})

      const num= await page.waitForXPath(`/html/body/section/div[2]/div/div[10]/div[3]/form/div[2]/div[8]/div[2]/input`);
      await num.click();
      await num.type(`${casa}`)

      const nasc= await page.waitForXPath(`/html/body/section/div[2]/div/div[10]/div[3]/form/div[2]/div[14]/div[2]/input`);
      await nasc.click();
      await nasc.type(`${nascimento}`,{delay: 100})

      //CHECKBOX
      const a3= await page.waitForXPath(`/html/body/section/div[2]/div/div[10]/div[3]/form/div[2]/div[15]/input`);
      await a3.click();
      //AVANÇAR
      const a4= await page.waitForXPath(`/html/body/section/div[2]/div/div[10]/div[3]/form/div[2]/div[16]/input`);
      await a4.click();

      await page.waitForNavigation()

      //DADOS DA CC
      await page.waitForTimeout(18000);
      await page.keyboard.press('Tab');
      await page.keyboard.press('Tab');
      await page.keyboard.press('Tab');
      await page.keyboard.type(cc);
      await page.keyboard.press('Tab');
      await page.keyboard.type(nome);
      await page.keyboard.press('Tab');
      await page.keyboard.type(data);
      await page.keyboard.press('Tab');
      await page.keyboard.type(cvv);
      await page.keyboard.press('Tab');
      await page.keyboard.press('Tab');
      await page.keyboard.press('Enter');

      //PAGAMENTO NAO APROVADO
      await new Promise(r => setTimeout(r, 8000));
      let resultado = await page.evaluate(() => document.body.innerHTML)
      if(resultado.includes('negado')) {
      count++
      signale.error(`Testadas: [${count}] ==> ${cc}|${data}|${cvv} ${pagamento}- Live`)
      fs.appendFile('aprovada.txt', `${cc}|${data}|${cvv} ${pagamento} - Live\n`, function (err){});
      await browser.close();
      if (lista.length !== 0) init(lista.shift())
        return;
      }else{
      count++
      signale.error(`Testadas: [${count}] ==> ${cc}|${data}|${cvv} ${pagamento}- Die`)
      fs.appendFile('reprovada.txt', `${cc}|${data}|${cvv} ${pagamento} - Die\n`, function (err){});
      await browser.close();
      if (lista.length !== 0) init(lista.shift())
        return;
      }

} catch (e) {
console.error(`#Erro estranho ${e}`)
if (lista.length !== 0) init(lista.shift())
await browser.close();
}

}

`