问:
How to modify the tweet.created_at.date() within a for loop using Tweepy
I currently have a for loop which appends tweets to a list if they were created before 9:30am on a weekday, excluding holidays. I want to append a maximum of 100 tweets per day, and once those 100 tweets have been reached, I want to move on to the next day.
My for loop correctly recognizes when 100 tweets have been appended, and correctly switches to the next day once, but it is not updating the tweet.created_at.date() to the new day, so the correct tweets are not being appended after the first 100.
Any help at all would be amazing

```<code>day = datetime.now()
tweets_per_day = 0
# Iterate through the pages of results
all_tweets = []
for tweet in cursor.items(limit=500):
    current_day = day
    tweet_date = pd.to_datetime(tweet.created_at.date().strftime('%Y-%m-%d'))
    # Only add tweets which were made before market open on a weekends
    if tweet.created_at.time() < time(hour=9, minute=30) and current_day.weekday() < 5:
        # Do not add tweets if they were made on a holiday
        if not holiday_df['Date'].eq(tweet_date).any():
            tweets_per_day += 1
            if tweets_per_day <= 100:
                print(tweet.created_at.date())
                print(tweet.created_at.time())
                print(tweets_per_day)
                all_tweets.append(tweet.text)
            else:
                # Go page by page for efficiency
                for page in cursor.pages():
                    # Get the first tweet in the page
                    tweet = page[0]
                    if tweet.created_at.date() < current_day.date():
                        print(tweet.created_at.date())
                        all_tweets.append(tweet)  # This code is working, I do want to append the tweet
                        tweets_per_day = 0  # This code is working, I want to restart the tweets_per_day count
                        day -= timedelta(days=1)  # This code does not alter the day
                        break
                    # If the tweet's created_at date is the current day, continue the loop
                    else:
                        continue
</code>```

After correctly switching to the right date, I tried to store the tweet.created_at.date() in a current_day variable, and update that variable using -= datetime.timedelta(days=1), to shift the date backwards by 1. But this didnt work.

Body:
I currently have a for loop which appends tweets to a list if they were created before 9:30am on a weekday, excluding holidays. I want to append a maximum of 100 tweets per day, and once those 100 tweets have been reached, I want to move on to the next day.
My for loop correctly recognizes when 100 tweets have been appended, and correctly switches to the next day once, but it is not updating the tweet.created_at.date() to the new day, so the correct tweets are not being appended after the first 100.
Any help at all would be amazing

day = datetime.now()
tweets_per_day = 0
# Iterate through the pages of results
all_tweets = []
for tweet in cursor.items(limit=500):
    current_day = day
    tweet_date = pd.to_datetime(tweet.created_at.date().strftime('%Y-%m-%d'))
    # Only add tweets which were made before market open on a weekends
    if tweet.created_at.time() < time(hour=9, minute=30) and current_day.weekday() < 5:
        # Do not add tweets if they were made on a holiday
        if not holiday_df['Date'].eq(tweet_date).any():
            tweets_per_day += 1
            if tweets_per_day <= 100:
                print(tweet.created_at.date())
                print(tweet.created_at.time())
                print(tweets_per_day)
                all_tweets.append(tweet.text)
            else:
                # Go page by page for efficiency
                for page in cursor.pages():
                    # Get the first tweet in the page
                    tweet = page[0]
                    if tweet.created_at.date() < current_day.date():
                        print(tweet.created_at.date())
                        all_tweets.append(tweet)  # This code is working, I do want to append the tweet
                        tweets_per_day = 0  # This code is working, I want to restart the tweets_per_day count
                        day -= timedelta(days=1)  # This code does not alter the day
                        break
                    # If the tweet's created_at date is the current day, continue the loop
                    else:
                        continue

After correctly switching to the right date, I tried to store the tweet.created_at.date() in a current_day variable, and update that variable using -= datetime.timedelta(days=1), to shift the date backwards by 1. But this didnt work.


来源: stackexchange

问:
i want to create this type of custom expansion tile that allows one panel to be open at a time
```<code> onExpansionChanged: (value){
                                                        if(value) {
                                                          setState((){
                                                            selected = index;
                                                          });
                                                        }
                                                        else{
                                                          setState(() {
                                                            selected = -1;
                                                          });
                                                        }
                                                      },
</code>```

i am building a app in home page i want to dislay this list i want to create this type of custom expansion tile that allows one panel to be open at a time , i implement expansion tile but its not work perfect according to my need

ContentLicense: CC BY-SA 4.0

Body:
 onExpansionChanged: (value){
                                                        if(value) {
                                                          setState((){
                                                            selected = index;
                                                          });
                                                        }
                                                        else{
                                                          setState(() {
                                                            selected = -1;
                                                          });
                                                        }
                                                      },

i am building a app in home page i want to dislay this list i want to create this type of custom expansion tile that allows one panel to be open at a time , i implement expansion tile but its not work perfect according to my need


问:
Beat resolution in miditok library
I am working on a music generation problem and the first step towards training a model is to tokenize the MIDI file into tensors

Luckily I found a package Miditok to do it for me. But one parameter of it somehow bugs me out is the beat_res (or beat resolution).

In their example (and the default value in constants.py) the value is:

BEAT_RES = {(0, 4): 8, (4, 12): 4}

I got that the first 4 beats are quantized by 8 samples per beat, and the second 4 beats by 4 samples per beat.

How about the rest of the beats? By how many samples each of them is quantized?

Do they take the last given value (4 here) or there's a default one?

If the first option was the case, isn't it a bad design?

Thank you in advance.

Title: Beat resolution in miditok library


问:
Oracle SQL - how can I list infomation in the columns
Sorry, I can't understand how this can be done by reading a similar post. Can you pls reopen the question?

I'm trying to list for each counterparty their name, vendor no. and customer no. Similar to the table below

I wrote this SQL, which will have two rows for each counterparty and in the column value, it will have the Vendor no, and the Customer no. I want to have instead one row per counterparty and have the Vendor no, and the Customer no as separate columns.

 SELECT par.name
        ,inf.value
    FROM party_info inf
        ,party_info_types typ
        ,party par
    WHERE inf.type_id = typ.type_id
        AND inf.party_id = par.party_id
        AND typ.type_id IN (
            21185
            ,21186
            ) -- Vendor no / Customer no
```


问:
Expression error while trying to insert a JavaScript code into head section in Gatsby
I am trying to insert a JavaScript code snippet into the head section of the document but it's showing an expression error. I am using the Gatsby framework.

The code is

```<code><Helmet>
   <script>
      var _paq = window._paq = window._paq || [];
      _paq.push(["disableCookies"]);
      _paq.push(['trackPageView']);
      _paq.push(['enableLinkTracking']);
      (function() {
         var u="SITELINK"; //Error is on var
         _paq.push(['setTrackerUrl', u+'matomo.php']);
         _paq.push(['setSiteId', 'SITEID']);
         var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0];
         g.async=true; g.src=u+'matomo.js'; s.parentNode.insertBefore(g,s);
      })(); //Error is on closing curly bracket
  </script>
</Helmet>
</code>```

And the errors are on

"var" - "Expression expected just after the function() declared

Closing curly bracket of the function()

I have checked for any junk characters but it's clean.

Body:
I am trying to insert a JavaScript code snippet into the head section of the document but it's showing an expression error. I am using the Gatsby framework.

The code is

<Helmet>

</Helmet>

And the errors are on

"var" - "Expression expected just after the function() declared

Closing curly bracket of the function()

I have checked for any junk characters but it's clean.


问:
Should I add array to collection or seperate them
I'm using MongoDB with NodeJS (express) and mongoose for my SPA.

I have a collection apps that contains multiple app documents. Those apps have categories like A, B or C for example. I want to add an array of all possible categories to be in the collection apps.

Is something like this recommended or better to separate them:

```<code>collection apps:
{
allCategories: [ 'A', 'B', 'C' ],
apps: [
  {
    name: 'first app'
    category: [ 'A', 'C']
   },
   {
    name: 'second app'
    category: ['C']
   },
}
</code>```

Now i have it split in two collections:

apps collection that contains the app documents, no array or whatever specified just multiple apps

categories collection with an array of possible categories.

What is the best practice? What is better to do? Separate them like i have now or put them together as they are linked?

How should i do that with mongoose? I don't want all the categories to be stored in every document.

I know Mongo recommends using embedded documents but my case is slightly different .

Body:
I'm using MongoDB with NodeJS (express) and mongoose for my SPA.

I have a collection apps that contains multiple app documents. Those apps have categories like A, B or C for example. I want to add an array of all possible categories to be in the collection apps.

Is something like this recommended or better to separate them:

collection apps:
{
allCategories: [ 'A', 'B', 'C' ],
apps: [
  {
    name: 'first app'
    category: [ 'A', 'C']
   },
   {
    name: 'second app'
    category: ['C']
   },
}

Now i have it split in two collections:

apps collection that contains the app documents, no array or whatever specified just multiple apps

categories collection with an array of possible categories.

What is the best practice? What is better to do? Separate them like i have now or put them together as they are linked?

How should i do that with mongoose? I don't want all the categories to be stored in every document.

I know Mongo recommends using embedded documents but my case is slightly different .


问:
We retriever data and sending a data into database, but its not working
Actually, i create a for loop
(for _, data := range b.CabinBookingRecords )
*, for the pointing array of *CabinBookingRecords *. from this object we retrieving data and sending a data into a data base ,But its not working ,yaa that's it. ***

I'm trying that, pointing bcabinbooking *,In that im using array of pointer *CabinBookingRecords []CabinBookingDetails in this we create a struct CabinBookingDetails in this we create many objects. Problem is their controllers not goes to for loop i think for loop getting something wrong

func (b *CabinBooking) UpdateCabinBooking(id int16, id1 int16) error {
dt := time.Now()

```<code>for _, data := range b.CabinBookingRecords {

    cBD := new(CabinBookingDetails)
    cBD.CityId = data.CityId
    cBD.BuildingId = data.BuildingId
    cBD.FloorId = data.FloorId
    cBD.CabinBookingId = data.CabinBookingId
    cBD.CabinId = data.CabinId
    cBD.BookingDate = data.BookingDate
    cBD.BookedBy = data.BookedBy
    cBD.BookingSlot = data.BookingSlot
    cBD.BookingSlotHrs = data.BookingSlotHrs
    cBD.CancelledBy = data.CancelledBy
    cBD.Active = data.Active

    fmt.Println(id, "   cabinBookingId", id1, "cabinBookingDetailsId", "   slot", cBD.BookingSlot, cBD.BookingSlotHrs)

    query := "UPDATE cabin_booking_details SET city_id=$1, building_id=$2, floor_id=$3, cabin_id=$4,booking_date=$5, booked_by=$6, booking_slot=$7,booking_slot_hrs=$8, updated_at=$9 WHERE id=$10 AND cabin_booking_id = $11"
    d := migration.DbPool.QueryRow(
        context.Background(), query, cBD.CityId, cBD.BuildingId, cBD.FloorId, cBD.CabinId, cBD.BookingDate, cBD.BookedBy, cBD.BookingSlot, cBD.BookingSlotHrs, dt, id1, id,
    )
    err := d.Scan(&b.Id, &b.CreatedAt, &b.UpdatedAt)
    if err != nil {
        return err
    }
}
return nil
</code>```

}`

```<code>
func UpdateCabinBooking(c *fiber.Ctx) error {

    id := c.Query("cabin_booking_id")
    id1 := c.Query("id") //cabin_booking_details_id

    i, e := strconv.Atoi(id)
    j, e1 := strconv.Atoi(id1)

    if e != nil || e1 != nil {
        return c.Status(400).SendString(e.Error())
    }

    cabinBookingId := int16(i)
    cabinBookingDetailsId := int16(j)

    workspaceParams := new(model.CabinBooking)

    workspaceParams.UpdateCabinBooking(cabinBookingId, cabinBookingDetailsId)
    fmt.Println("working")
    if err := c.JSON(&fiber.Map{
        "success": true,
        "message": "Cabin Booking successfully updated",
    }); err != nil {
        return utility.ErrResponse(c, "Error in response", 500, err)
    }
    return nil
}

and this router......

api.Put("/cabin_workspace", func(c *fiber.Ctx) error {
        user := c.Locals("verify")
        if user == "true" {
            return controller.UpdateCabinBooking(c)
        }
        return c.SendStatus(fiber.StatusForbidden)
    })

type CabinBooking struct {
    Id                  int16                  `json:"id"`
    BookingDates        []string               `json:"booking_dates"`
    CabinBookingRecords []*CabinBookingDetails `json:"cabin_booking_records"`
    Active              bool                   `json:"active"`
    BookedBy            int16                  `json:"booked_by"`    //userID
    CancelledBy         int16                  `json:"cancelled_by"` //userID
    CreatedAt           time.Time              `json:"created_at"`
    UpdatedAt           time.Time              `json:"updated_at"`
}

type CabinBookingDetails struct {
    Id             int16     `json:"id"`
    CabinBookingId int16     `json:"cabin_booking_id"`
    CabinId        int16     `json:"cabin_id"`
    CityId         int16     `json:"city_id"`
    BuildingId     int16     `json:"building_id"`
    FloorId        int16     `json:"floor_id"`
    BookingDate    string    `json:"booking_date"`
    BookedBy       int16     `json:"booked_by"`    //userID
    CancelledBy    int16     `json:"cancelled_by"` //userID
    BookingSlot    string    `json:"booking_slot"`
    BookingSlotHrs int16     `json:"booking_slot_hrs"`
    Active         bool      `json:"active"`
    CreatedAt      time.Time `json:"created_at"`
    UpdatedAt      time.Time `json:"updated_at"`
}

we sending(retrieving) input from postman(api testing),  but update the data base:-

{

"booking_dates": ["2022-12-30",
               "2022-12-31",
            "2022-12-27"
            ],
    "cabin_booking_records" : [
       {
    "booking_date": "2022-12-30",
        "cabin_id": 1,
        "city_id": 1,
        "building_id" : 1,
        "floor_id" : 1,
        "booking_slot": "First_half",
        "booking_slot_hrs":4,
        "active" : true,
        "booked_by" : 5,
        "canceled_by" : 0
        }
    ],
      "active" : true,
       "booked_by" : 5,
        "canceled_by" : 0
}
</code>```

Body:
Actually, i create a for loop
(for _, data := range b.CabinBookingRecords )
*, for the pointing array of *CabinBookingRecords *. from this object we retrieving data and sending a data into a data base ,But its not working ,yaa that's it. ***

I'm trying that, pointing bcabinbooking *,In that im using array of pointer *CabinBookingRecords []CabinBookingDetails in this we create a struct CabinBookingDetails in this we create many objects. Problem is their controllers not goes to for loop i think for loop getting something wrong

func (b *CabinBooking) UpdateCabinBooking(id int16, id1 int16) error {
dt := time.Now()

for _, data := range b.CabinBookingRecords {

    cBD := new(CabinBookingDetails)
    cBD.CityId = data.CityId
    cBD.BuildingId = data.BuildingId
    cBD.FloorId = data.FloorId
    cBD.CabinBookingId = data.CabinBookingId
    cBD.CabinId = data.CabinId
    cBD.BookingDate = data.BookingDate
    cBD.BookedBy = data.BookedBy
    cBD.BookingSlot = data.BookingSlot
    cBD.BookingSlotHrs = data.BookingSlotHrs
    cBD.CancelledBy = data.CancelledBy
    cBD.Active = data.Active

    fmt.Println(id, "   cabinBookingId", id1, "cabinBookingDetailsId", "   slot", cBD.BookingSlot, cBD.BookingSlotHrs)

    query := "UPDATE cabin_booking_details SET city_id=$1, building_id=$2, floor_id=$3, cabin_id=$4,booking_date=$5, booked_by=$6, booking_slot=$7,booking_slot_hrs=$8, updated_at=$9 WHERE id=$10 AND cabin_booking_id = $11"
    d := migration.DbPool.QueryRow(
        context.Background(), query, cBD.CityId, cBD.BuildingId, cBD.FloorId, cBD.CabinId, cBD.BookingDate, cBD.BookedBy, cBD.BookingSlot, cBD.BookingSlotHrs, dt, id1, id,
    )
    err := d.Scan(&b.Id, &b.CreatedAt, &b.UpdatedAt)
    if err != nil {
        return err
    }
}
return nil

}`

func UpdateCabinBooking(c *fiber.Ctx) error {

    id := c.Query("cabin_booking_id")
    id1 := c.Query("id") //cabin_booking_details_id

    i, e := strconv.Atoi(id)
    j, e1 := strconv.Atoi(id1)

    if e != nil || e1 != nil {
        return c.Status(400).SendString(e.Error())
    }

    cabinBookingId := int16(i)
    cabinBookingDetailsId := int16(j)

    workspaceParams := new(model.CabinBooking)

    workspaceParams.UpdateCabinBooking(cabinBookingId, cabinBookingDetailsId)
    fmt.Println("working")
    if err := c.JSON(&fiber.Map{
        "success": true,
        "message": "Cabin Booking successfully updated",
    }); err != nil {
        return utility.ErrResponse(c, "Error in response", 500, err)
    }
    return nil
}

and this router......

api.Put("/cabin_workspace", func(c *fiber.Ctx) error {
        user := c.Locals("verify")
        if user == "true" {
            return controller.UpdateCabinBooking(c)
        }
        return c.SendStatus(fiber.StatusForbidden)
    })

type CabinBooking struct {
    Id                  int16                  `json:"id"`
    BookingDates        []string               `json:"booking_dates"`
    CabinBookingRecords []*CabinBookingDetails `json:"cabin_booking_records"`
    Active              bool                   `json:"active"`
    BookedBy            int16                  `json:"booked_by"`    //userID
    CancelledBy         int16                  `json:"cancelled_by"` //userID
    CreatedAt           time.Time              `json:"created_at"`
    UpdatedAt           time.Time              `json:"updated_at"`
}

type CabinBookingDetails struct {
    Id             int16     `json:"id"`
    CabinBookingId int16     `json:"cabin_booking_id"`
    CabinId        int16     `json:"cabin_id"`
    CityId         int16     `json:"city_id"`
    BuildingId     int16     `json:"building_id"`
    FloorId        int16     `json:"floor_id"`
    BookingDate    string    `json:"booking_date"`
    BookedBy       int16     `json:"booked_by"`    //userID
    CancelledBy    int16     `json:"cancelled_by"` //userID
    BookingSlot    string    `json:"booking_slot"`
    BookingSlotHrs int16     `json:"booking_slot_hrs"`
    Active         bool      `json:"active"`
    CreatedAt      time.Time `json:"created_at"`
    UpdatedAt      time.Time `json:"updated_at"`
}

we sending(retrieving) input from postman(api testing),  but update the data base:-

{

"booking_dates": ["2022-12-30",
               "2022-12-31",
            "2022-12-27"
            ],
    "cabin_booking_records" : [
       {
    "booking_date": "2022-12-30",
        "cabin_id": 1,
        "city_id": 1,
        "building_id" : 1,
        "floor_id" : 1,
        "booking_slot": "First_half",
        "booking_slot_hrs":4,
        "active" : true,
        "booked_by" : 5,
        "canceled_by" : 0
        }
    ],
      "active" : true,
       "booked_by" : 5,
        "canceled_by" : 0
}


问:
CORS with Flask, axios and https not working (response header sends origin as http instead of https)
My frontend (Expo Go web) is running at http://localhost:19006/ but when it receives a response from the backend, it somehow believes it runs under https://localhost:19006/

Also, the iOS version of Expo Go logs the following error:

LOG  [AxiosError: Network Error]

I'm using Flask in the backend with CORS set as follows:

```<code>app = Flask(__name__)
app.config['DEBUG'] = True
app.config['CORS_HEADERS'] = 'Content-Type'
app.config['SECRET_KEY'] = os.environ.get("SECRET_KEY", 'xxx')

cors = CORS(app, resources={r"/*": {"origins": "*", "allow_headers": "*", "expose_headers": "*", "Access-Control-Allow-Origin": "*"}})
</code>```

and a simple return function:

```<code>@app.route("/matches", methods=["GET"])
def getMatches():
    print('request for matches')
    response = matches.getMatches()
    return response

if __name__ == '__main__':
    app.run(ssl_context=('certs/cert.pem', 'certs/key.pem'))
</code>```

My frontend part is using react native with Expo Go. The query to the backend is done this way:

```<code>export default function App() {

   const axiosApiCall = () => {

    const config = {
      headers:{
        'origin': 'https://localhost:19006' #<- Here also tried http but no change
      }
    };

 axios
  .get("https://127.0.0.1:5000/matches", config)
  .then((response) => {

      setState({quote : 'yes'});
      console.log(response.data);
    })
    .catch((error) => {
      console.log(error);
    })
}
</code>```

The backend works properly fine as I can see in Postman. The result is technically showing up in the response of the web-version of Expo Go, however, it appears that there's an issue with CORS:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://127.0.0.1:5000/matches. (Reason: CORS header ‘Access-Control-Allow-Origin’ does not match ‘https://localhost:19006’).

And here's the response header:

HTTP/1.1 200 OK

Server: Werkzeug/2.2.2 Python/3.9.16

Date: Thu, 05 Jan 2023 10:16:42 GMT

Content-Type: application/json

Content-Length: 274552

Access-Control-Allow-Origin: http://localhost:19006

Access-Control-Expose-Headers: *

Vary: Origin

Connection: close

GET /matches HTTP/1.1

Host: 127.0.0.1:5000

User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:108.0) Gecko/20100101 Firefox/108.0

Accept: application/json, text/plain, */*

Accept-Language: en-US,en;q=0.5

Accept-Encoding: gzip, deflate, br

Origin: http://localhost:19006

DNT: 1

Connection: keep-alive

Referer: http://localhost:19006/

Sec-Fetch-Dest: empty

Sec-Fetch-Mode: cors

Sec-Fetch-Site: cross-site

Sec-GPC: 1

Anyone any idea? Thanks!!!

Hardcoding the CORS origins: no change

Changing the query from axios to async fetch calls: no change

Including/modifying the header in the axios config: no change

Other browsers: no change

Deactivating SSL in the backend: caused other problems related to react native

Body:
My frontend (Expo Go web) is running at http://localhost:19006/ but when it receives a response from the backend, it somehow believes it runs under https://localhost:19006/

Also, the iOS version of Expo Go logs the following error:

LOG  [AxiosError: Network Error]

I'm using Flask in the backend with CORS set as follows:

app = Flask(__name__)
app.config['DEBUG'] = True
app.config['CORS_HEADERS'] = 'Content-Type'
app.config['SECRET_KEY'] = os.environ.get("SECRET_KEY", 'xxx')

cors = CORS(app, resources={r"/*": {"origins": "*", "allow_headers": "*", "expose_headers": "*", "Access-Control-Allow-Origin": "*"}})

and a simple return function:

@app.route("/matches", methods=["GET"])
def getMatches():
    print('request for matches')
    response = matches.getMatches()
    return response

if __name__ == '__main__':
    app.run(ssl_context=('certs/cert.pem', 'certs/key.pem'))

My frontend part is using react native with Expo Go. The query to the backend is done this way:

export default function App() {

   const axiosApiCall = () => {

    const config = {
      headers:{
        'origin': 'https://localhost:19006' #<- Here also tried http but no change
      }
    };

 axios
  .get("https://127.0.0.1:5000/matches", config)
  .then((response) => {

      setState({quote : 'yes'});
      console.log(response.data);
    })
    .catch((error) => {
      console.log(error);
    })
}

The backend works properly fine as I can see in Postman. The result is technically showing up in the response of the web-version of Expo Go, however, it appears that there's an issue with CORS:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://127.0.0.1:5000/matches. (Reason: CORS header ‘Access-Control-Allow-Origin’ does not match ‘https://localhost:19006’).

And here's the response header:

HTTP/1.1 200 OK

Server: Werkzeug/2.2.2 Python/3.9.16

Date: Thu, 05 Jan 2023 10:16:42 GMT

Content-Type: application/json

Content-Length: 274552

Access-Control-Allow-Origin: http://localhost:19006

Access-Control-Expose-Headers: *

Vary: Origin

Connection: close

GET /matches HTTP/1.1

Host: 127.0.0.1:5000

User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:108.0) Gecko/20100101 Firefox/108.0

Accept: application/json, text/plain, */*

Accept-Language: en-US,en;q=0.5

Accept-Encoding: gzip, deflate, br

Origin: http://localhost:19006

DNT: 1

Connection: keep-alive

Referer: http://localhost:19006/

Sec-Fetch-Dest: empty

Sec-Fetch-Mode: cors

Sec-Fetch-Site: cross-site

Sec-GPC: 1

Anyone any idea? Thanks!!!

Hardcoding the CORS origins: no change

Changing the query from axios to async fetch calls: no change

Including/modifying the header in the axios config: no change

Other browsers: no change

Deactivating SSL in the backend: caused other problems related to react native


问:
how to make table of sale that sale for then one item in one transaction mysql
Is there a way to make a column that can have multiple value of id from one table. I want to create a transaction table where user can buy multiple items in one transaction receipt. Iam using MySQL

this is how my current table are

tbl_transaction

```<code>id_transaction int auto_increment
id_customer int
product (i dont know the type?)
total_transaction varchar(20)
</code>```

tbl_product

```<code>id_product int auto_increment
product_name varchar(40)
price varchar(20)
</code>```

so when a customer choose one or more item the id_product can be save in product from table tbl_transaction

Body:
Is there a way to make a column that can have multiple value of id from one table. I want to create a transaction table where user can buy multiple items in one transaction receipt. Iam using MySQL

this is how my current table are

tbl_transaction

id_transaction int auto_increment
id_customer int
product (i dont know the type?)
total_transaction varchar(20)

tbl_product

id_product int auto_increment
product_name varchar(40)
price varchar(20)

so when a customer choose one or more item the id_product can be save in product from table tbl_transaction


问:
SSRS Auto Subcription Creation Default Values not binding
We are migrating our project SSRS 2013 Sharepoint Integration Mode to SSRS 2019 Native Mode. All .RDL Files are migrated including default values for Few parameters.
Those parameters would be loaded based on cascaded drop down but we want default value -1 to be selected in the subscription

When we create subscription from our c# code reportingService.CreateDataDrivenSubscription subscription is sucessful for all parameters except the one with Default Values.
These Parameters are ParameterValue & others are ParamterReferenceField.
The subscription is unable to populate the choose default values. The question is not related to .rdl file having default values, the error is only in Subscription that we are creating using reporting service .asmx

In createDataDrivenSubcription function we are setting parameter Value in reportParameters but not working

is there any other way to call the above function so that in the subscription created we would

Enter Default Value in the drop down similar to Get Value from Dataset automatically.


问:
Sudo apt-get install commands with Jenkins
I have a jenkins server open and I'm attempting to sudo install:

```<code>sudo apt-get install libsqlite3-dev
</code>```

Because I am using a pipeline that runs a python script, whereby this script would return the following error:

builtins.ModuleNotFoundError: No module named '_sqlite3'

Online articles have suggested to sudo install the package above. However, I would need root-privileges to do so.

I have installed the ssh-server plugin within jenkins and jenkins-cli.jar, is there a way to install the package with any of these two options, or an easier alternative?

Body:
I have a jenkins server open and I'm attempting to sudo install:

sudo apt-get install libsqlite3-dev

Because I am using a pipeline that runs a python script, whereby this script would return the following error:

builtins.ModuleNotFoundError: No module named '_sqlite3'

Online articles have suggested to sudo install the package above. However, I would need root-privileges to do so.

I have installed the ssh-server plugin within jenkins and jenkins-cli.jar, is there a way to install the package with any of these two options, or an easier alternative?


问:
Why is my vue development server not updating after a change?
First post so don't roast me too hard.

I am running a development server for my Vue app with npm run serve. The server takes several minutes to start and build. I read online that my changes should reload the server, this is not the case. I am new to Vue and npm so I am not sure what to do.

Here is what my terminal says:

```<code>npm run serve

> myapp@0.1.0 serve
> vue-cli-service serve --host localhost

 INFO  Starting development server...

 DONE  Compiled successfully in 103891ms                                                                            3:30:58 AM

  App running at:
  - Local:   http://localhost:8080/
  - Network: http://localhost:8080/

  Note that the development build is not optimized.
  To create a production build, run npm run build.
</code>```

And here is my package.json

```<code>{
  "name": "myapp",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "serve": "vue-cli-service serve --host localhost",
    "build": "vue-cli-service build",
    "lint": "vue-cli-service lint"
  },
  "dependencies": {
    "core-js": "^3.8.3",
    "vue": "^3.2.13"
  },
  "devDependencies": {
    "@babel/core": "^7.12.16",
    "@babel/eslint-parser": "^7.12.16",
    "@vue/cli-plugin-babel": "~5.0.0",
    "@vue/cli-plugin-eslint": "~5.0.0",
    "@vue/cli-service": "~5.0.0",
    "eslint": "^7.32.0",
    "eslint-plugin-vue": "^8.0.3"
  },
  "eslintConfig": {
    "root": true,
    "env": {
      "node": true
    },
    "extends": [
      "plugin:vue/vue3-essential",
      "eslint:recommended"
    ],
    "parserOptions": {
      "parser": "@babel/eslint-parser"
    },
    "rules": {}
  },
  "browserslist": [
    "> 1%",
    "last 2 versions",
    "not dead",
    "not ie 11"
  ]
}
</code>```

I tried the solutions on this post but nothing worked.

Anyone have any ideas?

Update

Got it to work much faster by switching from working in the windows file system to the Linux one.

Body:
First post so don't roast me too hard.

I am running a development server for my Vue app with npm run serve. The server takes several minutes to start and build. I read online that my changes should reload the server, this is not the case. I am new to Vue and npm so I am not sure what to do.

Here is what my terminal says:

npm run serve

> myapp@0.1.0 serve
> vue-cli-service serve --host localhost

 INFO  Starting development server...

 DONE  Compiled successfully in 103891ms                                                                            3:30:58 AM

  App running at:
  - Local:   http://localhost:8080/
  - Network: http://localhost:8080/

  Note that the development build is not optimized.
  To create a production build, run npm run build.

And here is my package.json

{
  "name": "myapp",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "serve": "vue-cli-service serve --host localhost",
    "build": "vue-cli-service build",
    "lint": "vue-cli-service lint"
  },
  "dependencies": {
    "core-js": "^3.8.3",
    "vue": "^3.2.13"
  },
  "devDependencies": {
    "@babel/core": "^7.12.16",
    "@babel/eslint-parser": "^7.12.16",
    "@vue/cli-plugin-babel": "~5.0.0",
    "@vue/cli-plugin-eslint": "~5.0.0",
    "@vue/cli-service": "~5.0.0",
    "eslint": "^7.32.0",
    "eslint-plugin-vue": "^8.0.3"
  },
  "eslintConfig": {
    "root": true,
    "env": {
      "node": true
    },
    "extends": [
      "plugin:vue/vue3-essential",
      "eslint:recommended"
    ],
    "parserOptions": {
      "parser": "@babel/eslint-parser"
    },
    "rules": {}
  },
  "browserslist": [
    "> 1%",
    "last 2 versions",
    "not dead",
    "not ie 11"
  ]
}

I tried the solutions on this post but nothing worked.

Anyone have any ideas?

Update

Got it to work much faster by switching from working in the windows file system to the Linux one.


问:
GL_INVALID_OPERAION in glDrawElements while rendering to Framebuffer from external texture
I am trying to render the contents of an external texture (which gets its data from android MediaCodec) to a framebuffer with a texture atttachment (first pass) and then using that texture to render to display (second pass)

My overall goal is to do some operation in the shader in the first pass and some more operation in the second pass. But I am getting GL_INVALID_OPERAION in the first pass and hence texture associated with the Framebuffer is not populated.

Below is the summary of the code

OpenGL environment initialization

```<code>
GLES20.glGenFramebuffers(1,frameBufferHandles,0);

GLES20.glGenBuffers(2, bufferHandles, 0);
GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, bufferHandles[0]);
GLES20.glBufferData(GLES20.GL_ARRAY_BUFFER, Utils.VERTICES.length * FLOAT_SIZE_BYTES, Utils.getVertexBuffer(), GLES20.GL_DYNAMIC_DRAW);
GLES20.glBindBuffer(GLES20.GL_ELEMENT_ARRAY_BUFFER, bufferHandles[1]);
GLES20.glBufferData(GLES20.GL_ELEMENT_ARRAY_BUFFER, Utils.INDICES.length * FLOAT_SIZE_BYTES, Utils.getIndicesBuffer(), GLES20.GL_DYNAMIC_DRAW);

GLES20.glGenTextures(2, textureHandles, 0);

GLES20.glBindTexture(GL_TEXTURE_EXTERNAL_OES, textureHandles[0]);
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR);
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR);
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE);
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE);
GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER,frameBufferHandles[0]);

GLES20.glActiveTexture(GLES20.GL_TEXTURE2);
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textureHandles[1]);
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR);
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR);
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE);
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE);
GLES20.glTexImage2D(GLES20.GL_TEXTURE_2D,0,GLES20.GL_RGBA,width,height,0,GLES20.GL_RGBA,GLES20.GL_UNSIGNED_BYTE,null); //width.height are of that viewport and are initialized properly
GLES20.glFramebufferTexture2D(GLES20.GL_FRAMEBUFFER,GLES20.GL_COLOR_ATTACHMENT0,GLES20.GL_TEXTURE_2D,textureHandles[1],0);

int status = GLES20.glCheckFramebufferStatus(GLES20.GL_FRAMEBUFFER);
if(status != GLES20.GL_FRAMEBUFFER_COMPLETE) {
    Log.d(TAG,"Frame Buffer Incomplete : " + status);
} else
    Log.d(TAG,"Frame Buffer Complete");

GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER,0);
</code>```

Vertex Shader setup

```<code>public static final String DEFAULT_VERTEX_SHADER = "uniform mat4 uMVPMatrix;\n"
        + "uniform mat4 uSTMatrix;\n"
        + "attribute vec4 aPosition;\n"
        + "attribute vec4 aTextureCoord;\n"
        + "varying vec2 vTextureCoord;\n"
        + "void main() {\n"
        + "  gl_Position = uMVPMatrix * aPosition;\n"
        + "  vTextureCoord = (uSTMatrix * aTextureCoord).xy;\n"
        + "}\n";
</code>```

Fragment shader setup

```<code>#extension GL_OES_EGL_image_external : require
precision mediump float;
varying vec2 vTextureCoord;
uniform samplerExternalOES sTexture;
uniform sampler2D sTextureSampler;
uniform float r;
uniform int pass;

void main() {
        if(pass == 0) {
            gl_FragColor = texture2D(sTexture, vTextureCoord);
            //gl_FragColor = vec4(1.0,1.0,0.0,1.0);
         }
        else if(pass == 1) {
            gl_FragColor = texture2D(sTextureSampler, vTextureCoord);
         }
}
</code>```

Vertex Attributes and Index buffer are defined like below

```<code>public static float[] VERTICES = {
        -1.0f, -1.0f, 0.0f, 0f, 0f,
        -1.0f,  1.0f, 0.0f, 0f, 1f,
         1.0f,  1.0f, 0.0f, 1f, 1f,
         1.0f, -1.0f, 0.0f, 1f, 0f
};

public static int[] INDICES = {
        2, 1, 0, 0, 3, 2
};
</code>```

And finally my draw() function looks like this

```<code>protected void draw() {
    Matrix.setIdentityM(mvpMatrix, 0);

    if(mProgram != -1)
        mProgram = createProgram();

    int vertexHandle = GLES20.glGetAttribLocation(mProgram, "aPosition");
    int uvsHandle = GLES20.glGetAttribLocation(mProgram, "aTextureCoord");
    int texMatrixHandle = GLES20.glGetUniformLocation(mProgram, "uSTMatrix");
    int mvpMatrixHandle = GLES20.glGetUniformLocation(mProgram, "uMVPMatrix");

    int textureHandle = GLES20.glGetUniformLocation(mProgram, "sTextureSampler");

    int pass = GLES20.glGetUniformLocation(mProgram, "pass");

    GLES20.glUseProgram(mProgram);
    GLES20.glUniformMatrix4fv(texMatrixHandle, 1, false, texMatrix, 0);
    GLES20.glUniformMatrix4fv(mvpMatrixHandle, 1, false, mvpMatrix, 0);

    GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, bufferHandles[0]);
    GLES20.glBindBuffer(GLES20.GL_ELEMENT_ARRAY_BUFFER, bufferHandles[1]);
    GLES20.glEnableVertexAttribArray(vertexHandle);
    GLES20.glVertexAttribPointer(vertexHandle, 3, GLES20.GL_FLOAT, false, 4 * 5, 0);
    GLES20.glEnableVertexAttribArray(uvsHandle);
    GLES20.glVertexAttribPointer(uvsHandle, 2, GLES20.GL_FLOAT, false, 4 * 5, 3 * 4);

    //Pass 0 - Render to framebuffer , gives GL_INVALID_OPERAION error
    GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER,frameBufferHandles[0]);
    GLES20.glUniform1i(pass, 0);
    GLES20.glDrawElements(GLES20.GL_TRIANGLES, 6, GLES20.GL_UNSIGNED_INT, 0);

    //Pass 1 - Render to display
    GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER,0);
    GLES20.glUniform1i(textureHandle, 2);
    GLES20.glUniform1i(pass, 1);
    GLES20.glDrawElements(GLES20.GL_TRIANGLES, 6, GLES20.GL_UNSIGNED_INT, 0);

}
</code>```

I am guessing it is related to vTextureCoord, because if I dont use  vTextureCoord and render a constant color to the framebuffer during first pass , then I can read it back during the second pass from the texture associated with the framebuffer.

Body:
I am trying to render the contents of an external texture (which gets its data from android MediaCodec) to a framebuffer with a texture atttachment (first pass) and then using that texture to render to display (second pass)

My overall goal is to do some operation in the shader in the first pass and some more operation in the second pass. But I am getting GL_INVALID_OPERAION in the first pass and hence texture associated with the Framebuffer is not populated.

Below is the summary of the code

OpenGL environment initialization

GLES20.glGenFramebuffers(1,frameBufferHandles,0);

GLES20.glGenBuffers(2, bufferHandles, 0);
GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, bufferHandles[0]);
GLES20.glBufferData(GLES20.GL_ARRAY_BUFFER, Utils.VERTICES.length * FLOAT_SIZE_BYTES, Utils.getVertexBuffer(), GLES20.GL_DYNAMIC_DRAW);
GLES20.glBindBuffer(GLES20.GL_ELEMENT_ARRAY_BUFFER, bufferHandles[1]);
GLES20.glBufferData(GLES20.GL_ELEMENT_ARRAY_BUFFER, Utils.INDICES.length * FLOAT_SIZE_BYTES, Utils.getIndicesBuffer(), GLES20.GL_DYNAMIC_DRAW);

GLES20.glGenTextures(2, textureHandles, 0);

GLES20.glBindTexture(GL_TEXTURE_EXTERNAL_OES, textureHandles[0]);
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR);
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR);
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE);
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE);
GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER,frameBufferHandles[0]);

GLES20.glActiveTexture(GLES20.GL_TEXTURE2);
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textureHandles[1]);
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR);
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR);
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE);
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE);
GLES20.glTexImage2D(GLES20.GL_TEXTURE_2D,0,GLES20.GL_RGBA,width,height,0,GLES20.GL_RGBA,GLES20.GL_UNSIGNED_BYTE,null); //width.height are of that viewport and are initialized properly
GLES20.glFramebufferTexture2D(GLES20.GL_FRAMEBUFFER,GLES20.GL_COLOR_ATTACHMENT0,GLES20.GL_TEXTURE_2D,textureHandles[1],0);

int status = GLES20.glCheckFramebufferStatus(GLES20.GL_FRAMEBUFFER);
if(status != GLES20.GL_FRAMEBUFFER_COMPLETE) {
    Log.d(TAG,"Frame Buffer Incomplete : " + status);
} else
    Log.d(TAG,"Frame Buffer Complete");

GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER,0);

Vertex Shader setup

public static final String DEFAULT_VERTEX_SHADER = "uniform mat4 uMVPMatrix;\n"
        + "uniform mat4 uSTMatrix;\n"
        + "attribute vec4 aPosition;\n"
        + "attribute vec4 aTextureCoord;\n"
        + "varying vec2 vTextureCoord;\n"
        + "void main() {\n"
        + "  gl_Position = uMVPMatrix * aPosition;\n"
        + "  vTextureCoord = (uSTMatrix * aTextureCoord).xy;\n"
        + "}\n";

Fragment shader setup

#extension GL_OES_EGL_image_external : require
precision mediump float;
varying vec2 vTextureCoord;
uniform samplerExternalOES sTexture;
uniform sampler2D sTextureSampler;
uniform float r;
uniform int pass;

void main() {
        if(pass == 0) {
            gl_FragColor = texture2D(sTexture, vTextureCoord);
            //gl_FragColor = vec4(1.0,1.0,0.0,1.0);
         }
        else if(pass == 1) {
            gl_FragColor = texture2D(sTextureSampler, vTextureCoord);
         }
}

Vertex Attributes and Index buffer are defined like below

public static float[] VERTICES = {
        -1.0f, -1.0f, 0.0f, 0f, 0f,
        -1.0f,  1.0f, 0.0f, 0f, 1f,
         1.0f,  1.0f, 0.0f, 1f, 1f,
         1.0f, -1.0f, 0.0f, 1f, 0f
};

public static int[] INDICES = {
        2, 1, 0, 0, 3, 2
};

And finally my draw() function looks like this

protected void draw() {
    Matrix.setIdentityM(mvpMatrix, 0);

    if(mProgram != -1)
        mProgram = createProgram();

    int vertexHandle = GLES20.glGetAttribLocation(mProgram, "aPosition");
    int uvsHandle = GLES20.glGetAttribLocation(mProgram, "aTextureCoord");
    int texMatrixHandle = GLES20.glGetUniformLocation(mProgram, "uSTMatrix");
    int mvpMatrixHandle = GLES20.glGetUniformLocation(mProgram, "uMVPMatrix");

    int textureHandle = GLES20.glGetUniformLocation(mProgram, "sTextureSampler");

    int pass = GLES20.glGetUniformLocation(mProgram, "pass");

    GLES20.glUseProgram(mProgram);
    GLES20.glUniformMatrix4fv(texMatrixHandle, 1, false, texMatrix, 0);
    GLES20.glUniformMatrix4fv(mvpMatrixHandle, 1, false, mvpMatrix, 0);

    GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, bufferHandles[0]);
    GLES20.glBindBuffer(GLES20.GL_ELEMENT_ARRAY_BUFFER, bufferHandles[1]);
    GLES20.glEnableVertexAttribArray(vertexHandle);
    GLES20.glVertexAttribPointer(vertexHandle, 3, GLES20.GL_FLOAT, false, 4 * 5, 0);
    GLES20.glEnableVertexAttribArray(uvsHandle);
    GLES20.glVertexAttribPointer(uvsHandle, 2, GLES20.GL_FLOAT, false, 4 * 5, 3 * 4);

    //Pass 0 - Render to framebuffer , gives GL_INVALID_OPERAION error
    GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER,frameBufferHandles[0]);
    GLES20.glUniform1i(pass, 0);
    GLES20.glDrawElements(GLES20.GL_TRIANGLES, 6, GLES20.GL_UNSIGNED_INT, 0);

    //Pass 1 - Render to display
    GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER,0);
    GLES20.glUniform1i(textureHandle, 2);
    GLES20.glUniform1i(pass, 1);
    GLES20.glDrawElements(GLES20.GL_TRIANGLES, 6, GLES20.GL_UNSIGNED_INT, 0);

}

I am guessing it is related to vTextureCoord, because if I dont use  vTextureCoord and render a constant color to the framebuffer during first pass , then I can read it back during the second pass from the texture associated with the framebuffer.


问:
Trying to write a macro using SpreadsheetApp.CopyPasteType.PASTE_FORMULA that copy pastes a formula and data validation but not working
I have a google form and the responses are being recorded in a google sheet. I want to add some data processing to the cells following the responses, such as changing the timestamp to week number, timestamp as year, days since submission.
So I have the formulas in my example row, row 2.
And i'm trying to copy them into the last row with data.

Timestamp
Formula 1 (Column L)
Formula 2 (Column M)
Formula 3 (Column N)

Timestamp 1
formula 1
formula 2
formula 3

Timestamp 2
Blank
Blank
Blank

In both attempts below I am getting the data validation copied, but the formulas don't copy and the cells remain blank.
I first tried modifying an existing macro.

```<code>function Copypaste()
{
  var sheet1 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Form Responses');
  var lastrow = sheet1.getLastRow();
  sheet1.getRange(lastrow, 12).activate();
  sheet1.getRange(2, 12, 1, 15).copyTo(spreadsheet.getActiveRange(), SpreadsheetApp.CopyPasteType.PASTE_FORMULA, false);
  sheet1.getRange(2, 12, 1, 15).copyTo(spreadsheet.getActiveRange(), SpreadsheetApp.CopyPasteType.PASTE_DATA_VALIDATION, false);
};
</code>```

And then I tried recording a Macro.

```<code>function CopyFormula() {
  var spreadsheet = SpreadsheetApp.getActive();
  spreadsheet.getRange('L12').activate();
  spreadsheet.getRange('L2:Q2').copyTo(spreadsheet.getActiveRange(), SpreadsheetApp.CopyPasteType.PASTE_FORMULA, false);
  spreadsheet.getRange('L2:Q2').copyTo(spreadsheet.getActiveRange(), SpreadsheetApp.CopyPasteType.PASTE_FORMAT, false);
};
</code>```

As far as I can tell, they are essentially the same. I can run my recorded Macro and it works, but my modyified macro doesn't. Why?

Body:
I have a google form and the responses are being recorded in a google sheet. I want to add some data processing to the cells following the responses, such as changing the timestamp to week number, timestamp as year, days since submission.
So I have the formulas in my example row, row 2.
And i'm trying to copy them into the last row with data.

Timestamp
Formula 1 (Column L)
Formula 2 (Column M)
Formula 3 (Column N)

Timestamp 1
formula 1
formula 2
formula 3

Timestamp 2
Blank
Blank
Blank

In both attempts below I am getting the data validation copied, but the formulas don't copy and the cells remain blank.
I first tried modifying an existing macro.

function Copypaste()
{
  var sheet1 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Form Responses');
  var lastrow = sheet1.getLastRow();
  sheet1.getRange(lastrow, 12).activate();
  sheet1.getRange(2, 12, 1, 15).copyTo(spreadsheet.getActiveRange(), SpreadsheetApp.CopyPasteType.PASTE_FORMULA, false);
  sheet1.getRange(2, 12, 1, 15).copyTo(spreadsheet.getActiveRange(), SpreadsheetApp.CopyPasteType.PASTE_DATA_VALIDATION, false);
};

And then I tried recording a Macro.

function CopyFormula() {
  var spreadsheet = SpreadsheetApp.getActive();
  spreadsheet.getRange('L12').activate();
  spreadsheet.getRange('L2:Q2').copyTo(spreadsheet.getActiveRange(), SpreadsheetApp.CopyPasteType.PASTE_FORMULA, false);
  spreadsheet.getRange('L2:Q2').copyTo(spreadsheet.getActiveRange(), SpreadsheetApp.CopyPasteType.PASTE_FORMAT, false);
};

As far as I can tell, they are essentially the same. I can run my recorded Macro and it works, but my modyified macro doesn't. Why?


问:
@typescript-eslint errors in redux slice
I have the following redux slice (slice-example.ts):

import { createSlice } from '@reduxjs/toolkit';
import type { PayloadAction } from '@reduxjs/toolkit';
import type { RootState } from '../index';

// Define a type for the slice state
interface ExampleState {
  isActive: boolean;
}

// Define the initial state using that type
const initialState: ExampleState = {
  isActive: true
};

export const sliceExample = createSlice({
  name: 'example',
  initialState,
  reducers: {
    setActive: (state, action: PayloadAction<boolean>) => {
      state.isActive = action.payload;
    }
  }
});

export const { setActive } = sliceExample.actions;

// Other code such as selectors can use the imported `RootState` type
export const isActive = (state: RootState): boolean => state.example.isActive;

export default sliceExample.reducer;
```
<p>And this is my store's index.ts</p>
<pre class="lang-ts prettyprint-override"><code>import { Store } from '@reduxjs/toolkit';
import { configureStore } from '@reduxjs/toolkit';
import sliceExample from './slices/slice-example';

export const store: Store = configureStore({
  reducer: {
    example: sliceExample
  }
});

export type RootState = ReturnType<typeof store.getState>;

export type AppDispatch = typeof store.dispatch;
</code>```

I have a @typescript-eslint errors in this line:

export const isActive = (state: RootState): boolean => state.example.isActive

I'm getting the following errors:

Unsafe member access .example on an any value.

Unsafe return of an any typed value.

Without disabling these rules in .eslintrc and without using something like // @ts-ignore, how do I fix this error? How do I make this code correct?

Body:
I have the following redux slice (slice-example.ts):

import { createSlice } from '@reduxjs/toolkit';
import type { PayloadAction } from '@reduxjs/toolkit';
import type { RootState } from '../index';

// Define a type for the slice state
interface ExampleState {
  isActive: boolean;
}

// Define the initial state using that type
const initialState: ExampleState = {
  isActive: true
};

export const sliceExample = createSlice({
  name: 'example',
  initialState,
  reducers: {
    setActive: (state, action: PayloadAction<boolean>) => {
      state.isActive = action.payload;
    }
  }
});

export const { setActive } = sliceExample.actions;

// Other code such as selectors can use the imported `RootState` type
export const isActive = (state: RootState): boolean => state.example.isActive;

export default sliceExample.reducer;

And this is my store's index.ts

import { Store } from '@reduxjs/toolkit';
import { configureStore } from '@reduxjs/toolkit';
import sliceExample from './slices/slice-example';

export const store: Store = configureStore({
  reducer: {
    example: sliceExample
  }
});

export type RootState = ReturnType<typeof store.getState>;

export type AppDispatch = typeof store.dispatch;

I have a @typescript-eslint errors in this line:

export const isActive = (state: RootState): boolean => state.example.isActive

I'm getting the following errors:

Unsafe member access .example on an any value.

Unsafe return of an any typed value.

Without disabling these rules in .eslintrc and without using something like // @ts-ignore, how do I fix this error? How do I make this code correct?


问:
How to use custom permalink for products in wordpress/woocommerce?
How to use custom permalink for products in wordpress/woocommerce? Is there any ready solution?

I managed to change:
/product/cabinet-with-handle-white-2/

on
/cabinet-with-handle-white-2.html

and ultimately I need to have:
/cabinet-with-white-handle-2,id[PRODUCT ID].html

example: /cabinet-with-handle-white-2,id1453.html

Then when I change the slug name, it will find the product by id

I can't find anything else... anyone have the same?


问:
Grafana dashboard panel with custom time range
I have a Grafana dashboard with a time range for "today so far"

"time": {
    "from": "now/d",
    "to": "now"
 }
```
<p>But I have a service that runs only between 4am and 5am every day for which I would like to plot some metrics in a panel on this dashboard. I'm trying to set the time range for that panel to 4am-5am of the current day so that it doesn't show a full 24 hour x-axis for data that only exists between 4am and 5am. If I were able to specify the time range for the panel using <code>From:</code> and <code>To:</code>, it would have looked something like this:</p>
<pre class="lang-json prettyprint-override"><code>"time": {
    "from": "now/d+4h",
    "to": "now/d-19h"
 }
</code>```

But of course, you can't specify a time range like that for individual panels. You have to make use of the Relative Time and Time Shift values in Query Options for the panel but, for the life of me, I can't figure out how to represent the time range I want in relative time using those two values. It would seem that Grafana's documentation in this regard is sorely lacking; They only show a few very basic and specific examples, none of which helps me with this query.

Would anyone be able to set me straight here please?

For what it's worth, my data source for this Grafana dashboard is Prometheus but I don't think that is germane to this question.

Body:
I have a Grafana dashboard with a time range for "today so far"

"time": {
    "from": "now/d",
    "to": "now"
 }

But I have a service that runs only between 4am and 5am every day for which I would like to plot some metrics in a panel on this dashboard. I'm trying to set the time range for that panel to 4am-5am of the current day so that it doesn't show a full 24 hour x-axis for data that only exists between 4am and 5am. If I were able to specify the time range for the panel using From: and To:, it would have looked something like this:

"time": {
    "from": "now/d+4h",
    "to": "now/d-19h"
 }

But of course, you can't specify a time range like that for individual panels. You have to make use of the Relative Time and Time Shift values in Query Options for the panel but, for the life of me, I can't figure out how to represent the time range I want in relative time using those two values. It would seem that Grafana's documentation in this regard is sorely lacking; They only show a few very basic and specific examples, none of which helps me with this query.

Would anyone be able to set me straight here please?

For what it's worth, my data source for this Grafana dashboard is Prometheus but I don't think that is germane to this question.


问:
Pythonnet cannot convert object to target type
Using pythonnet I am calling a Python function, which returns an object, from my C# script. Once I get the result from Python function I want to be able to cast/convert this Python object into C# user defined class. I tried using AsManagedObject (Type t) and As<T> () functions but during runtime I got an error -

Cannot convert object to target type
Inner Exception PythonException: 'Result' value cannot be converted to Models.Result

I could use some help to convert PyObjects to C# user defined types.

Python -

```<code>#Result.py
class Result:
    def __init__(self, Sum) -> None:
        self.Sum = Sum

#Main.py
from Result import Result
def add(inputCsharp) -> Result:
     result = Result(inputCsharp.Input1 + inputCsharp/input2)
     return result
</code>```

C# -

```<code>//Result.cs
public class Result
{
    public int Sum { get; set; }
}

//Program.cs
using (Py.GIL())
{
    using (var scope = Py.CreateScope())
    {
        dynamic obj = Py.Import(@"Main");

        var inputCsharp = new Input()
        {
            Input1 = 2,
            Input2 = 3
        };

        var result = obj.add(inputCsharp.ToPython());
        var t = (Result)result.AsManagedObject(typeof(Result)); //here it is throwing an error
    }
}
</code>```

Body:
Using pythonnet I am calling a Python function, which returns an object, from my C# script. Once I get the result from Python function I want to be able to cast/convert this Python object into C# user defined class. I tried using AsManagedObject (Type t) and As<T> () functions but during runtime I got an error -

Cannot convert object to target type
Inner Exception PythonException: 'Result' value cannot be converted to Models.Result

I could use some help to convert PyObjects to C# user defined types.

Python -

#Result.py
class Result:
    def __init__(self, Sum) -> None:
        self.Sum = Sum

#Main.py
from Result import Result
def add(inputCsharp) -> Result:
     result = Result(inputCsharp.Input1 + inputCsharp/input2)
     return result

C# -

//Result.cs
public class Result
{
    public int Sum { get; set; }
}

//Program.cs
using (Py.GIL())
{
    using (var scope = Py.CreateScope())
    {
        dynamic obj = Py.Import(@"Main");

        var inputCsharp = new Input()
        {
            Input1 = 2,
            Input2 = 3
        };

        var result = obj.add(inputCsharp.ToPython());
        var t = (Result)result.AsManagedObject(typeof(Result)); //here it is throwing an error
    }
}


问:
Display fields (from query) on Swagger UI from complex record
I have a complex record SearchProductsRequest  in a GET request that receives the parameters by query (
/v1/products?ids=1,2,3&name=hombre&page=3&pageItems=4&sortField=name&sort=asc ).

app.MapGet(
           $"/{ProductCatalogueApi.Version}/products",
           (SearchProductsRequest request)
                => ProductApiDelegates.SearchProducts(
                  request));
```
<p>In the record, I've implemented the bind async
<code>public static ValueTask<SearchProductsRequest?> BindAsync(HttpContext httpContext, ParameterInfo parameter);</code> and now the parameters from the URL automatically convert the parameters to <code>SearchProductsRequest</code>.</p>
<p>The request is working as intended, but we are using (Swashbuckle -> ) Swagger UI for development.</p>
<p>Swagger UI does not recognize the members from <code>SearchProductsRequest</code> to display them as input boxes. Is there a way to make swagger UI know them and display them so a user consulting the swagger endpoint can pass value through it?</p>
<p>I was hoping to get the following:</p>
<p><img src="https://i.stack.imgur.com/EZHWl.png" alt="Endpoint with fields to add values" /></p>
<p>Until now, I've only managed to have the fields displayed in swagger if I have all of them in the Map.Get() explicitly.</p>
<p>EDIT:</p>
<p>Adding asked content</p>
<p>Record:</p>
<pre class="lang-cs prettyprint-override"><code>public record SearchProductsRequest
{
    public IEnumerable<int>? Ids { get; private set; }

    public string? Name { get; private set; }

    public PaginationInfoRequest? PaginationInfo { get; private set; }

    public SortingInfoRequest? SortingInfo { get; private set; }

    public SearchProductsRequest(
        IEnumerable<int>? ids,
        string? name,
        PaginationInfoRequest? PaginationInfo,
        SortingInfoRequest? SortingInfo)
    {
        this.Ids = ids;
        this.Name = name;
        this.PaginationInfo = PaginationInfo;
        this.SortingInfo = SortingInfo;
    }

    public static ValueTask<SearchProductsRequest?> BindAsync(
        HttpContext httpContext,
        ParameterInfo parameter)
    {
        var ids = ParseIds(httpContext);

        var name = httpContext?.Request.Query["name"] ?? string.Empty;

        PaginationInfoRequest? pagination = null;
        SortingInfoRequest? sorting = null;

        if (int.TryParse(httpContext?.Request.Query["page"], out var page)
            && int.TryParse(httpContext?.Request.Query["pageItems"], out var pageItems))
        {
            pagination = new PaginationInfoRequest(page, pageItems);
        }

        var sortField = httpContext?.Request.Query["sortField"].ToString();
        if (!string.IsNullOrEmpty(sortField))
        {
            sorting = new SortingInfoRequest(
                sortField,
                httpContext?.Request.Query["sort"].ToString() == "asc");
        }

        return ValueTask.FromResult<SearchProductsRequest?>(
            new SearchProductsRequest(
                ids,
                name!,
                pagination,
                sorting));
    }

#pragma warning disable SA1011 // Closing square brackets should be spaced correctly
    private static int[]? ParseIds(HttpContext httpContext)
    {
        int[]? ids = null;

        var commaSeparatedIds = httpContext?.Request.Query["ids"]
                    .ToString();

        if (!string.IsNullOrEmpty(commaSeparatedIds))
        {
            ids = commaSeparatedIds
            .Split(",")
            .Select(int.Parse)
            .ToArray() ?? Array.Empty<int>();
        }

        return ids;
    }
#pragma warning restore SA1011 // Closing square brackets should be spaced correctly
}
</code>```

Delegate:

internal static async Task<IResult> SearchProducts(
        ILogger<ProductApiDelegates> logger,
        IMapper mapper,
        SearchProductsRequest request,
        IValidator<SearchProductsRequest> validator,
        IProductService productService)
    {
        using var activity = s_activitySource.StartActivity("Search products");
        var validationResult = await validator.ValidateAsync(request);
        if (!validationResult.IsValid)
        {
            var errors = validationResult.GetErrors();
            logger.LogError("Bad Request: {Errors}", errors);
            return Results.BadRequest();
        }

        try
        {
            logger.LogInformation("Searching product details by name");
            var filtersContainer = mapper.Map<SearchProductsFiltersContainer>(request);
            var products = await productService.SearchProductsAsync(filtersContainer);
            if (products == null)
            {
                return Results.NotFound();
            }

            var searchProducts = BuildSearchProducts(mapper, products);
            var paginationInfo = await BuildPaginationInfo(filtersContainer, productService);
            var response = new SearchProductsResponse(searchProducts, paginationInfo);
            return Results.Ok(response);
        }
        catch (Exception ex)
        {
            logger.LogError(ex, "Error searching the products");
            return Results.Problem();
        }
    }
```

Body:
I have a complex record SearchProductsRequest  in a GET request that receives the parameters by query (
/v1/products?ids=1,2,3&name=hombre&page=3&pageItems=4&sortField=name&sort=asc ).

app.MapGet(
           $"/{ProductCatalogueApi.Version}/products",
           (SearchProductsRequest request)
                => ProductApiDelegates.SearchProducts(
                  request));

In the record, I've implemented the bind async
public static ValueTask<SearchProductsRequest?> BindAsync(HttpContext httpContext, ParameterInfo parameter); and now the parameters from the URL automatically convert the parameters to SearchProductsRequest.

The request is working as intended, but we are using (Swashbuckle -> ) Swagger UI for development.

Swagger UI does not recognize the members from SearchProductsRequest to display them as input boxes. Is there a way to make swagger UI know them and display them so a user consulting the swagger endpoint can pass value through it?

I was hoping to get the following:

Until now, I've only managed to have the fields displayed in swagger if I have all of them in the Map.Get() explicitly.

EDIT:

Adding asked content

Record:

public record SearchProductsRequest
{
    public IEnumerable<int>? Ids { get; private set; }

    public string? Name { get; private set; }

    public PaginationInfoRequest? PaginationInfo { get; private set; }

    public SortingInfoRequest? SortingInfo { get; private set; }

    public SearchProductsRequest(
        IEnumerable<int>? ids,
        string? name,
        PaginationInfoRequest? PaginationInfo,
        SortingInfoRequest? SortingInfo)
    {
        this.Ids = ids;
        this.Name = name;
        this.PaginationInfo = PaginationInfo;
        this.SortingInfo = SortingInfo;
    }

    public static ValueTask<SearchProductsRequest?> BindAsync(
        HttpContext httpContext,
        ParameterInfo parameter)
    {
        var ids = ParseIds(httpContext);

        var name = httpContext?.Request.Query["name"] ?? string.Empty;

        PaginationInfoRequest? pagination = null;
        SortingInfoRequest? sorting = null;

        if (int.TryParse(httpContext?.Request.Query["page"], out var page)
            && int.TryParse(httpContext?.Request.Query["pageItems"], out var pageItems))
        {
            pagination = new PaginationInfoRequest(page, pageItems);
        }

        var sortField = httpContext?.Request.Query["sortField"].ToString();
        if (!string.IsNullOrEmpty(sortField))
        {
            sorting = new SortingInfoRequest(
                sortField,
                httpContext?.Request.Query["sort"].ToString() == "asc");
        }

        return ValueTask.FromResult<SearchProductsRequest?>(
            new SearchProductsRequest(
                ids,
                name!,
                pagination,
                sorting));
    }

#pragma warning disable SA1011 // Closing square brackets should be spaced correctly
    private static int[]? ParseIds(HttpContext httpContext)
    {
        int[]? ids = null;

        var commaSeparatedIds = httpContext?.Request.Query["ids"]
                    .ToString();

        if (!string.IsNullOrEmpty(commaSeparatedIds))
        {
            ids = commaSeparatedIds
            .Split(",")
            .Select(int.Parse)
            .ToArray() ?? Array.Empty<int>();
        }

        return ids;
    }
#pragma warning restore SA1011 // Closing square brackets should be spaced correctly
}

Delegate:

internal static async Task<IResult> SearchProducts(
        ILogger<ProductApiDelegates> logger,
        IMapper mapper,
        SearchProductsRequest request,
        IValidator<SearchProductsRequest> validator,
        IProductService productService)
    {
        using var activity = s_activitySource.StartActivity("Search products");
        var validationResult = await validator.ValidateAsync(request);
        if (!validationResult.IsValid)
        {
            var errors = validationResult.GetErrors();
            logger.LogError("Bad Request: {Errors}", errors);
            return Results.BadRequest();
        }

        try
        {
            logger.LogInformation("Searching product details by name");
            var filtersContainer = mapper.Map<SearchProductsFiltersContainer>(request);
            var products = await productService.SearchProductsAsync(filtersContainer);
            if (products == null)
            {
                return Results.NotFound();
            }

            var searchProducts = BuildSearchProducts(mapper, products);
            var paginationInfo = await BuildPaginationInfo(filtersContainer, productService);
            var response = new SearchProductsResponse(searchProducts, paginationInfo);
            return Results.Ok(response);
        }
        catch (Exception ex)
        {
            logger.LogError(ex, "Error searching the products");
            return Results.Problem();
        }
    }


问:
Wordpress permalinks are showing as updated, but still point to an old permalink
I have an issue with the taxonomy setup. If I create a category or a brand, say, for example, "Antica Barbieria Colla" and set the slug to /antica-barbieria-colla-2/ - when I go to site.com/product-category/antica-barbieria-colla-2 -> it works fine.

However, if I then go into the wp-admin, and edit the slug of this brand, to, for example, /antica-barbieria-colla/, ALL the links to this particular category still show as /antica-barbieria-colla-2/ - both in the admin panel (if I click "view" on the category), in wp-menu, and on the front-end.

/antica-barbieria-colla-2/ becomes a 404 (which it should). /antica-barbieria-colla/ becomes the correct taxonomy brand archive (which it should). All of the links in admin, wp-menu and on the front-end goto /antica-barbieria-colla-2/, but it's correctly set as /antica-barbieria-colla/

Screenshot of this issue

I already tried to clear cache and reset Permalinks. WMPL is up to dated. If I turn WPML plugin off, the issue seems to be resolved, but this plugin is necessary for the website.


问:
How to get hidden data when scraping this site?
I am beginner in mastering of Python and scraping data into internet.Once I faced issue I can't solve. There is a site tenchat.ru. On personal pages there is hidden information like phone numbers and mail addresses. I was trying to extract that data trying GET and POST requests. Reloading page on Network page of Devtools I see that XHR response with name of person('venss') in preload has fields like individualConnection: false and hiddenFields: ["phoneWithPrefixInnerSto", "contactPhone"]0: "phoneWithPrefixInnerSto"1: "contactPhone". It is get request. There is also field 'current' where in preload I see my data similar to json. And in preload I  see also field individualConnection: false. I guess that as this field has value False server doesn't allow me to see phone number.

Another issue is that http addresses shown in headers always give me 401 response. Only url https://tenchat.ru/venss gives me response 200. Main address is https://tenchat.ru. But there is authentication via phone number and sms.

May be it is not possible at all to get data I want but may be there is a way which is not known for me.

If more info is needed I may provide.

Please advise.

I used requests, httpx, requests_html for sending POST and GET requests. Also I used Insomnia to varify if JSON is available and curlconverter.

My code:

```<code>import httpx

url = 'https://tenchat.ru/prisyazhnaya_o'
url1 = 'https://tenchat.ru/gostinder/api/web/auth/account/username/venss'
url2 = 'https://tenchat.ru/gostinder/api/web/auth/account'

params = {"cache-control": "no-cache, no-store, max-age=0, must-revalidate", "content-encoding":       "gzip",
      "content-type": "application/json", "date": "Thu, 05 Jan 2023 09:11:25 GMT",
      "expires": 0, "pragma": "no-cache", "referrer-policy": "no-referrer", "server": "nginx",
      "strict-transport-security": "max-age=31536000", "vary": "Accept-Encoding",
      "x-content-type-options": "nosniff", "x-frame-options": "ACCEPT",
      "x-xss-protection": "1; mode=block"}

cookies = {
'_ym_uid': '167240745648292064',
'_ym_d': '1672407456',
'tmr_lvid': 'bd33e7b65db07187d68680e428694394',
'tmr_lvidTS': '1672407474003',
'_ym_isad': '1',
'_ym_visorc': 'w',
'TCAF': '0pVpAvxaxLhSt1pjk_op4SZmcBs',
'TCRF': 'OKF7KxB0Wz1l17BIMzPEopsIKPM',
'SESSION': '225fb0ff-0503-4a86-b459-5ceab7fca181',
</code>```

}

```<code>headers = {
'authority': 'tenchat.ru',
'accept': 'application/json, text/plain, */*',
'accept-language': 'ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7',
# 'cookie': '_ym_uid=167240745648292064; _ym_d=1672407456; tmr_lvid=bd33e7b65db07187d68680e428694394; tmr_lvidTS=1672407474003; _ym_isad=1; _ym_visorc=w; TCAF=0pVpAvxaxLhSt1pjk_op4SZmcBs; TCRF=OKF7KxB0Wz1l17BIMzPEopsIKPM; SESSION=225fb0ff-0503-4a86-b459-5ceab7fca181',
'dnt': '1',
'sec-ch-ua': '"Not?A_Brand";v="8", "Chromium";v="108", "Google Chrome";v="108"',
'sec-ch-ua-mobile': '?0',
'sec-ch-ua-platform': '"Windows"',
'sec-fetch-dest': 'empty',
'sec-fetch-mode': 'cors',
'sec-fetch-site': 'same-origin',
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36',
</code>```

}

```<code>response = httpx.post(url, cookies=cookies, headers=headers)

print(response.status_code)
</code>```

Body:
I am beginner in mastering of Python and scraping data into internet.Once I faced issue I can't solve. There is a site tenchat.ru. On personal pages there is hidden information like phone numbers and mail addresses. I was trying to extract that data trying GET and POST requests. Reloading page on Network page of Devtools I see that XHR response with name of person('venss') in preload has fields like individualConnection: false and hiddenFields: ["phoneWithPrefixInnerSto", "contactPhone"]0: "phoneWithPrefixInnerSto"1: "contactPhone". It is get request. There is also field 'current' where in preload I see my data similar to json. And in preload I  see also field individualConnection: false. I guess that as this field has value False server doesn't allow me to see phone number.

Another issue is that http addresses shown in headers always give me 401 response. Only url https://tenchat.ru/venss gives me response 200. Main address is https://tenchat.ru. But there is authentication via phone number and sms.

May be it is not possible at all to get data I want but may be there is a way which is not known for me.

If more info is needed I may provide.

Please advise.

I used requests, httpx, requests_html for sending POST and GET requests. Also I used Insomnia to varify if JSON is available and curlconverter.

My code:

import httpx

url = 'https://tenchat.ru/prisyazhnaya_o'
url1 = 'https://tenchat.ru/gostinder/api/web/auth/account/username/venss'
url2 = 'https://tenchat.ru/gostinder/api/web/auth/account'

params = {"cache-control": "no-cache, no-store, max-age=0, must-revalidate", "content-encoding":       "gzip",
      "content-type": "application/json", "date": "Thu, 05 Jan 2023 09:11:25 GMT",
      "expires": 0, "pragma": "no-cache", "referrer-policy": "no-referrer", "server": "nginx",
      "strict-transport-security": "max-age=31536000", "vary": "Accept-Encoding",
      "x-content-type-options": "nosniff", "x-frame-options": "ACCEPT",
      "x-xss-protection": "1; mode=block"}

cookies = {
'_ym_uid': '167240745648292064',
'_ym_d': '1672407456',
'tmr_lvid': 'bd33e7b65db07187d68680e428694394',
'tmr_lvidTS': '1672407474003',
'_ym_isad': '1',
'_ym_visorc': 'w',
'TCAF': '0pVpAvxaxLhSt1pjk_op4SZmcBs',
'TCRF': 'OKF7KxB0Wz1l17BIMzPEopsIKPM',
'SESSION': '225fb0ff-0503-4a86-b459-5ceab7fca181',

}

headers = {
'authority': 'tenchat.ru',
'accept': 'application/json, text/plain, */*',
'accept-language': 'ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7',
# 'cookie': '_ym_uid=167240745648292064; _ym_d=1672407456; tmr_lvid=bd33e7b65db07187d68680e428694394; tmr_lvidTS=1672407474003; _ym_isad=1; _ym_visorc=w; TCAF=0pVpAvxaxLhSt1pjk_op4SZmcBs; TCRF=OKF7KxB0Wz1l17BIMzPEopsIKPM; SESSION=225fb0ff-0503-4a86-b459-5ceab7fca181',
'dnt': '1',
'sec-ch-ua': '"Not?A_Brand";v="8", "Chromium";v="108", "Google Chrome";v="108"',
'sec-ch-ua-mobile': '?0',
'sec-ch-ua-platform': '"Windows"',
'sec-fetch-dest': 'empty',
'sec-fetch-mode': 'cors',
'sec-fetch-site': 'same-origin',
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36',

}

response = httpx.post(url, cookies=cookies, headers=headers)

print(response.status_code)


问:
how i can create input location in template django without create field for location
i want to determine location in template django without create field and model for location just show the box location and determine location and input lat & long in text

```<code>   {% elif field.field.field_type == 'location' %}
        <div class="">
            <input type="text" name="{{ field.field.slug }}" maxlength="255" class="textinput textInput form-control"
                   required="" id="{{ field.field.slug }}">
        </div>
</code>```

Body:
i want to determine location in template django without create field and model for location just show the box location and determine location and input lat & long in text

   {% elif field.field.field_type == 'location' %}

            <input type="text" name="{{ field.field.slug }}" maxlength="255" class="textinput textInput form-control"
                   required="" id="{{ field.field.slug }}">


问:
Safari throws cross domain errors when an iframe is cross domain and tall enough
I have a case where I need to show an iframe cross domains. In development, I have a site hosted at http://localhost:3000 that have an iframe showing http://localhost:3001. For example, with this iframe:

Safari gives me this error when I load http://localhost:3000:

Blocked a frame with origin "http://localhost:3000" from accessing a frame with origin "http://localhost:3001". Protocols, domains, and ports must match.

However, this only happens if the iframe is tall enough. Reducing the height to 92vh remove the error. This might be a security measure implemented by the Safari team to prevent phising. The 92vh is not 100% consistant, but reducing the height to some lower value than a 100 fixes the error, in this cause I needed to go down to 92vh.

What is strange is that this error happens even though no code tries to access the iframe. I set up two new Next.js apps to test this with only boiler plate. The error still occurs, so I don't think it is any JavaScript in the original applications that causing this. So it seems that either

Safari tries to access the iframe itself, and blocks itself

It is not really an error, but a warning. It still seems to work.

Anyone knows what might be wrong?


问:
How to scroll to a specific part of an HTML page after serving a response to a FORM post?
I have an HTML form with many different input buttons.  Scrolling is needed to see some of them on the user's browser screen.

When the user presses one of the buttons the server receives a POST and processes it.  It alters the content of the HTML and re serves it.

Is there some way to serve the HTML so that the user's display scrolls back to the position it displayed when the FORM input button was pushed?  At the moment the display returns to the top of the page and the user has to scroll down again in order to see the results.

Any help or advice would be gratefully appreciated!

I wish to have a function similar to browsing to an anchor on the page, such as http://my_url.com/my+page#my_tag.  The trouble is that a POST is not a GET, so I'm not sure how to specify the #my_tag anchor in the POST


问:
Removing padding/margins with Excel to PDF
I try to print a regular A4 page from Excel to PDF.

So for I tried

Remove margins manually

Remove header footer

Print manually using Microsoft Print

Print manually using Export to PDF

VBA Scripts with margin setting to 0

It still prints white areas around the data

The file can be found at https://github.com/aavanesy/ExcelPDF/blob/main/Demo1.xlsm

Is there a way to print the BLUE area only?


问:
How to create a class that can analyze all 10 txt files in a file?
I have created a class that analyzes the text file with functions 'average_word_length' and 'average_sentence_length'. The text are ten stories stored in the folder 'stories'. I would like to create a code that reads all 10 files in the 'stories' folder and returns all the results at once. However I am seemingly able to analyze only one text file in the folder.

My entire code looks like that:

```<code>from os.path import splitext
from os.path import basename
from glob import glob
from nltk.tokenize import sent_tokenize
import nltk as nlp
import re

def read_file(filename):
    with open(filename, encoding='utf8') as infile:
        contents = infile.read()
    return contents

def remove_ext(filename):
    root, ext = splitext(filename)
    return root

def remove_dir(filepath):
    return basename(filepath)

def remove_dir_ext(filepath):
    no_ext = remove_ext(filepath)
    base = remove_dir(no_ext)
    return base

def get_story(filepath):
    return int(remove_dir_ext(filepath))
</code>```
```<code># importing required modules
import zipfile
from zipfile import ZipFile
import nltk
nltk.download('punkt')

# specifying the zip file name
file_name = "stories_n10.zip.2"

# opening the zip file in READ mode
with ZipFile(file_name, 'r') as zip:
    # printing all the contents of the zip file
    zip.printdir()

    # extracting all the files
    zip.extractall()
</code>```
```<code>corpus = []
filenames = glob('story1.txt')
filenames = sorted(filenames, key=get_story)
for filename in filenames:
    text = read_file(filename)
</code>```
```<code>#number of letters
number_od_letters=sum(len(x) for x in text.split())

#Counting number of words
s = text
len(s.split())
number_of_words=len(text.split())

#Counting number of sentences
sentences = text

number_of_sentences = sent_tokenize(sentences)

no_of_sentences=len(number_of_sentences)

</code>```
```<code>#average_sentence_length=number of words/ number of sentences

average_sentence_length= number_of_words/no_of_sentences

# average_word_length = total number of letters/ total number of words

average_word_length= number_od_letters/number_of_words
</code>```
```<code>class TextAnalysis:
    def __init__(self, average_word_length, average_sentence_length):
        self.average_word_length = average_word_length
        self.average_sentence_length = average_sentence_length
print(average_word_length, average_sentence_length)
</code>```

And the output are two numbers for example.

3, 21

Now I would like to create the class that takes ALL the files in the folder at once and returns all 20 results from all files of the folder. For example this:

3, 21

2, 23

5, 17

5, 43

1, 34

3, 67

8, 71

3, 75

1, 37

4, 61

But then each time I try to get the entire folder I am getting an error, so I can only get one file (the sotry) at once.
Anyone knows how to compute imput in multiple files at once? I don't want to copy paste my code all ten times, but then nothing else seems to work.

I tried multiple alteration of using 'glob' file, but nothing seemed to work: when I add the name of the entire folder I receive the error

invalid literal for int() with base 10

Body:
I have created a class that analyzes the text file with functions 'average_word_length' and 'average_sentence_length'. The text are ten stories stored in the folder 'stories'. I would like to create a code that reads all 10 files in the 'stories' folder and returns all the results at once. However I am seemingly able to analyze only one text file in the folder.

My entire code looks like that:

from os.path import splitext
from os.path import basename
from glob import glob
from nltk.tokenize import sent_tokenize
import nltk as nlp
import re

def read_file(filename):
    with open(filename, encoding='utf8') as infile:
        contents = infile.read()
    return contents

def remove_ext(filename):
    root, ext = splitext(filename)
    return root

def remove_dir(filepath):
    return basename(filepath)

def remove_dir_ext(filepath):
    no_ext = remove_ext(filepath)
    base = remove_dir(no_ext)
    return base

def get_story(filepath):
    return int(remove_dir_ext(filepath))

# importing required modules
import zipfile
from zipfile import ZipFile
import nltk
nltk.download('punkt')

# specifying the zip file name
file_name = "stories_n10.zip.2"

# opening the zip file in READ mode
with ZipFile(file_name, 'r') as zip:
    # printing all the contents of the zip file
    zip.printdir()

    # extracting all the files
    zip.extractall()

corpus = []
filenames = glob('story1.txt')
filenames = sorted(filenames, key=get_story)
for filename in filenames:
    text = read_file(filename)

#number of letters
number_od_letters=sum(len(x) for x in text.split())

#Counting number of words
s = text
len(s.split())
number_of_words=len(text.split())

#Counting number of sentences
sentences = text

number_of_sentences = sent_tokenize(sentences)

no_of_sentences=len(number_of_sentences)

#average_sentence_length=number of words/ number of sentences

average_sentence_length= number_of_words/no_of_sentences

# average_word_length = total number of letters/ total number of words

average_word_length= number_od_letters/number_of_words

class TextAnalysis:
    def __init__(self, average_word_length, average_sentence_length):
        self.average_word_length = average_word_length
        self.average_sentence_length = average_sentence_length
print(average_word_length, average_sentence_length)

And the output are two numbers for example.

3, 21

Now I would like to create the class that takes ALL the files in the folder at once and returns all 20 results from all files of the folder. For example this:

3, 21

2, 23

5, 17

5, 43

1, 34

3, 67

8, 71

3, 75

1, 37

4, 61

But then each time I try to get the entire folder I am getting an error, so I can only get one file (the sotry) at once.
Anyone knows how to compute imput in multiple files at once? I don't want to copy paste my code all ten times, but then nothing else seems to work.

I tried multiple alteration of using 'glob' file, but nothing seemed to work: when I add the name of the entire folder I receive the error

invalid literal for int() with base 10


问:
Report builder not executing complete SQL query
I'm working with a SQL query which has around 900 lines, I have copied the entire SQL query and pasted in report builder to develop a report. But,the report builder taking only 500 lines of the query remaining 400 lines are not visible or missing.

Does report builder have any limitations with lines? How can I deal with this?


问:
Should I wrap React.cloneElement into useEffect?
I read the official React doc for cloneElement. I also checked how exactly the MUI ToggleButton component is implemented and overrides the children. In both cases there is no mention on that we should wrap it into useEffect to prevent each time recalculation.

Don't we need to wrap cloneElement, especially when we do Children.map, into useEffect to prevent this potentially heavy operation each time the component rerenders?

I created a code example where it clearly seen it is always recalled.


问:
Pythonnet cannot convert object to target type why?
using pythonnet during runtime i got an error.

I tried using AsManagedObject(Type t) and as () functions but showing runtime error.


问:
Code Coverage for Backend code when running UI Automated tests
I ve a test automation suite in Cypress for testing a webapp. The webapp is developed using JS frameworks in the frontend and Java/C# in the backend. My requirement is to calculate code coverage for both fronend and backend code when running my cypress automated tests. We have libraries like Istanbul that does this job for fronend/UI code.

Now I want to know how to calculate the code coverage for the backend/API code when running our Cypress UI automation tests?


问:
Throttle Cosmos DB throughput while querying
I have a method that queries a Cosmos DB collection like this:

```<code>public async IAsyncEnumerable<TObject> Query(Expression<Func<TObject, bool>> filter)
{
    FeedIterator<TObject> feedIterator = this.CosmosClient
        .GetContainer(this.DatabaseName, this.CollectionName).GetItemLinqQueryable<TObject>()
        .Where(filter)
        .ToFeedIterator();

    while (feedIterator.HasMoreResults)
    {
        FeedResponse<TObject> response = await feedIterator.ReadNextAsync();
        foreach (TObject r in response.Resource)
        {
            yield return r;
        }
    }
}
</code>```

This utilizes the maximum throughput so that the database may become unresponsive. In cases where the query takes a long time to complete but has low priority, I would like to throttle the throughput it consumes by adding an extra parameter to the method:

```<code>public async IAsyncEnumerable<TObject> Query(Expression<Func<TObject, bool>> filter,
    double maxThroughputInRUsPerSecond)
</code>```

I know I can retrieve the consumed throughput with response.RequestCharge. What would be a good way to estimate the RU/s, and how should I add back off delays to (approximately) limit the throughput to the given value?

Body:
I have a method that queries a Cosmos DB collection like this:

public async IAsyncEnumerable<TObject> Query(Expression<Func<TObject, bool>> filter)
{
    FeedIterator<TObject> feedIterator = this.CosmosClient
        .GetContainer(this.DatabaseName, this.CollectionName).GetItemLinqQueryable<TObject>()
        .Where(filter)
        .ToFeedIterator();

    while (feedIterator.HasMoreResults)
    {
        FeedResponse<TObject> response = await feedIterator.ReadNextAsync();
        foreach (TObject r in response.Resource)
        {
            yield return r;
        }
    }
}

This utilizes the maximum throughput so that the database may become unresponsive. In cases where the query takes a long time to complete but has low priority, I would like to throttle the throughput it consumes by adding an extra parameter to the method:

public async IAsyncEnumerable<TObject> Query(Expression<Func<TObject, bool>> filter,
    double maxThroughputInRUsPerSecond)

I know I can retrieve the consumed throughput with response.RequestCharge. What would be a good way to estimate the RU/s, and how should I add back off delays to (approximately) limit the throughput to the given value?


问:
x64 Calling Convention of Windows OS and Following it in a Assembly program
I am working with Windows and x64 assembly. I am eager to know more and more about x64 calling convention. My program seems couldn't handle calling convention correctly, so I need some help and experience to handle its issue.

Based on MSDN:

The x64 Application Binary Interface (ABI) uses a four-register fast-call calling convention by default. Space is allocated on the call stack as a shadow store for callees to save those registers.

So before I make any call to Windows API, I try to store all parameters in the registers RCX, RDX, R8 and R9 but when I wanted to call WriteConsoleA, It get 5 parameter from user so I decided to add fifth parameter into the stack. Also, I consider when Call instruction trigger it put return address of the caller to the stack so the ret instruction work correctly.

However, based on this assumption, I written the following code. It is work and print HelloWorld to the screen but when WriteConsole triggered it can't back to the caller position and successfully call ExitProcess function. Because when program done, in console I see the return value of the program isn't zero.

This is the final code which I have written as a learning process:

```<code>GetStdHandle PROTO
ExitProcess PROTO
WriteConsoleA PROTO

.data
    message         DB "Hello World",0
    message_size    DQ SIZEOF message

.code
    ShowMessageConsole PROC
        POP R10
        POP R9
        POP R8
        POP RDX
        POP RCX
        MOV  QWORD PTR [RSP + 4 * SIZEOF QWORD], 0
        CALL WriteConsoleA
        RET
    ShowMessageConsole ENDP

    main PROC
        MOV RCX, -11
        CALL GetStdHandle
        PUSH RAX
        LEA RDX, message
        PUSH RDX
        MOV R8, SIZEOF message - 1
        PUSH R8
        MOV R9, message_size
        PUSH R9
        CALL ShowMessageConsole

        MOV RCX, 0
        CALL ExitProcess
    main ENDP
END
</code>```

This program show Hello World to the screen, but terminated with a random value so I can understand program execution flow corrupted. I debug the program but I couldn't figure out the problem of the program.

Thank you folks for helping me and other people who entered to the low-level field of computer system. Thank you stackoverflow for this nice platform.

Body:
I am working with Windows and x64 assembly. I am eager to know more and more about x64 calling convention. My program seems couldn't handle calling convention correctly, so I need some help and experience to handle its issue.

Based on MSDN:

The x64 Application Binary Interface (ABI) uses a four-register fast-call calling convention by default. Space is allocated on the call stack as a shadow store for callees to save those registers.

So before I make any call to Windows API, I try to store all parameters in the registers RCX, RDX, R8 and R9 but when I wanted to call WriteConsoleA, It get 5 parameter from user so I decided to add fifth parameter into the stack. Also, I consider when Call instruction trigger it put return address of the caller to the stack so the ret instruction work correctly.

However, based on this assumption, I written the following code. It is work and print HelloWorld to the screen but when WriteConsole triggered it can't back to the caller position and successfully call ExitProcess function. Because when program done, in console I see the return value of the program isn't zero.

This is the final code which I have written as a learning process:

GetStdHandle PROTO
ExitProcess PROTO
WriteConsoleA PROTO

.data
    message         DB "Hello World",0
    message_size    DQ SIZEOF message

.code
    ShowMessageConsole PROC
        POP R10
        POP R9
        POP R8
        POP RDX
        POP RCX
        MOV  QWORD PTR [RSP + 4 * SIZEOF QWORD], 0
        CALL WriteConsoleA
        RET
    ShowMessageConsole ENDP

    main PROC
        MOV RCX, -11
        CALL GetStdHandle
        PUSH RAX
        LEA RDX, message
        PUSH RDX
        MOV R8, SIZEOF message - 1
        PUSH R8
        MOV R9, message_size
        PUSH R9
        CALL ShowMessageConsole

        MOV RCX, 0
        CALL ExitProcess
    main ENDP
END

This program show Hello World to the screen, but terminated with a random value so I can understand program execution flow corrupted. I debug the program but I couldn't figure out the problem of the program.

Thank you folks for helping me and other people who entered to the low-level field of computer system. Thank you stackoverflow for this nice platform.


问:
Excel - SUMPRODUCT dynamic range
I am trying to make the following formula work based on date, this is due to when the fiscal year starts.

```<code>=IFERROR(SUMPRODUCT(IFERROR(--($E6:$ET6=$EW$5)*($B6:$EQ6),0))+SUMPRODUCT(IFERROR(--($E6:$ET6=$EW$5)*($C6:$ER6),0))+SUMPRODUCT(IFERROR(--($E6:$ET6=$EW$5)*($D6:$ES6),0)),0)
</code>```

This formula currently works across all the days. i need this broken in two parts,

Part 1 will select x amount of days based on a cell reference (FB1) of how many days to select i.e first 6 days This would start at Col B and finish on Col AA for earlies and start at Col C and finish on Col AB for Lates etc.

Part 2 will select the remaining Starting from AF.

The sheet is setup as the following.

Name
Earlies
Lates
Nights
Type
Ticket
Earlies
Lates
Nights
Type
Ticket
Earlies
Lates
Nights
Type
Ticket

Joe Bloggs
8

Holiday
#12345
8

Holiday

Jane Doe

8

Holiday
#76543

8

Holiday

Name is Col A
Earlies/Lates/Nights/Type/Ticket repeats for 30/31 days (except feb of course)

Thanks

Title: Excel - SUMPRODUCT dynamic range

Body:
I am trying to make the following formula work based on date, this is due to when the fiscal year starts.

=IFERROR(SUMPRODUCT(IFERROR(--($E6:$ET6=$EW$5)*($B6:$EQ6),0))+SUMPRODUCT(IFERROR(--($E6:$ET6=$EW$5)*($C6:$ER6),0))+SUMPRODUCT(IFERROR(--($E6:$ET6=$EW$5)*($D6:$ES6),0)),0)

This formula currently works across all the days. i need this broken in two parts,

Part 1 will select x amount of days based on a cell reference (FB1) of how many days to select i.e first 6 days This would start at Col B and finish on Col AA for earlies and start at Col C and finish on Col AB for Lates etc.

Part 2 will select the remaining Starting from AF.

The sheet is setup as the following.

Name
Earlies
Lates
Nights
Type
Ticket
Earlies
Lates
Nights
Type
Ticket
Earlies
Lates
Nights
Type
Ticket

Joe Bloggs
8

Holiday
#12345
8

Holiday

Jane Doe

8

Holiday
#76543

8

Holiday

Name is Col A
Earlies/Lates/Nights/Type/Ticket repeats for 30/31 days (except feb of course)

Thanks