问:
How find max of an inner element in a list of key, values?
I have a list of items as you see below. The values for each year key is a list of 10 items but to make it short, I am only showing the first couple of them. How I can find the maximum of all inner "count" values? I have looked at various approaches but none has worked so far and perhaps I am missing something here. For instance, I really like some of one liners here but they didnt work for me enter link description here

Just to clarify that data is the result of a nest on csv file and it meant to be used in d3 chart and preferably no import library other than standard ones.

```<code>data = [
         {'2015': values: [{key: '0', value: {count: 45}},{key: '1', value: {count: 3}}, ... ]},
         {'2016': values: [{key: '0', value: {count: 67}},{key: '1', value: {count: 0}}, ... ]},
     {'2017': values: [{key: '0', value: {count: 12}},{key: '1', value: {count: 8}}, ... ]}
        ]
</code>```

To better show how data looks like, here is the screen shot in case it helps clarification of the question.

答:
You could destructure the object like this by flattening the values array and then mapping to get the count variable.

var data = [
         {"key":"2015", "values": [{"key": 0, "value": {"count": 45}},{"key": 1, "value": {"count": 3}}]},{"key":"2016", "values": [{"key": 0, "value": {"count": 67}},{"key": 1, "value": {"count": 0}}]},{"key": "2017", "values": [{"key": 0, "value": {"count": 12}},{"key": 1, "value": {"count": 8}}]}
   ]

  var num = Math.max(... data.map(d=>d.values).flat().map(v=>v.value.count))
  console.log(num)```

Body:
I have a list of items as you see below. The values for each year key is a list of 10 items but to make it short, I am only showing the first couple of them. How I can find the maximum of all inner "count" values? I have looked at various approaches but none has worked so far and perhaps I am missing something here. For instance, I really like some of one liners here but they didnt work for me enter link description here

Just to clarify that data is the result of a nest on csv file and it meant to be used in d3 chart and preferably no import library other than standard ones.

data = [
         {'2015': values: [{key: '0', value: {count: 45}},{key: '1', value: {count: 3}}, ... ]},
         {'2016': values: [{key: '0', value: {count: 67}},{key: '1', value: {count: 0}}, ... ]},
     {'2017': values: [{key: '0', value: {count: 12}},{key: '1', value: {count: 8}}, ... ]}
        ]

To better show how data looks like, here is the screen shot in case it helps clarification of the question.


来源: stackexchange

问:
How to select all text in a tk input box (ruby)
Just coming up to speed with tk / ruby.

I have a very simple window with a one line text input area, a "go" button, and a feedback label.

The desired behavior is that a user enters some text, hits the "go" button, and the code does some work.

When its all over the input box should have the text entered, but it should be highlighted and the focus in the input box, so that if the user begins typing again what was in the box will be overwritten.

In .net this was pretty easy, just say .selectall to the input field.  can't figure out how to do it in tk.

```<code>    root = TkRoot.new {title "Test App"}
content = Tk::Tile::Frame.new(root) {padding "3 3 12 12"}.grid( :sticky => 'nsew')
TkGrid.columnconfigure root, 0, :weight => 1; TkGrid.rowconfigure root, 0, :weight => 1
$job= TkVariable.new; $status = TkVariable.new
$j = Tk::Tile::Entry.new(content) {
      width 14; textvariable $job}.grid( :column => 1, :row => 1, :sticky => 'we' )
Tk::Tile::Button.new(content) {
         text 'Find Job'
         command {go_do_something}
       }.grid( :column => 2, :row => 1, :sticky => 'w')

    def go_do_something
       # ... do some processing, then I want to...
       # $j.focus
       # $j.select_all
    end
</code>```

Thanks in advance

答:
Order is important:

```<code>$j.focus;
$j.selection_range(0,100)
</code>```

This works to get the text box selected.   Getting the focus back to the window is another question I will ask elsewhere.

ContentLicense: CC BY-SA 3.0

Body:
Just coming up to speed with tk / ruby.

I have a very simple window with a one line text input area, a "go" button, and a feedback label.

The desired behavior is that a user enters some text, hits the "go" button, and the code does some work.

When its all over the input box should have the text entered, but it should be highlighted and the focus in the input box, so that if the user begins typing again what was in the box will be overwritten.

In .net this was pretty easy, just say .selectall to the input field.  can't figure out how to do it in tk.

    root = TkRoot.new {title "Test App"}
content = Tk::Tile::Frame.new(root) {padding "3 3 12 12"}.grid( :sticky => 'nsew')
TkGrid.columnconfigure root, 0, :weight => 1; TkGrid.rowconfigure root, 0, :weight => 1
$job= TkVariable.new; $status = TkVariable.new
$j = Tk::Tile::Entry.new(content) {
      width 14; textvariable $job}.grid( :column => 1, :row => 1, :sticky => 'we' )
Tk::Tile::Button.new(content) {
         text 'Find Job'
         command {go_do_something}
       }.grid( :column => 2, :row => 1, :sticky => 'w')

    def go_do_something
       # ... do some processing, then I want to...
       # $j.focus
       # $j.select_all
    end

Thanks in advance

Body:
Order is important:

$j.focus;
$j.selection_range(0,100)

This works to get the text box selected.   Getting the focus back to the window is another question I will ask elsewhere.


问:
Redim Preserve VBA Alternatives

Background

I just read a comment on this question that states that Redim Preserve is expensive and should be avoided. I use Redim Preserve in many scenarios, let us say for example to save field names from a PT that meet some specific criteria to use them later on with an API for Access/Selenium/XlWings,etc. where I need to access the elements in the array at different times, thus not looping in the original sheet(s) where PT(s) are; I use them to save data that came outside Excel too. This is to save the time to redo verification/processes and everything that was considered by saving the array in the first place.

Research/thoughts

I have seen that a similar question was asked at VB.net where they  suggest List(Of Variable) but I do not think this may be achieved within Excel. I Erase them once they are not longer needed too. In addition, where it is possible, I try to use dictionaries instead of arrays, but it may not be always the case where it is easier to go by index numbers and there is a need for array and not dictionaries. I was thinking that I may be able to create a sheet with the specified items instead of saving them to an array, but I do not see the benefit of doing so in terms of memory saving.

Question

What would be the best alternative to Redim Preserve in VBA?

答:
Update for 20 May 2022.  An updated version of the class below can be found at

https://github.com/FullValueRider/WCollection

This update has a more extensive collection of methods and is also available as a 32 bit or 64 bit ActiveX.dll (thanks to twinBasic).  There are currently 148 passing tests so the problems of things not working should hopefully be avoided.

Please leave any further comments or requests for updates as an issue on the github page.

===============================================

A collection is a good way to go but the default collection is a bit limited.

You may wish to use a wrapped collection which gives you more flexibility.

Class WCollection (but its easy to change the name to List if you prefer)

```<code>VERSION 1.0 CLASS
BEGIN
  MultiUse = -1  'True
END
Attribute VB_Name = "WCollection"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = True
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = True
'Rubberduck annotations
'@PredeclaredId
'@Exposed
Option Explicit

'@ModuleDescription("A wrapper for the collection object to add flexibility")

Private Type State

    Coll                                        As Collection

End Type

Private s                                       As State

Private Sub Class_Initialize()
    Set s.Coll = New Collection
End Sub

Public Function Deb() As WCollection
    With New WCollection
        Set Deb = .ReadyToUseInstance
    End With
End Function

Friend Function ReadyToUseInstance() As WCollection
    Set ReadyToUseInstance = Me
End Function

Public Function NewEnum() As IEnumVARIANT
    Set NewEnum = s.Coll.[_NewEnum]
End Function

Public Function Add(ParamArray ipItems() As Variant) As WCollection
    Dim myItem As Variant
    For Each myItem In ipItems
        s.Coll.Add myItem
    Next
        Set Add = Me
End Function

Public Function AddRange(ByVal ipIterable As Variant) As WCollection
    Dim myitem As Variant
    For Each myitem In ipIterable
        s.Coll.Add myitem
    Next
    Set AddRange = Me
End Function

Public Function AddString(ByVal ipString As String) As WCollection
    Dim myIndex As Long
    For myIndex = 1 To Len(ipString)
        s.Coll.Add VBA.Mid$(ipString, myIndex, 1)
    Next
End Function

Public Function Clone() As WCollection
    Set Clone = WCollection.Deb.AddRange(s.Coll)
End Function
'@DefaultMember
Public Property Get Item(ByVal ipIndex As Long) As Variant
    If VBA.IsObject(s.Coll.Item(ipIndex)) Then
        Set Item = s.Coll.Item(ipIndex)
    Else
        Item = s.Coll.Item(ipIndex)
    End If
End Property

Public Property Let Item(ByVal ipIndex As Long, ByVal ipItem As Variant)
    s.Coll.Add ipItem, after:=ipIndex
    s.Coll.Remove ipIndex
End Property

Public Property Set Item(ByVal ipindex As Long, ByVal ipitem As Variant)
    s.Coll.Add ipitem, after:=ipindex
    s.Coll.Remove ipindex
End Property

Public Function HoldsItem(ByVal ipItem As Variant) As Boolean
    HoldsItem = True
    Dim myItem As Variant
    For Each myItem In s.Coll
        If myItem = ipItem Then Exit Function
    Next
    HoldsItem = False
End Function

Public Function Join(Optional ByVal ipSeparator As String) As String

    If TypeName(s.Coll.Item(1)) <> "String" Then
        Join = "Items are not string type"
        Exit Function
    End If

    Dim myStr As String
    Dim myItem As Variant
    For Each myItem In s.Coll
        If Len(myStr) = 0 Then
            myStr = myItem
        Else
            myStr = myStr & ipSeparator
        End If

    Next

End Function

Public Function Reverse() As WCollection
    Dim myW As WCollection
    Set myW = WCollection.Deb
    Dim myIndex As Long
    For myIndex = LastIndex To FirstIndex Step -1
        myW.Add s.Coll.Item(myIndex)
    Next
    Set Reverse = myW
End Function

Public Function HasItems() As Boolean
    HasItems = s.Coll.Count > 0
End Function

Public Function HasNoItems() As Boolean
    HasNoItems = Not HasItems
End Function

Public Function Indexof(ByVal ipItem As Variant, Optional ipIndex As Long = -1) As Long
    Dim myIndex As Long
    For myIndex = IIf(ipIndex = -1, 1, ipIndex) To s.Coll.Count
        If ipItem = s.Coll.Item(myIndex) Then
            Indexof = myIndex
            Exit Function
        End If
    Next
End Function

Public Function LastIndexof(ByVal ipItem As Variant, Optional ipIndex As Long = -1) As Long
    Dim myIndex As Long
    For myIndex = LastIndex To IIf(ipIndex = -1, 1, ipIndex) Step -1
        If ipItem = s.Coll.Item(myIndex) Then
            LastIndexof = myIndex
            Exit Function
        End If
    Next
    LastIndexof = -1
End Function

Public Function LacksItem(ByVal ipItem As Variant) As Boolean
    LacksItem = Not HoldsItem(ipItem)
End Function

Public Function Insert(ByVal ipIndex As Long, ByVal ipItem As Variant) As WCollection
    s.Coll.Add ipItem, before:=ipIndex
    Set Insert = Me
End Function

Public Function Remove(ByVal ipIndex As Long) As WCollection
    s.Coll.Remove ipIndex
    Set Remove = Me
End Function

Public Function FirstIndex() As Long
    FirstIndex = 1
End Function

Public Function LastIndex() As Long
    LastIndex = s.Coll.Count
End Function

Public Function RemoveAll() As WCollection
    Dim myIndex As Long
    For myIndex = s.Coll.Count To 1 Step -1
        Remove myIndex
    Next
    Set RemoveAll = Me
End Function

Public Property Get Count() As Long
    Count = s.Coll.Count
End Property

Public Function ToArray() As Variant
    Dim myarray As Variant
    ReDim myarray(0 To s.Coll.Count - 1)
    Dim myItem As Variant
    Dim myIndex As Long
    myIndex = 0
    For Each myItem In s.Coll
        If VBA.IsObject(myItem) Then
            Set myarray(myIndex) = myItem
        Else
            myarray(myIndex) = myItem
        End If
        myIndex = myIndex + 1
    Next
    ToArray = myarray
End Function

Public Function RemoveFirstOf(ByVal ipItem As Variant) As WCollection
    Set RemoveFirstOf = Remove(Indexof(ipItem))
    Set RemoveFirstOf = Me
End Function

Public Function RemoveLastOf(ByVal ipItem As Variant) As WCollection
    Set RemoveLastOf = Remove(LastIndexof(ipItem))
    Set RemoveLastOf = Me
End Function

Public Function RemoveAnyOf(ByVal ipItem As Variant) As WCollection
    Dim myIndex As Long
    For myIndex = LastIndex To FirstIndex Step -1

        If s.Coll.Item(myIndex) = ipItem Then Remove myIndex

    Next
    Set RemoveAnyOf = Me
End Function

Public Function First() As Variant
    If VBA.IsObject(s.Coll.Item(FirstIndex)) Then
        Set First = s.Coll.Item(FirstIndex)
    Else
        First = s.Coll.Item(FirstIndex)
    End If
End Function

Public Function Last() As Variant
    If VBA.IsObject(s.Coll.Item(LastIndex)) Then
        Set Last = s.Coll.Item(LastIndex)
    Else
        Last = s.Coll.Item(LastIndex)
    End If
End Function

Public Function Enqueue(ByVal ipItem As Variant) As WCollection
    Add ipItem
    Set Enqueue = Me
End Function

Public Function Dequeue() As Variant
    If VBA.IsObject(s.Coll.Item(FirstIndex)) Then
        Set Dequeue = s.Coll.Item(FirstIndex)
    Else
        Dequeue = s.Coll.Item(FirstIndex)
    End If
    Remove 0
End Function

Public Function Push(ByVal ipitem As Variant) As WCollection
    Add ipitem
    Set Push = Me
End Function

Public Function Pop(ByVal ipitem As Variant) As Variant
    If VBA.IsObject(s.Coll.Item(FirstIndex)) Then
        Set Pop = s.Coll.Item(FirstIndex)
    Else
        Pop = s.Coll.Item(FirstIndex)
    End If
    Remove s.Coll.Count
End Function

Public Function Peek(ByVal ipIndex As Long) As Variant
    If VBA.IsObject(s.Coll.Item(FirstIndex)) Then
        Set Peek = s.Coll.Item(FirstIndex)
    Else
        Peek = s.Coll.Item(FirstIndex)
    End If
End Function

</code>```

ContentLicense: CC BY-SA 4.0

Title: Redim Preserve VBA Alternatives

Body:
Update for 20 May 2022.  An updated version of the class below can be found at

https://github.com/FullValueRider/WCollection

This update has a more extensive collection of methods and is also available as a 32 bit or 64 bit ActiveX.dll (thanks to twinBasic).  There are currently 148 passing tests so the problems of things not working should hopefully be avoided.

Please leave any further comments or requests for updates as an issue on the github page.

===============================================

A collection is a good way to go but the default collection is a bit limited.

You may wish to use a wrapped collection which gives you more flexibility.

Class WCollection (but its easy to change the name to List if you prefer)

VERSION 1.0 CLASS
BEGIN
  MultiUse = -1  'True
END
Attribute VB_Name = "WCollection"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = True
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = True
'Rubberduck annotations
'@PredeclaredId
'@Exposed
Option Explicit

'@ModuleDescription("A wrapper for the collection object to add flexibility")

Private Type State

    Coll                                        As Collection

End Type

Private s                                       As State

Private Sub Class_Initialize()
    Set s.Coll = New Collection
End Sub

Public Function Deb() As WCollection
    With New WCollection
        Set Deb = .ReadyToUseInstance
    End With
End Function

Friend Function ReadyToUseInstance() As WCollection
    Set ReadyToUseInstance = Me
End Function

Public Function NewEnum() As IEnumVARIANT
    Set NewEnum = s.Coll.[_NewEnum]
End Function

Public Function Add(ParamArray ipItems() As Variant) As WCollection
    Dim myItem As Variant
    For Each myItem In ipItems
        s.Coll.Add myItem
    Next
        Set Add = Me
End Function

Public Function AddRange(ByVal ipIterable As Variant) As WCollection
    Dim myitem As Variant
    For Each myitem In ipIterable
        s.Coll.Add myitem
    Next
    Set AddRange = Me
End Function

Public Function AddString(ByVal ipString As String) As WCollection
    Dim myIndex As Long
    For myIndex = 1 To Len(ipString)
        s.Coll.Add VBA.Mid$(ipString, myIndex, 1)
    Next
End Function

Public Function Clone() As WCollection
    Set Clone = WCollection.Deb.AddRange(s.Coll)
End Function
'@DefaultMember
Public Property Get Item(ByVal ipIndex As Long) As Variant
    If VBA.IsObject(s.Coll.Item(ipIndex)) Then
        Set Item = s.Coll.Item(ipIndex)
    Else
        Item = s.Coll.Item(ipIndex)
    End If
End Property

Public Property Let Item(ByVal ipIndex As Long, ByVal ipItem As Variant)
    s.Coll.Add ipItem, after:=ipIndex
    s.Coll.Remove ipIndex
End Property

Public Property Set Item(ByVal ipindex As Long, ByVal ipitem As Variant)
    s.Coll.Add ipitem, after:=ipindex
    s.Coll.Remove ipindex
End Property

Public Function HoldsItem(ByVal ipItem As Variant) As Boolean
    HoldsItem = True
    Dim myItem As Variant
    For Each myItem In s.Coll
        If myItem = ipItem Then Exit Function
    Next
    HoldsItem = False
End Function

Public Function Join(Optional ByVal ipSeparator As String) As String

    If TypeName(s.Coll.Item(1)) <> "String" Then
        Join = "Items are not string type"
        Exit Function
    End If

    Dim myStr As String
    Dim myItem As Variant
    For Each myItem In s.Coll
        If Len(myStr) = 0 Then
            myStr = myItem
        Else
            myStr = myStr & ipSeparator
        End If

    Next

End Function

Public Function Reverse() As WCollection
    Dim myW As WCollection
    Set myW = WCollection.Deb
    Dim myIndex As Long
    For myIndex = LastIndex To FirstIndex Step -1
        myW.Add s.Coll.Item(myIndex)
    Next
    Set Reverse = myW
End Function

Public Function HasItems() As Boolean
    HasItems = s.Coll.Count > 0
End Function

Public Function HasNoItems() As Boolean
    HasNoItems = Not HasItems
End Function

Public Function Indexof(ByVal ipItem As Variant, Optional ipIndex As Long = -1) As Long
    Dim myIndex As Long
    For myIndex = IIf(ipIndex = -1, 1, ipIndex) To s.Coll.Count
        If ipItem = s.Coll.Item(myIndex) Then
            Indexof = myIndex
            Exit Function
        End If
    Next
End Function

Public Function LastIndexof(ByVal ipItem As Variant, Optional ipIndex As Long = -1) As Long
    Dim myIndex As Long
    For myIndex = LastIndex To IIf(ipIndex = -1, 1, ipIndex) Step -1
        If ipItem = s.Coll.Item(myIndex) Then
            LastIndexof = myIndex
            Exit Function
        End If
    Next
    LastIndexof = -1
End Function

Public Function LacksItem(ByVal ipItem As Variant) As Boolean
    LacksItem = Not HoldsItem(ipItem)
End Function

Public Function Insert(ByVal ipIndex As Long, ByVal ipItem As Variant) As WCollection
    s.Coll.Add ipItem, before:=ipIndex
    Set Insert = Me
End Function

Public Function Remove(ByVal ipIndex As Long) As WCollection
    s.Coll.Remove ipIndex
    Set Remove = Me
End Function

Public Function FirstIndex() As Long
    FirstIndex = 1
End Function

Public Function LastIndex() As Long
    LastIndex = s.Coll.Count
End Function

Public Function RemoveAll() As WCollection
    Dim myIndex As Long
    For myIndex = s.Coll.Count To 1 Step -1
        Remove myIndex
    Next
    Set RemoveAll = Me
End Function

Public Property Get Count() As Long
    Count = s.Coll.Count
End Property

Public Function ToArray() As Variant
    Dim myarray As Variant
    ReDim myarray(0 To s.Coll.Count - 1)
    Dim myItem As Variant
    Dim myIndex As Long
    myIndex = 0
    For Each myItem In s.Coll
        If VBA.IsObject(myItem) Then
            Set myarray(myIndex) = myItem
        Else
            myarray(myIndex) = myItem
        End If
        myIndex = myIndex + 1
    Next
    ToArray = myarray
End Function

Public Function RemoveFirstOf(ByVal ipItem As Variant) As WCollection
    Set RemoveFirstOf = Remove(Indexof(ipItem))
    Set RemoveFirstOf = Me
End Function

Public Function RemoveLastOf(ByVal ipItem As Variant) As WCollection
    Set RemoveLastOf = Remove(LastIndexof(ipItem))
    Set RemoveLastOf = Me
End Function

Public Function RemoveAnyOf(ByVal ipItem As Variant) As WCollection
    Dim myIndex As Long
    For myIndex = LastIndex To FirstIndex Step -1

        If s.Coll.Item(myIndex) = ipItem Then Remove myIndex

    Next
    Set RemoveAnyOf = Me
End Function

Public Function First() As Variant
    If VBA.IsObject(s.Coll.Item(FirstIndex)) Then
        Set First = s.Coll.Item(FirstIndex)
    Else
        First = s.Coll.Item(FirstIndex)
    End If
End Function

Public Function Last() As Variant
    If VBA.IsObject(s.Coll.Item(LastIndex)) Then
        Set Last = s.Coll.Item(LastIndex)
    Else
        Last = s.Coll.Item(LastIndex)
    End If
End Function

Public Function Enqueue(ByVal ipItem As Variant) As WCollection
    Add ipItem
    Set Enqueue = Me
End Function

Public Function Dequeue() As Variant
    If VBA.IsObject(s.Coll.Item(FirstIndex)) Then
        Set Dequeue = s.Coll.Item(FirstIndex)
    Else
        Dequeue = s.Coll.Item(FirstIndex)
    End If
    Remove 0
End Function

Public Function Push(ByVal ipitem As Variant) As WCollection
    Add ipitem
    Set Push = Me
End Function

Public Function Pop(ByVal ipitem As Variant) As Variant
    If VBA.IsObject(s.Coll.Item(FirstIndex)) Then
        Set Pop = s.Coll.Item(FirstIndex)
    Else
        Pop = s.Coll.Item(FirstIndex)
    End If
    Remove s.Coll.Count
End Function

Public Function Peek(ByVal ipIndex As Long) As Variant
    If VBA.IsObject(s.Coll.Item(FirstIndex)) Then
        Set Peek = s.Coll.Item(FirstIndex)
    Else
        Peek = s.Coll.Item(FirstIndex)
    End If
End Function


问:
Copy Data From On-Premise SQL Server To Azure SQL - Azure Private Network
Requirement: I wanted to copy data from a specific table/view residing on a on-premise SQL Server to Azure SQL DB.

Infrastructure: As depicted in below picture. Essentially, the Azure network is directly connected with corporate network over Express Route. Thus it's a pure private network connection; as good as the corporate network itself.

Issue/Question: I know there are multiple approaches present to get this operation done and I am not restricted to use ADF copy Data tool only. BUT, for all of these I see some cavets or extra steps needed to be done as below:

ADF Copy Data Tool: Needs a SH-IR and a small MSI package needs to be installed on on-premise machine which hosts the SQL server for registration purpose.

Logic Apps: Needs a Virtual Gateway (OR) ASE

App Service: If the operation is wrapped in a C# application and I choose to deploy to a Azure Web Apps. Then in-order to connect to on-premise SQL Server we need to setup hybrid connection manager and as in #1 we need to install something in on-premise machine.

For my case, none of these extra steps can be done. essentially, the on-premise SQL Server comes under a different BU and thus I don't have any permission there; except they have given grant to a table/view. Thus, none of these extra shitty steps can be done.

Moreover, as mentioned above; since it's connected over express route as direct connection, As can be seen in above picture, both the on-premise and azure SQL are essentially inside the same corporate network. THUS, I should be able to access them directly without configuring any of these extra steps as mentioned above.

Please confirm on these and provide a suggestion.

Thank You.

答: You can still go with the ADF scenario without a SHIR by creating ADF in a Managed VNET using Private Endpoint. As you already have an ER circuit and have the flexibility to configure the Azure side, can you do this with Azure IR: Access on-premises SQL Server from Data Factory Managed VNet using Private Endpoint - Azure Data Factory | Microsoft Docs</p>


问:
Can't figure out logic for this assignment
```<code>school_days = 15
classes_per_day = 5
total_classes = 75
for counter in range(school_days):
    total_classes = total_classes + classes_per_day

print(total_classes)
</code>```

Here are the instructions in the assignment:

Task - Change the values stored in the variables school_days, classes_per_day, and total_classes so that the loop calculates the classes for a student that has 15 school days left. The student has 5 classes per day. The final value of total classes should be 75.

Output: 75

I've been trying to figure this out for the last hour, and I don't know what I'm doing wrong.

答:
I don't know exactly what you are trying to achieve but you could try this:</p>
```<code>school_days = 1
classes_per_day = 0
total_classes = 0
total_classes = total_classes + classes_per_day
for counter in range(school_days):
    print(total_classes + 1)
</code>```

Body:
school_days = 15
classes_per_day = 5
total_classes = 75
for counter in range(school_days):
    total_classes = total_classes + classes_per_day

print(total_classes)

Here are the instructions in the assignment:

Task - Change the values stored in the variables school_days, classes_per_day, and total_classes so that the loop calculates the classes for a student that has 15 school days left. The student has 5 classes per day. The final value of total classes should be 75.

Output: 75

I've been trying to figure this out for the last hour, and I don't know what I'm doing wrong.

Body:
I don't know exactly what you are trying to achieve but you could try this:

school_days = 1
classes_per_day = 0
total_classes = 0
total_classes = total_classes + classes_per_day
for counter in range(school_days):
    print(total_classes + 1)


问:
Any way to pull player data using (Google Sheets) IMPORTHTML or XML
Is there any way I can pull the players from this website onto google sheets using importhtml or xml.

https://leftwinglock.com/line-combinations/chicago-blackhawks/?team=chicago-blackhawks&strength=EV&gametype=GD

答:
There is something with the site that prevents access on to the data (tested and got the same issue with script).

However, if you only want the list of the names of the players, you could use another link (e.g. https://www.espn.com/nhl/team/roster/_/name/chi/chicago-blackhawks) to fetch the player names.

Formula:

```<code>=arrayformula(regexreplace(transpose({
importxml("https://www.espn.com/nhl/team/roster/_/name/chi/chicago-blackhawks", "//*[@id='fittPageContainer']/div[2]/div[5]/div/div/section/div/section/div[2]/div[1]/div[2]/div/div[2]/table/tbody"),
importxml("https://www.espn.com/nhl/team/roster/_/name/chi/chicago-blackhawks", "//*[@id='fittPageContainer']/div[2]/div[5]/div/div/section/div/section/div[2]/div[2]/div[2]/div/div[2]/table/tbody"),
importxml("https://www.espn.com/nhl/team/roster/_/name/chi/chicago-blackhawks", "//*[@id='fittPageContainer']/div[2]/div[5]/div/div/section/div/section/div[2]/div[3]/div[2]/div/div[2]/table/tbody"),
importxml("https://www.espn.com/nhl/team/roster/_/name/chi/chicago-blackhawks", "//*[@id='fittPageContainer']/div[2]/div[5]/div/div/section/div/section/div[2]/div[4]/div[2]/div/div[2]/table/tbody"),
importxml("https://www.espn.com/nhl/team/roster/_/name/chi/chicago-blackhawks", "//*[@id='fittPageContainer']/div[2]/div[5]/div/div/section/div/section/div[2]/div[5]/div[2]/div/div[2]/table/tbody")
}), "\d.*", ""))
</code>```

Output:

You can store your links and paths into cells and then just call them so you can reuse them (xpaths) with other teams as well and have the final formula easier to read. See sample below using another team (Colorado Avalanche)

B1 (link to the team):

```<code>https://www.espn.com/nhl/team/roster/_/name/col/colorado-avalanche
</code>```

E1 - E5 (xpaths of each table):

```<code>//*[@id='fittPageContainer']/div[2]/div[5]/div/div/section/div/section/div[2]/div[1]/div[2]/div/div[2]/table/tbody
//*[@id='fittPageContainer']/div[2]/div[5]/div/div/section/div/section/div[2]/div[2]/div[2]/div/div[2]/table/tbody
//*[@id='fittPageContainer']/div[2]/div[5]/div/div/section/div/section/div[2]/div[3]/div[2]/div/div[2]/table/tbody
//*[@id='fittPageContainer']/div[2]/div[5]/div/div/section/div/section/div[2]/div[4]/div[2]/div/div[2]/table/tbody
//*[@id='fittPageContainer']/div[2]/div[5]/div/div/section/div/section/div[2]/div[5]/div[2]/div/div[2]/table/tbody
</code>```

Formula:

```<code>=arrayformula(regexreplace(transpose({
importxml(B1, E1),
importxml(B1, E2),
importxml(B1, E3),
importxml(B1, E4),
importxml(B1, E5)
}), "\d.*", ""))
</code>```

Output:

Body:
There is something with the site that prevents access on to the data (tested and got the same issue with script).

However, if you only want the list of the names of the players, you could use another link (e.g. https://www.espn.com/nhl/team/roster/_/name/chi/chicago-blackhawks) to fetch the player names.

Formula:

=arrayformula(regexreplace(transpose({
importxml("https://www.espn.com/nhl/team/roster/_/name/chi/chicago-blackhawks", "//*[@id='fittPageContainer']/div[2]/div[5]/div/div/section/div/section/div[2]/div[1]/div[2]/div/div[2]/table/tbody"),
importxml("https://www.espn.com/nhl/team/roster/_/name/chi/chicago-blackhawks", "//*[@id='fittPageContainer']/div[2]/div[5]/div/div/section/div/section/div[2]/div[2]/div[2]/div/div[2]/table/tbody"),
importxml("https://www.espn.com/nhl/team/roster/_/name/chi/chicago-blackhawks", "//*[@id='fittPageContainer']/div[2]/div[5]/div/div/section/div/section/div[2]/div[3]/div[2]/div/div[2]/table/tbody"),
importxml("https://www.espn.com/nhl/team/roster/_/name/chi/chicago-blackhawks", "//*[@id='fittPageContainer']/div[2]/div[5]/div/div/section/div/section/div[2]/div[4]/div[2]/div/div[2]/table/tbody"),
importxml("https://www.espn.com/nhl/team/roster/_/name/chi/chicago-blackhawks", "//*[@id='fittPageContainer']/div[2]/div[5]/div/div/section/div/section/div[2]/div[5]/div[2]/div/div[2]/table/tbody")
}), "\d.*", ""))

Output:

You can store your links and paths into cells and then just call them so you can reuse them (xpaths) with other teams as well and have the final formula easier to read. See sample below using another team (Colorado Avalanche)

B1 (link to the team):

https://www.espn.com/nhl/team/roster/_/name/col/colorado-avalanche

E1 - E5 (xpaths of each table):

//*[@id='fittPageContainer']/div[2]/div[5]/div/div/section/div/section/div[2]/div[1]/div[2]/div/div[2]/table/tbody
//*[@id='fittPageContainer']/div[2]/div[5]/div/div/section/div/section/div[2]/div[2]/div[2]/div/div[2]/table/tbody
//*[@id='fittPageContainer']/div[2]/div[5]/div/div/section/div/section/div[2]/div[3]/div[2]/div/div[2]/table/tbody
//*[@id='fittPageContainer']/div[2]/div[5]/div/div/section/div/section/div[2]/div[4]/div[2]/div/div[2]/table/tbody
//*[@id='fittPageContainer']/div[2]/div[5]/div/div/section/div/section/div[2]/div[5]/div[2]/div/div[2]/table/tbody

Formula:

=arrayformula(regexreplace(transpose({
importxml(B1, E1),
importxml(B1, E2),
importxml(B1, E3),
importxml(B1, E4),
importxml(B1, E5)
}), "\d.*", ""))

Output:


问:
Unscope scoped css style for selected module
I've been trying not apply a scoped style for one certain element in the DOM hierarchy.

The use case is that I want to apply the style defined in the parent page's theme inside a widget for specific elements.

      body {
        font-family: 'Times New Roman', Times, serif;
        font-weight: 400;
        font-style: normal;
        color: #2b2b2b;
        background: white;
        line-height: 1.65;
      }

      button {
        font-family: 'Times New Roman', Times, serif;
        background-color: green;
      }

      .scope {}

      .reset {
        composes: scope;
      }

      .reset div,
      .reset button {
        font-size: 32pt;
        font-family: sans-serif;
      }

      .reset button {
        background-color: blue;
      }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
  <head>
    <title>Unscope scope</title>
  </head>

  <body style="background-color: rgb(194, 194, 194)">
    <h1>Hello</h1>
    <button type="button">
      Standard style button
    </button>
    <div id="app" class="reset">
      <div>
        <button type="button">
          Scope style button
        </button>
      </div>
      <div>
        <button type="button" class="unscoped">
          Unscoped style button
        </button>
      </div>
    </div>
  </body>
</html></code>```

This is how I want it too look like:

答:
You can use the :not pseudo class in CSS to make sure you only apply your style to elements without the selector inside.

This is what that would look like in your case:

body {
  font-family: 'Times New Roman', Times, serif;
  font-weight: 400;
  font-style: normal;
  color: #2b2b2b;
  background: white;
  line-height: 1.65;
}

button {
  font-family: 'Times New Roman', Times, serif;
  background-color: green;
}

.scope {}

.reset {
  composes: scope;
  /* ^ I don't think this is valid CSS or at least I've never seen this */
}

.reset button:not(.unscoped) {
  /*          ^ See the change here */
  font-size: 32pt;
  background-color: blue;
  font-family: sans-serif;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
  <head>
    <title>Unscope scope</title>
  </head>

  <body style="background-color: rgb(194, 194, 194)">
    <h1>Hello</h1>
    <button type="button">
      Standard style button
    </button>
    <div id="app" class="reset">
      <div>
        <button type="button">
          Scope style button
        </button>
      </div>
      <div>
        <button type="button" class="unscoped">
          Unscoped style button
        </button>
      </div>
    </div>
  </body>
</html></code>```

Body:
I've been trying not apply a scoped style for one certain element in the DOM hierarchy.

The use case is that I want to apply the style defined in the parent page's theme inside a widget for specific elements.

      body {
        font-family: 'Times New Roman', Times, serif;
        font-weight: 400;
        font-style: normal;
        color: #2b2b2b;
        background: white;
        line-height: 1.65;
      }

      button {
        font-family: 'Times New Roman', Times, serif;
        background-color: green;
      }

      .scope {}

      .reset {
        composes: scope;
      }

      .reset div,
      .reset button {
        font-size: 32pt;
        font-family: sans-serif;
      }

      .reset button {
        background-color: blue;
      }

    <title>Unscope scope</title>

Hello

    <button type="button">
      Standard style button
    </button>

        <button type="button">
          Scope style button
        </button>

        <button type="button" class="unscoped">
          Unscoped style button
        </button>

This is how I want it too look like:

Body:
You can use the :not pseudo class in CSS to make sure you only apply your style to elements without the selector inside.

This is what that would look like in your case:

body {
  font-family: 'Times New Roman', Times, serif;
  font-weight: 400;
  font-style: normal;
  color: #2b2b2b;
  background: white;
  line-height: 1.65;
}

button {
  font-family: 'Times New Roman', Times, serif;
  background-color: green;
}

.scope {}

.reset {
  composes: scope;
  /* ^ I don't think this is valid CSS or at least I've never seen this */
}

.reset button:not(.unscoped) {
  /*          ^ See the change here */
  font-size: 32pt;
  background-color: blue;
  font-family: sans-serif;
}

<html>
  <head>
    <title>Unscope scope</title>
  </head>

  <body style="background-color: rgb(194, 194, 194)">
    <h1>Hello</h1>
    <button type="button">
      Standard style button
    </button>
    <div id="app" class="reset">
      <div>
        <button type="button">
          Scope style button
        </button>
      </div>
      <div>
        <button type="button" class="unscoped">
          Unscoped style button
        </button>
      </div>
    </div>
  </body>
</html>


问:
How to change the color of Radwindow loading image to blue
I have radgrid on click of add new record, my radwindow opens up with loading image in green color but i want that to be changed to blue color, and my radwindow skin should remain black only.

This is my code where i am setting the property for radwindow

```<code><telerik:RadWindowManager ID="RadWindowManager1" runat="server" EnableShadow="true"
                        Skin="Black" >
                        <Windows>
                            <telerik:RadWindow ID="UserListDialog" runat="server" Height="620px" Width="620px"
                                ReloadOnShow="true" ShowContentDuringLoad="false" Modal="true" VisibleStatusbar="false" Animation="Resize"  AutoSize="false" Behaviors="Close"/>
                        </Windows>
                    </telerik:RadWindowManager>
</code>```

答:
You can examine the resulting markup with a tool like FireBug and copy the needed CSS selector. Here is an example yielded in the same manner:

```<code>        .RadWindow_Black td.rwWindowContent.rwLoading
    {
        background-image: url("custom-loading-image.gif") !important;
    }
</code>```

Where, of course, the custom-loading-image.gif is your version of the loading sign that you wish to have and this CSS rule should be added to the head of the page in the  tag. This information, along with some more useful tips is available in their Knowledge Base section: http://www.telerik.com/support/kb/aspnet-ajax/window/custom-loading-sign-for-radwindow.aspx.

Body:
I have radgrid on click of add new record, my radwindow opens up with loading image in green color but i want that to be changed to blue color, and my radwindow skin should remain black only.

This is my code where i am setting the property for radwindow

<telerik:RadWindowManager ID="RadWindowManager1" runat="server" EnableShadow="true"
                        Skin="Black" >
                        <Windows>
                            <telerik:RadWindow ID="UserListDialog" runat="server" Height="620px" Width="620px"
                                ReloadOnShow="true" ShowContentDuringLoad="false" Modal="true" VisibleStatusbar="false" Animation="Resize"  AutoSize="false" Behaviors="Close"/>
                        </Windows>
                    </telerik:RadWindowManager>

Body:
You can examine the resulting markup with a tool like FireBug and copy the needed CSS selector. Here is an example yielded in the same manner:

        .RadWindow_Black td.rwWindowContent.rwLoading
    {
        background-image: url("custom-loading-image.gif") !important;
    }

Where, of course, the custom-loading-image.gif is your version of the loading sign that you wish to have and this CSS rule should be added to the head of the page in the  tag. This information, along with some more useful tips is available in their Knowledge Base section: http://www.telerik.com/support/kb/aspnet-ajax/window/custom-loading-sign-for-radwindow.aspx.


问:
How can I get my min and max function to print my error message properly?
This is the prompt we were given to find the function needed:

A function that prompts the user for the minimum value and returns it
to the calling statement. Function to also deal with range checking to
make sure that the minimum value provided is greater than 0

Here's my code below however it doesn't print out the error message when I enter a minimum value higher than the maximum value.

```<code>def get_min():
       return int(input("What's your minimum value?"))

def min_Check(get_min):
    if (get_min >= 0):
      return print("ERROR. Minimum should be greater than 0")
else:
      return get_min

def get_max():
        return int(input("What's your maximun value?"))

def max_Check(get_min):
   if (get_max <= get_min):
    return print(f"ERROR. Maximum value must be greater {min}")
else:
    return max

min_value = get_min()
max_value = get_max()
get_check1 = min_Check(get_min)
get_check2 = max_Check(get_min)
</code>```

答:
There are a couple of things in your code that need fixing:

Both max_Check and min_Check have the else statement outside the
function, I don't know if this was a copy paste error but you need
to fix that.

You never pass get_max as an argument for max_Check so it will never
do the if correctly because it is missing an argument. You should
have gotten an error for that.

Body:
This is the prompt we were given to find the function needed:

A function that prompts the user for the minimum value and returns it
to the calling statement. Function to also deal with range checking to
make sure that the minimum value provided is greater than 0

Here's my code below however it doesn't print out the error message when I enter a minimum value higher than the maximum value.

def get_min():
       return int(input("What's your minimum value?"))

def min_Check(get_min):
    if (get_min >= 0):
      return print("ERROR. Minimum should be greater than 0")
else:
      return get_min

def get_max():
        return int(input("What's your maximun value?"))

def max_Check(get_min):
   if (get_max <= get_min):
    return print(f"ERROR. Maximum value must be greater {min}")
else:
    return max

min_value = get_min()
max_value = get_max()
get_check1 = min_Check(get_min)
get_check2 = max_Check(get_min)


问:
Alternating lines with Nested Loops
This is the exercise I need to complete:
Using nested loops, write some code that outputs the following:

```<code>##########
**********
##########
**********
##########
</code>```

Following is all the code I have so far. I assume I need to combine these two loop functions to one but I'm struggling with it. I'm early on in my first class and any help with this would be appreciated!

```<code>for a in range (0, 5, 2):
    for b in range(10):
        print("#", end = "")
    print("")
for a in range (1, 5, 2):
    for b in range(10):
        print("*", end = "")
    print("")
</code>```

答:
There are several ways to do it. First you should check how many lines you need to output. 5, so you need a loop doing something 5 times.

```<code>for i in range(5):
</code>```

Now you need 2 loops to paste print the 2 line patterns (you already have them in your code)

```<code> for b in range(10):
        print("#", end = "")
    print("")
</code>```

and

```<code>for b in range(10):
        print("*", end = "")
    print("")
</code>```

If you need to alternate between 2 values it's mostly the best to use the Modulo Operator.

So you can just switch between the 2 loops by % 2.

```<code>for i in range(5):
  if i % 2 == 0:
    for b in range(10):
        print("#", end = "")
    print("")
  else:
    for b in range(10):
        print("*", end = "")
    print("")
</code>```

Title: Alternating lines with Nested Loops

Body:
This is the exercise I need to complete:
Using nested loops, write some code that outputs the following:

##########
**********
##########
**********
##########

Following is all the code I have so far. I assume I need to combine these two loop functions to one but I'm struggling with it. I'm early on in my first class and any help with this would be appreciated!

for a in range (0, 5, 2):
    for b in range(10):
        print("#", end = "")
    print("")
for a in range (1, 5, 2):
    for b in range(10):
        print("*", end = "")
    print("")

Body:
There are several ways to do it. First you should check how many lines you need to output. 5, so you need a loop doing something 5 times.

for i in range(5):

Now you need 2 loops to paste print the 2 line patterns (you already have them in your code)

 for b in range(10):
        print("#", end = "")
    print("")

and

for b in range(10):
        print("*", end = "")
    print("")

If you need to alternate between 2 values it's mostly the best to use the Modulo Operator.

So you can just switch between the 2 loops by % 2.

for i in range(5):
  if i % 2 == 0:
    for b in range(10):
        print("#", end = "")
    print("")
  else:
    for b in range(10):
        print("*", end = "")
    print("")


问:
Cheat single inheritance in Java?
I have heard there is a way to cheat single inheritance and implement multiple inheritance in Java. Does anyone know how to implement this(with out using interface)?

Just out of curiosity ;-)

答:
Sure you can, but it's tricky and you should really consider if that's the way you want to go.

The idea is to use scope-based inheritance coupled with type-based one. Which is type-talk for saying that for internal purposes, inner classes "inherit" methods and fields of the outer class. It's a bit like mixins, where the outer class is mixed-in to the inner class, but not as safe, as you can change the state of the outer class as well as use its methods.

Gilad Bracha (one of the main java language designers) wrote a paper discussing that.
So, suppose you want to share some methods for internal use between some unrelated classes (e.g, for string manipulation), you can create sub classes of them as inner classes of a class that has all the needed methods, and the sub classes could use methods both from their super classes and from the outer class.

Anyway, it's tricky for complex classes, and you could get most of the functionality using static imports (from java 5 on). Great question for job interviews and pub quizzes, though ;-)

OwnerDisplayName: Omnipotent

Title: Cheat single inheritance in Java?

LastEditorDisplayName: Omnipotent

LastEditorDisplayName: Konrad Rudolph


问:
INSERT 6000 Rows - best practice
I have a PHP script that calls an API method that can easily return 6k+ results.

I use PEAR DB_DataObject to write each row in a foreach loop to the DB.

The above script is batch processing 20 users at a time - and although some will only have a few results from the API others will have more. Worst case is that all have 1000's of results.

The loop to call the API seems to be ok, batches of 20 every 5 minutes works fine. My only concern is 1000's of mysql INSERTs for each user (with a long pause between each user for fresh API calls)

Is there a good way to do this? Or am I doing it a good way?!

答:
Database abstraction layers usually add a pretty decent amount of overhead. I've found that, in PHP atleast, it's much easier to use a plain mysql_query for the sake of speed than it is to optimize your library of choice.

Like Eric P and weinzierl.name have said, using a multi-row insert or LOAD will give you the best direct performance.

ContentLicense: CC BY-SA 2.5

Title: INSERT 6000 Rows - best practice

OwnerDisplayName: whichdan


问:
Responsive 9:16 HTML video element on iOS
I want to make a 9:16 video responsive with dynamic content below. I want the full container to take up the height of the screen, and then the video to scale based on the height / # of the items below it. How can I make this happen?

I've tried doing this with flexbox, but on iOS safari, the video takes up the full width of the container which means it doesn't respect the height of the container and pushes the items below the fold.

```<code>    <div
      className="flex flex-col"
      style={{
        height: window.innerHeight,
      }}
    >
      <div className="flex-1 bg-gray-500">
        <video
          src="https://assets.mixkit.co/videos/preview/mixkit-tree-with-yellow-flowers-1173-large.mp4"
          autoPlay
          playsInline
        ></video>
      </div>
      <div>foo</div>
      <div>bar</div>
      <div>baz</div>
    </div>
</code>```

This is in JSX, but I couldn't get it to work in vanilla HTML either.

答:
I had more success using grid rather than flex - defining the column to have 4 rows, all being auto except the first one.

The video is placed absolutely with height of 100%.

This snippet is a pure HTML/CSS version (with a bit of JS to set the height to window.innerHeight as in the question's code).

Tested on Safari IOS 15 on iPad.

const container = document.querySelector('.container');
container.style.height = window.innerHeight + 'px';```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.container {
  display: grid;
  grid-template-columns: 1fr;
  grid-template-rows: 1fr auto auto auto;
}

.video {
  background: gray;
  position: relative;
}

video {
  position: absolute;
  height: 100%;
}</code>```

      <video src="https://assets.mixkit.co/videos/preview/mixkit-tree-with-yellow-flowers-1173-large.mp4" autoplay playsinline></video>

foo

bar

baz

```

Body:
I want to make a 9:16 video responsive with dynamic content below. I want the full container to take up the height of the screen, and then the video to scale based on the height / # of the items below it. How can I make this happen?

I've tried doing this with flexbox, but on iOS safari, the video takes up the full width of the container which means it doesn't respect the height of the container and pushes the items below the fold.

        <video
          src="https://assets.mixkit.co/videos/preview/mixkit-tree-with-yellow-flowers-1173-large.mp4"
          autoPlay
          playsInline
        ></video>

foo

bar

baz

This is in JSX, but I couldn't get it to work in vanilla HTML either.

Body:
I had more success using grid rather than flex - defining the column to have 4 rows, all being auto except the first one.

The video is placed absolutely with height of 100%.

This snippet is a pure HTML/CSS version (with a bit of JS to set the height to window.innerHeight as in the question's code).

Tested on Safari IOS 15 on iPad.

const container = document.querySelector('.container');
container.style.height = window.innerHeight + 'px';

.container {
  display: grid;
  grid-template-columns: 1fr;
  grid-template-rows: 1fr auto auto auto;
}

.video {
  background: gray;
  position: relative;
}

video {
  position: absolute;
  height: 100%;
}

<div class="container">
  <div class="video">
    <div class="sub">
      <video src="https://assets.mixkit.co/videos/preview/mixkit-tree-with-yellow-flowers-1173-large.mp4" autoplay playsinline></video></div>
  </div>
  <div>foo</div>
  <div>bar</div>
  <div>baz</div>
</div>


问:
Unity HDRP Lighting way too bright but there is no light source
Alright so I spent hours working on a scene in unity HDRP but now the scene is overwhelmingly bright and I've literally deleted the direction light and its still so bright. Spent the last 5 hours trying to find a fix but can't. Can someone please chime in?

答: You can turn off Sky Reflection in your HDRP settings - How you find it in the project settings.</p>


问:
how do you clear the outlook addon | add ins cache via browser?
I am developing an outlook officejs add on. When we remove and re-add the add on, it often caches the old files and doesnt over write even though the manifest has an incriminating ver number or/and the GUID is changed.

I found this link to remove the cache on the local box if using the client, but what if you're using the browser? This doesnt seem to work.

https://learn.microsoft.com/en-us/office/dev/add-ins/testing/clear-cache

The same question was asked in 2020 with no solution (I have tested all these steps) How to clean the cache of Outlook add-ins?

答: There is no way to clear the cache from the web add-in. Instead, you may consider using mime headers for caching control of your files by the browser on the end user machines. Read more about that in the HTTP caching and Cache-Control pages on MDN.</p>


问:
How can I set src and alt attributes on an image tag using JavaScript
JavaScript is something that I am learning bit by bit, so please excuse my ignorance...!

I have a list of images in a gallery, and I am creating a modal on a click event. I have managed to collect all of the sources for the images into an array and have then used the forEach method to appended an li and img tag into a parent ul, with all of the sources going into the src attribute.

My problem is I also have an array of alt attributes as well that I also need to set into the same list of images.

I don't think I can do both attributes in one forEach loop, and it seems too messy to do a second loop for the alt attributes. There must be a simpler way, it's just beyond my current understanding.

Here is the code I already have below, I was wondering if perhaps I should be looking at a JSON object instead rather than this approach?

```<code> $('.gallery-image img').click(function(){
            $('.modal').addClass('show');
            var images = document.getElementsByClassName('aurora-gallery-image');
            var imageSources = [];
            var imageTitles = [];
            for (var i = 0; i < images.length; i++) {
                 imageSources.push(images[i].src);
                 imageTitles.push(images[i].alt);
            }
           imageSources.forEach(imageFunction);

            function imageFunction(item){
               $('.image-modal ul').append('<li class="image-modal-item"><img class="modal-content" alt="" src="' + item + '" /><p id="aurora-gallery-image-title">  </p></li>');
            }

      });

</code>```

答:
forEach() passes the array index as the second argument to the callback function. You can use that to get the corresponding element from the imageTitles array

```<code>function imageFunction(item, index){
  $('.image-modal ul').append(`<li class="image-modal-item"><img class="modal-content" alt="${imageTitles[i]}" src="${item}" /><p id="aurora-gallery-image-title">  </p></li>`);
}
</code>```

But you don't really need the arrays at all. Just do it in the for loop:

```<code>for (let i = 0; i < images.length; i++) {
  $('.image-modal ul').append(`<li class="image-modal-item"><img class="modal-content" alt="${images[i].alt}" src="${images[i].src}" /><p id="aurora-gallery-image-title">  </p></li>`);
}
</code>```

Body:
JavaScript is something that I am learning bit by bit, so please excuse my ignorance...!

I have a list of images in a gallery, and I am creating a modal on a click event. I have managed to collect all of the sources for the images into an array and have then used the forEach method to appended an li and img tag into a parent ul, with all of the sources going into the src attribute.

My problem is I also have an array of alt attributes as well that I also need to set into the same list of images.

I don't think I can do both attributes in one forEach loop, and it seems too messy to do a second loop for the alt attributes. There must be a simpler way, it's just beyond my current understanding.

Here is the code I already have below, I was wondering if perhaps I should be looking at a JSON object instead rather than this approach?

 $('.gallery-image img').click(function(){
            $('.modal').addClass('show');
            var images = document.getElementsByClassName('aurora-gallery-image');
            var imageSources = [];
            var imageTitles = [];
            for (var i = 0; i < images.length; i++) {
                 imageSources.push(images[i].src);
                 imageTitles.push(images[i].alt);
            }
           imageSources.forEach(imageFunction);

            function imageFunction(item){
               $('.image-modal ul').append('

');
            }

      });

Body:
forEach() passes the array index as the second argument to the callback function. You can use that to get the corresponding element from the imageTitles array

function imageFunction(item, index){
  $('.image-modal ul').append(`<li class="image-modal-item"><img class="modal-content" alt="${imageTitles[i]}" src="${item}" /><p id="aurora-gallery-image-title">  </p></li>`);
}

But you don't really need the arrays at all. Just do it in the for loop:

for (let i = 0; i < images.length; i++) {
  $('.image-modal ul').append(`<li class="image-modal-item"><img class="modal-content" alt="${images[i].alt}" src="${images[i].src}" /><p id="aurora-gallery-image-title">  </p></li>`);
}


问:
Sliding an image from top of a stack of images
I want to create a stack of images like that of spotify design homepage (https://spotify.design/)
and remove them one by one on a set of timer. I have looked around everywhere but to no help. Can anyone send me a tutorial or some sort of help I'll be so glad.</p>

答:
This is hard to answer without knowing your abilities, but I would look into the z-index css properties and conditional rendering. each card can be at a different z-index and a function on a timer would pop the last one off, setting state to stop it from rendering conditionally.

representing the stack of cards in an array would make it easy to keep track of.


问:
Vue array undefined
I recently work on my team project that uses vue3. I am still trying to get used to vue component and api, so please excuse me for asking such a simple question. I was working on this page where I was supposed to filter objects out of an array that I computed the data (using the computed method) and use the data info in another function called filterItem. Before I use the function filterItem, everything in the data (issue) worked fine as I console logged the object, but when I passed the data in the function and parsed the array, I got an undefined array. But if do a small edit (like a space) and save the file then the local server would rebuild and rerun the server then I would see all of the objects in the array (issue.value), I was wondering why this happen and is there a way to work around this?

start local server

small edit in code and save, local server rebuild with this

Vue single component

```<code><template >
  <div class="relative bg-container-bg px-8 py-2">
    <div v-for="log in issue" :key="log">
     <div class="flex px-0.5 bg-container-bg py-4" v-if="log.failure_type === 'machine'">
       <h1 class="myText px-3 rounded-lg ">Machine</h1>
       <!-- <h1 v-for="item in filterItems(issue)" :key="item.key"></h1> -->
       <!-- {{log.failure_type}} -->
     </div>
    </div>
  <VueGoodTable
    class="issue-table m-0.5"
    v-bind:columns="headers"
    v-bind:rows="issue"
    v-bind:sort-options="{enabled: false}"
  >
    <template v-slot:table-row="props">
        <button
          class="
          px-3 py-1
          bg-gray-500
          text-white
          rounded-md
          text-sm hover:bg-black focus:outline-none"
          v-if="props.column.field == 'analysis'"
          v-bind:value="props.row.issue_id"
          v-on:click="onEdit"
        >
          Edit
        </button>
    </template>
  </VueGoodTable>
  </div>
</template>

 <script lang='ts'>
   const headers = [
    {
      label: 'Issue ID',
      field: 'issue_id',
    },
    {
      label: 'Part ID',
      field: 'part_id',
    },
    {
      label: 'Station ID',
      field: 'station_id',
    },
    {
      label: 'Description',
      field: 'description',
    },
    {
      label: 'Timestamp',
      field: 'timestamp',
    },
    {
      label: 'SN',
      field: 'serial_number',
    },
    {
      label: 'Failure Type',
      field: 'failure_type',
    },
    {
      label: 'Analysis',
      field: 'analysis'
    },
  ]
 </script>

<script setup lang='ts'>
  import router from '../../router/index'
  import { useStore } from 'vuex'
  import { computed, onMounted, watch, ref} from 'vue'
  import { VueGoodTable } from 'vue-good-table-next'
  import datetime_prettify from '../../utils/datetime_prettify'
  const store = useStore()

  const onEdit = (event: any) => {
    store.commit('UPDATE_SELECTED_ISSUE', event.target.value)
    router.push({name: 'Issue Analysis'})
  }

  onMounted(async () => {
    // console.log('state', store.getters.selected_issue_id)
    // console.log('test getter', store.getters.test('cus message'))
    store.dispatch('fetch_issue');
  })

  const issue = computed(() => {
    const data=store.getters.get_issue
    const update_data=data.map((elem:any) => {
      const d1=elem.raised_time_1
      const d2=elem.raised_time_2

      if(d1===d2) {

        return { ...elem, timestamp: datetime_prettify(d1) }
      } else {
        return { ...elem, timestamp: `Start: ${datetime_prettify(d1)} \n\n End: ${datetime_prettify(d2)}` }
      }
    })
    return update_data
  })

  function filterItems (logs:any){
    let objects = Array<any>()
    //for testing purposes on why logs.value is empt
    if(logs.value.length > 0){
      console.log("logs.value is not empty")
      for (let i = 0; i < logs.value.length; i++) {
        objects.push(logs.value[i])
      }
    }

    if (logs.value.length === 0)console.log("value.log is empty")
    return objects
  }

  console.log("before passing issue to filterItems\n", issue)
  console.log("passing issue to filterItems\n",filterItems(issue))
  console.log("passing Value: [{}] to filterItem\n", filterItems({value:[{}]}))
  console.log("Test issue.value\n", issue.value)
  console.log("Test store.getters.get_issue\n", store.getters.get_issue)

</script>

<style>
.myText {
  color: rgb(235, 168, 52);
  background-color: rgb(255, 230, 189);
}
.issue-table tbody span{
  font-size: 13px;
}

</style>
</code>```

答:
UPDATE:

I figured it out now since the function that I made (filterItem) does not have a reactive property so by making a new computed property and having the computed method return the function, in term solve the issue of having an empty array in the data 'issue'

Title: Vue array undefined

Body:
I recently work on my team project that uses vue3. I am still trying to get used to vue component and api, so please excuse me for asking such a simple question. I was working on this page where I was supposed to filter objects out of an array that I computed the data (using the computed method) and use the data info in another function called filterItem. Before I use the function filterItem, everything in the data (issue) worked fine as I console logged the object, but when I passed the data in the function and parsed the array, I got an undefined array. But if do a small edit (like a space) and save the file then the local server would rebuild and rerun the server then I would see all of the objects in the array (issue.value), I was wondering why this happen and is there a way to work around this?

start local server

small edit in code and save, local server rebuild with this

Vue single component

<template >

Machine

  <VueGoodTable
    class="issue-table m-0.5"
    v-bind:columns="headers"
    v-bind:rows="issue"
    v-bind:sort-options="{enabled: false}"
  >
    <template v-slot:table-row="props">
        <button
          class="
          px-3 py-1
          bg-gray-500
          text-white
          rounded-md
          text-sm hover:bg-black focus:outline-none"
          v-if="props.column.field == 'analysis'"
          v-bind:value="props.row.issue_id"
          v-on:click="onEdit"
        >
          Edit
        </button>
    </template>
  </VueGoodTable>

</template>


问:
How do I add text to the side of an image in HTML
I'm trying to add text to the side of an image (more of an oval) in HTML, does anyone know how?

答:
```<code><div>
   <Img src='' style='float:left' />
   <span>Some text</span>
</div>
</code>```


问:
Powershell Function with multiple parameters not accepting second pram
Trying to create a function that checks if you have a module installed along with that module being a minimum version. I have gotten it to work as a stand-alone check but when I try to make it function so that I don't have to have it repeated over and over when I have to check for multiple modules it fails the check for second input the version.</p>
```<code>#Check if Module is avaiable
Function Module-Check {
#Set Pramatators
Param(
    [Parameter(
        Mandatory=$true,
        Position=0,
        HelpMessage="Enter the Modules name has show in Powershell",
        ParameterSetName="Module Name")]
    [string]
        $ModuleName,

    [Parameter(
        Mandatory=$true,
        Position=1,
        HelpMessage="Enter the Modules Major Version Required has show in Powershell",
        ParameterSetName="Major Version")]
    [string]
        $ModuleVersion
        )

$ModuleAvaiable = Get-Module -ListAvailable | Select Name,Version | Where-Object {$_.name -eq "$ModuleName"}

if ($ModuleAvaiable.Name.Count -eq '0') {
Write-Host -ForegroundColor Red "$ModuleName Module is not available on this computer"
$InstallModule=Read-Host "Would you like to install it now (Y)es or (N)o"
    Switch -Wildcard($InstallModule)
    {
        "Y*" {$Action= Write-host "Importing $ModuleName Module"
           Install-Module -Name "$ModuleName"}
        "N*" {$Action= Write-host -ForegroundColor Yellow "Functions in the Powershell rely on This module and will not be able to function PS will now exit"
            break
            }
        Default {$Action= Write-Host "No input selected ending script"
                break}
        }
    return $Action
}
else {
Write-Host "$ModuleName" $ModuleAvaiable.Version"is Avaiable on this computer"
$RequiredVersion = ($ModuleAvaiable.Version.Major -ge $ModuleVersion)
    if ($RequiredVersion = $true) {
    }
else {
    Write-Host -ForegroundColor Yellow "$ModuleName Module Version installed does not meet the required mimium version (version $ModuleVersion.X)"
    $UpdateModule=Read-Host "Update the Module version now (Y)es or (N)o"
        switch -Wildcard ($UpdateModule)
        {
        "Y*" {$Action2= Write-host "Update $ModuleName Module"
            update-Module -Name "$ModuleName"}
        "N*" {$Action2= Write-host -ForegroundColor Yellow "Functions in the Powershell rely on this module and may not function properly with a lower version installed"

            }
        Default {$Action2= Write-Host "No input selected updating ALL Modules"
                foreach ($module in Get-InstalledModule) {
                    Get-InstalledModule $module.Name -AllVersions |
                    Where-Object Version -ne $module.Version |
                    Uninstall-Module
                                                            }
                }
        }
    Return $Action2

     }
  }
}

</code>```

答:
You are not understanding ParameterSetName and Mandatory.  The code below is from one of over a dozen functions I've been working on.

It allows for:

$KeyPath by itself - Parameter set KHK

$KeyPath with only one of the six data types - Parameter sets BVE, DVE, EVE, MVE, QVE, and SVE

$Keypath with $ValueName and only one of the six data types - Parameter sets BVN, DVN, EVN, MVN, QVN, and SVN

Near the top you can see that 'KHK' is the default parameter set.  If you look at $KeyPath, it is mandatory for all parameter sets, so specifying only $KeyPath results in 'KHK'.  But if you look at $ValueName, it is mandatory for all the parameter sets that end in the letters 'VN', this also means you will need to include a data type parameter with $ValueName.  The VN stands for $ValueName.

In my scheme I'm using the first letter as the type of data that will be written to the registry.  And you can see below that each data type has those parameter sets that match.  Binary requires 'B', PSInt/$RegDWord requires 'D', and so on.

The goal is to make it mandatory for certain parameters to be in the same set, while others are excluded.  What may not be obvious in this code is the fact that specifying only $KeyPath and $RegDWord will result in 'DVE' since $ValueName wasn't included, but adding $ValueName to the parameters results in 'DVN'. But what should be hopefully be obvious is that once $RegDWord is provided, no other data type parameter is allowed since they do not share any of the same parameter sets.

Also, at the bottom of the code is included a way to break the resulting ParametSetName into two, so it can be known if $ValueName was provided and what data type was provided.

Sorry if this code is a bit much to chew on for someone still new to parameter sets, but it is one of the best real world examples I know of for showing what can be done.  I'm sure there are examples out there, but I didn't find them when I was trying to figure this out myself.

One last thing, what isn't shown in the code is that you can have a parameter that is part of a parameter set, but not mandatory.  This means that this "parameter set" does not require that parameter.  Think of it this way, you cannot have a certain "parameter set" become active UNLESS all of its mandatory parameters are provided.  I might add, there is a limit to how many parameter sets you can have, I think it is around two and half to three times what is in this example - yeah, I hit that wall!

```<code>Function Set-Reg {
    [CmdletBinding(DefaultParameterSetName = 'KHK')]
    Param(
        [Parameter(Mandatory = $true, Position = 0)]
        [string]$KeyPath,

        [Parameter(Mandatory, ParameterSetName = 'BVN')]
        [Parameter(Mandatory, ParameterSetName = 'DVN')]
        [Parameter(Mandatory, ParameterSetName = 'EVN')]
        [Parameter(Mandatory, ParameterSetName = 'MVN')]
        [Parameter(Mandatory, ParameterSetName = 'QVN')]
        [Parameter(Mandatory, ParameterSetName = 'SVN')]
        [AllowEmptyString()]
        [Alias("v")]
        [string]$ValueName,

        [Parameter(Mandatory, ParameterSetName = 'BVE')]
        [Parameter(Mandatory, ParameterSetName = 'BVN')]
        [Alias("PSBytes")]
        [byte[]]$RegBinary,
        [Parameter(Mandatory, ParameterSetName = 'DVE')]
        [Parameter(Mandatory, ParameterSetName = 'DVN')]
        [Alias("PSInt")]
        [int]$RegDWord,
        [Parameter(Mandatory, ParameterSetName = 'EVE')]
        [Parameter(Mandatory, ParameterSetName = 'EVN')]
        [AllowEmptyString()]
        [Alias("PSEString")]
        [string]$RegExpandString,
        [Parameter(Mandatory, ParameterSetName = 'MVE')]
        [Parameter(Mandatory, ParameterSetName = 'MVN')]
        [Alias("PSStrings")]
        [string[]]$RegMultiString,
        [Parameter(Mandatory, ParameterSetName = 'QVE')]
        [Parameter(Mandatory, ParameterSetName = 'QVN')]
        [Alias("PSLong")]
        [long]$RegQWord,
        [Parameter(Mandatory, ParameterSetName = 'SVE')]
        [Parameter(Mandatory, ParameterSetName = 'SVN')]
        [AllowEmptyString()]
        [Alias("PSString")]
        [string]$RegString,
        [switch]$x32
    )
    # ve: default string "(value not set)"
    $SetNames = [PSCustomObject]@{
        Type = $PsCmdlet.ParameterSetName.Substring(0, 1)
        Mode = $PsCmdlet.ParameterSetName.Substring(1, 2)
    }
</code>```

Body:
Trying to create a function that checks if you have a module installed along with that module being a minimum version. I have gotten it to work as a stand-alone check but when I try to make it function so that I don't have to have it repeated over and over when I have to check for multiple modules it fails the check for second input the version.

#Check if Module is avaiable
Function Module-Check {
#Set Pramatators
Param(
    [Parameter(
        Mandatory=$true,
        Position=0,
        HelpMessage="Enter the Modules name has show in Powershell",
        ParameterSetName="Module Name")]
    [string]
        $ModuleName,

    [Parameter(
        Mandatory=$true,
        Position=1,
        HelpMessage="Enter the Modules Major Version Required has show in Powershell",
        ParameterSetName="Major Version")]
    [string]
        $ModuleVersion
        )

$ModuleAvaiable = Get-Module -ListAvailable | Select Name,Version | Where-Object {$_.name -eq "$ModuleName"}

if ($ModuleAvaiable.Name.Count -eq '0') {
Write-Host -ForegroundColor Red "$ModuleName Module is not available on this computer"
$InstallModule=Read-Host "Would you like to install it now (Y)es or (N)o"
    Switch -Wildcard($InstallModule)
    {
        "Y*" {$Action= Write-host "Importing $ModuleName Module"
           Install-Module -Name "$ModuleName"}
        "N*" {$Action= Write-host -ForegroundColor Yellow "Functions in the Powershell rely on This module and will not be able to function PS will now exit"
            break
            }
        Default {$Action= Write-Host "No input selected ending script"
                break}
        }
    return $Action
}
else {
Write-Host "$ModuleName" $ModuleAvaiable.Version"is Avaiable on this computer"
$RequiredVersion = ($ModuleAvaiable.Version.Major -ge $ModuleVersion)
    if ($RequiredVersion = $true) {
    }
else {
    Write-Host -ForegroundColor Yellow "$ModuleName Module Version installed does not meet the required mimium version (version $ModuleVersion.X)"
    $UpdateModule=Read-Host "Update the Module version now (Y)es or (N)o"
        switch -Wildcard ($UpdateModule)
        {
        "Y*" {$Action2= Write-host "Update $ModuleName Module"
            update-Module -Name "$ModuleName"}
        "N*" {$Action2= Write-host -ForegroundColor Yellow "Functions in the Powershell rely on this module and may not function properly with a lower version installed"

            }
        Default {$Action2= Write-Host "No input selected updating ALL Modules"
                foreach ($module in Get-InstalledModule) {
                    Get-InstalledModule $module.Name -AllVersions |
                    Where-Object Version -ne $module.Version |
                    Uninstall-Module
                                                            }
                }
        }
    Return $Action2

     }
  }
}

Body:
You are not understanding ParameterSetName and Mandatory.  The code below is from one of over a dozen functions I've been working on.

It allows for:

$KeyPath by itself - Parameter set KHK

$KeyPath with only one of the six data types - Parameter sets BVE, DVE, EVE, MVE, QVE, and SVE

$Keypath with $ValueName and only one of the six data types - Parameter sets BVN, DVN, EVN, MVN, QVN, and SVN

Near the top you can see that 'KHK' is the default parameter set.  If you look at $KeyPath, it is mandatory for all parameter sets, so specifying only $KeyPath results in 'KHK'.  But if you look at $ValueName, it is mandatory for all the parameter sets that end in the letters 'VN', this also means you will need to include a data type parameter with $ValueName.  The VN stands for $ValueName.

In my scheme I'm using the first letter as the type of data that will be written to the registry.  And you can see below that each data type has those parameter sets that match.  Binary requires 'B', PSInt/$RegDWord requires 'D', and so on.

The goal is to make it mandatory for certain parameters to be in the same set, while others are excluded.  What may not be obvious in this code is the fact that specifying only $KeyPath and $RegDWord will result in 'DVE' since $ValueName wasn't included, but adding $ValueName to the parameters results in 'DVN'. But what should be hopefully be obvious is that once $RegDWord is provided, no other data type parameter is allowed since they do not share any of the same parameter sets.

Also, at the bottom of the code is included a way to break the resulting ParametSetName into two, so it can be known if $ValueName was provided and what data type was provided.

Sorry if this code is a bit much to chew on for someone still new to parameter sets, but it is one of the best real world examples I know of for showing what can be done.  I'm sure there are examples out there, but I didn't find them when I was trying to figure this out myself.

One last thing, what isn't shown in the code is that you can have a parameter that is part of a parameter set, but not mandatory.  This means that this "parameter set" does not require that parameter.  Think of it this way, you cannot have a certain "parameter set" become active UNLESS all of its mandatory parameters are provided.  I might add, there is a limit to how many parameter sets you can have, I think it is around two and half to three times what is in this example - yeah, I hit that wall!

Function Set-Reg {
    [CmdletBinding(DefaultParameterSetName = 'KHK')]
    Param(
        [Parameter(Mandatory = $true, Position = 0)]
        [string]$KeyPath,

        [Parameter(Mandatory, ParameterSetName = 'BVN')]
        [Parameter(Mandatory, ParameterSetName = 'DVN')]
        [Parameter(Mandatory, ParameterSetName = 'EVN')]
        [Parameter(Mandatory, ParameterSetName = 'MVN')]
        [Parameter(Mandatory, ParameterSetName = 'QVN')]
        [Parameter(Mandatory, ParameterSetName = 'SVN')]
        [AllowEmptyString()]
        [Alias("v")]
        [string]$ValueName,

        [Parameter(Mandatory, ParameterSetName = 'BVE')]
        [Parameter(Mandatory, ParameterSetName = 'BVN')]
        [Alias("PSBytes")]
        [byte[]]$RegBinary,
        [Parameter(Mandatory, ParameterSetName = 'DVE')]
        [Parameter(Mandatory, ParameterSetName = 'DVN')]
        [Alias("PSInt")]
        [int]$RegDWord,
        [Parameter(Mandatory, ParameterSetName = 'EVE')]
        [Parameter(Mandatory, ParameterSetName = 'EVN')]
        [AllowEmptyString()]
        [Alias("PSEString")]
        [string]$RegExpandString,
        [Parameter(Mandatory, ParameterSetName = 'MVE')]
        [Parameter(Mandatory, ParameterSetName = 'MVN')]
        [Alias("PSStrings")]
        [string[]]$RegMultiString,
        [Parameter(Mandatory, ParameterSetName = 'QVE')]
        [Parameter(Mandatory, ParameterSetName = 'QVN')]
        [Alias("PSLong")]
        [long]$RegQWord,
        [Parameter(Mandatory, ParameterSetName = 'SVE')]
        [Parameter(Mandatory, ParameterSetName = 'SVN')]
        [AllowEmptyString()]
        [Alias("PSString")]
        [string]$RegString,
        [switch]$x32
    )
    # ve: default string "(value not set)"
    $SetNames = [PSCustomObject]@{
        Type = $PsCmdlet.ParameterSetName.Substring(0, 1)
        Mode = $PsCmdlet.ParameterSetName.Substring(1, 2)
    }