问:
How to get the ValueItem value of ListBox item by its index
I have a listbox that has a description and a value stored in it (the description is a customer name and the valueitem is that customer's ID in the database) On my form I have two listboxes the one on the left has a full list of customer names and the user then selects from that list and adds the ones they want to associate a user with to the right hand listbox. When I come to save the record I want to store the list of customerIDs in a table so that I can identify which customers this record relates to.

My code loops through the list using a For .. Next loop:

```<code>For n = 0 To lbxCustomerList.Items.Count - 1
  U.CustomersLinkedTo += lbxCustomerList.Items(n).Value.ToString() & ","
Next
</code>```

U is a User record class and the field CustomersLinkedTo is an NVarchar(255) field that I will build a comma separated list to of the CustomerIDs that the user has allocated this user to.

The issue is that lbxCustomerList.Items(n).Value is not allowed. I am using VB.NET and Dot Net Framework V4.

I have tried loading the ListBox into a ListBox.ObjectCollection variable and then seeing if that allows me to access the ValuItems but that doesn't allow it either.  How do I get the values as opposed to the description text??

EDIT ****
In order to aid those good people who are trying to help me I am adding below the code I use to populate the Customer list and then the code I use to populate the lbxCustomersLinkedTo that contains the customers they have selected:

Populate the list on the left that the user picks Customer names from and adds them to the list on the right that contains the subset the user wants to allocate to to a user.

```<code>    Private Sub PopulateCustomerList()
    Dim c As New Customer()
    Dim cc As New ArrayList()

    Try
        'Clear list
        lbxCustomerList.Items.Clear()
        lbxCustomerList.DataSource = Nothing

        'Populate from DB.
        cc = c.GetCustomersForDropLists(customerTypeEnum.Active)
        lbxCustomerList.DataSource = cc
        lbxCustomerList.DisplayMember = "DisplayedText"
        lbxCustomerList.ValueMember = "ReturnedID"
        lbxCustomerList.Refresh()

    Catch ex As Exception
        PEH("PopulateCustomerList", "frmUserSetup", ex.Message)
    End Try
End Sub
</code>```

Code that adds the items the user selects from the Customers list to the one I am interested in that I use to derive teh Customer ID list I want to add to my user's record.

```<code>   Private Sub AddToList()
    Dim SelItems As New ListBox.SelectedObjectCollection(lbxCustomerList)
    SelItems = lbxCustomerList.SelectedItems

    Try

        If lbxCustomerList.SelectedItems.Count > 0 Then
            For n = 0 To SelItems.Count - 1
                lbxCustomersLinkedTo.Items.Add(SelItems(n))
            Next
            lbxCustomerList.ClearSelected()
        End If

    Catch ex As Exception
        PEH("AddToList", "frmUserSetup", ex.Message)
    End Try
End Sub
</code>```

This is an image of the part of the user form I am talking about:

@ThePeter - Thanks your routine with a slight modification did the trick.

This is my code in the save routine now:

```<code>           'Get the Customers an officer works for into a comma separated list.
        'First remove any existing items.
        U.CustomersLinkedTo = ""

        If (lbxCustomersLinkedTo.Items.Count > 0) Then
            For n = 0 To lbxCustomersLinkedTo.Items.Count - 1
                If n = lbxCustomersLinkedTo.Items.Count - 1 Then
                    U.CustomersLinkedTo += WhatValueIsSelectedInListBoxForIndex(lbxCustomersLinkedTo, n) 'Don't add comma to last item.
                Else
                    U.CustomersLinkedTo += WhatValueIsSelectedInListBoxForIndex(lbxCustomersLinkedTo, n) & ","
                End If
            Next
        End If
</code>```

This is your routine modified slightly as it gave an error initially:

```<code>   ''' <summary>
''' Use this function to get the values of an item in the list box. It works with list boxes that are bound to a DataSet, and those that have been populated via code, or manually populated via the GUI.
''' </summary>
''' <param name="lstBox">The list box you want to find the selected value in.</param>
''' <param name="iIndex">The number of the item in the ListBox that you want the value for.</param>
''' <param name="DesiredReturnValue">By default it returns the hidden return value, but you can ask for the display value if desired.</param>
''' <returns>This function returns a String value.</returns>
Public Function WhatValueIsSelectedInListBoxForIndex(ByVal lstBox As ListBox, ByVal iIndex As Integer, Optional ByVal DesiredReturnValue As SelectByMode = SelectByMode.ByReturnValue) As String
    Dim sReturn As String = ""

    Try
        If DesiredReturnValue = SelectByMode.ByReturnValue Then
            'Returns the value that is not visible, but stored in the "ValueMember" field of the bound ComboBox
            If lstBox.ValueMember.Length > 0 And lstBox.DisplayMember.Length > 0 Then
                'This is a bound listbox.
                Dim drSelectedItem As DataRowView = lstBox.Items(iIndex)
                sReturn = drSelectedItem.Item(0).ToString
            Else
                Try
                    'This listbox was populated in code with display values and return values.
                    sReturn = lstBox.Items(iIndex).ReturnedID
                Catch ex As Exception
                    PEH("WhatValueIsSelectedInListBoxForIndex - Populated Code section", "frmUserSetup", ex.Message)
                End Try
            End If
        ElseIf DesiredReturnValue = SelectByMode.ByDisplayName Then
            'Return the selected TEXT (visible in the control)
            If lstBox.ValueMember.Length > 0 And lstBox.DisplayMember.Length > 0 Then
                'This is a bound listbox.
                Dim drSelectedItem As DataRowView = lstBox.Items(iIndex)
                sReturn = drSelectedItem.Item(1).ToString
            Else
                sReturn = lstBox.Items(iIndex).ToString
            End If
        Else
            sReturn = ""
        End If
    Catch Ex As Exception

        PEH("WhatValueIsSelectedInListBoxForIndex", "frmUserSetup", Ex.Message)
        sReturn = ""
    End Try

    If sReturn Is Nothing Then sReturn = ""
    Return sReturn

End Function
</code>```

The bit I had to modify to suit my listbox was the line:

```<code>                       'This listbox was populated in code with display values and return values.
                    sReturn = lstBox.Items(iIndex).ReturnedID
</code>```

With your help, this now works and populates the database field directly.

Siv

答:
This function will allow you to find the value of what is selected in a ListBox. You can use it to get either the "hidden" value of a selected item or the displayed value of an item in the ListBox.

Update: I adjusted the function so it works based on the index value, as per the original question

```<code>Public Enum SelectByMode As Integer
   ByDisplayName = 1
   ByReturnValue = 2
End Enum

''' <summary>
''' Use this function to get the values of an item in the list box. It works with list boxes that are bound to a DataSet, and those that have been populated via code, or manually populated via the GUI.
''' </summary>
''' <param name="lstBox">The list box you want to find the selected value in.</param>
''' <param name="iIndex">The number of the item in the ListBox that you want the value for.</param>
''' <param name="DesiredReturnValue">By default it returns the hidden return value, but you can ask for the display value if desired.</param>
''' <returns>This function returns a String value.</returns>
Public Function WhatValueIsSelectedInListBoxForIndex(ByVal lstBox As ListBox, ByVal iIndex As Integer, Optional ByVal DesiredReturnValue As SelectByMode = SelectByMode.ByReturnValue) As String
    Dim sReturn As String = ""

    Try
        If DesiredReturnValue = SelectByMode.ByReturnValue Then
            'Returns the value that is not visible, but stored in the "ValueMember" field of the bound ComboBox
            If lstBox.ValueMember.Length > 0 And lstBox.DisplayMember.Length > 0 Then
                'This is a bound listbox.
                Dim drSelectedItem As DataRowView = lstBox.Items(iIndex)
                sReturn = drSelectedItem.Item(0).ToString
            Else
                Try
                    'This listbox was populated in code with display values and return values.
                    sReturn = lstBox.Items(iIndex).ReturnValue
                Catch Exp As Exception
                    '
                End Try
            End If
        ElseIf DesiredReturnValue = SelectByMode.ByDisplayName Then
            'Return the selected TEXT (visible in the control)
            If lstBox.ValueMember.Length > 0 And lstBox.DisplayMember.Length > 0 Then
                'This is a bound listbox.
                Dim drSelectedItem As DataRowView = lstBox.Items(iIndex)
                sReturn = drSelectedItem.Item(1).ToString
            Else
                sReturn = lstBox.Items(iIndex).ToString
            End If
        Else
            sReturn = ""
        End If
    Catch Exp As Exception
        'You do whatever you want to do here when an error occurs.
    End Try

    If sReturn Is Nothing Then sReturn = ""
    Return sReturn
End Function
</code>```

Body:
I have a listbox that has a description and a value stored in it (the description is a customer name and the valueitem is that customer's ID in the database) On my form I have two listboxes the one on the left has a full list of customer names and the user then selects from that list and adds the ones they want to associate a user with to the right hand listbox. When I come to save the record I want to store the list of customerIDs in a table so that I can identify which customers this record relates to.

My code loops through the list using a For .. Next loop:

For n = 0 To lbxCustomerList.Items.Count - 1
  U.CustomersLinkedTo += lbxCustomerList.Items(n).Value.ToString() & ","
Next

U is a User record class and the field CustomersLinkedTo is an NVarchar(255) field that I will build a comma separated list to of the CustomerIDs that the user has allocated this user to.

The issue is that lbxCustomerList.Items(n).Value is not allowed. I am using VB.NET and Dot Net Framework V4.

I have tried loading the ListBox into a ListBox.ObjectCollection variable and then seeing if that allows me to access the ValuItems but that doesn't allow it either.  How do I get the values as opposed to the description text??

EDIT ****
In order to aid those good people who are trying to help me I am adding below the code I use to populate the Customer list and then the code I use to populate the lbxCustomersLinkedTo that contains the customers they have selected:

Populate the list on the left that the user picks Customer names from and adds them to the list on the right that contains the subset the user wants to allocate to to a user.

    Private Sub PopulateCustomerList()
    Dim c As New Customer()
    Dim cc As New ArrayList()

    Try
        'Clear list
        lbxCustomerList.Items.Clear()
        lbxCustomerList.DataSource = Nothing

        'Populate from DB.
        cc = c.GetCustomersForDropLists(customerTypeEnum.Active)
        lbxCustomerList.DataSource = cc
        lbxCustomerList.DisplayMember = "DisplayedText"
        lbxCustomerList.ValueMember = "ReturnedID"
        lbxCustomerList.Refresh()

    Catch ex As Exception
        PEH("PopulateCustomerList", "frmUserSetup", ex.Message)
    End Try
End Sub

Code that adds the items the user selects from the Customers list to the one I am interested in that I use to derive teh Customer ID list I want to add to my user's record.

   Private Sub AddToList()
    Dim SelItems As New ListBox.SelectedObjectCollection(lbxCustomerList)
    SelItems = lbxCustomerList.SelectedItems

    Try

        If lbxCustomerList.SelectedItems.Count > 0 Then
            For n = 0 To SelItems.Count - 1
                lbxCustomersLinkedTo.Items.Add(SelItems(n))
            Next
            lbxCustomerList.ClearSelected()
        End If

    Catch ex As Exception
        PEH("AddToList", "frmUserSetup", ex.Message)
    End Try
End Sub

This is an image of the part of the user form I am talking about:

@ThePeter - Thanks your routine with a slight modification did the trick.

This is my code in the save routine now:

           'Get the Customers an officer works for into a comma separated list.
        'First remove any existing items.
        U.CustomersLinkedTo = ""

        If (lbxCustomersLinkedTo.Items.Count > 0) Then
            For n = 0 To lbxCustomersLinkedTo.Items.Count - 1
                If n = lbxCustomersLinkedTo.Items.Count - 1 Then
                    U.CustomersLinkedTo += WhatValueIsSelectedInListBoxForIndex(lbxCustomersLinkedTo, n) 'Don't add comma to last item.
                Else
                    U.CustomersLinkedTo += WhatValueIsSelectedInListBoxForIndex(lbxCustomersLinkedTo, n) & ","
                End If
            Next
        End If

This is your routine modified slightly as it gave an error initially:

   '''
''' Use this function to get the values of an item in the list box. It works with list boxes that are bound to a DataSet, and those that have been populated via code, or manually populated via the GUI.
'''
''' <param name="lstBox">The list box you want to find the selected value in.</param>
''' <param name="iIndex">The number of the item in the ListBox that you want the value for.</param>
''' <param name="DesiredReturnValue">By default it returns the hidden return value, but you can ask for the display value if desired.</param>
''' <returns>This function returns a String value.</returns>
Public Function WhatValueIsSelectedInListBoxForIndex(ByVal lstBox As ListBox, ByVal iIndex As Integer, Optional ByVal DesiredReturnValue As SelectByMode = SelectByMode.ByReturnValue) As String
    Dim sReturn As String = ""

    Try
        If DesiredReturnValue = SelectByMode.ByReturnValue Then
            'Returns the value that is not visible, but stored in the "ValueMember" field of the bound ComboBox
            If lstBox.ValueMember.Length > 0 And lstBox.DisplayMember.Length > 0 Then
                'This is a bound listbox.
                Dim drSelectedItem As DataRowView = lstBox.Items(iIndex)
                sReturn = drSelectedItem.Item(0).ToString
            Else
                Try
                    'This listbox was populated in code with display values and return values.
                    sReturn = lstBox.Items(iIndex).ReturnedID
                Catch ex As Exception
                    PEH("WhatValueIsSelectedInListBoxForIndex - Populated Code section", "frmUserSetup", ex.Message)
                End Try
            End If
        ElseIf DesiredReturnValue = SelectByMode.ByDisplayName Then
            'Return the selected TEXT (visible in the control)
            If lstBox.ValueMember.Length > 0 And lstBox.DisplayMember.Length > 0 Then
                'This is a bound listbox.
                Dim drSelectedItem As DataRowView = lstBox.Items(iIndex)
                sReturn = drSelectedItem.Item(1).ToString
            Else
                sReturn = lstBox.Items(iIndex).ToString
            End If
        Else
            sReturn = ""
        End If
    Catch Ex As Exception

        PEH("WhatValueIsSelectedInListBoxForIndex", "frmUserSetup", Ex.Message)
        sReturn = ""
    End Try

    If sReturn Is Nothing Then sReturn = ""
    Return sReturn

End Function

The bit I had to modify to suit my listbox was the line:

                       'This listbox was populated in code with display values and return values.
                    sReturn = lstBox.Items(iIndex).ReturnedID

With your help, this now works and populates the database field directly.

Siv

Body:
This function will allow you to find the value of what is selected in a ListBox. You can use it to get either the "hidden" value of a selected item or the displayed value of an item in the ListBox.

Update: I adjusted the function so it works based on the index value, as per the original question

Public Enum SelectByMode As Integer
   ByDisplayName = 1
   ByReturnValue = 2
End Enum

''' <summary>
''' Use this function to get the values of an item in the list box. It works with list boxes that are bound to a DataSet, and those that have been populated via code, or manually populated via the GUI.
''' </summary>
''' <param name="lstBox">The list box you want to find the selected value in.</param>
''' <param name="iIndex">The number of the item in the ListBox that you want the value for.</param>
''' <param name="DesiredReturnValue">By default it returns the hidden return value, but you can ask for the display value if desired.</param>
''' <returns>This function returns a String value.</returns>
Public Function WhatValueIsSelectedInListBoxForIndex(ByVal lstBox As ListBox, ByVal iIndex As Integer, Optional ByVal DesiredReturnValue As SelectByMode = SelectByMode.ByReturnValue) As String
    Dim sReturn As String = ""

    Try
        If DesiredReturnValue = SelectByMode.ByReturnValue Then
            'Returns the value that is not visible, but stored in the "ValueMember" field of the bound ComboBox
            If lstBox.ValueMember.Length > 0 And lstBox.DisplayMember.Length > 0 Then
                'This is a bound listbox.
                Dim drSelectedItem As DataRowView = lstBox.Items(iIndex)
                sReturn = drSelectedItem.Item(0).ToString
            Else
                Try
                    'This listbox was populated in code with display values and return values.
                    sReturn = lstBox.Items(iIndex).ReturnValue
                Catch Exp As Exception
                    '
                End Try
            End If
        ElseIf DesiredReturnValue = SelectByMode.ByDisplayName Then
            'Return the selected TEXT (visible in the control)
            If lstBox.ValueMember.Length > 0 And lstBox.DisplayMember.Length > 0 Then
                'This is a bound listbox.
                Dim drSelectedItem As DataRowView = lstBox.Items(iIndex)
                sReturn = drSelectedItem.Item(1).ToString
            Else
                sReturn = lstBox.Items(iIndex).ToString
            End If
        Else
            sReturn = ""
        End If
    Catch Exp As Exception
        'You do whatever you want to do here when an error occurs.
    End Try

    If sReturn Is Nothing Then sReturn = ""
    Return sReturn
End Function


来源: stackexchange

问:
How to remove this part of the URL?
I have a problem that I hope you can help me with. So, basically, I developed a portfolio website for a client, and it has 4 sections: home, work, feed, info.

So the thing is that I developed everything but the home page using Wordpress (Semplice template, which is kind of a live editor).The home page was created using html, css and js on my own.

I uploaded everything to my host, and I want the website to load firstly the Home page I designed with my code. From this home page you can go using the nav to the other sections created with Wordpress.

So one of the main things that I already solved was the fact that I had in the same folder an index.php (the wordpress default index, needed to load all of the other wordpress sections, so I cant delete it) and the index.html (the one I've coded myself). As I couldn't just delete the index.php as it was necessary to load the other wordpress sections, I had to use the .htaccess file to redirect it, so when I type https://mysitedomain.com it goes to https://mysitedomain.com/index.html

I managed to do it pasting this code on top of the .htaccess file:

```<code>RewriteRule ^$ https://mysitedomain.com/index.html [L,R=301]
</code>```

What I want to do now is hiding that "/index.html" from the main link when I go to the website. If I take it away from my .htaccess file, the website will charge the wordpress index.php, which is what I am trying to avoid.

How can I hide that "/index.html" from the main link but not affecting the redirection that I previously did to charge my index.html file instead of the wordpress index.php?

答:
Add to top of .htaccess file the following line and remove your index.html RewriteRule:</p>

```<code>DirectoryIndex index.html index.php
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to remove this part of the URL?

Body:
I have a problem that I hope you can help me with. So, basically, I developed a portfolio website for a client, and it has 4 sections: home, work, feed, info.

So the thing is that I developed everything but the home page using Wordpress (Semplice template, which is kind of a live editor).The home page was created using html, css and js on my own.

I uploaded everything to my host, and I want the website to load firstly the Home page I designed with my code. From this home page you can go using the nav to the other sections created with Wordpress.

So one of the main things that I already solved was the fact that I had in the same folder an index.php (the wordpress default index, needed to load all of the other wordpress sections, so I cant delete it) and the index.html (the one I've coded myself). As I couldn't just delete the index.php as it was necessary to load the other wordpress sections, I had to use the .htaccess file to redirect it, so when I type https://mysitedomain.com it goes to https://mysitedomain.com/index.html

I managed to do it pasting this code on top of the .htaccess file:

RewriteRule ^$ https://mysitedomain.com/index.html [L,R=301]

What I want to do now is hiding that "/index.html" from the main link when I go to the website. If I take it away from my .htaccess file, the website will charge the wordpress index.php, which is what I am trying to avoid.

How can I hide that "/index.html" from the main link but not affecting the redirection that I previously did to charge my index.html file instead of the wordpress index.php?

Body:
Add to top of .htaccess file the following line and remove your index.html RewriteRule:

DirectoryIndex index.html index.php


问:
extending @font-face declaration from external css file
I am using a web-font that is declared with @font-face in an external css file. The font service is setup such that I source the external css file and then just use the font in my css.  I cannot source the font file itself in my own @font-face definition.

Every time I use the web-font on my site, I add the same two style definitions to it.  So, my font use always looks something like this:

```<code>h2{
   font-family: 'Knockout 26 A';
   -webkit-font-smoothing: antialiased;
   -moz-osx-font-smoothing: grayscale;
}
</code>```

Adding the antialiasing and grayscale EVERY TIME I use the font seems unnecessarily redundant. Is there a way for me to extend the @font-face declaration from the external file in my own css?

Thanks!

答:
I actually faced the same kind of issue because the @font-face declaration was made in an external CSS file that I couldn't control.

I also tried to override the @font-face declaration but it does not work.

So the solution in my case was actually to declare the @font-face BEFORE the inclusion of the external CSS file. The browser will then use my @font-face declaration and ignore the one in the external file.

ContentLicense: CC BY-SA 3.0

Body:
I am using a web-font that is declared with @font-face in an external css file. The font service is setup such that I source the external css file and then just use the font in my css.  I cannot source the font file itself in my own @font-face definition.

Every time I use the web-font on my site, I add the same two style definitions to it.  So, my font use always looks something like this:

h2{
   font-family: 'Knockout 26 A';
   -webkit-font-smoothing: antialiased;
   -moz-osx-font-smoothing: grayscale;
}

Adding the antialiasing and grayscale EVERY TIME I use the font seems unnecessarily redundant. Is there a way for me to extend the @font-face declaration from the external file in my own css?

Thanks!


问:
Require filling out or giving an empty field alert for a form field before scrolling or clicking a "next" button in a multi-part form?
I'm building a multi-part form that is actually all on one page, it just uses anchors to give the illusion of multiple pages. Users click a link to continue to the next segment.

I am looking for a way to have an alert to fill in certain fields before clicking the next button or possibly by scrolling past a certain point. The next button is just a link and not a submit button, thus all the billions of times this has been asked before on the Internet don't apply here.

I am just looking for a soft-required, it doesn't have to actually force them to do it. And the reason I can't really do required on submitting fields in this form is that all of the unique segments and a user might never see a segment that has a required field based on their inputs. Not to mention it would be a pain to go back in a 20 step form to find the field you left blank.

It's not critical that they are filled out, just looking to give a heads-up to the users.

答:
It is a little confusing regarding exactly what you are wishing to do, but I would use javascript to create this.

Add a listener to the prev/next buttons calling a function when they are clicked.

In this function, check each input on the page to see if they are empty.

If they are empty, somehow explain to the user that they are empty (using an alert popup or some sort of css change)

You can use event.preventDefault() to prevent the user from navigating to the next page.

Let me know if you have any questions, I am explaining the process I believe you should follow.


问:
Declare non-void method as lambda
I really like how you can quickly implement interfaces using lambdas, the code becomes much shorter and more readable... We can use lambdas to implement properties

```<code>public ICollection<TKey> Keys => _dict.Keys;

public TValue this[TKey key] { get => _dict[key]; set => _dict[key] = value; }
</code>```

...or even methods

```<code>public void Clear() => _dict.Clear();
</code>```

But I can't figure out how to rewrite a non-void method using lamdbas? Like this one for example:

```<code>public bool ContainsKey(TKey key)
{
    return _dict.ContainsKey(key);
}
</code>```

答:
The syntax is the same:

```<code>public bool ContainsKey(TKey key) => _dict.ContainsKey(key);
</code>```

Also, these aren't really lambda expressions, rather "expression bodied members"; see: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/lambda-operator

Title: Declare non-void method as lambda

Body:
I really like how you can quickly implement interfaces using lambdas, the code becomes much shorter and more readable... We can use lambdas to implement properties

public ICollection<TKey> Keys => _dict.Keys;

public TValue this[TKey key] { get => _dict[key]; set => _dict[key] = value; }

...or even methods

public void Clear() => _dict.Clear();

But I can't figure out how to rewrite a non-void method using lamdbas? Like this one for example:

public bool ContainsKey(TKey key)
{
    return _dict.ContainsKey(key);
}

Body:
The syntax is the same:

public bool ContainsKey(TKey key) => _dict.ContainsKey(key);

Also, these aren't really lambda expressions, rather "expression bodied members"; see: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/lambda-operator


问:
LocalDateTime to specific timezone
I have a localdatetime object that is in UTC. I want to convert into IST.
How can I do that?

```<code>LocalDateTime dateTimeOfAfterFiveDays = LocalDateTime.ofEpochSecond(after5,0,ZoneOffset.UTC);
</code>```

答:
tl;dr

Use Instant, not LocalDateTime for tracking a moment.

```<code>Instant                                         // Represents a moment in UTC with a resolution of nanoseconds.
.ofEpochSecond(
    myCountOfWholeSecondsSinceStartOf1970UTC    // Internally, time is tracked as a count of seconds since 1970-01-01T00:00Z plus a fractional second as nanoseconds.
)                                               // Returns a moment in UTC.
.atZone(                                        // Adjust from UTC to another time zone. Same moment, different wall-clock time.
    ZoneId.of( "Asia/Kolkata" )                 // Specify time zone name in `Continent/Region` format, never 2-4 letter pseudo-zone.
)                                               // Returns a `ZonedDateTime` object.
.toString()                                     // Generate a string representing the value of this `ZonedDateTime` in standard ISO 8601 format extended to append the name of the time zone in square brackets.
</code>```

Wrong class

LocalDateTime dateTimeOfAfterFiveDays = LocalDateTime.ofEpochSecond(after5,0,ZoneOffset.UTC);

LocalDateTime is the wrong class to use here. This class cannot represent a moment. It lacks any concept of time zone or offset-from-UTC. A LocalDateTime holds just a date and a time-of-day, say noon on the 23rd of January this year. But we have no idea if what was intended was noon in Tokyo, noon in Kolkata, noon in Paris, or noon in Montréal — all of these are hours apart, very different moments.

Instant

To represent a moment in UTC, use Instant.

Apparently you have a count of whole seconds since the epoch reference of first moment of 1970 in UTC.

```<code>Instant instant = Instant.ofEpochSecond( count ) ;
</code>```

ZoneId & ZonedDateTime

To see this value through the wall-clock time used by the people of a particular region (a time zone), apply a ZoneId to get a ZonedDateTime.

Specify a proper time zone name in the format of Continent/Region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 2-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

```<code>ZoneId z = ZoneId.of( "Asia/Kolkata" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;
</code>```

Title: LocalDateTime to specific timezone

Body:
I have a localdatetime object that is in UTC. I want to convert into IST.
How can I do that?

LocalDateTime dateTimeOfAfterFiveDays = LocalDateTime.ofEpochSecond(after5,0,ZoneOffset.UTC);

Body:
tl;dr

Use Instant, not LocalDateTime for tracking a moment.

Instant                                         // Represents a moment in UTC with a resolution of nanoseconds.
.ofEpochSecond(
    myCountOfWholeSecondsSinceStartOf1970UTC    // Internally, time is tracked as a count of seconds since 1970-01-01T00:00Z plus a fractional second as nanoseconds.
)                                               // Returns a moment in UTC.
.atZone(                                        // Adjust from UTC to another time zone. Same moment, different wall-clock time.
    ZoneId.of( "Asia/Kolkata" )                 // Specify time zone name in `Continent/Region` format, never 2-4 letter pseudo-zone.
)                                               // Returns a `ZonedDateTime` object.
.toString()                                     // Generate a string representing the value of this `ZonedDateTime` in standard ISO 8601 format extended to append the name of the time zone in square brackets.

Wrong class

LocalDateTime dateTimeOfAfterFiveDays = LocalDateTime.ofEpochSecond(after5,0,ZoneOffset.UTC);

LocalDateTime is the wrong class to use here. This class cannot represent a moment. It lacks any concept of time zone or offset-from-UTC. A LocalDateTime holds just a date and a time-of-day, say noon on the 23rd of January this year. But we have no idea if what was intended was noon in Tokyo, noon in Kolkata, noon in Paris, or noon in Montréal — all of these are hours apart, very different moments.

Instant

To represent a moment in UTC, use Instant.

Apparently you have a count of whole seconds since the epoch reference of first moment of 1970 in UTC.

Instant instant = Instant.ofEpochSecond( count ) ;

ZoneId & ZonedDateTime

To see this value through the wall-clock time used by the people of a particular region (a time zone), apply a ZoneId to get a ZonedDateTime.

Specify a proper time zone name in the format of Continent/Region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 2-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

ZoneId z = ZoneId.of( "Asia/Kolkata" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;


问:
Do I need to opt-in to Ivy to use dynamic imports when lazy loading routes (Angular 8)?
I've recently upgraded to Angular 8 and want to make use of the new dynamic imports feature.

I want to convert this:

```<code> { path: 'payments', loadChildren: './components/payments/payments.module#PaymentsModule' }
</code>```

To this:

```<code> { path: 'payments', loadChildren: () => import('./components/payments/payments.module').then(m => m.PaymentsModule)}
</code>```

However my code editor (VSCode) throws a Dynamic import is only supported when '--module' flag is 'commonjs' or 'esNext' error, which I'm unsure how to fix.

On the Angular update guide (https://update.angular.io/), when talking about using the new import syntax, it says:

For lazy loaded modules via the router, importing via string is
  deprecated. ng update will take care of this automatically. The new
  syntax leverages the ecosystem wide support for import rather than our
  custom rewrites.

ng update did not do this automatically and throws the aforementioned error when manually changing the syntax.

I read an article by one of the maintainers of this new feature and he mentions that I will need to opt-in to Ivy.

I'm not sure if this is an Angular 8 bug, or if I will need to opt-in to Ivy (in which case, the docs need to be clearer)

My package.json:

```<code>  "dependencies": {
    "@angular/animations": "^8.0.0",
    "@angular/cdk": "^8.0.0",
    "@angular/common": "^8.0.0",
    "@angular/compiler": "^8.0.0",
    "@angular/core": "^8.0.0",
    "@angular/flex-layout": "^8.0.0-beta.26",
    "@angular/forms": "^8.0.0",
    "@angular/http": "^7.1.1",
    "@angular/material": "^8.0.0",
    "@angular/material-moment-adapter": "^8.0.0",
    "@angular/platform-browser": "^8.0.0",
    "@angular/platform-browser-dynamic": "^8.0.0",
    "@angular/pwa": "^0.800.0",
    "@angular/router": "^8.0.0",
    "@angular/service-worker": "^8.0.0",
    "basic-keyboard-event-polyfill": "^1.0.1",
    "classlist.js": "^1.1.20150312",
    "concurrently": "^4.1.0",
    "core-js": "^3.1.3",
    "hammerjs": "^2.0.8",
    "moment": "^2.22.2",
    "ng-click-outside": "^4.0.0",
    "ng2-pdf-viewer": "^5.2.1",
    "ngx-device-detector": "^1.3.3",
    "ngx-logger": "^3.3.11",
    "phantomjs": "^2.1.7",
    "rxjs": "^6.2.1",
    "web-animations-js": "^2.3.1",
    "zone.js": "^0.9.1"
   },
  "devDependencies": {
    "@angular-devkit/build-angular": "^0.800.0",
    "@angular-devkit/build-ng-packagr": "~0.800.0",
    "@angular-devkit/build-optimizer": "^0.800.0",
    "@angular/cli": "^8.0.0",
    "@angular/compiler-cli": "^8.0.0",
    "@angular/language-service": "^8.0.0",
    "@compodoc/compodoc": "^1.1.3",
    "@types/jasmine": "~3.3.13",
    "@types/jasminewd2": "~2.0.3",
    "@types/karma-viewport": "^0.4.0",
    "@types/node": "12.0.3",
    "codelyzer": "~5.0.1",
    "gulp": "^4.0.2",
    "gulp-sass": "^4.0.1",
    "gzipper": "^2.5.1",
    "http-server": "^0.11.1",
    "jasmine-core": "^3.3.0",
    "jasmine-spec-reporter": "^4.2.1",
    "karma": "^4.1.0",
    "karma-chrome-launcher": "^2.2.0",
    "karma-coverage-istanbul-reporter": "^2.0.4",
    "karma-ie-launcher": "^1.0.0",
    "karma-jasmine": "^2.0.1",
    "karma-jasmine-html-reporter": "^1.4.0",
    "karma-junit-reporter": "^1.2.0",
    "karma-phantomjs-launcher": "^1.0.4",
    "karma-viewport": "^1.0.4",
    "ng-packagr": "^5.2.0",
    "node-sass": "^4.12.0",
    "protractor": "~5.4.2",
    "rimraf": "^2.6.2",
    "ts-node": "~8.2.0",
    "tsickle": "^0.35.0",
    "tslib": "^1.9.3",
    "tslint": "~5.16.0",
    "typescript": "3.4.5",
    "webpack-bundle-analyzer": "^3.3.2"
   }
</code>```

答:
You don't need Ivy to use this new feature. But you have to change your tsconfig.json, and have the following line:

```<code>"module": "commonjs"
</code>```

I had es2015 as the value before. Changing to commonjs solved the problem.

Body:
I've recently upgraded to Angular 8 and want to make use of the new dynamic imports feature.

I want to convert this:

 { path: 'payments', loadChildren: './components/payments/payments.module#PaymentsModule' }

To this:

 { path: 'payments', loadChildren: () => import('./components/payments/payments.module').then(m => m.PaymentsModule)}

However my code editor (VSCode) throws a Dynamic import is only supported when '--module' flag is 'commonjs' or 'esNext' error, which I'm unsure how to fix.

On the Angular update guide (https://update.angular.io/), when talking about using the new import syntax, it says:

For lazy loaded modules via the router, importing via string is
  deprecated. ng update will take care of this automatically. The new
  syntax leverages the ecosystem wide support for import rather than our
  custom rewrites.

ng update did not do this automatically and throws the aforementioned error when manually changing the syntax.

I read an article by one of the maintainers of this new feature and he mentions that I will need to opt-in to Ivy.

I'm not sure if this is an Angular 8 bug, or if I will need to opt-in to Ivy (in which case, the docs need to be clearer)

My package.json:

  "dependencies": {
    "@angular/animations": "^8.0.0",
    "@angular/cdk": "^8.0.0",
    "@angular/common": "^8.0.0",
    "@angular/compiler": "^8.0.0",
    "@angular/core": "^8.0.0",
    "@angular/flex-layout": "^8.0.0-beta.26",
    "@angular/forms": "^8.0.0",
    "@angular/http": "^7.1.1",
    "@angular/material": "^8.0.0",
    "@angular/material-moment-adapter": "^8.0.0",
    "@angular/platform-browser": "^8.0.0",
    "@angular/platform-browser-dynamic": "^8.0.0",
    "@angular/pwa": "^0.800.0",
    "@angular/router": "^8.0.0",
    "@angular/service-worker": "^8.0.0",
    "basic-keyboard-event-polyfill": "^1.0.1",
    "classlist.js": "^1.1.20150312",
    "concurrently": "^4.1.0",
    "core-js": "^3.1.3",
    "hammerjs": "^2.0.8",
    "moment": "^2.22.2",
    "ng-click-outside": "^4.0.0",
    "ng2-pdf-viewer": "^5.2.1",
    "ngx-device-detector": "^1.3.3",
    "ngx-logger": "^3.3.11",
    "phantomjs": "^2.1.7",
    "rxjs": "^6.2.1",
    "web-animations-js": "^2.3.1",
    "zone.js": "^0.9.1"
   },
  "devDependencies": {
    "@angular-devkit/build-angular": "^0.800.0",
    "@angular-devkit/build-ng-packagr": "~0.800.0",
    "@angular-devkit/build-optimizer": "^0.800.0",
    "@angular/cli": "^8.0.0",
    "@angular/compiler-cli": "^8.0.0",
    "@angular/language-service": "^8.0.0",
    "@compodoc/compodoc": "^1.1.3",
    "@types/jasmine": "~3.3.13",
    "@types/jasminewd2": "~2.0.3",
    "@types/karma-viewport": "^0.4.0",
    "@types/node": "12.0.3",
    "codelyzer": "~5.0.1",
    "gulp": "^4.0.2",
    "gulp-sass": "^4.0.1",
    "gzipper": "^2.5.1",
    "http-server": "^0.11.1",
    "jasmine-core": "^3.3.0",
    "jasmine-spec-reporter": "^4.2.1",
    "karma": "^4.1.0",
    "karma-chrome-launcher": "^2.2.0",
    "karma-coverage-istanbul-reporter": "^2.0.4",
    "karma-ie-launcher": "^1.0.0",
    "karma-jasmine": "^2.0.1",
    "karma-jasmine-html-reporter": "^1.4.0",
    "karma-junit-reporter": "^1.2.0",
    "karma-phantomjs-launcher": "^1.0.4",
    "karma-viewport": "^1.0.4",
    "ng-packagr": "^5.2.0",
    "node-sass": "^4.12.0",
    "protractor": "~5.4.2",
    "rimraf": "^2.6.2",
    "ts-node": "~8.2.0",
    "tsickle": "^0.35.0",
    "tslib": "^1.9.3",
    "tslint": "~5.16.0",
    "typescript": "3.4.5",
    "webpack-bundle-analyzer": "^3.3.2"
   }

Body:
You don't need Ivy to use this new feature. But you have to change your tsconfig.json, and have the following line:

"module": "commonjs"

I had es2015 as the value before. Changing to commonjs solved the problem.


问:
C# - Is there no simple way to concatenate hex and ASCII into a single string
In Python I'm able to concatenate both hex and ascii into a single string, then send it to the device I'm trying to control

```<code>   _startTransmit = "\x02"
   _channel = 7
   command_string = _startTransmit + "PGM:" + str(_channel) + ";"
try:
  written = conn.write(command_string.encode('utf-8'))
</code>```

This SO Answer makes it appear building a byte array is the only way to do it in C#

So, it appears there is no similar way to concatenate hex and ascii in C# as there is in Python. Am I correct?

答:
I'd look at using the string interpolator operator $ before the "string":

```<code>var _startTransmit = (char)0x02; //ints can be written in 0xFF format in the source code and cast to char e.g. (char)0x41 is a capital A
var _channel = 7;
var command_string = $"{_startTransmit}PGM:{_channel};"
</code>```

The last line is syntactic sugar for:

```<code>var command_string = string.Format("{0}PGM:{1};", _startTransmit, _channel);
</code>```

The things in {brackets} can have format specifiers, eg pad out the _channel to 4 chars with leading spaces, zeroes etc {_channel:0000} - see https://learn.microsoft.com/en-us/dotnet/api/system.string.format?view=netframework-4.8

Body:
In Python I'm able to concatenate both hex and ascii into a single string, then send it to the device I'm trying to control

   _startTransmit = "\x02"
   _channel = 7
   command_string = _startTransmit + "PGM:" + str(_channel) + ";"
try:
  written = conn.write(command_string.encode('utf-8'))

This SO Answer makes it appear building a byte array is the only way to do it in C#

So, it appears there is no similar way to concatenate hex and ascii in C# as there is in Python. Am I correct?

Body:
I'd look at using the string interpolator operator $ before the "string":

var _startTransmit = (char)0x02; //ints can be written in 0xFF format in the source code and cast to char e.g. (char)0x41 is a capital A
var _channel = 7;
var command_string = $"{_startTransmit}PGM:{_channel};"

The last line is syntactic sugar for:

var command_string = string.Format("{0}PGM:{1};", _startTransmit, _channel);

The things in {brackets} can have format specifiers, eg pad out the _channel to 4 chars with leading spaces, zeroes etc {_channel:0000} - see https://learn.microsoft.com/en-us/dotnet/api/system.string.format?view=netframework-4.8


问:
Javascript Timing : is it possible and how to pass a variable to second argument of setTimeout() & setInterval()?
I'm not able to pass an index from an array to the 2nd argument of a window.setTimout() function (https://www.w3schools.com/js/js_timing.asp)

```<code>function joueursCascade(){

     for (i = 0; i <= my_params.nbJoueurs; i++) {
        var del = tabDel[i]; c

        function getName(){

        message = new Paho.MQTT.Message(document.getElementById('btn3').value);

        message.destinationName = document.getElementById('esp'+i).value+"/ledstate";

        mon_client.send(message);

        }
    window.setTimeout(getName(), del);
    }
}
</code>```

called by something like joueursCascade() this code should send "my_params.nbJoueurs" strings via MQTT at "del" time intervals.

答:
Yes, you just need to make sure that your del variable is numerical.

Try to add parseInt(del)

Otherwise that question was already answered here

Body:
I'm not able to pass an index from an array to the 2nd argument of a window.setTimout() function (https://www.w3schools.com/js/js_timing.asp)

function joueursCascade(){

     for (i = 0; i <= my_params.nbJoueurs; i++) {
        var del = tabDel[i]; c

        function getName(){

        message = new Paho.MQTT.Message(document.getElementById('btn3').value);

        message.destinationName = document.getElementById('esp'+i).value+"/ledstate";

        mon_client.send(message);

        }
    window.setTimeout(getName(), del);
    }
}

called by something like joueursCascade() this code should send "my_params.nbJoueurs" strings via MQTT at "del" time intervals.


问:
onLocationChanged() is called too many times, even when the device hasn't move
I have implemented OnLocationChanged(Location location) as a overrided method in my Activity as shown:

```<code>@Override
public void onLocationChanged(Location location) {

    mCurrentLocation = location;
    if (wifiSpotList != null) {
        presenter.onLocationUpdated(wifiSpotList, mCurrentLocation);
        centerInLoc(location);
    }
}
</code>```

The problem is, this method get triggered even if the device is not moving. It always happens in an interval of milliseconds.

Debugger over location param gets me this logs:

```<code>mTime = 1446035851646
mLongitude = -3.6923793
mLatitude = 40.5008861

mTime = 1446035856976
mLongitude = -3.6923596
mLatitude = 40.5008932

mTime = 1446035867327
mLongitude = -3.6923681
mLatitude = 40.5008987

mTime = 1446035877344
mLongitude = -3.6923778
mLatitude = 40.5008949

mTime = 1446035882442
mLongitude = -3.6923734
mLatitude = 40.5008926

...
</code>```

EDIT:

This is the code where requestLocationUpdates is initialized:

```<code>protected void startLocationUpdates() {
    LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
    this.locationUpdatesStarted = true;
}
</code>```

EDIT
mLocationRequest:

```<code>protected void createLocationRequest() {
    LocationRequest mLocationRequest = new LocationRequest();
    mLocationRequest.setInterval(LOCATION_REQUEST_INTERVAL);
    mLocationRequest.setFastestInterval(LOCATION_REQUEST_FASTEST_INTERVAL);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    this.mLocationRequest = mLocationRequest;
}
</code>```

Is the method triggered because of longitud\latitud change?
Why is it triggering even when the device is not moving?
Can I limit the accuracy?
Is there any clean way to implement onLocationChanged()?

答:
I fixed it by setting

mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);

instead of

mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

Then I set

mLocationRequest.setInterval(UPDATE_INTERVAL); UPDATE_INTERVAL to 10 * 1000 milli seconds.

Also

mLocationRequest.setSmallestDisplacement(200) // 200 meters

Body:
I have implemented OnLocationChanged(Location location) as a overrided method in my Activity as shown:

@Override
public void onLocationChanged(Location location) {

    mCurrentLocation = location;
    if (wifiSpotList != null) {
        presenter.onLocationUpdated(wifiSpotList, mCurrentLocation);
        centerInLoc(location);
    }
}

The problem is, this method get triggered even if the device is not moving. It always happens in an interval of milliseconds.

Debugger over location param gets me this logs:

mTime = 1446035851646
mLongitude = -3.6923793
mLatitude = 40.5008861

mTime = 1446035856976
mLongitude = -3.6923596
mLatitude = 40.5008932

mTime = 1446035867327
mLongitude = -3.6923681
mLatitude = 40.5008987

mTime = 1446035877344
mLongitude = -3.6923778
mLatitude = 40.5008949

mTime = 1446035882442
mLongitude = -3.6923734
mLatitude = 40.5008926

...

EDIT:

This is the code where requestLocationUpdates is initialized:

protected void startLocationUpdates() {
    LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
    this.locationUpdatesStarted = true;
}

EDIT
mLocationRequest:

protected void createLocationRequest() {
    LocationRequest mLocationRequest = new LocationRequest();
    mLocationRequest.setInterval(LOCATION_REQUEST_INTERVAL);
    mLocationRequest.setFastestInterval(LOCATION_REQUEST_FASTEST_INTERVAL);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    this.mLocationRequest = mLocationRequest;
}

Is the method triggered because of longitud\latitud change?
Why is it triggering even when the device is not moving?
Can I limit the accuracy?
Is there any clean way to implement onLocationChanged()?


问:
reCaptcha checkbox spins for 15 seconds, then remains unchecked
I have put reCaptcha on a website. reCaptcha loads without problem but as soon as you click the checkbox, it spins for 15 seconds and remains unchecked. It also does not make any background connection (POST) to google to evaluate the click (should happen).

I have added this to the header of the website and this is the first script that is loaded.

```<code><script src='https://www.google.com/recaptcha/api.js'></script>
</code>```

I also added this field to my login form:

```<code><div class="g-recaptcha" data-sitekey="6LcGv3MUAAAAALdBp38mExUgAAAAAAH_IX522Gr" style="transform:scale(0.75);transform-origin:100% 0;"></div>
</code>```

There is no network activity (in the network tab of developer tools) when I click the checkbox and the only thing I see in the console tab are 2 strange errors from reCaptcha:

I put a bare html form with above modifications on the same domain and server and the reCaptcha works. So I guess this is some kind of conflict with my large existing code (both html and javascript). How can I find or solve the conflict?

答:
I solved this on my site by switching to explicit rendering:

```<code><script src="https://www.google.com/recaptcha/api.js?onload=recaptchaOnLoad&render=explicit" async defer></script>
</code>```

...

```<code><div id="recaptcha"></div>
</code>```

I use recaptchaOnLoad to reset a global recaptcha_rendered variable, because my recaptcha is on the second page of a jQuery Steps wizard, which I think is what was confusing automatic rendering. I probably don't need this function (also referenced in the script tag used to load the recaptcha API above), but it doesn't do any harm:

```<code>function recaptchaOnLoad() {
    recaptcha_rendered = false;
}
</code>```

When the wizard switches to the page containing the recaptcha, I reset or render it with:

```<code>if( recaptcha_rendered ) {
    grecaptcha.reset();
} else {
    grecaptcha.render( 'recaptcha', {
        'sitekey': 'my-site-key',
        'callback': 'recaptchaOnData',
        'expired-callback': 'recaptchaOnExpiry'
    } );
    recaptcha_rendered = true;
}
</code>```

It now works every time.

Body:
I have put reCaptcha on a website. reCaptcha loads without problem but as soon as you click the checkbox, it spins for 15 seconds and remains unchecked. It also does not make any background connection (POST) to google to evaluate the click (should happen).

I have added this to the header of the website and this is the first script that is loaded.

I also added this field to my login form:

There is no network activity (in the network tab of developer tools) when I click the checkbox and the only thing I see in the console tab are 2 strange errors from reCaptcha:

I put a bare html form with above modifications on the same domain and server and the reCaptcha works. So I guess this is some kind of conflict with my large existing code (both html and javascript). How can I find or solve the conflict?

Body:
I solved this on my site by switching to explicit rendering:

<script src="https://www.google.com/recaptcha/api.js?onload=recaptchaOnLoad&render=explicit" async defer></script>

...

<div id="recaptcha"></div>

I use recaptchaOnLoad to reset a global recaptcha_rendered variable, because my recaptcha is on the second page of a jQuery Steps wizard, which I think is what was confusing automatic rendering. I probably don't need this function (also referenced in the script tag used to load the recaptcha API above), but it doesn't do any harm:

function recaptchaOnLoad() {
    recaptcha_rendered = false;
}

When the wizard switches to the page containing the recaptcha, I reset or render it with:

if( recaptcha_rendered ) {
    grecaptcha.reset();
} else {
    grecaptcha.render( 'recaptcha', {
        'sitekey': 'my-site-key',
        'callback': 'recaptchaOnData',
        'expired-callback': 'recaptchaOnExpiry'
    } );
    recaptcha_rendered = true;
}

It now works every time.


问:
MPMoviePlayerController stops iPod playback and doesn't restart
I've got an iPhone app with a short intro video.  If a user launches the app while their iPod is playing music, the music will stop while the video plays (whether or not the video has sound), and the audio stays permanently stopped after video playback.
Apple seems to indicate that you can solve this with AudioSession tricks:
https://web.archive.org/web/20100819124854/http://developer.apple.com:80/iPhone/library/documentation/Audio/Conceptual/AudioSessionProgrammingGuide/WorkingWithOpenALiPodMusicandMovies/WorkingWithOpenALiPodMusicandMovies.html

But their suggestions here just don't seem to work; it seems like MPMoviePlayerController overrides the audio session configuration for its own purposes. Ideally I'd mix the movie audio over the iPod audio or maybe use ducking, but even restarting the music might be a passable fix.

答:
I've found a great solution for that. In the .h file, you must create a BOOL called "wasPlaying". Before playing your video, you ask the iPod if it was playing.

```<code>if ([[MPMusicPlayerController iPodMusicPlayer] playbackState] == MPMusicPlaybackStatePlaying)
{
    NSLog(@"Music was playing, lets put YES to the bool");
    wasPlaying = YES;
}
</code>```

Then, after you tell the movie player to play, you call the following:

```<code>[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(finishedPlaying) name:MPMoviePlayerPlaybackDidFinishNotification object: moviePlayer];
</code>```

And after that, in the method finishedPlaying:

```<code>if (wasPlaying ==YES)
{
    NSLog(@"Music was playing, lets play music again");
    [[MPMusicPlayerController iPodMusicPlayer] play];
}
</code>```

For me it worked fine!

Body:
I've found a great solution for that. In the .h file, you must create a BOOL called "wasPlaying". Before playing your video, you ask the iPod if it was playing.

if ([[MPMusicPlayerController iPodMusicPlayer] playbackState] == MPMusicPlaybackStatePlaying)
{
    NSLog(@"Music was playing, lets put YES to the bool");
    wasPlaying = YES;
}

Then, after you tell the movie player to play, you call the following:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(finishedPlaying) name:MPMoviePlayerPlaybackDidFinishNotification object: moviePlayer];

And after that, in the method finishedPlaying:

if (wasPlaying ==YES)
{
    NSLog(@"Music was playing, lets play music again");
    [[MPMusicPlayerController iPodMusicPlayer] play];
}

For me it worked fine!


问:
How to place a small square box across every td element having text in css?
I am working on a table in html in which I want to place a square box across every td element in css

```<code><tr>
    <td style="width:8%; text-align:center; border: 1px solid #000; margin-left: 30px;"><?php echo $program["series_title"]; ?></td>
    <td style="width:8%; text-align:center; border: 1px solid #000; margin-left: 30px;"><?php echo $program["episode_title"]; ?></td>
    <td style="width:8%; text-align:center; border: 1px solid #000; margin-left: 30px;"><?php echo $program["description"]; ?></td>
    <td style="width:8%; text-align:center; border: 1px solid #000; margin-left: 30px;"><?php echo $program["series_title_fr"]; ?></td>
    <td style="width:8%; text-align:center; border: 1px solid #000; margin-left: 30px;"><?php echo $program["episode_title_fr"]; ?></td>
    <td style="width:8%; text-align:center; border: 1px solid #000; margin-left: 30px;"><?php echo $program["description_fr"]; ?></td>
    <td style="width:8%; text-align:center; border: 1px solid #000; margin-left: 30px;"> <?php echo basename($file, ".mp4"); ?></td>
</tr>
</code>```

The above html/php code display the table/td element in the following fashion:

Problem Statement:

I am wondering what changes I should make in the inline css code above so that I am able to make a small square box (as shown below) across every td element having text in css. At this moment, as shown above in an image it is
making a big square box

答:
You can use another element, such as a span, to wrap the text that is inside each td. Then you can style that element with a border. For example:

```<code><td><span style="border: 1px solid black; padding: 5px;">Test</span></td>
</code>```

Check this fiddle. Table 1  shows both the borders of td and span, while Table 2 only shows the border of span.

Body:
I am working on a table in html in which I want to place a square box across every td element in css

    <?php echo $program["series_title"]; ?>
    <?php echo $program["episode_title"]; ?>
    <?php echo $program["description"]; ?>
    <?php echo $program["series_title_fr"]; ?>
    <?php echo $program["episode_title_fr"]; ?>
    <?php echo $program["description_fr"]; ?>
     <?php echo basename($file, ".mp4"); ?>

The above html/php code display the table/td element in the following fashion:

Problem Statement:

I am wondering what changes I should make in the inline css code above so that I am able to make a small square box (as shown below) across every td element having text in css. At this moment, as shown above in an image it is
making a big square box

Body:
You can use another element, such as a span, to wrap the text that is inside each td. Then you can style that element with a border. For example:

<td><span style="border: 1px solid black; padding: 5px;">Test</span></td>

Check this fiddle. Table 1  shows both the borders of td and span, while Table 2 only shows the border of span.


问:
Typescript error messages for javascript file
I only have a minified version of the javascript code below. It works as is but I needed to integrate this code inside of a typescript file. It still works pretty well at runtime but in my editor (Visual Studio Code) I got errors.

Below is the code.

```<code>!function(e){"use strict";function i(i,a){var s=i.outerWidth(!0),o={};if(!i.is(":visible")&&!n){switch(n=!0,i.addClass("ps-active-panel").css({position:"fixed",top:0,height:"100%","z-index":9999999999}),i.data(a),e("html").addClass("overflow-hidden"),e("body").addClass("overflow-hidden"),e("#eskimo-overlay").bind("touchmove",!1),e("#eskimo-overlay").fadeIn(200),a.side){case"left":i.css({left:"-"+s+"px",right:"auto"}),o.left="+="+s;break;case"right":i.css({left:"auto",right:"-"+s+"px"}),o.right="+="+s}t.animate({},a.duration),i.show().animate(o,a.duration,function(){n=!1,"function"==typeof a.onOpen&&a.onOpen()})}}var t=e("body"),n=!1;e.panelslider=function(t,n){var a=e(".ps-active-panel");n=e.extend({},{side:"left",duration:200,clickClose:!0,onOpen:null},n),a.is(":visible")&&a[0]!=t[0]?e.panelslider.close(function(){i(t,n)}):a.length&&!a.is(":hidden")||i(t,n)},e.panelslider.close=function(i){var a=e(".ps-active-panel"),s=a.data("duration"),o=a.outerWidth(!0),l={};if(a.length&&!a.is(":hidden")&&!n){switch(n=!0,a.data("side")){case"left":l.left="-="+o;break;case"right":l.right="-="+o}a.animate(l,s),t.animate({},s,function(){a.fadeOut(200),a.removeClass("ps-active-panel"),e("html").removeClass("overflow-hidden"),e("body").removeClass("overflow-hidden"),e("#eskimo-overlay").fadeOut(200),n=!1,i&&i()})}},e(document).bind("click keyup",function(i){var t=e(".ps-active-panel");"keyup"==i.type&&27!=i.keyCode||t.is(":visible")&&t.data("clickClose")&&e.panelslider.close()}),e(document).on("click",".ps-active-panel",function(e){e.stopPropagation()}),e.fn.panelslider=function(i){return this.on("click",function(t){var n=e(".ps-active-panel"),a=e(this.getAttribute("href"));n.is(":visible")&&a[0]==n[0]?e.panelslider.close():e.panelslider(a,i),t.preventDefault(),t.stopPropagation()}),this}}(jQuery);
jQuery(document).ready(function(){jQuery("body").find(".eskimo-panel-open").panelslider({side:"right",clickClose:!0,duration:400}),jQuery("body").find(".eskimo-panel-close").on("click",function(){return jQuery.panelslider.close(),!1})});
</code>```

What can be done on this code to avoid TypeScript errors in my editor ?

EDIT

For this moment, I copy/paste minified javascript code inside another TypeScript file (wrap it in panel function) and it works at runtime but got errors in my editor.

答:
You can use //@ts-ignore directive in order to avoid typings or you can create our declaration file (d.ts) for panelslider plugin.

First let's move all plugin related code into a separate file, name it panelslider.plugin.ts. so content should be like this, here I have imported jQuery and added @ts-ignore directives to get rid of all errors.

```<code>import jQuery from "jquery";

// @ts-ignore

    !function(e){"use strict";function i(i,a){var s=i.outerWidth(!0),o={};if(!i.is(":visible")&&!n){switch(n=!0,i.addClass("ps-active-panel").css({position:"fixed",top:0,height:"100%","z-index":9999999999}),i.data(a),e("html").addClass("overflow-hidden"),e("body").addClass("overflow-hidden"),e("#eskimo-overlay").bind("touchmove",!1),e("#eskimo-overlay").fadeIn(200),a.side){case"left":i.css({left:"-"+s+"px",right:"auto"}),o.left="+="+s;break;case"right":i.css({left:"auto",right:"-"+s+"px"}),o.right="+="+s}t.animate({},a.duration),i.show().animate(o,a.duration,function(){n=!1,"function"==typeof a.onOpen&&a.onOpen()})}}var t=e("body"),n=!1;e.panelslider=function(t,n){var a=e(".ps-active-panel");n=e.extend({},{side:"left",duration:200,clickClose:!0,onOpen:null},n),a.is(":visible")&&a[0]!=t[0]?e.panelslider.close(function(){i(t,n)}):a.length&&!a.is(":hidden")||i(t,n)},e.panelslider.close=function(i){var a=e(".ps-active-panel"),s=a.data("duration"),o=a.outerWidth(!0),l={};if(a.length&&!a.is(":hidden")&&!n){switch(n=!0,a.data("side")){case"left":l.left="-="+o;break;case"right":l.right="-="+o}a.animate(l,s),t.animate({},s,function(){a.fadeOut(200),a.removeClass("ps-active-panel"),e("html").removeClass("overflow-hidden"),e("body").removeClass("overflow-hidden"),e("#eskimo-overlay").fadeOut(200),n=!1,i&&i()})}},e(document).bind("click keyup",function(i){var t=e(".ps-active-panel");"keyup"==i.type&&27!=i.keyCode||t.is(":visible")&&t.data("clickClose")&&e.panelslider.close()}),e(document).on("click",".ps-active-panel",function(e){e.stopPropagation()}),e.fn.panelslider=function(i){return this.on("click",function(t){var n=e(".ps-active-panel"),a=e(this.getAttribute("href"));n.is(":visible")&&a[0]==n[0]?e.panelslider.close():e.panelslider(a,i),t.preventDefault(),t.stopPropagation()}),this}}(jQuery);
    jQuery(document).ready(function(){jQuery("body").find(".eskimo-panel-open").panelslider({side:"right",clickClose:!0,duration:400}),jQuery("body").find(".eskimo-panel-close").on("click",function(){return jQuery.panelslider.close(),!1})});
</code>```

Code

```<code>import jQuery from "jquery";

// @ts-ignore
import "./panelslider.plugin";

jQuery(document).ready(function() {
    jQuery("body")
        .find(".eskimo-panel-open")
        .panelslider({ side: "right", clickClose: !0, duration: 400 });

        jQuery("body")
            .find(".eskimo-panel-close")
            .on("click", function() {
                return jQuery.panelslider.close(), !1;
            });
});
</code>```

Type declaration for panelslider plugin. Just add following code into  type declaration file(global.d.ts make sure ts complier honoring)

```<code>export type PanelSlider = {
    side: "right";
    clickClose: boolean;
    duration: number;
};

interface JQuery {
    panelslider(options: PanelSlider): void;
}

interface JQueryStatic {
    panelslider: {
        close(): any;
    };
}
</code>```

Body:
I only have a minified version of the javascript code below. It works as is but I needed to integrate this code inside of a typescript file. It still works pretty well at runtime but in my editor (Visual Studio Code) I got errors.

Below is the code.

!function(e){"use strict";function i(i,a){var s=i.outerWidth(!0),o={};if(!i.is(":visible")&&!n){switch(n=!0,i.addClass("ps-active-panel").css({position:"fixed",top:0,height:"100%","z-index":9999999999}),i.data(a),e("html").addClass("overflow-hidden"),e("body").addClass("overflow-hidden"),e("#eskimo-overlay").bind("touchmove",!1),e("#eskimo-overlay").fadeIn(200),a.side){case"left":i.css({left:"-"+s+"px",right:"auto"}),o.left="+="+s;break;case"right":i.css({left:"auto",right:"-"+s+"px"}),o.right="+="+s}t.animate({},a.duration),i.show().animate(o,a.duration,function(){n=!1,"function"==typeof a.onOpen&&a.onOpen()})}}var t=e("body"),n=!1;e.panelslider=function(t,n){var a=e(".ps-active-panel");n=e.extend({},{side:"left",duration:200,clickClose:!0,onOpen:null},n),a.is(":visible")&&a[0]!=t[0]?e.panelslider.close(function(){i(t,n)}):a.length&&!a.is(":hidden")||i(t,n)},e.panelslider.close=function(i){var a=e(".ps-active-panel"),s=a.data("duration"),o=a.outerWidth(!0),l={};if(a.length&&!a.is(":hidden")&&!n){switch(n=!0,a.data("side")){case"left":l.left="-="+o;break;case"right":l.right="-="+o}a.animate(l,s),t.animate({},s,function(){a.fadeOut(200),a.removeClass("ps-active-panel"),e("html").removeClass("overflow-hidden"),e("body").removeClass("overflow-hidden"),e("#eskimo-overlay").fadeOut(200),n=!1,i&&i()})}},e(document).bind("click keyup",function(i){var t=e(".ps-active-panel");"keyup"==i.type&&27!=i.keyCode||t.is(":visible")&&t.data("clickClose")&&e.panelslider.close()}),e(document).on("click",".ps-active-panel",function(e){e.stopPropagation()}),e.fn.panelslider=function(i){return this.on("click",function(t){var n=e(".ps-active-panel"),a=e(this.getAttribute("href"));n.is(":visible")&&a[0]==n[0]?e.panelslider.close():e.panelslider(a,i),t.preventDefault(),t.stopPropagation()}),this}}(jQuery);
jQuery(document).ready(function(){jQuery("body").find(".eskimo-panel-open").panelslider({side:"right",clickClose:!0,duration:400}),jQuery("body").find(".eskimo-panel-close").on("click",function(){return jQuery.panelslider.close(),!1})});

What can be done on this code to avoid TypeScript errors in my editor ?

EDIT

For this moment, I copy/paste minified javascript code inside another TypeScript file (wrap it in panel function) and it works at runtime but got errors in my editor.

Body:
You can use //@ts-ignore directive in order to avoid typings or you can create our declaration file (d.ts) for panelslider plugin.

First let's move all plugin related code into a separate file, name it panelslider.plugin.ts. so content should be like this, here I have imported jQuery and added @ts-ignore directives to get rid of all errors.

import jQuery from "jquery";

// @ts-ignore

    !function(e){"use strict";function i(i,a){var s=i.outerWidth(!0),o={};if(!i.is(":visible")&&!n){switch(n=!0,i.addClass("ps-active-panel").css({position:"fixed",top:0,height:"100%","z-index":9999999999}),i.data(a),e("html").addClass("overflow-hidden"),e("body").addClass("overflow-hidden"),e("#eskimo-overlay").bind("touchmove",!1),e("#eskimo-overlay").fadeIn(200),a.side){case"left":i.css({left:"-"+s+"px",right:"auto"}),o.left="+="+s;break;case"right":i.css({left:"auto",right:"-"+s+"px"}),o.right="+="+s}t.animate({},a.duration),i.show().animate(o,a.duration,function(){n=!1,"function"==typeof a.onOpen&&a.onOpen()})}}var t=e("body"),n=!1;e.panelslider=function(t,n){var a=e(".ps-active-panel");n=e.extend({},{side:"left",duration:200,clickClose:!0,onOpen:null},n),a.is(":visible")&&a[0]!=t[0]?e.panelslider.close(function(){i(t,n)}):a.length&&!a.is(":hidden")||i(t,n)},e.panelslider.close=function(i){var a=e(".ps-active-panel"),s=a.data("duration"),o=a.outerWidth(!0),l={};if(a.length&&!a.is(":hidden")&&!n){switch(n=!0,a.data("side")){case"left":l.left="-="+o;break;case"right":l.right="-="+o}a.animate(l,s),t.animate({},s,function(){a.fadeOut(200),a.removeClass("ps-active-panel"),e("html").removeClass("overflow-hidden"),e("body").removeClass("overflow-hidden"),e("#eskimo-overlay").fadeOut(200),n=!1,i&&i()})}},e(document).bind("click keyup",function(i){var t=e(".ps-active-panel");"keyup"==i.type&&27!=i.keyCode||t.is(":visible")&&t.data("clickClose")&&e.panelslider.close()}),e(document).on("click",".ps-active-panel",function(e){e.stopPropagation()}),e.fn.panelslider=function(i){return this.on("click",function(t){var n=e(".ps-active-panel"),a=e(this.getAttribute("href"));n.is(":visible")&&a[0]==n[0]?e.panelslider.close():e.panelslider(a,i),t.preventDefault(),t.stopPropagation()}),this}}(jQuery);
    jQuery(document).ready(function(){jQuery("body").find(".eskimo-panel-open").panelslider({side:"right",clickClose:!0,duration:400}),jQuery("body").find(".eskimo-panel-close").on("click",function(){return jQuery.panelslider.close(),!1})});

Code

import jQuery from "jquery";

// @ts-ignore
import "./panelslider.plugin";

jQuery(document).ready(function() {
    jQuery("body")
        .find(".eskimo-panel-open")
        .panelslider({ side: "right", clickClose: !0, duration: 400 });

        jQuery("body")
            .find(".eskimo-panel-close")
            .on("click", function() {
                return jQuery.panelslider.close(), !1;
            });
});

Type declaration for panelslider plugin. Just add following code into  type declaration file(global.d.ts make sure ts complier honoring)

export type PanelSlider = {
    side: "right";
    clickClose: boolean;
    duration: number;
};

interface JQuery {
    panelslider(options: PanelSlider): void;
}

interface JQueryStatic {
    panelslider: {
        close(): any;
    };
}


问:
Testing if a java program calls System.exist - without exiting Junit
I am trying to test a file processing program with Junit. In some cases, the program should print an error and finish its run. However, using "System.exit(-1)" causes the program to exit the entire Junit tests.
Is there some way of avoiding it?

I can instead print the error and then return null, however I find it quite inelegant.

    private List<String> parseData(String[] args){
        if (args.length != 2){
            System.err.println(ERROR + INPUT_ERROR + "\n");
            System.exit(EXIT_CODE);
```

Is there a way to check if the program called "System.exit" without closing it?
Thank you.

答:
I think it's more inelegant to use System.exit to validate input parameters.
Why not just throw an exception and let the caller of this method handle it ?</p>

Body:
I am trying to test a file processing program with Junit. In some cases, the program should print an error and finish its run. However, using "System.exit(-1)" causes the program to exit the entire Junit tests.
Is there some way of avoiding it?

I can instead print the error and then return null, however I find it quite inelegant.

    private List<String> parseData(String[] args){
        if (args.length != 2){
            System.err.println(ERROR + INPUT_ERROR + "\n");
            System.exit(EXIT_CODE);

Is there a way to check if the program called "System.exit" without closing it?
Thank you.


问:
Sending Data to a Feed of io.Adafruit through URL
I am stuck in a huge problem and i have very less time to complete my Final Year Project.
My Question is : I want to send some data or value to a feed of io.adafruit through URL, mean when i enter a URL in the Browser, it just send a value to the feed.
For Example: https://io.adafruit.com/SOME_Value      PLEASE HELP ME

答:
Adafruit IO's API documentation makes it quite clear how to add data using HTTP.

You cannot do it by entering a URL in a web browser. The IO API requires a custom header field, X-AIO-Key, which contains the Adafruit IO API key. There's no way to add this header field when you enter a URL from a browser.

You can, however, use a command-line utility, like curl. The API documentation is really clear about this and shows examples, like so:

```<code>curl -F 'value=42' -H "X-AIO-Key: {io_key}" https://io.adafruit.com/api/v2/{username}/feeds/{feed_key}/data
</code>```

Here you'd replace io_key with the API key, username with the Adafruit IO username on the account and feed_key with the variable you're trying to set, and 42 with the value you're setting it to.

Body:
Adafruit IO's API documentation makes it quite clear how to add data using HTTP.

You cannot do it by entering a URL in a web browser. The IO API requires a custom header field, X-AIO-Key, which contains the Adafruit IO API key. There's no way to add this header field when you enter a URL from a browser.

You can, however, use a command-line utility, like curl. The API documentation is really clear about this and shows examples, like so:

curl -F 'value=42' -H "X-AIO-Key: {io_key}" https://io.adafruit.com/api/v2/{username}/feeds/{feed_key}/data

Here you'd replace io_key with the API key, username with the Adafruit IO username on the account and feed_key with the variable you're trying to set, and 42 with the value you're setting it to.


问:
WCF methods are getting called twice when their HTTP verb is PUT or DELETE
I have a WCF service with multiple endpoints which I call from AJAX/JS. Everything is working fine, except if I go to my log table.
I store every call to this wcf service in a table and I've noticed that, if the verb used to call the methods is PUT or DELETE, the method is called twice. Of course, it has no impact on data since PUT and DELETE are supposed to be idempotent (and I made the corresponding stored procedures to act as such).

Digging this problem, I have changed PUT to POST in one method and it was then only called once. Changed it back to PUT, and it was called twice again. So it can't be related to the DataContracts, as I have read in another post. I have used SVCTraceViewer and nothing unexpected appeared, except for the double calls of course.
I must also add that
1) WebDav Publishing is NOT installed
2) I've checked in IIS and svc handlers have all verbs authorized
Still, I'm more and more convinced it's a IIS issue, but I don't know where to look.
Any advice would be welcome.
Thanks for the time you've spent reading this post... and thinking of an solution to my problem.

答:
OK, found it. Thought I would post the answer : I was using Response status code 204 for put and delete successful requests. However it seems that code 204 asks the page to remain and actually request the same url a second time. Changed it to 202 : problem solved.
Best regards to stack o.</p>


问:
How to compare two arrays by multiple columns (row with row)
I have two tables in one spreadsheet. both have the same columns - Name, City, Province. My goal is to compare both and if three out of three values in a row match, then pull "Yes", if not, pull "No". I compare rows with rows in these two tables (not random cells).

I have not found a proper formula, so probably need to code it.

I have found a good code, but it works only for looking at the same values in one array. I hope it could be adapted to my problem. Or maybe I need another one.

```<code>Sub Compare()
    Dim row As Integer
    row = 2
    Dim firstColumn As String
    firstColumn = "H"
    Dim lastColumn As String
    lastColumn = "J"
    Dim resultsColumn As String
    resultsColumn = "M"
    Dim isFoundText As String
    isFoundText = "YES"
    Dim isNotFoundText As String
    isNotFoundText = "NO"

    Do While Range("B" & row).Value <> ""

        Dim startChar As Integer
        startChar = Asc(firstColumn)
        Dim endChar As Integer
        endChar = Asc(lastColumn)
        Dim i As Integer
        Dim hasMatch As Boolean
        hasMatch = False

        For i = startChar To endChar
            If Range(Chr(i) & row).Value = Range(Chr(i + 1) & row).Value Then
                hasMatch = True
            End If
            If Range(Chr(startChar) & row).Value = Range(Chr(i + 1) & row).Value Then
                hasMatch = True
            End If
        Next i

        If (hasMatch) Then
            Range(resultsColumn & row).Value = isFoundText
        Else
            Range(resultsColumn & row).Value = isNotFoundText
        End If
        row = row + 1
    Loop

End Sub
</code>```

答:
Adding some indents so we can read this:

```<code>Sub Compare()
    Dim firstColumn As String, lastColumn As String, resultsColumn As String, isFoundText As String, isNotFoundText As String,
    Dim row As Integer, startChar As Integer, endChar As Integer, i As Integer
    Dim hasMatch As Boolean
    row = 2
    firstColumn = "H"
    lastColumn = "J"
    resultsColumn = "M"
    isFoundText = "YES"
    isNotFoundText = "NO"
    Do While Range("B" & row).Value <> ""
        startChar = Asc(firstColumn)
        endChar = Asc(lastColumn)
        hasMatch = False
        For i = startChar To endChar
            If Range(Chr(i) & row).Value = Range(Chr(i + 1) & row).Value Then
                hasMatch = True
            End If
            If Range(Chr(startChar) & row).Value = Range(Chr(i + 1) & row).Value Then
                hasMatch = True
            End If
        Next i
        If (hasMatch) Then
            Range(resultsColumn & row).Value = isFoundText
        Else
            Range(resultsColumn & row).Value = isNotFoundText
        End If
        row = row + 1
    Loop
End Sub
</code>```

Now, to start making changes... Looks like you can clean up your code with a simpler loop, such that (untested):

```<code>Dim lri as long, lrj as long, i as long, j as long
lri = cells(rows.count,"H").end(xlup).row
lrj = range(columns("B"),columns("D")).Find("*", , , , xlByRows, xlPrevious).Row
For i = 2 to lri
    For j = 2 to lrj
        If Cells(j,"B").Value = cells(i,"J").Value AND Cells(j,"C").Value = Cells(i,"I").Value AND Cells(j,"D").Value = Cells(i,"H").Value Then
        Cells(i,"M").Value = "Yes" 'don't need variables for these anymore
        'may want to put an exit to j loop if True
    Else
        Cells(i,"M").Value = "No"
    End If
    row = row + 1
Loop
</code>```

This compares the values in each of the cells with their respective section (B to J, C to I, and D to H).

Body:
I have two tables in one spreadsheet. both have the same columns - Name, City, Province. My goal is to compare both and if three out of three values in a row match, then pull "Yes", if not, pull "No". I compare rows with rows in these two tables (not random cells).

I have not found a proper formula, so probably need to code it.

I have found a good code, but it works only for looking at the same values in one array. I hope it could be adapted to my problem. Or maybe I need another one.

Sub Compare()
    Dim row As Integer
    row = 2
    Dim firstColumn As String
    firstColumn = "H"
    Dim lastColumn As String
    lastColumn = "J"
    Dim resultsColumn As String
    resultsColumn = "M"
    Dim isFoundText As String
    isFoundText = "YES"
    Dim isNotFoundText As String
    isNotFoundText = "NO"

    Do While Range("B" & row).Value <> ""

        Dim startChar As Integer
        startChar = Asc(firstColumn)
        Dim endChar As Integer
        endChar = Asc(lastColumn)
        Dim i As Integer
        Dim hasMatch As Boolean
        hasMatch = False

        For i = startChar To endChar
            If Range(Chr(i) & row).Value = Range(Chr(i + 1) & row).Value Then
                hasMatch = True
            End If
            If Range(Chr(startChar) & row).Value = Range(Chr(i + 1) & row).Value Then
                hasMatch = True
            End If
        Next i

        If (hasMatch) Then
            Range(resultsColumn & row).Value = isFoundText
        Else
            Range(resultsColumn & row).Value = isNotFoundText
        End If
        row = row + 1
    Loop

End Sub

Body:
Adding some indents so we can read this:

Sub Compare()
    Dim firstColumn As String, lastColumn As String, resultsColumn As String, isFoundText As String, isNotFoundText As String,
    Dim row As Integer, startChar As Integer, endChar As Integer, i As Integer
    Dim hasMatch As Boolean
    row = 2
    firstColumn = "H"
    lastColumn = "J"
    resultsColumn = "M"
    isFoundText = "YES"
    isNotFoundText = "NO"
    Do While Range("B" & row).Value <> ""
        startChar = Asc(firstColumn)
        endChar = Asc(lastColumn)
        hasMatch = False
        For i = startChar To endChar
            If Range(Chr(i) & row).Value = Range(Chr(i + 1) & row).Value Then
                hasMatch = True
            End If
            If Range(Chr(startChar) & row).Value = Range(Chr(i + 1) & row).Value Then
                hasMatch = True
            End If
        Next i
        If (hasMatch) Then
            Range(resultsColumn & row).Value = isFoundText
        Else
            Range(resultsColumn & row).Value = isNotFoundText
        End If
        row = row + 1
    Loop
End Sub

Now, to start making changes... Looks like you can clean up your code with a simpler loop, such that (untested):

Dim lri as long, lrj as long, i as long, j as long
lri = cells(rows.count,"H").end(xlup).row
lrj = range(columns("B"),columns("D")).Find("*", , , , xlByRows, xlPrevious).Row
For i = 2 to lri
    For j = 2 to lrj
        If Cells(j,"B").Value = cells(i,"J").Value AND Cells(j,"C").Value = Cells(i,"I").Value AND Cells(j,"D").Value = Cells(i,"H").Value Then
        Cells(i,"M").Value = "Yes" 'don't need variables for these anymore
        'may want to put an exit to j loop if True
    Else
        Cells(i,"M").Value = "No"
    End If
    row = row + 1
Loop

This compares the values in each of the cells with their respective section (B to J, C to I, and D to H).


问:
How can I add a watermark to a PDF that is generated by puppeteer?
I'm using puppeteer to generate a PDF file for my report view and I want to add a watermark on that report PDF version. Is there anyway that I can do that?</p>

答:
The easiest way to do it, is to add an additional element to the page, which represents the watermark when the PDF is created. As you can change the page in any way you like, you could add a "Watermark" element to the page like this:

await page.evaluate(() => {
  const div = document.createElement('div');
  div.innerHTML = 'Watermark Text...';
  div.style.cssText = "position: fixed; bottom: 10px; right: 10px; background: red; z-index: 10000";
  document.body.appendChild(div);
});
await page.pdf(/* ... */);
```

The code adds a fixed element to the bottom right of the page. When printed it will appear on every printed page. You can use any kind of CSS styling to style your watermark. Just make sure it has a high z-index value, so that nothing overlaps it.

Body:
The easiest way to do it, is to add an additional element to the page, which represents the watermark when the PDF is created. As you can change the page in any way you like, you could add a "Watermark" element to the page like this:

await page.evaluate(() => {
  const div = document.createElement('div');
  div.innerHTML = 'Watermark Text...';
  div.style.cssText = "position: fixed; bottom: 10px; right: 10px; background: red; z-index: 10000";
  document.body.appendChild(div);
});
await page.pdf(/* ... */);

The code adds a fixed element to the bottom right of the page. When printed it will appear on every printed page. You can use any kind of CSS styling to style your watermark. Just make sure it has a high z-index value, so that nothing overlaps it.


问:
How can I check whether a method is defined in a JavaScript class
I need to check whether a class definition provides either via inheritance or not, a specific method. Do I need to travel the prototype chain to accomplish this?</p>

```<code>function TestClass(config){
    //NOTE: cannot instantiate class because if config not valid Error is thrown
}
TestClass.prototype.sampleMethod = function(){};

function isDefined(klass){
      console.log(typeof klass.sampleMethod); //'undefined'
      console.log('sampleMethod' in klass); //false
      console.log(klass['sampleMethod']); //undefined

      console.log(typeof klass.prototype.sampleMethod); //'function' ...inheritance?
}

isDefined(TestClass);
</code>```

答:
Yes, you need to check the prototype chain.

```<code>function TestClass(config){}
TestClass.prototype.sampleMethod = function(){};

function TestClass2() {}
TestClass2.prototype = TestClass;

function isDefined(obj, method) {
    if (obj.prototype !== undefined) {
        var methodInPrototype = (method in obj.prototype);
        console.log("Is " + method + " in prototype of " + obj + ": " + methodInPrototype);
        if (methodInPrototype) {
                return true;
        } else {
            isDefined(obj.prototype, method);
        }
    }
    return false;
}

isDefined(TestClass, "sampleMethod");
isDefined(TestClass2, "sampleMethod");
isDefined(TestClass2, "sampleMethod2");
</code>```

Prints:

```<code>// Is sampleMethod in prototype of function TestClass(config) {}: true
// Is sampleMethod in prototype of function TestClass2() {}: false
// Is sampleMethod in prototype of function TestClass(config) {}: true
// Is sampleMethod2 in prototype of function TestClass2() {}: false
// Is sampleMethod2 in prototype of function TestClass(config) {}: false
</code>```

Body:
I need to check whether a class definition provides either via inheritance or not, a specific method. Do I need to travel the prototype chain to accomplish this?

function TestClass(config){
    //NOTE: cannot instantiate class because if config not valid Error is thrown
}
TestClass.prototype.sampleMethod = function(){};

function isDefined(klass){
      console.log(typeof klass.sampleMethod); //'undefined'
      console.log('sampleMethod' in klass); //false
      console.log(klass['sampleMethod']); //undefined

      console.log(typeof klass.prototype.sampleMethod); //'function' ...inheritance?
}

isDefined(TestClass);

Body:
Yes, you need to check the prototype chain.

function TestClass(config){}
TestClass.prototype.sampleMethod = function(){};

function TestClass2() {}
TestClass2.prototype = TestClass;

function isDefined(obj, method) {
    if (obj.prototype !== undefined) {
        var methodInPrototype = (method in obj.prototype);
        console.log("Is " + method + " in prototype of " + obj + ": " + methodInPrototype);
        if (methodInPrototype) {
                return true;
        } else {
            isDefined(obj.prototype, method);
        }
    }
    return false;
}

isDefined(TestClass, "sampleMethod");
isDefined(TestClass2, "sampleMethod");
isDefined(TestClass2, "sampleMethod2");

Prints:

// Is sampleMethod in prototype of function TestClass(config) {}: true
// Is sampleMethod in prototype of function TestClass2() {}: false
// Is sampleMethod in prototype of function TestClass(config) {}: true
// Is sampleMethod2 in prototype of function TestClass2() {}: false
// Is sampleMethod2 in prototype of function TestClass(config) {}: false


问:
Compare two columns of one file to two columns in another file
I have two files as shown below.

First file:

```<code>Start State,Next State,Session Count,Transition%
/ccstoreui/v1/pages/layout/home,/ccstoreui/v1/pages/layout/home,1126,28.600%
/ccstoreui/v1/pages/layout/home,/ccstoreui/v1/pages/layout/LA_product_view,818,20.780%
/ccstoreui/v1/pages/layout/home,/ccstoreui/v1/orders/price,21,0.530%
/ccstoreui/v1/pages/layout/home,/ccstoreui/v1/login/,997,25.330%
/ccstoreui/v1/pages/layout/home,/ccstoreui/v1/organizations,31,0.780%
/ccstoreui/v1/pages/layout/home,/ccstoreui/v1/pages/layout/partsVisualizer,167,4.240%
</code>```

Second file:

```<code>/ccstoreui/v1/pages/layout/home,/ccstoreui/v1/pages/layout/LA_product_view,894,13.100%
/ccstoreui/v1/pages/layout/home,/ccstoreui/v1/pages/layout/home,1184,17.350%
/ccstoreui/v1/pages/layout/home,/ccstoreui/v1/orders/price,25,0.360%
/ccstoreui/v1/pages/layout/home,/ccstoreui/v1/pages/layout/searchresults,226,3.310%
/ccstoreui/v1/pages/layout/home,/ccstoreui/v1/inventories/LA_entry,3,0.040%
/ccstoreui/v1/pages/layout/home,/ccstoreui/v1/pages/layout/cart,51,0.740%
</code>```

I need to compare the first two columns of the first file and the first two columns of the second file and if they both match it should print 3,4 columns of both file. If both the files has unique they should be listed with NA from the both files.

My output should be like:

```<code>/ccstoreui/v1/pages/layout/home,/ccstoreui/v1/pages/layout/LA_product_view,818,20.780%,894,13.100%
/ccstoreui/v1/pages/layout/home,/ccstoreui/v1/pages/layout/home,1126,28.600%,1184,17.350%
/ccstoreui/v1/pages/layout/home,/ccstoreui/v1/orders/price,21,0.530%,25,0.360%
/ccstoreui/v1/pages/layout/home,/ccstoreui/v1/pages/layout/searchresults,NA,NA,226,3.310%
/ccstoreui/v1/pages/layout/home,/ccstoreui/v1/inventories/LA_entry,NA,NA,3,0.040%
/ccstoreui/v1/pages/layout/home,/ccstoreui/v1/pages/layout/cart,NA,NA,51,0.740%
/ccstoreui/v1/pages/layout/home,/ccstoreui/v1/organizations,31,0.780%,NA,NA
/ccstoreui/v1/pages/layout/home,/ccstoreui/v1/pages/layout/partsVisualizer,167,4.240%,NA,NA
/ccstoreui/v1/pages/layout/home,/ccstoreui/v1/login/,997,25.330%,NA,NA
</code>```

Can someone please help me with this?

答:
awk -f rag.awk file1 file2 where rag.awk is:

```<code>    BEGIN {
FS=OFS=","
}
{idx=$1 OFS $2; _34=$3 OFS $4}
FNR==NR {if (FNR>1) f1[idx]=_34; next}
idx in f1 { print idx, f1[idx], _34; delete f1[idx];next}
{print idx, "NA","NA", _34}
END {
  for (i in f1)
     print i, f1[i], "NA", "NA"
}
</code>```

output:

```<code>/ccstoreui/v1/pages/layout/home,/ccstoreui/v1/pages/layout/LA_product_view,818,20.780%,894,13.100%
/ccstoreui/v1/pages/layout/home,/ccstoreui/v1/pages/layout/home,1126,28.600%,1184,17.350%
/ccstoreui/v1/pages/layout/home,/ccstoreui/v1/orders/price,21,0.530%,25,0.360%
/ccstoreui/v1/pages/layout/home,/ccstoreui/v1/pages/layout/searchresults,NA,NA,226,3.310%
/ccstoreui/v1/pages/layout/home,/ccstoreui/v1/inventories/LA_entry,NA,NA,3,0.040%
/ccstoreui/v1/pages/layout/home,/ccstoreui/v1/pages/layout/cart,NA,NA,51,0.740%
/ccstoreui/v1/pages/layout/home,/ccstoreui/v1/organizations,31,0.780%,NA,NA
/ccstoreui/v1/pages/layout/home,/ccstoreui/v1/pages/layout/partsVisualizer,167,4.240%,NA,NA
/ccstoreui/v1/pages/layout/home,/ccstoreui/v1/login/,997,25.330%,NA,NA
</code>```

Body:
I have two files as shown below.

First file:

Start State,Next State,Session Count,Transition%
/ccstoreui/v1/pages/layout/home,/ccstoreui/v1/pages/layout/home,1126,28.600%
/ccstoreui/v1/pages/layout/home,/ccstoreui/v1/pages/layout/LA_product_view,818,20.780%
/ccstoreui/v1/pages/layout/home,/ccstoreui/v1/orders/price,21,0.530%
/ccstoreui/v1/pages/layout/home,/ccstoreui/v1/login/,997,25.330%
/ccstoreui/v1/pages/layout/home,/ccstoreui/v1/organizations,31,0.780%
/ccstoreui/v1/pages/layout/home,/ccstoreui/v1/pages/layout/partsVisualizer,167,4.240%

Second file:

/ccstoreui/v1/pages/layout/home,/ccstoreui/v1/pages/layout/LA_product_view,894,13.100%
/ccstoreui/v1/pages/layout/home,/ccstoreui/v1/pages/layout/home,1184,17.350%
/ccstoreui/v1/pages/layout/home,/ccstoreui/v1/orders/price,25,0.360%
/ccstoreui/v1/pages/layout/home,/ccstoreui/v1/pages/layout/searchresults,226,3.310%
/ccstoreui/v1/pages/layout/home,/ccstoreui/v1/inventories/LA_entry,3,0.040%
/ccstoreui/v1/pages/layout/home,/ccstoreui/v1/pages/layout/cart,51,0.740%

I need to compare the first two columns of the first file and the first two columns of the second file and if they both match it should print 3,4 columns of both file. If both the files has unique they should be listed with NA from the both files.

My output should be like:

/ccstoreui/v1/pages/layout/home,/ccstoreui/v1/pages/layout/LA_product_view,818,20.780%,894,13.100%
/ccstoreui/v1/pages/layout/home,/ccstoreui/v1/pages/layout/home,1126,28.600%,1184,17.350%
/ccstoreui/v1/pages/layout/home,/ccstoreui/v1/orders/price,21,0.530%,25,0.360%
/ccstoreui/v1/pages/layout/home,/ccstoreui/v1/pages/layout/searchresults,NA,NA,226,3.310%
/ccstoreui/v1/pages/layout/home,/ccstoreui/v1/inventories/LA_entry,NA,NA,3,0.040%
/ccstoreui/v1/pages/layout/home,/ccstoreui/v1/pages/layout/cart,NA,NA,51,0.740%
/ccstoreui/v1/pages/layout/home,/ccstoreui/v1/organizations,31,0.780%,NA,NA
/ccstoreui/v1/pages/layout/home,/ccstoreui/v1/pages/layout/partsVisualizer,167,4.240%,NA,NA
/ccstoreui/v1/pages/layout/home,/ccstoreui/v1/login/,997,25.330%,NA,NA

Can someone please help me with this?

Body:
awk -f rag.awk file1 file2 where rag.awk is:

    BEGIN {
FS=OFS=","
}
{idx=$1 OFS $2; _34=$3 OFS $4}
FNR==NR {if (FNR>1) f1[idx]=_34; next}
idx in f1 { print idx, f1[idx], _34; delete f1[idx];next}
{print idx, "NA","NA", _34}
END {
  for (i in f1)
     print i, f1[i], "NA", "NA"
}

output:

/ccstoreui/v1/pages/layout/home,/ccstoreui/v1/pages/layout/LA_product_view,818,20.780%,894,13.100%
/ccstoreui/v1/pages/layout/home,/ccstoreui/v1/pages/layout/home,1126,28.600%,1184,17.350%
/ccstoreui/v1/pages/layout/home,/ccstoreui/v1/orders/price,21,0.530%,25,0.360%
/ccstoreui/v1/pages/layout/home,/ccstoreui/v1/pages/layout/searchresults,NA,NA,226,3.310%
/ccstoreui/v1/pages/layout/home,/ccstoreui/v1/inventories/LA_entry,NA,NA,3,0.040%
/ccstoreui/v1/pages/layout/home,/ccstoreui/v1/pages/layout/cart,NA,NA,51,0.740%
/ccstoreui/v1/pages/layout/home,/ccstoreui/v1/organizations,31,0.780%,NA,NA
/ccstoreui/v1/pages/layout/home,/ccstoreui/v1/pages/layout/partsVisualizer,167,4.240%,NA,NA
/ccstoreui/v1/pages/layout/home,/ccstoreui/v1/login/,997,25.330%,NA,NA


问:
Conversion failed when converting date and/or time from character string while inserting datetime SQL
I inserted some columns from an excel file into a SQL Table.

I am trying to select the date column but I get
"Conversion failed when converting date and/or time from character string while inserting datetime"

My Query is

```<code>Select
CONVERT(datetime2, SS.OrderDate) Date_Created
--CAST(SS.OrderDate as datetime2) Date_Created
FROM Table SS (nolock)
</code>```

Both of these lines fail.

My date column look like this:

```<code>43613
43612
43611
</code>```

Which excel can format back into (does anyone know how? what format is this?)

```<code>5/28/2019
5/27/2019
5/26/2019
</code>```

How can I get the same to be done in SQL?

答:
Just another option is to use the implicit conversion of a float to datetime.  Notice the minus 2.0

Example

```<code>Select AsInt       = convert(datetime,43613-2.0)
      ,WithDecimal = convert(datetime,43613.5-2.0)
</code>```

Returns

```<code>AsInt                    WithDecimal
2019-05-28 00:00:00.000  2019-05-28 12:00:00.000
</code>```

Now, IF your column is a varchar, perhaps something like this

Example

```<code>Declare @YourTable Table ([OrderDate] varchar(50))
Insert Into @YourTable Values
('43613'),
('43612'),
('43611')

select AsDateTime = convert(datetime,0+[OrderDate]-2.0)
 From @YourTable
</code>```

Returns

```<code>AsDateTime
2019-05-28 00:00:00.000
2019-05-27 00:00:00.000
2019-05-26 00:00:00.000
</code>```

Body:
I inserted some columns from an excel file into a SQL Table.

I am trying to select the date column but I get
"Conversion failed when converting date and/or time from character string while inserting datetime"

My Query is

Select
CONVERT(datetime2, SS.OrderDate) Date_Created
--CAST(SS.OrderDate as datetime2) Date_Created
FROM Table SS (nolock)

Both of these lines fail.

My date column look like this:

43613
43612
43611

Which excel can format back into (does anyone know how? what format is this?)

5/28/2019
5/27/2019
5/26/2019

How can I get the same to be done in SQL?

Body:
Just another option is to use the implicit conversion of a float to datetime.  Notice the minus 2.0

Example

Select AsInt       = convert(datetime,43613-2.0)
      ,WithDecimal = convert(datetime,43613.5-2.0)

Returns

AsInt                    WithDecimal
2019-05-28 00:00:00.000  2019-05-28 12:00:00.000

Now, IF your column is a varchar, perhaps something like this

Example

Declare @YourTable Table ([OrderDate] varchar(50))
Insert Into @YourTable Values
('43613'),
('43612'),
('43611')

select AsDateTime = convert(datetime,0+[OrderDate]-2.0)
 From @YourTable

Returns

AsDateTime
2019-05-28 00:00:00.000
2019-05-27 00:00:00.000
2019-05-26 00:00:00.000


问:
How to programatically hide a tooltip in highcharts?
I am trying to implement highcharts in a mobile application, everything works fine but there is one issue in which on changing orientation from potrait to landscape the tooltip shown for any point selected does not hide on orientation change.

Please suggest me how to hide a tooltip programatically in highcharts ..

I tried the below code:

$('#tankActualUsagechart').highcharts().tooltip.hide();

but this does not hide the marker which i am displaying ...

If there is a way to hide the marker i am fine with that also ..

Please help me on this issue

答:
You can use the update function

```<code>    var mychart = $('#container').highcharts();
</code>```

For disable tooltip:

```<code>    mychart.update({tooltip: {enabled: false}});
</code>```

For enable tooltip:

```<code>    mychart.update({tooltip: {enabled: true}});
</code>```

Check this jsfiddle:

Body:
You can use the update function

    var mychart = $('#container').highcharts();

For disable tooltip:

    mychart.update({tooltip: {enabled: false}});

For enable tooltip:

    mychart.update({tooltip: {enabled: true}});

Check this jsfiddle: