问:
Blazor WASM - statehaschanged not rerendering dropdown
I have the following dropdown that holds a list of zones for my project.

```<code>            <div class="col-9">
                <select class="coral-input" style="width:200px" @onchange="ChangeZone" @onchange:stopPropagation="true">
                    @if (zones.Count > 0)
                    {
                        count = 0;
                        foreach (var zone in zones)
                        {
                            if (count == 0)
                            {
                                <option value="@zone" selected>@zone</option>
                            }
                            else
                            {
                                <option value="@zone">@zone</option>
                            }
                            count++;
                        }
                    }
                </select>
            </div>
</code>```

When a page is selected by clicking on it this Task is used

```<code>        private async Task PageSelected(FlyerPage p, int pIndexInList, bool propagateSelection)
        {
            loading = true;

            //   FlyerSvc.SelectPage(p);
            selectedPageIndex = pIndexInList;
            IsAddBlockDisabled = selectedPage == null;

            try
            {
                if (propagateSelection)
                {
                    _dispatcher.Dispatch(new SelectPageAction(p));
                    _dispatcher.Dispatch(new LoadBlocksAction(p.Id));
                }

                GetZones();
                StateHasChanged();
            }
            catch
            {
                throw;
            }
            finally
            {
                loading = false;
            }
        }
</code>```

My GetZones() method then does the following

```<code>        private void GetZones()
        {

            zones.Clear();
            flyerBlockZones = flyerBlocks.Where(b => b.PageId == selectedPage.Id).Where(x => x.DocumentName != null).Select(b => b.Zones).ToList();
            foreach (var flyerBlockZone in flyerBlockZones.Where(z => z != null))
            {
                for (int i = 0; i < flyerBlockZone.Length; i++)
                {
                    if (!zones.Contains(flyerBlockZone[i]))
                        zones.Add(flyerBlockZone[i]);
                }
            }

            zones = zones.OrderBy(z => z).ToList();
            flyerPageToolbar.AddZones(zones);

            if (zones.Count > 0)
                zone = zones[0];
            else
                zone = "";
            ChangeZone(zone);
        }
</code>```

and finally this leads to my ChangeZone() method which assigns the zone in the UI

```<code>        public void ChangeZone(string zone)
        {
            this.zone = zone;
            pageDetailsComponent.ChangeZone(this.zone);
            StateHasChanged();
        }
</code>```

The problem I am running into is that when a page is selected my dropdown does not update even when my ChangeZone() method is being used. I can't figure out why. Now I can use NavManager to just refresh and have everything reset but it would make my application look a bit clunky so I am trying to avoid that. Any help would be appreciated.

Body:
I have the following dropdown that holds a list of zones for my project.

                <select class="coral-input" style="width:200px" @onchange="ChangeZone" @onchange:stopPropagation="true">
                    @if (zones.Count > 0)
                    {
                        count = 0;
                        foreach (var zone in zones)
                        {
                            if (count == 0)
                            {
                                <option value="@zone" selected>@zone</option>
                            }
                            else
                            {
                                <option value="@zone">@zone</option>
                            }
                            count++;
                        }
                    }
                </select>

When a page is selected by clicking on it this Task is used

        private async Task PageSelected(FlyerPage p, int pIndexInList, bool propagateSelection)
        {
            loading = true;

            //   FlyerSvc.SelectPage(p);
            selectedPageIndex = pIndexInList;
            IsAddBlockDisabled = selectedPage == null;

            try
            {
                if (propagateSelection)
                {
                    _dispatcher.Dispatch(new SelectPageAction(p));
                    _dispatcher.Dispatch(new LoadBlocksAction(p.Id));
                }

                GetZones();
                StateHasChanged();
            }
            catch
            {
                throw;
            }
            finally
            {
                loading = false;
            }
        }

My GetZones() method then does the following

        private void GetZones()
        {

            zones.Clear();
            flyerBlockZones = flyerBlocks.Where(b => b.PageId == selectedPage.Id).Where(x => x.DocumentName != null).Select(b => b.Zones).ToList();
            foreach (var flyerBlockZone in flyerBlockZones.Where(z => z != null))
            {
                for (int i = 0; i < flyerBlockZone.Length; i++)
                {
                    if (!zones.Contains(flyerBlockZone[i]))
                        zones.Add(flyerBlockZone[i]);
                }
            }

            zones = zones.OrderBy(z => z).ToList();
            flyerPageToolbar.AddZones(zones);

            if (zones.Count > 0)
                zone = zones[0];
            else
                zone = "";
            ChangeZone(zone);
        }

and finally this leads to my ChangeZone() method which assigns the zone in the UI

        public void ChangeZone(string zone)
        {
            this.zone = zone;
            pageDetailsComponent.ChangeZone(this.zone);
            StateHasChanged();
        }

The problem I am running into is that when a page is selected my dropdown does not update even when my ChangeZone() method is being used. I can't figure out why. Now I can use NavManager to just refresh and have everything reset but it would make my application look a bit clunky so I am trying to avoid that. Any help would be appreciated.


来源: stackexchange

问:
Blazor: using pdfjs in iframe creates multiple instances
I have a Blazor app (WASM). In it I use mozilla pdf.js inside a iframe.
I call this iframe from different pages and component.
At the Chrome Developer Tools in Source I see, that each time I enter a page where the iframe is used a new instance is created and after leaving the instance is not killed.
So while acting on the website the user creates more and more instances and I'm afraid, it will fill the RAM.
How can I kill the instances before leaving a page (to another page)?

```<code><iframe id="pdfViewer" src="_content/Somiso.Net.PdfViewer/lib/pdfjs/web/viewer.html" style="@Style"></iframe> (WASM)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a Blazor app (WASM). In it I use mozilla pdf.js inside a iframe.
I call this iframe from different pages and component.
At the Chrome Developer Tools in Source I see, that each time I enter a page where the iframe is used a new instance is created and after leaving the instance is not killed.
So while acting on the website the user creates more and more instances and I'm afraid, it will fill the RAM.
How can I kill the instances before leaving a page (to another page)?

 (WASM)


问:
getting value and Display Text RepositoryItemLookUpEdit
how i can get value and display text from RepositoryItemLookUpEdit

i knew on lookupedit use GetDisplayText and edit value
how i can get the value and display text RepositoryItemLookUpEdit ?

c#


问:
Invalid procedure call or argument (VBA Excel)
I am trying to make a tool in VBA excel. I created a userform with a textbox and some checkboxes. Underneath this checkbox i have 3 buttons. Each button has to run a powershell script. The powershell script is as following ('value-button', 'value from textbox', 'value from chosen option in checkbox') and if more than one chosen option the value must end with a ',' in the powershell script. Like this for example if i choose 3 options (XXX-0037,XXX-0037,XXX-0077)

I am getting now the above error with this code: Invalid procedure call or argument

I tried this code:

```<code>Private Sub togglebutton1_Click()
    Dim value As String
    Dim choice As String
    value = TextBox1.Text
    If CheckBox1.value = True Then
        choice = "LA1-037"
    ElseIf CheckBox2.value = True Then
        choice = "LA1-077"
    End If
    Dim command As String
    command = "Start-ExamSession -value " & value & " -choice " & choice
    Call Shell("powershell.exe -command " & command, vbHide)
End Sub
</code>```

Can anyone help me out with this?

Body:
I am trying to make a tool in VBA excel. I created a userform with a textbox and some checkboxes. Underneath this checkbox i have 3 buttons. Each button has to run a powershell script. The powershell script is as following ('value-button', 'value from textbox', 'value from chosen option in checkbox') and if more than one chosen option the value must end with a ',' in the powershell script. Like this for example if i choose 3 options (XXX-0037,XXX-0037,XXX-0077)

I am getting now the above error with this code: Invalid procedure call or argument

I tried this code:

Private Sub togglebutton1_Click()
    Dim value As String
    Dim choice As String
    value = TextBox1.Text
    If CheckBox1.value = True Then
        choice = "LA1-037"
    ElseIf CheckBox2.value = True Then
        choice = "LA1-077"
    End If
    Dim command As String
    command = "Start-ExamSession -value " & value & " -choice " & choice
    Call Shell("powershell.exe -command " & command, vbHide)
End Sub

Can anyone help me out with this?


问:
I am trying to make undo/redo function to a textbox using stack but it only undo one character at a time I want to undo a string
I am trying to make an undo/redo feature on a textbox in Winforms, I found a code in here that works but it only undo one character at a time. I was hoping to undo a whole string, can someone help me or give me an idea how? I'm new at data structure and don't really know how to start.

Here's the code:

```<code>        Stack<Func<object>> undoStack = new Stack<Func<object>>();
        Stack<Func<object>> redoStack = new Stack<Func<object>>();

        public LowQuantityProd()
        {
            InitializeComponent();
            textBox1.KeyDown += TextBox1_KeyDown;
        }

        private void TextBox1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.ControlKey && ModifierKeys == Keys.Control) { }
            else if (e.KeyCode == Keys.U && ModifierKeys == Keys.Control)
            {
                if (undoStack.Count > 0)
                {
                    StackPush(sender, redoStack);
                    undoStack.Pop()();
                }
            }
            else if (e.KeyCode == Keys.R && ModifierKeys == Keys.Control)
            {
                if (redoStack.Count > 0)
                {
                    StackPush(sender, undoStack);
                    redoStack.Pop()();
                }
            }
            else
            {
                redoStack.Clear();
                StackPush(sender, undoStack);
            }
        }

        private void StackPush(object sender, Stack<Func<object>> stack)
        {
            TextBox textBox = (TextBox)sender;
            var tBT = textBox.Text(textBox.Text, textBox.SelectionStart);
            stack.Push(tBT);
        }
}

public static class Extensions
    {
        public static Func<TextBox> Text(this TextBox textBox, string text, int sel)
        {
            return () =>
            {
                textBox.Text = text;
                textBox.SelectionStart = sel;
                return textBox;
            };
        }
    }
</code>```

Body:
I am trying to make an undo/redo feature on a textbox in Winforms, I found a code in here that works but it only undo one character at a time. I was hoping to undo a whole string, can someone help me or give me an idea how? I'm new at data structure and don't really know how to start.

Here's the code:

        Stack<Func<object>> undoStack = new Stack<Func<object>>();
        Stack<Func<object>> redoStack = new Stack<Func<object>>();

        public LowQuantityProd()
        {
            InitializeComponent();
            textBox1.KeyDown += TextBox1_KeyDown;
        }

        private void TextBox1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.ControlKey && ModifierKeys == Keys.Control) { }
            else if (e.KeyCode == Keys.U && ModifierKeys == Keys.Control)
            {
                if (undoStack.Count > 0)
                {
                    StackPush(sender, redoStack);
                    undoStack.Pop()();
                }
            }
            else if (e.KeyCode == Keys.R && ModifierKeys == Keys.Control)
            {
                if (redoStack.Count > 0)
                {
                    StackPush(sender, undoStack);
                    redoStack.Pop()();
                }
            }
            else
            {
                redoStack.Clear();
                StackPush(sender, undoStack);
            }
        }

        private void StackPush(object sender, Stack<Func<object>> stack)
        {
            TextBox textBox = (TextBox)sender;
            var tBT = textBox.Text(textBox.Text, textBox.SelectionStart);
            stack.Push(tBT);
        }
}

public static class Extensions
    {
        public static Func<TextBox> Text(this TextBox textBox, string text, int sel)
        {
            return () =>
            {
                textBox.Text = text;
                textBox.SelectionStart = sel;
                return textBox;
            };
        }
    }


问:
Configuring JNDI datasource in SpringBoot+Jetty
I need to move JNDI configuration in jetty-env.xml to configuration class using SpringBoot's JettyServletWebServerFactory, but I can not find any documentation/tutorial about this.

Any examples would be greatly appreciated.

Best regards,

SetNug


问:
CSS filters past viewport edges
I'm trying to achieve a metaball effect by blurring svg's (CSS Blur), then applying CSS contrast to the parent div to get hard edges back. Below is an example. For some reason, the filter does a weird thing on the edges.

I believe i would need to first extend the div to be bigger than the viewport, but some elements are dependent on VW and would therefore scale in an unexpected manner.. Anyone have an idea of how to expand the filter past the viewport edges?

Don't really know how to approach this, i would like the blur to extend past the viewport but retain current layout.

EDIT:
Needed to add white background to container div to make the contrast behave in the way i wanted. ( not go crazy on the viewport edges)

Title: CSS filters past viewport edges


问:
Beginner Here Needing Some Direction
I've done some coding in the past but not for a long, long time.
In setting up our message system I want something with the least amount of coding required.
We're looking to send simple SMS messages only on a notification basis. There may be an occasional picture to send as well.

What do you recommend from the list below?

```<code>C# with .NET Framework
C# with .NET Core
Java
Node.js
PHP
Python
Ruby
</code>```

Just getting started

Title: Beginner Here Needing Some Direction

Body:
I've done some coding in the past but not for a long, long time.
In setting up our message system I want something with the least amount of coding required.
We're looking to send simple SMS messages only on a notification basis. There may be an occasional picture to send as well.

What do you recommend from the list below?

C# with .NET Framework
C# with .NET Core
Java
Node.js
PHP
Python
Ruby

Just getting started


问:
Variable set of attributes $facets MongoDB
How to use the $facet aggregation when I don't know upfront the name of all the attributes?

The documentation in https://www.mongodb.com/docs/atlas/atlas-search/facet only provides examples for a fixed and known upfront set of attributes.


问:
Turn off text suggestions when I swipe on the keyboard
I know how to disable the text suggestions on an UITextField through the following properties:

```<code>textField.spellCheckingType = .no
textField.autocorrectionType = .no
</code>```

But when I swipe on the Keyboard the view also appear and ignore the given values. Has anybody an idea how I can disable this behaviour also when I swipe on the Keyboard?

Body:
I know how to disable the text suggestions on an UITextField through the following properties:

textField.spellCheckingType = .no
textField.autocorrectionType = .no

But when I swipe on the Keyboard the view also appear and ignore the given values. Has anybody an idea how I can disable this behaviour also when I swipe on the Keyboard?


问:
Microsoft Graph - How to get App to read user calendar events
I'm trying to create a Node/Javascript service that will read a user's outlook calendar.
This took about 2 hours to get the front and backend fully setup and working with Google Calendar.
I'm on my 2nd week of trying to get this to work with Microsoft Graph.

The user giving authorization will be outside of my app's tenant/organization.

I've registered an app in Azure, and given it the Calendars.ReadWrite and Users.Read permissions.

I've granted Admin consent for the default directory (someone suggested this).

I've setup the front end authorization page for the user to give authorization for the app permissions defined in the scope.

The front end user authorization works fine, the authorization page pops up describing the access that the app is requesting and on confirmation it returns the user's access_token, refresh_token, does the redirect, etc.

The part I'm having the problem with is for the Node application to read that user's calendar events.
Depending on whether I add the user's accessToken to the call, I get different errors returned.

I have created 2 functions so far in the Node application.
The first function getMSClient populates the authProvider with clientId, clientSecret, tenantId, and gets/returns a client with the authProvider information
This function "seems" to be working fine.  If I do an output of the client I get an object with config: {...lots of properties}

The second function is where I'm trying to make the call to read the user calendar, but I get all sorts of errors,

If I use the client and make the call with:
const events = await client.api(users/${email}/calendar/getSchedule).get()
I receive an object with a statusCode of 401

If I use the client and add the user's accessToken to the header and make the call with:
const events = await client.api(users/${email}/calendar/getSchedule)..header('Authorization', Bearer ${userAccessToken}).get()
I get an error message about 'CompactToken parsing failed with error code: 80049217'
with 401 statusCode and code 'InvalidAuthenticationToken'

Here is the code:

```<code>  const getMSClient = async () => {

  const credsJSON = await fs.readFile(CREDENTIALS_PATH);
  const creds = JSON.parse(credsJSON);

  const {tenantId, clientId, clientSecret } = creds;

  const credential = new ClientSecretCredential(tenantId, clientId, clientSecret);
  const authProvider = new TokenCredentialAuthenticationProvider(
    credential, {
      scopes: ['https://graph.microsoft.com/.default']
  });

  const client = await Client.initWithMiddleware({
      debugLogging: true,
      authProvider
  });
  return client;
}

const getAllEvents = async () => {
  const userAccessToken = 'eyJ0eXAiOiJKV1QiLCJ .........';
  const email = 'user@outlook.com'

  const client = await getMSClient();

  const events = await client.api(`users/${email}/calendar/getSchedule`).header('Authorization', `Bearer ${userAccessToken}`).get()

  console.log(`events: `);
  console.dir(events)
}

getAllEvents();

</code>```

Body:
I'm trying to create a Node/Javascript service that will read a user's outlook calendar.
This took about 2 hours to get the front and backend fully setup and working with Google Calendar.
I'm on my 2nd week of trying to get this to work with Microsoft Graph.

The user giving authorization will be outside of my app's tenant/organization.

I've registered an app in Azure, and given it the Calendars.ReadWrite and Users.Read permissions.

I've granted Admin consent for the default directory (someone suggested this).

I've setup the front end authorization page for the user to give authorization for the app permissions defined in the scope.

The front end user authorization works fine, the authorization page pops up describing the access that the app is requesting and on confirmation it returns the user's access_token, refresh_token, does the redirect, etc.

The part I'm having the problem with is for the Node application to read that user's calendar events.
Depending on whether I add the user's accessToken to the call, I get different errors returned.

I have created 2 functions so far in the Node application.
The first function getMSClient populates the authProvider with clientId, clientSecret, tenantId, and gets/returns a client with the authProvider information
This function "seems" to be working fine.  If I do an output of the client I get an object with config: {...lots of properties}

The second function is where I'm trying to make the call to read the user calendar, but I get all sorts of errors,

If I use the client and make the call with:
const events = await client.api(users/${email}/calendar/getSchedule).get()
I receive an object with a statusCode of 401

If I use the client and add the user's accessToken to the header and make the call with:
const events = await client.api(users/${email}/calendar/getSchedule)..header('Authorization', Bearer ${userAccessToken}).get()
I get an error message about 'CompactToken parsing failed with error code: 80049217'
with 401 statusCode and code 'InvalidAuthenticationToken'

Here is the code:

  const getMSClient = async () => {

  const credsJSON = await fs.readFile(CREDENTIALS_PATH);
  const creds = JSON.parse(credsJSON);

  const {tenantId, clientId, clientSecret } = creds;

  const credential = new ClientSecretCredential(tenantId, clientId, clientSecret);
  const authProvider = new TokenCredentialAuthenticationProvider(
    credential, {
      scopes: ['https://graph.microsoft.com/.default']
  });

  const client = await Client.initWithMiddleware({
      debugLogging: true,
      authProvider
  });
  return client;
}

const getAllEvents = async () => {
  const userAccessToken = 'eyJ0eXAiOiJKV1QiLCJ .........';
  const email = 'user@outlook.com'

  const client = await getMSClient();

  const events = await client.api(`users/${email}/calendar/getSchedule`).header('Authorization', `Bearer ${userAccessToken}`).get()

  console.log(`events: `);
  console.dir(events)
}

getAllEvents();


问:
How to get top 2 labels for same X_test value
I have Description and Team_area in a dataframe.
Description being the Independent data and Team_area being the dependent/label.

if i run
Team_area_result = model.predict(count_vect.transform(["It is a bright sunny day"]))

complete function:
def data_preprocessing(self,df):
"""
Exploratory Data Analysis (EDA) and Training the data
"""

```<code>    df['Description'] = df['Description'].fillna(df['Name'])
    df['Name_Desc'] = np.where(df['Description'] == 'nan', df['Name'], df['Name'].str.cat(df['Description'],sep=' '))
    df['Name_Desc'] = df['Name_Desc'].astype(str).str.replace("_"," ",regex=True)

    tfidf = TfidfVectorizer(sublinear_tf=True, max_df=0.95, min_df=5, norm='l2', encoding='latin-1', ngram_range=(1, 2), stop_words='english')
    features = tfidf.fit_transform(df.Description).toarray()
    labels = df.category_id

    X_train, y_train = df.Description, df['Team_Area']
    count_vect = CountVectorizer()
    X_train_counts = count_vect.fit_transform(X_train)
    tfidf_transformer = TfidfTransformer()
    X_train_tfidf = tfidf_transformer.fit_transform(X_train_counts)

    model = RandomForestClassifier().fit(X_train_tfidf, y_train)

    # create an iterator object with write permission - model.pkl
    with open('C:\\model_pkl_1', 'wb') as files:
        pickle.dump((df,count_vect,tfidf_transformer,model), files)

    return "Model Created !!"
</code>```

output: ['Weather']
expected Output: ['Weather','Season']
I what to fetch top 2 team area for same input text.
I'm using Random forest classifier

Body:
I have Description and Team_area in a dataframe.
Description being the Independent data and Team_area being the dependent/label.

if i run
Team_area_result = model.predict(count_vect.transform(["It is a bright sunny day"]))

complete function:
def data_preprocessing(self,df):
"""
Exploratory Data Analysis (EDA) and Training the data
"""

    df['Description'] = df['Description'].fillna(df['Name'])
    df['Name_Desc'] = np.where(df['Description'] == 'nan', df['Name'], df['Name'].str.cat(df['Description'],sep=' '))
    df['Name_Desc'] = df['Name_Desc'].astype(str).str.replace("_"," ",regex=True)

    tfidf = TfidfVectorizer(sublinear_tf=True, max_df=0.95, min_df=5, norm='l2', encoding='latin-1', ngram_range=(1, 2), stop_words='english')
    features = tfidf.fit_transform(df.Description).toarray()
    labels = df.category_id

    X_train, y_train = df.Description, df['Team_Area']
    count_vect = CountVectorizer()
    X_train_counts = count_vect.fit_transform(X_train)
    tfidf_transformer = TfidfTransformer()
    X_train_tfidf = tfidf_transformer.fit_transform(X_train_counts)

    model = RandomForestClassifier().fit(X_train_tfidf, y_train)

    # create an iterator object with write permission - model.pkl
    with open('C:\\model_pkl_1', 'wb') as files:
        pickle.dump((df,count_vect,tfidf_transformer,model), files)

    return "Model Created !!"

output: ['Weather']
expected Output: ['Weather','Season']
I what to fetch top 2 team area for same input text.
I'm using Random forest classifier


问:
R dataframe Herfindahl index calculation for inflows and outflows
I have a dataframe looking like below (the real data has many more people and club):

```<code>Year   Player    Club
2005   Phelan    Chicago Fire
2006   Phelan    Chicago Fire
2007   Phelan    Boston Pant
2008   Phelan    Boston Pant
2009   Phelan    Chicago Fire
2010   Phelan    Chicago Fire

2002   John      New York Jet
2003   John      New York Jet
2004   John      Atlanta Elephant
2005   John      Atlanta Elephant
2006   John      Chicago Fire
</code>```

I want to calculate two club level measures (previous_exp & post_exp) for each club. The calculations are very similar to the calculation of Herfindahl–Hirschman index.  Clubs are linked together through the mobility of players. "previous_exp" captures club-level inflow sources for each club and "post_exp" captures club-level outlow destinations for each club.

For the calculations of "previous_exp" and "post_exp", I want to only consider the immediate sources and destinations of each club. For example, for Chicago Fire, Phelan came to this club in 2005 and then left. He returned in 2010. Before Phelan's first stay in Chicago Fire, he had zero previous experience (so we ignore it). However, before his second stay in Chicago Fire, he stayed in Boston pant for 2 years. Similarly,John stayed in Atlanta Elephant for 2 years before coming to Chicago. For Chicago Fire, based on the career records of Phelan and John, it in total accumulated 2+2=4 years of previous experience from other clubs. Among these 4 years, 2 years are from Boston Pant and 2 years are from Atlanta Elephant (John 2007-2008). I can then calculate the "previous_exp" value for Chicago Fire by using the formula: (length of the experience 1/total years)^2+(length of the experience 2/total years)^2+......, which equals to (2/4)^2+(2/4)^2=0.5.

I can use the similar procedure to calculate values for "post_exp".

The sample output looks like below:

```<code>Club               previous_exp
Chicago Fire       0.5
Boston Pant        1
New York Jet       NA
Atlanta Elephant   1

Club               post_exp
Chicago Fire       1
Boston Pant        1
New York Jet       1
Atlanta Elephant   1
</code>```

Body:
I have a dataframe looking like below (the real data has many more people and club):

Year   Player    Club
2005   Phelan    Chicago Fire
2006   Phelan    Chicago Fire
2007   Phelan    Boston Pant
2008   Phelan    Boston Pant
2009   Phelan    Chicago Fire
2010   Phelan    Chicago Fire

2002   John      New York Jet
2003   John      New York Jet
2004   John      Atlanta Elephant
2005   John      Atlanta Elephant
2006   John      Chicago Fire

I want to calculate two club level measures (previous_exp & post_exp) for each club. The calculations are very similar to the calculation of Herfindahl–Hirschman index.  Clubs are linked together through the mobility of players. "previous_exp" captures club-level inflow sources for each club and "post_exp" captures club-level outlow destinations for each club.

For the calculations of "previous_exp" and "post_exp", I want to only consider the immediate sources and destinations of each club. For example, for Chicago Fire, Phelan came to this club in 2005 and then left. He returned in 2010. Before Phelan's first stay in Chicago Fire, he had zero previous experience (so we ignore it). However, before his second stay in Chicago Fire, he stayed in Boston pant for 2 years. Similarly,John stayed in Atlanta Elephant for 2 years before coming to Chicago. For Chicago Fire, based on the career records of Phelan and John, it in total accumulated 2+2=4 years of previous experience from other clubs. Among these 4 years, 2 years are from Boston Pant and 2 years are from Atlanta Elephant (John 2007-2008). I can then calculate the "previous_exp" value for Chicago Fire by using the formula: (length of the experience 1/total years)^2+(length of the experience 2/total years)^2+......, which equals to (2/4)^2+(2/4)^2=0.5.

I can use the similar procedure to calculate values for "post_exp".

The sample output looks like below:

Club               previous_exp
Chicago Fire       0.5
Boston Pant        1
New York Jet       NA
Atlanta Elephant   1

Club               post_exp
Chicago Fire       1
Boston Pant        1
New York Jet       1
Atlanta Elephant   1


问:
File locations for Github Pages with an rss (podcast) feed
I have a Github pages site setup to host my website. I'd like to host a small podcast (for myself) through pages. I wrote a feed.xml file with the rss code for the podcast. I'm having trouble figuring out where the file is located via the browser. I can see it in Github, and I can open other files in that same folder in the browser (such as the index.html file), but I cannot open the rss feed file in the browser. (I get a 404 message.) Nor can I get my podcast manager (Pocket Casts) to find it. Is it in some kind of folder?

I was using this person's website/github page as a bit of a template, but he appears to have things nested in folders that I'm finding difficult to follow as they are different on Github Pages vs. in the code files.


问:
Matching Torch STFT with Accelerate
Im trying to re-implement Torch's STFT code in Swift with Accelerate / vDSP, to produce a Log Mel Spectrogram by post processing the STFT so I can use the Mel Spectrogram as an input for a CoreML port of OpenAI's Whisper

Pytorch's native STFT / Mel code produces this Spectrogram (its clipped due to importing raw float 32s into Photoshop lol)

and mine:

Obviously the two things to notice are the values, and the lifted frequency components.

The STFT Docs here https://pytorch.org/docs/stable/generated/torch.stft.html

```<code>X[ω,m]=
k=0
∑
win_length-1

window[k] input[m×hop_length+k] * exp(−j * (2π⋅ωk) /win_length)
</code>```

I believe Im properly handling window[k] input[m×hop_length+k]  but I'm a bit lost as to how to calculate the exponent and what -J is referring to in the documentation, and how to convert the final exponential in vDSP. Also, if its a sum, how do I get the 200 elements I need!?

My Log Mel Spectrogram

My code follows:

```<code>  func processData(audio: [Int16]) -> [Float]
    {
        assert(self.sampleCount == audio.count)

        var audioFloat:[Float] = [Float](repeating: 0, count: audio.count)

        vDSP.convertElements(of: audio, to: &audioFloat)

        vDSP.divide(audioFloat, 32768.0, result: &audioFloat)

        // Up to this point, Python and swift are numerically identical

        // insert numFFT/2 samples before and numFFT/2 after so we have a extra numFFT amount to process
        // TODO: Is this stricly necessary?
        audioFloat.insert(contentsOf: [Float](repeating: 0, count: self.numFFT/2), at: 0)
        audioFloat.append(contentsOf: [Float](repeating: 0, count: self.numFFT/2))

        // Split Complex arrays holding the FFT results
        var allSampleReal = [[Float]](repeating: [Float](repeating: 0, count: self.numFFT/2), count: self.melSampleCount)
        var allSampleImaginary = [[Float]](repeating: [Float](repeating: 0, count: self.numFFT/2), count: self.melSampleCount)

        // Step 2 - we need to create 200 x 3000 matrix of STFTs - note we appear to want to output complex numbers (?)
        for (m) in 0 ..< self.melSampleCount
        {
            // Slice numFFTs every hop count (barf) and make a mel spectrum out of it
            // audioFrame ends up holding split complex numbers
            var audioFrame = Array<Float>( audioFloat[ (m * self.hopCount) ..< ( (m * self.hopCount) + self.numFFT) ] )

            // Copy of audioFrame original samples
            let audioFrameOriginal = audioFrame

            assert(audioFrame.count == self.numFFT)

            // Split Complex arrays holding a single FFT result of our Audio Frame, which gets appended to the allSample Split Complex arrays
            var sampleReal:[Float] = [Float](repeating: 0, count: self.numFFT/2)
            var sampleImaginary:[Float] = [Float](repeating: 0, count: self.numFFT/2)

            sampleReal.withUnsafeMutableBytes { unsafeReal in
                sampleImaginary.withUnsafeMutableBytes { unsafeImaginary in

                    vDSP.multiply(audioFrame,
                                  hanningWindow,
                                  result: &audioFrame)

                    var complexSignal = DSPSplitComplex(realp: unsafeReal.bindMemory(to: Float.self).baseAddress!,
                                                        imagp: unsafeImaginary.bindMemory(to: Float.self).baseAddress!)

                    audioFrame.withUnsafeBytes { unsafeAudioBytes in
                        vDSP.convert(interleavedComplexVector: [DSPComplex](unsafeAudioBytes.bindMemory(to: DSPComplex.self)),
                                     toSplitComplexVector: &complexSignal)
                    }

                    // Step 3 - creating the FFT
                    self.fft.forward(input: complexSignal, output: &complexSignal)
                }
            }

            // We need to match: https://pytorch.org/docs/stable/generated/torch.stft.html
            // At this point, I'm unsure how to continue?

//            let twoπ = Float.pi * 2
//            let freqstep:Float = Float(16000 / (self.numFFT/2))
//
//            var w:Float = 0.0
//            for (k) in 0 ..< self.numFFT/2
//            {
//                let j:Float = sampleImaginary[k]
//                let sample = audioFrame[k]
//
//                let exponent = -j * ( (twoπ * freqstep * Float(k) ) / Float((self.numFFT/2)))
//
//                w += powf(sample, exponent)
//            }

            allSampleReal[m] = sampleReal
            allSampleImaginary[m] = sampleImaginary
        }

        // We now have allSample Split Complex holding 3000  200 dimensional real and imaginary FFT results

        // We create flattened  3000 x 200 array of DSPSplitComplex values
        var flattnedReal:[Float] = allSampleReal.flatMap { $0 }
        var flattnedImaginary:[Float] = allSampleImaginary.flatMap { $0 }

</code>```

Title: Matching Torch STFT with Accelerate

Body:
Im trying to re-implement Torch's STFT code in Swift with Accelerate / vDSP, to produce a Log Mel Spectrogram by post processing the STFT so I can use the Mel Spectrogram as an input for a CoreML port of OpenAI's Whisper

Pytorch's native STFT / Mel code produces this Spectrogram (its clipped due to importing raw float 32s into Photoshop lol)

and mine:

Obviously the two things to notice are the values, and the lifted frequency components.

The STFT Docs here https://pytorch.org/docs/stable/generated/torch.stft.html

X[ω,m]=
k=0
∑
win_length-1

window[k] input[m×hop_length+k] * exp(−j * (2π⋅ωk) /win_length)

I believe Im properly handling window[k] input[m×hop_length+k]  but I'm a bit lost as to how to calculate the exponent and what -J is referring to in the documentation, and how to convert the final exponential in vDSP. Also, if its a sum, how do I get the 200 elements I need!?

My Log Mel Spectrogram

My code follows:

  func processData(audio: [Int16]) -> [Float]
    {
        assert(self.sampleCount == audio.count)

        var audioFloat:[Float] = [Float](repeating: 0, count: audio.count)

        vDSP.convertElements(of: audio, to: &audioFloat)

        vDSP.divide(audioFloat, 32768.0, result: &audioFloat)

        // Up to this point, Python and swift are numerically identical

        // insert numFFT/2 samples before and numFFT/2 after so we have a extra numFFT amount to process
        // TODO: Is this stricly necessary?
        audioFloat.insert(contentsOf: [Float](repeating: 0, count: self.numFFT/2), at: 0)
        audioFloat.append(contentsOf: [Float](repeating: 0, count: self.numFFT/2))

        // Split Complex arrays holding the FFT results
        var allSampleReal = [[Float]](repeating: [Float](repeating: 0, count: self.numFFT/2), count: self.melSampleCount)
        var allSampleImaginary = [[Float]](repeating: [Float](repeating: 0, count: self.numFFT/2), count: self.melSampleCount)

        // Step 2 - we need to create 200 x 3000 matrix of STFTs - note we appear to want to output complex numbers (?)
        for (m) in 0 ..< self.melSampleCount
        {
            // Slice numFFTs every hop count (barf) and make a mel spectrum out of it
            // audioFrame ends up holding split complex numbers
            var audioFrame = Array<Float>( audioFloat[ (m * self.hopCount) ..< ( (m * self.hopCount) + self.numFFT) ] )

            // Copy of audioFrame original samples
            let audioFrameOriginal = audioFrame

            assert(audioFrame.count == self.numFFT)

            // Split Complex arrays holding a single FFT result of our Audio Frame, which gets appended to the allSample Split Complex arrays
            var sampleReal:[Float] = [Float](repeating: 0, count: self.numFFT/2)
            var sampleImaginary:[Float] = [Float](repeating: 0, count: self.numFFT/2)

            sampleReal.withUnsafeMutableBytes { unsafeReal in
                sampleImaginary.withUnsafeMutableBytes { unsafeImaginary in

                    vDSP.multiply(audioFrame,
                                  hanningWindow,
                                  result: &audioFrame)

                    var complexSignal = DSPSplitComplex(realp: unsafeReal.bindMemory(to: Float.self).baseAddress!,
                                                        imagp: unsafeImaginary.bindMemory(to: Float.self).baseAddress!)

                    audioFrame.withUnsafeBytes { unsafeAudioBytes in
                        vDSP.convert(interleavedComplexVector: [DSPComplex](unsafeAudioBytes.bindMemory(to: DSPComplex.self)),
                                     toSplitComplexVector: &complexSignal)
                    }

                    // Step 3 - creating the FFT
                    self.fft.forward(input: complexSignal, output: &complexSignal)
                }
            }

            // We need to match: https://pytorch.org/docs/stable/generated/torch.stft.html
            // At this point, I'm unsure how to continue?

//            let twoπ = Float.pi * 2
//            let freqstep:Float = Float(16000 / (self.numFFT/2))
//
//            var w:Float = 0.0
//            for (k) in 0 ..< self.numFFT/2
//            {
//                let j:Float = sampleImaginary[k]
//                let sample = audioFrame[k]
//
//                let exponent = -j * ( (twoπ * freqstep * Float(k) ) / Float((self.numFFT/2)))
//
//                w += powf(sample, exponent)
//            }

            allSampleReal[m] = sampleReal
            allSampleImaginary[m] = sampleImaginary
        }

        // We now have allSample Split Complex holding 3000  200 dimensional real and imaginary FFT results

        // We create flattened  3000 x 200 array of DSPSplitComplex values
        var flattnedReal:[Float] = allSampleReal.flatMap { $0 }
        var flattnedImaginary:[Float] = allSampleImaginary.flatMap { $0 }


问:
error no such option: --build-dir pycharm
I installed a second older Version of python (3.6) because I couldn't do something in my newer version. I created a new pycharm project with a new virtual environment and 3.6 as base interpreter. But when I try to install a package in pycharm (for example numpy) I get the error: no such option: --build-dir

Some things of note, that might be important to answer my question: I haven't added 3.6 to the path, when I installed it because the newer version is the one I mainly use. Also according to the following code my pip version is 21.3.1 :

```<code>import pkg_resources
print(pkg_resources.get_distribution("pip").version)
</code>```

Body:
I installed a second older Version of python (3.6) because I couldn't do something in my newer version. I created a new pycharm project with a new virtual environment and 3.6 as base interpreter. But when I try to install a package in pycharm (for example numpy) I get the error: no such option: --build-dir

Some things of note, that might be important to answer my question: I haven't added 3.6 to the path, when I installed it because the newer version is the one I mainly use. Also according to the following code my pip version is 21.3.1 :

import pkg_resources
print(pkg_resources.get_distribution("pip").version)


问:
not able use the variable of handelebars passed while rendering on html page as variable is array of object
```<code>app.post("/search", async (req, res)=>{
    try{
        const service = req.body.service;
        const cityup = req.body.city;
        const city = cityup.toLowerCase();
        const state = req.body.state;
        const registered = await Truck.find({
            $and:[
                {$or:[{service1:service},{service2:service},{service3:service},{service4:service},
                    {service5:service},{service6:service},{service7:service},{service8:service}]},
                {city:city},
                {state:state}
            ]
        });
        console.log(registered);
        res.status(201).render("result",{registered});
    }catch(err){
        res.status(400).send(err);
    }

})

** here code search the data and this is the result saved in registered variable**

[
  {
    _id: new ObjectId("63a999338ebc14fc2d79bd36"),
    pword: '$2a$10$xdSZTSOqegZRMWFiP7l/6utfDJ0HBTY4bD/5VJf420W7RpyGDiI9e',
    tokens: [ [Object] ],
    __v: 19,
    fname: 'omanpreet',
    lname: 'singh',
    service1: 'Mobile Repair',
    service2: 'Repair Shops',
    account: 'Diamond',
    image: '1672082263213__damru.gif'
  },
  {
    _id: new ObjectId("63a99ff05b17abefabb914b7"),
    pword: '$2a$10$pkaY42SHf3biyjde7oU98OlIQnyKBrDx7SIf2VHUzH2/I94zsyw9O',
    tokens: [],
    __v: 7,
    fname: 'Amarjeet',
    lname: 'Singh',
    account: 'Gold',
    service1: 'Mobile Repair',
    service2: 'Repair Shops',
    service3: 'Towing Service',
    image: '1672081757265__damru2.gif'
  }
]

</code>```

I want to display result the way if account is Gold then show image size small and info of gold account and for diamond image size bigger and info of diamond account.
I don't know how to catch variable on the html page and use values stored in it. if anyone knows how to use or print the values properly please share info or reference of data where I can find solution for the same.

```<code>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Prototype</title>
</head>
<body>

<!-- ========================================
          Our Result Section Start
    ========================================  -->
 <section class="container grid section"   id="bannerid">
      <div class="banner-preview" id="bannerpreviewdiamond">
        {{!-- <h4> {{registered.company}}</h4> --}}
        <div class="continer grid banner">
          <div class="banner-img">
          {{!-- <img src="./uploads/{{registered.image}}" alt="banner preview" width="295px" height="250px"> --}}
          </div>
          <div class="info">
            <p class="comp">{{registered.company}}</p>
            <p>{{registered.maddress}}</p>
            <p> {{registered.city}}, {{registered.state}}</p>
            <p><ion-icon name="call-outline"></ion-icon> {{registered.phone}}</p>
            <a href="www.instagram.com">vendors website link</a>
          </div>
          <div class="desc">
            <span class="description">
              ```

  • {{registered.service1}}                       • {{registered.service2}}
  • {{registered.service3}}                     • {{registered.service4}}
  • {{registered.service5}}                          • {{registered.service6}}
  • {{registered.service7}}                          • {{registered.service8}}

Business Description
              ```
<p>
{{registered.dbox}}
</p>
            </span>
          </div>
        </div>
      </div>
           </div>
      </section>
    <!-- ========================================
          Our Footer Section Start
    ========================================  -->
    {{!-- {{>footer}} --}}
</body>
</html>

</code>```

Body:
app.post("/search", async (req, res)=>{
    try{
        const service = req.body.service;
        const cityup = req.body.city;
        const city = cityup.toLowerCase();
        const state = req.body.state;
        const registered = await Truck.find({
            $and:[
                {$or:[{service1:service},{service2:service},{service3:service},{service4:service},
                    {service5:service},{service6:service},{service7:service},{service8:service}]},
                {city:city},
                {state:state}
            ]
        });
        console.log(registered);
        res.status(201).render("result",{registered});
    }catch(err){
        res.status(400).send(err);
    }

})

** here code search the data and this is the result saved in registered variable**

[
  {
    _id: new ObjectId("63a999338ebc14fc2d79bd36"),
    pword: '$2a$10$xdSZTSOqegZRMWFiP7l/6utfDJ0HBTY4bD/5VJf420W7RpyGDiI9e',
    tokens: [ [Object] ],
    __v: 19,
    fname: 'omanpreet',
    lname: 'singh',
    service1: 'Mobile Repair',
    service2: 'Repair Shops',
    account: 'Diamond',
    image: '1672082263213__damru.gif'
  },
  {
    _id: new ObjectId("63a99ff05b17abefabb914b7"),
    pword: '$2a$10$pkaY42SHf3biyjde7oU98OlIQnyKBrDx7SIf2VHUzH2/I94zsyw9O',
    tokens: [],
    __v: 7,
    fname: 'Amarjeet',
    lname: 'Singh',
    account: 'Gold',
    service1: 'Mobile Repair',
    service2: 'Repair Shops',
    service3: 'Towing Service',
    image: '1672081757265__damru2.gif'
  }
]

I want to display result the way if account is Gold then show image size small and info of gold account and for diamond image size bigger and info of diamond account.
I don't know how to catch variable on the html page and use values stored in it. if anyone knows how to use or print the values properly please share info or reference of data where I can find solution for the same.

<!DOCTYPE html>

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

        {{!--
 {{registered.company}}
 --}}

          {{!--  --}}

{{registered.company}}

{{registered.maddress}}

 {{registered.city}}, {{registered.state}}

<ion-icon name="call-outline"></ion-icon> {{registered.phone}}

            vendors website link

  • {{registered.service1}}                       • {{registered.service2}}
  • {{registered.service3}}                     • {{registered.service4}}
  • {{registered.service5}}                          • {{registered.service6}}
  • {{registered.service7}}                          • {{registered.service8}}

Business Description

{{registered.dbox}}

    {{!-- {{>footer}} --}}


问:
What should I do if I am using an Apache License 2.0 library in my android application? Where Should I add or give Credit?
I am new developer and going to upload my First App on Google Play but I have a query. I am using Apache 2.0 Libraries in my app Like Glide and many more under Apache 2.0, I read the Apache License but I didn't understand it well, I don't know where should i give/add credit in my app or in apk file, I dont have any clue yet

If i use this plugin "OSS Licenses Gradle Plugin", Is that enough?


问:
Caching files (with Service Worker) whose name's change (due to checksums) during build
I'm attempting to cache my React site's HTML, JS and CSS files with a Service Worker. I understand the logic and am using a pattern similar to the below:

```<code>const CACHE_NAME = "version-1";

const urls = [
  'index.html',
  'static/js/main.js',
  'static/css/styles.css'
];

self.addEventListener('install', (event) => {
  console.log('Installed');
  event.waitUntil(
    caches.open(CACHE_NAME)
      .then((cache) => {
        console.log('Opened cache');
        return cache.addAll(urls);
      })
  )
});
</code>```

My issue is that when I run my build the outputted filenames for the JS and CSS include a random checksum (such as main.d74d6f35.js) and I am unable to include this value in my files to cache.

Is there a way around this or do I need to use Workbox when making React apps offline compatible?

Ideally I'd like to avoid Workbox if there is an alternative.

Body:
I'm attempting to cache my React site's HTML, JS and CSS files with a Service Worker. I understand the logic and am using a pattern similar to the below:

const CACHE_NAME = "version-1";

const urls = [
  'index.html',
  'static/js/main.js',
  'static/css/styles.css'
];

self.addEventListener('install', (event) => {
  console.log('Installed');
  event.waitUntil(
    caches.open(CACHE_NAME)
      .then((cache) => {
        console.log('Opened cache');
        return cache.addAll(urls);
      })
  )
});

My issue is that when I run my build the outputted filenames for the JS and CSS include a random checksum (such as main.d74d6f35.js) and I am unable to include this value in my files to cache.

Is there a way around this or do I need to use Workbox when making React apps offline compatible?

Ideally I'd like to avoid Workbox if there is an alternative.


问:
vue js button disable and enable

when page is landing default next button is disabled, we will selected one radio button
next button is disabled.

condition based on work with disable and enable next button

{% if cust_package == '6 Free Trades'  %}
Subscribe for more Trades options will be enabled once you consume all 6 free trades

{% comment %} {% elif cust_package == " "  %}

 {% endcomment %}
{% elif cust_package == "" %}
Subscribe for more Trades options will be enabled once you consume all 6 free trades

```<code>                         {% endif %}
                 <hr style="position: relative;top: -4px;border-color: lightgray;">
                 <p class="head-trades" style="top: -11px;"> Subscribe for more Trades:</p>
             {% if cust_package and package_value != 0%}
                 <p class="sixfreetrade">
                     <input style="position: relative;width: 4%;left: 1px;"
                            type="radio" id="business"
                            name="flag" value="15 Trades for $6.99" v-model="subscribe" disabled>
                     <span style="" class="Business_postadTrade">15 Trades for $6.99 </span>
                 </p>
                 <div v-if="subscribe == '15 Trades for $6.99'">
                     {% if cust_package %}
                     {% if cust_package == '15 Trades for $6.99' %}
                         {% if  package_value == 0 and cust_package == '15 Trades for $6.99' %}

                             <p style = "color: #DB0038;">* You consumed {{consumed_ads}} Trades and left with {{package_value}} Trade  * Please upgrade higher subscription if you want more Trades to post</p>
                         {% elif  package_value != 0 and cust_package == '15 Trades for $6.99' %}
                             <p>* You consumed {{consumed_ads}} trades and left with {{package_value}} trades.</p>
                             {% comment %} <p>* Want more ads in this month, please upgrade higher package</p> {% endcomment %}
                         {% endif %}

                     {% else %}
                     <p>* You consumed 0 trades and left with 15 trades.</p>
                     {% comment %} <p>* Want more ads in this month, please upgrade higher package</p> {% endcomment %}
                     {% endif %}
                     {% endif %}
                 </div>
                 <p class="sixfreetrade">
                     <input style="position: relative;width: 4%;left: 1px;"
                            type="radio" id="business"
                            name="flag" value="30 Trades for $12.99" v-model="subscribe" disabled>
                     <span style="" class="Business_postadTrade">30 Trades for $12.99 </span>
                 </p>
                 <div v-if="subscribe == '30 Trades for $12.99'">
                     {% if cust_package %}
                     {% if cust_package == '30 Trades for $12.99' %}
                         {% if  package_value == 0 and cust_package == '30 Trades for $12.99' %}

                         <p style="color: #DB0038;">* You consumed {{consumed_ads}} Trades and left with {{package_value}} Trade  * Please upgrade higher subscription if you want more Trades to post</p>
                         {% elif  package_value != 0 and cust_package == '30 Trades for $12.99' %}
                         <p>* You consumed {{consumed_ads}} trades and left with {{package_value}} trades.</p>
                         {% comment %} <p>* Want more ads in this month, please upgrade higher package</p> {% endcomment %}
                         {% endif %}

                     {% else %}
                     <p>* You consumed 0 trades and left with 30 trades.</p>
                     {% comment %} <p>* Want more ads in this month, please upgrade higher package</p> {% endcomment %}
                     {% endif %}
                     {% endif %}
                 </div>
                 <p class="sixfreetrade">
                     <input style="position: relative;width: 4%;left: 1px;"
                            type="radio" id="business"
                            name="flag" value="120 Trades for $24.99" v-model="subscribe" disabled>
                     <span style="" class="Business_postadTrade">120 Trades for $24.99 </span>
                 </p>
                 <div v-if="subscribe == '120 Trades for $24.99'">
                     {% if cust_package %}
                     {% if cust_package == '120 Trades for $24.99' %}
                         {% if package_value == 0 and cust_package == '120 Trades for $24.99' %}

                             <p style="color: #DB0038;">* You consumed {{consumed_ads}} Trades and left with {{package_value}} Trade  * Please upgrade higher subscription if you want more Trades to post</p>
                         {% elif package_value != 0 and cust_package == '120 Trades for $24.99' %}
                             <p>* You consumed {{consumed_ads}} trades and left with {{package_value}} trades.</p>
                             {% comment %} <p>* Want more ads in this month, please upgrade higher package</p> {% endcomment %}
                         {% endif %}

                     {% else %}
                     <p>* You consumed 0 trades and left with 120 trades.</p>
                     {% comment %} <p>* Want more ads in this month, please upgrade higher package</p> {% endcomment %}
                     {% endif %}
                     {% endif %}
                 </div>
</code>```

default next button is disable and click on radio button next button is enable

Title: vue js button disable and enable

Body:
when page is landing default next button is disabled, we will selected one radio button
next button is disabled.

condition based on work with disable and enable next button

{% if cust_package == '6 Free Trades'  %}
Subscribe for more Trades options will be enabled once you consume all 6 free trades

{% comment %} {% elif cust_package == " "  %}

 {% endcomment %}
{% elif cust_package == "" %}
Subscribe for more Trades options will be enabled once you consume all 6 free trades

                         {% endif %}

 Subscribe for more Trades:

             {% if cust_package and package_value != 0%}

                     <input style="position: relative;width: 4%;left: 1px;"
                            type="radio" id="business"
                            name="flag" value="15 Trades for $6.99" v-model="subscribe" disabled>
                     15 Trades for $6.99

                     {% if cust_package %}
                     {% if cust_package == '15 Trades for $6.99' %}
                         {% if  package_value == 0 and cust_package == '15 Trades for $6.99' %}

* You consumed {{consumed_ads}} Trades and left with {{package_value}} Trade  * Please upgrade higher subscription if you want more Trades to post

                         {% elif  package_value != 0 and cust_package == '15 Trades for $6.99' %}

* You consumed {{consumed_ads}} trades and left with {{package_value}} trades.

                             {% comment %}
* Want more ads in this month, please upgrade higher package
 {% endcomment %}
                         {% endif %}

                     {% else %}

* You consumed 0 trades and left with 15 trades.

                     {% comment %}
* Want more ads in this month, please upgrade higher package
 {% endcomment %}
                     {% endif %}
                     {% endif %}

                     <input style="position: relative;width: 4%;left: 1px;"
                            type="radio" id="business"
                            name="flag" value="30 Trades for $12.99" v-model="subscribe" disabled>
                     30 Trades for $12.99

                     {% if cust_package %}
                     {% if cust_package == '30 Trades for $12.99' %}
                         {% if  package_value == 0 and cust_package == '30 Trades for $12.99' %}

* You consumed {{consumed_ads}} Trades and left with {{package_value}} Trade  * Please upgrade higher subscription if you want more Trades to post

                         {% elif  package_value != 0 and cust_package == '30 Trades for $12.99' %}

* You consumed {{consumed_ads}} trades and left with {{package_value}} trades.

                         {% comment %}
* Want more ads in this month, please upgrade higher package
 {% endcomment %}
                         {% endif %}

                     {% else %}

* You consumed 0 trades and left with 30 trades.

                     {% comment %}
* Want more ads in this month, please upgrade higher package
 {% endcomment %}
                     {% endif %}
                     {% endif %}

                     <input style="position: relative;width: 4%;left: 1px;"
                            type="radio" id="business"
                            name="flag" value="120 Trades for $24.99" v-model="subscribe" disabled>
                     120 Trades for $24.99

                     {% if cust_package %}
                     {% if cust_package == '120 Trades for $24.99' %}
                         {% if package_value == 0 and cust_package == '120 Trades for $24.99' %}

* You consumed {{consumed_ads}} Trades and left with {{package_value}} Trade  * Please upgrade higher subscription if you want more Trades to post

                         {% elif package_value != 0 and cust_package == '120 Trades for $24.99' %}

* You consumed {{consumed_ads}} trades and left with {{package_value}} trades.

                             {% comment %}
* Want more ads in this month, please upgrade higher package
 {% endcomment %}
                         {% endif %}

                     {% else %}

* You consumed 0 trades and left with 120 trades.

                     {% comment %}
* Want more ads in this month, please upgrade higher package
 {% endcomment %}
                     {% endif %}
                     {% endif %}

default next button is disable and click on radio button next button is enable


问:
R: One-Way ANOVA and Scheffé - Test (Independent Measures vs. Repeated Measures)
I know how to code a one way ANOVA with 3 groups (a, b, c):

```<code>> a=c(45,42,36,39,51,44); b=c(50,42,41,35,55,49);
> c=c(55,45,43,40,59,56); vec1=c(a,b,c); F0=gl(3,6,18);
>
> df=data.frame(f=F0,d=vec1); model=aov(d~f,data=df);
</code>```

And I know how to perform, given that, a Scheffé-post-hoc test:

```<code>library(DescTools);
ScheffeTest(model)
</code>```

BUT WHAT if I have a repeated-measures-ANOVA with 3 groups (a, b, c):

```<code>df=data.frame(pa=rep(1:6,3),f=F0,d=vec1);
modelRm=aov(d~factor(f)+Error(factor(pa)),data=df)
</code>```

My question is:

HOW WOULD THE repeated-measures-Scheffé-post-hoc test BE expressed? When I type

```<code>ScheffeTest(modelRm)
</code>```

it raises:

Error in modelRm.frame.default(formula = x ~ g, drop.unused.levels = TRUE) :
invalid type (list) for variable 'x'

Body:
I know how to code a one way ANOVA with 3 groups (a, b, c):

> a=c(45,42,36,39,51,44); b=c(50,42,41,35,55,49);
> c=c(55,45,43,40,59,56); vec1=c(a,b,c); F0=gl(3,6,18);
>
> df=data.frame(f=F0,d=vec1); model=aov(d~f,data=df);

And I know how to perform, given that, a Scheffé-post-hoc test:

library(DescTools);
ScheffeTest(model)

BUT WHAT if I have a repeated-measures-ANOVA with 3 groups (a, b, c):

df=data.frame(pa=rep(1:6,3),f=F0,d=vec1);
modelRm=aov(d~factor(f)+Error(factor(pa)),data=df)

My question is:

HOW WOULD THE repeated-measures-Scheffé-post-hoc test BE expressed? When I type

ScheffeTest(modelRm)

it raises:

Error in modelRm.frame.default(formula = x ~ g, drop.unused.levels = TRUE) :
invalid type (list) for variable 'x'


问:
TRPC: TypeError: Cannot read properties of undefined (reading '_def')
I'm using the T3 stack and whenever I try to query one of my controllers I get this type error on the server. On the client I'm getting TRPCClientError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON. Any ideas?


问:
How to recieve repl.it username on a static HTML page?
I am creating a games website on repl.it (https://goofyahgames.ml)
I am trying to make a repl.it authentication, which works. BUT I need to receive who is logging in, which I can't figure out how to do on HTML.
Repl.It docs (https://docs.replit.com/hosting/repl-auth-sidebar)

FOR MORE CLAIRITY: I want to recieve "X-Replit-User-Name" and log it to a .txt, OR have the info sent to my phone, OR log it in some other way.

Thanks!

I HAVE tried the recommendations for Node.Js (didn't work be cause im on basic HTML) and other methods. These just aren't working.


问:
Dependent and Dynamic Dropdown form in js
Hey so I am trying to to make both a dynamic and dependent dropdown form. Essentially I want the second form to be dependent of the first forms option, and when you add a new form field I want it to generate a new div form with a different ID and and the option in the first form removed from the second and then third form. In the case the user only selects on form and doesn't decide to add a second or a third, I would like to still submit a NULL value through the form's that aren't submitted. Js is not my strong suit so any help would be appreciated</p>
```<code><!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="nativelangdrop">
    <option value="1">Fashion Designer</option>
    <option value="2">Visual Artist</option>
    <option value="3">Clothing reseller</option>
    <option value="4">Musician</option>
    <option value="5">Videographer</option>
    <option value="6">Photographer</option>
    <option value="7">Dancer</option>
    <option value="8">Sculpter</option>
</select>
<span id="additional"></span>
<input id="addBtn" type="button" value=" + "/>
<hr />
<select id="genre">
    <option value="1">Fashion Designer</option>
    <option value="2">Visual Artist</option>
    <option value="3">Clothing reseller</option>
    <option value="4">Musician</option>
    <option value="5">Videographer</option>
    <option value="6">Photographer</option>
    <option value="7">Dancer</option>
    <option value="8">Sculpter</option>
</select>
  <span id="additional2"></span>
<script>
var total;

// To auto limit based on the number of options
// total = $("#nativelangdrop").find("option").length - 1;

// Hard code a limit
total = 2;
//if total two hide plus button

$("#addBtn").on("click", function() {
    var button = document.getElementById('addBtn');
    var ctr = $("#additional").find(".extra").length;
    var ctr2 = $("#additional2").find(".extra2").length;
    if (ctr < total) {
        var $ddl = $("#nativelangdrop").clone();
        var $ddl2 = $("#genre").clone();
        $ddl.attr("id", "ddl" + ctr);
        // $ddl2.attr("id", "ddl2" + ctr);
        $ddl.addClass("extra");
        $ddl2.addClass("extra2");
        $("#additional").append($ddl);
        $("#additional2").append($ddl2);
    }
    else{
       button.style.display = 'none';
    }
});
//implement dependent genre form.
/*implement creating form after each iteration of ctr, var MyIDvariable = "MyID123";
    var cartHTML = '<div id="'+MyIDvariable+'" class="soft_add_wrapper" onmouseover="setTimer();">';
... the rest of your code ... */
</script>

</body>
</html>```
</code>```

Body:
Hey so I am trying to to make both a dynamic and dependent dropdown form. Essentially I want the second form to be dependent of the first forms option, and when you add a new form field I want it to generate a new div form with a different ID and and the option in the first form removed from the second and then third form. In the case the user only selects on form and doesn't decide to add a second or a third, I would like to still submit a NULL value through the form's that aren't submitted. Js is not my strong suit so any help would be appreciated

<!DOCTYPE html>

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<select id="nativelangdrop">
    <option value="1">Fashion Designer</option>
    <option value="2">Visual Artist</option>
    <option value="3">Clothing reseller</option>
    <option value="4">Musician</option>
    <option value="5">Videographer</option>
    <option value="6">Photographer</option>
    <option value="7">Dancer</option>
    <option value="8">Sculpter</option>
</select>

<input id="addBtn" type="button" value=" + "/>

<select id="genre">
    <option value="1">Fashion Designer</option>
    <option value="2">Visual Artist</option>
    <option value="3">Clothing reseller</option>
    <option value="4">Musician</option>
    <option value="5">Videographer</option>
    <option value="6">Photographer</option>
    <option value="7">Dancer</option>
    <option value="8">Sculpter</option>
</select>

```


问:
Vertical navigation scroll effect modification
I got this pen: https://codepen.io/janmez/pen/gryoKG but would like it to work more like on this site: https://rallyinteractive.com/. Not the background change, just list on the left. My js knowledge is not sufficient, can you help?

I tried achieving this with css but no success.

Edit: I added the full code and now what I want to achieve. I don't care about background animation, just wanted to make the nav and .content-section work more like on the site I mentioned above. Pen code does some of what I want: nav items get selected while scrolling to the relevant section. What I want to do is to have active nav elements always centered vertically and scroll together with sections. The example site (rallyinteractive.com) does exactly what I need.

$(document).ready(function(){
    var contentSection = $('.content-section');
    var navigation = $('nav');

    //when a nav link is clicked, smooth scroll to the section
    navigation.on('click', 'a', function(event){
        event.preventDefault(); //prevents previous event
        smoothScroll($(this.hash));
    });

    //update navigation on scroll...
    $(window).on('scroll', function(){
        updateNavigation();
    })
    //...and when the page starts
    updateNavigation();

    /////FUNCTIONS
    function updateNavigation(){
        contentSection.each(function(){
            var sectionName = $(this).attr('id');
            var navigationMatch = $('nav a[href="#' + sectionName + '"]');
            if( ($(this).offset().top - $(window).height()/2 < $(window).scrollTop()) &&
                  ($(this).offset().top + $(this).height() - $(window).height()/2 > $(window).scrollTop()))
                {
                    navigationMatch.addClass('active-section');
                }
            else {
                navigationMatch.removeClass('active-section');
            }
        });
    }
    function smoothScroll(target){
        $('body,html').animate({
            scrollTop: target.offset().top
        }, 800);
    }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>@import url(https://fonts.googleapis.com/css?family=Open+Sans);
@import url(https://fonts.googleapis.com/css?family=Lato);

html{
    height: 100%;
    font-family: 'Open Sans', sans-serif;
    background-color: #E9E8E2;
}
body{
    height: 100%;
}
nav{
    width: 15%;
    height: 400px;
    position: fixed;
    top: auto;
    bottom: auto;
    z-index: 10;
        scroll-snap-type: y mandatory;
overflow-y: hidden;
}
ul{
    list-style: none;
    padding: 0;
text-align:center;
    valign:center;
}
li{
    padding: 40px 0;
    scroll-snap-align: center;
}
span{
    display: inline-block;
    position:relative;
}
nav a{
    display: inline-block;
    color: #272727;
    text-decoration: none;
    font-size: 1em;
}
.circle{
    height: 10px;
    width: 10px;
    left: -10px;
    border-radius: 50%;
    background-color: #272727;
}
.rect{
    height: 3px;
    width: 0px;
    left: 0;
    bottom: 4px;
    background-color: #272727;
    -webkit-transition: -webkit-transform 0.6s, width 1s;
    -moz-transition: -webkit-transform 0.6s, width 1s;
    transition: transform 0.6s, width 1s;
}
nav a:hover, nav .active-section{
    color: #9b59b6;
}
nav a:hover span, nav .active-section span{
    background-color: #9b59b6;
}
nav .active-section .rect{
    width: 40px;
}
.content-section{
    position: relative;
    width: 80%;
    height: 90%;
    left: 50%;
    background-color: #ecf1f1;
    text-align: center;
    -webkit-transform: translateX(-50%);
  -moz-transform: translateX(-50%);
  -ms-transform: translateX(-50%);
  -o-transform: translateX(-50%);
  transform: translateX(-50%);
}
.content-section h1{
    position: relative;
    top: 50%;
    left: 50%;
    -webkit-transform: translateX(-50%) translateY(-50%);
  -moz-transform: translateX(-50%) translateY(-50%);
  -ms-transform: translateX(-50%) translateY(-50%);
  -o-transform: translateX(-50%) translateY(-50%);
  transform: translateX(-50%) translateY(-50%);
    color:#9b59b6;
    font-size: 3em;
}

/*CREDITS*/
.about{
    position: fixed;
    bottom:0;
    left: 1%;
}
.about a{
    text-decoration: none;
    font-size: 1.5em;
}
.about a:visited, .about a:active, .about a:link{
    color:#000;
}
.about a:hover{
    color: red;
}</code>```

                ONE

                TWO

                THREE

                FOUR

                FIVE

SECTION ONE

SECTION TWO

SECTION THREE

SECTION FOUR

SECTION FIVE

♡

```

Body:
I got this pen: https://codepen.io/janmez/pen/gryoKG but would like it to work more like on this site: https://rallyinteractive.com/. Not the background change, just list on the left. My js knowledge is not sufficient, can you help?

I tried achieving this with css but no success.

Edit: I added the full code and now what I want to achieve. I don't care about background animation, just wanted to make the nav and .content-section work more like on the site I mentioned above. Pen code does some of what I want: nav items get selected while scrolling to the relevant section. What I want to do is to have active nav elements always centered vertically and scroll together with sections. The example site (rallyinteractive.com) does exactly what I need.

$(document).ready(function(){
    var contentSection = $('.content-section');
    var navigation = $('nav');

    //when a nav link is clicked, smooth scroll to the section
    navigation.on('click', 'a', function(event){
        event.preventDefault(); //prevents previous event
        smoothScroll($(this.hash));
    });

    //update navigation on scroll...
    $(window).on('scroll', function(){
        updateNavigation();
    })
    //...and when the page starts
    updateNavigation();

    /////FUNCTIONS
    function updateNavigation(){
        contentSection.each(function(){
            var sectionName = $(this).attr('id');
            var navigationMatch = $('nav a[href="#' + sectionName + '"]');
            if( ($(this).offset().top - $(window).height()/2 < $(window).scrollTop()) &&
                  ($(this).offset().top + $(this).height() - $(window).height()/2 > $(window).scrollTop()))
                {
                    navigationMatch.addClass('active-section');
                }
            else {
                navigationMatch.removeClass('active-section');
            }
        });
    }
    function smoothScroll(target){
        $('body,html').animate({
            scrollTop: target.offset().top
        }, 800);
    }
});

@import url(https://fonts.googleapis.com/css?family=Open+Sans);
@import url(https://fonts.googleapis.com/css?family=Lato);

html{
    height: 100%;
    font-family: 'Open Sans', sans-serif;
    background-color: #E9E8E2;
}
body{
    height: 100%;
}
nav{
    width: 15%;
    height: 400px;
    position: fixed;
    top: auto;
    bottom: auto;
    z-index: 10;
        scroll-snap-type: y mandatory;
overflow-y: hidden;
}
ul{
    list-style: none;
    padding: 0;
text-align:center;
    valign:center;
}
li{
    padding: 40px 0;
    scroll-snap-align: center;
}
span{
    display: inline-block;
    position:relative;
}
nav a{
    display: inline-block;
    color: #272727;
    text-decoration: none;
    font-size: 1em;
}
.circle{
    height: 10px;
    width: 10px;
    left: -10px;
    border-radius: 50%;
    background-color: #272727;
}
.rect{
    height: 3px;
    width: 0px;
    left: 0;
    bottom: 4px;
    background-color: #272727;
    -webkit-transition: -webkit-transform 0.6s, width 1s;
    -moz-transition: -webkit-transform 0.6s, width 1s;
    transition: transform 0.6s, width 1s;
}
nav a:hover, nav .active-section{
    color: #9b59b6;
}
nav a:hover span, nav .active-section span{
    background-color: #9b59b6;
}
nav .active-section .rect{
    width: 40px;
}
.content-section{
    position: relative;
    width: 80%;
    height: 90%;
    left: 50%;
    background-color: #ecf1f1;
    text-align: center;
    -webkit-transform: translateX(-50%);
  -moz-transform: translateX(-50%);
  -ms-transform: translateX(-50%);
  -o-transform: translateX(-50%);
  transform: translateX(-50%);
}
.content-section h1{
    position: relative;
    top: 50%;
    left: 50%;
    -webkit-transform: translateX(-50%) translateY(-50%);
  -moz-transform: translateX(-50%) translateY(-50%);
  -ms-transform: translateX(-50%) translateY(-50%);
  -o-transform: translateX(-50%) translateY(-50%);
  transform: translateX(-50%) translateY(-50%);
    color:#9b59b6;
    font-size: 3em;
}

/*CREDITS*/
.about{
    position: fixed;
    bottom:0;
    left: 1%;
}
.about a{
    text-decoration: none;
    font-size: 1.5em;
}
.about a:visited, .about a:active, .about a:link{
    color:#000;
}
.about a:hover{
    color: red;
}

                ONE

                TWO

                THREE

                FOUR

                FIVE

SECTION ONE

SECTION TWO

SECTION THREE

SECTION FOUR

SECTION FIVE

♡


问:
Removing HTML tags from Postgres text/xml, with exceptions?
I am working with a frontend that utilizes a wysiwyg editor, and we want to be able to support specific html tags in the string input (i, strong, p, h1 tags, etc).

The frontend makes serverless queries directly to a Postgres db.

There seem to be ways to remove all HTML tags from a string/xml by utilizing regexp_replace; but is there a way to utilize a Postgres trigger/function to remove HTML tags with a set of explicit exceptions?

I am looking for functionality similar to pHp's strip_tags method, but I have not been able to find guidance for this use case.

TIA!


问:
Waterfall spectrogram using js library
I would like to add a waterfall spectrogram to my web page and I didn't find the proper js library to fit my needs.
Do you have some suggestions to implement this task?
Is it possible to use js only? Or do I have to "touch" the backend as well?
I need something like this :

Title: Waterfall spectrogram using js library


问:
react-native assembleRelease Can't Access Database on higher Android versions
I just recently assemble my react native app, the app is able to access my database which is in my computer on android versions 9 below, but when it comes to 10 and above it won't, i'm able to open the app but couldn't do much other than navigating to the landing page.

in debug mode i can access the database using android 10 and up


问:
Key not found in response array for php and my chart is empty for my javaScript
i'm doing this school project. can you help me?

The project consists in the creation of a web interface which, by querying an endpoint, is able to:
log in with a registered user to retrieve an authentication token.
once the token has been recovered, show two graphs that update independently of each other at regular intervals, without having to reload the page
The end-point must be created in object-oriented PHP, and must in turn query, using the php cURL library,

Specifications Endpoints

url: https://cool/login/

request format: x-www-form-urlencoded

response format: json

error example: {status: 123, message:'error description'}

LOGIN:

http:POST method

parameters: email, password

response example: {status: 0, message:'login completed', token: '...'}

GRAPHIC DATA:

http method: GET

headers: tokens

parameters:graph

response example: {status: 0, dataset: [{email: test1@test.it, data: 10}, {...}]}

this is my login html page:

```<code><!DOCTYPE html>
<html lang="en">
<head>

 <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>My Login Interface</title>

</head>
<body>

    <div class="login-box">
        <!-- Login form -->
        <div class="card">
          <div class="card-body login-card-body">
        <form id="login-form" method="post" action="home.php">
          <div class="input-group mb-3">
          <label for="email">Email:</label><br>
          <input type="email" class="form-control" id="email" name="email"><br>
          <div class="input-group-append">
            <div class="input-group-text">
              <span class="fas fa-envelope"></span>
            </div>
          </div>
          </div>
          <div class="input-group mb-3">
          <label for="password">Password:</label><br>
          <input type="password" class="form-control" id="password" name="password"><br><br>
          <div class="input-group-append">
            <div class="input-group-text">
              <span class="fas fa-lock"></span>
            </div>
          </div>
          </div>
          <input type="submit" value="Submit">

        </form>
          </div>
        </div>
    </div>

</body>
</html>
</code>```

This is my php page where speak with the server:

```<code><?php
session_start();
$email = "";
$password = "";
$response = "";
$chart_url = "";

// Check if the form was submitted
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email = htmlspecialchars($_POST['email']);
    $password = htmlspecialchars($_POST['password']);
}

$response = curl_exec($ch);
$token = $response;

$response_array = json_decode($response, true);
$_SESSION['token'] = $response_array['token'];
if(isset($response_array['chart_url'])){
    $chart_url = $response_array['chart_url'];
} else {
    echo 'Error: chart_url key not found in response array';
}
$chart_url = "https://cool/login/3?token=" . $response_array['token'];
if ($response_array['status'] === 0) {
    $_SESSION['token'] = $response_array['token'];

    //if the authentication was successful, include the HTML file that contains the chart
    require_once("graph_test.html");
    //pass the chart url to the iframe
    echo "<script>document.getElementById('chart-iframe').src = '$chart_url';</script>";
    echo "<script>var token = '$token';</script>";
} else {
    echo '<p>Incorrect email or password</p>';
}
curl_close($ch);
?>
</code>```

so i suceded in getting the token and got redirected to my graph.html

this is my graph.html:

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <script src="https://code.highcharts.com/highcharts.js"></script>
</head>
<body>

<div id="chart-container"></div>
       <iframe id="chart-iframe" src="https://cool/login/?token=<?php echo urlencode($_SESSION['token']); ?>&graph=1"></iframe>
      </div>
<script>
    // Get the iframe element
    var chartIframe = document.getElementById("chart-iframe");

    // Set the src attribute of the iframe to the chart URL
    chartIframe.src = "https://cool/login/?token=<?php echo urlencode($_SESSION['token']); ?>&graph=1";
    // Get the token from PHP
    var token = '<?php echo $token; ?>';
    document.getElementById('chart-iframe').src = '$chart_url';
        // Set the URL of the API endpoint
        var apiUrl = "https://cool/login/?token=" + token + "&graph=1";

        // Initialize the chart
        var chart = new Highcharts.Chart({
            chart: {
                renderTo: 'chart-container',
                type: 'bar'
            },
            title: {
                text: 'Chart Title'
            },
            xAxis: {
                type: 'category',
                labels: {
                    rotation: -45,
                    style: {
                        fontSize: '13px',
                        fontFamily: 'Verdana, sans-serif'
                    }
                }
            },
            yAxis: {
                min: 0,
                title: {
                    text: 'Y-axis Label'
                }
            },
            legend: {
                enabled: false
            },
            series: [{
                name: 'Series Name',
                data: []  // Data will be populated here
            }]
        });
// Create an XMLHttpRequest object
var xhr = new XMLHttpRequest();

// Open the request and set the headers
xhr.open("GET", chartUrl);
xhr.setRequestHeader("Authorization", "Bearer " + token);

// Function to handle the response
xhr.onload = function() {
    if (xhr.status === 200) {
        var response = JSON.parse(xhr.responseText);
        // Use the response data to update the chart
        chart.series[0].setData(response.data);
    } else {
        console.log("Error: " + xhr.status);
    }
};

// Send the request
xhr.send();
</script>
</body>
</html>
</code>```

But i have encontuered a couple of problems.

the graph.html gives me the: Error: chart_url key not found in response array
plus my chart is completely empty and i can't understand why.

The error message "Error: chart_url key not found in response array" is usually indicating that the $response_array variable doesn't contain a key named "chart_url". so if i want to use the token that you received from the API in the iframe's URL, i change this line:

```<code>$chart_url = $response_array['chart_url'];
</code>```

to this line:

```<code>$chart_url = "https://cloud.fatturapro.click/junior2023?token=" . $response_array['token'];
</code>```

This will append the token that you received from the API to the URL of the iframe. You can test the iframe by adding this line at the end of my php file

```<code>echo "<script>document.getElementById('chart-iframe').src = '$chart_url';</script>";
</code>```

but than again it didn't work.
I am really a beginner in php.

for the other problem

i've tried to make an additional API call to get the data:

```<code>//create an XMLHttpRequest object
  var xhr = new XMLHttpRequest();

  //open the request and set the headers
  xhr.open("GET", chart_url);
  xhr.setRequestHeader("Authorization", "Bearer " + token);

  //function to handle the response
  xhr.onload = function() {
    if (xhr.status === 200) {
      var data = JSON.parse(xhr.responseText);
      //update the chart with the retrieved data
      chart.update({
        series: [{
          data: data
        }]
      });
    } else {
      console.log("Error: " + xhr.status);
    }
  };

  //send the request
  xhr.send();
</code>```

but it didn't work.
Could you help?

Body:
i'm doing this school project. can you help me?

The project consists in the creation of a web interface which, by querying an endpoint, is able to:
log in with a registered user to retrieve an authentication token.
once the token has been recovered, show two graphs that update independently of each other at regular intervals, without having to reload the page
The end-point must be created in object-oriented PHP, and must in turn query, using the php cURL library,

Specifications Endpoints

url: https://cool/login/

request format: x-www-form-urlencoded

response format: json

error example: {status: 123, message:'error description'}

LOGIN:

http:POST method

parameters: email, password

response example: {status: 0, message:'login completed', token: '...'}

GRAPHIC DATA:

http method: GET

headers: tokens

parameters:graph

response example: {status: 0, dataset: [{email: test1@test.it, data: 10}, {...}]}

this is my login html page:

<!DOCTYPE html>

 <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>My Login Interface</title>

        <form id="login-form" method="post" action="home.php">

          Email:

          <input type="email" class="form-control" id="email" name="email">

          Password:

          <input type="password" class="form-control" id="password" name="password">

          <input type="submit" value="Submit">

        </form>

This is my php page where speak with the server:

<?php
session_start();
$email = "";
$password = "";
$response = "";
$chart_url = "";

// Check if the form was submitted
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email = htmlspecialchars($_POST['email']);
    $password = htmlspecialchars($_POST['password']);
}

$response = curl_exec($ch);
$token = $response;

$response_array = json_decode($response, true);
$_SESSION['token'] = $response_array['token'];
if(isset($response_array['chart_url'])){
    $chart_url = $response_array['chart_url'];
} else {
    echo 'Error: chart_url key not found in response array';
}
$chart_url = "https://cool/login/3?token=" . $response_array['token'];
if ($response_array['status'] === 0) {
    $_SESSION['token'] = $response_array['token'];

    //if the authentication was successful, include the HTML file that contains the chart
    require_once("graph_test.html");
    //pass the chart url to the iframe
    echo "";
    echo "";
} else {
    echo '
Incorrect email or password
';
}
curl_close($ch);
?>

so i suceded in getting the token and got redirected to my graph.html

this is my graph.html:

<!DOCTYPE html>

       <iframe id="chart-iframe" src="https://cool/login/?token=<?php echo urlencode($_SESSION['token']); ?>&graph=1">

But i have encontuered a couple of problems.

the graph.html gives me the: Error: chart_url key not found in response array
plus my chart is completely empty and i can't understand why.

The error message "Error: chart_url key not found in response array" is usually indicating that the $response_array variable doesn't contain a key named "chart_url". so if i want to use the token that you received from the API in the iframe's URL, i change this line:

$chart_url = $response_array['chart_url'];

to this line:

$chart_url = "https://cloud.fatturapro.click/junior2023?token=" . $response_array['token'];

This will append the token that you received from the API to the URL of the iframe. You can test the iframe by adding this line at the end of my php file

echo "";

but than again it didn't work.
I am really a beginner in php.

for the other problem

i've tried to make an additional API call to get the data:

//create an XMLHttpRequest object
  var xhr = new XMLHttpRequest();

  //open the request and set the headers
  xhr.open("GET", chart_url);
  xhr.setRequestHeader("Authorization", "Bearer " + token);

  //function to handle the response
  xhr.onload = function() {
    if (xhr.status === 200) {
      var data = JSON.parse(xhr.responseText);
      //update the chart with the retrieved data
      chart.update({
        series: [{
          data: data
        }]
      });
    } else {
      console.log("Error: " + xhr.status);
    }
  };

  //send the request
  xhr.send();

but it didn't work.
Could you help?


问:
How to import csv file to MySQL workbench?
I am trying to import .sql file of about 0.6 million rows to Mysql workbench, I am following this procedure ( Right click on database --> click on Table Data import Wizard --> browse to my csv -- next -->  next)  but I get the following error

```<code>`Prepare Import...
Prepare Import done
Import data file....
- Truncate table
- Prepare Import

Traceback (most recent call last):
  File "C:\Program Files\MySQL\MySQL Workbench 8.0\workbench\wizard_progress_page_widget.py", line 197, in thread_work
    self.func()
  File "C:\Program Files\MySQL\MySQL Workbench 8.0\modules\sqlide_power_import_wizard.py", line 131, in start_import
    retval = self.module.start(self.stop)
  File "C:\Program Files\MySQL\MySQL Workbench 8.0\modules\sqlide_power_import_export_be.py", line 300, in start
    ret = self.start_import()
  File "C:\Program Files\MySQL\MySQL Workbench 8.0\modules\sqlide_power_import_export_be.py", line 430, in start_import
    self._editor.executeManagementCommand(query, 1)
grt.DBError: ("Unknown column 'None' in 'field list'", 1054)
ERROR: Import data file: ("Unknown column 'None' in 'field list'", 1054)
Failed
`
</code>```

Can someone help me
Also I follow this query

```<code>LOAD DATA LOCAL INFILE 'D:\REPORTING_GENERAL.csv'
INTO TABLE reporting_general FIELDS TERMINATED BY ','
ENCLOSED BY '"' LINES TERMINATED BY '\n';
</code>```

but it gives this error

Error Code: 2068. LOAD DATA LOCAL INFILE file request rejected due to restrictions on access.`

I've checked all the questions on stackoverflow but failed, so please don't consider my question as duplicate

Body:
I am trying to import .sql file of about 0.6 million rows to Mysql workbench, I am following this procedure ( Right click on database --> click on Table Data import Wizard --> browse to my csv -- next -->  next)  but I get the following error

`Prepare Import...
Prepare Import done
Import data file....
- Truncate table
- Prepare Import

Traceback (most recent call last):
  File "C:\Program Files\MySQL\MySQL Workbench 8.0\workbench\wizard_progress_page_widget.py", line 197, in thread_work
    self.func()
  File "C:\Program Files\MySQL\MySQL Workbench 8.0\modules\sqlide_power_import_wizard.py", line 131, in start_import
    retval = self.module.start(self.stop)
  File "C:\Program Files\MySQL\MySQL Workbench 8.0\modules\sqlide_power_import_export_be.py", line 300, in start
    ret = self.start_import()
  File "C:\Program Files\MySQL\MySQL Workbench 8.0\modules\sqlide_power_import_export_be.py", line 430, in start_import
    self._editor.executeManagementCommand(query, 1)
grt.DBError: ("Unknown column 'None' in 'field list'", 1054)
ERROR: Import data file: ("Unknown column 'None' in 'field list'", 1054)
Failed
`

Can someone help me
Also I follow this query

LOAD DATA LOCAL INFILE 'D:\REPORTING_GENERAL.csv'
INTO TABLE reporting_general FIELDS TERMINATED BY ','
ENCLOSED BY '"' LINES TERMINATED BY '\n';

but it gives this error

Error Code: 2068. LOAD DATA LOCAL INFILE file request rejected due to restrictions on access.`

I've checked all the questions on stackoverflow but failed, so please don't consider my question as duplicate


问:
Decode ArrayBuffer on React-Native
I'm trying to decode an ArrayBuffer on React-Native. My data is an h264 stream, but for now i write native code for Android (MediaCodec) and iOS (VideoToolBox) for decode frames, work "nice".

But i would like use JS (or library) for this, for lack of knowledge in Java / Kotlin and Objective-c.

So, i've try to convert my ArrayBuffer to base64 (with base64-arraybuffer library) and try to play it with react-native-video, but not result.

```<code>const buffer = encode(data);
const blob = new Blob([buffer], {
  type: "video/avc",
  lastModified: Date.now(),
});
const url = URL.createObjectURL(blob);
</code>```

Maybe, the best is to write stream file ?

If anyone have an idea, very big thank you.

Title: Decode ArrayBuffer on React-Native

Body:
I'm trying to decode an ArrayBuffer on React-Native. My data is an h264 stream, but for now i write native code for Android (MediaCodec) and iOS (VideoToolBox) for decode frames, work "nice".

But i would like use JS (or library) for this, for lack of knowledge in Java / Kotlin and Objective-c.

So, i've try to convert my ArrayBuffer to base64 (with base64-arraybuffer library) and try to play it with react-native-video, but not result.

const buffer = encode(data);
const blob = new Blob([buffer], {
  type: "video/avc",
  lastModified: Date.now(),
});
const url = URL.createObjectURL(blob);

Maybe, the best is to write stream file ?

If anyone have an idea, very big thank you.


问:
Should we use getDerivedStateFromProps for class components every time when state relays on props?
I had to maintain an old project on class components, and so it turns out that the data for the modal window depends on the props, even though it is antipatern sometimes have to do something similar. My question is, should we use getDerivedStateFromProps for this or just save the props data to the state?

Example1:

```<code>    class Test extends Component {
     state = {
       data: 0,
     };

  static getDerivedStateFromProps(props, state) {
    if (this.props.data !== this.state.data) {
      return {
        monthlyLimit: this.props.data,
      };
    }
  }
</code>```

Example2:

```<code> class Test extends Component {
 state = {
   data: this.props.data,
 };
....
</code>```

Body:
I had to maintain an old project on class components, and so it turns out that the data for the modal window depends on the props, even though it is antipatern sometimes have to do something similar. My question is, should we use getDerivedStateFromProps for this or just save the props data to the state?

Example1:

    class Test extends Component {
     state = {
       data: 0,
     };

  static getDerivedStateFromProps(props, state) {
    if (this.props.data !== this.state.data) {
      return {
        monthlyLimit: this.props.data,
      };
    }
  }

Example2:

 class Test extends Component {
 state = {
   data: this.props.data,
 };
....


问:
Advanced Installer: How to prevent running jar file from other computer after installation
I used Advanced Installer to covert jar file to exe installer. To install exe file the user need to type serial key but after installation jar file is appear in installation folder and the user can copy it to another computer and can run it.

The another problems is after extract this jar file the user can see source code of my project.

I want to know how to prevent running this jar file from other computer and how to prevent viewing source code of my project after installation exe file.


问:
PTC Windchill WRS API "Cannot process objects checked out to another Workspace" when running the CreateAssociations command
Running the WRS '/Windchill/servlet/odata/v5/ProdMgmt/CreateAssociations' command returns this error message:

```<code>{ "error": { "code": "Error", "message": "Cannot process objects checked out to another Workspace" } }
</code>```

The part is checked out by the same user who is trying to run the API call.

Any suggestions?

The full command is:

```<code>curl -X POST --header 'Content-Type: application/json' --header 'Accept: application/json' --header 'CSRF_NONCE: #########' -d '{"PartDocAssociations":[{"AssociationType":{"Value":"OWNER"},"RelatedPart@odata.bind":"Parts('OR:wt.part.WTPart:######')","RelatedCADDoc@odata.bind":"CADDocuments('OR:wt.epm.EPMDocument:######')"}]}' 'http://##.###.#.##/Windchill/servlet/odata/v5/ProdMgmt/CreateAssociations?$count=false'
</code>```

Body:
Running the WRS '/Windchill/servlet/odata/v5/ProdMgmt/CreateAssociations' command returns this error message:

{ "error": { "code": "Error", "message": "Cannot process objects checked out to another Workspace" } }

The part is checked out by the same user who is trying to run the API call.

Any suggestions?

The full command is:

curl -X POST --header 'Content-Type: application/json' --header 'Accept: application/json' --header 'CSRF_NONCE: #########' -d '{"PartDocAssociations":[{"AssociationType":{"Value":"OWNER"},"RelatedPart@odata.bind":"Parts('OR:wt.part.WTPart:######')","RelatedCADDoc@odata.bind":"CADDocuments('OR:wt.epm.EPMDocument:######')"}]}' 'http://##.###.#.##/Windchill/servlet/odata/v5/ProdMgmt/CreateAssociations?$count=false'