问:
how to add emmet in vs code
I want to use emmet on VS Code for React and they say emmet is default on vs code, I don't need to add an emmet extension. I check on setting there is emmet section. but, Is it only default to HTML and CSS?

Please Help me to add it.

I check the internet slightly but every one said, to go to user setting>extension>emmet> under Then select Extensions >  Emmet Include: Languages and select the Edit in settings.JSON link directly underneath it.
but in my vs, I don't have this setting.JSON under the Emmet Include: Language. i just have Item value and ADD Item beneath it. like tin the pic.

Title: how to add emmet in vs code


来源: stackexchange

问:
Invalid language element error in Assembly
I am trying to execute this riscv assembly code but I keep getting the error :Invalid language element

This is the code part that error happend. (last row)

```<code>main:
        addi    sp,sp,-32
        sw      ra,28(sp)
        sw      s0,24(sp)
        addi    s0,sp,32
        li      a5,32
        sw      a5,-20(s0)
        li      a5,8
        sw      a5,-24(s0)
        li      a5,4
        sw      a5,-28(s0)
        sw      zero,-32(s0)
        call    initialize
        lw      a3,-32(s0)
        lw      a2,-28(s0)
        lw      a1,-24(s0)
        lw      a0,-20(s0)
        call    accessWords
        li      a5,0
        mv      a0,a5
        lw      ra,28(sp)
        lw      s0,24(sp)
        addi    sp,sp,32
        jr      ra
</code>```

I just want to run this program. This is the error.

```<code>Error in C:\Users\ASUS\OneDrive\Desktop\riscv1.asm line 110 column 3:         jr      ra
Invalid language element:       jr      ra
Assemble: operation completed with errors.
</code>```

I cant understand why I am getting the error.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to execute this riscv assembly code but I keep getting the error :Invalid language element

This is the code part that error happend. (last row)

main:
        addi    sp,sp,-32
        sw      ra,28(sp)
        sw      s0,24(sp)
        addi    s0,sp,32
        li      a5,32
        sw      a5,-20(s0)
        li      a5,8
        sw      a5,-24(s0)
        li      a5,4
        sw      a5,-28(s0)
        sw      zero,-32(s0)
        call    initialize
        lw      a3,-32(s0)
        lw      a2,-28(s0)
        lw      a1,-24(s0)
        lw      a0,-20(s0)
        call    accessWords
        li      a5,0
        mv      a0,a5
        lw      ra,28(sp)
        lw      s0,24(sp)
        addi    sp,sp,32
        jr      ra

I just want to run this program. This is the error.

Error in C:\Users\ASUS\OneDrive\Desktop\riscv1.asm line 110 column 3:         jr      ra
Invalid language element:       jr      ra
Assemble: operation completed with errors.

I cant understand why I am getting the error.


问:
how to debug java-script code along with .ndoejs
I am having problems while debugging a javascript that is written with .nodejs, I am using third-party apps like bug battle, Qt, etc.

I have also tried different apps like embrace and Bug battle but was not able to do anything.


问:
Not able to get options about routing and styling in git bash for Angular project
I don't know why but when I tried to initialize the angular project using git bash on windows it doesn't ask the questions about routing and style sheets. However, when I tried to use the same command in the terminal inside de VS code it worked. It's strange since both terminals runs with bash. I need answer.

expecting to work in git bash


问:
Finding Milestones that are changing in term of specific milestone
I need a query to find all the milestones if I make any change for milestonetotalmonth using java spring features where milestoneno is 1 and that is related to milestonestartedfrom table iamge:  Is it possible ?

I tried in java to fetch the milestoneno and store in a List of Object array


问:
Bloc watch function is running even if no event is triggered
here is my code , I am watching bloc using the watch function and my handleApiResponse using in the build section and this state is running even if no events are triggered....</p>
```<code>Future<void> handleApiResponse(BuildContext context) async {
    final state = context.watch<LoginBloc>().state;
    if (state is VendorLoginState) {
      emailErr = state.emailError;
      passError = state.passwordError;
      if (state.isOnChange!) {
        if (state.isSuccess!) {
         // here is the logic
        }
      }
    }
  }
</code>```

Body:
here is my code , I am watching bloc using the watch function and my handleApiResponse using in the build section and this state is running even if no events are triggered....

Future<void> handleApiResponse(BuildContext context) async {
    final state = context.watch<LoginBloc>().state;
    if (state is VendorLoginState) {
      emailErr = state.emailError;
      passError = state.passwordError;
      if (state.isOnChange!) {
        if (state.isSuccess!) {
         // here is the logic
        }
      }
    }
  }


问:
How to solve Oracle BI Publisher Template compatibility issue - xsl-fo template - encountering Completed warning in EBS
I've created an XSL-FO template using Oracle BI Publisher Add-in for Microsoft Word I have define it on BI publisher template.
Type: XSL-FO
Default File: .xsl
Default Output Type: Excel

However, upon running the concurrent program, I encountered completed warning, there is data generated in the xml. But no generated excel output.

See the screenshot of my xsl-fo template here

I tried changing the xdocalendar to AMERICAN but still completed warning


问:
Error declaring a variable in a switch statement
Here's my code:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct Person {
    char *name;
    struct Person *next;
} Person;

typedef struct EscalatorQueue {
    Person *head;
    Person *tail;
} EscalatorQueue;

EscalatorQueue *create_queue() {
    EscalatorQueue *queue = malloc(sizeof(EscalatorQueue));
    queue->head = NULL;
    queue->tail = NULL;
    return queue;
}

void add_person(EscalatorQueue *queue, char *name) {
    Person *person = malloc(sizeof(Person));
    person->name = malloc(strlen(name) + 1);
    strcpy(person->name, name);
    person->next = NULL;
    if (queue->tail == NULL) {
        queue->head = person;
        queue->tail = person;
    } else {
        queue->tail->next = person;
        queue->tail = person;
    }
}

char *remove_person(EscalatorQueue *queue) {
    if (queue->head == NULL) {
        return NULL;
    }
    char *name = queue->head->name;
    Person *temp = queue->head;
    queue->head = queue->head->next;
    if (queue->head == NULL) {
        queue->tail = NULL;
    }
    free(temp);
    return name;
}

int main() {
    EscalatorQueue *queue = create_queue();

    int choice;
    char name[100];
    while (1) {
        printf("Enter 1 to add a person, 2 to remove a person, or 0 to exit: ");
        scanf("%d", &choice);
        switch (choice) {
            case 0:
                return 0;
            case 1:
                printf("Enter the name of the person: ");
                scanf("%s", name);
                add_person(queue, name);
                break;
            case 2:
                char *removed_name = remove_person(queue);
                if (removed_name == NULL) {
                    printf("Queue is empty\n");
                } else {
                    printf("%s was removed from the queue\n", removed_name);
                    free(removed_name);
                }
                break;
        }
    }
}
</code>```

When I compile my code in DEV C++ I'm getting an error in the case 2: of the switch statement, on this line:

```<code>char *removed_name = remove_person(queue);
</code>```

However, when compiling this code on the online compilers, I get no error.

So, what mistake have I made and how can I fix it?

Body:
Here's my code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct Person {
    char *name;
    struct Person *next;
} Person;

typedef struct EscalatorQueue {
    Person *head;
    Person *tail;
} EscalatorQueue;

EscalatorQueue *create_queue() {
    EscalatorQueue *queue = malloc(sizeof(EscalatorQueue));
    queue->head = NULL;
    queue->tail = NULL;
    return queue;
}

void add_person(EscalatorQueue *queue, char *name) {
    Person *person = malloc(sizeof(Person));
    person->name = malloc(strlen(name) + 1);
    strcpy(person->name, name);
    person->next = NULL;
    if (queue->tail == NULL) {
        queue->head = person;
        queue->tail = person;
    } else {
        queue->tail->next = person;
        queue->tail = person;
    }
}

char *remove_person(EscalatorQueue *queue) {
    if (queue->head == NULL) {
        return NULL;
    }
    char *name = queue->head->name;
    Person *temp = queue->head;
    queue->head = queue->head->next;
    if (queue->head == NULL) {
        queue->tail = NULL;
    }
    free(temp);
    return name;
}

int main() {
    EscalatorQueue *queue = create_queue();

    int choice;
    char name[100];
    while (1) {
        printf("Enter 1 to add a person, 2 to remove a person, or 0 to exit: ");
        scanf("%d", &choice);
        switch (choice) {
            case 0:
                return 0;
            case 1:
                printf("Enter the name of the person: ");
                scanf("%s", name);
                add_person(queue, name);
                break;
            case 2:
                char *removed_name = remove_person(queue);
                if (removed_name == NULL) {
                    printf("Queue is empty\n");
                } else {
                    printf("%s was removed from the queue\n", removed_name);
                    free(removed_name);
                }
                break;
        }
    }
}

When I compile my code in DEV C++ I'm getting an error in the case 2: of the switch statement, on this line:

char *removed_name = remove_person(queue);

However, when compiling this code on the online compilers, I get no error.

So, what mistake have I made and how can I fix it?


问:
Ordinal Logistic Regression: Reordering the ordinal categorical response variable for correct cumulative probabilities
I'm using R to construct an ordinal logistic regression model for response variable "Total.Spent".

First up, I'm aware that the lowest level for "Total.Spent" should be "$0 - $499" to avoid ambiguity but this isn't material to my problem.

Because the response variable is ordinal, and the model calculates cumulative probability, I need to get the levels for the response variable in the correct order.  The default order is $0-$500, $1,000-$2,499, $2,500-$4,999, $5,000+, $500-$999. There are missing values in the data set.

I've reordered one of the predictor variables "Month", (and the code returns the expected result),but when I attempt to re-order the response variable, the values in my "Total.Spent" column in my data frame are removed, giving me an empty column.

Here's the code I've used:

```<code># Re-order Month so that months appear in calendar order, beginning in April
months_in_survey_year_order <- c("April", "May", "June", "July", "August", "September",
                                 "October", "November", "December", "January",
                                 "February", "March")

KI_Data$Month <- factor(KI_Data$Month,
                        levels = months_in_survey_year_order)

# Re-order Total.Spent so that the levels appear in the correct order
spend_in_order <- c("$0 - $500", "$500 - $999", "$1,000 - $2,499",
                    "$2,500 - $4,999", "$5,000+")

KI_Data$Total.Spent <- factor(KI_Data$Total.Spent,
                         levels = spend_in_order) # This line is deleting all of the Total.Spent values
</code>```

I have no idea what's going on to cause the values in KI_Data$Total.Spent to disappear. I'm wondering whether it's because this is the model's response variable? Maybe it's because there's missing values in the data set? Or is there something else going on?

I'd appreciate any guidance.

Thanks, Kirsten

Body:
I'm using R to construct an ordinal logistic regression model for response variable "Total.Spent".

First up, I'm aware that the lowest level for "Total.Spent" should be "$0 - $499" to avoid ambiguity but this isn't material to my problem.

Because the response variable is ordinal, and the model calculates cumulative probability, I need to get the levels for the response variable in the correct order.  The default order is $0-$500, $1,000-$2,499, $2,500-$4,999, $5,000+, $500-$999. There are missing values in the data set.

I've reordered one of the predictor variables "Month", (and the code returns the expected result),but when I attempt to re-order the response variable, the values in my "Total.Spent" column in my data frame are removed, giving me an empty column.

Here's the code I've used:

# Re-order Month so that months appear in calendar order, beginning in April
months_in_survey_year_order <- c("April", "May", "June", "July", "August", "September",
                                 "October", "November", "December", "January",
                                 "February", "March")

KI_Data$Month <- factor(KI_Data$Month,
                        levels = months_in_survey_year_order)

# Re-order Total.Spent so that the levels appear in the correct order
spend_in_order <- c("$0 - $500", "$500 - $999", "$1,000 - $2,499",
                    "$2,500 - $4,999", "$5,000+")

KI_Data$Total.Spent <- factor(KI_Data$Total.Spent,
                         levels = spend_in_order) # This line is deleting all of the Total.Spent values

I have no idea what's going on to cause the values in KI_Data$Total.Spent to disappear. I'm wondering whether it's because this is the model's response variable? Maybe it's because there's missing values in the data set? Or is there something else going on?

I'd appreciate any guidance.

Thanks, Kirsten


问:
Calling method '_start_suite' of listener 'DataDriver' failed: ImportError: Requirements (pandas, openpyxl)
Calling method '_start_suite' of listener 'DataDriver' failed: ImportError: Requirements (pandas, openpyxl) for XLSX support are not installed.
Use 'pip install -U robotframework-datadriver[XLS]' to install XLSX support.

Python Version - 3.7.8
Robot Framework - 6.0.1
Robot Framework Data Driver - 1.7.0

Library     DataDriver     ../Data/PLAC_Dehumidification_SQA_Scenario.xlsx      sheet_name=Automation


问:
Ads are showing when I build a apk in unity but when app bundle is uploaded on playstore, it doesn't
I recently launched a game in unity which I uploaded on playstore. I was able to display ads when I just built an apk from the app but when I upload the app bundle on playstore and playstore launched that update, the ads stop displaying. My admob account is approved and my individual app's approval status is also 'Ready'.
I am not able to understand why my game is not displaying any ads as it should be working. All the ad ids are correct and it works fine in the normal apk. I am seeing proper ads.

Can someone help me please.

My AdManager Script

```<code>
using GoogleMobileAds.Api;
using GoogleMobileAds.Common;
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class MediationManager : MonoBehaviour
{
    #region Ad_IDs
    public string app_Id;
    public string banner_Id;
    public string nativeBanner_Id;
    public string interstitial_Id;
    public string rewardedVideo_Id;

    public static MediationManager Instance;
    private BannerView bannerView;
    private BannerView nativebannerView;
    private InterstitialAd interstitial;
    private RewardedAd rewardedAd;
    #endregion

    private void Awake()
    {

        if (Instance == null)
        {
            Instance = this;
            DontDestroyOnLoad(this);
            print("again");
        }
        else
        {
            print("not again");

            Destroy(this.gameObject);
        }
    }
    // Start is called before the first frame update

    void Start()
    {

        MobileAds.SetiOSAppPauseOnBackground(true);
        //RequestConfiguration requestConfiguration =
        //   new RequestConfiguration.Builder()
        //   .SetTagForChildDirectedTreatment(TagForChildDirectedTreatment.True)
        //   .build();
        //MobileAds.SetRequestConfiguration(requestConfiguration);

        // Initialize the Google Mobile Ads SDK.
        MobileAds.Initialize(HandleInitCompleteAction);

    }

    private void HandleInitCompleteAction(InitializationStatus initstatus)
    {

        MobileAdsEventExecutor.ExecuteInUpdate(() =>
        {
            //RequestBanner();
            RequestInterstitial();
            RequestAdmobRewarded();
            // RequestNativeBanner();
            //ShowTopBanner();
        });
    }

    #region Request Ads
    public AdRequest CreateAdRequest()
    {
        return new AdRequest.Builder().Build();
    }
    private void RequestInterstitial()
    {
        if (PlayerPrefs.GetInt("adsRemoveCount") <= 2)
        {
            // Clean up interstitial ad before creating a new one.
            if (this.interstitial != null)
            {
                this.interstitial.Destroy();
            }

            // Create an interstitial.
            this.interstitial = new InterstitialAd(interstitial_Id);

            // Register for ad events.
            this.interstitial.OnAdLoaded += this.HandleOnAdLoaded;
            this.interstitial.OnAdFailedToLoad += this.HandleOnAdFailedToLoad;
            this.interstitial.OnAdOpening += this.HandleOnAdOpened;
            this.interstitial.OnAdClosed += this.HandleOnAdClosed;
            // this.interstitial. += this.HandleOnAdLeavingApplication;

            // Load an interstitial ad.
            this.interstitial.LoadAd(this.CreateAdRequest());
        }

    }
    public void RequestBanner()
    {
        if (PlayerPrefs.GetInt("RemoveAds") == 0)
        {
            // Clean up banner ad before creating a new one.
            if (this.bannerView != null)
            {
                this.bannerView.Destroy();
            }
            // Create a 320x50 banner at the top of the screen.
            this.bannerView = new BannerView(banner_Id, AdSize.Banner, AdPosition.Top);

            // Register for ad events.
            this.bannerView.OnAdLoaded += this.HandleAdLoaded;
            this.bannerView.OnAdFailedToLoad += this.HandleAdFailedToLoad;
            this.bannerView.OnAdOpening += this.HandleAdOpened;
            this.bannerView.OnAdClosed += this.HandleAdClosed;
            //this.bannerView.OnAdLeavingApplication += this.HandleAdLeftApplication;

            // Load a banner ad.
            this.bannerView.LoadAd(this.CreateAdRequest());
            this.bannerView.Hide();
            print("Show Top Banner");
        }
    }
    public void RequestNativeBanner()
    {
        if (PlayerPrefs.GetInt("RemoveAds") == 0)
        {
            if (this.nativebannerView != null)
            {
                this.nativebannerView.Destroy();
            }

            this.nativebannerView = new BannerView(banner_Id, AdSize.MediumRectangle, 0, 54);

            this.nativebannerView.LoadAd(this.CreateAdRequest());
            this.nativebannerView.Hide();
        }
    }
    private void RequestAdmobRewarded()
    {

        if (PlayerPrefs.GetInt("adsRemoveCount") <= 2)
        {
            this.rewardedAd = new RewardedAd(rewardedVideo_Id);

            // Called when an ad request has successfully loaded.
            this.rewardedAd.OnAdLoaded += HandleRewardedAdLoaded;
            // Called when an ad request failed to load.
            //      this.rewardedAd.OnAdFailedToLoad += HandleRewardedAdFailedToLoad;

            // Called when an ad is shown.
            this.rewardedAd.OnAdOpening += HandleRewardedAdOpening;
            // Called when an ad request failed to show.
            this.rewardedAd.OnAdFailedToShow += HandleRewardedAdFailedToShow;
            // Called when the user should be rewarded for interacting with the ad.
            this.rewardedAd.OnUserEarnedReward += HandleUserEarnedReward;
            // Called when the ad is closed.
            this.rewardedAd.OnAdClosed += HandleRewardedAdClosed;

            // Load the rewarded ad with the request.
            this.rewardedAd.LoadAd(this.CreateAdRequest());
        }
    }
    #endregion

    #region Banner callback handlers

    public void HandleAdLoaded(object sender, EventArgs args)
    {
        MonoBehaviour.print("HandleAdLoaded event received");
    }

    public void HandleAdFailedToLoad(object sender, AdFailedToLoadEventArgs args)
    {
        MonoBehaviour.print("HandleFailedToReceiveAd event received with message: " + args.LoadAdError);
    }

    public void HandleAdOpened(object sender, EventArgs args)
    {
        MonoBehaviour.print("HandleAdOpened event received");
    }

    public void HandleAdClosed(object sender, EventArgs args)
    {
        MonoBehaviour.print("HandleAdClosed event received");
    }

    public void HandleAdLeftApplication(object sender, EventArgs args)
    {
        MonoBehaviour.print("HandleAdLeftApplication event received");
    }

    #endregion

    #region Interstial callback handlers
    public void HandleOnAdLoaded(object sender, System.EventArgs args)
    {
        MonoBehaviour.print("HandleAdLoaded event received");
    }

    public void HandleOnAdFailedToLoad(object sender, AdFailedToLoadEventArgs args)
    {
        MonoBehaviour.print("HandleFailedToReceiveAd event received with message: "
                            + args.ToString());
        RequestInterstitial();
    }

    public void HandleOnAdOpened(object sender, System.EventArgs args)
    {
        MonoBehaviour.print("HandleAdOpened event received");

    }

    public void HandleOnAdClosed(object sender, System.EventArgs args)
    {
        MonoBehaviour.print("HandleAdClosed event received");
        RequestInterstitial();
        SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex - 1);

    }

    public void HandleOnAdLeavingApplication(object sender, System.EventArgs args)
    {
        MonoBehaviour.print("HandleAdLeavingApplication event received");
        SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex - 1);

    }
    #endregion

    #region AdmobRewarded_Ad callback handlers

    public void HandleRewardedAdLoaded(object sender, System.EventArgs args)
    {
        MonoBehaviour.print("HandleRewardedAdLoaded event received");
    }

    public void HandleRewardedAdFailedToLoad(object sender, AdErrorEventArgs args)
    {
        MonoBehaviour.print(
            "HandleRewardedAdFailedToLoad event received with message: "
                             + args.AdError.GetMessage());
        // RequestAdmobRewarded();
    }

    public void HandleRewardedAdOpening(object sender, System.EventArgs args)
    {
        MonoBehaviour.print("HandleRewardedAdOpening event received");
        // RequestAdmobRewarded();
    }

    public void HandleRewardedAdFailedToShow(object sender, AdErrorEventArgs args)
    {
        MonoBehaviour.print(
            "HandleRewardedAdFailedToShow event received with message: "
                             + args.AdError.GetMessage());

        //  RequestAdmobRewarded();
    }

    public void HandleRewardedAdClosed(object sender, System.EventArgs args)
    {
        MonoBehaviour.print("HandleRewardedAdClosed event received");
        RequestAdmobRewarded();

    }

    public void HandleUserEarnedReward(object sender, Reward args)
    {
        string type = args.Type;
        double amount = args.Amount;

        if (PlayerPrefs.HasKey("adsRemoveCount"))
        {
            PlayerPrefs.SetInt("adsRemoveCount", PlayerPrefs.GetInt("adsRemoveCount") + 1);
        }
        else
        {
            PlayerPrefs.SetInt("adsRemoveCount", 1);
        }

    }

    #endregion

    #region  Ads Call Function

    public void ShowAdmobInterstial()
    {
        if (PlayerPrefs.GetInt("adsRemoveCount") <= 2)
        {
            if (interstitial.IsLoaded())
            {
                interstitial.Show();
            }
            else
            {
                RequestInterstitial();
            }
        }
    }
    public void ShowAdmobRewardedVideo()
    {
        if (PlayerPrefs.GetInt("adsRemoveCount") <= 2)
        {
            if (this.rewardedAd.IsLoaded())
            {
                this.rewardedAd.Show();
            }
            else
            {
                RequestAdmobRewarded();
            }
        }
    }
    #endregion
}
</code>```

Body:
I recently launched a game in unity which I uploaded on playstore. I was able to display ads when I just built an apk from the app but when I upload the app bundle on playstore and playstore launched that update, the ads stop displaying. My admob account is approved and my individual app's approval status is also 'Ready'.
I am not able to understand why my game is not displaying any ads as it should be working. All the ad ids are correct and it works fine in the normal apk. I am seeing proper ads.

Can someone help me please.

My AdManager Script

using GoogleMobileAds.Api;
using GoogleMobileAds.Common;
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class MediationManager : MonoBehaviour
{
    #region Ad_IDs
    public string app_Id;
    public string banner_Id;
    public string nativeBanner_Id;
    public string interstitial_Id;
    public string rewardedVideo_Id;

    public static MediationManager Instance;
    private BannerView bannerView;
    private BannerView nativebannerView;
    private InterstitialAd interstitial;
    private RewardedAd rewardedAd;
    #endregion

    private void Awake()
    {

        if (Instance == null)
        {
            Instance = this;
            DontDestroyOnLoad(this);
            print("again");
        }
        else
        {
            print("not again");

            Destroy(this.gameObject);
        }
    }
    // Start is called before the first frame update

    void Start()
    {

        MobileAds.SetiOSAppPauseOnBackground(true);
        //RequestConfiguration requestConfiguration =
        //   new RequestConfiguration.Builder()
        //   .SetTagForChildDirectedTreatment(TagForChildDirectedTreatment.True)
        //   .build();
        //MobileAds.SetRequestConfiguration(requestConfiguration);

        // Initialize the Google Mobile Ads SDK.
        MobileAds.Initialize(HandleInitCompleteAction);

    }

    private void HandleInitCompleteAction(InitializationStatus initstatus)
    {

        MobileAdsEventExecutor.ExecuteInUpdate(() =>
        {
            //RequestBanner();
            RequestInterstitial();
            RequestAdmobRewarded();
            // RequestNativeBanner();
            //ShowTopBanner();
        });
    }

    #region Request Ads
    public AdRequest CreateAdRequest()
    {
        return new AdRequest.Builder().Build();
    }
    private void RequestInterstitial()
    {
        if (PlayerPrefs.GetInt("adsRemoveCount") <= 2)
        {
            // Clean up interstitial ad before creating a new one.
            if (this.interstitial != null)
            {
                this.interstitial.Destroy();
            }

            // Create an interstitial.
            this.interstitial = new InterstitialAd(interstitial_Id);

            // Register for ad events.
            this.interstitial.OnAdLoaded += this.HandleOnAdLoaded;
            this.interstitial.OnAdFailedToLoad += this.HandleOnAdFailedToLoad;
            this.interstitial.OnAdOpening += this.HandleOnAdOpened;
            this.interstitial.OnAdClosed += this.HandleOnAdClosed;
            // this.interstitial. += this.HandleOnAdLeavingApplication;

            // Load an interstitial ad.
            this.interstitial.LoadAd(this.CreateAdRequest());
        }

    }
    public void RequestBanner()
    {
        if (PlayerPrefs.GetInt("RemoveAds") == 0)
        {
            // Clean up banner ad before creating a new one.
            if (this.bannerView != null)
            {
                this.bannerView.Destroy();
            }
            // Create a 320x50 banner at the top of the screen.
            this.bannerView = new BannerView(banner_Id, AdSize.Banner, AdPosition.Top);

            // Register for ad events.
            this.bannerView.OnAdLoaded += this.HandleAdLoaded;
            this.bannerView.OnAdFailedToLoad += this.HandleAdFailedToLoad;
            this.bannerView.OnAdOpening += this.HandleAdOpened;
            this.bannerView.OnAdClosed += this.HandleAdClosed;
            //this.bannerView.OnAdLeavingApplication += this.HandleAdLeftApplication;

            // Load a banner ad.
            this.bannerView.LoadAd(this.CreateAdRequest());
            this.bannerView.Hide();
            print("Show Top Banner");
        }
    }
    public void RequestNativeBanner()
    {
        if (PlayerPrefs.GetInt("RemoveAds") == 0)
        {
            if (this.nativebannerView != null)
            {
                this.nativebannerView.Destroy();
            }

            this.nativebannerView = new BannerView(banner_Id, AdSize.MediumRectangle, 0, 54);

            this.nativebannerView.LoadAd(this.CreateAdRequest());
            this.nativebannerView.Hide();
        }
    }
    private void RequestAdmobRewarded()
    {

        if (PlayerPrefs.GetInt("adsRemoveCount") <= 2)
        {
            this.rewardedAd = new RewardedAd(rewardedVideo_Id);

            // Called when an ad request has successfully loaded.
            this.rewardedAd.OnAdLoaded += HandleRewardedAdLoaded;
            // Called when an ad request failed to load.
            //      this.rewardedAd.OnAdFailedToLoad += HandleRewardedAdFailedToLoad;

            // Called when an ad is shown.
            this.rewardedAd.OnAdOpening += HandleRewardedAdOpening;
            // Called when an ad request failed to show.
            this.rewardedAd.OnAdFailedToShow += HandleRewardedAdFailedToShow;
            // Called when the user should be rewarded for interacting with the ad.
            this.rewardedAd.OnUserEarnedReward += HandleUserEarnedReward;
            // Called when the ad is closed.
            this.rewardedAd.OnAdClosed += HandleRewardedAdClosed;

            // Load the rewarded ad with the request.
            this.rewardedAd.LoadAd(this.CreateAdRequest());
        }
    }
    #endregion

    #region Banner callback handlers

    public void HandleAdLoaded(object sender, EventArgs args)
    {
        MonoBehaviour.print("HandleAdLoaded event received");
    }

    public void HandleAdFailedToLoad(object sender, AdFailedToLoadEventArgs args)
    {
        MonoBehaviour.print("HandleFailedToReceiveAd event received with message: " + args.LoadAdError);
    }

    public void HandleAdOpened(object sender, EventArgs args)
    {
        MonoBehaviour.print("HandleAdOpened event received");
    }

    public void HandleAdClosed(object sender, EventArgs args)
    {
        MonoBehaviour.print("HandleAdClosed event received");
    }

    public void HandleAdLeftApplication(object sender, EventArgs args)
    {
        MonoBehaviour.print("HandleAdLeftApplication event received");
    }

    #endregion

    #region Interstial callback handlers
    public void HandleOnAdLoaded(object sender, System.EventArgs args)
    {
        MonoBehaviour.print("HandleAdLoaded event received");
    }

    public void HandleOnAdFailedToLoad(object sender, AdFailedToLoadEventArgs args)
    {
        MonoBehaviour.print("HandleFailedToReceiveAd event received with message: "
                            + args.ToString());
        RequestInterstitial();
    }

    public void HandleOnAdOpened(object sender, System.EventArgs args)
    {
        MonoBehaviour.print("HandleAdOpened event received");

    }

    public void HandleOnAdClosed(object sender, System.EventArgs args)
    {
        MonoBehaviour.print("HandleAdClosed event received");
        RequestInterstitial();
        SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex - 1);

    }

    public void HandleOnAdLeavingApplication(object sender, System.EventArgs args)
    {
        MonoBehaviour.print("HandleAdLeavingApplication event received");
        SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex - 1);

    }
    #endregion

    #region AdmobRewarded_Ad callback handlers

    public void HandleRewardedAdLoaded(object sender, System.EventArgs args)
    {
        MonoBehaviour.print("HandleRewardedAdLoaded event received");
    }

    public void HandleRewardedAdFailedToLoad(object sender, AdErrorEventArgs args)
    {
        MonoBehaviour.print(
            "HandleRewardedAdFailedToLoad event received with message: "
                             + args.AdError.GetMessage());
        // RequestAdmobRewarded();
    }

    public void HandleRewardedAdOpening(object sender, System.EventArgs args)
    {
        MonoBehaviour.print("HandleRewardedAdOpening event received");
        // RequestAdmobRewarded();
    }

    public void HandleRewardedAdFailedToShow(object sender, AdErrorEventArgs args)
    {
        MonoBehaviour.print(
            "HandleRewardedAdFailedToShow event received with message: "
                             + args.AdError.GetMessage());

        //  RequestAdmobRewarded();
    }

    public void HandleRewardedAdClosed(object sender, System.EventArgs args)
    {
        MonoBehaviour.print("HandleRewardedAdClosed event received");
        RequestAdmobRewarded();

    }

    public void HandleUserEarnedReward(object sender, Reward args)
    {
        string type = args.Type;
        double amount = args.Amount;

        if (PlayerPrefs.HasKey("adsRemoveCount"))
        {
            PlayerPrefs.SetInt("adsRemoveCount", PlayerPrefs.GetInt("adsRemoveCount") + 1);
        }
        else
        {
            PlayerPrefs.SetInt("adsRemoveCount", 1);
        }

    }

    #endregion

    #region  Ads Call Function

    public void ShowAdmobInterstial()
    {
        if (PlayerPrefs.GetInt("adsRemoveCount") <= 2)
        {
            if (interstitial.IsLoaded())
            {
                interstitial.Show();
            }
            else
            {
                RequestInterstitial();
            }
        }
    }
    public void ShowAdmobRewardedVideo()
    {
        if (PlayerPrefs.GetInt("adsRemoveCount") <= 2)
        {
            if (this.rewardedAd.IsLoaded())
            {
                this.rewardedAd.Show();
            }
            else
            {
                RequestAdmobRewarded();
            }
        }
    }
    #endregion
}


问:
Cannot connect to chrome at 127.0.0.1 python undetected-chromedriver
Running the following on a machine running Ubuntu 22.094 LTS:

```<code>chrome_options = Options()
chrome_options.add_argument("--headless")
chrome_options.add_argument("--no-sandbox")
driver = uc.Chrome(executable_path='/home/samuel04/chromedriver', chrome_options=chrome_options)
</code>```

I get the following error: Message: unknown error: cannot connect to chrome at 127.0.0.1:42129

How could I fix this? My chromedriver and chrome are both on version 108 and undetected-chromedriver is 3.2.1.

Body:
Running the following on a machine running Ubuntu 22.094 LTS:

chrome_options = Options()
chrome_options.add_argument("--headless")
chrome_options.add_argument("--no-sandbox")
driver = uc.Chrome(executable_path='/home/samuel04/chromedriver', chrome_options=chrome_options)

I get the following error: Message: unknown error: cannot connect to chrome at 127.0.0.1:42129

How could I fix this? My chromedriver and chrome are both on version 108 and undetected-chromedriver is 3.2.1.


问:
Viewport problem in iphone chrome browser landscape mode
I'm having a special problem using Chrome on relatively newer iPhone models. (iPhone 11 or higher)

With the viewport set, there is no problem on portrait screen, but on landscape screen It doesn't seem to be calculating the width of the screen correctly.

current viewport settings :

```<code><meta name="viewport" content="target-densitydpi=device-dpi, user-scalable=yes, width=1200, minimal-ui, minimum-scale=0.25, viewport-fit=cover">
</code>```

In other words, the problem is that the content does not fit into the screen width properly and scrolling occurs.

!! It should be properly fitted as below !!

bug
normal

For reference, there is no problem at all in other device brand and browsers such as Safari and Firefox.

Is it possible to solve it by setting the viewport? Or should I write a separate script?

How can i solve it? I need your help.

Tried everything related to the viewport but failed..

Body:
I'm having a special problem using Chrome on relatively newer iPhone models. (iPhone 11 or higher)

With the viewport set, there is no problem on portrait screen, but on landscape screen It doesn't seem to be calculating the width of the screen correctly.

current viewport settings :

<meta name="viewport" content="target-densitydpi=device-dpi, user-scalable=yes, width=1200, minimal-ui, minimum-scale=0.25, viewport-fit=cover">

In other words, the problem is that the content does not fit into the screen width properly and scrolling occurs.

!! It should be properly fitted as below !!

bug
normal

For reference, there is no problem at all in other device brand and browsers such as Safari and Firefox.

Is it possible to solve it by setting the viewport? Or should I write a separate script?

How can i solve it? I need your help.

Tried everything related to the viewport but failed..


问:
Laravel and react not displaying component on page on certain path
I have a code below

app.js

```<code>/**
 * First we will load all of this project's JavaScript dependencies which
 * includes React and other helpers. It's a great starting point while
 * building robust, powerful web applications using React + Laravel.
 */

import './bootstrap';

/**
 * Next, we will create a fresh React component instance and attach it to
 * the page. Then, you may begin adding components to this application
 * or customize the JavaScript scaffolding to fit your unique needs.
 */

import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter as Router, Route } from 'react-router-dom';
import Index from './components/Index';

if (document.getElementById('app')) {
    const app = ReactDOM.createRoot(document.getElementById("app"));

    app.render(
        <React.StrictMode>
            <Router>
            <Route exact path="/" component={Index} />
            </Router>
        </React.StrictMode>
    )
}
</code>```

Basically on route (/) it should display index component but it's not showing up for some reason.

Welcome.blade.php

```<code><!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Welcome</title>
        <link href="{{ asset('css/app.css') }}" rel="stylesheet">
    </head>
    <body>
        <div id="app">
        </div>
        <script src="./js/app.js"></script>
    </body>
</html>
</code>```

I tried using react router but it's not working with what I currently have.

Body:
I have a code below

app.js

/**
 * First we will load all of this project's JavaScript dependencies which
 * includes React and other helpers. It's a great starting point while
 * building robust, powerful web applications using React + Laravel.
 */

import './bootstrap';

/**
 * Next, we will create a fresh React component instance and attach it to
 * the page. Then, you may begin adding components to this application
 * or customize the JavaScript scaffolding to fit your unique needs.
 */

import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter as Router, Route } from 'react-router-dom';
import Index from './components/Index';

if (document.getElementById('app')) {
    const app = ReactDOM.createRoot(document.getElementById("app"));

    app.render(
        <React.StrictMode>
            <Router>
            <Route exact path="/" component={Index} />
            </Router>
        </React.StrictMode>
    )
}

Basically on route (/) it should display index component but it's not showing up for some reason.

Welcome.blade.php

<!DOCTYPE html>
getLocale()) }}">

        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Welcome</title>
        <link href="{{ asset('css/app.css') }}" rel="stylesheet">

I tried using react router but it's not working with what I currently have.


问:
My link to a local markdown file does not work correctly
for example when link is: http://127.0.0.1:8000/entries/CSS

it throws an error:

```<code>Page not found (404)

“entries/CSS” does not exist
</code>```

But when i put a file format at the end (in this case it is .md) it downloads the file instead of opening it in my browser:

```<code><ul>
    {% for entry in entries %}
        <li><a href ="./entries/{{entry}}.md">{{ entry }}</li></a>
    {% endfor %}
</ul>
</code>```

link: 127.0.0.1:8000/entries/CSS.md

I need to open this pages in browser, how do i fix it?

Here is my urls.py file:

```<code>from django.conf import settings
from django.conf.urls.static import static
from . import views

urlpatterns = [
    path("", views.index, name="index"),
    path('newpage/', views.new_page, name = 'newpage'),
]

urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
</code>```

Body:
for example when link is: http://127.0.0.1:8000/entries/CSS

it throws an error:

Page not found (404)

“entries/CSS” does not exist

But when i put a file format at the end (in this case it is .md) it downloads the file instead of opening it in my browser:

    {% for entry in entries %}

{{ entry }}

    {% endfor %}

link: 127.0.0.1:8000/entries/CSS.md

I need to open this pages in browser, how do i fix it?

Here is my urls.py file:

from django.conf import settings
from django.conf.urls.static import static
from . import views

urlpatterns = [
    path("", views.index, name="index"),
    path('newpage/', views.new_page, name = 'newpage'),
]

urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)


问:
Cause of overflow when scrolling a table with fixed first column and first row of HTML

Problem

When I scroll a table with a fixed first column and first row in HTML, the scrolled column overtakes the first column and protrudes, as shown in the image below.

table.crossLine td:nth-of-type(2n-1){
    background: whitesmoke;
}

.rowFixed {
    position: sticky;
    top:      0;
    z-index: 100;
}

.colFixed {
    position: sticky;
    left: 0;
    z-index: 101;

}

.fixed {
    position: sticky;
    top:      0;
    left: 0;
    z-index: 102;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="ja"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
</head>
<div class="container" style="margin-left: 5px; margin-right: 0px;">
    <div class="row">
        <div style="width:100%; overflow:scroll;">
            <table class="table table-bordered text-nowrap crossLine" style="table-layout: fixed" >
                <thead class="thead-light bg-danger">
                <tr>
                    <th class="xl65 bg-light fixed" style="height:15pt;width:120px;"></th>
                    <th class="bg-danger rowFixed" style="width:45px; ">1</th>
                    <th class="bg-danger rowFixed" style="width:45px; ">2</th>
                    <th class="bg-danger rowFixed" style="width:45px; ">3</th>
                    <th class="bg-danger rowFixed" style="width:45px; ">4</th>
                    <th class="bg-danger rowFixed" style="width:45px; ">5</th>
                    <th class="bg-danger rowFixed" style="width:45px; ">6</th>
                    <th class="bg-danger rowFixed" style="width:45px; ">7</th>
                    <th class="bg-danger rowFixed" style="width:45px; ">8</th>
                    <th class="bg-danger rowFixed" style="width:45px; ">9</th>
                    <th class="bg-danger rowFixed" style="width:45px; ">10</th>
                </tr>
                </thead>
                <tbody><tr>
                    <th class="bg-danger colFixed" style="height:15pt;">A</th>
                    <td style="width:40px;" >0</td>
                    <td style="width:40px;" >0</td>
                    <td style="width:40px;" >0</td>
                    <td style="width:40px;" >0</td>
                    <td style="width:40px;" >0</td>
                    <td style="width:40px;" >0</td>
                    <td style="width:40px;" >0</td>
                    <td style="width:40px;" >0</td>
                    <td style="width:40px;" >0</td>
                    <td style="width:40px;" >0</td>
                </tr>
            </tbody></table>
        </div>
    </div>
</div>
</body></html></code>```

Question

Why does it stick out after scrolling?

Can you advise us to investigate the cause?
Is there a problem with the way the CSS is written?

Body:
Problem

When I scroll a table with a fixed first column and first row in HTML, the scrolled column overtakes the first column and protrudes, as shown in the image below.

table.crossLine td:nth-of-type(2n-1){
    background: whitesmoke;
}

.rowFixed {
    position: sticky;
    top:      0;
    z-index: 100;
}

.colFixed {
    position: sticky;
    left: 0;
    z-index: 101;

}

.fixed {
    position: sticky;
    top:      0;
    left: 0;
    z-index: 102;
}

<!DOCTYPE html>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

                    1
                    2
                    3
                    4
                    5
                    6
                    7
                    8
                    9
                    10

                    A
                    0
                    0
                    0
                    0
                    0
                    0
                    0
                    0
                    0
                    0

Question

Why does it stick out after scrolling?

Can you advise us to investigate the cause?
Is there a problem with the way the CSS is written?


问:
Calculating the average per day in pandas
I want to calculate the average per day but in a monthly table.

My data looks like this:

```<code>ID      order   col1    col2    col3    date1       date2       user    category
ID_1    Order1  data1   data2   data100 2022-06-19  2021-10-10  User1   HR
ID_2    Order2  data1   data3   data101 2022-07-26  2022-01-13  User1   HR
ID_3    Order3  data1   data4   data102 2022-02-17  2022-02-17  User1   HR
ID_4    Order4  data1   data5   data103 2022-02-17  2022-02-20  User1   HR
ID_5    Order5  data1   data6   data104 2022-02-21  2022-02-21  User1   HR
ID_6    Order6  data1   data7   data105 2022-02-23  2022-02-23  User1   Purchasing
ID_7    Order7  data1   data8   data106 2022-02-23  2022-02-23  User1   Purchasing
ID_8    Order8  data1   data9   data107 2022-02-23  2022-02-23  User1   Purchasing
ID_9    Order9  data1   data10  data108 2022-02-23  2022-02-23  User1   Purchasing
ID_10   Order10 data1   data11  data109 2022-02-23  2022-02-23  User2   Purchasing
ID_11   Order11 data1   data12  data110 2022-02-23  2022-02-23  User2   Purchasing
ID_12   Order12 data1   data13  data111 2022-02-23  2022-02-23  User2   Admin
ID_13   Order13 data1   data14  data112 2022-02-23  2022-02-23  User3   Admin
ID_14   Order14 data1   data15  data113 2022-02-23  2022-02-23  User3   Admin
ID_15   Order15 data1   data16  data114 2022-02-21  2022-02-23  User3   Admin
ID_16   Order16 data1   data17  data115 2022-02-23  2022-02-23  User3   Admin
ID_17   Order17 data1   data18  data116 2022-03-06  2022-03-06  User4   Purchasing
ID_18   Order18 data1   data19  data117 2022-03-04  2022-03-06  User4   Purchasing
ID_19   Order19 data1   data20  data118 2022-03-06  2022-03-06  User4   Admin
ID_20   Order20 data1   data21  data119 2022-03-06  2022-03-06  User4   Admin
ID_21   Order21 data1   data22  data120 2022-03-06  2022-03-06  User4   Admin
ID_22   Order22 data1   data23  data121 2022-03-06  2022-03-06  User5   HR
ID_23   Order23 data1   data24  data122 2022-03-06  2022-03-06  User5   HR
ID_24   Order24 data1   data25  data123 2022-03-06  2022-03-06  User5   HR
ID_25   Order25 data1   data26  data124 2022-03-06  2022-03-06  User5   Admin
ID_26   Order26 data1   data27  data125 2022-03-06  2022-03-06  User5   Admin
ID_27   Order27 data1   data28  data126 2022-03-06  2022-03-06  User5   Purchasing
ID_28   Order28 data1   data29  data127 2022-03-06  2022-03-06  User5   Purchasing
ID_29   Order29 data1   data30  data128 2022-03-06  2022-03-06  User5   Purchasing
</code>```

My output is:

```<code>user    category    January February    March   April   May June    July    August
User1   HR          0       3 | 1.0     0       0       0   0       0       0
        Purchasing  0       4 | 0.0     0       0       0   0       0       0
User2   Admin       0       1 | 0.0     0       0       0   0       0       0
        Purchasing  0       2 | 0.0     0       0       0   0       0       0
User3   Admin       0       4 | 0.5     0       0       0   0       0       0
User4   Admin       0       0           3 | 0.0 0       0   0       0       0
        Purchasing  0       0           2 | 1.0 0       0   0       0       0
User5   Admin       0       0           2 | 0.0 0       0   0       0       0
        HR          0       0           3 | 0.0 0       0   0       0       0
        Purchasing  0       0           3 | 0.0 0       0   0       0       0
</code>```

In each month column first value indicates the count and second value indicates the average per month.

My code looks like this:

```<code>df1= pd.read_csv("test_data.csv")
for i in range(1,13):
    m = str(i).zfill(2)
    start_date = '2022-'+str(m)+'-01'
    end_date = '2022-'+str(m)+'-31'

    mask = (df1['date1'] >= start_date) & (df1['date2'] <= end_date)
    df2 = df1.loc[mask]
    df2.date1 = pd.to_datetime(df2.date1)
    df2.date2 = pd.to_datetime(df2.date2)
    df2.drop(df2[df2.date2 < df2.date1].index, inplace=True)

    df2["days"] = (df2['date2'] - df2['date1']).dt.days
    combinations = pd.DataFrame(df2.groupby(['user','category'])
     .agg({'order':'count', 'days': 'mean'})
    )
    combinations['order'] = combinations['order'].astype(str)
    combinations['days'] = combinations['days'].astype(str)
    combinations["agg"]= combinations["order"].str.cat(combinations["days"], sep =" | ")
    combinations=combinations.drop(['order', 'days'], axis=1)
    if (i==1):
        final_df=combinations
    else:
        final_df=final_df.merge(combinations, how='outer', on=['user','category'])

final_df = final_df.fillna(0)
final_df.columns =['January','February','March','April','May','June','July','August','September','October','Novemeber','December']
display(final_df)
</code>```

My code gives me the average per month but I want to get average per day in each column of month. (How much average orders per day have been received in this month?)

********* EDITED ***********

My final output should look like the same as my current output except replacing the value of average per month to average per days (after the "|").

Thanks,

Body:
I want to calculate the average per day but in a monthly table.

My data looks like this:

ID      order   col1    col2    col3    date1       date2       user    category
ID_1    Order1  data1   data2   data100 2022-06-19  2021-10-10  User1   HR
ID_2    Order2  data1   data3   data101 2022-07-26  2022-01-13  User1   HR
ID_3    Order3  data1   data4   data102 2022-02-17  2022-02-17  User1   HR
ID_4    Order4  data1   data5   data103 2022-02-17  2022-02-20  User1   HR
ID_5    Order5  data1   data6   data104 2022-02-21  2022-02-21  User1   HR
ID_6    Order6  data1   data7   data105 2022-02-23  2022-02-23  User1   Purchasing
ID_7    Order7  data1   data8   data106 2022-02-23  2022-02-23  User1   Purchasing
ID_8    Order8  data1   data9   data107 2022-02-23  2022-02-23  User1   Purchasing
ID_9    Order9  data1   data10  data108 2022-02-23  2022-02-23  User1   Purchasing
ID_10   Order10 data1   data11  data109 2022-02-23  2022-02-23  User2   Purchasing
ID_11   Order11 data1   data12  data110 2022-02-23  2022-02-23  User2   Purchasing
ID_12   Order12 data1   data13  data111 2022-02-23  2022-02-23  User2   Admin
ID_13   Order13 data1   data14  data112 2022-02-23  2022-02-23  User3   Admin
ID_14   Order14 data1   data15  data113 2022-02-23  2022-02-23  User3   Admin
ID_15   Order15 data1   data16  data114 2022-02-21  2022-02-23  User3   Admin
ID_16   Order16 data1   data17  data115 2022-02-23  2022-02-23  User3   Admin
ID_17   Order17 data1   data18  data116 2022-03-06  2022-03-06  User4   Purchasing
ID_18   Order18 data1   data19  data117 2022-03-04  2022-03-06  User4   Purchasing
ID_19   Order19 data1   data20  data118 2022-03-06  2022-03-06  User4   Admin
ID_20   Order20 data1   data21  data119 2022-03-06  2022-03-06  User4   Admin
ID_21   Order21 data1   data22  data120 2022-03-06  2022-03-06  User4   Admin
ID_22   Order22 data1   data23  data121 2022-03-06  2022-03-06  User5   HR
ID_23   Order23 data1   data24  data122 2022-03-06  2022-03-06  User5   HR
ID_24   Order24 data1   data25  data123 2022-03-06  2022-03-06  User5   HR
ID_25   Order25 data1   data26  data124 2022-03-06  2022-03-06  User5   Admin
ID_26   Order26 data1   data27  data125 2022-03-06  2022-03-06  User5   Admin
ID_27   Order27 data1   data28  data126 2022-03-06  2022-03-06  User5   Purchasing
ID_28   Order28 data1   data29  data127 2022-03-06  2022-03-06  User5   Purchasing
ID_29   Order29 data1   data30  data128 2022-03-06  2022-03-06  User5   Purchasing

My output is:

user    category    January February    March   April   May June    July    August
User1   HR          0       3 | 1.0     0       0       0   0       0       0
        Purchasing  0       4 | 0.0     0       0       0   0       0       0
User2   Admin       0       1 | 0.0     0       0       0   0       0       0
        Purchasing  0       2 | 0.0     0       0       0   0       0       0
User3   Admin       0       4 | 0.5     0       0       0   0       0       0
User4   Admin       0       0           3 | 0.0 0       0   0       0       0
        Purchasing  0       0           2 | 1.0 0       0   0       0       0
User5   Admin       0       0           2 | 0.0 0       0   0       0       0
        HR          0       0           3 | 0.0 0       0   0       0       0
        Purchasing  0       0           3 | 0.0 0       0   0       0       0

In each month column first value indicates the count and second value indicates the average per month.

My code looks like this:

df1= pd.read_csv("test_data.csv")
for i in range(1,13):
    m = str(i).zfill(2)
    start_date = '2022-'+str(m)+'-01'
    end_date = '2022-'+str(m)+'-31'

    mask = (df1['date1'] >= start_date) & (df1['date2'] <= end_date)
    df2 = df1.loc[mask]
    df2.date1 = pd.to_datetime(df2.date1)
    df2.date2 = pd.to_datetime(df2.date2)
    df2.drop(df2[df2.date2 < df2.date1].index, inplace=True)

    df2["days"] = (df2['date2'] - df2['date1']).dt.days
    combinations = pd.DataFrame(df2.groupby(['user','category'])
     .agg({'order':'count', 'days': 'mean'})
    )
    combinations['order'] = combinations['order'].astype(str)
    combinations['days'] = combinations['days'].astype(str)
    combinations["agg"]= combinations["order"].str.cat(combinations["days"], sep =" | ")
    combinations=combinations.drop(['order', 'days'], axis=1)
    if (i==1):
        final_df=combinations
    else:
        final_df=final_df.merge(combinations, how='outer', on=['user','category'])

final_df = final_df.fillna(0)
final_df.columns =['January','February','March','April','May','June','July','August','September','October','Novemeber','December']
display(final_df)

My code gives me the average per month but I want to get average per day in each column of month. (How much average orders per day have been received in this month?)

********* EDITED ***********

My final output should look like the same as my current output except replacing the value of average per month to average per days (after the "|").

Thanks,


问:
How can I make two identical types two distinguishable types
How can I make non-primitive types A and B two distinguishable types in order to add type safety to the interface of function f?

```<code>constexpr std::size_t type_size{ 8U };
using A = std::array<char, type_size>;
using B = std::array<char, type_size>;

constexpr auto f(A const a, B const b)
{
   // Not shown logic here.
}
</code>```

Body:
How can I make non-primitive types A and B two distinguishable types in order to add type safety to the interface of function f?

constexpr std::size_t type_size{ 8U };
using A = std::array<char, type_size>;
using B = std::array<char, type_size>;

constexpr auto f(A const a, B const b)
{
   // Not shown logic here.
}


问:
Mock class with static method to execute test case in Springboot
Hi I have a class with static method as below

```<code>@Log4j2
@Profile("!ut")
@Component('CALC')
@ConditionalOnProperty(name = 'CALC', havingValue = 'VAL')
public class
ClassA extends ClassMain {
    public static org.apache.logging.log4j.Logger narrLogger;

    @Autowired
    IHCRefDataMgr ihcRefDataMgr;

    public ClassA(IHCRefDataMgr ihcRefDataMgr) {
        super(ihcRefDataMgr);
        this.ihcRefDataMgr = ihcRefDataMgr;
    }

    public boolean calculate(msg) {
        narrLogger = Narratives.getNarrativeLogger(msg)
    }
}
</code>```

I have another class where i trace the logs

```<code>@Data
@Component
@ConditionalOnProperty(name = 'CALC', havingValue = 'VAL')
@Log4j2
public class ClassB {

    Boolean prepareMap() {
        Boolean status = true;
        try {
            Set<String> securityKeys = ConcurrentHashMap.newKeySet();
            ClassA.narrLogger.trace("Security Keys for given BA:  {}", securityKeys);
            // doing some processing
        } catch (Exception e) {
            status = false;
            System.out.println(e);
        }
    }
}
</code>```

Now I want to write a test case for ClassB, In my debugger when I come to ClassA.narrLogger, i get null pointer exception. How can i mock ClassA and allow it to pass assuming i dont want to test narrLogger.

Test Case

```<code>@Log4j2
@SpringBootTest
@TestPropertySource(properties = {"spring.profiles.active=test,ut", "calculator.name = ClassA", "eureka.client.enabled = false"})
public class ClassBTest {

    ClassB classb;

    @Test
    public void prepareMapTest() {
        var status = classb.prepareMap();
        Assertions.assertEquals(true, status)
    }
}
</code>```

While running test case, it falls in exception as null pointer comes at ClassA.narrLogger

Body:
Hi I have a class with static method as below

@Log4j2
@Profile("!ut")
@Component('CALC')
@ConditionalOnProperty(name = 'CALC', havingValue = 'VAL')
public class
ClassA extends ClassMain {
    public static org.apache.logging.log4j.Logger narrLogger;

    @Autowired
    IHCRefDataMgr ihcRefDataMgr;

    public ClassA(IHCRefDataMgr ihcRefDataMgr) {
        super(ihcRefDataMgr);
        this.ihcRefDataMgr = ihcRefDataMgr;
    }

    public boolean calculate(msg) {
        narrLogger = Narratives.getNarrativeLogger(msg)
    }
}

I have another class where i trace the logs

@Data
@Component
@ConditionalOnProperty(name = 'CALC', havingValue = 'VAL')
@Log4j2
public class ClassB {

    Boolean prepareMap() {
        Boolean status = true;
        try {
            Set<String> securityKeys = ConcurrentHashMap.newKeySet();
            ClassA.narrLogger.trace("Security Keys for given BA:  {}", securityKeys);
            // doing some processing
        } catch (Exception e) {
            status = false;
            System.out.println(e);
        }
    }
}

Now I want to write a test case for ClassB, In my debugger when I come to ClassA.narrLogger, i get null pointer exception. How can i mock ClassA and allow it to pass assuming i dont want to test narrLogger.

Test Case

@Log4j2
@SpringBootTest
@TestPropertySource(properties = {"spring.profiles.active=test,ut", "calculator.name = ClassA", "eureka.client.enabled = false"})
public class ClassBTest {

    ClassB classb;

    @Test
    public void prepareMapTest() {
        var status = classb.prepareMap();
        Assertions.assertEquals(true, status)
    }
}

While running test case, it falls in exception as null pointer comes at ClassA.narrLogger


问:
How to enable vue-cookies as httponly
I'm using vue-cookies in my application and couldn't find any option to enable the httponly.vue-cookies

I have tried adding httponly:true, but it's not working

Vue.$cookies.config('7d','','',true, {httpOnly: true})

Title: How to enable vue-cookies as httponly


问:
How to pass return kwargs from flask's before_request to endpoint functions
I haven't been able to pass the return values of a @app.before_request function to the endpoint's function.

I want the app to be authentication first and add decorators in case authentication is not required.

Hope you guys can help me sort this one out.

```<code>@app.before_request
def check_authentication_user():
    if request.endpoint in _insecure_views:
        print("Skipped authentication")
        return

    try:
        cookieVal = request.cookies.get('usrCredentials')
        if not cookieVal:
            resp = make_response(redirect('/login'))
            return resp
        # Some code
        return cookieVal # I need to pass this return to the route's function
    except (InvalidToken):
        resp = make_response(redirect('/login'))
        return resp

def skip_authentication(fn):
    '''decorator to disable user authentication'''
    endpoint = fn.__name__
    _insecure_views.append(endpoint)
    return fn

@app.route('/')
@skip_authentication
def index(cookieVal):
    print("cookieVal: ", cookieVal)
    ### Some code with cookie val###
    return "data", 200
</code>```

I think if there's a way to treat the before_request as a wrapper to the endpoint's function it would work but I'm new to wrappers and have not been able to do so.

Also I know about the flask g variable but by using g I would have to check the data on the variables at every endpoint instead of the getting it directly in the parameters

Body:
I haven't been able to pass the return values of a @app.before_request function to the endpoint's function.

I want the app to be authentication first and add decorators in case authentication is not required.

Hope you guys can help me sort this one out.

@app.before_request
def check_authentication_user():
    if request.endpoint in _insecure_views:
        print("Skipped authentication")
        return

    try:
        cookieVal = request.cookies.get('usrCredentials')
        if not cookieVal:
            resp = make_response(redirect('/login'))
            return resp
        # Some code
        return cookieVal # I need to pass this return to the route's function
    except (InvalidToken):
        resp = make_response(redirect('/login'))
        return resp

def skip_authentication(fn):
    '''decorator to disable user authentication'''
    endpoint = fn.__name__
    _insecure_views.append(endpoint)
    return fn

@app.route('/')
@skip_authentication
def index(cookieVal):
    print("cookieVal: ", cookieVal)
    ### Some code with cookie val###
    return "data", 200

I think if there's a way to treat the before_request as a wrapper to the endpoint's function it would work but I'm new to wrappers and have not been able to do so.

Also I know about the flask g variable but by using g I would have to check the data on the variables at every endpoint instead of the getting it directly in the parameters


问:
Cassandra: Execution order of Insert statements in a Batch request
I have a table with the following schema:

```<code>CREATE TABLE IF NOT EXISTS data (
 key TEXT,
 created_at TIMEUUID,
 value TEXT,
 PRIMARY KEY (key, created_at)
) WITH CLUSTERING ORDER BY (created_at DESC);
</code>```

Data is appended only and to get the value of a key, we retrieve the record with latest created_at using the query:

```<code>SELECT * FROM data WHERE key = ? ORDER BY created_at DESC LIMIT 1
</code>```

In our application, we can insert multiple records of the same key using Batch statement as following:

```<code>BEGIN BATCH
INSERT INTO data (key, created_at, value) VALUES ('MyKey', now(), 'value1');
INSERT INTO data (key, created_at, value) VALUES ('MyKey', now(), 'value2');
....
INSERT INTO data (key, created_at, value) VALUES ('MyKey', now(), 'value10');
APPLY BATCH;
</code>```

What will be the latest record of this MyKey? Is the result deterministic?

I tested using values with random data and found that the value from SELECT query is always the value of the last statement of the batch.

My assumption is when the batch query sent to Coordinator node, the statements will be parsed by QueryProcessor in the order they appear in the batch query. And for each statement, the native function now() will be evaluated and a unique timeuuid generated in an increasing order.

now()
In the coordinator node, generates a new unique timeuuid in milliseconds when the statement is executed. The timestamp portion of the timeuuid conforms to the UTC (Universal Time) standard. This method is useful for inserting values. The value returned by now() is guaranteed to be unique.

Summary of findings regarding order of statements in a batch can be found in the comments.

Body:
I have a table with the following schema:

CREATE TABLE IF NOT EXISTS data (
 key TEXT,
 created_at TIMEUUID,
 value TEXT,
 PRIMARY KEY (key, created_at)
) WITH CLUSTERING ORDER BY (created_at DESC);

Data is appended only and to get the value of a key, we retrieve the record with latest created_at using the query:

SELECT * FROM data WHERE key = ? ORDER BY created_at DESC LIMIT 1

In our application, we can insert multiple records of the same key using Batch statement as following:

BEGIN BATCH
INSERT INTO data (key, created_at, value) VALUES ('MyKey', now(), 'value1');
INSERT INTO data (key, created_at, value) VALUES ('MyKey', now(), 'value2');
....
INSERT INTO data (key, created_at, value) VALUES ('MyKey', now(), 'value10');
APPLY BATCH;

What will be the latest record of this MyKey? Is the result deterministic?

I tested using values with random data and found that the value from SELECT query is always the value of the last statement of the batch.

My assumption is when the batch query sent to Coordinator node, the statements will be parsed by QueryProcessor in the order they appear in the batch query. And for each statement, the native function now() will be evaluated and a unique timeuuid generated in an increasing order.

now()
In the coordinator node, generates a new unique timeuuid in milliseconds when the statement is executed. The timestamp portion of the timeuuid conforms to the UTC (Universal Time) standard. This method is useful for inserting values. The value returned by now() is guaranteed to be unique.

Summary of findings regarding order of statements in a batch can be found in the comments.


问:
Python performance test is extremely slow
I'm trying to run a python performance test from pytest by starting 3 processes with subprocess.Popen(...). However, using the same commands from command line seems to be 50-100x faster than from pytest. I've the same result if I use for benchmarking an external process, or python code.

Is there any specific reason which can cause this slow behaviour on pytest?
What can be the reason for this?
Same machine, same commands, etc... .


问:
save model using joblib/pickle which is trained in a for loop
I am training my arima model in a for loop for unique combinations of a key column ,now i am creating an azureml pipeline for the same in which i am saving the trained model,my question is how should i save the trained model as if i save it in a loop it will override the trained model of previous iteration.

i tried appending my train data and then apply model.fit but i am predicting also in key combinations so i think that is not the right thing to do.Any suggestions please?

```<code>import pandas as pd

import time

def arima(train,test,k):

       predict_df=pd.DataFrame()
       model=ARIMA(train.astype(float),order=(1,1,1))
       res=model.fit()

       start_index= len(train)
       end_index= start_index + (len(test)-1)
       forecast=res.predict(start=start_index,end=end_index)
       forecast=forecast.reset_index(drop=True)
       #print(forecast)

       #y_actual=pd.DataFrame(test.Litres)
       #y_predict=pd.DataFrame(forecast)

       predict_df['Actual']=test.values
       predict_df['Predict']=forecast
       predict_df['Key'] = k
       # predict_df['Pack'] = pack

       return predict_df

#Creating key for the combination we need data in

train["Keep_Keys"] = train["Customer Level 3"]+train["Product Brand Level 2"]+train["Product Pack Level 3"]+train["Sales Office\Calendar Year/Week"]

test["Keep_Keys"] = test["Customer Level 3"]+test["Product Brand Level 2"]+test["Product Pack Level 3"]+test["Sales Office\Calendar Year/Week"]

#grouping data by key column

train_dict=train.groupby('Keep_Keys').apply(lambda x: dict(week_date = x['week_date'], cases = x['cases']))

test_dict=test.groupby('Keep_Keys').apply(lambda x: dict(week_date = x['week_date'], cases = x['cases']))

arima_pred=pd.DataFrame()

for k,v in train_dict.items():

    #print(train_dict[k]['cases'])
    arima_predict=arima(train_dict[k]['cases'],test_dict[k]['cases'],k)
    #print(naive_predict)
    arima_pred=arima_pred.append(arima_predict,ignore_index=True)
</code>```

Body:
I am training my arima model in a for loop for unique combinations of a key column ,now i am creating an azureml pipeline for the same in which i am saving the trained model,my question is how should i save the trained model as if i save it in a loop it will override the trained model of previous iteration.

i tried appending my train data and then apply model.fit but i am predicting also in key combinations so i think that is not the right thing to do.Any suggestions please?

import pandas as pd

import time

def arima(train,test,k):

       predict_df=pd.DataFrame()
       model=ARIMA(train.astype(float),order=(1,1,1))
       res=model.fit()

       start_index= len(train)
       end_index= start_index + (len(test)-1)
       forecast=res.predict(start=start_index,end=end_index)
       forecast=forecast.reset_index(drop=True)
       #print(forecast)

       #y_actual=pd.DataFrame(test.Litres)
       #y_predict=pd.DataFrame(forecast)

       predict_df['Actual']=test.values
       predict_df['Predict']=forecast
       predict_df['Key'] = k
       # predict_df['Pack'] = pack

       return predict_df

#Creating key for the combination we need data in

train["Keep_Keys"] = train["Customer Level 3"]+train["Product Brand Level 2"]+train["Product Pack Level 3"]+train["Sales Office\Calendar Year/Week"]

test["Keep_Keys"] = test["Customer Level 3"]+test["Product Brand Level 2"]+test["Product Pack Level 3"]+test["Sales Office\Calendar Year/Week"]

#grouping data by key column

train_dict=train.groupby('Keep_Keys').apply(lambda x: dict(week_date = x['week_date'], cases = x['cases']))

test_dict=test.groupby('Keep_Keys').apply(lambda x: dict(week_date = x['week_date'], cases = x['cases']))

arima_pred=pd.DataFrame()

for k,v in train_dict.items():

    #print(train_dict[k]['cases'])
    arima_predict=arima(train_dict[k]['cases'],test_dict[k]['cases'],k)
    #print(naive_predict)
    arima_pred=arima_pred.append(arima_predict,ignore_index=True)


问:
Trainig ckpt in tensorflow object detection
Can i ask if this is normal?

I0105 14:21:41.290731  1512 model_lib_v2.py:705] Step 19400 per-step time 0.530s
INFO:tensorflow:{'Loss/classification_loss': 313630.25,
'Loss/localization_loss': 1025.6028,
'Loss/regularization_loss': 10148650000.0,
'Loss/total_loss': 10148964000.0,
'learning_rate': 0.5674639}
I0105 14:21:41.293730  1512 model_lib_v2.py:708] {'Loss/classification_loss': 313630.25,
'Loss/localization_loss': 1025.6028,
'Loss/regularization_loss': 10148650000.0,
'Loss/total_loss': 10148964000.0,
'learning_rate': 0.5674639}


问:
cannot set a frame with no defined index and a scalar using "Loc" function
I'm using python 3
i was calculating RSI strategy but getting a "cannot set a frame with no defined index and a scalar"error

with data :
ticker_list

```<code>def RSIcalc(ticker):
    df = yf.download(ticker, start='2012-01-01')
    df['MA200'] = df['Adj Close'].rolling(window=200).mean()
    df['price change'] = df['Adj Close'].pct_change()
    df['Upmove'] = df['price change'].apply(lambda x: x if x>0 else 0)
    df['Downmove'] = df['price change'].apply(lambda x: abs(x) if x<0 else 0)
    df['avg Up']  = df['Upmove'].ewm(span=90).mean()
    df['avg Down'] = df['Downmove'].ewm(span=90).mean()
    df = df.dropna()
    df['RS'] = df['avg Up']/df['avg Down']
    df['RSI'] = df['RS'].apply(lambda x:100-(100/(x+1)))
    df.loc[(df['Adj Close']>df['MA200']) &(df['RSI']<30),'Buy'] = 'Yes'
    df.loc[(df['Adj Close']<df['MA200']) | (df['RSI']>30),'Buy'] = 'No'
    return df
</code>```
```<code>def getSignals(df):
    Buying_dates = []
    Selling_dates = []

    for i in range(len(df)):
        if "Yes" in df['Buy'].iloc[i]:
            Buying_dates.append(df.iloc[i+1].name)
            print(1)
            for j in range(1,11):
                if df['RSI'].iloc[i+j]>40:
                    Selling_dates.append(df.iloc[i+j+1].name)
                    break
                    print(0)
                elif j==10:
                    Selling_dates.append(df.iloc[i+j+1].name)
    return Buying_dates,Selling_dates
</code>```

after running these two cells

```<code>for tick in ticker_list['Symbol']:
    frame = RSIcalc(tick)
    buy, sell = getSignals(frame)
</code>```

I'm getting a valueerror

```<code>ValueError                                Traceback (most recent call last)
Input In [43], in <cell line: 1>()
      1 for tick in ticker_list['Symbol']:
----> 2     frame = RSIcalc(tick)
      3     buy, sell = getSignals(frame)

Input In [14], in RSIcalc(ticker)
     10 df['RS'] = df['avg Up']/df['avg Down']
     11 df['RSI'] = df['RS'].apply(lambda x:100-(100/(x+1)))
---> 12 df.loc[(df['Adj Close']>df['MA200']) &(df['RSI']<30),'Buy'] = 'Yes'
     13 df.loc[(df['Adj Close']<df['MA200']) | (df['RSI']>30),'Buy'] = 'No'
     14 return df

File ~\Anaconda3\lib\site-packages\pandas\core\indexing.py:716, in _LocationIndexer.__setitem__(self, key, value)
    713 self._has_valid_setitem_indexer(key)
    715 iloc = self if self.name == "iloc" else self.obj.iloc
--> 716 iloc._setitem_with_indexer(indexer, value, self.name)

File ~\Anaconda3\lib\site-packages\pandas\core\indexing.py:1615, in _iLocIndexer._setitem_with_indexer(self, indexer, value, name)
   1613 if not len(self.obj):
   1614     if not is_list_like_indexer(value):
-> 1615         raise ValueError(
   1616             "cannot set a frame with no "
   1617             "defined index and a scalar"
   1618         )
   1619     self.obj[key] = value
   1620     return

ValueError: cannot set a frame with no defined index and a scalar
</code>```

How do i fix this

have set "pd.options.mode.chained_assignment = None" but no luck

Body:
I'm using python 3
i was calculating RSI strategy but getting a "cannot set a frame with no defined index and a scalar"error

with data :
ticker_list

def RSIcalc(ticker):
    df = yf.download(ticker, start='2012-01-01')
    df['MA200'] = df['Adj Close'].rolling(window=200).mean()
    df['price change'] = df['Adj Close'].pct_change()
    df['Upmove'] = df['price change'].apply(lambda x: x if x>0 else 0)
    df['Downmove'] = df['price change'].apply(lambda x: abs(x) if x<0 else 0)
    df['avg Up']  = df['Upmove'].ewm(span=90).mean()
    df['avg Down'] = df['Downmove'].ewm(span=90).mean()
    df = df.dropna()
    df['RS'] = df['avg Up']/df['avg Down']
    df['RSI'] = df['RS'].apply(lambda x:100-(100/(x+1)))
    df.loc[(df['Adj Close']>df['MA200']) &(df['RSI']<30),'Buy'] = 'Yes'
    df.loc[(df['Adj Close']<df['MA200']) | (df['RSI']>30),'Buy'] = 'No'
    return df

def getSignals(df):
    Buying_dates = []
    Selling_dates = []

    for i in range(len(df)):
        if "Yes" in df['Buy'].iloc[i]:
            Buying_dates.append(df.iloc[i+1].name)
            print(1)
            for j in range(1,11):
                if df['RSI'].iloc[i+j]>40:
                    Selling_dates.append(df.iloc[i+j+1].name)
                    break
                    print(0)
                elif j==10:
                    Selling_dates.append(df.iloc[i+j+1].name)
    return Buying_dates,Selling_dates

after running these two cells

for tick in ticker_list['Symbol']:
    frame = RSIcalc(tick)
    buy, sell = getSignals(frame)

I'm getting a valueerror

ValueError                                Traceback (most recent call last)
Input In [43], in <cell line: 1>()
      1 for tick in ticker_list['Symbol']:
----> 2     frame = RSIcalc(tick)
      3     buy, sell = getSignals(frame)

Input In [14], in RSIcalc(ticker)
     10 df['RS'] = df['avg Up']/df['avg Down']
     11 df['RSI'] = df['RS'].apply(lambda x:100-(100/(x+1)))
---> 12 df.loc[(df['Adj Close']>df['MA200']) &(df['RSI']<30),'Buy'] = 'Yes'
     13 df.loc[(df['Adj Close']<df['MA200']) | (df['RSI']>30),'Buy'] = 'No'
     14 return df

File ~\Anaconda3\lib\site-packages\pandas\core\indexing.py:716, in _LocationIndexer.__setitem__(self, key, value)
    713 self._has_valid_setitem_indexer(key)
    715 iloc = self if self.name == "iloc" else self.obj.iloc
--> 716 iloc._setitem_with_indexer(indexer, value, self.name)

File ~\Anaconda3\lib\site-packages\pandas\core\indexing.py:1615, in _iLocIndexer._setitem_with_indexer(self, indexer, value, name)
   1613 if not len(self.obj):
   1614     if not is_list_like_indexer(value):
-> 1615         raise ValueError(
   1616             "cannot set a frame with no "
   1617             "defined index and a scalar"
   1618         )
   1619     self.obj[key] = value
   1620     return

ValueError: cannot set a frame with no defined index and a scalar

How do i fix this

have set "pd.options.mode.chained_assignment = None" but no luck


问:
Using Django formset displaying related names in template
I am trying to display the state values for each country name in Django app. To save the user response, I am using Django generic CreateView. My models look something like this:

```<code>class Question(model.Models):
    ques_id = models.AutoField(primary_key=True)
    country = models.ForeignKey(Country)
    state = models.CharField(max_length=...)

class Test(model.Models):
    test = models.AutoField(primary_key=True, )
    test_num = models.CharField(max_length=6, )

class Response(model.Models):
    response = models.AutoField(primary_key=True)
    test_id = models.ForeignKey(Test, related_name='test', )
    ques_offered = models.ForeignKey(Question, related_name='choice',
    ans_submitted = models.CharField(max_length=240,
</code>```

To display the available choices for field state for each country value (in the db), I am looping through Django management form for the formset in my template. However, I am unable to get to the values of field state instead I am getting the country values.

Additional info:

The views that I am using to achieve this:

```<code>class ResponseCreateView(CreateView):
    template_name = ...
    model = Test
    form_class = # Form_name

def get_context_data(self, **kwargs):

    data = super(ResponseCreateView, self).get_context_data(**kwargs)
    if self.request.POST:
        data['get_response'] = responseFormset(self.request.POST, self.request.FILES)
    else:
        data['get_response'] = responseFormset()

    def form_valid(self, form):
        context = self.get_context_data()
        get_response = context['get_response']

        with transaction.atomic():
            if get_response.is_valid():
                self.object = form.save()
                get_response.instance = self.object
                get_response.save()
                return redirect('...')
            else:
                context.update({'get_response': get_response,
                                })
                return self.render_to_response(context)
        return super(ResponseCreateView, self).form_valid(form)
</code>```

Body:
I am trying to display the state values for each country name in Django app. To save the user response, I am using Django generic CreateView. My models look something like this:

class Question(model.Models):
    ques_id = models.AutoField(primary_key=True)
    country = models.ForeignKey(Country)
    state = models.CharField(max_length=...)

class Test(model.Models):
    test = models.AutoField(primary_key=True, )
    test_num = models.CharField(max_length=6, )

class Response(model.Models):
    response = models.AutoField(primary_key=True)
    test_id = models.ForeignKey(Test, related_name='test', )
    ques_offered = models.ForeignKey(Question, related_name='choice',
    ans_submitted = models.CharField(max_length=240,

To display the available choices for field state for each country value (in the db), I am looping through Django management form for the formset in my template. However, I am unable to get to the values of field state instead I am getting the country values.

Additional info:

The views that I am using to achieve this:

class ResponseCreateView(CreateView):
    template_name = ...
    model = Test
    form_class = # Form_name

def get_context_data(self, **kwargs):

    data = super(ResponseCreateView, self).get_context_data(**kwargs)
    if self.request.POST:
        data['get_response'] = responseFormset(self.request.POST, self.request.FILES)
    else:
        data['get_response'] = responseFormset()

    def form_valid(self, form):
        context = self.get_context_data()
        get_response = context['get_response']

        with transaction.atomic():
            if get_response.is_valid():
                self.object = form.save()
                get_response.instance = self.object
                get_response.save()
                return redirect('...')
            else:
                context.update({'get_response': get_response,
                                })
                return self.render_to_response(context)
        return super(ResponseCreateView, self).form_valid(form)


问:
Qt C++ GUI not drawing till pooled thread ends
I'm calling a function on QMainWindow's constructor via QtConcurrent in hope that the GUI will be up and showing while the background IO bound task will be processing in the background:

MainWindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QtConcurrent>
#include <QFuture>

QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE

class MainWindow: public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = nullptr);
    ~MainWindow();
private:
    Ui::MainWindow *ui;
    int init();
};
#endif

```
<p><strong>MainWindow.cpp</strong></p>
<pre class="lang-cpp prettyprint-override"><code>MainWindow::MainWindow(QWidget *parent):QMainWindow(parent),ui(new MainWindow){
    ui->setupUi(this);
    ui->myLabel->setText("");
    ui->progress->setVisible(false);
    QFuture<int>future=QtConcurrent::run(MainWindow::init,this);
    if(future.result()==0){
        qInfo()<<"Init successful";
    }else{
        qInfo()<<"Init not successful";
    }
}

int MainWindow::init(){
    QThread::sleep(4);    //simulate IO task
    return 0;
}
</code>```

But the GUI doesn't appear until init finishes. How to detach this pooled thread with main thread? Or from where should I run this thread?

EDIT: added QFutureWatcher to constructor but I don't know how to pass the return value of init to another function done:

MainWindow::MainWindow(QWidget *parent):QMainWindow(parent),ui(new MainWindow){
    ui->setupUi(this);
    ui->myLabel->setText("");
    ui->progress->setVisible(false);
    QFutureWatcher<int> watcher;
    QFuture future;
    connect(&watcher,QFutureWatcher<int>::finished,this,done(future.result())));//wrong code; need help here
    future=QtConcurrent::run(MainWindow::init,this);
}

int MainWindow::init(){
    QThread::sleep(4);    //simulate IO task
    return 0;
}
void done(int val){
    if(val==0){
        qInfo()<<"Init successful";
    }else{
        qInfo()<<"Init not successful";
    }
}
```

Body:
I'm calling a function on QMainWindow's constructor via QtConcurrent in hope that the GUI will be up and showing while the background IO bound task will be processing in the background:

MainWindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QtConcurrent>
#include <QFuture>

QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE

class MainWindow: public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = nullptr);
    ~MainWindow();
private:
    Ui::MainWindow *ui;
    int init();
};
#endif

MainWindow.cpp

MainWindow::MainWindow(QWidget *parent):QMainWindow(parent),ui(new MainWindow){
    ui->setupUi(this);
    ui->myLabel->setText("");
    ui->progress->setVisible(false);
    QFuture<int>future=QtConcurrent::run(MainWindow::init,this);
    if(future.result()==0){
        qInfo()<<"Init successful";
    }else{
        qInfo()<<"Init not successful";
    }
}

int MainWindow::init(){
    QThread::sleep(4);    //simulate IO task
    return 0;
}

But the GUI doesn't appear until init finishes. How to detach this pooled thread with main thread? Or from where should I run this thread?

EDIT: added QFutureWatcher to constructor but I don't know how to pass the return value of init to another function done:

MainWindow::MainWindow(QWidget *parent):QMainWindow(parent),ui(new MainWindow){
    ui->setupUi(this);
    ui->myLabel->setText("");
    ui->progress->setVisible(false);
    QFutureWatcher<int> watcher;
    QFuture future;
    connect(&watcher,QFutureWatcher<int>::finished,this,done(future.result())));//wrong code; need help here
    future=QtConcurrent::run(MainWindow::init,this);
}

int MainWindow::init(){
    QThread::sleep(4);    //simulate IO task
    return 0;
}
void done(int val){
    if(val==0){
        qInfo()<<"Init successful";
    }else{
        qInfo()<<"Init not successful";
    }
}


问:
Problem with OWIN Authorization Server MachineKey Validation
Hello Guys I'm kind of desperate because I'm not able to figure out what's happening here:
I have been in charge of the upgrade from .NET Framework 4.5.1 to 4.8 of a Legacy Application that no one has changed for several years, it creates bearer tokens using OWIN Authorization and is targeting .NET framework 4.8.
Some other services consume these tokens as bearer tokens, so far I have been able to create the tokens using the Authorization server but when I try to consume them on the services I see that the consumer cannot get the claims successfully.
I have been told that the machine key property must match in both services but despite the two services having the same machine key I keep getting unauthorized responses.

The Auth Server WebConfig Looks like this:

```<code><system.web>
    <compilation debug="true" targetFramework="4.8" />
    <httpRuntime targetFramework="4.8" />
    <machineKey validationKey="xxx" decryptionKey="aaa" validation="SHA1" decryption="AES" />
  </system.web>
</code>```

And the Consumer Service Web Config Looks like this:

```<code><system.web>
    <compilation debug="true" targetFramework="4.8">
      <!-- <assemblies>
        <add assembly="AuthComponent2, Version=4.0.0.0, Culture=neutral, PublicKeyToken=457ad908cac10889, processorArchitecture=MSIL" />
        <add assembly="Disney.IAME.Keystone.KeystoneDAL, Version=1.0.10.0, Culture=neutral, processorArchitecture=MSIL" />
        <add assembly="Disney.Keystone.Common.Model.Service, Version=1.0.10.0, Culture=neutral, processorArchitecture=MSIL" />
        <add assembly="Microsoft.Web.Services3, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL" />
        <add assembly="System.IO.Compression, Version=4.2.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
      </assemblies> -->
    </compilation>
    <httpRuntime targetFramework="4.8"/>
    <machineKey validationKey="xxx" decryptionKey="aaa" validation="SHA1" decryption="AES"/>
  </system.web>
</code>```

If you guys know if there is something missing that I can check I will be very very grateful.
Thanks in advance.

Body:
Hello Guys I'm kind of desperate because I'm not able to figure out what's happening here:
I have been in charge of the upgrade from .NET Framework 4.5.1 to 4.8 of a Legacy Application that no one has changed for several years, it creates bearer tokens using OWIN Authorization and is targeting .NET framework 4.8.
Some other services consume these tokens as bearer tokens, so far I have been able to create the tokens using the Authorization server but when I try to consume them on the services I see that the consumer cannot get the claims successfully.
I have been told that the machine key property must match in both services but despite the two services having the same machine key I keep getting unauthorized responses.

The Auth Server WebConfig Looks like this:

<system.web>
    <compilation debug="true" targetFramework="4.8" />
    <httpRuntime targetFramework="4.8" />
    <machineKey validationKey="xxx" decryptionKey="aaa" validation="SHA1" decryption="AES" />
  </system.web>

And the Consumer Service Web Config Looks like this:

<system.web>
    <compilation debug="true" targetFramework="4.8">

    </compilation>
    <httpRuntime targetFramework="4.8"/>
    <machineKey validationKey="xxx" decryptionKey="aaa" validation="SHA1" decryption="AES"/>
  </system.web>

If you guys know if there is something missing that I can check I will be very very grateful.
Thanks in advance.


问:
How do I decrease load time for generating around 1000 divs?
I'm working on my portfolio website so, I was trying some animation for the landing page. Everything is working fine but the animation takes very long time to load. I was generating a matrix of divs using JS and appling CSS and  animation to each one of them. Please suggest something to decrease the load time.
My Website

Javascript

```<code>let holder = document.getElementById("hero");

let gs = 25;

window.onload = () => {
  for (let i = 0; i < gs; i++) {
    for (let j = 0; j < gs; j++) {
      let dot = document.createElement("div");
      dot.classList.add("dot");
      dot.style.animationDelay = `${Math.sin(i * j) / 2}s`;
      holder.appendChild(dot);
    }
  }
};
</code>```

CSS

```<code>.hero {
  /* background-image: url(media/Background.jpg); */
  height: 100vh;
  position: absolute;
  width: 100%;
  display: grid;
  grid-template-columns: repeat(50, 90px);
  grid-template-rows: repeat(50, 90px);
  overflow: hidden;
  text-align: left;
}

.dot {
  width: 2px;
  height: 2px;
  animation-name: wavyDots;
  animation-duration: 1s;
  animation-iteration-count: infinite;
  animation-direction: alternate-reverse;
  z-index: -1;
}

.dot:nth-child(odd) {
  background-color: #0cf5d5;
}

.dot:nth-child(even) {
  background-color: #e0017a;
}

@keyframes wavyDots {
  0% {
    transform: translate(0, 0);
  }
  100% {
    transform: translate(30px, 30px);
  }
}
</code>```

I tried decreasing the matrix size but didn't help much, if I decrease more then I don't have enough divs to cover my entire page.

Body:
I'm working on my portfolio website so, I was trying some animation for the landing page. Everything is working fine but the animation takes very long time to load. I was generating a matrix of divs using JS and appling CSS and  animation to each one of them. Please suggest something to decrease the load time.
My Website

Javascript

let holder = document.getElementById("hero");

let gs = 25;

window.onload = () => {
  for (let i = 0; i < gs; i++) {
    for (let j = 0; j < gs; j++) {
      let dot = document.createElement("div");
      dot.classList.add("dot");
      dot.style.animationDelay = `${Math.sin(i * j) / 2}s`;
      holder.appendChild(dot);
    }
  }
};

CSS

.hero {
  /* background-image: url(media/Background.jpg); */
  height: 100vh;
  position: absolute;
  width: 100%;
  display: grid;
  grid-template-columns: repeat(50, 90px);
  grid-template-rows: repeat(50, 90px);
  overflow: hidden;
  text-align: left;
}

.dot {
  width: 2px;
  height: 2px;
  animation-name: wavyDots;
  animation-duration: 1s;
  animation-iteration-count: infinite;
  animation-direction: alternate-reverse;
  z-index: -1;
}

.dot:nth-child(odd) {
  background-color: #0cf5d5;
}

.dot:nth-child(even) {
  background-color: #e0017a;
}

@keyframes wavyDots {
  0% {
    transform: translate(0, 0);
  }
  100% {
    transform: translate(30px, 30px);
  }
}

I tried decreasing the matrix size but didn't help much, if I decrease more then I don't have enough divs to cover my entire page.


问:
Tomcat 6 and foreign characters (UTF-8 and non UTF-8 mixup)
I have a problem displaying foreign language characters in web app with Tomcat 6. Previously we were using Tomcat 5.5 and we did not face this issue. To fix this issue I followed http://wiki.apache.org/tomcat/FAQ/CharacterEncoding#Q8 and made changes to my web app accordingly. Now the web app supports URF-8 encoding and most of the issues with encoding are fixed. The bigger problem that I am facing now is with the old data that is stored in the database using the app with Tomcat 5.5. The old data is not displayed correctly on the webapp with UTF-8 encoding. What is the best way to to have the webapp configured with UTF-8 encoding and also to be able to display the old data which are not UTF-8 encoded?

Also, the I am not able to determine what encoding was used previously. Thanks.

ContentLicense: CC BY-SA 3.0


问:
Race condition in Google Appsheet when updating row after created
It seems I'm experiencing a race condition in Google Appsheet:

I've configured a Behavior in my form view: Once the form is saved -> run 'Data: set the values of some columns in this row' (edit one of the fields). Looking in the chrome developer tools, I see two calls are sent to AppSheet API - one to create the row and another to edit it:

The update is working correctly. Still, then there is a screen flickering, and the original value before the set data action overrides the edited value again. Eventually, the initial value is saved to the DB, not the new one.

My app is working against Postgres (RDS) DB

https://www.appsheet.com/api/template/<row_id>/table/<table_name>/row
https://www.appsheet.com/api/template/<row_id>/table/<table_name>/row/update


问:
What is the role of the CX in 42h DOS function in assembly Language?
```<code>
    mov ah, 42h
    mov bx, address
    xor cx, cx
    xor dx, dx
    mov al, 2
    int 21h
</code>```

This is the Code I wrote to move file pointer

What's actually the Role of cx register? when I do mov cx, 1. It created file with the size of 15mb -_-. Basically, I am not understanding what actually cx is doing.

Body:
    mov ah, 42h
    mov bx, address
    xor cx, cx
    xor dx, dx
    mov al, 2
    int 21h

This is the Code I wrote to move file pointer

What's actually the Role of cx register? when I do mov cx, 1. It created file with the size of 15mb -_-. Basically, I am not understanding what actually cx is doing.


问:
create log file name with current date using appenders path present in log4rs YAML configuration file
I want to add the current date to the log file name using log4rs library based on YAML configuration file. Although we perform daily rollovers, the current log file lacks a date. The format for the log file name would be logs/Application.2023-01-04.log . But using the below code i am getting file name as same whatever i have given in path filed. Any idea on this?

Please find the code i am using below.

```<code>refresh_rate: 600 seconds
appenders:
stdout:
kind: console
encoder:
pattern: "{d(%Y-%m-%d %H:%M:%S)(utc)} - | {h({l}):5} | {f}:{L} — {m}{n}"
file_logger:
kind: file
path: "logs/Application.{d}-{m}-{n}.log"
encoder:
pattern: "{d(%Y-%m-%d %H:%M:%S)(utc)} - | {h({l}):5} | {f}:{L} — {m}{n}"
root:
level: info
appenders:
- stdout
- file_logger
</code>```

Body:
I want to add the current date to the log file name using log4rs library based on YAML configuration file. Although we perform daily rollovers, the current log file lacks a date. The format for the log file name would be logs/Application.2023-01-04.log . But using the below code i am getting file name as same whatever i have given in path filed. Any idea on this?

Please find the code i am using below.

refresh_rate: 600 seconds
appenders:
stdout:
kind: console
encoder:
pattern: "{d(%Y-%m-%d %H:%M:%S)(utc)} - | {h({l}):5} | {f}:{L} — {m}{n}"
file_logger:
kind: file
path: "logs/Application.{d}-{m}-{n}.log"
encoder:
pattern: "{d(%Y-%m-%d %H:%M:%S)(utc)} - | {h({l}):5} | {f}:{L} — {m}{n}"
root:
level: info
appenders:
- stdout
- file_logger


问:
Windows batch command to move all the files whose contents start by 0 to a dedicated folder
There are some files with extension .out in a folder. They can be opened as text. The contents of some of these files start by the character 0. I want to move them to a dedicated folder (named zero) using a Windows batch command.

I tried the following:

```<code>@echo off
setlocal EnableDelayedExpansion
for %%x in (*.out) do (set /p y=< "%%x" & echo !y! & if !y:~0,1!==0 move "%%x" "zero")
</code>```

but it does not work... How to do that?

Body:
There are some files with extension .out in a folder. They can be opened as text. The contents of some of these files start by the character 0. I want to move them to a dedicated folder (named zero) using a Windows batch command.

I tried the following:

@echo off
setlocal EnableDelayedExpansion
for %%x in (*.out) do (set /p y=< "%%x" & echo !y! & if !y:~0,1!==0 move "%%x" "zero")

but it does not work... How to do that?