问:
Click an item in autocomplete list with VBA and HTML
I've created an automation where it will allow me to enter details on a website (though I cannot share it as it is internal). My code below is working only until it enters a text on "received from". However, this "received from" field has an autocomplete list and I need to select it in order to populate other fields such as TIN and Address.

The autocomplete list is quite similar with the one in
https://jqueryui.com/autocomplete/
or http://demos.codexworld.com/autocomplete-textbox-using-jquery-php-mysql/

Below is my code:

```<code>Sub Automate_IE_Enter_Data()
'This will load a webpage in IE
Dim i               As Long
Dim Url             As String
Dim IE              As InternetExplorer
Dim objElement      As Object
Dim objCollection   As Object
Dim HWNDSrc         As Long
Dim wsTemplate      As Worksheet
Dim objEvent        As Object
Dim li_arr          As Variant
Dim NodeList        As Object
Dim x               As Long

Set wsTemplate = ThisWorkbook.Sheets("Template")

'Create InternetExplorer Object
Set IE = New InternetExplorerMedium

'Set IE.Visible = True to make IE visible, or False for IE to run in the background
IE.Visible = True

'Define URL by getting the value in rngURL; can be found in the main sheet
Url = "http://URL Path"

'Navigate to URL
IE.Navigate Url

' Statusbar let's user know website is loading
Application.StatusBar = Url & " is loading. Please wait..."

Do
DoEvents
Loop Until IE.ReadyState = READYSTATE_COMPLETE

'Webpage Loaded
Application.StatusBar = Url & " Loaded"

'Get Window ID for IE so we can set it as activate window
HWNDSrc = IE.hwnd
'Set IE as Active Window
SetForegroundWindow HWNDSrc
ShowWindow IE.hwnd, SW_SHOWMAXIMIZED

Dim Doc As HTMLDocument
Set Doc = IE.document

inputString = "Nuevo"

With Doc.getElementById("supName")

    .Focus
    SendKeys inputString 'Trigger the field to show autocomplete list

End With

'----THIS IS WHERE I AM TRYING TO CLICK THE AUTOCOMPLETE LIST THAT IS BEING DISPLAYED-----
'-----HOWEVER, CLICKING DOESN'T SEEM TO WORK.-----

Set NodeList = Doc.querySelectorAll(".ui-active-menuitem[role=""menuitem""]")

For x = 0 To NodeList.Length - 1
'Debug.Print NodeList.Item(x).Click '<==this way
NodeList.Item(x).Focus
NodeList(x).Click   '<==Or this method

Next x

MsgBox "Done"

'Unload IE
endmacro:
Set IE = Nothing
Set objElement = Nothing
Set objCollection = Nothing

End Sub
</code>```

Below is the HTML which I think would be helpful to understand my issue:

```<code>'----- NAME OF THE FIELD THAT HAS AN AUTOCOMPLETE LIST----
<INPUT name=supName class="required-placeholder simple-placeholder ui-autocomplete-input placeholding" id=supName role=textbox aria-haspopup=true aria-autocomplete=list type=text value=Required jQuery17102032699680461189="39" placeholder="Required" autocomplete="off">

<UL class="ui-autocomplete ui-menu ui-widget ui-widget-content ui-corner-all" role=listbox aria-activedescendant=ui-active-menuitem style="WIDTH: 400px; LEFT: 751px; Z-INDEX: 1; DISPLAY: none; TOP: 287px" jQuery17102032699680461189="42"><LI class=ui-menu-item role=menuitem jQuery17102032699680461189="104"><A tabIndex=-1 class=ui-corner-all jQuery17102032699680461189="114">List 0</A></LI>

<LI class=ui-menu-item role=menuitem jQuery17102032699680461189="105"><A tabIndex=-1 class=ui-corner-all jQuery17102032699680461189="115">List 1</A></LI>
<LI class=ui-menu-item role=menuitem jQuery17102032699680461189="106"><A tabIndex=-1 class=ui-corner-all jQuery17102032699680461189="116">List 2</A></LI>
<LI class=ui-menu-item role=menuitem jQuery17102032699680461189="107"><A tabIndex=-1 class=ui-corner-all jQuery17102032699680461189="117">List 3</A></LI>
<LI class=ui-menu-item role=menuitem jQuery17102032699680461189="108"><A tabIndex=-1 class=ui-corner-all jQuery17102032699680461189="118">List 4</A></LI>
<LI class=ui-menu-item role=menuitem jQuery17102032699680461189="109"><A tabIndex=-1 class=ui-corner-all jQuery17102032699680461189="119">List 5</A></LI>
<LI class=ui-menu-item role=menuitem jQuery17102032699680461189="110"><A tabIndex=-1 class=ui-corner-all jQuery17102032699680461189="120">List 6</A></LI>
<LI class=ui-menu-item role=menuitem jQuery17102032699680461189="111"><A tabIndex=-1 class=ui-corner-all jQuery17102032699680461189="121">List 7</A></LI>
<LI class=ui-menu-item role=menuitem jQuery17102032699680461189="112"><A tabIndex=-1 class=ui-corner-all jQuery17102032699680461189="122">List 8</A></LI>
<LI class=ui-menu-item role=menuitem jQuery17102032699680461189="113"><A tabIndex=-1 class=ui-corner-all jQuery17102032699680461189="123">List 9</A></LI></UL>
</code>```

A sample screenshot of autocomplete list:

More of the HTML:

  <FORM id=receiptEntryForm action=/ReceiptEntry/SaveReceipt method=post jQuery17109198838813964318="40">

          OR No:
          Date:
          Received From:
          TIN:
          Address:

          <INPUT name=ReceiptNumber disabled id=ReceiptNumber type=text data-val-required="The ReceiptNumber field is required." data-val-number="The field ReceiptNumber must be a number." data-val="true">

          <INPUT name=printDate class="datepicker hasDatepicker" id=printDate type=text jQuery17109198838813964318="38">

          <INPUT name=supName class="required-placeholder simple-placeholder ui-autocomplete-input placeholding" id=supName role=textbox aria-haspopup=true aria-autocomplete=list type=text value=Required jQuery17109198838813964318="39" placeholder="Required" autocomplete="off">

          <INPUT name=SupplierCode id=SupplierCode type=hidden data-val-required="The SupplierCode field is required." data-val="true" data-val-length-max="20" data-val-length="You've reached the maximum length allowed.">

          <INPUT name=SupTIN class="required-placeholder placeholding simple-placeholder" id=SupTIN type=text value=Required jQuery17109198838813964318="41" placeholder="Required" ,>

          <TEXTAREA name=SupAdd class="textarea-wide required-placeholder" id=SupAdd rows=3 cols=48 placeholder="Required"></TEXTAREA>

        The sum of ****:

          Receipt Type:
          VATable Receipt:

IN PAYMENT OF

          <SELECT id=receiptentry-type jQuery17109198838813964318="36">
            <OPTION value=cr selected>Collection Receipt</OPTION>
            <OPTION value=or>Official Receipt</OPTION>
          </SELECT>

          <INPUT disabled id=chk-vatable type=checkbox jQuery17109198838813964318="37">

                  INVOICE NO.
                  AMOUNT
                  FORM OF PAYMENT
                  AMOUNT

                  CASH

                  BANK
                  CHECK NO.
                  DATE

                  TOTAL

      THIS CANCELS OUR P.R.#
      <INPUT name=CancelPrNo id=CancelPrNo type=text data-val="true" data-val-length-max="50" data-val-length="You've reached the maximum length allowed.">
      <INPUT class="right button-style" id=add-receipt type=button value=Add jQuery17109198838813964318="43">

  </FORM>

```

<p><strong>Chrome Console:</strong> </p>

<p><img src="https://i.stack.imgur.com/OuDR7.png" alt="enter image description here"></p>

<p><strong>Inspect element of autocomplete list:</strong> </p>

```

*TEXT RESULT OF THE AUTOCOMPLETE LIST*

```

答:
I hope the example page is real quite similar to your page. I used it to show how you can deal with those things. What you need to have in your head is thinking about the dynamik of a page. I have commented on the macro in detail. Please read everything carefully to understand it. The solution consists of the following 3 parts. Copy all into one module.

First: A method to make breaks less than a second. We can do that with a Windows api function:

```<code>'With the following Windows api function we can do breaks less than 1 second
'It works with Excel 32 bit an Excel 64 bit
#If Win64 Then
  'For 64 Bit Systems
  Public Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As LongPtr)
#Else
  'For 32 Bit Systems
  Public Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
#End If
</code>```

Second: The main part which clicks through the pop-up menu

```<code>Sub JQueryAutocomplete()

  Dim url As String
  Dim browser As Object
  Dim nodeInput As Object
  Dim nodeUi As Object
  Dim nodeLi As Object
  Dim countOfLi As Long
  Dim controlValue As Long
  Dim searchString As String
  Dim countOfLiDone As Boolean
  Dim result As String

  'Initializing variables and load page
  '-------------------------------------------------------------------------------------------
  'Part of the string to autocomplete
  searchString = "h"

  'The controlValue shows the number of next li-tag in pop-up menu to pass through
  controlValue = 1

  'We use the iFrame document from the JQuery sample page directly
  'So we have less code overhead to reach the point we need in the HTML code
  url = "https://jqueryui.com/resources/demos/autocomplete/default.html"

  'Initialize Internet Explorer, set visibility,
  'call URL and wait until page is fully loaded
  Set browser = CreateObject("internetexplorer.application")
  browser.Visible = True 'You can set this to False because this macro don't use sendkeys()
  browser.navigate url
  Do Until browser.ReadyState = 4: DoEvents: Loop
  '-------------------------------------------------------------------------------------------

  'Try to get textbox for input
  '-------------------------------------------------------------------------------------------
  On Error Resume Next
  Set nodeInput = browser.document.getElementByID("tags")
  On Error GoTo 0

  'Check if nodeInput could be created
  If Not nodeInput Is Nothing Then
    'Loop over all auto completed strings in the pop-up menu
    'Yes, we start the loop before we know anything obout the pop-up menu
    '-----------------------------------------------------------------------------------------
    Do
      'Insert part of search string
      '---------------------------------------------------------------------------------------
      'Everytime we want to place text into the textbox, we must prepare it to react with the
      'pop-up menu. We do this by triggering the input HTML event of the textbox
      '(You do this with sendkeys in your macro. But sendkeys should be avoided if possible)
      Call TriggerEvent(browser.document, nodeInput, "input")

      'Insert text
      nodeInput.Value = searchString

      'Wait briefly to open the pop-up menu
      'It may be that with your computer speed and your internet speed (ping) it must be a
      'larger value or it may be a smaller value. 1 counts 1 millisecond. So 100 is a tenth
      'of a second and 1000 is one second
      Sleep (500)
      '---------------------------------------------------------------------------------------

      'Count generated li tags if not done in the past
      '---------------------------------------------------------------------------------------
      If countOfLiDone = False Then
        'Try to get pop-up menu
        'It may be that there is no pop-up menu if the string does not provide auto-completion
        'It is important to know this to be able to exit the loop
        On Error Resume Next
        Set nodeUi = browser.document.getElementByID("ui-id-1")
        On Error GoTo 0

        'Check if nodeUi could be created
        'If nodeUi couldn't be created, no pop-up menu. The variable countOfLi is 0 by default
        'and less than controlValue, which is 1 by initializing. The termination condition of
        'the loop is thus reached immediately
        If Not nodeUi Is Nothing Then
          'Count li tags in the pop-up
          countOfLi = nodeUi.getElementsByTagName("li").Length
          countOfLiDone = True
        End If
      End If
      '---------------------------------------------------------------------------------------

      'Go on if there is a pop-up menu
      '---------------------------------------------------------------------------------------
      If countOfLi > 0 Then
        'To get the text from the next li tag into the input textbox we must click the li tag
        nodeUi.getElementsByTagName("li")(controlValue - 1).Click

        'Here you can do what you want with the new situation of the page
        '-------------------------------------------------------------------------------------
        'If there come up new contents you need at first a short break after the click for the
        'same reason we wait earlier in the macro, after inserting our searchString
        Sleep (500)

        'I don't know what you want to da but on the example page nothing hapen than the
        'clicked text is now in the input textbox. So we gather all clicks in a string
        'to show something at the end of macro runtime
        result = result & nodeInput.Value & Chr(13)
        '---------------------------------------------------------------------------------------
      End If
      '---------------------------------------------------------------------------------------

      'Prepare next loop pass
      '---------------------------------------------------------------------------------------
      controlValue = controlValue + 1
      '---------------------------------------------------------------------------------------
    Loop Until controlValue > countOfLi
    '-----------------------------------------------------------------------------------------
  Else
    'nodeInput couldn't be created
    result = "Textbox to insert search string not found"
  End If
  '-------------------------------------------------------------------------------------------

  'Clean up
  '-------------------------------------------------------------------------------------------
  browser.Quit
  Set browser = Nothing
  Set nodeInput = Nothing
  Set nodeUi = Nothing
  Set nodeLi = Nothing
  '-------------------------------------------------------------------------------------------

  'Show the result of this demo
  '-------------------------------------------------------------------------------------------
  MsgBox result
  '-------------------------------------------------------------------------------------------
End Sub
</code>```

Third: The function to trigger the HTML event. So you don't need sendkeys()

```<code>Private Sub TriggerEvent(htmlDocument As Object, htmlElementWithEvent As Object, eventType As String)

  Dim theEvent As Object

  htmlElementWithEvent.Focus
  Set theEvent = htmlDocument.createEvent("HTMLEvents")
  theEvent.initEvent eventType, True, False
  htmlElementWithEvent.dispatchEvent theEvent
End Sub
</code>```

Body:
I've created an automation where it will allow me to enter details on a website (though I cannot share it as it is internal). My code below is working only until it enters a text on "received from". However, this "received from" field has an autocomplete list and I need to select it in order to populate other fields such as TIN and Address.

The autocomplete list is quite similar with the one in
https://jqueryui.com/autocomplete/
or http://demos.codexworld.com/autocomplete-textbox-using-jquery-php-mysql/

Below is my code:

Sub Automate_IE_Enter_Data()
'This will load a webpage in IE
Dim i               As Long
Dim Url             As String
Dim IE              As InternetExplorer
Dim objElement      As Object
Dim objCollection   As Object
Dim HWNDSrc         As Long
Dim wsTemplate      As Worksheet
Dim objEvent        As Object
Dim li_arr          As Variant
Dim NodeList        As Object
Dim x               As Long

Set wsTemplate = ThisWorkbook.Sheets("Template")

'Create InternetExplorer Object
Set IE = New InternetExplorerMedium

'Set IE.Visible = True to make IE visible, or False for IE to run in the background
IE.Visible = True

'Define URL by getting the value in rngURL; can be found in the main sheet
Url = "http://URL Path"

'Navigate to URL
IE.Navigate Url

' Statusbar let's user know website is loading
Application.StatusBar = Url & " is loading. Please wait..."

Do
DoEvents
Loop Until IE.ReadyState = READYSTATE_COMPLETE

'Webpage Loaded
Application.StatusBar = Url & " Loaded"

'Get Window ID for IE so we can set it as activate window
HWNDSrc = IE.hwnd
'Set IE as Active Window
SetForegroundWindow HWNDSrc
ShowWindow IE.hwnd, SW_SHOWMAXIMIZED

Dim Doc As HTMLDocument
Set Doc = IE.document

inputString = "Nuevo"

With Doc.getElementById("supName")

    .Focus
    SendKeys inputString 'Trigger the field to show autocomplete list

End With

'----THIS IS WHERE I AM TRYING TO CLICK THE AUTOCOMPLETE LIST THAT IS BEING DISPLAYED-----
'-----HOWEVER, CLICKING DOESN'T SEEM TO WORK.-----

Set NodeList = Doc.querySelectorAll(".ui-active-menuitem[role=""menuitem""]")

For x = 0 To NodeList.Length - 1
'Debug.Print NodeList.Item(x).Click '<==this way
NodeList.Item(x).Focus
NodeList(x).Click   '<==Or this method

Next x

MsgBox "Done"

'Unload IE
endmacro:
Set IE = Nothing
Set objElement = Nothing
Set objCollection = Nothing

End Sub

Below is the HTML which I think would be helpful to understand my issue:

'----- NAME OF THE FIELD THAT HAS AN AUTOCOMPLETE LIST----
<INPUT name=supName class="required-placeholder simple-placeholder ui-autocomplete-input placeholding" id=supName role=textbox aria-haspopup=true aria-autocomplete=list type=text value=Required jQuery17102032699680461189="39" placeholder="Required" autocomplete="off">

List 0

List 1

List 2

List 3

List 4

List 5

List 6

List 7

List 8

List 9

A sample screenshot of autocomplete list:

More of the HTML:

  <FORM id=receiptEntryForm action=/ReceiptEntry/SaveReceipt method=post jQuery17109198838813964318="40">

          OR No:
          Date:
          Received From:
          TIN:
          Address:

          <INPUT name=ReceiptNumber disabled id=ReceiptNumber type=text data-val-required="The ReceiptNumber field is required." data-val-number="The field ReceiptNumber must be a number." data-val="true">

          <INPUT name=printDate class="datepicker hasDatepicker" id=printDate type=text jQuery17109198838813964318="38">

          <INPUT name=supName class="required-placeholder simple-placeholder ui-autocomplete-input placeholding" id=supName role=textbox aria-haspopup=true aria-autocomplete=list type=text value=Required jQuery17109198838813964318="39" placeholder="Required" autocomplete="off">

          <INPUT name=SupplierCode id=SupplierCode type=hidden data-val-required="The SupplierCode field is required." data-val="true" data-val-length-max="20" data-val-length="You&#39;ve reached the maximum length allowed.">

          <INPUT name=SupTIN class="required-placeholder placeholding simple-placeholder" id=SupTIN type=text value=Required jQuery17109198838813964318="41" placeholder="Required" ,>

          <TEXTAREA name=SupAdd class="textarea-wide required-placeholder" id=SupAdd rows=3 cols=48 placeholder="Required"></TEXTAREA>

        The sum of ****:

          Receipt Type:
          VATable Receipt:

IN PAYMENT OF

          <SELECT id=receiptentry-type jQuery17109198838813964318="36">
            <OPTION value=cr selected>Collection Receipt</OPTION>
            <OPTION value=or>Official Receipt</OPTION>
          </SELECT>

          <INPUT disabled id=chk-vatable type=checkbox jQuery17109198838813964318="37">

                  INVOICE NO.
                  AMOUNT
                  FORM OF PAYMENT
                  AMOUNT

                  CASH

                  BANK
                  CHECK NO.
                  DATE

                  TOTAL

      THIS CANCELS OUR P.R.#
      <INPUT name=CancelPrNo id=CancelPrNo type=text data-val="true" data-val-length-max="50" data-val-length="You&#39;ve reached the maximum length allowed.">
      <INPUT class="right button-style" id=add-receipt type=button value=Add jQuery17109198838813964318="43">

  </FORM>

Chrome Console:

Inspect element of autocomplete list:

*TEXT RESULT OF THE AUTOCOMPLETE LIST*

Body:
I hope the example page is real quite similar to your page. I used it to show how you can deal with those things. What you need to have in your head is thinking about the dynamik of a page. I have commented on the macro in detail. Please read everything carefully to understand it. The solution consists of the following 3 parts. Copy all into one module.

First: A method to make breaks less than a second. We can do that with a Windows api function:

'With the following Windows api function we can do breaks less than 1 second
'It works with Excel 32 bit an Excel 64 bit
#If Win64 Then
  'For 64 Bit Systems
  Public Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As LongPtr)
#Else
  'For 32 Bit Systems
  Public Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
#End If

Second: The main part which clicks through the pop-up menu

Sub JQueryAutocomplete()

  Dim url As String
  Dim browser As Object
  Dim nodeInput As Object
  Dim nodeUi As Object
  Dim nodeLi As Object
  Dim countOfLi As Long
  Dim controlValue As Long
  Dim searchString As String
  Dim countOfLiDone As Boolean
  Dim result As String

  'Initializing variables and load page
  '-------------------------------------------------------------------------------------------
  'Part of the string to autocomplete
  searchString = "h"

  'The controlValue shows the number of next li-tag in pop-up menu to pass through
  controlValue = 1

  'We use the iFrame document from the JQuery sample page directly
  'So we have less code overhead to reach the point we need in the HTML code
  url = "https://jqueryui.com/resources/demos/autocomplete/default.html"

  'Initialize Internet Explorer, set visibility,
  'call URL and wait until page is fully loaded
  Set browser = CreateObject("internetexplorer.application")
  browser.Visible = True 'You can set this to False because this macro don't use sendkeys()
  browser.navigate url
  Do Until browser.ReadyState = 4: DoEvents: Loop
  '-------------------------------------------------------------------------------------------

  'Try to get textbox for input
  '-------------------------------------------------------------------------------------------
  On Error Resume Next
  Set nodeInput = browser.document.getElementByID("tags")
  On Error GoTo 0

  'Check if nodeInput could be created
  If Not nodeInput Is Nothing Then
    'Loop over all auto completed strings in the pop-up menu
    'Yes, we start the loop before we know anything obout the pop-up menu
    '-----------------------------------------------------------------------------------------
    Do
      'Insert part of search string
      '---------------------------------------------------------------------------------------
      'Everytime we want to place text into the textbox, we must prepare it to react with the
      'pop-up menu. We do this by triggering the input HTML event of the textbox
      '(You do this with sendkeys in your macro. But sendkeys should be avoided if possible)
      Call TriggerEvent(browser.document, nodeInput, "input")

      'Insert text
      nodeInput.Value = searchString

      'Wait briefly to open the pop-up menu
      'It may be that with your computer speed and your internet speed (ping) it must be a
      'larger value or it may be a smaller value. 1 counts 1 millisecond. So 100 is a tenth
      'of a second and 1000 is one second
      Sleep (500)
      '---------------------------------------------------------------------------------------

      'Count generated li tags if not done in the past
      '---------------------------------------------------------------------------------------
      If countOfLiDone = False Then
        'Try to get pop-up menu
        'It may be that there is no pop-up menu if the string does not provide auto-completion
        'It is important to know this to be able to exit the loop
        On Error Resume Next
        Set nodeUi = browser.document.getElementByID("ui-id-1")
        On Error GoTo 0

        'Check if nodeUi could be created
        'If nodeUi couldn't be created, no pop-up menu. The variable countOfLi is 0 by default
        'and less than controlValue, which is 1 by initializing. The termination condition of
        'the loop is thus reached immediately
        If Not nodeUi Is Nothing Then
          'Count li tags in the pop-up
          countOfLi = nodeUi.getElementsByTagName("li").Length
          countOfLiDone = True
        End If
      End If
      '---------------------------------------------------------------------------------------

      'Go on if there is a pop-up menu
      '---------------------------------------------------------------------------------------
      If countOfLi > 0 Then
        'To get the text from the next li tag into the input textbox we must click the li tag
        nodeUi.getElementsByTagName("li")(controlValue - 1).Click

        'Here you can do what you want with the new situation of the page
        '-------------------------------------------------------------------------------------
        'If there come up new contents you need at first a short break after the click for the
        'same reason we wait earlier in the macro, after inserting our searchString
        Sleep (500)

        'I don't know what you want to da but on the example page nothing hapen than the
        'clicked text is now in the input textbox. So we gather all clicks in a string
        'to show something at the end of macro runtime
        result = result & nodeInput.Value & Chr(13)
        '---------------------------------------------------------------------------------------
      End If
      '---------------------------------------------------------------------------------------

      'Prepare next loop pass
      '---------------------------------------------------------------------------------------
      controlValue = controlValue + 1
      '---------------------------------------------------------------------------------------
    Loop Until controlValue > countOfLi
    '-----------------------------------------------------------------------------------------
  Else
    'nodeInput couldn't be created
    result = "Textbox to insert search string not found"
  End If
  '-------------------------------------------------------------------------------------------

  'Clean up
  '-------------------------------------------------------------------------------------------
  browser.Quit
  Set browser = Nothing
  Set nodeInput = Nothing
  Set nodeUi = Nothing
  Set nodeLi = Nothing
  '-------------------------------------------------------------------------------------------

  'Show the result of this demo
  '-------------------------------------------------------------------------------------------
  MsgBox result
  '-------------------------------------------------------------------------------------------
End Sub

Third: The function to trigger the HTML event. So you don't need sendkeys()

Private Sub TriggerEvent(htmlDocument As Object, htmlElementWithEvent As Object, eventType As String)

  Dim theEvent As Object

  htmlElementWithEvent.Focus
  Set theEvent = htmlDocument.createEvent("HTMLEvents")
  theEvent.initEvent eventType, True, False
  htmlElementWithEvent.dispatchEvent theEvent
End Sub


来源: stackexchange

问:
Call a method from a declaration
my question is kinda simple but I haven't found it over here. I always find my answers over here and now I probably can't find a good match to set my search terms..

I got the following code:

```<code>Business businessClass = new Business();
Entity entityName = new Entity();

entityName = businessClass.find(object);
</code>```

There is anyway to call the "find" method the of businessClass in the declaration of the entity ?

I don't know if it's better or worse but, seems to make more sense.

Thanks for your help. You guys are great ! I learn a lot with you all.

@Mr47, true, but

True, in this case there's no difference and this way is better, but, let's say that I got a Model and inside this model I need to initialize an object before because later I'll check if a variable of this entity is null or not.

I will try to explain:
My entity:

```<code>public class Entity1
{
public int num {get; set;}
public int num1 {get; set;}
}
</code>```

My model:

```<code>Public class viewTest : ViewDatabase
{
  public Entity1 entityTest {get; set;}

}
</code>```

My controller:

```<code>public class ClassTest : Controller
{
  public ActionResult myMethod (int id)
  {
    ViewTest viewModel = new ViewTest();
    Business businessClass = new Business();

    viewModel.entityTest = new ViewTest()
    viewModel.entityTest =  businessClass.find(object);
  }
}
</code>```

as I inicialized it before, I can test if my variable num or num1 is false or not.
but if I try to call the business class method without  making new, my whole "entity test" will be null and not their attributes.

There's anyway to call my method and inicialize the object at the same line ?

答:
Do you mean like this?</p>

```<code>Business businessClass = new Business();
Entity entityName = businessClass.find(object);
</code>```

ContentLicense: CC BY-SA 3.0

Title: Call a method from a declaration

Body:
my question is kinda simple but I haven't found it over here. I always find my answers over here and now I probably can't find a good match to set my search terms..

I got the following code:

Business businessClass = new Business();
Entity entityName = new Entity();

entityName = businessClass.find(object);

There is anyway to call the "find" method the of businessClass in the declaration of the entity ?

I don't know if it's better or worse but, seems to make more sense.

Thanks for your help. You guys are great ! I learn a lot with you all.

@Mr47, true, but

True, in this case there's no difference and this way is better, but, let's say that I got a Model and inside this model I need to initialize an object before because later I'll check if a variable of this entity is null or not.

I will try to explain:
My entity:

public class Entity1
{
public int num {get; set;}
public int num1 {get; set;}
}

My model:

Public class viewTest : ViewDatabase
{
  public Entity1 entityTest {get; set;}

}

My controller:

public class ClassTest : Controller
{
  public ActionResult myMethod (int id)
  {
    ViewTest viewModel = new ViewTest();
    Business businessClass = new Business();

    viewModel.entityTest = new ViewTest()
    viewModel.entityTest =  businessClass.find(object);
  }
}

as I inicialized it before, I can test if my variable num or num1 is false or not.
but if I try to call the business class method without  making new, my whole "entity test" will be null and not their attributes.

There's anyway to call my method and inicialize the object at the same line ?

Body:
Do you mean like this?

Business businessClass = new Business();
Entity entityName = businessClass.find(object);


问:
Are Javascript arrays sparse?
That is, if I use the current time as an index into the array:

```<code>array[Date.getTime()] = value;
</code>```

will the interpreter instantiate all the elements from 0 to now?  Do different browsers do it differently?

I remember there used to be a bug in the AIX kernel, which would create pseudo-ttys on request, but if you did, say, "echo > /dev/pty10000000000" it would create /dev/pty0, /dev/pty1, .... and then fall over dead.  It was fun at trade shows, but I don't want this to happen to my customers.

答:
Sparseness (or denseness) can be confirmed empirically for NodeJS with the non-standard process.memoryUsage().

Sometimes node is clever enough to keep the array sparse:

```<code>Welcome to Node.js v12.15.0.
Type ".help" for more information.
> console.log(`The script is using approximately ${Math.round(process.memoryUsage().heapUsed / 1024 / 1024 * 100) / 100} MB`)
The script is using approximately 3.07 MB
undefined
> array = []
[]
> array[2**24] = 2**24
16777216
> array
[ <16777216 empty items>, 16777216 ]
> console.log(`The script is using approximately ${Math.round(process.memoryUsage().heapUsed / 1024 / 1024 * 100) / 100} MB`)
The script is using approximately 2.8 MB
undefined
</code>```

Sometimes node chooses to make it dense (this behavior might well be optimized in future):

```<code>> otherArray = Array(2**24)
[ <16777216 empty items> ]
> console.log(`The script is using approximately ${Math.round(process.memoryUsage().heapUsed / 1024 / 1024 * 100) / 100} MB`)
The script is using approximately 130.57 MB
undefined
</code>```

Then sparse again:

```<code>> yetAnotherArray = Array(2**32-1)
[ <4294967295 empty items> ]
> console.log(`The script is using approximately ${Math.round(process.memoryUsage().heapUsed / 1024 / 1024 * 100) / 100} MB`)
The script is using approximately 130.68 MB
undefined
</code>```

So perhaps using a dense array to get a feel for the original AIX kernel bug might need to be forced with a range-alike:

```<code>> denseArray = [...Array(2**24).keys()]
[
   0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11,
  12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23,
  24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
  36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47,
  48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59,
  60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71,
  72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83,
  84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95,
  96, 97, 98, 99,
  ... 16777116 more items
]
> console.log(`The script is using approximately ${Math.round(process.memoryUsage().heapUsed / 1024 / 1024 * 100) / 100} MB`);
The script is using approximately 819.94 MB
undefined
</code>```

Because why not make it fall over?

```<code>> tooDenseArray = [...Array(2**32-1).keys()]

<--- Last few GCs --->

[60109:0x1028ca000]   171407 ms: Scavenge 1072.7 (1090.0) -> 1056.7 (1090.0) MB, 0.2 / 0.0 ms  (average mu = 0.968, current mu = 0.832) allocation failure
[60109:0x1028ca000]   171420 ms: Scavenge 1072.7 (1090.0) -> 1056.7 (1090.0) MB, 0.2 / 0.0 ms  (average mu = 0.968, current mu = 0.832) allocation failure
[60109:0x1028ca000]   171434 ms: Scavenge 1072.7 (1090.0) -> 1056.7 (1090.0) MB, 0.2 / 0.0 ms  (average mu = 0.968, current mu = 0.832) allocation failure

<--- JS stacktrace --->

==== JS stack trace =========================================

    0: ExitFrame [pc: 0x100931399]
    1: StubFrame [pc: 0x1008ee227]
    2: StubFrame [pc: 0x100996051]
Security context: 0x1043830808a1 <JSObject>
    3: /* anonymous */ [0x1043830b6919] [repl:1] [bytecode=0x1043830b6841 offset=28](this=0x104306fc2261 <JSGlobal Object>)
    4: InternalFrame [pc: 0x1008aefdd]
    5: EntryFrame [pc: 0x1008aedb8]
    6: builtin exit frame: runInThisContext(this=0x104387b8cac1 <ContextifyScript map = 0x1043...

FATAL ERROR: invalid array length Allocation failed - JavaScript heap out of memory

Writing Node.js report to file: report.20200220.220620.60109.0.001.json
Node.js report completed
 1: 0x10007f4b9 node::Abort() [/Users/pzrq/.nvm/versions/node/v12.15.0/bin/node]
 2: 0x10007f63d node::OnFatalError(char const*, char const*) [/Users/pzrq/.nvm/versions/node/v12.15.0/bin/node]
 3: 0x100176a27 v8::Utils::ReportOOMFailure(v8::internal::Isolate*, char const*, bool) [/Users/pzrq/.nvm/versions/node/v12.15.0/bin/node]
 4: 0x1001769c3 v8::internal::V8::FatalProcessOutOfMemory(v8::internal::Isolate*, char const*, bool) [/Users/pzrq/.nvm/versions/node/v12.15.0/bin/node]
 5: 0x1002fab75 v8::internal::Heap::FatalProcessOutOfMemory(char const*) [/Users/pzrq/.nvm/versions/node/v12.15.0/bin/node]
 6: 0x1005f3e9b v8::internal::Runtime_FatalProcessOutOfMemoryInvalidArrayLength(int, unsigned long*, v8::internal::Isolate*) [/Users/pzrq/.nvm/versions/node/v12.15.0/bin/node]
 7: 0x100931399 Builtins_CEntry_Return1_DontSaveFPRegs_ArgvOnStack_NoBuiltinExit [/Users/pzrq/.nvm/versions/node/v12.15.0/bin/node]
 8: 0x1008ee227 Builtins_IterableToList [/Users/pzrq/.nvm/versions/node/v12.15.0/bin/node]
Abort trap: 6
</code>```

Title: Are Javascript arrays sparse?

Body:
That is, if I use the current time as an index into the array:

array[Date.getTime()] = value;

will the interpreter instantiate all the elements from 0 to now?  Do different browsers do it differently?

I remember there used to be a bug in the AIX kernel, which would create pseudo-ttys on request, but if you did, say, "echo > /dev/pty10000000000" it would create /dev/pty0, /dev/pty1, .... and then fall over dead.  It was fun at trade shows, but I don't want this to happen to my customers.

Body:
Sparseness (or denseness) can be confirmed empirically for NodeJS with the non-standard process.memoryUsage().

Sometimes node is clever enough to keep the array sparse:

Welcome to Node.js v12.15.0.
Type ".help" for more information.
> console.log(`The script is using approximately ${Math.round(process.memoryUsage().heapUsed / 1024 / 1024 * 100) / 100} MB`)
The script is using approximately 3.07 MB
undefined
> array = []
[]
> array[2**24] = 2**24
16777216
> array
[ <16777216 empty items>, 16777216 ]
> console.log(`The script is using approximately ${Math.round(process.memoryUsage().heapUsed / 1024 / 1024 * 100) / 100} MB`)
The script is using approximately 2.8 MB
undefined

Sometimes node chooses to make it dense (this behavior might well be optimized in future):

> otherArray = Array(2**24)
[ <16777216 empty items> ]
> console.log(`The script is using approximately ${Math.round(process.memoryUsage().heapUsed / 1024 / 1024 * 100) / 100} MB`)
The script is using approximately 130.57 MB
undefined

Then sparse again:

> yetAnotherArray = Array(2**32-1)
[ <4294967295 empty items> ]
> console.log(`The script is using approximately ${Math.round(process.memoryUsage().heapUsed / 1024 / 1024 * 100) / 100} MB`)
The script is using approximately 130.68 MB
undefined

So perhaps using a dense array to get a feel for the original AIX kernel bug might need to be forced with a range-alike:

> denseArray = [...Array(2**24).keys()]
[
   0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11,
  12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23,
  24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
  36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47,
  48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59,
  60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71,
  72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83,
  84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95,
  96, 97, 98, 99,
  ... 16777116 more items
]
> console.log(`The script is using approximately ${Math.round(process.memoryUsage().heapUsed / 1024 / 1024 * 100) / 100} MB`);
The script is using approximately 819.94 MB
undefined

Because why not make it fall over?

> tooDenseArray = [...Array(2**32-1).keys()]

<--- Last few GCs --->

[60109:0x1028ca000]   171407 ms: Scavenge 1072.7 (1090.0) -> 1056.7 (1090.0) MB, 0.2 / 0.0 ms  (average mu = 0.968, current mu = 0.832) allocation failure
[60109:0x1028ca000]   171420 ms: Scavenge 1072.7 (1090.0) -> 1056.7 (1090.0) MB, 0.2 / 0.0 ms  (average mu = 0.968, current mu = 0.832) allocation failure
[60109:0x1028ca000]   171434 ms: Scavenge 1072.7 (1090.0) -> 1056.7 (1090.0) MB, 0.2 / 0.0 ms  (average mu = 0.968, current mu = 0.832) allocation failure

<--- JS stacktrace --->

==== JS stack trace =========================================

    0: ExitFrame [pc: 0x100931399]
    1: StubFrame [pc: 0x1008ee227]
    2: StubFrame [pc: 0x100996051]
Security context: 0x1043830808a1 <JSObject>
    3: /* anonymous */ [0x1043830b6919] [repl:1] [bytecode=0x1043830b6841 offset=28](this=0x104306fc2261 <JSGlobal Object>)
    4: InternalFrame [pc: 0x1008aefdd]
    5: EntryFrame [pc: 0x1008aedb8]
    6: builtin exit frame: runInThisContext(this=0x104387b8cac1 <ContextifyScript map = 0x1043...

FATAL ERROR: invalid array length Allocation failed - JavaScript heap out of memory

Writing Node.js report to file: report.20200220.220620.60109.0.001.json
Node.js report completed
 1: 0x10007f4b9 node::Abort() [/Users/pzrq/.nvm/versions/node/v12.15.0/bin/node]
 2: 0x10007f63d node::OnFatalError(char const*, char const*) [/Users/pzrq/.nvm/versions/node/v12.15.0/bin/node]
 3: 0x100176a27 v8::Utils::ReportOOMFailure(v8::internal::Isolate*, char const*, bool) [/Users/pzrq/.nvm/versions/node/v12.15.0/bin/node]
 4: 0x1001769c3 v8::internal::V8::FatalProcessOutOfMemory(v8::internal::Isolate*, char const*, bool) [/Users/pzrq/.nvm/versions/node/v12.15.0/bin/node]
 5: 0x1002fab75 v8::internal::Heap::FatalProcessOutOfMemory(char const*) [/Users/pzrq/.nvm/versions/node/v12.15.0/bin/node]
 6: 0x1005f3e9b v8::internal::Runtime_FatalProcessOutOfMemoryInvalidArrayLength(int, unsigned long*, v8::internal::Isolate*) [/Users/pzrq/.nvm/versions/node/v12.15.0/bin/node]
 7: 0x100931399 Builtins_CEntry_Return1_DontSaveFPRegs_ArgvOnStack_NoBuiltinExit [/Users/pzrq/.nvm/versions/node/v12.15.0/bin/node]
 8: 0x1008ee227 Builtins_IterableToList [/Users/pzrq/.nvm/versions/node/v12.15.0/bin/node]
Abort trap: 6

ContentLicense: CC BY-SA 4.0


问:
AWS Cognito for Django3 + DRF Authentication
I'm trying to set up an AWS Cognito backend
I have a React frontend already working with it, now I need my DRF API to authenticate using the Cognito as backend.

I have found a few Python packages for that, none of them seem to be actively maintained
django-warrant doesn't work with Django3 and is pretty much dead

Django Cognito JWT seems to be my best bet,
but also not actively maintained, the documentation is very poor, and there is a medium post on how to use, not very detailed, but better than nothing.

So, I tried to follow the documentation

Added the env vars on my settings

COGNITO_AWS_REGION = 'us-east-1'
COGNITO_USER_POOL = 'us-east-1_xxxxxxx'  # same user pool id I'm using on the React app
COGNITO_AUDIENCE = 'XXXXXXXXXXXXXXXXXXXXXX' # the same client id I'm using on the React app
```

<p>Then on my DRF authentication classes:</p>

<pre class="lang-py prettyprint-override"><code>    'DEFAULT_AUTHENTICATION_CLASSES': [
        'django_cognito_jwt.JSONWebTokenAuthentication',
        'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
        'rest_framework.authentication.BasicAuthentication',
        'rest_framework.authentication.SessionAuthentication',
    ],
</code>```

And finally the user model:

AUTH_USER_MODEL = 'accounts.MyUser'
COGNITO_USER_MODEL = "accounts.MyUser"
```

<p>My custom User Model:</p>

<pre class="lang-py prettyprint-override"><code>class MyUser(AbstractUser):
    """User model."""

    username = None
    email = models.EmailField(_('email address'), unique=True)

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []

    objects = UserManager()
</code>```

I'm also using DRF JWT package, and if I try to login with a Cognito user, something like:

curl -X POST -H "Content-Type: application/json" -d '{"email":"user@invalid.com","password":"secretpassword"}' http://localhost/api-token-auth/

I get an error

{"non_field_errors":["Unable to log in with provided credentials."]}

On another hand, if I try to login with a local Django user via Django Rest Framework JWT it works fine and I get the JWT token as a response, so I guess the issue is the Cognito integration.

Any idea what I'm missing? or how can I debug in order to figure out what is happening?

UPDATE

After digging a bit more on the code, I found out a few things:

Even doing a DRF JWT authentication, the code end up at:
django/contrib/auth/init.py
Where it loops through all the authentication backends for Django, not for DRF:

for backend, backend_path in _get_backends(return_tuples=True):
```

Still using the ModelBackend to authenticate the user.

So, I guess I also need to add some Cognito authentication backend for Django.
I checked if I could just use the same backend used on DRF, but then I got an error of invalid argument:
TypeError: authenticate() got an unexpected keyword argument 'email'

UPDATE 2
It seems that one of the issues is because I use email instead of username to authenticate, and none of the packages seems to support it

答:
Basically, there are 2 steps to achieve your goal.

Get IdToken and AccessToken from Cognito by Boto3 library.

Apply the IdToken in this Pattern Authorization Bearer IdToken to call API  via curl.

Unlike rest_framework_jwt , django_cognito_jwt only deals with JWT token at header. django_cognito_jwt does not cover step 1. That is why you are getting this error  TypeError: authenticate() got an unexpected keyword argument 'email'.

So, solution is use boto3 to get IdToken and apply curl by passing Authorization:Bearer IdToken header.

Body:
I'm trying to set up an AWS Cognito backend
I have a React frontend already working with it, now I need my DRF API to authenticate using the Cognito as backend.

I have found a few Python packages for that, none of them seem to be actively maintained
django-warrant doesn't work with Django3 and is pretty much dead

Django Cognito JWT seems to be my best bet,
but also not actively maintained, the documentation is very poor, and there is a medium post on how to use, not very detailed, but better than nothing.

So, I tried to follow the documentation

Added the env vars on my settings

COGNITO_AWS_REGION = 'us-east-1'
COGNITO_USER_POOL = 'us-east-1_xxxxxxx'  # same user pool id I'm using on the React app
COGNITO_AUDIENCE = 'XXXXXXXXXXXXXXXXXXXXXX' # the same client id I'm using on the React app

Then on my DRF authentication classes:

    'DEFAULT_AUTHENTICATION_CLASSES': [
        'django_cognito_jwt.JSONWebTokenAuthentication',
        'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
        'rest_framework.authentication.BasicAuthentication',
        'rest_framework.authentication.SessionAuthentication',
    ],

And finally the user model:

AUTH_USER_MODEL = 'accounts.MyUser'
COGNITO_USER_MODEL = "accounts.MyUser"

My custom User Model:

class MyUser(AbstractUser):
    """User model."""

    username = None
    email = models.EmailField(_('email address'), unique=True)

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []

    objects = UserManager()

I'm also using DRF JWT package, and if I try to login with a Cognito user, something like:

curl -X POST -H "Content-Type: application/json" -d '{"email":"user@invalid.com","password":"secretpassword"}' http://localhost/api-token-auth/

I get an error

{"non_field_errors":["Unable to log in with provided credentials."]}

On another hand, if I try to login with a local Django user via Django Rest Framework JWT it works fine and I get the JWT token as a response, so I guess the issue is the Cognito integration.

Any idea what I'm missing? or how can I debug in order to figure out what is happening?

UPDATE

After digging a bit more on the code, I found out a few things:

Even doing a DRF JWT authentication, the code end up at:
django/contrib/auth/init.py
Where it loops through all the authentication backends for Django, not for DRF:

for backend, backend_path in _get_backends(return_tuples=True):

Still using the ModelBackend to authenticate the user.

So, I guess I also need to add some Cognito authentication backend for Django.
I checked if I could just use the same backend used on DRF, but then I got an error of invalid argument:
TypeError: authenticate() got an unexpected keyword argument 'email'

UPDATE 2
It seems that one of the issues is because I use email instead of username to authenticate, and none of the packages seems to support it


问:
Find mean of list in F#
I'm trying to find the average of a list

Here's what I have so far

```<code>let rec avg aList =
    match aList with
    | head::tail -> head+avg(tail)
    | [] -> 0

</code>```

This obtains the sum. I've tried head+avg(tail)/aList.Length, but it gives me an incorrect result as I don't know exactly what that's doing

Any help would be appreciated

答:
The simplest way of doing this is using the average high-order function from the List module. You can do this on a single line with </p>

```<code>let myAverage = aList |> List.average
</code>```

Title: Find mean of list in F#

Body:
I'm trying to find the average of a list

Here's what I have so far

let rec avg aList =
    match aList with
    | head::tail -> head+avg(tail)
    | [] -> 0

This obtains the sum. I've tried head+avg(tail)/aList.Length, but it gives me an incorrect result as I don't know exactly what that's doing

Any help would be appreciated

Body:
The simplest way of doing this is using the average high-order function from the List module. You can do this on a single line with

let myAverage = aList |> List.average


问:
TortoiseSVN switching branch - some files stay on previous branch
When using TortoiseSVN on Windows to switch branch, occasionally some files and/or folders will remain on the previous branch.  There seems to be no consistent pattern to this.  It doesn't happen every time, and it doesn't happen to the same files.  So usually you only find out about it when there's a problem due to the old file no longer working in conjuction with the new files.

So I'd like either of two things:

A way to consistently switch branch that prevents this happening again

If that's not possible, some way of listing the entire contents of a directory along with which branch each file and folder is in.

答:
If you have a clean working copy (no changes), you shouldn't have this problem.

You could do a revert followed by a switch. You will lose any changes you have made to your working copy though.

Alternatively you could commit your changes then switch


问:
git reset --hard origin/master failing
Trying to discard changes on server, and make it exactly the same as origin/master:

```<code>git fetch --all
git reset --hard origin/master
</code>```

I've done this before on same repo without problems, but this time it fails with the following:

```<code>fatal: Could not reset index file to revision 'origin/master'
</code>```

Have tried the following:

remove index and reset as suggested here:

```<code>rm .git/index
git reset
</code>```

also suggested here that some process could have a lock on .git\index. That killing process and then executing git reset could fix it, but not sure how to check if something has a lock on file remotely. Also seems that removing index file and reset would have had same effect.

Loosing my mind. Would really appreciate any help.

答:
Just wanted to note that this ended up being the source of my problem:

also suggested here that some process could have a lock on .git\index. That killing process and then executing git reset could fix it, but not sure how to check if something has a lock on file remotely. Also seems that removing index file and reset would have had same effect.

If you're running anything on local, like Jekyll, React, etc. that has a lock on the files in your project, then killing that process with Ctrl+C/Cmd+C will do the trick.

Title: git reset --hard origin/master failing

Body:
Trying to discard changes on server, and make it exactly the same as origin/master:

git fetch --all
git reset --hard origin/master

I've done this before on same repo without problems, but this time it fails with the following:

fatal: Could not reset index file to revision 'origin/master'

Have tried the following:

remove index and reset as suggested here:

rm .git/index
git reset

also suggested here that some process could have a lock on .git\index. That killing process and then executing git reset could fix it, but not sure how to check if something has a lock on file remotely. Also seems that removing index file and reset would have had same effect.

Loosing my mind. Would really appreciate any help.


问:
Static class storing current user in web application
I'm new to web application in asp.net mvc 5. I'm curious about how static classes behaves in web application. I'd like to know how my program will behave.

Let's say I have CurrentUser static class which stores logged user id.

```<code>public static class CurrentUser{
     public static int UserId {get; set;}
}
</code>```

Which is set whenerever user is logging in.
My app is in external server.

So what will happen if:

User A log in -> userId is set to 1, then User B log in (they access to from differentlcoations) so user Id is set to 2. When User A would like to perform action which need to check his Id, will it be 1 or 2?

I checked one scenario where 2 differentpersons log in from one pc at the same time (different tabs) and I know that User Id will be 2 for both of them (when User B logged in as second to the app). How to resolve this?

I've already read: Static classes in web applications.
I know that my solution may be error prone because every one has access to that class but I don't know if static classes in web app aren't store per user (thread?)?

答: If you store current user in session storage it will be better than static class. Because there is one copy of static class and fields and for every user login the last login is kept.</p>

Body:
I'm new to web application in asp.net mvc 5. I'm curious about how static classes behaves in web application. I'd like to know how my program will behave.

Let's say I have CurrentUser static class which stores logged user id.

public static class CurrentUser{
     public static int UserId {get; set;}
}

Which is set whenerever user is logging in.
My app is in external server.

So what will happen if:

User A log in -> userId is set to 1, then User B log in (they access to from differentlcoations) so user Id is set to 2. When User A would like to perform action which need to check his Id, will it be 1 or 2?

I checked one scenario where 2 differentpersons log in from one pc at the same time (different tabs) and I know that User Id will be 2 for both of them (when User B logged in as second to the app). How to resolve this?

I've already read: Static classes in web applications.
I know that my solution may be error prone because every one has access to that class but I don't know if static classes in web app aren't store per user (thread?)?


问:
What is better design approach for RabbitMQ?
I have been playing around with RabbitMQ for last couple of weeks and developed the following design pattern

producer <--> Exchange <---> queues <---> consumer.

I have used couple of RabbitMQ clients like EasyNetQ and MassTransit. Both clients work with my above design however one thing common between them is that if an Exchange doesn't exist it creates one and similarly if a queue doesn't exist then it creates one accordingly.

However, I am thinking creating exchange, queues and binding from either producer or consumers a good design approach?

Is it more meaningful to create the exchange and queues within the RabbitMQ Management manually? Then prevent Producer and Consumer from creating the above in the code?

But I am more concerned what if the exchanges and queues are deleted then it also breaks the producer and consumers?

What do you suggest guys?

答:
Your CD (Continuous Deployment)  for both producer and consumer should be responsible of creating these resources, your CD should check for the existence of resource and create if it doesn't exist.

You should avoid creating/deleting resources from code, producer and consumer should really just publish/consume, if you are using a cloud provider, code shouldn't be authorized to manipulate resources at all.

The way I would do it:

Info of Exchanges/Queues used by consumer/producer should be read from settings file.

When deployment starts, CD should create the required exchanges/queues.

CD should then override settings through environment variables.

Producer/Consumer will then deal with resources info fed by CD, this way CD can make sure that both parties are using same queue/exchange info.

Also you will be making the risk of miscommunication, resource over usage, and resource manipulation (like deleting a queue!) less.

In production, Nothing/No one should be authorized to edit resources except for few people who really know what they are doing.


问:
Flatten Nested schema in DataFrame, getting AnalysisException: cannot resolve column name
I have a DF:

```<code> -- str1: struct (nullable = true)
 |    |-- a1: string (nullable = true)
 |    |-- a2: string (nullable = true)
 |    |-- a3: string (nullable = true)
 |-- str2: string (nullable = true)
 |-- str3: string (nullable = true)
 |-- str4: array (nullable = true)
 |    |-- element: struct (containsNull = true)
 |    |    |-- b1: string (nullable = true)
 |    |    |-- b2: string (nullable = true)
 |    |    |-- b3: boolean (nullable = true)
 |    |    |-- b4: struct (nullable = true)
 |    |    |    |-- c1: integer (nullable = true)
 |    |    |    |-- c2: string (nullable = true)
 |    |    |    |-- c3: integer (nullable = true)
</code>```

I am trying to flatten it, to do that I have used code below:

```<code>  def flattenSchema(schema: StructType, prefix: String = null):Array[Column]=
  {
    schema.fields.flatMap(f => {
      val colName = if (prefix == null) f.name else (prefix + "." + f.name)

      f.dataType match {
        case st: StructType => flattenSchema(st, colName)
        case at: ArrayType =>
          val st = at.elementType.asInstanceOf[StructType]
          flattenSchema(st, colName)
        case _ => Array(new Column(colName).as(colName))
      }
    })
  }

val d1 = df.select(flattenSchema(df.schema):_*)
</code>```

Its giving me below Output:

```<code> |-- str1.a1: string (nullable = true)
 |-- str1.a2: string (nullable = true)
 |-- str1.a3: string (nullable = true)
 |-- str2: string (nullable = true)
 |-- str3: string (nullable = true)
 |-- str4.b1: array (nullable = true)
 |    |-- element: string (containsNull = true)
 |-- str4.b2: array (nullable = true)
 |    |-- element: string (containsNull = true)
 |-- str4.b3: array (nullable = true)
 |    |-- element: string (containsNull = true)
 |-- str4.b4.c1: array (nullable = true)
 |    |-- element: integer (containsNull = true)
 |-- str4.b4.c2: array (nullable = true)
 |    |-- element: string (containsNull = true)
 |-- str4.b4.c3: array (nullable = true)
 |    |-- element: integer (containsNull = true)
</code>```

Problem is arising when I am trying to query it:

d1.select("str2").show -- Its giving me no issue

but when I do query on any flattened nested column

```<code>d1.select("str1.a1")
</code>```

Error:

```<code>org.apache.spark.sql.AnalysisException: cannot resolve '`str1.a1`' given input columns: ....
</code>```

What I am doing wrong here? or any other way to achieve the desired result?

答: Spark does not support string type column name with dot(.). Dot is use to access child column of any struct type column. If you will try to access same column from dataframe df then it should work since in df it struct type.

Body:
I have a DF:

 -- str1: struct (nullable = true)
 |    |-- a1: string (nullable = true)
 |    |-- a2: string (nullable = true)
 |    |-- a3: string (nullable = true)
 |-- str2: string (nullable = true)
 |-- str3: string (nullable = true)
 |-- str4: array (nullable = true)
 |    |-- element: struct (containsNull = true)
 |    |    |-- b1: string (nullable = true)
 |    |    |-- b2: string (nullable = true)
 |    |    |-- b3: boolean (nullable = true)
 |    |    |-- b4: struct (nullable = true)
 |    |    |    |-- c1: integer (nullable = true)
 |    |    |    |-- c2: string (nullable = true)
 |    |    |    |-- c3: integer (nullable = true)

I am trying to flatten it, to do that I have used code below:

  def flattenSchema(schema: StructType, prefix: String = null):Array[Column]=
  {
    schema.fields.flatMap(f => {
      val colName = if (prefix == null) f.name else (prefix + "." + f.name)

      f.dataType match {
        case st: StructType => flattenSchema(st, colName)
        case at: ArrayType =>
          val st = at.elementType.asInstanceOf[StructType]
          flattenSchema(st, colName)
        case _ => Array(new Column(colName).as(colName))
      }
    })
  }

val d1 = df.select(flattenSchema(df.schema):_*)

Its giving me below Output:

 |-- str1.a1: string (nullable = true)
 |-- str1.a2: string (nullable = true)
 |-- str1.a3: string (nullable = true)
 |-- str2: string (nullable = true)
 |-- str3: string (nullable = true)
 |-- str4.b1: array (nullable = true)
 |    |-- element: string (containsNull = true)
 |-- str4.b2: array (nullable = true)
 |    |-- element: string (containsNull = true)
 |-- str4.b3: array (nullable = true)
 |    |-- element: string (containsNull = true)
 |-- str4.b4.c1: array (nullable = true)
 |    |-- element: integer (containsNull = true)
 |-- str4.b4.c2: array (nullable = true)
 |    |-- element: string (containsNull = true)
 |-- str4.b4.c3: array (nullable = true)
 |    |-- element: integer (containsNull = true)

Problem is arising when I am trying to query it:

d1.select("str2").show -- Its giving me no issue

but when I do query on any flattened nested column

d1.select("str1.a1")

Error:

org.apache.spark.sql.AnalysisException: cannot resolve '`str1.a1`' given input columns: ....

What I am doing wrong here? or any other way to achieve the desired result?


问:
Split values and loop through them
I have two tables:
Table1:

```<code>id | value
1  | val1
2  | val2
3  | val3
</code>```

Table2:

```<code>id | value
1  | val1,val2,val22
2  | val2
3  | val3,val15,
</code>```

The thing that I want to do is to split the values from Table2 by comma (to get separated values), next loop through it and find them in Table1. As a result I need the Table1.id and Table2.id that contains value from Table1 to insert them in the new table.

Is it possible to do it in mysql as there is no SPLIT function?

Edit: MySql version 5.7.27

Edit2: Desired result:

```<code>table1.id  table1.valie  table1.id  table1.valie
        1          val1          1  val1,val2,val22
        2          val2          1  val1,val2,val22
        2          val2          2  val2
        3          val3          3  val3,val15,
</code>```

答:
```<code>CREATE TABLE table3
SELECT t1.id `t1.id`, t1.value `t1.value`, t2.id `t2.id`, t2.value `t2.value`
FROM table1 t1
JOIN table2 t2 ON FIND_IN_SET(t1.value, t2.value);
</code>```

fiddle

Title: Split values and loop through them

Body:
I have two tables:
Table1:

id | value
1  | val1
2  | val2
3  | val3

Table2:

id | value
1  | val1,val2,val22
2  | val2
3  | val3,val15,

The thing that I want to do is to split the values from Table2 by comma (to get separated values), next loop through it and find them in Table1. As a result I need the Table1.id and Table2.id that contains value from Table1 to insert them in the new table.

Is it possible to do it in mysql as there is no SPLIT function?

Edit: MySql version 5.7.27

Edit2: Desired result:

table1.id  table1.valie  table1.id  table1.valie
        1          val1          1  val1,val2,val22
        2          val2          1  val1,val2,val22
        2          val2          2  val2
        3          val3          3  val3,val15,

Body:
CREATE TABLE table3
SELECT t1.id `t1.id`, t1.value `t1.value`, t2.id `t2.id`, t2.value `t2.value`
FROM table1 t1
JOIN table2 t2 ON FIND_IN_SET(t1.value, t2.value);

fiddle


问:
Change position when something is in perspective
I would like to draw a grid in perspective and draw a circle in in te left bottom corner.
But I am not able to get it right.

So, first I draw the grid and circle without perspective.

```<code>public class test extends MovieClip
    {
        private var _gridSprite:Sprite;
        private var _xLineHolder:Sprite;
        private var _yLineHolder:Sprite;
        private var _circle:Sprite;

        public function test()
        {
            init();
        }

        private function init()
        {
            _gridSprite = new Sprite();
            this.addChild(_gridSprite);

            _xLineHolder = new Sprite();
            _gridSprite.addChild(_xLineHolder);
            _yLineHolder = new Sprite();
            _gridSprite.addChild(_yLineHolder);

            draw();

            _circle = new Sprite();
            _circle.graphics.beginFill(0xFF0000);
            _circle.graphics.drawCircle(0, 0, 5);
            this.addChild(_circle);

                   //Here do I set the position of the circle
            _circle.x = _gridSprite.width + _gridSprite.x;
            _circle.y = _gridSprite.height + _gridSprite.y;
        }

        private function draw()
        {
            var spaceXDiv:Number = 160/20;
            var spaceYDiv:Number = 160/20;

            _xLineHolder.graphics.clear();
            _yLineHolder.graphics.clear();

            _xLineHolder.graphics.lineStyle(1);
            _yLineHolder.graphics.lineStyle(1);

            for(var i:int = 0; i <= spaceXDiv; i++){
                _xLineHolder.graphics.moveTo(i * 20, 0);
                _xLineHolder.graphics.lineTo(i * 20, 160);
            }

            for(var j:int = 0; j <= spaceYDiv; j++){
                _yLineHolder.graphics.moveTo( 0, j * 20);
                _yLineHolder.graphics.lineTo(160, j * 20);
            }
        }
    }
</code>```

With this code, I get the following result

This is all ok, the circle is in te bottom left corner.

Now I set the perspective of the grid in init(). I use rotationY (I don't know if this is the proper way). The angle is 20 degrees.

```<code>_gridSprite = new Sprite();
this.addChild(_gridSprite);
_gridSprite.rotationY = -20;
</code>```

The result is not ok anymore. The circle isn't anymore in the bottom left corner of the grid.

My question is: how do I change the position of the circle, so that it is in the bottom left corner of the grid in perspective?

I tried a lot, but my mathematics aren't that good anymore.
This is example code that doesn't put the circle at the bottom left corner.

```<code>var gridLeft:Number = _gridSprite.width + _gridSprite.x;
_circle.x = gridLeft - gridLeft * Math.tan(20 * Math.PI / 180);

var gridBottom:Number = _gridSprite.height + _gridSprite.y;
_circle.y = gridBottom - gridBottom * Math.tan(20 * Math.PI / 180);
</code>```

I hope you understand my question and that you can help me.

Thanks,

Vincent

答:
I think you're over-complicating the problem.  You only need to rotate both the grid and the circle in the same container.  In this case, your 'test' class is the container, but you could always create another sprite as the container.

So, if you want to rotate both grid and circle, just do this.rotationY = -20 instead of _gridSprite.rotationY = -20;

Body:
I would like to draw a grid in perspective and draw a circle in in te left bottom corner.
But I am not able to get it right.

So, first I draw the grid and circle without perspective.

public class test extends MovieClip
    {
        private var _gridSprite:Sprite;
        private var _xLineHolder:Sprite;
        private var _yLineHolder:Sprite;
        private var _circle:Sprite;

        public function test()
        {
            init();
        }

        private function init()
        {
            _gridSprite = new Sprite();
            this.addChild(_gridSprite);

            _xLineHolder = new Sprite();
            _gridSprite.addChild(_xLineHolder);
            _yLineHolder = new Sprite();
            _gridSprite.addChild(_yLineHolder);

            draw();

            _circle = new Sprite();
            _circle.graphics.beginFill(0xFF0000);
            _circle.graphics.drawCircle(0, 0, 5);
            this.addChild(_circle);

                   //Here do I set the position of the circle
            _circle.x = _gridSprite.width + _gridSprite.x;
            _circle.y = _gridSprite.height + _gridSprite.y;
        }

        private function draw()
        {
            var spaceXDiv:Number = 160/20;
            var spaceYDiv:Number = 160/20;

            _xLineHolder.graphics.clear();
            _yLineHolder.graphics.clear();

            _xLineHolder.graphics.lineStyle(1);
            _yLineHolder.graphics.lineStyle(1);

            for(var i:int = 0; i <= spaceXDiv; i++){
                _xLineHolder.graphics.moveTo(i * 20, 0);
                _xLineHolder.graphics.lineTo(i * 20, 160);
            }

            for(var j:int = 0; j <= spaceYDiv; j++){
                _yLineHolder.graphics.moveTo( 0, j * 20);
                _yLineHolder.graphics.lineTo(160, j * 20);
            }
        }
    }

With this code, I get the following result

This is all ok, the circle is in te bottom left corner.

Now I set the perspective of the grid in init(). I use rotationY (I don't know if this is the proper way). The angle is 20 degrees.

_gridSprite = new Sprite();
this.addChild(_gridSprite);
_gridSprite.rotationY = -20;

The result is not ok anymore. The circle isn't anymore in the bottom left corner of the grid.

My question is: how do I change the position of the circle, so that it is in the bottom left corner of the grid in perspective?

I tried a lot, but my mathematics aren't that good anymore.
This is example code that doesn't put the circle at the bottom left corner.

var gridLeft:Number = _gridSprite.width + _gridSprite.x;
_circle.x = gridLeft - gridLeft * Math.tan(20 * Math.PI / 180);

var gridBottom:Number = _gridSprite.height + _gridSprite.y;
_circle.y = gridBottom - gridBottom * Math.tan(20 * Math.PI / 180);

I hope you understand my question and that you can help me.

Thanks,

Vincent


问:
Java8 Date and Time with Instant API
I get dynamic date from my request,

```<code>Instant duration = request.getStartDate();   // my input is 2020-03-01T00:00:01Z
for (int i = 0; i < 12; i++) {
  duration  = duration.with(TemporalAdjusters.firstDayOfNextMonth ());
}

</code>```

Basically i wanted to get first day of every month for 12 months, i tried with above code but getting exception,

```<code>java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: DayOfMonth
</code>```

My output could be,

```<code>2020-04-01T00:00:01Z
2020-05-01T00:00:01Z
2020-06-01T00:00:01Z
:
:
2021-03-01T00:00:01Z
</code>```

anything am missing here? tried with using plus()

```<code>duration.plus(30, ChronoUnit.DAYS);

</code>```

I tried to convert instant to locateDate, then it prints fine, but for my required format i need to convert to Instant from localdate. I'm not seeing 1st day of next month.

```<code>
2019-03-31T22:00:00Z
2019-04-30T22:00:00Z
2019-05-31T22:00:00Z
2019-06-30T22:00:00Z
2019-07-31T22:00:00Z
2019-08-31T22:00:00Z
2019-09-30T22:00:00Z
2019-10-31T23:00:00Z
2019-11-30T23:00:00Z
2019-12-31T23:00:00Z
</code>```

any suggestion are appreciated. Thanks!

答:
```<code>Instant startInstant = request.getStartDate();
LocalDate start = startInstant.atZone(ZoneOffset.UTC).toLocalDate().withDayOfMonth(1);
for (int i = 0; i < 12; i++) {
    System.out.println(start.plusMonths(i).atStartOfDay().toInstant(ZoneOffset.UTC));
}
</code>```

Title: Java8 Date and Time with Instant API

Body:
I get dynamic date from my request,

Instant duration = request.getStartDate();   // my input is 2020-03-01T00:00:01Z
for (int i = 0; i < 12; i++) {
  duration  = duration.with(TemporalAdjusters.firstDayOfNextMonth ());
}

Basically i wanted to get first day of every month for 12 months, i tried with above code but getting exception,

java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: DayOfMonth

My output could be,

2020-04-01T00:00:01Z
2020-05-01T00:00:01Z
2020-06-01T00:00:01Z
:
:
2021-03-01T00:00:01Z

anything am missing here? tried with using plus()

duration.plus(30, ChronoUnit.DAYS);

I tried to convert instant to locateDate, then it prints fine, but for my required format i need to convert to Instant from localdate. I'm not seeing 1st day of next month.

2019-03-31T22:00:00Z
2019-04-30T22:00:00Z
2019-05-31T22:00:00Z
2019-06-30T22:00:00Z
2019-07-31T22:00:00Z
2019-08-31T22:00:00Z
2019-09-30T22:00:00Z
2019-10-31T23:00:00Z
2019-11-30T23:00:00Z
2019-12-31T23:00:00Z

any suggestion are appreciated. Thanks!


问:
Implementing a lambda layer within a Keras model
I'm trying to implement an external lambda function from a Keras model. But the function is called twice or the '### x' and '### x_reshape'are printed twice. How to eliminate this?</p>

```<code>def RA_reshape(x):
    print('\n### x ', x)
    x_reshape = K.reshape(x, [1, x.shape[1].value, x.shape[2].value, x.shape[3].value])
    print('\n### x_reshape ', x_reshape)
    return x_reshape

def unet(pretrained_weights = None,input_size = None):
    inputs = Input(input_size)

    conv1 = Conv2D(64, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(inputs)
    conv1 = Conv2D(64, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv1)

    RA_0 = Lambda(lambda y: RA_reshape(x=y) )
    conv1 = RA_0(conv1)
</code>```

答:
Could you try to call it like that :

```<code>def unet(pretrained_weights = None,input_size = None):
    inputs = Input(input_size)

    conv1 = Conv2D(64, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(inputs)
    conv1 = Conv2D(64, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv1)

    RA_0 = Lambda(RA_reshape)(conv1)
</code>```

Tell me if that working !

Body:
I'm trying to implement an external lambda function from a Keras model. But the function is called twice or the '### x' and '### x_reshape'are printed twice. How to eliminate this?

def RA_reshape(x):
    print('\n### x ', x)
    x_reshape = K.reshape(x, [1, x.shape[1].value, x.shape[2].value, x.shape[3].value])
    print('\n### x_reshape ', x_reshape)
    return x_reshape

def unet(pretrained_weights = None,input_size = None):
    inputs = Input(input_size)

    conv1 = Conv2D(64, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(inputs)
    conv1 = Conv2D(64, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv1)

    RA_0 = Lambda(lambda y: RA_reshape(x=y) )
    conv1 = RA_0(conv1)

Body:
Could you try to call it like that :

def unet(pretrained_weights = None,input_size = None):
    inputs = Input(input_size)

    conv1 = Conv2D(64, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(inputs)
    conv1 = Conv2D(64, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv1)

    RA_0 = Lambda(RA_reshape)(conv1)

Tell me if that working !


问:
Mouse event getAction name
I am trying to find out the Action Name that is being performed by the mouse. I tried

```<code>String act=String.valueof(event.getAction());
</code>```

it returns me integer 3.
Can anyone guide me with the list of integer associated with motionevent in android.

答:
`

```<code>private static String getActionName(MotionEvent event) {
   try {
       for (Field f : MotionEvent.class.getFields()) {
           if (f.getName().startsWith("ACTION_") &&
               f.getInt(null) == event.getAction()) {
                   return f.getName();
            }
        }
    }
    catch (IllegalAccessException ignored) {}
    return event.getAction()+"";
}
</code>```

`

Title: Mouse event getAction name

Body:
I am trying to find out the Action Name that is being performed by the mouse. I tried

String act=String.valueof(event.getAction());

it returns me integer 3.
Can anyone guide me with the list of integer associated with motionevent in android.

Body:
`

private static String getActionName(MotionEvent event) {
   try {
       for (Field f : MotionEvent.class.getFields()) {
           if (f.getName().startsWith("ACTION_") &&
               f.getInt(null) == event.getAction()) {
                   return f.getName();
            }
        }
    }
    catch (IllegalAccessException ignored) {}
    return event.getAction()+"";
}

`


问:
How to get Java class' real module dependency?
My JDK version is OpenJDK 11.
My class File is jmx.Main.class

Here are my code.

```<code>package jmx;
import java.lang.management.ManagementFactory;

import javax.management.AttributeNotFoundException;
import javax.management.InstanceNotFoundException;
import javax.management.MBeanException;
import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import javax.management.ReflectionException;

public class Main {
    public static void main(String[] args) throws InstanceNotFoundException, AttributeNotFoundException, MalformedObjectNameException, ReflectionException, MBeanException  {
        /* Total number of processors or cores available to the JVM */
        MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
        Object attribute = mBeanServer.getAttribute(new ObjectName("java.lang","type","OperatingSystem"), "TotalPhysicalMemorySize");
        Object attribute2 = mBeanServer.getAttribute(new ObjectName("java.lang","type","OperatingSystem"), "FreePhysicalMemorySize");
        System.out.println("Total memory: "+ Long.parseLong(attribute.toString()) / 1024  +"MB");
        System.out.println("Free  memory: "+ Long.parseLong(attribute2.toString()) / 1024  +"MB");
    }
}
</code>```

It works fine when it runs in IDE. I want to use a custom jre. Then I use jdeps to analyze dependencies. The result is:

```<code>Main.class -> java.base
Main.class -> java.management
   jmx                                        -> java.io                                            java.base
   jmx                                        -> java.lang                                          java.base
   jmx                                        -> java.lang.invoke                                   java.base
   jmx                                        -> java.lang.management                               java.management
   jmx                                        -> javax.management                                   java.management
</code>```

So I think java.base and java.management is the dependency modules.

Then I use jlink to generate my custom jre.

```<code>jlink --module-path "C:\Program Files\Java\jdk-11.0.6\jmods" --add-modules java.base,java.management --output jre11
</code>```

Before using my custom jre, I had run my code in cmd windows. It works fine.

Then I run the code in my jre. The code can't run and I got an error:

```<code>javax.management.AttributeNotFoundException: No such attribute: TotalPhysicalMemorySize
</code>```

So I think the reason is that some dependency modules is missing. I run jlink to generate a whole module jre. When I use the whole module jre, the code runs correctly again.

How can I get the real dependency modules? or It's a JDK's bug?

答:
Before JDK 9, the type com.sun.management.OperatingSystemMXBean was an undocumented extension of java.lang.management.OperatingSystemMXBean. So it was reasonable to use a reflective attribute query like getAttribute(new ObjectName("java.lang","type","OperatingSystem"), "TotalPhysicalMemorySize") which does not create a dependency to nonstandard APIs.

The advantage is also the disadvantage. When there is no dependency, a tool to analyse dependencies can’t detect a dependency.

When you add the module jdk.management, the extension will be available. Being part of a documented module also implies that when you are willing to accept a permanent dependency to the module, you can use the extended OperatingSystemMXBean directly.

```<code>import com.sun.management.OperatingSystemMXBean;
import java.lang.management.ManagementFactory;

public class OSMX {
    public static void main(String[] args) {
        OperatingSystemMXBean osBean
            = ManagementFactory.getPlatformMXBean(OperatingSystemMXBean.class);
        System.out.println("Total memory: "
            + osBean.getTotalPhysicalMemorySize() / (1024*1024)  +"MB");
        System.out.println("Free  memory: "
            + osBean.getFreePhysicalMemorySize() / (1024*1024)  +"MB");
    }
}
</code>```

Then, jdeps will report the dependency to jdk.management correctly.

Body:
My JDK version is OpenJDK 11.
My class File is jmx.Main.class

Here are my code.

package jmx;
import java.lang.management.ManagementFactory;

import javax.management.AttributeNotFoundException;
import javax.management.InstanceNotFoundException;
import javax.management.MBeanException;
import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import javax.management.ReflectionException;

public class Main {
    public static void main(String[] args) throws InstanceNotFoundException, AttributeNotFoundException, MalformedObjectNameException, ReflectionException, MBeanException  {
        /* Total number of processors or cores available to the JVM */
        MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
        Object attribute = mBeanServer.getAttribute(new ObjectName("java.lang","type","OperatingSystem"), "TotalPhysicalMemorySize");
        Object attribute2 = mBeanServer.getAttribute(new ObjectName("java.lang","type","OperatingSystem"), "FreePhysicalMemorySize");
        System.out.println("Total memory: "+ Long.parseLong(attribute.toString()) / 1024  +"MB");
        System.out.println("Free  memory: "+ Long.parseLong(attribute2.toString()) / 1024  +"MB");
    }
}

It works fine when it runs in IDE. I want to use a custom jre. Then I use jdeps to analyze dependencies. The result is:

Main.class -> java.base
Main.class -> java.management
   jmx                                        -> java.io                                            java.base
   jmx                                        -> java.lang                                          java.base
   jmx                                        -> java.lang.invoke                                   java.base
   jmx                                        -> java.lang.management                               java.management
   jmx                                        -> javax.management                                   java.management

So I think java.base and java.management is the dependency modules.

Then I use jlink to generate my custom jre.

jlink --module-path "C:\Program Files\Java\jdk-11.0.6\jmods" --add-modules java.base,java.management --output jre11

Before using my custom jre, I had run my code in cmd windows. It works fine.

Then I run the code in my jre. The code can't run and I got an error:

javax.management.AttributeNotFoundException: No such attribute: TotalPhysicalMemorySize

So I think the reason is that some dependency modules is missing. I run jlink to generate a whole module jre. When I use the whole module jre, the code runs correctly again.

How can I get the real dependency modules? or It's a JDK's bug?

Body:
Before JDK 9, the type com.sun.management.OperatingSystemMXBean was an undocumented extension of java.lang.management.OperatingSystemMXBean. So it was reasonable to use a reflective attribute query like getAttribute(new ObjectName("java.lang","type","OperatingSystem"), "TotalPhysicalMemorySize") which does not create a dependency to nonstandard APIs.

The advantage is also the disadvantage. When there is no dependency, a tool to analyse dependencies can’t detect a dependency.

When you add the module jdk.management, the extension will be available. Being part of a documented module also implies that when you are willing to accept a permanent dependency to the module, you can use the extended OperatingSystemMXBean directly.

import com.sun.management.OperatingSystemMXBean;
import java.lang.management.ManagementFactory;

public class OSMX {
    public static void main(String[] args) {
        OperatingSystemMXBean osBean
            = ManagementFactory.getPlatformMXBean(OperatingSystemMXBean.class);
        System.out.println("Total memory: "
            + osBean.getTotalPhysicalMemorySize() / (1024*1024)  +"MB");
        System.out.println("Free  memory: "
            + osBean.getFreePhysicalMemorySize() / (1024*1024)  +"MB");
    }
}

Then, jdeps will report the dependency to jdk.management correctly.


问:
How to enable and disable openGL2.0 in android
I want to learn OpenGL2.0 in android.But I didn't find the way how to enable and disable OpenGL2.0 in andorid and Android Browser. If anyone knows please help me on this..</p>

答:
I don't believe you enable or disable OpenGL 2.0, or 1.1, or any other version.  Rather, either your device supports it or it doesn't.  If you want to find out how to check what it supports, we can help you with that.

To use the 2.0 functionality simply cast your GL10 object to a GL20 object and start calling the GL20 specific methods.


问:
iOS slow initialisation times due to cocoapods
I have a fairly simple iOS app that depends only on two pods, Firebase and Alamofire, but I get awful startup time before any code of mine could run.

I see times like

Total pre-main time: 18.5 seconds (100.0%)
 dylib loading time: 11.1 seconds (59.7%)
rebase/binding time: 366.92 milliseconds (1.9%)
    ObjC setup time: 752.48 milliseconds (4.0%)
   initializer time: 6.3 seconds (34.2%)

       slowest intializers :
         libSystem.B.dylib : 936.19 milliseconds (5.0%)
libMainThreadChecker.dylib : 1.8 seconds (9.8%)
                  CoreDuet : 514.37 milliseconds (2.7%)
              ShimmyMobile : 2.9 seconds (15.7%)
```

<p>Although the pre-main time has ranged from 2 seconds to this extreme.
I am running in the simulator so that may make things a little worse?</p>

<p>Firebase has a lot of dependencies, i.e. when running pod install I see:</p>

<pre class="lang-none prettyprint-override"><code>Installing Alamofire (4.9.1)
Installing Firebase (6.17.0)
Installing FirebaseAnalyticsInterop (1.5.0)
Installing FirebaseCore (6.6.2)
Installing FirebaseCoreDiagnostics (1.2.0)
Installing FirebaseCoreDiagnosticsInterop (1.2.0)
Installing FirebaseInstallations (1.1.0)
Installing FirebaseInstanceID (4.3.1)
Installing FirebaseMessaging (4.2.1)
Installing GoogleDataTransport (4.0.0)
Installing GoogleDataTransportCCTSupport (1.4.0)
Installing GoogleUtilities (6.5.1)
Installing PromisesObjC (1.2.8)
Installing Protobuf (3.11.4)
Installing nanopb (0.3.9011)
</code>```

I am only using FirebaseMessaging so is there something I can do to improve my startup times? Either removing unused dependencies or using a static build (I am using Swift 5)?

答:
I was able to solve this by first updating cocoa pods then in my podfile
commenting use_frameworks and adding use_modular_headers!

Ie

use_frameworks!

use_modular_headers!

But yes the simulator is much slower as well.

Body:
I have a fairly simple iOS app that depends only on two pods, Firebase and Alamofire, but I get awful startup time before any code of mine could run.

I see times like

Total pre-main time: 18.5 seconds (100.0%)
 dylib loading time: 11.1 seconds (59.7%)
rebase/binding time: 366.92 milliseconds (1.9%)
    ObjC setup time: 752.48 milliseconds (4.0%)
   initializer time: 6.3 seconds (34.2%)

       slowest intializers :
         libSystem.B.dylib : 936.19 milliseconds (5.0%)
libMainThreadChecker.dylib : 1.8 seconds (9.8%)
                  CoreDuet : 514.37 milliseconds (2.7%)
              ShimmyMobile : 2.9 seconds (15.7%)

Although the pre-main time has ranged from 2 seconds to this extreme.
I am running in the simulator so that may make things a little worse?

Firebase has a lot of dependencies, i.e. when running pod install I see:

Installing Alamofire (4.9.1)
Installing Firebase (6.17.0)
Installing FirebaseAnalyticsInterop (1.5.0)
Installing FirebaseCore (6.6.2)
Installing FirebaseCoreDiagnostics (1.2.0)
Installing FirebaseCoreDiagnosticsInterop (1.2.0)
Installing FirebaseInstallations (1.1.0)
Installing FirebaseInstanceID (4.3.1)
Installing FirebaseMessaging (4.2.1)
Installing GoogleDataTransport (4.0.0)
Installing GoogleDataTransportCCTSupport (1.4.0)
Installing GoogleUtilities (6.5.1)
Installing PromisesObjC (1.2.8)
Installing Protobuf (3.11.4)
Installing nanopb (0.3.9011)

I am only using FirebaseMessaging so is there something I can do to improve my startup times? Either removing unused dependencies or using a static build (I am using Swift 5)?


问:
MySQL query runs very slow
I have a MySQL (v5.7.26) query that runs forever. Here is the query:

```<code>SELECT
    ur.user_id      AS user_id,
    sum(r.duration) AS total_time,
    count(user_id)  AS number_of_workouts
FROM user_resource ur
INNER JOIN resource r ON r.id = ur.resource_id
WHERE
    ur.status = 1
    AND NOT ur.action_date IS NULL
    AND ur.user_id IN (
        SELECT user_id
        FROM user_resource ur2
        WHERE ur2.action_date >= now() - INTERVAL 2 DAY
    )
    AND r.type = 'WORKOUT'
    GROUP BY ur.user_id;
</code>```

I have played a bit with it, by trying to understand where is the problem. For the testing purposes, I tried breaking in two. So:

```<code>SELECT user_id
FROM user_resource ur2
WHERE ur2.action_date >= now() - INTERVAL 2 DAY;
</code>```

That returns (very quickly) list of user user_id's.
When I plug the returned result in to the first part of the query, like this:

```<code>SELECT
    ur.user_id      AS user_id,
    sum(r.duration) AS total_time,
    count(user_id)  AS number_of_workouts
FROM user_resource ur
INNER JOIN resource r ON r.id = ur.resource_id
WHERE
    ur.status = 1
    AND NOT ur.action_date IS NULL
    AND ur.user_id IN (1,1,1,4,4,5,6,7,7,7);
      AND r.type = 'WORKOUT'
GROUP BY ur.user_id
</code>```

It runs very fast. My assumption is the IN (Subquery) is the bottleneck.

I was thinking to extract the subquery and get the user_ids, and then used it as a variable, but I am not sure is it the good approach, and additionally I am having issues with it. this is my attempt:

```<code>-- first statement
SET @v1 = (SELECT user_id
FROM user_resource ur2
WHERE ur2.action_date >= now() - INTERVAL 2 DAY)

-- second statement
SELECT
    ur.user_id      AS user_id,
    sum(r.duration) AS total_time,
    count(user_id)  AS prefixes
FROM user_resource ur
INNER JOIN resource r ON r.id = ur.resource_id
WHERE
    ur.status = 1
    AND NOT ur.action_date IS NULL
    AND ur.user_id IN (@v1);
    AND r.type = 'WORKOUT'
GROUP BY ur.user_id
</code>```

Problem here is that the first statement returns an error:

Subquery returns more than 1 row.

Expected result are user_id's, that can be duplicates. And I need those duplicated for the count.

How can I fix this?

答:
Try EXISTS instead of IN

```<code>...
AND EXISTS (SELECT *
                   FROM user_resource ur2
                   WHERE ur2.user_id = ur.user_id
                         AND ur2.action_date >= now() - INTERVAL 2 DAY)
...
</code>```

and indices on user_resource (user_id, action_date), user_resource (status, action_date, user_id) and/or user_resource (type).

Title: MySQL query runs very slow

Body:
I have a MySQL (v5.7.26) query that runs forever. Here is the query:

SELECT
    ur.user_id      AS user_id,
    sum(r.duration) AS total_time,
    count(user_id)  AS number_of_workouts
FROM user_resource ur
INNER JOIN resource r ON r.id = ur.resource_id
WHERE
    ur.status = 1
    AND NOT ur.action_date IS NULL
    AND ur.user_id IN (
        SELECT user_id
        FROM user_resource ur2
        WHERE ur2.action_date >= now() - INTERVAL 2 DAY
    )
    AND r.type = 'WORKOUT'
    GROUP BY ur.user_id;

I have played a bit with it, by trying to understand where is the problem. For the testing purposes, I tried breaking in two. So:

SELECT user_id
FROM user_resource ur2
WHERE ur2.action_date >= now() - INTERVAL 2 DAY;

That returns (very quickly) list of user user_id's.
When I plug the returned result in to the first part of the query, like this:

SELECT
    ur.user_id      AS user_id,
    sum(r.duration) AS total_time,
    count(user_id)  AS number_of_workouts
FROM user_resource ur
INNER JOIN resource r ON r.id = ur.resource_id
WHERE
    ur.status = 1
    AND NOT ur.action_date IS NULL
    AND ur.user_id IN (1,1,1,4,4,5,6,7,7,7);
      AND r.type = 'WORKOUT'
GROUP BY ur.user_id

It runs very fast. My assumption is the IN (Subquery) is the bottleneck.

I was thinking to extract the subquery and get the user_ids, and then used it as a variable, but I am not sure is it the good approach, and additionally I am having issues with it. this is my attempt:

-- first statement
SET @v1 = (SELECT user_id
FROM user_resource ur2
WHERE ur2.action_date >= now() - INTERVAL 2 DAY)

-- second statement
SELECT
    ur.user_id      AS user_id,
    sum(r.duration) AS total_time,
    count(user_id)  AS prefixes
FROM user_resource ur
INNER JOIN resource r ON r.id = ur.resource_id
WHERE
    ur.status = 1
    AND NOT ur.action_date IS NULL
    AND ur.user_id IN (@v1);
    AND r.type = 'WORKOUT'
GROUP BY ur.user_id

Problem here is that the first statement returns an error:

Subquery returns more than 1 row.

Expected result are user_id's, that can be duplicates. And I need those duplicated for the count.

How can I fix this?

Body:
Try EXISTS instead of IN

...
AND EXISTS (SELECT *
                   FROM user_resource ur2
                   WHERE ur2.user_id = ur.user_id
                         AND ur2.action_date >= now() - INTERVAL 2 DAY)
...

and indices on user_resource (user_id, action_date), user_resource (status, action_date, user_id) and/or user_resource (type).


问:
How to fetch hierarchy data with dynamic changes
I have emp table like as follows:

```<code>Empname              Mgr_hierarchy
-------    ---------------------------------
arjun      Giri    | Raj    | Suresh
arun       arjun   | Giri   | Raj    | Suresh
alex       Pandey  | Ravi   | Suresh
adam       alex    | Pandey | Ravi   | Suresh
bux        alex    | Pandey | Ravi   | Suresh
bony       Agarwal | Ram    | Nitesh | Suresh
</code>```

A manager table as like follows:

```<code>Mgr_names
----------
Raj
Ram
Ravi
</code>```

I want to fetch the all the employee details who are have the listed managers in their hierarchy,

I have use the following code for that

```<code>    select empname from `project.dataset.emp`
 where
(mgr_hierarchy like '%Raj%' or mgr_hierarchy like '%Ravi%' or mgr_hierarchy like '%Ram%')
</code>```

But the problem is the manager table is dynamically changing; as of now it contains 3 values after one month these managers are replaced with another 3 or 4 values. So every time I am changing the condition. Are there any solutions for this?

答:
You can use in operator as:

```<code>select empname from `project.dataset.emp`
 where
(mgr_hierarchy in (select names from Mgr_names where names like '%your search query%'  ) )
enter code here
</code>```

You can search now any names and that will get all belonging from table Mgr_names and for those member empname will be printed.

Body:
I have emp table like as follows:

Empname              Mgr_hierarchy
-------    ---------------------------------
arjun      Giri    | Raj    | Suresh
arun       arjun   | Giri   | Raj    | Suresh
alex       Pandey  | Ravi   | Suresh
adam       alex    | Pandey | Ravi   | Suresh
bux        alex    | Pandey | Ravi   | Suresh
bony       Agarwal | Ram    | Nitesh | Suresh

A manager table as like follows:

Mgr_names
----------
Raj
Ram
Ravi

I want to fetch the all the employee details who are have the listed managers in their hierarchy,

I have use the following code for that

    select empname from `project.dataset.emp`
 where
(mgr_hierarchy like '%Raj%' or mgr_hierarchy like '%Ravi%' or mgr_hierarchy like '%Ram%')

But the problem is the manager table is dynamically changing; as of now it contains 3 values after one month these managers are replaced with another 3 or 4 values. So every time I am changing the condition. Are there any solutions for this?

Body:
You can use in operator as:

select empname from `project.dataset.emp`
 where
(mgr_hierarchy in (select names from Mgr_names where names like '%your search query%'  ) )
enter code here

You can search now any names and that will get all belonging from table Mgr_names and for those member empname will be printed.


问:
Image Angular create dynamically in assets folder refresh webpage
I have an Angular webpage where I have images. I also have a script which create and save png images in assets folder. So, I want to display each image which are created dynamically in my webpage.
But when they are created, the webpage is always refreshing and this is not what I want.

Can you please, help me on how to add images in angular webpage dynamically without refreshing the page.

答:
I finally managed to solve my problem.
Indeed, I just have to run my angular project with

```<code>ng serve --live-reload false
</code>```

With this command, the project doesn't refresh automatically. Hope it will help other people who are facing the same issue.

Body:
I finally managed to solve my problem.
Indeed, I just have to run my angular project with

ng serve --live-reload false

With this command, the project doesn't refresh automatically. Hope it will help other people who are facing the same issue.