问:
Why I have 'Undelivered Messages' if my receiver works?

I restarted my Windows VM but this did not help. On the next day I restarted my main.go and right after that I saw that old stuck messages began to come.

My Subscription Type is Pull, my Acknowledgement Deadline is maximum: 600 seconds.

Background: I want to use Pubsub as a load balancer in my managed group of Windows instances (I need Windows API for that task). Message processing is CPU intensive (with a few HTTP calls) and can take from a few seconds to a few minutes.

Some other metrics from Stackdriver:

I have no idea what I can check. Day ago I did a highload testing and looks like everything was fine (Undelivered Messages was zero as we see on the first screenshot above). Now my CPU consumption is zero, managed group decreased to one instance (this is not in a production environment). I try to use Pubsub for the first time. Code of my main() that synthesize audio from text chunks, encode to two formats and upload to S3:

```<code>func main() {
    fmt.Printf("Current time: %v\n",
        time.Now().Format(timeFormat),
    )

    // https://godoc.org/cloud.google.com/go/pubsub#Subscription.Receive
    err := subscription.Receive(ctx, func(ctx context.Context, m *pubsub.Message) {
        timeStart := time.Now()
        if timeStartFirstMessage == nil {
            timeStartFirstMessage = &timeStart
        }

        var data pubsubMessage
        json.Unmarshal(m.Data, &data)
        fmt.Printf("Got message: %#v\n", data)

        var wg sync.WaitGroup
        wg.Add(len(data.TextChunks))

        wavs := make([][]byte, len(data.TextChunks))
        for i, chunk := range data.TextChunks {
            /** TODO without 'go' (sequential) will process in correct order:
             * user can listen first and seconds chunks faster,
             * but m4a will be later,
             * but on "high load" of the VM with ~2x more messages in parallel
             * (each message on it is own goroutine)
             * performance may be even better (I think) because
             * hundreds of CPU intensive goroutine is worse.
             *
             * Also in sequential code I can append() to wav[]
             * instead of doind it later in another func,
             * maybe this will also improve perfomance (profile).
            **/
            go func(i int, chunk string) {
                fmt.Printf("Index of text chunk: %d\n", i)
                wav := tts(data.Voice, chunk)
                streamOfOggEncoder := encodeOggVorbis(wav)
                uploadToS3(
                    "intelligentspeaker",
                    data.Sub+"/"+data.HashArticle+"/"+fmt.Sprint(i),
                    "audio/ogg",
                    streamOfOggEncoder,
                )
                wavs[i] = wav

                wg.Done()
            }(i, chunk)
        }
        wg.Wait()
        wavConcated := concat(wavs)

        filename := buildPodcastEpisodeFilename(data.Title)
        err := encodePodcastEpisode(wavConcated, filename)
        if err != nil {
            m.Nack()
            return
        }

        if err != nil {
            logger.Log(logging.Entry{Payload: fmt.Sprintf("ERROR on m4a deleting: %v", err)})
        }

        key := data.Sub + "/" + data.HashArticle + "/" + random() + "/" + filename
        readCloser, size := getReadCloserAndSize(filename)
        if readCloser == nil {
            m.Nack()
            return
        }
        uploadToS3("intelligentspeaker--podcasts", key, "audio/x-m4a", readCloser)
        // Next message may be with the same title (filename)
        err = os.Remove(filename)

        fmt.Printf("Duration: %v\n", duration(wavConcated))
        updatePodcastXML(
            key,
            data.Title,
            data.URLArticle,
            data.FavIconURL,
            duration(wavConcated),
            data.Utc,
            size,
        )

        fmt.Printf("DONE pubsub message, current time: %v\n", time.Now().Format(timeFormat))
        fmt.Printf("Time of message processing: %v\n", time.Since(timeStart).Round(time.Second))
        fmt.Printf(
            "Time of all messages processing (counted from the first message, not from the start of this app): %v\n",
            time.Since(*timeStartFirstMessage).Round(time.Second),
        )

        m.Ack()

    })
    if err != nil {
        logger.Log(logging.Entry{Payload: fmt.Sprintf("ERROR on registering receiver: %v", err)})
    }

}

</code>```

Update: found similar question.

答:
I'm assuming that the metric that is concerning is pubsub.googleapis.com/subscription/num_undelivered_messages which measures the "Number of unacknowledged messages (a.k.a. backlog messages) in a subscription." From the "Acknowledge Requests" graph, we see that your subscribers stopped acknowledging message at around 9pm on the 28th. That's the same time when the "Oldest Unacknowledged Message" age started growing (linearly). Meanwhile, the "Backlog Size" graph is pretty flat. This means that there is a small number of "problematic" messages in the subscription's backlog that the subscribers are not acknowledging. Most likely, the subscribers are having trouble processing this small set of messages for some reason. Perhaps these messages are malformed in some way, or do not conform some expectation of the subscriber code.

One thing you can do to try to debug this is to use the gcloud command-line tool to "peek" into the messages in the subscription's backlog: https://cloud.google.com/sdk/gcloud/reference/pubsub/subscriptions/pull. Note that gcloud tool will not acknowledge any messages if you do not set the --auto-ack flag.

Body:
I restarted my Windows VM but this did not help. On the next day I restarted my main.go and right after that I saw that old stuck messages began to come.

My Subscription Type is Pull, my Acknowledgement Deadline is maximum: 600 seconds.

Background: I want to use Pubsub as a load balancer in my managed group of Windows instances (I need Windows API for that task). Message processing is CPU intensive (with a few HTTP calls) and can take from a few seconds to a few minutes.

Some other metrics from Stackdriver:

I have no idea what I can check. Day ago I did a highload testing and looks like everything was fine (Undelivered Messages was zero as we see on the first screenshot above). Now my CPU consumption is zero, managed group decreased to one instance (this is not in a production environment). I try to use Pubsub for the first time. Code of my main() that synthesize audio from text chunks, encode to two formats and upload to S3:

func main() {
    fmt.Printf("Current time: %v\n",
        time.Now().Format(timeFormat),
    )

    // https://godoc.org/cloud.google.com/go/pubsub#Subscription.Receive
    err := subscription.Receive(ctx, func(ctx context.Context, m *pubsub.Message) {
        timeStart := time.Now()
        if timeStartFirstMessage == nil {
            timeStartFirstMessage = &timeStart
        }

        var data pubsubMessage
        json.Unmarshal(m.Data, &data)
        fmt.Printf("Got message: %#v\n", data)

        var wg sync.WaitGroup
        wg.Add(len(data.TextChunks))

        wavs := make([][]byte, len(data.TextChunks))
        for i, chunk := range data.TextChunks {
            /** TODO without 'go' (sequential) will process in correct order:
             * user can listen first and seconds chunks faster,
             * but m4a will be later,
             * but on "high load" of the VM with ~2x more messages in parallel
             * (each message on it is own goroutine)
             * performance may be even better (I think) because
             * hundreds of CPU intensive goroutine is worse.
             *
             * Also in sequential code I can append() to wav[]
             * instead of doind it later in another func,
             * maybe this will also improve perfomance (profile).
            **/
            go func(i int, chunk string) {
                fmt.Printf("Index of text chunk: %d\n", i)
                wav := tts(data.Voice, chunk)
                streamOfOggEncoder := encodeOggVorbis(wav)
                uploadToS3(
                    "intelligentspeaker",
                    data.Sub+"/"+data.HashArticle+"/"+fmt.Sprint(i),
                    "audio/ogg",
                    streamOfOggEncoder,
                )
                wavs[i] = wav

                wg.Done()
            }(i, chunk)
        }
        wg.Wait()
        wavConcated := concat(wavs)

        filename := buildPodcastEpisodeFilename(data.Title)
        err := encodePodcastEpisode(wavConcated, filename)
        if err != nil {
            m.Nack()
            return
        }

        if err != nil {
            logger.Log(logging.Entry{Payload: fmt.Sprintf("ERROR on m4a deleting: %v", err)})
        }

        key := data.Sub + "/" + data.HashArticle + "/" + random() + "/" + filename
        readCloser, size := getReadCloserAndSize(filename)
        if readCloser == nil {
            m.Nack()
            return
        }
        uploadToS3("intelligentspeaker--podcasts", key, "audio/x-m4a", readCloser)
        // Next message may be with the same title (filename)
        err = os.Remove(filename)

        fmt.Printf("Duration: %v\n", duration(wavConcated))
        updatePodcastXML(
            key,
            data.Title,
            data.URLArticle,
            data.FavIconURL,
            duration(wavConcated),
            data.Utc,
            size,
        )

        fmt.Printf("DONE pubsub message, current time: %v\n", time.Now().Format(timeFormat))
        fmt.Printf("Time of message processing: %v\n", time.Since(timeStart).Round(time.Second))
        fmt.Printf(
            "Time of all messages processing (counted from the first message, not from the start of this app): %v\n",
            time.Since(*timeStartFirstMessage).Round(time.Second),
        )

        m.Ack()

    })
    if err != nil {
        logger.Log(logging.Entry{Payload: fmt.Sprintf("ERROR on registering receiver: %v", err)})
    }

}

Update: found similar question.


来源: stackexchange

问:
How to wait until ActiveWorkbook.RefreshAll finishes before executing more code
I have a subroutine that calls ActiveWorkbook.RefreshAll to bring new data in from an XML source on a website, and then performs multiple modifications to it. The problem is that not enough time is given for the RefreshAll command to finish, so the following subs and functions end up not executing correctly, which result in repeated rows not being correctly erased.

I have tried using Application.Wait and the Sleep function, but they seem to pause the refresh process too. I simply want the rest of the code to wait until the refresh process finishes before executing the rest of the code.

Right now I was only able to fix it by not calling on RefreshAll, which gives me the idea of implementing a second flow to be executed afterwards, but that's not a good workaround.

According to http://www.mrexcel.com/forum/excel-questions/564959-execute-code-after-data-connection-refresh-finished.html, XML connections do not have a BackgroundQuery boolean. That option is only available for ODBC and OLEDB connections, which are types xlConnectionTypeODBC and xlConnectionTypeOLEDB, respectively. The XML connection I am using is of type xlConnectionTypeXMLMAP.

This code is the macro that is recorded when I do this via the UI (including unchecking the "Enable background refresh" in the table properties):

```<code>With ActiveWorkbook.Connections("XMLTable")
        .Name = "XMLTable"
        .Description = ""
End With
ActiveWorkbook.Connections("XMLTable").refresh
</code>```

The class ActiveWorkbook.Connections does NOT have a BackgroundQuery option so that I can set it to False.

How can I force my subsequent code to wait until RefreshAll finishes?

答:
This worked for me:

```<code>ActiveWorkbook.refreshall
ActiveWorkbook.Save
</code>```

When you save the workbook it's necessary to complete the refresh.

ContentLicense: CC BY-SA 4.0

Body:
I have a subroutine that calls ActiveWorkbook.RefreshAll to bring new data in from an XML source on a website, and then performs multiple modifications to it. The problem is that not enough time is given for the RefreshAll command to finish, so the following subs and functions end up not executing correctly, which result in repeated rows not being correctly erased.

I have tried using Application.Wait and the Sleep function, but they seem to pause the refresh process too. I simply want the rest of the code to wait until the refresh process finishes before executing the rest of the code.

Right now I was only able to fix it by not calling on RefreshAll, which gives me the idea of implementing a second flow to be executed afterwards, but that's not a good workaround.

According to http://www.mrexcel.com/forum/excel-questions/564959-execute-code-after-data-connection-refresh-finished.html, XML connections do not have a BackgroundQuery boolean. That option is only available for ODBC and OLEDB connections, which are types xlConnectionTypeODBC and xlConnectionTypeOLEDB, respectively. The XML connection I am using is of type xlConnectionTypeXMLMAP.

This code is the macro that is recorded when I do this via the UI (including unchecking the "Enable background refresh" in the table properties):

With ActiveWorkbook.Connections("XMLTable")
        .Name = "XMLTable"
        .Description = ""
End With
ActiveWorkbook.Connections("XMLTable").refresh

The class ActiveWorkbook.Connections does NOT have a BackgroundQuery option so that I can set it to False.

How can I force my subsequent code to wait until RefreshAll finishes?

Body:
This worked for me:

ActiveWorkbook.refreshall
ActiveWorkbook.Save

When you save the workbook it's necessary to complete the refresh.


问:
Button Text does not Update
>> BACKGROUND :

I want to update/change the text of a Button in the SecondScreen with a press of a Button in the MainScreen. Well I did some research and did what I want, and when I checked in the terminal the text did change. BUUT, the text shown on the SecondScreen did not.

>> THIS IS WHAT I DID :

((Mind you that I'm only using snippets of code for example, I'm going to post the whole code below.))

```<code>Button:
    text:"PRESS TO CHANGE TEXT"
    on_press:
        root.funcself()
        ## on press it goes to it's root and do the "funcself" function in it
</code>```

which is :

```<code>class MainScreen(Screen):
    def funcself(self):
        app.second.funcscreen()
        ## it re-directs to the SecondScreen and do the "funcscreen" function
</code>```

which is :

```<code>class SecondScreen(Screen):
    def funcscreen(self):
        self.ids["button"].text = "SUPPOSED TO CHANGE TO THIS"
</code>```

and then I checked if I did it successfully by doing print(self.ids["button"].text), and yes!
It did change, but when I navigated to the next screen, the text shown still didn't change.

Anyone mind helping and explaining?

FULL CODE :

python file :

```<code>import kivy
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.label import Label
from kivy.uix.widget import Widget
from kivy.uix.button import Button
from kivy.uix.gridlayout import GridLayout
from kivy.uix.screenmanager import ScreenManager, Screen

class MainScreen(Screen):
    def funcself(self):
        app.second.funcscreen()

class SecondScreen(Screen):
    def funcscreen(self):
        value = self.ids["button"]
        self.ids["button"].text = "SUPPOSED TO CHANGE TO THIS"

kv = Builder.load_file("reproduce.kv")
class reproduce(App):
    second = SecondScreen()
    def build(self):
        return kv

    def change_screen(self, x):
        scrnmngr = self.root.ids["sm"]
        scrnmngr.current = x

    def check(self):
        print(self.second.ids["button"].text)

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

kivy file :

```<code><MainScreen>:
    GridLayout:
        rows:2
        Label:
            text: "PRESS TO GO TO THE NEXT PAGE"
        GridLayout:
            cols:2
            Button:
                text:"PRESS TO CHANGE TEXT"
                on_press:
                    root.funcself()

            Button:
                text:">>>"
                on_press:
                    app.change_screen("second")
                    root.manager.transition.direction = "left"

<SecondScreen>:
    GridLayout:
        rows:2
        Label:
            id:label
            text: "PRESS TO CHECK AND RETURN TO PREV PAGE"
        Button:
            id:button
            text:"TEXT BEFORE CHANGE"
            on_press:
                app.change_screen("first")
                root.manager.transition.direction = "right"
                app.check()
GridLayout:
    cols: 1
    ScreenManager:
        id:sm
        MainScreen:
            id:main
            name:"first"
        SecondScreen:
            id:second
            name:"second"
</code>```

答:
Root Cause

It did not change because there are two instances of SecondScreen() i.e. one instantiated in the kv file and the other one instantiated in the App class, reproduce(). The view presented is created from the kv file and the second instance does not has a view associated to it.

Solution

There are two solutions to the problem, and remove second = SecondScreen() from the App class.

Kivy Screen » default property manager

Each screen has by default a property manager that gives you the
  instance of the ScreenManager used.

Using get_screen()

```<code>class MainScreen(Screen):
    def funcself(self):
        self.manager.get_screen('second').funcscreen()
</code>```

Using App.get_running_app() & ids

```<code>class MainScreen(Screen):
    def funcself(self):
        App.get_running_app().root.ids.second.funcscreen()
</code>```

Example

In the following example, there are two solutions provided but one of it is commented off.

main.py

```<code>from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import Screen

class MainScreen(Screen):
    def funcself(self):
        self.manager.get_screen('second').funcscreen()
        # App.get_running_app().root.ids.second.funcscreen()

class SecondScreen(Screen):
    def funcscreen(self):
        value = self.ids["button"]
        self.ids["button"].text = "SUPPOSED TO CHANGE TO THIS"

kv = Builder.load_file("reproduce.kv")

class reproduce(App):

    def build(self):
        return kv

    def change_screen(self, x):
        scrnmngr = self.root.ids["sm"]
        scrnmngr.current = x

    def check(self):
        print(self.second.ids["button"].text)

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

Output

Title: Button Text does not Update

Body:
>> BACKGROUND :

I want to update/change the text of a Button in the SecondScreen with a press of a Button in the MainScreen. Well I did some research and did what I want, and when I checked in the terminal the text did change. BUUT, the text shown on the SecondScreen did not.

>> THIS IS WHAT I DID :

((Mind you that I'm only using snippets of code for example, I'm going to post the whole code below.))

Button:
    text:"PRESS TO CHANGE TEXT"
    on_press:
        root.funcself()
        ## on press it goes to it's root and do the "funcself" function in it

which is :

class MainScreen(Screen):
    def funcself(self):
        app.second.funcscreen()
        ## it re-directs to the SecondScreen and do the "funcscreen" function

which is :

class SecondScreen(Screen):
    def funcscreen(self):
        self.ids["button"].text = "SUPPOSED TO CHANGE TO THIS"

and then I checked if I did it successfully by doing print(self.ids["button"].text), and yes!
It did change, but when I navigated to the next screen, the text shown still didn't change.

Anyone mind helping and explaining?

FULL CODE :

python file :

import kivy
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.label import Label
from kivy.uix.widget import Widget
from kivy.uix.button import Button
from kivy.uix.gridlayout import GridLayout
from kivy.uix.screenmanager import ScreenManager, Screen

class MainScreen(Screen):
    def funcself(self):
        app.second.funcscreen()

class SecondScreen(Screen):
    def funcscreen(self):
        value = self.ids["button"]
        self.ids["button"].text = "SUPPOSED TO CHANGE TO THIS"

kv = Builder.load_file("reproduce.kv")
class reproduce(App):
    second = SecondScreen()
    def build(self):
        return kv

    def change_screen(self, x):
        scrnmngr = self.root.ids["sm"]
        scrnmngr.current = x

    def check(self):
        print(self.second.ids["button"].text)

if __name__ == "__main__":
    app = reproduce()
    app.run()

kivy file :

<MainScreen>:
    GridLayout:
        rows:2
        Label:
            text: "PRESS TO GO TO THE NEXT PAGE"
        GridLayout:
            cols:2
            Button:
                text:"PRESS TO CHANGE TEXT"
                on_press:
                    root.funcself()

            Button:
                text:">>>"
                on_press:
                    app.change_screen("second")
                    root.manager.transition.direction = "left"

<SecondScreen>:
    GridLayout:
        rows:2
        Label:
            id:label
            text: "PRESS TO CHECK AND RETURN TO PREV PAGE"
        Button:
            id:button
            text:"TEXT BEFORE CHANGE"
            on_press:
                app.change_screen("first")
                root.manager.transition.direction = "right"
                app.check()
GridLayout:
    cols: 1
    ScreenManager:
        id:sm
        MainScreen:
            id:main
            name:"first"
        SecondScreen:
            id:second
            name:"second"

Body:
Root Cause

It did not change because there are two instances of SecondScreen() i.e. one instantiated in the kv file and the other one instantiated in the App class, reproduce(). The view presented is created from the kv file and the second instance does not has a view associated to it.

Solution

There are two solutions to the problem, and remove second = SecondScreen() from the App class.

Kivy Screen » default property manager

Each screen has by default a property manager that gives you the
  instance of the ScreenManager used.

Using get_screen()

class MainScreen(Screen):
    def funcself(self):
        self.manager.get_screen('second').funcscreen()

Using App.get_running_app() & ids

class MainScreen(Screen):
    def funcself(self):
        App.get_running_app().root.ids.second.funcscreen()

Example

In the following example, there are two solutions provided but one of it is commented off.

main.py

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import Screen

class MainScreen(Screen):
    def funcself(self):
        self.manager.get_screen('second').funcscreen()
        # App.get_running_app().root.ids.second.funcscreen()

class SecondScreen(Screen):
    def funcscreen(self):
        value = self.ids["button"]
        self.ids["button"].text = "SUPPOSED TO CHANGE TO THIS"

kv = Builder.load_file("reproduce.kv")

class reproduce(App):

    def build(self):
        return kv

    def change_screen(self, x):
        scrnmngr = self.root.ids["sm"]
        scrnmngr.current = x

    def check(self):
        print(self.second.ids["button"].text)

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

Output


问:
git@github.com: Permission denied (publickey) ERROR
I've have been trying to push to origin master, and I was getting different errors now I'm getting this

```<code>git@github.com: Permission denied (publickey).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.
</code>```

How can I connect my github again? I've tryed multiple different stuff.

答:
You need to have a SSH key on your machine generated if not already generated.

This can be done by running following command in your .ssh folder

```<code>ssh-keygen -t ecdsa -b 521 -f 'filepath/id_ecdsa'
</code>```

More reading on ssh command.

This will generate a public and private key pair. You need the public key added to your github account added or for a specific repo.

cat id_ecdsa.pub and get it added to your github repo's SSH keys.

Note that the name of file above can be anything.  I just named it after the encryption type ecdsa preferable.

Body:
I've have been trying to push to origin master, and I was getting different errors now I'm getting this

git@github.com: Permission denied (publickey).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

How can I connect my github again? I've tryed multiple different stuff.

Body:
You need to have a SSH key on your machine generated if not already generated.

This can be done by running following command in your .ssh folder

ssh-keygen -t ecdsa -b 521 -f 'filepath/id_ecdsa'

More reading on ssh command.

This will generate a public and private key pair. You need the public key added to your github account added or for a specific repo.

cat id_ecdsa.pub and get it added to your github repo's SSH keys.

Note that the name of file above can be anything.  I just named it after the encryption type ecdsa preferable.


问:
OmniORB compilation error Windows 7 64 bit
Has anyone encountered the error below when compiling omniORB_4.1.6 64-bit for windows?
'RegQueryValueEx failed - error 109'

I followed the procedure in the readme.win32 and I get linking errors in the omniDyamic, codesets etc.. So someone suggested to rebuild the omniorb_root/src/tools/win32 and copy it in bin/x86_win32/. That's what I did and when I recompile the whole omniORB, the error is as below:

```<code>../../../../bin/x86_win32/omkdepend -D__cplusplus -D_MSC_VER -DIDLMODULE_VERSION
="0x2630" -DMSDOS -DOMNIIDL_EXECUTABLE -Ic:/python27/include -Ic:/python27/PC -I
c:/python27/include/python2.7 -DPYTHON_INCLUDE=<Python.h> -I. -I. -I../../../../
include -D__WIN32__ -D_WIN32_WINNT=0x0501 -D__x86__ -D__NT__ -D__OSVERSION__=4 -
D_CRT_SECURE_NO_DEPRECATE=1 idlc.cc idlpython.cc idlfixed.cc idlconfig.cc idldum
p.cc idlvalidate.cc idlast.cc idlexpr.cc idlscope.cc idlrepoId.cc idltype.cc idl
util.cc idlerr.cc lex.yy.cc y.tab.cc
RegQueryValueEx failed - error 109
-----------------------------------------------------------------------------------------------
make[4]: Entering directory `/cygdrive/c/Software/COTS/omniORB/omniORB_4.1.6/src
/tool/omniidl/cxx/cccp'
../../../../../bin/x86_win32/clwrapper -gnuwin32 -c -O2 -MD -GS -GR -Zi -nologo
-DHAVE_CONFIG_H -I. -I. -I. -I../../../../../include -D__WIN32__ -D_WIN32_WINNT=
0x0501 -D__x86__ -D__NT__ -D__OSVERSION__=4 -D_CRT_SECURE_NO_DEPRECATE=1 -Focexp
.o cexp.c
RegQueryValueEx failed - error 109
</code>```

答:
I spent quite some time trying to compile OmniORB on windows 10 with visual studio 2017.

Assuming Cygwin64 was installed in directory

c:\software\cygwin64

, the compilation of OmniORB is quite straightforward:

open a command terminal (cmd)

in that terminal, setup the Visual environment:

"C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Auxiliary\Build\vcvarsall.bat" x64

then, append the PATH (yes append and not prepend):

set PATH=%PATH%;c:\software\cygwin64\bin

then, in file config\config.mk, uncomment this line

platform = x86_win32_vs_15

in file platforms\x86_win32_vs_15, set PYTHON to target the python executable, in my case Python 3.6.5

PYTHON = /cygdrive/c/software/Python/python

finally start the compilation with make:

make export

Hope this helps.

ContentLicense: CC BY-SA 3.0

Body:
Has anyone encountered the error below when compiling omniORB_4.1.6 64-bit for windows?
'RegQueryValueEx failed - error 109'

I followed the procedure in the readme.win32 and I get linking errors in the omniDyamic, codesets etc.. So someone suggested to rebuild the omniorb_root/src/tools/win32 and copy it in bin/x86_win32/. That's what I did and when I recompile the whole omniORB, the error is as below:

../../../../bin/x86_win32/omkdepend -D__cplusplus -D_MSC_VER -DIDLMODULE_VERSION
="0x2630" -DMSDOS -DOMNIIDL_EXECUTABLE -Ic:/python27/include -Ic:/python27/PC -I
c:/python27/include/python2.7 -DPYTHON_INCLUDE=<Python.h> -I. -I. -I../../../../
include -D__WIN32__ -D_WIN32_WINNT=0x0501 -D__x86__ -D__NT__ -D__OSVERSION__=4 -
D_CRT_SECURE_NO_DEPRECATE=1 idlc.cc idlpython.cc idlfixed.cc idlconfig.cc idldum
p.cc idlvalidate.cc idlast.cc idlexpr.cc idlscope.cc idlrepoId.cc idltype.cc idl
util.cc idlerr.cc lex.yy.cc y.tab.cc
RegQueryValueEx failed - error 109
-----------------------------------------------------------------------------------------------
make[4]: Entering directory `/cygdrive/c/Software/COTS/omniORB/omniORB_4.1.6/src
/tool/omniidl/cxx/cccp'
../../../../../bin/x86_win32/clwrapper -gnuwin32 -c -O2 -MD -GS -GR -Zi -nologo
-DHAVE_CONFIG_H -I. -I. -I. -I../../../../../include -D__WIN32__ -D_WIN32_WINNT=
0x0501 -D__x86__ -D__NT__ -D__OSVERSION__=4 -D_CRT_SECURE_NO_DEPRECATE=1 -Focexp
.o cexp.c
RegQueryValueEx failed - error 109


问:
"write after end" error with Express and its json parser
I'm trying to build an API that takes a JSON input with Express. That seems quite straightforward, but I'm getting the error [ERR_STREAM_WRITE_AFTER_END]: write after end.

My (much simplified) (TypeScript) code is as follow:

```<code>import express from 'express';
const app = express();
const jsonParser = express.json();

app.use(async (req, res, next) => {
  // Common actions for all requests
  console.log('Raw request:', req);
  res.setHeader('Content-Type', 'application/json');
  await next();
  res.end();
});

app.post('/example', jsonParser, async (req, res) => {
  console.log('Parsed request body:', req.body);
  res.write('ok');
});

app.listen(3000);
</code>```

When I post some JSON (simply {"test":"test"}), with a Content-Type: application/json to 127.0.0.1:3000/example, my program crashes with the "write after end" error. I've tried the following things:

If I set the Content-Type to something else (like text/plain), it doesn't crash, but the JSON isn't caught properly (my log "Parsed request body" shows an empty object).

If I remove the res.write('ok');, it doesn't crash either (and returns an empty string), but this means I'm not able to return stuff, which isn't acceptable.

If I remove the whole app.use(...) section, it works fine, but I'd really like to be able to do some pre- +/- post-processing on all routes there, so that's not a satisfying option either.

Is there something I'm doing wrong, or is it just impossible to do what I'm trying to do and I should stick with option number 3?

答:
Well the error is expected. You're writing to response stream after closing (or ending) it.

```<code>await next(); // <-- This is calling you next middleware
res.end(); // meanwhile this is executed and closes the stream
</code>```

You can do like:

```<code>app.use(async (req, res, next) => {
  // Common actions for all requests
  console.log('Raw request:', req);
  res.setHeader('Content-Type', 'application/json');
  next();
});

app.post('/example', jsonParser, async (req, res) => {
  console.log('Parsed request body:', req.body);
  res.write('ok');
  res.end();
});
</code>```

Body:
I'm trying to build an API that takes a JSON input with Express. That seems quite straightforward, but I'm getting the error [ERR_STREAM_WRITE_AFTER_END]: write after end.

My (much simplified) (TypeScript) code is as follow:

import express from 'express';
const app = express();
const jsonParser = express.json();

app.use(async (req, res, next) => {
  // Common actions for all requests
  console.log('Raw request:', req);
  res.setHeader('Content-Type', 'application/json');
  await next();
  res.end();
});

app.post('/example', jsonParser, async (req, res) => {
  console.log('Parsed request body:', req.body);
  res.write('ok');
});

app.listen(3000);

When I post some JSON (simply {"test":"test"}), with a Content-Type: application/json to 127.0.0.1:3000/example, my program crashes with the "write after end" error. I've tried the following things:

If I set the Content-Type to something else (like text/plain), it doesn't crash, but the JSON isn't caught properly (my log "Parsed request body" shows an empty object).

If I remove the res.write('ok');, it doesn't crash either (and returns an empty string), but this means I'm not able to return stuff, which isn't acceptable.

If I remove the whole app.use(...) section, it works fine, but I'd really like to be able to do some pre- +/- post-processing on all routes there, so that's not a satisfying option either.

Is there something I'm doing wrong, or is it just impossible to do what I'm trying to do and I should stick with option number 3?

Body:
Well the error is expected. You're writing to response stream after closing (or ending) it.

await next(); // <-- This is calling you next middleware
res.end(); // meanwhile this is executed and closes the stream

You can do like:

app.use(async (req, res, next) => {
  // Common actions for all requests
  console.log('Raw request:', req);
  res.setHeader('Content-Type', 'application/json');
  next();
});

app.post('/example', jsonParser, async (req, res) => {
  console.log('Parsed request body:', req.body);
  res.write('ok');
  res.end();
});


问:
Calling a base abstract method in an override of that method
If I have the following:

e.g.

```<code>public abstract class ClassA
{
     protected abstract void ValidateTransaction();
}

public abstract class ClassB : ClassA
{
     protected override void ValidateTransaction()
     {
          // some custom logic here
     }
}

public class ClassC : ClassB
{
     protected override void ValidateTransaction()
     {
          base.ValidateTransaction();
          // some additional custom logic here
     }
}
</code>```

So I did not find usages on ClassC's ValidateTransaction.  I don't see it being called anywhere.

So then I guess how does this work?  I mean it's calling the method at the top of the stack here (calls the ClassB's override method and then includes logic in my ClassC's override of ClassB's method?)

This doesn't make sense to me why or how this works or the intention here.

UPDATED

Ok so I did find a spot where ClassA's PerformTransaction() method is called from a lot of sub classes in our project.

So ClassA now looks like this with more details for you here:

```<code>public abstract class ClassA
{
     public void PerformTransaction()
     {
           ValidateTransaction();
           // and calls some other code here.
     }

     protected abstract void ValidateTransaction();
}
</code>```

Ok then we still have:

```<code>public abstract class ClassB : ClassA
{
     protected override void ValidateTransaction()
     {
          // some custom logic here
     }
}

public class ClassC : ClassB
{
     protected override void ValidateTransaction()
     {
          base.ValidateTransaction();
          // some additional custom logic here
     }
}

public class SomeAbritraryClass : ClassC
{
      ClassA.PerformTransaction();
      ...
 }
</code>```

so ClassA.PerformTransaction() is being called in some classes that inherit ClassC.

答:
So then I guess how does this work? I mean it's calling the method at the top of the stack here (calls the ClassB's override method and then includes logic in my ClassC's override of ClassB's method?)

Yes, that's basically what happens.  When you call ValidateTransaction on an instance of ClassC, it's method is run.  It, then, explicitly executes the base class (ClassB) method, then adds its own additional validation.

You're probably not finding direct usages of ClassB.ValidateTransaction() because there are no instances of ClassB (defined as ClassB) on which this is called.  However, any ClassC call will be indirectly using ClassB.ValidateTransaction() through the base.ValidateTransaction() line.

Body:
If I have the following:

e.g.

public abstract class ClassA
{
     protected abstract void ValidateTransaction();
}

public abstract class ClassB : ClassA
{
     protected override void ValidateTransaction()
     {
          // some custom logic here
     }
}

public class ClassC : ClassB
{
     protected override void ValidateTransaction()
     {
          base.ValidateTransaction();
          // some additional custom logic here
     }
}

So I did not find usages on ClassC's ValidateTransaction.  I don't see it being called anywhere.

So then I guess how does this work?  I mean it's calling the method at the top of the stack here (calls the ClassB's override method and then includes logic in my ClassC's override of ClassB's method?)

This doesn't make sense to me why or how this works or the intention here.

UPDATED

Ok so I did find a spot where ClassA's PerformTransaction() method is called from a lot of sub classes in our project.

So ClassA now looks like this with more details for you here:

public abstract class ClassA
{
     public void PerformTransaction()
     {
           ValidateTransaction();
           // and calls some other code here.
     }

     protected abstract void ValidateTransaction();
}

Ok then we still have:

public abstract class ClassB : ClassA
{
     protected override void ValidateTransaction()
     {
          // some custom logic here
     }
}

public class ClassC : ClassB
{
     protected override void ValidateTransaction()
     {
          base.ValidateTransaction();
          // some additional custom logic here
     }
}

public class SomeAbritraryClass : ClassC
{
      ClassA.PerformTransaction();
      ...
 }

so ClassA.PerformTransaction() is being called in some classes that inherit ClassC.


问:
Configuring Log Level for Azure Functions
I have an Azure Function App which has Application Insights configured. My functions have some LogTrace() messages in but they are not being captured by AppInsights. Do I have to configure a minimum loglevel somewhere?

答:
To further add to @Ivan Yang's excellent answer, you can specify a minimum logging level per function in v2 of Azure Functions. (I have not verified if it does/doesn't work in v1) Using his example host.json:

```<code>{
  "version": "2.0",
  "logging": {
    "fileLoggingMode": "always",
    "logLevel": {
      "default": "Information",
      "Host.Results": "Error",
      "Function": "Trace",
      "Function.FunctionA": "Warning",
      "Host.Aggregator": "Trace"
    }
  }
}
</code>```

Function.FunctionA is assuming you have a function named (via the FunctionName attribute) "FunctionA", e.g.:

```<code>[FunctionName("FunctionA")]
public static async Task<IActionResult> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "")]HttpRequest req, ILogger log)
{
  ...function code here
}
</code>```

So whatever value you specify in the FunctionName attribute can be used to explicitly define a minimum log level just for that function. In the host.json example above, all functions, by default, will have a minimum log level of Trace while FunctionA will have a minimum log level of Warning.

Body:
To further add to @Ivan Yang's excellent answer, you can specify a minimum logging level per function in v2 of Azure Functions. (I have not verified if it does/doesn't work in v1) Using his example host.json:

{
  "version": "2.0",
  "logging": {
    "fileLoggingMode": "always",
    "logLevel": {
      "default": "Information",
      "Host.Results": "Error",
      "Function": "Trace",
      "Function.FunctionA": "Warning",
      "Host.Aggregator": "Trace"
    }
  }
}

Function.FunctionA is assuming you have a function named (via the FunctionName attribute) "FunctionA", e.g.:

[FunctionName("FunctionA")]
public static async Task<IActionResult> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "")]HttpRequest req, ILogger log)
{
  ...function code here
}

So whatever value you specify in the FunctionName attribute can be used to explicitly define a minimum log level just for that function. In the host.json example above, all functions, by default, will have a minimum log level of Trace while FunctionA will have a minimum log level of Warning.


问:
Join value of the properties in the For Each loop to one line output
Sorry for my bad English.

At here Parse properties string in an array to For Each loop, with support from https://stackoverflow.com/users/1630171/
I was able to read the battery information. But it is just separate information, so how do we assemble it and export the results into one line.

```<code>Dim strResult, objItem, arrayItem
On Error Resume Next
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colItems = objWMIService.ExecQuery("Select * from Win32_Battery")
arrayItems = Array("Name", "Availability", "BatteryStatus", "Chemistry")
For Each objItem in colItems
     For Each arrayItem In arrayItems
        strResult = Join(objItem.Properties_(arrayItem))
    Next
    WScript.Echo strResult
Next
</code>```

And it shows empty result of the output.

答:
You need to collect the properties and join them into a string.

Try this:

```<code>Option Explicit

Dim objItem, arrayItems, strComputer
Dim objWMIService, colItems, arrResult, i

strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")

'The third parameter 48 for 'ExecQuery' is the combination of wbemFlagForwardOnly + wbemFlagReturnImmediately
'see: https://learn.microsoft.com/en-us/windows/desktop/wmisdk/swbemservices-execquery#parameters
Set colItems = objWMIService.ExecQuery("Select * from Win32_Battery",,48)
arrayItems = Array("Name", "Availability", "BatteryStatus", "Chemistry")

For Each objItem in colItems
    'create/clear an array to store the various pieces of information
    ReDim arrResult(UBound(arrayItems))
    For i = 0 To (UBound(arrayItems))
        ' Sometimes the WMI property returns a Null value (Nothing)..
        If Not IsNull (objItem.Properties_(arrayItems(i))) Then
            arrResult(i) = objItem.Properties_(arrayItems(i))
        Else
            arrResult(i) = "Unknown"
        End If
    Next
    'as example I'm using the Tab character to join the pieces
    WScript.Echo Join(arrResult, Chr(9))
Next
</code>```

Body:
Sorry for my bad English.

At here Parse properties string in an array to For Each loop, with support from https://stackoverflow.com/users/1630171/
I was able to read the battery information. But it is just separate information, so how do we assemble it and export the results into one line.

Dim strResult, objItem, arrayItem
On Error Resume Next
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colItems = objWMIService.ExecQuery("Select * from Win32_Battery")
arrayItems = Array("Name", "Availability", "BatteryStatus", "Chemistry")
For Each objItem in colItems
     For Each arrayItem In arrayItems
        strResult = Join(objItem.Properties_(arrayItem))
    Next
    WScript.Echo strResult
Next

And it shows empty result of the output.

Body:
You need to collect the properties and join them into a string.

Try this:

Option Explicit

Dim objItem, arrayItems, strComputer
Dim objWMIService, colItems, arrResult, i

strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")

'The third parameter 48 for 'ExecQuery' is the combination of wbemFlagForwardOnly + wbemFlagReturnImmediately
'see: https://learn.microsoft.com/en-us/windows/desktop/wmisdk/swbemservices-execquery#parameters
Set colItems = objWMIService.ExecQuery("Select * from Win32_Battery",,48)
arrayItems = Array("Name", "Availability", "BatteryStatus", "Chemistry")

For Each objItem in colItems
    'create/clear an array to store the various pieces of information
    ReDim arrResult(UBound(arrayItems))
    For i = 0 To (UBound(arrayItems))
        ' Sometimes the WMI property returns a Null value (Nothing)..
        If Not IsNull (objItem.Properties_(arrayItems(i))) Then
            arrResult(i) = objItem.Properties_(arrayItems(i))
        Else
            arrResult(i) = "Unknown"
        End If
    Next
    'as example I'm using the Tab character to join the pieces
    WScript.Echo Join(arrResult, Chr(9))
Next


问:
Send a typing indicator in bot-framework v4 using DirectLine and webchat (Node.js)
The official docs for Microsoft bot-framework SDK v4 do not demonstrate how to send a typing indicator (whereas v3 has these instructions). I'm using DirectLine and botframework-webchat.

How do I do this? Thanks!

答:
I believe you should do something like this</p>

```<code>await context.sendActivities([
    { type: 'typing' },
    { type: 'delay', value: 2000 },
    { type: 'message', text: 'Your message here' }
]);
</code>```

Body:
I believe you should do something like this

await context.sendActivities([
    { type: 'typing' },
    { type: 'delay', value: 2000 },
    { type: 'message', text: 'Your message here' }
]);


问:
flatpickr: set date of a second date picker to the same date of the first one
I'm using flatpikr https://flatpickr.js.org/
I want on close event of an outbound (only date) picker, to set the initial date of the return picker to the same date selected in the first one.
I wrote this code which is working, but is not switching to the correct month page, it simply disables all the dates before the selected one in the outbound picker.
Here you can check what happens in the booking form.

```<code>https://anekitalia.com/en/
</code>```

I have tried to use defaultDate instead of minDate in the on close function but it doesn't works.

```<code><script>
 $( function() {
 /*selecting datepiker language*/
 flatpickr.localize(flatpickr.l10ns.en);
 /*declaring return datepicker*/
 var FLATPICKER_RITORNO = flatpickr('#cal_DATA_RITORNO', {
 altInput: true,
 altFormat: "j F, Y",
 dateFormat: "d-m-Y",
 disableMobile: "true",
 maxDate: new Date().fp_incr(365),
 });
 /*declaring outbound datepicker*/
 $("#cal_DATA_ANDATA").flatpickr(
 {
 altInput: true,
 altFormat: "j F, Y",
 dateFormat: "d-m-Y",
 disableMobile: "true",
 minDate: "today",
 maxDate: new Date().fp_incr(365),
 defaultDate: "today",
 /* setting initial date of return picker to the one selected in
 outbound*/
 onClose: function( selectedDates, dateStr, instance ) {
 FLATPICKER_RITORNO.set( 'minDate', dateStr)}
 });
 } );
</script>
</code>```

答:
fixed this by adding setDate(dateObj) and changing the onClose event to onChange so code now will look like this</p>

```<code><script>
  $(function () {
    /*selecting datepiker language*/
    flatpickr.localize(flatpickr.l10ns.en);
    /*declaring return datepicker*/
    var FLATPICKER_RITORNO = flatpickr('#cal_DATA_RITORNO', {
      altInput: true,
      altFormat: "j F, Y",
      dateFormat: "d-m-Y",
      disableMobile: "true",
      maxDate: new Date().fp_incr(365),
      defaultDate: "today"
    });
    /*declaring outbound datepicker*/
    $("#cal_DATA_ANDATA").flatpickr(
      {
        altInput: true,
        altFormat: "j F, Y",
        dateFormat: "d-m-Y",
        disableMobile: "true",
        minDate: "today",
        maxDate: new Date().fp_incr(365),
        defaultDate: "today",
        /* setting initial date of return picker to the one selected in
        outbound*/
        onChange: function (dateStr, dateObj) {
          FLATPICKER_RITORNO.set("minDate", dateObj);
          FLATPICKER_RITORNO.setDate(dateObj);
        }
      });
  });
</script>
</code>```

Body:
I'm using flatpikr https://flatpickr.js.org/
I want on close event of an outbound (only date) picker, to set the initial date of the return picker to the same date selected in the first one.
I wrote this code which is working, but is not switching to the correct month page, it simply disables all the dates before the selected one in the outbound picker.
Here you can check what happens in the booking form.

https://anekitalia.com/en/

I have tried to use defaultDate instead of minDate in the on close function but it doesn't works.

Body:
fixed this by adding setDate(dateObj) and changing the onClose event to onChange so code now will look like this

<script>
  $(function () {
    /*selecting datepiker language*/
    flatpickr.localize(flatpickr.l10ns.en);
    /*declaring return datepicker*/
    var FLATPICKER_RITORNO = flatpickr('#cal_DATA_RITORNO', {
      altInput: true,
      altFormat: "j F, Y",
      dateFormat: "d-m-Y",
      disableMobile: "true",
      maxDate: new Date().fp_incr(365),
      defaultDate: "today"
    });
    /*declaring outbound datepicker*/
    $("#cal_DATA_ANDATA").flatpickr(
      {
        altInput: true,
        altFormat: "j F, Y",
        dateFormat: "d-m-Y",
        disableMobile: "true",
        minDate: "today",
        maxDate: new Date().fp_incr(365),
        defaultDate: "today",
        /* setting initial date of return picker to the one selected in
        outbound*/
        onChange: function (dateStr, dateObj) {
          FLATPICKER_RITORNO.set("minDate", dateObj);
          FLATPICKER_RITORNO.setDate(dateObj);
        }
      });
  });
</script>


问:
How to write data to file on starting
I am using below code to write data in a file.

```<code>public static void writeDataToFile(final String fileName, final String fileContents) {
    try {
        File file = new File(Environment.getExternalStorageDirectory() + fileName);

        if (!file.exists()) {
            file.createNewFile();
        }
        FileWriter writer = new FileWriter(file, true);
        writer.append(fileContents);
        writer.flush();
        writer.close();
    } catch (IOException e) {
        LogUtility.logInfo(TAG, e.getMessage());
    }
}
</code>```

Here FileWriter Constructor takes boolean that means it concatenates data to file every time to the last data. What I am trying to get is to have a file that has logs of my activities I am performing. And I am achieving via above mentioned code. but the problem is it is always concatenating logs to the last of data every time. What I want is to write new log on starting ever time.By this I will not have search file to the bottom for last log. It will be on start evyer time. Any help

答:
You can set the append flag to false in the FileWriter constructor.  Then, use the write() function instead of the append() function

```<code>FileWriter writer = new FileWriter(file, false);
writer.write(fileContents);
</code>```

Title: How to write data to file on starting

Body:
I am using below code to write data in a file.

public static void writeDataToFile(final String fileName, final String fileContents) {
    try {
        File file = new File(Environment.getExternalStorageDirectory() + fileName);

        if (!file.exists()) {
            file.createNewFile();
        }
        FileWriter writer = new FileWriter(file, true);
        writer.append(fileContents);
        writer.flush();
        writer.close();
    } catch (IOException e) {
        LogUtility.logInfo(TAG, e.getMessage());
    }
}

Here FileWriter Constructor takes boolean that means it concatenates data to file every time to the last data. What I am trying to get is to have a file that has logs of my activities I am performing. And I am achieving via above mentioned code. but the problem is it is always concatenating logs to the last of data every time. What I want is to write new log on starting ever time.By this I will not have search file to the bottom for last log. It will be on start evyer time. Any help

Body:
You can set the append flag to false in the FileWriter constructor.  Then, use the write() function instead of the append() function

FileWriter writer = new FileWriter(file, false);
writer.write(fileContents);


问:
If I quit terminal on mac, do I lose all tmux sessions after I re-open terminal?
I can't afford to give it a try since I've got a bunch of working tmux sessions running now. </p>

答:
No, you do not. This is one of the many benefits of using tmux. Simply do tmux ls to list all the current sessions open after you re-open your terminal, and then do tmux a -t <session-name> to re-attach the session.

Although this is very nice, if you shut down or restart your computer, you will in fact lose all of your sessions. To get around this, many people (including myself) use tmux-resurrect, a plugin that lets you save sessions to disk, and restore them later whenever you want (even after restart).


问:
Selenium Button Selector and Click
I want to automate the restart of my router using Selenium on Python. Everything is working fine except for the last step, which is locating the restart button and click it!

I have tried to locate it by (id, css_selector, name, value, xpath), but nothing seemed to work.

Here is my code:

```<code>driver = webdriver.Firefox()
driver.get('http://192.168.100.1')

english = driver.find_element_by_id("English")
english.click()

usr = "username"
pwd = "password"

usrname_box = driver.find_element_by_id("txt_Username")
usrname_box.send_keys(usr)

pwd_box = driver.find_element_by_id("txt_Password")
pwd_box.send_keys(pwd)

submit_ = driver.find_element_by_id("button")
submit_.click()
sleep(1)

resetit = driver.find_element_by_name("maindiv_reset")
resetit.click()
sleep(1)

# This is the one I want to locate
reboot = driver.find_element_by_xpath("//input[@id='btnReboot']")
reboot.click()
</code>```

And this is the HTML code for the target button:

```<code><input class="ApplyButtoncss buttonwidth_150px" name="btnReboot" id="btnReboot" type="button" onclick="Reboot()" bindtext="s0603" value="Restart">
</code>```

When trying anything, I get the error:

```<code>NoSuchElementException: Message: Unable to locate element: (WHATEVER I TRY)
</code>```

A Screenshot of the HTML Page:

Thank you all for your help in advance.

答:
Thy this one:</p>

```<code>reboot = driver.find_element_by_name("btnReboot")
reboot.click()
</code>```

Title: Selenium Button Selector and Click

Body:
I want to automate the restart of my router using Selenium on Python. Everything is working fine except for the last step, which is locating the restart button and click it!

I have tried to locate it by (id, css_selector, name, value, xpath), but nothing seemed to work.

Here is my code:

driver = webdriver.Firefox()
driver.get('http://192.168.100.1')

english = driver.find_element_by_id("English")
english.click()

usr = "username"
pwd = "password"

usrname_box = driver.find_element_by_id("txt_Username")
usrname_box.send_keys(usr)

pwd_box = driver.find_element_by_id("txt_Password")
pwd_box.send_keys(pwd)

submit_ = driver.find_element_by_id("button")
submit_.click()
sleep(1)

resetit = driver.find_element_by_name("maindiv_reset")
resetit.click()
sleep(1)

# This is the one I want to locate
reboot = driver.find_element_by_xpath("//input[@id='btnReboot']")
reboot.click()

And this is the HTML code for the target button:

<input class="ApplyButtoncss buttonwidth_150px" name="btnReboot" id="btnReboot" type="button" onclick="Reboot()" bindtext="s0603" value="Restart">

When trying anything, I get the error:

NoSuchElementException: Message: Unable to locate element: (WHATEVER I TRY)

A Screenshot of the HTML Page:

Thank you all for your help in advance.

Body:
Thy this one:

reboot = driver.find_element_by_name("btnReboot")
reboot.click()


问:
OCaml equivalent of Javascript's console.log
I am currently working on an OCaml project. From time to time, I would like to debug the data I am currently working with, and see the output in the terminal from .ml file I am building. I was just wondering what the equivalent in OCaml would be?

Let's assume that user is creating an executable file, being built by dune: dune build example.bc -w

Thank you, your time is very much so appreciated.

答:
If you mean a logger function that works 'universally', i.e. it can print out some representation of any type, then try https://reason-native.com/docs/console/ . It's meant to be similar to JavaScript's console.log. Examples on the page are in ReasonML syntax but will work in OCaml too.

Console is not published to opam though, and unfortunately does not currently support opam. However, since it is a dune project ( https://github.com/facebookexperimental/reason-native/tree/master/src/console ), you could keep it in-source as part of your own project.


问:
PreparedStatement Does Not Work For Sybase IQ In Java
Me and my team faced a problem. We are trying to retrieve some data from Sybase IQ database and are using where clause to filter out and get specific data.

The SQL is tested and works fine but it fails when using Prepared Statement.

Tests done:

If we run the query (with or without where clause parameters), it works fine.

If we run the query with parameters hard coded in the Prepared Statement, it also works fine.

If we set the parameters of prepared statement programmatically, it does not work.

The above tests confirm the JDBC connection is working fine.

The same error appears when PreparedStatement, JdbcTemplate  or NamedParameterJdbcTemplate is used, so I suspect there might be an issue between PreparedStatement and Sybase IQ.

Could anyone help to investigate that? We have found a workaround for that, but it would be really useful to know why this was not working.

I found very similar thread (How do I execute PreparedStatement(select object_id()) in sybase iq?) about the same issue, but nobody provided an accepted and correct answer there, so I decided to create a new question for this.

The code used is:

Class.forName("com.sybase.jdbc4.jdbc.SybDriver");

PreparedStatement stmt = con.prepareStatement("select * from myView where off = ? and acc = ?");

stmt.setString(1, "260");
stmt.setString(2, "9050V");
ResultSet set = stmt.executeQuery();
```

<p><strong>The error message is:</strong></p>

<pre class="lang-java prettyprint-override"><code>Exception in thread "main" java.sql.SQLException: JZ0SA: Prepared Statement: Input parameter not set, index: 0.
    at com.sybase.jdbc4.jdbc.SybConnection.getAllExceptions(Unknown Source)
    at com.sybase.jdbc4.jdbc.SybStatement.handleSQLE(Unknown Source)
    at com.sybase.jdbc4.jdbc.SybStatement.sendQuery(Unknown Source)
    at com.sybase.jdbc4.jdbc.SybPreparedStatement.sendQuery(Unknown Source)
    at com.sybase.jdbc4.jdbc.SybStatement.executeQuery(Unknown Source)
    at com.sybase.jdbc4.jdbc.SybPreparedStatement.executeQuery(Unknown Source)
</code>```

JDBC Driver used (Maven dependency):

<dependency>
            <groupId>com.sybase</groupId>
            <artifactId>jconn4</artifactId>
            <version>7.0</version>
</dependency>
```

答:
stmt.setString(1, "260");
stmt.setString(2, "9050V");

Array index starts with 0 no? is it not a zero based indexing in your API used?

Body:
Me and my team faced a problem. We are trying to retrieve some data from Sybase IQ database and are using where clause to filter out and get specific data.

The SQL is tested and works fine but it fails when using Prepared Statement.

Tests done:

If we run the query (with or without where clause parameters), it works fine.

If we run the query with parameters hard coded in the Prepared Statement, it also works fine.

If we set the parameters of prepared statement programmatically, it does not work.

The above tests confirm the JDBC connection is working fine.

The same error appears when PreparedStatement, JdbcTemplate  or NamedParameterJdbcTemplate is used, so I suspect there might be an issue between PreparedStatement and Sybase IQ.

Could anyone help to investigate that? We have found a workaround for that, but it would be really useful to know why this was not working.

I found very similar thread (How do I execute PreparedStatement(select object_id()) in sybase iq?) about the same issue, but nobody provided an accepted and correct answer there, so I decided to create a new question for this.

The code used is:

Class.forName("com.sybase.jdbc4.jdbc.SybDriver");

PreparedStatement stmt = con.prepareStatement("select * from myView where off = ? and acc = ?");

stmt.setString(1, "260");
stmt.setString(2, "9050V");
ResultSet set = stmt.executeQuery();

The error message is:

Exception in thread "main" java.sql.SQLException: JZ0SA: Prepared Statement: Input parameter not set, index: 0.
    at com.sybase.jdbc4.jdbc.SybConnection.getAllExceptions(Unknown Source)
    at com.sybase.jdbc4.jdbc.SybStatement.handleSQLE(Unknown Source)
    at com.sybase.jdbc4.jdbc.SybStatement.sendQuery(Unknown Source)
    at com.sybase.jdbc4.jdbc.SybPreparedStatement.sendQuery(Unknown Source)
    at com.sybase.jdbc4.jdbc.SybStatement.executeQuery(Unknown Source)
    at com.sybase.jdbc4.jdbc.SybPreparedStatement.executeQuery(Unknown Source)

JDBC Driver used (Maven dependency):

<dependency>
            <groupId>com.sybase</groupId>
            <artifactId>jconn4</artifactId>
            <version>7.0</version>
</dependency>


问:
Remove a users reaction from fetchMessage? - Discord JS
I have a question for Discord.js.
How would I remove a specific user's reaction from a message?

I have tried to do so with this code:

```<code>// Now known as 'messages.fetch'.
message.channel.fetchMessage(MessageID).then(m => {
   m.reactions.remove(UserID);
});
</code>```

But it doesn't remove the user's reaction at all. Am I doing something wrong?

Any help would be appreciated.

答:
message.reactions is a collection of messageReactions. I think you need to loop through the collection and then remove the messageReaction required.

```<code>message.channel.fetchMessage(messageID).map(r => r).then(message => {
  message.reactions.forEach(reaction => reaction.remove(UserID))
})
</code>```

Body:
I have a question for Discord.js.
How would I remove a specific user's reaction from a message?

I have tried to do so with this code:

// Now known as 'messages.fetch'.
message.channel.fetchMessage(MessageID).then(m => {
   m.reactions.remove(UserID);
});

But it doesn't remove the user's reaction at all. Am I doing something wrong?

Any help would be appreciated.

Body:
message.reactions is a collection of messageReactions. I think you need to loop through the collection and then remove the messageReaction required.

message.channel.fetchMessage(messageID).map(r => r).then(message => {
  message.reactions.forEach(reaction => reaction.remove(UserID))
})


问:
How do I move from a relational database and do I need to?
I'm currently building a CRM for a niche industry that can be tailored for the end user. We currently are using a base table for leads and then basically a hacked together combination of tables as a key/value store for any custom fields that might be added.

Each lead in the CRM also has tables for various owners, permissions, access logs, scheduled tasks, and generated contracts/documents.

Currently, everything is stored in a MySQL database but it just seems really messy. I'm thinking of using a NoSQL solution like MongoDB and then using Redis to create any relationships between tables.

Example: I'm thinking of storing the leads and users in a MongoDB database and then using Redis for storing what users a certain lead belongs to etc.

Just looking for some general advice on what the best solution is for this situation as I haven't dealt with NoSQL before.

答:
mysql is a great tool

storages is not some stuff that works automagically. For being working well - the great developer needs to implement great schema and great code.

What I wanted to say: if you have some issues now - it doesn't mean that they will disappear once you moved to another database (paradigm, ideology, etc). Even if they moved away - the new ones will come. Nothing happens without hard working.

And especially to big volumes of data and high loaded projects - there is no general advice and silver bullet.

ps:

I'm thinking of using a NoSQL solution like MongoDB and then using Redis to create any relationships between tables.

MongoDB can maintain relations. This is one more argument to not move to the databases you are not well experienced in.


答:
Why don't you remove the file if it exists:</p>

```<code>    if (!file.exists()) {
        file.createNewFile();
    } else {
        file.delete()
        file.createNewFile();
    }
</code>```

Title: How to write data to file on starting

Body:
Why don't you remove the file if it exists:

    if (!file.exists()) {
        file.createNewFile();
    } else {
        file.delete()
        file.createNewFile();
    }


问:
Not able to download Page blob type file from Azure blob storage using SSIS
In SSIS job, I added a step for download files from Azure Blob Storage. After adding a Azure Blob Download task, in the control flow, and entering in the storage configuration (Test connection successfully).

But it download only Block blob type file only.  Not able to download Page blob type files.

How we can download page blob type file using SSIS?  If anyone have other approach then it also fine for me.

答: Using for each container and Flexible File task component, we can download the Page blob file.</p>


问:
Multiply objects in an array witrh another object recursively in Java
Hello there I am learning Java and after doing some tasks to learn recursion I was giving my self some exercises to learn it a bit more but now I am struggeling with some..

So the main Problem is that I dont know how I can multiply every element in an Array recursively when the elements in that array are object (Maybe there is at the end no difference if objects are in there or not). So the exercise I gave myself was: check if 1 / 3 is in the given Array. If Yes then multiply everything in that array with 2 / 1.
This is Fraction:

 private int numerator;      // Zaehler
 private int denominator;    // Nenner

        public Fraction ( int num, int denom )
        {
            if ( denom != 0 )
            {
                if ( denom < 0 )
                {
                    numerator = -num;
                    denominator = -denom;
                }
                else
                {
                    numerator = num;
                    denominator = denom;
                }
                reduce();
            }
            else
            {
                // error: division by zero
                throw new IllegalArgumentException();
            }
        }

        public Fraction()
        {
            numerator = 0;
            denominator = 1;
        }

        public Fraction( int num )
        {
            numerator = num;
            denominator = 1;
        }
```

<p>So I got it done by doing it with an for loop: </p>

<pre class="lang-java prettyprint-override"><code>public static Fraction[] mulWithFor(Fraction[] arr)
        {
            for (int i = 0; i<arr.length; i++)
            {
                arr[i] = arr[i].multiply(new Fraction(2,1));
            }
            return arr;
        }
</code>```

But thats not my Main goal I want to do it recursively so that was my approach:

public static Fraction[] mulAus(Fraction[] arr, int i)
        {
            if (i>= 0 && i<arr.length)
            {
                rekurMul(arr,i);
                //return mulAus(rekurMul(arr,i-1));
            }
            return arr;
        }

        public static Fraction rekurMul(Fraction[] arr, int i)
        {
            if (i>= 0 && i<arr.length)
            {
                return arr[i].multiply(new Fraction(2,1));
                return arr[i].multiply(new Fraction(2, 1)); // Does Not Work!!!
            }
            throw new IndexOutOfBoundsException();
        }
```

<p>Maybe there is someone who can Help me! Thank you for your attention.</p>

<p>OK Thanks to @Chaï Sarfati and also to the others trying to help me out. I now know how to multiply recursive things in an Array! I used the Methods from @Chaï Sarfati but wrote an alternative method for his "oneThirdIsPresent" which is also a recursive method : So now my working code looks like this </p>

<pre class="lang-java prettyprint-override"><code> public static Fraction[] mulAus(Fraction[] arr)
        {
            if(contains(arr,arr.length-1,new Fraction(1,3)))
            {
                rekurMul(arr,0);
                return arr;
            }
            throw new IllegalArgumentException("1/3 does not exist in the Input-Array");
        }

        public static void rekurMul(Fraction[] arr, int i)
        {
            if(i == arr.length)
            {
                return ;
            }
            arr[i] = arr[i].multiply(new Fraction(2,1));
            rekurMul(arr,i+1);
        }
</code>```

The Method to check if 1 / 3 exists in the given Array.

public static boolean contains(Fraction[] arr, int i, Fraction x)
        {
            if (i>= 0 && i < arr.length)
            {
                if (arr[i].equals(x))
                { return true;}
                else
                { return contains(arr, i-1,x); }
            }
            return false;
        }
```

I hope other People can learn from the code.. Maybe there are better solutions but I am just starting Programming so I dont know them for now.
Bye

答:
Assuming you have a multiplyBy(Fraction f) method that works properly in you Fraction class.
Moreover, it will be better (more readable, more time & space complexity saving) to do it iteratively.
For the sake of the example, I would do like this:

First define:

```<code>private static boolean oneThirdIsPresent(Fraction[] arr){
    for (int i = 0; i < arr.length; i++) {
        if(arr[i].numerator == 1 && arr[i].denominator == 3) {
            return true;
        }
    }
    return false;
}

private static void recursivelyMultBy2(Fraction[] arr, int index){
    if(index == arr.length){
        return;
    }
    arr[index] = arr[index].multiplyBy(new Fraction(2));
    recursivelyMultBy2(arr, index+1);
}
</code>```

In order to solve finally:

```<code>public static void multBy2IfOneThirdIsPresent(Fraction[] arr){
    if(oneThirdIsPresent(arr)){
        recursivelyMultBy2(arr, 0);
    }else{
        return;
    }
}
</code>```

Body:
Hello there I am learning Java and after doing some tasks to learn recursion I was giving my self some exercises to learn it a bit more but now I am struggeling with some..

So the main Problem is that I dont know how I can multiply every element in an Array recursively when the elements in that array are object (Maybe there is at the end no difference if objects are in there or not). So the exercise I gave myself was: check if 1 / 3 is in the given Array. If Yes then multiply everything in that array with 2 / 1.
This is Fraction:

 private int numerator;      // Zaehler
 private int denominator;    // Nenner

        public Fraction ( int num, int denom )
        {
            if ( denom != 0 )
            {
                if ( denom < 0 )
                {
                    numerator = -num;
                    denominator = -denom;
                }
                else
                {
                    numerator = num;
                    denominator = denom;
                }
                reduce();
            }
            else
            {
                // error: division by zero
                throw new IllegalArgumentException();
            }
        }

        public Fraction()
        {
            numerator = 0;
            denominator = 1;
        }

        public Fraction( int num )
        {
            numerator = num;
            denominator = 1;
        }

So I got it done by doing it with an for loop:

public static Fraction[] mulWithFor(Fraction[] arr)
        {
            for (int i = 0; i<arr.length; i++)
            {
                arr[i] = arr[i].multiply(new Fraction(2,1));
            }
            return arr;
        }

But thats not my Main goal I want to do it recursively so that was my approach:

public static Fraction[] mulAus(Fraction[] arr, int i)
        {
            if (i>= 0 && i<arr.length)
            {
                rekurMul(arr,i);
                //return mulAus(rekurMul(arr,i-1));
            }
            return arr;
        }

        public static Fraction rekurMul(Fraction[] arr, int i)
        {
            if (i>= 0 && i<arr.length)
            {
                return arr[i].multiply(new Fraction(2,1));
                return arr[i].multiply(new Fraction(2, 1)); // Does Not Work!!!
            }
            throw new IndexOutOfBoundsException();
        }

Maybe there is someone who can Help me! Thank you for your attention.

OK Thanks to @Chaï Sarfati and also to the others trying to help me out. I now know how to multiply recursive things in an Array! I used the Methods from @Chaï Sarfati but wrote an alternative method for his "oneThirdIsPresent" which is also a recursive method : So now my working code looks like this

 public static Fraction[] mulAus(Fraction[] arr)
        {
            if(contains(arr,arr.length-1,new Fraction(1,3)))
            {
                rekurMul(arr,0);
                return arr;
            }
            throw new IllegalArgumentException("1/3 does not exist in the Input-Array");
        }

        public static void rekurMul(Fraction[] arr, int i)
        {
            if(i == arr.length)
            {
                return ;
            }
            arr[i] = arr[i].multiply(new Fraction(2,1));
            rekurMul(arr,i+1);
        }

The Method to check if 1 / 3 exists in the given Array.

public static boolean contains(Fraction[] arr, int i, Fraction x)
        {
            if (i>= 0 && i < arr.length)
            {
                if (arr[i].equals(x))
                { return true;}
                else
                { return contains(arr, i-1,x); }
            }
            return false;
        }

I hope other People can learn from the code.. Maybe there are better solutions but I am just starting Programming so I dont know them for now.
Bye

Body:
Assuming you have a multiplyBy(Fraction f) method that works properly in you Fraction class.
Moreover, it will be better (more readable, more time & space complexity saving) to do it iteratively.
For the sake of the example, I would do like this:

First define:

private static boolean oneThirdIsPresent(Fraction[] arr){
    for (int i = 0; i < arr.length; i++) {
        if(arr[i].numerator == 1 && arr[i].denominator == 3) {
            return true;
        }
    }
    return false;
}

private static void recursivelyMultBy2(Fraction[] arr, int index){
    if(index == arr.length){
        return;
    }
    arr[index] = arr[index].multiplyBy(new Fraction(2));
    recursivelyMultBy2(arr, index+1);
}

In order to solve finally:

public static void multBy2IfOneThirdIsPresent(Fraction[] arr){
    if(oneThirdIsPresent(arr)){
        recursivelyMultBy2(arr, 0);
    }else{
        return;
    }
}


问:
Why is flink SplitStream marked deprecated
Why is flink SplitStream marked deprecated?
Will the stream be removed in the future?
Or what else is there to replace this</p>

答: Side outputs are more flexible and more efficient than split/select.</p>


问:
"tee" like programming api in UNIX
I want to have something like this

```<code>$> ps -ax | tee -a processes.txt
</code>```

In a UNIX C programming environment, meaning not via shell scripts.

Basically is there a API so that I can tee on STDIN and/or STDOUT so that I can recording automatically anything appears on the CLI down to a file. Imagine there's a foreground process interact with user and response with some output to the terminal. I want to have everything shown in the terminal also in a file for later examination.

I would imagine something as magic as this:

```<code>tee(STDIN, "append", logFile);
</code>```

Thanks!

Follow-up, this is the program I wrote according to Lars (see Answer section below), but not exactly what I desired:

```<code>int main(int argc, char** argv){

        int pfd[2];
        if (pipe(pfd) == -1) { perror("pipe"); }

        if (fork()==0) { // child reads from pipe
                close(pfd[1]);

                mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
                int ufd = open("user_study.log", O_CREAT | O_APPEND | O_WRONLY, mode);
                if (ufd == -1) {
                        perror("Cannot open output file"); exit(1);
                } // ++

                char buf;
                while (read(pfd[0], &buf, 1) > 0) {
                        write(STDOUT_FILENO, &buf, 1); // write to stdout
                        write(ufd, &buf,1);            //   and to log
                }

                close(pfd[0]);

        } else { // parent write to pipe
                // dup STDOUT to the pipe
                close(pfd[0]);
                dup2(pfd[1], STDOUT_FILENO);

                char msg[200];
                msg[0] = "";
                do {
                        scanf("%s", msg);
                        printf("program response..");

                } while (strcmp(msg, "exit")!=0);

                close(pfd[1]);

        }

        return 1;
}
</code>```

Actual running:

```<code>[feih@machine ~/mytest]$ ./a.out
abc
haha
exit
program response..   <---- the output is delayed by the chld process, not desired
program response..
program response..

[feih@machine ~/mytest]$ less user_study.log
program response..   <---- the log doesn't contain input
program response..
program response..
</code>```

Desired running and log(simulated):

```<code>[feih@machine ~/mytest]$ ./a.out
abc
program response..
haha
program response..
exit
program response..

[feih@machine ~/mytest]$ less user_study.log
abc
program response..      <--- the log should be the same as the running
haha
program response..
exit
program response..
</code>```

So up till now, this problem hasn't been fully resolved.

答:
You can do this:

create a pipe (see pipe(2))

fork

in the child, read from the pipe and write to each output

stdout and a file, or whatever you need

in the parent, redirect stdout to the pipe (see dup2(2))

There's a bunch of trickiness you need to take care of, but it's doable.

You can't do it this without an extra process, since printf only writes to one file descriptor (the stdout one).

Title: "tee" like programming api in UNIX

Body:
I want to have something like this

$> ps -ax | tee -a processes.txt

In a UNIX C programming environment, meaning not via shell scripts.

Basically is there a API so that I can tee on STDIN and/or STDOUT so that I can recording automatically anything appears on the CLI down to a file. Imagine there's a foreground process interact with user and response with some output to the terminal. I want to have everything shown in the terminal also in a file for later examination.

I would imagine something as magic as this:

tee(STDIN, "append", logFile);

Thanks!

Follow-up, this is the program I wrote according to Lars (see Answer section below), but not exactly what I desired:

int main(int argc, char** argv){

        int pfd[2];
        if (pipe(pfd) == -1) { perror("pipe"); }

        if (fork()==0) { // child reads from pipe
                close(pfd[1]);

                mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
                int ufd = open("user_study.log", O_CREAT | O_APPEND | O_WRONLY, mode);
                if (ufd == -1) {
                        perror("Cannot open output file"); exit(1);
                } // ++

                char buf;
                while (read(pfd[0], &buf, 1) > 0) {
                        write(STDOUT_FILENO, &buf, 1); // write to stdout
                        write(ufd, &buf,1);            //   and to log
                }

                close(pfd[0]);

        } else { // parent write to pipe
                // dup STDOUT to the pipe
                close(pfd[0]);
                dup2(pfd[1], STDOUT_FILENO);

                char msg[200];
                msg[0] = "";
                do {
                        scanf("%s", msg);
                        printf("program response..");

                } while (strcmp(msg, "exit")!=0);

                close(pfd[1]);

        }

        return 1;
}

Actual running:

[feih@machine ~/mytest]$ ./a.out
abc
haha
exit
program response..   <---- the output is delayed by the chld process, not desired
program response..
program response..

[feih@machine ~/mytest]$ less user_study.log
program response..   <---- the log doesn't contain input
program response..
program response..

Desired running and log(simulated):

[feih@machine ~/mytest]$ ./a.out
abc
program response..
haha
program response..
exit
program response..

[feih@machine ~/mytest]$ less user_study.log
abc
program response..      <--- the log should be the same as the running
haha
program response..
exit
program response..

So up till now, this problem hasn't been fully resolved.


问:
Passing values between 2 arraylists
Hi I have two arraylists, in the first arraySpinner are loaded with the present values of a given object, I have to extrapolate the string field and add to the arraylist arrayTemp how can I do?

Code:

```<code>ArrayList<Tipologia> arraySpinner=Articolo.CaricamentoTipologie();
ArrayList<String> arrayTemp=new ArrayList<String>();
//Object Tipologia
public class Tipologia implements Serializable {

    private int IdTipologiaArticolo;
    private String Nome;

    public Tipologia(int IdTipologiaArticolo, String Nome) {
        this.Nome = Nome;
        this.IdTipologiaArticolo = IdTipologiaArticolo;
    }

    public String GetNomeTipologia(){
        return Nome;
    }

    public int GetIdTipologiaArticolo(){
        return IdTipologiaArticolo;
    }
}
</code>```

答:
Here:

```<code>ArrayList<Tipologia> arraySpinner=Articolo.CaricamentoTipologie();
</code>```

You have multiple Tipologia objects. You can simply iterate them:

```<code>for (Tipologia tipo : arraySpinner) {
  arrayTemp.add(tipo.GetNomeTipologia());
}
</code>```

And a few hints:

follow java naming conventions: method names go camelCase()

prefer to use the List interface where possible, like List<String> tipoNames=new ArrayList<String>(); (and use names that say what they are)

For the record: you could also use java streams, like:

```<code>List<String> names = arraySpinner.stream().map(tipo -> tipo.GetNomeTipologia()).collect(Collectors.toList());
</code>```

That "streams" the elements of your arraySpinner list, and for each entry, it will call that get method, which creates a stream of Strings, which we finally push into a new List.

Title: Passing values between 2 arraylists

Body:
Hi I have two arraylists, in the first arraySpinner are loaded with the present values of a given object, I have to extrapolate the string field and add to the arraylist arrayTemp how can I do?

Code:

ArrayList<Tipologia> arraySpinner=Articolo.CaricamentoTipologie();
ArrayList<String> arrayTemp=new ArrayList<String>();
//Object Tipologia
public class Tipologia implements Serializable {

    private int IdTipologiaArticolo;
    private String Nome;

    public Tipologia(int IdTipologiaArticolo, String Nome) {
        this.Nome = Nome;
        this.IdTipologiaArticolo = IdTipologiaArticolo;
    }

    public String GetNomeTipologia(){
        return Nome;
    }

    public int GetIdTipologiaArticolo(){
        return IdTipologiaArticolo;
    }
}

Body:
Here:

ArrayList<Tipologia> arraySpinner=Articolo.CaricamentoTipologie();

You have multiple Tipologia objects. You can simply iterate them:

for (Tipologia tipo : arraySpinner) {
  arrayTemp.add(tipo.GetNomeTipologia());
}

And a few hints:

follow java naming conventions: method names go camelCase()

prefer to use the List interface where possible, like List<String> tipoNames=new ArrayList<String>(); (and use names that say what they are)

For the record: you could also use java streams, like:

List<String> names = arraySpinner.stream().map(tipo -> tipo.GetNomeTipologia()).collect(Collectors.toList());

That "streams" the elements of your arraySpinner list, and for each entry, it will call that get method, which creates a stream of Strings, which we finally push into a new List.


问:
Express+Typescript+React: Error: ENOENT: no such file or directory, stat '/app/frontend/build/index.html'?
i have this express server in ts and this is the converted js, code:

```<code>class App {
    constructor() {
        this.app = express();
        ...
        this.config();
        ...
    }
    config() {
        if (process.env.NODE_ENV === 'production') {
            // Serve any static files
            this.app.use(express.static(path.join(__dirname, '../../frontend/build')));
            // Handle React routing, return all requests to React app
            this.app.get('*', (req, res) => {
                res.sendFile(path.join(__dirname, '../../frontend/build', 'index.html'));
            });
        }
    }
}
exports.default = new App().app;
</code>```

but I am getting this error on heroku:

Error: ENOENT: no such file or directory, stat
  '/app/frontend/build/index.html'

I have checked the directories on heroku bash and build is there, and this is not my first time deploying app, but this time it is typescript, I'm used to to javascript and I am thinking maybe this is different? I am 100% certain the folder is properly targeted on config(). Help?

答:
TypeScript does not copy files that it does not actively compile to the destination directory, such as assets and template files.

I suspect that index.html was not copied to the output directory from where your code resolves the absolute path for res.sendFile(...).

You might want to move those files into a separate directory that is untouched by the TypeScript compilation process. Alternatively, implement a gulp or grunt task that recursively copies all non-JavaScript, non-JSON and non-TypeScript files over to your TypeScript output folder so that all relative paths resolve correctly.

This thread might help you: Angular 2 + Typescript compiler copy html and css files

Body:
i have this express server in ts and this is the converted js, code:

class App {
    constructor() {
        this.app = express();
        ...
        this.config();
        ...
    }
    config() {
        if (process.env.NODE_ENV === 'production') {
            // Serve any static files
            this.app.use(express.static(path.join(__dirname, '../../frontend/build')));
            // Handle React routing, return all requests to React app
            this.app.get('*', (req, res) => {
                res.sendFile(path.join(__dirname, '../../frontend/build', 'index.html'));
            });
        }
    }
}
exports.default = new App().app;

but I am getting this error on heroku:

Error: ENOENT: no such file or directory, stat
  '/app/frontend/build/index.html'

I have checked the directories on heroku bash and build is there, and this is not my first time deploying app, but this time it is typescript, I'm used to to javascript and I am thinking maybe this is different? I am 100% certain the folder is properly targeted on config(). Help?


问:
how to define a range object in VBscript
I'm trying to convert VBA program to VbScript in order to run it from the cmd.
I created a program in VBA that get an excel workbook and um-marged cells while keeping its content in all the newly formed un-marged cells.
explanation:
the balded zeros are in one merged cell and the one are in a non-merged cells

[[0][0]][0][0]][1][1][1]

After the function I expect the result to look like:

[0][0][0][0][1][1][1]

each value in one single cell

I wrote a VBA script that doing it

this function take one sheet and un-marge all the cells while keeping the values for all of the newly formed cells

```<code>Sub UnMergeFill(ByVal ws As Worksheet)

    Dim cell As Range, joinedCells As Range

    For Each cell In ws.UsedRange
        If cell.MergeCells Then
            Set joinedCells = cell.MergeArea
            cell.MergeCells = False
            joinedCells.Value = cell.Value
        End If
    Next

End Sub
</code>```

this  function takes the first function and applys it for all the sheets in the workbook

```<code>sub UnMergeFillAllSheets()
    Dim ws As Worksheet
    for Each ws In Worksheets
         UnMergeFill ws
    Next
End Sub
</code>```

when I'm converting it to VBScript its looks like:

```<code>Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True
Dim myworkbook, worksheetcount,cell
Set myworkbook = objExcel.Workbooks.Open("C:\Users\sm\Documents\work\try\try.xlsx")
worksheetcount = myworkbook.Worksheets.Count
Msgbox ("there are:"&worksheetcount&" sheets")'testing
set cell = CreateObject("Range")
For i= 1 To worksheetcount
    set ws = objExcel.Worksheets(i)
    ws.Activate
    for each cell in ws.UsedRange

    **take all merge cells and un-merge them**

    Next

Next
</code>```

my problem is that I need to refer a range of merged cells,
when I'm trying to create a range object I'm getting an error:

activeX component can't create object:'Range'

I know Range exists because I used TypeName(ws.UsedRange) and the object is range type.

Thank you for your help

答:
You are using Late Binding.  The correct form would be to just Dim cell, and set it to Range objects.  You will not get any debug help if you try to do something with it that Range objects cannot do, much like you will not get IntelliSense for it.

```<code>Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True

Dim myworkbook, worksheetcount, cell

Set myworkbook = objExcel.Workbooks.Open("C:\Users\sm\Documents\work\try\try.xlsx")
worksheetcount = myworkbook.Worksheets.Count

Msgbox ("there are:"&worksheetcount&" sheets")'testing

For Each ws In objExcel.Worksheets
    ws.Activate
    For each cell in ws.UsedRange.Cells 'Loop through Cells, not Rows or Columns

        **take all merge cells and un-merge them**
    Next cell
Next ws
</code>```

Body:
I'm trying to convert VBA program to VbScript in order to run it from the cmd.
I created a program in VBA that get an excel workbook and um-marged cells while keeping its content in all the newly formed un-marged cells.
explanation:
the balded zeros are in one merged cell and the one are in a non-merged cells

[[0][0]][0][0]][1][1][1]

After the function I expect the result to look like:

[0][0][0][0][1][1][1]

each value in one single cell

I wrote a VBA script that doing it

this function take one sheet and un-marge all the cells while keeping the values for all of the newly formed cells

Sub UnMergeFill(ByVal ws As Worksheet)

    Dim cell As Range, joinedCells As Range

    For Each cell In ws.UsedRange
        If cell.MergeCells Then
            Set joinedCells = cell.MergeArea
            cell.MergeCells = False
            joinedCells.Value = cell.Value
        End If
    Next

End Sub

this  function takes the first function and applys it for all the sheets in the workbook

sub UnMergeFillAllSheets()
    Dim ws As Worksheet
    for Each ws In Worksheets
         UnMergeFill ws
    Next
End Sub

when I'm converting it to VBScript its looks like:

Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True
Dim myworkbook, worksheetcount,cell
Set myworkbook = objExcel.Workbooks.Open("C:\Users\sm\Documents\work\try\try.xlsx")
worksheetcount = myworkbook.Worksheets.Count
Msgbox ("there are:"&worksheetcount&" sheets")'testing
set cell = CreateObject("Range")
For i= 1 To worksheetcount
    set ws = objExcel.Worksheets(i)
    ws.Activate
    for each cell in ws.UsedRange

    **take all merge cells and un-merge them**

    Next

Next

my problem is that I need to refer a range of merged cells,
when I'm trying to create a range object I'm getting an error:

activeX component can't create object:'Range'

I know Range exists because I used TypeName(ws.UsedRange) and the object is range type.

Thank you for your help

Body:
You are using Late Binding.  The correct form would be to just Dim cell, and set it to Range objects.  You will not get any debug help if you try to do something with it that Range objects cannot do, much like you will not get IntelliSense for it.

Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True

Dim myworkbook, worksheetcount, cell

Set myworkbook = objExcel.Workbooks.Open("C:\Users\sm\Documents\work\try\try.xlsx")
worksheetcount = myworkbook.Worksheets.Count

Msgbox ("there are:"&worksheetcount&" sheets")'testing

For Each ws In objExcel.Worksheets
    ws.Activate
    For each cell in ws.UsedRange.Cells 'Loop through Cells, not Rows or Columns

        **take all merge cells and un-merge them**
    Next cell
Next ws


问:
How can I change status text color (iOS) in NativeScript?
My Application has a white background, so I can't see anything there like time and battery icon.

I would need the dark status bar text color from iOS.

答:
You will have to update the info.plist at App_Resources/iOS. Detailed instructions can be found at {N} docs.

Use UIStatusBarStyleDefault for black text,

```<code><key>UIStatusBarStyle</key>
<string>UIStatusBarStyleLightContent</string>
<key>UIViewControllerBasedStatusBarAppearance</key>
<false/>
</code>```

Body:
You will have to update the info.plist at App_Resources/iOS. Detailed instructions can be found at {N} docs.

Use UIStatusBarStyleDefault for black text,

<key>UIStatusBarStyle</key>
<string>UIStatusBarStyleLightContent</string>
<key>UIViewControllerBasedStatusBarAppearance</key>
<false/>


问:
AS3 - Accessing Library Items from outside the Document class
How do you access Library items from classes other than the document class?

For example, if I create a movie clip in Flash and Export it for Actionscript with the name Foo, I can do this in the document class:

```<code>var f = new Foo();
this.addChild(f);
</code>```

And it appears on the stage, as it should. But I need to be able to create other instances of this object from other classes. If I use the same code above in SomeOtherClass.as, I get nothing on the stage, obviously because this class doesn't know about the Foo object in the library.

I know I probably need to use appplicationDomain.getDefinition somehow. This doesn't work:

```<code>var a = new ApplicationDomain(ApplicationDomain.currentDomain);
var foo: Class = a.getDefinition ( "com.me.CustomClass" ) ;
var f = new foo( ) ;
addChild ( f ) ;
</code>```

TypeError: Error #1007: Instantiation attempted on a non-constructor.

答:
I find these answers somewhat over-cooked,  because all I've ever done to use a Library Item from any class is to import it like any standard import. Surely that's why we select Export for Actionscript.

For example:

```<code>package
{
   import foo;                     // Library MovieClip
   import flash.display.MovieClip; // Must import MovieClip to Extend it.
   .......

   public class something extends MovieClip
   {
     private var _foo:foo;   // Create a local reference of the imported Library Item.
     ......

    public function something():void
    {
     _foo = new foo(); // Create a new instance of the imported Library Item.
     .........
    }
   }
  }
</code>```

I find this works each and every time, can't say whether or not it's the right way. but it works for me.

OwnerDisplayName: sol

ContentLicense: CC BY-SA 2.5

Body:
How do you access Library items from classes other than the document class?

For example, if I create a movie clip in Flash and Export it for Actionscript with the name Foo, I can do this in the document class:

var f = new Foo();
this.addChild(f);

And it appears on the stage, as it should. But I need to be able to create other instances of this object from other classes. If I use the same code above in SomeOtherClass.as, I get nothing on the stage, obviously because this class doesn't know about the Foo object in the library.

I know I probably need to use appplicationDomain.getDefinition somehow. This doesn't work:

var a = new ApplicationDomain(ApplicationDomain.currentDomain);
var foo: Class = a.getDefinition ( "com.me.CustomClass" ) ;
var f = new foo( ) ;
addChild ( f ) ;

TypeError: Error #1007: Instantiation attempted on a non-constructor.

Body:
I find these answers somewhat over-cooked,  because all I've ever done to use a Library Item from any class is to import it like any standard import. Surely that's why we select Export for Actionscript.

For example:

package
{
   import foo;                     // Library MovieClip
   import flash.display.MovieClip; // Must import MovieClip to Extend it.
   .......

   public class something extends MovieClip
   {
     private var _foo:foo;   // Create a local reference of the imported Library Item.
     ......

    public function something():void
    {
     _foo = new foo(); // Create a new instance of the imported Library Item.
     .........
    }
   }
  }

I find this works each and every time, can't say whether or not it's the right way. but it works for me.