问:
RSpec 2.3 + Devise 1.0.11
I've got a really old Rails 2.3.18, ruby 1.9.3, rspec 1.x application which we are upgrading and it had restful-authentication in it. So I've replaced that with Devise 1.0.11.

I can login to the application, but my tests will not run;

Here is the test in question

```<code>require 'spec_helper'

describe CategoriesController do
  context "As a logged in user" do
    before do
      login_user
      current_firm = mock_model(Firm, :id => 1)
      controller.stub!(:current_firm).and_return(current_firm)
    end

    describe "#index" do
      it "should render index" do
        get :index
        response.should render_template('index')
      end
    end

  end
end
</code>```

Here is the error I get;

```<code>NoMethodError in 'CategoriesController As a logged in user#index should render index'
You have a nil object when you didn't expect it!
You might have expected an instance of ActiveRecord::Base.
The error occurred while evaluating nil.[]=
/home/map7/code/pdfcat/spec/spec_helper.rb:18:in `login_user'
spec/controllers/categories_controller_spec.rb:6:in `block (3 levels) in <top (required)>'
</code>```

The error happens on this line;

```<code>[20, 29] in /usr/local/rbenv/versions/1.9.3-p551/lib/ruby/gems/1.9.1/gems/warden-0.10.7/lib/warden/session_serializer.rb
   20        key
   21      end
   22
   23      def store(user, scope)
   24        return unless user
=> 25        session[key_for(scope)] = serialize(user)
   26      end
</code>```

The problem is 'session' is nil when I'm at this point.

I've pushed the full code to here: https://github.com/map7/pdfcat/tree/devise

My plan was to get devise working in the tests then I could jump to Rails 3.0 and continue the upgrade.

答:
There's an old message in google groups that I think is relevant: https://groups.google.com/forum/#!topic/rspec/4AHuPtHFD34

It recommends using this:

```<code>before do
  request.env['warden'].stub(:authenticate!) { double(User) }
end
</code>```

I'd probably put it in rails_helper.rb so that it runs for all tests

Title: RSpec 2.3 + Devise 1.0.11

Body:
I've got a really old Rails 2.3.18, ruby 1.9.3, rspec 1.x application which we are upgrading and it had restful-authentication in it. So I've replaced that with Devise 1.0.11.

I can login to the application, but my tests will not run;

Here is the test in question

require 'spec_helper'

describe CategoriesController do
  context "As a logged in user" do
    before do
      login_user
      current_firm = mock_model(Firm, :id => 1)
      controller.stub!(:current_firm).and_return(current_firm)
    end

    describe "#index" do
      it "should render index" do
        get :index
        response.should render_template('index')
      end
    end

  end
end

Here is the error I get;

NoMethodError in 'CategoriesController As a logged in user#index should render index'
You have a nil object when you didn't expect it!
You might have expected an instance of ActiveRecord::Base.
The error occurred while evaluating nil.[]=
/home/map7/code/pdfcat/spec/spec_helper.rb:18:in `login_user'
spec/controllers/categories_controller_spec.rb:6:in `block (3 levels) in <top (required)>'

The error happens on this line;

[20, 29] in /usr/local/rbenv/versions/1.9.3-p551/lib/ruby/gems/1.9.1/gems/warden-0.10.7/lib/warden/session_serializer.rb
   20        key
   21      end
   22
   23      def store(user, scope)
   24        return unless user
=> 25        session[key_for(scope)] = serialize(user)
   26      end

The problem is 'session' is nil when I'm at this point.

I've pushed the full code to here: https://github.com/map7/pdfcat/tree/devise

My plan was to get devise working in the tests then I could jump to Rails 3.0 and continue the upgrade.

Body:
There's an old message in google groups that I think is relevant: https://groups.google.com/forum/#!topic/rspec/4AHuPtHFD34

It recommends using this:

before do
  request.env['warden'].stub(:authenticate!) { double(User) }
end

I'd probably put it in rails_helper.rb so that it runs for all tests


来源: stackexchange

问:
what is the shell script command to checkout a project from github
I'm running a Jenkins job on a GitHub project (Project A), as part of this job I want to checkout another different GitHub project (Project B) using shell script command

答:
If you really want to use a shell command for that you could go for

$ git clone https://<YOUR_REPOSITORY_URL>.

However, if you are using a Jenkins pipeline job you might consider using following command in your Jenkinsfile:

```<code>stage('Checkout') {
   git branch: '<BRANCH_NAME>', credentialsId: '<JENKINS_CREDENTIAL_ID>', url: 'git@<URL_OF_REPOSITORY>'
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
If you really want to use a shell command for that you could go for

$ git clone https://<YOUR_REPOSITORY_URL>.

However, if you are using a Jenkins pipeline job you might consider using following command in your Jenkinsfile:

stage('Checkout') {
   git branch: '<BRANCH_NAME>', credentialsId: '<JENKINS_CREDENTIAL_ID>', url: 'git@<URL_OF_REPOSITORY>'
}


问:
Why only the first column has values when assign values to a matrix in a nested loop?
I create a matrix, and I want to assign 3 to every entry of this matrix by a nested for loop.

```<code>   N=5
   be<- matrix(rep(NA, 5*N), ncol = N)
    for (j in 1:5){
      for (i in 1:N) {
        be[j][i]<-3
      }}
</code>```

The result is:

```<code>> be
     [,1] [,2] [,3] [,4] [,5]
[1,]    3   NA   NA   NA   NA
[2,]    3   NA   NA   NA   NA
[3,]    3   NA   NA   NA   NA
[4,]    3   NA   NA   NA   NA
[5,]    3   NA   NA   NA   NA
</code>```

Also there are 20 identical warnings like:

```<code>In be[j] <- `*vtmp*` :
  number of items to replace is not a multiple of replacement length
</code>```

I expected the result being:

```<code>> be
      [,1] [,2] [,3] [,4] [,5]
    [1,]    3   3   3   3   3
    [2,]    3   3   3   3   3
    [3,]    3   3   3   3   3
    [4,]    3   3   3   3   3
    [5,]    3   3   3   3   3
</code>```

Why is that and how can I fix my codes?

答:
Is the problem you're actually trying to solve more complicated? Otherwise there is no need to do this in a nested for loop.</p>

```<code>N=5
be<- matrix(rep(NA, 5*N), ncol = N)
be[] <- 3
be
     [,1] [,2] [,3] [,4] [,5]
[1,]    3    3    3    3    3
[2,]    3    3    3    3    3
[3,]    3    3    3    3    3
[4,]    3    3    3    3    3
[5,]    3    3    3    3    3
</code>```

Body:
I create a matrix, and I want to assign 3 to every entry of this matrix by a nested for loop.

   N=5
   be<- matrix(rep(NA, 5*N), ncol = N)
    for (j in 1:5){
      for (i in 1:N) {
        be[j][i]<-3
      }}

The result is:

> be
     [,1] [,2] [,3] [,4] [,5]
[1,]    3   NA   NA   NA   NA
[2,]    3   NA   NA   NA   NA
[3,]    3   NA   NA   NA   NA
[4,]    3   NA   NA   NA   NA
[5,]    3   NA   NA   NA   NA

Also there are 20 identical warnings like:

In be[j] <- `*vtmp*` :
  number of items to replace is not a multiple of replacement length

I expected the result being:

> be
      [,1] [,2] [,3] [,4] [,5]
    [1,]    3   3   3   3   3
    [2,]    3   3   3   3   3
    [3,]    3   3   3   3   3
    [4,]    3   3   3   3   3
    [5,]    3   3   3   3   3

Why is that and how can I fix my codes?

Body:
Is the problem you're actually trying to solve more complicated? Otherwise there is no need to do this in a nested for loop.

N=5
be<- matrix(rep(NA, 5*N), ncol = N)
be[] <- 3
be
     [,1] [,2] [,3] [,4] [,5]
[1,]    3    3    3    3    3
[2,]    3    3    3    3    3
[3,]    3    3    3    3    3
[4,]    3    3    3    3    3
[5,]    3    3    3    3    3


问:
Duplicate interface definition when mixing Objective-C files in projects in XCode
I have a situation where I have one XCode project, and I have another project that shares most of the code with it, with some small differences. So in the project, most of the files are just references to the files from the original project, and anywhere I need to make differences, I copy the file and change the copy. This is useful because for the files that are shared, any changes made in one project will automatically be reflected in the other. This has worked fine for the most part.

Now I am running into a problem where I need to make a change in a header file that is included among a lot of files. Call this file "shared.h". So I do the same thing I did before, delete the reference and copy the file over and change it.

But now the problem is that when I compile, I get hundreds of "duplicate interface declaration" errors from files that include this header. I understand perfectly why, but I just can't think of a way to fix it.

The reason is that suppose you have a file that includes headers from both the original project and the new project. In the files that are references to the original project, when you do #import "shared.h", they will import the file from the directory of the original project; and in the files that are copied into the new project, when you do #import "shared.h", they will import the file from the directory of the new project. So the classes that are defined in the header will be imported twice into the two different files, hence you get a duplicate interface definition. Objective-C's #import will include once per file, but since these are two different files, it will still include both of them.

I thought that the header that is actually listed in my project will take precedence over all else (at least I want it to do that), but it appears that putting headers into the project don't actually affect building of code at all. So now I am lost.

The only solution I can think of at this point is to duplicate all the code in the original project and move it over, to completely separate the projects. But that is terrible.

答:
Hmm, I actual think this is more of a problem with project management. I think linking in code from another project like this sounds really fragile. I.e. if project A is the original project and project B links in some of it's code, changes to project A may break project B without project B having any ability to restrict or control the influence of those changes.

I'd consider compiling the first project as a static library or framework and giving it a version number. Then the second project can import the library. Overrides should not be handled by effectively manipulating the class path. I've seen that done in Java and it's always an absolute last resort to work around bad code. Instead you should be making use of Objective C's abilities - inheritance, categories, etc to add or extend the functionality.

If you have versioned the first project (i.e. /v0.0.1/headers) then project B can keep using v0.0.1 of A until you are read to upgrade to v0.0.2. Then you can re-import A's static library, update a build path or whatever to point B at the new version you want to code against.

In summary, I would not recommend your technique of project management at all and suggest strongly that you rethink it.

ContentLicense: CC BY-SA 2.5


问:
OrderBy in SQL Server with custom "max" integer
I have table in SQL Server which contains a sort column of integers. All values in the column are positive. I want to sort the table such that I chose a "max" value (like 3) and all values are returned decreasing relative to 3. The "descending" order doesn't actually matter much as long as each item in the database is listed.

Database example:

```<code>Value SortColumn
A     1
B     5
C     4
D     3
E     0
F     2
</code>```

Desired output (with 3 as "max"):

```<code>Value SortColumn
D        3
C        4
B        5
E        0
A        1
F        2
</code>```

It seems that this similar post might be in the right direction, but it's not quite what I want....

答:
You want to sort numbers greater than 3 ascending and then numbers less than 3 ascending.  So do this:</p>

```<code>SELECT
   -- blah
ORDER BY CASE WHEN SortColumn >= 3 THEN 1 ELSE 0 DESC, SortColumn ASC
</code>```

Body:
I have table in SQL Server which contains a sort column of integers. All values in the column are positive. I want to sort the table such that I chose a "max" value (like 3) and all values are returned decreasing relative to 3. The "descending" order doesn't actually matter much as long as each item in the database is listed.

Database example:

Value SortColumn
A     1
B     5
C     4
D     3
E     0
F     2

Desired output (with 3 as "max"):

Value SortColumn
D        3
C        4
B        5
E        0
A        1
F        2

It seems that this similar post might be in the right direction, but it's not quite what I want....

Body:
You want to sort numbers greater than 3 ascending and then numbers less than 3 ascending.  So do this:

SELECT
   -- blah
ORDER BY CASE WHEN SortColumn >= 3 THEN 1 ELSE 0 DESC, SortColumn ASC


问:
Allign image and text
I have text "Helloooooooooooooooo" at the bottom of the image but the image should be in the center of text.

Expected output:

```<code>            IMG
Hellooooooooooooooooooooooooooo
</code>```

Currently wrong output:

```<code>IMG
Helloooooooooooooooooooooooooooooo
</code>```

What can I try?

  Hellooooooooooooooooooooooooooooooooooooooooooooo.

```

答:
You can set the img to display: block, then set margin: auto.

```<code>img { display: block; margin: auto; }
</code>```

Title: Allign image and text

Body:
I have text "Helloooooooooooooooo" at the bottom of the image but the image should be in the center of text.

Expected output:

            IMG
Hellooooooooooooooooooooooooooo

Currently wrong output:

IMG
Helloooooooooooooooooooooooooooooo

What can I try?

  Hellooooooooooooooooooooooooooooooooooooooooooooo.

Body:
You can set the img to display: block, then set margin: auto.

img { display: block; margin: auto; }


问:
Excel Forecast with occasional random numbers [Capacity Planning]
I'm currently working on a capacity plan and forecasting for future growth. As we get larger and acquire more customers, we'll eventually stall out and our numbers will start to slow. I'd like to figure a way to add random numbers into my forecast, that'll show a "decrease"

Example:

2008: 20
2009: 32
2010: 45
2011: 49
2012: 52
2013: 60
2014: 72
2015: 88
2016: 102
2017: 113
2018: 142
2019: 130
2020: 127

etc, etc - hope this all makes sense.

答:
Statistical software like R would me much more suited for this.  Ideally, as a business, you will continue acquiring more customers at a steady rate, but the relative percentages of customer acquisitions will level off.

I will explain the Excel I made for you.  For the years 2008-2017, we have data which you gave me.  I use that data to calculate the 2-year moving average and 2-year moving standard deviation over and over again.  These values are not all that useful, except for in the calculation of the random numbers we are looking for.

In 2018, we generate random numbers on a Gaussian distribution using the past-2-year moving average and past-2-year standard deviation. This generates completely random numbers, and generally come out to be somewhat interesting.  These numbers are recalculated every time you edit a formula, which is neat (double click any cell, press enter, watch the numbers move).  I also included a graph of the expected growth over time.  It is a fun tool to play with, if I do say so myself.  I included a screenshot here:

For those of you who like statistics, the function I used was =NORMINV(RAND(),mean,stddev).  This creates a Gaussian distribution around some mean value and stddev.  It is quite interesting, and has the nice effect of "leveling off" most of the time in calculations, which is perfect for this application.

The only problem is, I have no idea how to get this small file to you.  Someone please comment back to let me know how so I can help this poor soul out.


问:
setInterval not working (Javascript)
I'm trying to use setInterval in Javascript to redraw the canvas periodically. However, when I call the setInterval function, the function I pass to it only runs once. Here is a simplified version of my code:

```<code><canvas id="myCanvas" width="400" height="400">
</canvas>
<script type="text/javascript">

function makeBoard()
{
    this.board=[["O", " ", " "], [" ", " ", " "], [" ", "X", " "]];
}

var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var ticTacToeBoard=new makeBoard();

var drawCanvas = new Function("printBoard", "");

drawCanvas = function(printBoard)
{
    alert("Calling draw function.");
    // drawing code
}

setInterval(drawCanvas(ticTacToeBoard), 10);
</script>
</code>```

I've tested this on Firefox 54.0.1 and on Google Chrome Version 59.0. Why is this not working and how can I get my code to redraw the canvas periodically?

答:
You should pass a function definition to the setInterval method, not the result of a function call.

```<code>setInterval(function() {
  // Do something
}, 1000);
</code>```

For your case,

```<code>setInterval(function() {
  drawCanvas(ticTacToeBoard);
}, 10);
</code>```

Title: setInterval not working (Javascript)

Body:
I'm trying to use setInterval in Javascript to redraw the canvas periodically. However, when I call the setInterval function, the function I pass to it only runs once. Here is a simplified version of my code:

<canvas id="myCanvas" width="400" height="400">
</canvas>

I've tested this on Firefox 54.0.1 and on Google Chrome Version 59.0. Why is this not working and how can I get my code to redraw the canvas periodically?

Body:
You should pass a function definition to the setInterval method, not the result of a function call.

setInterval(function() {
  // Do something
}, 1000);

For your case,

setInterval(function() {
  drawCanvas(ticTacToeBoard);
}, 10);


问:
Javascript setTimeout while loading from XML into Google Maps
I have been struggling with this code for quite some time.
I am loading an XML into Google Maps and Geocoding addresses from the XML.
I need to add a delay to the code when there are too many addresses to look up at once.

Here is my entire code for doing this

I need to have it load from the xml file with a delay, as it is it loads it all at once and the Geocoder can not handle that many requests when the XML is large. The XML file is changing continuously so it needs to be reloaded and re-Geocoded. It only becomes a problem when the XML file becomes larger, which is when I need it to work the most.

I have placed the delay around geocoder.getLocations(address,createMarker); but the address variable contains all the addresses so it does not delay it.  If i only place the delay around var address = markers[i].getAttribute("address"); it does not pass the i variable to the function. Any help anyone can give would be greatly appreciated.

```<code>    // create marker
    function createMarker(response)
    {
        var place = response.Placemark[0];
        var point = new GLatLng(place.Point.coordinates[1],
                                    place.Point.coordinates[0]);
        var marker = new GMarker(point);
        GEvent.addListener(marker, "click",function()
            {
                marker.openInfoWindowHtml(place.address);
            });
            map.addOverlay(marker);
    }

      // Create new map object
       var map = new GMap2(document.getElementById("map"));
       map.addControl(new GSmallMapControl());
       map.addControl(new GMapTypeControl());
       map.enableScrollWheelZoom();
       map.addMapType(G_PHYSICAL_MAP);
       map.setCenter(new GLatLng(49.923068,-119.437981), 10);
       var geocoder = new GClientGeocoder();

     // Download the data in active.xml
    GDownloadUrl("active.xml", function(data)
    {

        var xml = GXml.parse(data);
        var markers = xml.documentElement.getElementsByTagName('INC');
        setTimeout( function()
            {
    for (var i = 0; i < markers.length; i++)
        {
        var address = markers[i].getAttribute("address");
                    geocoder.getLocations(address,createMarker);
                }
            },200);
    });
</code>```

答:
Try:

```<code>for (var i = 0; i < markers.length; i++) {
  var address = markers[i].getAttribute("address");
  function (innerAddress, j) {
      setTimeout(function() {
        geocoder.getLocations(innerAddress,createMarker);
      }, 200 * j);
  }(address, i);
}
</code>```

This should space out your requests to the geocoder.

Body:
I have been struggling with this code for quite some time.
I am loading an XML into Google Maps and Geocoding addresses from the XML.
I need to add a delay to the code when there are too many addresses to look up at once.

Here is my entire code for doing this

I need to have it load from the xml file with a delay, as it is it loads it all at once and the Geocoder can not handle that many requests when the XML is large. The XML file is changing continuously so it needs to be reloaded and re-Geocoded. It only becomes a problem when the XML file becomes larger, which is when I need it to work the most.

I have placed the delay around geocoder.getLocations(address,createMarker); but the address variable contains all the addresses so it does not delay it.  If i only place the delay around var address = markers[i].getAttribute("address"); it does not pass the i variable to the function. Any help anyone can give would be greatly appreciated.

    // create marker
    function createMarker(response)
    {
        var place = response.Placemark[0];
        var point = new GLatLng(place.Point.coordinates[1],
                                    place.Point.coordinates[0]);
        var marker = new GMarker(point);
        GEvent.addListener(marker, "click",function()
            {
                marker.openInfoWindowHtml(place.address);
            });
            map.addOverlay(marker);
    }

      // Create new map object
       var map = new GMap2(document.getElementById("map"));
       map.addControl(new GSmallMapControl());
       map.addControl(new GMapTypeControl());
       map.enableScrollWheelZoom();
       map.addMapType(G_PHYSICAL_MAP);
       map.setCenter(new GLatLng(49.923068,-119.437981), 10);
       var geocoder = new GClientGeocoder();

     // Download the data in active.xml
    GDownloadUrl("active.xml", function(data)
    {

        var xml = GXml.parse(data);
        var markers = xml.documentElement.getElementsByTagName('INC');
        setTimeout( function()
            {
    for (var i = 0; i < markers.length; i++)
        {
        var address = markers[i].getAttribute("address");
                    geocoder.getLocations(address,createMarker);
                }
            },200);
    });

Body:
Try:

for (var i = 0; i < markers.length; i++) {
  var address = markers[i].getAttribute("address");
  function (innerAddress, j) {
      setTimeout(function() {
        geocoder.getLocations(innerAddress,createMarker);
      }, 200 * j);
  }(address, i);
}

This should space out your requests to the geocoder.


问:
Conditionally declare directive in Angular 2 ngModule
In Angular 2 I would like to declare a directive inside my ngModule only if a global javascript variable is set to true (debug boolean).

This was working when compiling with tsc:

```<code>declare let isDebug: boolean;
let dependencyArray : any[] = [];

if ('undefined' !== typeof isDebug && isDebug) {
  dependencyArray.push(DebugDirective);
}

@NgModule({
  declarations: [AppComponent].concat(dependencyArray),
  imports: []
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {}
</code>```

However it seems than the ngc compiler (AOT compilation) does not accept function call in module files. The following error is thrown by ngc.

Error encountered resolving symbol values statically. Function calls are not supported. Consider replacing the function or lambda with a reference to an exported function

I have found the various threads explaining how to use a factory with an exported function for providers (e.g. https://github.com/angular/angular/issues/11262) but I have not found how to do the same for the declaration array.

How can I solve the issue for the module declaration?

答: How about exporting a function (returning an any[]) and the declaration directive pointing to the function reference.</p>

Body:
In Angular 2 I would like to declare a directive inside my ngModule only if a global javascript variable is set to true (debug boolean).

This was working when compiling with tsc:

declare let isDebug: boolean;
let dependencyArray : any[] = [];

if ('undefined' !== typeof isDebug && isDebug) {
  dependencyArray.push(DebugDirective);
}

@NgModule({
  declarations: [AppComponent].concat(dependencyArray),
  imports: []
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {}

However it seems than the ngc compiler (AOT compilation) does not accept function call in module files. The following error is thrown by ngc.

Error encountered resolving symbol values statically. Function calls are not supported. Consider replacing the function or lambda with a reference to an exported function

I have found the various threads explaining how to use a factory with an exported function for providers (e.g. https://github.com/angular/angular/issues/11262) but I have not found how to do the same for the declaration array.

How can I solve the issue for the module declaration?


问:
How to find the mean of the value at an index in numpy
Suppose I have a numpy array as show below and I want to calculate the mean of values at index 0 of each array (1,1,1) or index 3 (4,5,6). Is there a numpy function that can solve this? I tried numpy.mean, but it does not solve the issue.</p>

```<code>[[1,2,3,4],
[1,2,3,5],  --> = [(1+1+1)/3, (2+2+2)/3, (3+3+3)/3, (4+5+6)/3] --> [1,2,3,5]
[1,2,3,6]]
</code>```

答:
```<code>a = array([[1, 2, 3, 4],
       [1, 2, 3, 5],
       [1, 2, 3, 6]])

np.mean(a, axis=0)

-> array([ 1.,  2.,  3.,  5.])
</code>```

The parameter axis lets you select the direction across which you want to calculate the mean.

Body:
Suppose I have a numpy array as show below and I want to calculate the mean of values at index 0 of each array (1,1,1) or index 3 (4,5,6). Is there a numpy function that can solve this? I tried numpy.mean, but it does not solve the issue.

[[1,2,3,4],
[1,2,3,5],  --> = [(1+1+1)/3, (2+2+2)/3, (3+3+3)/3, (4+5+6)/3] --> [1,2,3,5]
[1,2,3,6]]

Body:
a = array([[1, 2, 3, 4],
       [1, 2, 3, 5],
       [1, 2, 3, 6]])

np.mean(a, axis=0)

-> array([ 1.,  2.,  3.,  5.])

The parameter axis lets you select the direction across which you want to calculate the mean.


Title: How to find the mean of the value at an index in numpy

Body:
Take the mean along the first axis - axis 0:

>>> a = np.array([[1,2,3,4],
...               [1,2,3,5],
...               [1,2,3,6]])
>>> a.mean(axis=0)
array([ 1.,  2.,  3.,  5.])

ContentLicense: CC BY-SA 4.0


问:
What is scenario of using Redux in mobile apps?
I am producing mobile app using react native, and after days of learning Redux, and react-redux.

I have a big question mark that:

What is the scenario of using Redux in react-native?

I studied many tutorials that told us how wonderful it manage the state, how simply it manage the actions.

BUT, is it just happening when you only have many components on one page in your app?

For example, if I have a app with 2 pages, so called Page A and Page B.

Does redux can maintain the state of A, then using at B? (I am using react-navigation of jumping among pages)

If it can do, what is the different of that I stored state to AsyStorage in A, then fetch it back on B?

Seriously confused.

Just need your discussion about it please, if I get thing wrongly.

THX!

答:
Before getting into your problem statement let us first see why we should use these tools anyway?

For Handling App's Data:

State - It handles component's internal data with not much complexity.

Props - It tosses data back and forth from parent component to children and vice verse.

Redux - It handles data efficiently using action-reducer-store architecture. Great for a complex app with a lot of user's data to handle.

For Data Persistance:

AsyncStorage - Simple API to save and manage data on device manually.

Redux Persist - Built over Redux to store all the Redux State data to device synchronously.

Now getting back to your situation,
If you JUST have TWO screens to manage data back and forth on, it's better to use just state and props. You don't need anything else.

By calling AsyncStorage you are saving data on the device and then receiving it from the other screen. This is not necessary if you don't want your app's data to remain on the device even after closing the app.

I hope this helps :)


问:
Understanding the Editorial for Prime XOR - HackerRank
Disclaimer: This question involves content from the corresponding editorial. Thus, if you want to attempt this problem on your own, I discourage you from reading this post. Also, my question leaves out some details mentioned in the editorial, so please do refer to the editorial as you read my question.

Also, please bear in my mind that it is not my intention to advertise for HackerRank; furthermore, in no way, am I taking credit for the content on the editorial, problem description, or any other material that would be deemed a copyright infringement by HackerRank or affiliated parties).

Actual Question:

I'm trying to understand the editorial for this problem. Specifically, the part that I'm getting confused over is the following piece of code:

```<code>...
for(int i=1;i<=k;i++) {
    for(int j=0;j<8192;j++) {
        mem[flag][j] = (mem[flag^1][j]*(1+(a[v[i-1]])/2))%mod + (mem[flag^1][j^v[i-1]]*((a[v[i-1]]+1)/2))%mod;
        if(mem[flag][j]>=mod)
            mem[flag][j]%=mod;
    }
    flag = flag^1;
}
</code>```

The editorial states that "...Using this property, we can write a O(N) dynammic programming solution with 8192 constant factor such that dp[i][j] would store the count of subsets that can be formed with the first  elements such that the xor-sum of the elements in the subset is j."

From the code, it appears that mem is essentially dp, except I can't wrap my head around the function of flag -- what is flag?. Also, I get that 1 + (a[v[i - 1]])/2 corresponds with the number of evens in [0, a[v[i - 1]]] and (a[v[i - 1]] + 1) / 2corresponds with the number of odds in that same interval, but I don't see how it quite ties in with everything.

Thanks in advance for your efforts.

答:
Explanation of Flag

This is a standard approach to reduce memory usage when using dynamic programming.

The idea is that often each row of a DP array only depends on the previous row.  In this case, instead of storing the whole 2d DP[i][j] array, you can instead just use 2 rows of the array.

In other words, DP[i][j] is stored in mem[0][j] if i is even, and in mem[1][j] if i is odd.  The mem array is reused multiple times and after each iteration holds the most recent two rows of the full DP array.

Explanation of recurrence

Suppose we have 5 duplicates of a certain value v.  There are 1+5/2 ways of making an xor of 0 (take either 0,2 or 4 copies).  There are (1+5)/2 ways of making an xor of v (take either 1,3 or 5 copies).

So to make the new value j, we can either start with j and add 0,2 or 4 copies of v, or start with j^v and add 1,3 or 5 copies.

Body:
Disclaimer: This question involves content from the corresponding editorial. Thus, if you want to attempt this problem on your own, I discourage you from reading this post. Also, my question leaves out some details mentioned in the editorial, so please do refer to the editorial as you read my question.

Also, please bear in my mind that it is not my intention to advertise for HackerRank; furthermore, in no way, am I taking credit for the content on the editorial, problem description, or any other material that would be deemed a copyright infringement by HackerRank or affiliated parties).

Actual Question:

I'm trying to understand the editorial for this problem. Specifically, the part that I'm getting confused over is the following piece of code:

...
for(int i=1;i<=k;i++) {
    for(int j=0;j<8192;j++) {
        mem[flag][j] = (mem[flag^1][j]*(1+(a[v[i-1]])/2))%mod + (mem[flag^1][j^v[i-1]]*((a[v[i-1]]+1)/2))%mod;
        if(mem[flag][j]>=mod)
            mem[flag][j]%=mod;
    }
    flag = flag^1;
}

The editorial states that "...Using this property, we can write a O(N) dynammic programming solution with 8192 constant factor such that dp[i][j] would store the count of subsets that can be formed with the first  elements such that the xor-sum of the elements in the subset is j."

From the code, it appears that mem is essentially dp, except I can't wrap my head around the function of flag -- what is flag?. Also, I get that 1 + (a[v[i - 1]])/2 corresponds with the number of evens in [0, a[v[i - 1]]] and (a[v[i - 1]] + 1) / 2corresponds with the number of odds in that same interval, but I don't see how it quite ties in with everything.

Thanks in advance for your efforts.


问:
Padding 1D NumPy array with zeros to form 2D array
I have a numpy array:

```<code>arr=np.array([0,1,0,0.5])
</code>```

I need to form a new array from it as follows, such that every zero elements is repeated thrice and every non-zero element has 2 preceding zeroes, followed by the non-zero number. In short, every element is repeated thrice, zero as it is and non-zero has 2 preceding 0 and then the number itself. It is as follows:

```<code>([0,1,0,0.5])=0,0,0, [for index 0]
              0,0,1 [for index 1]
              0,0,0 [for index 2, which again has a zero] and
              0,0,0.5
</code>```

final output should be:

```<code>new_arr=[0,0,0,0,0,1,0,0,0,0,0,0.5]
</code>```

np.repeat() repeats all the array elements n number of times, but i dont want that exactly. How should this be done? Thanks for the help.

Body:
I have a numpy array:

arr=np.array([0,1,0,0.5])

I need to form a new array from it as follows, such that every zero elements is repeated thrice and every non-zero element has 2 preceding zeroes, followed by the non-zero number. In short, every element is repeated thrice, zero as it is and non-zero has 2 preceding 0 and then the number itself. It is as follows:

([0,1,0,0.5])=0,0,0, [for index 0]
              0,0,1 [for index 1]
              0,0,0 [for index 2, which again has a zero] and
              0,0,0.5

final output should be:

new_arr=[0,0,0,0,0,1,0,0,0,0,0,0.5]

np.repeat() repeats all the array elements n number of times, but i dont want that exactly. How should this be done? Thanks for the help.

Body:
A variant on the pad idea is to concatenate a 2d array of zeros

In [477]: arr=np.array([0,1,0,0.5])
In [478]: np.column_stack([np.zeros((len(arr),2)),arr])
Out[478]:
array([[ 0. ,  0. ,  0. ],
       [ 0. ,  0. ,  1. ],
       [ 0. ,  0. ,  0. ],
       [ 0. ,  0. ,  0.5]])
In [479]: _.ravel()
Out[479]:
array([ 0. ,  0. ,  0. ,  0. ,  0. ,  1. ,  0. ,  0. ,  0. ,  0. ,  0. ,
        0.5])

or padding in the other direction:

In [481]: np.vstack([np.zeros((2,len(arr))),arr])
Out[481]:
array([[ 0. ,  0. ,  0. ,  0. ],
       [ 0. ,  0. ,  0. ,  0. ],
       [ 0. ,  1. ,  0. ,  0.5]])
In [482]: _.T.ravel()
Out[482]:
array([ 0. ,  0. ,  0. ,  0. ,  0. ,  1. ,  0. ,  0. ,  0. ,  0. ,  0. ,
        0.5])


问:
"nohup ./filename.sh" not working in tSSH talend component
I'm using the tssh component to unzip a file, then delete the zip folder on a host which works fine.

The problem is when I try to run a .sh file in the same directory. In the commands for the tSSh component I have added the command

```<code>nohup filename.sh > outfile.out
</code>```

in which case I get the error

no such file or directory

I have also tried

```<code>nohup ./filename.sh > outfile.out
</code>```

but now the error is

./filename.sh command not found

All I need to do is execute the sh file.

答:
Is your home directory the place where you expect to find the script filename.sh?

If yes, maybe you have a "cd" in your startup file.

If not, try to give 2 commands for nohup:

nohup `$(cd yourDirectoryPath ; ./filename.sh > outfile.out)

If you can't retrieve the result in outfile.out, check for nohup.out (and remove the redirection from the command line).

Hope this helps.

TRF

Body:
I'm using the tssh component to unzip a file, then delete the zip folder on a host which works fine.

The problem is when I try to run a .sh file in the same directory. In the commands for the tSSh component I have added the command

nohup filename.sh > outfile.out

in which case I get the error

no such file or directory

I have also tried

nohup ./filename.sh > outfile.out

but now the error is

./filename.sh command not found

All I need to do is execute the sh file.


问:
How to implement "class versioning" (using different version of the same class)
Here is the problem : our main class (say : Contract) change every year. Some properties are added, other are removed. We don't know how it will look next year. It may change a lot or not at all.

On the other hand, we now (new requirement...) have to keep an historic of every contracts. Each time the user update a contract, the whole object must be stored in a backup (e.g. - serialized in a table).

Of course, we must be able to read it back... One option (brutal) is to have a new Contract class every year (Contract2008, Contract2009, ...).

But it would be very cumbersome (and ugly) since a lot of classes depend on Contract - in facts, we would have to create a bunch of new classes every year.

Ever have this kind of problem ? Any suggestion ?

Thanks in advance !

(We're using C# 2.0.)

ADDED : Thank for your answers. We're now asking ourself how we could use a dictionary / an XML file to implement versioning without breaking all the code. Dictionary seems very sexy in this context :o)

答:
Stop serializing the object.  Store the data relationally.  Serialization is intended for short durations, say like streaming across the wire; not permanent storage.

Instead of coding the fields into the class; it sounds like you might need more of dictionary sort of structure that can dynamically pull fields based on database configuration values stored by year.  Then build a dynamic UI based on those values.  Having to create a new class each year and test the code seems impossibly expensive to maintain.

OwnerDisplayName: Sylvain Rodrigue

LastEditorDisplayName: Sylvain Rodrigue

OwnerDisplayName: DancesWithBamboo


问:
pip install --find-links html file format
I need to include a few python packages into my product, but the jenkins server that does the build does not have access to the Internet. I've downloaded one of the packages using pip download, which downloaded the package and all its dependencies. However, I need to make sure pip knows where to find those dependencies. I'm trying to use the options --no-index and --find-links with a path to an html file with links to those packages. The full command looks like this:

```<code>pip install http://SERVER/python-packages/impyla/0.14.0/impyla-0.14.0.tar.gz --no-index --trusted-host SERVER --find-links http://SERVER/python-packages/impyla/0.14.0/packages.html
</code>```

...and the packages.html file looks like this:

bitarray-0.8.1.tar.gz
ply-3.10.tar.gz
six-1.10.0-py2.py3-none-any.whl
thriftpy-0.3.9.tar.gz```

However, when jenkins tries to run these commands, I get:

Could not find a version that satisfies the requirement
  thriftpy>=0.3.5 (from impyla==0.14.0) (from versions: )

No matching distribution found for thriftpy>=0.3.5 (from
  impyla==0.14.0)

I'm wondering if my packages.html isn't in a correct format, but I can't find any examples of using an html file for dependency resolution. Has anyone used --find-links successfully?

答:
Thanks to emulbreh I added -v to the pip install command and it reported:

Skipping page http://SERVER/python-packages/impyla/0.14.0/packages.html
  because of Content-Type: text/plain; charset=utf-8

Once I made sure the html file is served with a proper Content Type, I got it to work.

Body:
I need to include a few python packages into my product, but the jenkins server that does the build does not have access to the Internet. I've downloaded one of the packages using pip download, which downloaded the package and all its dependencies. However, I need to make sure pip knows where to find those dependencies. I'm trying to use the options --no-index and --find-links with a path to an html file with links to those packages. The full command looks like this:

pip install http://SERVER/python-packages/impyla/0.14.0/impyla-0.14.0.tar.gz --no-index --trusted-host SERVER --find-links http://SERVER/python-packages/impyla/0.14.0/packages.html

...and the packages.html file looks like this:

bitarray-0.8.1.tar.gz
ply-3.10.tar.gz
six-1.10.0-py2.py3-none-any.whl
thriftpy-0.3.9.tar.gz

However, when jenkins tries to run these commands, I get:

Could not find a version that satisfies the requirement
  thriftpy>=0.3.5 (from impyla==0.14.0) (from versions: )

No matching distribution found for thriftpy>=0.3.5 (from
  impyla==0.14.0)

I'm wondering if my packages.html isn't in a correct format, but I can't find any examples of using an html file for dependency resolution. Has anyone used --find-links successfully?


问:
Looping over one pandas column to match values with index of another dataframe
Exp is one DataFrame with datetime object

```<code>           Exp
0   1989-06-01
1   1989-07-01
2   1989-08-01
3   1989-09-01
4   1989-10-01
</code>```

CL is the Dataframe with Index as DateTime Object

```<code>                    CL
1989-06-01   68.800026
1989-06-04   68.620026
1989-06-05   68.930023
1989-06-06   68.990021
1989-06-09   69.110023
</code>```

I want to add new column R into CL dataframe which have will have date from Exp matching with CL Index.

This what my desired output should look like

```<code>                   CL          R

1989-06-01   68.800026   1989-06-01
1989-06-04   68.620026
1989-06-05   68.930023
1989-06-06   68.990021
1989-06-09   69.110023
</code>```

This is what I tried doing:

```<code>for m in Exp.iloc[:,0]:
if m == CL.index:
    CL['R'] = m
</code>```

ValueError: The truth value of an array with more than one element is
  ambiguous. Use a.any() or a.all()

Can someone please help me ? I keep getting this ValueError a lot of times

Body:
Exp is one DataFrame with datetime object

           Exp
0   1989-06-01
1   1989-07-01
2   1989-08-01
3   1989-09-01
4   1989-10-01

CL is the Dataframe with Index as DateTime Object

                    CL
1989-06-01   68.800026
1989-06-04   68.620026
1989-06-05   68.930023
1989-06-06   68.990021
1989-06-09   69.110023

I want to add new column R into CL dataframe which have will have date from Exp matching with CL Index.

This what my desired output should look like

                   CL          R

1989-06-01   68.800026   1989-06-01
1989-06-04   68.620026
1989-06-05   68.930023
1989-06-06   68.990021
1989-06-09   69.110023

This is what I tried doing:

for m in Exp.iloc[:,0]:
if m == CL.index:
    CL['R'] = m

ValueError: The truth value of an array with more than one element is
  ambiguous. Use a.any() or a.all()

Can someone please help me ? I keep getting this ValueError a lot of times

Body:
Edit: updated with commenters suggestion.

You need to do LEFT JOIN:

Exp = pd.DataFrame(
    pd.to_datetime(['1989-06-01', '1989-07-01', '1989-08-01', '1989-09-01', '1989-10-01']),
    columns=['Exp'])

gives:

          Exp
0  1989-06-01
1  1989-07-01
2  1989-08-01
3  1989-09-01
4  1989-10-01

and

CL = pd.DataFrame(
[68.800026, 68.620026, 68.930023, 68.990021, 69.110023],
index = pd.to_datetime(['1989-06-01', '1989-06-04', '1989-06-05', '1989-06-06', '1989-06-09']),
columns = ['CL'])

gives

                   CL
1989-06-01  68.800026
1989-06-04  68.620026
1989-06-05  68.930023
1989-06-06  68.990021
1989-06-09  69.110023

then:

(CL
 .reset_index()
 .merge(Exp, how='left', right_on='Exp', left_on='index')
 .set_index('index')
 .rename(columns={'Exp': 'R'}))

returns what you are looking for

                   CL           R
index
1989-06-01  68.800026  1989-06-01
1989-06-04  68.620026         NaN
1989-06-05  68.930023         NaN
1989-06-06  68.990021         NaN
1989-06-09  69.110023         NaN

Because looping over dataframe is not Pandas way of doing things.


问:
Parsing address_components in Google Maps upon autocomplete select
I have the following code to parse the country when the autocomplete list is selected:

```<code>$('#spot_address').autocomplete({
  // This bit uses the geocoder to fetch address values
  source: function(request, response) {
    geocoder.geocode( {'address': request.term }, function(results, status) {
      // Get address_components
      for (var i = 0; i < results[0].address_components.length; i++)
      {
        var addr = results[0].address_components[i];
        var getCountry;
        if (addr.types[0] == 'country')
          getCountry = addr.long_name;
      }
      response($.map(results, function(item) {
        return {
          label: item.formatted_address,
          value: item.formatted_address,
          latitude: item.geometry.location.lat(),
          longitude: item.geometry.location.lng(),
          country: getCountry
        }
      }));
    })
  },

  // This bit is executed upon selection of an address
  select: function(event, ui) {
    // Get values
    $('#spot_country').val(ui.item.country);
    $('#spot_lat').val(ui.item.latitude);
    $('#spot_lng').val(ui.item.longitude);
    var location = new google.maps.LatLng(ui.item.latitude, ui.item.longitude);
    marker.setPosition(location);
    map.setCenter(location);
  },

  // Changes the current marker when autocomplete dropdown list is focused
  focus: function(event, ui) {
    var location = new google.maps.LatLng(ui.item.latitude, ui.item.longitude);
    marker.setPosition(location);
    map.setCenter(location);
  }
});
</code>```

However, the code above doesn't work, and when the country is parsed, only the first result of the autocomplete is parsed no matter what, which is significant with the array results[0] because it only fetches the first result.

I tried to move it to the select function, but ui in select only contains formatted_address, longitude and latitude, but not the address_components.

What must I do to send the correct country when the autocomplete list item is selected?

Many thanks.

答:
Country is always last in array that is returned from Geocoder.

Here is my solution -

```<code> geocoder.geocode( {'address': request.term }, function(results, status) {
   var location_country =
   results[0].address_components[results[0].address_components.length - 1].long_name;
});
</code>```

Hope this helps.

Body:
I have the following code to parse the country when the autocomplete list is selected:

$('#spot_address').autocomplete({
  // This bit uses the geocoder to fetch address values
  source: function(request, response) {
    geocoder.geocode( {'address': request.term }, function(results, status) {
      // Get address_components
      for (var i = 0; i < results[0].address_components.length; i++)
      {
        var addr = results[0].address_components[i];
        var getCountry;
        if (addr.types[0] == 'country')
          getCountry = addr.long_name;
      }
      response($.map(results, function(item) {
        return {
          label: item.formatted_address,
          value: item.formatted_address,
          latitude: item.geometry.location.lat(),
          longitude: item.geometry.location.lng(),
          country: getCountry
        }
      }));
    })
  },

  // This bit is executed upon selection of an address
  select: function(event, ui) {
    // Get values
    $('#spot_country').val(ui.item.country);
    $('#spot_lat').val(ui.item.latitude);
    $('#spot_lng').val(ui.item.longitude);
    var location = new google.maps.LatLng(ui.item.latitude, ui.item.longitude);
    marker.setPosition(location);
    map.setCenter(location);
  },

  // Changes the current marker when autocomplete dropdown list is focused
  focus: function(event, ui) {
    var location = new google.maps.LatLng(ui.item.latitude, ui.item.longitude);
    marker.setPosition(location);
    map.setCenter(location);
  }
});

However, the code above doesn't work, and when the country is parsed, only the first result of the autocomplete is parsed no matter what, which is significant with the array results[0] because it only fetches the first result.

I tried to move it to the select function, but ui in select only contains formatted_address, longitude and latitude, but not the address_components.

What must I do to send the correct country when the autocomplete list item is selected?

Many thanks.

Body:
Country is always last in array that is returned from Geocoder.

Here is my solution -

 geocoder.geocode( {'address': request.term }, function(results, status) {
   var location_country =
   results[0].address_components[results[0].address_components.length - 1].long_name;
});

Hope this helps.


问:
list query using if and .split() taking too long Python
Sorry if something along these lines has already been answered.

I am trying to find values in the list that are "after" 2004q2 (where 2004 is the year and 2 is the quarter.) I was looking for members of the list either in a year after 2004 or in 2004 but after quarter 2. To do this I tried the following code:

```<code>get_recession_start() is a separate function that returns '2004q2'
(changed value cause online class question)

def get_recession_start():
        return '2004q4'

two_q_growth =['2000q1', '2000q2', '2000q3', '2000q4', '2001q1', '2001q2', '2001q3',
 '2001q4', '2002q1', '2002q2', '2002q3', '2002q4', '2003q1', '2003q2', '2003q3', '2003q4',
 '2004q1', '2004q2', '2004q3', '2004q4', '2005q1', '2005q2', '2005q3', '2005q4', '2006q1',
 '2006q2', '2006q3', '2006q4', '2007q1', '2007q2', '2007q3', '2007q4', '2008q3', '2009q4',
 '2010q1', '2010q2', '2010q3', '2010q4', '2011q1', '2011q2', '2011q3', '2011q4', '2012q1',
 '2012q2', '2012q3', '2012q4', '2013q1', '2013q2', '2013q3', '2013q4', '2014q1', '2014q2',
 '2014q3', '2014q4', '2015q1', '2015q2', '2015q3', '2015q4', '2016q1', '2016q2']

for year in two_q_growth:
    start_year = get_recession_start().split('q')[0]
    start_q = get_recession_start().split('q')[1]
    if ((year.split('q')[0] > start_year)
        | ((year.split('q')[0] == start_year) &
        (year.split('q')[1] > start_q))):
        recession_end.append(year)
</code>```

This code has been taking forever and a day to run and I am not sure why. (I'm still new to Python and trying to figure out how to optimize things.)

Thanks!

Technically I just need the first value so I am working on writing something with break but I would like to get this faster too

Body:
Sorry if something along these lines has already been answered.

I am trying to find values in the list that are "after" 2004q2 (where 2004 is the year and 2 is the quarter.) I was looking for members of the list either in a year after 2004 or in 2004 but after quarter 2. To do this I tried the following code:

get_recession_start() is a separate function that returns '2004q2'
(changed value cause online class question)

def get_recession_start():
        return '2004q4'

two_q_growth =['2000q1', '2000q2', '2000q3', '2000q4', '2001q1', '2001q2', '2001q3',
 '2001q4', '2002q1', '2002q2', '2002q3', '2002q4', '2003q1', '2003q2', '2003q3', '2003q4',
 '2004q1', '2004q2', '2004q3', '2004q4', '2005q1', '2005q2', '2005q3', '2005q4', '2006q1',
 '2006q2', '2006q3', '2006q4', '2007q1', '2007q2', '2007q3', '2007q4', '2008q3', '2009q4',
 '2010q1', '2010q2', '2010q3', '2010q4', '2011q1', '2011q2', '2011q3', '2011q4', '2012q1',
 '2012q2', '2012q3', '2012q4', '2013q1', '2013q2', '2013q3', '2013q4', '2014q1', '2014q2',
 '2014q3', '2014q4', '2015q1', '2015q2', '2015q3', '2015q4', '2016q1', '2016q2']

for year in two_q_growth:
    start_year = get_recession_start().split('q')[0]
    start_q = get_recession_start().split('q')[1]
    if ((year.split('q')[0] > start_year)
        | ((year.split('q')[0] == start_year) &
        (year.split('q')[1] > start_q))):
        recession_end.append(year)

This code has been taking forever and a day to run and I am not sure why. (I'm still new to Python and trying to figure out how to optimize things.)

Thanks!

Technically I just need the first value so I am working on writing something with break but I would like to get this faster too

Body:
While it should work, your code is incredibly inefficient and seriously overcomplicated. You don't even need to parse your array as in this case even string comparison would work just fine:

two_q_growth = ['2000q1', '2000q2', '2000q3', '2000q4', '2001q1', '2001q2', '2001q3',
                '2001q4', '2002q1', '2002q2', '2002q3', '2002q4', '2003q1', '2003q2',
                '2003q3', '2003q4', '2004q1', '2004q2', '2004q3', '2004q4', '2005q1',
                '2005q2', '2005q3', '2005q4', '2006q1', '2006q2', '2006q3', '2006q4',
                '2007q1', '2007q2', '2007q3', '2007q4', '2008q3', '2009q4', '2010q1',
                '2010q2', '2010q3', '2010q4', '2011q1', '2011q2', '2011q3', '2011q4',
                '2012q1', '2012q2', '2012q3', '2012q4', '2013q1', '2013q2', '2013q3',
                '2013q4', '2014q1', '2014q2', '2014q3', '2014q4', '2015q1', '2015q2',
                '2015q3', '2015q4', '2016q1', '2016q2']

recession_start = '2004q2'  # get all entries after this one
recession_end = [year for year in two_q_growth if year > recession_start]

print(recession_end)

resulting in:

['2004q3', '2004q4', '2005q1', '2005q2', '2005q3', '2005q4', '2006q1', '2006q2', '2006q3',
'2006q4', '2007q1', '2007q2', '2007q3', '2007q4', '2008q3', '2009q4', '2010q1', '2010q2',
'2010q3', '2010q4', '2011q1', '2011q2', '2011q3', '2011q4', '2012q1', '2012q2', '2012q3',
'2012q4', '2013q1', '2013q2', '2013q3', '2013q4', '2014q1', '2014q2', '2014q3', '2014q4',
'2015q1', '2015q2', '2015q3', '2015q4', '2016q1', '2016q2']

And if you only need the first value after your recession_start value, assuming your list is sorted (and if not run it through sorted() first):

recession_start = '2004q2'  # get the entry after this one
recession_end = None  # just in case we don't find it
for year in two_q_growth:  # loop through the list
    if year > recession_start:  # grab the first value higher than recession_start
        recession_end = year  # store it to recession end
        break  # break away, no need to loop further as we only want the first element

print(recession_end)
# 2004q3


问:
Code working locally but not in Server, SQL and null string related
Hello i have the following cs code

```<code> SqlConnection con = new SqlConnection();
        SqlCommand com = new SqlCommand();
        String comando = "";
        con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["INBIOTECAConnectionString"].ToString());
        SqlDataReader leer = null;
        String diaUltimo = "";
        String fecha = DateTime.Now.ToString("dd/MM/yyyy");

        try
        {
            con.Open();
            comando = " SELECT TOP 1 hora FROM SI_RegEntrada  WHERE nombre = '" + name + "' and dia = '"+fecha+"' ORDER BY id DESC;";
            com = new SqlCommand(comando, con);
            leer = com.ExecuteReader();
            while (leer.Read())
            {
                diaUltimo = leer[0].ToString();
            }

            if (diaUltimo.Equals(""))
            {
                return false;
            }
            else
            {
                return true;
            }

        }
        catch (Exception ex)
        {
            return true;
        }
        finally
        {
            con.Close();
            con.Dispose();
            com.Dispose();
            com = null;
            con = null;
        }
</code>```

It's supposed to be pretty simple, it's gonna check if there's an entry on the SI_RegEntrada table today (fecha) from any user (name).

```<code>SELECT TOP 1 hora FROM SI_RegEntrada  WHERE nombre = '" + name + "' and dia = '"+fecha+"' ORDER BY id DESC;
</code>```

ok, so far so good, i proceed to read the results on the var diaUltimo.

On my local server, if there are no results (meaning that today, that user, hasn't interact with the system), diaUltimo will get the value of

```<code> diaUltimo = ""
</code>```

so I check for that in the if/else condition a return true or false.
In the live server, it always falls on the catch clause, and return always true.

I was thinking that, maybe diaUltimo will get some kind of null value, or some sql error.

I cannot debug or interact with the live server.

答: There is very high chance that con.Open() is raising exception. Nothing else looks problematic in your code.

Body:
Hello i have the following cs code

 SqlConnection con = new SqlConnection();
        SqlCommand com = new SqlCommand();
        String comando = "";
        con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["INBIOTECAConnectionString"].ToString());
        SqlDataReader leer = null;
        String diaUltimo = "";
        String fecha = DateTime.Now.ToString("dd/MM/yyyy");

        try
        {
            con.Open();
            comando = " SELECT TOP 1 hora FROM SI_RegEntrada  WHERE nombre = '" + name + "' and dia = '"+fecha+"' ORDER BY id DESC;";
            com = new SqlCommand(comando, con);
            leer = com.ExecuteReader();
            while (leer.Read())
            {
                diaUltimo = leer[0].ToString();
            }

            if (diaUltimo.Equals(""))
            {
                return false;
            }
            else
            {
                return true;
            }

        }
        catch (Exception ex)
        {
            return true;
        }
        finally
        {
            con.Close();
            con.Dispose();
            com.Dispose();
            com = null;
            con = null;
        }

It's supposed to be pretty simple, it's gonna check if there's an entry on the SI_RegEntrada table today (fecha) from any user (name).

SELECT TOP 1 hora FROM SI_RegEntrada  WHERE nombre = '" + name + "' and dia = '"+fecha+"' ORDER BY id DESC;

ok, so far so good, i proceed to read the results on the var diaUltimo.

On my local server, if there are no results (meaning that today, that user, hasn't interact with the system), diaUltimo will get the value of

 diaUltimo = ""

so I check for that in the if/else condition a return true or false.
In the live server, it always falls on the catch clause, and return always true.

I was thinking that, maybe diaUltimo will get some kind of null value, or some sql error.

I cannot debug or interact with the live server.


问:
Efficient small byte-arrays in C#
I have a huge collection of very small objects. To ensure the data is stored very compactly I rewrote the class to store all information within a byte-array with variable-byte encoding. Most instances of these millions of objects need only 3 to 7 bytes to store all the data.

After memory-profiling I found out that these byte-arrays always take at least 32 bytes.

Is there a way to store the information more compactly than bit-fiddled into a byte[]? Would it be better to point to an unmanaged array?

```<code>class MyClass
{
    byte[] compressed;

    public MyClass(IEnumerable<int> data)
    {
        compressed = compress(data);
    }

    private byte[] compress(IEnumerable<int> data)
    {
        // ...
    }

    private IEnumerable<int> decompress(byte[] compressedData)
    {
        // ...
    }

    public IEnumerable<int> Data { get { return decompress(compressed); } }
}
</code>```

答:
There are a couple problems you're facing that eat up memory. One is object overhead, and the other is objects aligning to 32 or 64 bit boundaries (depending on your build). Your current approach suffers from both issues. The following sources describe this in more detail:

Of Memory and Strings

How much memory does a C# string take up

I played around with this when I was fiddling with benchmarking sizes.

A solution that is simple would be to simply create a struct that has a single member that is a long value. Its methods would handle packing and unpacking bytes into and out of that long, using shift and mask bit fiddling.

Another idea would be a class that served up objects by ID, and stored the actual bytes in a single backing List<byte>. But this would get complicated and messy. I think the struct idea is much more straightforward.

Title: Efficient small byte-arrays in C#

Body:
I have a huge collection of very small objects. To ensure the data is stored very compactly I rewrote the class to store all information within a byte-array with variable-byte encoding. Most instances of these millions of objects need only 3 to 7 bytes to store all the data.

After memory-profiling I found out that these byte-arrays always take at least 32 bytes.

Is there a way to store the information more compactly than bit-fiddled into a byte[]? Would it be better to point to an unmanaged array?

class MyClass
{
    byte[] compressed;

    public MyClass(IEnumerable<int> data)
    {
        compressed = compress(data);
    }

    private byte[] compress(IEnumerable<int> data)
    {
        // ...
    }

    private IEnumerable<int> decompress(byte[] compressedData)
    {
        // ...
    }

    public IEnumerable<int> Data { get { return decompress(compressed); } }
}


问:
Creating a char function with char parameter in c
I am new in learning c language and I am trying to learn about functions with char arrays. In this code I want to wrtie a function which uses a char array as a parameter and give another char array as a result. When I run the code the output should be : Helloooo world!

However, when I run the code the program crashes. How can I fix the problem? Am I using the right type of variables?

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

char *write();

int main()
{
    char x[10] = "ooo";
    printf("%s, world!\n", *write(x));
    return 0;
}

char *write(char x[10])
{
    char str[10];
    strcpy(str, "Hello");
    strcat(str,x);
    x = str;
    return x;
}
</code>```

答:
You have two issues:

str is a local variable in the write function scope. So you return the pointer to something which does not exist any more.

Str is too short to accommodate your data. You copy "hello" (5 chars) + possible 10 chars from the function parameters.

```<code>char *write();

int main()
{
    char x[10] = "ooo";
    char buff[20];
    printf("%s, world!\n", write(buff, x, 20));
    return 0;
}

char *write(char *buff, char *s2, int maxsize)
{
    strcpy(buff, "Hello");
    if(strlen(buff) + strlen(s2) < maxsize)
        strcat(buff,s2);
      else
        strcpy(buff,"Error");
    return buff;
}
</code>```

Body:
I am new in learning c language and I am trying to learn about functions with char arrays. In this code I want to wrtie a function which uses a char array as a parameter and give another char array as a result. When I run the code the output should be : Helloooo world!

However, when I run the code the program crashes. How can I fix the problem? Am I using the right type of variables?

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

char *write();

int main()
{
    char x[10] = "ooo";
    printf("%s, world!\n", *write(x));
    return 0;
}

char *write(char x[10])
{
    char str[10];
    strcpy(str, "Hello");
    strcat(str,x);
    x = str;
    return x;
}

Body:
You have two issues:

str is a local variable in the write function scope. So you return the pointer to something which does not exist any more.

Str is too short to accommodate your data. You copy "hello" (5 chars) + possible 10 chars from the function parameters.

char *write();

int main()
{
    char x[10] = "ooo";
    char buff[20];
    printf("%s, world!\n", write(buff, x, 20));
    return 0;
}

char *write(char *buff, char *s2, int maxsize)
{
    strcpy(buff, "Hello");
    if(strlen(buff) + strlen(s2) < maxsize)
        strcat(buff,s2);
      else
        strcpy(buff,"Error");
    return buff;
}


问:
Architect a Cloudera CDH cluster on AWS: instances and storage
I have some doubts about a deployment of CDH on AWS. I read the reference architecture doc and other material I found on Cloudera Engineering Blog but I need some more suggestions about it.

1) Is the CDH deployment available only for some kind of instances or I can deploy it on all the AWS instance types?

2) Assuming I want to create a cluster that will be active 24x7. For a long-running cluster I understood it's better to have a cluster based on local-storage instances. If we consider a cluster of 2PBs I think that d2.8xlarge should be the best choice for the datanodes. About the Master Nodes: - if I want to deploy only 3 Master Nodes, is it better to have them as local-storage instances too or as EBS attached instances to be able to react quickly to a possible Master Node failure? - are there some best practice about the master node instance type (EBS or local-storage)? About the Data Nodes: - if a data node fails, Has the CDH some automated mechanism to automatically spin-up a new instance and connect it to the cluster in order to restore the cluster without down-times? Have we to build a script from scratch to do this thing? About the Edge Nodes: - are there some best practice about the instance type (EBS or local-storage)?

3) If I want to do a backup of the cluster on S3: - when I do a distcp from the CDH to S3, can I move the data directly on Glacier instead of the normal S3? If I have some compression applied on the data (e.g. snappy, gzip, etc.) and I do a distcp to S3: - Is the space occupied on S3 the same or the distcp command decompress the data for the copy?

If I have a cluster based on EBS attached instances: - is it possible to snapshot the disks and re-attach a datanode with the EBS disks rebuilt from the snapshot?

4) If I have the Data Nodes deployed as r4.8xlarge and I need more horsepower, is it possible to scale-up the cluster from r4.8xlarge to a r4.16xlarge on-the-fly? Attaching and detaching the disks in few mins?

Thanks a lot for the clarifications, I hope my doubts will help also other users.

答:
Point 3 only:

You need to distcp to S3 and move that to glacier via the AWS settings

It doesn't do anything to the data, compression, etc.

see the (hortonworks doc) Distcp and S3 and read its warnings/caveats. In particular, incremental distcp isn't checksum-based, atomic distcp isn't, it's just "really slow distcp"


问:
Cant Fully Install Hawq on Ambari
Im trying to run Pivotal Hawq with Ambari. I add the Hawq repository and install the Hawq and PXF through ambari. I have 4 nodes and so the configuration would be 1 Hawq master and 3 segment. The master is started correctly, but i only can start 2 of the 3 segments, one of the segments is always giving the error represented on the image  error_img. The error its like no hawq service is not installed.
Can someons give some help?</p>

答: hawq command not found on segment. Make sure you have hawq repo on segment host (yum repolist or yum provides hawq). Do you have httpd running on hawq repo node?  </p>

Title: Cant Fully Install Hawq on Ambari


问:
How to use Ember action helper in element append to the DOM
First, I wanna let you know that I'm just starting at Ember, so, if is there a better way to accomplish the same result, feel free to point at that.

I have a component called "select-room", it should work as the fields "Quartos", "Adultos" and "Crianças" at this site.

In this site when the field "Quartos" is changed, will be added or removed more selects fields on the form, the same happen when the value of "Crianças" change. I was able to accomplish this behavor using DOM manipulation, but when appending a select field like this html+= ''; the action helper don't work.

Link to the full code is at this repo in Github: https://github.com/darwinboaventura/embercvc

What is the best to way to solve this problem?

答:
You'd use data set on the component to render DOM elements using handlebars syntax.

```<code>{{#if items}}
  <select onchange={{action ..}}>
    {{#each items as |item|}}
      <option value={{item.value}}>{{item.label}}</option>
    {{/each}}
  </select>
{{/if}}
</code>```

See this example: https://guides.emberjs.com/v2.14.0/templates/displaying-a-list-of-items/

Overall, you should go through the tutorial, so you have a better grasp of how things work in Ember. Start here: https://guides.emberjs.com/v2.14.0/tutorial/ember-cli/

Body:
You'd use data set on the component to render DOM elements using handlebars syntax.

{{#if items}}
  <select onchange={{action ..}}>
    {{#each items as |item|}}
      <option value={{item.value}}>{{item.label}}</option>
    {{/each}}
  </select>
{{/if}}

See this example: https://guides.emberjs.com/v2.14.0/templates/displaying-a-list-of-items/

Overall, you should go through the tutorial, so you have a better grasp of how things work in Ember. Start here: https://guides.emberjs.com/v2.14.0/tutorial/ember-cli/


问:
Changing elements in a numpy Array
I have been sifting through the Numpy tutorials and I've tried several functions that are not working for me. I want to take an array such as:

```<code>    import numpy as np
    a = np.array([[[1, 2, 3, 4]],[[5, 6, 7, 8]],[[1, 2, 3, 4]],[[5, 6, 7, 8]]])
</code>```

which has the form

```<code>     [[[1 2 3 4]]

     [[4 5 6 7]]

     [[1 2 3 4]]

     [[4 5 6 7]]]
</code>```

This is the format a different function gives me results in, so, the form is not by choosing. What I want to do is make every other element negative, so it would look like

```<code>     [[[1 -2 3 -4]]

     [[4 -5 6 -7]]

     [[1 -2 3 -4]]

     [[4 -5 6 -7]]]
</code>```

I tried np.negative(a) and that made every element negative. There is a where option that I thought I could make use of, but, I couldn't find a way to have it affect only every other component. I've also built a double loop to move through the array as lists, but, I can't seem to rebuild the array from these lists

```<code>     new = np.array([])

     for n in range(len(a)):
         for x1,y1,x2,y2 in a[n]:
              y1 = -1 * y1
              y2 = -1 * y2
             row = [x1, y1, x2, y2]
         new = np.append(new,row)
     print(a)
</code>```

I feel like I'm making this too complicated, but, a better approach hasn't occurred to me.

答:
You can multiple every other column by -1 combined with slice:

```<code>a[...,1::2] *= -1
# here use ... to skip the first few dimensions, and slice the last dimension with 1::2
# which takes element from 1 with a step of 2 (every other element in the last dimension)
# now multiply with -1 and assign it back to the exact same locations

a
#array([[[ 1, -2,  3, -4]],

#       [[ 5, -6,  7, -8]],

#       [[ 1, -2,  3, -4]],

#       [[ 5, -6,  7, -8]]])
</code>```

You can see more about ellipsis here.

Title: Changing elements in a numpy Array

Body:
I have been sifting through the Numpy tutorials and I've tried several functions that are not working for me. I want to take an array such as:

    import numpy as np
    a = np.array([[[1, 2, 3, 4]],[[5, 6, 7, 8]],[[1, 2, 3, 4]],[[5, 6, 7, 8]]])

which has the form

     [[[1 2 3 4]]

     [[4 5 6 7]]

     [[1 2 3 4]]

     [[4 5 6 7]]]

This is the format a different function gives me results in, so, the form is not by choosing. What I want to do is make every other element negative, so it would look like

     [[[1 -2 3 -4]]

     [[4 -5 6 -7]]

     [[1 -2 3 -4]]

     [[4 -5 6 -7]]]

I tried np.negative(a) and that made every element negative. There is a where option that I thought I could make use of, but, I couldn't find a way to have it affect only every other component. I've also built a double loop to move through the array as lists, but, I can't seem to rebuild the array from these lists

     new = np.array([])

     for n in range(len(a)):
         for x1,y1,x2,y2 in a[n]:
              y1 = -1 * y1
              y2 = -1 * y2
             row = [x1, y1, x2, y2]
         new = np.append(new,row)
     print(a)

I feel like I'm making this too complicated, but, a better approach hasn't occurred to me.

Body:
You can multiple every other column by -1 combined with slice:

a[...,1::2] *= -1
# here use ... to skip the first few dimensions, and slice the last dimension with 1::2
# which takes element from 1 with a step of 2 (every other element in the last dimension)
# now multiply with -1 and assign it back to the exact same locations

a
#array([[[ 1, -2,  3, -4]],

#       [[ 5, -6,  7, -8]],

#       [[ 1, -2,  3, -4]],

#       [[ 5, -6,  7, -8]]])

You can see more about ellipsis here.


问:
Python Dependencies in Cloud DataFlow, requirements.txt works locally, but not on worker
I am trying to get my Cloud DataFlow job running with a requirements.txt file as described here

https://cloud.google.com/dataflow/pipelines/dependencies-python

Rather than building all of opencv from source (takes 20-30 minutes), I can just build the python library

From my compute engine, I could do this

```<code>root@fcfca6a4dad2:/DeepMeerkat# pip install opencv-python
Collecting opencv-python
  Downloading opencv_python-3.2.0.7-cp27-cp27mu-manylinux1_x86_64.whl (6.7MB)
    100% |################################| 6.7MB 163kB/s
Collecting numpy>=1.11.1 (from opencv-python)
  Downloading numpy-1.13.0-cp27-cp27mu-manylinux1_x86_64.whl (16.6MB)
    100% |################################| 16.6MB 68kB/s
Installing collected packages: numpy, opencv-python
  Found existing installation: numpy 1.8.2
    DEPRECATION: Uninstalling a distutils installed project (numpy) has been deprecated and will be removed in a future version. This is due to the fact that uninstalling a distutils project will only partially uninstall the project.
    Uninstalling numpy-1.8.2:
      Successfully uninstalled numpy-1.8.2
Successfully installed numpy-1.13.0 opencv-python-3.2.0.7
</code>```

I could wrap this into a requirements file with a few other modules

```<code>root@fcfca6a4dad2:/DeepMeerkat# pip install -r tests/prediction/requirements.txt
Requirement already satisfied: opencv-python in /usr/local/lib/python2.7/dist-packages (from -r tests/prediction/requirements.txt (line 1))
Collecting tensorflow==1.0.1 (from -r tests/prediction/requirements.txt (line 2))
  Downloading tensorflow-1.0.1-cp27-cp27mu-manylinux1_x86_64.whl (44.1MB)
    100% |################################| 44.1MB 27kB/s
Requirement already satisfied: numpy in /usr/local/lib/python2.7/dist-packages (from -r tests/prediction/requirements.txt (line 3))
Requirement already satisfied: mock>=2.0.0 in /usr/local/lib/python2.7/dist-packages (from tensorflow==1.0.1->-r tests/prediction/requirements.txt (line 2))
Requirement already satisfied: wheel in /usr/lib/python2.7/dist-packages (from tensorflow==1.0.1->-r tests/prediction/requirements.txt (line 2))
Requirement already satisfied: six>=1.10.0 in /usr/local/lib/python2.7/dist-packages (from tensorflow==1.0.1->-r tests/prediction/requirements.txt (line 2))
Requirement already satisfied: protobuf>=3.1.0 in /usr/local/lib/python2.7/dist-packages (from tensorflow==1.0.1->-r tests/prediction/requirements.txt (line 2))
Requirement already satisfied: funcsigs>=1; python_version < "3.3" in /usr/local/lib/python2.7/dist-packages (from mock>=2.0.0->tensorflow==1.0.1->-r tests/prediction/requirements.txt (line 2))
Requirement already satisfied: pbr>=0.11 in /usr/local/lib/python2.7/dist-packages (from mock>=2.0.0->tensorflow==1.0.1->-r tests/prediction/requirements.txt (line 2))
Requirement already satisfied: setuptools in /usr/local/lib/python2.7/dist-packages (from protobuf>=3.1.0->tensorflow==1.0.1->-r tests/prediction/requirements.txt (line 2))
Installing collected packages: tensorflow
Successfully installed tensorflow-1.0.1
</code>```

However, when I send it to cloud dataflow, it can't find opencv-python from the worker.

```<code>root@fcfca6a4dad2:/DeepMeerkat# python tests/prediction/run.py \
>     --runner DataflowRunner \
>     --project $PROJECT \
>     --staging_location $BUCKET/staging \
>     --temp_location $BUCKET/temp \
>     --job_name $PROJECT-deepmeerkat \
>     --setup_file tests/prediction/setup.py \
>     --requirements_file tests/prediction/requirements.txt
No handlers could be found for logger "oauth2client.contrib.multistore_file"
/usr/local/lib/python2.7/dist-packages/apache_beam/io/gcp/gcsio.py:113: DeprecationWarning: object() takes no parameters
  super(GcsIO, cls).__new__(cls, storage_client))
INFO:root:Starting the size estimation of the input
INFO:oauth2client.transport:Attempting refresh to obtain initial access_token
INFO:root:Finished the size estimation of the input at 1 files. Estimation took 0.0855119228363 seconds
INFO:root:Starting the size estimation of the input
INFO:oauth2client.transport:Attempting refresh to obtain initial access_token
INFO:root:Finished the size estimation of the input at 1 files. Estimation took 0.0597159862518 seconds
/usr/local/lib/python2.7/dist-packages/apache_beam/coders/typecoders.py:135: UserWarning: Using fallback coder for typehint: Any.
  warnings.warn('Using fallback coder for typehint: %r.' % typehint)
INFO:root:Starting GCS upload to gs://api-project-773889352370-testing/staging/api-project-773889352370-deepmeerkat.1499372970.163850/requirements.txt...
INFO:oauth2client.transport:Attempting refresh to obtain initial access_token
INFO:root:Completed GCS upload to gs://api-project-773889352370-testing/staging/api-project-773889352370-deepmeerkat.1499372970.163850/requirements.txt
INFO:root:Executing command: ['/usr/bin/python', '-m', 'pip', 'install', '--download', '/tmp/dataflow-requirements-cache', '-r', 'tests/prediction/requirements.txt', '--no-binary', ':all:']
DEPRECATION: pip install --download has been deprecated and will be removed in the future. Pip now has a download command that should be used instead.
Collecting opencv-python (from -r tests/prediction/requirements.txt (line 1))
  Could not find a version that satisfies the requirement opencv-python (from -r tests/prediction/requirements.txt (line 1)) (from versions: )
No matching distribution found for opencv-python (from -r tests/prediction/requirements.txt (line 1))
Traceback (most recent call last):
  File "tests/prediction/run.py", line 22, in <module>
    predict.run()
  File "/DeepMeerkat/tests/prediction/modules/predict.py", line 32, in run
    p.run()
  File "/usr/local/lib/python2.7/dist-packages/apache_beam/pipeline.py", line 167, in run
    self.to_runner_api(), self.runner, self._options).run(False)
  File "/usr/local/lib/python2.7/dist-packages/apache_beam/pipeline.py", line 176, in run
    return self.runner.run(self)
  File "/usr/local/lib/python2.7/dist-packages/apache_beam/runners/dataflow/dataflow_runner.py", line 252, in run
    self.dataflow_client.create_job(self.job), self)
  File "/usr/local/lib/python2.7/dist-packages/apache_beam/utils/retry.py", line 168, in wrapper
    return fun(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/apache_beam/runners/dataflow/internal/apiclient.py", line 425, in create_job
    self.create_job_description(job)
  File "/usr/local/lib/python2.7/dist-packages/apache_beam/runners/dataflow/internal/apiclient.py", line 448, in create_job_description
    job.options, file_copy=self._gcs_file_copy)
  File "/usr/local/lib/python2.7/dist-packages/apache_beam/runners/dataflow/internal/dependency.py", line 307, in stage_job_resources
    setup_options.requirements_file, requirements_cache_path)
  File "/usr/local/lib/python2.7/dist-packages/apache_beam/runners/dataflow/internal/dependency.py", line 241, in _populate_requirements_cache
    processes.check_call(cmd_args)
  File "/usr/local/lib/python2.7/dist-packages/apache_beam/utils/processes.py", line 44, in check_call
    return subprocess.check_call(*args, **kwargs)
  File "/usr/lib/python2.7/subprocess.py", line 540, in check_call
    raise CalledProcessError(retcode, cmd)
subprocess.CalledProcessError: Command '['/usr/bin/python', '-m', 'pip', 'install', '--download', '/tmp/dataflow-requirements-cache', '-r', 'tests/prediction/requirements.txt', '--no-binary', ':all:']' returned non-zero exit status 1
</code>```

It seems to be the no binary flag that is the problem. Locally running (after uninstalling the above)

```<code>root@fcfca6a4dad2:/DeepMeerkat# pip install -r tests/prediction/requirements.txt --no-binary :all:
Collecting opencv-python (from -r tests/prediction/requirements.txt (line 1))
  Could not find a version that satisfies the requirement opencv-python (from -r tests/prediction/requirements.txt (line 1)) (from versions: )
No matching distribution found for opencv-python (from -r tests/prediction/requirements.txt (line 1))
</code>```

The no-binary flag is described as excluding broken wheels? How is this applicable in this case?

Can confirm that the module can be run

again,

```<code>root@fcfca6a4dad2:/DeepMeerkat# pip install opencv-python
Collecting opencv-python
  Using cached opencv_python-3.2.0.7-cp27-cp27mu-manylinux1_x86_64.whl
Requirement already satisfied: numpy>=1.11.1 in /usr/local/lib/python2.7/dist-packages (from opencv-python)
Installing collected packages: opencv-python
Successfully installed opencv-python-3.2.0.7
root@fcfca6a4dad2:/DeepMeerkat# python
Python 2.7.9 (default, Jun 29 2016, 13:08:31)
[GCC 4.9.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import cv2
>>>
</code>```

答:
I think the error you are seeing is actually being caused because the worker is failing to install the wheel file. As noted on the opencv-python package page problems with wheel files may cause the package to appear as not found.

In this case, you can use the instructions for packages not-in PyPI and specify --extra_package <local path to wheel file> rather than adding opencv-python as a requirement. This should cause the wheel file to be staged and installed within each worker.

Body:
I am trying to get my Cloud DataFlow job running with a requirements.txt file as described here

https://cloud.google.com/dataflow/pipelines/dependencies-python

Rather than building all of opencv from source (takes 20-30 minutes), I can just build the python library

From my compute engine, I could do this

root@fcfca6a4dad2:/DeepMeerkat# pip install opencv-python
Collecting opencv-python
  Downloading opencv_python-3.2.0.7-cp27-cp27mu-manylinux1_x86_64.whl (6.7MB)
    100% |################################| 6.7MB 163kB/s
Collecting numpy>=1.11.1 (from opencv-python)
  Downloading numpy-1.13.0-cp27-cp27mu-manylinux1_x86_64.whl (16.6MB)
    100% |################################| 16.6MB 68kB/s
Installing collected packages: numpy, opencv-python
  Found existing installation: numpy 1.8.2
    DEPRECATION: Uninstalling a distutils installed project (numpy) has been deprecated and will be removed in a future version. This is due to the fact that uninstalling a distutils project will only partially uninstall the project.
    Uninstalling numpy-1.8.2:
      Successfully uninstalled numpy-1.8.2
Successfully installed numpy-1.13.0 opencv-python-3.2.0.7

I could wrap this into a requirements file with a few other modules

root@fcfca6a4dad2:/DeepMeerkat# pip install -r tests/prediction/requirements.txt
Requirement already satisfied: opencv-python in /usr/local/lib/python2.7/dist-packages (from -r tests/prediction/requirements.txt (line 1))
Collecting tensorflow==1.0.1 (from -r tests/prediction/requirements.txt (line 2))
  Downloading tensorflow-1.0.1-cp27-cp27mu-manylinux1_x86_64.whl (44.1MB)
    100% |################################| 44.1MB 27kB/s
Requirement already satisfied: numpy in /usr/local/lib/python2.7/dist-packages (from -r tests/prediction/requirements.txt (line 3))
Requirement already satisfied: mock>=2.0.0 in /usr/local/lib/python2.7/dist-packages (from tensorflow==1.0.1->-r tests/prediction/requirements.txt (line 2))
Requirement already satisfied: wheel in /usr/lib/python2.7/dist-packages (from tensorflow==1.0.1->-r tests/prediction/requirements.txt (line 2))
Requirement already satisfied: six>=1.10.0 in /usr/local/lib/python2.7/dist-packages (from tensorflow==1.0.1->-r tests/prediction/requirements.txt (line 2))
Requirement already satisfied: protobuf>=3.1.0 in /usr/local/lib/python2.7/dist-packages (from tensorflow==1.0.1->-r tests/prediction/requirements.txt (line 2))
Requirement already satisfied: funcsigs>=1; python_version < "3.3" in /usr/local/lib/python2.7/dist-packages (from mock>=2.0.0->tensorflow==1.0.1->-r tests/prediction/requirements.txt (line 2))
Requirement already satisfied: pbr>=0.11 in /usr/local/lib/python2.7/dist-packages (from mock>=2.0.0->tensorflow==1.0.1->-r tests/prediction/requirements.txt (line 2))
Requirement already satisfied: setuptools in /usr/local/lib/python2.7/dist-packages (from protobuf>=3.1.0->tensorflow==1.0.1->-r tests/prediction/requirements.txt (line 2))
Installing collected packages: tensorflow
Successfully installed tensorflow-1.0.1

However, when I send it to cloud dataflow, it can't find opencv-python from the worker.

root@fcfca6a4dad2:/DeepMeerkat# python tests/prediction/run.py \
>     --runner DataflowRunner \
>     --project $PROJECT \
>     --staging_location $BUCKET/staging \
>     --temp_location $BUCKET/temp \
>     --job_name $PROJECT-deepmeerkat \
>     --setup_file tests/prediction/setup.py \
>     --requirements_file tests/prediction/requirements.txt
No handlers could be found for logger "oauth2client.contrib.multistore_file"
/usr/local/lib/python2.7/dist-packages/apache_beam/io/gcp/gcsio.py:113: DeprecationWarning: object() takes no parameters
  super(GcsIO, cls).__new__(cls, storage_client))
INFO:root:Starting the size estimation of the input
INFO:oauth2client.transport:Attempting refresh to obtain initial access_token
INFO:root:Finished the size estimation of the input at 1 files. Estimation took 0.0855119228363 seconds
INFO:root:Starting the size estimation of the input
INFO:oauth2client.transport:Attempting refresh to obtain initial access_token
INFO:root:Finished the size estimation of the input at 1 files. Estimation took 0.0597159862518 seconds
/usr/local/lib/python2.7/dist-packages/apache_beam/coders/typecoders.py:135: UserWarning: Using fallback coder for typehint: Any.
  warnings.warn('Using fallback coder for typehint: %r.' % typehint)
INFO:root:Starting GCS upload to gs://api-project-773889352370-testing/staging/api-project-773889352370-deepmeerkat.1499372970.163850/requirements.txt...
INFO:oauth2client.transport:Attempting refresh to obtain initial access_token
INFO:root:Completed GCS upload to gs://api-project-773889352370-testing/staging/api-project-773889352370-deepmeerkat.1499372970.163850/requirements.txt
INFO:root:Executing command: ['/usr/bin/python', '-m', 'pip', 'install', '--download', '/tmp/dataflow-requirements-cache', '-r', 'tests/prediction/requirements.txt', '--no-binary', ':all:']
DEPRECATION: pip install --download has been deprecated and will be removed in the future. Pip now has a download command that should be used instead.
Collecting opencv-python (from -r tests/prediction/requirements.txt (line 1))
  Could not find a version that satisfies the requirement opencv-python (from -r tests/prediction/requirements.txt (line 1)) (from versions: )
No matching distribution found for opencv-python (from -r tests/prediction/requirements.txt (line 1))
Traceback (most recent call last):
  File "tests/prediction/run.py", line 22, in <module>
    predict.run()
  File "/DeepMeerkat/tests/prediction/modules/predict.py", line 32, in run
    p.run()
  File "/usr/local/lib/python2.7/dist-packages/apache_beam/pipeline.py", line 167, in run
    self.to_runner_api(), self.runner, self._options).run(False)
  File "/usr/local/lib/python2.7/dist-packages/apache_beam/pipeline.py", line 176, in run
    return self.runner.run(self)
  File "/usr/local/lib/python2.7/dist-packages/apache_beam/runners/dataflow/dataflow_runner.py", line 252, in run
    self.dataflow_client.create_job(self.job), self)
  File "/usr/local/lib/python2.7/dist-packages/apache_beam/utils/retry.py", line 168, in wrapper
    return fun(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/apache_beam/runners/dataflow/internal/apiclient.py", line 425, in create_job
    self.create_job_description(job)
  File "/usr/local/lib/python2.7/dist-packages/apache_beam/runners/dataflow/internal/apiclient.py", line 448, in create_job_description
    job.options, file_copy=self._gcs_file_copy)
  File "/usr/local/lib/python2.7/dist-packages/apache_beam/runners/dataflow/internal/dependency.py", line 307, in stage_job_resources
    setup_options.requirements_file, requirements_cache_path)
  File "/usr/local/lib/python2.7/dist-packages/apache_beam/runners/dataflow/internal/dependency.py", line 241, in _populate_requirements_cache
    processes.check_call(cmd_args)
  File "/usr/local/lib/python2.7/dist-packages/apache_beam/utils/processes.py", line 44, in check_call
    return subprocess.check_call(*args, **kwargs)
  File "/usr/lib/python2.7/subprocess.py", line 540, in check_call
    raise CalledProcessError(retcode, cmd)
subprocess.CalledProcessError: Command '['/usr/bin/python', '-m', 'pip', 'install', '--download', '/tmp/dataflow-requirements-cache', '-r', 'tests/prediction/requirements.txt', '--no-binary', ':all:']' returned non-zero exit status 1

It seems to be the no binary flag that is the problem. Locally running (after uninstalling the above)

root@fcfca6a4dad2:/DeepMeerkat# pip install -r tests/prediction/requirements.txt --no-binary :all:
Collecting opencv-python (from -r tests/prediction/requirements.txt (line 1))
  Could not find a version that satisfies the requirement opencv-python (from -r tests/prediction/requirements.txt (line 1)) (from versions: )
No matching distribution found for opencv-python (from -r tests/prediction/requirements.txt (line 1))

The no-binary flag is described as excluding broken wheels? How is this applicable in this case?

Can confirm that the module can be run

again,

root@fcfca6a4dad2:/DeepMeerkat# pip install opencv-python
Collecting opencv-python
  Using cached opencv_python-3.2.0.7-cp27-cp27mu-manylinux1_x86_64.whl
Requirement already satisfied: numpy>=1.11.1 in /usr/local/lib/python2.7/dist-packages (from opencv-python)
Installing collected packages: opencv-python
Successfully installed opencv-python-3.2.0.7
root@fcfca6a4dad2:/DeepMeerkat# python
Python 2.7.9 (default, Jun 29 2016, 13:08:31)
[GCC 4.9.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import cv2
>>>


问:
Copy Files don't begin with number char in Batch
how to copy files without begin number char in batch files

for example my Dir list its:

```<code>12red.pcx
9red.pcx
96blue.pcx
alipro.pcx
</code>```

then i need only copy alipro.pcx by batch

use this batch code for copy files begin with number char:

```<code>@echo off
set Design_path=D:\
set USB_path=E:\usb\
set t12=12*.pcx
set t9=9*.pcx
set t6=6*.pcx
set tsize=*.pcx
set design12=Dis_12
set design9=Dis_9
set design6=Dis_6
set designsize=D_Size
rem // Create Dir if not exist
if not exist %Design_path%%design12% (mkdir %Design_path%%design12%)
if not exist %Design_path%%design9% (mkdir %Design_path%%design9%)
if not exist %Design_path%%design6% (mkdir %Design_path%%design6%)
if not exist %Design_path%%designsize% (mkdir %Design_path%%designsize%)
if exist %USB_path%%t12% copy %USB_path%%t12% %Design_path%%design12%
if exist %USB_path%%t9% copy %USB_path%%t9% %Design_path%%design9%
if exist %USB_path%%t6% copy %USB_path%%t6% %Design_path%%design6%
</code>```

答:
This solution uses findstr's limited RegEx capabilities to select only lines
beginning (^ anchors at begin) with a negated character class [^] which are not
zero to nine [^0-9]

```<code>for /f "delims=" %%a in (
  'dir /B *.pcx^|findstr "^[^0-9]" '
) Do Echo copy %%a x:\whereever
</code>```

If you want to exclude special numbers you can do with a different RegEx which
filters lines not matching with the option /V
You can have several RegEx separated with a SPACE

```<code>for /f "delims=" %%a in (
  'dir /B "*.pcx" ^|findstr /V "^6 ^9 ^12" '
) Do (
  Echo %%a
  Rem copy ...
)
</code>```

Sample output

```<code>> Dir /B
11foo.pcx
12red.pcx
13bar.pcx
3366.pcx
96blue.pcx
9red.pcx
alipro.pcx

> SO_44875749.cmd
11foo.pcx
13bar.pcx
3366.pcx
alipro.pcx
</code>```

Body:
how to copy files without begin number char in batch files

for example my Dir list its:

12red.pcx
9red.pcx
96blue.pcx
alipro.pcx

then i need only copy alipro.pcx by batch

use this batch code for copy files begin with number char:

@echo off
set Design_path=D:\
set USB_path=E:\usb\
set t12=12*.pcx
set t9=9*.pcx
set t6=6*.pcx
set tsize=*.pcx
set design12=Dis_12
set design9=Dis_9
set design6=Dis_6
set designsize=D_Size
rem // Create Dir if not exist
if not exist %Design_path%%design12% (mkdir %Design_path%%design12%)
if not exist %Design_path%%design9% (mkdir %Design_path%%design9%)
if not exist %Design_path%%design6% (mkdir %Design_path%%design6%)
if not exist %Design_path%%designsize% (mkdir %Design_path%%designsize%)
if exist %USB_path%%t12% copy %USB_path%%t12% %Design_path%%design12%
if exist %USB_path%%t9% copy %USB_path%%t9% %Design_path%%design9%
if exist %USB_path%%t6% copy %USB_path%%t6% %Design_path%%design6%

Body:
This solution uses findstr's limited RegEx capabilities to select only lines
beginning (^ anchors at begin) with a negated character class [^] which are not
zero to nine [^0-9]

for /f "delims=" %%a in (
  'dir /B *.pcx^|findstr "^[^0-9]" '
) Do Echo copy %%a x:\whereever

If you want to exclude special numbers you can do with a different RegEx which
filters lines not matching with the option /V
You can have several RegEx separated with a SPACE

for /f "delims=" %%a in (
  'dir /B "*.pcx" ^|findstr /V "^6 ^9 ^12" '
) Do (
  Echo %%a
  Rem copy ...
)

Sample output

> Dir /B
11foo.pcx
12red.pcx
13bar.pcx
3366.pcx
96blue.pcx
9red.pcx
alipro.pcx

> SO_44875749.cmd
11foo.pcx
13bar.pcx
3366.pcx
alipro.pcx


问:
JacksonXML List duplicating tags
I have this

```<code>@JacksonXmlRootElement(localName = "results")
public class GenericResults{
    @JacksonXmlProperty
    private String copyright;
    @JacksonXmlProperty
    private int count;
    @JacksonXmlProperty(localName = "list")
    private List<Result> list;
</code>```

And on the Pojo I have this

```<code>public class Result {
    @JacksonXmlProperty(isAttribute = true, localName = "symbol")
    private String symbol;
    @JacksonXmlProperty(isAttribute = true, localName = "datatype")
    private String datatype;
    @JacksonXmlProperty(isAttribute = true, localName = "entitlement")
    private String entitlement;
    @JacksonXmlProperty(isAttribute = true, localName = "datetime")
    private Long datetime;
</code>```

The result is

```<code><results>
<copyright>Copyrights Bla Bla Bla </copyright>
<symbolCount>2</symbolCount>
<list>
<list symbolstring="x" datatype="a" entitlement="r" datetime="1499375390609"/>
<list symbolstring="y" datatype="a" entitlement="r" datetime="1499375390731"/>
</list>
</results>
</code>```

And what i Want to produce is...

```<code><results>
<copyright>Copyrights Bla Bla Bla </copyright>
<symbolCount>2</symbolCount>
<list symbolstring="x" datatype="a" entitlement="r" datetime="1499375390609"/>
<list symbolstring="y" datatype="a" entitlement="r" datetime="1499375390731"/>
</results>
</code>```

Someone Can help me?? I tried some other stuff but I was not able to do it... i dont want to have the duplicate tag for list....

答:
I found the solution just use @JacksonXmlElementWrapper(useWrapping = false)
on the list property.

Thanks!

Title: JacksonXML List duplicating tags

Body:
I have this

@JacksonXmlRootElement(localName = "results")
public class GenericResults{
    @JacksonXmlProperty
    private String copyright;
    @JacksonXmlProperty
    private int count;
    @JacksonXmlProperty(localName = "list")
    private List<Result> list;

And on the Pojo I have this

public class Result {
    @JacksonXmlProperty(isAttribute = true, localName = "symbol")
    private String symbol;
    @JacksonXmlProperty(isAttribute = true, localName = "datatype")
    private String datatype;
    @JacksonXmlProperty(isAttribute = true, localName = "entitlement")
    private String entitlement;
    @JacksonXmlProperty(isAttribute = true, localName = "datetime")
    private Long datetime;

The result is

<results>
<copyright>Copyrights Bla Bla Bla </copyright>
<symbolCount>2</symbolCount>
<list>
<list symbolstring="x" datatype="a" entitlement="r" datetime="1499375390609"/>
<list symbolstring="y" datatype="a" entitlement="r" datetime="1499375390731"/>
</list>
</results>

And what i Want to produce is...

<results>
<copyright>Copyrights Bla Bla Bla </copyright>
<symbolCount>2</symbolCount>
<list symbolstring="x" datatype="a" entitlement="r" datetime="1499375390609"/>
<list symbolstring="y" datatype="a" entitlement="r" datetime="1499375390731"/>
</results>

Someone Can help me?? I tried some other stuff but I was not able to do it... i dont want to have the duplicate tag for list....


答:
```<code>a[..., 1::2] *= -1
</code>```

Take every other element along the last axis and multiply them by -1.

Title: Changing elements in a numpy Array

Body:
a[..., 1::2] *= -1

Take every other element along the last axis and multiply them by -1.


问:
Disruptor or JMS?
Is the disruptor actually a replacement for application instead of JMS?
I currently transfer tasks using JMS messages.

Is the disruptor intended to replace it for message transfer?
what are the pros/cons of each one?

Currently I use JMS, I have a producer that sends messages to a queue and consumers (MDBs) that pull them off the queue.

Thanks.

答:
If we are talking about application scope, then yes, I agree with the topic author: disruptor came to replace JMS. In many organizations (including mine past) people used JMS to create their own internal frameworks to decouple application modules using JMS inside and make it async.

But what disruptor does not do: it does not replace JMS in terms of communication between applications.

I would recommend to use disruptor instead of JMS inside apps, it's easier to use, more understandable, more powerful etc.

Title: Disruptor or JMS?