问:
Is this variable just a string of numbers?
I want a code to specify which variables in a dictionary like the following are not just a string of numbers?

```<code>myDictionary = {
'first' : '2345687554',
'second' : 'fgdjsa87gh',
'third' : '87hfkd77d'
}
</code>```

In fact, I wrote a function that takes a number of usernames and passwords as arguments and returns the names that qualify in a list:

```<code>def check_registration_rules (**x):
mylist = []
for usname in x.keys():
    if (len(usname) >= 4) and (usname != 'quera' and usname != 'codecup') and (len(x[usname]) >= 6 ):
        mylist.append(usname)
return mylist
</code>```

But it is necessary to find out whether the password of a username is just a string of numbers or not. If it is a string of numbers, it does not have the necessary conditions.
I did not find a solution to this

答:
In Python you can check if a string is made out of only digits with str.isdigit().

```<code>>>> "42".isdigit()
True
>>> "53SS0".isdigit()
False
</code>```

In your case something like this should work:

```<code>if (not usname.isdigit()):
    ...
</code>```

Body:
I want a code to specify which variables in a dictionary like the following are not just a string of numbers?

myDictionary = {
'first' : '2345687554',
'second' : 'fgdjsa87gh',
'third' : '87hfkd77d'
}

In fact, I wrote a function that takes a number of usernames and passwords as arguments and returns the names that qualify in a list:

def check_registration_rules (**x):
mylist = []
for usname in x.keys():
    if (len(usname) >= 4) and (usname != 'quera' and usname != 'codecup') and (len(x[usname]) >= 6 ):
        mylist.append(usname)
return mylist

But it is necessary to find out whether the password of a username is just a string of numbers or not. If it is a string of numbers, it does not have the necessary conditions.
I did not find a solution to this

Body:
In Python you can check if a string is made out of only digits with str.isdigit().

>>> "42".isdigit()
True
>>> "53SS0".isdigit()
False

In your case something like this should work:

if (not usname.isdigit()):
    ...


来源: stackexchange

问:
How to Host HTML on a different server than Heroku
I have my index.html and the necessary .js files on heroku. Everything works fine. Now, I don't want to send my users to "myappname.herokuapp.com", so I plan to use my own website to store the .html file, but when the user taps "submit" on my HTML form, I want to execute the Herok NodeJS code.

Here is what the html looks like

```<code><script>
  const form = document.querySelector("form");

  form.addEventListener("submit", async (e) => {
    e.preventDefault();

    try {
      displayStatus("processing...");
      const request = new Request("/file-upload", {
        method: "POST",
        body: new FormData(form),
      });
      const res = await fetch(request);
      const resJson = await res.json();
      displayResult(resJson.result);
    } catch (err) {
      displayStatus("an unexpected error");
      console.error(err);
    }
  });

  function displayResult(result) {
    const content = `Your ID: ${result.id}`;
    displayStatus(content);
  }

  function displayStatus(msg) {
    result.textContent = msg;
  }
</script>
</code>```

How can I call this "/file-upload" from my HTML that is located on "mywebsite.com/index.html" while the actual NodeJS logic runs on "myappname.herokuapp.com"

I've tried to replace the "/file-upload" with "myappname.herokuapp.com/file-upload" but it doesn't work.

Again, the goal is to use what I have on Heroku, but not have the users go to "myappname.herokuapp.com" instead they should go to "mywebsite.com/index.html"

Thank you

答: Actually, replacing "/file-upload" with "myappname.herokuapp.com/file-upload" did the trick. The only issue is my "const request = new Request" request returning an error all the time, but Heroku logs shows a successful execution of "file-upload"</p>

ContentLicense: CC BY-SA 4.0

Body:
I have my index.html and the necessary .js files on heroku. Everything works fine. Now, I don't want to send my users to "myappname.herokuapp.com", so I plan to use my own website to store the .html file, but when the user taps "submit" on my HTML form, I want to execute the Herok NodeJS code.

Here is what the html looks like

How can I call this "/file-upload" from my HTML that is located on "mywebsite.com/index.html" while the actual NodeJS logic runs on "myappname.herokuapp.com"

I've tried to replace the "/file-upload" with "myappname.herokuapp.com/file-upload" but it doesn't work.

Again, the goal is to use what I have on Heroku, but not have the users go to "myappname.herokuapp.com" instead they should go to "mywebsite.com/index.html"

Thank you


问:
Finding _and then clicking_ ListBox Items from another program built in VB6 (ThunderRT6ListBox)
wracking my brain on this one.

I have successfully utilized this link to successfully grab text of the items of a ListBox (ThunderRT6ListBox specifically) working with WinAPI functions.  What I want to accomplish is to select and then double-click the necessary item from this list.  I've successfully been able to find the WindowRect of the ListBox itself, but I cannot get the cursor position relative to this Box and desired item.

I have to submit a double-click on this as the author of the application I'm ScreenScraping set the double-click event of the item to open a child window where parameters are set relative to the selected item.

I'm only going to post the part where I'm having trouble - again - I've successfully found the data and have been able to get the WindowRect of the ListBox - I'm now trying to click and double-click the item needed.  I imagine I need to then set my mouse cursor position using another winAPI, but when attempting to get the WindowRect of the Item it fails and gives a 0 for both x,y coordinates.  I have also tried SendKeys and other variants of this with an attempt to "Select" the item by value. . . this also fails.

I am writing in VB.NET but do not mind answers posted with C#, as there are converters and these answers are more prevalent for everything anyway (which is also helping me to learn that language too).

 Public Function GetListBoxContents(ByVal listBoxHwnd As IntPtr) As List(Of String)
    Dim cnt As Integer = CInt(SendMessage(listBoxHwnd, LB_GETCOUNT, IntPtr.Zero, Nothing))

    Dim listBoxContent As List(Of String) = New List(Of String)()

    For i As Integer = 0 To cnt - 1
      Dim sb As StringBuilder = New StringBuilder(256)
      Dim getTextLen As Integer = CInt(SendMessage(listBoxHwnd, LB_GETTEXTLEN, Nothing, Nothing))
      Dim getText As IntPtr = SendMessage(listBoxHwnd, LB_GETTEXT, CType(i, IntPtr), sb)
      Dim ComRect As RECT
      GetWindowRect(listBoxHwnd, ComRect)
      Debug.Print("Rect's x coordinate = " & ComRect.x) 'Produces valid X coord when looking
                                                         at listboxHwnd - if I look at "getText"
                                                         it fails - I assume because this really
                                                         is not
      Debug.Print("Rect's y coordinate = " & ComRect.y)
      Dim lparam As Integer = MakeLong(ComRect.x, ComRect.y)
      SetForegroundWindow(listBoxHwnd)
      If sb.ToString Like "*COM5*" Then
        Debug.Print("hWnd of ListBox item = ", getText)
        WindowsEnumerator.SendMessage(getText, WM_LBUTTONDOWN, &H1, lparam)
        WindowsEnumerator.SendMessage(getText, WM_LBUTTONUP, &H1, lparam)

        PostMessage(getText, WM_LBUTTONDBLCLK, &H1, lparam)

        PostMessage(getText, BM_CLICK, &H1, lparam)

        SendInputs.Mouse_Click()

        SendInputs.SendKey(Convert.ToChar(13))

        SendKeys.SendWait("{ENTER}")

      End If
      listBoxContent.Add(sb.ToString)
    Next

    Return listBoxContent
  End Function
```

答:
Based on the suggestions from both @IInspectable and @Charles, UI Automation is DEFINITELY the way to go.  I've always had a bit of a problem trudging through the MSDN Articles for each method because often times they use C++ or C# code (I guess someday I'll need to really learn these languages, but I digress).

For those who are intimidated by the UI Automation Approach, I'm leaving my other answer because it would be useful if you can master it. . . but it is literally reinventing UI Automation to try and DO IT!

Using the MSDN Documentation mostly confused me until I learned the structures of the Elements/Properties, etc.  (Further research also shows I could combine properties using AndCondition to build conjunctive properties.  This is well and great, however, I have to credit This YouTube Video which takes a UI Automation approach to reading text for getting me over the hump.  Sure it's a totally different approach/use case, BUT the structures are the same, and the author of the Video (Tech Savvy) uses VB.Net language which is what I really needed.

Below is the entire subroutine I built - from scratch yet!  I'm sure I can improve it, but for a first attempt at working with UI Automation I was able to accomplish the ENTIRE process needed, NOT just only a smidgen of some of the work, and it is MUCH. . . . MUCH easier long-run, so THANK YOU ALL for the suggestions to move to UI Automation - this is ABSOLUTELY the best move!  I felt like I gained a 'Level Up' in my coding.  <3

Note: When dealing with legacy objects from VB6 (Thunder Frames, etc), there is thankfully a LocalizedControlType Property which can be used to find your items as you walk the subtree of your initial program!

Note2: You'll notice I'm using a Click_Object routine for my calls. . .  This is NOT using the Invoke method because I had trouble with Invoke calls hanging for up to 10 Seconds or more for a simple button click.  I know I can call these using a separate thread dispatcher, but I ultimately went with Microsft.TestAPI's Mouse Class and the Click/MoveTo Methods therein as suggested in This SO Article.

  Public Shared Sub FindHMUtil(ByVal ComNum As String)
    Dim mW As MainWindow = CType(Application.Current.MainWindow, MainWindow)
    'If utility is open - need to kill it and restart.
    If Process.GetProcessesByName("hmutility").Count > 0 Then
      Commands(0, 0) = "/C TaskKill /FI ""imagename eq hmutility.exe"" /F"
      Commands(1, 0) = "Successfully able to kill Firmware Utility."
      Commands(2, 0) = "Unable TypeOf kill Firmware Utility."
      Commands(3, 0) = "Restarting TPG Printer Firmware Utility"
      Commands(4, 0) = "Confirming TPG Printer Firmware"
      Commands(5, 0) = "False"
      MyProcessControl.ProcessCommandLine("cmd.exe", Commands, mW.PrinterCheckText2)

    End If

    'Restart Utility
    Commands(0, 0) = "/C Start ""HmUtil"" ""C:\Program Files (x86)\hmUtility\hmUtility.exe"""
    Commands(1, 0) = "Successfully Able to Start Firmware Utility"
    Commands(2, 0) = "Unable to Start Firmware Utility"
    Commands(3, 0) = "Restarting TPG Printer Firmware Utility"
    Commands(4, 0) = "Confirming TPG Printer Firmware"
    Commands(5, 0) = "False"
    MyProcessControl.ProcessCommandLine("cmd.exe", Commands, mW.PrinterCheckText2)
    Thread.Sleep(350)

    Dim enumerator As New WindowsEnumerator

    'get handle for initial window
    'Note - FindWindow API will not find ThunderForm Windows with WindowTitle if they are part of a Thunder Wrapper!!!!
    'Leaving this as a construct for myself
    Dim hmImg As IntPtr = enumerator.FindWindowInt(Nothing, "Image")
    If hmImg = IntPtr.Zero Or hmImg = vbEmpty Or hmImg = 0 Or hmImg = vbNull Then
      'keeping as a reminder - sometimes the findwindow API will not find the ThunderForm
      hmImg = enumerator.FindWindowInt(ThunderForm, Nothing)
      If hmImg = IntPtr.Zero Or hmImg = vbEmpty Or hmImg = 0 Or hmImg = vbNull Then
        hmImg = enumerator.FindWindowExInt(Nothing, Nothing, ThunderForm, Nothing)
        Debug.Print("Still found nothing mate!")
      End If
    End If
    'get initial window element
    Dim hmWind As AutomationElement = AutomationElement.FromHandle(hmImg)

    'Get first set of Elements needed from initial window.  NOTE: Not all are used immediately, but keeping them read prevents need to find them a 2nd time.
    Dim hmWindExecute As AutomationElement = hmWind.FindFirst(TreeScope.Subtree, New PropertyCondition(AutomationElement.NameProperty, "Execute"))
    Dim hmWindResetPrntr As AutomationElement = hmWindExecute.FindFirst(TreeScope.Subtree, New PropertyCondition(AutomationElement.NameProperty, "Reset Printer"))
    Dim hmWindSetup As AutomationElement = hmWindExecute.FindFirst(TreeScope.Subtree, New PropertyCondition(AutomationElement.NameProperty, "Setup"))
    Dim hmWindSend As AutomationElement = hmWindExecute.FindFirst(TreeScope.Subtree, New PropertyCondition(AutomationElement.NameProperty, "Send"))
    Dim hmWindClearStat As AutomationElement = hmWindExecute.FindFirst(TreeScope.Subtree, New PropertyCondition(AutomationElement.NameProperty, "Clear Status"))
    Dim hmWindFLashHndl As IntPtr = enumerator.FindWindowExInt(Nothing, Nothing, ThunderFrame, "Flash File Selection")
    Dim hmWindPane As AutomationElement = hmWind.FindFirst(TreeScope.Subtree, New PropertyCondition(AutomationElement.LocalizedControlTypeProperty, "pane"))
    Dim hmWindPaneBtns As AutomationElementCollection = hmWindPane.FindAll(TreeScope.Subtree, New PropertyCondition(AutomationElement.LocalizedControlTypeProperty, "button"))

    Click_Object(hmWindPaneBtns(4), hmWindPaneBtns(4).GetClickablePoint)

    Dim hmWindFlashFileFrame As AutomationElement = hmWind.FindFirst(TreeScope.Subtree, New PropertyCondition(AutomationElement.NameProperty, "Flash File Selection"))
    Dim hmWindFlashFileBox As AutomationElement = hmWindFlashFileFrame.FindFirst(TreeScope.Subtree, New PropertyCondition(AutomationElement.LocalizedControlTypeProperty, "edit"))

    Click_Object(hmWindSetup, hmWindSetup.GetClickablePoint)

    'Get handle for new setup window
    Dim hmSetup As IntPtr = enumerator.FindWindowExInt(Nothing, Nothing, ThunderForm, "Setup")
    If hmSetup = IntPtr.Zero Or hmSetup = 0 Or hmSetup = vbEmpty Or hmSetup = vbNull Then
      hmSetup = enumerator.FindWindowExInt(Nothing, Nothing, ThunderForm, Nothing)
    End If

    'Get new window with listbox of ComPorts and get other controls inside new window
    Dim hmSetupWind As AutomationElement = AutomationElement.FromHandle(hmSetup)
    Dim hMSetupRemove As AutomationElement = hmSetupWind.FindFirst(TreeScope.Subtree, New PropertyCondition(AutomationElement.NameProperty, "Remove"))
    Dim hmSetupOk As AutomationElement = hmSetupWind.FindFirst(TreeScope.Subtree, New PropertyCondition(AutomationElement.NameProperty, "OK"))
    Dim hmSetupON As AutomationElement = hmSetupWind.FindFirst(TreeScope.Subtree, New PropertyCondition(AutomationElement.NameProperty, "On"))
    Dim hmSetupClear As AutomationElement = hmSetupWind.FindFirst(TreeScope.Subtree, New PropertyCondition(AutomationElement.NameProperty, "Clear"))
    Dim hmSetupStatList As AutomationElement
    Dim hmListHndl As IntPtr = enumerator.FindWindowExInt(Nothing, Nothing, ThunderList, Nothing)

    Dim hmListBox As AutomationElement
    If hmListHndl = IntPtr.Zero Or hmListHndl = 0 Or hmListHndl = vbEmpty Or hmListHndl = vbNull Then
      hmListBox = hmSetupWind.FindFirst(TreeScope.Subtree, New PropertyCondition(AutomationElement.LocalizedControlTypeProperty, "list"))
    Else
      hmListBox = AutomationElement.FromHandle(hmListHndl)

    End If
    'Get all ListBoxes of the new window
    Thread.Sleep(250)

    Dim hmSetupParent As TreeWalker
    'iterating through all listboxes - if not original list box then
    Dim checkItm As AutomationElement
    Dim checkItmCache As New CacheRequest
    checkItmCache.Add(AutomationElement.LocalizedControlTypeProperty)
    Click_Object(hMSetupRemove, hMSetupRemove.GetClickablePoint)

    Dim hmListItems As AutomationElementCollection = hmListBox.FindAll(TreeScope.Subtree, New PropertyCondition(AutomationElement.LocalizedControlTypeProperty, "list item"))

    For Each hmListItem As AutomationElement In hmListItems
      If hmListItem.Current.Name = ComNum Then
        'DoubleClick list item for ComPort of Printer
        hmListItem.SetFocus()
        DoubleClick_Object(hmListItem, hmListItem.GetClickablePoint)
        'Get info for new Window
        Dim hmPortSetupWindHndl As IntPtr = enumerator.FindWindowExInt(Nothing, Nothing, ThunderForm, Nothing)
        Dim hmPortsetupOK As AutomationElement = AutomationElement.FromHandle(hmPortSetupWindHndl).FindFirst(TreeScope.Subtree, New PropertyCondition(AutomationElement.NameProperty, "Ok"))
        'Click OK on new window with Port Settings - Defaults are fine.
        Click_Object(hmPortsetupOK, hmPortsetupOK.GetClickablePoint)

        'Turn port ON
        Click_Object(hmSetupON, hmSetupON.GetClickablePoint)

        'Get items from Status Boxt
        Dim hmSetupStatFind As TreeWalker

        Click_Object(hmSetupOk, hmSetupOk.GetClickablePoint)
        Exit For
      End If
    Next hmListItem

    Click_Object(hmWindFlashFileBox, hmWindFlashFileBox.GetClickablePoint)
    My.Computer.Clipboard.SetText(MyProcessControl.myPath & "TPG\189-798F304A.BIN")
    My.Computer.Keyboard.SendKeys("^V", True)

    Click_Object(hmWindSend, hmWindSend.GetClickablePoint)

    Dim hmStatus As AutomationElement = hmWind.FindFirst(TreeScope.Subtree, New PropertyCondition(AutomationElement.NameProperty, "Status"))
    Dim SectorStrng As String = "Derps"
    Do Until SectorStrng.Contains(ComNum & " open")
      Dim hmStatLines As AutomationElementCollection = hmStatus.FindAll(TreeScope.Subtree, New PropertyCondition(AutomationElement.LocalizedControlTypeProperty, "list item"))
      For a = 0 To hmStatLines.Count - 1
        If hmStatLines(a).Current.Name.Contains(ComNum & " open") Then
          SectorStrng = hmStatLines(a).Current.Name
        End If
      Next
      Dim e As EventArgs
      MyProcessControl.ForceUIToUpdate()
      MyProcessControl.OnTimedEvent(mW, e)
    Loop

    If Process.GetProcessesByName("hmutility").Count > 0 Then
      Commands(0, 0) = "/C TaskKill /FI ""imagename eq hmutility.exe"" /F"
      Commands(1, 0) = "Successfully able to kill Firmware Utility."
      Commands(2, 0) = "Unable TypeOf kill Firmware Utility."
      Commands(3, 0) = "Restarting TPG Printer Firmware Utility"
      Commands(4, 0) = "Confirming TPG Printer Firmware"
      Commands(5, 0) = "False"
      MyProcessControl.ProcessCommandLine("cmd.exe", Commands, mW.PrinterCheckText2)

    End If

  End Sub

  Public Shared Sub DoubleClick_Object(givenElement As AutomationElement, mousePoint As Point)
    givenElement.SetFocus()
    'Adding a 1/4 second sleep ensures object has proper focus before clicking - sometimes the routines moved too fast and threw an exception.
    Thread.Sleep(250)
    Input.Mouse.MoveTo(New System.Drawing.Point(mousePoint.X, mousePoint.Y))
    Input.Mouse.DoubleClick(Input.MouseButton.Left)
  End Sub

  Public Shared Sub Click_Object(givenElement As AutomationElement, mousePoint As Point)

    givenElement.SetFocus()
    Thread.Sleep(250)
    Input.Mouse.MoveTo(New System.Drawing.Point(mousePoint.X, mousePoint.Y))
    Input.Mouse.Click(Input.MouseButton.Left)

  End Sub

```


问:
Is there an efficient algorithm to perform inverted full text search?
I have a limited list of thousands of keywords (of one or more words in each keyword) in a database. I want to efficiently find which of those keywords are in given input text without having to test each of those keywords one by one (full table scan). Allowing to match some misspelled words in the text would be even better but not essential. Any algorithm/article suggestions to solve this?</p>

答:
You can use any of the given solutions described, however they all fundamentally do the same thing (then add bells and whistles)

So the basic approach is:

Split your search input into words

Remove noise (this might be very common words, punctuation, etc)

Your database should contain your keyphrases (you said a keyword could have multiple words, so
its a keyphrase)

You have a map of the words in a keyphrase

e.g.

keyphraseID:1 keyphrase:"the quick brown fox"

wordID:1 Word:the

wordID:2 Word:quick

mapID: 1 keyphraseID: 1 wordID: 1 position: 1

mapID: 2 keyphraseID: 1 wordID: 2 position: 2

Now you have a basic inverse index, and by putting a unique index on the word column - you avoid a full table scan.

Fuzzyness/spelling adjustments can be added by including things like Levenshtein distance, soundex or latent semantic indexing - a lot depends upon what you are doing, there is loads of research available on this.

Edit:-

You could also look at stemming - where you take words back to the same root e.g. fixing and fixed both root in 'fix'. A common stemming algorithm is called porter.

OwnerDisplayName: Antonio Leitao

ContentLicense: CC BY-SA 3.0

OwnerDisplayName: Jonno


答:
I think some of the answers so far are misunderstanding the problem that is being asked. My understanding is that you've got a (largish) list of words and a (largish) body of text. You want to know which words both lists have in common, is that correct?

If so, this isn't really a full-text problem at all. Basically, you just have two lists of words (your original keywords, and a list of words from the input text). If you sort both lists you can scan through both lists simultaneously and extract the words that are in common.

Assuming the list of keywords is already sorted, you can extract and sort the words from the body of text in O(n logn) time, and then scanning through both lists simultaneously is O(n+m) (where n is the number of words in the body of text and m is the number of words in the keyword list).

Title: Is there an efficient algorithm to perform inverted full text search?

Body: I have a limited list of thousands of keywords (of one or more words in each keyword) in a database. I want to efficiently find which of those keywords are in given input text without having to test each of those keywords one by one (full table scan). Allowing to match some misspelled words in the text would be even better but not essential. Any algorithm/article suggestions to solve this?

OwnerDisplayName: Dean Harding


问:
order of expansion between variable expansion and command substitution
The bash man says that variable expansion occurs before command substitution. I was seeking of an example that shows it clearly. So i tried this:

```<code>root@antec:/# var=1
root@antec:/# echo $(var=2; echo $var)
2
root@antec:/#
</code>```

I was expecting bash to do:

1) replace $var by "1" in the substitution

2) execute echo $(var=2; echo 1)

Obviously this is not what bash is doing ..

Can someone please explain what is going one here ? And if someone has an example showing the precedence of variable expansion over command substitution it would be nice too

答:
In newer bash man pages, they put semicolons to indicate the precedence:

The order of expansions is: brace expansion ; tilde expansion, parameter and variable expansion, arithmetic expansion, and command substitution (done in a left-to-right fashion) ; word splitting ; and pathname expansion.

And from the code you can see that a $ triggers the param_expand function, which will do command substitution or variable expansion if the next character is a parenthesis or a name respectively. It will not do an additional variable expansion in command_substitute.

Body:
The bash man says that variable expansion occurs before command substitution. I was seeking of an example that shows it clearly. So i tried this:

root@antec:/# var=1
root@antec:/# echo $(var=2; echo $var)
2
root@antec:/#

I was expecting bash to do:

1) replace $var by "1" in the substitution

2) execute echo $(var=2; echo 1)

Obviously this is not what bash is doing ..

Can someone please explain what is going one here ? And if someone has an example showing the precedence of variable expansion over command substitution it would be nice too


问:
Can't control floating button for KivyMD FIleManager
I'm trying to use the FileManager for KivyMD to select and execute a function using a certain path, but I can't assign a function to the floating checkmark button in the FileManager. I read something in the docs about the select_directory_on_press_button attribute, but it isn't working for me.

Here is my code:

from kivymd.app import MDApp
from kivymd.uix.screen import MDScreen
from kivymd.uix.toolbar import MDToolbar
from kivymd.uix.filemanager import MDFileManager
from kivymd.uix.button import MDFlatButton
from kivymd.toast import toast

class MyApp(MDApp):
    def select_path(self, path, args):
        print("selected")
        self.file_manager.current_path = path

    def exit_manager(self, args):
        self.file_manager.close()

    def confirm(self):
        print("confirmed")
        self.file_manager.close()
        print(open(self.file_manager.current_path).read())

    def fileman(self, args):
        self.file_manager = MDFileManager(
            exit_manager = self.exit_manager,
            ext = [".txt"]
        )

        self.file_manager.select_dir_or_file = self.select_path

        self.file_manager.select_directory_on_press_button = self.confirm

        self.file_manager.show("C:/Users/hiami/Downloads/")

    def build(self):
        screen = MDScreen()

        screen.add_widget(MDFlatButton(
            text = "press me",
            pos_hint = {"center_x": 0.5, "center_y": 0.5},
            on_release = self.fileman
        ))

        return screen

MyApp().run()
```

答:
When you tap on a file or dir, the method select_dir_or_file is automatically called and current path is set. Thus you don't need these lines, self.file_manager.select_dir_or_file = self.select_path and

self.file_manager.select_directory_on_press_button = self.confirm (This will call self.select_path internally)

I added a toast message in the method select_path

    def select_path(self, path, *args):
        toast(path)
        print("selected")
        #self.file_manager.current_path = path # This is automatically set.
```

Also all your 'args' are supposed to be varargs or '*args'.

Body:
When you tap on a file or dir, the method select_dir_or_file is automatically called and current path is set. Thus you don't need these lines, self.file_manager.select_dir_or_file = self.select_path and

self.file_manager.select_directory_on_press_button = self.confirm (This will call self.select_path internally)

I added a toast message in the method select_path

    def select_path(self, path, *args):
        toast(path)
        print("selected")
        #self.file_manager.current_path = path # This is automatically set.

Also all your 'args' are supposed to be varargs or '*args'.


问:
Why can't I iterate twice over the same iterator? How can I "reset" the iterator or reuse the data?
Consider the code:

def test(data):
    for row in data:
        print("first loop")
    for row in data:
        print("second loop")
```
<p>When <code>data</code> is an iterator, for example a list iterator or a generator expression<sup>*</sup>, this does not work:</p>
```>>> test(iter([1, 2]))
first loop
first loop
>>> test((_ for _ in [1, 2]))
first loop
first loop
```
<p>This prints <code>first loop</code> a few times, since <code>data</code> is non-empty. However, it does <em>not</em> print <code>second loop</code>. <strong>Why does iterating over <code>data</code> work the first time, but not the second time? How can I make it work a second time?</strong></p>
<p>Aside from <code>for</code> loops, the same problem appears to occur with any kind of iteration: list/set/dict comprehensions, passing the iterator to <code>list()</code>, <code>sum()</code> or <code>reduce()</code>, etc.</p>
<p>On the other hand, if <code>data</code> is another kind of iterable, such as a <code>list</code> or a <code>range</code> (which are both sequences), both loops run as expected:</p>
```>>> test([1, 2])
first loop
first loop
second loop
second loop
>>> test(range(2))
first loop
first loop
second loop
second loop
```

* More examples:

file objects

generators created from an explicit generator function

filter, map, and zip objects (in 3.x)

enumerate objects

csv.readers

various iterators defined in the itertools standard library

For general theory and terminology explanation, see What are iterator, iterable, and iteration?.

To detect whether the input is an iterator or a "reusable" iterable, see Ensure that an argument can be iterated twice.

答:
Iterators (e.g. from calling iter, from generator expressions, or from generator functions which yield) are stateful and can only be consumed once.

This is explained in Óscar López's answer, however, that answer's recommendation to use itertools.tee(data) instead of list(data) for performance reasons is misleading.
In most cases, where you want to iterate through the whole of data and then iterate through the whole of it again, tee takes more time and uses more memory than simply consuming the whole iterator into a list and then iterating over it twice. According to the documentation:

This itertool may require significant auxiliary storage (depending on how much temporary data needs to be stored). In general, if one iterator uses most or all of the data before another iterator starts, it is faster to use list() instead of tee().

tee may be preferred if you will only consume the first few elements of each iterator, or if you will alternate between consuming a few elements from one iterator and then a few from the other.

Body:
Consider the code:

def test(data):
    for row in data:
        print("first loop")
    for row in data:
        print("second loop")

When data is an iterator, for example a list iterator or a generator expression*, this does not work:

>>> test(iter([1, 2]))
first loop
first loop
>>> test((_ for _ in [1, 2]))
first loop
first loop

This prints first loop a few times, since data is non-empty. However, it does not print second loop. Why does iterating over data work the first time, but not the second time? How can I make it work a second time?

Aside from for loops, the same problem appears to occur with any kind of iteration: list/set/dict comprehensions, passing the iterator to list(), sum() or reduce(), etc.

On the other hand, if data is another kind of iterable, such as a list or a range (which are both sequences), both loops run as expected:

>>> test([1, 2])
first loop
first loop
second loop
second loop
>>> test(range(2))
first loop
first loop
second loop
second loop

* More examples:

file objects

generators created from an explicit generator function

filter, map, and zip objects (in 3.x)

enumerate objects

csv.readers

various iterators defined in the itertools standard library

For general theory and terminology explanation, see What are iterator, iterable, and iteration?.

To detect whether the input is an iterator or a "reusable" iterable, see Ensure that an argument can be iterated twice.


答:
The right way to do so would be to build an Automaton.

An Automaton is (by definition) built to recognize words of a language, which in this case is your collection of keywords.

Of course, in your case, it's a bit more complicated, because you may have overlapping keywords, but it's not that different either.

So, from a pure theoretical point of view:

Build an Automaton from your set of keywords

Scan the body of text thanks to that Automaton

The latter part is O(n), the former may be a bit trickier.

OwnerDisplayName: Matthieu M.


问:
Adding new column to DataFrame using a list
I am scraping the stock prices, and names from Yahoo's finance website. After making a dataframe with three columns "Name", "Code", and "Price" and representing the passed index variable. I want to go to another loop and add a column to the original dataframe with updated prices. But when I add the column it creates NaN values for my original data. What do I need to do to correctly place the indexes and not disturb the original dataframe data?</p>
```<code>class Stocks():
    def __init__(self):
        return self

    def Stock_ABV(str):
        pattern = re.compile(r'/([A-Z]*-[A-Z]*|[A-Z]*)')
        match = pattern.finditer(str)
        length = len(str)
        for match in match:
            name = match.group(0)
        return match.group(0)[1:length]

    def Yahoo_Finance(index):
        url_list = ['https://finance.yahoo.com/quote/GOOG','https://finance.yahoo.com/quote/DOGE-USD',
                'https://finance.yahoo.com/quote/AAPL', 'https://finance.yahoo.com/quote/HMC',
                'https://finance.yahoo.com/quote/TM', 'https://finance.yahoo.com/quote/DKS',
                'https://finance.yahoo.com/quote/SHIB-USD', 'https://finance.yahoo.com/quote/BTC-USD',
                'https://finance.yahoo.com/quote/WMT', 'https://finance.yahoo.com/quote/AMZN',
                'https://finance.yahoo.com/quote/NKE', 'https://finance.yahoo.com/quote/KO',
                'https://finance.yahoo.com/quote/PEP', 'https://finance.yahoo.com/quote/DAL',
                'https://finance.yahoo.com/quote/SAVE', 'https://finance.yahoo.com/quote/BLL',
                'https://finance.yahoo.com/quote/KMB', 'https://finance.yahoo.com/quote/GIS']
        url = ''
        i = 0
        L1 = []
        L2 = []
        structure = pd.DataFrame({'Name': [], 'Code': [], 'Price': []})
        if index == 1:
            while i < len(url_list):
                url = url + url_list[i]
                req = requests.get(url)
                soup = BeautifulSoup(req.text, 'html.parser')
                name = soup.find('h1', {'class': 'D(ib) Fz(18px)'}).text
                price = soup.find('fin-streamer', {'class': 'Fw(b) Fz(36px) Mb(-4px) D(ib)'}).text
                L1.append([name,Stocks.Stock_ABV(url_list[i]),price])
                df = pd.DataFrame(L1, columns = ['Name', 'Code', 'Price'])
                i += 1
                url = ''
            structure = df
            structure = structure.set_index(df.index)
        else:
            while i < len(url_list):
                req = requests.get(url_list[i])
                soup = BeautifulSoup(req.text, 'html.parser')
                price = soup.find('fin-streamer', {'class': 'Fw(b) Fz(36px) Mb(-4px) D(ib)'}).text
                L2.append(price)
                df2 = pd.DataFrame(L2, columns = [f'Price{index}'])
                i += 1
                url = ''
            structure[f'Price{index}'] = L2

        pd.set_option('display.max_rows', None)
        return structure

    def AFK_Runner():
        Stocks.Yahoo_Finance(1)

        return Stocks.Yahoo_Finance(2)

Stocks.AFK_Runner()
</code>```

Body:
I am scraping the stock prices, and names from Yahoo's finance website. After making a dataframe with three columns "Name", "Code", and "Price" and representing the passed index variable. I want to go to another loop and add a column to the original dataframe with updated prices. But when I add the column it creates NaN values for my original data. What do I need to do to correctly place the indexes and not disturb the original dataframe data?

class Stocks():
    def __init__(self):
        return self

    def Stock_ABV(str):
        pattern = re.compile(r'/([A-Z]*-[A-Z]*|[A-Z]*)')
        match = pattern.finditer(str)
        length = len(str)
        for match in match:
            name = match.group(0)
        return match.group(0)[1:length]

    def Yahoo_Finance(index):
        url_list = ['https://finance.yahoo.com/quote/GOOG','https://finance.yahoo.com/quote/DOGE-USD',
                'https://finance.yahoo.com/quote/AAPL', 'https://finance.yahoo.com/quote/HMC',
                'https://finance.yahoo.com/quote/TM', 'https://finance.yahoo.com/quote/DKS',
                'https://finance.yahoo.com/quote/SHIB-USD', 'https://finance.yahoo.com/quote/BTC-USD',
                'https://finance.yahoo.com/quote/WMT', 'https://finance.yahoo.com/quote/AMZN',
                'https://finance.yahoo.com/quote/NKE', 'https://finance.yahoo.com/quote/KO',
                'https://finance.yahoo.com/quote/PEP', 'https://finance.yahoo.com/quote/DAL',
                'https://finance.yahoo.com/quote/SAVE', 'https://finance.yahoo.com/quote/BLL',
                'https://finance.yahoo.com/quote/KMB', 'https://finance.yahoo.com/quote/GIS']
        url = ''
        i = 0
        L1 = []
        L2 = []
        structure = pd.DataFrame({'Name': [], 'Code': [], 'Price': []})
        if index == 1:
            while i < len(url_list):
                url = url + url_list[i]
                req = requests.get(url)
                soup = BeautifulSoup(req.text, 'html.parser')
                name = soup.find('h1', {'class': 'D(ib) Fz(18px)'}).text
                price = soup.find('fin-streamer', {'class': 'Fw(b) Fz(36px) Mb(-4px) D(ib)'}).text
                L1.append([name,Stocks.Stock_ABV(url_list[i]),price])
                df = pd.DataFrame(L1, columns = ['Name', 'Code', 'Price'])
                i += 1
                url = ''
            structure = df
            structure = structure.set_index(df.index)
        else:
            while i < len(url_list):
                req = requests.get(url_list[i])
                soup = BeautifulSoup(req.text, 'html.parser')
                price = soup.find('fin-streamer', {'class': 'Fw(b) Fz(36px) Mb(-4px) D(ib)'}).text
                L2.append(price)
                df2 = pd.DataFrame(L2, columns = [f'Price{index}'])
                i += 1
                url = ''
            structure[f'Price{index}'] = L2

        pd.set_option('display.max_rows', None)
        return structure

    def AFK_Runner():
        Stocks.Yahoo_Finance(1)

        return Stocks.Yahoo_Finance(2)

Stocks.AFK_Runner()

Body:
Do you know the yfinance package?

# pip install yfinance
import yfinance as yf

data = yf.download('GOOG DOGE-USD AAPL HMC')

Output:

             Adj Close                                         Close                                    ...        Open                                        Volume
                  AAPL  DOGE-USD         GOOG        HMC        AAPL  DOGE-USD         GOOG        HMC  ...        AAPL  DOGE-USD         GOOG        HMC        AAPL      DOGE-USD       GOOG        HMC
Date                                                                                ...
1980-03-17         NaN       NaN          NaN   0.718973         NaN       NaN          NaN   0.893750  ...         NaN       NaN          NaN   0.893750         NaN           NaN        NaN    26000.0
1980-03-18         NaN       NaN          NaN   0.731542         NaN       NaN          NaN   0.909375  ...         NaN       NaN          NaN   0.909375         NaN           NaN        NaN     2000.0
1980-03-19         NaN       NaN          NaN   0.724001         NaN       NaN          NaN   0.900000  ...         NaN       NaN          NaN   0.900000         NaN           NaN        NaN     2000.0
1980-03-20         NaN       NaN          NaN   0.724001         NaN       NaN          NaN   0.900000  ...         NaN       NaN          NaN   0.900000         NaN           NaN        NaN        0.0
1980-03-21         NaN       NaN          NaN   0.724001         NaN       NaN          NaN   0.900000  ...         NaN       NaN          NaN   0.900000         NaN           NaN        NaN     2000.0
...                ...       ...          ...        ...         ...       ...          ...        ...  ...         ...       ...          ...        ...         ...           ...        ...        ...
2022-02-09  176.279999  0.159123  2829.060059  30.500000  176.279999  0.159123  2829.060059  30.500000  ...  176.050003  0.158357  2816.995117  30.120001  71285000.0  7.786708e+08  1431400.0  1554600.0
2022-02-10  172.119995  0.151889  2772.050049  30.760000  172.119995  0.151889  2772.050049  30.760000  ...  174.139999  0.159145  2790.000000  31.000000  90865900.0  1.053631e+09  1650900.0  1398400.0
2022-02-11  168.639999  0.144847  2682.600098  30.459999  168.639999  0.144847  2682.600098  30.459999  ...  172.330002  0.151895  2775.000000  30.760000  98566000.0  7.767306e+08  1937700.0  1004200.0
2022-02-12         NaN  0.144405          NaN        NaN         NaN  0.144405          NaN        NaN  ...         NaN  0.144856          NaN        NaN         NaN  6.026994e+08        NaN        NaN
2022-02-13         NaN  0.153793          NaN        NaN         NaN  0.153793          NaN        NaN  ...         NaN  0.144308          NaN        NaN         NaN  1.346092e+09        NaN        NaN

[11055 rows x 24 columns]


问:
Dragging cursor does not apply cursor style change until drag is complete
I would like to follow up on this question:
Changing cursor on drag in openlayers 3

The answer provided is sound, and has a working example. I have used the basic OpenLayers quickstart code and added that user's answer to it to test, and I am sorry to say that it does not work.

What happens is that the cursor defined in "pointerup" is the starting cursor, and when you click and hold to drag the map around, it remains as that cursor until you let go of the mouse button to stop dragging. You'll see the hand icon change very briefly, then change back to the pointerup cursor. It is acting like the cursor cannot be changed while a dragging action is occurring.

What can be done to fix this?

Full code of my example file below. Please note that in jsfiddle, it demonstrates the expected behaviour. But when I make a file (eg. "test-drag.html") and load it up in Chrome, it acts as I described instead.

<link rel="stylesheet" href="https://openlayers.org/en/v4.6.5/css/ol.css" type="text/css">

```

答: The answer is that this is caused by Dev Tools being open, as mentioned in comments by @m.cekiera and @Psymøn.</p>


问:
How do I load url into Image into DrawImage in Compose UI Android Jetpack?
I can use
val image = +imageResource(R.drawable.header)
and use DrawImage(image) to load image from Drawable Resource,

But how do I load a string url into the DrawImage(image)?. I've tried using Glide, but it needs to load into imageView. meanwhile DrawImage(image) doesn't take input from imageView.

Thanks.

答:
Try to use https://github.com/skydoves/landscapist

It seems to be realy good library to load images along with glide, coil, etc
It enables to override handlers to do any custom things, e.q. when you got an error or during loading phase


问:
Node-sass related error attempting to setup Zurb Foundation 6 web project on Ubuntu20.04
Going to make a personal website and I want to use Zurb Foundation 6 for the framework.

I am running:

Ubuntu 20.04.3 LTS

Node 16.14.0

Npm 8.5.0

yarn 1.22.17

I am following this basic startup guide for the ZURB Foundation template. img of install instructions

I have tried installing with the Foundation CLI and the manual option both result in this error.

```<code>error /home/blake/gitworkspace/BlakeSite/node_modules/node-sass: Command failed.
</code>```

The error seems to be some consequence of node-sass.

The only lead I could find was here and I don't understand what to do with a bridge file or which one I would need.

Thanks for your help!

答: node-sass 4.14.1 doesn't support Node 16 https://github.com/sass/node-sass#node-version-support-policy. If you need that version, you need to use Node 14</p>

Body:
Going to make a personal website and I want to use Zurb Foundation 6 for the framework.

I am running:

Ubuntu 20.04.3 LTS

Node 16.14.0

Npm 8.5.0

yarn 1.22.17

I am following this basic startup guide for the ZURB Foundation template. img of install instructions

I have tried installing with the Foundation CLI and the manual option both result in this error.

error /home/blake/gitworkspace/BlakeSite/node_modules/node-sass: Command failed.

The error seems to be some consequence of node-sass.

The only lead I could find was here and I don't understand what to do with a bridge file or which one I would need.

Thanks for your help!


问:
POST variables won't arrive ... why?
I can't find the error. Why doesn't receive my result page the POST variables from my form? I do always get an empty array with my var_dump. Can anyone here help me out? The code is so simple that I don't know what further possible error sources I could remove. If I switch to GET it works instantly.

I'm testing this on my Debian old stable system which I have been using for such things for years now without issues. (But it doesn't work on my externally hosted web server either.)

My form.php:

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="device-width, initial-scale=1">
    <title>Form page</title>
</head>
<body>
    <form name="test" action="result.php" enctype="text/plain" method="post">
        <select name="chose">
            <option value="1">one</option>
            <option value="2">two</option>
            <option value="3">three</option>
        </select>
        <input type="submit" value="save">
    </form>
</body>
</html>
</code>```

My result.php:

```<code><?php
var_dump($_POST);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="device-width, initial-scale=1">
    <title>Result page</title>
</head>
<body>
    <h1>Result</h1>
    <p><a href="form.php">return</a></p>
</body>
</html>
</code>```

I think I'm getting crazy here. I must overlook something breathtakingly simple.

答:
enctype="text/plain" is designed to present form data in a human readable format for debugging. It is not machine processable (e.g. you can't distinguish between new lines in data and new lines between entries).

Remove that.

(I don't consider it very good for debugging anyway, the dev tools built into browsers can display URL encoded data in a human readable format)

PHP will automatically populate $_POST when data is encoded as application/x-www-form-urlencoded (the default for forms) or multipart/form-data (a chunkier format that supports file uploads).

Title: POST variables won't arrive ... why?

Body:
I can't find the error. Why doesn't receive my result page the POST variables from my form? I do always get an empty array with my var_dump. Can anyone here help me out? The code is so simple that I don't know what further possible error sources I could remove. If I switch to GET it works instantly.

I'm testing this on my Debian old stable system which I have been using for such things for years now without issues. (But it doesn't work on my externally hosted web server either.)

My form.php:

<!DOCTYPE html>

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

    <form name="test" action="result.php" enctype="text/plain" method="post">
        <select name="chose">
            <option value="1">one</option>
            <option value="2">two</option>
            <option value="3">three</option>
        </select>
        <input type="submit" value="save">
    </form>

My result.php:

<?php
var_dump($_POST);
?>
<!DOCTYPE html>

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

Result

return

I think I'm getting crazy here. I must overlook something breathtakingly simple.


问:
Convert hex value to decimal in C but keep getting incorrect value, plus too few argument error when calling func
Hello I am trying to convert a hex value into the decimal form but for some reason the result I'm getting each time is negative and completely incorrect. Additionally I would like to take that decimal number and then convert it into it binary value. I have created func's for both but have run into the problem of "too few arguments" when calling my bin() func. If somebody could point me in the right direction and explain what I am doing wrong I would sincerely appreciate it.

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

#define arraysize 20

int decimal() {

    int i = 0, val, len;
    char hex1[arraysize];
    long long dec = 0, base = 1;

    len = strlen(hex1);

    for (i = len--;i >= 0; i--) {
        if (hex1[1] >= '0' && hex1[i] <= '9') {
            dec += (hex1[i] - 48) * base;
            base *= 16;
        }
        else if (hex1[i] >= 'A' && hex1[i] <= 'F') {
            dec += (hex1[i] - 55) * base;
            base *= 16;
        }
        else if (hex1[i] >= 'a' && hex1[i] <= 'f') {
            dec += (hex1[i] - 87) * base;
            base *= 16;
        }
    }
    printf("Your decimal value is: %lld\n",dec);
    return 0;
}

int bin(long long dec) {

    int a[10], i;

    for (i = 0; dec > 0; i++) {
        a[i] = dec % 2;
        dec = dec / 2;
    }
    printf("\nThe binary value is: ");
    for (i = i - 1; i >= 0; i--) {
        printf("%d", a[i]);
    }
    return 0;
}

int main() {

    char hex1[arraysize];

    printf("Enter your HEX value: ");
    fflush(stdin);
    fgets(hex1, arraysize, stdin);

    decimal(hex1);
    bin();
}
</code>```

答:
The "too few arguments" error means exactly what it says: you are calling the bin() function with no arguments. In your function definition, you defined bin() as taking a long long dec argument. When you call bin(), you must give it an argument, like

```<code>bin(7);
</code>```

You have made the opposite mistake in the line above:

```<code>decimal(hex1);
</code>```

You defined decimal() as taking no arguments, yet you called it with a char[] argument. In your decimal function you can remove the line where you declare an array of chars, and instead make that an argument of the function:

```<code>int decimal(char* hex1) {

    int i = 0, val, len;
    long long dec = 0, base = 1;

    . . .
</code>```

You may want to further research the semantics of passing an array as an argument to a function.

Body:
Hello I am trying to convert a hex value into the decimal form but for some reason the result I'm getting each time is negative and completely incorrect. Additionally I would like to take that decimal number and then convert it into it binary value. I have created func's for both but have run into the problem of "too few arguments" when calling my bin() func. If somebody could point me in the right direction and explain what I am doing wrong I would sincerely appreciate it.

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

#define arraysize 20

int decimal() {

    int i = 0, val, len;
    char hex1[arraysize];
    long long dec = 0, base = 1;

    len = strlen(hex1);

    for (i = len--;i >= 0; i--) {
        if (hex1[1] >= '0' && hex1[i] <= '9') {
            dec += (hex1[i] - 48) * base;
            base *= 16;
        }
        else if (hex1[i] >= 'A' && hex1[i] <= 'F') {
            dec += (hex1[i] - 55) * base;
            base *= 16;
        }
        else if (hex1[i] >= 'a' && hex1[i] <= 'f') {
            dec += (hex1[i] - 87) * base;
            base *= 16;
        }
    }
    printf("Your decimal value is: %lld\n",dec);
    return 0;
}

int bin(long long dec) {

    int a[10], i;

    for (i = 0; dec > 0; i++) {
        a[i] = dec % 2;
        dec = dec / 2;
    }
    printf("\nThe binary value is: ");
    for (i = i - 1; i >= 0; i--) {
        printf("%d", a[i]);
    }
    return 0;
}

int main() {

    char hex1[arraysize];

    printf("Enter your HEX value: ");
    fflush(stdin);
    fgets(hex1, arraysize, stdin);

    decimal(hex1);
    bin();
}

Body:
The "too few arguments" error means exactly what it says: you are calling the bin() function with no arguments. In your function definition, you defined bin() as taking a long long dec argument. When you call bin(), you must give it an argument, like

bin(7);

You have made the opposite mistake in the line above:

decimal(hex1);

You defined decimal() as taking no arguments, yet you called it with a char[] argument. In your decimal function you can remove the line where you declare an array of chars, and instead make that an argument of the function:

int decimal(char* hex1) {

    int i = 0, val, len;
    long long dec = 0, base = 1;

    . . .

You may want to further research the semantics of passing an array as an argument to a function.


问:
Can i verify a list of xpaths at once?
I'm new using Robot Framework, so I created a Test Case to verify that a banch of elements exists on the target web page, so my question is instead of doing :

```<code>Page Should Contain Element    ${text_field1}
Page Should Contain Element    ${text_field2}
Page Should Contain Element    ${text_field3}
....
</code>```

can I do a list with these xpaths and verify if this list exists on the web page  at once ?
is there any robotframework function to do that ? thanks

答:
No, we don't have a keyword for multiple checking elements in pages. But we can create that logic in an user keyword. See below a fully working example.</p>
```<code>*** Settings ***
Library           SeleniumLibrary    15    2
Library           Collections

*** Variables ***
${BROWSER}        Chrome
@{elements}       xpath=//div[@id="error"]    id=searchInput    xpath=//button[@type="submit"]

*** Test Cases ***
Simple Test
    Open Browser    http://www.wikipedia.org    ${BROWSER}
    Comment    Wait Until Element Is Visible    id=searchInput    # search input field
    ${result}=    Page Should Contain Elements    ${elements}
    IF    not ${result}
        Fail    Page did not contained expected elements
    END
    Input Text    ${elements[0]}    Robot Framework
    Wait Until Element Is Visible    ${elements[1]}
    Click Button    ${elements[1]}
    Wait Until Page Contains    Robot Framework
    Capture Page Screenshot
    [Teardown]    Close All Browsers

*** Keywords ***
Page Should Contain Elements
    [Arguments]    ${elements}
    @{results}=    Create List
    FOR    ${element}    IN    @{elements}
        ${result}=    Run Keyword And Ignore Error    Page Should Contain Element    ${element}
        IF    "${result[0]}" == "FAIL"
            Append To List    ${results}    ${element}
        END
    END
    ${ret}=    Evaluate    len(${results}) == 0
    Return From Keyword If    ${ret}    True
    FOR    ${element}    IN    @{results}
        Log    Fail: Page should have contained element ${element} but it did not    WARN
    END
    Return From Keyword    False
</code>```

Title: Can i verify a list of xpaths at once?

Body:
I'm new using Robot Framework, so I created a Test Case to verify that a banch of elements exists on the target web page, so my question is instead of doing :

Page Should Contain Element    ${text_field1}
Page Should Contain Element    ${text_field2}
Page Should Contain Element    ${text_field3}
....

can I do a list with these xpaths and verify if this list exists on the web page  at once ?
is there any robotframework function to do that ? thanks

Body:
No, we don't have a keyword for multiple checking elements in pages. But we can create that logic in an user keyword. See below a fully working example.

*** Settings ***
Library           SeleniumLibrary    15    2
Library           Collections

*** Variables ***
${BROWSER}        Chrome
@{elements}       xpath=//div[@id="error"]    id=searchInput    xpath=//button[@type="submit"]

*** Test Cases ***
Simple Test
    Open Browser    http://www.wikipedia.org    ${BROWSER}
    Comment    Wait Until Element Is Visible    id=searchInput    # search input field
    ${result}=    Page Should Contain Elements    ${elements}
    IF    not ${result}
        Fail    Page did not contained expected elements
    END
    Input Text    ${elements[0]}    Robot Framework
    Wait Until Element Is Visible    ${elements[1]}
    Click Button    ${elements[1]}
    Wait Until Page Contains    Robot Framework
    Capture Page Screenshot
    [Teardown]    Close All Browsers

*** Keywords ***
Page Should Contain Elements
    [Arguments]    ${elements}
    @{results}=    Create List
    FOR    ${element}    IN    @{elements}
        ${result}=    Run Keyword And Ignore Error    Page Should Contain Element    ${element}
        IF    "${result[0]}" == "FAIL"
            Append To List    ${results}    ${element}
        END
    END
    ${ret}=    Evaluate    len(${results}) == 0
    Return From Keyword If    ${ret}    True
    FOR    ${element}    IN    @{results}
        Log    Fail: Page should have contained element ${element} but it did not    WARN
    END
    Return From Keyword    False


问:
QDateEdit calendar popup
I'm trying to get a QDateEdit to allow the QCalendarWidget to show when requested (rather than just on clicking the down arrow). For example, somewhere in my class I should be able to say:

```<code>ui.datepicker.showCalendar()
</code>```

and it should load up the calendar that appears right below the date picker.

It looks like I need to sub-class QDateEdit, as this doesn't work:

```<code>QDateEdit *de = new QDateEdit();
de->calendarWidget()->show();
</code>```

I've also tried sending keyboard commands as dictated when you go through the QDateTimeEdit.cpp source for Qt, but seems my keyboard shortcuts are disabled or something.

Any ideas on what I have to do to sub-class to get this to work? I was thinking of something like:

```<code>class MyDateEdit : QDateEdit
{
  Q_OBJECT

protected:
  void mouseEvent(QEvent *event) {
    this.calendarWidget().show();
  }
};
</code>```

But alas that also doesn't seem to compile in or work correctly.

答:
I was able to figure it out on my own - still no sure how to get QDateEdit to work properly, but I used a QLineEdit and it suited my needs. Just connect QCalendarWidget's "onClick(QDate)" to a slot you create that does a:

```<code>setText(date.toString("M/d/yyyy"));
ui->calendar->hide();
</code>```

Then add an event filter to the QLineEdit using the "OnFocusIn" event that does a "ui->calendar->show();" See: Get a notification/event/signal when a Qt widget gets focus

Title: QDateEdit calendar popup

Body:
I'm trying to get a QDateEdit to allow the QCalendarWidget to show when requested (rather than just on clicking the down arrow). For example, somewhere in my class I should be able to say:

ui.datepicker.showCalendar()

and it should load up the calendar that appears right below the date picker.

It looks like I need to sub-class QDateEdit, as this doesn't work:

QDateEdit *de = new QDateEdit();
de->calendarWidget()->show();

I've also tried sending keyboard commands as dictated when you go through the QDateTimeEdit.cpp source for Qt, but seems my keyboard shortcuts are disabled or something.

Any ideas on what I have to do to sub-class to get this to work? I was thinking of something like:

class MyDateEdit : QDateEdit
{
  Q_OBJECT

protected:
  void mouseEvent(QEvent *event) {
    this.calendarWidget().show();
  }
};

But alas that also doesn't seem to compile in or work correctly.

Body:
I was able to figure it out on my own - still no sure how to get QDateEdit to work properly, but I used a QLineEdit and it suited my needs. Just connect QCalendarWidget's "onClick(QDate)" to a slot you create that does a:

setText(date.toString("M/d/yyyy"));
ui->calendar->hide();

Then add an event filter to the QLineEdit using the "OnFocusIn" event that does a "ui->calendar->show();" See: Get a notification/event/signal when a Qt widget gets focus


问:
Does a contract instance created via interfaces have the same address as the original deployed contract?
I have been following Solidity, Blockchain, and Smart Contract Course – Beginner to Expert Python Tutorial (https://www.youtube.com/watch?v=M576WGiDBdQ&t=28658s). instead of copying a ton of code, I'm trying to generalize my question as follows:

consider the following code snippet:

```<code>weth=interface.IWeth(SomeAddress)
tx=weth.deposit({"from":account, "value": 0.01*10**18})
</code>```

I understand that interface.IWeth(SomeAddress) tells Ethereum virtual machine to create an instance of the contract at SomeAddress ( which I will call SomeContract) with the functionalities of the interface.

I would like to confirm the following:

Does weth and SomeContract share the same address?

will the following state changes have the same outcome?

```<code>weth.deposit({"from":account, "value": 0.01*10**18})
</code>```

and

```<code>SomeContract.deposit({"from":account, "value": 0.01*10**18})
</code>```

答:
I'm a newbie on Solidity and it's not clear to me if the address of contractA is the transaction hash parameter (first bytes) that is specified on Remix console when contractA is deployed or it is the account address from which I deployed contractA. This query is because I'm getting an error when I try to call addToIncrement function from contractB, so I guess it is not connecting with contractA.

Transaction hash contractA

Error while calling addToIncrement function on contractB

Body:
I have been following Solidity, Blockchain, and Smart Contract Course – Beginner to Expert Python Tutorial (https://www.youtube.com/watch?v=M576WGiDBdQ&t=28658s). instead of copying a ton of code, I'm trying to generalize my question as follows:

consider the following code snippet:

weth=interface.IWeth(SomeAddress)
tx=weth.deposit({"from":account, "value": 0.01*10**18})

I understand that interface.IWeth(SomeAddress) tells Ethereum virtual machine to create an instance of the contract at SomeAddress ( which I will call SomeContract) with the functionalities of the interface.

I would like to confirm the following:

Does weth and SomeContract share the same address?

will the following state changes have the same outcome?

weth.deposit({"from":account, "value": 0.01*10**18})

and

SomeContract.deposit({"from":account, "value": 0.01*10**18})


问:
How best to make my scroll controllers available throughout the app?
Context: I'll be having a couple of scrollable lists in my app and I always want to scroll them to the latest item whenever an item is added.

Problem: My ListView.builders and the places where items are added are going to be quite far apart in my widget tree. Passing around all those scroll controllers via constructors seems to be super awkward.

My Solution:As I'm practising with Provider at the moment, I came up with a working solution using Provider:

```<code>class ScrollControllerProvider with ChangeNotifier {
  ScrollController _paneController = ScrollController();
  //setting up all other controllers here later

  get paneController {
    return _paneController;
  }

  void scrollHistory() {
    WidgetsBinding.instance?.addPostFrameCallback((_) {
      if (_paneController.hasClients) {
        _paneController.jumpTo(_paneController.position.maxScrollExtent);
      }
    });
  }
}
</code>```

I'll add all scroll controllers to that provider and grab what I need, where I need it. It already works with one, but someone on reddit told me it's not a good idea, as scroll controllers should be disposed. Im not super knowledgeable on the topic of life cycle yet and find it difficult to assess this.

Questions: Is it really a bad idea to use Provider here? Can you help me to understand why? If yes, what is the best approach to solve this issue?

答:
Provider is not the problem, using a disposable item inside a provider is. ScrollController is a disposable item related to its main Widget, or better to say its State.

If you want to notify your widgets about newly added items, create a variable inside the provider and listen to that variable in your widgets, then use your ScrollController to change the position.

To find out more about your question take a look at ScrollController class and Disposable class

Body:
Context: I'll be having a couple of scrollable lists in my app and I always want to scroll them to the latest item whenever an item is added.

Problem: My ListView.builders and the places where items are added are going to be quite far apart in my widget tree. Passing around all those scroll controllers via constructors seems to be super awkward.

My Solution:As I'm practising with Provider at the moment, I came up with a working solution using Provider:

class ScrollControllerProvider with ChangeNotifier {
  ScrollController _paneController = ScrollController();
  //setting up all other controllers here later

  get paneController {
    return _paneController;
  }

  void scrollHistory() {
    WidgetsBinding.instance?.addPostFrameCallback((_) {
      if (_paneController.hasClients) {
        _paneController.jumpTo(_paneController.position.maxScrollExtent);
      }
    });
  }
}

I'll add all scroll controllers to that provider and grab what I need, where I need it. It already works with one, but someone on reddit told me it's not a good idea, as scroll controllers should be disposed. Im not super knowledgeable on the topic of life cycle yet and find it difficult to assess this.

Questions: Is it really a bad idea to use Provider here? Can you help me to understand why? If yes, what is the best approach to solve this issue?


问:
What determines default row height for a new file in Google Sheets?
I created a spreadsheet to act as a template. It's set up and working as expected.
When I copy the template to a new file (right click on tab > Copy to > New/existing spreadsheet) it copies the template to the new file, everything works as expected except the row heights are different in the two files.

I don't remember changing row height when I was making the template, but the two files are different - the template row width default is 17px and the new/existing copy has a default row height of 21px.

Where is the default row-height value set?
Or, how do I make sure the template exports the row height setting when copies are made?

Thanks in advance.

答:
there is no setting for global width/height value.

but you are able to copy-paste it:


问:
create in pandas matrix rfm
I'm calculating a rfv table in pandas, but im not able to find a tutorial or post that helps me building the matrix necessary for the graph.
The graph i want using this base from matplot
each square being the count of clients in that position.

The dataframe im using now has this columns:

COD_CLIENT
RECENCY
FRE_VAL
R
FV
RFV
RFV_Score
RFV_Level

59
87
45.45
3
3
33
6
Potential

1846
75
6.00
3
2
32
5
Seleepers

4380
92
37.95
2
3
23
5
Seleepers

object
int64
float64
int32
int32
int32
int64
object

What do you guys sugest i do?
I already tried using R and FV as columns and rows and using a function but this went badly.

答:
You want to count the number of rows for each (R, FV) pair, so you could try using pandas.DataFrame.groupby and then counting the number of elements in each group by using .size() on the previous result. The resulting code should look like this:

```<code>import pandas as pd

>> df = ...  # Assuming your DataFrame has the format you showed

>> df.groupby(["R", "FV"]).size()
R  FV
1  1     2
   2     1
   3     1
2  1     1
   2     1
dtype: int64

>> df.groupby(["R", "FV"]).size().unstack()  # Add unstack to format the result
FV    1    2    3
R
1   2.0  1.0  1.0
2   1.0  1.0  NaN
</code>```

This should match your expected output.

Title: create in pandas matrix rfm

Body:
You want to count the number of rows for each (R, FV) pair, so you could try using pandas.DataFrame.groupby and then counting the number of elements in each group by using .size() on the previous result. The resulting code should look like this:

import pandas as pd

>> df = ...  # Assuming your DataFrame has the format you showed

>> df.groupby(["R", "FV"]).size()
R  FV
1  1     2
   2     1
   3     1
2  1     1
   2     1
dtype: int64

>> df.groupby(["R", "FV"]).size().unstack()  # Add unstack to format the result
FV    1    2    3
R
1   2.0  1.0  1.0
2   1.0  1.0  NaN

This should match your expected output.


问:
How do I get autoScroll to the bottom of a div working when using div class
I need an area that automatically scrolls to the bottom when new text comes in from an ajax request

CSS

```<code>div.scroll {
    height: 400px;
    width: 95%;
    overflow: auto;
    /* border: 1px solid #666; */
    background-color: #ccc;
    padding: 8px;
}
</code>```

HTML

```<code><html>
<head>
<script type="text/javascript">
        //Handle ajax data
    $(document).ready(function()
    {
        setInterval(doAjaxStuff, 2000);

    });

    function doAjaxStuff()
    {
        $.ajax
        ({
            url: "http:somewhere/getLog/",
            dataType: 'json',
            success: function(json)
            {
                if(json.status ==  "on")
                {
                    $('#log').html(json.log);

                    }
            }
    });
</script>
</head>
<body>

    <div class="scroll" id =log >pleas wait for log</div>

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

答:
You can use the scrollTop() function:

```<code>//will only auto-scroll if scroll position is already at bottom
var doAutoscroll = ($("#log").scrollTop()==$("#log")[0].scrollHeight);
$('#log').html(json.log)
if (doAutoscroll) $("#log").scrollTop($("#log")[0].scrollHeight);
</code>```

Body:
I need an area that automatically scrolls to the bottom when new text comes in from an ajax request

CSS

div.scroll {
    height: 400px;
    width: 95%;
    overflow: auto;
    /* border: 1px solid #666; */
    background-color: #ccc;
    padding: 8px;
}

HTML

pleas wait for log

Body:
You can use the scrollTop() function:

//will only auto-scroll if scroll position is already at bottom
var doAutoscroll = ($("#log").scrollTop()==$("#log")[0].scrollHeight);
$('#log').html(json.log)
if (doAutoscroll) $("#log").scrollTop($("#log")[0].scrollHeight);


问:
Random Forest always predicts same class
I have been trying to make a Random Forest model for Sign Language classification. The Data Set is balanced and the accuracy is 98%, but it always predicts the same class.

This is how I get and process the data:

```<code>train_dir = "../input/asl-alphabet/asl_alphabet_train/asl_alphabet_train/"
test_dir =  "../input/asl-alphabet/asl_alphabet_test/asl_alphabet_test/"

train_len = 87000
image_size=50

def get_data(folder):
    X = np.empty((train_len, image_size, image_size, 3), dtype = np.float32)
    y = np.empty((train_len), dtype = int)
    cnt = 0
    for folderName in os.listdir(folder):
        if not folderName.startswith('.'):
            if folderName in ['A']:
                label = 0
            elif folderName in ['B']:
                label = 1
            elif folderName in ['C']:
                label = 2
            elif folderName in ['D']:
                label = 3
            elif folderName in ['E']:
                label = 4
            elif folderName in ['F']:
                label = 5
            elif folderName in ['G']:
                label = 6
            elif folderName in ['H']:
                label = 7
            elif folderName in ['I']:
                label = 8
            elif folderName in ['J']:
                label = 9
            elif folderName in ['K']:
                label = 10
            elif folderName in ['L']:
                label = 11
            elif folderName in ['M']:
                label = 12
            elif folderName in ['N']:
                label = 13
            elif folderName in ['O']:
                label = 14
            elif folderName in ['P']:
                label = 15
            elif folderName in ['Q']:
                label = 16
            elif folderName in ['R']:
                label = 17
            elif folderName in ['S']:
                label = 18
            elif folderName in ['T']:
                label = 19
            elif folderName in ['U']:
                label = 20
            elif folderName in ['V']:
                label = 21
            elif folderName in ['W']:
                label = 22
            elif folderName in ['X']:
                label = 23
            elif folderName in ['Y']:
                label = 24
            elif folderName in ['Z']:
                label = 25
            elif folderName in ['del']:
                label = 26
            elif folderName in ['nothing']:
                label = 27
            elif folderName in ['space']:
                label = 28
            else:
                label = 29
            for image_filename in tqdm(os.listdir(folder + folderName)):
                img_file = cv2.imread(folder + folderName + '/' + image_filename)
                if img_file is not None:
                    img_file = skimage.transform.resize(img_file, (image_size, image_size, 3))
                    img_arr = np.asarray(img_file).reshape((-1, image_size, image_size, 3))

                    X[cnt] = img_arr
                    y[cnt] = label
                    cnt += 1
    return X,y

letters, labels= get_data(train_dir)

print("The shape of letters is : ", letters.shape)

    #preprocessing

import tensorflow as tf

X_train, X_test, y_train, y_test = train_test_split(letters, labels, test_size=0.3, random_state=42, stratify=labels)

X_valid, X_train = X_train[:20000] / 255., X_train[20000:] / 255.
y_valid, y_train = y_train[:20000], y_train[20000:]
X_test = X_test / 255.

#reshape to 2d array
nsamples, nx, ny, nrgb = X_train.shape
x_train2 = X_train.reshape((nsamples,nx*ny*nrgb))

#so,eventually,model.predict() should also be a 2d input
nsamples, nx, ny, nrgb = X_test.shape
x_test2 = X_test.reshape((nsamples,nx*ny*nrgb))
</code>```

This is how I made the model:

```<code>from sklearn.ensemble import RandomForestClassifier

model=RandomForestClassifier(random_state=42, n_jobs=-1, max_depth=20,
                                       n_estimators=100, oob_score=True)
model.fit(x_train2,y_train)

y_pred=model.predict(x_test2)
y_pred

#y_pred = clf.predict(X_test)
accuracy_score(y_test, y_pred)

accuracy_score(y_pred,y_test)
print(classification_report(y_pred,y_test))
</code>```

To test the predictions I use:

```<code>label_names = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N',
               'O','P','Q','R','S','T','U','V','W','X','Y','Z','del','nothing','space']

img_path='../input/asl-alphabet/asl_alphabet_test/asl_alphabet_test/L_test.jpg'

img_arr=cv2.imread(img_path)
img_arr=cv2.resize(img_arr,(64,64))

#so,eventually,model.predict() should also be a 2d input
nx, ny, nrgb = img_arr.shape
img_arr2 = img_arr.reshape(1,(nx*ny*nrgb))

classes = ["A","B","C","D","E","F","G","H","I","J", "K", "L", "M" "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "nothing", "space"]

ans=model.predict(img_arr2)

print(label_names[ans[0]])
</code>```

I have tried to implement Grid Search but I wasn't able to make it work. (I am writing it on Kaggle and it tells "Your notebook tried to allocate more memory than is available")

I am quite new to this, so I am not completely certain about anything in my code.

答:
You are missing the preprocessing of the images between training and testing. You need to be applying the same steps on the test set so your model is getting same kind of inputs. Try the following:

label_names = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N',
               'O','P','Q','R','S','T','U','V','W','X','Y','Z','del','nothing','space']

img_path='../input/asl-alphabet/asl_alphabet_test/asl_alphabet_test/L_test.jpg'

img_arr=cv2.imread(img_path)
# Preprocess test image
img_arr = skimage.transform.resize(img_arr, (50, 50, 3))
img_arr = img_arr/255.

#so,eventually,model.predict() should also be a 2d input
nx, ny, nrgb = img_arr.shape
img_arr2 = img_arr.reshape(1,(nx*ny*nrgb))

classes = ["A","B","C","D","E","F","G","H","I","J", "K", "L", "M" "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "nothing", "space"]

ans=model.predict(img_arr2)

print(label_names[ans[0]])
```

Body:
I have been trying to make a Random Forest model for Sign Language classification. The Data Set is balanced and the accuracy is 98%, but it always predicts the same class.

This is how I get and process the data:

train_dir = "../input/asl-alphabet/asl_alphabet_train/asl_alphabet_train/"
test_dir =  "../input/asl-alphabet/asl_alphabet_test/asl_alphabet_test/"

train_len = 87000
image_size=50

def get_data(folder):
    X = np.empty((train_len, image_size, image_size, 3), dtype = np.float32)
    y = np.empty((train_len), dtype = int)
    cnt = 0
    for folderName in os.listdir(folder):
        if not folderName.startswith('.'):
            if folderName in ['A']:
                label = 0
            elif folderName in ['B']:
                label = 1
            elif folderName in ['C']:
                label = 2
            elif folderName in ['D']:
                label = 3
            elif folderName in ['E']:
                label = 4
            elif folderName in ['F']:
                label = 5
            elif folderName in ['G']:
                label = 6
            elif folderName in ['H']:
                label = 7
            elif folderName in ['I']:
                label = 8
            elif folderName in ['J']:
                label = 9
            elif folderName in ['K']:
                label = 10
            elif folderName in ['L']:
                label = 11
            elif folderName in ['M']:
                label = 12
            elif folderName in ['N']:
                label = 13
            elif folderName in ['O']:
                label = 14
            elif folderName in ['P']:
                label = 15
            elif folderName in ['Q']:
                label = 16
            elif folderName in ['R']:
                label = 17
            elif folderName in ['S']:
                label = 18
            elif folderName in ['T']:
                label = 19
            elif folderName in ['U']:
                label = 20
            elif folderName in ['V']:
                label = 21
            elif folderName in ['W']:
                label = 22
            elif folderName in ['X']:
                label = 23
            elif folderName in ['Y']:
                label = 24
            elif folderName in ['Z']:
                label = 25
            elif folderName in ['del']:
                label = 26
            elif folderName in ['nothing']:
                label = 27
            elif folderName in ['space']:
                label = 28
            else:
                label = 29
            for image_filename in tqdm(os.listdir(folder + folderName)):
                img_file = cv2.imread(folder + folderName + '/' + image_filename)
                if img_file is not None:
                    img_file = skimage.transform.resize(img_file, (image_size, image_size, 3))
                    img_arr = np.asarray(img_file).reshape((-1, image_size, image_size, 3))

                    X[cnt] = img_arr
                    y[cnt] = label
                    cnt += 1
    return X,y

letters, labels= get_data(train_dir)

print("The shape of letters is : ", letters.shape)

    #preprocessing

import tensorflow as tf

X_train, X_test, y_train, y_test = train_test_split(letters, labels, test_size=0.3, random_state=42, stratify=labels)

X_valid, X_train = X_train[:20000] / 255., X_train[20000:] / 255.
y_valid, y_train = y_train[:20000], y_train[20000:]
X_test = X_test / 255.

#reshape to 2d array
nsamples, nx, ny, nrgb = X_train.shape
x_train2 = X_train.reshape((nsamples,nx*ny*nrgb))

#so,eventually,model.predict() should also be a 2d input
nsamples, nx, ny, nrgb = X_test.shape
x_test2 = X_test.reshape((nsamples,nx*ny*nrgb))

This is how I made the model:

from sklearn.ensemble import RandomForestClassifier

model=RandomForestClassifier(random_state=42, n_jobs=-1, max_depth=20,
                                       n_estimators=100, oob_score=True)
model.fit(x_train2,y_train)

y_pred=model.predict(x_test2)
y_pred

#y_pred = clf.predict(X_test)
accuracy_score(y_test, y_pred)

accuracy_score(y_pred,y_test)
print(classification_report(y_pred,y_test))

To test the predictions I use:

label_names = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N',
               'O','P','Q','R','S','T','U','V','W','X','Y','Z','del','nothing','space']

img_path='../input/asl-alphabet/asl_alphabet_test/asl_alphabet_test/L_test.jpg'

img_arr=cv2.imread(img_path)
img_arr=cv2.resize(img_arr,(64,64))

#so,eventually,model.predict() should also be a 2d input
nx, ny, nrgb = img_arr.shape
img_arr2 = img_arr.reshape(1,(nx*ny*nrgb))

classes = ["A","B","C","D","E","F","G","H","I","J", "K", "L", "M" "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "nothing", "space"]

ans=model.predict(img_arr2)

print(label_names[ans[0]])

I have tried to implement Grid Search but I wasn't able to make it work. (I am writing it on Kaggle and it tells "Your notebook tried to allocate more memory than is available")

I am quite new to this, so I am not completely certain about anything in my code.


问:
Removing arrows and make the line hearver igraph
In this graph:

The input data are:

```<code>df <- structure(list(book1 = structure(1:4, .Label = c("refid1", "refid2",
"refid3", "refid7"), class = "factor"), book2 = structure(c(2L,
3L, 3L, 1L), .Label = c("", "refid1", "refid3"), class = "factor"),
    book3 = structure(c(2L, 3L, 4L, 1L), .Label = c("", "refid1",
    "refid2", "refid4"), class = "factor"), book4 = structure(c(2L,
    3L, 4L, 1L), .Label = c("", "refid1", "refid3", "refid4"), class = "factor"),
    book5 = structure(c(2L, 3L, 3L, 1L), .Label = c("", "refid2",
    "refid6"), class = "factor"), book6 = structure(c(3L, 2L,
    1L, 1L), .Label = c("", "refid1", "refid2"), class = "factor"),
    book7 = structure(c(2L, 3L, 1L, 1L), .Label = c("", "refid1",
    "refid5"), class = "factor")), .Names = c("book1", "book2",
"book3", "book4", "book5", "book6", "book7"), class = "data.frame", row.names = c(NA,
-4L))
</code>```

and the graph plot comes from this:

```<code>library(dplyr)
library(igraph)
library(tidyr)

g<- df %>%
  gather(key = "From", "To", na.rm = TRUE) %>%
  graph_from_data_frame()

plot(g)
</code>```

How is it possible to remove the arrows of the graph and have just simple lines?

答:
If you already have a graph (that you could have imported via another method that doesn't support directed=FALSE or that you want to be directed but you just don't want to _ plot_ the arrows) you can also do:

    g<- df %>%
      gather(key = "From", "To", na.rm = TRUE) %>%
      distinct(From,To) %>%
      graph_from_data_frame()
    E(g)$arrow.mode="-" #or whatever symbol that is not in c("<", "<-",">",">",“<>”,“<->)
    plot(g)

```

As stated in the documentation this allows to create directed graph with mixed style edges representation.

Body:
In this graph:

The input data are:

df <- structure(list(book1 = structure(1:4, .Label = c("refid1", "refid2",
"refid3", "refid7"), class = "factor"), book2 = structure(c(2L,
3L, 3L, 1L), .Label = c("", "refid1", "refid3"), class = "factor"),
    book3 = structure(c(2L, 3L, 4L, 1L), .Label = c("", "refid1",
    "refid2", "refid4"), class = "factor"), book4 = structure(c(2L,
    3L, 4L, 1L), .Label = c("", "refid1", "refid3", "refid4"), class = "factor"),
    book5 = structure(c(2L, 3L, 3L, 1L), .Label = c("", "refid2",
    "refid6"), class = "factor"), book6 = structure(c(3L, 2L,
    1L, 1L), .Label = c("", "refid1", "refid2"), class = "factor"),
    book7 = structure(c(2L, 3L, 1L, 1L), .Label = c("", "refid1",
    "refid5"), class = "factor")), .Names = c("book1", "book2",
"book3", "book4", "book5", "book6", "book7"), class = "data.frame", row.names = c(NA,
-4L))

and the graph plot comes from this:

library(dplyr)
library(igraph)
library(tidyr)

g<- df %>%
  gather(key = "From", "To", na.rm = TRUE) %>%
  graph_from_data_frame()

plot(g)

How is it possible to remove the arrows of the graph and have just simple lines?

Body:
If you already have a graph (that you could have imported via another method that doesn't support directed=FALSE or that you want to be directed but you just don't want to _ plot_ the arrows) you can also do:

    g<- df %>%
      gather(key = "From", "To", na.rm = TRUE) %>%
      distinct(From,To) %>%
      graph_from_data_frame()
    E(g)$arrow.mode="-" #or whatever symbol that is not in c("<", "<-",">",">",“<>”,“<->)
    plot(g)

As stated in the documentation this allows to create directed graph with mixed style edges representation.


问:
Cycle through the tabs and reformat the columns
I have an Excel document consisting of data imported into multiple tabs. The columns in each tab are stretched out and hard to read.

I am trying to cycle through the tabs and reformat the columns.

Sub resize_columns()
'cycles through each tab (have to start in first tab)
'selects all columns and autofits them

Dim i As Integer

Dim num As Integer

num = ThisWorkbook.Sheets.Count - 1 'counts number of sheets to use in loop range

For i = 0 To num

    Sheets(ActiveSheet.Index + 1).Activate
    Columns("A:Q").Select
    Columns("A:Q").EntireColumn.AutoFit

Next i

End Sub
```
<p>This code produces</p>
<blockquote>
<p>"Run-time error '9': Subscript out of range"</p>
</blockquote>
<p>The debugger points to the first line inside the For loop.</p>
<p>If I run this code as a test, there is no error:</p>
<pre class="lang-vb prettyprint-override"><code>Sub resize_columns()
'cycles through each tab (have to start in first tab)
'selects all columns and autofits them

Dim i As Integer

For i = 1 To 2

    Sheets(ActiveSheet.Index + 1).Activate
    ActiveSheet.Columns("A:Q").Select
    ActiveSheet.Columns("A:Q").EntireColumn.AutoFit

Next i

End Sub
</code>```

I have two questions:

1 - How do I loop without the error?

2 - How do I start on the first tab?

答:
You will rarely need to use Select or Activate with Vba

Sub resize_columns()
   Dim ws As Worksheet
   For Each ws In ThisWorkbook.Sheets
      ws.Columns("A:Q").AutoFit
   Next
End Sub
```

Body:
I have an Excel document consisting of data imported into multiple tabs. The columns in each tab are stretched out and hard to read.

I am trying to cycle through the tabs and reformat the columns.

Sub resize_columns()
'cycles through each tab (have to start in first tab)
'selects all columns and autofits them

Dim i As Integer

Dim num As Integer

num = ThisWorkbook.Sheets.Count - 1 'counts number of sheets to use in loop range

For i = 0 To num

    Sheets(ActiveSheet.Index + 1).Activate
    Columns("A:Q").Select
    Columns("A:Q").EntireColumn.AutoFit

Next i

End Sub

This code produces

"Run-time error '9': Subscript out of range"

The debugger points to the first line inside the For loop.

If I run this code as a test, there is no error:

Sub resize_columns()
'cycles through each tab (have to start in first tab)
'selects all columns and autofits them

Dim i As Integer

For i = 1 To 2

    Sheets(ActiveSheet.Index + 1).Activate
    ActiveSheet.Columns("A:Q").Select
    ActiveSheet.Columns("A:Q").EntireColumn.AutoFit

Next i

End Sub

I have two questions:

1 - How do I loop without the error?

2 - How do I start on the first tab?


问:
tween back to auto-height with xuijs
I'm having problems to create a equivalent slideDown for xuijs.

The slideUp (hide) is easily done with

```<code>x$('elm').tween({height:'0'});
</code>```

but there seem to be no way to revert back to original height using tween.

```<code>$x('elm').setStyle('height','auto !important');
</code>```

works fine but no animation of course,

```<code>x$('elm').tween({height:'auto !important'});
</code>```

does not work. (setting height to fixed value does however, but that's not an option).

Kind of stuck here, document.getElementById('target_box').clientHeight doesn't help either once the height is set to 0 by tween or setStyle. Only solution I can think of is storing the heights in an array before initial global collapse of divs.

thankful for any help.

(the divs affected uses overflow: hidden)

regards,

//t

答:
If you're using html5 Why not store the height as a data- attribute before you call tween?

```<code>x$.extend({
 'slideUp' : function(){
    this = this[0];
    x$(this).attr('data-h',this.clientHeight);
    x$(this).tween({height:'0'});
 },
 'slideDown' : function(){
     this = this[0];
     x$(this).tween({height:x$(this).attr('data-h');});
  }
});
</code>```

this code is untested, but it's worth a shot.

Title: tween back to auto-height with xuijs

Body:
I'm having problems to create a equivalent slideDown for xuijs.

The slideUp (hide) is easily done with

x$('elm').tween({height:'0'});

but there seem to be no way to revert back to original height using tween.

$x('elm').setStyle('height','auto !important');

works fine but no animation of course,

x$('elm').tween({height:'auto !important'});

does not work. (setting height to fixed value does however, but that's not an option).

Kind of stuck here, document.getElementById('target_box').clientHeight doesn't help either once the height is set to 0 by tween or setStyle. Only solution I can think of is storing the heights in an array before initial global collapse of divs.

thankful for any help.

(the divs affected uses overflow: hidden)

regards,

//t

Body:
If you're using html5 Why not store the height as a data- attribute before you call tween?

x$.extend({
 'slideUp' : function(){
    this = this[0];
    x$(this).attr('data-h',this.clientHeight);
    x$(this).tween({height:'0'});
 },
 'slideDown' : function(){
     this = this[0];
     x$(this).tween({height:x$(this).attr('data-h');});
  }
});

this code is untested, but it's worth a shot.


问:
IsText and IsNumber functions from VBA got invalid results compared with IsText and IsNumber functions from Excel
I encountered several problems when I wanted to validate a column with dates, when I used IsText or IsNumber function in VBA and then when I noticed the wrong results, I compared the same function directly in Excel.

I was even more surprised to see that the two functions from VBA do not give the same result with the functions from Excel

My VBA code is:

```<code>Sub test()
Dim sh As Worksheet: Set sh = ThisWorkbook.Worksheets("Sheet1")

For i = 2 To 5
    sh.Cells(i, 4).Value = Application.WorksheetFunction.IsText(sh.Cells(i, 1).Value)
    sh.Cells(i, 6).Value = Application.WorksheetFunction.IsNumber(sh.Cells(i, 1).Value)

    sh.Cells(i, 10).Value = IsDate(sh.Cells(i, 1).Value)
    sh.Cells(i, 9).Value = IsNumeric(sh.Cells(i, 1).Value)
Next i

End Sub
</code>```

And below are the results:

In column D I have the result from IsText function from VBA and in column E I have the results from IsText function from Excel.

And similar, in column E I have the result from IsNumber function from VBA and in column G I have the results from IsNumber function from Excel.

As you already see the results are different. So what is the explanation?

Another weird thing was with VBA IsDate function where I have different results from 2 Virtual Machines but with the same OS date format. You can see the results in the clumn J.

答:
Bob,

In your VBA code you don't declare a type for the return of the ISTEXT therefore it is by default a Variant.

Here's some test code I ran in the Immediate window to demonstrate this:

```<code>x = Cells(3,1)
?x
May-10-22
?VarType(x)
 8
</code>```

If you look up the VarType function you'll see that 8 is String so ISNumber is going to return False and ISText is True as all values will be in when imported into VBA w/o a type declaration.

References:
Variant Variable Type
VarType Function

Body:
I encountered several problems when I wanted to validate a column with dates, when I used IsText or IsNumber function in VBA and then when I noticed the wrong results, I compared the same function directly in Excel.

I was even more surprised to see that the two functions from VBA do not give the same result with the functions from Excel

My VBA code is:

Sub test()
Dim sh As Worksheet: Set sh = ThisWorkbook.Worksheets("Sheet1")

For i = 2 To 5
    sh.Cells(i, 4).Value = Application.WorksheetFunction.IsText(sh.Cells(i, 1).Value)
    sh.Cells(i, 6).Value = Application.WorksheetFunction.IsNumber(sh.Cells(i, 1).Value)

    sh.Cells(i, 10).Value = IsDate(sh.Cells(i, 1).Value)
    sh.Cells(i, 9).Value = IsNumeric(sh.Cells(i, 1).Value)
Next i

End Sub

And below are the results:

In column D I have the result from IsText function from VBA and in column E I have the results from IsText function from Excel.

And similar, in column E I have the result from IsNumber function from VBA and in column G I have the results from IsNumber function from Excel.

As you already see the results are different. So what is the explanation?

Another weird thing was with VBA IsDate function where I have different results from 2 Virtual Machines but with the same OS date format. You can see the results in the clumn J.

Body:
Bob,

In your VBA code you don't declare a type for the return of the ISTEXT therefore it is by default a Variant.

Here's some test code I ran in the Immediate window to demonstrate this:

x = Cells(3,1)
?x
May-10-22
?VarType(x)
 8

If you look up the VarType function you'll see that 8 is String so ISNumber is going to return False and ISText is True as all values will be in when imported into VBA w/o a type declaration.

References:
Variant Variable Type
VarType Function


问:
Buttons On NEXTCORD
Why is this code not working ?The purpose of the code was to make the button work forever, because after a while, it stops working, can someone give me some naughty help? xD</p>
```<code>@client.command()
async def teste(ctx, role : nextcord.Role):
    class buttons(nextcord.ui.View(timeout = 0)):
        def __init__(self):
            super().__init__()
            self.value = None
        @nextcord.ui.button(label = "teste", style = nextcord.ButtonStyle.blurple)
        async def teste(self, button : nextcord.ui.Button, interaction : nextcord.Interaction):
            if role in interaction.user.roles:
                await interaction.user.remove_roles(role)
            else:
                await interaction.user.add_roles(role)
    view = buttons()
    await ctx.send("teste", view = view)
    await view.wait()
</code>```

答:
You cannot build a class inside a command.

```<code>class buttons(nextcord.ui.View(timeout = 0)):

        def __init__(self):
            super().__init__()
            self.value = None

        @nextcord.ui.button(label = "teste", style = nextcord.ButtonStyle.blurple)
        async def teste(self, button : nextcord.ui.Button, interaction : nextcord.Interaction):
            if role in interaction.user.roles:
                await interaction.user.remove_roles(role)
            else:
                await interaction.user.add_roles(role)
</code>```

Make sure to keep your class above the actual command. That way it works.

```<code>@client.command()
async def teste(ctx, role : nextcord.Role):
    view = buttons()
    await ctx.send("teste", view=view)
    await view.wait()
</code>```

Title: Buttons On NEXTCORD

Body:
Why is this code not working ?The purpose of the code was to make the button work forever, because after a while, it stops working, can someone give me some naughty help? xD

@client.command()
async def teste(ctx, role : nextcord.Role):
    class buttons(nextcord.ui.View(timeout = 0)):
        def __init__(self):
            super().__init__()
            self.value = None
        @nextcord.ui.button(label = "teste", style = nextcord.ButtonStyle.blurple)
        async def teste(self, button : nextcord.ui.Button, interaction : nextcord.Interaction):
            if role in interaction.user.roles:
                await interaction.user.remove_roles(role)
            else:
                await interaction.user.add_roles(role)
    view = buttons()
    await ctx.send("teste", view = view)
    await view.wait()

Body:
You cannot build a class inside a command.

class buttons(nextcord.ui.View(timeout = 0)):

        def __init__(self):
            super().__init__()
            self.value = None

        @nextcord.ui.button(label = "teste", style = nextcord.ButtonStyle.blurple)
        async def teste(self, button : nextcord.ui.Button, interaction : nextcord.Interaction):
            if role in interaction.user.roles:
                await interaction.user.remove_roles(role)
            else:
                await interaction.user.add_roles(role)

Make sure to keep your class above the actual command. That way it works.

@client.command()
async def teste(ctx, role : nextcord.Role):
    view = buttons()
    await ctx.send("teste", view=view)
    await view.wait()


问:
How to add the same Layout to Layout via kv file?
There is a problem that it is impossible to add BoxLayout to BoxLayout via kv file.

GTN.py

```<code>from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button

class GTNApp(App):
    def build(self):
        return Main()

class Main(BoxLayout):
    pass

if __name__ == "__main__":
    GTNApp().run()
</code>```

GTN.kv

```<code><BoxLayout>:
    orientation: 'vertical'
    BoxLayout:
        orientation: 'horizontal'
        Button:
            text: '1'
</code>```

После этого выдает ошибку: AssertionError

答:
Solved my problem like this.

GTN.py

```<code>from kivy.app import App
from kivy.uix.widget import Widget

class Main(Widget):
    pass

class GTNApp(App):
    def build(self):
        return Main()

if __name__ == '__main__':
    GTNApp().run()
</code>```

GTN.kv

```<code><Main>
    BoxLayout:
        orientation: 'vertical'
        size: root.width, root.height
        BoxLayout:
            orientation: 'horizontal'
            Button:
                text: '1'
</code>```

Body:
There is a problem that it is impossible to add BoxLayout to BoxLayout via kv file.

GTN.py

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button

class GTNApp(App):
    def build(self):
        return Main()

class Main(BoxLayout):
    pass

if __name__ == "__main__":
    GTNApp().run()

GTN.kv

<BoxLayout>:
    orientation: 'vertical'
    BoxLayout:
        orientation: 'horizontal'
        Button:
            text: '1'

После этого выдает ошибку: AssertionError

Body:
Solved my problem like this.

GTN.py

from kivy.app import App
from kivy.uix.widget import Widget

class Main(Widget):
    pass

class GTNApp(App):
    def build(self):
        return Main()

if __name__ == '__main__':
    GTNApp().run()

GTN.kv

<Main>
    BoxLayout:
        orientation: 'vertical'
        size: root.width, root.height
        BoxLayout:
            orientation: 'horizontal'
            Button:
                text: '1'