问:
wx processing detail and progress bar
I'm trying to make a file downloader program and want to show a panel that shows all the processing details in that panel and not in the shell I already have a progress bar, but want to put the processing panel below the wxpython mainframe.
I tried to do it but didn't find any solution, I want to ask does wxpython supports this feature and if yes, then can you help me to do so

I'm not an expert just started working with python... will be very thankful for your replies.

答:
You will want to use a thread to do the downloading part as doing file I/O tends to be blocking. I wrote about this a few years ago here:

https://www.blog.pythonlibrary.org/2013/09/04/wxpython-how-to-update-a-progress-bar-from-a-thread/

More recently, I actually put together a simple application that demonstrates how to download a file using wxPython and a progress bar:

https://www.blog.pythonlibrary.org/2014/01/29/wxpython-creating-a-file-downloading-app/

Here's the code example:

```<code>import requests
import os
import wx
import wx.lib.scrolledpanel as scrolled

from threading import Thread
from wx.lib.pubsub import pub

########################################################################
class DownloadThread(Thread):
    """Downloading thread"""

    #----------------------------------------------------------------------
    def __init__(self, gnum, url, fsize):
        """Constructor"""
        Thread.__init__(self)
        self.fsize = fsize
        self.gnum = gnum
        self.url = url
        self.start()

    #----------------------------------------------------------------------
    def run(self):
        """
        Run the worker thread
        """
        local_fname = os.path.basename(self.url)
        count = 1
        while True:
            if os.path.exists(local_fname):
                tmp, ext = os.path.splitext(local_fname)
                cnt = "(%s)" % count
                local_fname = tmp + cnt + ext
                count += 1
            else:
                break
        req = requests.get(self.url, stream=True)
        total_size = 0
        print local_fname
        with open(local_fname, "wb") as fh:
            for byte in req.iter_content(chunk_size=1024):
                if byte:
                    fh.write(byte)
                    fh.flush()
                total_size += len(byte)
                if total_size < self.fsize:
                    wx.CallAfter(pub.sendMessage,
                                 "update_%s" % self.gnum,
                                 msg=total_size)
        print "DONE!"
        wx.CallAfter(pub.sendMessage,
                     "update_%s" % self.gnum,
                     msg=self.fsize)

########################################################################
class MyGauge(wx.Gauge):
    """"""

    #----------------------------------------------------------------------
    def __init__(self, parent, range, num):
        """Constructor"""
        wx.Gauge.__init__(self, parent, range=range)

        pub.subscribe(self.updateProgress, "update_%s" % num)

    #----------------------------------------------------------------------
    def updateProgress(self, msg):
        """"""
        self.SetValue(msg)

########################################################################
class MyPanel(scrolled.ScrolledPanel):
    """"""

    #----------------------------------------------------------------------
    def __init__(self, parent):
        """Constructor"""
        scrolled.ScrolledPanel.__init__(self, parent)

        self.data = []
        self.download_number = 1

        # create the sizers
        self.main_sizer = wx.BoxSizer(wx.VERTICAL)
        dl_sizer = wx.BoxSizer(wx.HORIZONTAL)

        # create the widgets
        lbl = wx.StaticText(self, label="Download URL:")
        self.dl_txt = wx.TextCtrl(self)
        btn = wx.Button(self, label="Download")
        btn.Bind(wx.EVT_BUTTON, self.onDownload)

        # layout the widgets
        dl_sizer.Add(lbl, 0, wx.ALL|wx.CENTER, 5)
        dl_sizer.Add(self.dl_txt, 1, wx.EXPAND|wx.ALL, 5)
        dl_sizer.Add(btn, 0, wx.ALL, 5)
        self.main_sizer.Add(dl_sizer, 0, wx.EXPAND)

        self.SetSizer(self.main_sizer)
        self.SetAutoLayout(1)
        self.SetupScrolling()

    #----------------------------------------------------------------------
    def onDownload(self, event):
        """
        Update display with downloading gauges
        """
        url = self.dl_txt.GetValue()
        try:
            header = requests.head(url)
            fsize = int(header.headers["content-length"]) / 1024

            sizer = wx.BoxSizer(wx.HORIZONTAL)
            fname = os.path.basename(url)
            lbl = wx.StaticText(self, label="Downloading %s" % fname)
            gauge = MyGauge(self, fsize, self.download_number)

            sizer.Add(lbl, 0, wx.ALL|wx.CENTER, 5)
            sizer.Add(gauge, 0, wx.ALL|wx.EXPAND, 5)
            self.main_sizer.Add(sizer, 0, wx.EXPAND)

            self.Layout()

            # start thread
            DownloadThread(self.download_number, url, fsize)
            self.dl_txt.SetValue("")
            self.download_number += 1
        except Exception, e:
            print "Error: ", e

########################################################################
class DownloaderFrame(wx.Frame):
    """"""

    #----------------------------------------------------------------------
    def __init__(self):
        """Constructor"""
        wx.Frame.__init__(self, None, title="Downloader", size=(800, 400))
        panel = MyPanel(self)
        self.Show()

#----------------------------------------------------------------------
if __name__ == "__main__":
    app = wx.App(False)
    frame = DownloaderFrame()
    app.MainLoop()
</code>```

Note that I am using requests instead of Python's urllib for the actual downloading, so you will want to get that as well or update this code to use urllib.

Title: wx processing detail and progress bar

Body:
You will want to use a thread to do the downloading part as doing file I/O tends to be blocking. I wrote about this a few years ago here:

https://www.blog.pythonlibrary.org/2013/09/04/wxpython-how-to-update-a-progress-bar-from-a-thread/

More recently, I actually put together a simple application that demonstrates how to download a file using wxPython and a progress bar:

https://www.blog.pythonlibrary.org/2014/01/29/wxpython-creating-a-file-downloading-app/

Here's the code example:

import requests
import os
import wx
import wx.lib.scrolledpanel as scrolled

from threading import Thread
from wx.lib.pubsub import pub

########################################################################
class DownloadThread(Thread):
    """Downloading thread"""

    #----------------------------------------------------------------------
    def __init__(self, gnum, url, fsize):
        """Constructor"""
        Thread.__init__(self)
        self.fsize = fsize
        self.gnum = gnum
        self.url = url
        self.start()

    #----------------------------------------------------------------------
    def run(self):
        """
        Run the worker thread
        """
        local_fname = os.path.basename(self.url)
        count = 1
        while True:
            if os.path.exists(local_fname):
                tmp, ext = os.path.splitext(local_fname)
                cnt = "(%s)" % count
                local_fname = tmp + cnt + ext
                count += 1
            else:
                break
        req = requests.get(self.url, stream=True)
        total_size = 0
        print local_fname
        with open(local_fname, "wb") as fh:
            for byte in req.iter_content(chunk_size=1024):
                if byte:
                    fh.write(byte)
                    fh.flush()
                total_size += len(byte)
                if total_size < self.fsize:
                    wx.CallAfter(pub.sendMessage,
                                 "update_%s" % self.gnum,
                                 msg=total_size)
        print "DONE!"
        wx.CallAfter(pub.sendMessage,
                     "update_%s" % self.gnum,
                     msg=self.fsize)

########################################################################
class MyGauge(wx.Gauge):
    """"""

    #----------------------------------------------------------------------
    def __init__(self, parent, range, num):
        """Constructor"""
        wx.Gauge.__init__(self, parent, range=range)

        pub.subscribe(self.updateProgress, "update_%s" % num)

    #----------------------------------------------------------------------
    def updateProgress(self, msg):
        """"""
        self.SetValue(msg)

########################################################################
class MyPanel(scrolled.ScrolledPanel):
    """"""

    #----------------------------------------------------------------------
    def __init__(self, parent):
        """Constructor"""
        scrolled.ScrolledPanel.__init__(self, parent)

        self.data = []
        self.download_number = 1

        # create the sizers
        self.main_sizer = wx.BoxSizer(wx.VERTICAL)
        dl_sizer = wx.BoxSizer(wx.HORIZONTAL)

        # create the widgets
        lbl = wx.StaticText(self, label="Download URL:")
        self.dl_txt = wx.TextCtrl(self)
        btn = wx.Button(self, label="Download")
        btn.Bind(wx.EVT_BUTTON, self.onDownload)

        # layout the widgets
        dl_sizer.Add(lbl, 0, wx.ALL|wx.CENTER, 5)
        dl_sizer.Add(self.dl_txt, 1, wx.EXPAND|wx.ALL, 5)
        dl_sizer.Add(btn, 0, wx.ALL, 5)
        self.main_sizer.Add(dl_sizer, 0, wx.EXPAND)

        self.SetSizer(self.main_sizer)
        self.SetAutoLayout(1)
        self.SetupScrolling()

    #----------------------------------------------------------------------
    def onDownload(self, event):
        """
        Update display with downloading gauges
        """
        url = self.dl_txt.GetValue()
        try:
            header = requests.head(url)
            fsize = int(header.headers["content-length"]) / 1024

            sizer = wx.BoxSizer(wx.HORIZONTAL)
            fname = os.path.basename(url)
            lbl = wx.StaticText(self, label="Downloading %s" % fname)
            gauge = MyGauge(self, fsize, self.download_number)

            sizer.Add(lbl, 0, wx.ALL|wx.CENTER, 5)
            sizer.Add(gauge, 0, wx.ALL|wx.EXPAND, 5)
            self.main_sizer.Add(sizer, 0, wx.EXPAND)

            self.Layout()

            # start thread
            DownloadThread(self.download_number, url, fsize)
            self.dl_txt.SetValue("")
            self.download_number += 1
        except Exception, e:
            print "Error: ", e

########################################################################
class DownloaderFrame(wx.Frame):
    """"""

    #----------------------------------------------------------------------
    def __init__(self):
        """Constructor"""
        wx.Frame.__init__(self, None, title="Downloader", size=(800, 400))
        panel = MyPanel(self)
        self.Show()

#----------------------------------------------------------------------
if __name__ == "__main__":
    app = wx.App(False)
    frame = DownloaderFrame()
    app.MainLoop()

Note that I am using requests instead of Python's urllib for the actual downloading, so you will want to get that as well or update this code to use urllib.


来源: stackexchange

问:
How to Do Jquery equivalent of prevAll() nextAll() in AngularJS?
I'm building a project using AngularJS and can't seem to find any example of what I'm looking for...

Using AngularJS, I know how to add a class to anything that's clicked, but how do I add a class to all previous items and remove class from all next items?

I'd like to do the jquery equivalent of .prevAll()/.nextAll(), but using AngularJS.

Here's and example of the jquery way for reference:

HTML:

```<code><a class="btn btn-primary"> Progress 1</a>
<a class="btn btn-primary"> Progress 2</a>
<a class="btn btn-primary"> Progress 3</a>
<a class="btn btn-primary"> Progress 4</a>
<a class="btn btn-primary"> Progress 5</a>
<a class="btn btn-primary"> Progress 6</a>
</code>```

Jquery:

```<code>$(".btn").on("click", function(){
    $(this).addClass('active');
    $(this).prevAll().addClass('active');
    $(this).nextAll().removeClass('active');
});
</code>```

https://jsfiddle.net/mujaji/yy82twho/1/

I'm trying to figure out how to do using AngularJS. Can someone explain a good strategy or standard?

thanks
Joe

答:
As all the  have same structue so i am assuming it is generated by ng-repeat.

You can do this by using the $index of ng-repeat in angularjs as below

```<code><a class="btn btn-primary" ng-class="{'active': $index <= selectedIndex}"
         ng-repeat="p in progress" ng-click="click($index)"> {{p}}</a>
</code>```

active class will be automatically added and removed to a tag based on the condition given in ng-class

selectedIndex is set in the controller based on the  clicked.

In the controller you will have somthing like below.

```<code>  $scope.progress = ['Progress 1','Progress 2','Progress 3','Progress 4','Progress 5','Progress 6'];

  $scope.selectedIndex = 0;

  $scope.click = function(indexclicked){
    $scope.selectedIndex = indexclicked;
  }
</code>```

Here is the working Jsfiddle demo i have created : http://jsfiddle.net/Makarand_Patil/U3pVM/34638/

Hope this helps you.

ContentLicense: CC BY-SA 3.0

Body:
I'm building a project using AngularJS and can't seem to find any example of what I'm looking for...

Using AngularJS, I know how to add a class to anything that's clicked, but how do I add a class to all previous items and remove class from all next items?

I'd like to do the jquery equivalent of .prevAll()/.nextAll(), but using AngularJS.

Here's and example of the jquery way for reference:

HTML:

 Progress 1
 Progress 2
 Progress 3
 Progress 4
 Progress 5
 Progress 6

Jquery:

$(".btn").on("click", function(){
    $(this).addClass('active');
    $(this).prevAll().addClass('active');
    $(this).nextAll().removeClass('active');
});

https://jsfiddle.net/mujaji/yy82twho/1/

I'm trying to figure out how to do using AngularJS. Can someone explain a good strategy or standard?

thanks
Joe

Body:
As all the <a> have same structue so i am assuming it is generated by ng-repeat.

You can do this by using the $index of ng-repeat in angularjs as below

<a class="btn btn-primary" ng-class="{'active': $index <= selectedIndex}"
         ng-repeat="p in progress" ng-click="click($index)"> {{p}}</a>

active class will be automatically added and removed to a tag based on the condition given in ng-class

selectedIndex is set in the controller based on the <a> clicked.

In the controller you will have somthing like below.

  $scope.progress = ['Progress 1','Progress 2','Progress 3','Progress 4','Progress 5','Progress 6'];

  $scope.selectedIndex = 0;

  $scope.click = function(indexclicked){
    $scope.selectedIndex = indexclicked;
  }

Here is the working Jsfiddle demo i have created : http://jsfiddle.net/Makarand_Patil/U3pVM/34638/

Hope this helps you.


问:
Get final url after timed delay or redirect
I am trying to scrape a website, but when I open the webpage it has 5 seconds redirect delay, i.e. you have to wait for 5 sec and then the real page loads.
I have tried the following code .

```<code>from bs4 import BeautifulSoup
import time
import requests

r=requests.get("https://etherscan.io/address/0xc257274276a4e539741ca11b590b9447b26a8051",timeout=6)
time.sleep(5)
print(r.history)

data=r.text

soup=BeautifulSoup(data)

print(soup.prettify())
</code>```

But when I run the code I get the redirect page, not the final page. Thanks for help

答:
It looks like etherscan.io is protected by Cloudflare, and Cloudflare is causing the delayed redirect that you are seeing.  One of the purposes of Cloudflare is to prevent bots from making automated requests to the site (which seems a lot like what you are doing).

Getting around Cloudflare will not be easy.  First, you'll need to make your requests 'look like' they are coming from a real browser - meaning that the tool that you are using to make these requests needs to present the same request headers that a real browser would, handle cookies like a browser would, run javascript like a browser would, etc.

Even if you succeed in doing all of the above, Cloudflare is likely to block your requests (or challenge them) after certain number of requests have been made over some period of time.

Body:
I am trying to scrape a website, but when I open the webpage it has 5 seconds redirect delay, i.e. you have to wait for 5 sec and then the real page loads.
I have tried the following code .

from bs4 import BeautifulSoup
import time
import requests

r=requests.get("https://etherscan.io/address/0xc257274276a4e539741ca11b590b9447b26a8051",timeout=6)
time.sleep(5)
print(r.history)

data=r.text

soup=BeautifulSoup(data)

print(soup.prettify())

But when I run the code I get the redirect page, not the final page. Thanks for help


问:
Visual Studio freezing (crashing) while loading solution
I've met with a strange problem. I had 7 projects in the solution. I had to add another MVC project. Now when the document (from the new project) is opened  (for example HomeController.cs) and when this project is initializing at the start, it freezes the whole IDE like this:

(Some projects do not load)

After that, I have to kill the process. When I open VS again and fast click on another project (which is initializing) the freezing issue is gone. I have no idea what can cause a problem like this. I've tried with and without ReSharper but I get the same result. Also, I restored default settings of VS. Also repaired whole VS.

Maybe someone had the same problem and could give some helpful advice?

答: I used to have this problem, it was solved just by double clicking any of the stuck projects. This nudges the loading process somehow and causes unloaded projects to complete its loading.</p>

ContentLicense: CC BY-SA 4.0


问:
Is there cppcheck plugin available in netbeans
I am using netbeans IDE for development. I want to check my code using cppcheck. Can any one tell me , is cppcheck plugin available for netbeans. If yes how to do that..?</p>

答:
Not exactly. There's an open bug for this functionality and the start of a module.
See https://netbeans.org/bugzilla/show_bug.cgi?id=201680 and https://github.com/johngull/nb-cppcheck

You could always add a custom makefile target that calls cppcheck. Maybe cppcheck's output will be something that NetBeans can recognize and provide hyperlinks to the source lines in the output window.


问:
Extracting fields from a url in scala-js
Suppose I've a url like :

```<code>https://example.com/myproject/index-dev.html?_ijt=hsdlgh8h5g8hh489sajoej&a=102&b=a%20m&c=45&d=all&e=all
</code>```

or it may be a webpage on localhost like :

```<code>localhost:63342/my project/index-dev.html?_ijt=hsdlgh8h5g8hh489sajoej&a=102&b=a%20m&c=45&d=all&e=all
</code>```

and I've to extract query fields (appearing after '?') from these urls in 2-D array as following :

```<code>_ijt    |    hsdlgh8h5g8hh489sajoej
a       |    102
b       |    a m
c       |    45
d       |    all
e       |    all
</code>```

Please do note that in 'b' field, I've replaced '%20' with a space. These fields like _ijt,a,b,c,d,e etc can vary in number and their names eg 'a' can be 'city'.
So far I've used regular expression to extract out the part after '?' and then use split("&") method to split the string into multiple strings.
Code -

```<code>val url=localhost:63342/my project/index-dev.html?_ijt=hsdlgh8h5g8hh489sajoej&a=102&b=a%20m&c=45&d=all&e=all
val pattern="""(http|htpps)([A-Za-z0-9\:\/\%\-\.]*)\?""".r
val temp_url=pattern.replaceFirstIn(url,"")
val fields=temp_url.split("&")
println(fields.foreach(println))
</code>```

and the output is :

```<code>_ijt=hsdlgh8h5g8hh489sajoej
a=102
b=a%20m
c=45
d=all
e=all
</code>```

But it doesn't seem to be the correct way to do this. Any help ?

答:
Building on the suggestions to use "decodeURIComponent" and "java.net.URI" I came up with this quick and dirty solution that almost certainly could be improved but perhaps it helps:</p>

```<code>def getUrlParameters(url: String): Map[String, Array[String]] = {
    java.net.URI.create(url).getQuery.split('&').map(js.URIUtils.decodeURIComponent).map { p =>
      val split = p.split('=')
      (split.head, split.tail.mkString("="))
    }.groupBy(_._1).map(m => m._1 -> m._2.map(_._2))
}

def getUrlParameter(url: String, parameter: String): Option[String] = {
    getUrlParameters(url).get(parameter).flatMap(_.headOption)
}
</code>```

Body:
Suppose I've a url like :

https://example.com/myproject/index-dev.html?_ijt=hsdlgh8h5g8hh489sajoej&a=102&b=a%20m&c=45&d=all&e=all

or it may be a webpage on localhost like :

localhost:63342/my project/index-dev.html?_ijt=hsdlgh8h5g8hh489sajoej&a=102&b=a%20m&c=45&d=all&e=all

and I've to extract query fields (appearing after '?') from these urls in 2-D array as following :

_ijt    |    hsdlgh8h5g8hh489sajoej
a       |    102
b       |    a m
c       |    45
d       |    all
e       |    all

Please do note that in 'b' field, I've replaced '%20' with a space. These fields like _ijt,a,b,c,d,e etc can vary in number and their names eg 'a' can be 'city'.
So far I've used regular expression to extract out the part after '?' and then use split("&") method to split the string into multiple strings.
Code -

val url=localhost:63342/my project/index-dev.html?_ijt=hsdlgh8h5g8hh489sajoej&a=102&b=a%20m&c=45&d=all&e=all
val pattern="""(http|htpps)([A-Za-z0-9\:\/\%\-\.]*)\?""".r
val temp_url=pattern.replaceFirstIn(url,"")
val fields=temp_url.split("&")
println(fields.foreach(println))

and the output is :

_ijt=hsdlgh8h5g8hh489sajoej
a=102
b=a%20m
c=45
d=all
e=all

But it doesn't seem to be the correct way to do this. Any help ?

Body:
Building on the suggestions to use "decodeURIComponent" and "java.net.URI" I came up with this quick and dirty solution that almost certainly could be improved but perhaps it helps:

def getUrlParameters(url: String): Map[String, Array[String]] = {
    java.net.URI.create(url).getQuery.split('&').map(js.URIUtils.decodeURIComponent).map { p =>
      val split = p.split('=')
      (split.head, split.tail.mkString("="))
    }.groupBy(_._1).map(m => m._1 -> m._2.map(_._2))
}

def getUrlParameter(url: String, parameter: String): Option[String] = {
    getUrlParameters(url).get(parameter).flatMap(_.headOption)
}


问:
Akka: First message going to dead letters, from second message it is all fine
I have supervisor actor which selects child actor based on command received, whenever it creates a new child actor and sends message(ask pattern) it timesout as child actor tries to send back response but it goes to dead letters.

Here is the child actor code

```<code>class IdActor(id: String, injector: Injector) extends Actor {
  override def receive: Receive = {
    case cmd: GenerateIdCmd =>
      val parent = sender()
      ...
      Future(idEvent) pipeTo sender //Issue is here going to dead letters
      //Future(idEvent) pipeTo parent //This also leads to same problem
      //parent ! idEvent // Same issue
  }
}
</code>```

Here is supervisor code

```<code>class IdSupervisor(injector: Injector) extends Actor {
  override def receive: Receive = {
    case cmd: GenerateIdCmd =>
      ...
      val ref = context.child(cmd.id).getOrElse {
        context.actorOf(Props(classOf[IdActor], cmd.id, injector), cmd.id)
      }
      ask(ref, cmd) pipeTo sender
  }
}
</code>```

Second message is flowing back to originator, first response from all new child actors going to dead letters from there afterwards going good.

Working Solution
Issue is with Supervisor, fixed code

```<code>class IdSupervisor(injector: Injector) extends Actor {
      override def receive: Receive = {
        case cmd: GenerateIdCmd =>
          val originator = sender
          ...
          val ref = context.child(cmd.id).getOrElse {
            context.actorOf(Props(classOf[IdActor], cmd.id, injector), cmd.id)
          }
          ask(ref, cmd) pipeTo originator
      }
    }
</code>```

答:
I suspect that the issue doesn't actually occur when a child replies to the parent as you describe, but when the parent sends a message to a child and expects a reply:

```<code>val ref = context.child(cmd.id).getOrElse {
  context.actorOf(Props(classOf[IdActor], cmd.id, injector), cmd.id)
}
ask(ref, cmd) pipeTo sender
</code>```

An actor is started asynchronously upon creation. The observation that, when a new child is created, the first message to that child results in dead letters, while subsequent messages to that child result in the intended behavior, suggests an actor initialization issue. What's probably happening is that the child actors receive their first GenerateIdCmd message before they have completely started.

Body:
I have supervisor actor which selects child actor based on command received, whenever it creates a new child actor and sends message(ask pattern) it timesout as child actor tries to send back response but it goes to dead letters.

Here is the child actor code

class IdActor(id: String, injector: Injector) extends Actor {
  override def receive: Receive = {
    case cmd: GenerateIdCmd =>
      val parent = sender()
      ...
      Future(idEvent) pipeTo sender //Issue is here going to dead letters
      //Future(idEvent) pipeTo parent //This also leads to same problem
      //parent ! idEvent // Same issue
  }
}

Here is supervisor code

class IdSupervisor(injector: Injector) extends Actor {
  override def receive: Receive = {
    case cmd: GenerateIdCmd =>
      ...
      val ref = context.child(cmd.id).getOrElse {
        context.actorOf(Props(classOf[IdActor], cmd.id, injector), cmd.id)
      }
      ask(ref, cmd) pipeTo sender
  }
}

Second message is flowing back to originator, first response from all new child actors going to dead letters from there afterwards going good.

Working Solution
Issue is with Supervisor, fixed code

class IdSupervisor(injector: Injector) extends Actor {
      override def receive: Receive = {
        case cmd: GenerateIdCmd =>
          val originator = sender
          ...
          val ref = context.child(cmd.id).getOrElse {
            context.actorOf(Props(classOf[IdActor], cmd.id, injector), cmd.id)
          }
          ask(ref, cmd) pipeTo originator
      }
    }

Body:
I suspect that the issue doesn't actually occur when a child replies to the parent as you describe, but when the parent sends a message to a child and expects a reply:

val ref = context.child(cmd.id).getOrElse {
  context.actorOf(Props(classOf[IdActor], cmd.id, injector), cmd.id)
}
ask(ref, cmd) pipeTo sender

An actor is started asynchronously upon creation. The observation that, when a new child is created, the first message to that child results in dead letters, while subsequent messages to that child result in the intended behavior, suggests an actor initialization issue. What's probably happening is that the child actors receive their first GenerateIdCmd message before they have completely started.


问:
BreakOut Detection Python/R Pkg Installation
I have been trying to install the BreakOut Detetction pkg in a Windows enviornment.

Following is the pkg I am talking about, https://github.com/roland-hochmuth/BreakoutDetection

I was able to get swig on my machine by following the directions@ http://www.swig.org/Doc1.3/Windows.html

The pkg details 3 steps to install:

```<code>swig -python -c++ breakout_detection.i
python setup.py build_ext -I../src build
sudo python setup.py build_ext -I../src install
</code>```

I somehow got the first step to work.
The second step gives a lot of compilation errors.

I was wondering if anyone has tried compiling this pkg.

答:
i had this same issue. i dont know what the deal is, but if you clone from https://github.com/mysl/BreakoutDetection which is a fork off of the roland hochmuth version, the installation commands work (i had to move into the python subfolder before running the commands).

hope it helps

Body:
I have been trying to install the BreakOut Detetction pkg in a Windows enviornment.

Following is the pkg I am talking about, https://github.com/roland-hochmuth/BreakoutDetection

I was able to get swig on my machine by following the directions@ http://www.swig.org/Doc1.3/Windows.html

The pkg details 3 steps to install:

swig -python -c++ breakout_detection.i
python setup.py build_ext -I../src build
sudo python setup.py build_ext -I../src install

I somehow got the first step to work.
The second step gives a lot of compilation errors.

I was wondering if anyone has tried compiling this pkg.


问:
Use query builder in form CollectionType
Is it possible to use a query builder or something else in my collectionType ?</p>

答:
You have two options as explained in this doc after that you could use the entity_manager to extract your data from database and fill your collection.

Give it a try and hope it helps


问:
Convert and Operation Not working as expected. Ignoring Year value
I have the following code:

```<code>CONVERT(VARCHAR(20), TimeCard_Date, 101) <
CONVERT(VARCHAR(20), dateadd(dd,-3,getdate()), 101)
</code>```

The Original TimeCard_Date value = 2018-06-01

The GetDate() return = 11/14/2017

Can anyone assist as to why it thinks the Timecard_Date value set for June  2018 is less than the GetDate() minus 3 days value?

答:
You don't need to convert DATETIME to VARCHAR in order to compare dates. Just use:

```<code>TimeCard_Date < DATEADD(dd,-3,GETDATE())
</code>```

On the other hand, if you ever have to convert them to do it, you have to standarize the format (yyyyMMdd). You can check the FORMAT function https://learn.microsoft.com/en-us/sql/t-sql/functions/format-transact-sql

Body:
I have the following code:

CONVERT(VARCHAR(20), TimeCard_Date, 101) <
CONVERT(VARCHAR(20), dateadd(dd,-3,getdate()), 101)

The Original TimeCard_Date value = 2018-06-01

The GetDate() return = 11/14/2017

Can anyone assist as to why it thinks the Timecard_Date value set for June  2018 is less than the GetDate() minus 3 days value?

Body:
You don't need to convert DATETIME to VARCHAR in order to compare dates. Just use:

TimeCard_Date < DATEADD(dd,-3,GETDATE())

On the other hand, if you ever have to convert them to do it, you have to standarize the format (yyyyMMdd). You can check the FORMAT function https://learn.microsoft.com/en-us/sql/t-sql/functions/format-transact-sql


问:
RXJS repeat does not have a chance to repeat?
I have the following epic I use in my application to handle api requests:

```<code>action$ => {
  return action$.ofType(actions.requestType)
    .do(() => console.log('handled epic ' + actions.requestType))
    .switchMap((action) => (
      Observable.create((obs) => {
        obs.next({ type: type, value: action.value, form: action.form });
      })
      .debounceTime(250)
      .switchMap((iea) => (
        Observable.ajax(ajaxPost(url(iea.value), body ? body(iea.value) : action.form))
          .mergeMap(payload => {
            return Observable.merge(
              Observable.of(actions.success(payload)),
              /* some other stuff */
            );
          })
          .catch(payload => {
            return [actions.failure(payload)];
          })
      ))
  ))
  .takeUntil(action$.filter((a) => (a.type === masterCancelAction))
  .repeat();
};
</code>```

Basically, any time I perform an api request, I dispatch a request action. If I dispatch another request quickly, the previous one is ignored using debounceTime. Additionally, the request can be cancelled using the masterCancelAction and when cancelled repeat() restarts the epic. This epic works as intended in all cases expect one.

The failure case occurs when a user uses the browser back during a request. In this case I fire the masterCancelAction to the request. However, on the same execution context as a result from the masterCancelAction, another request action dispatches to perform a new request on the same epic, but the api request does not occur (the console.log does occur though) as if there was no repeat(). In other cases where cancels occur, the next request is not invoked from the same execution context and it works fine, so it seems in this case my code does not give repeat a chance to restart the epic?

A dirty workaround I found was to use setTimeout(dispatch(action), 0) on the request that dispatches after the cancellation. This seems to allow repeat() to execute. I tried passing different schedulers into repeat, but that didn't seem to help. Also, attaching takeUntil and repeat into my inner switchMap solves the problem, but then other cases where my next request does not execute in the same call stack fail.

Is there a way I can solve this problem without using setTimeout? Maybe it is not a repeat related problem, but it seems to be the case.

Using rxjs 5.0.3 and redux-observable 0.14.1.

答:
The issue is not 100% clear without something like a jsbin to see what you mean, but I do see some general issues that might help:

Anonymous Observable never completes

When creating a custom anonymous Observable it's important to call observer.complete() if you do indeed want it to complete. In most cases, not doing so will cause the subscription to be a memory leak and might also other strange behaviors

```<code>Observable.create((observer) => {
  observer.next({ type: type, value: action.value, form: action.form });
  observer.complete();
})
</code>```

Observable.of would have been equivalent:

```<code>Observable.of({ type: type, value: action.value, form: action.form })
</code>```

However, it's not clear why this was done as the values it emits are in captured in scope.

debounceTime in this case does not debounce, it delays

Since the anonymous observable it's applied to only ever emits a single item, debounceTime will act just as a regular .delay(250). I'm betting you intended instead to debounce actions.requestType actions, in which case you'd need to apply your debouncing outside the switchMap, after the action$.ofType(actions.requestType).

Observable.of accepts any number of arguments to emit

This is more of a "did you know?" rather than an issue, but I noticed you're merging your of and /* some other actions */ I assume would be other of observables merged in. Instead, you can just return a single of and pass the actions as arguments.

```<code>Observable.of(
  actions.success(payload),
  /* some other actions */
  actions.someOtherOne(),
  actions.etc()
);
</code>```

Also, when you find yourself emitting multiple actions synchronously like this, consider whether your reducers should be listening for the same, single action instead of having two or more. Sometimes this wouldn't make sense as you want them to have completely unrelated actions, just something to keep in mind that people often forget--that all reducers receive all actions and so multiple reducers can change their state from the same action.

.takeUntil will stop the epic from listening for future actions

Placing the takeUntil on the top-level observable chain causes the epic to stop listening for action$.ofType(actions.requestType), which is why you added the .repeat() after. This might work in some cases, but it's inefficient and can cause other hard to realize bugs. Epics should be thought of instead as sort of like sidecar processes that usually "start up" with the app and then continue listening for a particular action until the app "shuts down" aka the user leaves the app. They aren't actually processes, it's just helpful to conceptually think of them this way as an abstraction.

So each time it matches its particular action it then most often will switchMap, mergeMap, concatMap, or exhaustMap into some side effect, like an ajax call. That inner observable chain is what you want to make cancellable. So you'd place your .takeUntil on it, at the appropriate place in the chain.

Summary

As mentioned, it's not clear what you intended to do and what the issue is, without a more complete example like a jsbin. But strictly based on the code provided, this is my guesstimate:

```<code>const someRequestEpic = action$ => {
  return action$.ofType(actions.requestType)
    .debounceTime(250)
    .do(() => console.log('handled epic ' + actions.requestType))
    .switchMap((action) =>
      Observable.ajax(ajaxPost(url(action.value), body ? body(action.value) : action.form))
        .takeUntil(action$.ofType(masterCancelAction))
        .mergeMap(payload => {
          return Observable.of(
            actions.success(payload),
            /* some other actions */
            ...etc
          );
        })
        .catch(payload => Observable.of(
          actions.failure(payload)
        ))
    );
};
</code>```

Check out the Cancellation page in the redux-observable docs.

If this is a bit confusing, I'd recommend digging a bit deeper into what Observables are and what an "operator" is and does so that it doesn't feel magical and where you should place an operator makes more sense.

Ben's post on Learning Observable by Building Observable is a good start.

Body:
I have the following epic I use in my application to handle api requests:

action$ => {
  return action$.ofType(actions.requestType)
    .do(() => console.log('handled epic ' + actions.requestType))
    .switchMap((action) => (
      Observable.create((obs) => {
        obs.next({ type: type, value: action.value, form: action.form });
      })
      .debounceTime(250)
      .switchMap((iea) => (
        Observable.ajax(ajaxPost(url(iea.value), body ? body(iea.value) : action.form))
          .mergeMap(payload => {
            return Observable.merge(
              Observable.of(actions.success(payload)),
              /* some other stuff */
            );
          })
          .catch(payload => {
            return [actions.failure(payload)];
          })
      ))
  ))
  .takeUntil(action$.filter((a) => (a.type === masterCancelAction))
  .repeat();
};

Basically, any time I perform an api request, I dispatch a request action. If I dispatch another request quickly, the previous one is ignored using debounceTime. Additionally, the request can be cancelled using the masterCancelAction and when cancelled repeat() restarts the epic. This epic works as intended in all cases expect one.

The failure case occurs when a user uses the browser back during a request. In this case I fire the masterCancelAction to the request. However, on the same execution context as a result from the masterCancelAction, another request action dispatches to perform a new request on the same epic, but the api request does not occur (the console.log does occur though) as if there was no repeat(). In other cases where cancels occur, the next request is not invoked from the same execution context and it works fine, so it seems in this case my code does not give repeat a chance to restart the epic?

A dirty workaround I found was to use setTimeout(dispatch(action), 0) on the request that dispatches after the cancellation. This seems to allow repeat() to execute. I tried passing different schedulers into repeat, but that didn't seem to help. Also, attaching takeUntil and repeat into my inner switchMap solves the problem, but then other cases where my next request does not execute in the same call stack fail.

Is there a way I can solve this problem without using setTimeout? Maybe it is not a repeat related problem, but it seems to be the case.

Using rxjs 5.0.3 and redux-observable 0.14.1.

Body:
The issue is not 100% clear without something like a jsbin to see what you mean, but I do see some general issues that might help:

Anonymous Observable never completes

When creating a custom anonymous Observable it's important to call observer.complete() if you do indeed want it to complete. In most cases, not doing so will cause the subscription to be a memory leak and might also other strange behaviors

Observable.create((observer) => {
  observer.next({ type: type, value: action.value, form: action.form });
  observer.complete();
})

Observable.of would have been equivalent:

Observable.of({ type: type, value: action.value, form: action.form })

However, it's not clear why this was done as the values it emits are in captured in scope.

debounceTime in this case does not debounce, it delays

Since the anonymous observable it's applied to only ever emits a single item, debounceTime will act just as a regular .delay(250). I'm betting you intended instead to debounce actions.requestType actions, in which case you'd need to apply your debouncing outside the switchMap, after the action$.ofType(actions.requestType).

Observable.of accepts any number of arguments to emit

This is more of a "did you know?" rather than an issue, but I noticed you're merging your of and /* some other actions */ I assume would be other of observables merged in. Instead, you can just return a single of and pass the actions as arguments.

Observable.of(
  actions.success(payload),
  /* some other actions */
  actions.someOtherOne(),
  actions.etc()
);

Also, when you find yourself emitting multiple actions synchronously like this, consider whether your reducers should be listening for the same, single action instead of having two or more. Sometimes this wouldn't make sense as you want them to have completely unrelated actions, just something to keep in mind that people often forget--that all reducers receive all actions and so multiple reducers can change their state from the same action.

.takeUntil will stop the epic from listening for future actions

Placing the takeUntil on the top-level observable chain causes the epic to stop listening for action$.ofType(actions.requestType), which is why you added the .repeat() after. This might work in some cases, but it's inefficient and can cause other hard to realize bugs. Epics should be thought of instead as sort of like sidecar processes that usually "start up" with the app and then continue listening for a particular action until the app "shuts down" aka the user leaves the app. They aren't actually processes, it's just helpful to conceptually think of them this way as an abstraction.

So each time it matches its particular action it then most often will switchMap, mergeMap, concatMap, or exhaustMap into some side effect, like an ajax call. That inner observable chain is what you want to make cancellable. So you'd place your .takeUntil on it, at the appropriate place in the chain.

Summary

As mentioned, it's not clear what you intended to do and what the issue is, without a more complete example like a jsbin. But strictly based on the code provided, this is my guesstimate:

const someRequestEpic = action$ => {
  return action$.ofType(actions.requestType)
    .debounceTime(250)
    .do(() => console.log('handled epic ' + actions.requestType))
    .switchMap((action) =>
      Observable.ajax(ajaxPost(url(action.value), body ? body(action.value) : action.form))
        .takeUntil(action$.ofType(masterCancelAction))
        .mergeMap(payload => {
          return Observable.of(
            actions.success(payload),
            /* some other actions */
            ...etc
          );
        })
        .catch(payload => Observable.of(
          actions.failure(payload)
        ))
    );
};

Check out the Cancellation page in the redux-observable docs.

If this is a bit confusing, I'd recommend digging a bit deeper into what Observables are and what an "operator" is and does so that it doesn't feel magical and where you should place an operator makes more sense.

Ben's post on Learning Observable by Building Observable is a good start.


问:
Python object to C++ pointer problem
this is my first post :). I could convert a python extended object into a C++ pointer, but I have a problem. First I will show you my code and then I will explain the problem.

This is my class:

```<code>#include <boost/python.hpp>

using namespace boost::python;

class Base
{

public:

    virtual const char* HelloWorld() = 0;

};

class BaseWrapper : public Base, public wrapper<BaseWrapper>
{

public:

    virtual const char* HelloWorld()
    {

        if (override f = this->get_override("HelloWorld"))
            return call<const char*>(f.ptr());

        return "FAILED TO CALL";

    }

};
</code>```

Boost wrapping:

```<code>BOOST_PYTHON_MODULE(hello_ext)
{

     class_<Base, boost::noncopyable>("Base", no_init);

     class_<BaseWrapper, bases<Base> >("BaseWrapper")
         .def("HelloWorld", &BaseWrapper::HelloWorld);

}
</code>```

The Python code (hello.py):

```<code>def NewDerived():
    import hello_ext

    class Derived(hello_ext.BaseWrapper):
        def __init__(self):
                super(Derived, self).__init__()
        def HelloWorld(self):
                return "This is a Hello World!!!"

    return Derived()
</code>```

and the main file:

```<code>int main()
{

     // Start the interpreter.
     Py_Initialize();

     // Import the module that we need (hello.py)
     object module = import("hello");

     // Get a C++ pointer of the derived python class.
     Base* base = extract< Base* >( module.attr("NewDerived")() );

     // Call the HelloWorld function
     std::cout << base->HelloWorld() << std::endl;

}
</code>```

When I run my application I can see at the screen "This is a Hello World!!!" as I expected.
So, what is the problem??? Suppose I change the python code to:

```<code>def NewDerived():
    import hello_ext

    class Derived(hello_ext.BaseWrapper):
        def __init__(self):
                super(Derived, self).__init__()
        def HelloWorld(self):
                return "This is a Hello" # I CHANGED THIS LINE!!!!

    return Derived()
</code>```

Then, when I run my application again, it crashes, because I got an error in the line:

```<code>std::cout << base->HelloWorld() << std::endl;
</code>```

because base is NULL.

More precisely, the error is "Access violation reading location 0xblablabla".
When I debug, the debugguer stops at the function (Boost or Python code, I think)

```<code>inline api::object_base::~object_base()
{
    Py_DECREF(m_ptr);
}
</code>```

What do you think???

答:
Finally, another programmer explained me the solution.

I don't know why it worked originally, but the problem is that the object is getting destroyed before I try calling the member function. I need to break the extract call into two parts like so:

```<code>object derived = module.attr("NewDerived")();
Base* base = extract< Base* >( derived );
</code>```

This will keep the object around long enough for me to actually call functions on it.

ContentLicense: CC BY-SA 2.5

Title: Python object to C++ pointer problem

Body:
this is my first post :). I could convert a python extended object into a C++ pointer, but I have a problem. First I will show you my code and then I will explain the problem.

This is my class:

#include <boost/python.hpp>

using namespace boost::python;

class Base
{

public:

    virtual const char* HelloWorld() = 0;

};

class BaseWrapper : public Base, public wrapper<BaseWrapper>
{

public:

    virtual const char* HelloWorld()
    {

        if (override f = this->get_override("HelloWorld"))
            return call<const char*>(f.ptr());

        return "FAILED TO CALL";

    }

};

Boost wrapping:

BOOST_PYTHON_MODULE(hello_ext)
{

     class_<Base, boost::noncopyable>("Base", no_init);

     class_<BaseWrapper, bases<Base> >("BaseWrapper")
         .def("HelloWorld", &BaseWrapper::HelloWorld);

}

The Python code (hello.py):

def NewDerived():
    import hello_ext

    class Derived(hello_ext.BaseWrapper):
        def __init__(self):
                super(Derived, self).__init__()
        def HelloWorld(self):
                return "This is a Hello World!!!"

    return Derived()

and the main file:

int main()
{

     // Start the interpreter.
     Py_Initialize();

     // Import the module that we need (hello.py)
     object module = import("hello");

     // Get a C++ pointer of the derived python class.
     Base* base = extract< Base* >( module.attr("NewDerived")() );

     // Call the HelloWorld function
     std::cout << base->HelloWorld() << std::endl;

}

When I run my application I can see at the screen "This is a Hello World!!!" as I expected.
So, what is the problem??? Suppose I change the python code to:

def NewDerived():
    import hello_ext

    class Derived(hello_ext.BaseWrapper):
        def __init__(self):
                super(Derived, self).__init__()
        def HelloWorld(self):
                return "This is a Hello" # I CHANGED THIS LINE!!!!

    return Derived()

Then, when I run my application again, it crashes, because I got an error in the line:

std::cout << base->HelloWorld() << std::endl;

because base is NULL.

More precisely, the error is "Access violation reading location 0xblablabla".
When I debug, the debugguer stops at the function (Boost or Python code, I think)

inline api::object_base::~object_base()
{
    Py_DECREF(m_ptr);
}

What do you think???

Body:
Finally, another programmer explained me the solution.

I don't know why it worked originally, but the problem is that the object is getting destroyed before I try calling the member function. I need to break the extract call into two parts like so:

object derived = module.attr("NewDerived")();
Base* base = extract< Base* >( derived );

This will keep the object around long enough for me to actually call functions on it.


问:
Finding all possible combinations of numbers to reach a given sum
How would you go about testing all possible combinations of additions from a given set N of numbers so they add up to a given final number?

A brief example:

Set of numbers to add: N = {1,5,22,15,0,...}

Desired result: 12345

答:
Recommended as an answer:

Here's a solution using es2015 generators:

```<code>function* subsetSum(numbers, target, partial = [], partialSum = 0) {

  if(partialSum === target) yield partial

  if(partialSum >= target) return

  for(let i = 0; i < numbers.length; i++){
    const remaining = numbers.slice(i + 1)
        , n = numbers[i]

    yield* subsetSum(remaining, target, [...partial, n], partialSum + n)
  }

}
</code>```

Using generators can actually be very useful because it allows you to pause script execution immediately upon finding a valid subset. This is in contrast to solutions without generators (ie lacking state) which have to iterate through every single subset of numbers

Body:
Recommended as an answer:

Here's a solution using es2015 generators:

function* subsetSum(numbers, target, partial = [], partialSum = 0) {

  if(partialSum === target) yield partial

  if(partialSum >= target) return

  for(let i = 0; i < numbers.length; i++){
    const remaining = numbers.slice(i + 1)
        , n = numbers[i]

    yield* subsetSum(remaining, target, [...partial, n], partialSum + n)
  }

}

Using generators can actually be very useful because it allows you to pause script execution immediately upon finding a valid subset. This is in contrast to solutions without generators (ie lacking state) which have to iterate through every single subset of numbers


问:
boto3 - Step Functions generate_presigned_url InvalidSignatureException
I'm attempting to generate a pre-signed URL for describe_execution.

After trying different variations of request methods, headers, requests bodies, etc. any request I send to the presigned url will always fail. Canonical Request Hex in the String-to-Sign never matches.

boto3: 1.4.7

botocore: 1.7.44

Code

Note that I've replaced the values in the URLs for executionArn, X-Amz-Credential.

```<code>import boto3
import requests

sfn = boto3.client("stepfunctions")

presigned_url = sfn.generate_presigned_url(
  "describe_execution",
  Params={
    "executionArn": "arn:aws:states:us-west-2:123:execution:abc:def-ghi-jkl-mno"
  }
)

response = requests.post(presigned_url, data={})
print(response.text)
</code>```

Logs

```<code>DEBUG:botocore.session:Loading variable profile from defaults.
DEBUG:botocore.session:Loading variable config_file from defaults.
DEBUG:botocore.session:Loading variable credentials_file from defaults.
DEBUG:botocore.session:Loading variable data_path from defaults.
DEBUG:botocore.session:Loading variable profile from defaults.
DEBUG:botocore.session:Loading variable ca_bundle from defaults.
DEBUG:botocore.session:Loading variable profile from defaults.
DEBUG:botocore.session:Loading variable api_versions from defaults.
DEBUG:botocore.session:Loading variable profile from defaults.
DEBUG:botocore.session:Loading variable credentials_file from defaults.
DEBUG:botocore.session:Loading variable config_file from defaults.
DEBUG:botocore.session:Loading variable profile from defaults.
DEBUG:botocore.session:Loading variable metadata_service_timeout from defaults.
DEBUG:botocore.session:Loading variable profile from defaults.
DEBUG:botocore.session:Loading variable metadata_service_num_attempts from defaults.
DEBUG:botocore.session:Loading variable profile from defaults.
DEBUG:botocore.credentials:Looking for credentials via: env
DEBUG:botocore.credentials:Looking for credentials via: assume-role
DEBUG:botocore.credentials:Looking for credentials via: shared-credentials-file
INFO:botocore.credentials:Found credentials in shared credentials file: ~/.aws/credentials
DEBUG:botocore.loaders:Loading JSON file: /Users/maxwellgbrown/.virtualenvs/boto3/lib/python3.5/site-packages/botocore/data/endpoints.json
DEBUG:botocore.session:Loading variable profile from defaults.
DEBUG:botocore.loaders:Loading JSON file: /Users/maxwellgbrown/.virtualenvs/boto3/lib/python3.5/site-packages/botocore/data/stepfunctions/2016-11-23/service-2.json
DEBUG:botocore.hooks:Event creating-client-class.stepfunctions: calling handler <function add_generate_presigned_url at 0x10f863c80>
DEBUG:botocore.args:The s3 config key is not a dictionary type, ignoring its value of: None
DEBUG:botocore.endpoint:Setting states timeout as (60, 60)
DEBUG:botocore.loaders:Loading JSON file: /Users/maxwellgbrown/.virtualenvs/boto3/lib/python3.5/site-packages/botocore/data/_retry.json
DEBUG:botocore.client:Registering retry handlers for service: stepfunctions
DEBUG:botocore.hooks:Event choose-signer.states.DescribeExecution: calling handler <function set_operation_specific_signer at 0x10f8dd2f0>
DEBUG:botocore.auth:Calculating signature using v4 auth.
DEBUG:botocore.auth:CanonicalRequest:
POST
/
X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=ZZZ%2F20171115%2Fus-west-2%2Fstates%2Faws4_request&X-Amz-Date=20171115T191510Z&X-Amz-Expires=3600&X-Amz-SignedHeaders=content-type%3Bhost%3Bx-amz-target&executionArn=arn%3Aaws%3Astates%3Aus-west-2%3123%3Aexecution%3Aabc%def-ghi-jkl-mno
content-type:application/x-amz-json-1.0
host:states.us-west-2.amazonaws.com
x-amz-target:AWSStepFunctions.DescribeExecution

content-type;host;x-amz-target
e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
DEBUG:botocore.auth:StringToSign:
AWS4-HMAC-SHA256
20171115T191510Z
20171115/us-west-2/states/aws4_request
3afe55bcd073fc24a7dce06bacc3661c000230fd2df13e40fbc4d2d6eb30849b
DEBUG:botocore.auth:Signature:
4bcb1c51cfcbf4274a17af7aa3202f23f6d7ceb314c2e1e1dd9faac1eb110e91
DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): states.us-west-2.amazonaws.com
DEBUG:urllib3.connectionpool:https://states.us-west-2.amazonaws.com:443 "POST /?executionArn=arn%3Aaws%3Astates%3Aus-west-2%123%3Aexecution%3Aabc%def-ghi-jkl-mno&X-Amz-Expires=3600&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-SignedHeaders=content-type%3Bhost%3Bx-amz-target&X-Amz-Credential=ZZZ%2Fus-west-2%2Fstates%2Faws4_request&X-Amz-Date=20171115T191510Z&X-Amz-Signature=4bcb1c51cfcbf4274a17af7aa3202f23f6d7ceb314c2e1e1dd9faac1eb110e91 HTTP/1.1" 403 1030
</code>```

print(response)

```<code><InvalidSignatureException>
  <Message>The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details.

The Canonical String for this request should have been
'POST
/
X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=ZZZ%2Fus-west-2%2Fstates%2Faws4_request&X-Amz-Date=20171115T191510Z&X-Amz-Expires=3600&X-Amz-SignedHeaders=content-type%3Bhost%3Bx-amz-target&executionArn=arn%3Aaws%3Astates%3Aus-west-2%3123%3Aexecution%3Aabc%3efg-hij-klm-nmo
content-type:
host:states.us-west-2.amazonaws.com
x-amz-target:

content-type;host;x-amz-target
e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'

The String-to-Sign should have been
'AWS4-HMAC-SHA256
20171115T191510Z
20171115/us-west-2/states/aws4_request
1f390ad977de8b8bd1dd0226424bb1389ba62b6bb185784bf499a45b80c7d476'
</Message>
</InvalidSignatureException>
</code>```

I've had no issues generating presigned urls for retrieving s3 objects doing this:

```<code>s3 = client('s3')
s3.generate_presigned_url('get_object', Params={'Bucket': 'my-bucket', 'Key': 'my/file.txt'})
</code>```

答:
Based off the response to my boto3 issue it seems like stepfunctions doesn't support presigned urls.

So with what I tried, I was able to get passed the signing problem by providing the headers in the request (which is what you have to do as the headers are not included in the url but are signed for). However, I ran into a serialization issue.

The tricky part with the generate_presigned_url() is that it is a general method that is applied to all services, but it is really up to the service in whether they actually support using presigned url's and this decision differs from service to service. Given that I got a serialization error back, it looks like step functions does not support using presigned url's.

Instead, I think to support the general functionality of generating/signing a request to defer making the HTTP request for later, we will need to expose a generate_presigned_request(), but for now I think you will have to use the client.describe_execution() method. Let us know what your thoughts on this.

Body:
I'm attempting to generate a pre-signed URL for describe_execution.

After trying different variations of request methods, headers, requests bodies, etc. any request I send to the presigned url will always fail. Canonical Request Hex in the String-to-Sign never matches.

boto3: 1.4.7

botocore: 1.7.44

Code

Note that I've replaced the values in the URLs for executionArn, X-Amz-Credential.

import boto3
import requests

sfn = boto3.client("stepfunctions")

presigned_url = sfn.generate_presigned_url(
  "describe_execution",
  Params={
    "executionArn": "arn:aws:states:us-west-2:123:execution:abc:def-ghi-jkl-mno"
  }
)

response = requests.post(presigned_url, data={})
print(response.text)

Logs

DEBUG:botocore.session:Loading variable profile from defaults.
DEBUG:botocore.session:Loading variable config_file from defaults.
DEBUG:botocore.session:Loading variable credentials_file from defaults.
DEBUG:botocore.session:Loading variable data_path from defaults.
DEBUG:botocore.session:Loading variable profile from defaults.
DEBUG:botocore.session:Loading variable ca_bundle from defaults.
DEBUG:botocore.session:Loading variable profile from defaults.
DEBUG:botocore.session:Loading variable api_versions from defaults.
DEBUG:botocore.session:Loading variable profile from defaults.
DEBUG:botocore.session:Loading variable credentials_file from defaults.
DEBUG:botocore.session:Loading variable config_file from defaults.
DEBUG:botocore.session:Loading variable profile from defaults.
DEBUG:botocore.session:Loading variable metadata_service_timeout from defaults.
DEBUG:botocore.session:Loading variable profile from defaults.
DEBUG:botocore.session:Loading variable metadata_service_num_attempts from defaults.
DEBUG:botocore.session:Loading variable profile from defaults.
DEBUG:botocore.credentials:Looking for credentials via: env
DEBUG:botocore.credentials:Looking for credentials via: assume-role
DEBUG:botocore.credentials:Looking for credentials via: shared-credentials-file
INFO:botocore.credentials:Found credentials in shared credentials file: ~/.aws/credentials
DEBUG:botocore.loaders:Loading JSON file: /Users/maxwellgbrown/.virtualenvs/boto3/lib/python3.5/site-packages/botocore/data/endpoints.json
DEBUG:botocore.session:Loading variable profile from defaults.
DEBUG:botocore.loaders:Loading JSON file: /Users/maxwellgbrown/.virtualenvs/boto3/lib/python3.5/site-packages/botocore/data/stepfunctions/2016-11-23/service-2.json
DEBUG:botocore.hooks:Event creating-client-class.stepfunctions: calling handler <function add_generate_presigned_url at 0x10f863c80>
DEBUG:botocore.args:The s3 config key is not a dictionary type, ignoring its value of: None
DEBUG:botocore.endpoint:Setting states timeout as (60, 60)
DEBUG:botocore.loaders:Loading JSON file: /Users/maxwellgbrown/.virtualenvs/boto3/lib/python3.5/site-packages/botocore/data/_retry.json
DEBUG:botocore.client:Registering retry handlers for service: stepfunctions
DEBUG:botocore.hooks:Event choose-signer.states.DescribeExecution: calling handler <function set_operation_specific_signer at 0x10f8dd2f0>
DEBUG:botocore.auth:Calculating signature using v4 auth.
DEBUG:botocore.auth:CanonicalRequest:
POST
/
X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=ZZZ%2F20171115%2Fus-west-2%2Fstates%2Faws4_request&X-Amz-Date=20171115T191510Z&X-Amz-Expires=3600&X-Amz-SignedHeaders=content-type%3Bhost%3Bx-amz-target&executionArn=arn%3Aaws%3Astates%3Aus-west-2%3123%3Aexecution%3Aabc%def-ghi-jkl-mno
content-type:application/x-amz-json-1.0
host:states.us-west-2.amazonaws.com
x-amz-target:AWSStepFunctions.DescribeExecution

content-type;host;x-amz-target
e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
DEBUG:botocore.auth:StringToSign:
AWS4-HMAC-SHA256
20171115T191510Z
20171115/us-west-2/states/aws4_request
3afe55bcd073fc24a7dce06bacc3661c000230fd2df13e40fbc4d2d6eb30849b
DEBUG:botocore.auth:Signature:
4bcb1c51cfcbf4274a17af7aa3202f23f6d7ceb314c2e1e1dd9faac1eb110e91
DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): states.us-west-2.amazonaws.com
DEBUG:urllib3.connectionpool:https://states.us-west-2.amazonaws.com:443 "POST /?executionArn=arn%3Aaws%3Astates%3Aus-west-2%123%3Aexecution%3Aabc%def-ghi-jkl-mno&X-Amz-Expires=3600&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-SignedHeaders=content-type%3Bhost%3Bx-amz-target&X-Amz-Credential=ZZZ%2Fus-west-2%2Fstates%2Faws4_request&X-Amz-Date=20171115T191510Z&X-Amz-Signature=4bcb1c51cfcbf4274a17af7aa3202f23f6d7ceb314c2e1e1dd9faac1eb110e91 HTTP/1.1" 403 1030

print(response)

<InvalidSignatureException>
  <Message>The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details.

The Canonical String for this request should have been
'POST
/
X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=ZZZ%2Fus-west-2%2Fstates%2Faws4_request&X-Amz-Date=20171115T191510Z&X-Amz-Expires=3600&X-Amz-SignedHeaders=content-type%3Bhost%3Bx-amz-target&executionArn=arn%3Aaws%3Astates%3Aus-west-2%3123%3Aexecution%3Aabc%3efg-hij-klm-nmo
content-type:
host:states.us-west-2.amazonaws.com
x-amz-target:

content-type;host;x-amz-target
e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'

The String-to-Sign should have been
'AWS4-HMAC-SHA256
20171115T191510Z
20171115/us-west-2/states/aws4_request
1f390ad977de8b8bd1dd0226424bb1389ba62b6bb185784bf499a45b80c7d476'
</Message>
</InvalidSignatureException>

I've had no issues generating presigned urls for retrieving s3 objects doing this:

s3 = client('s3')
s3.generate_presigned_url('get_object', Params={'Bucket': 'my-bucket', 'Key': 'my/file.txt'})


问:
CXF web service ClassCastException on assignment of return type when using WS-Reliable Messaging
I have a WSDL-first web service that is using CXF 2.7.6, using Wrapped-style. The getState web service interface method returns an int value. However, when I call the web service from my CXF client code, I usually get a ClassCastException with the message 'can't cast a GetStateResponse object to an Integer'. I say usually because the ClassCastException does not occur every time I make the web service call. I also intermittently get a similar ClassCastException on calls to other methods in the web service interface. Interestingly, this exception only occurs with WS-Reliable Messaging configured. We are deploying on a JBoss EAP 6 server but are using the CXF libraries directly (rather than using JBoss' built-in webservices subsystem)

I'm able to work-around the issue by assigning the return value to an Object and then determining its type and handling it accordingly, but this is a definite hack and I'd like to find the root cause of the issue. Below are excerpts from the WSDL, schema and interface class.

WSDL excerpts:

```<code><wsdl:definitions>
    <wsdl:message name="getState">
        <wsdl:part name="parameters" element="msgs:getState"/>
    </wsdl:message>

    <wsdl:portType>
        <wsdl:operation name="getState">
            <wsdl:input name="getState" message="tns:getState"/>
            <wsdl:output name="getStateResponse" message="tns:getStateResponse"/>
            <wsdl:fault name="SOAPFaultException" message="tns:SOAPFaultException"/>
        </wsdl:operation>
    </wsdl:portType>

    <wsdl:binding>
        <wsdl:operation name="getState">
            <soap:operation soapAction="" style="document"/>
            <wsdl:input name="getState">
                <soap:body use="literal"/>
            </wsdl:input>
            <wsdl:output name="getStateResponse">
                <soap:body use="literal"/>
            </wsdl:output>
            <wsdl:fault name="SOAPFaultException">
                <soap:fault name="SOAPFaultException" use="literal"/>
            </wsdl:fault>
        </wsdl:operation>
    </wsdl:binding>
</wsdl:definitions>
</code>```

SCHEMA referenced with 'msgs:' prefix above:

```<code><xs:element name="getState" type="tns:getState"/>

<xs:complexType name="getState">
    <xs:sequence>
        <xs:element minOccurs="0" name="param1" type="xs:string" />
        <xs:element minOccurs="0" name="param2" type="xs:string" />
    </xs:sequence>
</xs:complexType>
</code>```

INTERFACE CLASS:

```<code>@WebResult(name = "return", targetNamespace = "")
@RequestWrapper(localName = "getState", targetNamespace = "http://messages.space.my.name", className = "my.name.space.GetState")
@WebMethod
@ResponseWrapper(localName = "getStateResponse", targetNamespace = "http://messages.space.my.name", className = "my.name.space.GetStateResponse")
public int getState(
@WebParam(name = "param1", targetNamespace = "")
java.lang.String param1,
@WebParam(name = "param2", targetNamespace = "")
java.lang.String param2) throws SOAPFaultException;
</code>```

Spring jaxws client configuration:

```<code><jaxws:client id="wsProxy" serviceClass="my.name.space.IWebServiceInterface">
    <jaxws:inInterceptors>
        <bean id="loggingInInterceptor"
              class="org.apache.cxf.interceptor.LoggingInInterceptor" >
            <property name="prettyLogging" value="true" />
        </bean>
        <ref bean="rmLogicalIn"/>
        <ref bean="rmCodec"/>
    </jaxws:inInterceptors>
    <jaxws:outInterceptors>
        <bean id="loggingOutInterceptor"
              class="org.apache.cxf.interceptor.LoggingOutInterceptor" >
            <property name="prettyLogging" value="true" />
        </bean>
        <ref bean="rmLogicalOut"/>
        <ref bean="rmCodec"/>
    </jaxws:outInterceptors>
</jaxws:client>
</code>```

Stack trace:

```<code>[33m [0m [31m00:39:20,589 ERROR [org.apache.catalina.core.ContainerBase.[jboss.web].[default-host].[/TEST_GUI].[jsp]] (ajp-/0.0.0.0:8009-9) JBWEB000236:
Servlet.service() for servlet jsp threw exception: java.lang.ClassCastException: my.name.space.messages.GetStateResponse cannot be cast to java.lang.Integer [0m
[31m    at $Proxy139.getState(Unknown Source)   at org.apache.jsp.client.framework.MWS_005fTEST_jsp.waitForState(MWS_005fTEST_jsp.java:166) [0m
[31m    at org.apache.jsp.client.framework.MWS_005fTEST_jsp._jspService(MWS_005fTEST_jsp.java:508) [0m
[31m    at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:69) [jbossweb-7.4.10.Final-redhat-1.jar:7.4.10.Final-redhat-1] [0m
[31m    at javax.servlet.http.HttpServlet.service(HttpServlet.java:847) [jboss-servlet-api_3.0_spec-1.0.2.Final-redhat-1.jar:1.0.2.Final-redhat-1] [0m
[31m    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:365) [jbossweb-7.4.10.Final-redhat-1.jar:7.4.10.Final-redhat-1] [0m
[31m    at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:309) [jbossweb-7.4.10.Final-redhat-1.jar:7.4.10.Final-redhat-1] [0m
[31m    at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:242) [jbossweb-7.4.10.Final-redhat-1.jar:7.4.10.Final-redhat-1] [0m
[31m    at javax.servlet.http.HttpServlet.service(HttpServlet.java:847) [jboss-servlet-api_3.0_spec-1.0.2.Final-redhat-1.jar:1.0.2.Final-redhat-1] [0m
[31m    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:295) [jbossweb-7.4.10.Final-redhat-1.jar:7.4.10.Final-redhat-1] [0m
[31m    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214) [jbossweb-7.4.10.Final-redhat-1.jar:7.4.10.Final-redhat-1] [0m
[31m    at mil.jpmis.cbrnis.client.framework.SetCharacterEncodingFilter.doFilter(SetCharacterEncodingFilter.java:148) [TESTGUI.jar:] [0m
[31m    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:246) [jbossweb-7.4.10.Final-redhat-1.jar:7.4.10.Final-redhat-1] [0m
[31m    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214) [jbossweb-7.4.10.Final-redhat-1.jar:7.4.10.Final-redhat-1] [0m
[31m    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:231) [jbossweb-7.4.10.Final-redhat-1.jar:7.4.10.Final-redhat-1] [0m
[31m    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:149) [jbossweb-7.4.10.Final-redhat-1.jar:7.4.10.Final-redhat-1] [0m
[31m    at org.jboss.modcluster.container.jbossweb.JBossWebContext$RequestListenerValve.event(JBossWebContext.java:91) [0m
[31m    at org.jboss.modcluster.container.jbossweb.JBossWebContext$RequestListenerValve.invoke(JBossWebContext.java:72) [0m
[31m    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:512) [jbossweb-7.4.10.Final-redhat-1.jar:7.4.10.Final-redhat-1] [0m
[31m    at org.jboss.as.web.security.SecurityContextAssociationValve.invoke(SecurityContextAssociationValve.java:169) [jboss-as-web-7.4.3.Final-redhat-2.jar:7.4.3.Final-redhat-2] [0m
[31m    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:145) [jbossweb-7.4.10.Final-redhat-1.jar:7.4.10.Final-redhat-1] [0m
[31m    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:97) [jbossweb-7.4.10.Final-redhat-1.jar:7.4.10.Final-redhat-1] [0m
[31m    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:102) [jbossweb-7.4.10.Final-redhat-1.jar:7.4.10.Final-redhat-1] [0m
[31m    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:344) [jbossweb-7.4.10.Final-redhat-1.jar:7.4.10.Final-redhat-1] [0m
[31m    at org.apache.coyote.ajp.AjpProcessor.process(AjpProcessor.java:490) [jbossweb-7.4.10.Final-redhat-1.jar:7.4.10.Final-redhat-1] [0m
[31m    at org.apache.coyote.ajp.AjpProtocol$AjpConnectionHandler.process(AjpProtocol.java:420) [jbossweb-7.4.10.Final-redhat-1.jar:7.4.10.Final-redhat-1] [0m
[31m    at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:926) [jbossweb-7.4.10.Final-redhat-1.jar:7.4.10.Final-redhat-1] [0m
[31m    at java.lang.Thread.run(Unknown Source) [rt.jar:1.7.0]
</code>```

I also posted this on the cxf-users Nabble list, but no response yet.  Any help would be appreciated!

答: Update, and to respond to @gnzlrm in the comment above, if I recall correctly (this was over 2 years ago) we never did isolate the cause of this issue, but we did find when we updated to a later version of CXF we no longer saw the issue (I believe 2.7.13 and up worked but we ended up updating to 3.1.7).</p>

Body:
I have a WSDL-first web service that is using CXF 2.7.6, using Wrapped-style. The getState web service interface method returns an int value. However, when I call the web service from my CXF client code, I usually get a ClassCastException with the message 'can't cast a GetStateResponse object to an Integer'. I say usually because the ClassCastException does not occur every time I make the web service call. I also intermittently get a similar ClassCastException on calls to other methods in the web service interface. Interestingly, this exception only occurs with WS-Reliable Messaging configured. We are deploying on a JBoss EAP 6 server but are using the CXF libraries directly (rather than using JBoss' built-in webservices subsystem)

I'm able to work-around the issue by assigning the return value to an Object and then determining its type and handling it accordingly, but this is a definite hack and I'd like to find the root cause of the issue. Below are excerpts from the WSDL, schema and interface class.

WSDL excerpts:

<wsdl:definitions>
    <wsdl:message name="getState">
        <wsdl:part name="parameters" element="msgs:getState"/>
    </wsdl:message>

    <wsdl:portType>
        <wsdl:operation name="getState">
            <wsdl:input name="getState" message="tns:getState"/>
            <wsdl:output name="getStateResponse" message="tns:getStateResponse"/>
            <wsdl:fault name="SOAPFaultException" message="tns:SOAPFaultException"/>
        </wsdl:operation>
    </wsdl:portType>

    <wsdl:binding>
        <wsdl:operation name="getState">
            <soap:operation soapAction="" style="document"/>
            <wsdl:input name="getState">
                <soap:body use="literal"/>
            </wsdl:input>
            <wsdl:output name="getStateResponse">
                <soap:body use="literal"/>
            </wsdl:output>
            <wsdl:fault name="SOAPFaultException">
                <soap:fault name="SOAPFaultException" use="literal"/>
            </wsdl:fault>
        </wsdl:operation>
    </wsdl:binding>
</wsdl:definitions>

SCHEMA referenced with 'msgs:' prefix above:

<xs:element name="getState" type="tns:getState"/>

<xs:complexType name="getState">
    <xs:sequence>
        <xs:element minOccurs="0" name="param1" type="xs:string" />
        <xs:element minOccurs="0" name="param2" type="xs:string" />
    </xs:sequence>
</xs:complexType>

INTERFACE CLASS:

@WebResult(name = "return", targetNamespace = "")
@RequestWrapper(localName = "getState", targetNamespace = "http://messages.space.my.name", className = "my.name.space.GetState")
@WebMethod
@ResponseWrapper(localName = "getStateResponse", targetNamespace = "http://messages.space.my.name", className = "my.name.space.GetStateResponse")
public int getState(
@WebParam(name = "param1", targetNamespace = "")
java.lang.String param1,
@WebParam(name = "param2", targetNamespace = "")
java.lang.String param2) throws SOAPFaultException;

Spring jaxws client configuration:

<jaxws:client id="wsProxy" serviceClass="my.name.space.IWebServiceInterface">
    <jaxws:inInterceptors>
        <bean id="loggingInInterceptor"
              class="org.apache.cxf.interceptor.LoggingInInterceptor" >
            <property name="prettyLogging" value="true" />
        </bean>
        <ref bean="rmLogicalIn"/>
        <ref bean="rmCodec"/>
    </jaxws:inInterceptors>
    <jaxws:outInterceptors>
        <bean id="loggingOutInterceptor"
              class="org.apache.cxf.interceptor.LoggingOutInterceptor" >
            <property name="prettyLogging" value="true" />
        </bean>
        <ref bean="rmLogicalOut"/>
        <ref bean="rmCodec"/>
    </jaxws:outInterceptors>
</jaxws:client>

Stack trace:

[33m [0m [31m00:39:20,589 ERROR [org.apache.catalina.core.ContainerBase.[jboss.web].[default-host].[/TEST_GUI].[jsp]] (ajp-/0.0.0.0:8009-9) JBWEB000236:
Servlet.service() for servlet jsp threw exception: java.lang.ClassCastException: my.name.space.messages.GetStateResponse cannot be cast to java.lang.Integer [0m
[31m    at $Proxy139.getState(Unknown Source)   at org.apache.jsp.client.framework.MWS_005fTEST_jsp.waitForState(MWS_005fTEST_jsp.java:166) [0m
[31m    at org.apache.jsp.client.framework.MWS_005fTEST_jsp._jspService(MWS_005fTEST_jsp.java:508) [0m
[31m    at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:69) [jbossweb-7.4.10.Final-redhat-1.jar:7.4.10.Final-redhat-1] [0m
[31m    at javax.servlet.http.HttpServlet.service(HttpServlet.java:847) [jboss-servlet-api_3.0_spec-1.0.2.Final-redhat-1.jar:1.0.2.Final-redhat-1] [0m
[31m    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:365) [jbossweb-7.4.10.Final-redhat-1.jar:7.4.10.Final-redhat-1] [0m
[31m    at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:309) [jbossweb-7.4.10.Final-redhat-1.jar:7.4.10.Final-redhat-1] [0m
[31m    at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:242) [jbossweb-7.4.10.Final-redhat-1.jar:7.4.10.Final-redhat-1] [0m
[31m    at javax.servlet.http.HttpServlet.service(HttpServlet.java:847) [jboss-servlet-api_3.0_spec-1.0.2.Final-redhat-1.jar:1.0.2.Final-redhat-1] [0m
[31m    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:295) [jbossweb-7.4.10.Final-redhat-1.jar:7.4.10.Final-redhat-1] [0m
[31m    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214) [jbossweb-7.4.10.Final-redhat-1.jar:7.4.10.Final-redhat-1] [0m
[31m    at mil.jpmis.cbrnis.client.framework.SetCharacterEncodingFilter.doFilter(SetCharacterEncodingFilter.java:148) [TESTGUI.jar:] [0m
[31m    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:246) [jbossweb-7.4.10.Final-redhat-1.jar:7.4.10.Final-redhat-1] [0m
[31m    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214) [jbossweb-7.4.10.Final-redhat-1.jar:7.4.10.Final-redhat-1] [0m
[31m    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:231) [jbossweb-7.4.10.Final-redhat-1.jar:7.4.10.Final-redhat-1] [0m
[31m    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:149) [jbossweb-7.4.10.Final-redhat-1.jar:7.4.10.Final-redhat-1] [0m
[31m    at org.jboss.modcluster.container.jbossweb.JBossWebContext$RequestListenerValve.event(JBossWebContext.java:91) [0m
[31m    at org.jboss.modcluster.container.jbossweb.JBossWebContext$RequestListenerValve.invoke(JBossWebContext.java:72) [0m
[31m    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:512) [jbossweb-7.4.10.Final-redhat-1.jar:7.4.10.Final-redhat-1] [0m
[31m    at org.jboss.as.web.security.SecurityContextAssociationValve.invoke(SecurityContextAssociationValve.java:169) [jboss-as-web-7.4.3.Final-redhat-2.jar:7.4.3.Final-redhat-2] [0m
[31m    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:145) [jbossweb-7.4.10.Final-redhat-1.jar:7.4.10.Final-redhat-1] [0m
[31m    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:97) [jbossweb-7.4.10.Final-redhat-1.jar:7.4.10.Final-redhat-1] [0m
[31m    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:102) [jbossweb-7.4.10.Final-redhat-1.jar:7.4.10.Final-redhat-1] [0m
[31m    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:344) [jbossweb-7.4.10.Final-redhat-1.jar:7.4.10.Final-redhat-1] [0m
[31m    at org.apache.coyote.ajp.AjpProcessor.process(AjpProcessor.java:490) [jbossweb-7.4.10.Final-redhat-1.jar:7.4.10.Final-redhat-1] [0m
[31m    at org.apache.coyote.ajp.AjpProtocol$AjpConnectionHandler.process(AjpProtocol.java:420) [jbossweb-7.4.10.Final-redhat-1.jar:7.4.10.Final-redhat-1] [0m
[31m    at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:926) [jbossweb-7.4.10.Final-redhat-1.jar:7.4.10.Final-redhat-1] [0m
[31m    at java.lang.Thread.run(Unknown Source) [rt.jar:1.7.0]

I also posted this on the cxf-users Nabble list, but no response yet.  Any help would be appreciated!


问:
How to implement regex in if statement in dictionaries
I have the following code snippet:
I want to find the row, with the value is digit (they are integers all the time) on the column/key "Something" and delete the matched row. I have tried it with re.compile()

```<code>for row in list:
    if re.compile("\d") in row["Something"]:
        print(row)
        del (row)
</code>```

How is the right implementation in this case?

答:
Rather than deleting your row, you might want to match those which do not contain digits:

```<code>import re
rx = re.compile(r'^\D+$')

new_rows = (row for row in lst if rx.match(row))
</code>```

This yields a generator which you could either iterate over or convert it to a list entirely.

Additionally, using list as a variable name is a no-no.

Body:
I have the following code snippet:
I want to find the row, with the value is digit (they are integers all the time) on the column/key "Something" and delete the matched row. I have tried it with re.compile()

for row in list:
    if re.compile("\d") in row["Something"]:
        print(row)
        del (row)

How is the right implementation in this case?

Body:
Rather than deleting your row, you might want to match those which do not contain digits:

import re
rx = re.compile(r'^\D+$')

new_rows = (row for row in lst if rx.match(row))

This yields a generator which you could either iterate over or convert it to a list entirely.

Additionally, using list as a variable name is a no-no.


问:
How to increment an Integer variable by X without creating a new object instance
How can I increment an Integer variable by X without creating a new object instance?

+= does not work because:

```<code>ree-1.8.7-2010.02 > x = 1
1
ree-1.8.7-2010.02 > x.object_id
3
ree-1.8.7-2010.02 > x += 1
2
ree-1.8.7-2010.02 > x.object_id
5
</code>```

答:
Execution time is really terrible even if just you organize a simple loop. Primitives shouldn't be ditched from Ruby.

```<code>(1..16000).each do
  (1..16000).each do
  end
end
</code>```

This itself takes 30-40 seconds to complete (Lenovo T400, Virtualboxed Ubuntu), and you haven't even done something sophisticated.

Body:
How can I increment an Integer variable by X without creating a new object instance?

+= does not work because:

ree-1.8.7-2010.02 > x = 1
1
ree-1.8.7-2010.02 > x.object_id
3
ree-1.8.7-2010.02 > x += 1
2
ree-1.8.7-2010.02 > x.object_id
5

Body:
Execution time is really terrible even if just you organize a simple loop. Primitives shouldn't be ditched from Ruby.

(1..16000).each do
  (1..16000).each do
  end
end

This itself takes 30-40 seconds to complete (Lenovo T400, Virtualboxed Ubuntu), and you haven't even done something sophisticated.


问:
MODX Revo tvFilter with getResources and/or pdoResources
I have a checkbox-TV:
City 1||City 2||City 3||City 4

With getResources and pdpResources tvFilter wont't work. Only if I check
only on of the "Citys". If I check 2 or more nothing worked.

```<code>&tvFilters=`art.start-city==yes%,art.city==%City 2%`
</code>```

Any Ideas?

答:
I think, that your problem is in &tvFilters value. I had similar problem and solved it by adding % to the value.
Try this:</p>

```<code>&tvFilters=`art.start-city==%yes%,art.city==%City 2%`
</code>```

Body:
I have a checkbox-TV:
City 1||City 2||City 3||City 4

With getResources and pdpResources tvFilter wont't work. Only if I check
only on of the "Citys". If I check 2 or more nothing worked.

&tvFilters=`art.start-city==yes%,art.city==%City 2%`

Any Ideas?

Body:
I think, that your problem is in &tvFilters value. I had similar problem and solved it by adding % to the value.
Try this:

&tvFilters=`art.start-city==%yes%,art.city==%City 2%`


问:
Perl use of array vs file
Which of the following is a better way to write the code, considering impact on performance/time taken etc -
(Following is a pseudo code, please ignore syntax issues. Idea here is to understand under what circumstances to use an array vs a file )
Case 1::

```<code>@array; # globally accessible
sub 1 {
    #some operations on @array
}
.
.
.
sub 2 {
    #print @array info
}
</code>```

Case 2 :: #instead of using array, use file

```<code> sub 1 {
   #open file1
    #write to file1
    #close file
}
.
.
.
sub 2 {
    #open file1
    #read file1
    #print file1 info
    #close file1
}
</code>```

答:
It depends on what you are going to do inside those subs

The first example never makes sense in the given form ( wroten some operation on the array! you need to be specific).

If you are processing stuff sequentially, from beginning to end, it makes sense to use the file iterator instead of slurping it into memory, as by that way, you will not use as much system memory and perls buffering will handle the reading from the file in a relatively efficient manner.

You should always process files line by line unless you can't otherwise avoid it.

As soon as you need to go back and forth between lines, and jump backwards in the files, then the first approach of reading the whole file into memory makes the algorithm much easier to write (at the cost of some system memory).

If system memory is scarce and you are able to trade a bit of time against memory, take a look at Tie::File, which lets you access a file on disk just like an array in memory.

Title: Perl use of array vs file

Body:
Which of the following is a better way to write the code, considering impact on performance/time taken etc -
(Following is a pseudo code, please ignore syntax issues. Idea here is to understand under what circumstances to use an array vs a file )
Case 1::

@array; # globally accessible
sub 1 {
    #some operations on @array
}
.
.
.
sub 2 {
    #print @array info
}

Case 2 :: #instead of using array, use file

 sub 1 {
   #open file1
    #write to file1
    #close file
}
.
.
.
sub 2 {
    #open file1
    #read file1
    #print file1 info
    #close file1
}


问:
Add custom ID to Wordpress Audio Player Play Button?
I have a page with several players on it and a click event setup in Google Tag Manager.  That said the play button that is clicked has no class or id for the tracking to label it with.  I need to give each players play button a unique class or ID that when clicked has something to pass to GTM.

Basically when the player shows on my site it comes in as:

```<code><button type="button" aria-controls="mep_0" title="Play" aria-label="Play"></button>
</code>```

And I would like it to be:

```<code><button type="button" aria-controls="mep_0" title="Play" aria-label="Play" id="audio title or some unique identifier"></button>
</code>```

Thank you all in advance.

答:
I was researching this very issue and came up with a solution. Its a bit hacky but it does work for my needs.

it requires a hack to wpincludes/mediaelements/mediaelement-and-player.min.js (I plan an creating a plugin to to do this at some point...)

Find the section for the play button  add a new id and class to the button. The id is grabbed by google tag manager and the class is updated with the post title.

```<code>('<div class="mejs-button mejs-playpause-button mejs-play" ><button id="perplay" class="playername" type="button" aria-controls="'+g.id+'" title="'+h.playText+'" aria-label="'+h.playText+'"></button></div>').
</code>```

In each wordpress theme content page (content.php, content-single.php, content-front.php, etc)

Find the audio/video section

```<code><div class="entry-content video">

<!-- Underneath it add the following code -->

<!-- hack to add podcast name (post title) to the player button class -->
    <?php $x = get_the_title(); // gets post title ?>
    <script>
        <!-- js to find element with class name of playername and append the class name with the post title -->
        document.addEventListener('DOMContentLoaded', function() {
         document.getElementsByClassName('playername')[0].className = " <?php  echo $x; ?>";
})
</script>
</code>```

in my case I was then able to get the element.css value in Google tag manager and use that to track what audio file was played and on which page it was played on.

If you need to track more than one audio file per post you could probably get the media id and use that instead of the post title - tho in GA you would need a lookup table if you have a lot of IDs.

Body:
I have a page with several players on it and a click event setup in Google Tag Manager.  That said the play button that is clicked has no class or id for the tracking to label it with.  I need to give each players play button a unique class or ID that when clicked has something to pass to GTM.

Basically when the player shows on my site it comes in as:

<button type="button" aria-controls="mep_0" title="Play" aria-label="Play"></button>

And I would like it to be:

<button type="button" aria-controls="mep_0" title="Play" aria-label="Play" id="audio title or some unique identifier"></button>

Thank you all in advance.

Body:
I was researching this very issue and came up with a solution. Its a bit hacky but it does work for my needs.

it requires a hack to wpincludes/mediaelements/mediaelement-and-player.min.js (I plan an creating a plugin to to do this at some point...)

Find the section for the play button  add a new id and class to the button. The id is grabbed by google tag manager and the class is updated with the post title.

('<div class="mejs-button mejs-playpause-button mejs-play" ><button id="perplay" class="playername" type="button" aria-controls="'+g.id+'" title="'+h.playText+'" aria-label="'+h.playText+'"></button></div>').

In each wordpress theme content page (content.php, content-single.php, content-front.php, etc)

Find the audio/video section

<div class="entry-content video">

<!-- Underneath it add the following code -->

<!-- hack to add podcast name (post title) to the player button class -->
    <?php $x = get_the_title(); // gets post title ?>
    <script>
        <!-- js to find element with class name of playername and append the class name with the post title -->
        document.addEventListener('DOMContentLoaded', function() {
         document.getElementsByClassName('playername')[0].className = " <?php  echo $x; ?>";
})
</script>

in my case I was then able to get the element.css value in Google tag manager and use that to track what audio file was played and on which page it was played on.

If you need to track more than one audio file per post you could probably get the media id and use that instead of the post title - tho in GA you would need a lookup table if you have a lot of IDs.


问:
powershell equivalent of linux "mkdir -p"?
How can I get the powershell "mkdir" command to act exactly like Linux's mkdir -p command?

Under Linux, mkdir -p will create nested directories, but only if they don't exist already.  For example, suppose you have a directory /foo that you have write permissions for. mkdir -p /foo/bar/baz creates bar and baz within bar under existing /foo. You run the same command over again, you will not get an error, but nothing will be created.

答:
```<code>New-Item -Path "c:\some\folder\path" -ItemType Directory
</code>```


问:
Behind the scenes activity on python prompt load-up
What happens behind the scenes when we invoke the python prompt?

I am more interested in understanding how do the methods/functions like print, import and the likes load up in the interpreter?

EDIT: Some clarification on my question:

When we type python on our unix prompt/windows console and Hit enter, what are the libraries that get loaded. My specific interest is as to how the keywords like print and import are made available to the user.

答:
There are too many levels to that question. Here's a very rough sketch.

There's the whole C-level interpreter initialization, a bunch of in-the-interpreter tasks, reading the environment and options, customization of the interpreter session. All that defines what you see when you run python.

I know there's a good description of the whole process somewhere.


问:
SQL - Dateadd on working hours only?
I wonder if anyone could help?

I have a table that has the following columns

```<code>creationdate (datetime)
SLAhours (int)
</code>```

I want to create a column called completebydate which would be a dateadd function adding on the SLA hours to the creation date. However I only want it to count 9am to 5pm on the creation date table.

For example, if an SLAhour value is 9, and the create datetime is '01 sep 2017 12:30' then the completebydate would be '02 sep 2017 13:30" instead of '01 sep 2017 21:30'

Does this make sense? Is this easily doable?

答:
There are many different ways of implementing this, anywhere from writing it out in a view, to a udf, to a trigger. You might need to provide more context around the situation for someone to advise on which one is best for you.

Regardless of how you do it, the logic could look like this:

```<code>declare @example table
    (
        creationdate datetime
        , slahours int
    )

insert into @example
values ('2017-09-01 12:30', 9)
    , ('2017-09-01 16:00', 12)

declare @hrs_in_day int = 8
    , @end_time time = '17:00'

select b.creationdate
, b.slahours
, dateadd(hh, b.hr_cnt, dateadd(d, b.day_cnt, b.creationdate)) as completebydate
from (
    select a.creationdate
    , a.slahours
    , a.day_cnt + case when a.hr_cnt > a.first_day_remaining_hours then 1 else 0 end as day_cnt
    , a.hr_cnt + case when a.hr_cnt > a.first_day_remaining_hours then -1 * @hrs_in_day else 0 end as hr_cnt
    from (
        select e.creationdate
        , e.slahours
        , datediff(mi, cast(e.creationdate as time), @end_time) / 60.0 as first_day_remaining_hours
        , floor(e.slahours / @hrs_in_day) as day_cnt
        , e.slahours - (floor(e.slahours / @hrs_in_day) * @hrs_in_day) as hr_cnt
        from @example as e
        ) as a
    ) as b
</code>```

The first sub-query is not necessary, just makes the code easier to understand.

Output:

```<code>creationdate             slahours   completebydate
2017-09-01 12:30:00.000     9       2017-09-02 13:30:00.000
2017-09-01 16:00:00.000     12      2017-09-03 12:00:00.000
</code>```

As far as the weekend/holiday issue, that might warrant a separate question, but I would also take a look at existing questions around the same concept.

Title: SQL - Dateadd on working hours only?

Body:
I wonder if anyone could help?

I have a table that has the following columns

creationdate (datetime)
SLAhours (int)

I want to create a column called completebydate which would be a dateadd function adding on the SLA hours to the creation date. However I only want it to count 9am to 5pm on the creation date table.

For example, if an SLAhour value is 9, and the create datetime is '01 sep 2017 12:30' then the completebydate would be '02 sep 2017 13:30" instead of '01 sep 2017 21:30'

Does this make sense? Is this easily doable?

Body:
There are many different ways of implementing this, anywhere from writing it out in a view, to a udf, to a trigger. You might need to provide more context around the situation for someone to advise on which one is best for you.

Regardless of how you do it, the logic could look like this:

declare @example table
    (
        creationdate datetime
        , slahours int
    )

insert into @example
values ('2017-09-01 12:30', 9)
    , ('2017-09-01 16:00', 12)

declare @hrs_in_day int = 8
    , @end_time time = '17:00'

select b.creationdate
, b.slahours
, dateadd(hh, b.hr_cnt, dateadd(d, b.day_cnt, b.creationdate)) as completebydate
from (
    select a.creationdate
    , a.slahours
    , a.day_cnt + case when a.hr_cnt > a.first_day_remaining_hours then 1 else 0 end as day_cnt
    , a.hr_cnt + case when a.hr_cnt > a.first_day_remaining_hours then -1 * @hrs_in_day else 0 end as hr_cnt
    from (
        select e.creationdate
        , e.slahours
        , datediff(mi, cast(e.creationdate as time), @end_time) / 60.0 as first_day_remaining_hours
        , floor(e.slahours / @hrs_in_day) as day_cnt
        , e.slahours - (floor(e.slahours / @hrs_in_day) * @hrs_in_day) as hr_cnt
        from @example as e
        ) as a
    ) as b

The first sub-query is not necessary, just makes the code easier to understand.

Output:

creationdate             slahours   completebydate
2017-09-01 12:30:00.000     9       2017-09-02 13:30:00.000
2017-09-01 16:00:00.000     12      2017-09-03 12:00:00.000

As far as the weekend/holiday issue, that might warrant a separate question, but I would also take a look at existing questions around the same concept.


问:
The vocabulary of first class functions
When people say that Python, for instance, has first class functions, it makes it sound like Python also has second class functions. However, I've never yet (knowingly) encountered a second class function in Python. When we say this, does it really mean "All Python functions are first class?" Or is there an example of a second class function in Python? </p>

答:
Usually, when we say "language X has first-class functions", we actually mean that "language X treats functions as first-class" (just like it does with other types). It usually means that you can pass functions as arguments, store them in arrays, etc.

I don't see any reason why a particular language (that treated functions as first-class) would also have second-class functions (i.e. those that couldn't be passed as arguments), but can't say whether Python does or doesn't.

Title: The vocabulary of first class functions